Skip to content

Commit f12b3c9

Browse files
committed
wip(audit): package_uninstall ledger row from the uninstall verb
Claude-Session: https://claude.ai/code/session_017ihL2bwU56eMCkj69h7Gd8 Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 169ff7e commit f12b3c9

8 files changed

Lines changed: 389 additions & 1 deletion

File tree

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

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ import { canonicalMetaType, captureUninstallDeclared, metadataReadFailureError,
4646
export interface PackageUninstallHost {
4747
readonly deleteMetaItem: ObjectStackProtocolImplementation['deleteMetaItem'];
4848
readonly engine: ObjectStackProtocolImplementation['engine'];
49+
/**
50+
* [#31186] The environment the protocol is bound to. The class field is
51+
* private, so it cannot be named by an indexed access; it is read for the
52+
* package's ledger row and nothing else.
53+
*/
54+
readonly environmentId: string | undefined;
4955
readonly findEnvironmentRows: ObjectStackProtocolImplementation['findEnvironmentRows'];
5056
readonly getServicesRegistry: ObjectStackProtocolImplementation['getServicesRegistry'];
5157
readonly packagelessAddress: ObjectStackProtocolImplementation['packagelessAddress'];
@@ -54,7 +60,7 @@ export interface PackageUninstallHost {
5460
}
5561

5662
/** 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> {
63+
export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMetaItem' | 'engine' | 'environmentId' | 'findEnvironmentRows' | 'getServicesRegistry' | 'packagelessAddress' | 'runUninstallCleanups' | 'shouldDropStorage'>, request: DeletePackageRequest): Promise<DeletePackageResponse> {
5864
// [ADR-0131 D6/D12] An uninstall is environment-wide by construction:
5965
// every `sys_metadata` row bound to the package, in this environment,
6066
// whatever organization a legacy row was stored under. The
@@ -140,6 +146,11 @@ export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMeta
140146
packageRegistry.assertPackageUninstallable(request.packageId);
141147
}
142148

149+
// [#31186] What the running registry holds for this id, read before
150+
// anything is removed: whether there is a package to uninstall at all, and
151+
// its version, for the package's own ledger row at the end of this verb.
152+
const installed = readInstalledPackage(packageRegistry, request.packageId);
153+
143154
// [#23473, ADR-0048] THE SHARED-OBJECT REFUSAL, ALSO ASKED BEFORE THE
144155
// STORE DELETE. A `sys_metadata` row is keyed by its package, so an
145156
// object this package holds can also be held by another package's row,
@@ -354,6 +365,24 @@ export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMeta
354365
// uninstall door calls too.
355366
const cleanups = await this.runUninstallCleanups({ ...request, ...(declared ? { declared } : {}) });
356367

368+
// [#31186] The package's own ledger row, written once, here, after its
369+
// stored row is gone — the one place every uninstall door passes. A
370+
// refusal above threw before this line, so it writes none. An id the
371+
// registry did not hold and the store bound no metadata to was not a
372+
// package, so it writes none either: the `DELETE` door answers that `404`.
373+
if (installed.held || deleted.length > 0 || failed.length > 0) {
374+
await recordPackageUninstall(this.getServicesRegistry?.()?.get('audit'), {
375+
action: 'package_uninstall',
376+
packageId: request.packageId,
377+
...(installed.version ? { version: installed.version } : {}),
378+
...(this.environmentId ? { environmentId: this.environmentId } : {}),
379+
...(request.actor ? { actor: request.actor } : {}),
380+
...(request.keepData === true ? { keepData: true } : {}),
381+
itemsRemoved: deleted.length,
382+
itemsFailed: failed.length,
383+
});
384+
}
385+
357386
return {
358387
success: failed.length === 0 && deleted.length > 0,
359388
deletedCount: deleted.length,
@@ -363,3 +392,61 @@ export async function deletePackage(this: Pick<PackageUninstallHost, 'deleteMeta
363392
cleanups,
364393
};
365394
}
395+
396+
/**
397+
* [#31186] The event the uninstall verb hands the `audit` slot's
398+
* `recordPackageLifecycleEvent` — declared here, structurally, so this package
399+
* does not depend on `@objectstack/plugin-audit`, which owns the row shape
400+
* (`package-lifecycle-audit.ts` there).
401+
*/
402+
export interface PackageUninstallAuditEvent {
403+
action: 'package_uninstall';
404+
packageId: string;
405+
version?: string;
406+
environmentId?: string;
407+
actor?: string;
408+
keepData?: boolean;
409+
itemsRemoved: number;
410+
itemsFailed: number;
411+
}
412+
413+
/** The `audit` slot member the verb calls. */
414+
interface PackageLifecycleAuditSurface {
415+
recordPackageLifecycleEvent?(event: PackageUninstallAuditEvent): unknown;
416+
}
417+
418+
/** Whether the registry holds `packageId`, and the version it holds. Never throws. */
419+
function readInstalledPackage(registry: unknown, packageId: string): { held: boolean; version?: string } {
420+
try {
421+
const pkg = (registry as { getPackage?(id: string): unknown } | undefined)?.getPackage?.(packageId) as
422+
| { manifest?: { version?: unknown } }
423+
| undefined;
424+
if (pkg === undefined || pkg === null) return { held: false };
425+
const version = pkg.manifest?.version;
426+
return { held: true, ...(typeof version === 'string' && version !== '' ? { version } : {}) };
427+
} catch {
428+
// A registry that cannot answer is not asked again: the row is then
429+
// written only when stored items were removed, without a version.
430+
return { held: false };
431+
}
432+
}
433+
434+
/**
435+
* Hand the event to the `audit` slot. A host with no audit plugin has no
436+
* ledger at all, so the call is skipped silently. The writer never throws; a
437+
* slot that does anyway is a foreign writer, and the uninstall it reports on
438+
* has already completed, so its failure is logged, never answered.
439+
*/
440+
async function recordPackageUninstall(audit: unknown, event: PackageUninstallAuditEvent): Promise<void> {
441+
const record = (audit as PackageLifecycleAuditSurface | undefined)?.recordPackageLifecycleEvent;
442+
if (typeof record !== 'function') return;
443+
try {
444+
await record.call(audit, event);
445+
} catch (e) {
446+
console.error(
447+
`[protocol.deletePackage] '${event.packageId}' was uninstalled, but the audit service refused its `
448+
+ '`package_uninstall` row, so the compliance ledger does not record who uninstalled it: '
449+
+ `${(e as Error)?.message ?? String(e)}`,
450+
);
451+
}
452+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10937,9 +10937,11 @@ export class ObjectStackProtocolImplementation implements
1093710937
// [#25467 cut 35] The body moved to `protocol-package-uninstall.ts` (see `PackageUninstallHost`).
1093810938
const readEngine = () => this.engine;
1093910939
const readGetServicesRegistry = () => this.getServicesRegistry;
10940+
const readEnvironmentId = () => this.environmentId;
1094010941
const host: ThisParameterType<typeof deletePackage> = {
1094110942
deleteMetaItem: (...a) => this.deleteMetaItem(...a),
1094210943
get engine() { return readEngine(); },
10944+
get environmentId() { return readEnvironmentId(); },
1094310945
findEnvironmentRows: (...a) => this.findEnvironmentRows(...a),
1094410946
get getServicesRegistry() { return readGetServicesRegistry(); },
1094510947
packagelessAddress: (...a) => this.packagelessAddress(...a),

‎packages/plugins/plugin-audit/src/audit-plugin.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit
3131
import { createAuthEventAuditSink } from './auth-event-audit.js';
3232
import { createActionInvocationAuditWriter } from './action-invocation-audit.js';
3333
import { createDataExportAuditWriter } from './data-export-audit.js';
34+
import { createPackageLifecycleAuditWriter } from './package-lifecycle-audit.js';
3435
import { installCommentAccessHooks, installCommentReadVisibility } from './comment-access-hooks.js';
3536
import {
3637
COMMENT_REACTION_REMOVE_ROUTE,
@@ -326,6 +327,12 @@ export class AuditPlugin implements Plugin {
326327
// export door resolves it per request and hands it one event per export
327328
// it streamed, so every export of every object, this ledger included,
328329
// leaves a run-level `export` row (`data-export-audit.ts`).
330+
//
331+
// [#31186] And the package lifecycle writer (`recordPackageLifecycleEvent`):
332+
// the uninstall verb (`deletePackage` in `@objectstack/metadata-protocol`)
333+
// resolves it per call and hands it one event per package it uninstalled,
334+
// so the package itself leaves a `package_uninstall` row
335+
// (`package-lifecycle-audit.ts`).
329336
const getLedgerEngine = (): IDataEngine | undefined => {
330337
try {
331338
return ctx.getService<IDataEngine>('objectql');
@@ -343,6 +350,7 @@ export class AuditPlugin implements Plugin {
343350
...createAuthEventAuditSink({ getEngine: getLedgerEngine, logger: ctx.logger }),
344351
...createActionInvocationAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
345352
...createDataExportAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
353+
...createPackageLifecycleAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
346354
});
347355

348356
// ADR-0029 D8 — contribute this plugin's object translations to the i18n

‎packages/plugins/plugin-audit/src/index.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,19 @@ export type {
4141
ExportFilterSummary,
4242
ExportFilterTerm,
4343
} from './data-export-audit.js';
44+
// [#31186] The `package_uninstall` row writer the uninstall verb reaches
45+
// through the `audit` slot.
46+
export {
47+
buildPackageLifecycleAuditRow,
48+
createPackageLifecycleAuditWriter,
49+
PACKAGE_UNINSTALL_AUDIT_ACTION,
50+
} from './package-lifecycle-audit.js';
51+
export type {
52+
PackageLifecycleAuditAction,
53+
PackageLifecycleAuditEvent,
54+
PackageLifecycleAuditWriter,
55+
PackageLifecycleAuditWriterOptions,
56+
} from './package-lifecycle-audit.js';
4457
export {
4558
createReadAuditBatcher,
4659
extractDetailReadId,

‎packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ describe('sys_audit_log.action option labels', () => {
3131
'platform_admin_standing_change',
3232
// #27908: a new value, added writer-first; no existing value moved.
3333
'action_invocation',
34+
// #31186: a new value, added writer-first; no existing value moved.
35+
'package_uninstall',
3436
]);
3537
});
3638

‎packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ const ACTIONS_WITH_WRITERS: ReadonlyArray<readonly [action: string, writer: stri
105105
+ 'slot; called by runtime/src/domains/actions.ts (REST door) and runtime/src/action-execution.ts + '
106106
+ 'runtime/src/domains/mcp.ts (MCP run_action / resume_run) (#27908)',
107107
],
108+
[
109+
'package_uninstall',
110+
'plugin-audit/src/package-lifecycle-audit.ts — createPackageLifecycleAuditWriter on the `audit` slot; '
111+
+ 'called by metadata-protocol/src/protocol-package-uninstall.ts (deletePackage, the uninstall verb '
112+
+ 'every door reaches) once per package it uninstalled (#31186)',
113+
],
108114
];
109115

110116
/** Option values declared by the `action` select field. */

‎packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,18 @@ export const SysAuditLog = ObjectSchema.create({
390390
// above, as for `platform_admin_standing_change`. No new column: the
391391
// surface rides `metadata` beside `performed_by` / `on_behalf_of`.
392392
//
393+
// [#31186] `package_uninstall` joins the enum WRITER-FIRST. Its writer is
394+
// `package-lifecycle-audit.ts` (`createPackageLifecycleAuditWriter`, on the
395+
// `audit` slot), called by the uninstall verb (`deletePackage` in
396+
// `@objectstack/metadata-protocol`) once per package it uninstalled, from
397+
// every door that reaches the verb: one row about the package itself, which
398+
// `sys_packages`'s raw-SQL delete never produced. The row names no record
399+
// (`sys_packages` is not an object) and no organization (an uninstall is
400+
// environment-wide), so it is a deployment-level row; the package, its
401+
// version and the environment ride `metadata`. Its shipped surfaces are the
402+
// unfiltered `recent` and `all_events` views above, as for
403+
// `platform_admin_standing_change`.
404+
//
393405
// Each option carries a label (#27855): the list, the detail and the System
394406
// Overview "Audit Events by Action" chart (whose dimension resolves through
395407
// these options) read it, where the bare-array shorthand made the label the
@@ -410,6 +422,7 @@ export const SysAuditLog = ObjectSchema.create({
410422
{ label: 'Export', value: 'export' },
411423
{ label: 'Platform Admin Standing Change', value: 'platform_admin_standing_change' },
412424
{ label: 'Action Invocation', value: 'action_invocation' },
425+
{ label: 'Package Uninstall', value: 'package_uninstall' },
413426
],
414427
label: 'Action',
415428
required: true,

0 commit comments

Comments
 (0)