Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): pass and lease readers decide from one observation on the database clock; unrecorded stops end the pass resumable; a lean read-only serve binds its own read socket (#7611, #7612, #7614)
garrytan618d0a25d027
diff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.mdindex 455e4cc1d9..eb9790f52a 100644--- a/docs/architecture/key-files/core-services-1-continued.md+++ b/docs/architecture/key-files/core-services-1-continued.md@@ -9,7 +9,7 @@ The content-repair judgment tier under `src/core/content-repair/`, then the Retr- `src/core/content-repair/judgment.ts` — #6377 (Lane B3) the content-repair lane's model tier for a slug conflict: `judgeSlugConflict` builds the prompt from both files' frontmatter, headings and first 60 lines of body plus every line that mentions the other's slug anywhere in either body (evidence past line 60 counts), both slugs and paths, the hold's reason and the allowed answers, and parses exactly one JSON object `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}` with an optional `why` sentence that reaches the run's output only, never hold metadata. The same failure classes, `thinkingOffControl` and output ceiling as the fence tier; a `canonical` outside the two slugs is `llm_malformed`. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. The model is `models.content_repair` (an explicit model always runs), else `models.fence_repair`, else `CONTENT_REPAIR_MEASURED_MODELS` (the eval's qualifiers, best first, ties to the cheaper), else the fence list. Tests: `test/repair-slug-conflicts.test.ts`.- `src/core/content-repair/llm.ts` — #6377 (Lane B3) the paid call behind `judgment.ts`: one gateway chat under the fence repair's caps and ledger (`FENCE_REPAIR_LEDGER`, so one `fences.repair.max_usd_per_day` covers the whole lane and today's fence spend counts; the per-page cap applies per candidate), `fences.repair.llm=false` and `--no-llm` turn it off, the attempt memo keeps rejected bytes from costing twice, and a transient `llm_unavailable` does not consume the memo. Spend is reported as the item's `llm_usd` and carried into the `content_repair` receipt (`model`, `cost`); prompts never include the rest of either page.-- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (`writer_lock_unavailable`, before any model call) re-queued after 5, 15 and 45 s (`writer_busy_requeued`; the retry skips admission, a pending retry dedups a re-schedule as `already_queued`, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code or `reason` within the 48-char reason-code shape (`operationerror:writer_lock_unavailable`), the first failure of each reason logged to stderr once per serve run — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195: `entity-salience.extractCandidates` also emits lowercase 2-3-word weak n-grams (`multiToken`, own budget `MAX_WEAK_NGRAM_CANDIDATES` = 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, and `retrieval-reflex` arm 2.6 (`weak-title`, 0.72, behind `lexicalArms`, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.+- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). A lean read-only Postgres serve binds the `read` socket kind instead (#7612); `hookResolveSocketForConfig` falls back to it after the source socket, and a `delegation: true` caller never targets it. Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (`writer_lock_unavailable`, before any model call) re-queued after 5, 15 and 45 s (`writer_busy_requeued`; the retry skips admission, a pending retry dedups a re-schedule as `already_queued`, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code or `reason` within the 48-char reason-code shape (`operationerror:writer_lock_unavailable`), the first failure of each reason logged to stderr once per serve run — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195: `entity-salience.extractCandidates` also emits lowercase 2-3-word weak n-grams (`multiToken`, own budget `MAX_WEAK_NGRAM_CANDIDATES` = 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, and `retrieval-reflex` arm 2.6 (`weak-title`, 0.72, behind `lexicalArms`, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex acf95c2a4d..51701d1332 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/result-rows.ts` — the transport side of the `search`/`query` row shape. `resolveResultRowsMode(engine, config)`: dual-plane `mcp.result_rows` (DB > file > 'lean'; a failed DB read falls to the file plane). `resultRowsForRequest(header, hostMode)`: the `X-Gbrain-Client` header naming `gbrain-remote-cli` (sent by `src/core/mcp-client.ts`) selects full rows, otherwise the host mode. The OAuth HTTP transport resolves both per request, the legacy bearer transport per tools/call, and stdio once at start (file plane only when the engine is degraded). The header is unverified and selects a row shape only; it must never gate anything security-relevant. Pinned by `test/mcp-result-rows-skew.test.ts`.-- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. `turn_context` and `context_pack` (`context-pack-handler.ts`) read `context.hot_memory.session_only` per request (`readHotMemorySessionOnly`) and pass it as `sessionOnly` to the assembler (pinned by `test/hot-memory-session-only-7026.test.ts`). Pinned by `test/resolve-ipc-binding.test.ts`.+- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. `turn_context` and `context_pack` (`context-pack-handler.ts`) read `context.hot_memory.session_only` per request (`readHotMemorySessionOnly`) and pass it as `sessionOnly` to the assembler (pinned by `test/hot-memory-session-only-7026.test.ts`). Pinned by `test/resolve-ipc-binding.test.ts`. #7612: a lean serve (`lean`, a read-only stdio serve on Postgres) binds only its read socket (`resolveSocketPathForConfig(cfg, 'read', source)`: resolve, turn_context and context_pack), never the source or legacy socket, so a read-write serve started later for the same source holds both and answers delegated sync instead of `unsupported_kind`. Hooks try the source socket, then the read socket, then legacy; `src/commands/sync-delegate.ts` passes `{ delegation: true }` to skip the read socket (pinned by `test/resolve-ipc-source-keyed.test.ts` and `test/e2e/serve-read-only-session-lane-postgres.test.ts`).- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep; #7599: a read-only stdio serve on Postgres (`readOnlyServeSkipsResidentDuties`) binds IPC with no delegation kinds (`lean`), starts no consumer, runs no session-cursor GC or startup sweep and writes `READ_ONLY_SERVE_NOTE` to stderr; PGLite keeps all of it) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`. Each tool call resolves its source inside one request config snapshot that dispatch reuses for a read op (the config table is read alongside the source rows), so the pre-op reads cost one round trip (GBRA-156).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex f9eb3dbe08..e2b9f30e70 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1523 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)-src/core/behavior-change-notice.ts 1505 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: the GBRA-95 RLS backfill row (+2) and +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling; the behavior-change table split (#7607) retires this row+src/core/behavior-change-notice.ts 1507 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: the GBRA-95 RLS backfill row (+2) and +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling; +2 rows for #7611/#7614 sync pass readers and #7612 the lean serve read socket; the behavior-change table split (#7607) retires this rowdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex b2a3f9a703..9813fa7596 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -371,7 +371,7 @@ test/serve-head-watcher-managed.serial.test.ts global-state global-state: startstest/serve-http-head-watcher.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SERVE_HEAD_POLL_MS); spies on global setInterval/clearInterval, emits SIGINT on the process and reads the process-wide cleanup registrytest/serve-http-run-teardown.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/serve-http-status-mode.serial.test.ts R1 R1: sets process.env.GBRAIN_HOME for the status marker reads; binds local servers/ports-test/serve-idle-sweep-source.serial.test.ts R2 R2: mock.module(../src/core/sweep.ts) replaces modules for every file in the process+test/serve-idle-sweep-source.serial.test.ts R2 R2: mock.module(../src/core/sweep.ts, facts/drain-scheduler.ts, persistence/sync-movement.ts, serve-head-watcher.ts) replaces modules for every file in the processtest/serve-source-guard.serial.test.ts R1 R1: mutates process.env (GBRAIN_SOURCE)test/serve-status-mode.serial.test.ts global-state global-state: binds local servers/portstest/serve-sync-embed-drain.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests, __resetDelegatedSyncForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/consolediff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.tsindex f6007743d4..0fe5bc2837 100644--- a/src/commands/doctor/checks/managed-sync-blocked.ts+++ b/src/commands/doctor/checks/managed-sync-blocked.ts@@ -33,7 +33,7 @@ async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]>details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },message: `${list}: the managed sync run is stopped on a page that did not commit, its passes keep stopping without converging, or its pass stopped before it ended with no process left to finish it (killed or crashed), so the source indexes nothing new until it is cleared`+ `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}.`- + (blocked.some(b => b.code !== 'pass_interrupted') ? " Freshness sync jobs for the source end dead with the run's next step instead of completed." : ''),+ + (blocked.some(b => b.code !== 'pass_interrupted' && b.code !== 'pass_abandoned') ? " Freshness sync jobs for the source end dead with the run's next step instead of completed." : ''),fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],'Read-only: names the page the run stopped on, its fault class and the next step (a hold to reconcile, a repair to preview, or the resume command).','managed_sync_blocked', { docs: DOCS }) });diff --git a/src/commands/sources-strategy.ts b/src/commands/sources-strategy.tsindex c9ee5ffb5b..c65f3f3d29 100644--- a/src/commands/sources-strategy.ts+++ b/src/commands/sources-strategy.ts@@ -33,7 +33,10 @@ export async function unfinishedManagedSyncRuns(engine: BrainEngine, sourceId: sWHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true' AND s.id=$1 ORDER BY c.updated_at`, [sourceId]);}-/** Why a strategy change would cut under a running or unfinished pass: a live drain lease, or an open episode (read-only). */+/**+ * Why a strategy change would cut under a running or unfinished pass: a drain lease's lock row (a live holder's, or, until a+ * takeover, a killed holder's: refusing on that is the safe side), or an open episode (read-only).+ */export async function unfinishedManagedSyncPass(engine: BrainEngine, sourceId: string): Promise<{ lease: string | null; episode: { opened_at: string; full_id: string | null } | null }> {const [{ readDrainHolder }, { readPassRow }] = await Promise.all([import('../core/persistence/sync-lease.ts'), import('../core/persistence/sync-pass-row.ts')]);const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex a5ec109df0..86ef07dfd0 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -581,7 +581,7 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:}// 4. Socket + secret: the serve bound to this source, else the legacy URL-keyed socket.const { sock, secret } = deps.socket ? await deps.socket(sourceId)- : { sock: await hookResolveSocketForConfig(cfg, sourceId), secret: readIpcSecretForConfig(cfg) };+ : { sock: await hookResolveSocketForConfig(cfg, sourceId, { delegation: true }), secret: readIpcSecretForConfig(cfg) };if (!sock || !existsSync(sock) || !secret) {return own('no_socket', fallbackLine(pid, 'the running gbrain serve exposes no sync IPC socket (older gbrain, or GBRAIN_SERVE_SYNC_IPC=0 on the serve)', false));}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e130cdaf7d..47d499aa86 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1307,6 +1307,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.464.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves, and any serve on PGLite (the process that owns the database file), are unchanged.' },{ since: '0.60.464.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },{ since: '0.60.464.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },+ { since: 'TBD', text: '`gbrain sync status` and doctor `managed_sync_blocked` no longer read a managed sync pass `pass_abandoned` while a process still renews its drain lease (a pass started over earlier interrupted ones), nor `pass_interrupted` when the pass ended between their pass and lease reads; liveness reads the database clock, and doctor keeps status\'s quiet-window rule when the lock read fails. A pass stopped by a lost database connection, a statement timeout, write back-pressure or a lost drain lease now ends `resumable` (`stop_reason` `transient` or `lease_lost`) instead of reading killed. The on-commit notifier, the notifier block and `sources status` `writer_heartbeat` no longer count a killed holder\'s lock row as a live holder, so the notifier starts the sync that takes its expired lease over.' },+ { since: 'TBD', text: 'On Postgres, `gbrain serve --access read-only` (stdio) binds its own read socket for resolve, turn_context and context_pack instead of the source and legacy sockets, so a read-write serve started later for the same source always answers delegated sync, nudge and sweep requests; before, a read-only serve that bound first made the CLI fall back with `unsupported_kind`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.tsindex 98f28338e1..229d99b912 100644--- a/src/core/context/resolve-ipc.ts+++ b/src/core/context/resolve-ipc.ts@@ -391,12 +391,19 @@ export interface IpcPathConfig {* defers instead of unlinking it, #4896). The persistence socket ignores* `sourceId`: it routes to the single resident owner, so it stays* brain-keyed. Bound-source rejection [CX2-10] still applies per request.+ *+ * #7612: `read` is the socket a lean serve (a read-only stdio serve on+ * Postgres, which registers no delegated sync, nudge or sweep kind) binds+ * instead of the two above, keyed like the source socket. It answers only+ * resolve, turn_context and context_pack, so it never takes the+ * delegation-capable sockets from a read-write serve. PGLite has none (a+ * PGLite serve is never lean).*/-export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined, kind: 'resolve' | 'persistence' = 'resolve', sourceId?: string): string | null {+export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined, kind: 'resolve' | 'persistence' | 'read' = 'resolve', sourceId?: string): string | null {if (!cfg) return null;- if (cfg.engine === 'pglite' && cfg.database_path) return localIpcSocketPath(join(cfg.database_path, `.gbrain-${kind}.sock`));+ if (cfg.engine === 'pglite' && cfg.database_path) return kind === 'read' ? null : localIpcSocketPath(join(cfg.database_path, `.gbrain-${kind}.sock`));if (cfg.engine === 'postgres' && cfg.database_url) {- const sourceKey = kind === 'resolve' && sourceId ? `-${hash12(sourceId)}` : '';+ const sourceKey = kind !== 'persistence' && sourceId ? `-${hash12(sourceId)}` : '';return localIpcSocketPath(join(ipcRunDir(), `${kind}-${hash12(cfg.database_url)}${sourceKey}.sock`));}return null;@@ -404,15 +411,20 @@ export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined/*** The resolve socket a hook calls (#5042): its own source's socket- * (`GBRAIN_SOURCE`, else `default`) when a serve listens there, else the- * legacy URL-only socket (an older serve, or a serve bound to a source the- * hook does not name). PGLite has a single path (one serve per data dir).+ * (`GBRAIN_SOURCE`, else `default`) when a serve listens there, then a lean+ * serve's read socket for that source (#7612), else the legacy URL-only+ * socket (an older serve, or a serve bound to a source the hook does not+ * name). A delegation client (`delegation: true`) skips the read socket: a+ * lean serve registers no delegated kind. PGLite has a single path (one+ * serve per data dir).*/-export async function hookResolveSocketForConfig(cfg: IpcPathConfig | null | undefined, sourceId: string | undefined): Promise<string | null> {+export async function hookResolveSocketForConfig(cfg: IpcPathConfig | null | undefined, sourceId: string | undefined, opts: { delegation?: boolean } = {}): Promise<string | null> {const legacy = resolveSocketPathForConfig(cfg);const keyed = resolveSocketPathForConfig(cfg, 'resolve', sourceId || 'default');if (!legacy || !keyed || keyed === legacy) return legacy;- return (await socketHasLiveListener(keyed)) ? keyed : legacy;+ if (await socketHasLiveListener(keyed)) return keyed;+ const read = opts.delegation ? null : resolveSocketPathForConfig(cfg, 'read', sourceId || 'default');+ return read && (await socketHasLiveListener(read)) ? read : legacy;}/**diff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex a83448d40e..d26c0d9375 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -539,19 +539,23 @@ interface RawLockRow {acquired_at?: Date | string;ttl_expires_at?: Date | string;last_refreshed_at?: Date | string | null;+ /** #7614: the database clock at the read, so every derived age compares database stamps with the database clock. */+ db_now?: Date | string;}/** Canonical column list for every lock SELECT — keep in lockstep with `RawLockRow`. */-const LOCK_SELECT_COLS = 'id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token';+const LOCK_SELECT_COLS = 'id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token, now() AS db_now';/*** Row → `LockSnapshot` mapper. Coerces postgres.js Date|string columns to Date- * and computes the derived fields (age_ms, ttl_expired, ms_since_last_refresh).+ * and computes the derived fields (age_ms, ttl_expired, ms_since_last_refresh) against the database clock the row+ * carries (#7614: a reader whose clock runs ahead of the database read a renewing holder as expired), else `now`.* Returns null for a structurally-incomplete row (missing pid / acquired_at /* ttl). v0.41.13.0: last_refreshed_at may be NULL on pre-v98 brains.*/-function rowToLockSnapshot(row: RawLockRow, now: number): LockSnapshot | null {+function rowToLockSnapshot(row: RawLockRow, readerNow: number): LockSnapshot | null {if (row.holder_pid === undefined || !row.acquired_at || !row.ttl_expires_at) return null;+ const now = row.db_now == null ? readerNow : new Date(row.db_now).getTime();const acquired = row.acquired_at instanceof Date ? row.acquired_at : new Date(row.acquired_at);const ttlExpires = row.ttl_expires_at instanceof Date ? row.ttl_expires_at : new Date(row.ttl_expires_at);const lastRefreshed = row.last_refreshed_at == null@@ -574,6 +578,8 @@ function rowToLockSnapshot(row: RawLockRow, now: number): LockSnapshot | null {interface SelectLockRowsOpts {/** Return only the row for this exact lock id (the `inspectLock` case). */lockId?: string;+ /** #7614: return only the rows for these lock ids, in one read (the `inspectLocks` case). */+ lockIds?: readonly string[];/** Return only rows whose ttl_expires_at < NOW() (the `listStaleLocks` case). */staleOnly?: boolean;}@@ -595,15 +601,19 @@ async function selectLockRows(engine: BrainEngine, opts: SelectLockRowsOpts = {}if (engine.kind === 'postgres' && maybePG.sql) {const sql = maybePG.sql as any;if (opts.lockId !== undefined) {- rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token FROM gbrain_cycle_locks WHERE id = ${opts.lockId}`;+ rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token, now() AS db_now FROM gbrain_cycle_locks WHERE id = ${opts.lockId}`;+ } else if (opts.lockIds !== undefined) {+ rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token, now() AS db_now FROM gbrain_cycle_locks WHERE id = ANY(${[...opts.lockIds]}::text[])`;} else if (opts.staleOnly) {- rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token FROM gbrain_cycle_locks WHERE ttl_expires_at < NOW() ORDER BY acquired_at`;+ rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token, now() AS db_now FROM gbrain_cycle_locks WHERE ttl_expires_at < NOW() ORDER BY acquired_at`;} else {- rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token FROM gbrain_cycle_locks ORDER BY acquired_at`;+ rows = await sql`SELECT id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token, now() AS db_now FROM gbrain_cycle_locks ORDER BY acquired_at`;}} else if (engine.kind === 'pglite' && maybePGLite.db) {if (opts.lockId !== undefined) {rows = (await maybePGLite.db.query(`SELECT ${LOCK_SELECT_COLS} FROM gbrain_cycle_locks WHERE id = $1`, [opts.lockId])).rows as RawLockRow[];+ } else if (opts.lockIds !== undefined) {+ rows = (await maybePGLite.db.query(`SELECT ${LOCK_SELECT_COLS} FROM gbrain_cycle_locks WHERE id = ANY($1::text[])`, [[...opts.lockIds]])).rows as RawLockRow[];} else if (opts.staleOnly) {rows = (await maybePGLite.db.query(`SELECT ${LOCK_SELECT_COLS} FROM gbrain_cycle_locks WHERE ttl_expires_at < NOW() ORDER BY acquired_at`)).rows as RawLockRow[];} else {@@ -624,6 +634,12 @@ export async function inspectLock(engine: BrainEngine, lockId: string): Promise<return rows[0] ?? null;}+/** #7614: the rows of several locks in one read, by lock id (a lock with no row is absent from the map). */+export async function inspectLocks(engine: BrainEngine, lockIds: readonly string[]): Promise<Map<string, LockSnapshot>> {+ if (!lockIds.length) return new Map();+ return new Map((await selectLockRows(engine, { lockIds })).map(snap => [snap.id, snap]));+}+/*** v0.41.6.0 D3: list every lock whose TTL has expired. Used by gbrain* doctor's `stale_locks` check. The query reuses the same canonicaldiff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.tsindex 6705b1b99c..8bd17815ee 100644--- a/src/core/notifier/resident.ts+++ b/src/core/notifier/resident.ts@@ -148,8 +148,9 @@ export function runnerStart(engine: BrainEngine): Pick<CommitNotifierOptions, 's},syncRunning: async () => (await load()).isDelegatedSyncRunning(),drainHeld: async (sourceId) => {- const { holderStalled, readDrainHolder } = await import('../persistence/sync-lease.ts');- const holder = await readDrainHolder(engine, sourceId);+ // #7614: a killed holder's lock row defers nothing; the sync this starts takes its expired lease over.+ const { holderStalled, readLiveDrainHolder } = await import('../persistence/sync-lease.ts');+ const holder = await readLiveDrainHolder(engine, sourceId);return holder === null ? false : holderStalled(holder) ? 'stalled' : true;},};diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.tsindex b25135416a..10eb637a9a 100644--- a/src/core/notifier/status.ts+++ b/src/core/notifier/status.ts@@ -14,7 +14,7 @@ import { missingTable, type DetectionMode, type NotifierState } from './store.tsimport { residentNotifier } from './resident.ts';import { parseOnCommit } from '../commit-notifier.ts';import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';-import { HOLDER_STALL_MS, holderStalled, publicDrainHolder, readDrainHolder, type DrainHolder } from '../persistence/sync-lease.ts';+import { HOLDER_STALL_MS, holderStalled, publicDrainHolder, readLiveDrainHolder, type DrainHolder } from '../persistence/sync-lease.ts';type Exec = Pick<BrainEngine, 'executeRaw' | 'kind'>;type FreshnessExec = Exec & Pick<BrainEngine, 'getConfig'>;@@ -150,7 +150,8 @@ export async function readNotifierBlock(engine: BrainEngine, sourceId: string, oconst live = ownerLive(engine, row);const stalled = row.reason === 'notifier_stalled' || row.state === 'operator_blocked';const resident = live ? { kind: row.owner_kind ?? 'unknown', pid: remote ? null : row.owner_pid === null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id, live } : null;- const holder = live ? null : await readDrainHolder(engine, sourceId).catch(() => null);+ // #7614: a holder that stopped renewing the drain lease (killed) syncs nothing, so it does not stand in for the resident.+ const holder = live ? null : await readLiveDrainHolder(engine, sourceId).catch(() => null);// #7243: the resident the row last recorded (the one its trace rows name), whose notifier lease is no longer live.const recorded = !live && row.owner_kind ? { kind: row.owner_kind, pid: remote || row.owner_pid == null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id,seen_at: iso(row.owner_seen_at), lease_expired_at: iso(row.lease_expires_at) } : null;diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.tsindex 8aa898313b..faea7a0215 100644--- a/src/core/persistence/applied-watermark.ts+++ b/src/core/persistence/applied-watermark.ts@@ -32,7 +32,7 @@ import { execFileBounded } from '../bounded-child-exec.ts';import { gitChildEnv } from '../git-env.ts';import { readGitBehind, type BehindReader } from './sync-freshness.ts';import { countGitHolds } from './sync-holds.ts';-import { holderStalled, publicDrainHolder, readDrainHolder } from './sync-lease.ts';+import { holderStalled, publicDrainHolder, readLiveDrainHolder } from './sync-lease.ts';export interface WriteWatermark {source_id: string;@@ -133,7 +133,7 @@ export async function readAppliedWatermark(engine: BrainEngine, sourceId: string: { state: 'complete', commit, before: null, unembedded_pages: 0, held_pages: 0 };}- const holder = await readDrainHolder(engine, sourceId).catch(() => null);+ const holder = await readLiveDrainHolder(engine, sourceId).catch(() => null);const shown = opts.remote ? publicDrainHolder(holder) : holder;const lastProgress = holder?.progress?.last_progress_at ?? null;return {diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.tsindex 9d6a2bffe8..1475134b74 100644--- a/src/core/persistence/sync-blocked.ts+++ b/src/core/persistence/sync-blocked.ts@@ -57,16 +57,20 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s// #7596: an open pass no recorded stop explains, whose drain lease no process renews: its process was killed or crashed.const open = readings.filter(reading => reading.row.value.telemetry.outcome === 'open' && !listed.some(blocked => blocked.source_id === reading.source_id));if (!open.length) return listed;- const [{ inspectLock, syncLockId }, { drainLeaseLive }, { abandonedPasses }] = await Promise.all([+ const [{ inspectLocks, syncLockId }, { drainLeaseLive }, { abandonedPasses, openPassRowsStill }] = await Promise.all([import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts')]);const now = Date.now();- const locks = await Promise.all(open.map(({ source_id }) => inspectLock(engine, syncLockId(source_id)).catch(() => undefined)));- for (const [i, { source_id, row }] of open.entries()) {- const lock = locks[i];- if (lock === undefined) continue;- const interrupted = !lock || !drainLeaseLive(lock);- const abandoned = abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK;- if (interrupted || abandoned) listed.push({ source_id, code: abandoned ? 'pass_abandoned' : 'pass_interrupted', run_id: row.value.telemetry.pass_id, blocked_since: abandoned ? passStuckSince(row) : row.updated_at });+ // #7614: one read for every open source's lock. A read that failed decides nothing: the quiet-window rule (status's) still counts a streak.+ const locks = await inspectLocks(engine, open.map(({ source_id }) => syncLockId(source_id))).catch(() => undefined);+ const candidates = open.map(({ source_id, row }) => {+ const lock = locks?.get(syncLockId(source_id));+ const interrupted = locks === undefined ? undefined : !lock || !drainLeaseLive(lock);+ return { source_id, row, interrupted, abandoned: abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK };+ }).filter(entry => entry.interrupted || entry.abandoned);+ // #7614: a pass that ended (releasing its lease) after the pass read changed its row, so it is not listed; nor is an archived source.+ const still = candidates.length ? await openPassRowsStill(engine, candidates) : new Set<string>();+ for (const { source_id, row, abandoned } of candidates) {+ if (still.has(source_id)) listed.push({ source_id, code: abandoned ? 'pass_abandoned' : 'pass_interrupted', run_id: row.value.telemetry.pass_id, blocked_since: abandoned ? passStuckSince(row) : row.updated_at });}return listed;}diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.tsindex f053cbd970..82e2fd2a3f 100644--- a/src/core/persistence/sync-freshness.ts+++ b/src/core/persistence/sync-freshness.ts@@ -126,7 +126,7 @@ export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?:sample AS (SELECT r.source_id, r.slug, r.sequence, r.page_id, r.completed_at, c.committed_atFROM persistence_requests r JOIN c ON c.target=r.intent->>'target' WHERE ${SAMPLE_WHERE}),later AS MATERIALIZED (SELECT l.source_id, l.slug, max(l.sequence) AS sequence FROM persistence_requests l- WHERE l.state='committed' AND l.sequence > (SELECT min(sequence) FROM sample) GROUP BY l.source_id, l.slug),+ WHERE l.state='committed' AND l.source_id IN (SELECT source_id FROM sample) AND l.sequence > (SELECT min(sequence) FROM sample) GROUP BY l.source_id, l.slug),s AS (SELECT r.completed_at, r.committed_at, COALESCE(r.page_id, (SELECT p.id FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug LIMIT 1)) AS page_id,COALESCE(later.sequence > r.sequence, false) AS supersededFROM sample r LEFT JOIN later ON later.source_id=r.source_id AND later.slug=r.slug),diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex bf91887a90..1301f33b66 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -141,6 +141,12 @@ export async function readDrainLease(engine: BrainEngine, sourceId: string): Proreturn { holder, live: drainLeaseLive(snap) };}+/** #7614: the drain lease's holder while it still renews the lease, else null: a killed holder's lock row names a process that is gone. */+export async function readLiveDrainHolder(engine: BrainEngine, sourceId: string): Promise<DrainHolder | null> {+ const lease = await readDrainLease(engine, sourceId);+ return lease?.live ? lease.holder : null;+}+/** #7596: whether the drain lease's holder still renews it: `isLockHolderLive` at the drain TTL, the one rule status and doctor read. */export const drainLeaseLive = (snap: LockSnapshot): boolean => isLockHolderLive(snap, DRAIN_LEASE_TTL_MINUTES);diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 9ed708e77a..95253154dc 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -23,7 +23,7 @@ import type { Cursor, RetryWait } from './sync-run.ts';import { getWriteRequestById } from './journal.ts';import type { WriteRequest } from './model.ts';import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';-import { recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';+import { recordedStop, replaysUnchangedRefusal, unrecordedStop } from './sync-stop-class.ts';import { adoptLegacyPage, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';@@ -757,7 +757,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst stampFor = (level: ShadowLevel) => passStampFor(engine, { context, head, slugMode: levelSlugMode, episode, selection, configured, mode, leaseToken: lease.token, retry, level, selectionFp, parserFp,pack, full: kind === 'full', counts, extract: !processingOptions.noExtract, since: value.telemetry.started_at, rescreen: legacyWaived.size > 0, closures });- const save = async (outcome: PassOutcome, stopReason: string | null, pin = false) => {+ const save = async (outcome: PassOutcome, stopReason: string | null, pin = false, fenced = true) => {await beat.pending; const ended = outcome !== 'open';if (ended && outcome !== 'synced') {const open = await openPassRequests(engine, { sourceId, passId, carried: value.obligations.pending_requests ?? [] });@@ -767,7 +767,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prclasses: applied.classes, ...(applied.summary ? { summary: applied.summary } : {}),...(ended ? { ended_at: new Date().toISOString(), duration_ms: Date.now() - started } : {}) };if (outcome === 'blocked' || stopReason === 'not_converged') value.obligations.stuck_since ??= new Date().toISOString();- await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value, { pin }); });+ await engine.transaction(async tx => { if (fenced) await assertDrainLease(tx, sourceId); await writePassRow(tx, value, { pin }); });};// GBRA-108: a committed legacy-sweep slice is progress the row and the drain's governor see; #7355: so is a level read still working (`levelBeat`).const onSwept = async () => { assertActive(); await save('open', null); opts.onProgress?.({ phase: 'managed_sync.legacy_swept', bankedFiles: sliceBase.pages }); }, beat = levelBeat(opts, sliceBase, () => save('open', null));@@ -999,7 +999,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr}// A Git listing that did not finish cleanly classifies nothing (design v3.2 §9): the pass stops blocked, having written nothing for that round.if (error instanceof SyncTreeReadIncomplete) { await save('blocked', 'reconcile_read_incomplete').catch(() => undefined); return result('blocked_by_failures', 'reconcile_read_incomplete'); }- throw error;+ const stop = unrecordedStop(error); if (stop) await save('resumable', stop, false, stop !== 'lease_lost').catch(() => undefined); throw error;} finally {unregisterPassCost(passId);}diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex 6cce9efae5..e37bd1e192 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -10,7 +10,20 @@ import type { SyncAdmissionStatus } from './sync-admission.ts';import { digest } from './digest.ts';import { fileDriftSide, type GitHoldRecord } from './sync-holds.ts';import { readDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';-import { ABANDONED_QUIET_MS, ABANDONED_REPORT_STREAK, NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';+import { ABANDONED_QUIET_MS, ABANDONED_REPORT_STREAK, MANAGED_SYNC_PASS_OP, NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';++/**+ * #7614: the sources whose pass row is still the open one a reader saw (same last write, still `open`, source not+ * archived). A reader that saw an open row and then no live drain lease reads it interrupted only through this: a pass+ * that ended and released its lease between the two reads changed its row, so it is not reported killed.+ */+export async function openPassRowsStill(engine: Pick<BrainEngine, 'executeRaw'>, seen: ReadonlyArray<{ source_id: string; row: PassRow }>): Promise<Set<string>> {+ const rows = await engine.executeRaw<{ source_id: string; updated_at: Date | string; outcome: string | null }>(`SELECT s.id AS source_id, c.updated_at,+ c.completed_keys->0->'telemetry'->>'outcome' AS outcome FROM sources s JOIN op_checkpoints c ON c.op=$1 AND c.fingerprint=s.id||':'||s.incarnation::text+ WHERE s.id=ANY($2::text[]) AND s.archived IS NOT TRUE`, [MANAGED_SYNC_PASS_OP, seen.map(entry => entry.source_id)]);+ const at = new Map(seen.map(entry => [entry.source_id, entry.row.updated_at]));+ return new Set(rows.filter(row => row.outcome === 'open' && new Date(row.updated_at).toISOString() === at.get(row.source_id)).map(row => row.source_id));+}export interface PassConvergence {schema: 'convergence/1'; dry_run: false; source_id: string;@@ -62,8 +75,11 @@ export type PassStatusReason = 'pass_unfinished' | 'pass_interrupted' | 'pass_ab* #7355: passes in a row that never ended, the newest open one included once its row has been quiet past the no-progress* window. #7596: a caller that read the source's drain lease passes `interrupted` instead: the open pass counts when no process* holds the lease (its process was killed or crashed) and never while one does, since a pass writes its row only per batch.+ * #7611: nor does the streak an earlier pass stored while a live holder renews the lease: the open pass is running, and the+ * streak counts again once that holder stops renewing.*/export function abandonedPasses(row: PassRow, now = Date.now(), interrupted?: boolean): number {+ if (interrupted === false) return 0;const quiet = row.value.telemetry.outcome === 'open' && (interrupted ?? now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS);return row.value.telemetry.outcome === 'open' ? (row.value.obligations.abandoned_streak ?? 0) + (quiet ? 1 : 0) : 0;}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 1e59282d75..15c640c42f 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -12,7 +12,7 @@ import { digest, sha256 } from './digest.ts';import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';import { preflightSyncCapacity } from './sync-capacity-preflight.ts';import { preparationConfigView } from './config-snapshot.ts';-import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';+import { retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, readManagedSyncRows, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';import { checkpointRevival } from './sync-slug-mode.ts';@@ -44,7 +44,6 @@ import { admittedBy, localResumeRequired, readAdmitted, withoutUnadmitted } fromimport { cursorFenceCause, isSyncKnockOn } from './sync-knock-on.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';-import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { readDryRunWriterState } from './sync-dry-run-writer.ts';import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, unreadableFileHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';@@ -64,11 +63,11 @@ import { recordSyncRunTrend } from '../fence-repair/census-store.ts';import { outOfAttemptsHold, addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';import { withScreeningPaths } from './screening-paths.ts';import { withBoundedReadSession } from './bounded-reads.ts';-import { receiptClass, recordedStop, replaysContentRefusal, resumableStop, stopRecorded } from './sync-stop-class.ts';+import { receiptClass, recordedStop, replaysContentRefusal, resumableStop, stopRecorded, unrecordedStop } from './sync-stop-class.ts';import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';import { withSyncTail } from './sync-tail.ts';import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';-import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';+import { LockUnavailableError, syncLockId } from '../db-lock.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { assertPassAdmission, isPassBatchKey, passBatchStep, passedOverBefore, passRequestId, readPassBatch, setPassBatch, type PassEntry } from './sync-pass-batch.ts';import type { PassStamp } from './sync-prepare.ts';@@ -1363,11 +1362,9 @@ async function recordRunFailure(engine: BrainEngine, error: unknown, run: { cursdiscoveryRun: string; context: ManagedSyncContext; remote: boolean; syncOptions: Cursor['syncOptions']; processingOptions: NonNullable<Cursor['processingOptions']>; repoPath: string | undefined }): Promise<void> {const { cursor, key, phase, discoveryTarget, discoveryRun, context, syncOptions, processingOptions } = run;const code = error instanceof OperationError ? error.code : 'storage_error';- // A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain- // waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost- // database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.- if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error) && !(error instanceof LockStolenError)- && !isRetryableConnError(error) && !isStatementTimeoutError(error)) {+ // A refresh fence, write back-pressure, a lost connection or a statement timeout is not a sync failure to record: the+ // cursor and its frozen manifest stay, and the next pass resumes them (`unrecordedStop`).+ if (!unrecordedStop(error)) {const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);const failedCursor = cursor ?? stored?.completed_keys?.[0];const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 3800be9766..a1aa198e52 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -43,7 +43,7 @@ import type { PublicCategory } from './public-category.ts';import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';import { sha256 } from './digest.ts';import { passResumeArgs } from './sync-pass-readers.ts';-import { passConvergence, passStatusNext, passStatusState } from './sync-pass-status.ts';+import { openPassRowsStill, passConvergence, passStatusNext, passStatusState } from './sync-pass-status.ts';import { MANAGED_SYNC_PASS_OP, readPassRow, SYNC_DELETES_WITHHELD_OP, type PassRow } from './sync-pass-row.ts';import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionEffectParams, syncAdmissionEffectSql, syncAdmissionSettingSql, syncAdmissionStatus } from './sync-admission.ts';import type { DeletesWithheld } from './sync-markers.ts';@@ -403,7 +403,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts// A lease that could not be read decides nothing (undefined): the pass keeps the quiet-window rule.const lease = source.drain_lock ? await readDrainLease(engine, sourceId).catch(() => undefined) : null;const holder = lease?.live ? lease.holder : null;- const interrupted = lease === undefined || passRow?.value.telemetry.outcome !== 'open' ? undefined : !holder;+ // #7614: a pass that ended and released its lease between the source read and the lease read is not interrupted: the open row must still be the one read above.+ const raced = source.drain_lock && lease !== undefined && !holder && passRow?.value.telemetry.outcome === 'open' && !(await openPassRowsStill(engine, [{ source_id: sourceId, row: passRow }])).has(sourceId);+ const interrupted = lease === undefined || raced || passRow?.value.telemetry.outcome !== 'open' ? undefined : !holder;const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed, Date.now(), interrupted) : null;const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const human = holds.find(hold => hold.needs_human) ?? (liveError?.needs_human ? liveError : undefined);diff --git a/src/core/persistence/sync-stop-class.ts b/src/core/persistence/sync-stop-class.tsindex a3117dd17f..29f8147810 100644--- a/src/core/persistence/sync-stop-class.ts+++ b/src/core/persistence/sync-stop-class.ts@@ -13,6 +13,24 @@ import { sha256 } from './digest.ts';import { readSyncFile } from './sync-discovery.ts';import { VERSION } from '../../version.ts';import { pinnedWorktreeConflict } from './sync-page-fault.ts';+import { LockStolenError } from '../db-lock.ts';+import { OperationError } from '../ops/contract.ts';+import { isWriteCapacityWait } from './admission-retry.ts';+import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';++/**+ * A stop a managed sync run records no failure for, so the next pass resumes it: `lease_lost` when the pass lost its drain+ * lease (a lapse or a takeover); `transient` for a refresh fence, write back-pressure (#6278), a lost database connection or+ * a statement timeout (#6340), or a permission refusal. #7614: the pass ends its row `resumable` with this stop reason, so+ * only a process that died leaves an open row (status and doctor read an open row with no live holder as killed). A pass+ * that lost its lease writes that row unfenced, guarded by the row's lease token alone: a pass that pinned since keeps its row.+ */+export function unrecordedStop(error: unknown): 'lease_lost' | 'transient' | null {+ if (error instanceof LockStolenError) return 'lease_lost';+ const code = error instanceof OperationError ? error.code : null;+ return (code !== null && ['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code)) || isWriteCapacityWait(error)+ || isRetryableConnError(error) || isStatementTimeoutError(error) ? 'transient' : null;+}/*** #6712 (#6565): how the run treats a receipt that did not commit, from the terminal classifier: `transport` (a droppeddiff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex eb2bb919fd..d2755f566d 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -143,7 +143,7 @@ export async function bindResolveIpcForServe(persistenceProvider?: PersistenceIpcProvider,opts: {rememberCallable?: boolean | (() => boolean);- /** #7599: a lean serve (a read-only stdio serve on Postgres, `readOnlyServeSkipsResidentDuties`) registers no delegated sync, nudge or sweep kind (clients get the polite refusal); PGLite keeps them. */+ /** #7599: a lean serve (a read-only stdio serve on Postgres, `readOnlyServeSkipsResidentDuties`) registers no delegated sync, nudge or sweep kind (clients get the polite refusal); PGLite keeps them. #7612: it binds only its read socket, never the source or legacy socket a read-write serve answers delegation on. */lean?: boolean;/** Delay before each re-bind attempt of a socket this serve does not hold; tests inject a short one. */rebindDelayMs?: () => number;@@ -154,8 +154,11 @@ export async function bindResolveIpcForServe(const cfg = loadConfig();// #5042: this serve's own source-keyed socket, plus the legacy URL-only// socket when it is free (older hooks and hooks naming no source).- const resolveSocket = resolveSocketPathForConfig(cfg, 'resolve', defaultSource);- const legacySocket = resolveSocketPathForConfig(cfg);+ // #7612: a lean serve on Postgres binds its read socket alone, so it can+ // never hold either delegation-capable socket ahead of a read-write serve.+ const readSocket = opts.lean ? resolveSocketPathForConfig(cfg, 'read', defaultSource) : null;+ const resolveSocket = readSocket ?? resolveSocketPathForConfig(cfg, 'resolve', defaultSource);+ const legacySocket = readSocket ?? resolveSocketPathForConfig(cfg);if (!resolveSocket || !legacySocket) return NULL_BINDING;// #6573: a socket path the OS cannot bind (even after the per-userdiff --git a/test/context-engine-checkpoint.serial.test.ts b/test/context-engine-checkpoint.serial.test.tsindex 8b58237511..27993d8cad 100644--- a/test/context-engine-checkpoint.serial.test.ts+++ b/test/context-engine-checkpoint.serial.test.ts@@ -29,21 +29,29 @@ describe('checkpoint compaction (cathedral 5)', () => {const { existsSync, readdirSync, readFileSync } = require('node:fs') as typeof import('node:fs');let home: string | undefined;- let savedHome: string | undefined;let servers: Array<{ close: () => void }> = [];+ // The sandboxed home alone decides the engine: loadConfig lets an ambient+ // DATABASE_URL / GBRAIN_DATABASE_URL override it, which would give rung 3 a+ // Postgres engine instead of none or the home's PGLite IPC socket.+ const SAVED: Record<string, string | undefined> = {};+ const ENV_KEYS = ['GBRAIN_HOME', 'DATABASE_URL', 'GBRAIN_DATABASE_URL'];beforeEach(() => {__resetSdkLoadStateForTests();- savedHome = process.env.GBRAIN_HOME;+ for (const k of ENV_KEYS) SAVED[k] = process.env[k];home = mkdtempSync(join(tmpdir(), 'gb-ce-ckpt-'));process.env.GBRAIN_HOME = home;+ delete process.env.DATABASE_URL;+ delete process.env.GBRAIN_DATABASE_URL;});afterEach(() => {for (const s of servers) { try { s.close(); } catch { /* noop */ } }servers = [];- if (savedHome === undefined) delete process.env.GBRAIN_HOME;- else process.env.GBRAIN_HOME = savedHome;+ for (const k of ENV_KEYS) {+ if (SAVED[k] === undefined) delete process.env[k];+ else process.env[k] = SAVED[k];+ }if (home) rmSync(home, { recursive: true, force: true });home = undefined;if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });diff --git a/test/doctor-volunteer-channels.test.ts b/test/doctor-volunteer-channels.test.tsindex 5c3dcf33c6..f61e20e1e9 100644--- a/test/doctor-volunteer-channels.test.ts+++ b/test/doctor-volunteer-channels.test.ts@@ -10,6 +10,9 @@* Hermetic: stub engine + temp GBRAIN_HOME per test (the check reads the real* config for engine-aware guidance and the hook heartbeat for delivery* reconciliation — both must come from the temp home, never this machine's).+ * DATABASE_URL and GBRAIN_DATABASE_URL are cleared too: loadConfig lets either+ * override a PGLite config, so a Postgres arm run would turn the PGLite cases+ * into Postgres ones.*/import { describe, test, expect } from 'bun:test';import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';@@ -50,10 +53,14 @@ function tmpHome(engine: 'pglite' | 'postgres'): string {return parent;}+function homeEnv(home: string): Record<string, string | undefined> {+ return { GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined };+}+describe('checkVolunteerChannels', () => {test('groups active channels with counts + last_fired; status ok', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine([{ channel: 'claude-code', n: 12, last_fired: '2026-08-10T10:00:00Z' },@@ -73,7 +80,7 @@ describe('checkVolunteerChannels', () => {test('quiet week on PGLite: registration/restart diagnosis; status ok (info-only)', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine([]));expect(check.status).toBe('ok');expect(check.message).toContain('no push-context activity');@@ -84,7 +91,7 @@ describe('checkVolunteerChannels', () => {test('quiet week on Postgres: engine-aware message — never sends the operator chasing hook registration (red-team)', async () => {const home = tmpHome('postgres');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine([]));expect(check.status).toBe('ok');expect(check.message).toContain('PGLite serve socket');@@ -102,7 +109,7 @@ describe('checkVolunteerChannels', () => {...Array.from({ length: 2 }, () => ({ ts: new Date().toISOString(), event: 'user-prompt', outcome: 'ok' })),];writeFileSync(join(hooksDir, 'heartbeat.jsonl'), lines.map((l) => JSON.stringify(l)).join('\n') + '\n');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine([{ channel: 'claude-code', n: 10, last_fired: '2026-08-11T09:00:00Z' }]),);@@ -116,7 +123,7 @@ describe('checkVolunteerChannels', () => {test('pre-v117 brain (table absent) → ok with a note, never a throw', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine(new Error('relation "context_volunteer_events" does not exist')));expect(check.status).toBe('ok');expect(check.message).toContain('pre-v117');@@ -127,7 +134,7 @@ describe('checkVolunteerChannels', () => {test('transient failure is NOT misreported as pre-v117 (multi-specialist finding)', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine(new Error('connection reset by peer')));expect(check.status).toBe('ok');expect(check.message).not.toContain('pre-v117');@@ -138,7 +145,7 @@ describe('checkVolunteerChannels', () => {test('engine-parity row shapes: string counts and Date/null last_fired coerce correctly', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const check = await checkVolunteerChannels(stubEngine([{ channel: 'op', n: '7', last_fired: null },@@ -155,7 +162,7 @@ describe('checkVolunteerChannels', () => {test('source isolation (cross-model P1): a scoped caller\'s query filters on its authorized sources', async () => {const home = tmpHome('pglite');- await withEnv({ GBRAIN_HOME: home }, async () => {+ await withEnv(homeEnv(home), async () => {const captured: Array<{ sql: string; params: unknown[] }> = [];await checkVolunteerChannels(stubEngine([], captured), { sourceIds: ['team-a'] });expect(captured[0].sql).toContain('source_id = ANY');diff --git a/test/e2e/serve-read-only-session-lane-postgres.test.ts b/test/e2e/serve-read-only-session-lane-postgres.test.tsindex 7dc9b53102..ffe9535e4b 100644--- a/test/e2e/serve-read-only-session-lane-postgres.test.ts+++ b/test/e2e/serve-read-only-session-lane-postgres.test.ts@@ -16,6 +16,8 @@ import { importFromContent } from '../../src/core/import-file.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { withEnv } from '../helpers/with-env.ts';+import { hookResolveSocketForConfig, readIpcSecretForConfig, requestSyncStatus, socketHasLiveListener } from '../../src/core/context/resolve-ipc.ts';const DATABASE_URL = process.env.DATABASE_URL;const WORD = 'quillmarsh';@@ -27,7 +29,7 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session lalet admin: PostgresEngine | null = null;let tag = '';let directBase = '';- let serve: ChildProcess | null = null;+ const serves: ChildProcess[] = [];const directConnections = async () => Number((await admin!.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_stat_activity WHERE application_name = $1', [tag]))[0]!.n);@@ -39,7 +41,7 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session ladirect.searchParams.set('application_name', tag);const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--surface', 'full', '--access', access],{ cwd: process.cwd(), env: { ...env, GBRAIN_DIRECT_DATABASE_URL: direct.toString() }, stdio: ['pipe', 'pipe', 'pipe'] });- serve = child;+ serves.push(child);child.stderr!.on('data', data => { log += String(data); });child.stdout!.on('data', data => { out += String(data); });const call = async (id: number, method: string, params: object) => {@@ -57,14 +59,11 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session la}async function stopServe(): Promise<void> {- const child = serve;- serve = null;- if (!child || child.exitCode !== null || child.signalCode !== null) return;- await new Promise<void>(resolve => {+ await Promise.all(serves.splice(0).map(child => child.exitCode !== null || child.signalCode !== null ? undefined : new Promise<void>(resolve => {const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);child.once('exit', () => { clearTimeout(deadline); resolve(); });child.stdin!.end();- });+ })));}beforeAll(async () => {@@ -119,4 +118,26 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session laexpect(s.log()).toContain("owner of this host's notifier");await stopServe();}, 120_000);++ test('#7612: a read-write serve started after a read-only one for the same source answers delegated sync, not unsupported_kind', async () => {+ const cfg = { engine: 'postgres' as const, database_url: directBase };+ const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, fn);+ const until = async (probe: () => Promise<boolean>) => { for (let i = 0; i < 120 && !(await probe()); i++) await Bun.sleep(250); };+ const lean = await startServe('read-only');+ await lean.call(2, 'tools/list', {});+ await until(() => inHome(async () => socketHasLiveListener((await hookResolveSocketForConfig(cfg, 'default'))!)));+ expect(await inHome(async () => socketHasLiveListener((await hookResolveSocketForConfig(cfg, 'default'))!))).toBe(true);++ const full = await startServe('full');+ await full.call(2, 'tools/list', {});+ const delegated = () => inHome(async () => {+ const socket = await hookResolveSocketForConfig(cfg, 'default', { delegation: true });+ return ((await requestSyncStatus(socket!, { secret: readIpcSecretForConfig(cfg)!, jobId: 'no-such-job' })) as { error?: string }).error;+ });+ await until(async () => (await delegated()) === 'unknown_job');+ expect(await delegated()).toBe('unknown_job');+ // The hook lane now reaches the read-write serve too.+ expect(await inHome(() => hookResolveSocketForConfig(cfg, 'default'))).toBe(await inHome(() => hookResolveSocketForConfig(cfg, 'default', { delegation: true })));+ await stopServe();+ }, 120_000);});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3c2ed50bec..2ab60fbe83 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -488,6 +488,7 @@ test/sync-pass-cost-grouping-gbra130.test.tstest/sync-pass-dirty-after-freeze-gbra130.test.tstest/sync-pass-interrupted-7596.test.tstest/sync-pass-phase-lines-7243.serial.test.ts+test/sync-pass-readers-7614.test.tstest/sync-pass-stop-in-level-gbra133.test.tstest/sync-prescreen-both-delta-6712.test.tstest/sync-prescreen-drift-6712.test.tsdiff --git a/test/resolve-ipc-source-keyed.test.ts b/test/resolve-ipc-source-keyed.test.tsindex 23690af875..c1392ab107 100644--- a/test/resolve-ipc-source-keyed.test.ts+++ b/test/resolve-ipc-source-keyed.test.ts@@ -16,7 +16,7 @@ import { join } from 'node:path';import { once } from 'node:events';import type { Server } from 'node:net';import { bindResolveIpcForServe, type ResolveIpcBinding } from '../src/mcp/resolve-ipc-binding.ts';-import { hookResolveSocketForConfig, IPC_UNAVAILABLE, resolveSocketPathForConfig, resolveViaIpc, startResolveIpcServer } from '../src/core/context/resolve-ipc.ts';+import { hookResolveSocketForConfig, IPC_UNAVAILABLE, readIpcSecretForConfig, requestSyncStatus, resolveSocketPathForConfig, resolveViaIpc, socketHasLiveListener, startResolveIpcServer } from '../src/core/context/resolve-ipc.ts';import { persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withEnv } from './helpers/with-env.ts';@@ -26,10 +26,10 @@ beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'gb-ipc-source-')); });afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });const cfg = { engine: 'postgres' as const, database_url: 'postgresql://user:[email protected]:5432/brain' };-const inBrain = <T>(fn: () => Promise<T>) => {+const inBrain = <T>(fn: () => Promise<T>, env: Record<string, string | undefined> = {}) => {mkdirSync(join(tmp, '.gbrain'), { recursive: true });writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify(cfg));- return withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: '0' }, fn);+ return withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: '0', ...env }, fn);};async function closeAll(bindings: ResolveIpcBinding[], servers: Array<Server | null> = []) {const all = [...bindings.map(b => b.server), ...servers].filter(Boolean) as Server[];@@ -78,6 +78,41 @@ describe('source-keyed resolve socket (#5042)', () => {});});+ it('#7612: a lean serve never holds the delegation sockets, so a later read-write serve for the same source owns them', async () => {+ await inBrain(async () => {+ const keyed = resolveSocketPathForConfig(cfg, 'resolve', 'alpha')!;+ const legacy = resolveSocketPathForConfig(cfg)!;+ const lean = await bindResolveIpcForServe({} as BrainEngine, 'alpha', undefined, { lean: true });+ const bindings = [lean];+ try {+ expect(lean.server).not.toBeNull();+ // Alone, the lean serve still answers the hook lane for its source.+ const hookSocket = await hookResolveSocketForConfig(cfg, 'alpha');+ expect(hookSocket).toBe(lean.socketPath);+ expect(await resolveViaIpc(hookSocket!, { candidates: [], sourceId: 'alpha' })).toBeNull();+ expect(await socketHasLiveListener(keyed)).toBe(false);+ expect(await socketHasLiveListener(legacy)).toBe(false);++ const full = await bindResolveIpcForServe({} as BrainEngine, 'alpha');+ bindings.push(full);+ expect(full.socketPath).toBe(keyed);+ const secret = readIpcSecretForConfig(cfg)!;+ const delegation = await hookResolveSocketForConfig(cfg, 'alpha', { delegation: true });+ expect(delegation).toBe(keyed);+ for (const socket of [keyed, legacy]) {+ expect(((await requestSyncStatus(socket, { secret, jobId: 'no-such-job' })) as { error?: string }).error).toBe('unknown_job');+ }+ // Hooks prefer the read-write serve once it is up.+ expect(await hookResolveSocketForConfig(cfg, 'alpha')).toBe(keyed);+ // A delegation client never targets the lean socket, even when it is the only one listening.+ bindings.pop();+ await closeAll([full]);+ expect(await hookResolveSocketForConfig(cfg, 'alpha', { delegation: true })).toBe(legacy);+ expect(await hookResolveSocketForConfig(cfg, 'alpha')).toBe(lean.socketPath);+ } finally { await closeAll(bindings); }+ }, { GBRAIN_SERVE_SYNC_IPC: undefined });+ });+it('the persistence socket stays brain-keyed and PGLite keeps one path', async () => {await inBrain(async () => {const persistence = persistenceSocketPathForConfig(cfg)!;@@ -85,6 +120,8 @@ describe('source-keyed resolve socket (#5042)', () => {expect(persistence).toBe(resolveSocketPathForConfig(cfg)!.replace(/resolve-([0-9a-f]{12})\.sock$/, 'persistence-$1.sock'));const pglite = { engine: 'pglite' as const, database_path: join(tmp, 'db') };expect(resolveSocketPathForConfig(pglite, 'resolve', 'alpha')).toBe(resolveSocketPathForConfig(pglite));+ // #7612: a PGLite serve is never lean, so PGLite has no read socket.+ expect(resolveSocketPathForConfig(pglite, 'read', 'alpha')).toBeNull();});});});diff --git a/test/serve-idle-sweep-source.serial.test.ts b/test/serve-idle-sweep-source.serial.test.tsindex ba39a29fd2..0451a404d9 100644--- a/test/serve-idle-sweep-source.serial.test.ts+++ b/test/serve-idle-sweep-source.serial.test.ts@@ -8,7 +8,8 @@* links against 'default' — in-session writes got zero edges until a restart.** Serial: top-level mock.module (captures runMaintenanceSweep's opts without- * running the real sweep) + process.chdir (serve.ts resolves from process.cwd()).+ * running the real sweep, and records which resident tickers a serve starts)+ * + process.chdir (serve.ts resolves from process.cwd()).*/import { afterAll, describe, expect, mock, test } from 'bun:test';import { EventEmitter } from 'node:events';@@ -17,6 +18,9 @@ import { join } from 'node:path';import { tmpdir } from 'node:os';import type { BrainEngine } from '../src/core/engine.ts';import * as realSweep from '../src/core/sweep.ts';+import * as realDrain from '../src/core/facts/drain-scheduler.ts';+import * as realMovement from '../src/core/persistence/sync-movement.ts';+import * as realHeadWatcher from '../src/core/serve-head-watcher.ts';import { withEnv } from './helpers/with-env.ts';const sweepCalls: Array<{ sourceId?: string }> = [];@@ -28,6 +32,20 @@ mock.module('../src/core/sweep.ts', () => ({},}));+const tickerStarts: string[] = [];+mock.module('../src/core/facts/drain-scheduler.ts', () => ({+ ...realDrain,+ startFactsDrainScheduler: () => { tickerStarts.push('facts_drain'); return { stop: async () => {} }; },+}));+mock.module('../src/core/persistence/sync-movement.ts', () => ({+ ...realMovement,+ startMovementWatch: () => { tickerStarts.push('movement_watch'); return { stop: () => {} }; },+}));+mock.module('../src/core/serve-head-watcher.ts', () => ({+ ...realHeadWatcher,+ startServeHeadWatcher: () => { tickerStarts.push('head_watcher'); return { stop: async () => {} }; },+}));+// Imported AFTER the mock so serve.ts's lazy `import('../core/sweep.ts')`// resolves to the capture above.const { runServe } = await import('../src/commands/serve.ts');@@ -123,4 +141,24 @@ describe('serve idle sweep source resolution (#4679)', () => {}expect(armed).toEqual(['postgres --access read-only: 0', 'postgres --access=read-only: 0', 'postgres read-write: 1', 'pglite --access read-only: 1']);}, 20_000);++ test('#7599: a read-only serve on Postgres starts no resident ticker (facts drain, movement watch, head watcher); read-write, or on PGLite, it does', async () => {+ const started: string[] = [];+ for (const [kind, args] of [['postgres', ['--access', 'read-only']], ['postgres', ['--access=read-only']], ['postgres', []], ['pglite', ['--access', 'read-only']]] as const) {+ tickerStarts.length = 0;+ await withEnv({ GBRAIN_SOURCE: undefined }, () => runServe({ ...makeEngine(['default']), kind } as BrainEngine, [...args], {+ stdin: new EventEmitter() as never, signals: new EventEmitter() as never, exit: () => {}, log: () => {}, startMcpServer: async () => {},+ getParentPid: () => 1, probeWatchdog: () => true, setInterval: () => ({ unref() {} }), clearInterval: () => {},+ mcpStdio: false, bootTimeoutMs: 0, sweepEnabled: false, factsDrain: {},+ }));+ started.push(`${kind} ${args.join(' ') || 'read-write'}: ${[...tickerStarts].sort().join(',') || 'none'}`);+ }+ // The facts drain is PGLite-only (a Postgres brain has a job worker), so a read-write Postgres serve starts the other two.+ expect(started).toEqual([+ 'postgres --access read-only: none',+ 'postgres --access=read-only: none',+ 'postgres read-write: head_watcher,movement_watch',+ 'pglite --access read-only: facts_drain,head_watcher,movement_watch',+ ]);+ }, 20_000);});diff --git a/test/serve-stdio-read-only.test.ts b/test/serve-stdio-read-only.test.tsindex acc2e29cff..2d4e5933d8 100644--- a/test/serve-stdio-read-only.test.ts+++ b/test/serve-stdio-read-only.test.ts@@ -80,6 +80,8 @@ test('--surface reads both forms; a repeated flag takes the narrowest value, andfor (const args of [['--surface', 'verbs'], ['--http', '--surface=verbs'], ['--surface=full', '--surface', 'verbs'], ['--surface', 'starter', '--surface=verbs']])expect(parseSurfaceFlag(args)).toBe('verbs');expect(parseSurfaceFlag(['--surface=starter'])).toBe('starter');+ // The wider value last never widens: narrowest wins whatever the order.+ expect(parseSurfaceFlag(['--surface', 'verbs', '--surface=full'])).toBe('verbs');for (const args of [['--surface'], ['--surface='], ['--surface', '--http']]) expect(() => parseSurfaceFlag(args)).toThrow(/--surface requires a value/);expect(() => parseSurfaceFlag(['--surface=all'])).toThrow(/Unknown --surface "all"/);});diff --git a/test/sync-admission-6712.test.ts b/test/sync-admission-6712.test.tsindex e127c958e5..522dd8150e 100644--- a/test/sync-admission-6712.test.ts+++ b/test/sync-admission-6712.test.ts@@ -36,6 +36,8 @@ async function reset(): Promise<void> {await engine.unsetConfig(SYNC_ADMISSION_KEY);await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=ANY($1::text[])', [[SYNC_ADMISSION_SET_OP, 'managed-sync-pass']]);await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(SOURCE)]);+ // A shared Postgres keeps earlier files' requests for this source, and their effects reference them.+ await engine.executeRaw('DELETE FROM persistence_effects WHERE request_id IN (SELECT id FROM persistence_requests WHERE source_id=$1)', [SOURCE]);await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=$1', [SOURCE]);}diff --git a/test/sync-pass-interrupted-7596.test.ts b/test/sync-pass-interrupted-7596.test.tsindex 43eec98979..fc21cdc03c 100644--- a/test/sync-pass-interrupted-7596.test.ts+++ b/test/sync-pass-interrupted-7596.test.ts@@ -88,14 +88,14 @@ for (const backend of testBackends()) {// A lease that cannot be read decides nothing: the fresh open pass reads unfinished, and doctor lists nothing for it.const passRowNow = () => engine.executeRaw(`SELECT completed_keys, updated_at FROM op_checkpoints WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);const before = await passRowNow();- const lockRead = spyOn(dbLock, 'inspectLock').mockRejectedValue(new Error('lock read failed'));+ const lockReads = [spyOn(dbLock, 'inspectLock').mockRejectedValue(new Error('lock read failed')), spyOn(dbLock, 'inspectLocks').mockRejectedValue(new Error('lock read failed'))];try {status = await readSyncStatus(engine, 'default', { detail: false });expect(await passRowNow()).toEqual(before);expect(status.reason).toBe('pass_unfinished');expect(status.interrupted).toBeNull();expect(await blocked()).toEqual([]);- } finally { lockRead.mockRestore(); }+ } finally { for (const spy of lockReads) spy.mockRestore(); }// Passes in a row keep stopping that way: status and doctor both read pass_abandoned, with the lock row left or released.await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,obligations,abandoned_streak}','1') WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);diff --git a/test/sync-pass-readers-7614.test.ts b/test/sync-pass-readers-7614.test.tsnew file mode 100644index 0000000000..99149d4ff7--- /dev/null+++ b/test/sync-pass-readers-7614.test.ts@@ -0,0 +1,206 @@+/**+ * #7611 / #7614 (the sync wave after #7603): the readers of a managed sync pass and its drain lease decide from one+ * consistent observation on the database clock. A live holder renewing the lease over a stored abandoned streak is running+ * (#7611); a reader whose clock runs ahead of the database still sees a renewing holder; a pass that ended and released its+ * lease between two reads is not reported killed; a lock read that failed keeps status's quiet-window rule in doctor too; an+ * archived source is not listed; a stop the run records nowhere (a lost connection, a lost lease) ends the row resumable, so+ * only a dead process leaves it open; and the notifier and watermark readers no longer stand a killed holder in for a live one.+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { writeFileSync } from 'node:fs';+import { hostname } from 'node:os';+import { join } from 'node:path';+import type { Check } from '../src/commands/doctor.ts';+import { managedSyncBlockedEntry } from '../src/commands/doctor/checks/managed-sync-blocked.ts';+import { readBrainHealthBands } from '../src/commands/doctor/brain-health-bands.ts';+import { runSyncStatus } from '../src/commands/sync/operator.ts';+import * as dbLock from '../src/core/db-lock.ts';+import { LockStolenError, syncLockId } from '../src/core/db-lock.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { runnerStart } from '../src/core/notifier/resident.ts';+import { readNotifierBlock } from '../src/core/notifier/status.ts';+import { readAppliedWatermark } from '../src/core/persistence/applied-watermark.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';+import { readSourceMovement } from '../src/core/persistence/sync-movement.ts';+import { abandonedPasses, passStatusState } from '../src/core/persistence/sync-pass-status.ts';+import { MANAGED_SYNC_PASS_OP, type PassRow, readPassRow } from '../src/core/persistence/sync-pass-row.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const git = (root: string, args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const now = Date.parse('2026-10-26T12:00:00Z');+const row = (streak: number | undefined, quietMs: number): PassRow => ({ updated_at: new Date(now - quietMs).toISOString(),+ value: { source_id: 's', incarnation: 'i', lease_token: 't', obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {}, ...(streak ? { abandoned_streak: streak } : {}) },+ telemetry: { pass_id: 'p', target: 'h', started_at: '', ended_at: null, kind: 'full', round: 0, outcome: 'open', stop_reason: null, candidates: 0, settled: 0, remaining: 0, counts: {}, duration_ms: null, timings_ms: {} } } });++describe('#7611: a stored abandoned streak under a live holder', () => {+ test('a live holder renewing the lease makes the open pass running, whatever streak earlier passes stored', () => {+ const open = row(2, 10_000);+ expect(abandonedPasses(open, now, false)).toBe(0);+ expect(passStatusState(open, null, null, now, false)).toEqual(['resumable', 'pass_unfinished']);+ // The streak counts again once the holder stops renewing (or when no lease reading decides it, by the quiet window).+ expect(passStatusState(open, null, null, now, true)).toEqual(['blocked', 'pass_abandoned']);+ expect(passStatusState(row(2, 6 * 60_000), null, null, now)).toEqual(['blocked', 'pass_abandoned']);+ });+});++const LOCK = syncLockId('default');+const lockRow = (engine: BrainEngine, beat: string, ttl: string) => engine.executeRaw(`INSERT INTO gbrain_cycle_locks(id,holder_pid,holder_host,acquired_at,ttl_expires_at,last_refreshed_at)+ VALUES($1,$2,$3,now()-interval '10 minutes',now()+$5::interval,now()-$4::interval)+ ON CONFLICT(id) DO UPDATE SET holder_pid=EXCLUDED.holder_pid,acquired_at=EXCLUDED.acquired_at,ttl_expires_at=EXCLUDED.ttl_expires_at,last_refreshed_at=EXCLUDED.last_refreshed_at`, [LOCK, 4242, hostname(), beat, ttl]);+const live = (engine: BrainEngine) => lockRow(engine, '1 second', '2 minutes');+const dead = (engine: BrainEngine) => lockRow(engine, '3 minutes', '-1 minute');+const unlock = (engine: BrainEngine) => engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [LOCK]);+const setPass = (engine: BrainEngine, outcome: string, streak: number, age = '0 seconds') => engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,+ '{0,telemetry,outcome}',to_jsonb($2::text)),'{0,obligations,abandoned_streak}',to_jsonb($3::int)), updated_at=now()-$4::interval WHERE op=$1`, [MANAGED_SYNC_PASS_OP, outcome, streak, age]);+const commitFile = (root: string, name: string) => { writeFileSync(join(root, name), `---\ntype: concept\ntitle: ${name}\n---\n\nA note about ${name}.\n`); git(root, ['add', '-A']); git(root, ['commit', '-qm', name]); };++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ /** A managed brain whose first sync converged, its pass row then edited by each case. */+ const synced = (name: string, run: (brain: { engine: BrainEngine; root: string; sync: () => ReturnType<typeof performManagedSync>; status: () => ReturnType<typeof readSyncStatus>;+ blocked: (ids?: string[]) => Promise<Array<{ source_id: string; code: string }>> }) => Promise<void>) => test(`${name} [${backend}]`, () => managedBrain(async ({ engine, root }) => {+ const sync = () => performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });+ expect((await sync()).status).toMatch(/^(first_sync|synced)$/);+ await run({ engine, root, sync, status: () => readSyncStatus(engine, 'default', { detail: false }),+ blocked: async (ids = ['default']) => (await readBlockedManagedSyncs(engine, ids)).filter(entry => ids.includes(entry.source_id)) });+ }, { databaseUrl, setup: ({ root }) => { git(root, ['init', '-q']); commitFile(root, 'a.md'); } }), 120_000);++ synced('#7611: a pass drained under a live lease over a stored abandoned streak is running in status and doctor', async ({ engine, status, blocked }) => {+ await setPass(engine, 'open', 2);+ await live(engine);+ expect([(await status()).state, (await status()).reason]).toEqual(['resumable', 'pass_unfinished']);+ expect((await status()).live).toMatchObject({ pid: 4242 });+ expect(await blocked()).toEqual([]);+ // Once that holder stops renewing, the stored streak counts again.+ await dead(engine);+ expect((await status()).reason).toBe('pass_abandoned');+ expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_abandoned' })]);+ });++ synced('#7614: drain-lease liveness reads the database clock, not the reader\'s', async ({ engine, status, blocked }) => {+ // A reader whose clock runs half an hour ahead still sees a renewing holder. (PGLite's clock is the process's own, so+ // only a database server can run behind the reader.)+ await setPass(engine, 'open', 0);+ await live(engine);+ const realNow = Date.now.bind(Date);+ const ahead = spyOn(Date, 'now').mockImplementation(() => realNow() + (backend === 'postgres' ? 30 * 60_000 : 0));+ try {+ const snap = await dbLock.inspectLock(engine, LOCK);+ expect(snap && dbLock.isLockHolderLive(snap, 2)).toBe(true);+ expect((await status()).interrupted).toBeNull();+ expect(await blocked()).toEqual([]);+ } finally { ahead.mockRestore(); }+ });++ synced('#7614: a pass that ends and releases its lease between the pass read and the lease read is not reported killed', async ({ engine, status, blocked }) => {+ const endBetween = (name: 'inspectLock' | 'inspectLocks') => {+ const original = dbLock[name] as (...args: unknown[]) => Promise<unknown>;+ return spyOn(dbLock, name).mockImplementation((async (...args: unknown[]) => {+ await setPass(engine, 'up_to_date', 0); await unlock(engine);+ return original(...args);+ }) as never);+ };+ await setPass(engine, 'open', 1); await dead(engine);+ let race = endBetween('inspectLock');+ try {+ const raced = await status();+ expect(raced.interrupted).toBeNull();+ expect(raced.reason).not.toMatch(/^pass_(interrupted|abandoned)$/);+ } finally { race.mockRestore(); }+ await setPass(engine, 'open', 1); await dead(engine);+ race = endBetween(typeof (dbLock as Record<string, unknown>).inspectLocks === 'function' ? 'inspectLocks' : 'inspectLock');+ try { expect(await blocked()).toEqual([]); } finally { race.mockRestore(); }+ });++ synced('#7614: a lock read that failed keeps the quiet-window rule in doctor as in status', async ({ engine, status, blocked }) => {+ await setPass(engine, 'open', 1, '10 minutes'); await dead(engine);+ const failed = (['inspectLock', 'inspectLocks'] as const).filter(name => typeof (dbLock as Record<string, unknown>)[name] === 'function')+ .map(name => spyOn(dbLock, name).mockRejectedValue(new Error('lock read failed')));+ try {+ expect((await status()).reason).toBe('pass_abandoned');+ expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_abandoned' })]);+ // A fresh open row with no streak decides nothing without the lease: neither lists it.+ await setPass(engine, 'open', 0);+ expect((await status()).reason).toBe('pass_unfinished');+ expect(await blocked()).toEqual([]);+ } finally { for (const spy of failed) spy.mockRestore(); }+ });++ synced('#7614: doctor\'s message for killed passes only, the human INTERRUPTED line and the sync_blocked health band', async ({ engine }) => {+ // Killed passes only: doctor does not say freshness jobs end dead (a resume over a killed pass completes).+ await setPass(engine, 'open', 1); await unlock(engine);+ const warned = (await managedSyncBlockedEntry.run({ engine } as never) as Check[])[0]!;+ expect(warned).toMatchObject({ name: 'managed_sync_blocked', status: 'warn' });+ expect(warned.message).not.toContain('Freshness sync jobs');+ const printed = async () => {+ const out: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { out.push(parts.join(' ')); });+ try { await runSyncStatus(engine, ['--source', 'default']); } finally { log.mockRestore(); }+ return out.join('\n');+ };+ await setPass(engine, 'open', 0);+ expect(await printed()).toMatch(/INTERRUPTED: pass \w+ stopped before it ended \(last write [^)]+\)$/m);+ await dead(engine);+ expect(await printed()).toContain('(PID 4242) stopped renewing the lease at');+ // An interrupted pass over an hour old turns get_brain_health to attention with a sync_blocked band.+ await unlock(engine); await setPass(engine, 'open', 0, '2 hours');+ expect(await readBrainHealthBands(engine, { sourceIds: ['default'] }, Date.now() + 7_000_000)).toMatchObject({ status: 'attention', sync_blocked: { band: '1-9' } });+ });++ synced('#7614: the notifier block, the on-commit notifier and the writer heartbeat do not count a killed holder', async ({ engine }) => {+ await setPass(engine, 'open', 0); await dead(engine);+ const drainHeld = runnerStart(engine).drainHeld!;+ expect(await drainHeld('default')).toBe(false);+ expect((await readAppliedWatermark(engine, 'default', { behind: async () => null })).writer_heartbeat.holder).toBeNull();+ await engine.executeRaw('INSERT INTO sync_notifier_sources(source_id) VALUES($1) ON CONFLICT DO NOTHING', ['default']);+ const notifier = await readNotifierBlock(engine, 'default');+ expect(notifier?.drain_holder).toBeNull();+ expect(notifier?.fix?.argv).toEqual(['gbrain', 'sync', '--source', 'default', '--no-pull']);+ await live(engine);+ expect(await drainHeld('default')).toBe(true);+ expect((await readNotifierBlock(engine, 'default'))?.drain_holder).toMatchObject({ pid: 4242 });+ expect((await readAppliedWatermark(engine, 'default', { behind: async () => null })).writer_heartbeat.holder).toMatchObject({ pid: 4242 });+ });++ synced('#7614: a renewing holder that makes no progress reads not moving; open passes of several sources in one read', async ({ engine, blocked }) => {+ await setPass(engine, 'open', 0); await live(engine);+ expect((await readSourceMovement(engine, { sourceIds: ['default'], now: Date.now() + 3 * 3_600_000 }))[0]).toMatchObject({ movement_state: 'not_moving', live: { drain: true } });+ // Two open-pass sources: only the one with no live holder is listed; an archived source's killed pass is not.+ const topology = (sql: string) => engine.transaction(async tx => { await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)"); await tx.executeRaw(sql); });+ await topology("INSERT INTO sources(id,name) VALUES('source-b','source-b')");+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) SELECT op,'source-b:'||(SELECT incarnation::text FROM sources WHERE id='source-b'),+ jsonb_set(completed_keys,'{0,source_id}','"source-b"'),updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE 'default:%'`, [MANAGED_SYNC_PASS_OP]);+ const both = async () => (await blocked(['default', 'source-b'])).map(entry => [entry.source_id, entry.code]);+ expect(await both()).toEqual([['source-b', 'pass_interrupted']]);+ await topology("UPDATE sources SET archived=true WHERE id='source-b'");+ expect(await both()).toEqual([]);+ await unlock(engine);+ expect(await both()).toEqual([['default', 'pass_interrupted']]);+ });++ synced('#7614: a lost connection or a lost lease ends the pass row resumable, so no streak builds and nothing reads killed', async ({ engine, root, sync, status, blocked }) => {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const lostConnection = () => Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' });+ for (const [i, [thrown, reason]] of ([[lostConnection, 'transient'], [() => new LockStolenError(LOCK, 'the drain lease of source default lapsed in this pass'), 'lease_lost'],+ [lostConnection, 'transient']] as const).entries()) {+ commitFile(root, `stop-${i}.md`);+ installFaultHook(async point => { if (point === 'sync:round_start') throw thrown(); });+ try {+ // A lost connection reaches the caller; a lost lease reads as the lease held by another drainer (partial, nothing lost).+ if (reason === 'transient') await expect(sync()).rejects.toThrow('Connection terminated unexpectedly');+ else expect(await sync()).toMatchObject({ status: 'partial', reason: 'drain_lease_held' });+ } finally { installFaultHook(undefined); }+ const stopped = (await readPassRow(engine, 'default', incarnation!))!;+ expect([stopped.value.telemetry.outcome, stopped.value.telemetry.stop_reason, abandonedPasses(stopped)]).toEqual(['resumable', reason, 0]);+ expect((await status()).reason).toBe('pass_unfinished');+ expect(await blocked()).toEqual([]);+ }+ expect((await sync()).status).toMatch(/^(up_to_date|synced)$/);+ });+}diff --git a/test/tailscale.test.ts b/test/tailscale.test.tsindex c557475476..011788bc26 100644--- a/test/tailscale.test.ts+++ b/test/tailscale.test.ts@@ -285,9 +285,15 @@ describe('defaultCommandRunner (real spawn, hermetic commands only)', () => {expect(missing.status).toBeNull();expect(missing.stdout).toBe('');expect(missing.stderr).toMatch(/ENOENT|no such file/i);- const killed = await defaultCommandRunner(['sh', '-c', 'sleep 5'], { timeoutMs: 50 });+ // `sleep` itself, not `sh -c 'sleep 5'`: dash (Ubuntu's /bin/sh) forks the+ // sleep, so the SIGTERM ends only the shell and the orphan holds the pipes+ // open for the full 5s. The SIGTERM at 50ms must end the call well before+ // the 3s SIGKILL grace.+ const killStarted = Date.now();+ const killed = await defaultCommandRunner(['sleep', '5'], { timeoutMs: 50 });expect(killed.status).toBeNull();expect(killed.stderr).toContain('(timed out after 50ms)');+ expect(Date.now() - killStarted).toBeLessThan(3_000);// inherit (login / installer): nothing is captured, the child's status still comes backexpect(await defaultCommandRunner(['sh', '-c', 'exit 7'], { inherit: true, stdoutToStderr: true })).toEqual({ status: 7, stdout: '', stderr: '' });});