Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/33786-in-product-ai-performed-by.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/spec': patch
'@objectstack/objectql': patch
'@objectstack/runtime': patch
---

feat(spec): the server-constructed in-product AI path can name itself on `ExecutionContext.performedBy`, and hooks see it on `HookContext.provenance`

Clause-②: yes — widened: `ExecutionContext.performedBy` accepts three new optional keys beside `clientId`: `agentId` (the in-product AI agent that performed the write for the signed-in person), `conversationId` (the AI conversation) and `confirmationId` (the id of the pending item the person approved). `clientId` is now optional, and a `performedBy` must name at least one of `clientId` and `agentId`, so `{ agentId }` parses where only `{ clientId }` did; a `performedBy` naming neither is refused at parse exactly as before, and the published JSON Schema states that rule as an `anyOf`. `HookContext.provenance` accepts `performedByAgentId`, `performedByConversationId` and `performedByConfirmationId`, each copied from its `performedBy` sibling by the engine the way `performedByClientId` is copied from `clientId`, and a sandboxed hook body reads them on `ctx.provenance` too.
Metadata-protocol: none

Before this, the in-product AI had no place on the write context: it writes as the person, and `ObjectQL#createContext` parses the envelope, so an `agentId` a host put on `performedBy` was dropped there and the write looked like the person's own. The attribution stays server-constructed and never client-supplied, no security middleware reads it, and it never becomes the subject a write is authorized as; the write still runs as the person, with `userId` theirs and no `onBehalfOf`. The OAuth `/mcp` door is unchanged: it still sets `performedBy.clientId` alone, and hooks still see `provenance.performedByClientId`.

What to do: nothing, unless your TypeScript reads `ExecutionContext['performedBy']` and assumes `clientId` is there. It is now `string | undefined`, because the in-product AI path names `agentId` instead; check it before use, as `performedBy?.clientId` readers already do. Recording these keys in `sys_audit_log` is a separate change to the audit writer.
24 changes: 12 additions & 12 deletions content/docs/references/data/data-engine.mdx

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion content/docs/references/data/hook.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
| **submitted** | `Record<string, any>` | optional | What the caller submitted, as sent (update only) — diagnostics only, never the persist image |
| **dispatch** | `{ mode: Enum<'record' \| 'per-row'>; index: integer; scope: Record<string, any> }` | optional | How this hook call relates to the caller's write (engine-produced) |
| **session** | `{ userId?: string; actor?: string; organizationId?: string; accessToken?: string; … }` | optional | Current session context |
| **provenance** | `{ flowRunId?: string; attributedUserId?: string; performedByClientId?: string; impersonatedBy?: string }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) |
| **provenance** | `{ flowRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) |
| **referentialFieldClear** | `boolean` | optional | Engine-produced marker: true exactly when this write is the engine's own referential cleanup (the set_null cascade UPDATE clearing — or, for multiple: true, removing the deleted member from — a lookup, tree or user field that references a record being deleted, where a user field takes part only when it declares its deleteBehavior). Absent on every other write, including a user hand-clearing the same field; read as `ctx.referentialFieldClear === true`. The declared projection of the operation-private `__referentialFieldClear`, carried across the sandbox boundary by contract; server-derived and never client-supplied. |
| **referentialCascadeDelete** | `boolean` | optional | Engine-produced marker: true exactly when this delete is one the engine's cascade issued (the child delete removing a row that references a record being deleted through a relation whose deleteBehavior resolves to cascade, at any depth), in both phases of that delete. Absent on every other delete, including a user hand-deleting the same child and a delete a hook issues through ctx.api; read as `ctx.referentialCascadeDelete === true`. The delete twin of referentialFieldClear, carried across the sandbox boundary by contract; server-derived, never client-supplied, and with no operation-private spelling to read instead. |
| **transaction** | `any` | optional | Database transaction handle |
Expand Down Expand Up @@ -148,6 +148,9 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
| **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. |
| **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. |
| **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. |
| **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. |
| **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. |
| **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. |
| **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. |

### Nested Shape: `HookContext.user`
Expand Down
11 changes: 10 additions & 1 deletion content/docs/references/kernel/execution-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const result = AuthGateCodeSchema.parse(data);
| **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. |
| **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. |
| **onBehalfOf** | `{ userId: string; principalKind?: Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'> }` | optional | |
| **performedBy** | `{ clientId: string }` | optional | ADR-0090 D10 rule 4 dual attribution: the agent that PERFORMED this operation, when the performer is not the principal the write is authorized as. Set only at the /mcp OAuth door, on the same branch that decides principalKind: agent and onBehalfOf; absent everywhere else, and the absence is the record that the principal acted for itself. 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. Surfaced to hooks as HookContext.provenance.performedByClientId and recorded by the audit writer as sys_audit_log.metadata.performed_by beside on_behalf_of; it does not move `actor`, which ADR-0118 D1/D5 keeps two-valued. |
| **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. |
| **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. |
| **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. |
| **permissions** | `string[]` | optional (default: `[]`) | |
Expand All @@ -87,6 +87,15 @@ const result = AuthGateCodeSchema.parse(data);
| **transaction** | `any` | optional | |
| **traceId** | `string` | optional | |

### Nested Shape: `ExecutionContext.performedBy`

| Property | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| **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. |
| **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. |
| **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. |
| **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. |

### Nested Shape: `ExecutionContext.permissionSetAddresses[number]`

The address of one granted permission set (ADR-0150 D3): the package that holds it (`null` for the environment's own or the platform's) and its name.
Expand Down
10 changes: 8 additions & 2 deletions packages/cli/test/lowered-body-face-enumeration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,14 @@ describe('the lowered body face, against the in-process HookContext (#22837)', (
expect(body.get('dispatch')).toEqual(new Set(['mode', 'index']));
expect(body.get('session')).toBe('passthrough');
// [#25905] Carried member by member, so a member the spec adds to it later is seen as absent.
expect(inProcess.get('provenance')).toEqual(new Set(['flowRunId', 'attributedUserId', 'performedByClientId', 'impersonatedBy']));
expect(body.get('provenance')).toEqual(new Set(['flowRunId', 'attributedUserId', 'performedByClientId', 'impersonatedBy']));
expect(inProcess.get('provenance')).toEqual(new Set([
'flowRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId',
'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy',
]));
expect(body.get('provenance')).toEqual(new Set([
'flowRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId',
'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy',
]));
// A tombstone is no member: `session.roles` is `retiredKey(…)`.
expect(inProcess.get('session')).not.toContain('roles');
expect(absent.length).toBeGreaterThan(0);
Expand Down
22 changes: 20 additions & 2 deletions packages/objectql/src/engine-execution-plumbing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,17 +143,35 @@ export function buildSession(execCtx?: ExecutionContext): HookContext['session']
* write authorizes as the impersonated user, so the administrator at the
* keyboard reaches the audit writer here and never through `session`, where
* every caller-gating hook would read the administrator as the caller.
*
* `performedByAgentId`, `performedByConversationId` and
* `performedByConfirmationId` ride it on the reasoning of
* `performedByClientId`: the server-constructed in-product AI path writes AS
* the signed-in person, so the AI that performed the write reaches the audit
* writer here, never through `session` (ADR-0090 D10 rule 4, as the owner's
* ruling on objectstack-ai/cloud#3826 reads it; #33786). Each is copied from
* its `ExecutionContext.performedBy` sibling and nothing else.
*/
export function buildProvenance(execCtx?: ExecutionContext): HookContext['provenance'] {
const flowRunId = (execCtx as any)?.flowRunId;
const attributedUserId = (execCtx as any)?.attributedUserId;
const performedByClientId = (execCtx as any)?.performedBy?.clientId;
const performedBy = (execCtx as any)?.performedBy;
const performedByClientId = performedBy?.clientId;
const performedByAgentId = performedBy?.agentId;
const performedByConversationId = performedBy?.conversationId;
const performedByConfirmationId = performedBy?.confirmationId;
const impersonatedBy = (execCtx as any)?.impersonatedBy;
if (!flowRunId && !attributedUserId && !performedByClientId && !impersonatedBy) return undefined;
if (
!flowRunId && !attributedUserId && !performedByClientId && !performedByAgentId
&& !performedByConversationId && !performedByConfirmationId && !impersonatedBy
) return undefined;
return {
...(flowRunId ? { flowRunId: String(flowRunId) } : {}),
...(attributedUserId ? { attributedUserId: String(attributedUserId) } : {}),
...(performedByClientId ? { performedByClientId: String(performedByClientId) } : {}),
...(performedByAgentId ? { performedByAgentId: String(performedByAgentId) } : {}),
...(performedByConversationId ? { performedByConversationId: String(performedByConversationId) } : {}),
...(performedByConfirmationId ? { performedByConfirmationId: String(performedByConfirmationId) } : {}),
...(impersonatedBy ? { impersonatedBy: String(impersonatedBy) } : {}),
};
}
Expand Down
Loading
Loading