From 8f91d2941e3b68ccb0831c2bed482eb876b79828 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:48:25 +0000 Subject: [PATCH 1/7] wip(approvals): the hold through a passage, and the root run on a run's writes (ADR-0162 D5, item 8) Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq Co-authored-by: Claude --- .../assemble-execution-context.test.ts | 1 + .../security/assemble-execution-context.ts | 3 +- .../objectql/src/engine-execution-plumbing.ts | 4 + .../objectql/src/engine-scoped-context.ts | 2 +- .../plugin-approvals/src/approval-service.ts | 94 ++++++- .../plugin-approvals/src/lifecycle-hooks.ts | 233 +++++++++++++++++- packages/runtime/src/sandbox/body-runner.ts | 1 + packages/runtime/src/sandbox/script-runner.ts | 3 +- .../src/runtime-identity.ts | 16 ++ packages/spec/src/data/hook.zod.ts | 1 + .../spec/src/kernel/execution-context.zod.ts | 20 ++ 11 files changed, 353 insertions(+), 25 deletions(-) diff --git a/packages/core/src/security/assemble-execution-context.test.ts b/packages/core/src/security/assemble-execution-context.test.ts index c1ba4c9ab59..c4e13e5a652 100644 --- a/packages/core/src/security/assemble-execution-context.test.ts +++ b/packages/core/src/security/assemble-execution-context.test.ts @@ -470,6 +470,7 @@ describe('#6216 — the field set is CLOSED', () => { 'transaction', 'traceId', 'flowRunId', + 'flowRootRunId', 'skipTriggers', 'skipAutomations', 'seedReplay', diff --git a/packages/core/src/security/assemble-execution-context.ts b/packages/core/src/security/assemble-execution-context.ts index 7d79757889a..bd7fc7bbb3f 100644 --- a/packages/core/src/security/assemble-execution-context.ts +++ b/packages/core/src/security/assemble-execution-context.ts @@ -91,7 +91,7 @@ import type { ResolvedAuthzContext } from './resolve-authz-context.js'; * hook layer (ADR-0014 D2, #4586), never by identity resolution. * - `rlsMembership` — engine-side RLS scoping cache. * - `transaction` / `traceId` — per-operation handles. - * - `flowRunId`, `skipTriggers`, `skipAutomations`, `seedReplay`, + * - `flowRunId`, `flowRootRunId`, `skipTriggers`, `skipAutomations`, `seedReplay`, * `skipStateMachine`, `preserveAudit`, `keptOptionValues` — per-write * behaviour flags, server-constructed at the call site (`keptOptionValues` * by the import runner, from the cells one import kept). @@ -106,6 +106,7 @@ type NonEntryExecutionContextField = | 'transaction' | 'traceId' | 'flowRunId' + | 'flowRootRunId' | 'skipTriggers' | 'skipAutomations' | 'seedReplay' diff --git a/packages/objectql/src/engine-execution-plumbing.ts b/packages/objectql/src/engine-execution-plumbing.ts index 1b890f64e2a..43750ea780d 100644 --- a/packages/objectql/src/engine-execution-plumbing.ts +++ b/packages/objectql/src/engine-execution-plumbing.ts @@ -161,6 +161,9 @@ export function buildSession(execCtx?: ExecutionContext): HookContext['session'] */ export function buildProvenance(execCtx?: ExecutionContext): HookContext['provenance'] { const flowRunId = (execCtx as any)?.flowRunId; + // [ADR-0162 D5, "the hold"] The root run of `flowRunId`'s tree rides beside + // it, and only beside it: a root run id with no run id is no run's write. + const flowRootRunId = flowRunId ? (execCtx as any)?.flowRootRunId : undefined; const attributedUserId = (execCtx as any)?.attributedUserId; const performedBy = (execCtx as any)?.performedBy; const performedByClientId = performedBy?.clientId; @@ -174,6 +177,7 @@ export function buildProvenance(execCtx?: ExecutionContext): HookContext['proven ) return undefined; return { ...(flowRunId ? { flowRunId: String(flowRunId) } : {}), + ...(flowRootRunId ? { flowRootRunId: String(flowRootRunId) } : {}), ...(attributedUserId ? { attributedUserId: String(attributedUserId) } : {}), ...(performedByClientId ? { performedByClientId: String(performedByClientId) } : {}), ...(performedByAgentId ? { performedByAgentId: String(performedByAgentId) } : {}), diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 8e7dbc5f68d..0219e3851cc 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -134,7 +134,7 @@ export class ScopedContextFacet { */ static platformSystemApi(this: Pick): ScopedContext { if (this.appAuthored || isDispatchedActionApi(this.facade)) return ScopedContextFacet.sudo.call(this); - const { flowRunId: _run, ...context } = withoutAppAutomationElevation({ ...this.executionContext, isSystem: true }); + const { flowRunId: _run, flowRootRunId: _root, ...context } = withoutAppAutomationElevation({ ...this.executionContext, isSystem: true }); return this.derive(context as ExecutionContext); } diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index b22ec20ce47..9cd93c58a77 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -170,7 +170,8 @@ import { } from './payload-redaction.js'; import { APPROVAL_REQUEST_CHILD_OBJECTS, type RequestVisibilitySource } from './request-read-gate.js'; import { - detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval, + ABANDONED_SNAPSHOT_KEY, detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, + recordHeldByLockingApproval, } from './lifecycle-hooks.js'; import { PendingApproverReadGrantSource, type PendingApproverReadGrants } from './pending-approver-read-grant.js'; // The ADR-0043 pages — the ONE copy of their text, rendered by the plugin's @@ -1892,9 +1893,10 @@ const FLOW_NOT_CONTINUED_TOPIC = 'approval.flow_not_continued'; * [ADR-0162 Execution item 8] The keys of a request's config snapshot that the * judgement of an approval leaves: the approval was abandoned (`__abandoned`), * and a later step of it could not open (`__laterStepNotOpened`). Internal - * stamps, like `__round`: the snapshot is not authored config. + * stamps, like `__round`: the snapshot is not authored config. The first is + * read by the hold as well (`lifecycle-hooks.ts`), which owns its spelling. */ -const ABANDONED_KEY = '__abandoned'; +const ABANDONED_KEY = ABANDONED_SNAPSHOT_KEY; const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; /** The run statuses a run reports while it is being advanced, or is about to be. */ @@ -9992,6 +9994,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ); return empty; } + // [ADR-0162 D5, "the hold"] After the pending requests are read, so that + // a delete in a passage ends its approval whether or not one is pending. + await this.endApprovalsOfDeletedRecord(object, record); if (pending.length === 0) return empty; const now = this.clock.now().toISOString(); @@ -12435,7 +12440,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega seen.add(key); try { if (await this.recordIsGone(raw)) { - await this.clearApprovalMarks(raw); + await this.endApprovalOfDeletedRecord(raw); deletedRecords++; this.logger?.info?.( `[approvals] the reconciler cleared the marks of the approval of ${String(raw.object_name)}/${String(raw.record_id)}: ` @@ -12477,17 +12482,88 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } - /** [ADR-0162 Execution item 8] Clear the marks of every request of `row`'s approval on its record, `row` included. */ - private async clearApprovalMarks(row: any): Promise { + /** + * [ADR-0162 D5 "the hold", Execution item 8] End the approval `row` belongs + * to, whose record was deleted: the approval is marked abandoned on its + * latest request on the record, its marks are cleared and nothing is + * written, so that no mark of a deleted record stands for good, holds + * nothing, and leaves the reconciler nothing to try again or to notify for. + * The decisions already made stay on their requests. A request already + * marked abandoned is not stamped again. + */ + private async endApprovalOfDeletedRecord(row: any): Promise { if (!row?.root_run_id) { await this.clearMarks([row]); return; } - const rows = await this.engine.find('sys_approval_request', { + const found = await this.engine.find('sys_approval_request', { where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, - fields: ['id', 'unjudged_since'], limit: 500, context: SYSTEM_CTX, + fields: ['id', 'created_at', 'unjudged_since', 'node_config_json'], limit: 500, context: SYSTEM_CTX, }); - await this.clearMarks(Array.isArray(rows) ? rows : [row]); + const rows: any[] = Array.isArray(found) && found.length > 0 ? found : [row]; + const at = (r: any): number => { + const t = new Date(r?.created_at ?? '').getTime(); + return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY; + }; + const latest = rows.reduce((best, r) => (best === undefined || at(r) > at(best) ? r : best), undefined); + const abandoned = rows.some((r) => parseJson>(r?.node_config_json, {})[ABANDONED_KEY] !== undefined); + if (latest && !abandoned) { + const now = this.clock.now().toISOString(); + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [ABANDONED_KEY]: { at: now, reason: 'the record was deleted.' } }), + }, { context: SYSTEM_CTX }); + } + await this.clearMarks(rows); + } + + /** + * [ADR-0162 D5 "the hold", Execution item 8] A caller's delete lands in a + * passage, as it lands while a request is pending, and ends the approval of + * the deleted record ({@link endApprovalOfDeletedRecord}), once for each + * approval whose marks stand on it. Best-effort, like the rest of the + * record-delete void: a mark this cannot clear is the reconciler's, which + * ends the approval the same way. + */ + private async endApprovalsOfDeletedRecord(object: string, record: string): Promise { + let marked: any[]; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { object_name: object, record_id: record, unjudged_since: { $null: false } }, + limit: RECORD_DELETE_CANCEL_LIMIT, context: SYSTEM_CTX, + }); + marked = Array.isArray(rows) ? rows : []; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the marks on a deleted record; the reconciler ends its approval', { + object, record, error: err?.message ?? String(err), + }); + return []; + } + const ended: string[] = []; + const seen = new Set(); + for (const raw of marked) { + if (!isMarked(raw)) continue; + const key = raw?.root_run_id ? String(raw.root_run_id) : `request\u0000${String(raw?.id)}`; + if (seen.has(key)) continue; + seen.add(key); + try { + await this.endApprovalOfDeletedRecord(raw); + ended.push(String(raw.id)); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not end the approval of a record deleted between two of its steps; the reconciler ends it', { + object, record, request: raw?.id, error: err?.message ?? String(err), + }); + } + } + if (ended.length > 0) { + this.logger?.info?.( + `[approvals] the record ${object}/${record} was deleted between two steps of its approval: the approval was ` + + 'marked abandoned and its marks cleared; nothing is written.', + { object, record, requests: ended }, + ); + } + return ended; } async releaseDeadRunRequests(): Promise<{ scanned: number; released: number }> { diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index 7fd8b445a39..898e5440052 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -636,6 +636,174 @@ export async function recordsHeldByLockingApproval( return new Set(held.map((pending) => String(pending?.record_id ?? ''))); } +// ── The hold through a passage (ADR-0162 D5 "the hold", Execution item 8) ── +// +// A passage is the time from a step's decision until the next request of the +// approval opens on the record, or until the approval is over. No request is +// pending in it, so the three pending reads above see nothing. On an object +// that declares `closedStates` the write side also reads the requests that +// carry the mark (`unjudged_since`): a decision of an approval the check +// stamped, whose sequel nobody has judged yet. Such a request holds its record +// and the record's direct `master_detail` lines as a pending request under a +// locking node does, with the passes D5 gives the hold: +// +// - a system context, and a write that carries only the mirror field (the +// record lock's own caller-level passes, unchanged); +// - a write that carries a run of the approval: its root run is the one the +// request records (`flowRootRunId`, ADR-0162 Execution item 7), or it is +// one of the runs the request names; +// - the revise window: the hold stands only while the marked request is the +// approval's latest on the record, so a later returned request (its revise +// window), a later pending one (the pending lock's own rules) or an +// approval marked abandoned ends it, also where a mark was left behind; +// - the record's own delete, which this `beforeUpdate` guard never sees. +// +// A passage does not ask the node's `lockRecord`: the hold is the promise of +// `closedStates`, not a node's choice. The approvals-family read +// (`getRecordLock`, {@link recordHeldByLockingApproval} and its siblings) is +// not touched and answers for a pending request only, as published. + +/** The key the approval's judgement leaves on a request's snapshot when it abandons the approval. */ +export const ABANDONED_SNAPSHOT_KEY = '__abandoned'; + +/** Whether `row` carries the mark: it was decided, and what follows is not judged yet. */ +function carriesMark(row: any): boolean { + return row?.unjudged_since != null && row.unjudged_since !== ''; +} + +/** Whether `row`'s snapshot says its approval was abandoned. */ +function snapshotAbandoned(row: any): boolean { + return parseJson>(row?.node_config_json, {})[ABANDONED_SNAPSHOT_KEY] !== undefined; +} + +/** + * Whether `objectName` declares `closedStates` with at least one closed value, + * read from the registry the engine validates writes against. A registry that + * cannot answer reads as "declares none", the same degradation the pending + * lock makes for bookkeeping it cannot read: this guard is global over every + * object. + */ +function declaresClosedStates(engine: Pick, objectName: string): boolean { + let closed: unknown; + try { + closed = engine.getSchema?.(objectName)?.closedStates; + } catch { + return false; + } + if (!closed || typeof closed !== 'object' || Array.isArray(closed)) return false; + return Object.values(closed as Record).some((v) => Array.isArray(v) && v.length > 0); +} + +/** + * The marked requests on `recordIds` of `objectName` (or on any record of it, + * for `null`), where the object declares `closedStates`. A read that fails + * answers none, like {@link pendingRequestsForRecords}. + */ +async function passageRequestsFor( + engine: Pick, + objectName: string, + recordIds: ReadonlyArray | null, +): Promise { + if (isApprovalBookkeepingObject(objectName) || !declaresClosedStates(engine, objectName)) return []; + if (recordIds !== null && recordIds.length === 0) return []; + const where: Record = { object_name: objectName, unjudged_since: { $null: false } }; + if (recordIds !== null) { + where.record_id = recordIds.length === 1 ? String(recordIds[0]) : { $in: recordIds.map(String) }; + } + try { + const rows = await engine.find('sys_approval_request', { + where, limit: PENDING_LOCK_LIMIT + 1, context: { ...SYSTEM_CTX }, + } as any); + return Array.isArray(rows) ? rows : []; + } catch { + return []; + } +} + +/** The runs a write carries, as the engine stamped them on its provenance. */ +interface WriterRuns { + /** The run that makes the write (`flowRunId`). */ + run?: string; + /** The root run of that run's tree (`flowRootRunId`). */ + root?: string; +} + +function writerRunsOf(ctx: any): WriterRuns { + const provenance = ctx?.provenance as { flowRunId?: unknown; flowRootRunId?: unknown } | undefined; + const run = typeof provenance?.flowRunId === 'string' && provenance.flowRunId ? provenance.flowRunId : undefined; + const root = run && typeof provenance?.flowRootRunId === 'string' && provenance.flowRootRunId + ? provenance.flowRootRunId + : undefined; + return { ...(run ? { run } : {}), ...(root ? { root } : {}) }; +} + +/** + * Whether the write is made by a run of the approval `marked` belongs to: its + * tree's root run is the one the request records, or the run is one the + * request names (the run that opened it, the root run, the run that carries + * its record). + */ +function writesAsApprovalRun(marked: any, writer: WriterRuns): boolean { + if (!writer.run) return false; + const root = marked?.root_run_id ? String(marked.root_run_id) : ''; + if (root && writer.root === root) return true; + return [marked?.flow_run_id, marked?.root_run_id, marked?.record_run_id] + .some((id) => id != null && id !== '' && String(id) === writer.run); +} + +/** + * Whether `marked`'s approval is still in the passage its decision began: the + * request is the approval's latest on its record, carries the mark, and the + * approval was not abandoned. A read that fails holds: a mark is known to + * stand. + */ +async function approvalInPassage(engine: Pick, marked: any): Promise { + if (!carriesMark(marked) || snapshotAbandoned(marked)) return false; + if (!marked?.root_run_id) return true; + let rows: any[]; + try { + const found = await engine.find('sys_approval_request', { + where: { root_run_id: marked.root_run_id, object_name: marked.object_name, record_id: marked.record_id }, + fields: ['id', 'status', 'created_at', 'unjudged_since', 'node_config_json'], + limit: 500, context: { ...SYSTEM_CTX }, + } as any); + rows = Array.isArray(found) ? found : []; + } catch { + return true; + } + if (rows.some(snapshotAbandoned)) return false; + const at = (r: any): number => { + const t = new Date(r?.created_at ?? '').getTime(); + return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY; + }; + const latest = rows.reduce((best, r) => (best === undefined || at(r) > at(best) ? r : best), undefined); + if (!latest) return true; + // Two requests opened in the same instant: one that is not marked (pending + // or returned) is the newer state of the approval. + const tied = rows.filter((r) => at(r) === at(latest)); + return tied.every(carriesMark); +} + +/** + * The hold's judgement of one marked request against one write: `true` where + * the write is refused. `changedFields` is the update's changed fields for the + * record itself, where a write that carries only the mirror field passes; a + * line write passes no field. + */ +async function passageHoldsAgainst( + engine: Pick, + marked: any, + writer: WriterRuns, + changedFields?: readonly string[], +): Promise { + if (writesAsApprovalRun(marked, writer)) return false; + if (changedFields) { + const mirror = parseJson(marked?.node_config_json, {})?.approvalStatusField; + if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) return false; + } + return approvalInPassage(engine, marked); +} + /** * Narrow `candidates` (pending requests) to the ones whose record the caller's * predicate actually matches — asked of the engine as an intersection, so the @@ -689,7 +857,10 @@ async function gatingRequests( objectName: string, ): Promise { const byId = asIdList(ctx?.input?.id); - if (byId) return pendingRequestsForRecords(engine, objectName, byId); + if (byId) { + const pending = await pendingRequestsForRecords(engine, objectName, byId); + return withPassage(pending, await passageRequestsFor(engine, objectName, byId)); + } // Predicate write. `where` is canonical here: the engine folds the `filter` // alias into it before hooks run (PD #12 — no consumer-side `?? filter`). @@ -700,10 +871,14 @@ async function gatingRequests( : null; const namedIds = whereObj ? asIdList(whereObj.id) : null; - const candidates = namedIds + const pending = namedIds ? await pendingRequestsForRecords(engine, objectName, namedIds) : await pendingRequestsForObject(engine, objectName); - if (candidates === null) return []; // bookkeeping unreadable — see the note above + // [ADR-0162 D5, "the hold"] The marked requests of a passage, on an object + // that declares `closedStates`, are candidates beside the pending ones. + const passage = await passageRequestsFor(engine, objectName, namedIds); + if (pending === null && passage.length === 0) return []; // bookkeeping unreadable — see the note above + const candidates = withPassage(pending ?? [], passage); if (candidates.length === 0) return []; // nothing locked in reach if (candidates.length > PENDING_LOCK_LIMIT) { lockedError( @@ -718,6 +893,13 @@ async function gatingRequests( return narrowToMatchedRecords(engine, objectName, rawWhere, candidates); } +/** `pending` and then the marked requests of `passage` that are not among them. */ +function withPassage(pending: any[], passage: any[]): any[] { + if (passage.length === 0) return pending; + const seen = new Set(pending.map((r) => String(r?.id ?? ''))); + return [...pending, ...passage.filter((r) => !seen.has(String(r?.id ?? '')))]; +} + /** * Bind the global record-lock hook. Caller is responsible for calling * {@link unbindAllHooks} first if re-binding. @@ -784,19 +966,26 @@ export function bindApprovalLockHook( // session, and that shape is the one that used to die on its own lock // (#3712). const writerRun = (ctx?.provenance as any)?.flowRunId; + const writer = writerRunsOf(ctx); // Per-row verdict: the write is refused as soon as ONE touched record is // locked against it. Each request carries its own snapshotted policy, so a // multi-row write spanning two approvals is judged by each of them. for (const pending of gating) { - if (writerRun && pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id)) continue; + if (pending?.status !== 'pending') { + // [ADR-0162 D5, "the hold"] A marked request of a passage: held + // whatever its node's `lockRecord`, with the hold's own passes. + if (!(await passageHoldsAgainst(engine, pending, writer, changedFields))) continue; + } else { + if (writerRun && pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id)) continue; - const config = parseJson(pending?.node_config_json, {}); - if (!nodeConfigLocksRecord(config)) continue; + const config = parseJson(pending?.node_config_json, {}); + if (!nodeConfigLocksRecord(config)) continue; - // Allow when every changed field is the approval status mirror. - const mirror = config?.approvalStatusField; - if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) continue; + // Allow when every changed field is the approval status mirror. + const mirror = config?.approvalStatusField; + if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) continue; + } // ── The one END-USER sentence of the four (#18153) ───────────── // See the module docstring. The id and the API name are not deleted — @@ -837,7 +1026,9 @@ export function bindApprovalLockHook( logger?.info?.( `[approvals] update refused RECORD_LOCKED: record '${recordId}' of '${object}' ` + - `is held by pending approval request '${String(pending?.id ?? '')}'`, + (pending?.status === 'pending' + ? `is held by pending approval request '${String(pending?.id ?? '')}'` + : `is held between two steps of its approval, after the decision of request '${String(pending?.id ?? '')}'`), ); const sentence = recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate); lockedError(sentence, sentence); @@ -1099,6 +1290,14 @@ export function bindDetailRowLockHook( const writerRun = (ctx?.provenance as any)?.flowRunId; const exempt = (pending: any) => !!writerRun && !!pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id); + // [ADR-0162 D5, "the hold"] The marked requests of a passage that hold a + // master against this write: a line write carries no mirror field. + const writer = writerRunsOf(ctx); + const holdingInPassage = async (marked: readonly any[]): Promise => { + const out: any[] = []; + for (const m of marked) if (await passageHoldsAgainst(engine, m, writer)) out.push(m); + return out; + }; // The end-user sentence naming the MASTER object (the record lock's own). const sentenceFor = (master: string): string => { @@ -1117,7 +1316,10 @@ export function bindDetailRowLockHook( if (unresolved) { for (const e of edges) { const held = (await pendingRequestsForObject(engine, e.master)) ?? []; - const locking = held.filter((p) => nodeConfigLocksRecord(parseJson(p?.node_config_json, {})) && !exempt(p)); + const locking = [ + ...held.filter((p) => nodeConfigLocksRecord(parseJson(p?.node_config_json, {})) && !exempt(p)), + ...await holdingInPassage(await passageRequestsFor(engine, e.master, null)), + ]; if (locking.length > 0) { lockedError( `cannot determine which '${e.master}' record a ${event} on its detail object '${object}' falls under, ` + @@ -1129,11 +1331,16 @@ export function bindDetailRowLockHook( } for (const { master, id } of touched) { - const locking = (await lockingRequestsForRecords(engine, master, [id])).filter((p) => !exempt(p)); + const locking = [ + ...(await lockingRequestsForRecords(engine, master, [id])).filter((p) => !exempt(p)), + ...await holdingInPassage(await passageRequestsFor(engine, master, [id])), + ]; if (locking.length === 0) continue; logger?.info?.( `[approvals] ${event} on detail object '${object}' refused RECORD_LOCKED: its master '${master}' ` + - `record '${id}' is held by pending approval request '${String(locking[0]?.id ?? '')}'`, + (locking[0]?.status === 'pending' + ? `record '${id}' is held by pending approval request '${String(locking[0]?.id ?? '')}'` + : `record '${id}' is held between two steps of its approval, after the decision of request '${String(locking[0]?.id ?? '')}'`), ); const sentence = sentenceFor(master); lockedError(sentence, sentence); diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index e659821e3d3..fc6e792521d 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -1541,6 +1541,7 @@ function buildSandboxContext( const provenanceRaw = engineCtx?.provenance; const provenance = declaredStringMarks({ flowRunId: provenanceRaw?.flowRunId, + flowRootRunId: provenanceRaw?.flowRootRunId, attributedUserId: provenanceRaw?.attributedUserId, performedByClientId: provenanceRaw?.performedByClientId, performedByAgentId: provenanceRaw?.performedByAgentId, diff --git a/packages/runtime/src/sandbox/script-runner.ts b/packages/runtime/src/sandbox/script-runner.ts index 404db3f8b56..b30cb82f12f 100644 --- a/packages/runtime/src/sandbox/script-runner.ts +++ b/packages/runtime/src/sandbox/script-runner.ts @@ -275,7 +275,7 @@ export interface ScriptContext { * (`@objectstack/spec/data`), which objectql's `buildProvenance()` stamps from * the server-built execution context on every write assembly site. * - * Projected to the three declared members, each copied only in its declared + * Projected to the declared members, each copied only in its declared * shape (a string) and absent otherwise; the whole key is ABSENT when none * survives, which is what the engine face carries on a write with no origin * (a plain REST write). Read it as `ctx.provenance?.flowRunId`. @@ -290,6 +290,7 @@ export interface ScriptContext { */ provenance?: { flowRunId?: string; + flowRootRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; diff --git a/packages/services/service-automation/src/runtime-identity.ts b/packages/services/service-automation/src/runtime-identity.ts index a4e002a2663..335e6bb7d0c 100644 --- a/packages/services/service-automation/src/runtime-identity.ts +++ b/packages/services/service-automation/src/runtime-identity.ts @@ -5,6 +5,7 @@ import { AuthzPostureSchema, type AuthzPosture } from '@objectstack/spec/securit import type { PermissionSetAddressParsed } from '@objectstack/spec/kernel'; import { markFlowWriteReferenceCheck, markRunCaller } from '@objectstack/core'; import { markGuardRefusal } from './guard-refusal.js'; +import { readRootRun } from './root-run.js'; /** * The IDENTITY envelope a flow's data nodes pass to ObjectQL as @@ -143,6 +144,16 @@ export interface RunIdentityContext { * state that run itself opened (the approvals record lock). */ flowRunId?: string; + /** + * The root run of the tree {@link flowRunId} belongs to (ADR-0162 Execution + * item 7, "The root run"), carried as the kernel + * `ExecutionContext.flowRootRunId`. Provenance only, like + * {@link flowRunId}: the approvals plugin's hold between two steps lets + * through the writes of any run of the approval, which it knows by this id + * (ADR-0162 D5). Carried only beside {@link flowRunId}, and absent on a run + * the engine could not place in a tree. + */ + flowRootRunId?: string; /** * The administrator who made the write that started this run from an * impersonation session ({@link AutomationContext.impersonatedBy}), carried @@ -476,6 +487,9 @@ export function runPrincipalKind(context: AutomationContext | undefined): 'agent */ export function resolveRunDataContext(context: AutomationContext | undefined): RunDataContext | undefined { const flowRunId = context?.flowRunId; + // [ADR-0162 D5, "the hold"] The root run the engine stamps on every run of a + // tree (`root-run.ts`), beside the run id and only beside it. + const flowRootRunId = flowRunId ? readRootRun(context)?.runId : undefined; // The starter's language rides into every write, on both arms — see // RunDataContext.locale. const locale = typeof context?.locale === 'string' && context.locale.length > 0 ? context.locale : undefined; @@ -568,6 +582,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R : {}), ...(context.userId && caller === undefined && runPosture(context) ? { posture: runPosture(context) } : {}), ...(flowRunId ? { flowRunId } : {}), + ...(flowRootRunId ? { flowRootRunId } : {}), ...(locale ? { locale } : {}), ...(impersonatedBy ? { impersonatedBy } : {}), }); @@ -619,6 +634,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R if (runPrincipalKind(context)) out.principalKind = 'agent'; if (context.tenantId) out.tenantId = context.tenantId; if (flowRunId) out.flowRunId = flowRunId; + if (flowRootRunId) out.flowRootRunId = flowRootRunId; if (locale) out.locale = locale; if (impersonatedBy) out.impersonatedBy = impersonatedBy; return out; diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index e412970962f..f64f35be932 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1684,6 +1684,7 @@ export const HookContextSchema = lazySchema(() => z.object({ */ provenance: z.object({ flowRunId: z.string().optional().describe('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.'), + flowRootRunId: z.string().optional().describe('Id of the root run of the flow-run tree `flowRunId` belongs to: the run the tree was started on, above every `subflow` child and `map` item run (equal to `flowRunId` on a run with no parent). Copied from `ExecutionContext.flowRootRunId`, which only the automation engine sets, beside `flowRunId`. Provenance, not authorization: lets a hook recognize a write by any run of one tree — the approvals plugin passes the runs of an approval through the hold it keeps between two steps on an object that declares `closedStates` (ADR-0162 D5).'), attributedUserId: z.string().optional().describe('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: z.string().optional().describe('[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.'), performedByAgentId: z.string().optional().describe('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.'), diff --git a/packages/spec/src/kernel/execution-context.zod.ts b/packages/spec/src/kernel/execution-context.zod.ts index b152d4eafa7..f403964057f 100644 --- a/packages/spec/src/kernel/execution-context.zod.ts +++ b/packages/spec/src/kernel/execution-context.zod.ts @@ -614,6 +614,26 @@ export const ExecutionContextSchema = lazySchema(() => z.object({ */ flowRunId: z.string().optional(), + /** + * Id of the ROOT run of the tree {@link flowRunId} belongs to: the run the + * tree was started on, at any depth of `subflow` children and `map` item + * runs below it (ADR-0162 Execution item 7, "The root run"). On a run with + * no parent it equals {@link flowRunId}. Server-constructed by the automation + * engine beside {@link flowRunId}, from the root run it stamps on every run + * of the tree, and carried wherever {@link flowRunId} is carried — never + * client-supplied. Absent where {@link flowRunId} is, and on a run the + * engine could not place in a tree. + * + * Provenance, NOT authorization, exactly like {@link flowRunId}. It exists so + * a hook can tell a write made by ANY run of one tree from an unrelated + * caller: the approvals plugin holds a record between two steps of an + * approval on an object that declares `closedStates`, and lets through the + * writes of that approval's own runs, which it knows by the root run its + * requests record (ADR-0162 D5, "the hold"). Surfaced to hooks as + * `HookContext.provenance.flowRootRunId`. + */ + flowRootRunId: z.string().optional(), + /** * Suppress record-change AUTOMATION (autolaunched flow triggers: * record-after-insert / -update / -delete) for writes made under this From 6df8b90f95624455c026bac534965ebf4693d6c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:00:38 +0000 Subject: [PATCH 2/7] test(approvals): the hold, measured from inside each passage; docs, changesets and the spec's generated outputs (ADR-0162 D5, item 8) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- .changeset/37767-hold-root-run-spec.md | 11 + .changeset/37767-hold-root-run.md | 13 + .changeset/37767-hold.md | 23 + content/docs/automation/approvals.mdx | 60 ++- content/docs/references/data/data-engine.mdx | 12 + content/docs/references/data/hook.mdx | 3 +- .../approval-hold-37767.integration.test.ts | 405 ++++++++++++++++++ packages/spec/authorable-surface/kernel.json | 1 + .../references/kernel/execution-context.md | 1 + 9 files changed, 526 insertions(+), 3 deletions(-) create mode 100644 .changeset/37767-hold-root-run-spec.md create mode 100644 .changeset/37767-hold-root-run.md create mode 100644 .changeset/37767-hold.md create mode 100644 packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts diff --git a/.changeset/37767-hold-root-run-spec.md b/.changeset/37767-hold-root-run-spec.md new file mode 100644 index 00000000000..2caf01e37d5 --- /dev/null +++ b/.changeset/37767-hold-root-run-spec.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): a run's writes name the root run of its tree (`ExecutionContext.flowRootRunId`, `HookContext.provenance.flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — `skills/` names neither `flowRootRunId` nor `flowRunId` (git grep, 0 hits): both are stamped by the automation engine on a run's writes, and no skill teaches an author to write them + +Widened: `ExecutionContextSchema` and the `provenance` of `HookContextSchema` gain the optional string `flowRootRunId`, beside `flowRunId`: the run id of the root of the run tree the writing run belongs to (the run itself for a root run). The automation engine stamps it on every write a run makes; it is never read from a request. Nothing an author writes changes. diff --git a/.changeset/37767-hold-root-run.md b/.changeset/37767-hold-root-run.md new file mode 100644 index 00000000000..db64ff6ec72 --- /dev/null +++ b/.changeset/37767-hold-root-run.md @@ -0,0 +1,13 @@ +--- +'@objectstack/core': patch +'@objectstack/objectql': patch +'@objectstack/service-automation': patch +'@objectstack/runtime': patch +--- + +feat(automation): every write of a run carries the root run of its tree (`flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: a data write a run makes (`resolveRunDataContext`, the run identity of `@objectstack/service-automation`) carries `flowRootRunId`, the run id of the root of its run tree, beside `flowRunId`; the engine carries it onto the write's `HookContext.provenance` (`@objectstack/objectql`), the platform system api strips it with the other run marks, a sandboxed body and script see it among the declared provenance members (`@objectstack/runtime`), and it is one of the fields an entry point may not set on an `ExecutionContext` (`assembleExecutionContext`, `@objectstack/core`). The approvals plugin reads it to let every run of an approval through the hold. Absent on a write that is not a run's. diff --git a/.changeset/37767-hold.md b/.changeset/37767-hold.md new file mode 100644 index 00000000000..bdd29a7aba9 --- /dev/null +++ b/.changeset/37767-hold.md @@ -0,0 +1,23 @@ +--- +'@objectstack/plugin-approvals': minor +--- + +feat(approvals)!: on an object that declares `closedStates`, the document is held for the whole approval (ADR-0162 D5, Execution item 8, the hold) + +Clause-②: yes (narrowing) +Metadata-protocol: semantic +Skills-docs: none — `skills/` names no `closedStates` (git grep, 0 hits); its `lockRecord` rows describe the lock while a request is pending, which this does not change, and `content/docs/automation/approvals.mdx` teaches the hold + +**BREAKING** for a caller that edits a record of an object that declares `closedStates` while its approval is between two steps, or after its last decision until the approval is over: FROM the edit landing (the record was locked only while a request was pending, and only under a node whose `lockRecord` is not `false`) TO the edit refused `409 RECORD_LOCKED`. The one-line fix: make the edit before submitting or after the approval is over, or make it from the approval's own flow, whose every run passes. No metadata changes and no stored metadata is refused. + +What the hold is. Every decision on such an approval leaves a mark on its request (`unjudged_since`), cleared once the approval is judged or its next request opens. While a mark stands, the pending lock holds the record and its direct `master_detail` lines as a pending request under a locking node does, whatever field the object closes on and whatever the node's `lockRecord` says. It passes: + +- a system context, the approval status mirror among them; +- a write that carries only the mirror field; +- a write by any run of the approval, the record's run or a `subflow` or `map` run under it at any depth, known by the root run (`flowRootRunId`) the automation engine now carries on every write of a run; a hook's write through its own `ctx.api` carries it, a write a hook makes as another caller does not; +- the revise window of a returned request; +- the record's own delete, which lands and ends the approval: it is marked abandoned on its latest request, its marks are cleared, and nothing is written (the reconciler does the same for a record deleted another way). + +An approval that opened before its object declared `closedStates` left no marks and is not held. The approvals-family lock read (`getRecordLock`, the `/lock` and `/locks` routes) answers for a pending request only, as published: in a passage it answers `{ "locked": false }`. + + diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 6a653c29d05..2fc192e660b 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -408,6 +408,10 @@ never deadlock against itself. The exemption is keyed on run identity rather tha elevation, so a `runAs:'user'` run stays row-level-security scoped while it writes — it does not become a system write. +On an object that declares `closedStates`, the document is held for the whole +approval, between its steps as well, and every run of the approval writes it: +see [the hold](#hold). + **The record's lines are locked with it.** Rows of a `master_detail` child of the locked record (an expense claim's lines, an opportunity's products) refuse insert, update and delete with the same `409 RECORD_LOCKED`, and so does moving a row into @@ -1638,6 +1642,12 @@ the step's decision is held back: the request records it, and the field keeps written as before: `pending` as a request opens, `returned` at a send-back, and what an abandoned request leaves. +So a node that follows a decision in the flow reads `pending` on the field, not +the decision, and a flow or a trigger that fires when the field becomes +`approved` fires once, when the approval is over, not at each step. A node that +needs a step's decision reads it on the step's outcome, as the flow's own edges +do. + After each action that moves a run of the approval on (a decision, by a person or by the escalation clock, a send-back, a resubmission, a recall, and the continuation of a restored run), the platform reads the approval's requests on @@ -1769,8 +1779,54 @@ own approval, only whether the run has ended. Where nothing was held back it clears the mark and writes nothing; where it concluded that a run had stopped, a line in the server log says so. A write that a rule or a hook refuses is reported as above, once, and tried again on each -sweep while the mark stands. Where the record was deleted, the reconciler clears -the mark and writes nothing. +sweep while the mark stands. Where the record was deleted, the approval is over: +it is marked abandoned on its latest request, its marks are cleared, and nothing +is written. The delete does that as it lands, below, and the reconciler does it +for a record that went another way. + +### The document is held for the whole approval [#hold] + +On an object that declares `closedStates`, every approval holds the document from +its submission until it is over: while a request is pending, as on any object, +and also through each passage, from a step's decision until the next request +opens or the approval is over (ADR-0162 D5). A passage holds the record and its +direct `master_detail` lines as a pending request does, whatever field the +object closes on and whatever the step's `lockRecord` says: a step that leaves +the record open while its request is pending (`lockRecord: false`) still holds +it once that request is decided. A caller's edit in a passage is refused +`409 RECORD_LOCKED`, so the document cannot change between the decision on it +and the outcome the approval writes. + +What passes the hold: + +- **The approval's own runs.** A write made by any run of the approval, the run + started for the record or a `subflow` or `map` run under it at any depth, a + hook's write through its own `ctx.api` included, lands. A run is known by the + root run it belongs to, which the automation engine carries on every write of + a run (`flowRootRunId`, beside `flowRunId`). A write a hook makes outside that + context, as another caller, is refused. +- **A system context**, the approval status mirror among them. +- **A write that carries only the mirror field.** +- **The revise window** of a returned request, as on any object. +- **The record's own delete.** It lands and ends the approval: the approval is + marked abandoned on its latest request, its marks are cleared, and nothing is + written. A line's delete, or a delete that cascades into a line, is held as + an edit is. + +A passage lasts as long as the approval's marks stand (`unjudged_since`, above). +A run that pauses between two steps, at a `wait` or a screen, holds the +document while it waits; so does a process that stops in a passage, until the +reconciler judges the approval: at its next sweep where the runs can be read, +otherwise once the hour above has passed. Where that is too long for the +business, the flow should not pause between two steps on such an object. + +An approval that was in flight when its object first declared `closedStates` +left no marks, and is not held between its steps. + +The approvals-family lock read (`getRecordLock`, above) answers for a pending +request only: in a passage it answers `{ "locked": false }` while an edit is +refused `409 RECORD_LOCKED`. A page that offers an edit in a passage learns of +the hold from the refusal. ## Why diff --git a/content/docs/references/data/data-engine.mdx b/content/docs/references/data/data-engine.mdx index 7b603eab15c..00a619378bb 100644 --- a/content/docs/references/data/data-engine.mdx +++ b/content/docs/references/data/data-engine.mdx @@ -70,6 +70,7 @@ const result = BaseEngineOptionsSchema.parse(data); | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -128,6 +129,7 @@ Options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -184,6 +186,7 @@ Options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -241,6 +244,7 @@ Options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -320,6 +324,7 @@ Options for DataEngine.insert operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -382,6 +387,7 @@ Query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -470,6 +476,7 @@ Options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -547,6 +554,7 @@ QueryAST-aligned options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -636,6 +644,7 @@ QueryAST-aligned options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -707,6 +716,7 @@ QueryAST-aligned options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -773,6 +783,7 @@ QueryAST-aligned query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -867,6 +878,7 @@ QueryAST-aligned options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 6dac1015ed2..f599774da6d 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -115,7 +115,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **submitted** | `Record` | 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 }` | 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; performedByAgentId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) | +| **provenance** | `{ flowRunId?: string; flowRootRunId?: string; attributedUserId?: string; performedByClientId?: 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 | @@ -155,6 +155,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **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. | +| **flowRootRunId** | `string` | optional | Id of the root run of the flow-run tree `flowRunId` belongs to: the run the tree was started on, above every `subflow` child and `map` item run (equal to `flowRunId` on a run with no parent). Copied from `ExecutionContext.flowRootRunId`, which only the automation engine sets, beside `flowRunId`. Provenance, not authorization: lets a hook recognize a write by any run of one tree — the approvals plugin passes the runs of an approval through the hold it keeps between two steps on an object that declares `closedStates` (ADR-0162 D5). | | **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`, 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. | | **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. | diff --git a/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts new file mode 100644 index 00000000000..5021f2a5e87 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts @@ -0,0 +1,405 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5 "the hold", Execution item 8, #37767 piece 5] On an object that + * declares `closedStates`, a document is held for the whole of every approval: + * through each passage, from a step's decision until the next request opens + * or the approval is over, as well as while a request is pending. + * + * The pending lock reads the requests that carry the mark (`unjudged_since`) + * beside the pending ones, and holds the record and its `master_detail` lines + * as a pending request under a locking node does, whatever the node's + * `lockRecord`. It passes a system context, a write that carries only the + * mirror field, the revise window of a returned request, the record's own + * delete, and a write that carries a run of the approval, known by its root + * run (`flowRootRunId`, which the automation engine stamps on every write of + * a run beside `flowRunId`). + * + * Each passage is observed from inside it: a `mark` node between two steps + * (or after the last) runs the write under test while the passage lasts, + * either as a caller or as its own run, the way a data node writes + * (`resolveRunDataContext`). + * + * Real kernel, real ObjectQL engine, real automation engine, real approval + * node, the plugin's own lock hooks, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, resolveRunDataContext, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { bindApprovalLockHook, bindDetailRowLockHook, bindRecordDeleteCancelHook } from './lifecycle-hooks.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, tenantId: ORG, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes only on a value of its own, on another field than the approval's. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, held as on `main`. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; +/** Declares no closed state when its approval opens; the test declares one afterwards. */ +const late = { name: 'crm_late', label: 'Late', fields }; +const lateClosing = { ...late, closedStates: { stage: ['done'] } }; +/** A line of the invoice. */ +const invoiceLine = { + name: 'crm_invoice_line', label: 'Invoice Line', + fields: { name: text('name'), invoice: { name: 'invoice', type: 'master_detail' as const, reference: 'crm_invoice' } }, +}; +/** A product whose delete cascades into the invoice's bundle lines. */ +const product = { name: 'crm_product', label: 'Product', fields: { name: text('name') } }; +const bundleLine = { + name: 'crm_bundle_line', label: 'Bundle Line', + fields: { + name: text('name'), + invoice: { name: 'invoice', type: 'master_detail' as const, reference: 'crm_invoice' }, + product: { name: 'product', type: 'lookup' as const, reference: 'crm_product', deleteBehavior: 'cascade' as const }, + }, +}; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const probe = { id: 'probe', type: 'mark', label: 'Probe' }; +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[]) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges }); +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + // A probe between the two steps. + flow('two_probe', [step('first', 'approver'), probe, step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), + // The same, under a node that leaves the record open while its request is pending. + flow('unlocked_probe', [step('first', 'approver', { lockRecord: false }), probe, step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), + // A probe after the only step. + flow('only_probe', [step('only', 'approver'), probe], + [edge('start', 'only'), ...decided('only', 'probe'), edge('probe', 'end')]), + // Two levels of runs: the root delegates to a middle run, which delegates the + // first step and then probes, as the middle run, after the child's decision. + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + flow('mid_probe', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }, probe], + [edge('start', 'inner'), edge('inner', 'probe'), edge('probe', 'end')]), + flow('root_mid_probe', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'mid_probe' } }, step('second', 'approver2')], + [edge('start', 'mid'), edge('mid', 'second'), ...decided('second', 'end')]), + // Two steps, the second of which can be sent back for revision. + flow('two_revise', [step('first', 'approver'), step('second', 'approver2'), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'end', 'approve'), edge('second', 'end', 'reject'), + edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), +]; + +describe('[ADR-0162 D5, item 8] the hold: a document is held through every passage of its approval', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** What runs while the `probe` node executes: inside the passage that reached it, with the run's context. */ + let during: ((context: any) => Promise) | undefined; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + during = undefined; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, ticket, memo, late, invoiceLine, product, bundleLine, + SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async () => {} } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + bindApprovalLockHook(ql as any, quiet as any); + bindDetailRowLockHook(ql as any, quiet as any); + bindRecordDeleteCancelHook(ql as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (node.id === 'probe') await during?.(context); + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T, code: undefined as string | undefined }), (e: any) => ({ ok: undefined, code: String(e?.code ?? e?.message ?? e) })); + /** A caller's edit of the record: no run behind it. */ + const callerEdit = (object: string, id: string, stage = 'edited by a caller') => + settle(ql.update(object, { id, stage }, { context: asPerson('owner') })); + /** A write by the run whose node is executing, as a data node makes it. */ + const runEdit = (context: any, object: string, id: string, stage = 'edited by the run') => + settle(ql.update(object, { id, stage }, { context: resolveRunDataContext(context) as any })); + /** Run `fn` with no door judging: the shape a process that died after the door's own action leaves. */ + const withoutDoor = async (fn: () => Promise): Promise => { + const judge = (svc as any).judgeApprovalAfterDoor; + (svc as any).judgeApprovalAfterDoor = async () => 'undetermined'; + try { return await fn(); } finally { (svc as any).judgeApprovalAfterDoor = judge; } + }; + + describe('a caller is held through the passage', () => { + it('between two steps: a caller\'s edit is refused, the run\'s own write lands, and the field reads pending', async () => { + await start('two_probe', 'crm_invoice', 'i_between'); + const seen: unknown[] = []; + during = async (context) => { + seen.push(['caller', (await callerEdit('crm_invoice', 'i_between')).code]); + seen.push(['run', (await runEdit(context, 'crm_invoice', 'i_between')).code]); + seen.push(['field', (await read('crm_invoice', 'i_between')).approval_status]); + seen.push(['marks', await marks('i_between')]); + }; + await decide('i_between', 'approve', 'approver'); + expect(seen).toEqual([['caller', 'RECORD_LOCKED'], ['run', undefined], ['field', 'pending'], ['marks', [true]]]); + expect((await read('crm_invoice', 'i_between')).stage).toBe('edited by the run'); + expect((await requestsOn('i_between')).map((r) => r.status), 'the approval went on').toEqual(['approved', 'pending']); + }); + + it('after the last decision, until the approval is over: a caller\'s edit is refused', async () => { + await start('only_probe', 'crm_invoice', 'i_after'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_invoice', 'i_after')).code; }; + await decide('i_after', 'approve', 'approver'); + expect(caller).toBe('RECORD_LOCKED'); + expect((await read('crm_invoice', 'i_after')).approval_status, 'the outcome, once the approval is over').toBe('approved'); + expect(await marks('i_after')).toEqual([false]); + }); + + it('an approval whose field the object does not close on, on an object that closes only on a value of its own: held too', async () => { + await start('two_probe', 'crm_ticket', 't_between'); + const seen: unknown[] = []; + during = async () => { + seen.push((await callerEdit('crm_ticket', 't_between')).code); + seen.push((await read('crm_ticket', 't_between')).approval_status); + }; + await decide('t_between', 'approve', 'approver'); + expect(seen, 'held, and its outcome written at once').toEqual(['RECORD_LOCKED', 'approved']); + }); + + it('CONTROL: an object that declares no closed state is not held between two steps, as on main', async () => { + await start('two_probe', 'crm_memo', 'm_between'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_memo', 'm_between')).code; }; + await decide('m_between', 'approve', 'approver'); + expect(caller).toBeUndefined(); + expect((await read('crm_memo', 'm_between')).stage).toBe('edited by a caller'); + }); + + it('a write that carries only the mirror field passes, as it does while a request is pending', async () => { + await start('two_probe', 'crm_ticket', 't_mirror'); + // A writer that stamps no `updated_by`: the only shape whose write + // carries the mirror field alone (a person's write carries `updated_by` + // as well, and is refused in both states). + const unattributed = { tenantId: ORG, positions: [], permissions: [] } as any; + const mirrorWrite = (ctx: any, value: string) => + settle(ql.update('crm_ticket', { id: 't_mirror', approval_status: value }, { context: ctx })); + const pending = [(await mirrorWrite(unattributed, 'pending')).code, (await mirrorWrite(asPerson('owner'), 'pending')).code]; + let passage: unknown[] = []; + during = async () => { passage = [(await mirrorWrite(unattributed, 'pending')).code, (await mirrorWrite(asPerson('owner'), 'pending')).code]; }; + await decide('t_mirror', 'approve', 'approver'); + expect(pending).toEqual([undefined, 'RECORD_LOCKED']); + expect(passage).toEqual(pending); + }); + + it('a node that declares lockRecord: false: a caller\'s edit lands while its request is pending, and is refused after its decision', async () => { + await start('unlocked_probe', 'crm_invoice', 'i_unlocked'); + expect((await callerEdit('crm_invoice', 'i_unlocked', 'while pending')).code).toBeUndefined(); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_invoice', 'i_unlocked')).code; }; + await decide('i_unlocked', 'approve', 'approver'); + expect(caller).toBe('RECORD_LOCKED'); + }); + + it('a line of the record: a caller\'s line write is refused in the passage, and the run\'s lands', async () => { + await start('two_probe', 'crm_invoice', 'i_lines'); + const seen: unknown[] = []; + during = async (context) => { + seen.push((await settle(ql.insert('crm_invoice_line', { id: 'l_caller', name: 'x', invoice: 'i_lines', organization_id: ORG }, { context: asPerson('owner') }))).code); + seen.push((await settle(ql.insert('crm_invoice_line', { id: 'l_run', name: 'y', invoice: 'i_lines', organization_id: ORG }, { context: resolveRunDataContext(context) as any }))).code); + }; + await decide('i_lines', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await ql.find('crm_invoice_line', { where: { invoice: 'i_lines' }, context: SYS })).map((l: any) => l.id)).toEqual(['l_run']); + }); + }); + + describe('the approval\'s own runs pass, known by their root run', () => { + it('a node of a middle run, after the step its child decided: its write lands, and a caller\'s is refused', async () => { + await start('root_mid_probe', 'crm_invoice', 'i_mid'); + const seen: unknown[] = []; + let runs: { run?: string; root?: string } = {}; + during = async (context) => { + const data = resolveRunDataContext(context) as any; + runs = { run: data.flowRunId, root: data.flowRootRunId }; + seen.push(['run', (await runEdit(context, 'crm_invoice', 'i_mid')).code]); + seen.push(['caller', (await callerEdit('crm_invoice', 'i_mid')).code]); + // The same run's write without the root run it carries: the run is + // none the request names, so only the root run lets it through. + seen.push(['run without its root', (await settle(ql.update('crm_invoice', { id: 'i_mid', stage: 'x' }, { context: { ...data, flowRootRunId: undefined } }))).code]); + }; + await decide('i_mid', 'approve', 'approver'); + const [first] = await requestsOn('i_mid'); + expect(runs.root, 'the write carries the root run the request records').toBe(String(first.root_run_id)); + expect([first.flow_run_id, first.root_run_id, first.record_run_id].map(String), 'the middle run is none the request names').not.toContain(runs.run); + expect(seen).toEqual([['run', undefined], ['caller', 'RECORD_LOCKED'], ['run without its root', 'RECORD_LOCKED']]); + expect((await requestsOn('i_mid')).map((r) => r.status), 'the approval went on to its second step').toEqual(['approved', 'pending']); + }); + + it('a hook\'s write-back carries the run where the hook writes through its own api, and is refused where it writes outside it', async () => { + await start('two_probe', 'crm_invoice', 'i_hook'); + ql.registerHook('afterUpdate', async (ctx: any) => { + const stage = ctx?.input?.data?.stage; + if (stage === 'through the api') await ctx.api.object('crm_invoice').update({ id: 'i_hook', name: 'written back' }); + if (stage === 'outside the run') await ql.update('crm_invoice', { id: 'i_hook', name: 'written back' }, { context: asPerson('owner') }); + }, { object: 'crm_invoice', packageId: 'hold-test-hook' } as any); + const seen: unknown[] = []; + during = async (context) => { + seen.push((await runEdit(context, 'crm_invoice', 'i_hook', 'outside the run')).code); + seen.push((await runEdit(context, 'crm_invoice', 'i_hook', 'through the api')).code); + }; + await decide('i_hook', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await read('crm_invoice', 'i_hook')).name).toBe('written back'); + }); + + it('a cascade into a line: a caller\'s delete of the other master is refused, and the run\'s lands', async () => { + await start('two_probe', 'crm_invoice', 'i_cascade'); + for (const id of ['p_caller', 'p_run']) await ql.insert('crm_product', { id, name: id, organization_id: ORG }, { context: SYS }); + for (const p of ['p_caller', 'p_run']) { + await ql.insert('crm_bundle_line', { id: `b_${p}`, name: p, invoice: 'i_cascade', product: p, organization_id: ORG }, { context: SYS }); + } + const seen: unknown[] = []; + during = async (context) => { + seen.push((await settle(ql.delete('crm_product', { where: { id: 'p_caller' }, context: asPerson('owner') } as any))).code); + seen.push((await settle(ql.delete('crm_product', { where: { id: 'p_run' }, context: resolveRunDataContext(context) } as any))).code); + }; + await decide('i_cascade', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await ql.find('crm_bundle_line', { where: { invoice: 'i_cascade' }, context: SYS })).map((l: any) => l.id)).toEqual(['b_p_caller']); + }); + }); + + describe('what the hold keeps of the pending lock', () => { + it('the revise window that follows an earlier step\'s decision is open to every caller who may edit, a mark left behind included', async () => { + await start('two_revise', 'crm_invoice', 'i_revise'); + await decide('i_revise', 'approve', 'approver'); + const [first, second] = await requestsOn('i_revise'); + await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect((await requestsOn('i_revise')).map((r) => r.status)).toEqual(['approved', 'returned']); + // A mark the opening of the second request did not clear. + await ql.update('sys_approval_request', { id: first.id, unjudged_since: new Date().toISOString() }, { context: SYS }); + expect((await callerEdit('crm_invoice', 'i_revise')).code).toBeUndefined(); + }); + + it('a caller\'s delete in a passage lands and ends the approval: marked abandoned, its marks cleared, nothing written', async () => { + await start('only_probe', 'crm_invoice', 'i_delete'); + let deleted: string | undefined = 'not reached'; + during = async () => { deleted = (await settle(ql.delete('crm_invoice', { where: { id: 'i_delete' }, context: asPerson('owner') } as any))).code; }; + await settle(decide('i_delete', 'approve', 'approver')); + expect(deleted).toBeUndefined(); + expect(await read('crm_invoice', 'i_delete')).toBeUndefined(); + const [only] = await requestsOn('i_delete'); + expect(only.status).toBe('approved'); + expect(only.unjudged_since).toBeNull(); + expect(JSON.parse(only.node_config_json).__abandoned?.reason).toBe('the record was deleted.'); + expect((await svc.reconcileMarkedApprovals()).scanned, 'the reconciler has nothing to try again').toBe(0); + }); + + it('the approvals-family read answers for a pending request only, as published: not locked in a passage', async () => { + await start('two_probe', 'crm_invoice', 'i_read'); + let answer: unknown; + during = async () => { answer = await svc.getRecordLock('crm_invoice', 'i_read', asPerson('owner')); }; + await decide('i_read', 'approve', 'approver'); + expect(answer).toEqual({ locked: false }); + expect(await svc.getRecordLock('crm_invoice', 'i_read', asPerson('owner')), 'its next request pending').toEqual({ locked: true, lockSource: 'record' }); + }); + + it('an approval that opened before the object declared closedStates is not held', async () => { + await start('two_probe', 'crm_late', 'x_late'); + ql.registry.registerObject(lateClosing as any, 'approvals-test', 'approvals-test'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_late', 'x_late')).code; }; + await decide('x_late', 'approve', 'approver'); + expect(await marks('x_late')).toEqual([false, false]); + expect(caller).toBeUndefined(); + }); + + it('a process that dies in a passage leaves the document held, and the reconciler ends the hold', async () => { + await start('two_step', 'crm_ticket', 't_died'); + await decide('t_died', 'approve', 'approver'); + await withoutDoor(() => decide('t_died', 'approve', 'approver2')); + expect(await marks('t_died')).toEqual([false, true]); + expect((await callerEdit('crm_ticket', 't_died')).code, 'held while nobody judged the approval').toBe('RECORD_LOCKED'); + + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await marks('t_died')).toEqual([false, false]); + expect((await callerEdit('crm_ticket', 't_died')).code, 'the hold ended with the judgement').toBeUndefined(); + }); + }); +}); diff --git a/packages/spec/authorable-surface/kernel.json b/packages/spec/authorable-surface/kernel.json index 6e7a3a8f0f6..de279dff3df 100644 --- a/packages/spec/authorable-surface/kernel.json +++ b/packages/spec/authorable-surface/kernel.json @@ -175,6 +175,7 @@ "kernel/ExecutionContext:authGate", "kernel/ExecutionContext:currency", "kernel/ExecutionContext:email", + "kernel/ExecutionContext:flowRootRunId", "kernel/ExecutionContext:flowRunId", "kernel/ExecutionContext:impersonatedBy", "kernel/ExecutionContext:isSystem", diff --git a/packages/spec/docs/references/kernel/execution-context.md b/packages/spec/docs/references/kernel/execution-context.md index 90ba68375bf..10b7f761dfa 100644 --- a/packages/spec/docs/references/kernel/execution-context.md +++ b/packages/spec/docs/references/kernel/execution-context.md @@ -70,6 +70,7 @@ const result = AuthGateCodeSchema.parse(data); | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | From b4c94c6d31a92ceaf0cf4055a8c17b40a061796c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:08:19 +0000 Subject: [PATCH 3/7] chore(approvals): the write census counts the abandoned stamp of a deleted record; the spec key is server-set (ADR-0162 D5, item 8) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- .changeset/37767-hold-root-run-spec.md | 5 ++--- .../plugins/plugin-approvals.md | 16 ++++++++-------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/.changeset/37767-hold-root-run-spec.md b/.changeset/37767-hold-root-run-spec.md index 2caf01e37d5..da86dbe6298 100644 --- a/.changeset/37767-hold-root-run-spec.md +++ b/.changeset/37767-hold-root-run-spec.md @@ -1,11 +1,10 @@ --- -'@objectstack/spec': minor +'@objectstack/spec': patch --- feat(spec): a run's writes name the root run of its tree (`ExecutionContext.flowRootRunId`, `HookContext.provenance.flowRootRunId`, ADR-0162 D5) Clause-②: yes (widening) -Metadata-protocol: added -Skills-docs: none — `skills/` names neither `flowRootRunId` nor `flowRunId` (git grep, 0 hits): both are stamped by the automation engine on a run's writes, and no skill teaches an author to write them +Metadata-protocol: none Widened: `ExecutionContextSchema` and the `provenance` of `HookContextSchema` gain the optional string `flowRootRunId`, beside `flowRunId`: the run id of the root of the run tree the writing run belongs to (the run itself for a root run). The automation engine stamps it on every write a run makes; it is never read from a request. Nothing an author writes changes. diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 45b009061f5..bcaeb4fd4f9 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 50 | -| Object name statically decidable | 48 | +| Write call sites | 51 | +| Object name statically decidable | 49 | | Object name chosen at run time | 2 | -| Object name spelled inline | 46 | +| Object name spelled inline | 47 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 48 | +| Against a tenancy-enabled object | 49 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 50 | +| Threading a tenant context | 51 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 48 | +| Threading a decidably elevated (`isSystem`) context | 49 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 50 | +| Receiver carried a readable engine type | 51 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -54,7 +54,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 15 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 16 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | From dc12b076f5701a043fd2dce4d2e60d2af1acbdac Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:57:39 +0000 Subject: [PATCH 4/7] test(automation): a root run's write carries itself as the root run (ADR-0162 D5) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- .../src/runas-user-posture-rung.integration.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/services/service-automation/src/runas-user-posture-rung.integration.test.ts b/packages/services/service-automation/src/runas-user-posture-rung.integration.test.ts index 462bffaa59a..0e9c86b36c1 100644 --- a/packages/services/service-automation/src/runas-user-posture-rung.integration.test.ts +++ b/packages/services/service-automation/src/runas-user-posture-rung.integration.test.ts @@ -169,6 +169,7 @@ describe("[#28070] a runAs:'user' run's data context carries the rung its resolv await h.engine.execute('rung_sys', { userId: 'usr_admin', tenantId: 'org_a' } as never); expect(h.ctxOf('first')).toEqual({ isSystem: true, actor: 'svc:flow:rung_sys', userId: 'usr_admin', tenantId: 'org_a', flowRunId: expect.any(String), + flowRootRunId: h.ctxOf('first').flowRunId, // ADR-0162 D5: a root run is the root of its own tree posture: 'PLATFORM_ADMIN', [FLOW_WRITE_REFERENCE_CHECK]: true, // #28881 }); From 2802399e1d8b30f23820380e442a8173009aeedc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:44:01 +0000 Subject: [PATCH 5/7] =?UTF-8?q?fix(approvals):=20CI=20round=20=E2=80=94=20?= =?UTF-8?q?the=20body-face=20pin=20names=20the=20new=20provenance=20member?= =?UTF-8?q?;=20typed=20find=20options=20(ADR-0162=20D5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- packages/cli/test/lowered-body-face-enumeration.test.ts | 4 ++-- packages/plugins/plugin-approvals/src/lifecycle-hooks.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cli/test/lowered-body-face-enumeration.test.ts b/packages/cli/test/lowered-body-face-enumeration.test.ts index cf5d7953323..481c74bff72 100644 --- a/packages/cli/test/lowered-body-face-enumeration.test.ts +++ b/packages/cli/test/lowered-body-face-enumeration.test.ts @@ -281,11 +281,11 @@ describe('the lowered body face, against the in-process HookContext (#22837)', ( 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', 'performedByAgentId', + 'flowRunId', 'flowRootRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', 'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy', ])); expect(body.get('provenance')).toEqual(new Set([ - 'flowRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', + 'flowRunId', 'flowRootRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', 'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy', ])); // A tombstone is no member: `session.roles` is `retiredKey(…)`. diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index 898e5440052..4e4a899be2e 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -713,7 +713,7 @@ async function passageRequestsFor( try { const rows = await engine.find('sys_approval_request', { where, limit: PENDING_LOCK_LIMIT + 1, context: { ...SYSTEM_CTX }, - } as any); + }); return Array.isArray(rows) ? rows : []; } catch { return []; @@ -766,7 +766,7 @@ async function approvalInPassage(engine: Pick, marked: an where: { root_run_id: marked.root_run_id, object_name: marked.object_name, record_id: marked.record_id }, fields: ['id', 'status', 'created_at', 'unjudged_since', 'node_config_json'], limit: 500, context: { ...SYSTEM_CTX }, - } as any); + }); rows = Array.isArray(found) ? found : []; } catch { return true; From 56e735f99a500a7b6ba0f670a55927178b79589a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 11:17:53 +0000 Subject: [PATCH 6/7] docs(automation): a hook body's provenance table names flowRootRunId (ADR-0162 D5) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- content/docs/automation/hook-bodies.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 4cdd61ef5f7..c5012c0ea60 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -117,6 +117,7 @@ A hook body sees the same server-stamped write provenance an in-process handler | Member | Present when | |---|---| | `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. | +| `ctx.provenance.flowRootRunId` | Set beside `flowRunId`: the id of the root run of that run's tree, the run itself for a run no other run started. | | `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). | | `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. | | `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. | From 1d89edbc91b7ad0fe4a02e347b16808acf5d6679 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 11:39:21 +0000 Subject: [PATCH 7/7] docs(approvals): name the user-run automation the hold refuses, and when flowRootRunId is absent (ADR-0162 D5) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmPpwJymVUdp5AnRPBq --- .changeset/37767-hold.md | 2 +- content/docs/automation/approvals.mdx | 6 +++++- content/docs/automation/hook-bodies.mdx | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.changeset/37767-hold.md b/.changeset/37767-hold.md index bdd29a7aba9..227e6743eb1 100644 --- a/.changeset/37767-hold.md +++ b/.changeset/37767-hold.md @@ -8,7 +8,7 @@ Clause-②: yes (narrowing) Metadata-protocol: semantic Skills-docs: none — `skills/` names no `closedStates` (git grep, 0 hits); its `lockRecord` rows describe the lock while a request is pending, which this does not change, and `content/docs/automation/approvals.mdx` teaches the hold -**BREAKING** for a caller that edits a record of an object that declares `closedStates` while its approval is between two steps, or after its last decision until the approval is over: FROM the edit landing (the record was locked only while a request was pending, and only under a node whose `lockRecord` is not `false`) TO the edit refused `409 RECORD_LOCKED`. The one-line fix: make the edit before submitting or after the approval is over, or make it from the approval's own flow, whose every run passes. No metadata changes and no stored metadata is refused. +**BREAKING** for a caller that edits a record of an object that declares `closedStates` while its approval is between two steps, or after its last decision until the approval is over: FROM the edit landing (the record was locked only while a request was pending, and only under a node whose `lockRecord` is not `false`) TO the edit refused `409 RECORD_LOCKED`. The same holds for an automation that runs as a user outside the approval's own flow, such as a record-change flow with `runAs: 'user'` that a decision sets off. The one-line fix: make the edit before submitting or after the approval is over, or make it from the approval's own flow, whose every run passes; for such an automation, run it with `runAs: 'system'`. No metadata changes and no stored metadata is refused. What the hold is. Every decision on such an approval leaves a mark on its request (`unjudged_since`), cleared once the approval is judged or its next request opens. While a mark stands, the pending lock holds the record and its direct `master_detail` lines as a pending request under a locking node does, whatever field the object closes on and whatever the node's `lockRecord` says. It passes: diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 2fc192e660b..6c5742c1ef4 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1795,7 +1795,11 @@ object closes on and whatever the step's `lockRecord` says: a step that leaves the record open while its request is pending (`lockRecord: false`) still holds it once that request is decided. A caller's edit in a passage is refused `409 RECORD_LOCKED`, so the document cannot change between the decision on it -and the outcome the approval writes. +and the outcome the approval writes. That caller includes an automation that +runs as a user outside the approval's own flow: a record-change flow with +`runAs: 'user'` that a decision sets off starts a run tree of its own, and its +write to the document is refused the same way. Run such a flow with +`runAs: 'system'`, or make the write from the approval's own flow. What passes the hold: diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index c5012c0ea60..b19ee0a8baa 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -117,7 +117,7 @@ A hook body sees the same server-stamped write provenance an in-process handler | Member | Present when | |---|---| | `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. | -| `ctx.provenance.flowRootRunId` | Set beside `flowRunId`: the id of the root run of that run's tree, the run itself for a run no other run started. | +| `ctx.provenance.flowRootRunId` | Set beside `flowRunId`: the id of the root run of that run's tree, the run itself for a run no other run started. Absent on a run the engine could not place in a tree. | | `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). | | `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. | | `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. |