From 48a589bab624526c627e2a1a598c8abb083ee96a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:55:03 +0000 Subject: [PATCH 1/9] feat(spec, plugin-audit): a sealed object names its chain column with lifecycle.seal.chainField The sealer, the live check and the proof bundle read a row's chain value through one reader, chainValueOf; the signed body keeps its tenant_id member, carrying that value. Authoring refuses a named chain column the object does not have, injected columns counting. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-audit/src/audit-seal/canonical.ts | 26 ++++++ .../plugin-audit/src/audit-seal/sealer.ts | 28 +++--- .../src/audit-seal/signed-body.ts | 7 +- .../plugin-audit/src/audit-seal/verifier.ts | 8 +- ...t-lifecycle-seal-chain-field-34164.test.ts | 86 +++++++++++++++++++ packages/spec/src/data/object.zod.ts | 54 ++++++++++++ 6 files changed, 194 insertions(+), 15 deletions(-) create mode 100644 packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts diff --git a/packages/plugins/plugin-audit/src/audit-seal/canonical.ts b/packages/plugins/plugin-audit/src/audit-seal/canonical.ts index 5f2bffa416d..eb8e71fac02 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/canonical.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/canonical.ts @@ -359,6 +359,32 @@ export function rowIdOf(row: Readonly>): string { throw new CanonicalFormError(`a sealed row carries no usable id (a ${id === null ? 'null' : typeof id})`); } +/** + * ADR-0154 D5, read with the D10 note on `chainField`: the column whose value + * names the organization chain a sealed object's rows join, when the object + * names none. `sys_audit_log` and every object sealed before the key existed + * chain by it. + */ +export const AUDIT_SEAL_DEFAULT_CHAIN_FIELD = 'tenant_id'; + +/** The chain column a sealed object's `lifecycle` block names (`seal.chainField`), or the default. */ +export function sealChainFieldOf(lifecycle: unknown): string { + const named = (lifecycle as { seal?: { chainField?: unknown } } | null | undefined)?.seal?.chainField; + return typeof named === 'string' && named !== '' ? named : AUDIT_SEAL_DEFAULT_CHAIN_FIELD; +} + +/** + * The organization chain a sealed row joins: the value of its object's chain + * column ({@link sealChainFieldOf}), or `null` — the deployment chain (D5) — + * when that value is not a non-empty string. The one reader of a row's chain: + * the sealer, the live check and the proof bundle it writes all call it, and + * the checkpoint's signed `tenant_id` carries what it answers. + */ +export function chainValueOf(row: Readonly>, chainField: string): string | null { + const value = row[chainField]; + return typeof value === 'string' && value !== '' ? value : null; +} + /** UTF-16 code-unit order — the order JCS sorts names in, and the leaf order below uses. */ function compareCodeUnits(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index e6877d87bee..98fa51054c0 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -14,9 +14,11 @@ import { AUDIT_SEAL_CANON_VERSION, CanonicalFormError, canonicalDatetime, + chainValueOf, leafHash, leafInput, rowIdOf, + sealChainFieldOf, sealedColumnSet, unsealableColumns, type SealedColumnSet, @@ -162,6 +164,8 @@ interface SealPlan { readonly name: string; readonly fields: SealedFieldTypes; readonly columns: SealedColumnSet; + /** The column each row's chain is read from ({@link chainValueOf}): `lifecycle.seal.chainField`, or `tenant_id`. */ + readonly chainField: string; readonly archiveTo?: string; } @@ -217,7 +221,6 @@ function faultOf(err: unknown): string { return typeof code === 'string' || typeof code === 'number' ? `${String(code)}: ${reason}` : reason; } const windowOf = (ms: number): number => Math.floor(ms / AUDIT_SEAL_WINDOW_MS) * AUDIT_SEAL_WINDOW_MS; -const tenantOf = (row: Row): string | null => (typeof row.tenant_id === 'string' && row.tenant_id !== '' ? row.tenant_id : null); /** Q2 (a): with no cluster service the lock is this process's, with its own fencing counter. */ let inProcessHeld = false; @@ -321,6 +324,7 @@ export class AuditSealer { const lifecycle = object.lifecycle as { seal?: { valueFields?: string[] }; archive?: { to?: string } } | undefined; if (!lifecycle?.seal) continue; const fields = (object.fields ?? {}) as SealedFieldTypes; + const chainField = sealChainFieldOf(lifecycle); let reason: string | null = null; let columns: SealedColumnSet | null = null; try { @@ -329,9 +333,11 @@ export class AuditSealer { if (refused.length > 0) { reason = `its column(s) ${refused.map((c) => `'${c.column}' (type '${c.type ?? 'none'}')`).join(', ')} ` + 'have no canonical rule'; - } else if (!Object.prototype.hasOwnProperty.call(fields, 'tenant_id')) { - // S3: a chain is the row's own `tenant_id`; without the column every organization would share one. - reason = "it declares no 'tenant_id' field, so its rows cannot be chained per organization"; + } else if (!Object.prototype.hasOwnProperty.call(fields, chainField)) { + // S3: a chain is the row's own chain column (D10 note: `seal.chainField`, default `tenant_id`); without + // it every organization would share one. A NAMED column the object lacks is refused at authoring; this + // stays for the default, and for a definition that reached the registry without the parse. + reason = `it has no '${chainField}' field, the column its rows are chained by per organization`; } } catch (err) { reason = (err as Error).message; @@ -340,11 +346,11 @@ export class AuditSealer { this.report(`plan:${object.name}`, () => `AuditSealer: '${object.name}' declares lifecycle.seal but cannot be sealed: ${reason}. Its rows are NOT ` + 'being sealed — no checkpoint covers them, so a change made outside the platform would not show. Fix: ' + - "give the object a 'tenant_id' field and only columns of a type with a canonical rule (ADR-0154 D1, D5), " + - 'or remove lifecycle.seal.'); + "give the object its chain column ('tenant_id', or the one lifecycle.seal.chainField names) and only " + + 'columns of a type with a canonical rule (ADR-0154 D1, D5, D10), or remove lifecycle.seal.'); continue; } - plans.push({ name: object.name, fields, columns, ...(lifecycle.archive?.to ? { archiveTo: lifecycle.archive.to } : {}) }); + plans.push({ name: object.name, fields, columns, chainField, ...(lifecycle.archive?.to ? { archiveTo: lifecycle.archive.to } : {}) }); } return plans; } @@ -518,7 +524,7 @@ class ObjectPass { break; } const start = windowOf(next); - const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(tenantOf(row)))); + const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(chainValueOf(row, this.plan.chainField)))); if (chains.size > 0) n += 1; else if (this.skipped.size > 0) idle += 1; await this.writeChains(chains, start, 'window', Math.max(this.watermark ?? Number.NEGATIVE_INFINITY, Math.min(start, this.stuckFrom()))); @@ -589,7 +595,7 @@ class ObjectPass { } } const chains = await this.readWindow(start, (row) => - !ids.has(rowIdOf(row)) && start < this.cursorOf(chainKeyOf(tenantOf(row)))); + !ids.has(rowIdOf(row)) && start < this.cursorOf(chainKeyOf(chainValueOf(row, this.plan.chainField)))); await this.writeChains(chains, start, 'late', this.watermark ?? start); } } @@ -665,7 +671,7 @@ class ObjectPass { limit: PAGE_SIZE, }); for (const row of rows) { - const tenantId = tenantOf(row); + const tenantId = chainValueOf(row, this.plan.chainField); const key = chainKeyOf(tenantId); if (this.skipped.has(key)) continue; // S4: out for the rest of the pass try { @@ -797,7 +803,7 @@ class ObjectPass { const row = byId.get(id); if (!row) continue; const at = canonicalDatetime(row.created_at, `${id}.created_at`); - if (windowOf(Date.parse(at)) !== start || chainKeyOf(tenantOf(row)) !== key) continue; + if (windowOf(Date.parse(at)) !== start || chainKeyOf(chainValueOf(row, this.plan.chainField)) !== key) continue; leaves.push({ id, at, hash: leafHash(leafInput(row, this.plan.columns, this.plan.fields, saltOf)) }); } return leaves.sort(leafOrder); diff --git a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts index 6cc14de7493..98300a1d73a 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts @@ -61,7 +61,12 @@ export function chainKeyOf(tenantId: string | null): string { /** What a checkpoint's signature covers (D4). */ export interface CheckpointSignedBody { readonly sealed_object: string; - /** The chain's organization; `null` for the deployment chain (D5). */ + /** + * The chain's organization; `null` for the deployment chain (D5). The value + * of the sealed object's chain column (`lifecycle.seal.chainField`, default + * `tenant_id`; `chainValueOf` reads it), under this member name whatever the + * column is called, so a `tenant_id` object's bytes are what they were. + */ readonly tenant_id: string | null; readonly sequence: number; readonly kind: AuditCheckpointKind; diff --git a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts index 1bb8c22d765..f29f0168849 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts @@ -4,7 +4,7 @@ import { createPublicKey, verify, type KeyObject } from 'node:crypto'; import { parseLifecycleDuration } from '@objectstack/objectql'; import type { IAuditCheckpointSigner, ICryptoProvider } from '@objectstack/spec/contracts'; import { isMissingTableError } from '@objectstack/types'; -import { canonicalDatetime, leafHash, leafInput, rowIdOf, type SealedFieldTypes } from './canonical.js'; +import { canonicalDatetime, chainValueOf, leafHash, leafInput, rowIdOf, sealChainFieldOf, type SealedFieldTypes } from './canonical.js'; import { AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT, AUDIT_SIGNING_KEY_OBJECT, checkpointSeedContext, columnSaltsOf, decodeCheckpointSeed } from './seed.js'; import { AUDIT_SEAL_WINDOW_MS } from './sealer.js'; import { @@ -250,7 +250,6 @@ interface BundleDraft { const PAGE_SIZE = 500; const iso = (ms: number): string => new Date(ms).toISOString(); const windowOf = (ms: number): number => Math.floor(ms / AUDIT_SEAL_WINDOW_MS) * AUDIT_SEAL_WINDOW_MS; -const tenantOf = (row: Row): string | null => (typeof row.tenant_id === 'string' && row.tenant_id !== '' ? row.tenant_id : null); const zero = (): AuditVerdictCounts => ({ unmodified: 0, modified: 0, missing: 0, late: 0, redacted: 0, expired: 0, unsealed: 0 }); const messageOf = (err: unknown): string => String((err as Error)?.message ?? err); @@ -861,6 +860,8 @@ function jsonColumn(value: unknown): unknown { /** One sealed object's chains and rows, read live. */ class ObjectCheck extends ChainCheck { private readonly types: SealedFieldTypes; + /** The column a row's chain is read from, as the sealer reads it ({@link chainValueOf}). */ + private readonly chainField: string; private readonly hot: SealStorageDriver; private readonly archive: SealStorageDriver | undefined; /** The object's highest trusted `sealed_through`, and the windows a trusted `window` checkpoint names. */ @@ -881,6 +882,7 @@ class ObjectCheck extends ChainCheck { ) { super(check, object.name); this.types = (object.fields ?? {}) as SealedFieldTypes; + this.chainField = sealChainFieldOf(object.lifecycle); const { engine } = check; const hot = engine.getDriverForObject(object.name); if (!hot) throw new Error(`no driver resolves for '${object.name}'`); @@ -1077,7 +1079,7 @@ class ObjectCheck extends ChainCheck { for (const { row, head } of ordered) await this.judgeCheckpoint(row, head, (body) => this.readLeaves(body, head, rows)); const sealedWindow = start + AUDIT_SEAL_WINDOW_MS <= this.watermark || this.sealedWindows.has(start); for (const [id, row] of rows) { - const chain = chainKeyOf(tenantOf(row)); + const chain = chainKeyOf(chainValueOf(row, this.chainField)); if (!this.check.inScope(chain) || this.held.has(id)) continue; if (sealedWindow || this.listedByFaulted.has(id)) this.unheld.set(id, { chain, windowStart: start }); } diff --git a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts new file mode 100644 index 00000000000..1eabdcb26ef --- /dev/null +++ b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts @@ -0,0 +1,86 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { ObjectSchema } from './object.zod'; + +// --------------------------------------------------------------------------- +// [ADR-0154 D10, note on `chainField`] `lifecycle.seal.chainField` names the +// column whose value is the organization chain a sealed row joins; absent, the +// sealer chains by `tenant_id`. Its reader is `@objectstack/plugin-audit`'s +// sealer and live check (`chainValueOf`). +// +// This file pins the authoring half: a named column the object has parses and +// is kept as authored — a declared field, or the tenant column the registry +// injects (ADR-0131 `organization_id`) — and a name the object does not have +// is refused, located at the key. Refusals are asserted by code and path. +// --------------------------------------------------------------------------- + +const AUDIT = { class: 'audit', retention: { maxAge: '90d' } } as const; + +const ledger = (seal: Record, extra: Record = {}) => ({ + name: 'ai_audit_probe', + fields: { + id: { type: 'text', label: 'ID' }, + created_at: { type: 'datetime', label: 'Created At' }, + action: { type: 'text', label: 'Action' }, + payload: { type: 'textarea', label: 'Payload' }, + }, + lifecycle: { ...AUDIT, seal }, + ...extra, +}); + +function refusals(input: unknown): Array<{ code: string; path: PropertyKey[] }> { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, 'the declaration must NOT parse clean').toBe(false); + if (parsed.success) return []; + return parsed.error.issues.map((i) => ({ code: i.code, path: i.path })); +} + +function sealOf(input: unknown) { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + return parsed.success ? parsed.data.lifecycle?.seal : undefined; +} + +describe('lifecycle.seal.chainField — a column the object has parses, as authored', () => { + it('accepts the tenant column the registry injects, organization_id, though the object never declares it', () => { + expect(sealOf(ledger({ valueFields: ['payload'], chainField: 'organization_id' }))).toEqual({ + valueFields: ['payload'], + chainField: 'organization_id', + }); + }); + + it('accepts a declared field', () => { + const input = ledger({ valueFields: [], chainField: 'tenant_id' }); + (input.fields as Record).tenant_id = { type: 'text', label: 'Organization' }; + expect(sealOf(input)).toEqual({ valueFields: [], chainField: 'tenant_id' }); + }); + + it('leaves a seal that names no chain column exactly as before: no key added, no new refusal', () => { + expect(sealOf(ledger({ valueFields: ['payload'] }))).toEqual({ valueFields: ['payload'] }); + }); +}); + +describe('lifecycle.seal.chainField — a name the object does not have is refused at authoring', () => { + it('refuses a name that is neither declared nor injected, at the key', () => { + expect(refusals(ledger({ valueFields: [], chainField: 'org' }))).toEqual([ + { code: 'custom', path: ['lifecycle', 'seal', 'chainField'] }, + ]); + }); + + it('refuses tenant_id when the object does not declare it, though it is the default', () => { + expect(refusals(ledger({ valueFields: [], chainField: 'tenant_id' }))).toEqual([ + { code: 'custom', path: ['lifecycle', 'seal', 'chainField'] }, + ]); + }); + + it.each([ + ['systemFields: false', { systemFields: false }], + ['systemFields.tenant: false', { systemFields: { tenant: false } }], + ['tenancy.enabled: false', { tenancy: { enabled: false } }], + ])('refuses organization_id where the registry injects no tenant column (%s)', (_label, extra) => { + expect(refusals(ledger({ valueFields: [], chainField: 'organization_id' }, extra))).toEqual([ + { code: 'custom', path: ['lifecycle', 'seal', 'chainField'] }, + ]); + }); +}); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 42c0b107951..4d12c10c01a 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -54,6 +54,11 @@ import { aiReadExposureRefusal } from './ai-read-exposure'; // roster object's declarative membership keys. No cycle: `security/rls.zod` // imports only zod, `shared/` and the resolver contract's constants. import { DefaultRowScopeSchema, MembershipKeysSchema } from '../security/rls.zod'; +// [ADR-0154 D10] The registry's injected-column plan, read by the +// `lifecycle.seal.chainField` refusal. A deliberate cycle: that module imports +// `isTenancyDisabled` from here, and each side calls the other only at parse +// time (see `refuseUnknownSealChainField`). +import { resolveInjectedSystemColumns } from './injected-system-columns'; export const ApiMethod = z.enum([ 'get', 'list', // Read 'create', 'update', 'delete', // Write @@ -1114,6 +1119,11 @@ export const LifecycleSchema = lazySchema(() => strictObject({ 'carries their values; every other declared column enters in clear. Each must name a declared field ' + 'other than `id` and `created_at`, which order the leaves.', ), + chainField: z.string().optional().describe( + 'The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row ' + + 'whose value is empty seals into the deployment chain. It must name a declared field or a column the ' + + 'platform injects, such as the tenant column `organization_id`.', + ), }).optional().describe( 'Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside ' + "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + @@ -3004,6 +3014,47 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct }); } +/** + * [ADR-0154 D10, note on `chainField`] A `lifecycle.seal.chainField` the + * author names is a field the object has: one it declares, or a column the + * registry injects into it ({@link resolveInjectedSystemColumns} — above all + * ADR-0131's tenant column `organization_id`). The sealer chains each row by + * that column's value, so a name the object does not have would put every + * row into the deployment chain, where no organization's check finds it. One + * located issue, at `['lifecycle', 'seal', 'chainField']`. + * + * Only a NAMED chain column is judged here. An object that names none chains + * by `tenant_id`, as before the key existed, and one without that column is + * reported by the sealer at `error`, as before. The injected plan is read with + * no deployment, as every author-time caller reads it; a deployment that + * declares the object platform-global withholds the tenant column, and the + * sealer reports that object the same way. + * + * `injected-system-columns` imports this module (for `isTenancyDisabled`), so + * the two form an import cycle. Each side calls the other only from inside a + * function — here, at parse time — never while a module evaluates, so both + * bindings are initialized by the time either is called. + */ +function refuseUnknownSealChainField(object: { lifecycle?: unknown; fields?: unknown }, ctx: z.RefinementCtx): void { + const lifecycle = object.lifecycle; + if (lifecycle === null || typeof lifecycle !== 'object') return; + const seal = (lifecycle as { seal?: { chainField?: unknown } }).seal; + if (!seal || typeof seal.chainField !== 'string') return; + const name = seal.chainField; + const declared = object.fields !== null && typeof object.fields === 'object' ? object.fields : {}; + if (Object.prototype.hasOwnProperty.call(declared, name)) return; + if (resolveInjectedSystemColumns(object).names.has(name)) return; + ctx.addIssue({ + code: 'custom', + path: ['lifecycle', 'seal', 'chainField'], + message: + `\`lifecycle.seal.chainField\` names \`${name}\`, which is not a field of this object. ` + + 'The sealer chains each row by that column\'s value, one chain per organization, so it must name a ' + + 'declared field or a column the platform injects (the tenant column is `organization_id`); declare ' + + 'the field, name another, or remove the key to chain by `tenant_id` (ADR-0154 D10).', + }); +} + /** * [#27069] A field group that carries `relatedList` stands for a body table, * not a section of fields, so no field may join it. One located issue per @@ -4625,6 +4676,9 @@ const ObjectSchemaBase = strictObject( // [ADR-0154 D10] Each `lifecycle.seal.valueFields` name is a declared field. // See the helper's docblock. refuseUndeclaredSealValueFields(object.lifecycle, object.fields, ctx); + // [ADR-0154 D10, note on `chainField`] A named chain column is a field the + // object has, injected ones included. See the helper's docblock. + refuseUnknownSealChainField(object, ctx); // [ruling A on the read half of #32442] `enable.aiReadable` only on a `sys_*` // object, never on the stored-metadata family — the same door: only the // object knows its name. See the helper's docblock. From 8195e780cd4e07974ffbe6d5fa0d68d4b21fac56 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:51:11 +0000 Subject: [PATCH 2/9] test(plugin-audit, cli): pin the chain column on a live engine, through os audit verify --org, and byte for byte for tenant_id ADR-0154 gains a note recording lifecycle.seal.chainField under D10 and how D5 reads with it; the reference docs regenerate; a changeset. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/34164-seal-chain-field.md | 20 ++ content/docs/references/data/object.mdx | 5 +- ...er-signed-checkpoints-amendments-verify.md | 18 ++ ...rify.chain-field-34164.integration.test.ts | 235 ++++++++++++++++ .../audit-seal-chain-field-34164.test.ts | 263 ++++++++++++++++++ 5 files changed, 539 insertions(+), 2 deletions(-) create mode 100644 .changeset/34164-seal-chain-field.md create mode 100644 packages/cli/src/commands/audit/verify.chain-field-34164.integration.test.ts create mode 100644 packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md new file mode 100644 index 00000000000..c283da8a848 --- /dev/null +++ b/.changeset/34164-seal-chain-field.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/plugin-audit': minor +--- + +feat(spec, plugin-audit): a sealed object names its chain column with `lifecycle.seal.chainField` + +Clause-②: yes (widening). A sealed object may name its chain column, the default stays `tenant_id`, and an object that seals today is byte-identical. +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-data/rules/lifecycle.md (its § Sealing teaches the chain as `tenant_id` only) + +An audit-class object that declares `lifecycle.seal` was sealed only when it had a `tenant_id` column, because the sealer read each row's organization from that column alone. An object whose organization lives in the tenant column the platform injects, `organization_id`, was reported at `error` every hour and never sealed. + +- **The key.** `lifecycle.seal.chainField` names the column whose value is the organization chain a sealed row joins, for example `seal: { valueFields: ['payload'], chainField: 'organization_id' }`. It is optional. An object that names none chains by `tenant_id`, as before. +- **Refused at authoring.** A named column the object does not have is refused at `lifecycle.seal.chainField`, with the reason. Declared fields count, and so do the columns the platform injects: `organization_id` counts unless the object opts out of the tenant column (`systemFields: false`, `systemFields.tenant: false`, `tenancy.enabled: false`). +- **One reader.** The sealer, `os audit verify`'s live check and the proof bundle it writes read a row's chain value through one function. `os audit verify --org X` reports the rows of organization `X` whichever column holds it. +- **Bytes unchanged.** The checkpoint's signed `tenant_id` member keeps its name and carries the chain column's value. For an object chained by `tenant_id`, the leaf input, the signed body and the root are byte for byte what they were. +- **Still reported, not refused.** An object that names no chain column and has no `tenant_id` still parses. The sealer still reports it at `error` and does not seal it, as it does for a definition that reached the registry without the parse and names a column it lacks. + +ADR-0154 gains a note recording the key under D10, and how D5's "its `tenant_id` names" reads with it. diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index c571b0fe6bf..eeaf4a14abc 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[] }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -121,6 +121,7 @@ const result = ApiMethod.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **valueFields** | `string[]` | ✅ | Columns that enter each sealed row as salted commitments instead of in clear, so a checkpoint never carries their values; every other declared column enters in clear. Each must name a declared field other than `id` and `created_at`, which order the leaves. | +| **chainField** | `string` | optional | The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row whose value is empty seals into the deployment chain. It must name a declared field or a column the platform injects, such as the tenant column `organization_id`. | --- @@ -366,7 +367,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[] }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md b/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md index 4b1ffc1c3ab..7ab1a633574 100644 --- a/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md +++ b/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md @@ -232,3 +232,21 @@ Ruling record 6885005594 (E + B). - **Unchanged.** The cluster lock `audit.sealer`, the unique `(chain, sequence)` index, and D7's order — the amendment is written before the row is rewritten ([D7](#d7--redaction-writes-a-signed-amendment-before-the-rewrite)) — all stay. The migrations' dry-run default is unchanged. - **The build pins in tests** that the lock is taken on the datasource holding the audit rows (the hot store, where it differs from the primary), and that the command's wait timeout outlasts a normal sealer pass. - **Not taken.** Composing `os serve`'s cluster driver into the one-shot boot of the migrate commands (the area's option A); a lock that excludes nothing (option D, ruled out by the red line); option C, because it would reopen D7. + +--- + +## Note (2026-11-16, #34164): the chain column, `lifecycle.seal.chainField` (D10), and how D5 reads + +**Status of this note**: a seat ruling by the owning seat (`domain:server#5`) on card [#34164](https://github.com/objectstack-ai/objectstack/issues/34164), recorded with the card's claim [`6906547049`](https://github.com/objectstack-ai/objectstack/issues/34164#issuecomment-6906547049), which names this note as the governed change it ships with, for this card only. `docs/adr/**` is a Tier H governed surface (Prime Directive #14): this note is accepted by the merge that lands it. **Change**: no decision above is reversed and no sentence above is edited. The note adds one optional key to D10's `lifecycle.seal` and records how D5's wording reads with it. Its consumer is cloud#4128, where Enterprise's `sys_ai_audit_log` opts in as D10 says it will. That object's organization lives in the tenant column the registry injects (ADR-0131 `organization_id`), and it has no `tenant_id`. + +### D10 — the chain column + +- **The key.** `lifecycle.seal = { valueFields, chainField? }`. `chainField` names the column whose value is the organization chain a sealed row joins ([D5](#d5--rows-about-no-organization-seal-into-a-deployment-chain)). It is optional, and when absent the chain column is `tenant_id`, as before the key existed. +- **It names a field the object has.** The field may be declared, or it may be a column the registry injects, the ADR-0131 tenant column `organization_id` included. A named column the object does not have is refused at authoring, with the reason, at `lifecycle.seal.chainField`. +- **One reader.** The sealer, the live check of [D9](#d9--os-audit-verify) and the proof bundle it writes read a row's chain value through one function (`chainValueOf` in `@objectstack/plugin-audit`). The key and its reader land together, as an ADR-0049 pair, declaring `Metadata-protocol: added`. +- **The chain column is a clear column of the leaf** ([D1](#d1--canonical-form-each-row-is-one-leaf-value-columns-enter-as-salted-commitments)), like every other declared column, so a row moved to another organization reads `modified`. + +### D5, read with it + +- D5's "a row whose `tenant_id` is NULL" and "the organization its `tenant_id` names" read as the sealed object's **chain column**: `tenant_id`, unless `chainField` names another. A row whose chain value is empty seals into the deployment chain. +- [D4](#d4--checkpoints-one-merkle-root-per-chain-per-window-chained-and-signed) is unchanged. It defines a checkpoint's chain as an organization id, not a column, so the signed body's member keeps its name `tenant_id` and carries the chain column's value. The leaf input, the signed body and the root of an object chained by `tenant_id` are byte for byte what they were before this note. diff --git a/packages/cli/src/commands/audit/verify.chain-field-34164.integration.test.ts b/packages/cli/src/commands/audit/verify.chain-field-34164.integration.test.ts new file mode 100644 index 00000000000..36755283d70 --- /dev/null +++ b/packages/cli/src/commands/audit/verify.chain-field-34164.integration.test.ts @@ -0,0 +1,235 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os audit verify --org` (ADR-0154 D9) over a sealed object whose + * organization lives in the tenant column the registry injects, ADR-0131's + * `organization_id`, named by `lifecycle.seal.chainField` (ADR-0154 D10, as + * its note on the key records). The object declares no `tenant_id`. + * + * A child process seals the ledger with plugin-audit's own sealer, composed + * with the crypto provider `os serve` would choose (the local data key the + * spawned runs share), as `verify.integration.test.ts` does. Then the real + * command, spawned from its source entry: + * + * 1. sealing wrote one checkpoint per organization; + * 2. `--org org_x` reports org_x's chain and its two rows, and no other + * chain, and exits 0; + * 3. a row of org_x edited through the database, below every hook, reads + * `modified` in org_x's chain under `--org org_x` (exit 1), while + * `--org org_y` still verifies (exit 0). + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import Database from 'better-sqlite3'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +/** The source entry, as `test/helpers/serve-process.ts` spawns it; `src/` cannot import that helper. */ +const CLI = resolve(HERE, '../../../bin/run-dev.js'); + +const HOOK_TIMEOUT_MS = 480_000; +const RUN_BUDGET_MS = 120_000; +const LEDGER = 'os34164_ai_ledger'; + +/** Env that would point a boot somewhere other than the fixture. */ +const OVERRIDING_ENV = ['OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME'] as const; + +/** This process's environment for a child, minus the families `test/helpers/serve-process.ts` strips. */ +function childEnv(overrides: Record): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key === 'TEST' || key === 'VITEST' || key.startsWith('VITEST_') || key === 'NODE_PATH') continue; + env[key] = value; + } + const unset: Record = {}; + for (const key of OVERRIDING_ENV) unset[key] = undefined; + return { + ...env, + ...unset, + // One fixed data key for the sealing child and every command run. + OS_SECRET_KEY: '34ab'.repeat(16), + OS_TELEMETRY_DB: '0', + NO_COLOR: '1', + ...overrides, + }; +} + +/** + * The sealing child: the project's stack, the platform objects and + * plugin-audit composed with the local data key's provider. It writes rows of + * a settled window, two of org_x and one of org_y, each naming its + * organization in `organization_id` only, and seals them with the plugin's own + * sealer. + */ +const SEAL_CHILD = ` +const rt = await import('@objectstack/runtime'); +const { PlatformObjectsPlugin } = await import('@objectstack/platform-objects/plugin'); +const { AuditPlugin } = await import('@objectstack/plugin-audit'); +const { LocalCryptoProvider } = await import('@objectstack/service-settings'); +const stack = await rt.createStandaloneStack({ + projectRoot: process.env.FIXTURE_PROJECT, + databaseUrl: 'file:' + process.env.FIXTURE_DB, + skipSeedData: true, +}); +const runtime = new rt.Runtime({ cluster: false }); +const kernel = runtime.getKernel(); +for (const plugin of stack.plugins) await kernel.use(plugin); +await kernel.use(new PlatformObjectsPlugin()); +const cryptoProvider = new LocalCryptoProvider({ mode: 'production', env: { ...process.env, OS_CRYPTO_AUTOKEY: undefined } }); +const audit = new AuditPlugin({ cryptoProvider }); +await kernel.use(audit); +await runtime.start(); +const ql = kernel.getService('objectql'); +await audit.sealer.stop(); // the passes run here, not on the loop's clock +const H = 3600000; +const settled = Math.floor(Date.now() / H) * H - 3 * H; +const iso = (ms) => new Date(ms).toISOString(); +const k = ql.getDriverForObject(process.env.LEDGER).knex; +await k(process.env.LEDGER).insert([ + { id: 'x1', created_at: iso(settled + 60000), organization_id: 'org_x', action: 'tool_call', payload: '{"tool":"a"}' }, + { id: 'x2', created_at: iso(settled + 120000), organization_id: 'org_x', action: 'tool_call', payload: '{"tool":"b"}' }, + { id: 'y1', created_at: iso(settled + 150000), organization_id: 'org_y', action: 'tool_call', payload: '{"tool":"c"}' }, +]); +const checkpoints = await audit.sealer.runPass(); +await kernel.shutdown(); +process.stderr.write('[fixture] sealed ' + JSON.stringify({ checkpoints }) + '\\n'); +process.exit(0); +`; + +interface Run { + code: number | null; + stdout: string; + stderr: string; +} + +const sealedObject = { + name: LEDGER, + label: 'AI audit ledger', + // Only the tenant column is injected: no audit family, no ownership anchors. + ownership: 'none', + systemFields: { audit: false }, + fields: { + id: { type: 'text' }, + created_at: { type: 'datetime' }, + action: { type: 'text' }, + payload: { type: 'textarea' }, + }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload'], chainField: 'organization_id' } }, +}; + +function writeArtifact(project: string): void { + mkdirSync(join(project, 'dist'), { recursive: true }); + writeFileSync( + join(project, 'dist', 'objectstack.json'), + JSON.stringify({ manifest: { id: 'com.example.os34164', name: 'Sealed AI ledger', version: '0.0.0', type: 'app' }, datasources: [], objects: [sealedObject] }), + ); +} + +function seal(project: string, db: string): { checkpoints: number } { + const r = spawnSync(process.execPath, ['--input-type=module', '-e', SEAL_CHILD], { + cwd: CLI_ROOT, + env: childEnv({ OS_ARTIFACT_PATH: join(project, 'dist', 'objectstack.json'), FIXTURE_PROJECT: project, FIXTURE_DB: db, LEDGER }), + encoding: 'utf8', + timeout: RUN_BUDGET_MS, + }); + const line = String(r.stderr).split('\n').find((l) => l.startsWith('[fixture] sealed ')); + if (r.status !== 0 || !line) throw new Error(`the sealing child did not run (status ${r.status})\n${String(r.stderr).slice(-3000)}`); + return JSON.parse(line.slice('[fixture] sealed '.length)); +} + +/** One `os audit verify --org --json --database-url file:` run, in `project`. */ +function verify(project: string, db: string, org: string): Promise { + return new Promise((resolveRun, rejectRun) => { + const args = [CLI, 'audit', 'verify', '--org', org, '--json', '--database-url', `file:${db}`]; + const child = spawn(process.execPath, args, { + cwd: project, + env: childEnv({ OS_ARTIFACT_PATH: join(project, 'dist', 'objectstack.json') }), + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (c) => { stdout += String(c); }); + child.stderr.on('data', (c) => { stderr += String(c); }); + const timer = setTimeout(() => { + child.kill('SIGKILL'); + rejectRun(new Error(`os audit verify did not finish within ${RUN_BUDGET_MS}ms`)); + }, RUN_BUDGET_MS); + child.on('error', (err) => { clearTimeout(timer); rejectRun(err); }); + child.on('close', (code) => { clearTimeout(timer); resolveRun({ code, stdout, stderr }); }); + }); +} + +interface Report { + ok: boolean; + scope: { orgs: string[] | null }; + chains: Array<{ object: string; chain: string; checkpoints: number; counts: Record }>; + rows: Array<{ object: string; chain: string; row: string; verdict: string }>; + faults: unknown[]; +} + +/** The `--json` document of a run; a run that printed none fails with its output. */ +function reportOf(run: Run): Report { + const at = run.stdout.indexOf('{'); + if (at < 0) throw new Error(`no JSON document (exit ${run.code})\nstdout: ${run.stdout.slice(-2000)}\nstderr: ${run.stderr.slice(-2000)}`); + const doc = JSON.parse(run.stdout.slice(at)) as { report?: Report }; + if (!doc.report) throw new Error(`no report in the JSON document (exit ${run.code})\n${run.stdout.slice(-2000)}`); + return doc.report; +} + +let dir: string; +let db: string; +let sealed: { checkpoints: number }; +const runs: Record<'clean' | 'tampered' | 'otherOrg', Run> = {} as never; + +beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'os-34164-')); + mkdirSync(join(dir, 'data'), { recursive: true }); + db = join(dir, 'data', 'main.db'); + writeArtifact(dir); + sealed = seal(dir, db); + runs.clean = await verify(dir, db, 'org_x'); + const hot = new Database(db); + try { + hot.prepare(`UPDATE ${LEDGER} SET payload = ? WHERE id = 'x1'`).run('{"tool":"z"}'); + } finally { + hot.close(); + } + runs.tampered = await verify(dir, db, 'org_x'); + runs.otherOrg = await verify(dir, db, 'org_y'); +}, HOOK_TIMEOUT_MS); + +afterAll(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); +}); + +describe('os audit verify --org on an object chained by organization_id (ADR-0154 D9, D10 note)', () => { + it('sealed one checkpoint per organization', () => { + expect(sealed.checkpoints).toBe(2); + }); + + it("reports the scoped organization's chain and its rows, and no other chain (exit 0)", () => { + const report = reportOf(runs.clean); + expect(report.scope.orgs).toEqual(['org_x']); + expect(report.faults).toEqual([]); + expect(report.chains.map((c) => [c.object, c.chain, c.checkpoints, c.counts.unmodified])).toEqual([[LEDGER, 'org:org_x', 1, 2]]); + expect(report.ok).toBe(true); + expect(runs.clean.code).toBe(0); + }); + + it("reads a row of the scoped organization edited in the database modified, in that organization's chain (exit 1)", () => { + const report = reportOf(runs.tampered); + expect(report.rows.map((r) => [r.chain, r.row, r.verdict])).toEqual([['org:org_x', 'x1', 'modified']]); + expect(runs.tampered.code).toBe(1); + }); + + it("leaves another organization's chain verifying (exit 0)", () => { + const report = reportOf(runs.otherOrg); + expect(report.chains.map((c) => [c.chain, c.counts.unmodified])).toEqual([['org:org_y', 1]]); + expect(runs.otherOrg.code).toBe(0); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts new file mode 100644 index 00000000000..d415f6f2eef --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts @@ -0,0 +1,263 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { createHash } from 'node:crypto'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { SysSecret } from '@objectstack/platform-objects/system'; +import type { CryptoContext, CryptoHandle, IAuditCheckpointSigner, IClusterService } from '@objectstack/spec/contracts'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { AuditPlugin } from '../audit-plugin.js'; +import { installDefaultOrganization } from '../default-organization.testkit.js'; +import { canonicalJsonBytes } from './jcs.js'; +import { leafInput } from './canonical.js'; +import { AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; +import { checkpointBodyFromRow, signedBodyBytes } from './signed-body.js'; +import { columnSaltsOf } from './seed.js'; +import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; +import { verifyAuditLedger } from './verifier.js'; + +/** + * ADR-0154 D10, as its note on `chainField` records: a sealed object names the + * column its rows are chained by with `lifecycle.seal.chainField`, read by the + * sealer, the live check and the proof bundle through one reader + * (`chainValueOf`), and the signed body's `tenant_id` member carries that + * column's value. + * + * 1. On a live engine over SQLite, an object whose organization lives in the + * tenant column the registry injects (ADR-0131 `organization_id`) seals + * one chain per organization, and the live check scoped to one + * organization (`os audit verify --org`) reports that chain's rows. + * 2. An object that names no chain column chains by `tenant_id`, and its + * leaf input, signed body and root are byte for byte what they were + * before the key existed: the digests below were taken from the sealer + * as it stood before this change, with the seed, the clock, the lock, the + * seed handle and the signer held fixed. + * 3. A definition that reached the registry without the parse and names a + * chain column it does not have is not sealed, and the sealer says so at + * `error`; the parse refuses it at authoring (spec). + */ + +// Leg 2 holds the seed fixed; every other caller of the module is unchanged. +vi.mock('./seed.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, generateCheckpointSeed: () => Buffer.alloc(actual.AUDIT_SEAL_SEED_BYTES, 7) }; +}); + +const H = 60 * 60 * 1000; +const SYS = { isSystem: true } as const; +type Row = Record; +const iso = (ms: number) => new Date(ms).toISOString(); +const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); + +interface Driver { + find(o: string, q: Row): Promise; + create(o: string, r: Row): Promise; + update(o: string, id: string, r: Row): Promise; +} + +// ── 1. one chain per organization, by the injected tenant column ────────────── + +const CHAIN_PROBE = 'chain_probe'; +const chainProbe = { + name: CHAIN_PROBE, + label: 'Chain Probe', + // Only the tenant column is injected: no audit family, no ownership anchors. + ownership: 'none', + systemFields: { audit: false }, + fields: { + id: { name: 'id', label: 'ID', type: 'text' }, + created_at: { name: 'created_at', label: 'Created At', type: 'datetime' }, + action: { name: 'action', label: 'Action', type: 'text' }, + payload: { name: 'payload', label: 'Payload', type: 'textarea' }, + }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload'], chainField: 'organization_id' } }, +}; + +describe('a sealed object chained by organization_id, on a live engine (ADR-0154 D5, D10 note)', () => { + const crypto = bindingCrypto(); + const plugin = new AuditPlugin({ cryptoProvider: crypto }); + let kernel: ObjectKernel; + let engine: ObjectQL; + const past = Math.floor(Date.now() / H) * H - 3 * H; // a window three hours ago: settled + const hot = () => engine.getDriverForObject(CHAIN_PROBE) as unknown as Driver; + const sealer = () => (plugin as unknown as { sealer: AuditSealer }).sealer; + const verify = (orgs: string[]) => verifyAuditLedger({ engine: engine as never, crypto, orgs }); + let written = 0; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(plugin); + await kernel.bootstrap(); + engine = kernel.getService('objectql'); + const sqlite = new SqliteWasmDriver({ filename: ':memory:' }); + await sqlite.connect(); + engine.registerDriver(sqlite, true); + engine.registry.registerObject(chainProbe as never, 'com.objectstack.audit.test.chain-probe'); + engine.registry.registerObject(SysSecret as never, 'com.objectstack.audit.test.chain-probe'); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + await hot().create(CHAIN_PROBE, { id: 'x1', created_at: iso(past + 60_000), action: 'update', organization_id: 'org_x', payload: '{"from":1}' }); + await hot().create(CHAIN_PROBE, { id: 'x2', created_at: iso(past + 120_000), action: 'delete', organization_id: 'org_x', payload: null }); + await hot().create(CHAIN_PROBE, { id: 'y1', created_at: iso(past + 180_000), action: 'update', organization_id: 'org_y', payload: 'kept' }); + + await sealer().stop(); // drive the passes here, not on the loop's clock + written = await sealer().runPass(); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('has the tenant column only because the registry injected it', () => { + const fields = (engine.registry.getObject(CHAIN_PROBE) as { fields: Record }).fields; + expect(Object.keys(chainProbe.fields)).not.toContain('organization_id'); + expect(fields.organization_id).toBeDefined(); + }); + + it('seals one chain per organization, each signed body carrying its organization in tenant_id', async () => { + expect(written).toBe(2); + const rows = (await engine.find('sys_audit_checkpoint', { where: { sealed_object: CHAIN_PROBE }, context: SYS })) as Row[]; + const bodies = rows.map((r) => ({ chain_key: r.chain_key, body: checkpointBodyFromRow(r) })); + expect(bodies.map((b) => [b.chain_key, b.body.tenant_id, b.body.row_ids]).sort()).toEqual([ + ['org:org_x', 'org_x', ['x1', 'x2']], + ['org:org_y', 'org_y', ['y1']], + ]); + // The chain column is a column of the leaf, in clear, like every other declared one. + expect(bodies[0].body.columns.clear).toContain('organization_id'); + }); + + it("reports the rows of the one organization it is scoped to, as `os audit verify --org` asks", async () => { + const report = await verify(['org_x']); + expect(report.faults).toEqual([]); + expect(report.scope.orgs).toEqual(['org_x']); + expect(report.chains.map((c) => [c.object, c.chain, c.checkpoints, c.counts.unmodified])).toEqual([[CHAIN_PROBE, 'org:org_x', 1, 2]]); + expect(report.ok).toBe(true); + }); + + it("judges a row of that organization edited below every hook modified, in its organization's chain only", async () => { + await hot().update(CHAIN_PROBE, 'x1', { payload: '{"from":2}' }); + const scoped = await verify(['org_x']); + expect(scoped.rows.map((r) => [r.chain, r.row, r.verdict])).toEqual([['org:org_x', 'x1', 'modified']]); + expect(scoped.ok).toBe(false); + const other = await verify(['org_y']); + expect(other.chains.map((c) => [c.chain, c.counts.unmodified])).toEqual([['org:org_y', 1]]); + expect(other.ok).toBe(true); + }); +}); + +// ── 2. a tenant_id object: byte for byte what it was ───────────────────────── + +const DAY0 = Date.UTC(2026, 10, 10); +const at = (h: number, m: number) => new Date(DAY0 + h * H + m * 60_000).toISOString(); + +const tenantLedger = (seal: Record) => ({ + name: 'ledger_probe', + fields: { id: { type: 'text' }, created_at: { type: 'datetime' }, action: { type: 'text' }, tenant_id: { type: 'lookup' }, payload: { type: 'textarea' } }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal }, +}); + +/** A signer double whose key id and signature depend on the signed bytes alone. */ +const fixedSigner: IAuditCheckpointSigner & { activeKeyId(): Promise } = { + activeKeyId: async () => 'key_fixed', + sign: async (bytes: Uint8Array) => ({ keyId: 'key_fixed', signature: sha256(bytes) }), + publicKey: async () => null, +} as never; + +/** A cluster double that grants one lease with a fixed fencing token. */ +const fixedCluster = { + lock: { acquire: async () => ({ key: AUDIT_SEALER_LOCK, fencingToken: 1n, renew: async () => {}, release: async () => {}, isHeld: () => true }) }, +} as unknown as IClusterService; + +/** Seal three rows of two chains, everything but the rows held fixed; each checkpoint's digests, by chain. */ +async function sealFixed(seal: Record) { + const object = tenantLedger(seal); + const store = memoryEngine([object] as never); + const base = bindingCrypto(); + let handles = 0; + const crypto = { + ...base, + encrypt: async (plain: string, ctx: CryptoContext): Promise => ({ ...(await base.encrypt(plain, ctx)), id: `seed_${handles++}` }), + }; + const sealer = new AuditSealer({ + engine: store.engine, + crypto, + signer: () => fixedSigner, + cluster: () => fixedCluster, + logger: recordingLogger(), + now: () => DAY0 + 12 * H + 30 * 60_000, + }); + const rows = [ + { id: 'r1', created_at: at(9, 10), action: 'update', tenant_id: 'org_a', payload: '{"v":1}' }, + { id: 'r2', created_at: at(9, 20), action: 'create', tenant_id: 'org_a', payload: 'two' }, + { id: 'r3', created_at: at(9, 30), action: 'config', tenant_id: null, payload: null }, + ]; + store.hot.table('ledger_probe').push(...rows.map((r) => ({ ...r }))); + expect(await sealer.runPass()).toBe(2); + const out: Record = {}; + for (const stored of store.hot.table('sys_audit_checkpoint')) { + const body = checkpointBodyFromRow(stored); + const saltOf = columnSaltsOf(Buffer.alloc(32, 7), body.sealed_object); + const first = rows.find((r) => r.id === body.row_ids[0])!; + out[String(stored.chain_key)] = { + leaf: sha256(canonicalJsonBytes(leafInput(first, body.columns, object.fields as never, saltOf))), + body: sha256(signedBodyBytes(body)), + root: body.root, + }; + } + return out; +} + +/** + * Taken from the sealer before `chainField` existed (commit 43dd5656e, this branch's base), by + * {@link sealFixed} with `{ valueFields: ['payload'] }`: the SHA-256 of the first row's canonical leaf + * input and of each signed body, and each root. + */ +const BEFORE = { + 'org:org_a': { + leaf: 'a1be98314b7f10696268e3873e1c5138b13d28b5a42800ad5249261faa529516', + body: 'caec188d55ea3cf44825d6b237a845d42af163797da6f88e33d8ec21ef3b7c78', + root: '8d1f06e3959b8a15702ece5bd9de8246a971b6180c8f617145713cca04594cd5', + }, + deployment: { + leaf: '4c6df364c7279185ba2c3fc7d01b47ee82ea14c556bfea4492fe522cdfd2e408', + body: '1652e2fb53a7238f930416c5f4ee3fe28e358ed7b872015c007faf62e489421c', + root: '4ed41adcb5461893747d0834c78f4a4d1bdb52131af84747ef43639ebeca27c6', + }, +}; + +describe('an object that names no chain column chains by tenant_id, byte for byte as before (ADR-0154 D1, D4)', () => { + it('writes the leaf input, signed body and root it wrote before the key existed', async () => { + expect(await sealFixed({ valueFields: ['payload'] })).toEqual(BEFORE); + }); + + it('writes the same bytes when it names tenant_id itself', async () => { + expect(await sealFixed({ valueFields: ['payload'], chainField: 'tenant_id' })).toEqual(BEFORE); + }); +}); + +// ── 3. a chain column the object does not have ────────────────────────────── + +describe('a chain column the object does not have, on a definition that skipped the parse', () => { + it('is not sealed, and the sealer names the column at error', async () => { + const store = memoryEngine([tenantLedger({ valueFields: ['payload'], chainField: 'org_ref' })] as never); + const logger = recordingLogger(); + const sealer = new AuditSealer({ + engine: store.engine, + crypto: bindingCrypto(), + signer: () => fixedSigner, + cluster: () => fixedCluster, + logger, + now: () => DAY0 + 12 * H + 30 * 60_000, + }); + store.hot.table('ledger_probe').push({ id: 'r1', created_at: at(9, 10), action: 'update', tenant_id: 'org_a', org_ref: 'org_a', payload: 'x' }); + expect(await sealer.runPass()).toBe(0); + expect(store.hot.table('sys_audit_checkpoint')).toEqual([]); + const errors = logger.lines.filter((l) => l.level === 'error').map((l) => l.message); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("'ledger_probe'"); + expect(errors[0]).toContain("'org_ref'"); + }); +}); From 5d76f1e9eee423ccd793caba222ea207a42a8f51 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:58:26 +0000 Subject: [PATCH 3/9] docs(data-modeling): teach lifecycle.seal.chainField and its tenant_id default; changeset states what authoring refuses The objects page now names the chain column a sealed object chains by, its tenant_id default, which names authoring refuses, and that an object with neither tenant_id nor chainField still parses and is reported by the sealer. The changeset says the same, and its Skills-docs line names both skills files the follow-up owes. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/34164-seal-chain-field.md | 4 ++-- content/docs/data-modeling/objects.mdx | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md index c283da8a848..9ca37a5ab0f 100644 --- a/.changeset/34164-seal-chain-field.md +++ b/.changeset/34164-seal-chain-field.md @@ -7,7 +7,7 @@ feat(spec, plugin-audit): a sealed object names its chain column with `lifecycle Clause-②: yes (widening). A sealed object may name its chain column, the default stays `tenant_id`, and an object that seals today is byte-identical. Metadata-protocol: added -Skills-docs: follow-up owed — skills/objectstack-data/rules/lifecycle.md (its § Sealing teaches the chain as `tenant_id` only) +Skills-docs: follow-up owed — skills/objectstack-data/rules/lifecycle.md, skills/objectstack-data/evals/objects-fields-relationships.json An audit-class object that declares `lifecycle.seal` was sealed only when it had a `tenant_id` column, because the sealer read each row's organization from that column alone. An object whose organization lives in the tenant column the platform injects, `organization_id`, was reported at `error` every hour and never sealed. @@ -15,6 +15,6 @@ An audit-class object that declares `lifecycle.seal` was sealed only when it had - **Refused at authoring.** A named column the object does not have is refused at `lifecycle.seal.chainField`, with the reason. Declared fields count, and so do the columns the platform injects: `organization_id` counts unless the object opts out of the tenant column (`systemFields: false`, `systemFields.tenant: false`, `tenancy.enabled: false`). - **One reader.** The sealer, `os audit verify`'s live check and the proof bundle it writes read a row's chain value through one function. `os audit verify --org X` reports the rows of organization `X` whichever column holds it. - **Bytes unchanged.** The checkpoint's signed `tenant_id` member keeps its name and carries the chain column's value. For an object chained by `tenant_id`, the leaf input, the signed body and the root are byte for byte what they were. -- **Still reported, not refused.** An object that names no chain column and has no `tenant_id` still parses. The sealer still reports it at `error` and does not seal it, as it does for a definition that reached the registry without the parse and names a column it lacks. +- **Still reported, not refused.** Authoring refuses only a `chainField` the object names and does not have. An object that names no chain column and has no `tenant_id` still parses: the sealer reports it at `error` and does not seal it, as before. It does the same for a definition that reached the registry without the parse and names a column it lacks, and for an object chained by `organization_id` that its deployment declares platform-global, which withholds that column. Refusing the default case at authoring is a narrowing, and #34352 carries it. ADR-0154 gains a note recording the key under D10, and how D5's "its `tenant_id` names" reads with it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 9ac2f014c3e..0ff877d5fb9 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -234,8 +234,23 @@ lifecycle: { commitments instead of in clear, so a checkpoint never carries their values. Each must be a declared field other than `id` and `created_at` (refused at parse time otherwise). Both must be in the object's registered fields, with - `tenant_id`, which keys each checkpoint chain: an object without one of the - three is not sealed. + the chain column below: an object without one of the three is not sealed. +- `chainField` names the chain column: the column whose value is the + organization a row's checkpoint chain belongs to. It is optional and + defaults to `tenant_id`. An object whose organization lives in the tenant + column the platform injects names that column instead: + `seal: { valueFields: ['payload'], chainField: 'organization_id' }`. A + named column must be a declared field or a column the platform injects; + `organization_id` counts unless the object opts out of the tenant column + (`systemFields: false`, `systemFields.tenant: false` or + `tenancy.enabled: false`). Any other name is refused at parse time, at + `lifecycle.seal.chainField`. An object that names no chain column and has + no `tenant_id` field still parses, but it is not sealed: the sealer reports + it at `error`. So is an object chained by `organization_id` that its + deployment declares platform-global, which withholds that column. A row whose chain column is empty is + sealed with the rows about no organization. `os audit verify --org ` + reads the same column, so it reports that organization's rows whichever + column holds it. - Every column must have a type with one canonical spelling. A column of type `password`, `secret`, `formula`, `summary`, `image`, `file`, `avatar`, `video` or `audio` has none, and an object that declares one is not sealed. From ebd7fbd78affdb93461d489821ff39ba2e50bead Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:59:02 +0000 Subject: [PATCH 4/9] docs(changeset): the Skills-docs line names its follow-up card Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/34164-seal-chain-field.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md index 9ca37a5ab0f..743cd17f5c6 100644 --- a/.changeset/34164-seal-chain-field.md +++ b/.changeset/34164-seal-chain-field.md @@ -7,7 +7,7 @@ feat(spec, plugin-audit): a sealed object names its chain column with `lifecycle Clause-②: yes (widening). A sealed object may name its chain column, the default stays `tenant_id`, and an object that seals today is byte-identical. Metadata-protocol: added -Skills-docs: follow-up owed — skills/objectstack-data/rules/lifecycle.md, skills/objectstack-data/evals/objects-fields-relationships.json +Skills-docs: follow-up #33773 An audit-class object that declares `lifecycle.seal` was sealed only when it had a `tenant_id` column, because the sealer read each row's organization from that column alone. An object whose organization lives in the tenant column the platform injects, `organization_id`, was reported at `error` every hour and never sealed. From 470a621dbefaf906931baabcb10c176640556d37 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:50:50 +0000 Subject: [PATCH 5/9] feat(spec): refuse a named lifecycle.seal.chainField that cannot name an organization chain A non-text column (number, boolean, date, datetime, JSON, multi-value), a leaf-order column (id, created_at; the predicate valueFields reads), or a valueFields member is refused at lifecycle.seal.chainField (ADR-0154 D10). Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- ...t-lifecycle-seal-chain-field-34164.test.ts | 109 +++++++++++++++ packages/spec/src/data/object.zod.ts | 131 +++++++++++++++--- 2 files changed, 224 insertions(+), 16 deletions(-) diff --git a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts index 1eabdcb26ef..8b2c609058d 100644 --- a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts +++ b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts @@ -84,3 +84,112 @@ describe('lifecycle.seal.chainField — a name the object does not have is refus ]); }); }); + +// --------------------------------------------------------------------------- +// A column the object HAS is still refused when it cannot name an +// organization chain: a column whose value is not one text on every store, a +// column that orders the leaves, and a `valueFields` member. Each refusal is +// asserted by code, path and the first sentence of its message. +// --------------------------------------------------------------------------- + +function issues(input: unknown): Array<{ code: string; path: PropertyKey[]; message: string }> { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, 'the declaration must NOT parse clean').toBe(false); + if (parsed.success) return []; + return parsed.error.issues.map((i) => ({ code: i.code, path: i.path, message: i.message })); +} + +const withField = (name: string, def: Record, seal: Record, extra: Record = {}) => { + const input = ledger(seal, extra); + (input.fields as Record)[name] = { label: name, ...def }; + return input; +}; + +describe('lifecycle.seal.chainField — a text column that holds the organization parses', () => { + it.each([ + ['text', { type: 'text' }], + ['lookup', { type: 'lookup', reference: 'sys_organization' }], + ['select', { type: 'select', options: [{ label: 'A', value: 'org_a' }] }], + ])('accepts a declared %s column', (_label, def) => { + expect(sealOf(withField('org_ref', def, { valueFields: ['payload'], chainField: 'org_ref' }))).toEqual({ + valueFields: ['payload'], + chainField: 'org_ref', + }); + }); +}); + +describe('lifecycle.seal.chainField — a column whose value is not one text on every store is refused', () => { + it.each([ + ['number', { type: 'number' }], + ['currency', { type: 'currency' }], + ['boolean', { type: 'boolean' }], + ['date', { type: 'date' }], + ['datetime', { type: 'datetime' }], + ['json', { type: 'json' }], + ['multiselect', { type: 'multiselect', options: [{ label: 'A', value: 'a' }] }], + ])('refuses a declared %s column, at the key', (type, def) => { + const [issue, ...rest] = issues(withField('org_ref', def, { valueFields: [], chainField: 'org_ref' })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch( + new RegExp(`^\`lifecycle\\.seal\\.chainField\` names \`org_ref\`, a \`${type}\` column, whose value is not one text on every store\\.`), + ); + }); + + it('refuses a lookup declared multiple: true, which stores a list', () => { + const [issue, ...rest] = issues( + withField('org_ref', { type: 'lookup', reference: 'sys_organization', multiple: true }, { valueFields: [], chainField: 'org_ref' }), + ); + expect(rest).toEqual([]); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch(/^`lifecycle\.seal\.chainField` names `org_ref`, a `lookup \(multi-value\)` column, whose value is not one text on every store\./); + }); + + it('judges an injected column by the definition the registry injects: updated_at is a datetime', () => { + const [issue, ...rest] = issues(ledger({ valueFields: [], chainField: 'updated_at' })); + expect(rest).toEqual([]); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch(/^`lifecycle\.seal\.chainField` names `updated_at`, a `datetime` column, whose value is not one text on every store\./); + }); +}); + +describe('lifecycle.seal.chainField — a column that orders the leaves is refused, by the predicate valueFields reads', () => { + it.each([ + ['id, declared', 'id'], + ['created_at, declared', 'created_at'], + ])('refuses %s, at the key', (_label, name) => { + const [issue, ...rest] = issues(ledger({ valueFields: [], chainField: name })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch(new RegExp(`^\`lifecycle\\.seal\\.chainField\` cannot name \`${name}\`: it orders each sealed leaf, and it names no organization\\.`)); + }); + + it('refuses id where only the driver provides it (no declared id)', () => { + const input = ledger({ valueFields: [], chainField: 'id' }); + delete (input.fields as Record).id; + const [issue, ...rest] = issues(input); + expect(rest).toEqual([]); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch(/^`lifecycle\.seal\.chainField` cannot name `id`: it orders each sealed leaf/); + }); +}); + +describe('lifecycle.seal.chainField — a valueFields member is refused', () => { + it('refuses a chain column the leaf also commits, at the key', () => { + const [issue, ...rest] = issues(withField('org_ref', { type: 'text' }, { valueFields: ['payload', 'org_ref'], chainField: 'org_ref' })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal', 'chainField']); + expect(issue.message).toMatch(/^`lifecycle\.seal\.chainField` names `org_ref`, which `lifecycle\.seal\.valueFields` also lists\./); + }); + + it('refuses the injected organization_id listed in valueFields too', () => { + // valueFields judges names against the AUTHORED map, so the undeclared name is refused there as well. + const found = issues(ledger({ valueFields: ['organization_id'], chainField: 'organization_id' })); + expect(found.filter((i) => i.path.join('.') === 'lifecycle.seal.chainField').map((i) => i.message.split('. ')[0])).toEqual([ + '`lifecycle.seal.chainField` names `organization_id`, which `lifecycle.seal.valueFields` also lists', + ]); + }); +}); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 4d12c10c01a..52a5495615d 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -59,6 +59,18 @@ import { DefaultRowScopeSchema, MembershipKeysSchema } from '../security/rls.zod // `isTenancyDisabled` from here, and each side calls the other only at parse // time (see `refuseUnknownSealChainField`). import { resolveInjectedSystemColumns } from './injected-system-columns'; +// [ADR-0154 D10] The injected columns' definitions, so a chain column the +// registry injects is judged by its type as a declared one is. The same cycle +// as above, one module further: nothing here is called while a module evaluates. +import { injectedSystemColumnDefs } from './injected-system-column-provenance'; +import { + BOOLEAN_VALUE_TYPES, + CALENDAR_DATE_TYPES, + INSTANT_TYPES, + NUMERIC_VALUE_TYPES, + STRUCTURED_JSON_TYPES, + isMultiValueField, +} from './field-value.zod'; export const ApiMethod = z.enum([ 'get', 'list', // Read 'create', 'update', 'delete', // Write @@ -1122,7 +1134,9 @@ export const LifecycleSchema = lazySchema(() => strictObject({ chainField: z.string().optional().describe( 'The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row ' + 'whose value is empty seals into the deployment chain. It must name a declared field or a column the ' + - 'platform injects, such as the tenant column `organization_id`.', + 'platform injects, such as the tenant column `organization_id`, whose value is one text on every store ' + + '(not a number, boolean, date, datetime, JSON or multi-value column); not `id` or `created_at`, which ' + + 'order the leaves; and not a `valueFields` member. Fixed once the object has checkpoints.', ), }).optional().describe( 'Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside ' + @@ -2979,6 +2993,43 @@ function refuseAttachedBlockConflicts(attachedOnRead: unknown, fields: unknown, } } +/** + * [ADR-0154 D1, D10] The columns that order each sealed leaf (`id`, then + * `created_at`) and so enter every leaf in clear. Neither may be committed + * (`valueFields`) nor name the chain (`chainField`): the one predicate both + * refusals read. + */ +function isSealLeafOrderColumn(name: unknown): boolean { + return name === 'id' || name === 'created_at'; +} + +/** + * [ADR-0154 D10, note on `chainField`] The value classes whose stored value is + * not one text on every store, from the field-value contract (ADR-0104 D1): + * numbers and booleans never are; a `date` or `datetime` is a `Date` on one + * driver and text on another; a JSON payload is parsed on one and text on + * another. A field declared multi-value stores a list + * ({@link isMultiValueField}). The sealer reads a row's chain as a non-empty + * string only (`chainValueOf`), so a chain column of one of these would put + * some or all rows into the deployment chain, with no report. Every other + * class reads as text — its canonical rule in the sealer is `text`. + */ +function isNonTextChainValueType(type: string): boolean { + // Read at parse time, never at module evaluation: `field-value.zod` sits in + // the `field.zod` evaluation cycle, so its sets are not read from here. + return NUMERIC_VALUE_TYPES.has(type) || BOOLEAN_VALUE_TYPES.has(type) || CALENDAR_DATE_TYPES.has(type) + || INSTANT_TYPES.has(type) || STRUCTURED_JSON_TYPES.has(type); +} + +/** The declared type of a non-text chain column, or `null` when its value reads as text. */ +function nonTextChainColumnType(def: unknown): string | null { + if (def === null || typeof def !== 'object') return null; + const { type, multiple } = def as { type?: unknown; multiple?: unknown }; + if (typeof type !== 'string') return null; + if (isNonTextChainValueType(type)) return type; + return isMultiValueField({ type, multiple: multiple === true }) ? `${type} (multi-value)` : null; +} + /** * [ADR-0154 D10] Each `lifecycle.seal.valueFields` name is a field this object * declares: a sealed checkpoint commits that column's value instead of carrying @@ -2998,7 +3049,7 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct if (!seal || !Array.isArray(seal.valueFields)) return; const declared = fields !== null && typeof fields === 'object' ? fields : {}; seal.valueFields.forEach((name, index) => { - if (name === 'id' || name === 'created_at') { + if (isSealLeafOrderColumn(name)) { ctx.addIssue({ code: 'custom', path: ['lifecycle', 'seal', 'valueFields', index], message: `lifecycle.seal.valueFields cannot name '${name}': it orders each sealed leaf, so it enters in clear (ADR-0154 D10).` }); return; } @@ -3020,8 +3071,17 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct * registry injects into it ({@link resolveInjectedSystemColumns} — above all * ADR-0131's tenant column `organization_id`). The sealer chains each row by * that column's value, so a name the object does not have would put every - * row into the deployment chain, where no organization's check finds it. One - * located issue, at `['lifecycle', 'seal', 'chainField']`. + * row into the deployment chain, where no organization's check finds it. + * + * A column the object has is refused too when it cannot name an organization + * chain: a leaf-order column ({@link isSealLeafOrderColumn}, the predicate + * `valueFields` reads); a `valueFields` member, whose value the leaf commits + * while the chain carries it in clear (D1, D9); and a column whose value is not + * one text on every store ({@link nonTextChainColumnType}), judged by the + * declared field or, for an injected column, by the definition the registry + * injects ({@link injectedSystemColumnDefs}). Each is one located issue at + * `['lifecycle', 'seal', 'chainField']`. Every refusal here needs the key, which + * did not exist before it, so none refuses a declaration that parsed before. * * Only a NAMED chain column is judged here. An object that names none chains * by `tenant_id`, as before the key existed, and one without that column is @@ -3041,18 +3101,57 @@ function refuseUnknownSealChainField(object: { lifecycle?: unknown; fields?: unk const seal = (lifecycle as { seal?: { chainField?: unknown } }).seal; if (!seal || typeof seal.chainField !== 'string') return; const name = seal.chainField; - const declared = object.fields !== null && typeof object.fields === 'object' ? object.fields : {}; - if (Object.prototype.hasOwnProperty.call(declared, name)) return; - if (resolveInjectedSystemColumns(object).names.has(name)) return; - ctx.addIssue({ - code: 'custom', - path: ['lifecycle', 'seal', 'chainField'], - message: - `\`lifecycle.seal.chainField\` names \`${name}\`, which is not a field of this object. ` - + 'The sealer chains each row by that column\'s value, one chain per organization, so it must name a ' - + 'declared field or a column the platform injects (the tenant column is `organization_id`); declare ' - + 'the field, name another, or remove the key to chain by `tenant_id` (ADR-0154 D10).', - }); + const path = ['lifecycle', 'seal', 'chainField']; + const declared = (object.fields !== null && typeof object.fields === 'object' ? object.fields : {}) as Record; + const isDeclared = Object.prototype.hasOwnProperty.call(declared, name); + if (!isDeclared && !resolveInjectedSystemColumns(object).names.has(name)) { + ctx.addIssue({ + code: 'custom', + path, + message: + `\`lifecycle.seal.chainField\` names \`${name}\`, which is not a field of this object. ` + + 'The sealer chains each row by that column\'s value, one chain per organization, so it must name a ' + + 'declared field or a column the platform injects (the tenant column is `organization_id`); declare ' + + 'the field, name another, or remove the key to chain by `tenant_id` (ADR-0154 D10).', + }); + return; + } + if (isSealLeafOrderColumn(name)) { + ctx.addIssue({ + code: 'custom', + path, + message: + `\`lifecycle.seal.chainField\` cannot name \`${name}\`: it orders each sealed leaf, and it names no ` + + 'organization. Name the column that holds the organization id of each row, such as `organization_id` ' + + '(ADR-0154 D10).', + }); + return; + } + const valueFields = (seal as { valueFields?: unknown }).valueFields; + if (Array.isArray(valueFields) && valueFields.includes(name)) { + ctx.addIssue({ + code: 'custom', + path, + message: + `\`lifecycle.seal.chainField\` names \`${name}\`, which \`lifecycle.seal.valueFields\` also lists. ` + + 'A value field enters each sealed leaf as a salted commitment so a checkpoint never carries it, but ' + + 'the chain value travels in clear in every checkpoint and proof bundle of its chain; remove it from ' + + '`valueFields`, or name another chain column (ADR-0154 D1, D9, D10).', + }); + } + const def = isDeclared ? declared[name] : injectedSystemColumnDefs(object)[name]; + const nonText = nonTextChainColumnType(def); + if (nonText !== null) { + ctx.addIssue({ + code: 'custom', + path, + message: + `\`lifecycle.seal.chainField\` names \`${name}\`, a \`${nonText}\` column, whose value is not one text on ` + + 'every store. The sealer reads a row\'s chain as a non-empty text only, so the rows would seal into ' + + 'the deployment chain with no report; name a text or lookup column that holds the organization id, ' + + 'such as `organization_id` (ADR-0154 D10).', + }); + } } /** From 901725e7b1402a7ed48965cf1f8b23bdb9fe96ba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:42:09 +0000 Subject: [PATCH 6/9] test(spec, plugin-audit), docs: pin the chainField refusals, measure a chain-column change, record both The multiselect fixture used an option value too short for a system identifier, so its first issue was that one; the fixtures now use a valid value. A type cross-check holds the spec refusal to the sealer's per-type canonical rules, and a memory-store test measures what changing chainField on a sealed object does. ADR-0154 note: status cites the 09:00Z hand-off and the default-case card; D5, D10 and the names table point to the note. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/34164-seal-chain-field.md | 2 + content/docs/data-modeling/objects.mdx | 14 ++- ...er-signed-checkpoints-amendments-verify.md | 9 +- .../audit-seal-chain-field-34164.test.ts | 92 ++++++++++++++++++- ...t-lifecycle-seal-chain-field-34164.test.ts | 2 +- packages/spec/src/data/object.zod.ts | 3 + 6 files changed, 115 insertions(+), 7 deletions(-) diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md index 743cd17f5c6..2d59b813ba3 100644 --- a/.changeset/34164-seal-chain-field.md +++ b/.changeset/34164-seal-chain-field.md @@ -13,6 +13,8 @@ An audit-class object that declares `lifecycle.seal` was sealed only when it had - **The key.** `lifecycle.seal.chainField` names the column whose value is the organization chain a sealed row joins, for example `seal: { valueFields: ['payload'], chainField: 'organization_id' }`. It is optional. An object that names none chains by `tenant_id`, as before. - **Refused at authoring.** A named column the object does not have is refused at `lifecycle.seal.chainField`, with the reason. Declared fields count, and so do the columns the platform injects: `organization_id` counts unless the object opts out of the tenant column (`systemFields: false`, `systemFields.tenant: false`, `tenancy.enabled: false`). +- **Also refused there: a column that cannot name an organization.** A column whose value is not one text on every store (a number, currency, percent, rating, slider, progress, summary, boolean, toggle, date, datetime, JSON-shaped or multi-value column, the injected `updated_at` included), which would put rows into the deployment chain with no report; `id` and `created_at`, which order the sealed rows; and a column `valueFields` also lists, whose value the chain would carry in clear. Name a text or lookup column that holds the organization id. +- **Fixed once sealed.** Changing `chainField` on an object that already has checkpoints seals the last sealed hour's rows again under the new column, which `os audit verify` reports as `listed_twice`, and `--org` then reads the earlier rows as `late`. Both fail the check. - **One reader.** The sealer, `os audit verify`'s live check and the proof bundle it writes read a row's chain value through one function. `os audit verify --org X` reports the rows of organization `X` whichever column holds it. - **Bytes unchanged.** The checkpoint's signed `tenant_id` member keeps its name and carries the chain column's value. For an object chained by `tenant_id`, the leaf input, the signed body and the root are byte for byte what they were. - **Still reported, not refused.** Authoring refuses only a `chainField` the object names and does not have. An object that names no chain column and has no `tenant_id` still parses: the sealer reports it at `error` and does not seal it, as before. It does the same for a definition that reached the registry without the parse and names a column it lacks, and for an object chained by `organization_id` that its deployment declares platform-global, which withholds that column. Refusing the default case at authoring is a narrowing, and #34352 carries it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 0ff877d5fb9..16322cf57f7 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -244,13 +244,23 @@ lifecycle: { `organization_id` counts unless the object opts out of the tenant column (`systemFields: false`, `systemFields.tenant: false` or `tenancy.enabled: false`). Any other name is refused at parse time, at - `lifecycle.seal.chainField`. An object that names no chain column and has + `lifecycle.seal.chainField`, and so is a column that cannot name an + organization: one whose value is not one text on every store (a number, + currency, percent, rating, slider, progress, summary, boolean, toggle, date, + datetime, JSON-shaped or multi-value column, the injected `updated_at` + included), `id` or `created_at` (they order the rows), and a column + `valueFields` also lists (the chain value travels in clear in every + checkpoint). Name a text or lookup column holding the organization id. An object that names no chain column and has no `tenant_id` field still parses, but it is not sealed: the sealer reports it at `error`. So is an object chained by `organization_id` that its deployment declares platform-global, which withholds that column. A row whose chain column is empty is sealed with the rows about no organization. `os audit verify --org ` reads the same column, so it reports that organization's rows whichever - column holds it. + column holds it. The chain column is fixed once the object has + checkpoints: after a change, the last sealed hour's rows are sealed again + under the new column, `os audit verify` reports them `listed_twice`, and + verifying one organization with `--org` reads the rows sealed before the + change as `late` and unsealed. Both fail the check. - Every column must have a type with one canonical spelling. A column of type `password`, `secret`, `formula`, `summary`, `image`, `file`, `avatar`, `video` or `audio` has none, and an object that declares one is not sealed. diff --git a/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md b/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md index 7ab1a633574..c852132d9bb 100644 --- a/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md +++ b/docs/adr/0154-audit-ledger-tamper-evidence-sealer-signed-checkpoints-amendments-verify.md @@ -91,7 +91,7 @@ Terms. A **sealed object** is an object that declares `lifecycle.seal` ([D10](#d ### D5 — Rows about no organization seal into a deployment chain -- **A row whose `tenant_id` is NULL** — a deployment-level action under ADR-0131 D7 (`config_change` on the settings global rung, `platform_admin_standing_change`, plugin-auth's run-level `import`) — seals into the sealed object's **deployment chain**, whose checkpoints carry a NULL organization id. Every other row seals into the chain of the organization its `tenant_id` names. +- **A row whose `tenant_id` is NULL** — a deployment-level action under ADR-0131 D7 (`config_change` on the settings global rung, `platform_admin_standing_change`, plugin-auth's run-level `import`) — seals into the sealed object's **deployment chain**, whose checkpoints carry a NULL organization id. Every other row seals into the chain of the organization its `tenant_id` names. *(Noted 2026-11-16: `tenant_id` here reads as the sealed object's chain column, which `lifecycle.seal.chainField` may name; see [the note](#note-2026-11-16-34164-the-chain-column-lifecycleseal-chainfield-d10-and-how-d5-reads).)* - **Why not leave them out.** The rows about no organization are the platform-administrator acts: who held standing, which global setting changed. A proof that skipped them would skip the rows a security review asks about first. - **Why not one deployment-wide chain for everything.** A per-organization chain is what lets an organization be verified, exported and expired on its own, and what stage 2 hands to one customer without the others' roots. An organization that is deleted keeps its ledger rows (the delete leaves every `append-only` object's rows naming it) and so keeps its chain. @@ -142,6 +142,7 @@ Terms. A **sealed object** is an object that declares `lifecycle.seal` ([D10](#d - **Only `lifecycle.class: 'audit'` may declare it**, and every name in `valueFields` must be a declared field; anything else is refused at authoring. The sealer's expiry rides on the same block's `archive.keep`, and the class that needs a proof is the one that block already calls the compliance ledger. - **Three lifecycle policies are refused beside it**, because [D8](#d8--expiry-removes-a-sealed-prefix-of-the-chain-and-writes-a-signed-amendment) cannot align them to whole windows and an honest expiry would read as `missing`: `retention.onlyWhen` (it deletes part of a window), a `ttl` whose `field` is not `created_at` (its cutoff is not a `created_at` window), and `storage: { strategy: 'rotation' }` (it drops whole shards, not windows). Each is refused at authoring with the reason, in the same change that adds the key. - **`sys_audit_log` opts in by default** with `valueFields: ['old_value', 'new_value', 'metadata']`. Enterprise's `sys_ai_audit_log` opts in from cloud. +- *(Noted 2026-11-16: the block gains the optional `chainField`, the column a row's chain is read from; see [the note](#note-2026-11-16-34164-the-chain-column-lifecycleseal-chainfield-d10-and-how-d5-reads).)* - **This record names the key; it does not add it.** The build card adds it to `packages/spec` together with its reader, as an ADR-0049 pair, declaring `Metadata-protocol: added`. Until then nothing is sealed. - **Not taken:** `enable.tamperEvidence` (a flag cannot say which columns are value-bearing, and `enable` gates UI and API capabilities, not persistence); a new top-level `ledger` block (a top-level key for one feature of one class). @@ -158,7 +159,7 @@ Terms. A **sealed object** is an object that declares `lifecycle.seal` ([D10](#d | What | Name | |:--|:--| -| Opt-in key | `lifecycle.seal` = `{ valueFields: string[] }`, `lifecycle.class: 'audit'` only | +| Opt-in key | `lifecycle.seal` = `{ valueFields: string[] }`, `lifecycle.class: 'audit'` only *(noted 2026-11-16: `{ valueFields, chainField? }`; see [the note](#note-2026-11-16-34164-the-chain-column-lifecycleseal-chainfield-d10-and-how-d5-reads))* | | Checkpoint object | `sys_audit_checkpoint` | | Amendment object | `sys_audit_amendment` | | Signing public-key object | `sys_audit_signing_key` | @@ -237,14 +238,16 @@ Ruling record 6885005594 (E + B). ## Note (2026-11-16, #34164): the chain column, `lifecycle.seal.chainField` (D10), and how D5 reads -**Status of this note**: a seat ruling by the owning seat (`domain:server#5`) on card [#34164](https://github.com/objectstack-ai/objectstack/issues/34164), recorded with the card's claim [`6906547049`](https://github.com/objectstack-ai/objectstack/issues/34164#issuecomment-6906547049), which names this note as the governed change it ships with, for this card only. `docs/adr/**` is a Tier H governed surface (Prime Directive #14): this note is accepted by the merge that lands it. **Change**: no decision above is reversed and no sentence above is edited. The note adds one optional key to D10's `lifecycle.seal` and records how D5's wording reads with it. Its consumer is cloud#4128, where Enterprise's `sys_ai_audit_log` opts in as D10 says it will. That object's organization lives in the tenant column the registry injects (ADR-0131 `organization_id`), and it has no `tenant_id`. +**Status of this note**: a seat ruling by the owning seat (`domain:server#5`) on card [#34164](https://github.com/objectstack-ai/objectstack/issues/34164), as narrowed at 09:00Z and recorded in hand-off [`6912069272`](https://github.com/objectstack-ai/objectstack/pull/34351#issuecomment-6912069272) on PR #34351: the key is a widening, a named chain column must be a field the object has, and refusing at authoring an object that names none and has no `tenant_id` is card [#34352](https://github.com/objectstack-ai/objectstack/issues/34352), not this note. Such an object still parses, and the sealer reports it at `error` and does not seal it. The ruling names this note as the governed change it ships with, for this card only. `docs/adr/**` is a Tier H governed surface (Prime Directive #14): this note is accepted by the merge that lands it. **Change**: no decision above is reversed and no sentence above is edited; D5, D10 and the "Names this record fixes" table each gain a dated pointer here. The note adds one optional key to D10's `lifecycle.seal` and records how D5's wording reads with it. Its consumer is cloud#4128, where Enterprise's `sys_ai_audit_log` opts in as D10 says it will. That object's organization lives in the tenant column the registry injects (ADR-0131 `organization_id`), and it has no `tenant_id`. ### D10 — the chain column - **The key.** `lifecycle.seal = { valueFields, chainField? }`. `chainField` names the column whose value is the organization chain a sealed row joins ([D5](#d5--rows-about-no-organization-seal-into-a-deployment-chain)). It is optional, and when absent the chain column is `tenant_id`, as before the key existed. - **It names a field the object has.** The field may be declared, or it may be a column the registry injects, the ADR-0131 tenant column `organization_id` included. A named column the object does not have is refused at authoring, with the reason, at `lifecycle.seal.chainField`. +- **It names a column that can carry an organization.** Also refused there, each with its reason: a column whose value is not one text on every store (a numeric, boolean, `date`, `datetime`, JSON-shaped or multi-value column, judged by the declared field or by the definition the registry injects, so the injected `updated_at` is refused), since `chainValueOf` reads a chain only from a non-empty string and such a column would seal rows into the deployment chain with no report; `id` and `created_at`, which order the leaves (the same predicate `valueFields` reads); and a `valueFields` member, whose value [D1](#d1--canonical-form-each-row-is-one-leaf-value-columns-enter-as-salted-commitments) commits while the chain carries it in clear in every checkpoint and proof bundle ([D9](#d9--os-audit-verify)). The default `tenant_id`, when `chainField` is absent, is not judged at authoring; that half is #34352. - **One reader.** The sealer, the live check of [D9](#d9--os-audit-verify) and the proof bundle it writes read a row's chain value through one function (`chainValueOf` in `@objectstack/plugin-audit`). The key and its reader land together, as an ADR-0049 pair, declaring `Metadata-protocol: added`. - **The chain column is a clear column of the leaf** ([D1](#d1--canonical-form-each-row-is-one-leaf-value-columns-enter-as-salted-commitments)), like every other declared column, so a row moved to another organization reads `modified`. +- **The chain column is fixed once the object has checkpoints.** Changing it does not move a sealed row: each checkpoint keeps the chain it was written in. Measured with the in-memory store (`audit-seal-chain-field-34164.test.ts`): the next pass starts each new chain at the object's floor, the last sealed window, so that window's rows are sealed again under the new chain, and `os audit verify` reports the second checkpoint `listed_twice`; scoped with `--org` to a new chain, the rows sealed before the change read `late` and unsealed. Both fail closed. ### D5, read with it diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts index d415f6f2eef..173e2a44995 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts @@ -9,11 +9,13 @@ import type { CryptoContext, CryptoHandle, IAuditCheckpointSigner, IClusterServi import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { AuditPlugin } from '../audit-plugin.js'; import { installDefaultOrganization } from '../default-organization.testkit.js'; +import { FieldType, ObjectSchema } from '@objectstack/spec/data'; import { canonicalJsonBytes } from './jcs.js'; -import { leafInput } from './canonical.js'; +import { AUDIT_SEAL_TYPE_RULES, leafInput } from './canonical.js'; import { AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { checkpointBodyFromRow, signedBodyBytes } from './signed-body.js'; import { columnSaltsOf } from './seed.js'; +import { LocalCheckpointSigner } from './signer.js'; import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; import { verifyAuditLedger } from './verifier.js'; @@ -261,3 +263,91 @@ describe('a chain column the object does not have, on a definition that skipped expect(errors[0]).toContain("'org_ref'"); }); }); + +// ── 4. which column types may name the chain: the sealer's own rules decide ── + +/** + * The authoring refusal of a non-text chain column (spec, `nonTextChainColumnType`) + * is derived from the field-value classes; this holds it to the sealer's own + * per-type rules (`AUDIT_SEAL_TYPE_RULES`): a type whose canonical rule is `text` + * is read as text on every store, so `chainValueOf` can read a chain from it, and + * every other rule (`number`, `boolean`, `date`, `datetime`, `json`) is a type a + * store hands back as something else. A type with no rule (`null`) is not sealed + * at all, so its object never reaches `chainValueOf` and the authoring answer is + * not judged here. + */ +describe('a chain column type is refused at authoring exactly where the sealer reads its value as other than text', () => { + const refusedAtChainField = (def: Record): boolean => { + const parsed = ObjectSchema.safeParse({ + name: 'chain_type_probe', + fields: { action: { type: 'text', label: 'Action' }, org_ref: { label: 'Org', ...def } }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: [], chainField: 'org_ref' } }, + }); + return !parsed.success && parsed.error.issues.some( + (i) => i.path.join('.') === 'lifecycle.seal.chainField' && /whose value is not one text on every store/.test(i.message), + ); + }; + const minimalDef = (type: string): Record => { + if (type === 'lookup' || type === 'master_detail' || type === 'tree') return { type, reference: 'sys_organization' }; + if (type === 'select' || type === 'radio' || type === 'multiselect' || type === 'checkboxes') return { type, options: [{ label: 'A', value: 'opt_a' }] }; + if (type === 'formula') return { type, expression: 'action' }; + if (type === 'summary') return { type }; + return { type }; + }; + + it.each(FieldType.options.filter((t) => AUDIT_SEAL_TYPE_RULES[t] !== null))('%s', (type) => { + expect(refusedAtChainField(minimalDef(type))).toBe(AUDIT_SEAL_TYPE_RULES[type] !== 'text'); + }); + + it.each(['select', 'radio', 'lookup', 'user'] as const)('%s declared multiple: true reads as json, and is refused', (type) => { + expect(AUDIT_SEAL_TYPE_RULES[type]).toBe('text'); + expect(refusedAtChainField({ ...minimalDef(type), multiple: true })).toBe(true); + }); +}); + +// ── 5. changing the chain column of an object that already has checkpoints ── + +describe('changing chainField on an object that already has checkpoints (ADR-0154 D10 note)', () => { + it('re-seals the last sealed window under the new chain, and the check fails closed (listed_twice; late under --org)', async () => { + const object = { + name: 'ledger_probe', + fields: { id: { type: 'text' }, created_at: { type: 'datetime' }, action: { type: 'text' }, tenant_id: { type: 'lookup' }, org_ref: { type: 'text' }, payload: { type: 'textarea' } }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload'] } as Record }, + }; + const store = memoryEngine([object, { name: 'sys_audit_amendment', fields: {} }] as never); + const crypto = bindingCrypto(); + const signer = new LocalCheckpointSigner({ engine: store.engine, crypto }); + const clock = { now: DAY0 + 12 * H + 30 * 60_000 }; + const run = () => new AuditSealer({ engine: store.engine, crypto, signer: () => signer, logger: recordingLogger(), now: () => clock.now }).runPass(); + const ledger = store.hot.table('ledger_probe'); + ledger.push( + { id: 'r1', created_at: at(8, 10), action: 'update', tenant_id: 'org_a', org_ref: 'org_b', payload: 'one' }, + { id: 'r2', created_at: at(10, 5), action: 'update', tenant_id: 'org_a', org_ref: 'org_b', payload: 'two' }, + ); + await run(); + const sealed = () => store.hot.table('sys_audit_checkpoint').map((r) => { + const body = checkpointBodyFromRow(r); + return [r.chain_key, body.kind, body.row_ids.join(',')].join(' '); + }); + const before = sealed(); + + object.lifecycle.seal = { valueFields: ['payload'], chainField: 'org_ref' }; + ledger.push({ id: 'r3', created_at: at(13, 10), action: 'update', tenant_id: 'org_a', org_ref: 'org_b', payload: 'three' }); + clock.now = DAY0 + 14 * H + 30 * 60_000; + await run(); + const after = sealed(); + + const report = await verifyAuditLedger({ engine: store.engine, crypto, now: () => clock.now }); + const scoped = await verifyAuditLedger({ engine: store.engine, crypto, now: () => clock.now, orgs: ['org_b'] }); + // The rows sealed by tenant_id stay in org_a's chain. The new chain starts from the object's + // floor, the last sealed window, so that window's r2 is sealed again under org_b. + expect(before).toEqual(['org:org_a window r1', 'org:org_a window r2']); + expect(after).toEqual([...before, 'org:org_b window r2', 'org:org_b window r3']); + // The whole ledger: r2 listed by two checkpoints is a fault, so the check fails closed. + expect(report.faults.map((f) => `${f.chain}#${f.sequence ?? '-'}:${f.kind}`)).toEqual(['org:org_b#0:listed_twice']); + expect(report.ok).toBe(false); + // Scoped to the new chain: r1, held only by org_a's chain, reads late and unsealed; it fails closed too. + expect(scoped.rows.map((r) => [r.chain, r.row, r.verdict, r.sealed])).toEqual([['org:org_b', 'r1', 'late', false]]); + expect(scoped.ok).toBe(false); + }); +}); diff --git a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts index 8b2c609058d..dc17ac4b26d 100644 --- a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts +++ b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts @@ -126,7 +126,7 @@ describe('lifecycle.seal.chainField — a column whose value is not one text on ['date', { type: 'date' }], ['datetime', { type: 'datetime' }], ['json', { type: 'json' }], - ['multiselect', { type: 'multiselect', options: [{ label: 'A', value: 'a' }] }], + ['multiselect', { type: 'multiselect', options: [{ label: 'A', value: 'opt_a' }] }], ])('refuses a declared %s column, at the key', (type, def) => { const [issue, ...rest] = issues(withField('org_ref', def, { valueFields: [], chainField: 'org_ref' })); expect(rest).toEqual([]); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 52a5495615d..702e5191a7c 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -3027,6 +3027,9 @@ function nonTextChainColumnType(def: unknown): string | null { const { type, multiple } = def as { type?: unknown; multiple?: unknown }; if (typeof type !== 'string') return null; if (isNonTextChainValueType(type)) return type; + // An inherently multi-value type (`multiselect`, `checkboxes`, `tags`) is named as it is; a + // multi-capable one is named for the `multiple: true` that makes it store a list. + if (isMultiValueField({ type, multiple: false })) return type; return isMultiValueField({ type, multiple: multiple === true }) ? `${type} (multi-value)` : null; } From d1d44a36b470ff2e8751584477c66487226f28f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:58:46 +0000 Subject: [PATCH 7/9] docs(references): regenerate the object reference for the chainField describe text Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- content/docs/references/data/object.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index eeaf4a14abc..c49e916ab0a 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -121,7 +121,7 @@ const result = ApiMethod.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **valueFields** | `string[]` | ✅ | Columns that enter each sealed row as salted commitments instead of in clear, so a checkpoint never carries their values; every other declared column enters in clear. Each must name a declared field other than `id` and `created_at`, which order the leaves. | -| **chainField** | `string` | optional | The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row whose value is empty seals into the deployment chain. It must name a declared field or a column the platform injects, such as the tenant column `organization_id`. | +| **chainField** | `string` | optional | The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row whose value is empty seals into the deployment chain. It must name a declared field or a column the platform injects, such as the tenant column `organization_id`, whose value is one text on every store (not a number, boolean, date, datetime, JSON or multi-value column); not `id` or `created_at`, which order the leaves; and not a `valueFields` member. Fixed once the object has checkpoints. | --- From 55812f71a89c8ed0d1055bf35e3b5a15551c9326 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:02:23 +0000 Subject: [PATCH 8/9] =?UTF-8?q?docs(changeset):=20the=20Clause-=E2=91=A1?= =?UTF-8?q?=20line=20reads=20as=20the=20takeover=20claim=20states=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/34164-seal-chain-field.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md index 2d59b813ba3..3d114ea5e9e 100644 --- a/.changeset/34164-seal-chain-field.md +++ b/.changeset/34164-seal-chain-field.md @@ -5,7 +5,7 @@ feat(spec, plugin-audit): a sealed object names its chain column with `lifecycle.seal.chainField` -Clause-②: yes (widening). A sealed object may name its chain column, the default stays `tenant_id`, and an object that seals today is byte-identical. +Clause-②: yes (widening). A sealed object may name its chain column with `lifecycle.seal.chainField`; the default stays `tenant_id`, and an object that seals today is byte-identical. Metadata-protocol: added Skills-docs: follow-up #33773 From a93c0509bbc92047d9a21b92287fa4fc2c4ce130 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:32:16 +0000 Subject: [PATCH 9/9] docs(changeset): the last bullet says only a named chainField is judged Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/34164-seal-chain-field.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34164-seal-chain-field.md b/.changeset/34164-seal-chain-field.md index 3d114ea5e9e..e09960b935b 100644 --- a/.changeset/34164-seal-chain-field.md +++ b/.changeset/34164-seal-chain-field.md @@ -17,6 +17,6 @@ An audit-class object that declares `lifecycle.seal` was sealed only when it had - **Fixed once sealed.** Changing `chainField` on an object that already has checkpoints seals the last sealed hour's rows again under the new column, which `os audit verify` reports as `listed_twice`, and `--org` then reads the earlier rows as `late`. Both fail the check. - **One reader.** The sealer, `os audit verify`'s live check and the proof bundle it writes read a row's chain value through one function. `os audit verify --org X` reports the rows of organization `X` whichever column holds it. - **Bytes unchanged.** The checkpoint's signed `tenant_id` member keeps its name and carries the chain column's value. For an object chained by `tenant_id`, the leaf input, the signed body and the root are byte for byte what they were. -- **Still reported, not refused.** Authoring refuses only a `chainField` the object names and does not have. An object that names no chain column and has no `tenant_id` still parses: the sealer reports it at `error` and does not seal it, as before. It does the same for a definition that reached the registry without the parse and names a column it lacks, and for an object chained by `organization_id` that its deployment declares platform-global, which withholds that column. Refusing the default case at authoring is a narrowing, and #34352 carries it. +- **Still reported, not refused.** Authoring judges only a named `chainField`; the default `tenant_id` is not judged. An object that names no chain column and has no `tenant_id` still parses: the sealer reports it at `error` and does not seal it, as before. It does the same for a definition that reached the registry without the parse and names a column it lacks, and for an object chained by `organization_id` that its deployment declares platform-global, which withholds that column. Refusing the default case at authoring is a narrowing, and #34352 carries it. ADR-0154 gains a note recording the key under D10, and how D5's "its `tenant_id` names" reads with it.