Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(backlinks): check-backlinks fix refuses a managed worktree once, dry run included (#5341)

garrytaneb1449767690
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 2c9fd7967b..2591fffc15 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.
-- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law). Repair-inserted references land as UNDATED rows (`- Referenced in [Title](../path)`) in a dedicated `## Referenced by` section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. `insertBacklinkEntry(content, bodyStart, entry)` never touches bytes before `bodyStart`, locates the timeline boundary via `findTimelineSplitIndex` (existing timeline sentinels take precedence over bare `## Timeline`/`## History` headings), appends to an existing `## Referenced by` section or creates one above the timeline, and is CRLF-tolerant; `insertTimelineEntry` is an alias for existing import sites. `buildBacklinkEntry(sourceTitle, sourcePath)` takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency).
+- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law). `fix` (and `fix --dry-run`) refuses once, before the scan, when the directory is a managed canonical worktree (`isManagedFilesystemPath` from `src/core/persistence/filesystem-guard.ts`, the predicate `assertManagedFilesystemWrite` uses), instead of skipping every page one by one; `check` still runs (#5341). Repair-inserted references land as UNDATED rows (`- Referenced in [Title](../path)`) in a dedicated `## Referenced by` section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. `insertBacklinkEntry(content, bodyStart, entry)` never touches bytes before `bodyStart`, locates the timeline boundary via `findTimelineSplitIndex` (existing timeline sentinels take precedence over bare `## Timeline`/`## History` headings), appends to an existing `## Referenced by` section or creates one above the timeline, and is CRLF-tolerant; `insertTimelineEntry` is an alias for existing import sites. `buildBacklinkEntry(sourceTitle, sourcePath)` takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency).
- `src/commands/book-mirror.ts` — `gbrain book-mirror --chapters-dir <path> --slug <slug> [flags]`. Submits N read-only subagent jobs (one per chapter; `allowed_tools: ['get_page', 'search']`), waits for all via `waitForCompletion`, reads each child's `job.result`, assembles two-column markdown CLI-side, writes a single operator-trust `put_page` to `media/books/<slug>-personalized.md`. Trust narrowing happens at the tool-allowlist layer (subagents can't call put_page) so untrusted EPUB content can't prompt-inject any people page. Cost-estimate prompt before launching; refuses to spend in non-TTY without `--yes`. Per-chapter idempotency keys (`book-mirror:<slug>:ch-<N>`) for retry-friendly re-runs. Final publication captures its page revision and request UUID before providers run; a pending or failed receipt prevents a false written report and preserves the request ID for inspection. Partial-failure: assembles completed chapters + a `## Failed chapters` section. Pinned by `test/book-mirror.test.ts` (9 cases).
diff --git a/src/commands/backlinks.ts b/src/commands/backlinks.ts
index 90c785b063..020f967834 100644
--- a/src/commands/backlinks.ts
+++ b/src/commands/backlinks.ts
@@ -391,6 +391,19 @@ export async function runBacklinksCore(opts: BacklinksOpts): Promise<BacklinksRe
if (!existsSync(opts.dir)) {
throw new Error(`Directory not found: ${opts.dir}`);
}
+ // #5341: the fixer writes markdown files directly, which a managed
+ // canonical worktree refuses page by page. Refuse once, before the scan,
+ // and for --dry-run too, so a preview never claims fixes that cannot apply.
+ if (opts.action === 'fix') {
+ const { isManagedFilesystemPath } = await import('../core/persistence/filesystem-guard.ts');
+ if (isManagedFilesystemPath(opts.dir)) {
+ throw new Error(
+ `check-backlinks fix is not supported on a managed canonical worktree (${opts.dir}): it writes markdown files directly, ` +
+ 'and managed brains accept file changes only through the persistence coordinator. ' +
+ '`gbrain check-backlinks check` still reports the gaps; the graph extractor already stores these links as edges.',
+ );
+ }
+ }
// findBacklinkGaps is a sync double-walk of the brain dir. On 50K-page
// brains that can take seconds — heartbeat so agents see we're working.
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 3f3fa04581..03033e91cc 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -40,10 +40,13 @@ export function hasFilesystemPublication(path: string): boolean {
const held = active.getStore();
return held?.active === true && held.roots.some(root => encloses(root, path));
}
-export function assertManagedFilesystemWrite(path: string): void {
- const managed = hasManagedRootMarker(path) || registeredManagedRoots().some(root => encloses(root, path) || encloses(path, root))
+/** True when the path is inside (or encloses) a managed canonical worktree. */
+export function isManagedFilesystemPath(path: string): boolean {
+ return hasManagedRootMarker(path) || registeredManagedRoots().some(root => encloses(root, path) || encloses(path, root))
|| [...managedRoots.values()].some(roots => [...roots].some(root => encloses(root, path) || encloses(path, root)));
- if (managed && !hasFilesystemPublication(path)) throw new OperationError('writer_coordinator_required',
+}
+export function assertManagedFilesystemWrite(path: string): void {
+ if (isManagedFilesystemPath(path) && !hasFilesystemPublication(path)) throw new OperationError('writer_coordinator_required',
'This file belongs to a managed canonical worktree.', 'Submit the change through the persistence coordinator.');
}
/** Invalidate inherited async contexts before the owner releases the kernel lock. */
diff --git a/test/backlinks-managed-refusal.test.ts b/test/backlinks-managed-refusal.test.ts
new file mode 100644
index 0000000000..9d5ec638ba
--- /dev/null
+++ b/test/backlinks-managed-refusal.test.ts
@@ -0,0 +1,49 @@
+/**
+ * #5341: `check-backlinks fix` writes markdown directly, which a managed
+ * canonical worktree refuses page by page ("Fixed 0 ... Skipped 32 page(s)")
+ * while --dry-run claimed every fix would apply. The fixer now refuses once,
+ * before the scan, for real runs and dry runs alike; `check` still works.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runBacklinksCore } from '../src/commands/backlinks.ts';
+
+const roots: string[] = [];
+function brain(managed: boolean): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-backlinks-'));
+ roots.push(root);
+ mkdirSync(join(root, 'people'));
+ mkdirSync(join(root, 'meetings'));
+ writeFileSync(join(root, 'people', 'alice-example.md'), '---\ntitle: Alice Example\n---\n# Alice Example\n');
+ writeFileSync(join(root, 'meetings', 'planning.md'), '---\ntitle: Planning\n---\nMet [Alice Example](../people/alice-example.md).\n');
+ if (managed) writeFileSync(join(root, '.gbrain-managed'), JSON.stringify({ managed: true, version: 1 }));
+ return root;
+}
+
+afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+describe('#5341 check-backlinks on a managed canonical worktree', () => {
+ test('fix and fix --dry-run refuse once with a mode-level error; the page is untouched', async () => {
+ const root = brain(true);
+ for (const dryRun of [false, true]) {
+ await expect(runBacklinksCore({ action: 'fix', dir: root, dryRun })).rejects.toThrow('not supported on a managed canonical worktree');
+ }
+ expect(readFileSync(join(root, 'people', 'alice-example.md'), 'utf8')).not.toContain('planning');
+ });
+
+ test('check still reports the gaps on a managed worktree', async () => {
+ const result = await runBacklinksCore({ action: 'check', dir: brain(true) });
+ expect(result.gaps_found).toBe(1);
+ });
+
+ test('an unmanaged brain still fixes', async () => {
+ const root = brain(false);
+ const result = await runBacklinksCore({ action: 'fix', dir: root });
+ expect(result.fixed).toBe(1);
+ expect(readFileSync(join(root, 'people', 'alice-example.md'), 'utf8')).toContain('planning');
+ });
+});