Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(docs): fence walkthrough harness with a local provider stand-in; drop temperature from the Tier 3 call (#6188)

garrytane0cf63bd7623
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index b35d7c023b..1ec63b309e 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -11,7 +11,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.
- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.
- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.
-- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`), `callTier3` (gateway `chat`, no tools, no fallback, temperature 0, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.
+- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.
- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource`: managed owner root (or `ownerElsewhere`), legacy checkout, mirror flag, unfinished managed sync cursor and the paths/slugs pending writes name. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.
- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 4efbf9bebb..c3bca27c72 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -822,18 +822,17 @@ step. Per-file outcomes report `written`, `imported`, `hold_cleared` and
<a id="fences"></a>
### Fences
-`gbrain repair fences` repairs malformed facts and takes fences: files sync
-held with `invalid_fence`, stored pages whose fence does not parse, and
-checkout files not yet synced. The maintenance run applies the same repair
-automatically (phase `fence_repair`), so a fence hold usually clears with no
-command. The preview is read-only and makes no model call; applying needs no
-extra consent. What each reason means and who acts:
-[fence holds](write-refusals.md#invalid_fence); the format and every rule:
-[fence format](fence-format.md).
-
-```bash
-gbrain repair fences --source <id> # preview: tiers, rows, estimated model cost, apply command
-gbrain repair fences --source <id> --apply --expect <hash> # apply exactly the previewed set
+DRAFT
+
+```console
+$ gbrain post-upgrade
+$ gbrain sync --source notes --no-pull
+$ gbrain sources status notes
+$ gbrain repair fences --source notes
+$ gbrain repair fences --source notes --apply --expect <hash>
+$ gbrain sync --source notes --no-pull
+$ git -C ~/brain/notes log --format=%s -4
+$ gbrain doctor --only fence_integrity
```
## Resume
diff --git a/src/core/fence-repair/llm.ts b/src/core/fence-repair/llm.ts
index 7425d9812f..20de683c81 100644
--- a/src/core/fence-repair/llm.ts
+++ b/src/core/fence-repair/llm.ts
@@ -245,7 +245,7 @@ export interface Tier3CallOptions {
signal?: AbortSignal;
}
-/** One gateway call (no tools, no fallback model, temperature 0), classified. */
+/** One gateway call (no tools, no fallback model, thinking off; no temperature, which reasoning models refuse), classified. */
export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Promise<Tier3Answer> {
const prompt = buildTier3Prompt(req);
const messages: ChatMessage[] = [{ role: 'user', content: prompt.user }];
@@ -253,7 +253,7 @@ export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Prom
const budget = tier3TokenBudget(req, opts.correction ? { answer: opts.correction.answer } : undefined);
let result: ChatResult;
try {
- result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, temperature: 0, allowFallback: false,
+ result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,
thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });
} catch (error) {
return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };
diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.ts
index e9e86bff22..58c69ba97b 100644
--- a/src/core/repair/fences.ts
+++ b/src/core/repair/fences.ts
@@ -379,7 +379,7 @@ export const fencesRepair: RepairHandler = {
const shown = opts.diff ? d.diffs : Object.values(d.samples);
for (const diff of shown) lines.push(` ${diff.tier}: ${diff.item} (${diff.classes.join(', ')})`, ...diff.diff.split('\n').map(line => ` ${line}`));
if (!opts.diff && d.diffs.length > shown.length) lines.push(` (one sample diff per tier; --diff or --json shows all ${d.diffs.length})`);
- for (const llm of d.llm_items) lines.push(` llm: ${llm.item} rows ${llm.rows.join(', ') || '?'} (${llm.reasons.join(', ')}): rewritten by ${d.model} at apply time, gated by (a)-(g); est. $${llm.estimate_usd.toFixed(4)}`);
+ for (const llm of d.llm_items) lines.push(` llm: ${llm.item}${llm.rows.length ? ` rows ${llm.rows.join(', ')}` : ''} (${llm.reasons.join(', ')}): rewritten by ${d.model} at apply time, gated by (a)-(g); est. $${llm.estimate_usd.toFixed(4)}`);
for (const h of d.held) lines.push(` held ${h.item} [${h.reason}${h.gate ? `, gate ${h.gate}` : ''}]: ${h.resolution}`);
for (const action of d.next_actions) lines.push(` next: ${shellQuote(action.argv!)}`);
return lines;
diff --git a/test/fence-repair-llm.test.ts b/test/fence-repair-llm.test.ts
index a227e3dd58..7e5c1d7699 100644
--- a/test/fence-repair-llm.test.ts
+++ b/test/fence-repair-llm.test.ts
@@ -115,7 +115,7 @@ describe('the gateway call', () => {
expect(calls[0]!.tools).toBeUndefined();
expect(calls[0]!.allowFallback).toBe(false);
expect(calls[0]!.model).toBe('anthropic:claude-fable-5');
- expect(calls[0]!.temperature).toBe(0);
+ expect(calls[0]!.thinking).toBe('off');
const spliced = spliceTier3(normalized.page, requests[0]!, (answer as Extract<typeof answer, { ok: true }>).table)!;
expect(spliced.compiled_truth.startsWith(`${PROSE}\n\n${FB}\n${NARROW}\n${SEP}\n| 1 | ${VALID} |`)).toBe(true);
const final = safeNormalizeFences(spliced, { pageVisibility: 'private' });
diff --git a/test/fence-walkthrough.test.ts b/test/fence-walkthrough.test.ts
new file mode 100644
index 0000000000..11b182bcc1
--- /dev/null
+++ b/test/fence-walkthrough.test.ts
@@ -0,0 +1,173 @@
+/**
+ * Doc test for docs/guides/repair.md "Fences" (#6188, D22, D33). It builds the
+ * walkthrough's fixture with the real CLI on a throwaway PGLite brain: a Git
+ * source synced once, then generator-written notes with malformed facts and
+ * takes fences committed while `sync.holds=fail` (the pre-upgrade fail-closed
+ * behavior) so the source is blocked. Then it runs every `$ ` command in the
+ * section's console blocks, in order, and checks that each output line the
+ * guide shows appears in the real output (hashes, ids, times, costs and the
+ * checkout path normalized) and that every command exits 0. The model is a
+ * local stand-in for the provider's Responses API (OPENAI_BASE_URL), so the
+ * spawned CLI makes its genuine provider call and no network or key is used.
+ *
+ * Protects: the documented journey (post-upgrade notice, converting sync,
+ * sources status, preview, apply, commit subjects, doctor ok) and its command
+ * counts: one command to green (the sync), two to repaired (preview, apply).
+ * Fails when: a message, command, flag or flow drifts from the guide.
+ * Why new: the fences walkthrough is new in PR4.
+ * Seams: none (a local provider stand-in behind the documented base-URL env).
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const REPO = join(import.meta.dir, '..');
+const work = mkdtempSync(join(tmpdir(), 'gbrain-fence-walkthrough-'));
+const checkout = join(work, 'notes');
+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const NARROW = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';
+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';
+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+const ACME_ROW = '| 1 | acme-example raised a seed round | fact | 0.9 | private | high | 2026-03-01 | | meeting notes | |';
+const usage = { input_tokens: 1200, output_tokens: 150 };
+
+let requests = 0;
+const provider = Bun.serve({
+ port: 0,
+ async fetch(req) {
+ const url = new URL(req.url);
+ if (!url.pathname.endsWith('/responses')) return new Response(JSON.stringify({ data: [{ id: 'gpt-5.5' }] }), { headers: { 'Content-Type': 'application/json' } });
+ requests++;
+ return new Response(JSON.stringify({ id: 'resp_walkthrough', object: 'response', created_at: 1, model: 'gpt-5.5', status: 'completed', error: null, incomplete_details: null,
+ output: [{ type: 'message', id: 'msg_walkthrough', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: `${NARROW}\n${SEP}\n${ACME_ROW}`, annotations: [] }] }],
+ usage: { ...usage, total_tokens: usage.input_tokens + usage.output_tokens } }), { headers: { 'Content-Type': 'application/json' } });
+ },
+});
+
+const env: Record<string, string> = Object.fromEntries(Object.entries(process.env)
+ .filter(([key, value]) => value !== undefined && !['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE', 'GBRAIN_BRAIN_ID', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY'].includes(key))) as Record<string, string>;
+env.GBRAIN_HOME = join(work, 'home');
+env.OPENAI_API_KEY = 'sk-walkthrough-not-used';
+env.OPENAI_BASE_URL = `http://127.0.0.1:${provider.port}/v1`;
+
+afterAll(() => { provider.stop(true); rmSync(work, { recursive: true, force: true }); });
+
+/** Async, so the provider stand-in in this process can answer while the CLI runs. */
+async function run(argv: string[]): Promise<{ out: string; status: number | null }> {
+ const cmd = argv[0] === 'gbrain' ? [process.execPath, '--no-env-file', join(REPO, 'src', 'cli.ts'), ...argv.slice(1)] : argv;
+ const proc = Bun.spawn(cmd, { cwd: REPO, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const killer = setTimeout(() => proc.kill('SIGKILL'), 120_000);
+ try {
+ const [stdout, stderr, status] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { out: `${stdout}${stderr}`, status };
+ } finally { clearTimeout(killer); }
+}
+
+async function ok(argv: string[]): Promise<string> {
+ const result = await run(argv);
+ if (result.status !== 0) throw new Error(`${argv.join(' ')} exited ${result.status}:\n${result.out}`);
+ return result.out;
+}
+
+const write = (files: Record<string, string>) => {
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(checkout, path, '..'), { recursive: true }); writeFileSync(join(checkout, path), content); }
+};
+const commit = async (message: string) => { await ok(['git', '-C', checkout, 'add', '-A']); await ok(['git', '-C', checkout, 'commit', '-qm', message]); };
+
+/** The guide's placeholders for values that differ per run. */
+function normalize(text: string): string {
+ return text.split(checkout).join('~/brain/notes')
+ .replace(/\b[0-9a-f]{64}\b/g, '<hash>')
+ .replace(/\b[0-9a-f]{7,40}\b(?= gbrain:)/g, '<commit>')
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, '<id>')
+ .replace(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?Z?)?/g, '<time>')
+ .replace(/\b\d+ h old\b/g, '<n> h old');
+}
+
+function tokens(command: string): string[] {
+ return [...command.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(m => m[1] ?? m[2] ?? m[3]!);
+}
+
+interface Step { command: string; expected: string[] }
+
+/** The normalized real output of every step, kept in .context/ (never committed) for updating the guide. */
+function writeDump(dump: string[]): void {
+ mkdirSync(join(REPO, '.context'), { recursive: true });
+ writeFileSync(join(REPO, '.context', 'fence-walkthrough-output.txt'), dump.join('\n'));
+}
+
+function walkthrough(): Step[] {
+ const guide = readFileSync(join(REPO, 'docs', 'guides', 'repair.md'), 'utf8');
+ const start = guide.indexOf('<a id="fences"></a>');
+ const section = guide.slice(start, guide.indexOf('\n## ', start));
+ const steps: Step[] = [];
+ for (const block of section.matchAll(/```console\n([\s\S]*?)```/g)) {
+ for (const raw of block[1]!.split('\n')) {
+ const line = raw.trim();
+ if (!line) continue;
+ if (line.startsWith('$ ')) steps.push({ command: line.slice(2), expected: [] });
+ else steps.at(-1)!.expected.push(line);
+ }
+ }
+ return steps;
+}
+
+test('docs/guides/repair.md "Fences": every command runs and prints every line the guide shows; one command to green, two to repaired', async () => {
+ const steps = walkthrough();
+ expect(steps.length).toBeGreaterThanOrEqual(6);
+
+ // A source synced once by the older gbrain.
+ mkdirSync(checkout, { recursive: true });
+ await ok(['git', 'init', '-q', checkout]);
+ await ok(['git', '-C', checkout, 'config', 'user.name', 'Example']);
+ await ok(['git', '-C', checkout, 'config', 'user.email', '[email protected]']);
+ // A hardened checkout (what `gbrain sources harden notes` installs), so the Git effect commits each repaired file.
+ writeFileSync(join(checkout, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');
+ chmodSync(join(checkout, '.git', 'hooks', 'post-commit'), 0o755);
+ write({ 'people/alice-example.md': '---\ntitle: Alice Example\n---\nAlice Example runs product at widget-co.\n' });
+ await commit('init');
+ await ok(['gbrain', 'init', '--pglite', '--no-embedding']);
+ await ok(['gbrain', 'config', 'set', 'self_upgrade.mode', 'off']);
+ await ok(['gbrain', 'config', 'set', 'models.fence_repair', 'openai:gpt-5.5']);
+ await ok(['gbrain', 'sources', 'add', 'notes', '--path', checkout]);
+ await ok(['gbrain', 'sync', '--source', 'notes', '--no-pull']);
+
+ // The generator's notes block the source under the pre-upgrade behavior.
+ await ok(['gbrain', 'config', 'set', 'sync.holds', 'fail']);
+ write({
+ 'meetings/2026-04-03.md': `---\ntitle: Widget launch sync\n---\nNotes from the launch sync.\n\n${FB}\n${FH}\n| 1 | widget-co ships the launch build | milestone | 0.8 | private | medium | 2026-04-03 | | meeting notes | |\n`,
+ 'companies/acme-example.md': `---\ntitle: acme-example\n---\nA company we track.\n\n${FB}\n${ACME_ROW}\n${FBE}\n`,
+ 'projects/widget-launch.md': `---\ntitle: Widget launch\n---\nThe launch plan.\n\n${T}\n${TH}\n| 1 | The launch slips a week | bet | Alice Example | 0.6 | 2026-04 | standup |\n${TE}\n`,
+ });
+ await commit('notes from the generator');
+ const blocked = await run(['gbrain', 'sync', '--source', 'notes', '--no-pull']);
+ expect(blocked.status).not.toBe(0);
+ await ok(['gbrain', 'config', 'unset', 'sync.holds']);
+
+ const counts = { toGreen: 0, toRepaired: 0 };
+ let synced = false;
+ const dump: string[] = [];
+ let lastHash: string | undefined;
+ for (const step of steps) {
+ const argv = tokens(step.command).map(token => token === '<hash>' ? lastHash ?? '<no preview hash yet>' : token.replace('~/brain/notes', checkout));
+ const out = await ok(argv);
+ if (argv[0] === 'gbrain' && argv[1] !== 'post-upgrade' && !synced) { counts.toGreen++; synced = argv[1] === 'sync'; }
+ if (argv[1] === 'repair' && argv[2] === 'fences') counts.toRepaired++;
+ lastHash = [...out.matchAll(/--expect ([0-9a-f]{64})/g)].at(-1)?.[1] ?? lastHash;
+ const shown = normalize(out);
+ dump.push(`$ ${step.command}\n${shown}`);
+ for (const line of step.expected) {
+ if (!shown.includes(line)) {
+ writeDump(dump);
+ throw new Error(`"$ ${step.command}" no longer prints the guide's line:\n ${line}\nActual output:\n${shown}`);
+ }
+ }
+ }
+ writeDump(dump);
+ expect(counts).toEqual({ toGreen: 1, toRepaired: 2 });
+ expect(requests).toBe(1);
+ expect((await run(['git', '-C', checkout, 'status', '--porcelain'])).out).toBe('');
+}, 600_000);