Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(harvest): re-queue writeback turns a busy canonical writer refused, keep error codes (#5557)
time-attack17a5b8df7bba
diff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.mdindex ee435b55d6..6bd5619c22 100644--- a/docs/architecture/key-files/core-services-1-continued.md+++ b/docs/architecture/key-files/core-services-1-continued.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.The Retrieval Reflex and session-context helpers under `src/core/context/`.-- `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) — 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.+- `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.- `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/guides/checkpoint-compaction.md b/docs/guides/checkpoint-compaction.mdindex b4886f4e59..1f97915f08 100644--- a/docs/guides/checkpoint-compaction.md+++ b/docs/guides/checkpoint-compaction.md@@ -109,7 +109,12 @@ only — never content.`dream_output` (dream-cycle output is never re-harvested) / `aborted`(retryable — nothing was written) / `manifest_failed` (receipt kept; theretry re-publishes without re-extracting). Hard failures carry the error- name as the reason.+ name as the reason, plus its code when it has one+ (`operationerror:writer_lock_unavailable`); serve's stderr names the first+ failure of each reason. A segment refused because the canonical writer+ stayed busy is not re-queued (its first window already wrote `.progress`):+ the error stands and the sweep resumes the segment. Only the writeback+ lane re-queues a busy-writer refusal.**Single-corpus-dir invariant:** the hook resolves the corpus dir from fileconfig while serve resolves it from DB config. Keepdiff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.tsindex 39ae589bc4..03191875f6 100644--- a/src/core/context/checkpoint-harvest.ts+++ b/src/core/context/checkpoint-harvest.ts@@ -40,11 +40,20 @@ import { corpusFileSessionId, corpusTextForExtraction, readSegmentLedger, selfCaimport { corpusFileStat, readCorpusProgress, runCorpusWindows } from './corpus-windows.ts';import { isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';import { writeHeartbeat } from './hook-heartbeat.ts';+import { OperationError } from '../ops/contract.ts';/** Bounded queue — overflow is a typed skip; the sweep backstop extracts later. */export const HARVEST_QUEUE_CAP = 8;/** Per-file abort so a hung provider can't wedge the FIFO. */export const HARVEST_JOB_TIMEOUT_MS = 60_000;+/**+ * #5557: a writeback turn whose facts preflight still finds the canonical+ * writer busy after its own wait (`writer_lock_unavailable`, thrown before any+ * model call) is re-queued after each of these delays in turn; past the last+ * one it ends as an error. A Git effect holds that lock through its commit and+ * its push.+ */+export const HARVEST_WRITER_BUSY_RETRY_DELAYS_MS: readonly number[] = [5_000, 15_000, 45_000];/** Receipt sidecar suffix — canonical home is corpus-segments (engine-free,* so the hook's GC can reap orphaned receipts); re-exported for callers. */export { HARVEST_RECEIPT_SUFFIX };@@ -71,6 +80,8 @@ export interface HarvestJob {capabilities?: CapabilityReport;/** TEST SEAM: per-job abort budget override (default HARVEST_JOB_TIMEOUT_MS). */timeoutMs?: number;+ /** Busy-writer re-queues already spent on this job; set by the pump only (#5557). */+ writerBusyRetries?: number;}interface HarvestReceipt {@@ -86,6 +97,11 @@ let shuttingDown = false;let currentAbort: AbortController | null = null;/** Resolves when the pump goes idle — the shutdown join point. */let idleResolve: (() => void) | null = null;+/** Busy-writer retries waiting on their delay (#5557); shutdown clears them. */+const pendingRetries = new Map<ReturnType<typeof setTimeout>, HarvestJob>();+let writerBusyRetryDelays: readonly number[] = HARVEST_WRITER_BUSY_RETRY_DELAYS_MS;+/** Error reasons already written to stderr by this serve run (#5557). */+const loggedErrorReasons = new Set<string>();export type HarvestAck = { status: 'scheduled' } | { status: 'skipped'; reason: string };@@ -95,7 +111,7 @@ export type HarvestAck = { status: 'scheduled' } | { status: 'skipped'; reason:*/export function scheduleCheckpointHarvest(job: HarvestJob): HarvestAck {if (shuttingDown) return { status: 'skipped', reason: 'shutting_down' };- if (queue.some((q) => q.file === job.file && q.corpusDir === job.corpusDir)) {+ if ([...queue, ...pendingRetries.values()].some((q) => q.file === job.file && q.corpusDir === job.corpusDir)) {return { status: 'skipped', reason: 'already_queued' };}// F9/OV2-4 cost posture: per-session prompt-harvest cap for the writeback@@ -153,6 +169,7 @@ export const HARVEST_SHUTDOWN_GRACE_MS = 5000;export async function shutdownCheckpointHarvest(): Promise<void> {shuttingDown = true;queue.length = 0;+ clearPendingRetries();try {currentAbort?.abort();} catch {@@ -177,11 +194,19 @@ export function __resetCheckpointHarvestForTests(): void {currentAbort = null;idleResolve = null;wbSessionCounts.clear();+ clearPendingRetries();+ writerBusyRetryDelays = HARVEST_WRITER_BUSY_RETRY_DELAYS_MS;+ loggedErrorReasons.clear();+}++/** TEST SEAM: busy-writer retry delays (null restores the defaults). */+export function __setWriterBusyRetryDelaysForTests(delays: readonly number[] | null): void {+ writerBusyRetryDelays = delays ?? HARVEST_WRITER_BUSY_RETRY_DELAYS_MS;}-/** TEST SEAM: resolves once the queue is fully drained. */+/** TEST SEAM: resolves once the queue is fully drained, pending retries included. */export async function __drainCheckpointHarvestForTests(): Promise<void> {- while (inFlight || queue.length > 0) {+ while (inFlight || queue.length > 0 || pendingRetries.size > 0) {await new Promise((r) => setTimeout(r, 10));}}@@ -211,8 +236,7 @@ async function pump(): Promise<void> {superseded = r.superseded;links = r.links;} catch (e) {- outcome = 'error';- reason = e instanceof Error ? (e.name || 'Error').toLowerCase() : 'error';+ ({ outcome, reason } = classifyHarvestFailure(job, e));} finally {inFlight = false;await writeHeartbeat({@@ -238,6 +262,78 @@ async function pump(): Promise<void> {}}+function clearPendingRetries(): void {+ for (const timer of pendingRetries.keys()) clearTimeout(timer);+ pendingRetries.clear();+}++/**+ * A writeback turn refused because the canonical writer stayed busy is+ * re-queued; any other failure is an error that keeps its code. A compact+ * segment is never re-queued: its first window already wrote `.progress`, which+ * a retry reads as window 1 done, so the error stands and the sweep resumes it.+ */+function classifyHarvestFailure(job: HarvestJob, e: unknown): { outcome: 'degraded' | 'error'; reason: string } {+ if (job.lane === 'writeback' && isWriterBusy(e) && requeueWhileWriterBusy(job)) {+ return { outcome: 'degraded', reason: 'writer_busy_requeued' };+ }+ const reason = harvestErrorReason(e);+ logFirstHarvestError(job, reason, e);+ return { outcome: 'error', reason };+}++/** The facts preflight refused because the canonical writer stayed busy; nothing was extracted. */+function isWriterBusy(e: unknown): boolean {+ return e instanceof OperationError && e.code === 'writer_lock_unavailable';+}++/**+ * Schedules the job's next attempt after its busy-writer delay; false once the+ * delays are spent or serve is stopping. The retry skips the admission checks:+ * the job was admitted (and counted against its session cap) once already.+ */+function requeueWhileWriterBusy(job: HarvestJob): boolean {+ const spent = job.writerBusyRetries ?? 0;+ const delay = writerBusyRetryDelays[spent];+ if (delay === undefined || shuttingDown) return false;+ const timer = setTimeout(() => {+ pendingRetries.delete(timer);+ if (shuttingDown) return;+ queue.push({ ...job, writerBusyRetries: spent + 1 });+ void pump();+ }, delay);+ (timer as { unref?: () => void }).unref?.();+ pendingRetries.set(timer, job);+ return true;+}++/** A heartbeat reason is a short machine code, the shape hook.ts's reasonCode() enforces. */+const HEARTBEAT_REASON_CODE = /^[A-Za-z0-9_.:-]{1,48}$/;++/**+ * The error name plus its `code`, or else its `reason` (FactsExtractionError):+ * `operationerror:writer_lock_unavailable`, `factsextractionerror:provider_error`.+ * A composite past the reason-code shape falls back to the bare name.+ */+function harvestErrorReason(e: unknown): string {+ if (!(e instanceof Error)) return 'error';+ const name = (e.name || 'Error').toLowerCase();+ const { code, reason } = e as { code?: unknown; reason?: unknown };+ const detail = typeof code === 'string' ? code : typeof reason === 'string' ? reason : null;+ const composite = detail === null ? name : `${name}:${detail.toLowerCase()}`;+ if (HEARTBEAT_REASON_CODE.test(composite)) return composite;+ return HEARTBEAT_REASON_CODE.test(name) ? name : 'error';+}++/** The heartbeat keeps counts and codes only; the first failure of each reason also reaches serve's stderr. */+function logFirstHarvestError(job: HarvestJob, reason: string, e: unknown): void {+ if (loggedErrorReasons.has(reason)) return;+ loggedErrorReasons.add(reason);+ const message = e instanceof Error ? e.message : String(e);+ console.error(`[checkpoint-harvest] ${job.lane ?? 'compact'} harvest failed (${reason}): ${message.slice(0, 300)} `+ + '(logged once per serve run; later failures with this reason are counted in the hooks heartbeat only)');+}+/** `<sessionId>.seg-<hash12>.txt` → hash12 ('' when the name has no hash part). */function segHashFromName(file: string): string {const m = /\.seg-([0-9a-f]+)\.txt$/.exec(file);diff --git a/test/checkpoint-harvest.serial.test.ts b/test/checkpoint-harvest.serial.test.tsindex 69fe9a011a..bf1e3e8019 100644--- a/test/checkpoint-harvest.serial.test.ts+++ b/test/checkpoint-harvest.serial.test.ts@@ -8,7 +8,8 @@** Serial: real PGLite engine + module-global harvest queue + GBRAIN_HOME env.*/-import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';+import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';@@ -25,6 +26,7 @@ import {__drainCheckpointHarvestForTests,__resetCheckpointHarvestForTests,HARVEST_RECEIPT_SUFFIX,+ __setWriterBusyRetryDelaysForTests,scheduleCheckpointHarvest,shutdownCheckpointHarvest,WRITEBACK_SESSION_CAP,@@ -35,6 +37,8 @@ import { getCheckpointManifest } from '../src/core/context/session-state.ts';import { makeContextPackIpcHandler } from '../src/mcp/context-pack-handler.ts';import { handleToolCall } from '../src/mcp/server.ts';import { readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding, MANAGED_WRITER_PROBE_WAIT_MS, type WorktreeBinding } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';const KEYED: CapabilityReport = {embeddings: { available: false },@@ -777,3 +781,174 @@ describe('serve-lane self-capture skip (#5820)', () => {expect(JSON.parse(readFileSync(join(corpusDir, banked.flushCorpusFile! + CORPUS_INGESTED_SUFFIX), 'utf8')).lane).toBe('writeback');});});++// ── canonical writer busy past the preflight wait (#5557) ──────────────────+describe('canonical writer busy past the preflight wait (#5557)', () => {+ const COFFEE_TURN = 'I prefer dark roast coffee and I want it on every order.';+ const releases: Array<() => Promise<void>> = [];+ afterEach(async () => {+ for (const release of releases.splice(0)) await release();+ __setWriterBusyRetryDelaysForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ });++ /** A managed source owned by this host, its worktree lock free. */+ async function managedSource(): Promise<{ sourceId: string; binding: WorktreeBinding }> {+ const sourceId = `wb-busy-${randomUUID().slice(0, 8)}`;+ const root = mkdtempSync(join(homeDir, 'root-'));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, binding: (await getWorktreeBinding(engine, sourceId))! };+ }++ /** Takes the worktree lock, as a Git effect's commit and push do, until the returned release runs. */+ async function takeWriter(binding: WorktreeBinding): Promise<() => Promise<void>> {+ const lock = await acquireWorktree(binding, 0, undefined, engine);+ expect(lock).not.toBeNull();+ const release = () => lock!.release();+ releases.push(release);+ return release;+ }++ async function bankTurn(sessionId: string, turn: string): Promise<string> {+ const gated = gateWritebackTurn(turn);+ if (!gated.ok) throw new Error(`fixture turn gated: ${gated.reason}`);+ return (await bankWritebackTurn(corpusDir, sessionId, gated.normalized, gated.hash24)).flushCorpusFile!;+ }++ const scheduleWb = (sourceId: string, sessionId: string, file: string) =>+ scheduleCheckpointHarvest({ engine, sourceId, sessionId, corpusDir, file, capabilities: KEYED, lane: 'writeback' });++ async function untilHeartbeat(event: string): Promise<void> {+ while (!(await readHeartbeatTail(10)).some((e) => e.event === event)) await new Promise((r) => setTimeout(r, 25));+ }++ /** Captures console.error lines while `run` executes. */+ async function stderrDuring(run: () => Promise<void>): Promise<string[]> {+ const lines: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });+ try {+ await run();+ } finally {+ spy.mockRestore();+ }+ return lines;+ }++ test('a turn refused while the writer is busy is re-queued and extracted once the writer frees', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ const prompts = recordingChatStub();+ __setWriterBusyRetryDelaysForTests([200]);+ const { sourceId, binding } = await managedSource();+ const file = await bankTurn('sess-busy-recover', COFFEE_TURN);+ const release = await takeWriter(binding);+ scheduleWb(sourceId, 'sess-busy-recover', file);+ await untilHeartbeat('writeback');+ await release();+ await __drainCheckpointHarvestForTests();++ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'writeback');+ expect(hb.map((e) => [e.outcome, e.reason ?? null])).toEqual([['degraded', 'writer_busy_requeued'], ['ok', null]]);+ expect(hb[1]?.inserted).toBe(1);+ expect(prompts.length).toBe(1);+ expect(existsSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX))).toBe(true);+ const rows = await engine.executeRaw<{ source_session: string }>(`SELECT source_session FROM facts WHERE source = 'hook:writeback'`);+ expect(rows.map((r) => r.source_session)).toEqual(['sess-busy-recover']);+ }, 30_000);++ test('a writer still busy after the last retry ends as an error that keeps its code, logged once per code; the turns stay for the sweep', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ const prompts = recordingChatStub();+ __setWriterBusyRetryDelaysForTests([50]);+ const { sourceId, binding } = await managedSource();+ const files = [+ await bankTurn('sess-busy-a', COFFEE_TURN),+ await bankTurn('sess-busy-b', 'I decided to move the weekly review to Thursday mornings.'),+ ];+ const release = await takeWriter(binding);+ const errors = await stderrDuring(async () => {+ scheduleWb(sourceId, 'sess-busy-a', files[0]!);+ scheduleWb(sourceId, 'sess-busy-b', files[1]!);+ await __drainCheckpointHarvestForTests();+ });+ await release();++ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'writeback');+ expect(hb.filter((e) => e.outcome === 'degraded').map((e) => e.reason)).toEqual(['writer_busy_requeued', 'writer_busy_requeued']);+ expect(hb.filter((e) => e.outcome === 'error').map((e) => e.reason))+ .toEqual(['operationerror:writer_lock_unavailable', 'operationerror:writer_lock_unavailable']);+ expect(errors.filter((line) => line.includes('operationerror:writer_lock_unavailable')).length).toBe(1);+ expect(prompts).toEqual([]);+ for (const file of files) {+ expect(existsSync(join(corpusDir, file))).toBe(true);+ expect(existsSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX))).toBe(false);+ }+ }, 30_000);++ test('a compact segment refused while the writer is busy is not re-queued: the error stands for the sweep', async () => {+ const prompts = recordingChatStub();+ __setWriterBusyRetryDelaysForTests([50]);+ const { sourceId, binding } = await managedSource();+ const seg = bankSegment('sess-busy-compact', `User: ${COFFEE_TURN}\n`);+ const release = await takeWriter(binding);+ scheduleCheckpointHarvest({ engine, sourceId, sessionId: 'sess-busy-compact', corpusDir, file: seg.file, capabilities: KEYED });+ await __drainCheckpointHarvestForTests();+ await release();++ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'checkpoint-harvest');+ expect(hb.map((e) => [e.outcome, e.reason ?? null])).toEqual([['error', 'operationerror:writer_lock_unavailable']]);+ expect(prompts).toEqual([]);+ expect(existsSync(join(corpusDir, seg.file))).toBe(true);+ expect(existsSync(join(corpusDir, seg.file + CORPUS_INGESTED_SUFFIX))).toBe(false);+ }, 30_000);++ test('an extraction failure keeps its reason; each distinct reason reaches stderr once', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ __setChatTransportForTests(async (): Promise<ChatResult> => { throw new Error('synthetic provider outage'); });+ __setWriterBusyRetryDelaysForTests([]);+ const { sourceId, binding } = await managedSource();+ const extractionFailure = await bankTurn('sess-fail-provider', COFFEE_TURN);+ const busyFailure = await bankTurn('sess-fail-busy', 'I decided to move the weekly review to Thursday mornings.');+ const errors = await stderrDuring(async () => {+ scheduleWb('default', 'sess-fail-provider', extractionFailure);+ await __drainCheckpointHarvestForTests();+ const release = await takeWriter(binding);+ scheduleWb(sourceId, 'sess-fail-busy', busyFailure);+ await __drainCheckpointHarvestForTests();+ await release();+ });++ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'writeback');+ expect(hb.map((e) => [e.outcome, e.reason])).toEqual([+ ['error', 'factsextractionerror:provider_error'],+ ['error', 'operationerror:writer_lock_unavailable'],+ ]);+ const harvestLines = errors.filter((line) => line.startsWith('[checkpoint-harvest]'));+ expect(harvestLines.length).toBe(2);+ expect(harvestLines[0]).toContain('(factsextractionerror:provider_error)');+ expect(harvestLines[1]).toContain('(operationerror:writer_lock_unavailable)');+ }, 30_000);++ test('a pending retry dedups a re-scheduled turn; shutdown drops the retry and nothing runs after it', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ const prompts = recordingChatStub();+ __setWriterBusyRetryDelaysForTests([60_000]);+ const { sourceId, binding } = await managedSource();+ const file = await bankTurn('sess-busy-shutdown', COFFEE_TURN);+ await takeWriter(binding);+ scheduleWb(sourceId, 'sess-busy-shutdown', file);+ await untilHeartbeat('writeback');+ expect(scheduleWb(sourceId, 'sess-busy-shutdown', file)).toEqual({ status: 'skipped', reason: 'already_queued' });+ const started = performance.now();+ await shutdownCheckpointHarvest();+ await __drainCheckpointHarvestForTests();+ expect(performance.now() - started).toBeLessThan(1000);+ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'writeback');+ expect(hb.map((e) => e.reason)).toEqual(['writer_busy_requeued']);+ expect(prompts).toEqual([]);+ expect(existsSync(join(corpusDir, file))).toBe(true);+ }, 30_000);+});