Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Audit exactly the owner decision that changed a memory proposal, and keep committed approvals audited

garrytan93bdfba8c0bb
diff --git a/src/commands/serve-http-access.ts b/src/commands/serve-http-access.ts
index 730c53cde2..a2adfca4ae 100644
--- a/src/commands/serve-http-access.ts
+++ b/src/commands/serve-http-access.ts
@@ -131,7 +131,7 @@ export function mountAdminMemoryProposals(app: Express, requireAdmin: RequestHan
const result = action === 'approve'
? await lib.approveMemoryProposal(ctx, row.request_id, { decidedBy: 'admin-api' })
: await lib.denyMemoryProposal(ctx, row.request_id, reason, { decidedBy: 'admin-api' });
- const applied = dryRun !== true && row.state === 'awaiting_owner';
+ const applied = dryRun !== true && result.decided === true;
if (applied) await audit(engine, `proposal_${action}`, { request_id: row.request_id, kind: row.kind, slug: row.slug, member: row.member_id, state: result.status });
return { applied, ...result, ...(action === 'approve' && lib.approveFailed(result) ? { outcome: 'failed' } : {}) };
}, 'Show the proposal (GET /admin/api/memory-proposals/<request_id>)');
diff --git a/src/core/persistence/memory-proposals.ts b/src/core/persistence/memory-proposals.ts
index 2d981a88cc..8463e68291 100644
--- a/src/core/persistence/memory-proposals.ts
+++ b/src/core/persistence/memory-proposals.ts
@@ -150,14 +150,21 @@ function pendingLimit(scope: 'actor' | 'credential', pending: number, cap: numbe
const expiryReason = (limits: ProposalLimits) => `No owner decision within ${limits.ttlHours} hours.`;
+type CloseFields = { reason: string | null; code?: string | null; decidedBy: string };
+
/** Closes an awaiting_owner proposal; returns the row as it is afterwards (unchanged when another decision got there first). */
-async function closeProposal(engine: SqlEngine, row: MemoryProposal, state: Exclude<ProposalState, 'awaiting_owner' | 'approved'>,
- fields: { reason: string | null; code?: string | null; decidedBy: string }): Promise<MemoryProposal> {
+async function closeProposal(engine: SqlEngine, row: MemoryProposal, state: Exclude<ProposalState, 'awaiting_owner' | 'approved'>, fields: CloseFields): Promise<MemoryProposal> {
+ return (await decideClose(engine, row, state, fields)).row;
+}
+
+/** closeProposal, also saying whether this call's own conditional UPDATE made the change (decided) or another decision got there first. */
+async function decideClose(engine: SqlEngine, row: MemoryProposal, state: Exclude<ProposalState, 'awaiting_owner' | 'approved'>,
+ fields: CloseFields): Promise<{ row: MemoryProposal; decided: boolean }> {
const [updated] = await engine.executeRaw<Record<string, unknown>>(`UPDATE memory_proposals SET state=$4, reason=$5, error_code=$6, decided_by=$7,
decided_at=now(), updated_at=now() WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid AND state='awaiting_owner' RETURNING *`,
[row.principal_kind, row.principal_id, row.request_id, state, fields.reason, fields.code ?? null, fields.decidedBy]);
- if (updated) return normalize(updated);
- return (await getProposal(engine, { kind: row.principal_kind, id: row.principal_id } as Principal, row.request_id)) ?? row;
+ if (updated) return { row: normalize(updated), decided: true };
+ return { row: (await getProposal(engine, { kind: row.principal_kind, id: row.principal_id } as Principal, row.request_id)) ?? row, decided: false };
}
async function overdue(engine: SqlEngine, row: MemoryProposal): Promise<boolean> {
@@ -284,7 +291,8 @@ function publicJournal(row: WriteRequest): Record<string, unknown> {
* The owner's yes: re-runs the approval checks, then in one transaction locks the proposal, admits the write into the
* journal under the same request id and marks the proposal approved, so neither commits without the other; then waits
* for publication like any write. A refused check closes the proposal failed or conflict with that code. A second
- * approve after a lost reply returns the same journal receipt.
+ * approve after a lost reply returns the same journal receipt. `decided` is true only when this call's own conditional
+ * update made the decision; once the approval commits nothing throws, so a failed wait returns the admitted receipt.
*/
export async function approveMemoryProposal(ctx: OperationContext, requestId: string, opts: { decidedBy: string; waitMs?: number }): Promise<Record<string, unknown>> {
const engine = ctx.engine;
@@ -293,7 +301,7 @@ export async function approveMemoryProposal(ctx: OperationContext, requestId: st
const { getWriteRequest } = await import('./journal.ts');
if (row.state === 'approved') {
const written = await getWriteRequest(engine, principal, row.request_id);
- return { status: 'approved', request_id: row.request_id, decided_at: row.decided_at, ...(written ? { write_request: publicJournal(written) } : {}) };
+ return { status: 'approved', decided: false, request_id: row.request_id, decided_at: row.decided_at, ...(written ? { write_request: publicJournal(written) } : {}) };
}
if (row.state !== 'awaiting_owner') throw proposalClosedError(row);
if (await overdue(engine, row)) {
@@ -303,8 +311,9 @@ export async function approveMemoryProposal(ctx: OperationContext, requestId: st
const prepared = await prepareApproval(ctx, row);
if ('state' in prepared) {
if (ctx.dryRun) return { dry_run: true, action: 'approve', request_id: row.request_id, would: prepared.state, error_code: prepared.code, reason: prepared.reason };
- const closed = await closeProposal(engine, row, prepared.state, { reason: prepared.reason, code: prepared.code, decidedBy: opts.decidedBy });
- return { status: closed.state, request_id: row.request_id, error_code: closed.error_code, reason: closed.reason };
+ const closed = await decideClose(engine, row, prepared.state, { reason: prepared.reason, code: prepared.code, decidedBy: opts.decidedBy });
+ if (!closed.decided) throw proposalClosedError(closed.row);
+ return { status: closed.row.state, decided: true, request_id: row.request_id, error_code: closed.row.error_code, reason: closed.row.reason };
}
if (ctx.dryRun) return { dry_run: true, action: 'approve', request_id: row.request_id, would: 'approved' };
const { admitWriteInTransaction } = await import('./journal.ts');
@@ -326,9 +335,13 @@ export async function approveMemoryProposal(ctx: OperationContext, requestId: st
await closeProposal(engine, row, 'expired', { reason: expiryReason(await readProposalLimits(engine)), decidedBy: 'gbrain:expiry' });
throw proposalExpiredError(row);
}
- const { waitForWrite } = await import('./service.ts');
- const settled = await waitForWrite(engine, outcome.written, ctx.config, opts.waitMs ?? 5000);
- return { status: 'approved', request_id: row.request_id, write_request: publicJournal(settled) };
+ try {
+ const { waitForWrite } = await import('./service.ts');
+ const settled = await waitForWrite(engine, outcome.written, ctx.config, opts.waitMs ?? 5000);
+ return { status: 'approved', decided: true, request_id: row.request_id, write_request: publicJournal(settled) };
+ } catch {
+ return { status: 'approved', decided: true, request_id: row.request_id, write_request: publicJournal(outcome.written) };
+ }
}
/** The owner's no, with a reason (1 to proposals.max_reason_chars characters). */
@@ -345,9 +358,9 @@ export async function denyMemoryProposal(ctx: OperationContext, requestId: strin
throw proposalExpiredError(row);
}
if (ctx.dryRun) return { dry_run: true, action: 'deny', request_id: row.request_id, would: 'denied' };
- const after = await closeProposal(ctx.engine, row, 'denied', { reason, decidedBy: opts.decidedBy });
- if (after.state !== 'denied') throw proposalClosedError(after);
- return { status: 'denied', request_id: row.request_id, reason, decided_at: after.decided_at };
+ const after = await decideClose(ctx.engine, row, 'denied', { reason, decidedBy: opts.decidedBy });
+ if (after.row.state !== 'denied') throw proposalClosedError(after.row);
+ return { status: 'denied', decided: after.decided, request_id: row.request_id, reason: after.row.reason, decided_at: after.row.decided_at };
}
/** An approve that did not publish: the checks closed the proposal, or the approved write ended without committing. */
diff --git a/test/serve-http-memory-proposals.test.ts b/test/serve-http-memory-proposals.test.ts
index 50f0aed048..ed587ccb5b 100644
--- a/test/serve-http-memory-proposals.test.ts
+++ b/test/serve-http-memory-proposals.test.ts
@@ -15,7 +15,7 @@
* an attested OAuth client-credentials token through MCP dispatch; publication through the persistence consumer;
* on a repo-less brain (PGLite, and Postgres when DATABASE_URL is set).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import express from 'express';
import cookieParser from 'cookie-parser';
import { randomUUID } from 'node:crypto';
@@ -29,6 +29,7 @@ import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
import { addMember, bindCredential } from '../src/core/access/members.ts';
import { linkMember } from '../src/core/access/actor.ts';
+import * as persistenceService from '../src/core/persistence/service.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { mountAdminAccess, mountAdminMemoryProposals } from '../src/commands/serve-http-access.ts';
import { createRequireAdmin } from '../src/commands/serve-http-admin-api.ts';
@@ -86,6 +87,21 @@ for (const kind of testBackends()) {
})) as typeof engine.transaction;
return restore;
}
+ /** Holds every proposal-closing conditional UPDATE until n of them have arrived, so concurrent decisions all pass their reads first. */
+ function barrierOnClose(requestId: string, n: number): () => void {
+ const original = engine.executeRaw;
+ const held: Array<() => void> = [];
+ let open = false;
+ const release = () => { open = true; held.splice(0).forEach(go => go()); };
+ const timer = setTimeout(release, 10_000);
+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[], ...rest: unknown[]) {
+ if (!open && params?.[2] === requestId && /^UPDATE memory_proposals SET state=\$4/.test(sql.trim())) {
+ await new Promise<void>(go => { held.push(go); if (held.length >= n) release(); });
+ }
+ return (original as (...args: unknown[]) => Promise<unknown>).call(this, sql, params, ...rest);
+ }) as typeof engine.executeRaw;
+ return () => { clearTimeout(timer); engine.executeRaw = original; };
+ }
const unlinkInside = (externalId: string) => (tx: BrainEngine) => tx.executeRaw("DELETE FROM access_member_links WHERE system = 'qm' AND external_id = $1", [externalId]).then(() => undefined);
async function cli(args: string[]) {
const lines: string[] = [];
@@ -277,5 +293,62 @@ for (const kind of testBackends()) {
expect((await proposalAudits()).length).toBe(before);
expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve' })).json).toMatchObject({ applied: true, status: 'approved' });
}, 90_000);
+
+ test('concurrent decisions on one proposal: exactly one is applied and audited, and both answers carry the stored decision', async () => {
+ const id = await propose(BOB_ID, 'Race deny canaryracedeny');
+ const before = (await proposalAudits()).length;
+ let restore = barrierOnClose(id, 2);
+ let answers: Array<Awaited<ReturnType<typeof call>>>;
+ try {
+ answers = await Promise.all([
+ call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: 'First reason' }),
+ call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: 'Second reason' }),
+ ]);
+ } finally { restore(); }
+ const stored = await proposalRow(id);
+ expect(stored.state).toBe('denied');
+ expect(answers.filter(a => a.json.applied === true)).toHaveLength(1);
+ for (const a of answers) expect(a.json).toMatchObject({ status: 'denied', reason: stored.reason });
+ expect((await proposalAudits()).slice(before)).toEqual([
+ { actor: 'admin-api', action: 'proposal_deny', request_id: id, kind: 'timeline', slug: ACME, member: 'bob-example', state: 'denied' },
+ ]);
+
+ await linkMember(engine, 'alice-example', 'qm', 'U0ALICE4');
+ const refused = await propose('U0ALICE4', 'Race refused canaryracerefused');
+ await engine.executeRaw("DELETE FROM access_member_links WHERE system = 'qm' AND external_id = 'U0ALICE4'");
+ const mark = (await proposalAudits()).length;
+ restore = barrierOnClose(refused, 2);
+ try {
+ answers = await Promise.all([
+ call('POST', '/admin/api/memory-proposals/' + refused, { action: 'approve' }),
+ call('POST', '/admin/api/memory-proposals/' + refused, { action: 'deny', reason: 'Owner said no' }),
+ ]);
+ } finally { restore(); }
+ const after = await proposalRow(refused);
+ expect(['failed', 'denied']).toContain(after.state);
+ expect(answers.filter(a => a.json.applied === true)).toHaveLength(1);
+ const audited = (await proposalAudits()).slice(mark);
+ expect(audited).toHaveLength(1);
+ expect(audited[0]).toMatchObject({ action: after.state === 'denied' ? 'proposal_deny' : 'proposal_approve', state: after.state, request_id: refused });
+ for (const a of answers.filter(x => x.json.applied !== true)) expect(a.status === 400 ? a.json.code : a.json.status).toBe(a.status === 400 ? 'proposal_closed' : after.state);
+ }, 90_000);
+
+ test('a failure after the approval commits still answers applied with one audit row, and a retry writes none', async () => {
+ const id = await propose(ALICE_ID, 'Post-commit failure canarypostcommit');
+ const before = (await proposalAudits()).length;
+ const waiting = spyOn(persistenceService, 'waitForWrite').mockImplementation(async () => { throw new Error('injected failure after commit'); });
+ let res: Awaited<ReturnType<typeof call>>;
+ try { res = await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve' }); } finally { waiting.mockRestore(); }
+ expect(res.status).toBe(200);
+ expect(res.json).toMatchObject({ applied: true, status: 'approved', request_id: id, write_request: { request_id: id } });
+ expect(res.text).not.toContain('injected');
+ expect((await proposalRow(id))).toMatchObject({ state: 'approved', decided_by: 'admin-api' });
+ expect(await journalRows(id)).toHaveLength(1);
+ const retry = await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve' });
+ expect(retry.json).toMatchObject({ applied: false, status: 'approved' });
+ expect((await proposalAudits()).slice(before)).toEqual([
+ { actor: 'admin-api', action: 'proposal_approve', request_id: id, kind: 'timeline', slug: ACME, member: 'alice-example', state: 'approved' },
+ ]);
+ }, 90_000);
});
}