Skip to content

Commit 3d98273

Browse files
committed
fix(metadata-protocol,runtime)!: the uninstall verb asks registered pre-uninstall guards; the runtime registers the dependent-rule verdict
WIP: seam and registration; pins follow. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2c1rk1PGZ51s32cxZt
1 parent bdefd49 commit 3d98273

8 files changed

Lines changed: 190 additions & 5 deletions

File tree

‎packages/metadata-protocol/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export type {
135135
SeedTenancySplit,
136136
SeedTenancyCollision,
137137
} from './migrations/seed-tenancy-backfill.js';
138-
export type { UninstallCleanup, UninstallCleanupOutcome, UninstallDeclared } from './protocol.js';
138+
export type { UninstallCleanup, UninstallCleanupOutcome, UninstallDeclared, UninstallGuard, UninstallGuardRefusal } from './protocol.js';
139139
export { captureUninstallDeclared } from './protocol.js';
140140
// [#9960] The ONE declared shape of the `deletePackage` seam, exported so the
141141
// two consumers that speak it (`@objectstack/rest`'s direct-mount package

‎packages/metadata-protocol/src/protocol-class-head.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
* `onMetadataMutation`, `emitMetadataMutation`, `attachMetadataMutationPubSub`,
1313
* `detachMetadataMutationPubSub`, `applyRemoteMetadataMutation`,
1414
* `onMetaItemPublished`, `getOverlayRepo` moved out of `protocol.ts` whole by
15-
* `scripts/codemod-split-protocol.mjs`.
15+
* `scripts/codemod-split-protocol.mjs`; `registerUninstallGuard` (#31232) was
16+
* written here in the same shape, beside `registerUninstallCleanup`.
1617
*
1718
* A MOVE, not a redesign. `ProtocolClassHeadFacet` is a stateless facet over the host
1819
* (ruling 6624345766): each static method below is the body of the class
@@ -52,6 +53,7 @@ import type {
5253
UninstallCleanup,
5354
UninstallCleanupOutcome,
5455
UninstallDeclared,
56+
UninstallGuard,
5557
} from './protocol-package-lifecycle-types.js';
5658
import { METADATA_MUTATION_CLUSTER_CHANNEL } from './protocol-mutation-events.js';
5759
import type {
@@ -104,6 +106,11 @@ export class ProtocolClassHeadFacet {
104106
host.uninstallCleanups.set(name, cleanup);
105107
}
106108

109+
/** The body of `ObjectStackProtocolImplementation#registerUninstallGuard`; the method's docblock there is its contract. */
110+
static registerUninstallGuard(host: Pick<ProtocolHost, 'uninstallGuards'>, name: string, guard: UninstallGuard): void {
111+
host.uninstallGuards.set(name, guard);
112+
}
113+
107114
/** The body of `ObjectStackProtocolImplementation#runUninstallCleanups`; the method's docblock there is its contract. */
108115
static async runUninstallCleanups(host: Pick<ProtocolHost, 'uninstallCleanups'>, request: Pick<DeletePackageRequest, 'packageId' | 'actor'> & { declared?: UninstallDeclared },): Promise<UninstallCleanupOutcome[]> {
109116
const cleanups: UninstallCleanupOutcome[] = [];

‎packages/metadata-protocol/src/protocol-host.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ export interface ProtocolHost {
259259
readonly tenantAuthoredWriteRefusal: ObjectStackProtocolImplementation['tenantAuthoredWriteRefusal'];
260260
readonly throwMetadataServiceUnavailable: ObjectStackProtocolImplementation['throwMetadataServiceUnavailable'];
261261
readonly uninstallCleanups: ObjectStackProtocolImplementation['uninstallCleanups'];
262+
readonly uninstallGuards: ObjectStackProtocolImplementation['uninstallGuards'];
262263
readonly uninstalledNamedBaseRefusal: ObjectStackProtocolImplementation['uninstalledNamedBaseRefusal'];
263264
readonly unknownDatasourceSaveRefusal: ObjectStackProtocolImplementation['unknownDatasourceSaveRefusal'];
264265
readonly unknownGrantObjectSaveRefusal: ObjectStackProtocolImplementation['unknownGrantObjectSaveRefusal'];

‎packages/metadata-protocol/src/protocol-package-lifecycle-types.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,37 @@ export type UninstallCleanup = (args: {
5454
declared?: UninstallDeclared;
5555
}) => Promise<{ success: boolean; removed: number; error?: string }>;
5656

57+
/**
58+
* [#31232] A guard's answer to "may this package be uninstalled now?": the
59+
* refusal {@link ObjectStackProtocolImplementation.deletePackage} throws, as
60+
* the guard spelled it — `code` (a ledgered error code), `status` (its HTTP
61+
* status) and `message` (the sentence the caller is shown). `undefined` lets
62+
* the uninstall proceed.
63+
*/
64+
export interface UninstallGuardRefusal {
65+
code: string;
66+
status: number;
67+
message: string;
68+
}
69+
70+
/**
71+
* [#31232] Pre-uninstall guard: the BEFORE-half of {@link UninstallCleanup}.
72+
* A plugin that owns a verdict this package must not know (the runtime's
73+
* dependent-rule scan reads the schema registry's fold, which lives above this
74+
* package and must not be imported here) registers it by name, and
75+
* {@link ObjectStackProtocolImplementation.deletePackage} asks every guard,
76+
* in registration order, before it reads or moves anything; the first refusal
77+
* is thrown as the verb's refusal, with nothing removed.
78+
*
79+
* A guard only reads: it is asked before the uninstall is decided, so it must
80+
* not write. A guard that throws instead of answering refuses the uninstall
81+
* with its throw — an uninstall a guard could not judge does not proceed.
82+
*/
83+
export type UninstallGuard = (args: {
84+
packageId: string;
85+
actor?: string;
86+
}) => UninstallGuardRefusal | undefined | Promise<UninstallGuardRefusal | undefined>;
87+
5788
/**
5889
* [ADR-0090 D5, ADR-0131 D4] The security-catalog names an uninstalled package
5990
* held. A grant names its set, and the package's sets are served from the

‎packages/metadata-protocol/src/protocol-package-uninstall.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,11 @@ export interface PackageUninstallHost {
5151
readonly packagelessAddress: ObjectStackProtocolImplementation['packagelessAddress'];
5252
readonly runUninstallCleanups: ObjectStackProtocolImplementation['runUninstallCleanups'];
5353
readonly shouldDropStorage: ObjectStackProtocolImplementation['shouldDropStorage'];
54+
readonly uninstallGuards: ObjectStackProtocolImplementation['uninstallGuards'];
5455
}
5556

5657
/** The body of `ObjectStackProtocolImplementation#deletePackage`; the method's docblock there is its contract. */
57-
export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMetaItem' | 'engine' | 'findEnvironmentRows' | 'getServicesRegistry' | 'packagelessAddress' | 'runUninstallCleanups' | 'shouldDropStorage'>, request: DeletePackageRequest): Promise<DeletePackageResponse> {
58+
export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMetaItem' | 'engine' | 'findEnvironmentRows' | 'getServicesRegistry' | 'packagelessAddress' | 'runUninstallCleanups' | 'shouldDropStorage' | 'uninstallGuards'>, request: DeletePackageRequest): Promise<DeletePackageResponse> {
5859
// [ADR-0131 D6/D12] An uninstall is environment-wide by construction:
5960
// every `sys_metadata` row bound to the package, in this environment,
6061
// whatever organization a legacy row was stored under. The
@@ -77,6 +78,25 @@ export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMeta
7778
throw err;
7879
}
7980
}
81+
82+
// [#31232] THE PRE-UNINSTALL GUARDS, ASKED BEFORE ANYTHING IS READ OR
83+
// MOVED. A plugin that owns a verdict this package must not know
84+
// registers it as a guard (`registerUninstallGuard`); the runtime
85+
// registers its dependent-rule scan, so an uninstall that would withdraw
86+
// a field an active validation rule of another enabled package reads is
87+
// refused here for EVERY caller of this verb (a host's own uninstall
88+
// tool, install-local's pair-install undo, the unmanaged-import
89+
// rollback), not only at the package door that asks it first. This
90+
// package holds no copy of the rule.
91+
//
92+
// Each guard is asked in registration order and the first refusal is
93+
// thrown, spelled as the guard answered it (`code`, `status`, `message`):
94+
// nothing has been read or removed yet, so there is nothing to undo. A
95+
// guard's own throw propagates as is — an uninstall a guard could not
96+
// judge does not proceed. With no guard registered nothing is asked, and
97+
// the verb behaves exactly as it did before guards existed.
98+
await askUninstallGuards(this.uninstallGuards, request);
99+
80100
const where: Record<string, unknown> = { package_id: request.packageId };
81101
// [#8136] This read is the uninstall's FIRST database touch, and until
82102
// now it sat outside every `try` in this method — the per-item `catch`
@@ -363,3 +383,23 @@ export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMeta
363383
cleanups,
364384
};
365385
}
386+
387+
/**
388+
* [#31232] Ask every registered pre-uninstall guard, in registration order,
389+
* and throw the first refusal one answers: an `Error` carrying the guard's
390+
* `message`, with its `code` and `status`. Asked by {@link deletePackage}
391+
* before it reads or moves anything; a guard's own throw propagates.
392+
*/
393+
async function askUninstallGuards(
394+
guards: PackageUninstallHost['uninstallGuards'],
395+
request: DeletePackageRequest,
396+
): Promise<void> {
397+
for (const guard of guards.values()) {
398+
const refusal = await guard({
399+
packageId: request.packageId,
400+
...(request.actor ? { actor: request.actor } : {}),
401+
});
402+
if (!refusal) continue;
403+
throw Object.assign(new Error(refusal.message), { code: refusal.code, status: refusal.status });
404+
}
405+
}

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,8 @@ import type {
527527
UninstallCleanup,
528528
UninstallCleanupOutcome,
529529
UninstallDeclared,
530+
UninstallGuard,
531+
UninstallGuardRefusal,
530532
} from './protocol-package-lifecycle-types.js';
531533
export { captureUninstallDeclared } from './protocol-package-lifecycle-types.js';
532534
export type {
@@ -537,6 +539,8 @@ export type {
537539
UninstallCleanup,
538540
UninstallCleanupOutcome,
539541
UninstallDeclared,
542+
UninstallGuard,
543+
UninstallGuardRefusal,
540544
} from './protocol-package-lifecycle-types.js';
541545
import { METADATA_MUTATION_CLUSTER_CHANNEL } from './protocol-mutation-events.js';
542546
import type {
@@ -761,6 +765,9 @@ export class ObjectStackProtocolImplementation implements
761765
/** [#2747] Named uninstall cleanups, run by {@link deletePackage}. */
762766
private uninstallCleanups = new Map<string, UninstallCleanup>();
763767

768+
/** [#31232] Named pre-uninstall guards, asked by {@link deletePackage} before it reads or moves anything. */
769+
private uninstallGuards = new Map<string, UninstallGuard>();
770+
764771
/**
765772
* Awaited per-type mutation projectors (ADR-0094), keyed by singular
766773
* metadata type. Unlike {@link publishMaterializers} (publish-only,
@@ -1379,6 +1386,7 @@ export class ObjectStackProtocolImplementation implements
13791386
tenantAuthoredWriteRefusal: (...a) => protocol.tenantAuthoredWriteRefusal(...a),
13801387
throwMetadataServiceUnavailable: (...a) => protocol.throwMetadataServiceUnavailable(...a),
13811388
get uninstallCleanups() { return protocol.uninstallCleanups; },
1389+
get uninstallGuards() { return protocol.uninstallGuards; },
13821390
uninstalledNamedBaseRefusal: (...a) => protocol.uninstalledNamedBaseRefusal(...a),
13831391
unknownDatasourceSaveRefusal: (...a) => protocol.unknownDatasourceSaveRefusal(...a),
13841392
unknownGrantObjectSaveRefusal: (...a) => protocol.unknownGrantObjectSaveRefusal(...a),
@@ -1413,6 +1421,27 @@ export class ObjectStackProtocolImplementation implements
14131421
return ProtocolClassHeadFacet.registerUninstallCleanup(protocolHost(this), name, cleanup);
14141422
}
14151423

1424+
/**
1425+
* [#31232] Register a named pre-uninstall guard: the before-half of
1426+
* {@link registerUninstallCleanup}. {@link deletePackage} asks every
1427+
* registered guard, in registration order, before it reads or moves
1428+
* anything, and throws the first refusal one answers as its own, with
1429+
* `code` and `status` as the guard spelled them; nothing is removed. A
1430+
* guard that throws refuses with its throw. With no guard registered the
1431+
* verb behaves exactly as it did before guards existed.
1432+
*
1433+
* Called by a plugin that owns a verdict this package must not know — the
1434+
* runtime registers its dependent-rule scan (an active validation rule of
1435+
* another enabled package reading a field the package adds through
1436+
* `objectExtensions`), the one the package doors ask, so every caller of
1437+
* the verb is refused on the verdict those doors answer, and this package
1438+
* holds no copy of it. One guard per name; a second registration replaces
1439+
* the first (idempotent re-init).
1440+
*/
1441+
registerUninstallGuard(name: string, guard: UninstallGuard): void {
1442+
return ProtocolClassHeadFacet.registerUninstallGuard(protocolHost(this), name, guard);
1443+
}
1444+
14161445
/**
14171446
* Run every registered uninstall cleanup for one package and report each
14181447
* outcome (ADR-0086 D3, #2747) — THE one runner of the registry above.
@@ -10915,7 +10944,10 @@ export class ObjectStackProtocolImplementation implements
1091510944
*
1091610945
* [#21276] The steps, in order. Nothing durable happens before step 4, so
1091710946
* a refusal at any of steps 1–4 leaves everything as it was:
10918-
* 1. the retired-key refusal (`INVALID_REQUEST`) — pure;
10947+
* 1. the retired-key refusal (`INVALID_REQUEST`) — pure; then [#31232]
10948+
* every registered pre-uninstall guard ({@link registerUninstallGuard}),
10949+
* in registration order — the first refusal is thrown with its own
10950+
* `code` and `status`, a guard's throw as is;
1091910951
* 2. the `sys_metadata` read — a read; a failure is thrown;
1092010952
* 3. the registry's uninstall refusal (another package extends an object
1092110953
* this one owns, ADR-0029), asked through
@@ -10937,6 +10969,7 @@ export class ObjectStackProtocolImplementation implements
1093710969
// [#25467 cut 35] The body moved to `protocol-package-uninstall.ts` (see `PackageUninstallHost`).
1093810970
const readEngine = () => this.engine;
1093910971
const readGetServicesRegistry = () => this.getServicesRegistry;
10972+
const readUninstallGuards = () => this.uninstallGuards;
1094010973
const host: ThisParameterType<typeof deletePackage> = {
1094110974
deleteMetaItem: (...a) => this.deleteMetaItem(...a),
1094210975
get engine() { return readEngine(); },
@@ -10945,6 +10978,7 @@ export class ObjectStackProtocolImplementation implements
1094510978
packagelessAddress: (...a) => this.packagelessAddress(...a),
1094610979
runUninstallCleanups: (...a) => this.runUninstallCleanups(...a),
1094710980
shouldDropStorage: (...a) => this.shouldDropStorage(...a),
10981+
get uninstallGuards() { return readUninstallGuards(); },
1094810982
};
1094910983
return deletePackage.call(host, request);
1095010984
}

‎packages/runtime/src/app-plugin.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import { mergeSeedDatasets, readSeedDatasets, registerSeedReplayerOnce } from '.
3030
import { describeSeedLocale, resolveSeedLocaleForLoad } from './seed-locale.js';
3131
import { declareSeedSource, recordOrganizationReplay, type SeedLandingReport } from './seed-settlement.js';
3232
import { loadDisabledPackageIds } from './package-state-store.js';
33-
import { readServedWithheldFieldReaders, servedWithheldFieldReadersMessage } from './domains/packages.js';
33+
import { ensureDependentRulesUninstallGuard, readServedWithheldFieldReaders, servedWithheldFieldReadersMessage } from './domains/packages.js';
3434
import { asPackageStateStore, ensurePackageStateUninstallCleanup, PACKAGE_STATE_STORE_PLUGIN_NAME } from './package-state-host-store.js';
3535
import type { IFieldFileService, IMetadataService, IObjectQLEngine, II18nService } from '@objectstack/spec/contracts';
3636
import { FIELD_FILE_SERVICE } from '@objectstack/spec/contracts';
@@ -1401,6 +1401,11 @@ export class AppPlugin implements Plugin {
14011401
// return: an empty env is where every package arrives by hydration or
14021402
// install, and is deleted the same way.
14031403
ensurePackageStateUninstallCleanup(ctx, this.projectContext?.environmentId);
1404+
// [#31232] …and refuses, before anything moves, an uninstall that would
1405+
// withdraw a field an active validation rule of another enabled
1406+
// package reads: the package doors' verdict, asked by the verb itself
1407+
// so every in-process caller is refused on it too.
1408+
ensureDependentRulesUninstallGuard(ctx);
14041409
if (this.empty) {
14051410
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping start', {
14061411
pluginName: this.name,

‎packages/runtime/src/domains/packages.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,73 @@ export interface DisableDependentRule {
920920
fields: string[];
921921
}
922922

923+
/**
924+
* [#31232] The name the dependent-rule verdict is registered under on the
925+
* protocol's pre-uninstall guard registry (`registerUninstallGuard`).
926+
*/
927+
export const PACKAGE_DEPENDENT_RULES_UNINSTALL_GUARD = 'runtime.package-dependent-rules';
928+
929+
/** The protocols this process registered the dependent-rule guard on — once each. */
930+
const DEPENDENT_RULES_GUARD_REGISTERED = new WeakSet<object>();
931+
932+
/**
933+
* [#31232] The refusal an uninstall of `packageId` answers while an active
934+
* validation rule of another enabled package reads a field the package adds
935+
* through `objectExtensions`: the disable door's verdict
936+
* ({@link readDisableDependentRules}) and sentence
937+
* ({@link disableDependentRulesMessage}) under an uninstall lead, as the wire
938+
* pair `409` `PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`. `undefined` when
939+
* no rule depends. Pure over `registry`.
940+
*/
941+
export function packageUninstallDependentRulesRefusal(
942+
registry: unknown,
943+
packageId: string,
944+
): { code: string; status: number; message: string } | undefined {
945+
const dependents = readDisableDependentRules(registry, packageId);
946+
if (dependents.length === 0) return undefined;
947+
return {
948+
code: PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE.code,
949+
status: PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE.status,
950+
message: disableDependentRulesMessage(`Package '${packageId}' cannot be uninstalled`, dependents),
951+
};
952+
}
953+
954+
/**
955+
* [#31232, ADR-0141 Open items 4] Register, once per kernel, the dependent-rule
956+
* verdict as a pre-uninstall guard on the protocol
957+
* ({@link PACKAGE_DEPENDENT_RULES_UNINSTALL_GUARD}, `registerUninstallGuard`),
958+
* so the uninstall verb itself (`deletePackage`) refuses, before it reads or
959+
* moves anything, an uninstall that would withdraw a field an active
960+
* validation rule of another enabled package reads
961+
* ({@link packageUninstallDependentRulesRefusal}). Once withdrawn, the rule
962+
* cannot be evaluated and fails closed, so every write to its object would be
963+
* refused with no package left to re-enable.
964+
*
965+
* Through the guard registry because every in-process caller of the verb (a
966+
* host's own uninstall tool, install-local's pair-install undo, the
967+
* unmanaged-import rollback) reaches it there, not only the package door:
968+
* `@objectstack/metadata-protocol` does not know the schema registry's fold the
969+
* verdict reads, and must not import this package. The mirror of
970+
* `ensurePackageStateUninstallCleanup`, which registers the after-half.
971+
*
972+
* The registry is the engine's, resolved when the guard is asked, as the
973+
* boot's withheld-field report resolves it. A kernel with no protocol, or a
974+
* protocol without the guard registry, registers nothing, and its verb
975+
* uninstalls as before.
976+
*/
977+
export function ensureDependentRulesUninstallGuard(ctx: { getService<T = unknown>(name: string): T }): void {
978+
let protocol: { registerUninstallGuard?: (name: string, guard: (args: { packageId: string }) => { code: string; status: number; message: string } | undefined) => void } | undefined;
979+
try { protocol = ctx.getService<any>('protocol'); } catch { return; }
980+
if (!protocol || typeof protocol.registerUninstallGuard !== 'function') return;
981+
if (DEPENDENT_RULES_GUARD_REGISTERED.has(protocol)) return;
982+
DEPENDENT_RULES_GUARD_REGISTERED.add(protocol);
983+
protocol.registerUninstallGuard(PACKAGE_DEPENDENT_RULES_UNINSTALL_GUARD, ({ packageId }) => {
984+
let registry: unknown;
985+
try { registry = ctx.getService<{ registry?: unknown }>('objectql')?.registry; } catch { registry = undefined; }
986+
return packageUninstallDependentRulesRefusal(registry, packageId);
987+
});
988+
}
989+
923990
/** The fields one validation rule reads: on its own object, and one hop through a reference field. */
924991
interface RuleFieldReads {
925992
readonly own: Set<string>;

0 commit comments

Comments
 (0)