diff --git a/.changeset/34396-composed-install-uninstall.md b/.changeset/34396-composed-install-uninstall.md new file mode 100644 index 00000000000..eb21507cd29 --- /dev/null +++ b/.changeset/34396-composed-install-uninstall.md @@ -0,0 +1,18 @@ +--- +'@objectstack/cloud-connection': patch +--- + +fix(cloud-connection): uninstalling a composed app through install-local uninstalls every package body it installed + +Clause-②: no +Metadata-protocol: none + +A composed release artifact (ADR-0130 D4: one `type: app` package and `type: module` packages) installs through `POST /api/v1/marketplace/install-local` as one install entry that registers every package body. When one module declared `objectExtensions` on the app's objects, the app could not be uninstalled: `DELETE /api/v1/marketplace/install-local/APP_ID` answered `409 RESOURCE_CONFLICT` and told the operator to uninstall the module first, but the module has no install entry of its own (`404 RESOURCE_NOT_FOUND`) and the package door refuses it as read-only (`422 WRITABLE_PACKAGE_REQUIRED`). Nothing could be removed, and the only way out was deleting the cached manifest on the host and restarting. + +The install entry's uninstall now removes the same unit its install registered. Every member is withdrawn from the running kernel, and an extension that one member contributes to another member's object decides the order instead of refusing the uninstall: the extending module goes first, then the package it extends. Each member's uninstall cleanups run for its own package id, so the permission sets of a module go with it. + +What does not change: + +- An extension or a paired customization package from a different install still refuses the uninstall with the registry's own `409 RESOURCE_CONFLICT`, naming that package, and nothing is removed. +- A single-package install is withdrawn alone, as before. +- A module of a composed artifact still has no install entry of its own and is still read-only. It is uninstalled through its artifact's entry. diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-uninstall.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-uninstall.test.ts new file mode 100644 index 00000000000..e2bc91194d8 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-composed-uninstall.test.ts @@ -0,0 +1,299 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0130 D4] `DELETE /api/v1/marketplace/install-local/:manifestId` of a + * COMPOSED artifact uninstalls the unit its install was: every package body + * the install registered, extending modules before the package they extend. + * + * ## The defect, read before the fix + * + * A composed artifact (one `type: app` package and `type: module` packages, a + * module declaring `objectExtensions` on the app's objects) installs through + * this door as ONE ledger entry, under the artifact's id, and registers every + * body. Its uninstall asked the registry about the app alone, and the registry + * refused (`409 RESOURCE_CONFLICT`, ADR-0029): the module extends an object the + * app owns. The prescribed first step had no door: the module has no ledger + * entry of its own (`404 RESOURCE_NOT_FOUND`), and the package door refuses a + * read-only installed package (`422 WRITABLE_PACKAGE_REQUIRED`, asked through + * `isWritablePackage`). Nothing could be removed. + * + * What this file pins, on a REAL engine and `manifest` service (an + * `ObjectKernel` with `ObjectQLPlugin`): + * + * - the reporter's three doors, as they answered; the module's own two still + * answer so after the fix, by design — the unit is uninstalled through its + * install entry; + * - the composed uninstall answers 200 and withdraws every member, the + * extending module first, whatever order the artifact lists its bodies in; + * - an extension from a DIFFERENT install still refuses the app's uninstall, + * with the registry's own `409` naming that package, and nothing moves; + * - a single-package install withdraws itself alone, as before. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +// The plugin reaches `@objectstack/runtime` through a lazy `import()`; its first +// load is paid here, at module top, never inside a clocked `it`. +import '@objectstack/runtime'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { isWritablePackage } from '@objectstack/metadata-protocol'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { LocalManifestSource } from './local-manifest-source.js'; +import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Bag = Record; +type Handler = (c: any) => Promise; + +const ROUTE = '/api/v1/marketplace/install-local'; +const APP = 'com.probe.suite'; +const MODULE = 'com.probe.suite.carbon'; +const OTHER_MODULE = 'com.probe.suite.reports'; +const ADDON = 'com.probe.addon'; +const OBJECT = 'probesuite_account'; + +const appBody = (): Bag => ({ + id: APP, name: 'probesuite', namespace: 'probesuite', version: '1.0.0', type: 'app', + objects: [{ name: OBJECT, label: 'Account', fields: { name: { type: 'text' } } }], +}); +const moduleBody = (): Bag => ({ + id: MODULE, name: 'probecarbon', namespace: 'probecarbon', version: '1.0.0', type: 'module', + objectExtensions: [{ extend: OBJECT, fields: { carbon_score: { type: 'number' } } }], +}); +/** A module of the same artifact that extends nothing. */ +const otherModuleBody = (): Bag => ({ + id: OTHER_MODULE, name: 'probereports', namespace: 'probereports', version: '1.0.0', type: 'module', +}); +/** + * The composed artifact: the app's body, an extending module, a module that + * extends nothing. `moduleFirst` lists the extending module ahead of the app, + * so the artifact's own order cannot be what puts it first on the way out. + */ +const composed = (opts: { moduleFirst?: boolean } = {}): Bag => ({ + ...appBody(), + packages: opts.moduleFirst + ? [{ manifest: moduleBody() }, { manifest: appBody() }, { manifest: otherModuleBody() }] + : [{ manifest: appBody() }, { manifest: moduleBody() }, { manifest: otherModuleBody() }], +}); +/** A package of a DIFFERENT install extending the app's object. */ +const addonBody = (): Bag => ({ + id: ADDON, name: 'probeaddon', namespace: 'probeaddon', version: '1.0.0', type: 'app', + objectExtensions: [{ extend: OBJECT, fields: { addon_flag: { type: 'boolean' } } }], +}); + +let dir: string; +const kernels: ObjectKernel[] = []; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-composed-uninstall-')); }); +afterEach(async () => { + while (kernels.length) { + const k = kernels.pop()!; + if (k.getState() === 'running') await k.shutdown(); + } + rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); +}); + +/** The plugin over a REAL engine and `manifest` service, booted to `kernel:ready`. */ +async function bootPlugin() { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + kernels.push(kernel); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + ql.registry.logLevel = 'silent'; + const withdrawn: string[] = []; + const uninstallPackage = ql.registry.uninstallPackage.bind(ql.registry); + vi.spyOn(ql.registry, 'uninstallPackage').mockImplementation((id: string, options?: { keepBootSeed?: boolean }) => { + withdrawn.push(id); + return uninstallPackage(id, options); + }); + const routes = new Map(); + const rawApp = { + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; + const hooks = new Map Promise>(); + const services: Record = { + manifest: kernel.getService('manifest'), + auth: installerAuthService(), + objectql: withInstallerGrants({ + convertPackageBodyForward: (b: unknown) => ql.convertPackageBodyForward(b), + registry: ql.registry, + syncSchemas: async () => undefined, + }), + }; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const ctx = { + hook: (e: string, h: () => Promise) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + if (!(name in services)) throw new Error(`no ${name}`); + return services[name]; + }, + logger, + trigger: async () => undefined, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + // Side readers that need services this harness does not carry; what is pinned is the registry and the ledger. + const p = plugin as unknown as Record; + p.bindArtifactHandlers = async () => undefined; + p.applySideEffects = async () => ({ seeded: { mode: 'none' } }); + p.maybeHealSampleData = async () => ({ seeded: { mode: 'none' } }); + await plugin.start(ctx as never); + await hooks.get('kernel:ready')?.(); + const request = (manifestId?: string, body?: Bag) => { + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); + return { + req: { + url: `http://localhost:3000${ROUTE}${manifestId ? `/${manifestId}` : ''}`, + raw: new Request('http://localhost:3000/x'), + json: async () => body ?? {}, + param: (name: string) => (name === 'manifestId' ? manifestId : undefined), + }, + json, + }; + }; + const install = async (manifest: Bag) => routes.get(`POST ${ROUTE}`)!(request(undefined, { manifest })); + const uninstall = async (manifestId: string) => routes.get(`DELETE ${ROUTE}/:manifestId`)!(request(manifestId)); + const ledgerIds = () => new LocalManifestSource(dir).list().entries.map((e) => e.manifestId).sort(); + const registered = (id: string) => ql.registry.getPackage(id) !== undefined; + const extenders = () => ql.registry.getObjectContributors(OBJECT) + .filter((c) => c.ownership === 'extend').map((c) => String(c.packageId)).sort(); + const warnings = () => logger.warn.mock.calls.map((c: unknown[]) => String(c[0])); + return { ql, install, uninstall, ledgerIds, registered, extenders, withdrawn, warnings }; +} + +async function installComposed(opts: { moduleFirst?: boolean } = {}) { + const booted = await bootPlugin(); + const installed = await booted.install(composed(opts)); + expect(installed.status, JSON.stringify(installed.payload)).toBe(200); + // ONE install entry, under the artifact's id, for three registered bodies. + expect(booted.ledgerIds()).toEqual([APP]); + expect([APP, MODULE, OTHER_MODULE].map(booted.registered)).toEqual([true, true, true]); + expect(booted.extenders()).toEqual([MODULE]); + return booted; +} + +describe('[ADR-0130 D4] an install-local uninstall of a composed artifact uninstalls the unit its install was', () => { + it('the module\'s own doors: no install entry of its own (404) and read-only (422\'s predicate) — and nothing moved', async () => { + const booted = await installComposed(); + + const own = await booted.uninstall(MODULE); + + expect(own.status, JSON.stringify(own.payload)).toBe(404); + expect(own.payload.error.code).toBe('RESOURCE_NOT_FOUND'); + // `DELETE /api/v1/packages/:id` answers `422 WRITABLE_PACKAGE_REQUIRED` + // exactly when this predicate is false: the installed module is not a + // writable base, so the package door is not its way out. + expect(isWritablePackage(booted.ql, MODULE)).toBe(false); + expect(booted.ledgerIds()).toEqual([APP]); + expect([APP, MODULE, OTHER_MODULE].map(booted.registered)).toEqual([true, true, true]); + expect(booted.withdrawn).toEqual([]); + }); + + it('DELETE of the install entry answers 200 and withdraws every member, the extending module before the app it extends', async () => { + const booted = await installComposed(); + const warnedBefore = booted.warnings().length; + + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(res.payload.success).toBe(true); + expect(booted.ledgerIds()).toEqual([]); + expect([APP, MODULE, OTHER_MODULE].map(booted.registered)).toEqual([false, false, false]); + expect(booted.withdrawn).toHaveLength(3); + expect(booted.withdrawn.indexOf(MODULE)).toBeLessThan(booted.withdrawn.indexOf(APP)); + expect(booted.ql.registry.getObjectContributors(OBJECT)).toEqual([]); + // Every withdrawal succeeded, so none is reported as a failed outcome. + expect(res.payload.data.cleanups).toEqual([]); + // The uninstall itself warns of nothing (the install's own warnings are not this test's). + expect(booted.warnings().slice(warnedBefore)).toEqual([]); + }); + + it('the extending module goes first even when the artifact lists it ahead of the app', async () => { + const booted = await installComposed({ moduleFirst: true }); + + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect([APP, MODULE, OTHER_MODULE].map(booted.registered)).toEqual([false, false, false]); + expect(booted.withdrawn.indexOf(MODULE)).toBeLessThan(booted.withdrawn.indexOf(APP)); + }); + + it('a reinstall after the uninstall registers the unit again — the recovery the stuck uninstall blocked', async () => { + const booted = await installComposed(); + expect((await booted.uninstall(APP)).status).toBe(200); + + const again = await booted.install(composed()); + + expect(again.status, JSON.stringify(again.payload)).toBe(200); + expect(booted.ledgerIds()).toEqual([APP]); + expect([APP, MODULE, OTHER_MODULE].map(booted.registered)).toEqual([true, true, true]); + }); +}); + +describe('[ADR-0029] an extension from a DIFFERENT install still refuses the app\'s uninstall', () => { + it('409 with the registry\'s refusal naming the other install\'s package; nothing of the unit moves', async () => { + const booted = await installComposed(); + const addon = await booted.install(addonBody()); + expect(addon.status, JSON.stringify(addon.payload)).toBe(200); + expect(booted.extenders()).toEqual([ADDON, MODULE]); + + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(409); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('RESOURCE_CONFLICT'); + expect(res.payload.error.message).toContain(ADDON); + expect(booted.ledgerIds()).toEqual([ADDON, APP]); + expect([APP, MODULE, OTHER_MODULE, ADDON].map(booted.registered)).toEqual([true, true, true, true]); + expect(booted.extenders()).toEqual([ADDON, MODULE]); + expect(booted.withdrawn).toEqual([]); + }); + + it('CONTROL: once the other install is uninstalled, the unit\'s uninstall goes through', async () => { + const booted = await installComposed(); + expect((await booted.install(addonBody())).status).toBe(200); + expect((await booted.uninstall(APP)).status).toBe(409); + + expect((await booted.uninstall(ADDON)).status).toBe(200); + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(booted.ledgerIds()).toEqual([]); + expect([APP, MODULE, OTHER_MODULE, ADDON].map(booted.registered)).toEqual([false, false, false, false]); + }); +}); + +describe('a single-package install withdraws itself alone, as before', () => { + it('one body, one withdrawal; a package of another install stays', async () => { + const booted = await bootPlugin(); + expect((await booted.install(appBody())).status).toBe(200); + expect((await booted.install(otherModuleBody())).status).toBe(200); + + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(booted.withdrawn).toEqual([APP]); + expect(booted.ledgerIds()).toEqual([OTHER_MODULE]); + expect([APP, OTHER_MODULE].map(booted.registered)).toEqual([false, true]); + expect(existsSync(join(dir, `${APP}.json`))).toBe(false); + }); + + it('extended by another install: the registry\'s 409, as before', async () => { + const booted = await bootPlugin(); + expect((await booted.install(appBody())).status).toBe(200); + expect((await booted.install(addonBody())).status).toBe(200); + + const res = await booted.uninstall(APP); + + expect(res.status, JSON.stringify(res.payload)).toBe(409); + expect(res.payload.error.code).toBe('RESOURCE_CONFLICT'); + expect(res.payload.error.message).toContain(ADDON); + expect(booted.withdrawn).toEqual([]); + expect(booted.registered(APP)).toBe(true); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index 9d8a99a29ed..cf62c5fcf12 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -204,6 +204,11 @@ * automation engine withdraws the package's flows and unbinds their * triggers at once (#27395); it reports each outcome as `cleanups`, * a refused withdrawal or a re-sync that did not run included. + * The entry of a composed artifact (ADR-0130 D4) uninstalls every + * package body its install registered, as one unit: an extension + * one member contributes to another member's object orders the + * withdrawal (the extending module first) rather than refusing it, + * and only an extension or pair from outside the unit refuses it. * * Persistence layout: * /.objectstack/installed-packages/.json @@ -1165,6 +1170,91 @@ function manifestIdOf(p: any): string | undefined { return p?.manifest?.id ?? p?.id ?? p?.manifest?.name ?? undefined; } +/** + * [ADR-0130 D4] The package ids one install-local ledger entry installed, in + * the order its uninstall withdraws them before the registry is asked: the + * reverse of the order the install registered them (dependents before the + * packages they declare, `orderHydrationBatch`, the rehydrate's own sorter), + * read off the entry's stored body the way the rehydrate reads it. + * + * A single-package entry is its own id alone. The entry's own id is always a + * member, last when no body carries it, so the door asks about and withdraws + * at least what it did before. + */ +function installedUnitPackageIds(manifestId: string, entryManifest: unknown): string[] { + const body = flattenPackageBody(entryManifest as Record); + if (!Array.isArray(body?.packages)) return [manifestId]; + const nodes = body.packages.flatMap((entry: { manifest?: unknown } | null) => { + const id = artifactPackageId(entry?.manifest); + return id === undefined ? [] : [{ item: id, label: id, packageIds: [id], declaredIds: declaredDependencyIds(entry?.manifest) }]; + }); + const ids = [...new Set(orderHydrationBatch(nodes).ordered.reverse())]; + return ids.includes(manifestId) ? ids : [...ids, manifestId]; +} + +/** + * What {@link planUnitWithdrawal} reads off the registry's uninstall refusal + * (`PackageUninstallExtendedError`, `RESOURCE_CONFLICT` / 409) of one member: + * its sentence, the packages extending the member's objects, and the + * member's installed paired customization package. Read by property, as the + * door reads `code`: the class is unexported. + */ +interface MemberUninstallRefusal { + message: string; + extenders?: unknown; + customizationPackageId?: unknown; +} + +/** + * [ADR-0130 D4, ADR-0029] The order an install-local uninstall withdraws its + * unit in, or the registry refusal that stops it — decided before anything + * moves. + * + * The registry refuses a package while another package extends an object it + * owns, or while its paired customization package is installed + * (`assertPackageUninstallable`, the ONE predicate its own `uninstallPackage` + * asks). Asked of each member with the whole unit still registered, a refusal + * whose every cause is another member of the SAME unit is not a refusal of + * the unit: those members are withdrawn first, extending modules before the + * package they extend. A cause outside the unit — a package of a different + * install, a pair this install did not deliver — refuses the whole uninstall + * with the registry's own sentence, as the single-package door always did; so + * does a refusal that names no causes to read, and a cycle of members that + * each extend the other, which no order can withdraw. + * + * `base` is {@link installedUnitPackageIds}' order; it decides wherever no + * extension does. A single-package unit is refused exactly when its registry + * refuses it: no other member can be a cause. + */ +function planUnitWithdrawal( + base: readonly string[], + refusalOf: (packageId: string) => MemberUninstallRefusal | undefined, +): { order: string[] } | { refusal: string } { + const unit = new Set(base); + const before = new Map(); + const refusals = new Map(); + for (const id of base) { + const refusal = refusalOf(id); + if (refusal === undefined) continue; + refusals.set(id, refusal); + const extenders = Array.isArray(refusal.extenders) ? refusal.extenders : undefined; + const pair = typeof refusal.customizationPackageId === 'string' ? refusal.customizationPackageId : undefined; + const causes = [...(extenders ?? []), ...(pair !== undefined ? [pair] : [])]; + if (extenders === undefined || causes.some((cause) => typeof cause !== 'string' || !unit.has(cause))) { + return { refusal: refusal.message }; + } + before.set(id, causes as string[]); + } + const order: string[] = []; + const remaining = [...base]; + while (remaining.length > 0) { + const next = remaining.findIndex((id) => (before.get(id) ?? []).every((cause) => order.includes(cause))); + if (next === -1) return { refusal: refusals.get(remaining.find((id) => refusals.has(id))!)!.message }; + order.push(...remaining.splice(next, 1)); + } + return { order }; +} + /** * [#28039] The datasources a package body declares, as `AppPlugin` reads a * stack's: a list, or a map keyed by name. @@ -3626,8 +3716,14 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // this package adds through `objectExtensions`) among them — and holds // no copy of any verdict. A refusal is the request's, spelled as the // guard spelled it (`code`, `status`, `message`), with nothing moved. - { - const refused = await this.askUninstallGuards(c, ctx, manifestId, admission.userId); + // + // [ADR-0130 D4] The install entry of a composed artifact installed + // every package body the artifact carries, so its uninstall is that + // same unit: each member is asked and, below, withdrawn. A + // single-package entry is its own id alone, as before. + const unit = installedUnitPackageIds(manifestId, this.ledger.read(manifestId).entry?.manifest); + for (const memberId of unit) { + const refused = await this.askUninstallGuards(c, ctx, memberId, admission.userId); if (refused) return refused; } // [#28511, ADR-0146 D3] THE REGISTRY'S UNINSTALL REFUSAL, ASKED BEFORE @@ -3654,20 +3750,35 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // meets is reported on `cleanups`. A throw that is not the coded // refusal is left to the withdrawal the same way, never answered as a // conflict it is not. + // + // [ADR-0130 D4] Asked of every member of the unit, with the whole unit + // still registered: a refusal caused only by other members of the + // same install (a module extending the app's objects) orders the + // withdrawal — those members go first — instead of refusing it; a + // cause outside the unit refuses it as before ({@link planUnitWithdrawal}). + let withdrawalOrder = unit; { let registry: { assertPackageUninstallable?(id: string): void } | undefined; try { registry = ctx.getService('objectql')?.registry as typeof registry; } catch { /* no data engine — nothing registered */ } if (typeof registry?.assertPackageUninstallable === 'function') { - try { - registry.assertPackageUninstallable(manifestId); - } catch (err: any) { - if (err?.code === 'RESOURCE_CONFLICT' && err?.status === 409) { - return c.json({ - success: false, - error: { code: 'RESOURCE_CONFLICT', message: String(err.message) }, - }, 409); + const ask = registry.assertPackageUninstallable.bind(registry); + const planned = planUnitWithdrawal(unit, (memberId) => { + try { + ask(memberId); + return undefined; + } catch (err: any) { + return err?.code === 'RESOURCE_CONFLICT' && err?.status === 409 + ? { message: String(err.message), extenders: err.extenders, customizationPackageId: err.customizationPackageId } + : undefined; } + }); + if ('refusal' in planned) { + return c.json({ + success: false, + error: { code: 'RESOURCE_CONFLICT', message: planned.refusal }, + }, 409); } + withdrawalOrder = planned.order; } } // [#31283] The version this uninstall removes, for the package's ledger row. @@ -3705,30 +3816,44 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // copies go right after the registry half and before the cleanups — // only once the registry withdrew, so a refused withdrawal leaves the // package whole, as loaded as it was. + // + // [ADR-0130 D4] Every member of the unit, in the planned order: each + // one's names captured, then each withdrawn — all synchronously, still + // no `await` between the ledger removal and the last withdrawal. A + // member whose withdrawal is refused keeps its own copies and its + // overrides; the others' go. let registry: unknown; try { registry = ctx.getService('objectql')?.registry; } catch { /* no data engine — nothing registered */ } - const declared = captureUninstallDeclared(registry, manifestId); - const withdrawal = this.withdrawFromRunningKernel(ctx, manifestId); + const declared = new Map(withdrawalOrder.map((memberId) => [memberId, captureUninstallDeclared(registry, memberId)])); + const refusedWithdrawals = new Map(); + for (const memberId of withdrawalOrder) { + const refused = this.withdrawFromRunningKernel(ctx, memberId); + if (refused) refusedWithdrawals.set(memberId, refused); + } + const withdrawn = withdrawalOrder.filter((memberId) => !refusedWithdrawals.has(memberId)); + const withdrawal = refusedWithdrawals.size > 0; // The registry verb reaches no executable handler: the package's // script-action handlers, body hooks and functions this door's install // bound on the engine ({@link bindArtifactHandlers}) go right after the // registry half withdrew, through the binder's own inverse — never on // a refused withdrawal, which leaves the package loaded and running. + // They are bound once for the whole install, under its entry's id. if (!withdrawal) await this.unbindArtifactHandlers(ctx, manifestId); - const copies = withdrawal ? undefined : await this.withdrawObjectCopies(ctx, manifestId); - // [#24182] …and the copies of OTHER packages' objects that this one's - // extensions rewrote: the bridge that wrote them restores the owner's - // definition (`manifest.restoreExtendedObjectCopies`, never rejects). - if (!withdrawal) { + const copies: UninstallCleanupOutcome[] = []; + for (const memberId of withdrawn) { + const kept = await this.withdrawObjectCopies(ctx, memberId); + if (kept) copies.push(kept); + // [#24182] …and the copies of OTHER packages' objects that this one's + // extensions rewrote: the bridge that wrote them restores the owner's + // definition (`manifest.restoreExtendedObjectCopies`, never rejects). let manifestService: { restoreExtendedObjectCopies?(id: string): Promise } | undefined; try { manifestService = ctx.getService('manifest') as typeof manifestService; } catch { /* no engine — nothing bridged */ } - await manifestService?.restoreExtendedObjectCopies?.(manifestId); + await manifestService?.restoreExtendedObjectCopies?.(memberId); + } + const cleanups = [...refusedWithdrawals.values(), ...copies]; + for (const memberId of withdrawalOrder) { + cleanups.push(...await this.runUninstallCleanups(ctx, memberId, admission.userId, declared.get(memberId))); } - const cleanups = [ - ...(withdrawal ? [withdrawal] : []), - ...(copies ? [copies] : []), - ...await this.runUninstallCleanups(ctx, manifestId, admission.userId, declared), - ]; // [#27395] LAST — after the registry withdrawal and the cleanups, never // before, for the window described above — announce the withdrawal as // `metadata:reloaded`, the re-sync the install's hot load announces, so @@ -3737,7 +3862,8 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // itself: the uninstall drives the one teardown a reload drives. Not // when the registry refused: the package is still registered, so a // re-sync would only read it back. - const resync = withdrawal ? undefined : await this.announceUninstall(ctx, manifestId); + // [ADR-0130 D4] Once, for the install, when any member was withdrawn. + const resync = withdrawn.length > 0 ? await this.announceUninstall(ctx, manifestId) : undefined; if (resync) cleanups.push(resync); // [#31283] The package's own `package_uninstall` ledger row (#31186), // written once the uninstall is durable — the ledger entry is gone — @@ -3746,15 +3872,18 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // stored `sys_metadata` items an uninstall removes: an install-local // package is registered from its ledger entry and has none. await this.recordUninstall(ctx, manifestId, removedVersion, admission.userId); - const withdrawals = (withdrawal ? 1 : 0) + (copies ? 1 : 0) + (resync ? 1 : 0); + const keptCopies = copies.length > 0; + const withdrawals = refusedWithdrawals.size + copies.length + (resync ? 1 : 0); ctx.logger?.info?.( `[MarketplaceInstallLocal] uninstalled ${manifestId} (cached manifest removed; ` + + (withdrawalOrder.length > 1 ? `the package bodies it installed: ${withdrawalOrder.join(', ')}; ` : '') + + (withdrawal && withdrawn.length > 0 ? `withdrawn: ${withdrawn.join(', ')}; ` : '') + (withdrawal ? 'the running kernel did NOT withdraw it, so it stays loaded until the next restart; ' - : copies || resync + : keptCopies || resync ? 'withdrawn from the running kernel\'s registry, but ' + [ - ...(copies ? ['the metadata service kept copies of its objects'] : []), + ...(keptCopies ? ['the metadata service kept copies of its objects'] : []), ...(resync ? ['the automation engine can still hold its flows'] : []), ].join(' and ') + ' until the next restart; ' @@ -3768,9 +3897,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin { cleanups, note: withdrawal ? 'Cached manifest removed, and the uninstall cleanups this runtime\'s plugins registered ran — each one\'s outcome is in `cleanups`. The running kernel did not withdraw the package, so it stays loaded until the next restart; that is the `registry.uninstallPackage` entry in `cleanups`.' - : copies || resync + : keptCopies || resync ? 'Cached manifest removed, the package withdrawn from the running kernel\'s registry, and the uninstall cleanups this runtime\'s plugins registered ran — each one\'s outcome is in `cleanups`.' - + (copies + + (keptCopies ? ' The metadata service kept copies of the package\'s objects, so the object listing and reads keep serving them until the next restart; that is the `metadata.unregister` entry in `cleanups`.' : '') + (resync