Skip to content

Commit 79a0d30

Browse files
fix(plugin-audit): a comment write leaves a ledger row and an activity row, stamped when the author was impersonated (#31128)
<!-- claude-projects-attribution: {"github_login":"marchtian"} --> _Requested by **田騏** · [project thread](https://claude.ai/code/project/chan_01VmuUhXU9SSUzqJYyXSmYSi?thread=cmsg_01VmuUhXU9SSUzqJYyXSmYSi9Hju7DThD7eoLKoJU9hnHj)_ Fixes #30979 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:评论(`sys_comment`)不再在审计镜像的跳过名单里。新建、编辑、删除评论现在和其他记录一样,各写一行审计(`sys_audit_log`)和一行动态(`sys_activity`);管理员模拟员工时写的评论,两行都带上「谁代谁」的标记。 - **为什么改**:按你在 #30213 选的 A(「A 评论也记审计和动态」)。之前模拟时写的评论和员工本人写的完全分不出来。 - **风险与回滚**:每条评论多两行数据;这两行只给能读这条评论(即能读评论所在记录)的人看,复用评论自己的读权限,没有新判断。记录详情页的动态流不会重复显示(它只读记录本身的动态)。回滚即撤销本 PR,已写下的行保留。 - **先看**:`packages/plugins/plugin-audit/src/audit-writers.ts`(跳过名单那一处);`src/activity-read-visibility.integration.test.ts` 末尾新增的读可见性用例。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-audit exec vitest run src/activity-actor-name.test.ts src/activity-read-visibility.integration.test.ts`,预期全部通过(34 条)。 - **需要你做的**:无,席位落地。 ## What changes - `packages/plugins/plugin-audit/src/audit-writers.ts`: `'sys_comment'` leaves `SKIP_OBJECTS`, so `AUDIT_EXCLUDED_OBJECTS` (derived from it) no longer lists it. A comment insert, update and delete now pass through `writeAudit` like any other object: one ledger row, one activity row, and PR #30800's impersonation stamp (`metadata.impersonated_by` on both, `impersonated_by_name` on the activity row) when the write came from an impersonation session. A comment above the list says why comments are not on it. Two stale code comments that said comments are skipped are corrected. No new column, no migration (option B was not chosen). - Readers of `AUDIT_EXCLUDED_OBJECTS`, checked: - the hook registrations' `excludeObjects` (the same list): comment writes now open the global after-phase hooks; - `parent-record-read-gate.ts` `enumerateParentObjects`: the activity and ledger gates now enumerate `sys_comment` as a parent. `sys_comment` carries an object-scoped read middleware (`installCommentReadVisibility`), so the planner routes it to the bounded probe (ADR-0139 D5.2), which reads `sys_comment` as the caller under that same comment gate. That is the read visibility the card asks for, with no second judgment; - `comment-access-hooks.ts` `commentThreadGate().namedParents`: it shrinks by `sys_comment`, which the comment gate already skips as its own gated object (`name === gate.object` is tested first), so the comment gate's parent set is unchanged. - Recursion: the "(1) recursion" group is about the audit and activity tables themselves, which stay listed. The writer writes only `sys_audit_log` and `sys_activity`; nothing it writes is a comment. - `.changeset/30979-comment-writes-audited.md`: patch for `@objectstack/plugin-audit`. ## Step 1 measurement: no timeline duplication (read at origin/main 5f00374) - The record page's 动态 stream reads `sys_activity` filtered to the RECORD's own pair: ui `RecordDetailView` `activityWindowQuery` (`object_name: objectName, record_id: recordId`), and the server record-page payload and timeline count (`packages/rest/src/record-page-routes.ts`, `where: { object_name: object, record_id: id }` and `ofRecord`). - The mirror writes a comment's activity row with `object_name: 'sys_comment'` and `record_id` the comment's id (`activityRow.object_name = ctx.object`), so it never matches the parent record's filter. No writer emits the `commented` activity type. - So a comment shows once on its record (from `sys_comment`), as before. Its new activity row appears only in the object-agnostic feeds (home recent activity, the bell's Activity tab, the `sys_activity` list) as a created/updated/deleted Comment entry, where no comment entry existed. No UI change is needed. ## Tests - `activity-actor-name.test.ts`, new describe "a comment written from an impersonation session is recorded like any other write": an impersonated comment insert writes one ledger row and one activity row, both stamped with the administrator; an impersonated edit and delete are stamped too; CONTROL: the user's own comment writes both rows, unstamped. - `activity-read-visibility.integration.test.ts`, new describe "a comment's ledger and activity rows are served only to a reader of the comment" (real kernel, real `AuditPlugin`, SQLite): each member is served the activity and ledger rows of the comment on its own record and neither row of the other member's comment (list, id-scoped find, count); controls: both comments' rows exist (system read), the comment gate answers each member its own comment, the admin is served both. - `audit-hook-object-scope.test.ts`: the two assertions that pinned `sys_comment` as excluded now pin the reverse (not in `excludeObjects`; the comment insert has a `create` ledger row). ## Acceptance notes - A holder of the ledger's audit capability (`view_all_audit_log`) keeps reading every ledger row of the organization, comment rows included, as for every other object (the gate's declared exemption). The activity stream has no exemption. - Comments written before this change have no rows; nothing is backfilled. - `os migrate comment-parent-pair --apply` boots `AuditPlugin` and updates unstamped comments through the engine as the system, so each stamped comment now also leaves one system-actor `update` ledger row and activity row. Raised for the seat in the report; not changed here (outside this card's file surface and a separate decision). - `identity-objects-feeds-off.test.ts` boots a `single` posture without a Default Organization, so its comment writes now print the writer's own one-time `Audit write FAILED ... ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` error line. That suite still passes; the line is the writer correctly reporting its harness. ## Verification All readings at head `8bc2feca4` (merge base `5f0037449` = current `origin/main`; no main commits since). - `bash scripts/pm/os-verify-lock.sh -c "pnpm --filter @objectstack/plugin-audit test"` :: exit 0 — Test Files 76 passed (76), Tests 1201 passed (1201). - `pnpm --filter @objectstack/plugin-audit typecheck` :: exit 0 (tsc src + scripts + test-typecheck). - `eslint --no-inline-config` over the four touched source and test files :: exit 0 (the package declares no lint script; the repo-wide `pnpm lint` is CI's). - Ablation 1, writer (`node scripts/ablation-replace.mjs`, anchor hit 1, restored blob == HEAD): `'sys_comment'` put back on `SKIP_OBJECTS` → `activity-actor-name.test.ts` + `activity-read-visibility.integration.test.ts`: 6 failed / 28 passed (all three impersonation pins, the CONTROL pin, the rows-exist control, the visibility pin and the admin control). Restored: green. - Ablation 2, read visibility: the comment read gate's registration (`engine.registerMiddleware(gate, { object: COMMENT_OBJECT })` in `comment-access-hooks.ts`) deleted → 2 failed / 14 passed: the comment-gate control and "a reader without read access to the comment's record is served neither of its rows" (`expected [ two comment ids ] to deeply equal [ one ]`: the other member's comment rows were served). Restored: green. So the rows' visibility is the comment gate's own answer, read through the probe. <details><summary>Derived gates: 65 / 65 exit 0 on the final head; `dispatch-gates --ran`: 65 derived, 65 run, 0 NOT-MEASURED, 0 UNRUN</summary> Three gates first answered exit 3 (PREREQUISITE NOT MET) and were re-run after the prerequisite: `check-plugin-teardown-shape --self-test` after fetching its pinned fixture commit, `check:dual-build-cjs-loads` and `check:i18n` after a full `pnpm build`. `check:query-options-erasure` first counted one new test-surface options cast; the cast was removed (`8bc2feca4`) and the whole list re-run on that head: ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:durability-log-level :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:i18n :: exit 0 pnpm check:i18n-stale-fill :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent af3451b commit 79a0d30

5 files changed

Lines changed: 226 additions & 9 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
---
4+
5+
fix(plugin-audit): a comment write leaves a ledger row and an activity row, stamped when the author was impersonated
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`sys_comment` is no longer on the audit writer's skip list. Creating, editing and deleting a comment now writes one `sys_audit_log` row and one `sys_activity` row, exactly like a write to any other object, and a comment written from an impersonation session carries the administrator in `metadata.impersonated_by` (and `impersonated_by_name` on the activity row). Before, such a comment could not be told from one the user wrote.
11+
12+
The rows name the comment as their parent (`object_name: 'sys_comment'`, `record_id`: the comment's id), so a record's own activity timeline does not show the comment twice; they appear in the object-agnostic feeds (the recent-activity feed, the Audit Logs list). A reader is served them only when it can read the comment, which means reading the record the comment is on: the activity and ledger read gates now enumerate `sys_comment` as a parent and ask the comment's own read gate. A holder of the ledger's audit capability keeps reading every ledger row of the organization, as before. Comments written before this change have no rows; nothing is backfilled.

‎packages/plugins/plugin-audit/src/activity-actor-name.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,3 +477,99 @@ describe('a write made from an impersonation session names the administrator bes
477477
expect(seen[0].provenance).toEqual({ impersonatedBy: GRACE });
478478
});
479479
});
480+
481+
/**
482+
* A comment is mirrored like every other write (maintainer ruling on #30213's
483+
* comments fork, 「A 评论也记审计和动态」): `sys_comment` is no longer on the
484+
* writer's skip list, so a comment written from an impersonation session
485+
* leaves the same two rows, with the same administrator stamp, as the task
486+
* above. Without it, a comment the administrator wrote as the user could not
487+
* be told from one the user wrote.
488+
*/
489+
describe('a comment written from an impersonation session is recorded like any other write', () => {
490+
const AUTHZ = {
491+
userId: ADA,
492+
tenantId: 'org_1',
493+
positions: ['member'],
494+
permissions: [],
495+
directPermissions: [],
496+
systemPermissions: [],
497+
org_user_ids: [ADA],
498+
accessible_org_ids: ['org_1'],
499+
};
500+
const envelope = (authz: Record<string, unknown>) =>
501+
assembleExecutionContext({
502+
authz: authz as any,
503+
oauth: undefined,
504+
localization: undefined,
505+
requestLocale: undefined,
506+
accessToken: undefined,
507+
authGate: undefined,
508+
}) as any;
509+
const impersonated = () => envelope({ ...AUTHZ, impersonatedBy: GRACE });
510+
const own = () => envelope({ ...AUTHZ });
511+
512+
/** The comment columns the writer reads; access and stamping hooks are not this file's subject. */
513+
const sysComment = {
514+
name: 'sys_comment', label: 'Comment', nameField: 'body',
515+
fields: {
516+
id: f('id', 'text', { primaryKey: true }), thread_id: f('thread_id', 'text'),
517+
body: f('body', 'textarea'), author_id: f('author_id', 'text'),
518+
},
519+
};
520+
const bootWithComments = async () => {
521+
const booted = await boot();
522+
booted.engine.registry.registerObject(sysComment as any, OWNER_PACKAGE);
523+
return booted;
524+
};
525+
const rowsAbout = (storeFor: (o: string) => Map<string, Record<string, unknown>>, table: string, id: string) =>
526+
Array.from(storeFor(table).values()).filter((r) => r.object_name === 'sys_comment' && r.record_id === id);
527+
const meta = (row: Record<string, unknown> | undefined) =>
528+
row?.metadata == null ? null : (JSON.parse(String(row.metadata)) as Record<string, unknown>);
529+
530+
it('an impersonated comment insert writes a ledger row and an activity row, both naming the administrator', async () => {
531+
const { engine, storeFor } = await bootWithComments();
532+
await engine.insert('sys_comment', { id: 'c1', thread_id: 'biz_task:t1', body: 'Looks good', author_id: ADA }, { context: impersonated() });
533+
534+
const [ledger, ...moreLedger] = rowsAbout(storeFor, 'sys_audit_log', 'c1');
535+
expect(moreLedger).toEqual([]);
536+
expect(ledger.action).toBe('create');
537+
expect(ledger.user_id).toBe(ADA);
538+
expect(meta(ledger)).toEqual({ impersonated_by: GRACE });
539+
540+
const [activity, ...moreActivity] = rowsAbout(storeFor, 'sys_activity', 'c1');
541+
expect(moreActivity).toEqual([]);
542+
expect(activity.type).toBe('created');
543+
expect(activity.actor_id).toBe(ADA);
544+
expect(meta(activity)).toMatchObject({ impersonated_by: GRACE, impersonated_by_name: 'Grace Hopper' });
545+
});
546+
547+
it('an impersonated edit and delete of a comment are recorded and stamped too', async () => {
548+
const { engine, storeFor } = await bootWithComments();
549+
await engine.insert('sys_comment', { id: 'c2', thread_id: 'biz_task:t1', body: 'Draft', author_id: ADA }, { context: own() });
550+
await engine.update('sys_comment', { body: 'Final' }, { where: { id: 'c2' }, context: impersonated() } as any);
551+
await engine.delete('sys_comment', { where: { id: 'c2' }, context: impersonated() } as any);
552+
553+
const ledger = rowsAbout(storeFor, 'sys_audit_log', 'c2');
554+
expect(ledger.map((r) => r.action)).toEqual(['create', 'update', 'delete']);
555+
expect(ledger.map((r) => meta(r)?.impersonated_by ?? null)).toEqual([null, GRACE, GRACE]);
556+
const activity = rowsAbout(storeFor, 'sys_activity', 'c2');
557+
expect(activity.map((r) => r.type)).toEqual(['created', 'updated', 'deleted']);
558+
expect(activity.map((r) => meta(r)?.impersonated_by ?? null)).toEqual([null, GRACE, GRACE]);
559+
});
560+
561+
it('control — the user\'s own comment writes both rows, unstamped', async () => {
562+
const { engine, storeFor } = await bootWithComments();
563+
await engine.insert('sys_comment', { id: 'c3', thread_id: 'biz_task:t1', body: 'Mine', author_id: ADA }, { context: own() });
564+
565+
const [ledger] = rowsAbout(storeFor, 'sys_audit_log', 'c3');
566+
expect(ledger.action).toBe('create');
567+
expect(ledger.user_id).toBe(ADA);
568+
expect(meta(ledger)).toBeNull();
569+
const [activity] = rowsAbout(storeFor, 'sys_activity', 'c3');
570+
expect(activity.type).toBe('created');
571+
expect(activity.actor_id).toBe(ADA);
572+
expect(meta(activity)).not.toHaveProperty('impersonated_by');
573+
expect(meta(activity)).not.toHaveProperty('impersonated_by_name');
574+
});
575+
});

‎packages/plugins/plugin-audit/src/activity-read-visibility.integration.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,102 @@ describe('sys_activity read visibility — the plugin read path', () => {
237237
expect(rows.length).toBe(allRows.length);
238238
});
239239
});
240+
241+
/**
242+
* A comment's own ledger and activity rows (maintainer ruling on #30213's
243+
* comments fork, 「A 评论也记审计和动态」): `sys_comment` is mirrored like any
244+
* other object, so both streams now hold rows whose parent is a comment. A
245+
* reader who cannot read the comment, because it cannot read the record the
246+
* comment is on, is not served them: the parent gates enumerate `sys_comment`
247+
* as a parent and, since the comment's read is narrowed by an object-scoped
248+
* middleware (`installCommentReadVisibility`), read it through the bounded
249+
* probe as the caller, so the comment's own thread gate decides. No second
250+
* judgment exists to drift from it.
251+
*
252+
* Same stand-in as above: the owned parent's middleware is the record's own
253+
* readability. The comments are written by their authors through the real
254+
* comment create path, which itself requires the parent to be readable.
255+
*/
256+
describe('a comment’s ledger and activity rows are served only to a reader of the comment', () => {
257+
const COMMENT = 'sys_comment';
258+
const LEDGER = 'sys_audit_log';
259+
let kernel: ObjectKernel;
260+
let engine: ObjectQL;
261+
const ids: Record<string, string> = {};
262+
263+
const aboutComments = async (object: string, context: object): Promise<string[]> =>
264+
(await engine.find(object, { where: { object_name: COMMENT }, context }))
265+
.map((r: Row) => String(r.record_id))
266+
.sort();
267+
268+
beforeAll(async () => {
269+
kernel = new ObjectKernel({ logger: { level: 'silent' } });
270+
await kernel.use(new ObjectQLPlugin());
271+
await kernel.use(singlePostureTenancy());
272+
await kernel.use(new AuditPlugin());
273+
await kernel.bootstrap();
274+
275+
engine = kernel.getService<ObjectQL>('objectql');
276+
const driver = new SqliteWasmDriver({ filename: ':memory:' });
277+
await driver.connect();
278+
engine.registerDriver(driver, true);
279+
engine.registry.registerObject(ownedObject as any, HARNESS_PACKAGE);
280+
await engine.syncSchemas();
281+
await installDefaultOrganization(engine);
282+
283+
engine.registerMiddleware(async (op: any, next: () => Promise<void>) => {
284+
if (READ_OPS.has(op.operation) && op.context && !op.context.isSystem && op.ast) {
285+
if (op.context.userId !== ADMIN.userId) {
286+
const mine = { owner: op.context.userId ?? '__nobody__' };
287+
op.ast.where = op.ast.where ? { $and: [op.ast.where, mine] } : mine;
288+
}
289+
}
290+
return next();
291+
}, { object: OWNED });
292+
293+
ids.mine = (await engine.insert(OWNED, { name: 'mine', owner: MEMBER.userId }, { context: SYS })).id;
294+
ids.theirs = (await engine.insert(OWNED, { name: 'theirs', owner: OTHER.userId }, { context: SYS })).id;
295+
// Each author comments on the record it can read.
296+
ids.myComment = (await engine.insert(COMMENT, { thread_id: `${OWNED}:${ids.mine}`, body: 'my note' }, { context: MEMBER })).id;
297+
ids.theirComment = (await engine.insert(COMMENT, { thread_id: `${OWNED}:${ids.theirs}`, body: 'their note' }, { context: OTHER })).id;
298+
}, 120_000);
299+
300+
afterAll(async () => {
301+
if (kernel) {
302+
await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
303+
}
304+
}, 30_000);
305+
306+
it('control: each comment write left one ledger row and one activity row, naming its author', async () => {
307+
const both = [ids.myComment, ids.theirComment].sort();
308+
expect(await aboutComments(LEDGER, SYS)).toEqual(both);
309+
expect(await aboutComments(ACTIVITY, SYS)).toEqual(both);
310+
const ledger = await engine.find(LEDGER, { where: { object_name: COMMENT }, context: SYS });
311+
const byComment = Object.fromEntries(ledger.map((r: Row) => [String(r.record_id), r]));
312+
expect(byComment[ids.myComment]).toMatchObject({ action: 'create', user_id: MEMBER.userId });
313+
expect(byComment[ids.theirComment]).toMatchObject({ action: 'create', user_id: OTHER.userId });
314+
});
315+
316+
it('control: the comment gate answers each member exactly the comment on its own record', async () => {
317+
expect((await engine.find(COMMENT, { context: MEMBER })).map((r: Row) => String(r.id))).toEqual([ids.myComment]);
318+
expect((await engine.find(COMMENT, { context: OTHER })).map((r: Row) => String(r.id))).toEqual([ids.theirComment]);
319+
});
320+
321+
it('a reader without read access to the comment’s record is served neither of its rows', async () => {
322+
expect(await aboutComments(ACTIVITY, MEMBER)).toEqual([ids.myComment]);
323+
expect(await aboutComments(LEDGER, MEMBER)).toEqual([ids.myComment]);
324+
expect(await aboutComments(ACTIVITY, OTHER)).toEqual([ids.theirComment]);
325+
expect(await aboutComments(LEDGER, OTHER)).toEqual([ids.theirComment]);
326+
// Scoped by id, the hidden comment's rows are absent too.
327+
const scoped = { object_name: COMMENT, record_id: ids.theirComment };
328+
expect(await engine.find(ACTIVITY, { where: scoped, context: MEMBER })).toEqual([]);
329+
expect(await engine.find(LEDGER, { where: scoped, context: MEMBER })).toEqual([]);
330+
expect(await engine.count(ACTIVITY, { where: scoped, context: MEMBER })).toBe(0);
331+
});
332+
333+
it('control: an admin, who reads every record, is served both comments’ rows', async () => {
334+
const both = [ids.myComment, ids.theirComment].sort();
335+
expect(await aboutComments(ACTIVITY, ADMIN)).toEqual(both);
336+
expect(await aboutComments(LEDGER, ADMIN)).toEqual(both);
337+
});
338+
});

‎packages/plugins/plugin-audit/src/audit-hook-object-scope.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,9 @@ describe('[#5860] the skip list is declared on the registration face', () => {
521521
// auth noise, and ADR-0057 operational telemetry.
522522
expect(excluded).toContain('sys_audit_log');
523523
expect(excluded).toContain('sys_activity');
524-
expect(excluded).toContain('sys_comment');
524+
// A comment is a person's act, so its writes are mirrored like any other
525+
// (ruling 「A 评论也记审计和动态」): it is not on the list.
526+
expect(excluded).not.toContain('sys_comment');
525527
expect(excluded).toContain('sys_job_queue');
526528
expect(excluded).not.toContain('biz_task');
527529
// Commit 69787f07b refuses both of these at registration; a spread of the real skip
@@ -609,7 +611,7 @@ describe('[#5860] the skip list is declared on the registration face', () => {
609611
await engine.insert('biz_task', { title: 'unrelated', status: 'todo' });
610612
expect(emit).not.toHaveBeenCalled();
611613

612-
// And sys_comment stays out of the ledger — it has its own feed.
613-
expect(auditRowsFor(storeFor, 'sys_comment')).toEqual([]);
614+
// And the comment write itself is in the ledger, like any mirrored write.
615+
expect(auditRowsFor(storeFor, 'sys_comment').map((r) => r.action)).toEqual(['create']);
614616
});
615617
});

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

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,15 @@ const SKIP_OBJECTS = new Set<string>([
258258
// (1) recursion + auth/session noise
259259
'sys_audit_log',
260260
'sys_activity',
261-
'sys_comment',
261+
// NOT `sys_comment`: a comment is an act a person performed, so its insert,
262+
// update and delete write the same ledger and activity rows as every other
263+
// mirrored write, an impersonated one stamped like the rest (maintainer
264+
// ruling on #30213's comments fork, 「A 评论也记审计和动态」). Its rows name
265+
// `sys_comment` as their parent, so the record timeline (which reads the
266+
// parent record's own pair) never draws them twice, and the parent-record
267+
// read gates serve them only to a reader the comment's own read gate admits
268+
// (`parent-record-read-gate.ts`: a parent narrowed by an object-scoped read
269+
// middleware is read through the bounded probe, as the caller).
262270
'sys_session',
263271
'sys_presence',
264272
'sys_account',
@@ -2481,8 +2489,8 @@ export function installAuditWriters(
24812489
// `showcase_task_assigned_notify` flow for a ready-made example.
24822490
//
24832491
// (Comment @mention notifications remain a platform behavior — they are
2484-
// handled separately by the sys_comment hook below, since SKIP_OBJECTS
2485-
// excludes it from this writer.)
2492+
// handled by the dedicated sys_comment hook below, which judges each
2493+
// mentioned reader; this writer records the comment write itself.)
24862494
await persistAuditTrailRow(api, auditRow, activityRowToWrite, progress);
24872495
} catch (err) {
24882496
// #5226 — DURABILITY degradation, not a functional one, so it is reported
@@ -2634,9 +2642,9 @@ export function installAuditWriters(
26342642
* M10.8: Dedicated hook on `sys_comment` afterInsert and afterUpdate that
26352643
* parses the `mentions` JSON field and writes one sys_notification per
26362644
* mentioned user who can read the comment and its record
2637-
* (`admitMentionRecipients`). Lives outside `writeAudit` because
2638-
* sys_comment is in SKIP_OBJECTS (we don't want audit/activity rows for
2639-
* comments — those have their own first-class feed).
2645+
* (`admitMentionRecipients`). Lives outside `writeAudit` because a
2646+
* notification is a per-recipient judgment, not the write's own record: the
2647+
* comment write itself is mirrored by `writeAudit` like any other.
26402648
*
26412649
* [#27703] An update judges only the mentions it ADDED — the entries of the
26422650
* written row's list that the bound pre-image (`ctx.previous`) did not carry

0 commit comments

Comments
 (0)