Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(takes): propose --accept needs no --dir and prints the claim; list --status refuses (#7271)

garrytan15fbc018aa33
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index d9079de021..b9286bb463 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -36,7 +36,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. #6450: `takes_add` and an explicit `takes_supersede` holder override are trimmed and checked with `isValidHolder` at the write boundary (syntax before authority: `invalid_params` naming the grammar, before `assertHolderAllowed`); the inherited supersede holder is not re-validated (the existing fence already round-tripped). Every prepared takes fence is parsed again before publication and refused `invalid_params` on any warning, so no write can leave a fence the next write would refuse. Test: `test/takes-holder-validation-6450.test.ts`. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`. GBRA-130 A-25: `takes propose --failed [--source <id>] [--json]` lists pages propose_takes held with a failure tombstone (`listFailedProposals`); `takes propose --retry-failed [--slug <slug>] [--source <id>] [--json]` deletes their tombstones and ledger records (`retryFailedProposals`) so the next run re-extracts them.
- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages take the same database path when the database is their copy of record (`sync.write_through` off, or the page in a declared `storage.db_only` directory; an unbound Postgres source skips that page `owner_unavailable`), and so does a file-backed page of a source with a canonical owner (bound before the run, or bound by the run's own first `put_page`, as PGLite does), so a mixed batch never reaches the fenced md-first writer; other unmanaged pages retain the md-first writer. A file-backed page whose file is missing is skipped as `mirror_unavailable` before the classifier runs. Pinned by `test/persistence-managed-takes-extract.test.ts`, `test/extract-takes-md-first.test.ts` and `test/pathological/d19-takes-bootstrap-db-only.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.
-- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.
+- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text. #7271: accept needs no brain directory (the mutation resolves its write root from the proposal's source; a repo-less brain writes through the database), `takes propose --accept` prints the accepted claim and page, and `takes list --status` refuses and points at `takes propose --json` (`test/takes-propose-cli-7271.test.ts`).
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
- `admin/src/index.css` — `--text-muted: #777` (WCAG AA contrast bump to ~5.5 on the #0a0a0f bg).
- `test/fixtures/calibration/extract-takes-corpus/` — synthetic prompt-tuning corpus. Ships 5 representative pages; full 50-page + 10-page holdout generated by `gbrain calibration build-corpus`. All anonymized per CLAUDE.md placeholder list.
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index cb544fbd3a..7611f063bf 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -50,22 +50,6 @@ function flagPresent(args: string[], name: string): boolean {
return args.includes(name);
}
-async function resolveBrainDir(engine: BrainEngine | null, explicitDir: string | null): Promise<string> {
- if (explicitDir) {
- if (!existsSync(explicitDir)) {
- console.error(`--dir path does not exist: ${explicitDir}`);
- process.exit(1);
- }
- return explicitDir;
- }
- if (engine) {
- const configured = await engine.getConfig('sync.repo_path');
- if (configured && existsSync(configured)) return configured;
- }
- console.error('No brain directory configured. Pass --dir <path> or run `gbrain init` first.');
- process.exit(1);
-}
-
/**
* Map a TakesWriteError to the historical CLI error surface (stderr + exit 1).
* Message text preserves the pre-extraction wording users and scripts saw.
@@ -105,6 +89,11 @@ async function cmdList(engine: BrainEngine, args: string[]): Promise<void> {
// takes — CLI parity with the takes_list operation. A leading flag is not
// a slug.
const slug = args[0] && !args[0].startsWith('-') ? args[0] : undefined;
+ // #7271: there is no status filter here; an ignored --status read as a filtered list.
+ if (args.some(arg => arg === '--status' || arg.startsWith('--status='))) {
+ console.error('takes list has no --status filter: it lists active takes, and --expired lists superseded ones. Proposed takes wait in the proposal queue: gbrain takes propose --json');
+ process.exit(1);
+ }
const json = flagPresent(args, '--json');
const holder = flagValue(args, '--who');
const kind = flagValue(args, '--kind') as string | undefined;
@@ -535,11 +524,15 @@ async function cmdPropose(engine: BrainEngine, args: string[], sourceId: string)
console.error(`Invalid --kind "${kind}". Expected fact, take, bet or hunch.`);
process.exit(1);
}
- const brainDir = await resolveBrainDir(engine, dirArg ?? null);
+ if (dirArg !== undefined && !existsSync(dirArg)) {
+ console.error(`--dir path does not exist: ${dirArg}`);
+ process.exit(1);
+ }
+ const claim = flagValue(args, '--claim');
try {
- const { proposal, rowNum } = await acceptProposal({ engine, brainDir, sourceId, actedBy, config: loadConfig() ?? { engine: 'pglite' },
- ...(dirArg ? { localDir: resolvePath(dirArg) } : {}) }, id, { claim: flagValue(args, '--claim'), weight, holder: flagValue(args, '--who'), kind });
- console.log(`Accepted proposal #${id} → take #${rowNum} on ${proposal.page_slug}.`);
+ const { proposal, rowNum } = await acceptProposal({ engine, sourceId, actedBy, config: loadConfig() ?? { engine: 'pglite' },
+ ...(dirArg ? { localDir: resolvePath(dirArg) } : {}) }, id, { claim, weight, holder: flagValue(args, '--who'), kind });
+ console.log(`Accepted proposal #${id} → take #${rowNum} on ${proposal.page_slug}: ${claim ?? proposal.claim_text}`);
} catch (err) {
if (err instanceof TakeProposalError) {
console.error(err.message);
diff --git a/src/core/take-proposals.ts b/src/core/take-proposals.ts
index a610b7462d..e21d413105 100644
--- a/src/core/take-proposals.ts
+++ b/src/core/take-proposals.ts
@@ -159,7 +159,7 @@ async function loadProposal(
export interface ProposalActionTarget {
engine: BrainEngine;
- /** Brain repo root — accept writes the markdown fence (markdown-canonical). */
+ /** Not read: the takes_add mutation accept submits resolves its write root from the proposal's source (#7271). */
brainDir?: string;
/** Source scope: a proposal outside this source reads as not_found. */
sourceId?: string;
@@ -256,12 +256,6 @@ export async function acceptProposal(
): Promise<{ proposal: TakeProposalRow; rowNum: number }> {
const { engine } = target;
const proposal = await loadProposal(engine, id, target.sourceId, { allowStranded: true });
- if (!target.brainDir) {
- throw new TakeProposalError(
- 'not_found',
- 'Accept requires a brain directory (takes are markdown-canonical). Pass --dir or configure sync.repo_path.',
- );
- }
// Claim-first CAS: exactly one caller wins the pending row. A claim that is
// already held without a recorded take resumes under its own request id.
const claimed = proposal.status === 'accepted'
diff --git a/test/takes-propose-cli-7271.test.ts b/test/takes-propose-cli-7271.test.ts
new file mode 100644
index 0000000000..05eb2cee11
--- /dev/null
+++ b/test/takes-propose-cli-7271.test.ts
@@ -0,0 +1,126 @@
+/**
+ * #7271: the takes proposal CLI.
+ *
+ * 1. Protects: \`takes list --status <x>\` refuses (takes list has no status filter) and points proposed takes at
+ * \`gbrain takes propose --json\` instead of silently listing active takes; \`takes propose --accept <id>\` without
+ * --dir works on a configured brain (a managed brain whose source has its checkout, and a repo-less brain), because
+ * the takes_add mutation resolves its own write root; the accept prints the accepted claim and its page.
+ * 2. Fails when: --status is ignored again, accept requires sync.repo_path or --dir again, or the accept line drops
+ * the claim text.
+ * 3. Why existing coverage misses it: every accept test passed --dir or set sync.repo_path, and no list test passed
+ * an unknown flag value.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runTakes } from '../src/commands/takes.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { put } from './helpers/wave-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+async function insertProposal(engine: BrainEngine, slug: string, claim: string): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ "INSERT INTO take_proposals (source_id, page_slug, content_hash, prompt_version, proposal_run_id, claim_text, kind, holder, weight, domain, model_id, status) "
+ + "VALUES ('default', $1, md5($2), 'test-v1', 'run-test', $2, 'bet', 'world', 0.7, NULL, 'test-model', 'pending') RETURNING id", [slug, claim]);
+ return Number(rows[0]!.id);
+}
+
+/** runTakes with stdout and stderr captured and process.exit stubbed (it throws to stop the command, as the real exit would). */
+async function run(engine: BrainEngine, args: string[]): Promise<{ exitCode: number | null; stdout: string; stderr: string }> {
+ let exitCode: number | null = null;
+ const out: string[] = [];
+ const err: string[] = [];
+ const originalExit = process.exit;
+ const originalLog = console.log;
+ const originalErr = console.error;
+ (process.exit as unknown as (code?: number) => void) = ((code?: number) => { exitCode = code ?? 0; throw new Error('exit-' + code); }) as never;
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ try {
+ await runTakes(engine, args);
+ } catch (e) {
+ if (exitCode === null) err.push(String(e));
+ } finally {
+ process.exit = originalExit;
+ console.log = originalLog;
+ console.error = originalErr;
+ }
+ return { exitCode, stdout: out.join('\n'), stderr: err.join('\n') };
+}
+
+const status = async (engine: BrainEngine, id: number) =>
+ (await engine.executeRaw<{ status: string }>('SELECT status FROM take_proposals WHERE id = $1', [id]))[0]!.status;
+
+describe('#7271 takes list --status', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ for (const value of ['proposed', 'active', 'bogus']) {
+ test('--status ' + value + ' refuses, naming --expired and takes propose --json', async () => {
+ const r = await run(engine, ['list', '--status', value]);
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('--expired');
+ expect(r.stderr).toContain('gbrain takes propose --json');
+ expect(r.stdout).toBe('');
+ });
+ }
+});
+
+describe('#7271 takes propose --accept on a repo-less brain', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ test('accepts with no repository and no --dir', async () => {
+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'About acme-example.' });
+ const id = await insertProposal(engine, 'companies/acme-example', 'Acme hires a CFO this year');
+ const r = await run(engine, ['propose', '--accept', String(id)]);
+ expect(r.stderr).toBe('');
+ expect(r.exitCode).toBeNull();
+ expect(r.stdout).toContain('Accepted proposal #' + id);
+ expect(r.stdout).toContain('companies/acme-example: Acme hires a CFO this year');
+ expect(await status(engine, id)).toBe('accepted');
+ const takes = await engine.executeRaw<{ claim: string }>("SELECT t.claim FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = 'companies/acme-example'");
+ expect(takes.map(t => t.claim)).toEqual(['Acme hires a CFO this year']);
+ });
+});
+
+describe('#7271 takes propose --accept without --dir', () => {
+ for (const backend of testBackends()) {
+ test(backend + ': a managed brain accepts from its source checkout and prints the claim and page', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const slug = 'companies/acme-example';
+ await put(ctx, slug, 'About acme-example.', 'company');
+ expect(await engine.getConfig('sync.repo_path')).toBeNull();
+ const id = await insertProposal(engine, slug, 'Acme ships the widget by Q3');
+ const r = await run(engine, ['propose', '--accept', String(id)]);
+ expect(r.stderr).toBe('');
+ expect(r.exitCode).toBeNull();
+ expect(r.stdout).toContain('Accepted proposal #' + id);
+ expect(r.stdout).toContain(slug);
+ expect(r.stdout).toContain('Acme ships the widget by Q3');
+ expect(await status(engine, id)).toBe('accepted');
+ const edited = await insertProposal(engine, slug, 'Acme doubles revenue');
+ const e = await run(engine, ['propose', '--accept', String(edited), '--claim', 'Acme doubles revenue next year']);
+ expect(e.stdout).toContain('Acme doubles revenue next year');
+ }, { databaseUrl: backend === 'postgres' ? process.env.DATABASE_URL : undefined });
+ }, 180_000);
+ }
+});