Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(cycle): opt-in markdown write-through for generated atoms and concepts (#5041)

time-attack2363c84efc7d
diff --git a/TODOS.md b/TODOS.md
index 5be9d48641..fe21e07cf4 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -385,8 +385,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
**What:** migration 150's volatile default rewrites `pages` and hits a torn TOAST chunk on a corrupt PGLite brain; doctor's `child_table_orphans` prints raw `DELETE` SQL that PGLite users cannot run. **Fix:** `gbrain repair orphans` running doctor's own cleanup, plus a re-import-from-canonical-file repair for a torn body. Changing migration 150 itself is high risk for a corruption edge case and stays out. **Effort:** M. **Priority:** P3.
- [ ] **P3 — #5279: abandon an unactivated writer claim.**
**What:** a claim that was never activated leaves ownership markers that fence legacy sync, and there is no undo before activation. **Fix:** `gbrain sources writer claim <source> --abandon`, refused once the brain is enabled, that removes only markers stamped with this brain and claim. **Effort:** M. **Priority:** P3.
-- [ ] **P3 — #5041: classic write-through for `extract_atoms` and `synthesize_concepts`.**
- **What:** on classic brains with `sync.repo_path`, atoms and concepts are written to the database only; neither phase calls `writePageThrough`. Managed brains publish them through maintenance publication. **Fix:** opt-in write-through for generated pages, careful not to write raw-input types into gitignored paths. **Effort:** M. **Priority:** P3.
+- [x] **P3 — #5041: classic write-through for `extract_atoms` and `synthesize_concepts`.** **Completed: fix wave 9 (lane P)** — opt-in keys `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` write generated atoms and concepts as markdown files on unmanaged brains (the next run backfills earlier pages; retired atoms lose their files; gitignored and declared `db_only` targets stay database-only), and a concept that already has a file is rewritten in place. Pinned by `test/cycle/derived-write-through.test.ts`.
- [ ] **P3 — #5061: `getStats`/`getHealth` cost on large Postgres brains.**
**What:** both are uncached full aggregates, and `getHealth` runs a per-page links count; they are reachable from the CLI, `/admin/api/full-stats` and the MCP stats and health ops, so a client polling them loads a large brain. The admin dashboard itself does not poll them. **Fix:** a short TTL cache or estimate counts on the HTTP and MCP paths. **Effort:** M. **Priority:** P3.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 4940833c5e..a59feade88 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -18,6 +18,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `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.
+- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory, then calls `writePageThrough` (which honours `sync.write_through=off`). Tests: `test/cycle/derived-write-through.test.ts`.
- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started or another writer owns it, and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`.
- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 6bdb7184dd..808fa8d640 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -32,13 +32,13 @@ src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (
src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle.ts runCycle 1271 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)
-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)
+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 789 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stop
src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 464 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts)
+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 465 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +1 (#5041): opt-in concept write-through hook
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/import-file.ts importFromContent 808 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4620a5c050..346149c620 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -15,7 +15,7 @@ src/core/ai/gateway.ts 4408 ratchet +7 fix wave 5 (#5137): provider-key redactor
src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)
src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)
src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
-src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
+src/core/cycle/extract-atoms.ts 1814 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts)
src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso
src/core/import-file.ts 2179 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts
index 3e5883f930..6f6f47552d 100644
--- a/src/core/cycle/concept-publication.ts
+++ b/src/core/cycle/concept-publication.ts
@@ -19,6 +19,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { acquirePageLock } from '../page-lock.ts';
import { importFromContent } from '../import-file.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
+import { writeDerivedPageThrough } from './derived-write-through.ts';
/** Error code for a concept held because republication could lose canonical material. */
export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';
@@ -153,12 +154,11 @@ export function stripFenceSections(body: string): string {
.replace(/\n{3,}/g, '\n\n').trim();
}
-/** The body and timeline a fence writer last wrote: the page's file when it has one, else the database row. */
-async function canonicalConceptBody(engine: BrainEngine, slug: string, sourceId: string,
- page: Pick<Page, 'compiled_truth' | 'timeline'>): Promise<Pick<Page, 'compiled_truth' | 'timeline'>> {
- if (await isWriteThroughDisabled(engine)) return page;
+/** The page's markdown file, when it has one and write-through is not off: the fence writers write it first. */
+async function conceptFile(engine: BrainEngine, slug: string, sourceId: string): Promise<Pick<Page, 'compiled_truth' | 'timeline'> | null> {
+ if (await isWriteThroughDisabled(engine)) return null;
const target = await resolvePageWriteTarget(engine, slug, sourceId);
- if (!target.ok || !existsSync(target.filePath)) return page;
+ if (!target.ok || !existsSync(target.filePath)) return null;
const parsed = parseMarkdown(readFileSync(target.filePath, 'utf-8'), target.filePath);
return { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline };
}
@@ -170,11 +170,14 @@ async function canonicalConceptBody(engine: BrainEngine, slug: string, sourceId:
* writer took it over, nothing is written and the concept is deferred
* (`revision_conflict`) to the next run. Otherwise the new narrative is
* composed with the latest `## Facts` / `## Takes` fences, timeline, tags and
- * frontmatter, so a take or fact appended during synthesis survives. Returns
- * the narrative now on the page (the next call's baseline).
+ * frontmatter, so a take or fact appended during synthesis survives. The
+ * page's file is rewritten when it already has one (a stale file would
+ * otherwise be synced back over the new narrative) or when
+ * `cycle.synthesize_concepts.write_through` is on (#5041). Returns the
+ * narrative now on the page (the next call's baseline).
*/
export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string,
- synthesized: Record<string, unknown>, narrative: string, baseline: string, noEmbed: boolean): Promise<string> {
+ synthesized: Record<string, unknown>, narrative: string, baseline: string, opts: { noEmbed: boolean; writeThrough: boolean }): Promise<string> {
const lock = await acquirePageLock(slug, { timeoutMs: 5_000 });
if (!lock) throw Object.assign(new Error('The concept page is locked by another writer.'), { code: 'revision_conflict' });
try {
@@ -185,10 +188,12 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s
throw Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' });
}
const title = slug.split('/').pop()!.replace(/-/g, ' ');
+ const file = page ? await conceptFile(engine, slug, sourceId) : null;
const markdown = page
- ? composeConceptRepublication({ ...page, ...await canonicalConceptBody(engine, slug, sourceId, page) }, snapshot!.tags, synthesized, narrative)
+ ? composeConceptRepublication({ ...page, ...file }, snapshot!.tags, synthesized, narrative)
: serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });
- await importFromContent(engine, slug, markdown, { noEmbed, sourceId });
+ await importFromContent(engine, slug, markdown, { noEmbed: opts.noEmbed, sourceId });
+ if (file || opts.writeThrough) await writeDerivedPageThrough(engine, slug, sourceId);
return narrative;
} finally {
await lock.release();
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.ts
new file mode 100644
index 0000000000..4b321cf0c7
--- /dev/null
+++ b/src/core/cycle/derived-write-through.ts
@@ -0,0 +1,89 @@
+/**
+ * Opt-in markdown write-through for pages the dream cycle generates on an
+ * unmanaged brain (#5041): atoms (`extract_atoms`) and concepts
+ * (`synthesize_concepts`). Off by default, so the cycle never adds files to a
+ * user's repository unasked; managed brains publish these pages through
+ * maintenance publication instead and never reach this module.
+ *
+ * Enabled by `cycle.extract_atoms.write_through` /
+ * `cycle.synthesize_concepts.write_through`. Each written page goes through
+ * `writePageThrough` (honouring `sync.write_through=off`, source containment
+ * and case collisions). A page whose target is ignored by git or sits in a
+ * declared `storage.db_only` directory (which sync gitignores) stays
+ * database-only. The first run after the key is enabled also writes the
+ * generated pages that have no file yet, a bounded batch per run. A page the
+ * phase retires has its file removed, so sync cannot bring it back.
+ */
+import { execFileSync } from 'node:child_process';
+import { relative } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { isDbOnly, loadStorageConfig } from '../storage-config.ts';
+import { deletePageThrough, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';
+
+export const DERIVED_WRITE_THROUGH_KEYS = {
+ extract_atoms: 'cycle.extract_atoms.write_through',
+ synthesize_concepts: 'cycle.synthesize_concepts.write_through',
+} as const;
+
+/** Pages without a file written per run by the enable-time backfill. */
+export const DERIVED_BACKFILL_LIMIT = 200;
+
+const ON_VALUES = new Set(['true', '1', 'yes', 'on']);
+
+export async function derivedWriteThroughEnabled(engine: BrainEngine, phase: keyof typeof DERIVED_WRITE_THROUGH_KEYS): Promise<boolean> {
+ const raw = await engine.getConfig(DERIVED_WRITE_THROUGH_KEYS[phase]).catch(() => null);
+ return raw != null && ON_VALUES.has(raw.trim().toLowerCase());
+}
+
+function gitIgnores(root: string, filePath: string): boolean {
+ try {
+ execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relative(root, filePath)], { stdio: 'ignore' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Write one generated page's markdown file. Never throws; returns whether a
+ * file was written. Ignored and db_only targets are skipped on purpose.
+ */
+export async function writeDerivedPageThrough(engine: BrainEngine, slug: string, sourceId: string): Promise<boolean> {
+ const target = await resolvePageWriteTarget(engine, slug, sourceId);
+ if (!target.ok) return false;
+ let storage = null;
+ try { storage = loadStorageConfig(target.writeRoot); } catch { /* unreadable gbrain.yml: sync reports it */ }
+ if ((storage && isDbOnly(slug, storage)) || gitIgnores(target.writeRoot, target.filePath)) return false;
+ const result = await writePageThrough(engine, slug, { sourceId });
+ if (result.error) console.error(`[write-through] ${slug}: ${result.error}`);
+ return result.written;
+}
+
+/**
+ * The phase's write-through hook, or null when it does not apply (key off,
+ * managed brain, dry run): writes the given pages and removes the files of
+ * the retired ones. Creating it writes the bounded backfill of generated
+ * pages of the phase's type in the source that have no file yet.
+ */
+export async function derivedWriteThrough(
+ engine: BrainEngine,
+ phase: keyof typeof DERIVED_WRITE_THROUGH_KEYS,
+ sourceId: string,
+ opts: { managed: boolean; dryRun: boolean },
+): Promise<((slugs: readonly string[], retired?: readonly string[]) => Promise<void>) | null> {
+ if (opts.managed || opts.dryRun || !await derivedWriteThroughEnabled(engine, phase)) return null;
+ const write = async (slugs: readonly string[], retired: readonly string[] = []) => {
+ for (const slug of slugs) await writeDerivedPageThrough(engine, slug, sourceId);
+ for (const slug of retired) await deletePageThrough(engine, slug, { sourceId });
+ };
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND source_path IS NULL
+ AND type = $2 AND ($2 <> 'concept' OR frontmatter->>'synthesized_by' LIKE 'synthesize_concepts%')
+ AND COALESCE(frontmatter->>'source_hash', '') NOT LIKE 'pending:%'
+ ORDER BY id LIMIT $3`,
+ [sourceId, phase === 'extract_atoms' ? 'atom' : 'concept', DERIVED_BACKFILL_LIMIT],
+ );
+ await write(rows.map(r => r.slug));
+ return write;
+}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index a3ea434086..81518f8525 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -66,6 +66,7 @@ import type { ProgressReporter } from '../progress.ts';
import { chat as gatewayChat, withBudgetTracker, isAvailable } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { importFromContent } from '../import-file.ts';
+import { derivedWriteThrough } from './derived-write-through.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
import { corpusTextForExtraction } from '../context/corpus-segments.ts';
@@ -691,6 +692,7 @@ export async function runPhaseExtractAtoms(
const sourceId = opts.sourceId ?? 'default';
const chat = opts._chat ?? gatewayChat;
const managed = await managedAtomSession(engine, sourceId, opts._managedRetry, opts.attempt?.writeWait);
+ const atomFiles = await derivedWriteThrough(engine, 'extract_atoms', sourceId, { managed: managed !== null, dryRun: opts.dryRun ?? false });
const writeRequests: WriteReceipt[] = [];
// 1a. Get transcripts (test seam OR production discovery).
@@ -1318,8 +1320,9 @@ export async function runPhaseExtractAtoms(
// C-14: atoms are keyed by LLM-chosen titles, which drift between
// extractions. Once this extraction is complete, retire the atoms an
// earlier extraction of the same source produced that this one did not.
- await retireStaleAtoms(engine, sourceId, item.kind === 'page'
+ const retired = await retireStaleAtoms(engine, sourceId, item.kind === 'page'
? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);
+ await atomFiles?.(importedSlugs, retired);
if (item.kind === 'page') {
await stampAtomsScanHash(item);
}
@@ -1658,7 +1661,7 @@ async function retireStaleAtoms(
origin: { key: 'source_slug' | 'source_path'; value: string },
hash16: string,
currentSlugs: string[],
-): Promise<void> {
+): Promise<string[]> {
try {
const rows = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM pages
@@ -1672,8 +1675,10 @@ async function retireStaleAtoms(
);
const stale = rows.map(r => r.slug);
for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));
+ return stale;
} catch (err) {
console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
+ return [];
}
}
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index 06100821ff..f4ace1d42d 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -34,6 +34,7 @@ import { slugifySegment } from '../sync.ts';
import { validatePageSlug } from '../ops/context.ts';
import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
+import { derivedWriteThrough } from './derived-write-through.ts';
import {
addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,
} from './concept-publication.ts';
@@ -289,6 +290,7 @@ export async function runPhaseSynthesizeConcepts(
// maintenance authority before any model spend so a missing canonical owner
// fails fast; null on an unmanaged brain.
const maintenance = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId ?? 'default', opts.brainDir);
+ const conceptFiles = await derivedWriteThrough(engine, 'synthesize_concepts', opts.sourceId ?? 'default', { managed: maintenance !== null, dryRun: opts.dryRun ?? false });
// Managed publication outcomes, kept out of `failures` (LLM fallback). A
// deferred concept moved under a concurrent writer and is retried next run;
// a held concept cannot be republished without losing canonical material.
@@ -450,7 +452,7 @@ export async function runPhaseSynthesizeConcepts(
}
// #4416: target the cycle's resolved source, not the 'default' literal.
baseline = await publishClassicConcept(engine, conceptSlug, opts.sourceId ?? 'default', synthesized(pageVisibility), narrative,
- baseline, !isAvailable('embedding'));
+ baseline, { noEmbed: !isAvailable('embedding'), writeThrough: conceptFiles !== null });
};
// A publication that lost a revision race or would lose canonical
// material is recorded and skipped; any other error stops the phase.
diff --git a/test/cycle/derived-write-through.test.ts b/test/cycle/derived-write-through.test.ts
new file mode 100644
index 0000000000..882ff21921
--- /dev/null
+++ b/test/cycle/derived-write-through.test.ts
@@ -0,0 +1,139 @@
+// #5041: opt-in markdown write-through for generated atoms and concepts on an
+// unmanaged brain.
+//
+// Protects: with `cycle.extract_atoms.write_through` /
+// `cycle.synthesize_concepts.write_through` unset the phases stay
+// database-only; once a key is on, new pages land as markdown files in the
+// source checkout, pages generated before it was on are written on the next
+// run, a retired atom's file is removed, and a gitignored target stays
+// database-only.
+// Fails when: neither phase writes files (the pre-fix behavior), or a phase
+// writes files unasked.
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';
+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetWriteThroughCacheForTest();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-derived-wt-'));
+ execFileSync('git', ['init', '-q'], { cwd: repo });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);
+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');
+});
+
+const chat = (atoms: string[]) => async (_o: ChatOpts): Promise<ChatResult> => {
+ const text = JSON.stringify(atoms.map(title => ({ title, atom_type: 'insight', body: `${title} body.` })));
+ return {
+ text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ };
+};
+const extract = (titles: string[], contentHash = 'hash-one') => runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: '/fake/2026-09-07-meeting.txt', content: 'content', contentHash }], _pages: [], _chat: chat(titles),
+});
+const atomSlugs = async (live = true) => (await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE type = 'atom' AND (deleted_at IS NULL) = $1 ORDER BY slug`, [live])).map(r => r.slug);
+const fileFor = (slug: string) => join(repo, `${slug}.md`);
+
+describe('extract_atoms write-through (#5041)', () => {
+ test('off by default: atoms stay database-only', async () => {
+ await extract(['Renders vs proof']);
+ const [slug] = await atomSlugs();
+ expect(slug).toBeDefined();
+ expect(existsSync(fileFor(slug!))).toBe(false);
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('on: each new atom lands as a markdown file with its final frontmatter', async () => {
+ await engine.setConfig('cycle.extract_atoms.write_through', 'true');
+ await extract(['Renders vs proof', 'Founder lesson']);
+ const slugs = await atomSlugs();
+ expect(slugs).toHaveLength(2);
+ for (const slug of slugs) {
+ const parsed = parseMarkdown(readFileSync(fileFor(slug), 'utf-8'), fileFor(slug));
+ expect(parsed.type).toBe('atom');
+ expect(String(parsed.frontmatter.source_hash)).not.toStartWith('pending:');
+ }
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('enabling the key writes earlier atoms on the next run, and a retired atom loses its file', async () => {
+ await extract(['Renders vs proof']);
+ const [old] = await atomSlugs();
+ await engine.setConfig('cycle.extract_atoms.write_through', 'on');
+ await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: [], _chat: chat([]) });
+ expect(existsSync(fileFor(old!))).toBe(true);
+ await extract(['A different lesson'], 'hash-two');
+ expect(await atomSlugs(false)).toEqual([old!]);
+ expect(existsSync(fileFor(old!))).toBe(false);
+ const [current] = await atomSlugs();
+ expect(existsSync(fileFor(current!))).toBe(true);
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('a gitignored target stays database-only', async () => {
+ writeFileSync(join(repo, '.gitignore'), 'atoms/\n');
+ await engine.setConfig('cycle.extract_atoms.write_through', 'true');
+ await extract(['Renders vs proof']);
+ const [slug] = await atomSlugs();
+ expect(existsSync(fileFor(slug!))).toBe(false);
+ rmSync(repo, { recursive: true, force: true });
+ });
+});
+
+describe('synthesize_concepts write-through (#5041)', () => {
+ const atoms = Array.from({ length: 2 }, (_, i) => ({ slug: `atoms/a${i}`, title: `A${i}`, body: `b${i}`, concept_refs: ['flywheel'], visibility: 'world' as const }));
+
+ test('off by default; on writes the concept page file', async () => {
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });
+ expect(existsSync(fileFor('concepts/flywheel'))).toBe(false);
+ await engine.setConfig('cycle.synthesize_concepts.write_through', 'true');
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });
+ const parsed = parseMarkdown(readFileSync(fileFor('concepts/flywheel'), 'utf-8'), fileFor('concepts/flywheel'));
+ expect(parsed.type).toBe('concept');
+ expect(parsed.frontmatter.synthesized_by).toBe('synthesize_concepts-v0.41');
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('on: a newly synthesized concept is written by the publication itself', async () => {
+ await engine.setConfig('cycle.synthesize_concepts.write_through', 'true');
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });
+ expect(readFileSync(fileFor('concepts/flywheel'), 'utf-8')).toContain('T3 concept. 2 atoms reference this.');
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('a concept that already has a file is rewritten in place even with the key off', async () => {
+ await engine.setConfig('cycle.synthesize_concepts.write_through', 'true');
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });
+ await engine.setConfig('cycle.synthesize_concepts.write_through', 'false');
+ const three = [...atoms, { slug: 'atoms/a2', title: 'A2', body: 'b2', concept_refs: ['flywheel'], visibility: 'world' as const }];
+ await runPhaseSynthesizeConcepts(engine, { _atoms: three, sourceId: 'default' });
+ expect(readFileSync(fileFor('concepts/flywheel'), 'utf-8')).toContain('T3 concept. 3 atoms reference this.');
+ rmSync(repo, { recursive: true, force: true });
+ });
+});