feat(bookkeeping): agent attribution into the immutable ledger layer (P0-1) (#678)

* feat(bookkeeping): agent attribution into the immutable ledger layer

Close the three attribution gaps left after 20260618120001 (which made
commit_method record 'api_key' for MCP-relayed approvals):

- journal_entries gains nullable committed_actor_type/committed_actor_label,
  stamped by commit_journal_entry in the same draft->posted UPDATE that
  writes commit_method. The RPC gains p_actor_type/p_actor_label
  (DEFAULT NULL; prior signature dropped first to avoid PostgREST overload
  ambiguity, same technique as 20260421140000).
- write_audit_log now populates audit_log.actor_type/actor_label from
  transaction-local gnubok.actor_* GUCs set by the RPC (the established
  gnubok.allow_delete pattern). Unset GUCs COALESCE to 'user' — byte-
  identical to the column's previous effective DEFAULT for every
  pre-existing write path.
- commitPendingOperation accepts opts.actor and runs the entire executor
  inside an AsyncLocalStorage runWithActor() scope read by commitEntry(),
  so EVERY journal commit an operation makes is attributed — closing the
  documented "commitMethod only reaches create_voucher" gap. MCP approve
  passes the api_key actor + key label; web single/bulk approve pass the
  user + email.

Known limitation (documented): reverseEntry posts reversal vouchers via
direct PostgREST writes, not the commit RPC — reversals keep NULL
attribution until that path is RPC-ified (follow-up).

pg-real coverage: lib/bookkeeping/__tests__/commit-actor.pg.test.ts
(RPC param stamping, audit GUC read, transaction-locality, CHECK
rejection, immutability of the new columns, single-signature guard).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(bookkeeping): split actor-context so client bundles never see node:async_hooks

CI core-only build failed: engine.ts is reachable from client component
bundles (invoices/[id] page), and the static node:async_hooks import in
actor-context.ts cannot be chunked for the browser. Split the module:

- actor-context.ts (isomorphic): CommitActor type + a storage registry +
  getActor(). In a client bundle the registry stays empty and getActor()
  returns undefined — identical to the server-side no-scope default.
- actor-context-node.ts (server-only): owns the AsyncLocalStorage, binds it
  into the registry on import, exports runWithActor(). Imported only by the
  approval paths (commit.ts), which are never client-reachable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-06 10:05:48 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 0ca9c25aba
commit 8d2ff61599
14 changed files with 638 additions and 10 deletions
@@ -0,0 +1,43 @@
import { describe, it, expect } from 'vitest'
import { runWithActor } from '../actor-context-node'
import { getActor } from '../actor-context'
describe('actor-context (AsyncLocalStorage commit attribution)', () => {
it('returns undefined outside a runWithActor scope', () => {
expect(getActor()).toBeUndefined()
})
it('exposes the actor inside the scope, across awaits', async () => {
const seen: Array<ReturnType<typeof getActor>> = []
await runWithActor({ type: 'api_key', label: 'Test Key' }, async () => {
seen.push(getActor())
await new Promise((resolve) => setTimeout(resolve, 0))
seen.push(getActor())
})
expect(seen).toEqual([
{ type: 'api_key', label: 'Test Key' },
{ type: 'api_key', label: 'Test Key' },
])
expect(getActor()).toBeUndefined()
})
it('keeps concurrent scopes isolated', async () => {
const results = await Promise.all([
runWithActor({ type: 'api_key', label: 'A' }, async () => {
await new Promise((resolve) => setTimeout(resolve, 5))
return getActor()?.label
}),
runWithActor({ type: 'user', label: 'B' }, async () => {
return getActor()?.label
}),
])
expect(results).toEqual(['A', 'B'])
})
it('propagates into nested calls without parameter threading', async () => {
const deepRead = async () => getActor()
const middle = async () => deepRead()
const actor = await runWithActor({ type: 'agent_chat' }, middle)
expect(actor).toEqual({ type: 'agent_chat' })
})
})
@@ -0,0 +1,154 @@
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import {
insertBalancedLines,
insertDraftJournalEntry,
seedCompany,
} from '@/tests/pg/fixtures'
/**
* Covers 20260619120000_journal_entry_committed_actor:
* - commit_journal_entry() gained p_actor_type/p_actor_label (DEFAULT NULL)
* and stamps journal_entries.committed_actor_* in the draft→posted UPDATE.
* - write_audit_log() reads the transaction-local gnubok.actor_* GUCs the
* RPC sets, so the COMMIT audit row carries actor attribution.
* - Every pre-existing call shape (2/4-arg) behaves byte-identically:
* NULL columns, audit actor_type 'user' (the column's previous effective
* DEFAULT), actor_label NULL.
* - The GUCs are transaction-local: attribution never leaks into later
* statements on the same connection.
* - The new columns are frozen by the posted-entry immutability trigger.
*/
async function seedDraft() {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
await insertBalancedLines(entryId)
return { companyId, entryId }
}
async function fetchCommitAudit(entryId: string) {
const { rows } = await getPool().query(
`SELECT actor_type, actor_label
FROM public.audit_log
WHERE record_id = $1 AND action = 'COMMIT'`,
[entryId],
)
return rows
}
describe('commit_journal_entry — actor attribution (committed_actor_* + audit GUCs)', () => {
it('stamps committed_actor_* and the COMMIT audit row when actor params are passed', async () => {
const { companyId, entryId } = await seedDraft()
await getPool().query(
`SELECT voucher_number FROM public.commit_journal_entry(
$1::uuid, $2::uuid, 'api_key', NULL, 'api_key', 'Claude Desktop')`,
[companyId, entryId],
)
const { rows } = await getPool().query(
`SELECT status, commit_method, committed_actor_type, committed_actor_label
FROM public.journal_entries WHERE id = $1`,
[entryId],
)
expect(rows[0]).toEqual({
status: 'posted',
commit_method: 'api_key',
committed_actor_type: 'api_key',
committed_actor_label: 'Claude Desktop',
})
const audit = await fetchCommitAudit(entryId)
expect(audit).toEqual([{ actor_type: 'api_key', actor_label: 'Claude Desktop' }])
})
it('keeps the pre-attribution behaviour for callers that omit the new params', async () => {
const { companyId, entryId } = await seedDraft()
// 2-arg call — the shape deployed code used before the 6-arg migration.
await getPool().query(
`SELECT voucher_number FROM public.commit_journal_entry($1::uuid, $2::uuid)`,
[companyId, entryId],
)
const { rows } = await getPool().query(
`SELECT committed_actor_type, committed_actor_label
FROM public.journal_entries WHERE id = $1`,
[entryId],
)
expect(rows[0]).toEqual({ committed_actor_type: null, committed_actor_label: null })
// Audit row falls back to 'user' — the column's previous effective DEFAULT.
const audit = await fetchCommitAudit(entryId)
expect(audit).toEqual([{ actor_type: 'user', actor_label: null }])
})
it('rejects committed_actor_type values outside the CHECK list', async () => {
const { companyId, entryId } = await seedDraft()
await expect(
getPool().query(
`SELECT voucher_number FROM public.commit_journal_entry(
$1::uuid, $2::uuid, NULL, NULL, 'robot', NULL)`,
[companyId, entryId],
),
).rejects.toMatchObject({ code: '23514' }) // check_violation
})
it('does not leak the actor GUCs into later transactions on the same connection', async () => {
const a = await seedDraft()
const b = await seedDraft()
const client = await getPool().connect()
try {
await client.query(
`SELECT voucher_number FROM public.commit_journal_entry(
$1::uuid, $2::uuid, NULL, NULL, 'api_key', 'Leaky Key')`,
[a.companyId, a.entryId],
)
// Same connection, next transaction: set_config(..., is_local=true) must
// have died with the previous transaction.
await client.query(
`SELECT voucher_number FROM public.commit_journal_entry($1::uuid, $2::uuid)`,
[b.companyId, b.entryId],
)
} finally {
client.release()
}
expect(await fetchCommitAudit(a.entryId)).toEqual([
{ actor_type: 'api_key', actor_label: 'Leaky Key' },
])
expect(await fetchCommitAudit(b.entryId)).toEqual([
{ actor_type: 'user', actor_label: null },
])
})
it('freezes committed_actor_* after posting (immutability trigger)', async () => {
const { companyId, entryId } = await seedDraft()
await getPool().query(
`SELECT voucher_number FROM public.commit_journal_entry(
$1::uuid, $2::uuid, NULL, NULL, 'api_key', 'Original')`,
[companyId, entryId],
)
await expect(
getPool().query(
`UPDATE public.journal_entries SET committed_actor_label = 'tampered' WHERE id = $1`,
[entryId],
),
).rejects.toThrow(/Cannot modify a posted journal entry/i)
})
it('exposes exactly one commit_journal_entry signature (no PostgREST overload ambiguity)', async () => {
const { rows } = await getPool().query(
`SELECT pg_get_function_identity_arguments(p.oid) AS args
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.proname = 'commit_journal_entry'`,
)
expect(rows).toHaveLength(1)
expect(rows[0]!.args).toContain('p_actor_type')
expect(rows[0]!.args).toContain('p_actor_label')
})
})
@@ -16,6 +16,7 @@ vi.mock('@/lib/logger', () => ({
}))
import { commitEntry, getNextVoucherNumber, createJournalEntry } from '../engine'
import { runWithActor } from '../actor-context-node'
import { BookkeepingDatabaseError } from '../errors'
describe('voucher number atomicity', () => {
@@ -78,6 +79,8 @@ describe('voucher number atomicity', () => {
p_entry_id: 'entry-1',
p_commit_method: null,
p_rubric_version: null,
p_actor_type: null,
p_actor_label: null,
})
// from() was never called — the RPC handles everything atomically
@@ -116,11 +119,52 @@ describe('voucher number atomicity', () => {
p_entry_id: 'entry-1',
p_commit_method: null,
p_rubric_version: null,
p_actor_type: null,
p_actor_label: null,
})
// from() called once to fetch the complete entry with lines
expect(supabase.from).toHaveBeenCalledWith('journal_entries')
})
/**
* Actor attribution (migration 20260619120000): commitEntry forwards the
* surrounding runWithActor() scope to the RPC so the immutable layer can
* record WHO relayed the commit. Outside a scope the params stay null
* (asserted by the two tests above).
*/
it('commitEntry forwards the runWithActor scope to the RPC', async () => {
const postedEntry = {
id: 'entry-1',
company_id: 'co-1',
voucher_number: 1,
status: 'posted' as JournalEntryStatus,
lines: [],
}
const supabase = {
from: vi.fn().mockImplementation(() => ({
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({ data: postedEntry, error: null }),
}),
}),
})),
rpc: vi.fn().mockResolvedValue({ data: [{ voucher_number: 1 }], error: null }),
}
await runWithActor({ type: 'api_key', label: 'Claude Desktop' }, () =>
commitEntry(supabase as never, 'co-1', 'user-1', 'entry-1', 'api_key')
)
expect(supabase.rpc).toHaveBeenCalledWith('commit_journal_entry', {
p_company_id: 'co-1',
p_entry_id: 'entry-1',
p_commit_method: 'api_key',
p_rubric_version: null,
p_actor_type: 'api_key',
p_actor_label: 'Claude Desktop',
})
})
/**
* getNextVoucherNumber is still used by reverseEntry and storno-service.
* Those flows INSERT a new entry (not UPDATE a draft), so the atomic