Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): foreign_writers check; owner-path guard modes and gbrain sources guard (PR B parts 4-5)
garrytanbe3ae6be4a47
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bfd01a71ee..4a37857a63 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2153 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2104 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2+src/commands/sources.ts 2107 ratchet +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/src/commands/doctor/checks/foreign-writers.ts b/src/commands/doctor/checks/foreign-writers.tsnew file mode 100644index 0000000000..1ed875d40a--- /dev/null+++ b/src/commands/doctor/checks/foreign-writers.ts@@ -0,0 +1,351 @@+/**+ * PR B Part 4 (docs/designs/REFRESH_WRITE_BARRIER.md): `foreign_writers`. Every registered source checkout on this host,+ * managed worktrees included, deduplicated by git common dir: each commit created locally in the covered window that+ * gbrain's commit ledger (src/core/git/commit-ledger.ts) does not name was made by another writer, and every page file+ * left untracked or modified that gbrain is not about to commit is listed with its age. Read-only.+ *+ * - Locally created commits come from the reflogs (logs/HEAD and logs/refs/heads/* in the common dir, and each+ * worktrees/<name>/logs/HEAD). Porcelain creations (commit, amend, initial, cherry-pick, revert, rebase picks,+ * pull --rebase picks, am) are looked up by their new sha. Other ref moves (update-ref after commit-tree) read the+ * old..new range: a single-parent commit whose committer time is within 10 minutes of the entry is a candidate; a range+ * that cannot be read is reported unknown. Merges, fast-forwards, pulls, resets, checkouts, branch moves and clones+ * are excluded.+ * - Reflog entries older than the ledger's start (or its oldest retained line after rotation) are uncovered, never+ * foreign. A commit matching an open intent (parent = head_before, message digest, within 60 s) is unconfirmed: a+ * warn, never written back.+ * - Dirty page files: untracked and unstaged files under the source roots, leaving out paths with a queued or running+ * git effect and paths in the write-through pending ledger; age is the file's mtime.+ */+import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { join, relative, resolve, sep } from 'node:path';+import { execFileSync } from '../../../core/spawn.ts';+import type { Check } from '../../doctor.ts';+import { readLedger, messageDigest } from '../../../core/git/commit-ledger.ts';+import { readPendingWriteThrough } from '../../../core/git/commit-push.ts';+import { GUARD_ENFORCE_MARKER, GUARD_HOOK, OWNER_HOOKS_DIR } from '../../../core/git/commit-guard.ts';+import { existingHostIdFor } from '../../../core/persistence/identity.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { doctorVerify, infoCheck } from '../check-fix.ts';+import { SCAN_REPORT_RESERVE_MS } from '../budget.ts';+import { sourceRoots } from './git-convergence.ts';+import type { BrainEngine } from '../../../core/engine.ts';++export const PLUMBING_WINDOW_S = 10 * 60;+export const UNCONFIRMED_WINDOW_MS = 60_000;+export const FOREIGN_DIRTY_WARN_MS = 30 * 60_000;+const MAX_REFLOG_ENTRIES = 5_000;+const MAX_RANGE_COMMITS = 500;+const GIT_TIMEOUT_MS = 5_000;+const MAX_ROOTS = 50;+const MAX_LISTED = 20;+const ZERO = /^0+$/;++export type ForeignKind = 'plain' | 'amend' | 'rewrite' | 'plumbing';+export interface ForeignCommit { sha: string; kind: ForeignKind; guard_bypassed: boolean; ref: string; time: string; subject: string; committer: string; checkout: string }+interface Candidate { sha: string; kind: ForeignKind; ref: string; time: number; gitDir: string | null; checkout: string }+interface Checkout { top: string; gitDir: string; source_ids: string[]; roots: string[] }+interface Repo { common: string; checkouts: Map<string, Checkout> }+interface Reflog { file: string; ref: string; gitDir: string | null }+interface Entry { old: string; next: string; time: number; message: string }++function git(root: string, args: string[], input?: string): string | null {+ try { return execFileSync('git', ['-C', root, ...args], { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'], input, timeout: GIT_TIMEOUT_MS, maxBuffer: 32 * 1024 * 1024 }).toString(); }+ catch { return null; }+}+const canonical = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };++/** Porcelain creation kind of a reflog message; 'excluded' for moves that create nothing locally; 'other' for the rest. */+export function classifyReflogMessage(message: string): ForeignKind | 'excluded' | 'other' {+ if (/^commit \(merge\)/.test(message)) return 'excluded';+ if (/^commit \(amend\):/.test(message)) return 'amend';+ if (/^commit( \(initial\))?:/.test(message)) return 'plain';+ if (/^commit \([^)]*\):/.test(message)) return 'rewrite';+ if (/^(cherry-pick|revert)( \([^)]*\))?:/.test(message)) return 'rewrite';+ if (/^(rebase|pull --rebase)( -[im])? \((pick|reword|edit|squash|fixup)\)/.test(message)) return 'rewrite';+ if (/^am:/.test(message)) return 'rewrite';+ if (/^(merge|pull|reset|checkout|branch|clone|rebase|fetch|push|update by push|initial pull|switch)\b/i.test(message)) return 'excluded';+ return 'other';+}++/** The newest MAX_REFLOG_ENTRIES lines of one reflog, oldest first. */+function readReflog(file: string): Entry[] {+ let text: string;+ try { text = readFileSync(file, 'utf8'); } catch { return []; }+ const lines = text.split('\n').filter(Boolean);+ const out: Entry[] = [];+ for (const line of lines.slice(-MAX_REFLOG_ENTRIES)) {+ const m = /^([0-9a-f]+) ([0-9a-f]+) .*? (\d+) [+-]\d{4}(?:\t(.*))?$/.exec(line);+ if (m) out.push({ old: m[1]!, next: m[2]!, time: Number(m[3]), message: m[4] ?? '' });+ }+ return out;+}++function reflogs(common: string): Reflog[] {+ const out: Reflog[] = [{ file: join(common, 'logs', 'HEAD'), ref: 'HEAD', gitDir: common }];+ try {+ for (const name of readdirSync(join(common, 'worktrees')).sort()) {+ out.push({ file: join(common, 'worktrees', name, 'logs', 'HEAD'), ref: `worktrees/${name}/HEAD`, gitDir: join(common, 'worktrees', name) });+ }+ } catch { /* no linked worktrees */ }+ const walk = (dir: string, ref: string) => {+ let names: string[];+ try { names = readdirSync(dir).sort(); } catch { return; }+ for (const name of names) {+ const path = join(dir, name);+ try { if (statSync(path).isDirectory()) walk(path, `${ref}/${name}`); else out.push({ file: path, ref: `${ref}/${name}`, gitDir: null }); } catch { /* raced away */ }+ }+ };+ walk(join(common, 'logs', 'refs', 'heads'), 'refs/heads');+ return out;+}++/** The checkout a worktree git dir belongs to (its gitdir file names <top>/.git), else the main checkout. */+function checkoutOf(repo: Repo, gitDir: string | null): string {+ if (gitDir) for (const c of repo.checkouts.values()) if (canonical(c.gitDir) === canonical(gitDir)) return c.top;+ if (gitDir && gitDir !== repo.common) {+ try { return resolve(readFileSync(join(gitDir, 'gitdir'), 'utf8').trim(), '..'); } catch { /* fall through */ }+ }+ return [...repo.checkouts.values()][0]!.top;+}++async function repositories(engine: BrainEngine): Promise<Repo[]> {+ const roots = new Map<string, string[]>(await sourceRoots(engine));+ try {+ const hostId = existingHostIdFor(engine);+ if (hostId) {+ for (const row of await engine.executeRaw<{ local_path: string; source_id: string | null }>(+ `SELECT h.local_path, s.source_id FROM persistence_host_bindings h LEFT JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id+ WHERE h.host_id=$1::uuid AND h.local_path IS NOT NULL ORDER BY h.local_path`, [hostId])) {+ const ids = roots.get(row.local_path) ?? [];+ if (row.source_id && !ids.includes(row.source_id)) ids.push(row.source_id);+ roots.set(row.local_path, ids);+ }+ }+ } catch { /* an embedded engine without a host id, or a brain without the managed tables */ }+ const repos = new Map<string, Repo>();+ for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {+ if (!existsSync(root)) continue;+ const out = git(root, ['rev-parse', '--show-toplevel', '--absolute-git-dir'])?.split('\n');+ if (!out?.[0] || !out[1]) continue;+ const [top, gitDir] = [out[0], out[1]];+ let common = gitDir;+ try { common = resolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim()); } catch { /* the main git dir */ }+ const key = canonical(common);+ const repo = repos.get(key) ?? { common, checkouts: new Map() };+ const rel = relative(canonical(top), canonical(root)).split(sep).join('/');+ const entry = repo.checkouts.get(top) ?? { top, gitDir, source_ids: [], roots: [] };+ entry.source_ids.push(...ids.filter(id => !entry.source_ids.includes(id)));+ entry.roots.push(rel.startsWith('..') ? '' : rel);+ repo.checkouts.set(top, entry);+ repos.set(key, repo);+ }+ return [...repos.values()];+}++/** Paths gbrain is about to commit: queued or running git effects, absolute. */+async function pendingEffectPaths(engine: BrainEngine): Promise<Set<string>> {+ let hostId: string | null = null;+ try { hostId = existingHostIdFor(engine); } catch { /* embedded engine without an id */ }+ const out = new Set<string>();+ try {+ const rows = await engine.executeRaw<{ rel: string; source_path: string | null; worktree_path: string | null }>(+ `SELECT e.data->>'relative_path' AS rel, s.local_path AS source_path, h.local_path AS worktree_path+ FROM persistence_effects e LEFT JOIN sources s ON s.id=e.source_id+ LEFT JOIN persistence_host_bindings h ON h.worktree_id=e.worktree_id AND h.host_id=$1::uuid+ WHERE e.kind='git' AND e.state IN ('queued','running') AND e.data ? 'relative_path' LIMIT 10000`, [hostId]);+ for (const row of rows) for (const base of [row.source_path, row.worktree_path]) if (base && row.rel) out.add(canonical(resolve(base, row.rel)));+ } catch { /* no persistence tables */ }+ return out;+}++interface Dirty { path: string; checkout: string; state: 'untracked' | 'modified' | 'deleted' | 'unmerged'; age_ms: number }++function dirtyFiles(c: Checkout, skip: Set<string>, now: number): Dirty[] | null {+ const specs = c.roots.includes('') ? ['.'] : c.roots.map(r => `:(literal)${r}`);+ const raw = git(c.top, ['status', '--porcelain=v2', '-z', '--untracked-files=all', '--', ...specs]);+ if (raw === null) return null;+ const pending = new Set(readPendingWriteThrough(c.top).map(e => canonical(join(c.top, e.path))));+ const fields = raw.split('\0');+ const out: Dirty[] = [];+ for (let i = 0; i < fields.length; i++) {+ const f = fields[i]!;+ let path: string | null = null;+ let state: Dirty['state'] = 'modified';+ if (f.startsWith('? ')) { path = f.slice(2); state = 'untracked'; }+ else if (f.startsWith('1 ') || f.startsWith('2 ')) {+ const parts = f.split(' ');+ const y = parts[1]![1];+ path = parts.slice(f.startsWith('1 ') ? 8 : 9).join(' ');+ if (f.startsWith('2 ')) i++;+ if (y === '.') continue;+ if (y === 'D') state = 'deleted';+ } else if (f.startsWith('u ')) { path = f.split(' ').slice(10).join(' '); state = 'unmerged'; }+ if (!path) continue;+ const abs = join(c.top, path);+ const key = canonical(abs);+ if (skip.has(key) || pending.has(key)) continue;+ let age = 0;+ try { age = Math.max(0, now - lstatSync(abs).mtimeMs); } catch { /* a deleted file has no mtime */ }+ out.push({ path, checkout: c.top, state, age_ms: Math.round(age) });+ }+ return out;+}++function enforceGuardSince(gitDir: string | null): number | null {+ if (!gitDir) return null;+ const hook = join(gitDir, OWNER_HOOKS_DIR, GUARD_HOOK);+ try { return readFileSync(hook, 'utf8').includes(GUARD_ENFORCE_MARKER) ? statSync(hook).mtimeMs : null; } catch { return null; }+}++interface RepoReport {+ common: string; checkouts: string[]; ledger: boolean; window_from: string | null; ledger_start: string | null; oldest_reflog: string | null;+ uncovered: number; foreign: ForeignCommit[]; unconfirmed: ForeignCommit[]; unknown: { ref: string; old: string; new: string; time: string }[];+}++function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial: boolean } {+ const ledger = readLedger(repo.common);+ const ledgered = new Set<string>();+ const intents: { head_before: string | null; msg: string; t: number }[] = [];+ let start: number | null = null;+ for (const r of ledger) {+ if (r.e === 'start') start = Date.parse(r.t);+ else if (r.e === 'commit') ledgered.add(r.sha);+ else intents.push({ head_before: r.head_before, msg: r.msg_sha256, t: Date.parse(r.t) });+ }+ if (start === null && ledger.length) start = Date.parse(ledger[0]!.t);+ const startSec = start === null ? null : Math.floor(start / 1000);+ const report: RepoReport = { common: repo.common, checkouts: [...repo.checkouts.keys()], ledger: ledger.length > 0, window_from: null,+ ledger_start: start === null ? null : new Date(start).toISOString(), oldest_reflog: null, uncovered: 0, foreign: [], unconfirmed: [], unknown: [] };+ const anyTop = [...repo.checkouts.keys()][0]!;+ const candidates = new Map<string, Candidate>();+ let oldest: number | null = null;+ let partial = false;+ for (const log of reflogs(repo.common)) {+ if (Date.now() > deadline) { partial = true; break; }+ const checkout = checkoutOf(repo, log.gitDir);+ const entries = readReflog(log.file);+ const firstLedgered = entries.findIndex(e => ledgered.has(e.next));+ for (const [index, entry] of entries.entries()) {+ oldest = oldest === null ? entry.time : Math.min(oldest, entry.time);+ if (ZERO.test(entry.next)) continue;+ const kind = classifyReflogMessage(entry.message);+ if (kind === 'excluded') continue;+ // Reflog times are whole seconds: in the start's own second only entries after this log's first ledgered one are covered.+ const covered = startSec !== null && (entry.time > startSec || (entry.time === startSec && firstLedgered >= 0 && index > firstLedgered));+ if (!covered) { report.uncovered++; continue; }+ if (kind !== 'other') {+ if (!candidates.has(entry.next)) candidates.set(entry.next, { sha: entry.next, kind, ref: log.ref, time: entry.time, gitDir: log.gitDir, checkout });+ continue;+ }+ if (Date.now() > deadline) { partial = true; break; }+ const range = git(anyTop, ['log', '--format=%H %P %ct', '-n', String(MAX_RANGE_COMMITS), ...(ZERO.test(entry.old) ? [entry.next] : [`${entry.old}..${entry.next}`]), '--']);+ if (range === null) { report.unknown.push({ ref: log.ref, old: entry.old, new: entry.next, time: new Date(entry.time * 1000).toISOString() }); continue; }+ for (const line of range.split('\n').filter(Boolean)) {+ const parts = line.split(' ');+ const ct = Number(parts.at(-1));+ if (parts.length !== 3 || Math.abs(ct - entry.time) > PLUMBING_WINDOW_S) continue;+ if (!candidates.has(parts[0]!)) candidates.set(parts[0]!, { sha: parts[0]!, kind: 'plumbing', ref: log.ref, time: entry.time, gitDir: log.gitDir, checkout });+ }+ }+ }+ report.oldest_reflog = oldest === null ? null : new Date(oldest * 1000).toISOString();+ const from = start === null ? null : Math.max(start, (oldest ?? 0) * 1000);+ report.window_from = from === null ? null : new Date(from).toISOString();+ const open = [...candidates.values()].filter(c => !ledgered.has(c.sha));+ for (let i = 0; i < open.length && !partial; i += 200) {+ if (Date.now() > deadline) { partial = true; break; }+ const batch = open.slice(i, i + 200);+ const out = git(anyTop, ['log', '--no-walk', '--ignore-missing', '--stdin', '--format=%H%x00%P%x00%ct%x00%cn <%ce>%x00%s%x00%B%x1e'], batch.map(c => c.sha).join('\n') + '\n');+ if (out === null) { partial = true; break; }+ const meta = new Map<string, string[]>();+ for (const rec of out.split('\x1e')) {+ const f = rec.replace(/^\n/, '').split('\0');+ if (f.length >= 6 && f[0]) meta.set(f[0], f);+ }+ for (const c of batch) {+ const f = meta.get(c.sha);+ if (!f) { report.unknown.push({ ref: c.ref, old: '', new: c.sha, time: new Date(c.time * 1000).toISOString() }); continue; }+ const parents = f[1]!.split(' ').filter(Boolean);+ if (parents.length > 1) continue;+ const ct = Number(f[2]);+ const guard = c.kind === 'plain' ? enforceGuardSince(c.gitDir) : null;+ const commit: ForeignCommit = { sha: c.sha, kind: c.kind, guard_bypassed: guard !== null && guard <= ct * 1000, ref: c.ref, time: new Date(ct * 1000).toISOString(), subject: f[4]!, committer: f[3]!, checkout: c.checkout };+ const digest = messageDigest(f[5]!);+ const matched = intents.some(t => t.head_before === (parents[0] ?? null) && t.msg === digest && ct * 1000 >= t.t - 1000 && ct * 1000 - t.t <= UNCONFIRMED_WINDOW_MS);+ (matched ? report.unconfirmed : report.foreign).push(commit);+ }+ }+ report.foreign.sort((a, b) => b.time.localeCompare(a.time));+ return { report, partial };+}++const label = (c: ForeignCommit) => c.guard_bypassed ? 'plain (guard bypassed)' : c.kind;+const ago = (ms: number) => ms >= 3_600_000 ? `${Math.round(ms / 3_600_000)}h` : `${Math.round(ms / 60_000)}m`;++async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('foreign_writers');+ const engine = connectedEngine(ctx);+ const repos = await repositories(engine);+ if (!repos.length) {+ checks.push(infoCheck('foreign_writers', 'Not applicable: no registered source on this host is a Git checkout, so there are no commits to attribute (the database is the record on a repo-less brain).', 'not_applicable'));+ return checks;+ }+ const deadline = (ctx.entryDeadlineAt ?? Number.POSITIVE_INFINITY) - SCAN_REPORT_RESERVE_MS;+ const now = Date.now();+ const skip = await pendingEffectPaths(engine);+ const reports: RepoReport[] = [];+ const dirty: Dirty[] = [];+ let partial = false;+ for (const repo of repos) {+ if (Date.now() > deadline) { partial = true; break; }+ const scanned = scanRepo(repo, deadline);+ reports.push(scanned.report);+ partial ||= scanned.partial;+ for (const c of repo.checkouts.values()) {+ if (Date.now() > deadline) { partial = true; break; }+ const found = dirtyFiles(c, skip, now);+ if (found === null) partial = true; else dirty.push(...found);+ }+ }+ dirty.sort((a, b) => b.age_ms - a.age_ms);+ const foreign = reports.flatMap(r => r.foreign).sort((a, b) => b.time.localeCompare(a.time));+ const unconfirmed = reports.flatMap(r => r.unconfirmed);+ const unknown = reports.flatMap(r => r.unknown);+ const old = dirty.filter(d => d.age_ms > FOREIGN_DIRTY_WARN_MS);+ const details = {+ window: reports.map(r => ({ common: r.common, from: r.window_from, to: new Date(now).toISOString(), ledger_start: r.ledger_start, oldest_reflog: r.oldest_reflog, uncovered: r.uncovered, ledger: r.ledger })),+ foreign, unconfirmed, unknown, dirty: dirty.slice(0, MAX_LISTED), dirty_count: dirty.length, dirty_warn_after_minutes: FOREIGN_DIRTY_WARN_MS / 60_000, partial,+ };+ const scope = `${repos.length} repositor${repos.length === 1 ? 'y' : 'ies'}${partial ? ' (partial: the scan stopped at doctor\'s budget)' : ''}`;+ if (foreign.length) {+ const newest = foreign[0]!;+ const line = `Commit ${newest.sha.slice(0, 12)} (${label(newest)}, "${newest.subject}", ${newest.time}) in ${newest.checkout} was not made by gbrain; route that writer through gbrain git commit-push or a page write`;+ checks.push({ name: 'foreign_writers', status: 'fail', details,+ message: `${foreign.length} commit(s) in ${scope} were made by a writer outside gbrain: ${foreign.slice(0, 5).map(c => `${c.sha.slice(0, 12)} ${label(c)} by ${c.committer}`).join(', ')}${foreign.length > 5 ? ', ...' : ''}. ${line}.`,+ fix: { ask_user: true, argv: ['git', '-C', newest.checkout, 'show', '--stat', newest.sha], consent: [], actor: 'user', requires_exclusive: false,+ why: `${line}. A commit made around gbrain skips its writer lock and leaves files no import recorded; finding and rerouting the writer (a cron, a script, an agent running plain git) is the user's call.`,+ user_message: `A writer outside gbrain committed ${newest.sha.slice(0, 12)} ("${newest.subject}") in ${newest.checkout} at ${newest.time}. Which job or agent makes these commits, so it can be switched to gbrain git commit-push or a page write?`,+ verify: doctorVerify('foreign_writers') } });+ return checks;+ }+ if (unconfirmed.length || unknown.length || old.length) {+ const parts = [+ unconfirmed.length ? `${unconfirmed.length} commit(s) match a gbrain intent whose commit line is missing (a crash between git commit and the ledger append): ${unconfirmed.slice(0, 5).map(c => c.sha.slice(0, 12)).join(', ')}; they are not written back to the ledger` : '',+ unknown.length ? `${unknown.length} ref move(s) whose commits could not be read: ${unknown.slice(0, 5).map(u => `${u.ref} -> ${u.new.slice(0, 12)}`).join(', ')}` : '',+ old.length ? `${old.length} page file(s) have been untracked or modified for more than ${FOREIGN_DIRTY_WARN_MS / 60_000} minutes with no gbrain commit pending: ${old.slice(0, 5).map(d => `${d.path} (${d.state}, ${ago(d.age_ms)})`).join(', ')}${old.length > 5 ? ', ...' : ''}` : '',+ ].filter(Boolean);+ checks.push({ name: 'foreign_writers', status: 'warn', details,+ message: `No foreign commit in ${scope}, but: ${parts.join('; ')}. A file another writer left there becomes a drift hold or rides along with the next commit made without paths.` });+ return checks;+ }+ checks.push({ name: 'foreign_writers', status: 'ok', details,+ message: `Every locally created commit in the covered window of ${scope} is in gbrain's commit ledger, and no page file waits uncommitted for more than ${FOREIGN_DIRTY_WARN_MS / 60_000} minutes.${reports.some(r => !r.ledger) ? ' A repository gbrain has not committed in yet has no ledger, so its window is empty.' : ''}` });+ return checks;+}++export const foreignWritersEntry: DoctorEntry = {+ name: 'foreign_writers',+ emits: ['foreign_writers'],+ run: runForeignWriters,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 68e826c79c..b3da83367b 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -102,6 +102,7 @@ import { runtimeBuildSkewEntry } from './checks/runtime-build-skew.ts';import { cliSocketRefusalsEntry } from './checks/cli-socket-refusals.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { gitWriterEntry } from './checks/git-writer.ts';+import { foreignWritersEntry } from './checks/foreign-writers.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';import { autoChronicleEntry } from './checks/auto-chronicle.ts';@@ -271,6 +272,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [commitNotifierEntry,gitConvergenceEntry,gitWriterEntry,+ foreignWritersEntry,decideHealthEntry,unlinkedFactsEntry,edgeValidityEntry,diff --git a/src/commands/sources-guard.ts b/src/commands/sources-guard.tsnew file mode 100644index 0000000000..154c2d74d7--- /dev/null+++ b/src/commands/sources-guard.ts@@ -0,0 +1,100 @@+/**+ * `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce] [--json]` (PR B Part 5,+ * docs/designs/REFRESH_WRITE_BARRIER.md): the commit guard on a managed source's canonical worktree. Trusted local CLI+ * only (no operation exposes it), on the worktree's registered owner host, and install/uninstall run under the+ * worktree's native writer lock. The hook goes in a hooks directory private to that worktree, so a person's own linked+ * checkout of the same repository is not guarded. `--mode enforce` also refuses cherry-pick, revert, rebase and+ * sequencer commits: in a managed worktree only the owner commits.+ */+import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';+import { acquireWorktree, getWorktreeBinding, managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { existingHostIdFor } from '../core/persistence/identity.ts';+import { installOwnerGuard, ownerGuardStatus, uninstallOwnerGuard, type GuardMode, type OwnerGuardStatus } from '../core/git/commit-guard.ts';++const USAGE = 'gbrain sources guard <source> --install|--uninstall|--status [--mode enforce] [--json]';+const LOCK_WAIT_MS = 10_000;++export interface SourcesGuardOptions { sourceId: string; action: 'install' | 'uninstall' | 'status'; mode: GuardMode }+export type SourcesGuardResult = OwnerGuardStatus & { source_id: string; action: SourcesGuardOptions['action']; changed: boolean };++export function parseSourcesGuardArgs(args: string[]): SourcesGuardOptions {+ const positional: string[] = [];+ const actions: SourcesGuardOptions['action'][] = [];+ let mode: GuardMode = 'default';+ for (let i = 0; i < args.length; i++) {+ const arg = args[i]!;+ if (arg === '--json') continue;+ if (arg === '--install' || arg === '--uninstall' || arg === '--status') { actions.push(arg.slice(2) as SourcesGuardOptions['action']); continue; }+ if (arg === '--mode') {+ const value = args[++i];+ if (value !== 'enforce' && value !== 'default') throw opError('invalid_params', `--mode takes enforce (or default); got ${value ?? 'nothing'}.`, `Usage: ${USAGE}`);+ mode = value;+ continue;+ }+ if (arg.startsWith('-')) throw opError('invalid_params', `Unknown flag ${arg}.`, `Usage: ${USAGE}`);+ positional.push(arg);+ }+ if (positional.length !== 1) throw opError('invalid_params', 'Name exactly one source.', `Usage: ${USAGE}`);+ if (actions.length > 1) throw opError('invalid_params', 'Pass one of --install, --uninstall or --status.', `Usage: ${USAGE}`);+ const action = actions[0] ?? 'status';+ if (mode === 'enforce' && action !== 'install') throw opError('invalid_params', '--mode applies to --install only.', `Usage: ${USAGE}`);+ return { sourceId: positional[0]!, action, mode };+}++/** The owner check `sources refresh` makes: this process's host identity, read without minting, owns the worktree. */+async function ownedBinding(engine: BrainEngine, sourceId: string) {+ if (!await managedPersistenceEnabled(engine)) {+ throw opError('invalid_params', `This brain is not managed, so source ${sourceId} has no canonical worktree to guard.`,+ 'In an unmanaged checkout, gbrain git guard --install (run inside the checkout) installs the opt-in guard.');+ }+ const hostId = existingHostIdFor(engine);+ const binding = await getWorktreeBinding(engine, sourceId, hostId);+ if (!binding) {+ throw opError('invalid_params', `Source ${sourceId} has no claimed canonical worktree.`,+ `Check the source with gbrain sources writer status --source ${sourceId} --json; an unmanaged checkout takes gbrain git guard --install.`);+ }+ if (binding.owner_host_id !== hostId || !binding.local_path) {+ throw opError('permission_denied', `Only the registered owner host (${binding.owner_host_id}) of source ${sourceId} may guard its worktree; this process has ${hostId ? `host identity ${hostId}` : 'no host identity'}.`,+ `Run it on the owner host with the HOME or GBRAIN_HOME its writer uses; check the owner with gbrain sources writer status ${sourceId}. Nothing was changed.`);+ }+ return { ...binding, local_path: binding.local_path };+}++export async function sourcesGuard(engine: BrainEngine, opts: SourcesGuardOptions): Promise<SourcesGuardResult> {+ const binding = await ownedBinding(engine, opts.sourceId);+ if (opts.action === 'status') return { ...ownerGuardStatus(binding.local_path), source_id: opts.sourceId, action: 'status', changed: false };+ const lock = await acquireWorktree(binding, LOCK_WAIT_MS, undefined, engine);+ if (!lock) {+ throw opError('writer_busy', `Source ${opts.sourceId}'s worktree writer lock stayed busy for ${LOCK_WAIT_MS / 1000}s.`,+ 'A page write or a refresh holds the worktree; retry once it finishes. Nothing was changed.', { retryable: true });+ }+ try {+ const result = opts.action === 'install' ? installOwnerGuard(binding.local_path, opts.mode) : uninstallOwnerGuard(binding.local_path);+ return { ...result, source_id: opts.sourceId, action: opts.action };+ } finally { await lock.release(); }+}++function describe(r: SourcesGuardResult): string {+ const state = r.installed ? `installed (${r.mode} mode)` : 'not installed';+ const lines = [`Commit guard on source ${r.source_id} (${r.worktree}): ${state}${r.action !== 'status' ? (r.changed ? ', changed' : ', already current') : ''}.`,+ `Effective hooks path: ${r.hooks_path}`];+ if (r.foreign.length) lines.push(`Another tool's hooks live there: ${r.foreign.join(', ')}.`);+ return lines.join('\n');+}++export async function runSourcesGuard(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ if (args.includes('--help') || args.includes('-h')) { console.log(`Usage: ${USAGE}`); return; }+ try {+ const result = await sourcesGuard(engine, parseSourcesGuardArgs(args));+ console.log(json ? JSON.stringify(result) : describe(result));+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ const env = toAgentError(error, { transport: 'cli', command: 'sources guard', render: cliRenderContext() });+ console.log(json ? JSON.stringify(env) : `Refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);+ setCliExitVerdict(error.code === 'invalid_params' ? 2 : 1);+ }+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex f1824294f2..ff77eea437 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1924,6 +1924,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);case 'git-gap': return (await import('./sources-git-gap.ts')).runSourcesGitGap(engine, rest);case 'host-repo': return (await import('./sources-host-repo.ts')).runHostRepo(engine, rest);+ case 'guard': return (await import('./sources-guard.ts')).runSourcesGuard(engine, rest);case 'reindex': return (await import('./sources-reindex.ts')).runSourcesReindex(engine, rest);case 'canonical': return (await import('./sources-canonical.ts')).runSourcesCanonical(engine, rest);case 'archive': return runArchive(engine, rest);@@ -2028,6 +2029,8 @@ Subcommands:set-sync <id> <on|off> [--dry-run] [--expect <on|off>] Include or exclude the source from automatic sync (config.syncEnabled).host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]Managed brains: host an empty source in a new bare repository with a gbrain-owned worktree; it becomes git-canonical.+ guard <id> [--install [--mode enforce] | --uninstall | --status] [--json]+ Managed brains, owner host: the commit guard on the source's worktree only.refresh <id> [--dry-run] [--wait-drain <s>] [--fetch-timeout-ms <ms>] [--resume|--abandon] [--json]Managed brains: drain writes to the source's worktree, fast-forwardit to its upstream (git merge --ff-only) and sync every source bounddiff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.tsindex 002a6371f4..0ae197d221 100644--- a/src/core/bootstrap/repo.ts+++ b/src/core/bootstrap/repo.ts@@ -441,7 +441,7 @@ function secretScanOrThrow(workspaceDir: string, relFiles: string[]): void {* scan (NEVER bypassed), commits. No-op when a commit already exists and the* tree is clean.*/-async function ensureWorkspaceCommit(runner: ExecRunner, workspaceDir: string): Promise<void> {+export async function ensureWorkspaceCommit(runner: ExecRunner, workspaceDir: string): Promise<void> {const head = await runner(['git', '-C', workspaceDir, 'rev-parse', '--verify', 'HEAD']);const hasCommit = head.code === 0;const statusRes = await runner(['git', '-C', workspaceDir, 'status', '--porcelain']);diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex e56e6d3c0a..c27cb81a94 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -229,6 +229,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['dirty_age','commits_outside_source_root','quarantined_changes',+ // PR B: commits in a source checkout that gbrain's commit ledger does not name, and page files left uncommitted (doctor/checks/foreign-writers.ts).+ 'foreign_writers','takes_count','takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).diff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsindex 9b1f2309ea..fe5bbbed49 100644--- a/src/core/git/commit-guard.ts+++ b/src/core/git/commit-guard.ts@@ -11,8 +11,11 @@* bypasses it for one command with GBRAIN_COMMIT_GUARD=off. Off unless the* brain opts in with gbrain git guard --install; CLI-only.*/-import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join, relative } from 'node:path';+import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';+import { execFileSync } from '../spawn.ts';+import { gitChildEnv } from '../git-env.ts';+import { GIT_ENV } from '../git-transport.ts';import { ensureExcluded, resolveHooksDir } from '../brain-repo-durability.ts';import { assertManagedFilesystemWrite } from '../persistence/filesystem-guard.ts';import { opError } from '../ops/contract.ts';@@ -22,16 +25,22 @@ export const GUARD_HOOK = 'prepare-commit-msg';export const GUARD_BANNER = '# gbrain commit guard (prepare-commit-msg)';export const GUARD_BYPASS_ENV = 'GBRAIN_COMMIT_GUARD';-export function renderGuardHook(): string {+/** PR B Part 5: the owner-path guard's mode line; enforce mode keeps only the merge exemption. */+export const GUARD_ENFORCE_MARKER = '# mode: enforce (managed worktree: only its owner commits; cherry-pick, revert, rebase and sequencer commits are refused too)';+export type GuardMode = 'default' | 'enforce';++export function renderGuardHook(mode: GuardMode = 'default'): string {+ const enforce = mode === 'enforce';return `#!/usr/bin/env bash${GUARD_BANNER}-# LOCAL + untracked: installed by gbrain git guard --install, removed by --uninstall.+${enforce ? `${GUARD_ENFORCE_MARKER}+# LOCAL + untracked: installed by gbrain sources guard <source> --install --mode enforce, removed by --uninstall.` : '# LOCAL + untracked: installed by gbrain git guard --install, removed by --uninstall.'}# Refuses commits in this shared brain checkout (--no-verify included) that did not come# through gbrain git commit-push or gbrain's own page writes, which hold the commit lock.# A person can bypass it for one command: ${GUARD_BYPASS_ENV}=off git <command>[ "\${${GUARD_BYPASS_ENV}:-}" = off ] && exit 0[ "\${2:-}" = merge ] && exit 0-for _op in MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer; do+for _op in ${enforce ? 'MERGE_HEAD' : 'MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer'}; do[ -e "$(git rev-parse --git-path "$_op")" ] && exit 0done_lock="$(git rev-parse --path-format=absolute --git-path ${COMMIT_LOCK_NAME} 2>/dev/null || true)"@@ -91,3 +100,124 @@ export function uninstallGuard(repo: string): GuardStatus & { changed: boolean }rmSync(status.hook, { force: true });return { ...guardStatus(root), changed: true };}++// ── PR B Part 5: the owner-path guard (gbrain sources guard) ───────────────++/** The hooks directory private to one worktree; core.hooksPath points there through `git config --worktree`. */+export const OWNER_HOOKS_DIR = 'gbrain-hooks';+const GBRAIN_HOOK = /^# gbrain (commit guard|brain-durability post-commit hook)/m;++export interface OwnerGuardStatus {+ installed: boolean;+ mode: GuardMode | null;+ /** Hooks of other tools at the effective hooks path (pointing the worktree elsewhere would silence them). */+ foreign: string[];+ hook: string;+ /** Where git looks for this worktree's hooks now (core.hooksPath honored). */+ hooks_path: string;+ worktree: string;+ worktree_config: boolean;+}++function gitIn(root: string, args: string[]): { code: number; stdout: string; stderr: string } {+ try {+ return { code: 0, stdout: execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000, env: gitChildEnv({ ...GIT_ENV, LC_ALL: 'C' }) }).toString().trim(), stderr: '' };+ } catch (error) {+ const e = error as { status?: number; stdout?: Buffer; stderr?: Buffer };+ return { code: e.status ?? -1, stdout: e.stdout?.toString().trim() ?? '', stderr: e.stderr?.toString().trim() ?? String(error) };+ }+}++function gitMust(root: string, args: string[]): string {+ const r = gitIn(root, args);+ if (r.code !== 0) throw opError('git_unavailable', `git ${args.join(' ')} failed in ${root}: ${r.stderr.slice(0, 300) || `exit ${r.code}`}`, `Check that git works in ${root} (git status), then rerun. Nothing else was changed.`);+ return r.stdout;+}++function ownerPaths(worktree: string) {+ const root = checkoutRoot(worktree);+ const gitDir = gitMust(root, ['rev-parse', '--absolute-git-dir']);+ const common = resolve(root, gitMust(root, ['rev-parse', '--git-common-dir']));+ const own = join(gitDir, OWNER_HOOKS_DIR);+ const effective = resolve(root, gitMust(root, ['rev-parse', '--path-format=absolute', '--git-path', 'hooks']));+ return { root, gitDir, common, own, hook: join(own, GUARD_HOOK), effective };+}++/** Active hooks at `dir` that gbrain did not write (sample files and gbrain's own hooks are not foreign). */+function foreignHooks(dir: string): string[] {+ let names: string[];+ try { names = readdirSync(dir); } catch { return []; }+ return names.filter(name => {+ if (name.endsWith('.sample')) return false;+ const path = join(dir, name);+ try { if (!statSync(path).isFile()) return false; return !GBRAIN_HOOK.test(readFileSync(path, 'utf8')); } catch { return false; }+ }).map(name => join(dir, name));+}++export function ownerGuardStatus(worktree: string): OwnerGuardStatus {+ const p = ownerPaths(worktree);+ const body = existsSync(p.hook) ? readFileSync(p.hook, 'utf8') : null;+ const installed = p.effective === p.own && !!body?.includes(GUARD_BANNER);+ return { installed, mode: installed ? (body!.includes(GUARD_ENFORCE_MARKER) ? 'enforce' : 'default') : null,+ foreign: p.effective === p.own ? (body !== null && !body.includes(GUARD_BANNER) ? [p.hook] : []) : foreignHooks(p.effective),+ hook: p.hook, hooks_path: p.effective, worktree: p.root, worktree_config: gitIn(p.root, ['config', '--type=bool', '--get', 'extensions.worktreeConfig']).stdout === 'true' };+}++/**+ * Point only this worktree's core.hooksPath at a hooks directory inside its own git dir and write the guard there. With+ * linked worktrees present, extensions.worktreeConfig is enabled first (moving core.bare / core.worktree into the main+ * worktree's config.worktree, as git requires), so a sibling worktree keeps its own hooks. Refuses, changing nothing, on+ * git older than 2.31 or another tool's hook at the effective hooks path. The caller holds the worktree's writer lock.+ */+export function installOwnerGuard(worktree: string, mode: GuardMode): OwnerGuardStatus & { changed: boolean } {+ const p = ownerPaths(worktree);+ const [maj, min] = gitVersion(p.root);+ if (maj < 2 || (maj === 2 && min < 31)) {+ throw opError('git_unavailable', `The owner-path guard needs git 2.31 or later (found ${maj}.${min}).`, 'Upgrade git on the owner host, then rerun. Nothing was changed.');+ }+ const before = ownerGuardStatus(p.root);+ if (before.foreign.length) {+ throw opError('git_unavailable', `Another tool's hook(s) live at this worktree's hooks path ${p.effective}: ${before.foreign.join(', ')}; gbrain does not replace or silence them.`,+ 'Move those hooks aside or chain them yourself, then rerun gbrain sources guard <source> --install. Nothing was changed.', { detail: before.foreign.join(',') });+ }+ const script = renderGuardHook(mode);+ const current = existsSync(p.hook) ? readFileSync(p.hook, 'utf8') : null;+ let changed = false;+ if (current !== script) {+ mkdirSync(p.own, { recursive: true });+ writeFileSync(p.hook, script);+ chmodSync(p.hook, 0o755);+ changed = true;+ }+ if (p.effective !== p.own) {+ const linked = gitMust(p.root, ['worktree', 'list', '--porcelain']).split('\n').filter(l => l.startsWith('worktree ')).length > 1;+ if (linked && !before.worktree_config) enableWorktreeConfig(p.root, p.common);+ gitMust(p.root, ['config', '--worktree', 'core.hooksPath', p.own]);+ changed = true;+ }+ return { ...ownerGuardStatus(p.root), changed };+}++/** git's documented upgrade: core.bare=true and core.worktree move from the common config to the main worktree's config.worktree. */+function enableWorktreeConfig(root: string, common: string): void {+ const config = join(common, 'config');+ const main = join(common, 'config.worktree');+ for (const key of ['core.bare', 'core.worktree']) {+ const value = gitIn(root, ['config', '--file', config, '--get', key]);+ if (value.code !== 0 || (key === 'core.bare' && value.stdout !== 'true')) continue;+ gitMust(root, ['config', '--file', main, key, value.stdout]);+ gitMust(root, ['config', '--file', config, '--unset', key]);+ }+ gitMust(root, ['config', '--file', config, 'extensions.worktreeConfig', 'true']);+}++export function uninstallOwnerGuard(worktree: string): OwnerGuardStatus & { changed: boolean } {+ const p = ownerPaths(worktree);+ let changed = false;+ if (existsSync(p.hook) && readFileSync(p.hook, 'utf8').includes(GUARD_BANNER)) { rmSync(p.hook, { force: true }); changed = true; }+ if (gitIn(p.root, ['config', '--worktree', '--get', 'core.hooksPath']).stdout === p.own) {+ gitMust(p.root, ['config', '--worktree', '--unset', 'core.hooksPath']);+ changed = true;+ }+ return { ...ownerGuardStatus(p.root), changed };+}diff --git a/test/doctor-foreign-writers.test.ts b/test/doctor-foreign-writers.test.tsnew file mode 100644index 0000000000..602cbaa025--- /dev/null+++ b/test/doctor-foreign-writers.test.ts@@ -0,0 +1,286 @@+/**+ * PR B Part 4: doctor `foreign_writers`. One repository gets seven commit kinds (door, commit-push, in-memory merge, plain+ * git commit, --amend, plumbing commit-tree + update-ref, and a hooks-path bypass under the enforce guard); only plain,+ * amend, bypass and plumbing are flagged, while effect-worker, replay, bootstrap and sync auto-init commits, an upstream+ * fast-forward and the merge are not. Real git repositories in temp dirs, in-memory PGLite.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { createHash, randomUUID } from 'node:crypto';+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { foreignWritersEntry, classifyReflogMessage, type ForeignCommit } from '../src/commands/doctor/checks/foreign-writers.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { commitAndPush, commitPathsLocked, notePending } from '../src/core/git/commit-push.ts';+import { installOwnerGuard } from '../src/core/git/commit-guard.ts';+import { ledgerFiles, readLedger, recordIntent } from '../src/core/git/commit-ledger.ts';+import { commitThroughDoor } from '../src/core/persistence/git-door.ts';+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';+import { createSyncBaselineCommit } from '../src/core/sync-git.ts';+import { defaultRunner, ensureWorkspaceCommit } from '../src/core/bootstrap/repo.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-foreign-writers-'));+const ID = { GIT_AUTHOR_NAME: 'Alice Example', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Alice Example', GIT_COMMITTER_EMAIL: '[email protected]' };++function git(cwd: string, args: string[], env: Record<string, string> = {}): string {+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...ID, ...env } }).toString().trim();+}+function write(root: string, rel: string, body: string): void {+ mkdirSync(join(root, rel, '..'), { recursive: true });+ writeFileSync(join(root, rel), body);+}+function identity(root: string): void {+ git(root, ['config', 'user.email', ID.GIT_AUTHOR_EMAIL]);+ git(root, ['config', 'user.name', ID.GIT_AUTHOR_NAME]);+ git(root, ['config', 'commit.gpgsign', 'false']);+}+let n = 0;+function checkout(): { bare: string; work: string; other: string } {+ const tag = n++;+ const bare = join(dir, `origin-${tag}.git`), work = join(dir, `work-${tag}`), other = join(dir, `other-${tag}`);+ git(dir, ['init', '-q', '--bare', '-b', 'main', bare]);+ git(dir, ['clone', '-q', bare, work]);+ identity(work);+ write(work, 'notes/seed.md', 'seed\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'seed']); git(work, ['push', '-q', '-u', 'origin', 'main']);+ git(dir, ['clone', '-q', bare, other]);+ identity(other);+ return { bare, work, other };+}+async function register(id: string, path: string): Promise<void> {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);+}+const run = async (): Promise<Check> => ((await foreignWritersEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext)) as Check[])[0]!;+const head = (root: string) => git(root, ['rev-parse', 'HEAD']);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});+beforeEach(async () => { await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'"); });++test('registered and categorized', () => {+ expect(DOCTOR_CHECK_REGISTRY.some(entry => entry.emits.includes('foreign_writers'))).toBe(true);+ expect(categorizeCheck('foreign_writers')).toBe('brain');+});++test('reflog messages classify into porcelain kinds, exclusions and other ref moves', () => {+ expect(classifyReflogMessage('commit: x')).toBe('plain');+ expect(classifyReflogMessage('commit (initial): x')).toBe('plain');+ expect(classifyReflogMessage('commit (amend): x')).toBe('amend');+ expect(classifyReflogMessage('commit (merge): x')).toBe('excluded');+ for (const m of ['cherry-pick: x', 'revert: Revert "x"', 'rebase (pick): x', 'rebase -i (squash): x', 'pull --rebase (pick): x', 'am: x']) expect(classifyReflogMessage(m)).toBe('rewrite');+ for (const m of ['merge origin/main: Fast-forward', 'pull: Fast-forward', 'reset: moving to HEAD~1', 'checkout: moving from a to b', 'branch: Created from HEAD', 'clone: from x', 'rebase (finish): returning to refs/heads/main']) expect(classifyReflogMessage(m)).toBe('excluded');+ expect(classifyReflogMessage('')).toBe('other');+ expect(classifyReflogMessage('gbrain: custom move')).toBe('other');+});++test('seven commit kinds: only plain, amend, the guard bypass and plumbing are foreign', async () => {+ const { work, other } = checkout();+ await register('notes', join(work, 'notes'));++ write(work, 'notes/door.md', 'door\n');+ const door = await commitThroughDoor(work, [{ path: join(work, 'notes/door.md'), planned: createHash('sha256').update('door\n').digest('hex') }]);+ expect(door).toBe(head(work));+ write(work, 'notes/push.md', 'push\n');+ const pushed = commitPathsLocked(work, ['notes/push.md'], 'commit-push page', { lockWaitMs: 1000 });++ write(work, 'notes/plain.md', 'plain\n');+ git(work, ['add', 'notes/plain.md']); git(work, ['commit', '-q', '-m', 'plain commit']);+ const plain = head(work);+ git(work, ['commit', '-q', '--amend', '-m', 'plain commit, amended']);+ const amend = head(work);++ installOwnerGuard(work, 'enforce');+ write(work, 'notes/effect.md', 'effect\n');+ const effect = (await commitGitTargets(join(work, 'notes'), ['effect.md'])).get('effect.md');+ expect(effect).toEqual({ git: 'committed' });+ const effectSha = head(work);+ write(work, 'notes/push2.md', 'push two\n');+ commitPathsLocked(work, ['notes/push2.md'], 'commit-push under the enforce guard', { lockWaitMs: 1000 });++ // Replay + in-memory merge: the remote already has a local commit's patch, so the local commits replay onto it.+ write(work, 'notes/same.md', 'same patch\n');+ commitPathsLocked(work, ['notes/same.md'], 'same patch here', { lockWaitMs: 1000 });+ write(other, 'notes/same.md', 'same patch\n');+ git(other, ['add', '-A']); git(other, ['commit', '-q', '-m', 'same patch there']); git(other, ['push', '-q']);+ write(work, 'notes/after.md', 'after\n');+ commitPathsLocked(work, ['notes/after.md'], 'after the patch', { lockWaitMs: 1000 });+ const published = commitAndPush({ repo: work, pushOnly: true });+ expect(published.checkout).toBe('advanced');+ const ledger = readLedger(join(work, '.git'));+ expect(ledger.some(r => r.e === 'commit' && r.writer === 'replay')).toBe(true);+ const merge = ledger.find(r => r.e === 'commit' && r.writer === 'merge');+ expect(merge && git(work, ['log', '--no-walk', '--format=%P', merge.sha]).split(' ').length).toBe(2);++ // Upstream fast-forward of a commit made minutes ago on another clone.+ git(other, ['pull', '-q', '--ff-only']);+ write(other, 'notes/upstream.md', 'upstream\n');+ git(other, ['add', '-A']); git(other, ['commit', '-q', '-m', 'upstream work']); git(other, ['push', '-q']);+ git(work, ['fetch', '-q']); git(work, ['merge', '-q', '--ff-only', '@{u}']);++ // The enforce guard refuses --no-verify; a hooks-path override bypasses every hook.+ write(work, 'notes/bypass.md', 'bypass\n');+ git(work, ['add', 'notes/bypass.md']);+ const before = head(work);+ expect(() => git(work, ['commit', '-q', '--no-verify', '-m', 'refused'])).toThrow(/gbrain commit guard/);+ expect(head(work)).toBe(before);+ git(work, ['-c', 'core.hooksPath=/dev/null', 'commit', '-q', '-m', 'hooks off']);+ const bypass = head(work);++ const tree = git(work, ['rev-parse', 'HEAD^{tree}']);+ const plumbing = git(work, ['commit-tree', tree, '-p', 'HEAD', '-m', 'plumbing']);+ git(work, ['update-ref', 'refs/heads/main', plumbing]);++ const check = await run();+ expect(check.status).toBe('fail');+ const foreign = (check.details!.foreign as ForeignCommit[]);+ const bySha = Object.fromEntries(foreign.map(c => [c.sha, c]));+ expect(new Set(Object.keys(bySha))).toEqual(new Set([plain, amend, bypass, plumbing]));+ expect(bySha[plain]).toMatchObject({ kind: 'plain', guard_bypassed: false });+ expect(bySha[amend]!.kind).toBe('amend');+ expect(bySha[bypass]).toMatchObject({ kind: 'plain', guard_bypassed: true });+ expect(bySha[plumbing]!.kind).toBe('plumbing');+ for (const sha of [door!, pushed!, effectSha]) expect(bySha[sha]).toBeUndefined();+ expect(check.message).toContain('was not made by gbrain; route that writer through gbrain git commit-push or a page write');+ expect(check.message).toContain('plain (guard bypassed)');+ expect(check.fix).toMatchObject({ ask_user: true });+ expect((check.details!.window as Array<{ uncovered: number }>)[0]!.uncovered).toBeGreaterThan(0);+}, 120_000);++test('bootstrap and sync auto-init commits are ledgered, not foreign', async () => {+ const synced = join(dir, `auto-init-${n++}`);+ mkdirSync(synced);+ git(synced, ['init', '-q', '-b', 'main']);+ write(synced, 'note.md', 'auto\n');+ createSyncBaselineCommit(synced);+ const boot = join(dir, `bootstrap-${n++}`);+ mkdirSync(boot);+ git(boot, ['init', '-q', '-b', 'main']);+ identity(boot);+ write(boot, 'SOUL.md', 'an agent workspace\n');+ await ensureWorkspaceCommit(defaultRunner, boot);+ await register('auto', synced);+ await register('boot', boot);+ expect(readLedger(join(synced, '.git')).some(r => r.e === 'commit' && r.writer === 'sync_init')).toBe(true);+ expect(readLedger(join(boot, '.git')).some(r => r.e === 'commit' && r.writer === 'bootstrap')).toBe(true);+ const check = await run();+ expect(check.details!.foreign).toEqual([]);+ expect(check.status).toBe('ok');+}, 60_000);++test('commits before the ledger starts are uncovered, never foreign', async () => {+ const { work } = checkout();+ write(work, 'notes/early.md', 'early\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'before gbrain']);+ await register('early', join(work, 'notes'));+ let check = await run();+ expect(check.status).toBe('ok');+ expect(check.message).toContain('has no ledger');+ await new Promise(r => setTimeout(r, 1100));+ write(work, 'notes/later.md', 'later\n');+ commitPathsLocked(work, ['notes/later.md'], 'gbrain starts the ledger', { lockWaitMs: 1000 });+ check = await run();+ expect(check.status).toBe('ok');+ expect((check.details!.window as Array<{ uncovered: number; from: string | null }>)[0]!.uncovered).toBeGreaterThan(0);+}, 60_000);++test('an open intent matching a commit is unconfirmed (warn) and never written back', async () => {+ const { work } = checkout();+ await register('crash', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ recordIntent(work, { writer: 'commit_push', head_before: head(work), message: 'crashed before the ledger line' });+ write(work, 'notes/b.md', 'b\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'crashed before the ledger line']);+ const sha = head(work);+ const before = readLedger(join(work, '.git')).length;+ const check = await run();+ expect(check.status).toBe('warn');+ expect((check.details!.unconfirmed as ForeignCommit[]).map(c => c.sha)).toEqual([sha]);+ expect(check.details!.foreign).toEqual([]);+ expect(readLedger(join(work, '.git')).length).toBe(before);+ // A different message is not covered by the intent.+ recordIntent(work, { writer: 'commit_push', head_before: head(work), message: 'one message' });+ write(work, 'notes/c.md', 'c\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'another message']);+ expect((await run()).status).toBe('fail');+}, 60_000);++test('after rotation the ledgered commits in commit-ledger.1.jsonl still count', async () => {+ const { work } = checkout();+ await register('rotated', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'ledgered before rotation', { lockWaitMs: 1000 });+ const files = ledgerFiles(join(work, '.git'));+ renameSync(files.current, files.rotated);+ write(work, 'notes/b.md', 'b\n');+ commitPathsLocked(work, ['notes/b.md'], 'ledgered after rotation', { lockWaitMs: 1000 });+ expect(readFileSync(files.current, 'utf8')).not.toContain('"e":"start"');+ const check = await run();+ expect(check.status).toBe('ok');+ expect(check.details!.foreign).toEqual([]);+}, 60_000);++test('a commit in a linked worktree is read from its own HEAD log', async () => {+ const { work } = checkout();+ await register('main', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ await new Promise(r => setTimeout(r, 1100));+ const linked = join(dir, `linked-${n++}`);+ git(work, ['worktree', 'add', '-q', '--detach', linked]);+ write(linked, 'notes/side.md', 'side\n');+ git(linked, ['add', '-A']); git(linked, ['commit', '-q', '-m', 'detached side commit']);+ const sha = head(linked);+ const check = await run();+ expect(check.status).toBe('fail');+ const found = (check.details!.foreign as ForeignCommit[]).find(c => c.sha === sha)!;+ expect(found.ref).toMatch(/^worktrees\/.+\/HEAD$/);+ expect(found.checkout).toBe(git(linked, ['rev-parse', '--show-toplevel']));+}, 60_000);++test('dirty page files: old ones warn; a pending git effect and a write-through pending path are left out', async () => {+ const { work } = checkout();+ await register('dirty', join(work, 'notes'));+ const old = (Date.now() - 2 * 3_600_000) / 1000;+ for (const name of ['stray.md', 'effect.md', 'pending.md']) { write(work, `notes/${name}`, `${name}\n`); utimesSync(join(work, 'notes', name), old, old); }+ appendFileSync(join(work, 'notes/seed.md'), 'edited\n');+ utimesSync(join(work, 'notes/seed.md'), old, old);+ write(work, 'outside.md', 'not under the source root\n');+ utimesSync(join(work, 'outside.md'), old, old);+ notePending(work, ['notes/pending.md']);+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='dirty'");+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ const [request] = await tx.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,+ intent_bytes,terminal_reservation) VALUES ('local_cli','test',$1::uuid,'put_page','dirty',$2::uuid,'effect','x','{}'::jsonb,0,0) RETURNING id::text`, [randomUUID(), incarnation]);+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,state,source_id,source_incarnation) VALUES ($1::uuid,'git',$2::text::jsonb,'queued','dirty',$3::uuid)`,+ [request!.id, JSON.stringify({ relative_path: 'effect.md', slug: 'effect' }), incarnation]);+ });+ const check = await run();+ expect(check.status).toBe('warn');+ const paths = (check.details!.dirty as Array<{ path: string; state: string; age_ms: number }>).map(d => d.path).sort();+ expect(paths).toEqual(['notes/seed.md', 'notes/stray.md']);+ expect(check.details!.dirty_count).toBe(2);+ expect(check.message).toContain('notes/stray.md (untracked, 2h)');+}, 60_000);++test('repo-less: no source checkout is a Git repository, so the check is not applicable', async () => {+ const plain = mkdtempSync(join(dir, 'plain-'));+ write(plain, 'note.md', 'no git here\n');+ await register('plain', plain);+ const check = await run();+ expect(check).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'not_applicable' });+});