Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.23.2 fix(dream): orchestrator-stamped self-consumption marker + verdict model tests (#527)
Garry Tan579722d9dc78
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a1f9322b81..a4a2166705 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,32 @@All notable changes to GBrain will be documented in this file.+## [0.23.2] - 2026-04-30++**The dream cycle now stamps every page it writes. The guard checks for the stamp. No content guessing, no false positives.**++The v0.23.1 prefix-string guard had two flaws caught by a codex review of the v0.23.2 plan. Real serialized brain pages do not always contain their own slug in the body. The synth prompt produces `[Alice](people/alice)` references far more often than the page's own slug, and `serializeMarkdown` does not embed the slug anywhere by default. So the heuristic could miss real dream output. And real conversation transcripts often DO mention brain slugs (`"earlier I wrote about wiki/personal/reflections/identity..."`), so the heuristic dropped legitimate transcripts silently.++v0.23.2 swaps content inference for explicit identity. Every page the synthesize phase writes now gets `dream_generated: true` stamped into its YAML frontmatter at render time. The self-consumption guard checks for that field. CRLF and BOM tolerated. Whitespace and case variants tolerated. Cannot drift, cannot false-positive on user text, cannot miss real output.++`gbrain dream --unsafe-bypass-dream-guard` is a new explicit escape hatch for power users who really do want to re-process a dream-generated page (rare, mostly testing). A loud stderr warning fires every time it runs. The flag is intentionally NOT tied to `--input` because that would let any caller silently re-trigger the loop bug.++The configurable verdict model from v0.23.1 stays. `gbrain config set dream.synthesize.verdict_model claude-sonnet-4-6` still works, with new unit-test coverage asserting the override actually reaches `client.create({ model })`.++### Itemized changes++#### Fixed+- `src/core/cycle/synthesize.ts`: `renderPageToMarkdown` (now exported) stamps `dream_generated: true` and `dream_cycle_date` into every reverse-write. `writeSummaryPage` does the same when building the dream-cycle summary index. The DB-stored frontmatter persists the marker across re-renders.+- `src/core/cycle/transcript-discovery.ts`: replaces v0.23.1's `DREAM_OUTPUT_SLUGS` content-prefix list with `DREAM_OUTPUT_MARKER_RE`, anchored at frontmatter open with optional BOM and CRLF tolerance. Runs in both `discoverTranscripts` and `readSingleTranscript`. Stderr log fires when the guard skips a file (no more silent skips).+- `src/core/cycle/synthesize.ts`: `judgeSignificance` and `JudgeClient` are now exported; `judgeSignificance` accepts a `verdictModel` parameter (default `claude-haiku-4-5-20251001`) loaded from `dream.synthesize.verdict_model` via `loadSynthConfig`.++#### Added+- `gbrain dream --unsafe-bypass-dream-guard` CLI flag. Plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` and `readSingleTranscript({bypassGuard})`. Fires a loud stderr warning at phase entry when set. Never auto-applied for `--input`.++#### Tests+- 12 new test cases in `test/cycle-synthesize.test.ts`:+ - `self-consumption guard (v0.23.2 marker-based)`: REGRESSION fixture built from a real `Page → renderPageToMarkdown → isDreamOutput` round-trip; legitimate user note citing a slug is NOT skipped; CRLF + BOM tolerated; whitespace and case variants tolerated; `false`/absent values do NOT match; `dream_generatedfoo` (no word boundary on key) does NOT match; marker buried past 2000 chars does NOT trigger (perf bound); `bypassGuard=true` overrides; `discoverTranscripts` respects the bypass; `DREAM_OUTPUT_MARKER_RE` is anchored at byte 0.+ - `judgeSignificance`: passes verdict_model override to `client.create`; defaults to `claude-haiku-4-5-20251001` when omitted; returns `worth_processing=false` on unparseable judge output.## [0.23.1] - 2026-04-30**`bun run ci:local` runs the full CI gate on your laptop, 4-way sharded, in ~100 seconds warm. Doc-only diffs go in 5 seconds.**diff --git a/CLAUDE.md b/CLAUDE.mdindex 9786fa6213..91936e47d9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -113,10 +113,10 @@ strict behavior when unset.- `src/core/sync-concurrency.ts` (v0.22.13) — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (Q1: explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars — replaces the prior parseInt-with-no-validation in both `sync.ts` and `import.ts`). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the three sites can no longer drift.- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). v0.22.13 (PR #490): `performSync` wraps its body in a `gbrain-sync` writer lock so two concurrent syncs (manual + autopilot, two terminals, two Conductor workspaces) cannot both write `last_commit` and let the last writer win. Head-drift gate after the import phase re-checks `git rev-parse HEAD`; if HEAD moved (someone ran `git checkout` / `git pull` mid-sync), the bookmark refuses to advance. Vanished files now record a failedFiles entry instead of silent-skip — the silent-skip-then-advance pathology that survived prior hardening passes is dead. Worker engines wrap in try/finally so disconnect always fires (panic-path leak fix). Both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`), validated via `parseWorkers`. Explicit `--workers` bypasses the auto-path file-count floor; auto path defers to `autoConcurrency()`. Banner moved to stderr.- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive (extended to **8 phases in v0.23**). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantically-driven order: **lint → backlinks → sync → synthesize → extract → patterns → embed → orphans**. v0.23's `synthesize` phase runs after sync (cross-references see fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (codex finding #7 — subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default; extract is the canonical materialization). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite. `CycleReport.schema_version: "1"` is stable; totals additively grew in v0.23 (`transcripts_processed`, `synth_pages_written`, `patterns_written`). `yieldBetweenPhases` runs between phases. **v0.23 added `yieldDuringPhase`** for in-phase keepalive — synthesize/patterns call it during long waits to renew the cycle-lock TTL. Engine nullable; lock-skip on read-only phase selections. v0.22.1 (#403): `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal; `checkAborted()` fires between every phase. v0.22.1 (#417): `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult`; `runCycle` captures it and threads to `runPhaseExtract` as the 4th arg. v0.22.1 (Codex F2): `runPhaseSync` takes `willRunExtractPhase: boolean` and sets `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. v0.22.5 (#475): `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor instead of the drift-prone global `config.sync.last_commit` key.-- `src/core/cycle/synthesize.ts` (v0.23) — Synthesize phase: conversation-transcript-to-brain pipeline. Reads from `dream.synthesize.session_corpus_dir`, runs cheap Haiku verdict (cached in `dream_verdicts`), then fans out one Sonnet subagent per worth-processing transcript with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at` — codex finding #2) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency key `dream:synth:<file_path>:<content_hash>`. Auto-commit deferred to v1.1 (codex #5). `--dry-run` runs Haiku, skips Sonnet (codex #8). Subagent never gets fs-write access.+- `src/core/cycle/synthesize.ts` (v0.23) — Synthesize phase: conversation-transcript-to-brain pipeline. Reads from `dream.synthesize.session_corpus_dir`, runs cheap Haiku verdict (cached in `dream_verdicts`), then fans out one Sonnet subagent per worth-processing transcript with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at` — codex finding #2) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency key `dream:synth:<file_path>:<content_hash>`. Auto-commit deferred to v1.1 (codex #5). `--dry-run` runs Haiku, skips Sonnet (codex #8). Subagent never gets fs-write access. **v0.23.2:** `renderPageToMarkdown` (now exported) stamps `dream_generated: true` and `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the dream-cycle summary index. The marker is the explicit identity surface checked by `isDreamOutput` in `transcript-discovery.ts` — replaces the v0.23.1 content-prefix heuristic that could miss real output (`serializeMarkdown` doesn't embed slugs in body) and false-positive on user transcripts citing brain pages. `judgeSignificance` and `JudgeClient` are exported; `judgeSignificance` accepts a `verdictModel` parameter (default `claude-haiku-4-5-20251001`) loaded from `dream.synthesize.verdict_model` via `loadSynthConfig`.- `src/core/cycle/patterns.ts` (v0.23) — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Single Sonnet subagent; same allow-list path as synthesize. Runs AFTER `extract` so the graph is fresh.-- `src/core/cycle/transcript-discovery.ts` (v0.23) — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (Q-3: `medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path.-- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI; ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. **v0.23 added** `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs Haiku significance verdict but skips Sonnet synthesis (codex finding #8 — NOT zero LLM calls). Exit code 1 on status=failed.+- `src/core/cycle/transcript-discovery.ts` (v0.23) — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (Q-3: `medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. **v0.23.2 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 `discoverTranscripts` and `readSingleTranscript` skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no more silent skips). `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`. Replaces v0.23.1's `DREAM_OUTPUT_SLUGS` content-prefix list.+- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI; ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. **v0.23 added** `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs Haiku significance verdict but skips Sonnet synthesis (codex finding #8 — NOT zero LLM calls). Exit code 1 on status=failed. **v0.23.2 added** `--unsafe-bypass-dream-guard` (long-form intentional, plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` and `readSingleTranscript({bypassGuard})`). Loud stderr warning fires at synthesize-phase entry when set. Never auto-applied for `--input` so any caller can't silently re-trigger the loop bug.- `src/commands/friction.ts` + `src/core/friction.ts` (v0.23) — `gbrain friction {log,render,list,summary}` reporter. Append-only JSONL under `$GBRAIN_HOME/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError` (D20). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.- `src/commands/claw-test.ts` + `src/core/claw-test/` (v0.23) — `gbrain claw-test [--scenario <name>] [--live --agent openclaw]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real openclaw subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Phases for scripted mode: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`, asserts `status: 'ok'`) → render. Live mode hands `BRIEF.md` from `test/fixtures/claw-test-scenarios/<name>/` to the agent runner. v1 ships with the OpenClaw runner only (`src/core/claw-test/runners/openclaw.ts`, invokes `openclaw agent --local --agent <name> --message <brief>`); hermes runner deferred to v1.1. Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure — D17 fix for the 256KB-burst child-stall scenario. v0.18 upgrade scenario seeded via `seed-pglite.ts` SQL replay.- `skills/_friction-protocol.md` (v0.23) — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.@@ -524,6 +524,24 @@ Two equivalent paths:Both must pass. Do not ship with failing E2E tests. Do not skip E2E tests.+**Always run typecheck before pushing.** `bun test` (the bun runner)+skips TypeScript type checking — it only enforces runtime behavior.+Three ways to actually gate on types:++1. `bun run test` (npm script in `package.json`) — includes `bun run typecheck`+ plus the four shell pre-checks (`check-jsonb-pattern.sh`,+ `check-progress-to-stdout.sh`, `check-trailing-newline.sh`,+ `check-wasm-embedded.sh`) before the runner. Use this mid-branch.+2. `bun run typecheck` — `tsc --noEmit` standalone. Fast (~5s on this repo).+3. `bun run ci:local` — the full local CI gate from Path A.++The trap is: writing a new test, running `bun test test/foo.test.ts`,+seeing it pass, pushing — and CI's separate typecheck stage rejects an+invalid type literal that the runner accepted. Caught one of these+shipping the v0.23.2 round-trip E2E (`type: 'reflection'` is not a+member of `PageType`). Run `bun run typecheck` once before push, even+when only test files changed.+## Post-ship requirements (MANDATORY)After EVERY /ship, you MUST run /document-release. This is NOT optional. Do NOTdiff --git a/VERSION b/VERSIONindex 610e28725b..fda96dcf63 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.23.1+0.23.2diff --git a/llms-full.txt b/llms-full.txtindex d7a04add0c..6115201873 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -199,10 +199,10 @@ strict behavior when unset.- `src/core/sync-concurrency.ts` (v0.22.13) — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (Q1: explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars — replaces the prior parseInt-with-no-validation in both `sync.ts` and `import.ts`). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the three sites can no longer drift.- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). v0.22.13 (PR #490): `performSync` wraps its body in a `gbrain-sync` writer lock so two concurrent syncs (manual + autopilot, two terminals, two Conductor workspaces) cannot both write `last_commit` and let the last writer win. Head-drift gate after the import phase re-checks `git rev-parse HEAD`; if HEAD moved (someone ran `git checkout` / `git pull` mid-sync), the bookmark refuses to advance. Vanished files now record a failedFiles entry instead of silent-skip — the silent-skip-then-advance pathology that survived prior hardening passes is dead. Worker engines wrap in try/finally so disconnect always fires (panic-path leak fix). Both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`), validated via `parseWorkers`. Explicit `--workers` bypasses the auto-path file-count floor; auto path defers to `autoConcurrency()`. Banner moved to stderr.- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive (extended to **8 phases in v0.23**). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantically-driven order: **lint → backlinks → sync → synthesize → extract → patterns → embed → orphans**. v0.23's `synthesize` phase runs after sync (cross-references see fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (codex finding #7 — subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default; extract is the canonical materialization). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite. `CycleReport.schema_version: "1"` is stable; totals additively grew in v0.23 (`transcripts_processed`, `synth_pages_written`, `patterns_written`). `yieldBetweenPhases` runs between phases. **v0.23 added `yieldDuringPhase`** for in-phase keepalive — synthesize/patterns call it during long waits to renew the cycle-lock TTL. Engine nullable; lock-skip on read-only phase selections. v0.22.1 (#403): `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal; `checkAborted()` fires between every phase. v0.22.1 (#417): `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult`; `runCycle` captures it and threads to `runPhaseExtract` as the 4th arg. v0.22.1 (Codex F2): `runPhaseSync` takes `willRunExtractPhase: boolean` and sets `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. v0.22.5 (#475): `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor instead of the drift-prone global `config.sync.last_commit` key.-- `src/core/cycle/synthesize.ts` (v0.23) — Synthesize phase: conversation-transcript-to-brain pipeline. Reads from `dream.synthesize.session_corpus_dir`, runs cheap Haiku verdict (cached in `dream_verdicts`), then fans out one Sonnet subagent per worth-processing transcript with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at` — codex finding #2) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency key `dream:synth:<file_path>:<content_hash>`. Auto-commit deferred to v1.1 (codex #5). `--dry-run` runs Haiku, skips Sonnet (codex #8). Subagent never gets fs-write access.+- `src/core/cycle/synthesize.ts` (v0.23) — Synthesize phase: conversation-transcript-to-brain pipeline. Reads from `dream.synthesize.session_corpus_dir`, runs cheap Haiku verdict (cached in `dream_verdicts`), then fans out one Sonnet subagent per worth-processing transcript with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at` — codex finding #2) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency key `dream:synth:<file_path>:<content_hash>`. Auto-commit deferred to v1.1 (codex #5). `--dry-run` runs Haiku, skips Sonnet (codex #8). Subagent never gets fs-write access. **v0.23.2:** `renderPageToMarkdown` (now exported) stamps `dream_generated: true` and `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the dream-cycle summary index. The marker is the explicit identity surface checked by `isDreamOutput` in `transcript-discovery.ts` — replaces the v0.23.1 content-prefix heuristic that could miss real output (`serializeMarkdown` doesn't embed slugs in body) and false-positive on user transcripts citing brain pages. `judgeSignificance` and `JudgeClient` are exported; `judgeSignificance` accepts a `verdictModel` parameter (default `claude-haiku-4-5-20251001`) loaded from `dream.synthesize.verdict_model` via `loadSynthConfig`.- `src/core/cycle/patterns.ts` (v0.23) — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Single Sonnet subagent; same allow-list path as synthesize. Runs AFTER `extract` so the graph is fresh.-- `src/core/cycle/transcript-discovery.ts` (v0.23) — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (Q-3: `medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path.-- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI; ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. **v0.23 added** `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs Haiku significance verdict but skips Sonnet synthesis (codex finding #8 — NOT zero LLM calls). Exit code 1 on status=failed.+- `src/core/cycle/transcript-discovery.ts` (v0.23) — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (Q-3: `medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. **v0.23.2 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 `discoverTranscripts` and `readSingleTranscript` skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no more silent skips). `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`. Replaces v0.23.1's `DREAM_OUTPUT_SLUGS` content-prefix list.+- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI; ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. **v0.23 added** `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs Haiku significance verdict but skips Sonnet synthesis (codex finding #8 — NOT zero LLM calls). Exit code 1 on status=failed. **v0.23.2 added** `--unsafe-bypass-dream-guard` (long-form intentional, plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` and `readSingleTranscript({bypassGuard})`). Loud stderr warning fires at synthesize-phase entry when set. Never auto-applied for `--input` so any caller can't silently re-trigger the loop bug.- `src/commands/friction.ts` + `src/core/friction.ts` (v0.23) — `gbrain friction {log,render,list,summary}` reporter. Append-only JSONL under `$GBRAIN_HOME/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError` (D20). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.- `src/commands/claw-test.ts` + `src/core/claw-test/` (v0.23) — `gbrain claw-test [--scenario <name>] [--live --agent openclaw]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real openclaw subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Phases for scripted mode: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`, asserts `status: 'ok'`) → render. Live mode hands `BRIEF.md` from `test/fixtures/claw-test-scenarios/<name>/` to the agent runner. v1 ships with the OpenClaw runner only (`src/core/claw-test/runners/openclaw.ts`, invokes `openclaw agent --local --agent <name> --message <brief>`); hermes runner deferred to v1.1. Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure — D17 fix for the 256KB-burst child-stall scenario. v0.18 upgrade scenario seeded via `seed-pglite.ts` SQL replay.- `skills/_friction-protocol.md` (v0.23) — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.@@ -610,6 +610,24 @@ Two equivalent paths:Both must pass. Do not ship with failing E2E tests. Do not skip E2E tests.+**Always run typecheck before pushing.** `bun test` (the bun runner)+skips TypeScript type checking — it only enforces runtime behavior.+Three ways to actually gate on types:++1. `bun run test` (npm script in `package.json`) — includes `bun run typecheck`+ plus the four shell pre-checks (`check-jsonb-pattern.sh`,+ `check-progress-to-stdout.sh`, `check-trailing-newline.sh`,+ `check-wasm-embedded.sh`) before the runner. Use this mid-branch.+2. `bun run typecheck` — `tsc --noEmit` standalone. Fast (~5s on this repo).+3. `bun run ci:local` — the full local CI gate from Path A.++The trap is: writing a new test, running `bun test test/foo.test.ts`,+seeing it pass, pushing — and CI's separate typecheck stage rejects an+invalid type literal that the runner accepted. Caught one of these+shipping the v0.23.2 round-trip E2E (`type: 'reflection'` is not a+member of `PageType`). Run `bun run typecheck` once before push, even+when only test files changed.+## Post-ship requirements (MANDATORY)After EVERY /ship, you MUST run /document-release. This is NOT optional. Do NOTdiff --git a/package.json b/package.jsonindex 28f93ee086..42195caad9 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.23.1",+ "version": "0.23.2","description": "Postgres-native personal knowledge brain with hybrid RAG search","type": "module","main": "src/core/index.ts",diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex a26268f2f4..91ffdaf4e0 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -47,6 +47,12 @@ interface DreamArgs {from: string | null;/** v0.21: backfill range end (YYYY-MM-DD). */to: string | null;+ /**+ * v0.23.2: disable the synthesize phase's self-consumption guard.+ * Long-form flag name to discourage casual use; loud stderr warning fires when set.+ * Never auto-applied for --input (codex finding #3).+ */+ bypassDreamGuard: boolean;}const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;@@ -114,6 +120,7 @@ function parseArgs(args: string[]): DreamArgs {date,from,to,+ bypassDreamGuard: args.includes('--unsafe-bypass-dream-guard'),};}@@ -179,6 +186,12 @@ Options:--from YYYY-MM-DD Backfill range start (use with --to).--to YYYY-MM-DD Backfill range end.+ --unsafe-bypass-dream-guard+ Disable the self-consumption guard. Use only when you+ know the input file is NOT dream-cycle output but the+ guard is firing. Loud stderr warning + cost reminder+ fires every run.+--help, -h Show this helpExamples:@@ -271,6 +284,7 @@ export async function runDream(engine: BrainEngine | null, args: string[]): PromsynthDate: opts.date ?? undefined,synthFrom: opts.from ?? undefined,synthTo: opts.to ?? undefined,+ synthBypassDreamGuard: opts.bypassDreamGuard,});if (opts.json) {diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex e3a5652108..c9ec558f70 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -176,6 +176,13 @@ export interface CycleOpts {synthDate?: string;synthFrom?: string;synthTo?: string;+ /**+ * v0.23.2: explicit opt-in to disable the synthesize self-consumption guard.+ * Wired from `gbrain dream --unsafe-bypass-dream-guard`. Never auto-applied+ * for `--input` because that would let any caller silently re-trigger the+ * loop bug (codex finding #3).+ */+ synthBypassDreamGuard?: boolean;/*** AbortSignal from the Minions worker (v0.22.1, #403). When aborted* (timeout, cancel, lock-loss), runCycle bails between phases and@@ -821,6 +828,7 @@ export async function runCycle(date: opts.synthDate,from: opts.synthFrom,to: opts.synthTo,+ bypassDreamGuard: opts.synthBypassDreamGuard,}));result.duration_ms = duration_ms;phaseResults.push(result);diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 96cd40e216..c47d67f8f8 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -57,6 +57,13 @@ export interface SynthesizePhaseOpts {date?: string;from?: string;to?: string;+ /**+ * Disable the self-consumption guard. Wired from the+ * `--unsafe-bypass-dream-guard` CLI flag. NOT auto-applied for `--input`+ * because that would allow any dream-generated page to silently re-enter+ * the synthesize loop. Caller must opt in explicitly.+ */+ bypassDreamGuard?: boolean;}export async function runPhaseSynthesize(@@ -87,9 +94,16 @@ export async function runPhaseSynthesize(}}+ if (opts.bypassDreamGuard) {+ process.stderr.write(+ '[dream] WARNING: --unsafe-bypass-dream-guard set; self-consumption guard disabled. ' ++ 'Re-ingestion of dream output will incur Sonnet costs forever.\n',+ );+ }+// Discover.const transcripts = opts.inputFile- ? loadAdHocTranscript(opts.inputFile, config.minChars, config.excludePatterns)+ ? loadAdHocTranscript(opts.inputFile, config.minChars, config.excludePatterns, opts.bypassDreamGuard): discoverTranscripts({corpusDir: config.corpusDir!,meetingTranscriptsDir: config.meetingTranscriptsDir ?? undefined,@@ -98,6 +112,7 @@ export async function runPhaseSynthesize(date: opts.date,from: opts.from,to: opts.to,+ bypassGuard: opts.bypassDreamGuard,});if (transcripts.length === 0) {@@ -120,7 +135,7 @@ export async function runPhaseSynthesize(verdicts.push({ filePath: t.filePath, worth: false, reasons: ['no ANTHROPIC_API_KEY for significance judge'], cached: false });continue;}- const verdict = await judgeSignificance(haiku, t);+ const verdict = await judgeSignificance(haiku, t, config.verdictModel);await engine.putDreamVerdict(t.filePath, t.contentHash, verdict);verdicts.push({ filePath: t.filePath, worth: verdict.worth_processing, reasons: verdict.reasons, cached: false });if (verdict.worth_processing) worthProcessing.push(t);@@ -248,6 +263,7 @@ interface SynthConfig {minChars: number;excludePatterns: string[];model: string;+ verdictModel: string;cooldownHours: number;}@@ -258,6 +274,7 @@ async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig> {const minCharsStr = await engine.getConfig('dream.synthesize.min_chars');const excludeStr = await engine.getConfig('dream.synthesize.exclude_patterns');const model = (await engine.getConfig('dream.synthesize.model')) || 'claude-sonnet-4-6';+ const verdictModel = (await engine.getConfig('dream.synthesize.verdict_model')) || 'claude-haiku-4-5-20251001';const cooldownHoursStr = await engine.getConfig('dream.synthesize.cooldown_hours');let excludePatterns: string[] = ['medical', 'therapy'];@@ -275,6 +292,7 @@ async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig> {minChars: minCharsStr ? Math.max(0, parseInt(minCharsStr, 10) || 2000) : 2000,excludePatterns,model,+ verdictModel,cooldownHours: cooldownHoursStr ? Math.max(0, parseInt(cooldownHoursStr, 10) || 12) : 12,};}@@ -318,7 +336,7 @@ async function loadAllowedSlugPrefixes(): Promise<string[]> {// ── Significance judge (Haiku) ───────────────────────────────────────-interface JudgeClient {+export interface JudgeClient {create: (params: Anthropic.MessageCreateParamsNonStreaming) => Promise<Anthropic.Message>;}@@ -333,9 +351,10 @@ interface VerdictResult {reasons: string[];}-async function judgeSignificance(+export async function judgeSignificance(client: JudgeClient,t: DiscoveredTranscript,+ verdictModel = 'claude-haiku-4-5-20251001',): Promise<VerdictResult> {// Truncate the transcript at 8K chars for cost control. Haiku's verdict// doesn't need the full body; the opening + closing sections are usually@@ -362,7 +381,7 @@ Respond as JSON: {"worth_processing": <bool>, "reasons": ["<short>", "<short>"]}Two reasons max, one phrase each.`;const msg = await client.create({- model: 'claude-haiku-4-5-20251001',+ model: verdictModel,max_tokens: 200,system: sys,messages: [{ role: 'user', content: `Transcript ${t.basename}:\n\n${trimmed}` }],@@ -480,10 +499,20 @@ async function reverseWriteSlugs(return count;}-function renderPageToMarkdown(page: Page, tags: string[]): string {- // serializeMarkdown's contract: takes (frontmatter, compiled_truth, timeline, meta)- // and emits frontmatter + body + (optional) timeline section.- const frontmatter = (page.frontmatter ?? {}) as Record<string, unknown>;+/**+ * Render a Page to markdown, stamping the dream-output identity marker into+ * frontmatter. This stamp is the explicit identity surface checked by+ * `isDreamOutput` in transcript-discovery.ts. Stamping at render time covers+ * every reverse-write path (subagent reflections + originals + summary) with+ * one funnel; the prior content-pattern guard could miss real output because+ * `serializeMarkdown` does not embed the page slug in the body.+ */+export function renderPageToMarkdown(page: Page, tags: string[]): string {+ const frontmatter: Record<string, unknown> = {+ ...((page.frontmatter ?? {}) as Record<string, unknown>),+ dream_generated: true,+ dream_cycle_date: today(),+ };return serializeMarkdown(frontmatter,page.compiled_truth ?? '',@@ -525,8 +554,11 @@ async function writeSummaryPage(}const body = lines.join('\n');+ // Stamp the dream-output identity marker into the summary's frontmatter.+ // parseMarkdown below round-trips it into the DB-stored frontmatter, so the+ // marker survives any later reverse-render of the summary page.const fullMarkdown = serializeMarkdown(- {} as Record<string, unknown>,+ { dream_generated: true, dream_cycle_date: summaryDate } as Record<string, unknown>,body,'',{ type: 'note' as PageType, title: `Dream cycle ${summaryDate}`, tags: ['dream-cycle'] },@@ -564,9 +596,10 @@ function loadAdHocTranscript(filePath: string,minChars: number,excludePatterns: string[],+ bypassGuard?: boolean,): DiscoveredTranscript[] {const { readSingleTranscript } = require('./transcript-discovery.ts') as typeof import('./transcript-discovery.ts');- const t = readSingleTranscript(filePath, { minChars, excludePatterns });+ const t = readSingleTranscript(filePath, { minChars, excludePatterns, bypassGuard });return t ? [t] : [];}diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.tsindex 31ece62640..19ae56ba52 100644--- a/src/core/cycle/transcript-discovery.ts+++ b/src/core/cycle/transcript-discovery.ts@@ -41,11 +41,41 @@ export interface DiscoverOpts {from?: string;/** Inclusive range end (YYYY-MM-DD). */to?: string;+ /**+ * Disable the self-consumption guard. Caller must opt in explicitly via+ * `--unsafe-bypass-dream-guard`; never auto-applied for `--input` because+ * that would let any caller silently re-trigger the loop bug.+ */+ bypassGuard?: boolean;}const DATE_RE = /^(\d{4}-\d{2}-\d{2})/;const WORD_BOUNDARY_HEURISTIC = /^[a-zA-Z][a-zA-Z0-9_-]*$/;+/**+ * Self-consumption guard: identity-marker check against `dream_generated: true`+ * stamped by the synthesize phase's render paths.+ *+ * v0.23.1 used a body slug-prefix string match. Codex review of the v0.23.2+ * plan caught two flaws: (1) `serializeMarkdown` does NOT embed the page slug+ * into body content, so the prefix heuristic could miss real dream output, and+ * (2) real conversation transcripts that legitimately cite a brain page would+ * be silently dropped. v0.23.2 swaps content inference for explicit identity+ * stamped at render time.+ *+ * Regex anchored at frontmatter open (`---\n`), tolerates optional BOM and CRLF,+ * scans the first 2000 chars for `dream_generated: true` (any whitespace, case-+ * insensitive value, word boundary on `true`).+ */+const DREAM_MARKER_REGEX_SRC =+ '^\\uFEFF?-{3}\\r?\\n[\\s\\S]{0,2000}?dream_generated\\s*:\\s*true\\b';+export const DREAM_OUTPUT_MARKER_RE = new RegExp(DREAM_MARKER_REGEX_SRC, 'i');++export function isDreamOutput(content: string, bypass = false): boolean {+ if (bypass) return false;+ return DREAM_OUTPUT_MARKER_RE.test(content);+}+/*** Auto-wrap bare-word patterns in `\b<word>\b`. Power users can pass full* regex (e.g. `^therapy:`) which we honor verbatim. Heuristic: any input@@ -115,12 +145,14 @@ function listTextFiles(dir: string): string[] {* - aren't `.txt`* - have date-prefixed basenames outside the requested window* - have content shorter than `minChars`+ * - carry the `dream_generated: true` self-consumption marker (unless `bypassGuard`)* - match any compiled exclude pattern (case-insensitive word-boundary by default)** Returns sorted by filePath so re-runs are deterministic.*/export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[] {const minChars = opts.minChars ?? 2000;+ const bypass = opts.bypassGuard === true;const excludeRes = compileExcludePatterns(opts.excludePatterns);const dirs = [opts.corpusDir, opts.meetingTranscriptsDir].filter((d): d is string => typeof d === 'string' && d.length > 0,@@ -141,6 +173,10 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]continue;}if (content.length < minChars) continue;+ if (isDreamOutput(content, bypass)) {+ process.stderr.write(`[dream] skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);+ continue;+ }if (matchesAnyExclude(content, excludeRes)) continue;results.push({@@ -159,13 +195,15 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]/*** Read a single ad-hoc transcript file (`gbrain dream --input <file>`).* Bypasses the corpus-dir scan and date filters but still applies- * minChars + exclude_patterns when provided.+ * minChars + exclude_patterns when provided. The self-consumption guard+ * also still fires unless `bypassGuard` is set explicitly.*/export function readSingleTranscript(filePath: string,- opts: { minChars?: number; excludePatterns?: string[] } = {},+ opts: { minChars?: number; excludePatterns?: string[]; bypassGuard?: boolean } = {},): DiscoveredTranscript | null {const minChars = opts.minChars ?? 2000;+ const bypass = opts.bypassGuard === true;const excludeRes = compileExcludePatterns(opts.excludePatterns);let content: string;try {@@ -175,6 +213,11 @@ export function readSingleTranscript(throw new Error(`could not read transcript at ${filePath}: ${msg}`);}if (content.length < minChars) return null;+ if (isDreamOutput(content, bypass)) {+ const baseName = basename(filePath, '.txt');+ process.stderr.write(`[dream] readSingleTranscript skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);+ return null;+ }if (matchesAnyExclude(content, excludeRes)) return null;const baseName = basename(filePath, '.txt');const dateMatch = DATE_RE.exec(baseName);diff --git a/test/cycle-synthesize.test.ts b/test/cycle-synthesize.test.tsindex ed1ba294cb..cfee8c6a02 100644--- a/test/cycle-synthesize.test.ts+++ b/test/cycle-synthesize.test.ts@@ -15,7 +15,10 @@ import {discoverTranscripts,readSingleTranscript,compileExcludePatterns,+ isDreamOutput,+ DREAM_OUTPUT_MARKER_RE,} from '../src/core/cycle/transcript-discovery.ts';+import { judgeSignificance, renderPageToMarkdown, type JudgeClient } from '../src/core/cycle/synthesize.ts';let tmpDir: string;@@ -189,3 +192,137 @@ describe('readSingleTranscript', () => {expect(t!.inferredDate).toBeNull();});});++describe('self-consumption guard (v0.23.2 marker-based)', () => {+ test('REGRESSION: catches actual reverseWriteSlugs output from a real Page', () => {+ // Build a Page like the synthesize subagent would produce, run it through+ // the same renderPageToMarkdown the orchestrator uses, and assert the guard+ // fires. Codex finding #5: synthetic-string fixtures don't prove the guard+ // catches what the synthesize phase actually produces.+ const page = {+ slug: 'wiki/personal/reflections/2026-04-30-test-abc123',+ type: 'reflection' as const,+ title: 'Test reflection',+ compiled_truth: 'I learned something about [Alice](people/alice). No own-slug citation in body.',+ timeline: '',+ frontmatter: {},+ };+ const md = renderPageToMarkdown(page as any, ['dream-cycle']);+ const path = makeTranscript('2026-04-30-output.txt', md + '\n' + 'x'.repeat(3000));+ const result = readSingleTranscript(path, { minChars: 100 });+ expect(result).toBeNull();+ });++ test('does NOT fire on real conversation transcript citing a brain slug', () => {+ // The exact false-positive case codex finding #1 named: a user note that+ // legitimately mentions a reflection slug in plain text. Must NOT be skipped.+ const path = makeTranscript('convo.txt',+ 'User: tell me about wiki/personal/reflections/identity-foo and how it relates to my work.\n' ++ 'Agent: ' + 'x'.repeat(3000));+ const result = readSingleTranscript(path, { minChars: 100 });+ expect(result).not.toBeNull();+ });++ test('CRLF + BOM frontmatter still triggers guard', () => {+ const content = '\uFEFF---\r\ndream_generated: true\r\n---\r\n# x\r\n' + 'x'.repeat(3000);+ const path = makeTranscript('crlf.txt', content);+ const result = readSingleTranscript(path, { minChars: 100 });+ expect(result).toBeNull();+ });++ test('whitespace and case tolerance: matches dream_generated: true variants', () => {+ const variants = [+ '---\ndream_generated:true\n---\nbody' + 'x'.repeat(3000),+ '---\ndream_generated: true\n---\nbody' + 'x'.repeat(3000),+ '---\ndream_generated: TRUE\n---\nbody' + 'x'.repeat(3000),+ '---\ntitle: foo\ndream_generated: true\n---\nbody' + 'x'.repeat(3000),+ ];+ for (const variant of variants) {+ expect(isDreamOutput(variant)).toBe(true);+ }+ });++ test('does NOT fire when dream_generated is false or absent', () => {+ expect(isDreamOutput('---\ntitle: foo\n---\nbody')).toBe(false);+ expect(isDreamOutput('---\ndream_generated: false\n---\nbody')).toBe(false);+ expect(isDreamOutput('plain text with no frontmatter')).toBe(false);+ // dream_generatedfoo: true (no word boundary on the key) must NOT match+ expect(isDreamOutput('---\ndream_generatedfoo: true\n---\nbody')).toBe(false);+ });++ test('marker buried past 2000 chars does NOT trigger guard (perf bound)', () => {+ const padding = 'x'.repeat(2100);+ const content = '---\ntitle: real\n---\n' + padding + '\ndream_generated: true\n' + 'x'.repeat(3000);+ const path = makeTranscript('buried.txt', content);+ const result = readSingleTranscript(path, { minChars: 100 });+ expect(result).not.toBeNull();+ });++ test('bypassGuard=true overrides marker (--unsafe-bypass-dream-guard plumbing)', () => {+ const md = '---\ndream_generated: true\n---\n# Page\n' + 'x'.repeat(3000);+ const path = makeTranscript('marked.txt', md);+ expect(readSingleTranscript(path, { minChars: 100 })).toBeNull();+ expect(readSingleTranscript(path, { minChars: 100, bypassGuard: true })).not.toBeNull();+ });++ test('discoverTranscripts respects bypassGuard', () => {+ const md = '---\ndream_generated: true\n---\n# Page\n' + 'x'.repeat(3000);+ makeTranscript('2026-04-30-output.txt', md);+ makeTranscript('2026-04-30-real.txt', 'real transcript ' + 'x'.repeat(3000));++ const guarded = discoverTranscripts({ corpusDir: tmpDir, minChars: 100 });+ expect(guarded).toHaveLength(1);+ expect(guarded[0].basename).toBe('2026-04-30-real');++ const bypassed = discoverTranscripts({ corpusDir: tmpDir, minChars: 100, bypassGuard: true });+ expect(bypassed).toHaveLength(2);+ });++ test('DREAM_OUTPUT_MARKER_RE is anchored at file start (not mid-content)', () => {+ // Frontmatter delimiter must be at byte 0; mid-content `---\n` does not count.+ const content = 'preamble\n---\ndream_generated: true\n---\nbody' + 'x'.repeat(3000);+ expect(DREAM_OUTPUT_MARKER_RE.test(content)).toBe(false);+ });+});++describe('judgeSignificance', () => {+ function makeTranscript(): import('../src/core/cycle/transcript-discovery.ts').DiscoveredTranscript {+ return {+ filePath: '/tmp/x.txt',+ contentHash: 'abc123',+ content: 'A short conversation about something interesting.',+ basename: 'x',+ inferredDate: null,+ };+ }++ function mockClient(captured: { model?: string }): JudgeClient {+ return {+ create: async (p: any) => {+ captured.model = p.model;+ return { content: [{ type: 'text', text: '{"worth_processing": true, "reasons": ["test"]}' }] } as any;+ },+ };+ }++ test('passes verdict_model override to client.create', async () => {+ const captured: { model?: string } = {};+ await judgeSignificance(mockClient(captured), makeTranscript(), 'claude-sonnet-4-6');+ expect(captured.model).toBe('claude-sonnet-4-6');+ });++ test('defaults to claude-haiku-4-5-20251001 when model omitted', async () => {+ const captured: { model?: string } = {};+ await judgeSignificance(mockClient(captured), makeTranscript());+ expect(captured.model).toBe('claude-haiku-4-5-20251001');+ });++ test('returns worth_processing=false when judge returns unparseable text', async () => {+ const client: JudgeClient = {+ create: async () => ({ content: [{ type: 'text', text: 'no json here' }] } as any),+ };+ const r = await judgeSignificance(client, makeTranscript());+ expect(r.worth_processing).toBe(false);+ expect(r.reasons[0]).toContain('unparseable');+ });+});diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.tsindex 734bb5dd44..a72221d057 100644--- a/test/e2e/dream-synthesize-pglite.test.ts+++ b/test/e2e/dream-synthesize-pglite.test.ts@@ -17,7 +17,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { runPhaseSynthesize } from '../../src/core/cycle/synthesize.ts';+import { runPhaseSynthesize, renderPageToMarkdown } from '../../src/core/cycle/synthesize.ts';interface TestRig {engine: PGLiteEngine;@@ -212,6 +212,206 @@ describe('E2E synthesize — cooldown', () => {}, 30_000);});+describe('E2E synthesize — round-trip self-consumption guard (v0.23.2)', () => {+ /**+ * Capture stderr writes during a single synthesize run, restoring the+ * original writer afterward (even on throw). Returns the captured chunks.+ */+ async function captureStderr<T>(body: () => Promise<T>): Promise<{ result: T; stderr: string }> {+ const chunks: string[] = [];+ const original = process.stderr.write.bind(process.stderr);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stderr as any).write = (chunk: any, ..._args: any[]): boolean => {+ const s = typeof chunk === 'string' ? chunk : chunk.toString();+ chunks.push(s);+ return true;+ };+ try {+ const result = await body();+ return { result, stderr: chunks.join('') };+ } finally {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stderr as any).write = original;+ }+ }++ test('round-trip: synthesize-rendered dream output is skipped on the next run', async () => {+ // Production-realistic recursion:+ // 1. The synthesize phase wrote a reflection (DB + reverseWriteSlugs).+ // 2. A workflow downstream moved that .md content into the corpus dir+ // as a .txt (or symlinked, or the dirs overlap, or someone copied+ // OpenClaw session output over the top of a brain page export).+ // 3. The next overnight cycle reads the corpus dir.+ //+ // Without the guard, step 3 re-synthesizes the page, paying Sonnet costs+ // and corrupting provenance. With the v0.23.2 guard, the file is detected+ // by the `dream_generated: true` frontmatter marker and skipped silently+ // (with a stderr log so the operator can debug).+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir);++ // 1. Insert a reflection page in the DB the way the subagent would.+ const slug = 'wiki/personal/reflections/2026-04-30-test-roundtrip-abc123';+ await rig.engine.putPage(slug, {+ type: 'note',+ title: 'Test reflection (E2E round-trip)',+ compiled_truth: 'I noticed something. Cross-references to [Alice](people/alice).',+ timeline: '',+ frontmatter: {},+ });++ // 2. Reverse-render via the real synthesize-phase helper. This is the+ // code path that stamps `dream_generated: true` into frontmatter.+ const page = await rig.engine.getPage(slug);+ expect(page).not.toBeNull();+ const md = renderPageToMarkdown(page!, ['dream-cycle']);+ // Sanity: the marker must actually be in the rendered output.+ expect(md).toMatch(/dream_generated:\s*true/);+ expect(md.length).toBeGreaterThan(100);++ // 3. Drop the rendered content into the corpus dir as a .txt file —+ // pad to clear the 2000-char minChars threshold so we don't get+ // short-circuited before the guard even runs.+ writeFileSync(+ join(rig.corpusDir, '2026-04-30-leaked-reflection.txt'),+ md + '\n' + '\nfollow-up notes that the operator scribbled.\n'.repeat(50),+ );++ // 4. Run synthesize. Capture stderr so we can prove the guard logged+ // its skip line (no-more-silent-skips contract).+ await withoutAnthropicKey(async () => {+ const { result, stderr } = await captureStderr(() =>+ runPhaseSynthesize(rig.engine, {+ brainDir: rig.brainDir,+ dryRun: false,+ }),+ );++ expect(result.status).toBe('ok');+ // Discovery skipped the file → the no-transcripts short-circuit fires.+ expect(result.summary).toMatch(/no transcripts to process/);+ expect((result.details as { transcripts_processed: number }).transcripts_processed).toBe(0);+ expect((result.details as { pages_written: number }).pages_written).toBe(0);+ // No verdicts entry: the file never made it past discovery, so the+ // verdict cache stays untouched (this matters because a cached "false"+ // would shadow a future legit edit of a real conversation transcript).+ const verdicts = (result.details as { verdicts?: unknown[] }).verdicts;+ expect(verdicts === undefined || (Array.isArray(verdicts) && verdicts.length === 0)).toBe(true);+ // Stderr log fired — operator can see the skip when debugging.+ expect(stderr).toMatch(/\[dream\] skipped 2026-04-30-leaked-reflection: dream_generated marker/);+ });+ } finally {+ await rig.cleanup();+ }+ }, 30_000);++ test('round-trip: bypassDreamGuard=true re-enables ingestion of marked output', async () => {+ // Power-user escape hatch (`gbrain dream --unsafe-bypass-dream-guard`).+ // The same marked file that was skipped above now gets discovered when+ // bypassDreamGuard is set at the phase entry. Proves the bypass plumbing+ // reaches discoverTranscripts at phase scope, not just at the+ // function-pair level the unit tests cover.+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir);++ const slug = 'wiki/personal/reflections/2026-04-30-bypass-test-def456';+ await rig.engine.putPage(slug, {+ type: 'note',+ title: 'Bypass test',+ compiled_truth: 'Some content. ' + 'x '.repeat(500),+ timeline: '',+ frontmatter: {},+ });+ const page = await rig.engine.getPage(slug);+ const md = renderPageToMarkdown(page!, ['dream-cycle']);+ writeFileSync(join(rig.corpusDir, '2026-04-30-bypass.txt'), md + '\n' + 'x '.repeat(500));++ await withoutAnthropicKey(async () => {+ const { result, stderr } = await captureStderr(() =>+ runPhaseSynthesize(rig.engine, {+ brainDir: rig.brainDir,+ dryRun: false,+ bypassDreamGuard: true,+ }),+ );++ expect(result.status).toBe('ok');+ // File was discovered — verdict array has the entry, even though+ // the no-key path makes it worth=false.+ const verdicts = (result.details as { verdicts: Array<{ worth: boolean; reasons: string[] }> }).verdicts;+ expect(verdicts).toHaveLength(1);+ expect(verdicts[0].reasons[0]).toMatch(/ANTHROPIC_API_KEY/);+ // Loud warning fired at phase entry so the operator never wonders+ // why the guard quietly let dream output through.+ expect(stderr).toMatch(/\[dream\] WARNING: --unsafe-bypass-dream-guard set/);+ // The standard "skipped" log must NOT have fired (the bypass kicks+ // in inside isDreamOutput before the log path runs).+ expect(stderr).not.toMatch(/\[dream\] skipped .*: dream_generated marker/);+ });+ } finally {+ await rig.cleanup();+ }+ }, 30_000);++ test('round-trip: dream output + real transcript → only the real one is discovered', async () => {+ // Mixed corpus: a leaked dream-output file alongside a legitimate+ // conversation transcript. The guard must skip exactly the marked file+ // and let the real one through.+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir);++ // Leaked reflection.+ const slug = 'wiki/personal/reflections/2026-04-30-mixed-ghi789';+ await rig.engine.putPage(slug, {+ type: 'note',+ title: 'Leaked',+ compiled_truth: 'leaked body. ' + 'x '.repeat(500),+ timeline: '',+ frontmatter: {},+ });+ const md = renderPageToMarkdown((await rig.engine.getPage(slug))!, ['dream-cycle']);+ writeFileSync(join(rig.corpusDir, '2026-04-30-leaked.txt'), md + '\n' + 'x '.repeat(500));++ // Real conversation transcript (no frontmatter, plain prose).+ writeFileSync(+ join(rig.corpusDir, '2026-04-30-real-convo.txt'),+ 'User: today I want to think about wiki/personal/reflections/identity.\n' ++ 'Agent: ' + 'meaningful conversation '.repeat(200),+ );++ await withoutAnthropicKey(async () => {+ const { result, stderr } = await captureStderr(() =>+ runPhaseSynthesize(rig.engine, {+ brainDir: rig.brainDir,+ dryRun: false,+ }),+ );++ expect(result.status).toBe('ok');+ const verdicts = (result.details as { verdicts: Array<{ filePath: string; worth: boolean }> }).verdicts;+ // Exactly one verdict — the real transcript. The leaked file was+ // dropped at discovery before the verdict pass even started.+ expect(verdicts).toHaveLength(1);+ expect(verdicts[0].filePath).toMatch(/2026-04-30-real-convo\.txt$/);+ // Stderr log fired for the leaked file specifically.+ expect(stderr).toMatch(/\[dream\] skipped 2026-04-30-leaked: dream_generated marker/);+ // ... and only the leaked file. A legitimate transcript that merely+ // mentions a reflection slug (codex finding #1's headline false-positive)+ // must not be skipped.+ expect(stderr).not.toMatch(/\[dream\] skipped 2026-04-30-real-convo/);+ });+ } finally {+ await rig.cleanup();+ }+ }, 30_000);+});+describe('E2E synthesize — verdict cache (Q-2)', () => {test('subsequent run with same content reads from dream_verdicts cache', async () => {// Two synth runs through the verdict-cache path; default 5s is tight.