From fd2e0e321dd948c9122766d51b5f4fde70b5802a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:21:44 +0000 Subject: [PATCH 1/5] test(objectql): pin the roll-up recompute audit stamp on the master Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 Co-authored-by: Claude --- ...gine-summary-recompute-audit-actor.test.ts | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 packages/objectql/src/engine-summary-recompute-audit-actor.test.ts diff --git a/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts b/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts new file mode 100644 index 00000000000..fee1a5a56fb --- /dev/null +++ b/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// ── A roll-up recompute is a SYSTEM write on the master's audit trail ── +// +// A child write recomputes the master's `summary` columns through +// `recomputeSummaries`, which issues an ordinary `update` of the master under a +// `sudo()`-shaped context (`{ ...caller, isSystem: true }`). The caller's +// `userId` rides along on purpose — hooks and record-triggered flows on the +// master still know who triggered the write — but the audit stamp read that +// same `userId` and wrote it into the master's `updated_by`. A finance user who +// inserted an invoice under a contract therefore showed up as the contract's +// last editor, though they edit neither record and hold no edit on it. +// +// Ruling (recorded on the card, comment 6902001862): 「确定汇总字段自动重算时 +// 主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. Under ADR-0118 D1 +// a system actor is `null` in a user lookup column (no system account, no +// sentinel), so the recompute stamps `updated_by = null` and refreshes +// `updated_at`; the UI renders the null as 系统. +// +// Every child write that recomputes goes through the same door, so each one is +// a row here: insert, update, delete, and a re-parent (which recomputes BOTH the +// old and the new master). The CONTROL is the other half of the contract: a +// direct edit of the master by the same user still stamps that user — the fix +// is scoped to the recompute's own write, not to `isSystem` writes in general. +// +// The harness boots the real `ObjectQLPlugin`, because the stamp under test is +// its `sys_stamp_audit_update` hook. What reaches the fake driver's store IS the +// stored row, so the store is the verdict. + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from './plugin.js'; +import { ObjectQL } from './engine.js'; + +const USER_A = 'u_owner_a'; +const USER_B = 'u_child_writer_b'; +/** An `updated_at` far in the past, so "the recompute refreshed it" is never a same-millisecond tie. */ +const STALE_AT = '2000-01-01T00:00:00.000Z'; + +function makeDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]: [string, any]) => { + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + if ('$eq' in v) return row?.[k] === v.$eq; + if ('$in' in v) return Array.isArray(v.$in) && v.$in.includes(row?.[k]); + throw new Error(`fake driver: unsupported operator in ${JSON.stringify(v)}`); + } + return row?.[k] === v; + }); + }; + let n = 0; + const driver: any = { + name: 'rollup-audit', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async syncSchema() {}, + async find(object: string, ast: any) { + return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).map((r) => ({ ...r })); + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(object: string, data: Record) { + n += 1; + const id = (data.id as string) ?? `r_${n}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return { ...row }; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return { ...row }; + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { + return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).length; + }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +describe('roll-up recompute stamps the master as a system write (updated_by = null)', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const d = makeDriver(); + storeFor = d.storeFor; + await kernel.use({ + name: 'rollup-audit-driver-plugin', type: 'driver', version: '1.0.0', + init: async (ctx: any) => { ctx.registerService('driver.rollup-audit', d.driver); }, + } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + // The audit family (`updated_by` / `updated_at` / …) is NOT declared: the + // registry injects it, exactly as on an authored business object. + ql.registry.registerObject({ + name: 'contract', + label: 'Contract', + datasource: 'rollup-audit', + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + invoiced: { name: 'invoiced', label: 'Invoiced', type: 'summary', summaryOperations: { object: 'invoice', field: 'amount', function: 'sum' } }, + invoice_count: { name: 'invoice_count', label: 'Invoices', type: 'summary', summaryOperations: { object: 'invoice', function: 'count' } }, + }, + } as any, 'test', 'test'); + ql.registry.registerObject({ + name: 'invoice', + label: 'Invoice', + datasource: 'rollup-audit', + fields: { + amount: { name: 'amount', label: 'Amount', type: 'number' }, + contract: { name: 'contract', label: 'Contract', type: 'master_detail', reference: 'contract' }, + }, + } as any, 'test', 'test'); + }); + + afterEach(async () => { + if (kernel.getState() === 'running') await kernel.shutdown(); + }); + + const as = (userId: string) => ({ context: { userId } as any }); + const master = (id: string) => storeFor('contract').get(id); + + /** User A creates and last edits the master; its `updated_at` is then aged so a refresh is visible. */ + async function masterLastEditedByA(name: string): Promise { + const c = await ql.insert('contract', { name }, as(USER_A)); + await ql.update('contract', { id: c.id, name: `${name} (edited)` }, as(USER_A)); + expect(master(c.id).updated_by).toBe(USER_A); + storeFor('contract').set(c.id, { ...master(c.id), updated_at: STALE_AT }); + return c.id; + } + + function expectSystemStamp(id: string) { + const row = master(id); + expect(row.updated_by).toBeNull(); + expect(row.updated_by).not.toBe(USER_B); + expect(typeof row.updated_at).toBe('string'); + expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); + } + + it('CONTROL: a direct edit of the master by B still stamps B', async () => { + const id = await masterLastEditedByA('CTR-CONTROL'); + await ql.update('contract', { id, name: 'CTR-CONTROL (B)' }, as(USER_B)); + expect(master(id).updated_by).toBe(USER_B); + expect(Date.parse(master(id).updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); + }); + + it('a child INSERT by B recomputes the master and stamps it as the system', async () => { + const id = await masterLastEditedByA('CTR-INSERT'); + await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_B)); + expect(master(id).invoiced).toBe(40); + expect(master(id).invoice_count).toBe(1); + expectSystemStamp(id); + }); + + it('a child UPDATE by B recomputes the master and stamps it as the system', async () => { + const id = await masterLastEditedByA('CTR-UPDATE'); + const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A)); + await ql.update('contract', { id, name: 'CTR-UPDATE (A again)' }, as(USER_A)); + storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT }); + expect(master(id).updated_by).toBe(USER_A); + + await ql.update('invoice', { id: inv.id, amount: 55 }, as(USER_B)); + expect(master(id).invoiced).toBe(55); + expectSystemStamp(id); + }); + + it('a child DELETE by B recomputes the master and stamps it as the system', async () => { + const id = await masterLastEditedByA('CTR-DELETE'); + const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A)); + await ql.update('contract', { id, name: 'CTR-DELETE (A again)' }, as(USER_A)); + storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT }); + expect(master(id).updated_by).toBe(USER_A); + + await ql.delete('invoice', { where: { id: inv.id }, ...as(USER_B) } as any); + expect(master(id).invoiced).toBe(0); + expect(master(id).invoice_count).toBe(0); + expectSystemStamp(id); + }); + + it('a child RE-PARENT by B recomputes BOTH masters and stamps each as the system', async () => { + const from = await masterLastEditedByA('CTR-FROM'); + const inv = await ql.insert('invoice', { contract: from, amount: 40 }, as(USER_A)); + await ql.update('contract', { id: from, name: 'CTR-FROM (A again)' }, as(USER_A)); + storeFor('contract').set(from, { ...master(from), updated_at: STALE_AT }); + const to = await masterLastEditedByA('CTR-TO'); + + await ql.update('invoice', { id: inv.id, contract: to }, as(USER_B)); + expect(master(from).invoiced).toBe(0); + expect(master(to).invoiced).toBe(40); + expectSystemStamp(from); + expectSystemStamp(to); + }); +}); From 07a9ecf4d1438bb36befb15296a79ca2cf10deee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:21:45 +0000 Subject: [PATCH 2/5] fix(objectql): a roll-up recompute stamps the master as a system write The master update recomputeSummaries issues carries an engine-only symbol option; the audit stamp then writes updated_by = null (ADR-0118 D1) and a fresh updated_at instead of the child writer's userId. Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 Co-authored-by: Claude --- .../src/engine-summaries-and-expansion.ts | 40 ++++++++++++++++++- packages/objectql/src/plugin.ts | 31 ++++++++++++-- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 2cefada19c3..154914f15ad 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -50,6 +50,29 @@ import { ENGINE_WIRE_ONLY_SLOTS, WIRE_ONLY_CANONICAL_SHAPES } from './engine-top import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; +/** + * The engine's own mark on the master `update` a roll-up recompute issues + * ({@link SummariesAndExpansionFacet.recomputeSummaries}): the write is the + * SYSTEM's on the master's audit trail. `ObjectQLPlugin`'s + * `sys_stamp_audit_update` hook reads it off the hook's `input.options` and + * stamps `updated_by = null` (ADR-0118 D1: a system actor is `null` in a user + * lookup column, no system account, no sentinel) and a fresh `updated_at`, + * instead of the triggering child writer's `userId`. Ruling recorded on the + * card, comment 6902001862: 「确定汇总字段自动重算时主记录的修改人和修改时间怎么记」 + * → 「记为系统并刷新时间」. + * + * An OPTION, not a context key, so it reaches exactly the one update it is put + * on: the master's hooks keep the caller's context — `userId` included, so a + * record-triggered flow or a hook on the master still knows who triggered the + * write — and a write one of those hooks issues through `ctx.api` carries the + * context, never this bag. A symbol, so no options object a door assembles + * from a request can carry it (`rejectUnknownEngineOptions` reads string keys + * only, and JSON has no symbols). `Symbol.for`, so every bundle of this + * package — both entries, ESM and CJS — names the one key, the shape + * `SECURITY_SERVICE_SOURCE_SLOT` takes for the same reason. + */ +export const SUMMARY_RECOMPUTE_WRITE: unique symbol = Symbol.for('objectstack.objectql.summaryRecomputeWrite'); + /** * The `ObjectQL` members the bodies of {@link SummariesAndExpansionFacet} read — every one of * them, and no other. Each is typed AS the class member (an indexed access on @@ -441,6 +464,17 @@ export class SummariesAndExpansionFacet { * `update` of the parent is refused exactly as before), the summary field * stays subject to the parent's FLS on read, and the only value this path can * move is the one the author DECLARED as a function of the child collection. + * + * # Who the master's audit trail names + * + * The SYSTEM, not the child's writer: the parent update carries + * {@link SUMMARY_RECOMPUTE_WRITE}, so the audit stamp writes + * `updated_by = null` and refreshes `updated_at` (a figure on the master did + * change). Elevation alone would not say this — `userId` rides the elevated + * context on purpose, and the stamp reads it — which is how a finance user + * who only inserted an invoice came to read as the contract's last editor. + * Insert, update, delete and a re-parent of a child all reach the master + * through this one write, so they all stamp the same way. */ static async recomputeSummaries(this: Pick, childObject: string, records: any, previous: any, execCtx?: ExecutionContext): Promise { const descriptors = this.getSummaryDescriptors(childObject); @@ -467,7 +501,11 @@ export class SummariesAndExpansionFacet { // lives where the insert-time seed and the one-off NULL backfill // can read the identical computation instead of copying it. const value = await aggregateSummaryValue(this.facade, desc, parentId, systemCtx); - await this.update(desc.parentObject, { id: parentId, [desc.summaryField]: value }, { context: systemCtx } as any); + await this.update( + desc.parentObject, + { id: parentId, [desc.summaryField]: value }, + { context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any, + ); }, this.summaryRetryOptions); } catch (err) { // Retries exhausted (or a non-transient failure). Record it so the diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index d5973e882ed..e13d8aeff4e 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -9,6 +9,7 @@ import { type UnservableControlledByParentMaster, } from './engine.js'; import { OWNERSHIP_QUEUE_SOURCE_SLOT, describeMissingOwnershipQueueService } from './assignment-rules.js'; +import { SUMMARY_RECOMPUTE_WRITE } from './engine-summaries-and-expansion.js'; import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol'; import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; @@ -2099,8 +2100,22 @@ export class ObjectQLPlugin implements Plugin { session: any, isInsert: boolean, seedReplay: boolean, + systemActor: boolean, ) => { const now = stamp(); + // A roll-up recompute's write onto the master (`SUMMARY_RECOMPUTE_WRITE`, + // set only by `recomputeSummaries`) is the SYSTEM's on the audit trail: + // `updated_by = null` (ADR-0118 D1) and a fresh `updated_at`, never the + // child writer the elevated context still carries as `userId`. Ruling + // recorded on the card, comment 6902001862 (「记为系统并刷新时间」). Update-only + // and unconditional on the session: a recompute triggered by a user-less + // write stamps the same null, and `preserveAudit` on the triggering + // import does not make a recompute historical. + if (systemActor && !isInsert) { + record.updated_at = now; + if (hasField(objectName, 'updated_by')) record.updated_by = null; + return; + } // A "historical" import (#3493) reinstates the ORIGINAL timeline, so a // client-supplied created_at/created_by/updated_at/updated_by is // CLIENT-PREFERRED under `preserveAudit` — instead of being overwritten @@ -2176,15 +2191,16 @@ export class ObjectQLPlugin implements Plugin { session: any, isInsert: boolean, seedReplay: boolean, + systemActor = false, ) => { if (Array.isArray(data)) { for (const row of data) { if (row && typeof row === 'object') { - applyToRecord(row as Record, objectName, session, isInsert, seedReplay); + applyToRecord(row as Record, objectName, session, isInsert, seedReplay, systemActor); } } } else if (data && typeof data === 'object') { - applyToRecord(data as Record, objectName, session, isInsert, seedReplay); + applyToRecord(data as Record, objectName, session, isInsert, seedReplay, systemActor); } }; @@ -2202,6 +2218,15 @@ export class ObjectQLPlugin implements Plugin { const isSeedReplay = (hookCtx: any): boolean => hookCtx?.input?.options?.context?.seedReplay === true; + /** + * Whether this `beforeUpdate` is the master write of a roll-up recompute. + * Read from `input.options` (the caller's own options bag, as above) under + * the engine's symbol key, which only `recomputeSummaries` sets — see + * `SUMMARY_RECOMPUTE_WRITE` for why it is an option and not a context key. + */ + const isSummaryRecomputeWrite = (hookCtx: any): boolean => + hookCtx?.input?.options?.[SUMMARY_RECOMPUTE_WRITE] === true; + const builtinHooks: any[] = [ { name: 'sys_stamp_audit_insert', @@ -2224,7 +2249,7 @@ export class ObjectQLPlugin implements Plugin { handler: async (hookCtx: any) => { if (hookCtx.input?.data) { // `seedReplay` is moot here: the update stamp never writes `created_at`. - stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false); + stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false, isSummaryRecomputeWrite(hookCtx)); } }, }, From af01ded096d7937298ec902e5ba66bee9ce14fe9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:24:42 +0000 Subject: [PATCH 3/5] test(dogfood): pin the roll-up recompute system stamp on a real showcase boot Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 Co-authored-by: Claude --- ...ary-recompute-system-stamp.dogfood.test.ts | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 packages/qa/dogfood/test/summary-recompute-system-stamp.dogfood.test.ts diff --git a/packages/qa/dogfood/test/summary-recompute-system-stamp.dogfood.test.ts b/packages/qa/dogfood/test/summary-recompute-system-stamp.dogfood.test.ts new file mode 100644 index 00000000000..d9db15ad33d --- /dev/null +++ b/packages/qa/dogfood/test/summary-recompute-system-stamp.dogfood.test.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A roll-up recompute is a SYSTEM write on the master's audit trail — measured + * on a real showcase boot (SQL driver, the app's own security profile, the + * audit plugin), through the real REST doors. + * + * The defect: a child write recomputes the master's `summary` columns through + * an ordinary engine `update` of the master, under the child writer's + * (elevated) context, and the audit stamp wrote that writer into the master's + * `updated_by`. A member who only added a task to a project they cannot edit + * then read as the project's last editor. + * + * Ruling (recorded on the card, comment 6902001862): 「确定汇总字段自动重算时 + * 主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. ADR-0118 D1: the system + * actor is `null`. So after the member's task write the project reads + * `updated_by = null` with a fresh `updated_at`, and no audit-ledger row on the + * project names the member. + * + * Showcase shape (the one the recompute's elevation was measured on): a plain + * member holds `create` + `read` on `showcase_task` and only `read` on + * `showcase_project`; `showcase_project.task_count` counts its tasks. + * + * CONTROL: the admin's own direct edit of the project still stamps the admin — + * the fix is the recompute's write, not every write. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { bootShowcase } from './showcase-boot.js'; + +const SYS = { isSystem: true } as const; +const STALE_AT = '2000-01-01T00:00:00.000Z'; + +type Row = Record; + +describe('roll-up recompute stamps the master as the system (updated_by = null)', () => { + let stack: VerifyStack; + let ql: any; + let adminToken: string; + let memberToken: string; + let adminId: string; + let memberId: string; + let projectId: string; + + const idFrom = async (res: Response): Promise => { + const text = await res.text(); + expect(res.status, text).toBeLessThan(300); + const json = JSON.parse(text) as { id?: string; data?: { id?: string }; record?: { id?: string } }; + return String(json.data?.id ?? json.record?.id ?? json.id); + }; + const project = async (): Promise => + (await ql.findOne('showcase_project', { where: { id: projectId }, context: SYS })) as Row; + /** Age the stored `updated_at` so "the recompute refreshed it" is never a same-millisecond tie. */ + const ageProject = async () => { + await ql.update('showcase_project', { id: projectId, updated_at: STALE_AT }, { context: { ...SYS, preserveAudit: true } }); + expect(new Date((await project()).updated_at).toISOString()).toBe(STALE_AT); + }; + const projectAuditRowsBy = async (userId: string): Promise => + (await ql.find('sys_audit_log', { + where: { object_name: 'showcase_project', record_id: projectId, user_id: userId }, + context: SYS, + })) as Row[]; + + beforeAll(async () => { + stack = await bootShowcase({ extraPlugins: [new AuditPlugin()] }); + ql = await stack.kernel.getServiceAsync('objectql'); + adminToken = await stack.signIn(); + memberToken = await stack.signUp('rollup-stamp-member@verify.test'); + memberId = String((await ql.findOne('sys_user', { where: { email: 'rollup-stamp-member@verify.test' }, context: SYS }))?.id ?? ''); + expect(memberId).not.toBe(''); + + const account = await idFrom(await stack.apiAs(adminToken, 'POST', '/data/showcase_account', { name: 'Rollup stamp account' })); + projectId = await idFrom(await stack.apiAs(adminToken, 'POST', '/data/showcase_project', { name: 'Rollup stamp project', account, status: 'planned' })); + adminId = String((await project()).created_by ?? ''); + expect(adminId).not.toBe(''); + expect(adminId).not.toBe(memberId); + expect((await project()).updated_by).toBe(adminId); + }, 180_000); + + afterAll(async () => { + if (stack) await stack.stop(); + }); + + it('the member cannot edit the project directly (the shape under test)', async () => { + const res = await stack.apiAs(memberToken, 'PATCH', `/data/showcase_project/${projectId}`, { name: 'member edit' }); + expect(res.status).toBeGreaterThanOrEqual(400); + expect((await project()).updated_by).toBe(adminId); + }); + + it('CONTROL: the admin\'s direct edit of the project stamps the admin', async () => { + await ageProject(); + const res = await stack.apiAs(adminToken, 'PATCH', `/data/showcase_project/${projectId}`, { name: 'Rollup stamp project (admin)' }); + expect(res.status, await res.clone().text()).toBe(200); + const row = await project(); + expect(row.updated_by).toBe(adminId); + expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); + }); + + it('the member\'s task insert recomputes the project and stamps it as the system, not the member', async () => { + await ageProject(); + const before = Number((await project()).task_count ?? 0); + const taskId = await idFrom(await stack.apiAs(memberToken, 'POST', '/data/showcase_task', { title: 'Rollup stamp task', project: projectId })); + expect(taskId).not.toBe(''); + const row = await project(); + expect(Number(row.task_count)).toBe(before + 1); + expect(row.updated_by).toBeNull(); + expect(row.updated_by).not.toBe(memberId); + expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); + expect(await projectAuditRowsBy(memberId)).toEqual([]); + }); +}); From f89df01cd38a348524e4ffd90a609cd87b9c4064 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:34:42 +0000 Subject: [PATCH 4/5] chore(changeset): objectql patch for the roll-up recompute system stamp Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 Co-authored-by: Claude --- .changeset/33950-summary-recompute-system-stamp.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/33950-summary-recompute-system-stamp.md diff --git a/.changeset/33950-summary-recompute-system-stamp.md b/.changeset/33950-summary-recompute-system-stamp.md new file mode 100644 index 00000000000..8294528b658 --- /dev/null +++ b/.changeset/33950-summary-recompute-system-stamp.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a roll-up recompute records the master's last change as the system, not as the person who wrote the child + +Clause-②: no +Metadata-protocol: none (runtime audit stamping; no authorable key changes; the dev confirms against the diff) + +When someone adds, changes, deletes or moves a child record, the engine recomputes the parent's `summary` (roll-up) fields. That recompute is a write onto the parent, and it used to stamp the parent's `updated_by` with the person who wrote the child. So a finance user who only added an invoice under a contract read as the contract's last editor, although they edited neither record and may hold no edit right on the contract. + +The recompute now records the system as the actor on the parent: `updated_by` is set to `null` (the platform's system actor, which the Console shows as 系统), and `updated_at` is refreshed, because a figure on the parent did change. This holds for a child insert, update and delete, and for a child moved to another parent (both parents). The person's own write to the child is still stamped with their name, and a direct edit of the parent still stamps whoever made it. Hooks and record-triggered flows on the parent still see who triggered the change; only the parent's audit stamp changes. + +What an upgrade changes: list views, reports, flows or filters on a parent's `updated_by` / "Last modified by" no longer match the child writer after a roll-up recompute; such a parent now reads as last changed by the system. Rows already stored keep the stamp they have until their next recompute or edit. From e5b5c82c6793f2f3283f80e161ac461a4c49fc06 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:39:59 +0000 Subject: [PATCH 5/5] test(objectql): the recompute-stamp driver double applies the caller's bound Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 Co-authored-by: Claude --- .../objectql/src/engine-summary-recompute-audit-actor.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts b/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts index fee1a5a56fb..e0f44cf143b 100644 --- a/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts +++ b/packages/objectql/src/engine-summary-recompute-audit-actor.test.ts @@ -63,7 +63,9 @@ function makeDriver() { async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, async syncSchema() {}, async find(object: string, ast: any) { - return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).map((r) => ({ ...r })); + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + return page.map((r) => ({ ...r })); }, async findOne(object: string, ast: any) { for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };