Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.15.0 fix: checkpoint retries, tool discovery, and durability (#5194)
Sina Matian7ef5165b4962
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 1ba25df157..f7987c25c5 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex bd5cae1ea9..e4d12f4a4d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 9eba330261..3cc6a54190 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.13.0 -->+<!-- gbrain-runbook-stamp: 0.60.15.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c75715710..0c6fa299b0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,23 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.15.0] - 2026-09-30++**Import retries pick up edited files, contacts recover from expired sync tokens, and published skills work without extra tool annotations.** This release also filters machine-authored transcript entries and makes lock, push, and health checks report the right outcome.++### Fixed+- **Retried imports recheck the files you have now.** A checkpoint left by an interrupted or partly failed import no longer hides later edits, including edits with preserved timestamps. Unchanged pages still avoid re-chunking and embedding; retrying a large import does repeat file reads and content-hash checks.+- **Claude Code transcript imports exclude metadata and explicitly non-human user text.** Root metadata and compact-summary markers are honored, while assistant text and tool placeholders keep their existing behavior. Legacy records without a structured origin remain compatible; this is not a strict human-origin requirement.+- **Quoted installation paths no longer make a live autopilot lock look abandoned.** Script paths containing spaces are recognized without accepting similarly named scripts.+- **Brain-repository pushes recognize work already saved remotely.** When a push reports failure, the helper checks fresh evidence from the exact branch at every configured push destination for the intended commit before reporting local-only work. Rebase conflicts and genuinely rejected pushes still fail; unrelated working-tree edits are not automatically stashed.+- **`gbrain schema lint --with-db` works with or without a pack name.** The flag can appear before or after the name, and unsupported lint arguments are rejected rather than mistaken for a pack.+- **Sync health checks respect `syncEnabled: false`.** Deliberately disabled sources no longer raise stale-sync warnings. Their scheduled non-sync maintenance still runs and remains covered by cycle-health checks.+- **Legacy host-repository MCP skills can omit optional `tools:` metadata.** Valid skills without that field inherit the caller's available brain tools, filtered by grants and the effective tool surface. Explicit tool lists still narrow the inventory, `tools: []` stays empty, and invalid metadata does not receive the fallback. Canonical shared-skill requirements and server authorization are unchanged.+- **Google contacts recover from HTTP 400 sync-token expiry.** A documented expiry reason or recognized expiry message triggers a full contacts refresh and stores a new token. Other bad requests still fail instead of silently resetting sync state.++### To take advantage of v0.60.15.0+If upgrading from before v0.51.0.0, first follow the [coordinated writer upgrade guide](skills/migrations/v0.51.0.0.md). From v0.51.0.0, run `gbrain upgrade` and restart long-running GBrain processes. Retry a partly failed import normally; deleting its checkpoint is no longer necessary to pick up edits. The next contacts sync recovers an expired token automatically. For existing hardened, unmanaged brain repositories, run `gbrain sources harden <source-id>` to refresh the generated push helper and local hook; managed worktrees retain the persistence outbox as their Git writer. This patch adds no migration, credentials, permission grants, or automatic-capture requirement beyond v0.51.0.0.+## [0.60.13.0] - 2026-09-30**Two things: your agent can now ask search for the whole conversation, section or page around each hit in the same call (off by default until a matched study shows it helps), and seven correctness fixes land, led by a privacy one: the entity card no longer shows remote agents that a private page links to a public one.**diff --git a/TODOS.md b/TODOS.mdindex 766c5e5db4..637d033cf9 100644--- a/TODOS.md+++ b/TODOS.md@@ -233,8 +233,8 @@ Evidence for each item is in `docs/test-audit/2026-09-29/`.**What:** `src/core/context/turn-context.ts` fetches delta facts with `listFactsSince(..., { limit: 50 })` ordered `created_at DESC` and never sets `has_more` for facts, so more than 50 new facts since the cursor silently drop the OLDEST ones as the page cursor advances past them. **Why:** the v0.50.1.0 pre-landing review found it while simplifying the delta cursor; the fix is an ascending keyset fetch plus `has_more` when the window is full (an engine-options change, so it was left out of the wave). **Effort:** M. **Priority:** P2.- [ ] **P2 — `session_context_state` cursor upsert: GREATEST, not COALESCE.****What:** `src/core/context/session-state.ts` upserts `last_wake_at = COALESCE(EXCLUDED.last_wake_at, …)` (last-writer-wins) while its own doc and `src/mcp/context-pack-handler.ts` assume a monotonic GREATEST, so a `context_pack` push after a `delta` wake can move the shared cursor forward past items the delta never delivered. **Why:** pre-existing, surfaced by the v0.50.1.0 review; fix the SQL to GREATEST and pin it. **Effort:** S. **Priority:** P2.-- [ ] **P3 — `schema lint --with-db` has no test.**- **What:** the v0.50.1.0 wave re-plumbed `gbrain schema lint --with-db` inside `withConnectedEngine` (tier-4 `schema_pack` read + `process.exit(1)` on a missing pack) and nothing in `test/` drives it. **Why:** a regression there would ship green. **Effort:** S. **Priority:** P3.+- [x] **P3 — `schema lint --with-db` has no test.** **Completed:** v0.60.15.0 (2026-09-30). `test/schema-cli-lint-with-db.test.ts` drives isolated CLI subprocesses for DB-plane pack resolution, flag ordering, missing packs, JSON output, invalid arguments, and plain-lint separation (12 cases).+ **What (as filed):** the v0.50.1.0 wave re-plumbed `gbrain schema lint --with-db` inside `withConnectedEngine` (tier-4 `schema_pack` read + `process.exit(1)` on a missing pack) and nothing in `test/` drives it. **Why:** a regression there would ship green. **Effort:** S. **Priority:** P3.- [ ] **P3 — recompute_emotional_weight: pin `pages_recomputed` semantics and the lock-steal path.****What:** `pages_recomputed` now counts evaluated rows (`details.pages_updated` counts writes) and feeds `totals.pages_emotional_weight_recomputed`; the phase moved under `racedTimePhase` with no lock-steal test, and its Postgres SQL twin runs only in the nightly e2e lane. **Why:** the coverage audit flagged both as unpinned behavior changes. **Effort:** S. **Priority:** P3.- [ ] **P3 — minion `put_page` type pin: round-trip fidelity test + delegated-lane wording.**diff --git a/VERSION b/VERSIONindex 442a06ccac..6f886a4f3d 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.13.0+0.60.15.0diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 05fbe75253..e39bf7fbe0 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -25,7 +25,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`.- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`.-- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `genuineUserTurnIndexes` separately records user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.+- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 6274f52553..bbacd56eee 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.- `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`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 61ea96f167..3490c7b4f4 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -23,7 +23,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 48 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig`; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 28ad5f0f4e..026437d0de 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness does not depend on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This rules out three failure classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is not part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the resume checkpoint stays dir-relative per `resumeFilter`'s contract). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex 0cf7264212..61161d45e6 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex ccd64446f1..0e23af0447 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last used by the sync cost-estimator's fetch-first path, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `http.followRedirects=false`, `protocol.file.allow=never`, `protocol.ext.allow=never`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>`. `pullRepo` argv: `git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only` — `durableSsrfFlags()`, not the hardcoded `GIT_SSRF_FLAGS`: identical `-c` flags except `protocol.file.allow` honors the `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` escape hatch. `fetchRemote` uses the same helper. Pinned by `test/git-remote.test.ts` position-anchored guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on ANY `pull --rebase` failure (the catch doesn't classify the cause — it's treated as a conflict) after up to two best-effort `rebase --abort` attempts (each swallows its own failure; `conflict_aborted` is still returned even if rebase state remains), else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike `cloneRepo`, which still uses the hardcoded `GIT_SSRF_FLAGS` and stays strict.-- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.+- `src/core/import-checkpoint.ts` — `loadCheckpoint(path, currentDir)`, `saveCheckpoint(path, cp)`, `resumeFilter(allFiles, dir, completed)`, `clearCheckpoint(path)`, `resolveImportTargetDir(dir)`, and the `ImportCheckpoint` type. Payload: `{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}`; `dir` is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary `runImport` revalidates all current files via `importFile`'s existing content-hash comparison rather than using `resumeFilter`. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged. `loadCheckpoint` returns `null` for missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard. `saveCheckpoint` sorts paths and atomically writes via `.tmp` + `rename()`; save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via `gbrainPath()`, preserving `GBRAIN_HOME` isolation. Pinned by `test/import-checkpoint.test.ts`, `test/import-resume.test.ts`, and `test/import-json-stdout.serial.test.ts`.- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 9d2e1a76b8..b8eca6089d 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).+- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 772548244d..c1edd7c7b7 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -21,7 +21,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/creds/export.ts` — versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's.- `src/core/google/access.ts` — the pluggable Google-access seam: `GoogleAccessProvider` (`getAccessToken`/`forceRefresh`) with `CommandAccessProvider` (`--access command`: any CLI that prints a token — gog/gcloud/a gateway's mint command; parsed as a bare token line or JSON `{token|access_token, expiry|expires_in}`, cached until expiry with a 60s margin, 30s exec timeout, failures = `access_command_failed` carrying the stderr tail) and `EnvAccessProvider` (`--access env`: a live token read from a NAMED env var each call, refreshed outside gbrain; missing = `access_env_missing`). The vault flow's `GoogleTokenProvider` satisfies the same interface. The token command executes only in the locally-running sync (google config keys are unreachable over MCP; same trust class as recipe health-check argv).-- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`).+- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path.- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound`; a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex d8cd20eb8e..afcc9fb5e6 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -25,7 +25,7 @@ Key files:- `src/core/schema-pack/mutate.ts` — 8-step `withMutation` skeleton (bundled-guard → lock → read → mutator → validate → atomic write → audit → invalidate) backs the 11 single-mutation primitives: `addTypeToPack`, `removeTypeFromPack` (with reference check), `updateTypeOnPack`, `addAliasToType`, `removeAliasFromType`, `addPrefixToType`, `removePrefixFromType`, `addLinkTypeToPack`, `removeLinkTypeFromPack`, `setExtractableOnType`, `setExpertRoutingOnType`. Each primitive's business-rule validation + transform is factored into a `build*Mutator(...)` pure `(manifest) => manifest` function shared with `applyMutationsAtomic` (the `schema_apply_mutations` batch entry point) so single-call and batched mutations can never validate differently. `applyMutationsAtomic` locks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and calls `writePackManifest` at MOST ONCE — only after the whole batch checks out — so a batch that fails partway leaves the pack file byte-identical to its pre-batch state. Atomic single write via `.tmp + fsync + rename` — the pack file on disk is NEVER partial, for either a single mutation or a batch. Inline minimal JSON→YAML emitter so YAML packs stay YAML (does NOT preserve comments — pin pack.json if you care about layout).- `src/core/schema-pack/stats.ts` — `runStatsCore(engine, opts)` returns per-source + aggregate page counts + coverage % + `dead_prefixes` (declared prefixes with zero matching pages — agent drilldown signal). Multi-source aware (`sourceIds[]` federated, `sourceId` single, or whole-brain). PGLite + Postgres parity via `executeRaw`. Empty brain → coverage:1.0 (vacuous truth).- `src/core/schema-pack/sync.ts` — `runSyncCore(engine, opts)` chunked UPDATE in 1000-row batches per declared prefix. Concurrent writers never block on a single row >100ms. Write-side scoping via `ctx.sourceId` directly (NOT `sourceScopeOpts`, which inherits OAuth read federation). Idempotent on `--apply` re-run.-- `src/commands/schema.ts` — 14 CLI verbs in the dispatch table: `add-type`, `remove-type`, `update-type`, `add-alias`, `remove-alias`, `add-prefix`, `remove-prefix`, `add-link-type`, `remove-link-type`, `set-extractable`, `set-expert-routing`, `stats`, `sync`, `reload`. `withConnectedEngine` routes `loadConfig()` through the canonical `toEngineConfig()` helper and passes the complete result (`database_url` and `database_path`) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned by `test/schema-cli-database-path.serial.test.ts`.+- `src/commands/schema.ts` — schema CLI dispatch, including `lint [<pack>] [--with-db] [--json]`. Lint parses `--with-db` as a boolean rather than a pack name, accepts it before or after the optional pack, and rejects unknown flags, boolean values, and multiple pack positionals. The DB-backed lane resolves the active pack and runs DB-plane rules on the same connection; plain lint does not run those rules. `test/schema-cli-lint-with-db.test.ts` drives real isolated CLI subprocesses for implicit/explicit packs, JSON output, missing packs, global source flags, invalid arguments, and plain-lint separation. `withConnectedEngine` routes `loadConfig()` through the canonical `toEngineConfig()` helper and passes the complete result (`database_url` and `database_path`) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned by `test/schema-cli-database-path.serial.test.ts`.- `skills/schema-author/SKILL.md` — Agent dispatcher for "evolve the schema pack." Triggers: 15+ phrasings incl. "add a page type", "my brain has untyped pages", "propose new types from my corpus", "backfill page types". Explicit Non-goals callout to `brain-taxonomist` (files one page) and `eiirp` (schema-check during iteration) so agents pick the right surface. 7-phase workflow: brain → assess → propose → apply → sync → verify → commit. Lists every gbrain schema CLI verb + every MCP op the skill uses. `brain_first: exempt` frontmatter. Required conformance sections: Contract, Anti-Patterns, Output Format.- `skills/conventions/schema-evolution.md` — Canonical convention: "when to add a type vs alias vs prefix." Decision tree: <20 pages → don't pack-codify; 20-100 → alias or narrow prefix on existing type; 100+ → first-class type. Don'ts section + "when to remove a type" + "when to commit the pack" all answered in one place.diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex 1f9ef64dcc..3a248dad42 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/skill-brain-first.ts` — pure analyzer. `analyzeSkillBrainFirst(skillPath, content): SkillBrainFirstResult` walks the compliance ladder for every SKILL.md: (1) absent external-lookup pattern → `no_external`; (2) `brain_first: exempt` frontmatter → `exempt_frontmatter`; (3) canonical `> **Convention:** see [conventions/brain-first.md](../...)` callout → `compliant_callout`; (4) explicit `## Phase 1: Brain` heading → `compliant_phase`; (5) first `gbrain search`/`query`/`get_page` reference precedes first external pattern in the BODY (frontmatter stripped) → `compliant_position`; (6) else `missing_brain_first` warn. External pattern set: word-boundary regex over `web_search`, `web_fetch`, `exa`, `perplexity`, `happenstance`, `crustdata`, `captain_api`, `firecrawl`. Position scan is BODY-ONLY so a `tools: [web_search]` frontmatter declaration doesn't false-flag the skill. The 40-name `FORMERLY_HARDCODED_EXEMPT` list is preserved so doctor can emit a "this used to be auto-exempt, declare `brain_first: exempt` if still appropriate" hint. Consumed by 3 surfaces: doctor check, skillify-check item 12, dry-fix MISSING_RULE_PATTERNS.-- `src/core/skill-catalog.ts` — host-repo skill catalog backing the MCP `list_skills` / `get_skill` ops. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `crossReferenceTools(declared, ctx)` splits a skill's declared `tools:` into `usable_tools` vs `unavailable_tools`; `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. Skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). Three ops register in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade): `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.+- `src/core/skill-catalog.ts` — legacy host-repo fallback for MCP `list_skills` / `get_skill`. Canonical schema-version-2 discovery uses [shared brain skills](shared-skills.md); version 1 also uses the canonical compatibility layer when that catalog is active. This module serves the remaining host-catalog fallback, not canonical revision discovery. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `resolveSkillTools` shares list/detail semantics: declared `tools:` narrow the caller's effective inventory via `crossReferenceTools`; valid mapping frontmatter that omits `tools` inherits `availableBrainTools(ctx)` without granting new permissions. Explicit `tools: []` stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates through `disabledOpsForPublishGates` before building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes. `opAllowedForBoundClient` also applies the same operation grants, slug-bound write fences, and degraded-projection policy as dispatch. Pure catalog calls without resolved gates conservatively hide gated operations from remote callers. The list's `tools` remains the declared list (empty when omitted), while `usable_tools` carries the effective inventory. Pinned by `test/skill-catalog-optional-tools.test.ts`. `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). The legacy catalog entrypoints in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade) are: `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.- `src/core/skill-fix-gates.ts` — shared safety primitives for `dry-fix.ts`. `getWorkingTreeStatus(file)` 3-state (`'clean' | 'dirty' | 'not_a_repo'`); `isInsideCodeFence(content, offset)`; `findAfterH1Paragraph(content)` (canonical insertion offset for the auto-inserted Convention callout). Both REPLACE expanders (DRY violations) and the INSERT expander (MISSING_RULE_PATTERNS) consume from here so the install-path refusal and dirty-tree gates apply uniformly. `src/core/dry-fix.ts` re-exports them.diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex b9d081e14a..f7efec6420 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -245,8 +245,10 @@ attached. The catalog (also emitted as structured JSON with `--json`):| `access_env_missing` | The `--access env` variable is unset/blank in this process | Export a live token into it (refresh externally), or switch back to the vault flow |Cursor expiries (`historyId` older than ~a week, calendar/contacts-`syncToken` 410) are handled automatically with bounded re-lists — never-user-facing.+`syncToken` 410, or a contacts HTTP 400 explicitly reporting an expired sync+token) use bounded re-lists automatically. Contacts recovery refreshes its+own cursor without restarting Gmail. Unrelated HTTP 400 errors remain+upstream failures rather than triggering a full re-list.## Custody, privacy, spenddiff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex c2083c6e32..ac37ae5a4f 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -206,7 +206,18 @@ vars — incident-time escape hatches, not everyday knobs.re-derived from the process working directory. Checkpoints written bygbrain include `schema_version: 1`, `owner: "gbrain"`, and`kind: "import"` so downstream tools can validate the contract before- deciding whether to resume.+ deciding whether to resume. For ordinary imports, completed paths record+ progress, not the revision imported: the next run re-reads current files+ and compares their content hashes with the database, including paths listed+ as completed.+ Unchanged files avoid re-import, but resuming a large import still pays+ the directory-walk, file-read, and hash-comparison cost. Checkpoint timestamps+ and file mtimes are not used as proof that content is unchanged.++ [Company-brain ingestion](company-brain-ingestion.md) uses a separate+ protected database checkpoint tied to an immutable approved committed+ manifest. It can skip paths completed for that admission receipt; it does+ not treat the ordinary import checkpoint as approval to read changed files.7. **Sync imports commits, not your working tree.** Files written into thebrain repo but never committed are invisible to incremental sync. Syncdiff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex cddf3fb4a3..52538b6401 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -285,6 +285,11 @@ without writing anything"* — your agent runs `gbrain sync --dry-run`.## Durability: keep a brain repo in sync (auto-harden)+This hardening path applies to unmanaged worktrees. After activating managed+writers, Git effects belong to the persistence outbox; generated legacy push+helpers refuse to run rather than bypass that ownership boundary. See the+[concurrent-write guide](concurrent-writes.md).+A long-lived agent that writes to a knowledge-wiki git repo needs threethings to never lose work: pull before it edits, push every write, and notgo stale while it sits idle. `gbrain sources harden` installs all of that,@@ -316,9 +321,12 @@ What hardening guarantees:rebase conflict is aborted cleanly and flagged for attention, never lefthalf-applied.- **Push is never deferred.** `scripts/brain-commit-push.sh "<msg>" <path>`- commits and pushes atomically and refuses to report success without a- confirmed push. The post-commit hook is a best-effort background fallback;- the helper is the guarantee.+ commits and pushes, and refuses to report success without a successful push+ or confirmation that the exact destination branch at every effective origin+ push URL contains the attempted commit. A rejected push can still succeed when another process+ already pushed that commit; a stale local tracking ref is not confirmation.+ The post-commit hook is a best-effort background fallback; the helper is+ the guarantee.- **No silent staleness.** A 30-minute background pull keeps an idle sessioncurrent. It runs DB-free, so it never contends with a live brain for thePGLite single-writer lock.@@ -328,6 +336,12 @@ probe, `--dry-run` reports what would change, `--json` emits a machinereport, `--all` hardens every source with a remote (same-account only).`--no-harden` on `sources add` opts out of auto-harden.+After upgrading GBrain, run `gbrain sources harden <source-id>` on each machine+with an already-hardened source to refresh its local hook and+`scripts/brain-commit-push.sh`. Upgrading the CLI alone does not update those+installed scripts. Existing repo-local credentials are reused; no new token+is required when that credential still works.+Security: the push automation is installed locally per machine (nevercommitted into the repo), the token is wired per-repo (an existingcredential helper is reused when present), and it never appears in the repo,diff --git a/llms-full.txt b/llms-full.txtindex c047d84012..9ff33cf485 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4940,7 +4940,18 @@ vars — incident-time escape hatches, not everyday knobs.re-derived from the process working directory. Checkpoints written bygbrain include `schema_version: 1`, `owner: "gbrain"`, and`kind: "import"` so downstream tools can validate the contract before- deciding whether to resume.+ deciding whether to resume. For ordinary imports, completed paths record+ progress, not the revision imported: the next run re-reads current files+ and compares their content hashes with the database, including paths listed+ as completed.+ Unchanged files avoid re-import, but resuming a large import still pays+ the directory-walk, file-read, and hash-comparison cost. Checkpoint timestamps+ and file mtimes are not used as proof that content is unchanged.++ [Company-brain ingestion](company-brain-ingestion.md) uses a separate+ protected database checkpoint tied to an immutable approved committed+ manifest. It can skip paths completed for that admission receipt; it does+ not treat the ordinary import checkpoint as approval to read changed files.7. **Sync imports commits, not your working tree.** Files written into thebrain repo but never committed are invisible to incremental sync. Syncdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex c315a34bb1..36046f6b43 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex bb3a8d9969..9b6eb19583 100644--- a/package.json+++ b/package.json@@ -204,7 +204,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.60.13.0",+ "version": "0.60.15.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 6d3d619df4..2116ca6933 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 281c4cebd2..a14603d9c8 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex ca46d5aeb5..672e888e3d 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.15.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 8872cd480f..6d3ad0fec9 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex be656425fe..20f78e9484 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.13.0",+ "version": "0.60.15.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 7ccaa01d3a..2fc5ec4cea 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.15.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex b8bf668331..3f4f5c4617 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.15.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex b223a95ae8..21883774fc 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -39,6 +39,7 @@ test/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.mdtest/bootstrap-shared-skills.test.ts (file-level) 18 readFileSynctest/brain-durability-hook.serial.test.ts #4682 — push-lock timeout is fail-loud for the helper only 1 readFileSynctest/brain-durability-hook.serial.test.ts brain-commit-push.sh (D13 guarantee) 4 readFileSync+test/brain-durability-hook.serial.test.ts durability push remote confirmation (#5138) 9 readFileSynctest/brain-durability-hook.serial.test.ts durability schedule (installCron:true) [D2/D12] 0 readFileSynctest/brain-durability-hook.serial.test.ts post-commit hook (D9 local, D7 self-contained) 4 readFileSynctest/brain-repo-durability.serial.test.ts hardenBrainRepo 16 readFileSyncdiff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 8cc55afb3b..02ff53ba60 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -25,6 +25,7 @@ import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/syncimport { resolveSourceLocalFilePath } from '../../../core/markdown.ts';import { scannerSlugRootMode } from '../../../core/write-through.ts';import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';+import { isSyncDisabledConfig } from '../../../core/sync-policy.ts';import type { Check } from '../../doctor.ts';import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';@@ -1146,39 +1147,36 @@ export async function computeExtractHealthCheck(}}+async function loadSyncFreshnessSources(engine: BrainEngine) {+ type FreshnessSourceRow = {+ id: string;+ name: string;+ local_path: string | null;+ last_sync_at: Date | null;+ last_commit: string | null;+ chunker_version: string | null;+ newest_content_at: Date | null;+ config: unknown;+ };+ let sources: FreshnessSourceRow[];+ try {+ sources = await engine.executeRaw<FreshnessSourceRow>(+ `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,+ );+ } catch {+ sources = await engine.executeRaw<FreshnessSourceRow>(+ `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config FROM sources WHERE local_path IS NOT NULL`,+ );+ }+ return sources.filter((source) => !isSyncDisabledConfig(source.config));+}+export async function checkSyncFreshness(engine: BrainEngine,opts?: { nowMs?: number; localOnly?: boolean },): Promise<Check> {try {- // v0.41.27.0: SELECT widens to carry last_commit + chunker_version so- // the git short-circuit gate (below) can compare against what- // `gbrain sync`'s up-to-date predicate at sync.ts:1057+1075 checks.- // Columns existed pre-v0.41 (writeSyncAnchor / writeChunkerVersion);- // no schema migration needed.- type FreshnessSourceRow = {- id: string;- name: string;- local_path: string | null;- last_sync_at: Date | null;- last_commit: string | null;- chunker_version: string | null;- newest_content_at: Date | null;- };- // v0.41.32.0: newest_content_at feeds the REMOTE (non-localOnly) lag so- // doctorReportRemote never shells out to git on a DB-supplied local_path.- // #3880: archived sources don't participate in freshness health (v34- // legacy fallback).- let sources: FreshnessSourceRow[];- try {- sources = await engine.executeRaw<FreshnessSourceRow>(- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,- );- } catch {- sources = await engine.executeRaw<FreshnessSourceRow>(- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL`,- );- }+ const sources = await loadSyncFreshnessSources(engine);if (sources.length === 0) {return {diff --git a/src/commands/import.ts b/src/commands/import.tsindex 87b21e0c27..d97926d194 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -539,9 +539,6 @@ export async function runImport(// See src/core/sort-newest-first.ts for the policy.sortNewestFirst(allFiles);- // Resume from checkpoint if available. v0.33.2: path-based resume —- // see src/core/import-checkpoint.ts for the bug-class this fixes- // (parallel-import silent-skip and failed-file no-retry).const checkpointPath = gbrainPath('import-checkpoint.json');const completed = new Set<string>();if (company) {@@ -551,11 +548,10 @@ export async function runImport(} else if (!fresh && !managedImport) {const cp = loadCheckpoint(checkpointPath, dir);if (cp) {- for (const p of cp.completedPaths) completed.add(p);- info(`Resuming from checkpoint: skipping ${completed.size} already-processed files`);+ info(`Resuming from checkpoint: re-checking current files via content_hash (${cp.completedPaths.length} previously completed)`);}}- const files = resumeFilter(allFiles, dir, completed);+ const files = company ? resumeFilter(allFiles, dir, completed) : allFiles;// Determine actual worker count. Import owns the same per-worker Postgres// pools as sync, so it must honor the shared opt-in connection budget too@@ -644,7 +640,7 @@ export async function runImport(// #753/#774: slug + source_path base. When performFullSync syncs a// monorepo subdir, slugRoot is the git root so slugs stay git-root-// relative (matching the incremental path's git-diff paths). The- // checkpoint (`completed`) stays dir-relative — resumeFilter's contract.+ // checkpoint (`completed`) stays dir-relative.const importRelPath = opts.slugRoot ? relative(opts.slugRoot, filePath) : relative(importRoot, filePath);// v0.31.2 (D5): per-file slow-path log. Fires only when a single// file takes >5s. The user's hang surfaces as one file takingdiff --git a/src/commands/schema.ts b/src/commands/schema.tsindex 5f7cb2ba23..423ab2250f 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -20,6 +20,7 @@ import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-guaimport { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';import { dirname, join } from 'node:path';+import { parseArgs } from 'node:util';import {addAliasToType,addLinkTypeToPack,@@ -730,8 +731,18 @@ async function runGraphCmd(args: string[]): Promise<void> {async function runLintCmd(args: string[]): Promise<void> {const { json, positional } = parseFlags(args);- const withDb = args.includes('--with-db');- const name = positional[0];+ const { values: { 'with-db': withDb }, positionals } = parseArgs({+ args: positional,+ allowPositionals: true,+ options: {+ 'with-db': { type: 'boolean' },+ },+ });+ if (positionals.length > 1) {+ console.error('Usage: gbrain schema lint [<pack>] [--with-db] [--json]');+ process.exit(2);+ }+ const name = positionals[0];const cfg = loadConfig();// v0.40.6.0 Phase 5: swap basic 2-rule check for the rich 11-rule lint// suite from Phase 1.5. File-plane rules run by default; --with-dbdiff --git a/src/core/autopilot-lock.ts b/src/core/autopilot-lock.tsindex c816b7624f..dd1500b99f 100644--- a/src/core/autopilot-lock.ts+++ b/src/core/autopilot-lock.ts@@ -82,8 +82,7 @@ export function looksLikeGbrainAutopilotCommand(command: string): boolean {if (!/(^|\s)autopilot(\s|$)/i.test(normalized)) return false;// Win32_Process.CommandLine quotes executables under paths with spaces: `"C:/Program Files/gbrain/gbrain.exe" autopilot`.if (/(^|[\/\s])"?gbrain(?:\.exe)?"?(\s|$)/i.test(normalized)) return true;- return /(^|\s)(?:\S+\/)?(?:\.{1,2}\/)?(?:src\/)?cli\.(?:ts|js|mjs)(\s|$)/i.test(normalized)- || /(^|\s)\S*\/src\/cli\.(?:ts|js|mjs)(\s|$)/i.test(normalized);+ return /(^|[\/\s])["']?cli\.(?:ts|js|mjs)["']?(\s|$)/i.test(normalized);}export function classifyAutopilotLockHolder(diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 0770e4ec1e..ef5ebe578c 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -167,8 +167,22 @@ export function maintainPushLog(): void {// the lock wait — env-only, incident/test escape hatch.function renderPushRetry(lockTimeoutRc: 0 | 1): string {return `# --- gbrain durability push-retry (generated; one source of truth) ---+brain_remote_contains_commit() {+ local _remote_tip _push_url+ git check-ref-format "refs/heads/$1" >/dev/null 2>&1 || return 1+ [ -n "$_push_urls" ] || return 1+ while IFS= read -r _push_url; do+ [ -n "$_push_url" ] || return 1+ [ "$(git ls-remote --get-url -- "$_push_url" 2>/dev/null)" = "$_push_url" ] || return 1+ _remote_tip="$(git ls-remote --exit-code -- "$_push_url" "refs/heads/$1" 2>/dev/null)" || return 1+ _remote_tip="\${_remote_tip%%[[:space:]]*}"+ git fetch --quiet --no-tags --no-write-fetch-head -- "$_push_url" "$_remote_tip" >/dev/null 2>&1 &&+ git merge-base --is-ancestor "$2" "$_remote_tip" >/dev/null 2>&1 || return 1+ done <<<"$_push_urls"+}+brain_push() {- _branch="$1"+ _branch="\${1#refs/heads/}"_managed_git="$(git rev-parse --git-dir 2>/dev/null || echo .git)"if [ -e "$_managed_git/gbrain-managed.json" ] || [ -e .gbrain-managed ]; thenecho "writer_coordinator_required: managed worktree git effects belong to the persistence outbox" >&2@@ -186,15 +200,30 @@ brain_push() {exec 9>"$_gd/gbrain-push.lock"flock -w "\${GBRAIN_PUSH_LOCK_WAIT_SECONDS:-30}" 9 || { echo "$(date -u +%FT%TZ) [push] lock-timeout $_branch" >>"$_log"; return ${lockTimeoutRc}; }fi- if git push origin "HEAD:$_branch" >>"$_log" 2>&1; then- echo "$(date -u +%FT%TZ) [push] ok $_branch $(git rev-parse --short HEAD 2>/dev/null)" >>"$_log"; return 0+ _head="$(git rev-parse HEAD)" || return 1+ _push_urls="$(git remote get-url --push --all origin 2>/dev/null)" || _push_urls=""+ if git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; then+ echo "$(date -u +%FT%TZ) [push] ok $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0+ fi+ if brain_remote_contains_commit "$_branch" "$_head"; then+ echo "$(date -u +%FT%TZ) [push] ok-already-on-remote $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0+ fi+ if [ "$(git rev-parse HEAD)" = "$_head" ]; then+ echo "$(date -u +%FT%TZ) [push] rejected; rebase-pull $_branch" >>"$_log"+ if git pull --rebase origin "$_branch" >>"$_log" 2>&1; then+ _head="$(git rev-parse HEAD)" || return 1+ _push_urls="$(git remote get-url --push --all origin 2>/dev/null)" || _push_urls=""+ if git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; then+ echo "$(date -u +%FT%TZ) [push] ok-after-rebase $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0+ fi+ else+ git rebase --abort >/dev/null 2>&1 || true+ fifi- echo "$(date -u +%FT%TZ) [push] rejected; rebase-pull $_branch" >>"$_log"- if git pull --rebase origin "$_branch" >>"$_log" 2>&1 && git push origin "HEAD:$_branch" >>"$_log" 2>&1; then- echo "$(date -u +%FT%TZ) [push] ok-after-rebase $_branch $(git rev-parse --short HEAD 2>/dev/null)" >>"$_log"; return 0+ if brain_remote_contains_commit "$_branch" "$_head"; then+ echo "$(date -u +%FT%TZ) [push] ok-already-on-remote $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0fi- git rebase --abort >/dev/null 2>&1 || true- echo "$(date -u +%FT%TZ) [push] LOCAL-ONLY, NEEDS ATTENTION: $_branch @ $(git rev-parse --short HEAD 2>/dev/null) could not reach origin. Run: gbrain sources pull <id> && git push" >>"$_log"+ echo "$(date -u +%FT%TZ) [push] LOCAL-ONLY, NEEDS ATTENTION: $_branch @ $(git rev-parse --short "$_head" 2>/dev/null) could not reach origin. Run: gbrain sources pull <id> && git push" >>"$_log"return 1}`;}@@ -517,7 +546,7 @@ export interface PushLogOutcome {at?: string;}-const PUSH_LOG_OK = /^(\S+) \[push\] (?:ok|ok-after-rebase) (\S+)\b/;+const PUSH_LOG_OK = /^(\S+) \[push\] (?:ok|ok-after-rebase|ok-already-on-remote) (\S+)\b/;const PUSH_LOG_LOCAL_ONLY = /^(\S+) \[push\] LOCAL-ONLY, NEEDS ATTENTION: (\S+) /;const PUSH_LOG_LOCK_TIMEOUT = /^(\S+) \[push\] lock-timeout (\S+)\b/;diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 3f77f8d9c2..812af01da9 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -24,7 +24,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--mode', '--output', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],+ 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],@@ -45,7 +45,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'conversation-parser': ['--brain', '--help', '--json', '--source'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],@@ -69,7 +69,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],+ 'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],@@ -98,7 +98,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--all', '--apply', '--brain', '--help', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -111,7 +111,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.tsindex 34c75e3d63..e6db0ba9f8 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -77,6 +77,7 @@ interface GoogleErrorBody {status?: string;message?: string;errors?: Array<{ reason?: string }>;+ details?: Array<{ '@type'?: string; reason?: string }>;};}@@ -153,6 +154,13 @@ export class GoogleApiClient {if (res.status === 404 || res.status === 410) {throw new GoogleCursorExpiredError(res.status, url);}+ if (res.status === 400 && apiHint === 'people' && new URL(url).searchParams.get('syncToken')) {+ const details = body.error?.details;+ const expired = (Array.isArray(details) && details.some(detail =>+ detail?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo' && detail.reason === 'EXPIRED_SYNC_TOKEN',+ )) || /^Sync token (?:is )?expired\b/i.test(body.error?.message ?? '');+ if (expired) throw new GoogleCursorExpiredError(res.status, url);+ }throw new CredentialError('upstream', `: HTTP ${res.status} on ${apiHint} (${body.error?.message ?? 'no detail'})`);}throw new CredentialError('upstream', `: unreachable ${apiHint}`);diff --git a/src/core/import-checkpoint.ts b/src/core/import-checkpoint.tsindex 64ea03c0fa..1bab35a9c4 100644--- a/src/core/import-checkpoint.ts+++ b/src/core/import-checkpoint.ts@@ -23,6 +23,10 @@ import { relative, isAbsolute, resolve } from 'path';* `processFile` returns successfully, the completed set is keyed by the* relative path string (sort-order-agnostic), and failed files never* enter the set.+ *+ * Persisted paths record progress, not the imported revision. Resume must+ * re-check files through importFile's content_hash comparison: neither path+ * membership nor an mtime before the checkpoint flush proves unchanged content.*/export interface ImportCheckpoint {/** Checkpoint payload schema. v1 is path-based with explicit producer metadata. */diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 2feebdebec..b8b6eb0033 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -234,6 +234,9 @@ export const SKILL_CATALOG_INSTRUCTIONS = {"correspondingly-named MCP tool on THIS server (e.g. search, query, put_page).","Only call tools in this skill's `usable_tools`; tools in `unavailable_tools` " +"are not callable by you on this server.",+ "For host-repository skills, declared `tools` narrow the usable tools. Valid " ++ "frontmatter without `tools` inherits your available brain tools; `tools: []` permits none. " ++ "Canonical shared skills use their approved requirements instead.",],} as const;@@ -249,6 +252,9 @@ export const SKILL_CLIENT_GUIDANCE = {"When the prose names a brain operation (search, store, link, look up), call " +"the MCP tool of that name on THIS server.","Do not invent tools — only the tools in `usable_tools` are callable by you.",+ "For host-repository skills, declared `tools` narrow this list. Valid frontmatter " ++ "without `tools` inherits your available brain tools; `tools: []` permits none. " ++ "Canonical shared skills use their approved requirements instead.","If `mutating` is true, this skill writes to the brain; confirm before doing so " +"if the user hasn't clearly asked for a write.",],diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.tsindex dbd25bdce1..2b68bae1bd 100644--- a/src/core/ops/skills-catalog.ts+++ b/src/core/ops/skills-catalog.ts@@ -45,7 +45,7 @@ const list_skills: Operation = {const override = await sc.readMcpSkillsDir(ctx);const { dir, source } = sc.resolveSkillsDir(ctx, override);const section = typeof p.section === 'string' ? p.section : undefined;- return sc.buildSkillCatalog(ctx, dir, source, { section });+ return sc.buildSkillCatalog(ctx, dir, source, { section, gateDisabled: await sc.readSkillToolGates(ctx) });},scope: 'read',cliHints: { name: 'skills', positional: [] },@@ -92,7 +92,7 @@ const get_skill: Operation = {const override = await sc.readMcpSkillsDir(ctx);const { dir } = sc.resolveSkillsDir(ctx, override);const name = typeof p.name === 'string' ? p.name : '';- return sc.getSkillDetail(ctx, dir, name);+ return sc.getSkillDetail(ctx, dir, name, { gateDisabled: await sc.readSkillToolGates(ctx) });},scope: 'read',cliHints: { name: 'skill', positional: ['name'] },diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.tsindex 1a811a54c5..6431941ceb 100644--- a/src/core/skill-catalog.ts+++ b/src/core/skill-catalog.ts@@ -38,6 +38,7 @@import { existsSync, readFileSync, realpathSync, statSync } from 'fs';import { basename, join, relative, resolve } from 'path';+import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';import {autoDetectSkillsDir,autoDetectSkillsDirReadOnly,@@ -48,8 +49,11 @@ import {import { loadOrDeriveManifest, type ManifestEntry } from './skill-manifest.ts';import { loadSkillTriggerIndex, FRONTMATTER_SECTION } from './skill-trigger-index.ts';import { parseSkillFrontmatter } from './skill-frontmatter.ts';-import { hasScope } from './scope.ts';-import { operations, OperationError, type Operation, type OperationContext } from './operations.ts';+import { operationScopesAllowed } from './scope.ts';+import { currentVerifiedLocalWriter } from './persistence/identity.ts';+import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';+import { filterOpsForSurface } from '../mcp/surface.ts';+import { operations, OperationError, opAllowedForBoundClient, type Operation, type OperationContext } from './operations.ts';import {SKILL_CATALOG_INSTRUCTIONS,SKILL_CLIENT_GUIDANCE,@@ -292,11 +296,22 @@ export function confineManifestPath(skillsDir: string, entry: ManifestEntry): st// ---------------------------------------------------------------------------/** Can THIS caller call THIS op on THIS server? Local owns everything. */-function opCallableByCaller(op: Operation, ctx: OperationContext): boolean {+function opCallableByCaller(op: Operation, ctx: OperationContext, gateDisabled?: ReadonlySet<string>): boolean {if (ctx.remote === false) return true; // local CLI — OS is the trust boundaryif (op.localOnly) return false; // not reachable over a remote transport- if (ctx.transport === 'stdio') return true; // auth-less local pipe — dispatch enforces no scopes- return hasScope(ctx.auth?.scopes ?? [], op.scope ?? 'read');+ if (!opAllowedForBoundClient(ctx.auth, op)) return false;+ if (filterOpsForSurface([op], ctx.auth?.effectiveSurface ?? ctx.surfaceCeiling ?? 'full').length === 0) return false;+ if (op.publishGateKey && (!gateDisabled || gateDisabled.has(op.name))) return false;+ if (ctx.transport === 'stdio') {+ const writer = currentVerifiedLocalWriter();+ if (!ctx.auth && writer?.remote && !opAllowedForBoundClient({+ allowedOperations: writer.grant.operations ?? undefined,+ boundSlugPrefixes: writer.grant.slugPrefixes ?? undefined,+ }, op)) return false;+ const scopes = ctx.auth?.scopes ?? (writer?.remote ? writer.grant.scopes : undefined);+ return scopes ? operationScopesAllowed(scopes, op) : !op.requiredScopes?.length;+ }+ return operationScopesAllowed(ctx.auth?.scopes ?? [], op);}/**@@ -307,20 +322,42 @@ function opCallableByCaller(op: Operation, ctx: OperationContext): boolean {export function crossReferenceTools(declared: string[],ctx: OperationContext,+ gateDisabled?: ReadonlySet<string>,): { usable_tools: string[]; unavailable_tools: string[] } {const usable: string[] = [];const unavailable: string[] = [];for (const tool of declared) {const op = operations.find(o => o.name === tool);- if (op && opCallableByCaller(op, ctx)) usable.push(tool);+ if (op && opCallableByCaller(op, ctx, gateDisabled)) usable.push(tool);else unavailable.push(tool);}return { usable_tools: usable, unavailable_tools: unavailable };}/** Every server tool this caller can call — the envelope's "what you can use". */-function availableBrainTools(ctx: OperationContext): string[] {- return operations.filter(op => opCallableByCaller(op, ctx)).map(op => op.name).sort();+function availableBrainTools(ctx: OperationContext, gateDisabled?: ReadonlySet<string>): string[] {+ return operations.filter(op => opCallableByCaller(op, ctx, gateDisabled)).map(op => op.name).sort();+}++export async function readSkillToolGates(ctx: OperationContext): Promise<ReadonlySet<string> | undefined> {+ return ctx.remote === false ? undefined : disabledOpsForPublishGates(ctx.engine, ctx.config);+}++function resolveSkillTools(+ parsed: ReturnType<typeof parseSkillFrontmatter>,+ ctx: OperationContext,+ gateDisabled?: ReadonlySet<string>,+): { usable_tools: string[]; unavailable_tools: string[] } {+ if (parsed?.tools !== undefined) return crossReferenceTools(parsed.tools, ctx, gateDisabled);+ if (parsed) {+ try {+ const data = safeLoad(parsed.raw, { schema: FAILSAFE_SCHEMA });+ if (data && typeof data === 'object' && !Array.isArray(data) && !Object.hasOwn(data, 'tools')) {+ return { usable_tools: availableBrainTools(ctx, gateDisabled), unavailable_tools: [] };+ }+ } catch {}+ }+ return { usable_tools: [], unavailable_tools: [] };}// ---------------------------------------------------------------------------@@ -439,7 +476,7 @@ export function buildSkillCatalog(ctx: OperationContext,skillsDir: string,source: ResolvedSkillsDirSource,- opts: { section?: string } = {},+ opts: { section?: string; gateDisabled?: ReadonlySet<string> } = {},): ListSkillsResult {const { skills: manifest } = loadOrDeriveManifest(skillsDir);const triggerMap = buildTriggerMap(skillsDir);@@ -472,7 +509,7 @@ export function buildSkillCatalog(if (sectionFilter && section !== sectionFilter) continue;const tools = parsed?.tools ?? [];- const { usable_tools, unavailable_tools } = crossReferenceTools(tools, ctx);+ const { usable_tools, unavailable_tools } = resolveSkillTools(parsed, ctx, opts.gateDisabled);skills.push({name: entry.name,description: oneLineDescription(raw, body),@@ -496,7 +533,7 @@ export function buildSkillCatalog(instructions: {summary: SKILL_CATALOG_INSTRUCTIONS.summary,how_to_use: [...SKILL_CATALOG_INSTRUCTIONS.how_to_use],- available_brain_tools: availableBrainTools(ctx),+ available_brain_tools: availableBrainTools(ctx, opts.gateDisabled),fetch_op: 'get_skill',},};@@ -507,6 +544,7 @@ export function getSkillDetail(ctx: OperationContext,skillsDir: string,name: string,+ opts: { gateDisabled?: ReadonlySet<string> } = {},): GetSkillResult {const path = resolveSkillMdPath(skillsDir, name);@@ -526,8 +564,7 @@ export function getSkillDetail(const parsed = parseSkillFrontmatter(content);const raw = parsed?.raw ?? '';const body = stripFrontmatterFence(content);- const tools = parsed?.tools ?? [];- const { usable_tools, unavailable_tools } = crossReferenceTools(tools, ctx);+ const { usable_tools, unavailable_tools } = resolveSkillTools(parsed, ctx, opts.gateDisabled);const mutating = parsed?.mutating ?? false;return {@@ -547,7 +584,7 @@ export function getSkillDetail(client_guidance: {nature: SKILL_CLIENT_GUIDANCE.nature,protocol: [...SKILL_CLIENT_GUIDANCE.protocol],- available_brain_tools: availableBrainTools(ctx),+ available_brain_tools: availableBrainTools(ctx, opts.gateDisabled),mutating,},};diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.tsindex 7db5880cf9..56ae13eff2 100644--- a/src/core/transcripts/claude-code-jsonl.ts+++ b/src/core/transcripts/claude-code-jsonl.ts@@ -16,7 +16,10 @@* text blocks are extracted verbatim, non-text blocks become placeholders* ([tool: name] / [tool result] / [thinking] / [image]) so the corpus* records THAT a tool ran, never its payload.- * - isSidechain:true entries (subagent traffic) are skipped.+ * - root isSidechain/isMeta/isCompactSummary exactly true entries are skipped.+ * - user text with a non-empty structured origin.kind other than 'human'+ * is excluded; absent/unstructured origins stay compatible. Non-text+ * placeholders and assistant text are retained, not classified by origin.* - type 'summary' entries and system/compact-boundary entries are skipped.* - malformed lines are counted (skippedLines), never fatal.*@@ -48,7 +51,9 @@ export const SPEC_TARGET: HostSpecTarget = {'block array ({type: "text"|"tool_use"|"tool_result"|"thinking"|"image", …}). ' +'Non-turn lines: {type: "summary"} and {type: "system", subtype: ' +'"compact_boundary"} among others — anything that is not a non-sidechain ' +- 'user/assistant message is skipped. Unknown fields tolerated everywhere.',+ 'user/assistant message is skipped, as are root isMeta/isCompactSummary: true. ' ++ 'User text with a non-empty string origin.kind other than "human" is excluded; ' ++ 'missing/unstructured origins stay compatible. Unknown fields tolerated elsewhere.',};// ── Byte caps ───────────────────────────────────────────────────────────────@@ -164,7 +169,7 @@ export interface ParsedTranscript {/** Conversation turns, oldest → newest (WindowTurn — the IPC window shape). */turns: WindowTurn[];/**- * Turn indexes whose user-role content contains genuine text. Claude records+ * Turn indexes whose accepted user-role content contains genuine text. Claude records* tool results as user-role messages too, so role alone cannot identify a* human prompt. Kept parallel to `turns` instead of removing placeholders:* archival/corpus consumers still see that tools ran, while prompt-only@@ -377,11 +382,21 @@ function isGenuineUserText(text: string): boolean {return text.replace(HARNESS_TAG_RE, '').trim().length > 0;}+function isSkippedTurnEntry(e: Record<string, unknown>): boolean {+ return e.isSidechain === true || e.isMeta === true || e.isCompactSummary === true;+}++function hasNonHumanOrigin(e: Record<string, unknown>): boolean {+ if (typeof e.origin !== 'object' || e.origin === null) return false;+ const kind = (e.origin as Record<string, unknown>).kind;+ return typeof kind === 'string' && kind.length > 0 && kind !== 'human';+}+/** One transcript line → a turn plus its structural human-prompt origin. */function entryToTurn(entry: unknown): { turn: WindowTurn; genuineUser: boolean } | null {if (typeof entry !== 'object' || entry === null) return null;const e = entry as Record<string, unknown>;- if (e.isSidechain === true) return null; // subagent traffic — skipped+ if (isSkippedTurnEntry(e)) return null;const type = e.type;if (type !== 'user' && type !== 'assistant') return null; // summary / system / compact boundaryconst msg = e.message;@@ -389,11 +404,13 @@ function entryToTurn(entry: unknown): { turn: WindowTurn; genuineUser: boolean }const m = msg as Record<string, unknown>;const role: WindowTurn['role'] =m.role === 'assistant' || m.role === 'user' ? m.role : (type as WindowTurn['role']);+ const acceptText = role !== 'user' || !hasNonHumanOrigin(e);const content = m.content;let text = '';let hasGenuineText = false;if (typeof content === 'string') {+ if (!acceptText) return null;text = content;hasGenuineText = isGenuineUserText(content);} else if (Array.isArray(content)) {@@ -403,7 +420,7 @@ function entryToTurn(entry: unknown): { turn: WindowTurn; genuineUser: boolean }const b = block as Record<string, unknown>;switch (b.type) {case 'text':- if (typeof b.text === 'string' && b.text.trim()) {+ if (acceptText && typeof b.text === 'string' && b.text.trim()) {parts.push(b.text);if (isGenuineUserText(b.text)) hasGenuineText = true;}@@ -463,7 +480,7 @@ interface ToolCallWithId extends ToolCallRecord {function entryContentBlocks(entry: unknown): unknown[] | null {if (typeof entry !== 'object' || entry === null) return null;const e = entry as Record<string, unknown>;- if (e.isSidechain === true) return null; // subagent traffic — skipped, same as entryToTurn+ if (isSkippedTurnEntry(e)) return null;const msg = e.message;if (typeof msg !== 'object' || msg === null) return null;const content = (msg as Record<string, unknown>).content;@@ -560,10 +577,10 @@ export interface ParsedClaudeSession {skippedLines: number;/*** Records that CLAIM to be importable turns: `type` user/assistant and not- * `isSidechain`. Zero of them means the file never had anything to import- * (a title/metadata-only stub, or all-subagent traffic) — understood, not- * host-format drift. Above zero with `turns` still empty is the real drift- * signal: turn records exist but no longer yield text.+ * skipped by entry markers or explicit non-human origins. Zero of them means+ * the file had nothing accepted to import (metadata or non-human text only) —+ * understood, not host-format drift. Above zero with `turns` still empty is+ * the real drift signal: turn records exist but no longer yield text.*/turnShapedLines: number;}@@ -602,10 +619,13 @@ export function parseClaudeSessionFile(const e = entry as Record<string, unknown>;if (!sessionId && typeof e.sessionId === 'string' && e.sessionId) sessionId = e.sessionId;if (!cwd && typeof e.cwd === 'string' && e.cwd) cwd = e.cwd;- if (e.isSidechain !== true && (e.type === 'user' || e.type === 'assistant')) {+ const turn = entryToTurn(entry);+ if (+ !isSkippedTurnEntry(e) && (e.type === 'user' || e.type === 'assistant') &&+ (turn || e.type === 'assistant' || !hasNonHumanOrigin(e))+ ) {turnShapedLines++;}- const turn = entryToTurn(entry);if (!turn) continue;const timestamp = typeof e.timestamp === 'string' ? e.timestamp : '';turns.push({ role: turn.turn.role, text: turn.turn.text, timestamp });diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.tsindex 8a13a5eb24..30bed43432 100644--- a/src/core/transcripts/claude-code.ts+++ b/src/core/transcripts/claude-code.ts@@ -195,9 +195,9 @@ export const claudeCodeAdapter: TranscriptAdapter = {}// A file with NO turn-shaped records never had anything to import: a// title/metadata-only stub (`last-prompt` + `custom-title` and nothing- // else) or all-`isSidechain` subagent traffic. That is understood, not- // host-format drift, so it must not freeze the shared watermark — the- // same distinction grok draws with expectedEmpty. Turn records that stop+ // else), explicitly non-human text, or all-`isSidechain` subagent traffic.+ // That is understood, not host-format drift, so it must not freeze the+ // shared watermark. As with grok's expectedEmpty, turn records that stop// yielding text (`turnShapedLines > 0` with zero turns) still drift, and// so does any file with unparseable lines.const expectedEmpty =@@ -211,7 +211,7 @@ export const claudeCodeAdapter: TranscriptAdapter = {zeroSessionsReason:sessions === 0? expectedEmpty- ? 'no turn records in file (title/metadata-only or all-subagent)'+ ? 'no turn records in file (title/metadata-only, non-human text only, or all-subagent)': 'no user or assistant turns in file': undefined,};diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 4b0a8f8640..6fe4651331 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.13.0 -->+<!-- gbrain-template-stamp: 0.60.15.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/autopilot-lock.test.ts b/test/autopilot-lock.test.tsindex 567505da7f..93152546ba 100644--- a/test/autopilot-lock.test.ts+++ b/test/autopilot-lock.test.ts@@ -86,6 +86,20 @@ describe('decideLockAcquisition', () => {});});+ test.each([+ 'bun "C:/Users/Example User/project/src/cli.ts" autopilot',+ "bun '/home/example user/project/src/cli.js' autopilot",+ 'node "/project/src/cli.mjs" autopilot',+ ])('keeps a stale lock held by a quoted autopilot command: %s', (command) => {+ writeFileSync(lockPath, '1234');+ const stale = new Date(Date.now() - AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS - 1000);+ utimesSync(lockPath, stale, stale);+ expect(decideLockAcquisition(lockPath, process.pid, {+ isPidAlive: (pid) => pid === 1234,+ readProcessCommand: () => command,+ })).toEqual({ action: 'exit', holderPid: 1234, holderState: 'alive-autopilot' });+ });+test('takes over a stale lock when the PID was reused by a foreign process', () => {writeFileSync(lockPath, '1234');const stale = new Date(Date.now() - AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS - 1000);@@ -225,4 +239,36 @@ describe('looksLikeGbrainAutopilotCommand', () => {expect(looksLikeGbrainAutopilotCommand('/sbin/launchd')).toBe(false);expect(looksLikeGbrainAutopilotCommand('/usr/bin/python worker.py')).toBe(false);});++ for (const extension of ['ts', 'js', 'mjs']) {+ test.each([+ `"C:/Users/Example User/project/src/cli.${extension}" autopilot`,+ `"C:\\Program Files\\Bun\\bun.exe" "C:\\Users\\Example User\\project\\src\\cli.${extension}" autopilot`,+ `bun '/home/example user/project/src/cli.${extension}' autopilot`,+ `bun "/project/src/cli.${extension}" autopilot`,+ `bun "cli.${extension}" autopilot`,+ `bun 'cli.${extension}' autopilot`,+ `bun /home/example user/project/src/cli.${extension} autopilot`,+ `bun /home/example/project dir /cli.${extension} autopilot`,+ `bun cli.${extension} autopilot`,+ `bun ./cli.${extension} autopilot`,+ `bun ../src/cli.${extension} autopilot`,+ `node /project/dist/cli.${extension} autopilot --repo repo`,+ ])('matches quoted and unquoted source paths: %s', (command) => {+ expect(looksLikeGbrainAutopilotCommand(command)).toBe(true);+ });+ }++ test.each([+ 'bun "C:/Users/Example User/project/src/cli.ts" serve',+ 'bun "C:/Users/Example User/project/src/cli.ts" autopilot-other',+ 'bun "C:/Users/Example User/project/src/not-cli.ts" autopilot',+ 'bun "C:/Users/Example User/project/src/cli.ts.bak" autopilot',+ 'bun "C:/Users/Example User/project/src/cli.jsx" autopilot',+ 'bun "C:/Users/Example User/project/src/cli.ts"suffix autopilot',+ 'other-gbrain autopilot',+ 'python worker.py autopilot',+ ])('rejects commands outside script and argument boundaries: %s', (command) => {+ expect(looksLikeGbrainAutopilotCommand(command)).toBe(false);+ });});diff --git a/test/brain-durability-hook.serial.test.ts b/test/brain-durability-hook.serial.test.tsindex 4b5ad660c3..d2a22d36b5 100644--- a/test/brain-durability-hook.serial.test.ts+++ b/test/brain-durability-hook.serial.test.ts@@ -8,8 +8,8 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test';import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';-import { execFileSync, spawn } from 'child_process';-import { hardenBrainRepo, unhardenBrainRepo } from '../src/core/brain-repo-durability.ts';+import { execFileSync, spawn, spawnSync } from 'child_process';+import { getLastPushOutcome, hardenBrainRepo, unhardenBrainRepo } from '../src/core/brain-repo-durability.ts';import { crontabAvailable } from './helpers/fs-perms.ts';import { runPull } from '../src/commands/sources-harden.ts';@@ -157,6 +157,319 @@ describe('brain-commit-push.sh (D13 guarantee)', () => {});});+describe('durability push remote confirmation (#5138)', () => {+ let intendedHead: string;++ beforeEach(() => {+ rmSync(join(work, '.git', 'hooks', 'post-commit'));+ writeFileSync(join(work, 'pending.md'), 'pending\n');+ git(work, 'add', 'pending.md');+ git(work, 'commit', '-qm', 'pending');+ intendedHead = git(work, 'rev-parse', 'HEAD');+ });++ function interceptGit(script: string): NodeJS.ProcessEnv {+ const bin = join(root, 'intercept-bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'git'), `#!/usr/bin/env bash+set -eu+${script}+exec "$GBRAIN_TEST_REAL_GIT" "$@"+`, { mode: 0o755 });+ return {+ ...process.env,+ PATH: `${bin}:${process.env.PATH ?? ''}`,+ GBRAIN_TEST_REAL_GIT: Bun.which('git')!,+ GBRAIN_TEST_PUSH_MARKER: join(root, 'push-attempted'),+ };+ }++ function pushOnly(env = process.env) {+ return spawnSync('bash', [join(work, 'scripts', 'brain-commit-push.sh'), '--push-only', 'main'], {+ cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', env,+ });+ }++ function advanceRemote(path = 'remote.md'): string {+ const other = join(root, 'other-worktree');+ git(work, 'worktree', 'add', '--detach', other, 'origin/main');+ writeFileSync(join(other, path), 'remote edit\n');+ git(other, 'add', path);+ git(other, 'commit', '-qm', 'remote advance');+ git(other, 'push', '-q', 'origin', 'HEAD:main');+ return originHead(bare);+ }++ function clonePushTarget(name: string): string {+ const target = join(root, `${name}.git`);+ git(work, 'clone', '--bare', '-q', bare, target);+ return target;+ }++ test('does not confirm a rejecting push target from the fetch repository', () => {+ const target = clonePushTarget('push target');+ const originalTargetHead = originHead(target);+ git(work, 'push', '-q', 'origin', 'HEAD:main');+ git(work, 'remote', 'set-url', '--push', 'origin', target);+ writeFileSync(join(target, 'hooks', 'pre-receive'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');++ const result = pushOnly();++ expect(originHead(bare)).toBe(intendedHead);+ expect(originHead(target)).toBe(originalTargetHead);+ expect(result.status).not.toBe(0);+ expect(getLastPushOutcome('main').status).toBe('needs_attention');+ });++ test('fails closed when a push path would resolve as a different remote alias', () => {+ const targetName = 'push-target';+ const target = join(work, targetName);+ git(work, 'clone', '--bare', '-q', bare, target);+ const originalTargetHead = originHead(target);+ git(work, 'push', '-q', 'origin', 'HEAD:main');+ git(work, 'remote', 'add', targetName, bare);+ git(work, 'remote', 'set-url', '--push', 'origin', targetName);+ writeFileSync(join(target, 'hooks', 'pre-receive'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');++ const result = pushOnly();++ expect(originHead(bare)).toBe(intendedHead);+ expect(originHead(target)).toBe(originalTargetHead);+ expect(result.status).not.toBe(0);+ });++ test.each(['pushurl', 'pushInsteadOf'])('confirms the effective %s destination without logging probe diagnostics', (configuration) => {+ const target = clonePushTarget('push target');+ if (configuration === 'pushurl') git(work, 'remote', 'set-url', '--push', 'origin', target);+ else git(work, 'config', `url.${target}.pushInsteadOf`, bare);+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');+ const env = interceptGit(`if [ "$1" = push ]; then+ "$GBRAIN_TEST_REAL_GIT" "$@"+ exit 1+fi+if [ "$1" = ls-remote ] || [ "$1" = fetch ]; then+ echo "synthetic-destination-credential" >&2+fi`);++ const result = pushOnly(env);++ expect(result.status).toBe(0);+ expect(originHead(target)).toBe(intendedHead);+ expect(originHead(bare)).not.toBe(intendedHead);+ const log = readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8');+ expect(log).toContain('ok-already-on-remote main');+ expect(log).not.toContain('synthetic-destination-credential');+ });++ test.each(['first', 'last', 'neither'])('requires every push URL to contain the commit when %s target rejects', (rejecting) => {+ const targets = [clonePushTarget('first push target'), clonePushTarget('last push target')];+ git(work, 'push', '-q', 'origin', 'HEAD:main');+ for (const target of targets) git(work, 'config', '--add', 'remote.origin.pushurl', target);+ const rejected = rejecting === 'first' ? 0 : rejecting === 'last' ? 1 : -1;+ if (rejected !== -1) {+ writeFileSync(join(targets[rejected], 'hooks', 'pre-receive'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });+ }+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');+ const env = interceptGit(`if [ "$1" = push ]; then+ "$GBRAIN_TEST_REAL_GIT" "$@" || true+ exit 1+fi`);++ const result = pushOnly(env);++ expect(result.status === 0).toBe(rejected === -1);+ for (const [index, target] of targets.entries()) {+ expect(originHead(target) === intendedHead).toBe(index !== rejected);+ }+ expect(getLastPushOutcome('main').status).toBe(rejected === -1 ? 'ok' : 'needs_attention');+ });++ test.each(['initial', 'retry'])('pushes the captured SHA when HEAD moves during the %s push', (attempt) => {+ if (attempt === 'retry') advanceRemote();+ const env = interceptGit(`if [ "$1" = push ]; then+ if [ "$GBRAIN_TEST_PUSH_ATTEMPT" = initial ] || [ -e "$GBRAIN_TEST_PUSH_MARKER" ]; then+ "$GBRAIN_TEST_REAL_GIT" rev-parse HEAD >"$GBRAIN_TEST_PUSH_MARKER"+ "$GBRAIN_TEST_REAL_GIT" reset --hard HEAD^ >/dev/null+ "$GBRAIN_TEST_REAL_GIT" "$@"+ exit 1+ fi+ : >"$GBRAIN_TEST_PUSH_MARKER"+fi`);+ env.GBRAIN_TEST_PUSH_ATTEMPT = attempt;++ const result = pushOnly(env);++ const captured = readFileSync(env.GBRAIN_TEST_PUSH_MARKER!, 'utf8').trim();+ expect(result.status).toBe(0);+ expect(originHead(bare)).toBe(captured);+ expect(git(work, 'rev-parse', 'HEAD')).not.toBe(captured);+ expect(git(bare, 'show', 'main:pending.md')).toBe('pending');+ });++ test.each(['initial', 'retry'])('does not confirm a moved HEAD ancestor when the captured %s commit is absent', (attempt) => {+ if (attempt === 'retry') advanceRemote();+ const remoteHead = originHead(bare);+ const env = interceptGit(`if [ "$1" = push ]; then+ if [ "$GBRAIN_TEST_PUSH_ATTEMPT" = initial ] || [ -e "$GBRAIN_TEST_PUSH_MARKER" ]; then+ "$GBRAIN_TEST_REAL_GIT" rev-parse HEAD >"$GBRAIN_TEST_PUSH_MARKER"+ "$GBRAIN_TEST_REAL_GIT" reset --hard "$GBRAIN_TEST_REMOTE_HEAD" >/dev/null+ exit 1+ fi+ : >"$GBRAIN_TEST_PUSH_MARKER"+fi`);+ env.GBRAIN_TEST_PUSH_ATTEMPT = attempt;+ env.GBRAIN_TEST_REMOTE_HEAD = remoteHead;++ const result = pushOnly(env);++ expect(result.status).not.toBe(0);+ expect(originHead(bare)).toBe(remoteHead);+ expect(git(work, 'rev-parse', 'HEAD')).toBe(remoteHead);+ expect(getLastPushOutcome('main').status).toBe('needs_attention');+ });++ test.each(['new-example', 'refs/heads/new-example'])('preserves pushes to a new branch: %s', (branch) => {+ const result = spawnSync('bash', [join(work, 'scripts', 'brain-commit-push.sh'), '--push-only', branch], {+ cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', env: process.env,+ });++ expect(result.status).toBe(0);+ expect(git(bare, 'rev-parse', 'refs/heads/new-example')).toBe(intendedHead);+ });++ test('does not treat a wildcard branch argument as exact remote confirmation', () => {+ git(work, 'push', '-q', 'origin', 'HEAD:main');+ const result = spawnSync('bash', [join(work, 'scripts', 'brain-commit-push.sh'), '--push-only', '*'], {+ cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', env: process.env,+ });++ expect(result.status).not.toBe(0);+ });++ test.each(['same commit', 'descendant'])('accepts a rejected push after a concurrent pusher lands the %s', (remoteShape) => {+ const remoteHead = remoteShape === 'same commit' ? intendedHead+ : git(work, 'commit-tree', 'HEAD^{tree}', '-p', intendedHead, '-m', 'remote descendant');+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');+ const env = interceptGit(`if [ "$1" = push ]; then+ "$GBRAIN_TEST_REAL_GIT" push origin "$GBRAIN_TEST_REMOTE_HEAD:refs/heads/main"+ echo "simulated stale expected-ref rejection" >&2+ exit 1+fi`);+ env.GBRAIN_TEST_REMOTE_HEAD = remoteHead;++ const result = pushOnly(env);++ expect(result.status).toBe(0);+ expect(originHead(bare)).toBe(remoteHead);+ expect(git(work, 'rev-parse', 'HEAD')).toBe(intendedHead);+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('unrelated dirty edit\n');+ const log = readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8');+ expect(log).toContain('ok-already-on-remote main');+ expect(log).not.toContain('rebase-pull');+ expect(log).not.toContain('LOCAL-ONLY');+ expect(getLastPushOutcome('main').status).toBe('ok');+ });++ test('confirms the rebased commit when the retry push lands but reports failure', () => {+ const remoteHead = advanceRemote();+ const env = interceptGit(`if [ "$1" = push ]; then+ if [ ! -e "$GBRAIN_TEST_PUSH_MARKER" ]; then+ : >"$GBRAIN_TEST_PUSH_MARKER"+ else+ "$GBRAIN_TEST_REAL_GIT" "$@"+ echo "simulated lost push acknowledgement" >&2+ exit 1+ fi+fi`);++ const result = pushOnly(env);++ expect(result.status).toBe(0);+ expect(originHead(bare)).toBe(git(work, 'rev-parse', 'HEAD'));+ expect(originHead(bare)).not.toBe(intendedHead);+ expect(git(work, 'merge-base', '--is-ancestor', remoteHead, 'HEAD')).toBe('');+ expect(git(bare, 'show', 'main:pending.md')).toBe('pending');+ expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('ok-already-on-remote main');+ });++ test('checks again after recovery fails while another pusher lands the commit', () => {+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');+ const env = interceptGit(`if [ "$1" = push ]; then exit 1; fi+if [ "$1" = pull ]; then+ "$GBRAIN_TEST_REAL_GIT" push origin HEAD:refs/heads/main+ exit 1+fi`);++ const result = pushOnly(env);++ expect(result.status).toBe(0);+ expect(originHead(bare)).toBe(intendedHead);+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('unrelated dirty edit\n');+ });++ test('does not trust stale remote evidence when origin is unreachable', () => {+ git(work, 'push', '-q', 'origin', 'HEAD:main');+ git(work, 'fetch', '-q', 'origin', 'main');+ expect(git(work, 'rev-parse', 'FETCH_HEAD')).toBe(intendedHead);+ expect(git(work, 'rev-parse', 'origin/main')).toBe(intendedHead);+ git(work, 'remote', 'set-url', 'origin', join(root, 'gone.git'));++ const result = pushOnly();++ expect(result.status).not.toBe(0);+ expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('LOCAL-ONLY, NEEDS ATTENTION');+ });++ test('does not accept containment on another remote branch', () => {+ git(work, 'push', '-q', 'origin', 'HEAD:other');+ git(work, 'fetch', '-q', 'origin', 'other');+ expect(git(work, 'rev-parse', 'FETCH_HEAD')).toBe(intendedHead);+ writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');+ const env = interceptGit('if [ "$1" = push ]; then exit 1; fi');++ const result = pushOnly(env);++ expect(result.status).not.toBe(0);+ expect(originHead(bare)).not.toBe(intendedHead);+ expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('LOCAL-ONLY, NEEDS ATTENTION');+ });++ test('keeps exit 4 and the failure message when the remote rejects every push', () => {+ const remoteHead = originHead(bare);+ writeFileSync(join(bare, 'hooks', 'pre-receive'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });+ writeFileSync(join(work, 'pending.md'), 'updated pending\n');++ const result = spawnSync('bash', [join(work, 'scripts', 'brain-commit-push.sh'), 'update pending', 'pending.md'], {+ cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', env: process.env,+ });++ expect(result.status).toBe(4);+ expect(result.stderr).toContain('PUSH FAILED');+ expect(originHead(bare)).toBe(remoteHead);+ expect(git(work, 'show', 'HEAD:pending.md')).toBe('updated pending');+ expect(getLastPushOutcome('main').status).toBe('needs_attention');+ });++ test('does not confirm the temporary remote HEAD of a conflicted rebase', () => {+ writeFileSync(join(work, 'README.md'), 'local edit\n');+ git(work, 'add', 'README.md');+ git(work, 'commit', '--amend', '--no-edit', '-q');+ const localHead = git(work, 'rev-parse', 'HEAD');+ const remoteHead = advanceRemote('README.md');++ const result = pushOnly();++ expect(result.status).not.toBe(0);+ expect(originHead(bare)).toBe(remoteHead);+ expect(git(work, 'rev-parse', 'HEAD')).toBe(localHead);+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('local edit\n');+ expect(existsSync(join(work, '.git', 'rebase-merge'))).toBe(false);+ expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('LOCAL-ONLY, NEEDS ATTENTION');+ });+});+describe('post-commit hook (D9 local, D7 self-contained)', () => {test('#3925 — the scaffolding commit does NOT fire the hook (no racing background push)', async () => {// beforeEach ran hardenBrainRepo. commitScaffolding commits withdiff --git a/test/claude-code-jsonl-origin.test.ts b/test/claude-code-jsonl-origin.test.tsnew file mode 100644index 0000000000..604746e8bc--- /dev/null+++ b/test/claude-code-jsonl-origin.test.ts@@ -0,0 +1,166 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { parseClaudeSessionFile, parseTranscript } from '../src/core/transcripts/claude-code-jsonl.ts';+import { claudeCodeAdapter } from '../src/core/transcripts/claude-code.ts';++let dir: string | undefined;++afterEach(() => {+ if (dir) rmSync(dir, { recursive: true, force: true });+ dir = undefined;+});++function transcript(entries: Record<string, unknown>[]): string {+ dir = mkdtempSync(join(tmpdir(), 'gb-jsonl-origin-'));+ const path = join(dir, 'synthetic.jsonl');+ writeFileSync(path, entries.map((entry, index) => JSON.stringify({+ sessionId: 'synthetic-origin-session',+ timestamp: `2026-08-01T10:00:${String(index).padStart(2, '0')}.000Z`,+ ...entry,+ })).join('\n') + '\n');+ return path;+}++function user(content: unknown, fields: Record<string, unknown> = {}): Record<string, unknown> {+ return { type: 'user', message: { role: 'user', content }, ...fields };+}++describe('Claude Code structured user origins', () => {+ test('hook and archive exclude root metadata and non-human text, retaining the human prompt and assistant', async () => {+ const path = transcript([+ user('synthetic metadata text', { isMeta: true, origin: { kind: 'human' } }),+ user('synthetic compact summary', { isCompactSummary: true, origin: { kind: 'human' } }),+ user('synthetic automation text', { origin: { kind: 'hook' } }),+ user('synthetic human prompt', { origin: { kind: 'human' } }),+ { type: 'assistant', origin: { kind: 'agent' }, message: { role: 'assistant', content: 'synthetic assistant reply' } },+ ]);+ const expected = [+ { role: 'user' as const, text: 'synthetic human prompt' },+ { role: 'assistant' as const, text: 'synthetic assistant reply' },+ ];+ const hook = parseTranscript(path);+ expect(hook.turns).toEqual(expected);+ expect(hook.genuineUserTurnIndexes).toEqual([0]);+ expect(hook.parsedLines).toBe(5);+ expect(hook.skippedLines).toBe(0);++ const archive = parseClaudeSessionFile(path);+ expect(archive.turns.map(({ role, text }) => ({ role, text }))).toEqual(expected);+ expect(archive.startedAt).toBe('2026-08-01T10:00:03.000Z');+ const result = await claudeCodeAdapter.parse(path).next();+ expect(result.done).toBe(false);+ if (!result.done) expect(result.value.messages.map(({ role, text }) => ({ role, text }))).toEqual(expected);+ });++ test.each(['isMeta', 'isCompactSummary'])('%s is only honored at the root and when exactly true', (flag) => {+ const values = [undefined, false, 'true', 1, null];+ const entries = values.map((value, index) => user(`synthetic prompt ${index}`, { [flag]: value }));+ entries.push({+ type: 'user',+ message: { role: 'user', content: 'synthetic nested marker', [flag]: true },+ });+ entries.push(user('synthetic excluded prompt', { [flag]: true }));+ const path = transcript(entries);+ const expected = [...values.map((_, index) => `synthetic prompt ${index}`), 'synthetic nested marker'];+ expect(parseTranscript(path).turns.map((turn) => turn.text)).toEqual(expected);+ expect(parseClaudeSessionFile(path).turns.map((turn) => turn.text)).toEqual(expected);+ expect(parseTranscript(path).genuineUserTurnIndexes).toEqual([0, 1, 2, 3, 4, 5]);+ });++ test('missing or unstructured origins stay compatible without guessing from message text', () => {+ const origins = [undefined, null, 'hook', {}, { kind: null }, { kind: 1 }, { kind: '' }, { kind: 'human' }];+ const text = 'synthetic hook output mentioning origin.kind and isMeta: true';+ const path = transcript(origins.map((origin) => user(text, { origin })));+ const hook = parseTranscript(path);+ expect(hook.turns.map((turn) => turn.text)).toEqual(origins.map(() => text));+ expect(hook.genuineUserTurnIndexes).toEqual(origins.map((_, index) => index));+ expect(parseClaudeSessionFile(path).turns.map((turn) => turn.text)).toEqual(origins.map(() => text));+ });++ test('explicit non-human origins filter text blocks but preserve placeholders and opt-in tool results', () => {+ const path = transcript([+ user('synthetic prompt', { origin: { kind: 'human' } }),+ { type: 'assistant', message: { role: 'assistant', content: [+ { type: 'tool_use', id: 'synthetic-tool', name: 'Read', input: { file_path: '/synthetic/example.txt' } },+ ] } },+ user([+ { type: 'text', text: 'synthetic hook text' },+ { type: 'tool_result', tool_use_id: 'synthetic-tool', content: 'synthetic result payload', is_error: true },+ { type: 'image', source: { data: 'synthetic image payload' } },+ ], { origin: { kind: 'hook' } }),+ user([{ type: 'text', text: 'synthetic task text' }], { origin: { kind: 'task' } }),+ user('synthetic future-origin text', { origin: { kind: 'future-automation' } }),+ { type: 'system', subtype: 'compact_boundary' },+ { type: 'assistant', message: { role: 'assistant', content: 'synthetic final reply' } },+ ]);+ const hook = parseTranscript(path, { collectToolCalls: true });+ expect(hook.turns.map((turn) => turn.text)).toEqual([+ 'synthetic prompt', '[tool: Read]', '[tool result]\n[image]', 'synthetic final reply',+ ]);+ expect(hook.genuineUserTurnIndexes).toEqual([0]);+ expect(hook.boundaryTurnIndexes).toEqual([3]);+ expect(hook.toolCallTurnIndexes).toEqual([1]);+ expect(hook.toolCalls).toEqual([+ { name: 'Read', input: { file_path: '/synthetic/example.txt' }, result: { ok: false } },+ ]);+ expect(parseTranscript(path).toolCalls).toEqual([]);+ expect(parseClaudeSessionFile(path).turns.map((turn) => turn.text)).toEqual(hook.turns.map((turn) => turn.text));+ });++ test('assistant-only output does not count as an accepted user prompt in compatibility mode', () => {+ const path = transcript([+ user('synthetic hook text', { origin: { kind: 'hook' } }),+ { type: 'assistant', message: { role: 'assistant', content: 'synthetic assistant reply' } },+ ]);+ const hook = parseTranscript(path);+ expect(hook.turns).toEqual([{ role: 'assistant', text: 'synthetic assistant reply' }]);+ expect(hook.genuineUserTurnIndexes).toEqual([]);+ expect(parseClaudeSessionFile(path).turns.map((turn) => turn.text)).toEqual(['synthetic assistant reply']);+ });++ test('root metadata entries cannot contribute orphaned tool calls or results', () => {+ const path = transcript([+ { type: 'assistant', isMeta: true, message: { role: 'assistant', content: [+ { type: 'tool_use', id: 'synthetic-meta-tool', name: 'Read', input: { file_path: '/synthetic/meta.txt' } },+ ] } },+ { type: 'assistant', origin: { kind: 'agent' }, message: { role: 'assistant', content: [+ { type: 'text', text: 'synthetic assistant text' },+ { type: 'tool_use', id: 'synthetic-tool', name: 'Read', input: { file_path: '/synthetic/example.txt' } },+ ] } },+ user([{ type: 'tool_result', tool_use_id: 'synthetic-tool', content: 'synthetic summary result' }], { isCompactSummary: true }),+ ]);+ const hook = parseTranscript(path, { collectToolCalls: true });+ expect(hook.turns).toEqual([{ role: 'assistant', text: 'synthetic assistant text\n[tool: Read]' }]);+ expect(hook.toolCalls).toEqual([{ name: 'Read', input: { file_path: '/synthetic/example.txt' } }]);+ expect(hook.toolCallTurnIndexes).toEqual([0]);+ expect(parseClaudeSessionFile(path).turns.map((turn) => turn.text)).toEqual(hook.turns.map((turn) => turn.text));+ });++ test('intentionally filtered files are expected empty, while unrecognized human content still signals drift', async () => {+ const path = transcript([+ user('synthetic metadata text', { isMeta: true }),+ user('synthetic compact summary', { isCompactSummary: true }),+ user('synthetic hook text', { origin: { kind: 'hook' } }),+ user([{ type: 'text', text: 'synthetic task text' }], { origin: { kind: 'task' } }),+ ]);+ expect(parseTranscript(path).genuineUserTurnIndexes).toEqual([]);+ expect(parseClaudeSessionFile(path).turnShapedLines).toBe(0);+ const empty = await claudeCodeAdapter.parse(path).next();+ expect(empty.done).toBe(true);+ if (empty.done) {+ expect(empty.value.sessions).toBe(0);+ expect(empty.value.expectedEmpty).toBe(true);+ }++ writeFileSync(path, JSON.stringify(user({ unrecognized: 'synthetic human content' }, { origin: { kind: 'human' } })) + '\n');+ expect(parseClaudeSessionFile(path).turnShapedLines).toBe(1);+ const drift = await claudeCodeAdapter.parse(path).next();+ expect(drift.done).toBe(true);+ if (drift.done) {+ expect(drift.value.sessions).toBe(0);+ expect(drift.value.expectedEmpty).toBeUndefined();+ }+ });+});diff --git a/test/doctor-cycle-freshness.test.ts b/test/doctor-cycle-freshness.test.tsindex 5baf75bcc4..de6813fd10 100644--- a/test/doctor-cycle-freshness.test.ts+++ b/test/doctor-cycle-freshness.test.ts@@ -29,14 +29,12 @@ beforeEach(async () => {const NOW = Date.parse('2026-05-22T12:00:00.000Z');const agoH = (h: number) => new Date(NOW - h * 3600_000).toISOString();-async function seed(id: string, lastFullCycleAt?: string, opts: { local_path?: string | null } = {}): Promise<void> {- const config = lastFullCycleAt- ? JSON.stringify({ last_full_cycle_at: lastFullCycleAt })- : '{}';+async function seed(id: string, lastFullCycleAt?: string, opts: { local_path?: string | null; syncEnabled?: boolean } = {}): Promise<void> {+ const config = JSON.stringify({ last_full_cycle_at: lastFullCycleAt, syncEnabled: opts.syncEnabled });const localPath = opts.local_path === undefined ? `/tmp/${id}` : opts.local_path;await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config, archived, created_at)- VALUES ($1, $2, $3, $4::jsonb, false, NOW())+ VALUES ($1, $2, $3, $4::text::jsonb, false, NOW())ON CONFLICT (id) DO UPDATE SET local_path = EXCLUDED.local_path, config = EXCLUDED.config`,[id, id, localPath, config],);@@ -147,4 +145,20 @@ describe('doctor checkCycleFreshness', () => {expect(result.status).toBe('ok');expect(result.message).toMatch(/No federated sources/);});++ test('sync-disabled sources still report stale maintenance cycles', async () => {+ await seed('disabled-example', agoH(72), { syncEnabled: false });+ await seed('enabled-example', agoH(1), { syncEnabled: true });+ const result = await checkCycleFreshness(engine, { nowMs: NOW });+ expect(result.status).toBe('fail');+ expect(result.message).toContain("'disabled-example' last cycled 72h ago");+ expect(result.message).not.toContain('enabled-example');+ });++ test('sync-disabled sources with fresh maintenance cycles remain healthy', async () => {+ await seed('disabled-example', agoH(1), { syncEnabled: false });+ const result = await checkCycleFreshness(engine, { nowMs: NOW });+ expect(result.status).toBe('ok');+ expect(result.message).toBe('All 1 federated source(s) cycled recently');+ });});diff --git a/test/doctor-sync-policy.test.ts b/test/doctor-sync-policy.test.tsnew file mode 100644index 0000000000..39800475b5--- /dev/null+++ b/test/doctor-sync-policy.test.ts@@ -0,0 +1,88 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkSyncFreshness } from '../src/commands/doctor.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+const NOW = Date.parse('2026-05-22T12:00:00.000Z');+const agoH = (hours: number) => new Date(NOW - hours * 3600_000).toISOString();++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function seed(id: string, config: unknown, lastSyncAt: string | null = null): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path, config, last_sync_at)+ VALUES ($1, $1, $2, $3::text::jsonb, $4)`,+ [id, `/example/${id}`, JSON.stringify(config), lastSyncAt],+ );+}++describe('doctor sync freshness honors automatic sync policy', () => {+ for (const config of [{ syncEnabled: false }, JSON.stringify({ syncEnabled: false })]) {+ for (const localOnly of [false, true]) {+ test(`excludes never-synced and stale disabled sources (${typeof config}, localOnly=${localOnly})`, async () => {+ await seed('disabled-never', config);+ await seed('disabled-stale', config, agoH(120));+ const result = await checkSyncFreshness(engine, { nowMs: NOW, localOnly });+ expect(result.status).toBe('ok');+ expect(result.message).toBe('No federated sources to sync');+ expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 0, stale_count: 0 });+ });+ }+ }++ test('mixed sources keep enabled failures and count only sync-eligible sources', async () => {+ await seed('disabled-example', { syncEnabled: false });+ await seed('stale-example', { syncEnabled: true }, agoH(120));+ await seed('fresh-example', {}, agoH(1));+ const result = await checkSyncFreshness(engine, { nowMs: NOW });+ expect(result.status).toBe('fail');+ expect(result.message).toContain("'stale-example'");+ expect(result.message).not.toContain('disabled-example');+ expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 1, stale_count: 1 });+ });++ test.each([+ { syncEnabled: true },+ JSON.stringify({ syncEnabled: true }),+ {},+ null,+ 'invalid-json',+ { syncEnabled: 'false' },+ ])('only boolean false disables sync (%j)', async (config) => {+ await seed('enabled-example', config);+ const result = await checkSyncFreshness(engine, { nowMs: NOW });+ expect(result.status).toBe('fail');+ expect(result.message).toContain("'enabled-example' has never been synced");+ expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 0, stale_count: 1 });+ });++ test('legacy archived-column fallback also loads and honors config', async () => {+ await seed('disabled-example', { syncEnabled: false });+ let usedFallback = false;+ const legacyEngine = {+ executeRaw: async (sql: string) => {+ if (sql.includes('archived IS NOT TRUE')) throw new Error('column archived does not exist');+ usedFallback = true;+ return engine.executeRaw(sql);+ },+ } as unknown as BrainEngine;+ const result = await checkSyncFreshness(legacyEngine, { nowMs: NOW });+ expect(usedFallback).toBe(true);+ expect(result.status).toBe('ok');+ expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 0, stale_count: 0 });+ });+});diff --git a/test/google-clients.test.ts b/test/google-clients.test.tsindex fd7c9ff890..b015a47257 100644--- a/test/google-clients.test.ts+++ b/test/google-clients.test.ts@@ -899,6 +899,41 @@ describe('CalendarClient', () => {// ── PeopleClient ─────────────────────────────────────────────────────────────describe('PeopleClient', () => {+ test.each([null, {}, [null], ['invalid'], []])('malformed expiry details preserve typed errors: %j', async details => {+ for (const expired of [true, false]) {+ const h = makeHarness(() => json({ error: {+ code: 400,+ message: expired ? 'Sync token is expired.' : 'Invalid personFields',+ details,+ } }, 400));+ const people = new PeopleClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID);+ await expect(people.listConnections({ syncToken: 'stale' })).rejects.toBeInstanceOf(+ expired ? GoogleCursorExpiredError : CredentialError,+ );+ }+ });++ test.each([+ { message: 'Sync token is expired. Clear local cache and retry call without the sync token.' },+ { details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'EXPIRED_SYNC_TOKEN' }] },+ ])('HTTP 400 expired sync tokens surface cursor expiry: %j', async error => {+ const h = makeHarness(() => json({ error: { code: 400, ...error } }, 400));+ const people = new PeopleClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID);+ await expect(people.listConnections({ syncToken: 'stale' })).rejects.toBeInstanceOf(GoogleCursorExpiredError);+ });++ test.each([+ ['people', 'https://people.googleapis.com/v1/people/me/connections?syncToken=stale', { message: 'Invalid personFields' }],+ ['people', 'https://people.googleapis.com/v1/people/me/connections', { message: 'Sync token is expired.' }],+ ['gmail', 'https://gmail.googleapis.com/gmail/v1/users/me/history?syncToken=stale', { message: 'Sync token is expired.' }],+ ['calendar-json', 'https://www.googleapis.com/calendar/v3/calendars/primary/events?syncToken=stale', { message: 'Sync token is expired.' }],+ ['people', 'https://people.googleapis.com/v1/people/me/connections?syncToken=stale', { details: [{ reason: 'INVALID_ARGUMENT' }] }],+ ] as const)('other HTTP 400 errors remain upstream failures: %s %s', async (api, url, error) => {+ const h = makeHarness(() => json({ error: { code: 400, ...error } }, 400));+ const client = new GoogleApiClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID);+ await expect(client.fetchJSON(url, api)).rejects.toBeInstanceOf(CredentialError);+ });+test('listConnections requests personFields and normalizes contacts', async () => {const h = makeHarness((u) => {expect(u.searchParams.get('personFields')).toBe('names,emailAddresses,organizations');diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.tsindex 50065cf2d7..be37f7985c 100644--- a/test/google-source-reconcile.test.ts+++ b/test/google-source-reconcile.test.ts@@ -101,6 +101,7 @@ interface FakeGoogle {contacts: unknown[];contactsDelta: unknown[];contactsExpireSyncToken: boolean;+ contactsExpireSyncStatus?: number;calendarEvents: unknown[];calendarDelta: unknown[];calendarExpireSyncToken: boolean;@@ -213,7 +214,10 @@ function buildFetch(fx: FakeGoogle): FetchImpl {if (u.pathname.includes('/people/me/connections')) {if (u.searchParams.get('syncToken')) {- if (fx.contactsExpireSyncToken) return json({ error: { code: 410, message: 'Sync token expired' } }, 410);+ if (fx.contactsExpireSyncToken) {+ const status = fx.contactsExpireSyncStatus ?? 410;+ return json({ error: { code: status, message: 'Sync token expired' } }, status);+ }return json({ connections: fx.contactsDelta, nextSyncToken: 'ppl-sync-delta' });}fx.contactsFullLists++;@@ -843,6 +847,72 @@ describe('syncToken 410 recovery', () => {rmSync(dir, { recursive: true, force: true });}});++ test('contacts: HTTP 400 expiry recovers without restarting Gmail or losing the contact', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-ppl400-'));+ const fx = emptyFx();+ const vault = makeVault();+ fx.contacts = [{+ resourceName: 'people/c000000001',+ names: [{ displayName: 'Alice Example', metadata: { primary: true } }],+ emailAddresses: [{ value: '[email protected]' }],+ }];+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'contacts');+ expect(readGoogleState(dir).contacts_sync_token).toBe('ppl-sync-w1');+ fx.contactsExpireSyncToken = true;+ fx.contactsExpireSyncStatus = 400;+ const result = await sweep(dir, fx, vault, {}, 'contacts');+ expect(result.status).not.toBe('partial');+ expect(readGoogleState(dir).contacts_sync_token).toBe('ppl-sync-w2');+ expect(fx.contactsFullLists).toBe(2);+ expect(fx.calls.some(call => call.includes('/people/me/connections?') && call.includes('syncToken=ppl-sync-w1'))).toBe(true);+ expect(fx.calls.some(call => call.includes('/gmail/'))).toBe(false);+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id = 'gsrc' AND deleted_at IS NULL AND slug = 'people/alice-example'`,+ );+ expect(rows).toHaveLength(1);+ fx.contactsExpireSyncToken = false;+ await sweep(dir, fx, vault, {}, 'contacts');+ expect(fx.contactsFullLists).toBe(2);+ expect(readGoogleState(dir).contacts_sync_token).toBe('ppl-sync-delta');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('contacts: HTTP 400 recovery preserves incremental Gmail in an all-services sync', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-ppl400-all-'));+ const fx = emptyFx();+ fx.contactsExpireSyncToken = true;+ fx.contactsExpireSyncStatus = 400;+ fx.historyResponseId = '2000';+ try {+ await insertGoogleSource(dir);+ writeBackfilledState(dir);+ const before = readGoogleState(dir);+ writeFileSync(googleStateFile(dir), JSON.stringify({ ...before, contacts_sync_token: 'expired' }));+ await withHome(async () => {+ const result = await sweep(dir, fx, makeVault(), {}, 'gmail,calendar,contacts');+ expect(result.status).not.toBe('partial');+ expect(fx.contactsFullLists).toBe(1);+ const after = readGoogleState(dir);+ expect(after.contacts_sync_token).toBe('ppl-sync-w1');+ expect(after.gmail_backfill_done).toBe(true);+ expect(after.gmail_backfill_floor_ms).toBe(before.gmail_backfill_floor_ms);+ expect(after.gmail_history_id).toBe('2000');+ expect(fx.calls.filter(call => call.includes('/users/me/history'))).toEqual([+ expect.stringContaining('startHistoryId=1000'),+ ]);+ expect(fx.calls.some(call => call.includes('/users/me/messages') || call.includes('/users/me/profile'))).toBe(false);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });});// ── loops_extract enqueue completeness ───────────────────────────────────────diff --git a/test/import-json-stdout.serial.test.ts b/test/import-json-stdout.serial.test.tsindex a46753528d..1e08415276 100644--- a/test/import-json-stdout.serial.test.ts+++ b/test/import-json-stdout.serial.test.ts@@ -143,12 +143,15 @@ describe('import --json stdout is parseable JSON (#3637) and lists per-file failexpect(mixedJson.failures[0].path).toBe('broken.md');expect(mixedJson.failures[0].error).toContain('Invalid YAML frontmatter');- // A failed import retains its checkpoint: a normal retry only processes- // the failed document and reports its error again.+ // A failed import retains its checkpoint: a normal retry rechecks content+ // hashes and reports the failed document's error again.const resumed = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);expect(resumed.exitCode).toBe(1);+ expect(resumed.stdout.trim().split('\n')).toHaveLength(1);+ expect(resumed.stderr).toContain('Resuming from checkpoint: re-checking current files via content_hash (1 previously completed)');expect(JSON.parse(resumed.stdout)).toMatchObject({- status: 'partial', total_files: 2, imported: 0, skipped: 1, errors: 1, unchanged: 0,+ status: 'partial', total_files: 2, imported: 0, skipped: 2, errors: 1, unchanged: 1,+ failures: mixedJson.failures,});// A fresh re-import scans both files: the good note is a content-hash no-op anddiff --git a/test/import-resume.test.ts b/test/import-resume.test.tsindex bd1bf08080..4eff5e1e85 100644--- a/test/import-resume.test.ts+++ b/test/import-resume.test.ts@@ -7,7 +7,7 @@** - Old positional checkpoints from pre-v0.33.2 brains are discarded* cleanly + the migration stderr log fires.- * - v0.33.2 path-based checkpoints honor the completedPaths set on resume.+ * - Path-based checkpoints re-check content hashes on resume.* - Failed files do NOT enter `completedPaths`; the next run retries them* (the pre-existing P1 codex caught).* - Clean completion clears the checkpoint.@@ -19,8 +19,8 @@* - PGLite via the canonical block (`beforeAll` + `resetPgliteState` +* `afterAll`) per CLAUDE.md test-isolation rules R3 + R4.*/-import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, realpathSync, chmodSync } from 'fs';+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';+import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, realpathSync, chmodSync, statSync, utimesSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -117,6 +117,9 @@ describe('runImport checkpoint resume — v0.33.2 path-based', () => {await withEnv({ GBRAIN_HOME: workspace }, async () => {writeBrainFile('a.md', validMarkdown('a'));writeBrainFile('b.md', validMarkdown('b'));+ expect((await runImport(engine, [brainDir, '--no-embed'])).imported).toBe(2);+ const originalChunks = await engine.getChunks('a', { sourceId: 'default' });+ expect(originalChunks.length).toBeGreaterThan(0);writeBrainFile('c.md', validMarkdown('c'));// Plant a v0.33.2 checkpoint that says a.md and b.md are done.@@ -127,9 +130,10 @@ describe('runImport checkpoint resume — v0.33.2 path-based', () => {}));const result = await runImport(engine, [brainDir, '--no-embed']);- // Only c.md should have been imported this run. The other two are- // already in `completed` and got filtered out before processFile.expect(result.imported).toBe(1);+ expect(result.skipped).toBe(2);+ expect(result.errors).toBe(0);+ expect(await engine.getChunks('a', { sourceId: 'default' })).toEqual(originalChunks);});}, 30_000);@@ -150,6 +154,114 @@ describe('runImport checkpoint resume — v0.33.2 path-based', () => {});}, 30_000);+ test.each(['newer mtime', 'preserved mtime'])('preserved checkpoint rechecks edited files with %s', async (mtimeMode) => {+ await withEnv({ GBRAIN_HOME: workspace }, async () => {+ writeBrainFile('changed-example.md', validMarkdown('changed-example', 'Original example'));+ writeBrainFile('stable-example.md', validMarkdown('stable-example'));+ writeBrainFile('invalid-example.md', validMarkdown('wrong-example'));+ const filePath = join(brainDir, 'changed-example.md');+ const originalTime = new Date('2026-01-01T00:00:00Z');+ utimesSync(filePath, originalTime, originalTime);++ const first = await runImport(engine, [brainDir, '--no-embed']);+ expect(first.imported).toBe(2);+ expect(first.errors).toBe(1);+ const checkpoint = JSON.parse(readFileSync(cpPath, 'utf8'));+ expect(checkpoint.completedPaths).toEqual(['changed-example.md', 'stable-example.md']);+ const stableChunks = await engine.getChunks('stable-example', { sourceId: 'default' });+ expect(stableChunks.length).toBeGreaterThan(0);++ writeBrainFile('changed-example.md', validMarkdown('changed-example', 'Modified example'));+ const editedTime = mtimeMode === 'preserved mtime'+ ? originalTime+ : new Date(Date.parse(checkpoint.timestamp) + 60_000);+ utimesSync(filePath, editedTime, editedTime);+ expect(statSync(filePath).mtimeMs).toBe(editedTime.getTime());+ writeBrainFile('new-example.md', validMarkdown('new-example'));++ const second = await runImport(engine, [brainDir, '--no-embed']);+ expect(second.imported).toBe(2);+ expect(second.errors).toBe(1);+ expect(second.failures.map(failure => failure.path)).toEqual(['invalid-example.md']);+ expect((await engine.getPage('changed-example', { sourceId: 'default' }))?.title).toBe('Modified example');+ expect(await engine.getPage('new-example', { sourceId: 'default' })).not.toBeNull();+ expect(await engine.getChunks('stable-example', { sourceId: 'default' })).toEqual(stableChunks);+ expect(JSON.parse(readFileSync(cpPath, 'utf8')).completedPaths).toEqual([+ 'changed-example.md', 'new-example.md', 'stable-example.md',+ ]);+ });+ }, 60_000);++ test('file edited after its database commit but before checkpoint flush is rechecked', async () => {+ await withEnv({ GBRAIN_HOME: workspace }, async () => {+ writeBrainFile('changed-example.md', validMarkdown('changed-example', 'Original example'));+ writeBrainFile('invalid-example.md', validMarkdown('wrong-example'));+ const filePath = join(brainDir, 'changed-example.md');+ const originalTransaction = engine.transaction;+ let edited = false;+ const transaction = spyOn(engine, 'transaction').mockImplementation(async function (this: PGLiteEngine, fn) {+ const result = await originalTransaction.bind(this)(fn);+ if (this === engine && !edited && await engine.getPage('changed-example', { sourceId: 'default' })) {+ edited = true;+ writeBrainFile('changed-example.md', validMarkdown('changed-example', 'Modified example'));+ }+ return result;+ });+ try {+ const first = await runImport(engine, [brainDir, '--no-embed']);+ expect(first.imported).toBe(1);+ expect(first.errors).toBe(1);+ } finally {+ transaction.mockRestore();+ }+ expect(edited).toBe(true);+ expect((await engine.getPage('changed-example', { sourceId: 'default' }))?.title).toBe('Original example');+ const checkpoint = JSON.parse(readFileSync(cpPath, 'utf8'));+ expect(checkpoint.completedPaths).toEqual(['changed-example.md']);+ expect(Math.floor(statSync(filePath).mtimeMs)).toBeLessThanOrEqual(Date.parse(checkpoint.timestamp));++ const second = await runImport(engine, [brainDir, '--no-embed']);+ expect(second.imported).toBe(1);+ expect(second.errors).toBe(1);+ expect((await engine.getPage('changed-example', { sourceId: 'default' }))?.title).toBe('Modified example');+ });+ }, 60_000);++ test('a checkpoint from another source rechecks completed files without changing the original source', async () => {+ await withEnv({ GBRAIN_HOME: workspace }, async () => {+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('source-a-example', 'source-a-example'), ('source-b-example', 'source-b-example')`,+ );+ writeBrainFile('good-example.md', validMarkdown('good-example'));+ writeBrainFile('invalid-example.md', validMarkdown('wrong-example'));++ const first = await runImport(engine, [brainDir, '--no-embed', '--source-id', 'source-a-example']);+ expect(first.imported).toBe(1);+ expect(first.errors).toBe(1);+ expect(first.failures.map(failure => failure.path)).toEqual(['invalid-example.md']);+ expect(JSON.parse(readFileSync(cpPath, 'utf8')).completedPaths).toEqual(['good-example.md']);+ const originalPage = await engine.getPage('good-example', { sourceId: 'source-a-example' });+ const originalChunks = await engine.getChunks('good-example', { sourceId: 'source-a-example' });+ expect(originalPage).not.toBeNull();+ expect(originalChunks.length).toBeGreaterThan(0);+ expect(await engine.getPage('good-example', { sourceId: 'source-b-example' })).toBeNull();++ const second = await runImport(engine, [brainDir, '--no-embed', '--source-id', 'source-b-example']);+ expect(second.imported).toBe(1);+ expect(second.errors).toBe(1);+ expect(second.failures).toEqual(first.failures);+ const secondPage = await engine.getPage('good-example', { sourceId: 'source-b-example' });+ expect(secondPage).not.toBeNull();+ expect(secondPage?.id).not.toBe(originalPage?.id);+ expect(secondPage?.content_hash).toBe(originalPage?.content_hash);+ expect((await engine.getChunks('good-example', { sourceId: 'source-b-example' })).length).toBe(originalChunks.length);+ expect(await engine.getPage('invalid-example', { sourceId: 'source-b-example' })).toBeNull();+ expect(await engine.getPage('good-example', { sourceId: 'source-a-example' })).toEqual(originalPage);+ expect(await engine.getChunks('good-example', { sourceId: 'source-a-example' })).toEqual(originalChunks);+ expect(JSON.parse(readFileSync(cpPath, 'utf8')).completedPaths).toEqual(['good-example.md']);+ });+ }, 60_000);+// skipIf: forces the error path via a chmod-000 file — unrunnable on hosts// that don't enforce permission bits (the read succeeds, errors stays 0,// and the checkpoint is legitimately cleared).diff --git a/test/schema-cli-lint-with-db.test.ts b/test/schema-cli-lint-with-db.test.tsnew file mode 100644index 0000000000..3b467e4e9b--- /dev/null+++ b/test/schema-cli-lint-with-db.test.ts@@ -0,0 +1,65 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';++let home: string;++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-schema-lint-with-db-'));+ const init = await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { home });+ expect(init.exitCode, init.stderr).toBe(0);+ const config = await runCli(['config', 'set', 'schema_pack', 'gbrain-base'], { home });+ expect(config.exitCode, config.stderr).toBe(0);+}, 120_000);++afterAll(() => {+ rmSync(home, { recursive: true, force: true });+});++describe('schema lint DB-plane arguments', () => {+ test.each([+ { args: ['--with-db'] },+ { args: ['--with-db', 'gbrain-base'] },+ { args: ['gbrain-base', '--with-db'] },+ { args: ['--source', 'example-source', '--with-db'] },+ { args: ['--with-db', '--source-id=example-source'] },+ ])('runs DB lint with %j', async ({ args }) => {+ const result = await runCli(['schema', 'lint', ...args, '--json'], { home });+ expect(result.exitCode, result.stderr).toBe(0);+ const report = JSON.parse(result.stdout);+ expect(report.pack).toBe('gbrain-base');+ expect(report.ok).toBe(true);+ expect(report.warnings.some((warning: { rule: string }) => warning.rule === 'extractable_empty_corpus')).toBe(true);+ });++ test.each([+ { args: ['--with-db', 'missing-example-pack'] },+ { args: ['missing-example-pack', '--with-db'] },+ ])('reports the missing pack with %j', async ({ args }) => {+ const result = await runCli(['schema', 'lint', ...args], { home });+ expect(result.exitCode).toBe(1);+ expect(result.stderr).toContain('Pack not found: missing-example-pack');+ expect(result.stderr).not.toContain('Pack not found: --with-db');+ });++ test('plain lint does not run DB-plane rules', async () => {+ const result = await runCli(['schema', 'lint', '--json'], { home });+ expect(result.exitCode, result.stderr).toBe(0);+ const report = JSON.parse(result.stdout);+ expect(report.pack).toBe('gbrain-base');+ expect(report.warnings.some((warning: { rule: string }) => warning.rule === 'extractable_empty_corpus')).toBe(false);+ });++ test.each([+ { args: ['gbrain-base', '--pack', 'gbrain-recommended'] },+ { args: ['gbrain-base', '--force'] },+ { args: ['gbrain-base', 'gbrain-recommended'] },+ { args: ['--with-db=false'] },+ ])('rejects unsupported lint arguments %j', async ({ args }) => {+ const result = await runCli(['schema', 'lint', ...args], { home });+ expect(result.exitCode).not.toBe(0);+ expect(result.stdout).not.toContain('lint clean');+ });+});diff --git a/test/skill-catalog-optional-tools.test.ts b/test/skill-catalog-optional-tools.test.tsnew file mode 100644index 0000000000..7f57888c42--- /dev/null+++ b/test/skill-catalog-optional-tools.test.ts@@ -0,0 +1,145 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { buildSkillCatalog, crossReferenceTools, getSkillDetail } from '../src/core/skill-catalog.ts';++describe('published skill optional tool metadata', () => {+ describe('registered stdio', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ beforeEach(async () => { await resetPgliteState(engine); });+ afterAll(async () => { await engine.disconnect(); });++ test.each([+ { scopes: ['read'], operations: null, expected: ['search'] },+ { scopes: ['read', 'write'], operations: null, expected: ['search', 'put_page'] },+ { scopes: ['read', 'write', 'skill_editor'], operations: null, expected: ['search', 'put_page', 'put_skill'] },+ { scopes: ['read', 'write', 'skill_editor'], operations: ['search'], expected: ['search'] },+ ])('registered stdio inventories honor the verified grant: %j', async ({ scopes, operations, expected }) => {+ const expectedTools: string[] = [...expected];+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-registered-skill-tools-'));+ try {+ const registration = { id: '00000000-0000-4000-8000-000000000123', credential: 'synthetic-test-credential', lane: 'stdio' as const };+ await engine.executeRaw('INSERT INTO persistence_local_writers (id, lane, credential_hash, grant_ceiling) VALUES ($1, $2, $3, $4::jsonb)', [+ registration.id, registration.lane, sha256(registration.credential),+ { sourceIds: ['*'], operations, scopes, slugPrefixes: null },+ ]);+ mkdirSync(join(dir, 'portable'));+ writeFileSync(join(dir, 'portable', 'SKILL.md'), '---\nname: portable\ndescription: A portable skill\n---\n\nRead the brain.\n');+ await withVerifiedLocalRegistration(engine, registration, async () => {+ const ctx = { remote: true, transport: 'stdio' } as OperationContext;+ const catalog = buildSkillCatalog(ctx, dir, 'config', { gateDisabled: new Set() });+ const detail = getSkillDetail(ctx, dir, 'portable', { gateDisabled: new Set() });+ const probes = ['search', 'put_page', 'put_skill'];+ for (const inventory of [catalog.skills[0].usable_tools, catalog.instructions.available_brain_tools, detail.usable_tools, detail.client_guidance.available_brain_tools]) {+ expect(probes.filter(name => inventory.includes(name))).toEqual(expectedTools);+ }+ expect(crossReferenceTools(probes, ctx, new Set())).toEqual({+ usable_tools: expectedTools,+ unavailable_tools: probes.filter(name => !expectedTools.includes(name)),+ });+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+ });+ test.each([+ { scopes: ['admin'], allowed: false },+ { scopes: ['write'], allowed: false },+ { scopes: ['write', 'skill_editor'], allowed: true },+ ])('shared-skill writes require the explicit editor grant: %j', ({ scopes, allowed }) => {+ for (const transport of [undefined, 'stdio'] as const) {+ const ctx = { remote: true, transport, auth: { token: 'test-token', clientId: 'test-client', scopes: [...scopes] } } as OperationContext;+ const tools = crossReferenceTools(['put_skill'], ctx, new Set());+ expect(tools.usable_tools).toEqual(allowed ? ['put_skill'] : []);+ expect(tools.unavailable_tools).toEqual(allowed ? [] : ['put_skill']);+ }+ });++ test('unregistered stdio cannot inherit explicitly granted shared-skill operations', () => {+ const tools = crossReferenceTools(['put_skill', 'search'], { remote: true, transport: 'stdio' } as OperationContext, new Set());+ expect(tools.usable_tools).toEqual(['search']);+ expect(tools.unavailable_tools).toEqual(['put_skill']);+ });++ test.each([+ { auth: { token: 'test-token', clientId: 'test-client', scopes: ['admin'], effectiveSurface: 'verbs' as const } },+ { transport: 'stdio' as const, surfaceCeiling: 'verbs' as const },+ ])('tool inventories respect the effective surface: %j', context => {+ const tools = crossReferenceTools(['remember', 'search'], { remote: true, ...context } as OperationContext, new Set());+ expect(tools.usable_tools).toEqual(['remember']);+ expect(tools.unavailable_tools).toEqual(['search']);+ });++ test.each([+ ['omitted', 'name: portable\ndescription: A portable skill', true],+ ['explicit empty', 'name: portable\ntools: []', false],+ ['invalid type', 'name: portable\ntools: search', false],+ ['malformed YAML', 'name: portable\ndescription: [unfinished', false],+ ['no frontmatter', '', false],+ ] as const)('%s tool metadata agrees across list and detail', (_label, raw, inherits) => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-skill-tools-'));+ try {+ mkdirSync(join(dir, 'portable'));+ writeFileSync(join(dir, 'portable', 'SKILL.md'), raw ? `---\n${raw}\n---\n\nRead the brain.\n` : 'Read the brain.\n');+ const ctx = {+ remote: true,+ auth: { token: 'test-token', clientId: 'test-client', scopes: ['read'] },+ } as OperationContext;+ const catalog = buildSkillCatalog(ctx, dir, 'config');+ const skill = catalog.skills.find(s => s.name === 'portable')!;+ const detail = getSkillDetail(ctx, dir, 'portable');+ expect(skill).toBeDefined();+ expect(skill.tools).toEqual([]);+ expect(skill.usable_tools).toEqual(inherits ? catalog.instructions.available_brain_tools : []);+ expect(detail.usable_tools).toEqual(skill.usable_tools);+ expect(skill.unavailable_tools).toEqual([]);+ expect(detail.unavailable_tools).toEqual([]);+ expect(detail.usable_tools).not.toContain('put_page');+ if (inherits) {+ expect(detail.usable_tools).toContain('search');+ expect(detail.usable_tools).toContain('query');+ expect(detail.frontmatter.tools).toBeUndefined();+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test.each([+ { remote: true, transport: 'stdio' },+ { remote: false },+ { remote: true, auth: { token: 'test-token', clientId: 'test-client', scopes: ['admin'] } },+ { remote: true, auth: { token: 'test-token', clientId: 'test-client', scopes: [] } },+ ] as const)('omitted tools inherit only the effective caller inventory: %j', context => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-skill-tools-'));+ try {+ mkdirSync(join(dir, 'portable'));+ writeFileSync(join(dir, 'portable', 'SKILL.md'), '---\nname: portable\n---\nRead the brain.\n');+ const ctx = context as OperationContext;+ const catalog = buildSkillCatalog(ctx, dir, 'config');+ const detail = getSkillDetail(ctx, dir, 'portable');+ expect(detail.usable_tools).toEqual(catalog.instructions.available_brain_tools);+ expect(catalog.skills[0].usable_tools).toEqual(detail.usable_tools);+ expect(detail.usable_tools.includes('purge_deleted_pages')).toBe(context.remote === false);+ if (context.remote === false || 'transport' in context || context.auth.scopes.length > 0) {+ expect(detail.usable_tools).toContain('put_page');+ } else {+ expect(detail.usable_tools).toEqual([]);+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/skill-catalog-transports.test.ts b/test/skill-catalog-transports.test.tsindex ba621db0a8..f22599972e 100644--- a/test/skill-catalog-transports.test.ts+++ b/test/skill-catalog-transports.test.ts@@ -12,7 +12,7 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { join } from 'path';-import { mkdtempSync, rmSync } from 'fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';@@ -60,6 +60,79 @@ async function call(}describe('list_skills over dispatch', () => {+ const boundClientCases: { auth: Partial<AuthInfo>; denied: string; allowed: string }[] = [+ { auth: { allowedOperations: ['list_skills', 'get_skill', 'search'] }, denied: 'query', allowed: 'search' },+ { auth: { boundSlugPrefixes: ['wiki/agents/example'] }, denied: 'remember', allowed: 'put_page' },+ { auth: { fenceProjectionDegraded: true }, denied: 'put_page', allowed: 'search' },+ ];+ test.each(boundClientCases)('tool inventories honor operation grants and bound-client fences: %j', async ({ auth, denied, allowed }) => {+ const dir = mkdtempSync(join(home, 'fenced-skills-'));+ try {+ for (const name of ['portable', 'declared']) {+ mkdirSync(join(dir, name));+ writeFileSync(join(dir, name, 'SKILL.md'), `---\nname: ${name}\n${name === 'declared' ? `tools: [${denied}, ${allowed}]\n` : ''}---\nRead the brain.\n`);+ }+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.setConfig('mcp.skills_dir', dir);+ await engine.setConfig('mcp.publish_skills', 'true');+ for (const transport of [undefined, 'stdio'] as const) {+ const opts = { remote: true, auth: { token: 't', clientId: 'c', scopes: ['read', 'write'], ...auth }, transport };+ const list = await call('list_skills', {}, opts);+ expect(list.isError).toBe(false);+ expect(list.body.instructions.available_brain_tools).not.toContain(denied);+ expect(list.body.instructions.available_brain_tools).toContain(allowed);+ for (const name of ['portable', 'declared']) {+ const listed = list.body.skills.find((skill: { name: string }) => skill.name === name);+ const detail = await call('get_skill', { name }, opts);+ expect(detail.isError).toBe(false);+ expect(detail.body.usable_tools).toEqual(listed.usable_tools);+ expect(detail.body.usable_tools).not.toContain(denied);+ expect(detail.body.usable_tools).toContain(allowed);+ expect(detail.body.client_guidance.available_brain_tools).not.toContain(denied);+ expect(detail.body.unavailable_tools.includes(denied)).toBe(name === 'declared');+ }+ }+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('inherited and declared tool inventories honor live publication gates in both catalog paths', async () => {+ const dir = mkdtempSync(join(home, 'published-skills-'));+ try {+ for (const name of ['portable', 'declared']) {+ mkdirSync(join(dir, name));+ writeFileSync(join(dir, name, 'SKILL.md'), `---\nname: ${name}\n${name === 'declared' ? 'tools: [advisor, search]\n' : ''}---\nRead the brain.\n`);+ }+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.setConfig('mcp.skills_dir', dir);+ await engine.setConfig('mcp.publish_skills', 'true');+ for (const enabled of [false, true, false]) {+ await engine.setConfig('mcp.publish_advisor', String(enabled));+ for (const transport of [undefined, 'stdio'] as const) {+ const opts = { remote: true, auth: { token: 't', clientId: 'c', scopes: ['read'] }, transport };+ const list = await call('list_skills', {}, opts);+ expect(list.isError).toBe(false);+ expect(list.body.instructions.available_brain_tools.includes('advisor')).toBe(enabled);+ for (const name of ['portable', 'declared']) {+ const listed = list.body.skills.find((skill: { name: string }) => skill.name === name);+ const detail = await call('get_skill', { name }, opts);+ expect(detail.isError).toBe(false);+ expect(detail.body.usable_tools).toEqual(listed.usable_tools);+ expect(detail.body.usable_tools.includes('advisor')).toBe(enabled);+ expect(detail.body.client_guidance.available_brain_tools.includes('advisor')).toBe(enabled);+ expect(detail.body.usable_tools).toContain('search');+ if (name === 'declared') expect(detail.body.unavailable_tools.includes('advisor')).toBe(!enabled);+ }+ }+ }+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+test('HTTP-remote + gate OFF → permission_denied', async () => {await withEnv({ GBRAIN_HOME: home }, async () => {const r = await call('list_skills', {}, { remote: true, auth: { token: 't', clientId: 'c', scopes: ['read'] } });