Skip to content

Commit a1082f3

Browse files
fix(plugin-audit): mark in-product AI calls on the action-invocation, data-export and dataset-query audit rows (#34679)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi99ewj5JRWXTB3u38E9HLhnj)_ Fixes #34556 Clause-②: no Metadata-protocol: none Spec surface: since round r2 this PR touches `packages/spec/src` (describe and JSDoc prose only, no key, type or refine), so it owes an L2 contract review and the seat's Tier H step before it lands. ## 维护者速读 1. **改了什么**:产品内 AI 替某人执行动作、导出数据、查询数据集时,这三类审计行现在和记录写入行一样,写明是哪个 AI(`performed_by`)、替谁(`on_behalf_of`)、在哪次对话(`conversation_id`)、经哪次确认(`confirmation_id`,没确认就不写)。spec 里描述这件事的说明文字同步改正(只改文字,不改字段)。 2. **为什么改**:之前这三类行只认 OAuth 客户端,产品内 AI 做的动作、导出、查询在审计日志里和本人亲手操作一模一样,查不到是哪次 AI 对话、哪次确认触发的。 3. **风险与回滚**:只在 metadata 里加键,`user_id` / `actor` 仍是本人;OAuth 客户端的行和本人亲手操作的行不变。四类行现在共用一个规则函数,记录写入行的行为不变(原有 15 条钉子测试全绿)。回滚即撤本 PR,历史行不受影响。 4. **先看**:`packages/plugins/plugin-audit/src/audit-writers.ts`(新的 `auditPerformerMetadata` 与记录写入处的调用)、`packages/spec/src/kernel/execution-context.zod.ts`(`performedBy` 的 describe 与 JSDoc 改句)、三个写入器各自的一行接线与三个测试文件末尾新增的 describe。 5. **两分钟验证**:`pnpm --filter @objectstack/plugin-audit exec vitest run src/action-invocation-audit.test.ts src/data-export-audit.test.ts src/dataset-query-audit.test.ts src/agent-dual-attribution.integration.test.ts`,预期 4 个文件 62 条全绿,其中 9 条是本卡新用例。 6. **需要你做的**:本 PR 改了 `packages/spec/src` 的说明文字,契约复审(L2)通过后按席位的 Tier H 流程由你确认落地。 ## What changes - **One performer rule for every `sys_audit_log` writer.** PR #34547 wrote the in-product AI rule inline in the record-write writer (`installAuditWriters`), reading `HookContext.provenance` through a private reader. This PR moves that rule, unchanged, into one exported function in `audit-writers.ts`, `auditPerformerMetadata(performer, onBehalfOf)`, which takes the `ExecutionContext.performedBy` shape (`clientId`, `agentId`, `conversationId`, `confirmationId`) and returns the metadata keys or nothing. The record-write writer now calls it with its four `provenance` marks. The rule is the one #34547 settled: - `performed_by` is the OAuth client, else the in-product agent; `on_behalf_of` is the row's own `user_id` value; - `conversation_id` / `confirmation_id` are written only when the in-product agent is the recorded performer, each only when stamped; - an envelope naming both performers records the OAuth client and drops the agent with its two marks; - no performer ⇒ none of these keys. - **The three writers apply it.** `action-invocation-audit.ts`, `data-export-audit.ts` and `dataset-query-audit.ts` read `performedBy.clientId` only. Each now calls `auditPerformerMetadata(ctx.performedBy, userId)` in place of its own two-key block. All three write `sys_audit_log` and keep `metadata` as one JSON text column, so no column or key is added. Their header comments now name the two marks. - **`hook-bodies.mdx`.** The `ctx.provenance` table listed `performedByClientId` only. It now lists `performedByAgentId`, `performedByConversationId`, `performedByConfirmationId` and `impersonatedBy`, which the hook-body sandbox already copies (`packages/runtime/src/sandbox/body-runner.ts`). `performedByAgentId` is included because the other two are defined as set beside it. - **Spec describes (round r2).** `packages/spec/src/kernel/execution-context.zod.ts`: the `performedBy` describe and JSDoc said "The action-invocation, data-export and dataset-query rows record clientId only", which this PR makes false. They now say those rows "record the performer and the two marks by the same rule". The reader rule there, and in `packages/spec/src/data/hook.zod.ts`'s `performedByAgentId` describe, also takes the L2 nit N3 from record 6937613475: "where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string". No key, type, refine or optionality moves. `content/docs/references/**` regenerated (`gen:docs`): `kernel/execution-context.mdx`, `data/data-engine.mdx` (12 `performedBy` rows), `data/hook.mdx`. - Changeset `.changeset/34556-audit-ai-marks-three-rows.md`: `@objectstack/plugin-audit` patch, `@objectstack/spec` patch (describe text ships). `auditPerformerMetadata` is exported from the module, not from the package entry (`src/index.ts` is unchanged), so the published API surface does not change. ## Enumeration (from the card) - [x] action-invocation audit row: pinned by `action-invocation-audit.test.ts` › "[#33694] an in-product AI call is marked on the action_invocation row by the CRUD mirror's rule" (the AI row is written and read back through a real ObjectQL engine). - [x] data-export audit row: pinned by `data-export-audit.test.ts` › "[#33694] an in-product AI export is marked on the export row by the CRUD mirror's rule". - [x] dataset-query audit row: pinned by `dataset-query-audit.test.ts` › "[#33694] an in-product AI query is marked on the dataset_query row by the CRUD mirror's rule". - [x] `hook-bodies.mdx`: the `ctx.provenance` table lists `performedByConversationId` and `performedByConfirmationId` (and `performedByAgentId`, and since L1 R1 `impersonatedBy`) beside `performedByClientId`. Docs only, no test. ## Tests Each of the three describes has three cases: - An AI-performed call (`performedBy: { agentId, conversationId, confirmationId }`) records `performed_by` = agent, `on_behalf_of` = person, `conversation_id`, `confirmation_id`; `user_id` stays the person. - CONTROL: an OAuth client with a conversation and a confirmation, and an envelope naming both a client and an agent, each record only `{ performed_by: client, on_behalf_of }` and no marks. - CONTROL: a person's own call carries none of the four keys. No existing test changed. `agent-dual-attribution.integration.test.ts` (the record-write pins #34547 added) passes unchanged against the extracted function. ## Acceptance notes - **Round r2 (seat chose option A).** The spec sentence this PR made false is corrected in this PR, as described above, instead of in a follow-up card. `hook.zod.ts` carried no "clientId only" claim; it is touched only to carry N3 in the third place the reader rule is stated. - **L1 R1 (record 6941727354).** The `ctx.provenance` table in `hook-bodies.mdx` now also lists `impersonatedBy`, which the sandbox copies (`packages/runtime/src/sandbox/body-runner.ts`), so every member it carries has a row. Commit `f62fa7ad00`, one docs line. - Merge probe against PR #34545 (`claude/project-thread-l1nf08`, which also edits `hook-bodies.mdx`): `git merge-tree --write-tree --name-only HEAD origin/claude/project-thread-l1nf08` reports `Auto-merging content/docs/automation/hook-bodies.mdx` with no conflict in that file. The one textual conflict it reports, `packages/spec/dropped-refinements.baseline.json`, is between #34545 and `main` and is not in this diff. The three-ref form in the dispatch (`git merge-tree --write-tree origin/main HEAD BRANCH`) is not valid syntax and exits 129, so the two-ref form was used. This is a local probe with the repo's merge driver registered, not GitHub's mergeability. ## Verification <details><summary>Round r2, at head 5f005fb (after merging origin/main twice)</summary> - Commits: `49dc838adb` (spec prose: the two spec files), `c5eafdb182` (regenerated references), `19d92fd27e` (changeset), then the merge of `origin/main` at `5f005fb26a`. - `pnpm --filter @objectstack/spec build` under the lock: exit 0. `pnpm --filter @objectstack/spec gen:docs`: exit 0, three reference pages changed (14 lines). `pnpm --filter @objectstack/spec check:generated`: "All 14 generated artifacts are up to date", exit 0. The first attempt reported `test-typecheck-debt.json` with "tsc -p tsconfig.test.json failed without diagnostics": a JavaScript heap OOM under the 4096 MB default on this shared box, not staleness. It was re-run with `--max-old-space-size=6144`, and the later gate sweep at 4096 was green too. - No remaining copy of "record clientId only" in `packages/spec/src` or `content/docs/references`. - `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2 src/kernel/execution-context.test.ts src/data/hook.test.ts`: Test Files 2 passed (2), Tests 146 passed (146). - plugin-audit after the final merge: closure build exit 0; `vitest run --maxWorkers=2` gives Test Files 101 passed (101), Tests 1696 passed (1696); typecheck exit 0. - Full workspace build (`turbo run build --concurrency=2 --filter=!@objectstack/docs`): 119 of 119 tasks successful. - `dispatch-gates --commands` derived 119 commands at this head. All ran with stdin closed and the exit taken before any pipe; all exited 0. `--ran`: "119 derived famil(ies) accounted for — 119 run, 0 NOT-MEASURED". </details> Round 1 readings below were taken at head `41a26f1134` (after merging `origin/main` `e5336512f`). The plugin-audit code has not changed since. <details><summary>Build, tests, typecheck</summary> - `pnpm --filter '@objectstack/plugin-audit^...' build` under the verify lock: exit 0. - `pnpm --filter @objectstack/plugin-audit exec vitest run --maxWorkers=2 src/action-invocation-audit.test.ts src/data-export-audit.test.ts src/dataset-query-audit.test.ts src/agent-dual-attribution.integration.test.ts`: Test Files 4 passed (4), Tests 62 passed (62). - `pnpm --filter @objectstack/plugin-audit exec vitest run --maxWorkers=2` (whole package): Test Files 101 passed (101), Tests 1696 passed (1696). - `pnpm --filter @objectstack/plugin-audit typecheck`: exit 0; `check:test-typecheck: OK`, 0 errors. </details> <details><summary>Ablations (scripts/ablation-replace.mjs; tests import the writers from src)</summary> Each writer's wiring `Object.assign(metadata, auditPerformerMetadata(ctx.performedBy, userId));` replaced by the old client-only reading `auditPerformerMetadata({ clientId: ctx.performedBy?.clientId }, userId)`. Anchor 1 → 0 each time; restored blob == HEAD and `git diff HEAD` empty each time. - `action-invocation-audit.ts` → its pin "an AI-performed call records the agent, the person, the conversation and the confirmation" FAILS: Tests 1 failed / 13 passed (14). - `data-export-audit.ts` → "an AI-performed export records …" FAILS: Tests 1 failed / 18 passed (19). - `dataset-query-audit.ts` → "an AI-performed query records …" FAILS: Tests 1 failed / 13 passed (14). The shared rule in `audit-writers.ts`: `agentIsRecordedPerformer = !performedByClientId && performedByAgentId !== undefined` replaced by `performedBy !== undefined`, run over the four files: Tests 5 failed / 57 passed (62). The three new CONTROL pins (client alone or beside an agent) fail, and so do #34547's two record-write pins ("never ride beside an OAuth client id", "an envelope naming both performers"). Restored blob == HEAD. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 102 commands for this diff. Each was run with stdin closed and its exit taken before any pipe. - Three first exited 3 (prerequisite not met: no built output): `check:skill-examples`, `check:dual-build-cjs-loads`, `check:i18n`. After `turbo run build --concurrency=2 --filter=!@objectstack/docs` under the lock (exit 0), each re-ran with exit 0. - `dispatch-gates --ran`: "102 derived famil(ies) accounted for — 102 run, 0 NOT-MEASURED". Exit 0. - Not run locally, left to CI: the repo-wide scans, `test:repo`, and the dogfood battery. The title has no `!` and the claim has no `(narrowing)` arm. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmSYVw1sqCsaHSJS9JC <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmSYVw1sqCsaHSJS9JC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f02f4f6 commit a1082f3

14 files changed

Lines changed: 281 additions & 77 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
Clause-②: no
7+
Metadata-protocol: none
8+
9+
The action-invocation, data-export and dataset-query rows in `sys_audit_log` now mark an in-product AI call the way the record-write row does. When the in-product AI performed the call for a person, `metadata` carries `performed_by` (the agent) beside `on_behalf_of` (the person), plus `conversation_id` and, when the person confirmed the call, `confirmation_id`. Before, these three rows read only an OAuth client from `performedBy` and recorded an in-product AI call as the person's own. An OAuth client stays the recorded performer, also when an envelope names both, and its rows never carry the two marks. A person's own call is unchanged. All four row kinds now apply one shared rule inside the package.
10+
11+
In `@objectstack/spec`, the `ExecutionContext.performedBy` describe no longer says these three rows record `clientId` only. It now says they record the performer and the two marks by the same rule. The reader rule there and in the `HookContext.provenance.performedByAgentId` describe now also says which tell decides when both apply. The change is describe text only, with no change to schema shape.

‎content/docs/automation/hook-bodies.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ A hook body sees the same server-stamped write provenance an in-process handler
119119
| `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. |
120120
| `ctx.provenance.attributedUserId` | The write is authorized as the system and credited to a real person (for example, the admin behind an identity-adapter call). |
121121
| `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. |
122+
| `ctx.provenance.performedByAgentId` | The in-product AI agent performed the write for the signed-in person in `ctx.session.userId`, whose write it runs as; the value is the agent's name. |
123+
| `ctx.provenance.performedByConversationId` | Set beside `performedByAgentId`: the AI conversation the write was performed in. |
124+
| `ctx.provenance.performedByConfirmationId` | Set beside `performedByAgentId` when the person confirmed the call first: the id of the pending item their approval decided. Absent when the write needed no confirmation. |
125+
| `ctx.provenance.impersonatedBy` | An administrator made the write from an impersonation session; the value is that administrator's `sys_user` id, while `ctx.session.userId` stays the impersonated user the write is authorized as. Attribution only: nothing authorizes on it. |
122126

123127
Each member is a string or absent, and `ctx.provenance` itself is **absent** when none applies — a plain REST write carries no provenance — so read it as `ctx.provenance?.flowRunId`. That is the guard that tells a flow's write apart from a user writing the same fields by hand, which matters most for a flow that runs `runAs: 'user'`: there `ctx.user`, `ctx.session` and `ctx.input` are identical for both writes.
124128

‎content/docs/references/data/data-engine.mdx‎

Lines changed: 12 additions & 12 deletions
Large diffs are not rendered by default.

‎content/docs/references/data/hook.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
156156
| **flowRunId** | `string` | optional | Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request. |
157157
| **attributedUserId** | `string` | optional | The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth `update-member-role` call the identity adapter executes as `isSystem`. ATTRIBUTION ONLY: the audit writer records it as `sys_audit_log.user_id`; no security middleware reads it, and it never becomes the subject the write is authorized as. |
158158
| **performedByClientId** | `string` | optional | [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, the `client_id` of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in `session.userId`. Copied from `ExecutionContext.performedBy.clientId`, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like `attributedUserId`: the audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork. |
159-
| **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. |
159+
| **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. |
160160
| **performedByConversationId** | `string` | optional | The AI conversation an in-product AI write was performed in. Copied from `ExecutionContext.performedBy.conversationId`, set beside `performedByAgentId`. ATTRIBUTION ONLY: the record-write audit writer records it as `sys_audit_log.metadata.conversation_id`, only when `performed_by` names the in-product agent; no security middleware reads it. |
161161
| **performedByConfirmationId** | `string` | optional | The confirmation the person gave before an AI-performed write ran: the id of the pending item their approval decided. Copied from `ExecutionContext.performedBy.confirmationId`; absent when the write needed no confirmation. ATTRIBUTION ONLY: the record-write audit writer records it as `sys_audit_log.metadata.confirmation_id`, only when `performed_by` names the in-product agent; no security middleware reads it, and it is never the authorization for the write, which runs as the person with every gate re-checked. |
162162
| **impersonatedBy** | `string` | optional | The ADMINISTRATOR (a sys_user id) who made this write from an impersonation session, while `session.userId` is the impersonated user the write is authorized as. Copied from `ExecutionContext.impersonatedBy`, which the shared request-identity resolution sets from the session read. ATTRIBUTION ONLY, exactly like `performedByClientId`: the audit writer records it as `sys_audit_log.metadata.impersonated_by` and on the sys_activity row; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the user made themselves. |

‎content/docs/references/kernel/execution-context.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ const result = AuthGateCodeSchema.parse(data);
6464
| **posture** | `Enum<'PLATFORM_ADMIN' \| 'TENANT_ADMIN' \| 'MEMBER' \| 'EXTERNAL'>` | optional | ADR-0095 D2 posture rung — PLATFORM_ADMIN crosses the tenant wall where object posture permits; TENANT_ADMIN sees all rows in the org; MEMBER gets business RLS; EXTERNAL (an external organization member) reaches explicit grants only — shares, sharing rules, and grant RLS — never the OWD baseline. |
6565
| **authGate** | `{ code: Enum<'PASSWORD_EXPIRED' \| 'PASSWORD_RESET_REQUIRED' \| 'MFA_REQUIRED'>; message: string }` | optional | ADR-0069 authentication-policy gate: present only while the principal is blocked from protected resources until they remediate (expired password, enforced MFA), absent for every healthy session. `code` is the stable machine code the client branches on, from the closed vocabulary PASSWORD_EXPIRED / PASSWORD_RESET_REQUIRED (an administrator forced a password change) / MFA_REQUIRED, and `message` is what the blocked user reads; both are required because the transport seam renders them as the 403 body. Each code declares a scope: MFA_REQUIRED holds the account, so an API key whose owner holds it is refused with the same 403; PASSWORD_EXPIRED and PASSWORD_RESET_REQUIRED hold password sign-in alone, and API keys of that owner keep working. AUTHENTICATION, not authorization — it suspends access entirely rather than narrowing it, and nothing in the permission/RLS path reads it, while the allow-listed remediation endpoints stay reachable. Server-constructed only, never client-supplied; a guest/anonymous principal never carries one. |
6666
| **onBehalfOf** | `{ userId: string; principalKind?: Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'> }` | optional | |
67-
| **performedBy** | `{ clientId?: string; agentId?: string; conversationId?: string; confirmationId?: string }` | optional | ADR-0090 D10 rule 4 dual attribution: what PERFORMED this operation, when the performer is not the principal the write is authorized as. Two server-side producers set it: the /mcp OAuth door names the agent client in clientId, on the same branch that decides principalKind: agent and onBehalfOf; the server-constructed in-product AI path, acting for the signed-in person and running as them, names its agent in agentId with conversationId and, when the person confirmed the call, confirmationId. Absent everywhere else, and the absence is the record that the principal acted for itself; when present it names its performer, at least one of clientId and agentId, each set only by its own producer. ATTRIBUTION ONLY — no security middleware reads it, it never becomes the authorization subject, and userId stays the human so owner-stamping and current_user.* RLS still resolve to them. Server-constructed only, never client-supplied: an id a request named (an agent name, a conversation, a pending item) is stamped only after the server resolved it in its own store for the person in userId, and an unresolved id is not stamped. Surfaced to hooks as HookContext.provenance.performedByClientId / performedByAgentId / performedByConversationId / performedByConfirmationId. The record-write audit writer records the performer (clientId, or agentId for the in-product AI) as sys_audit_log.metadata.performed_by beside on_behalf_of, so that key holds two id kinds. Only when the agent is the recorded performer does the row also carry conversationId as metadata.conversation_id and confirmationId as metadata.confirmation_id (each when set); a client row never carries them. A reader can tell: a value matching the client_id of an existing sys_oauth_application row is an OAuth client; a row carrying conversation_id or confirmation_id names an in-product agent. A row meeting neither may name an agent or the client of a since-deleted application, and the row alone cannot tell which; nor does the contract keep an agent name and a client_id from being the same string. An envelope carrying both performers is recorded as the client. The action-invocation, data-export and dataset-query rows record clientId only. It does not move `actor`, which ADR-0118 D1/D5 keeps two-valued. |
67+
| **performedBy** | `{ clientId?: string; agentId?: string; conversationId?: string; confirmationId?: string }` | optional | ADR-0090 D10 rule 4 dual attribution: what PERFORMED this operation, when the performer is not the principal the write is authorized as. Two server-side producers set it: the /mcp OAuth door names the agent client in clientId, on the same branch that decides principalKind: agent and onBehalfOf; the server-constructed in-product AI path, acting for the signed-in person and running as them, names its agent in agentId with conversationId and, when the person confirmed the call, confirmationId. Absent everywhere else, and the absence is the record that the principal acted for itself; when present it names its performer, at least one of clientId and agentId, each set only by its own producer. ATTRIBUTION ONLY — no security middleware reads it, it never becomes the authorization subject, and userId stays the human so owner-stamping and current_user.* RLS still resolve to them. Server-constructed only, never client-supplied: an id a request named (an agent name, a conversation, a pending item) is stamped only after the server resolved it in its own store for the person in userId, and an unresolved id is not stamped. Surfaced to hooks as HookContext.provenance.performedByClientId / performedByAgentId / performedByConversationId / performedByConfirmationId. The record-write audit writer records the performer (clientId, or agentId for the in-product AI) as sys_audit_log.metadata.performed_by beside on_behalf_of, so that key holds two id kinds. Only when the agent is the recorded performer does the row also carry conversationId as metadata.conversation_id and confirmationId as metadata.confirmation_id (each when set); a client row never carries them. A reader can tell: a value matching the client_id of an existing sys_oauth_application row is an OAuth client; a row carrying conversation_id or confirmation_id names an in-product agent. A row meeting neither may name an agent or the client of a since-deleted application, and the row alone cannot tell which; nor does the contract keep an agent name and a client_id from being the same string: where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string. An envelope carrying both performers is recorded as the client. The action-invocation, data-export and dataset-query rows record the performer and the two marks by the same rule. It does not move `actor`, which ADR-0118 D1/D5 keeps two-valued. |
6868
| **surface** | `Enum<'rest' \| 'mcp'>` | optional | The door an action invocation came through: `rest` (the REST POST /actions/:object/:action door — console buttons, the SDK) or `mcp` (the /mcp bridge's run_action and resume_run tools — an AI client). Set only by those two doors, on the envelope of the invocation they hand the audit writer, from the door's own identity (an upstream value, header or body member never moves it); absent on every other operation. ATTRIBUTION ONLY — no security middleware reads it and it is never an authorization subject, scope or gate. Server-constructed only, never client-supplied. Recorded by the audit writer as sys_audit_log.metadata.surface on the action_invocation row. |
6969
| **impersonatedBy** | `string` | optional | The administrator (a sys_user id) who started the impersonation session this request runs in — better-auth admin plugin session.impersonatedBy, stored as sys_session.impersonated_by. Absent on every other request; absence is the record that the user in userId acted themselves. userId stays the impersonated user, so ownership, current_user.* RLS and permissions still resolve to them. ATTRIBUTION ONLY — no security middleware reads it and it never becomes the authorization subject. Server-constructed only from the session read that admitted the caller, never client-supplied. Surfaced to hooks as HookContext.provenance.impersonatedBy and recorded by the audit writer as sys_audit_log.metadata.impersonated_by and on the sys_activity row metadata; it does not move actor or user_id. |
7070
| **permissions** | `string[]` | optional (default: `[]`) | |

‎packages/plugins/plugin-audit/src/action-invocation-audit.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,3 +300,51 @@ describe('[#27908] the action_invocation row tells an agent\'s call from a click
300300
expect(options).toContain(ACTION_INVOCATION_AUDIT_ACTION);
301301
});
302302
});
303+
304+
describe('[#33694] an in-product AI call is marked on the action_invocation row by the CRUD mirror\'s rule', () => {
305+
const AI_CALL: ActionInvocationAuditEvent = {
306+
...CLICK,
307+
context: {
308+
userId: 'usr_1',
309+
tenantId: 'org_1',
310+
surface: 'rest',
311+
performedBy: { agentId: 'sales_assistant', conversationId: 'conv_1', confirmationId: 'pend_1' },
312+
},
313+
};
314+
const PERFORMER_KEYS = ['performed_by', 'on_behalf_of', 'conversation_id', 'confirmation_id'];
315+
const metaOf = (row: Record<string, unknown>) => JSON.parse(String(row.metadata));
316+
317+
it('an AI-performed call records the agent, the person, the conversation and the confirmation', async () => {
318+
const engine = await boot();
319+
const writer = createActionInvocationAuditWriter({ getEngine: () => engine as any });
320+
321+
await writer.recordActionInvocation(AI_CALL);
322+
323+
const [row] = await ledgerRows(engine);
324+
expect(row.user_id).toBe('usr_1');
325+
expect(row.actor).toBe('usr_1');
326+
expect(JSON.parse(row.metadata)).toMatchObject({
327+
performed_by: 'sales_assistant',
328+
on_behalf_of: 'usr_1',
329+
conversation_id: 'conv_1',
330+
confirmation_id: 'pend_1',
331+
});
332+
});
333+
334+
it('CONTROL: an OAuth client — alone, or beside an agent — is the performer, with no conversation or confirmation', () => {
335+
for (const performedBy of [
336+
{ clientId: 'cli_agent', conversationId: 'conv_1', confirmationId: 'pend_1' },
337+
{ clientId: 'cli_agent', agentId: 'sales_assistant', conversationId: 'conv_1', confirmationId: 'pend_1' },
338+
]) {
339+
const meta = metaOf(buildActionInvocationAuditRow({ ...AI_CALL, context: { ...AI_CALL.context, performedBy } }));
340+
expect(meta).toMatchObject({ performed_by: 'cli_agent', on_behalf_of: 'usr_1' });
341+
expect(meta).not.toHaveProperty('conversation_id');
342+
expect(meta).not.toHaveProperty('confirmation_id');
343+
}
344+
});
345+
346+
it('CONTROL: a person\'s own call carries no performer key at all', () => {
347+
const meta = metaOf(buildActionInvocationAuditRow(CLICK));
348+
for (const key of PERFORMER_KEYS) expect(meta).not.toHaveProperty(key);
349+
});
350+
});

0 commit comments

Comments
 (0)