Skip to content

Commit bb3c163

Browse files
feat(plugin-audit): mark in-product AI writes on sys_audit_log rows (agent, conversation, confirmation) (#34547)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9WZvQNanG3W23XFGRFXLDAt)_ Fixes #33694 Clause-②: no Metadata-protocol: none ## 维护者速读 1. **改了什么**:产品内 AI 替某人改记录时,审计日志那一行现在写明是哪个 AI(`performed_by`)、替谁(`on_behalf_of`)、在哪次对话(`conversation_id`)、经哪次确认(`confirmation_id`,没确认就不写)。 2. **为什么改**:之前 AI 改的数据在审计日志里和本人手改一模一样,回答不了「这条是 AI 替张三在哪次对话里改的」;契约字段早已在 main(#33786),只差审计写入器去读。 3. **风险与回滚**:只加 metadata 键,`user_id` / `actor` 仍是本人,人手改的行不变;回滚即撤本 PR,历史行不受影响。 4. **先看**:`packages/plugins/plugin-audit/src/audit-writers.ts`(`performedBy` 取值与 metadata 拼装两处)、`agent-dual-attribution.integration.test.ts` 末尾新增的 describe、`packages/spec/src/kernel/execution-context.zod.ts` 的 describe 改句。 5. **两分钟验证**:`pnpm --filter @objectstack/plugin-audit exec vitest run src/agent-dual-attribution.integration.test.ts`,预期 15 条全绿,其中 6 条是本卡新用例。 6. **需要你做的**:无,席位落地。 ## What changes - **The record-write audit writer reads the in-product AI performer.** `audit-writers.ts` read only `provenance.performedByClientId` (the /mcp OAuth client). It now also reads `provenance.performedByAgentId`, `performedByConversationId` and `performedByConfirmationId`, which `buildProvenance` already copies from `ExecutionContext.performedBy` (#33786, PR #34018). On a row the in-product AI wrote for a person, `sys_audit_log.metadata` carries: - `performed_by`: the agent, beside `on_behalf_of`: the person (the existing pair, per the owner ruling on objectstack-ai/cloud#3826 「3826 照建议(征询版)」: reuse `performed_by` / `on_behalf_of`, no new actor vocabulary); - `conversation_id`: the AI conversation; - `confirmation_id`: the pending item the person's approval decided, only when there was one. `user_id` and `actor` stay the person (ADR-0073 D3, ADR-0118 D1/D5). A personal write still carries no metadata. `conversation_id` / `confirmation_id` are written only when the in-product agent is the recorded performer, never beside an OAuth client id. If an envelope ever carried both `clientId` and `agentId` (each producer sets only its own), the row records the OAuth client and drops the agent with its two marks. - **Spec describes.** The `ExecutionContext.performedBy` and `HookContext.provenance.performedByAgentId` / `performedByConversationId` / `performedByConfirmationId` describes and JSDoc no longer say the audit writer "does not record them yet". They name the metadata keys; say that `performed_by` holds either an OAuth client id or an in-product agent name, and state only what a reader can tell from a row: 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, 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; state the both-performers precedence; and say the action-invocation, data-export and dataset-query rows still record `clientId` only. The `performedBy` JSDoc's "no key holds two id namespaces" sentence now names the audit key as the ruled exception. No schema shape change; `content/docs/references/**` regenerated (`gen:docs`). - Changeset `.changeset/33694-audit-in-product-ai-performer.md`: `@objectstack/plugin-audit` patch, `@objectstack/spec` patch (describe text ships). ## Why The in-product AI writes as the signed-in person, so its rows were byte-identical to that person's own edits on every attribution column. The contract fields that tell them apart landed in #33786; nothing recorded them. ## Tests New top-level describe in `packages/plugins/plugin-audit/src/agent-dual-attribution.integration.test.ts` (the existing rule 4 harness: real kernel, `assembleExecutionContext`, objectql `buildProvenance`, the shipped `sys_audit_log` object and writer on sqlite-wasm). The person's envelope is built at the real door; `performedBy` is added as the in-product AI path stamps it (that producer lives outside this repository). - CONTROL: the envelope is a `human` principal with no `performedBy`, and `user_id` / `actor` are the person on all four rows. - A confirmed AI create records `{ performed_by, on_behalf_of, conversation_id, confirmation_id }`. - An AI create that needed no confirmation records no `confirmation_id`. - An AI update of a record the person created is marked on the update row; the person's own create row stays unmarked. - An envelope naming an OAuth client beside a conversation and a confirmation records only `{ performed_by: client, on_behalf_of }`. - An envelope naming both performers records the OAuth client, without the agent's marks. The last two envelopes have no producer in the tree; they pin what the spec tells a reader. No existing test changed. ## Acceptance notes - **Two id namespaces in `performed_by`.** `performed_by` now holds an OAuth client id or an in-product agent name, as the ruling chose (accepted in contract review 6934640918). Round 2 answered its S1: the writer keys `conversation_id` / `confirmation_id` on the agent being the recorded performer (which also closes N1). Round 3 answers S2 (6936045381): the describes no longer claim every value is classifiable, since an OAuth application row can be deleted while audit rows keep its `client_id`; a permanent per-row discriminator would need a kind mark on the row, which is a ruling, not this PR. ADR-0151 D5 reason 2 and ADR-0090 D10 rule 4 wording stay with carrier #34057. - **Out of scope, filed #34556:** the action-invocation, data-export and dataset-query writers (`action-invocation-audit.ts`, `data-export-audit.ts`, `dataset-query-audit.ts`) read `performedBy.clientId` only, so an in-product AI action run or export is still recorded as the person's own. The describes now say so. - The `clientId` / `performedByClientId` describes now name the OAuth client by the `client_id` of its `sys_oauth_application` row (they said the row's id; the two columns differ). - `content/docs/automation/hook-bodies.mdx` lists `ctx.provenance.performedByClientId` only; outside this card's file surface. Filed #34556. ## Verification <details><summary>Local runs (head and gate list in the report comment on #33694)</summary> - `pnpm --filter '@objectstack/plugin-audit^...' build` under the verify lock: exit 0. - `pnpm --filter @objectstack/plugin-audit exec vitest run src/agent-dual-attribution.integration.test.ts`: Test Files 1 passed, Tests 15 passed. - `pnpm --filter @objectstack/plugin-audit test` (after merging main): Test Files 101 passed, Tests 1676 passed. `pnpm --filter @objectstack/plugin-audit typecheck`: exit 0, test-typecheck 0 errors. - `pnpm --filter @objectstack/spec exec vitest run src/kernel/execution-context.test.ts src/data/hook.test.ts`: Tests 146 passed. - `pnpm --filter @objectstack/spec build && check:generated`: `content/docs/references/**` stale, regenerated with `--fix`, re-check green. - Ablation (`scripts/ablation-replace.mjs`, anchor hit 1 → 0): `performedBy = performedByClientId ?? performedByAgentId` → `performedByClientId` reds the three AI-row tests (3 failed / 10 passed); restore blob == HEAD, `git diff HEAD` empty. - Round 2 ablation: `agentIsRecordedPerformer = !performedByClientId && performedByAgentId !== undefined` → `performedBy !== undefined` reds the two new pins (2 failed / 13 passed); restore blob == HEAD, `git diff HEAD` empty. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [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. - [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_01ADHkmSQnLEs6vGofJXcguE)_ <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmSQnLEs6vGofJXcguE --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a8e09bb commit bb3c163

8 files changed

Lines changed: 298 additions & 41 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
feat(plugin-audit): a record write the in-product AI made for a person is marked on its `sys_audit_log` row
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Before this change, a record the in-product AI changed for a signed-in person produced a `sys_audit_log` row identical to one that person typed. The write context already carried the AI's identity (`ExecutionContext.performedBy.agentId`, `conversationId` and `confirmationId`, surfaced to hooks as `provenance.performedByAgentId` and its siblings), but the record-write audit writer read only the OAuth client (`performedByClientId`).
12+
13+
The writer now records the in-product AI the way it records an MCP OAuth client, in the row's `metadata`:
14+
15+
- `performed_by`: the agent that ran, beside `on_behalf_of`, the person (the existing pair; no new actor vocabulary);
16+
- `conversation_id`: the AI conversation the write was made in;
17+
- `confirmation_id`: the pending item the person's approval decided, present only when the write needed a confirmation.
18+
19+
`user_id` and `actor` still name the person, so ownership, joins to `sys_user` and existing readers are unchanged. A write the person made themselves still carries none of these keys. The action-invocation, data-export and dataset-query rows still record the OAuth client only.
20+
21+
The `@objectstack/spec` descriptions of `ExecutionContext.performedBy` and `HookContext.provenance` no longer say these keys are not recorded; they name the metadata keys above. No schema shape changes.

‎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: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,10 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
147147
| :--- | :--- | :--- | :--- |
148148
| **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. |
149149
| **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. |
150-
| **performedByClientId** | `string` | optional | [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, a registered sys_oauth_application id) 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. |
151-
| **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`: carried for the audit writer, which does not record it yet; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. |
152-
| **performedByConversationId** | `string` | optional | The AI conversation an in-product AI write was performed in. Copied from `ExecutionContext.performedBy.conversationId`, set beside `performedByAgentId`. ATTRIBUTION ONLY: no security middleware reads it. |
153-
| **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: no security middleware reads it, and it is never the authorization for the write, which runs as the person with every gate re-checked. |
150+
| **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. |
151+
| **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. |
152+
| **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. |
153+
| **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. |
154154
| **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. |
155155

156156
### Nested Shape: `HookContext.user`

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

Lines changed: 2 additions & 2 deletions
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 audit writer records clientId as sys_audit_log.metadata.performed_by beside on_behalf_of; the in-product AI keys are carried for the audit writer, which does not record them yet. 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. 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. |
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: `[]`) | |
@@ -91,7 +91,7 @@ const result = AuthGateCodeSchema.parse(data);
9191

9292
| Property | Type | Required | Description |
9393
| :--- | :--- | :--- | :--- |
94-
| **clientId** | `string` | optional | The OAuth client (`azp`, a registered sys_oauth_application id) that performed the operation. Set by the /mcp OAuth door only; absent when the in-product AI performed it. |
94+
| **clientId** | `string` | optional | The OAuth client (`azp`, the client_id of a registered sys_oauth_application) that performed the operation. Set by the /mcp OAuth door only; absent when the in-product AI performed it. |
9595
| **agentId** | `string` | optional | The in-product AI agent that performed the operation for the signed-in person in userId: the agent the chat runs as (the same value as ToolExecutionContext.agentId). Set by the server-constructed in-product AI path only, and only after the server resolved it as the agent it actually ran; never a sys_user id or an OAuth client id. |
9696
| **conversationId** | `string` | optional | The AI conversation the operation was performed in (the same id as ToolExecutionContext.conversationId). Set beside agentId by the in-product AI path, and only after the server resolved it as a conversation the person in userId owns. |
9797
| **confirmationId** | `string` | optional | The confirmation the person gave before the operation ran: the id of the pending item their approval decided (the in-app pending action id, or the pending-confirmation service item id). Stamped only after the server resolved it as a pending item the person in userId decided for this operation; absent when the operation needed no confirmation. |

0 commit comments

Comments
 (0)