Skip to content

Commit 57675a2

Browse files
fix(runtime)!: refuse a package uninstall while an active validation rule reads a field it adds (#31227)
domain:server#4 · marchtian · session_017ihL2dLQEXWGsE2SZ3Qn5F <!-- claude-projects-attribution: {"github_login":"marchtian"} --> _Requested by **田騏** · [project thread](https://claude.ai/code/project/chan_01VmuUhXU9SSUzqJYyXSmYSi?thread=cmsg_01VmuUhXU9SSUzqJYyXSmYSiGQNmXXF32wmaXpQFjc6kB9)_ Fixes #30999 Clause-②: yes (narrowing) Metadata-protocol: none ## 维护者速读 - **改了什么**:卸载包(`DELETE /api/v1/packages/:id`)现在先问停用门已经在问的同一个检查:如果别的已启用包有生效中的校验规则在读这个包通过 `objectExtensions` 加的字段,就拒绝卸载,返回 409 `PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`,消息和停用门同一句话,只是开头换成「cannot be uninstalled」,并列出每条规则(包 · 对象 · 规则)。拒绝时什么都不动。 - **为什么改**:以前卸载会直接撤掉这些字段,读它们的规则随即失效,该对象的每一次写入都报 400 `VALIDATION_FAILED`,而包已经没了,连重新启用这条退路都没有。停用门早就拦这种情况(#30379),卸载门是漏掉的那一个。 - **风险与回滚**:这是一次收窄(BREAKING):以前能卸载成功的请求,现在在有依赖规则时会被 409 拒绝。没有依赖规则的卸载、已停用包的卸载行为不变。没有改错误码台账、spec 或存储形状。回滚就是 revert 这个 PR。 - **先看**:`packages/runtime/src/domains/packages.ts` 的 DELETE 分支新增的那段检查(在 `requireWritablePackage` 之后、`resolveProtocol` 之前);`packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts` 末尾的 `[#30999]` describe;`.changeset/30999-uninstall-dependent-rule-refusal.md`。 - **两分钟验证**:`pnpm --filter @objectstack/runtime exec vitest run src/domains/packages-disable-module-extension-fields.test.ts -t 30999`,预期 4 条全绿:卸载被 409 拒绝且什么都没动、拒绝文案的卸载版只改“撤掉/保留安装”两处,以及两条 CONTROL(无依赖的包照常卸载并清掉停用记录,把规则在租户覆盖层关掉后卸载照常通过)。 - **需要你做的**:维护者在 PR 上确认这次收窄(卸载门在有依赖规则时改为拒绝)。席位合同复审 PASS 见 comment 6712022339(Head-sha `ee03285db1ab`),席位核对 ACCEPT 见 comment 6712026943;批准后由席位落地。 - **席位意见**:可合。拒绝在任何状态变动之前,复用停用门同一个判定和错误码,两门不会漂移;文案已改为“卸载会撤掉…或保留安装”。进程内卸载(`deletePackage`)同样缺这道拒绝,已另立 #31232,不在本 PR。 ## What changes `DELETE /api/v1/packages/:id` withdraws the package's `objectExtensions` fields from the served objects, exactly as `PATCH /packages/:id/disable` withholds them, but it never asked the dependent-rule scan the disable door asks. The door now asks that same verdict, `readDisableDependentRules` (exported as `readPackageDisableDependents`), with no second copy, and refuses with the same wire pair and the same sentence: - **Where.** Right after the read-only check (`requireWritablePackage`) and BEFORE `resolveProtocol`, `deletePackage`, the running-registry withdrawal and the disable-record clear. A refused uninstall moves nothing: stored rows, registry entry, served fields and the environment's disable record stay as they were. - **What it answers.** `409` with `{ error: { code: 'PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE', message } }`, the message built by `disableDependentRulesMessage` (exported as `formatPackageDisableDependents`) under the lead `Package 'ID' cannot be uninstalled`. No `error.details`, as at the disable door. - **The code stays.** It is ledgered once under `@objectstack/runtime` (`ERROR_CODE_LEDGER`), and the refused state is the same one the disable door refuses: a rule left reading a field the fold no longer serves. Reusing it touches nothing under `packages/spec`. - **What does not change.** An uninstall no active rule depends on proceeds exactly as before: the verb is still handed the session user (#31023) and the disable record is still cleared. A package that is already disabled withholds its fields already, so its verdict is empty and its uninstall proceeds. ## Why The disable door has refused this since #30379: once a field is withheld, a rule that reads it cannot be evaluated and fails closed, so every write to its object is refused. The uninstall door withdraws the same fields and skipped the scan, and after an uninstall there is no package left to re-enable. Both doors now answer the one verdict. ## Tests One new top-level describe in the shared dependent-rule harness, `packages-disable-module-extension-fields.test.ts`, on a real kernel (ObjectQL on SQLite, MetadataPlugin, the real uninstall verb spied on and passed through). Two writable packages (installed as authored, so the door may delete them) each extend the app's object with one field; a third package's active rule reads the first one's field. - **Refusal.** `DELETE` of the read package answers `409` with the code, and the message equals the exported builder over the exported verdict under the uninstall lead. Nothing moved: `deletePackage` was never called, the package and its field are still served, the state file is unchanged, and a write to the object still lands. - **CONTROL: no dependent.** The second package (its field read by no rule, while the reader's rule stays active on the same object), disabled first, uninstalls with `200`; the verb received `{ packageId, actor: 'u_admin' }`, the package left the registry, its field left the served object, and its disable record was cleared. - **CONTROL: rule switched off through the tenant overlay.** With the reader's rule switched off in the app's overlay, the first package uninstalls with `200`, its field leaves the served object, and a write to the object lands. ## Acceptance notes - **Re-measure at branch start (premise holds).** On this rig with the check removed, `DELETE` answered `200`, the field left the served object and the package left the registry, and the next write to the object answered `400 VALIDATION_FAILED`: `Validation rule 'qx_tier_known' could not be evaluated (runtime: No such key: qx_tier) — write rejected.` - **Wording.** The uninstall refusal says what the uninstall would do: "which the uninstall would withdraw" and "or keep the package installed.", through a new optional third argument of `formatPackageDisableDependents`, `{ operation: 'disable' | 'uninstall' }`, default `'disable'`, whose sentence is byte-identical to before (seat rework 1). - **Only the HTTP door refuses.** The in-process uninstall verb (`deletePackage` in `@objectstack/metadata-protocol`) does not ask the verdict, so an in-process caller can still withdraw a read field. The claim scoped this card to the door; that question is raised in the report for the seat. - **Studio.** The Studio delete dialog shows the thrown `message`, so an admin sees the refusal sentence naming the rules. ## Verification <details><summary>Ablation: the check removed, the refusal pin goes red</summary> `node scripts/ablation-replace.mjs` replaced the verdict read in the DELETE arm with an empty list (anchor `1 -> 0`, blob `97f5c5fb5c8b -> 197d54665e7a`), then restored it (blob equals HEAD, `git diff HEAD` empty). The subject is imported from `src` through a relative path, so no `dist/` leg applies. ``` × answers 409 with the disable door's code and sentence under an uninstall lead, and nothing moves AssertionError: expected { status: 200, code: undefined } to deeply equal { status: 409, …(1) } ``` The two CONTROLs also went red, by cascade: the first case's uninstall had already removed the package they build on. </details> <details><summary>Local gates at head 0fc6353</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 62 commands; all 62 exit 0. Two first exited 3 on prerequisites and were rerun once the prerequisite was met: `node scripts/check-plugin-teardown-shape.mjs --self-test` (its pinned fixture commit was outside the shallow clone; fetched that one commit) and `pnpm check:dual-build-cjs-loads` (needed every package's `dist/`; ran after a full `pnpm build`). - `--ran` reconciliation: 62 derived, 62 run, 0 NOT-MEASURED, 0 UNRUN. - `pnpm --filter @objectstack/runtime test`: 554 files, 8930 passed, 19 skipped. - `pnpm --filter @objectstack/runtime typecheck`: exit 0. - `eslint packages/runtime --no-inline-config` (the root `pnpm lint` over the touched package): exit 0. - Dogfood battery: see the os-dev-report on #30999. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` is not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_017ihL2dtwL9RzJUEskoEex5)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a5e280f commit 57675a2

3 files changed

Lines changed: 201 additions & 5 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime)!: a package uninstall is refused while an active validation rule reads a field the package adds through `objectExtensions`
6+
7+
Clause-②: yes (narrowing) — `DELETE /api/v1/packages/:id` now refuses, with `409 PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`, an uninstall it used to perform: one whose package adds a field through `objectExtensions` that an active validation rule of another enabled package reads.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no stored row changes shape: what moves is the uninstall door's answer to a request that would leave a validation rule reading a withdrawn field. Nothing at rest records that answer, so there is nothing for a migration to rewrite. -->
11+
12+
**BREAKING** accept-set narrowing at the uninstall door (`@objectstack/runtime`): `DELETE /api/v1/packages/:id` asks the dependent-rule check the disable door (`PATCH /api/v1/packages/:id/disable`) already asks, and refuses on the same verdict.
13+
14+
- **Before.** The uninstall withdrew the package's `objectExtensions` fields from the served objects with no check. Another enabled package's active validation rule that read one of those fields then failed closed, so every write to that rule's object answered `400 VALIDATION_FAILED`, and with the package gone there was nothing left to re-enable.
15+
- **Now.** While such a rule exists, the uninstall answers `409` with the nested `{ "error": { "code": "PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE", "message" } }` body, and nothing moves: the stored rows, the running registry and the environment's disable record stay as they were. The message is the disable door's sentence in its uninstall form: `Package 'ID' cannot be uninstalled: an active validation rule reads a field it adds through objectExtensions, which the uninstall would withdraw — PACKAGE · OBJECT · RULE (reads FIELD). Switch off or change that rule first, or keep the package installed.`, naming every such rule with the fields it reads. The check is the one the package entry exports as `readPackageDisableDependents`; the sentence is `formatPackageDisableDependents`, which takes a new optional third argument, `{ operation: 'disable' | 'uninstall' }` (default `'disable'`, whose sentence is unchanged), so a host door that uninstalls answers the same words. An uninstall no rule depends on, and an uninstall of a package that is already disabled, proceed exactly as before.
16+
- **Who moves.** A caller that uninstalls a package whose field another package's active rule reads.
17+
18+
**The remedy.** Switch off or change the rules the message names first (a packaged rule can be switched off through the tenant overlay), then uninstall.

‎packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts‎

Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
* A formula over the field does not refuse the disable: it answers `null`.
4646
*/
4747

48-
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
48+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
4949
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5050
import { tmpdir } from 'node:os';
5151
import { join } from 'node:path';
@@ -1194,6 +1194,18 @@ describe('[#31067] the verdict the disable door asks is the package entry\'s exp
11941194
expect(runtime.formatPackageDisableDependents).toBe(disableDependentRulesMessage);
11951195
});
11961196

1197+
it('[#30999] the builder\'s uninstall form changes only the effect and the remedy; the default is the disable form', () => {
1198+
const dependents = [{ packageId: READER, object: THING, rule: RULE, fields: [FLAG] }];
1199+
const disable = runtime.formatPackageDisableDependents('LEAD', dependents);
1200+
expect(runtime.formatPackageDisableDependents('LEAD', dependents, { operation: 'disable' })).toBe(disable);
1201+
expect(runtime.formatPackageDisableDependents('LEAD', dependents, { operation: 'uninstall' })).toBe(
1202+
disable
1203+
.replace('which the disable would withhold', 'which the uninstall would withdraw')
1204+
.replace('or keep the package enabled.', 'or keep the package installed.'),
1205+
);
1206+
expect(disable).toContain('which the disable would withhold');
1207+
});
1208+
11971209
it('answers the active rules a disable would leave reading a withheld field, and writes nothing', async () => {
11981210
const { registry } = await door();
11991211
const dependents: runtime.DisableDependentRule[] = runtime.readPackageDisableDependents(registry, EXTENDER);
@@ -1232,3 +1244,128 @@ describe('[#31067] the verdict the disable door asks is the package entry\'s exp
12321244
expect(registry.getPackage(EXTENDER)?.enabled).toBe(false);
12331245
});
12341246
});
1247+
1248+
/**
1249+
* [#30999] `DELETE /packages/:id` withdraws the package's `objectExtensions`
1250+
* fields from the served object, as a disable withholds them, so it asks the
1251+
* disable door's verdict and answers its refusal: `409`
1252+
* `PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`, the sentence the exported
1253+
* builder spells over the exported verdict under an uninstall lead, BEFORE the
1254+
* uninstall verb is reached. Measured before this change on this rig: the
1255+
* uninstall answered `200`, the field left the served object, and every write
1256+
* to the object then answered `400 VALIDATION_FAILED`, the rule failing closed
1257+
* on the withdrawn field with no package left to re-enable.
1258+
*
1259+
* Two writable packages (installed as authored, so the door may delete them)
1260+
* extend the app's object with one field each; a third package's active rule
1261+
* reads the first one's field. The uninstall verb is the real one, spied on
1262+
* and passed through, so "the verb was never reached" and "the verb was handed
1263+
* the session user" are read off the request it received.
1264+
*/
1265+
describe('[#30999] the uninstall door refuses while an enabled package\'s validation rule reads a field the package adds', () => {
1266+
const TIERS = 'com.qa.uninstall.tiers';
1267+
const NOTES = 'com.qa.uninstall.notes';
1268+
const READER = 'com.qa.uninstall.reader';
1269+
const TIER = 'qx_tier';
1270+
const NOTE = 'qx_note';
1271+
const RULE = 'qx_tier_known';
1272+
const CODE = 'PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE';
1273+
const manifestOf = (id: string) => ({ id, name: id, version: '1.0.0', type: 'module' });
1274+
1275+
let root: string;
1276+
let booted: Booted | undefined;
1277+
let accountId: string;
1278+
let deletePackage: ReturnType<typeof vi.spyOn>;
1279+
1280+
beforeAll(async () => {
1281+
root = mkdtempSync(join(tmpdir(), 'os-suite-ext-uninstall-'));
1282+
writeFileSync(join(root, '.keep'), '');
1283+
process.env.OS_HOME = mkdtempSync(join(home, 'uninstall-'));
1284+
booted = await bootKernel(root);
1285+
const { kernel, engine } = booted;
1286+
for (const id of [TIERS, NOTES, READER]) engine.registry.installPackage(manifestOf(id) as any, 'authored');
1287+
engine.registry.registerObject({ name: ACCOUNT, fields: { [TIER]: { name: TIER, type: 'text', label: 'Tier' } } } as any, TIERS, undefined, 'extend');
1288+
engine.registry.registerObject({ name: ACCOUNT, fields: { [NOTE]: { name: NOTE, type: 'text', label: 'Note' } } } as any, NOTES, undefined, 'extend');
1289+
engine.registry.registerObject({
1290+
name: ACCOUNT,
1291+
validations: [{ name: RULE, type: 'script', severity: 'error', message: 'Unknown tier', condition: `record.${TIER} == 'unknown'` }],
1292+
} as any, READER, undefined, 'extend');
1293+
await engine.syncSchemas();
1294+
const created = await dispatchAs(kernel, 'POST', `/data/${ACCOUNT}`, { name: 'Acme', [TIER]: 'gold', [NOTE]: 'n' });
1295+
expect(created.status, `precondition: the account is written (${String(created.message)})`).toBe(201);
1296+
accountId = idOf(created);
1297+
deletePackage = vi.spyOn(kernel.getService<any>('protocol'), 'deletePackage');
1298+
}, 120_000);
1299+
afterAll(async () => {
1300+
deletePackage?.mockRestore();
1301+
await shutdown(booted);
1302+
rmSync(root, { recursive: true, force: true });
1303+
}, 60_000);
1304+
1305+
it('answers 409 with the disable door\'s code and sentence under an uninstall lead, and nothing moves', async () => {
1306+
const { kernel, engine } = booted!;
1307+
const disabledBefore = [...loadDisabledPackageIds(ENVIRONMENT_ID)].sort();
1308+
const expected = disableDependentRulesMessage(
1309+
`Package '${TIERS}' cannot be uninstalled`,
1310+
readDisableDependentRules(engine.registry, TIERS),
1311+
{ operation: 'uninstall' },
1312+
);
1313+
// The uninstall form says what the uninstall would do and which remedy
1314+
// keeps the field served; keeping the package ENABLED would not.
1315+
expect(expected).toBe(
1316+
`Package '${TIERS}' cannot be uninstalled: an active validation rule reads a field it adds through objectExtensions, `
1317+
+ `which the uninstall would withdraw — ${READER} · ${ACCOUNT} · ${RULE} (reads ${TIER}). Switch off or change that rule first, `
1318+
+ 'or keep the package installed.',
1319+
);
1320+
1321+
const refused = await dispatchAs(kernel, 'DELETE', `/packages/${TIERS}`);
1322+
expect({ status: refused.status, code: refused.code }).toEqual({ status: 409, code: CODE });
1323+
expect(String(refused.message)).toBe(expected);
1324+
expect(refused.details).toBeUndefined();
1325+
1326+
// Nothing moved: the verb was never reached, the package and its field
1327+
// stay served, the state file is as it was, and writes still land.
1328+
expect(deletePackage).not.toHaveBeenCalled();
1329+
expect(engine.registry.getPackage(TIERS)?.enabled).not.toBe(false);
1330+
expect(await servedFieldNames(kernel)).toEqual(expect.arrayContaining([TIER, NOTE]));
1331+
expect([...loadDisabledPackageIds(ENVIRONMENT_ID)].sort()).toEqual(disabledBefore);
1332+
const written = await dispatchAs(kernel, 'PATCH', `/data/${ACCOUNT}/${accountId}`, { [TIER]: 'silver' });
1333+
expect(written.status, String(written.message)).toBe(200);
1334+
expect(await readAccount(kernel, accountId)).toMatchObject({ [TIER]: 'silver' });
1335+
});
1336+
1337+
it('control: a package no rule depends on uninstalls as before, the verb handed the session user and the disable record cleared', async () => {
1338+
const { kernel, engine } = booted!;
1339+
// Disabled first, so the uninstall has a disable record to clear. The
1340+
// reader's rule stays active on the same object: it reads another field.
1341+
expect((await dispatchAs(kernel, 'PATCH', `/packages/${NOTES}/disable`)).status).toBe(200);
1342+
expect(loadDisabledPackageIds(ENVIRONMENT_ID).has(NOTES), 'precondition: the disable is recorded').toBe(true);
1343+
1344+
const uninstalled = await dispatchAs(kernel, 'DELETE', `/packages/${NOTES}`);
1345+
expect(uninstalled.status, String(uninstalled.message)).toBe(200);
1346+
expect(deletePackage).toHaveBeenCalledTimes(1);
1347+
expect(deletePackage).toHaveBeenCalledWith(expect.objectContaining({ packageId: NOTES, actor: ADMIN.userId }));
1348+
expect(engine.registry.getPackage(NOTES)).toBeUndefined();
1349+
expect(loadDisabledPackageIds(ENVIRONMENT_ID).has(NOTES)).toBe(false);
1350+
expect(await servedFieldNames(kernel)).not.toContain(NOTE);
1351+
});
1352+
1353+
it('control: proceeds once the reading rule is switched off through the tenant overlay, and writes still land', async () => {
1354+
const { kernel, engine } = booted!;
1355+
engine.registry.registerObject({
1356+
name: ACCOUNT, label: 'Account', fields: { name: { name: 'name', type: 'text', label: 'Name' } },
1357+
validations: [{ name: RULE, type: 'script', message: 'Switched off by the tenant', condition: 'true', active: false }],
1358+
_provenance: 'org',
1359+
} as any, APP, undefined, 'overlay');
1360+
const served = ((engine.registry.getObject(ACCOUNT) as any)?.validations ?? []) as Array<{ name?: string; active?: unknown }>;
1361+
expect(served.find((r) => r.name === RULE)?.active, 'precondition: the reader\'s rule is served, switched off').toBe(false);
1362+
1363+
const uninstalled = await dispatchAs(kernel, 'DELETE', `/packages/${TIERS}`);
1364+
expect(uninstalled.status, String(uninstalled.message)).toBe(200);
1365+
expect(deletePackage).toHaveBeenLastCalledWith(expect.objectContaining({ packageId: TIERS, actor: ADMIN.userId }));
1366+
expect(engine.registry.getPackage(TIERS)).toBeUndefined();
1367+
expect(await servedFieldNames(kernel)).not.toContain(TIER);
1368+
const written = await dispatchAs(kernel, 'PATCH', `/data/${ACCOUNT}/${accountId}`, { name: 'Acme Ltd' });
1369+
expect(written.status, String(written.message)).toBe(200);
1370+
});
1371+
});

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

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -898,7 +898,9 @@ function isDisableablePackage(engine: unknown, id: string | undefined): boolean
898898
* [#30379 ruling A, ADR-0141 Open items 4] The code `PATCH /packages/:id/disable`
899899
* answers, with `409`, while a validation rule of any enabled package (declared
900900
* dependent or not, an app's `.custom` pair included) reads a field the package
901-
* adds through `objectExtensions` ({@link readDisableDependentRules}). Registered
901+
* adds through `objectExtensions` ({@link readDisableDependentRules}). [#30999]
902+
* `DELETE /packages/:id` answers it too, on the same verdict: an uninstall
903+
* withdraws those fields as a disable withholds them. Registered
902904
* under `@objectstack/runtime` in `ERROR_CODE_LEDGER` (#30724); asserted by value.
903905
* The refusal carries the code and a message naming every rule, and no
904906
* `error.details` beyond the code: a machine-readable shape for the
@@ -1193,17 +1195,30 @@ function ruleLayerLabel(layer: { packageId?: unknown; ownership?: unknown }): st
11931195
* Exported as `formatPackageDisableDependents` from `@objectstack/runtime`
11941196
* beside {@link readDisableDependentRules}; a host door answers it with `409`
11951197
* `PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`, as this door does.
1198+
*
1199+
* [#30999] `operation` names what was refused, so the sentence says what that
1200+
* operation would do and which remedy keeps the field served: a disable
1201+
* (the default) would withhold the fields and is avoided by keeping the
1202+
* package enabled; an uninstall would withdraw them and is avoided by keeping
1203+
* the package installed. The default's bytes are the disable door's, unchanged.
11961204
*/
1197-
export function disableDependentRulesMessage(lead: string, dependents: readonly DisableDependentRule[]): string {
1205+
export function disableDependentRulesMessage(
1206+
lead: string,
1207+
dependents: readonly DisableDependentRule[],
1208+
{ operation = 'disable' }: { operation?: 'disable' | 'uninstall' } = {},
1209+
): string {
11981210
const one = dependents.length === 1;
11991211
const listed = dependents
12001212
.map((d) => `${d.packageId} · ${d.object} · ${d.rule} (reads ${d.fields.join(', ')})`)
12011213
.join('; ');
1214+
const [effect, kept] = operation === 'uninstall'
1215+
? ['which the uninstall would withdraw', 'or keep the package installed.']
1216+
: ['which the disable would withhold', 'or keep the package enabled.'];
12021217
return `${lead}: ${one
12031218
? 'an active validation rule reads a field'
12041219
: `${dependents.length} active validation rules read fields`} it adds through objectExtensions, `
1205-
+ `which the disable would withhold — ${listed}. Switch off or change ${one ? 'that rule' : 'those rules'} first, `
1206-
+ 'or keep the package enabled.';
1220+
+ `${effect} — ${listed}. Switch off or change ${one ? 'that rule' : 'those rules'} first, `
1221+
+ kept;
12071222
}
12081223

12091224
/**
@@ -3757,6 +3772,32 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin
37573772
// listing (and with it every object the package registers) until
37583773
// the next restart.
37593774
const readOnly = requireWritablePackage(deps, qlService, id, 'delete'); if (readOnly) return readOnly;
3775+
// [#30999, ADR-0141 Open items 4] The uninstall withdraws the
3776+
// package's `objectExtensions` fields from the served objects just
3777+
// as a disable withholds them, so it asks the disable door's
3778+
// verdict ({@link readDisableDependentRules}, never a second copy):
3779+
// while an active validation rule of any enabled package reads one
3780+
// of those fields, every write to the rule's object would be
3781+
// refused once the package is gone, with no package left to
3782+
// re-enable. Refused with the disable door's code and sentence
3783+
// ({@link disableDependentRulesMessage}, in its uninstall form) under an uninstall lead,
3784+
// BEFORE the protocol is resolved and `deletePackage`, the
3785+
// registry withdrawal and the disable-record clear below, so a
3786+
// refused uninstall leaves the stored rows, the running registry
3787+
// and the environment's state exactly as they were. A package
3788+
// already disabled withholds its fields already: the verdict is
3789+
// empty and the uninstall proceeds as before.
3790+
const dependents = readDisableDependentRules(registry, id);
3791+
if (dependents.length > 0) {
3792+
return {
3793+
handled: true,
3794+
response: deps.error(
3795+
disableDependentRulesMessage(`Package '${id}' cannot be uninstalled`, dependents, { operation: 'uninstall' }),
3796+
PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE.status,
3797+
{ code: PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE.code },
3798+
),
3799+
};
3800+
}
37603801
const protocol = await resolveProtocol(deps, _context);
37613802
const persists = Boolean(protocol && typeof protocol.deletePackage === 'function');
37623803

0 commit comments

Comments
 (0)