Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(writeback): off-period turns stay retired wherever a rewrite puts them; dream synthesis skips them (#6091)

garrytan5dcb3cb2b722
diff --git a/docs/architecture/key-files/ambient-capture.md b/docs/architecture/key-files/ambient-capture.md
index c0b46125a9..8ae0b8b08c 100644
--- a/docs/architecture/key-files/ambient-capture.md
+++ b/docs/architecture/key-files/ambient-capture.md
@@ -8,4 +8,4 @@ each lane's claim, and a re-check at fact admission. User guide:
[ambient writeback](../../guides/ambient-writeback.md#capture-lanes-and-the-off-switch).
Key files:
-- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write `<file>.capture-off.json` — brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts` — BEFORE the file lands; GC reaps an orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's record via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`.
+- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write `<file>.capture-off.json` — brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts` — BEFORE the file lands; GC reaps an orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's record via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`. Retired turn hashes also land in `.progress` `retired_turns` (`retireCorpusFile`, `retireCorpusTurns`); `planCorpusWindows` skips them wherever a rewrite places them, and `withoutOffPeriodTurns` (capture-consent.ts) strips them from what `discoverTranscripts` hands dream synthesis.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 8452e34f90..ccdcda282c 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -15,7 +15,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached, nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.
-- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line. Its conversation-page section is the DB discovery (#4419): `discoverConversationPages(engine, opts)` returns the cycle source's live `type: conversation` pages (date filter on the `date` frontmatter, min_chars, exclude_patterns, `dream_generated`/`mode: lsd` and gbrain-self-session guards) as transcripts keyed `gbrain-page://<source>/<slug>` with a sha256 of the body; `withConversationPages(engine, opts, config, corpus)` appends them to the corpus list when the setting is on and drops a page whose body hash a corpus file already carries; `conversationPagesNotConsumed` returns the `conversation_pages_not_consumed` warn when synthesis is unconfigured but such pages exist. Gated by `dream.synthesize.conversation_pages` (on by default with a corpus dir, `true` opts in without one, `false` off). Pinned by `test/dream-conversation-pages.test.ts`. Each discovered corpus file carries `seat` when its session's `<sessionId>.seat.json` sidecar (`context/seat.ts`, keyed through `corpusFileSessionId`, so segments and writeback files share the session's seat) holds a valid label; the sidecar itself is never a transcript. `withTranscriptSeats` credits synthesis output refs to the seat of the transcript in their `raw_source`. Pinned by `test/transcript-discovery-seat.test.ts`.
+- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line. Its conversation-page section is the DB discovery (#4419): `discoverConversationPages(engine, opts)` returns the cycle source's live `type: conversation` pages (date filter on the `date` frontmatter, min_chars, exclude_patterns, `dream_generated`/`mode: lsd` and gbrain-self-session guards) as transcripts keyed `gbrain-page://<source>/<slug>` with a sha256 of the body; `withConversationPages(engine, opts, config, corpus)` appends them to the corpus list when the setting is on and drops a page whose body hash a corpus file already carries; `conversationPagesNotConsumed` returns the `conversation_pages_not_consumed` warn when synthesis is unconfigured but such pages exist. Gated by `dream.synthesize.conversation_pages` (on by default with a corpus dir, `true` opts in without one, `false` off). Pinned by `test/dream-conversation-pages.test.ts`. Each discovered corpus file carries `seat` when its session's `<sessionId>.seat.json` sidecar (`context/seat.ts`, keyed through `corpusFileSessionId`, so segments and writeback files share the session's seat) holds a valid label; the sidecar itself is never a transcript. `withTranscriptSeats` credits synthesis output refs to the seat of the transcript in their `raw_source`. Pinned by `test/transcript-discovery-seat.test.ts`. #6091: `.txt` corpus files pass through `withoutOffPeriodTurns` (capture-consent.ts), so turns captured or retired under writeback off never feed synthesis.
- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index ed2e32ac40..569539a559 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -99,8 +99,11 @@ the file's claim and before any provider call:
banked under off, before the file lands. Extraction applies the stricter of
that record and the current setting: a transcript banked under `off` is
never extracted, even after writeback is turned back on, and a resumed
- session extracts only the turns banked under `on`. A record written by
- another brain sharing the corpus directory is ignored.
+ session extracts only the turns banked under `on`, wherever a later rewrite
+ places the off-period turns (they are skipped by hash, not only as a leading
+ run). Dream synthesis reads the same transcripts without those turns, and
+ skips a transcript that holds nothing else. A record written by another
+ brain sharing the corpus directory is ignored.
- **In-flight calls.** Facts from a capture lane carry their provenance into
the fact request, and admission re-checks the gate (code
`ambient_capture_off`). `off` applies to every capture-lane request admitted
diff --git a/src/core/context/capture-consent.ts b/src/core/context/capture-consent.ts
index 313c942225..be0febe789 100644
--- a/src/core/context/capture-consent.ts
+++ b/src/core/context/capture-consent.ts
@@ -37,7 +37,7 @@ import type { GBrainConfig } from '../config.ts';
import { configDir, loadConfig } from '../config.ts';
import { captureGateDecision, fileCaptureIsOff, resolveWritebackConfig, type CaptureGateDecision, type CaptureGateLane, type WritebackMode } from '../facts/writeback-config.ts';
import { parseCorpusTurns } from './corpus-turns.ts';
-import { CAPTURE_OFF_SUFFIX, parseSegmentFileName, parseWbFileName, writebackOffSidecarJson } from './corpus-segments.ts';
+import { CAPTURE_OFF_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseSegmentFileName, parseWbFileName, writebackOffSidecarJson } from './corpus-segments.ts';
export { CAPTURE_OFF_SUFFIX };
@@ -143,3 +143,23 @@ export async function applyCaptureGate(full: string, decision: CaptureGateDecisi
export async function gateCorpusFile(engine: BrainEngine, full: string, lane: CaptureGateLane): Promise<AppliedCaptureGate> {
return applyCaptureGate(full, (await resolveCaptureGate(engine))[lane]);
}
+
+/**
+ * Readers outside fact extraction (dream synthesis): `content` of corpus file
+ * `full` without the turns captured or retired under writeback off (this
+ * brain's capture record plus `.progress` `retired_turns`). Null when nothing
+ * is left. Content with no off-period turns comes back unchanged.
+ */
+export function withoutOffPeriodTurns(full: string, content: string): string | null {
+ const record = readRecord(full + CAPTURE_OFF_SUFFIX);
+ let retired: string[] = [];
+ try { retired = (JSON.parse(readFileSync(full + CORPUS_PROGRESS_SUFFIX, 'utf8')) as { retired_turns?: string[] }).retired_turns ?? []; } catch { /* no progress */ }
+ const off = new Set([...(record && record.brain === brainIdentity() ? record.turns : []), ...retired]);
+ if (off.size === 0) return content;
+ const turns = parseCorpusTurns(content);
+ const kept = turns.filter((t) => !off.has(t.sha256));
+ if (kept.length === turns.length) return content;
+ if (kept.length === 0) return null;
+ const bytes = Buffer.from(content, 'utf8');
+ return kept.map((t) => bytes.subarray(t.start, t.end).toString('utf8').trimEnd()).join('\n\n') + '\n';
+}
diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.ts
index edd91cbd0f..e19eba96a7 100644
--- a/src/core/context/corpus-windows.ts
+++ b/src/core/context/corpus-windows.ts
@@ -78,6 +78,8 @@ export interface CorpusProgress {
totals: { inserted: number; duplicate: number; superseded: number };
entity_slugs: string[];
skipped_reason?: string;
+ /** #6091: hashes of turns captured or retired under writeback off; never extracted wherever they sit. */
+ retired_turns?: string[];
lease: { owner: string; at: number } | null;
}
@@ -139,6 +141,7 @@ export function planCorpusWindows(
turns: CorpusTurn[],
from: { turn: number; offset: number },
maxChars: number = MAX_TURN_TEXT_CHARS,
+ skip: ReadonlySet<string> = new Set(),
): CorpusWindow[] {
const windows: CorpusWindow[] = [];
let parts: string[] = [];
@@ -152,7 +155,7 @@ export function planCorpusWindows(
for (let t = from.turn; t < turns.length; t++) {
const { header, body } = turns[t];
let offset = t === from.turn ? Math.min(from.offset, body.length) : 0;
- if (offset >= body.length) {
+ if (offset >= body.length || skip.has(turns[t].sha256)) {
last = { turn: t, offset: null };
continue;
}
@@ -372,6 +375,7 @@ export async function retireCorpusFile(full: string, reason: string = 'writeback
const written = await updateProgress(full, (cur) => ({
...(cur ?? freshProgress()),
turns: mergeTurns(cur?.turns ?? [], parseCorpusTurns(raw)),
+ retired_turns: mergeRetired(cur, parseCorpusTurns(raw).map((t) => t.sha256)),
continuation: null,
finished: st,
skipped_reason: reason,
@@ -391,12 +395,23 @@ export async function retireCorpusTurns(full: string, hashes: readonly string[])
const written = await updateProgress(full, (cur) => {
const known = new Set(cur?.turns.map((t) => t.sha256) ?? []);
const added = hashes.filter((h) => !known.has(h));
- if (cur && added.length === 0) return null;
- return { ...(cur ?? freshProgress()), turns: [...(cur?.turns ?? []), ...added.map((h) => ({ start: 0, end: 0, sha256: h }))].slice(-MAX_RECORDED_TURNS) };
+ const retired = new Set(cur?.retired_turns ?? []);
+ if (cur && added.length === 0 && hashes.every((h) => retired.has(h))) return null;
+ return { ...(cur ?? freshProgress()), turns: [...(cur?.turns ?? []), ...added.map((h) => ({ start: 0, end: 0, sha256: h }))].slice(-MAX_RECORDED_TURNS),
+ retired_turns: mergeRetired(cur, hashes) };
});
return written !== null || (await readCorpusProgress(full)) !== null;
}
+function mergeRetired(cur: CorpusProgress | null, hashes: readonly string[]): string[] {
+ return [...new Set([...(cur?.retired_turns ?? []), ...hashes])].slice(-MAX_RECORDED_TURNS);
+}
+
+/** #6091: turns that must never reach extraction, wherever a rewrite puts them. */
+export function retiredTurns(progress: CorpusProgress | null): ReadonlySet<string> {
+ return new Set(progress?.retired_turns ?? []);
+}
+
function mergeTurns(recorded: CorpusProgress['turns'], turns: CorpusTurn[]): CorpusProgress['turns'] {
const known = new Set(recorded.map((t) => t.sha256));
const added = turns.filter((t) => !known.has(t.sha256)).map(({ start, end, sha256: h }) => ({ start, end, sha256: h }));
@@ -431,12 +446,12 @@ export async function runCorpusWindows(opts: {
const turns = parseCorpusTurns(opts.raw);
if (!state) {
const cur = await readCorpusProgress(full).catch(() => null);
- const remaining = planCorpusWindows(turns, resumePoint(turns, cur)).filter((w) => w.text).length;
+ const remaining = planCorpusWindows(turns, resumePoint(turns, cur), MAX_TURN_TEXT_CHARS, retiredTurns(cur)).filter((w) => w.text).length;
return { status: 'contended', windowsDone: 0, windowsRemaining: remaining, result: resultOf(cur ?? { ...freshProgress(), generation: 0 }) };
}
let cursor = resumePoint(turns, state);
- const windows = planCorpusWindows(turns, cursor);
+ const windows = planCorpusWindows(turns, cursor, MAX_TURN_TEXT_CHARS, retiredTurns(state));
let done = 0;
let status: CorpusWindowRun['status'] = 'complete';
let holding = true;
@@ -492,7 +507,7 @@ export async function runCorpusWindows(opts: {
if (released) state = released;
}
}
- const remaining = planCorpusWindows(turns, cursor).filter((w) => w.text).length;
+ const remaining = planCorpusWindows(turns, cursor, MAX_TURN_TEXT_CHARS, retiredTurns(state)).filter((w) => w.text).length;
// Rewritten while extracting: the snapshot's progress stands, but the file
// is not done; its new turns wait for the next run.
if (status === 'complete' && !sameCorpusFileStat(fileStat, corpusFileStat(await stat(full)))) status = 'changed';
diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.ts
index e6690368fd..d3594a5dbd 100644
--- a/src/core/cycle/transcript-discovery.ts
+++ b/src/core/cycle/transcript-discovery.ts
@@ -17,6 +17,7 @@ import { createHash } from 'node:crypto';
import { pruneDir } from '../sync.ts';
import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';
import { corpusFileSessionId } from '../context/corpus-segments.ts';
+import { withoutOffPeriodTurns } from '../context/capture-consent.ts';
import { readSeatSidecar } from '../context/seat.ts';
import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
import type { BrainEngine } from '../engine.ts';
@@ -322,13 +323,15 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]
}
}
- let content: string;
+ let content: string | null;
try {
content = readFileSync(filePath, 'utf8');
} catch {
continue;
}
- if (content.length < minChars) continue;
+ // #6091: turns captured under memory.auto_writeback off never feed synthesis.
+ if (ext === '.txt') content = withoutOffPeriodTurns(filePath, content);
+ if (content === null || content.length < minChars) continue;
if (isDreamOutput(content, bypass)) {
process.stderr.write(`[dream] skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);
continue;
diff --git a/test/capture-consent-gate.serial.test.ts b/test/capture-consent-gate.serial.test.ts
index 86d5840b33..9495f0b2d8 100644
--- a/test/capture-consent-gate.serial.test.ts
+++ b/test/capture-consent-gate.serial.test.ts
@@ -21,6 +21,7 @@ import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.t
import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';
import { appendSegmentLedger, segmentFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
import { runHook } from '../src/commands/hook.ts';
+import { discoverTranscripts } from '../src/core/cycle/transcript-discovery.ts';
const KEYED: CapabilityReport = {
embeddings: { available: false },
@@ -247,6 +248,36 @@ describe('durable revocation: a capture under off never extracts later', () => {
expect(prompts[0]).not.toContain('old secret plan alpha');
});
+ test('a rewrite that puts earlier on-period turns before the off-period turns still never extracts them', async () => {
+ await setMode('off');
+ await sessionEnd('sess-r5', ['old secret plan alpha', 'ack alpha']);
+ await sweep();
+ expect(prompts.length).toBe(0);
+ await setMode('salient');
+ await sessionEnd('sess-r5', ['earlier public plan zeta', 'ack zeta', 'old secret plan alpha', 'ack alpha', 'new public plan beta', 'ack beta']);
+ await sweep();
+ const sent = prompts.join('\n');
+ expect(sent).toContain('earlier public plan zeta');
+ expect(sent).toContain('new public plan beta');
+ expect(sent).not.toContain('old secret plan alpha');
+ expect(sent).not.toContain('ack alpha');
+ });
+
+ test('a worker-side retire is honored when the rewrite puts new turns first', async () => {
+ await setMode('off');
+ const full = join(corpusDir, 'sess-r6.txt');
+ writeFileSync(full, corpusText(['old secret plan alpha', 'ack alpha']));
+ await sweep();
+ expect(sidecar('sess-r6.txt')?.skipped).toBe('writeback_off');
+ await setMode('salient');
+ writeFileSync(full, corpusText(['earlier public plan zeta', 'ack zeta', 'old secret plan alpha', 'ack alpha']));
+ rmSync(full + CORPUS_INGESTED_SUFFIX, { force: true });
+ await sweep();
+ const sent = prompts.join('\n');
+ expect(sent).toContain('earlier public plan zeta');
+ expect(sent).not.toContain('old secret plan alpha');
+ });
+
test('appended turns after a worker-side retire: only the new turns extract', async () => {
await setMode('off');
const full = join(corpusDir, 'sess-r3.txt');
@@ -320,3 +351,19 @@ describe('two brains on one machine', () => {
expect(prompts[0]).toContain('gamma in the shared directory');
});
});
+
+describe('dream synthesis never reads off-period turns', () => {
+ test('discovery drops turns captured under off and skips a file holding nothing else', async () => {
+ await setMode('off');
+ await sessionEnd('sess-d1', ['old secret plan alpha', 'ack alpha']);
+ await sessionEnd('sess-d2', ['private plan gamma', 'ack gamma']);
+ await setMode('salient');
+ await sessionEnd('sess-d1', ['earlier public plan zeta', 'ack zeta', 'old secret plan alpha', 'ack alpha', 'new public plan beta', 'ack beta']);
+ const found = discoverTranscripts({ corpusDir, minChars: 1 });
+ const d1 = found.find((t) => t.basename === 'sess-d1');
+ expect(d1?.content).toContain('earlier public plan zeta');
+ expect(d1?.content).toContain('new public plan beta');
+ expect(d1?.content).not.toContain('old secret plan alpha');
+ expect(found.some((t) => t.basename === 'sess-d2')).toBe(false);
+ });
+});
diff --git a/test/corpus-windows.test.ts b/test/corpus-windows.test.ts
index c269c6c6c7..7d7ee23ff5 100644
--- a/test/corpus-windows.test.ts
+++ b/test/corpus-windows.test.ts
@@ -210,3 +210,14 @@ describe('resolveCorpusWindowsPerSweepTotal (GBRAIN_CORPUS_WINDOWS_PER_SWEEP)',
expect(warnings[0]).toContain('GBRAIN_CORPUS_WINDOWS_PER_SWEEP');
});
});
+
+describe('#6091: retired turns are skipped wherever they sit', () => {
+ test('planCorpusWindows leaves a retired turn out of every window, not only a leading run', () => {
+ const raw = '[user]\nfirst open turn\n\n[assistant]\nreply one\n\n[user]\nretired secret turn\n\n[assistant]\nreply two\n';
+ const turns = parseCorpusTurns(raw);
+ const text = planCorpusWindows(turns, { turn: 0, offset: 0 }, undefined, new Set([turns[2].sha256])).map((w) => w.text).join('\n');
+ expect(text).toContain('first open turn');
+ expect(text).toContain('reply two');
+ expect(text).not.toContain('retired secret turn');
+ });
+});