Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): wave #8123 part C — write_through-off writeback, impossible timeline dates, image slugs, managed dry-run counts, archived and missing sources (#7084 #8118 #8049 #7107 #7087 #7701 #7889)
garrytan611c8bff1161
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bebd4b391d..e00f062eaf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Managed sync and source checks fixes from the sync/refresh wave (#8123 part C): `sync.write_through=false` keeps sync's frontmatter corrections out of the checkout, a page with an impossible timeline date no longer blocks sync, images with punctuation in their names sync, `sync --dry-run` previews what it would do, and a missing source directory is no longer reported clean.**++- With `sync.write_through` off, a managed sync keeps its canonical correction of a file (the frontmatter, title or tags a page keeps when an upstream edit drops them) in the database and never rewrites the checkout. Before, it wrote the rendering into the working tree and left it uncommitted, including into a read-only mirror's checkout reached through the `default` source's `sync.repo_path` fallback (#7084, #8118).+- A timeline bullet or heading dated with an impossible day (`2026-02-30`, month 13) is no longer extracted as a timeline row. It used to reach the database's date cast and fail the page's publication, which blocked a managed sync and aborted a whole `repair file-drift` preview batch (#8049). The text stays in the page.+- Managed image sync now gives an image the importer's identity (path lowercased, punctuation kept), so `notes/Photo+A.png` imports as `notes/photo+a.png` instead of being refused, and stays distinct from `notes/PhotoA.png` (#7107).+- A managed `gbrain sync --dry-run` reports and prints how many files the run would add, modify, soft-delete and rename. It used to report zero, or repeat the previous run's counts (#7087).+- `gbrain sources list` marks archived sources with `⚠ archived` and `--json` carries `archived` per source (#7701).+- A registered source whose directory is missing is reported `missing` by the frontmatter audit and both frontmatter doctor checks, with the path and the restore or `sources set-path` step, instead of clean (#7889).+## [0.60.529.0] - 2026-10-31**A pull request that adds a file to the PGLite snapshot inputs no longer gets stopped at gstack's pregate secrets check by its own workflow cache keys (#8107).**diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 940f3d39f4..77191de2f2 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -507,7 +507,8 @@ vars — incident-time escape hatches, not everyday knobs.last good revision and is read-only for `put_page` until the file isrepaired. A hold clears when the file changes, is deleted, or a newergbrain can read it; `gbrain sync --dry-run` lists would-be holds- (`would_hold`) without writing anything. The backlog fix is one previewed,+ (`would_hold`) and counts the files the run would add, modify, soft-delete+ and rename, without writing anything. The backlog fix is one previewed,hash-bound command per kind of hold:```bashdiff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 87ff89e39e..cd083fc254 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -429,6 +429,8 @@ maintenance write) is stored database-only too; its receipt sayswrite on, except for pages created while the source was a mirror: those haveno file in the checkout and stay database-only. Git effects of a mirror'swrites (for example a `forget`) complete as skipped. The flag is off by default.+With `sync.write_through` off, sync keeps that canonical metadata in the+database for every source, mirror or not, and never rewrites a checkout file.A managed brain never pulls inside a cycle. Advance a managed checkout withone command on its owner host:diff --git a/llms-full.txt b/llms-full.txtindex ffafd12558..92b4cb9615 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7261,7 +7261,8 @@ vars — incident-time escape hatches, not everyday knobs.last good revision and is read-only for `put_page` until the file isrepaired. A hold clears when the file changes, is deleted, or a newergbrain can read it; `gbrain sync --dry-run` lists would-be holds- (`would_hold`) without writing anything. The backlog fix is one previewed,+ (`would_hold`) and counts the files the run would add, modify, soft-delete+ and rename, without writing anything. The backlog fix is one previewed,hash-bound command per kind of hold:```bashdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b2e11fd8fb..8dac08cb27 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2100 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured)+src/commands/sources.ts 2102 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move)src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1755 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1575 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +1 GBRA-250 #8071 rows_behind_checkpoint_8071 row (since TBD until the merge slot); +1 GBRA-250 #8073 derived_write_through_commits_8073 row (since TBD until the merge slot); +2 GBRA-250 #8072 rows (oversize hold left unread, refresh sync budget; since TBD until the merge slot); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1)+src/core/behavior-change-notice.ts 1578 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +1 GBRA-250 #8071 rows_behind_checkpoint_8071 row (since TBD until the merge slot); +1 GBRA-250 #8073 derived_write_through_commits_8073 row (since TBD until the merge slot); +2 GBRA-250 #8072 rows (oversize hold left unread, refresh sync budget; since TBD until the merge slot); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot)diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex 9cdbf0caf0..767811b952 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -406,7 +406,8 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {frontmatterOnly: true,});- if (report.total === 0 && !report.partial) {+ const missing = report.per_source.filter(src => src.status === 'missing');+ if (report.total === 0 && !report.partial && !missing.length) {const sources = report.per_source.length;checks.push({name: 'frontmatter_integrity',@@ -420,6 +421,10 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {// skipped so the user can tell which sources weren't checked.const sourceMessages: string[] = [];for (const src of report.per_source) {+ if (src.status === 'missing') {+ sourceMessages.push(`${src.source_id}: NOT SCANNED (its directory ${src.source_path} is missing)`);+ continue;+ }if (src.status === 'skipped') {// Codex adversarial #1: `gbrain frontmatter validate` takes a// filesystem PATH, not a source id. Pre-fix the hint pointed users@@ -450,14 +455,16 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {const repairHint = 'Fix: gbrain repair frontmatter --source <id> previews the line fix for every file it can repair (and names the manual fix for the rest, '+ 'such as a missing opening ---); on an unmanaged checkout gbrain frontmatter validate <source-path> --fix applies the same safe fixes';const sourcesWithIssues = report.per_source.filter(src => src.total > 0).map(src => src.source_id);- const fixHint = report.partial+ const missingHint = missing.length ? `Restore the missing directory, or point the source at its checkout with gbrain sources set-path <id> <path>. ` : '';+ const fixHint = missingHint + (report.partial? `Raise GBRAIN_DOCTOR_FM_TIMEOUT_MS or run \`gbrain frontmatter validate <source-path>\` directly. ${repairHint}`- : repairHint;+ : repairHint);checks.push({name: 'frontmatter_integrity',status: 'warn',// #7145: a partial walk is a floor with health unknown past it, readable without parsing the message.- details: { count: report.total, partial: report.partial, exact: !report.partial,+ details: { count: report.total, partial: report.partial, exact: !report.partial && !missing.length,+ ...(missing.length ? { missing_sources: missing.map(src => src.source_id) } : {}),...(report.partial ? { ...boundUnknownDetails('time'), limit: fmTimeoutMs } : {}) },message:`${report.total} frontmatter issue(s)` +@@ -465,7 +472,7 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {`. ${sourceMessages.join('; ')}. ${fixHint}`,...(sourcesWithIssues.length === 1 ? { fix: agentFix(['gbrain', 'repair', 'frontmatter', '--source', sourcesWithIssues[0]!],'Previews the line fix for each file the repair can fix and names the manual fix for the rest; it writes nothing.', 'frontmatter_integrity',- { docs: 'docs/guides/repair.md#frontmatter' }) } : {}),+ { docs: 'docs/guides/repair.md#frontmatter' }) } : missing.length ? { fix_unavailable_reason: 'operator_judgement' as const } : {}),});}checks.push(frontmatterRepairableFromReport(report, fmTimeoutMs));diff --git a/src/commands/doctor/checks/frontmatter-repairable.ts b/src/commands/doctor/checks/frontmatter-repairable.tsindex ab9901746b..e714216f91 100644--- a/src/commands/doctor/checks/frontmatter-repairable.ts+++ b/src/commands/doctor/checks/frontmatter-repairable.ts@@ -25,6 +25,8 @@ export function frontmatterRepairableFromReport(report: AuditReport, timeoutMs:}));const files = sources.reduce((sum, src) => sum + src.files, 0);const unscanned = report.per_source.filter(src => src.status !== 'scanned').map(src => src.source_id);+ const timedOut = report.per_source.filter(src => src.status === 'partial' || src.status === 'skipped').map(src => src.source_id);+ const missing = report.per_source.filter(src => src.status === 'missing');const details = { repairable: files, source_ids: sources.map(src => src.source_id), sources, partial: report.partial, unscanned,docs: 'docs/guides/repair.md#frontmatter' };const single = sources.length === 1 ? sources[0]!.source_id : undefined;@@ -32,18 +34,22 @@ export function frontmatterRepairableFromReport(report: AuditReport, timeoutMs:'Previews the minimal line fix per file (safe quoting first; interpretations only with --include-ambiguous) and prints the hash-bound apply command; it writes nothing.','frontmatter_repairable', { docs: 'docs/guides/repair.md#frontmatter' });const partial = report.partial- ? ` PARTIAL SCAN: the walk stopped after ${timeoutMs / 1000}s, so ${unscanned.join(', ')} ${unscanned.length === 1 ? 'was' : 'were'} not fully checked; raise GBRAIN_DOCTOR_FM_TIMEOUT_MS and run gbrain doctor --only frontmatter_repairable again.`+ ? ` PARTIAL SCAN: the walk stopped after ${timeoutMs / 1000}s, so ${timedOut.join(', ')} ${timedOut.length === 1 ? 'was' : 'were'} not fully checked; raise GBRAIN_DOCTOR_FM_TIMEOUT_MS and run gbrain doctor --only frontmatter_repairable again.`: '';- if (!files && !report.partial) {+ const notScanned = missing.length+ ? ` NOT SCANNED: the directory of ${missing.map(src => `${src.source_id} (${src.source_path})`).join(', ')} is missing; restore it, or point the source at its checkout with gbrain sources set-path <id> <path>, then run gbrain doctor --only frontmatter_repairable again.`+ : '';+ if (!files && !report.partial && !missing.length) {return { name: 'frontmatter_repairable', status: 'ok', details,message: report.per_source.length ? 'No file has frontmatter gbrain repair frontmatter would fix.' : 'No registered sources to scan.' };}- if (!files) return { name: 'frontmatter_repairable', status: 'warn', details, fix_unavailable_reason: 'check_errored', message: `No repairable frontmatter found so far.${partial}` };+ if (!files) return { name: 'frontmatter_repairable', status: 'warn', details, fix_unavailable_reason: report.partial ? 'check_errored' : 'operator_judgement',+ message: `No repairable frontmatter found so far.${partial}${notScanned}` };return {name: 'frontmatter_repairable', status: 'warn', details, fix,message: `${files} file(s) have frontmatter gbrain repair frontmatter can fix: `+ `${sources.map(src => `${src.source_id}: ${src.files} (${Object.entries(src.by_code).map(([code, n]) => `${code}=${n}`).join(', ')})`).join('; ')}. `- + `Preview with ${sources.map(src => src.preview).join('; ')} (writes nothing; add --include-ambiguous for interpretations after the safe pass).${partial}`,+ + `Preview with ${sources.map(src => src.preview).join('; ')} (writes nothing; add --include-ambiguous for interpretations after the safe pass).${partial}${notScanned}`,};}diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.tsindex 0a4986b6fb..09aecd7731 100644--- a/src/commands/frontmatter.ts+++ b/src/commands/frontmatter.ts@@ -688,6 +688,10 @@ function printAuditHumanReport(report: AuditReport): void {}for (const src of report.per_source) {console.log(`\n[${src.source_id}] ${src.source_path}`);+ if (src.status === 'missing') {+ console.log(' NOT SCANNED: the directory is missing (restore it, or gbrain sources set-path <id> <path>)');+ continue;+ }if (src.total === 0) {console.log(' clean');continue;diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 39a9de55b5..e754f2e4f4 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -116,6 +116,7 @@ interface SourceListEntry {pull_strategy: 'rebase' | 'merge';page_count: number;last_sync_at: string | null;+ archived: boolean;}// ── Helpers ─────────────────────────────────────────────────@@ -734,6 +735,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {pull_strategy: pullStrategyOf(parseConfig(r.config)),page_count: pageCount,last_sync_at: r.last_sync_at ? new Date(r.last_sync_at).toISOString() : null,+ archived: r.archived === true,});}@@ -752,7 +754,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {// it out of OTHER anchors' reads — its own unqualified reads still widen// outward (see sourceFederationState). Collapsing both to "isolated"// overstates what an unset flag does.- const fedMark = (e as any).archived ? '⚠ archived' : sourceFederationState(rows[i].config);+ const fedMark = e.archived ? '⚠ archived' : sourceFederationState(rows[i].config);const pathStr = e.local_path ?? '(no local path)';const sync = e.last_sync_at ? `last sync ${e.last_sync_at}` : 'never synced';console.log(` ${e.id.padEnd(20)} ${fedMark.padEnd(12)} ${String(e.page_count).padStart(6)} pages ${sync}`);diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.tsindex 34f2bff0dc..c7ed5aed1d 100644--- a/src/commands/sync/report.ts+++ b/src/commands/sync/report.ts@@ -110,7 +110,8 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pwrite(` ${result.added} file(s) imported, ${result.chunksCreated} chunks${result.embedded > 0 ? `, ${result.embedded} pages embedded` : ''}`);break;case 'dry_run':- break; // already printed in performSync+ if (result.managedCursor) write(`Sync dry run${result.toCommit ? ` to ${result.toCommit.slice(0, 8)}` : ''}: would add ${result.added}, modify ${result.modified}, soft-delete ${result.deleted}, rename ${result.renamed}${result.added + result.modified + result.deleted + result.renamed === 0 ? ' (no syncable changes)' : ''}.`);+ break;case 'blocked_by_failures': {if (result.runId || (result.pass && result.failures?.length)) {write(result.runId ? `Sync BLOCKED at ${result.toCommit}: committed counts are cumulative for run ${result.runId}.`diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d2bcaa71a8..7d8f73590a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1377,6 +1377,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.525.0', id: 'derived_write_through_commits_8073', text: 'Files the dream cycle writes into a source that is a Git checkout are now committed: atom and concept files (with `cycle.extract_atoms.write_through` or `cycle.synthesize_concepts.write_through` on) and the reverse-written synthesis, patterns and cycle-summary pages and their removals. Each batch (an item\'s atoms plus the files of the atoms it retired, the backfill, one concept, or one phase\'s reverse-written pages) is one local commit naming only those files, made through the checkout\'s commit lock (a hardened checkout\'s post-commit hook pushes it; a checkout with a canonical owner marker gets a named-paths-only commit). They used to stay untracked or modified, which made the scheduled sync skip every run. A commit the checkout refuses rolls back the files it wrote and reports `write_through_failed` with a warn status; atoms and concepts are written again on the next run. Each written file is also recorded in the pending write-through ledger, so files a crash left uncommitted go into the next commit gbrain makes in that checkout. Files left uncommitted by earlier versions are not touched; commit them with `gbrain git commit-push -m <msg> -- <paths>`.' },{ since: '0.60.525.0', id: 'oversize_hold_unread_8072', text: 'A Markdown file over 24 MiB that sync had to read whole to refuse (segmented storage on, held `file_too_large`, for example for a facts fence) is no longer read again by every sync: it stays held, unread, until it changes, gbrain is upgraded, or `gbrain sources retry-held <source>` schedules it. After changing a setting the hold message names, run `gbrain sources retry-held <source>`. A file held from its size alone still re-checks on every sync.' },{ since: '0.60.525.0', id: 'refresh_sync_budget_8072', text: 'The member syncs of one `gbrain sources refresh` run stop starting work after `sources.refresh_sync_budget_ms` (default 5 minutes; `GBRAIN_REFRESH_SYNC_BUDGET_MS`). Each member gets an equal share of what is left. A run past it reports `sync_deferred` with the members it left `deferred` and still completes the refresh, so writes to the checkout are admitted again and the next `gbrain sources refresh <source>` continues them; a member that committed nothing in its share is reported `refresh_sync_timeout` in `sync_blocked`. A stalled sync no longer holds the refresh lock across scheduled runs or starves the other members.' },+ { since: 'TBD', id: 'sync_write_through_off_writeback_7084', text: 'With `sync.write_through` off, a managed `gbrain sync` no longer writes its canonical correction of a file (the frontmatter, title or tags the page keeps when an upstream edit drops them) back into the checkout (#7084, #8118). The page keeps the correction in the database only, as on a read-only mirror source, and `git status` stays clean. With `sync.write_through` on, nothing changes. Files already rewritten by earlier versions are not touched; restore them with `git checkout -- <paths>` or commit them.' },+ { since: 'TBD', id: 'managed_sync_dry_run_counts_7087', text: 'A managed `gbrain sync --dry-run` now reports the files the run would add, modify, soft-delete and rename, and prints them as one line (#7087). It used to report the cursor\'s committed counts: zero before a run, or the previous run\'s counts when nothing had changed.' },+ { since: 'TBD', id: 'frontmatter_missing_source_dir_7889', text: 'A registered source whose directory does not exist is no longer reported frontmatter-clean (#7889). The frontmatter audit marks it `missing` (and lists it under `missing_sources`), and doctor `frontmatter_integrity` and `frontmatter_repairable` warn with the path and ask you to restore it or run `gbrain sources set-path <id> <path>`; they no longer call it clean or blame a timeout.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex 566305034c..58da6cf77d 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -94,8 +94,9 @@ export interface PerSourceReport {/** Did this source finish the walk, get interrupted, or never start?* 'scanned' = full walk completed.* 'partial' = deadline/abort fired mid-walk; counts reflect prefix only.- * 'skipped' = source was never visited (outer loop broke before reaching it). */- status: 'scanned' | 'partial' | 'skipped';+ * 'skipped' = source was never visited (outer loop broke before reaching it).+ * 'missing' = the registered local_path does not exist, so nothing was checked (#7889). */+ status: 'scanned' | 'partial' | 'skipped' | 'missing';/** Count of .md files actually parsed (numerator for "scanned ~N of M" doctor message).* Distinct from `total` (which counts ERRORS) and `ignoredMissingOpen`. */files_scanned: number;@@ -117,6 +118,8 @@ export interface AuditReport {* this to render the warn message and to ensure `ok` is false even when the* scanned prefix happened to be clean (codex C2 fix). */partial: boolean;+ /** Ids of sources whose registered directory is missing (`status: 'missing'`); `ok` is false when any is. */+ missing_sources?: string[];/** Source id where deadline/abort fired mid-walk, or null when no partial. */aborted_at_source: string | null;}@@ -697,8 +700,6 @@ export async function scanBrainSources(}if (!src.local_path) continue;if (!existsSync(src.local_path)) {- // Source registered but path is missing on disk; surface as a zero-row- // entry with a synthetic SCAN_PATH_MISSING note via warn-and-skip.perSource.push({source_id: src.id,source_path: src.local_path,@@ -706,7 +707,7 @@ export async function scanBrainSources(errors_by_code: {},sample: [],ignoredMissingOpen: 0,- status: 'scanned',+ status: 'missing',files_scanned: 0,});continue;@@ -795,12 +796,13 @@ export async function scanBrainSources(}const hasPartialOrSkipped = perSource.some(r => r.status === 'partial' || r.status === 'skipped');+ const missingSources = perSource.filter(r => r.status === 'missing').map(r => r.source_id);return {// Partial scans can never be 'ok' even when the scanned prefix is clean// (codex outside-voice C2 — a clean prefix doesn't speak for the// unscanned suffix).- ok: grandTotal === 0 && !hasPartialOrSkipped,+ ok: grandTotal === 0 && !hasPartialOrSkipped && missingSources.length === 0,total: grandTotal,errors_by_code: totals,recoverability_by_code: recoverabilityTotals,@@ -808,6 +810,7 @@ export async function scanBrainSources(scanned_at: new Date().toISOString(),ignored_missing_open: ignoredMissingOpen || undefined,partial: hasPartialOrSkipped,+ ...(missingSources.length ? { missing_sources: missingSources } : {}),aborted_at_source: abortedAtSource,};}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 2b5f5b9e40..4defb26417 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -35,6 +35,7 @@ import { digest, sha256 } from './digest.ts';import { preserveProtectedTakes } from './protected-takes.ts';import { getWorktreeBinding } from './ownership.ts';import { sourceMirrorReadOnly } from './mirror-read-only.ts';+import { writeThroughConfigured } from './switches.ts';import { assertConfiguredSyncRoot, assertSyncEntryOrigin, readSyncFile, syncGit, syncRawHash, type SyncRename } from './sync-discovery.ts';import { directoryAt } from './sync-entry-fault.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';@@ -906,7 +907,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c// #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.enterClaimStep(clock, 'mirror_check', undefined, 'db');const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);- const canonicalFile = overlay && !mirrorReadOnly ? serializePageToMarkdown(renderedPage, tags) : null;+ const canonicalFile = overlay && !mirrorReadOnly && writeThroughConfigured(await engine.getConfig('sync.write_through')) ? serializePageToMarkdown(renderedPage, tags) : null;const writeback = canonicalWritebackNeeded(row, p, p.content, canonicalFile);// A rename projects against the moved page (same id), so its pinned timeline rows carry over.enterClaimStep(clock, 'canonical_projections', undefined, 'db');diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex dcd9734092..6beb06cf7f 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -377,12 +377,20 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor/*** Dry run: screens every pending import entry read-only (batched Git reads)* and lists the holds a real run would record. Entries the screen cannot- * judge are reported in `screen_skipped`, never as holds.+ * judge are reported in `screen_skipped`, never as holds. #7087: the counts are the changes still to publish (a+ * prescreened no-op and a fenced unowned deletion change nothing); they replace the cursor's committed counts.*/export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscovery & { index?: number }, run: SyncScreenRun | null, retryCommand: string): Promise<{- dry_run: true; would_hold?: GitHoldItem[]; would_hold_count?: number; would_normalize?: Array<{ path: string; classes: string[] }>; would_normalize_count?: number;+ dry_run: true; added: number; modified: number; deleted: number; renamed: number; would_hold?: GitHoldItem[]; would_hold_count?: number; would_normalize?: Array<{ path: string; classes: string[] }>; would_normalize_count?: number;screen_skipped?: Array<{ path: string; code: string }> }> {- if (!run || discovery.companyPlan) return { dry_run: true };+ const planned = { added: 0, modified: 0, deleted: 0, renamed: 0 };+ for (const entry of discovery.entries.slice(discovery.index ?? 0)) {+ if (entry.action === 'delete') { if (!entry.unownedDeletion) planned.deleted++; }+ else if (entry.renameFrom) planned.renamed++;+ else if (entry.pageId == null) planned.added++;+ else if (!entry.prescreened) planned.modified++;+ }+ if (!run || discovery.companyPlan) return { dry_run: true, ...planned };const entries = discovery.entries.slice(discovery.index ?? 0).filter(entry => entry.action === 'import' && entry.slug);const committed = entries.filter(entry => !entry.working);const blobs = readTreeBlobs(discovery.gitRoot, discovery.target, committed.map(entry => syncGitPath(discovery, entry.path)));@@ -423,7 +431,7 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscoveryskipped.push({ path: entry.path, code: error instanceof OperationError ? error.code : 'storage_error' });}}- return { dry_run: true, ...(held.length ? { would_hold: held.slice(0, run.policy.cap), would_hold_count: held.length } : {}),+ return { dry_run: true, ...planned, ...(held.length ? { would_hold: held.slice(0, run.policy.cap), would_hold_count: held.length } : {}),...(normalized.length ? { would_normalize: normalized.slice(0, run.policy.cap), would_normalize_count: normalized.length } : {}),...(skipped.length ? { screen_skipped: skipped } : {}) };}diff --git a/src/core/sync.ts b/src/core/sync.tsindex fa073cbbe0..b762121d5d 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -826,6 +826,7 @@ export function pathToSlug(* flow through without touching the sync code path.*/export function resolveSlugForPath(filePath: string, repoPrefix?: string): string {+ if (isImageFilePath(filePath)) return (repoPrefix ? `${repoPrefix}/${filePath}` : filePath).replace(/\\/g, '/').toLowerCase();const pageKind = isCodeFilePath(filePath) ? 'code' : 'markdown';return pathToSlug(filePath, repoPrefix, { pageKind });}diff --git a/src/core/timeline-citations.ts b/src/core/timeline-citations.tsindex 4ca941bdde..85ca0dcd22 100644--- a/src/core/timeline-citations.ts+++ b/src/core/timeline-citations.ts@@ -172,7 +172,7 @@ export function supersededInlineCitationEntries(content: string, opts: CitationOreturn readCitations(content, opts, true).filter(e => !current.has(JSON.stringify([e.date, e.source, e.summary])));}-function isValidDate(s: string): boolean {+export function isValidDate(s: string): boolean {if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;const [y, mo, d] = s.split('-').map(Number);if (mo < 1 || mo > 12) return false;diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex aa7f219249..b0fa6a163f 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -12,7 +12,7 @@*/import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseTimelineEntries } from './link-extraction.ts';-import { isDatedTimelineLine, supersededInlineCitationEntries } from './timeline-citations.ts';+import { isDatedTimelineLine, isValidDate, supersededInlineCitationEntries } from './timeline-citations.ts';import { createHash } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { firstMaterializedMarkerIndex } from './timeline-marker.ts';@@ -46,6 +46,7 @@ export function extractTimelineFromContent(content: string, slug: string): Extraconst bulletPattern = /^-\s+\*\*(\d{4}-\d{2}-\d{2})\*\*\s*\|\s*(.+)$/gm;let match;while ((match = bulletPattern.exec(content)) !== null) {+ if (!isValidDate(match[1])) continue;const rest = match[2].trim();// #4277: dated auto-generated backlink receipts// (`- **date** | Referenced in [X](y.md)`) are graph-maintenance noise —@@ -66,6 +67,7 @@ export function extractTimelineFromContent(content: string, slug: string): Extra// Format 2: Header — ### YYYY-MM-DD — Titleconst headerPattern = /^###\s+(\d{4}-\d{2}-\d{2})\s*[—–-]\s*(.+)$/gm;while ((match = headerPattern.exec(content)) !== null) {+ if (!isValidDate(match[1])) continue;const afterIdx = match.index + match[0].length;const nextHeader = content.indexOf('\n### ', afterIdx);const nextSection = content.indexOf('\n## ', afterIdx);diff --git a/test/frontmatter-missing-source-dir-7889.test.ts b/test/frontmatter-missing-source-dir-7889.test.tsnew file mode 100644index 0000000000..8031998b86--- /dev/null+++ b/test/frontmatter-missing-source-dir-7889.test.ts@@ -0,0 +1,59 @@+/**+ * #7889: a registered source whose local_path does not exist was reported `scanned` with zero files, so both frontmatter+ * doctor checks called it clean. It is now `missing`: the audit is not ok, both checks warn with the path and the+ * restore / set-path step, and neither blames a timeout. An existing empty directory stays clean.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { scanBrainSources } from '../src/core/brain-writer.ts';+import { frontmatterEntry } from '../src/commands/doctor/checks/content-quality.ts';+import type { Check } from '../src/commands/doctor.ts';++let engine: PGLiteEngine;+let root: string;+beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gbrain-7889-'));+ mkdirSync(join(root, 'empty'));+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(root, { recursive: true, force: true }); });++const runChecks = async () => await frontmatterEntry.run({ engine, args: [], progress: { heartbeat() {} } } as never) as Check[];++test('an existing empty directory is a clean scan', async () => {+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('source-empty','source-empty',$1)", [join(root, 'empty')]);+ const report = await scanBrainSources(engine);+ expect(report).toMatchObject({ ok: true, partial: false });+ expect(report.missing_sources).toBeUndefined();+ expect((await runChecks()).map(c => [c.name, c.status])).toEqual([['frontmatter_integrity', 'ok'], ['frontmatter_repairable', 'ok']]);+});++// Value: protects=a registered source with a missing directory is never reported frontmatter-clean (#7889);+// fails_when=scanBrainSources records a nonexistent local_path as status 'scanned' or the checks fold it into the timeout story;+// why_new=the missing-path scanner test only asserted zero counts; seam=scanBrainSources + frontmatterEntry.run on PGLite;+// no_claim=the deadline/partial paths, covered by doctor-frontmatter-partial and brain-writer-partial-scan.+test('a registered source whose directory is missing is unverified in the audit and in both doctor checks', async () => {+ const absent = join(root, 'absent');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('source-ghost','source-ghost',$1)", [absent]);+ const report = await scanBrainSources(engine);+ expect(report).toMatchObject({ ok: false, partial: false, aborted_at_source: null, missing_sources: ['source-ghost'] });+ expect(report.per_source.find(s => s.source_id === 'source-ghost')).toMatchObject({ status: 'missing', files_scanned: 0 });+ expect(report.per_source.find(s => s.source_id === 'source-empty')).toMatchObject({ status: 'scanned' });++ const checks = await runChecks();+ for (const check of checks) {+ expect(check.status).toBe('warn');+ expect(check.message).toContain(absent);+ expect(check.message).toContain('missing');+ expect(check.message).toContain('gbrain sources set-path');+ expect(check.message).not.toContain('timeout');+ expect(check.message).not.toContain('GBRAIN_DOCTOR_FM_TIMEOUT_MS');+ expect(check.fix_unavailable_reason).toBe('operator_judgement');+ }+ expect(checks.find(c => c.name === 'frontmatter_integrity')!.details).toMatchObject({ missing_sources: ['source-ghost'], partial: false, exact: false });+});diff --git a/test/managed-sync-images-5493.test.ts b/test/managed-sync-images-5493.test.tsindex 68ef0b4bb5..24a552fc95 100644--- a/test/managed-sync-images-5493.test.ts+++ b/test/managed-sync-images-5493.test.ts@@ -218,4 +218,32 @@ describe('managed sync imports images when multimodal embedding is on (#5493 helexpect(await heldPaths(engine, sourceId)).toEqual([]);}}), 240_000);+ // Value: protects=managed sync gives an image the importer's punctuation-preserving identity, so it imports, renames and+ // stays distinct from a look-alike name (#7107); fails_when=resolveSlugForPath folds image paths like Markdown and the+ // prepared slug disagrees with the requested one; why_new=the cases above use plain names; seam=performManagedSync;+ // no_claim=Markdown and code slugs, which keep their folding.+ test('an image name with punctuation keeps the importer identity through import and rename (#7107)', async () =>+ withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, root, head } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/Photo+A.png': PNG,+ 'notes/PhotoA.png': Buffer.concat([PNG, Buffer.from([1])]), 'notes/Legacy+Photo.png': Buffer.concat([PNG, Buffer.from([2])]) });+ const first = await performManagedSync(engine, { sourceId, noPull: true });+ expect(first.status).toBe('first_sync');+ expect(first.failedFiles ?? 0).toBe(0);+ expect(first.added).toBe(4);+ expect(await lastCommit(engine, sourceId)).toBe(head);+ expect(await imagePage(engine, sourceId, 'notes/photo+a.png')).toMatchObject({ source_path: 'notes/Photo+A.png', has_vector: true });+ expect(await imagePage(engine, sourceId, 'notes/photoa.png')).toMatchObject({ source_path: 'notes/PhotoA.png', has_vector: true });++ git(root, 'mv', 'notes/Legacy+Photo.png', 'notes/Moved+Photo.png');+ const next = commit(root, 'rename image');+ const renamed = await performManagedSync(engine, { sourceId, noPull: true });+ expect(renamed.status).toBe('synced');+ expect(renamed.renamed).toBe(1);+ expect(await lastCommit(engine, sourceId)).toBe(next);+ expect(await imagePage(engine, sourceId, 'notes/legacy+photo.png')).toBeNull();+ expect(await imagePage(engine, sourceId, 'notes/moved+photo.png')).toMatchObject({ source_path: 'notes/Moved+Photo.png' });+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('up_to_date');+ }+ }), 240_000);});diff --git a/test/sources-list-archived-7701.test.ts b/test/sources-list-archived-7701.test.tsnew file mode 100644index 0000000000..9216816f83--- /dev/null+++ b/test/sources-list-archived-7701.test.ts@@ -0,0 +1,35 @@+/**+ * #7701: `gbrain sources list` loads archived (soft-deleted) sources but dropped the flag when it built each entry, so the+ * table never printed its archived marker and `--json` had no `archived` field: an archived source read as live.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });++async function listOutput(args: string[]): Promise<string> {+ const captured: string[] = [];+ const origLog = console.log;+ console.log = (...parts: unknown[]) => { captured.push(parts.map(String).join(' ')); };+ try { await runSources(engine, ['list', ...args]); } finally { console.log = origLog; }+ return captured.join('\n');+}++// Value: protects=an archived source is marked archived in `sources list` (table and --json) and a live one is not (#7701);+// fails_when=runList builds SourceListEntry without the row's archived flag; why_new=no test listed an archived source;+// seam=runSources(['list']) on PGLite; no_claim=the MCP sources_list op.+test('sources list marks an archived source in the table and in --json', async () => {+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('source-a','source-a',NULL,'{}'), ('source-b','source-b',NULL,'{}')");+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='source-a'");++ const table = (await listOutput([])).split('\n');+ expect(table.find(line => line.includes('source-a'))).toContain('⚠ archived');+ expect(table.find(line => line.includes('source-b'))).not.toContain('archived');++ const { sources } = JSON.parse(await listOutput(['--json'])) as { sources: Array<{ id: string; archived: boolean }> };+ expect(sources.find(s => s.id === 'source-a')?.archived).toBe(true);+ expect(sources.find(s => s.id === 'source-b')?.archived).toBe(false);+});diff --git a/test/sync-managed-dry-run-7087.test.ts b/test/sync-managed-dry-run-7087.test.tsnew file mode 100644index 0000000000..f16919ec30--- /dev/null+++ b/test/sync-managed-dry-run-7087.test.ts@@ -0,0 +1,83 @@+/**+ * #7087: a managed `gbrain sync --dry-run` returned the cursor's committed counts (zero before a run) and printed+ * nothing, so the preview said nothing would change while files differed. Its counts are now the changes the run+ * would publish (an idle preview after a run used to repeat that run's counts), and the CLI prints them.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { printSyncResult } from '../src/commands/sync/report.ts';+import type { SyncResult } from '../src/commands/sync.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-7087-'));+let engine: PGLiteEngine;+function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function commit(root: string, message: string): void {+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+}+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;+function printed(result: SyncResult): string {+ let out = '';+ printSyncResult(result, { write: (chunk: string) => { out += chunk; return true; } } as unknown as NodeJS.WriteStream);+ return out;+}++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++// Value: protects=a managed sync dry run previews the adds, edits, deletes and renames a real run would publish (#7087);+// fails_when=managedDryRun reports the cursor's committed counts (zero) or the CLI prints nothing for a managed dry run;+// why_new=the dry-run tests only checked would_hold and would_normalize; seam=performManagedSync({ dryRun }) + printSyncResult;+// no_claim=per-path listing (counts only); a --full dry run counts every existing file under modify (the full run re-reads+// each); the classic unmanaged dry run, which already lists paths.+test('a managed dry run counts what the run would publish and writes nothing', async () =>+ withEnv({ GBRAIN_HOME: home }, async () => {+ const sourceId = `d${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ for (const name of ['keep', 'edit', 'gone', 'old']) writeFileSync(join(root, 'notes', `${name}.md`), page(name, `The ${name} page body.`));+ commit(root, 'initial');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId, noPull: true, noEmbed: true, noExtract: true };++ const first = await performManagedSync(engine, { ...opts, dryRun: true });+ expect(first).toMatchObject({ status: 'dry_run', added: 4, modified: 0, deleted: 0, renamed: 0 });+ expect(printed(first)).toContain('would add 4, modify 0, soft-delete 0, rename 0');+ expect((await performManagedSync(engine, opts)).status).toBe('first_sync');++ writeFileSync(join(root, 'notes', 'edit.md'), page('edit', 'The edit page body, changed.'));+ writeFileSync(join(root, 'notes', 'new.md'), page('new', 'A new page.'));+ git(root, 'rm', '-q', 'notes/gone.md');+ git(root, 'mv', 'notes/old.md', 'notes/moved.md');+ commit(root, 'changes');+ const preview = await performManagedSync(engine, { ...opts, dryRun: true });+ expect(preview).toMatchObject({ status: 'dry_run', added: 1, modified: 1, deleted: 1, renamed: 1 });+ expect(printed(preview)).toContain('would add 1, modify 1, soft-delete 1, rename 1');+ const [live] = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);+ expect(live!.n).toBe(4);++ const synced = await performManagedSync(engine, opts);+ expect(synced).toMatchObject({ status: 'synced', added: 1, modified: 1, deleted: 1, renamed: 1 });+ const idle = await performManagedSync(engine, { ...opts, dryRun: true });+ expect(idle).toMatchObject({ status: 'dry_run', added: 0, modified: 0, deleted: 0, renamed: 0 });+ expect(printed(idle)).toContain('(no syncable changes)');+ }), 120_000);diff --git a/test/sync-write-through-off-7084.test.ts b/test/sync-write-through-off-7084.test.tsnew file mode 100644index 0000000000..47b157ddc6--- /dev/null+++ b/test/sync-write-through-off-7084.test.ts@@ -0,0 +1,127 @@+/**+ * #7084 / #8118: with `sync.write_through` off, managed sync keeps its canonical correction of a file (the frontmatter and+ * tags the page keeps when an upstream edit drops them) in the database and never rewrites the checkout, the same as a+ * read-only mirror (#5409). With it on, the correction is still written back. #8118's shape: the `default` source has no+ * local_path and falls back to `sync.repo_path`, the checkout of a read-only mirror source.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-7084-'));+const TYPED = '---\ntype: note\ntitle: Page\ntags: [alpha]\n---\n# Page\n\nBody.\n';+const BARE = '# Page\n\nBody, edited upstream.\n';+const LATER = '# Page\n\nBody, edited upstream again.\n';+let engine: PGLiteEngine;++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function commitPage(root: string, body: string, message: string): void {+ writeFileSync(join(root, 'notes', 'page.md'), body);+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+}+async function claimedSource(): Promise<{ sourceId: string; root: string }> {+ const sourceId = `w${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ commitPage(root, TYPED, 'typed page');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, root };+}+const sync = (sourceId: string) => performManagedSync(engine, { sourceId, noPull: true, noEmbed: true, noExtract: true });+async function storedPage(sourceId: string) {+ const [row] = await engine.executeRaw<{ title: string; compiled_truth: string; tags: string[] }>(+ `SELECT p.title, p.compiled_truth, ARRAY(SELECT t.tag FROM tags t WHERE t.page_id=p.id ORDER BY t.tag) AS tags+ FROM pages p WHERE p.source_id=$1 AND p.slug='notes/page' AND p.deleted_at IS NULL`, [sourceId]);+ return row;+}++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++// Value: protects=sync.write_through=false keeps managed sync's canonical correction out of the checkout (#7084);+// fails_when=prepareSyncMutation attaches the canonical file write without reading sync.write_through;+// why_new=the existing write-back tests run with write_through on and the mirror tests set mirror_read_only;+// seam=performManagedSync on a claimed PGLite source; no_claim=Postgres engine, legacy (unmanaged) sync.+test('write_through off: an upstream edit that drops frontmatter syncs without rewriting the checkout; a later edit syncs too', async () =>+ withEnv({ GBRAIN_HOME: home }, async () => {+ const { sourceId, root } = await claimedSource();+ expect((await sync(sourceId)).status).toBe('first_sync');+ await engine.setConfig('sync.write_through', 'false');+ try {+ commitPage(root, BARE, 'drop frontmatter');+ expect((await sync(sourceId)).status).toBe('synced');+ expect(readFileSync(join(root, 'notes', 'page.md'), 'utf8')).toBe(BARE);+ expect(git(root, 'status', '--porcelain')).toBe('');+ expect(await storedPage(sourceId)).toMatchObject({ title: 'Page', tags: ['alpha'] });+ expect((await storedPage(sourceId)).compiled_truth).toContain('edited upstream.');++ commitPage(root, LATER, 'edit again');+ const next = await sync(sourceId);+ expect(next.status).toBe('synced');+ expect(next.held_count ?? 0).toBe(0);+ expect((await storedPage(sourceId)).compiled_truth).toContain('edited upstream again.');+ expect(git(root, 'status', '--porcelain')).toBe('');+ } finally {+ await engine.setConfig('sync.write_through', 'true');+ }+ }), 120_000);++test('write_through on: the same upstream edit still gets its canonical correction written back', async () =>+ withEnv({ GBRAIN_HOME: home }, async () => {+ const { sourceId, root } = await claimedSource();+ expect((await sync(sourceId)).status).toBe('first_sync');+ commitPage(root, BARE, 'drop frontmatter');+ expect((await sync(sourceId)).status).toBe('synced');+ const file = readFileSync(join(root, 'notes', 'page.md'), 'utf8');+ expect(file).toContain('title: Page');+ expect(file).toContain('alpha');+ expect(git(root, 'status', '--porcelain')).toBe('M notes/page.md');+ }), 120_000);++// Value: protects=a read-only mirror's checkout stays clean when the default source re-syncs it through sync.repo_path (#8118);+// fails_when=the default source's managed sync writes its canonical correction into the shared checkout with write_through off;+// why_new=the mirror tests only sync the mirror source itself; seam=performManagedSync of 'default' over a mirror's checkout;+// no_claim=write_through on, where a non-mirror source sharing a mirror's tree is still a doctor default_source_local_path warning.+test('#8118: the default source falling back to a read-only mirror checkout never rewrites it with write_through off', async () =>+ withEnv({ GBRAIN_HOME: home }, async () => {+ const root = join(home, 'shared-checkout');+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ commitPage(root, TYPED, 'typed page');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ await claimWorktree(engine, 'default', root);+ await engine.executeRaw("UPDATE sources SET local_path=NULL, config=config||'{\"federated\":true}'::jsonb WHERE id='default'");+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('mirror-a','mirror-a',$1,'{\"mirror_read_only\":true}')", [root]);+ await engine.setConfig('sync.repo_path', root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect((await sync('default')).status).toBe('first_sync');+ await engine.setConfig('sync.write_through', 'false');+ try {+ commitPage(root, BARE, 'drop frontmatter');+ expect((await sync('default')).status).toBe('synced');+ expect(readFileSync(join(root, 'notes', 'page.md'), 'utf8')).toBe(BARE);+ expect(git(root, 'status', '--porcelain')).toBe('');+ } finally {+ await engine.setConfig('sync.write_through', 'true');+ }+ }), 120_000);diff --git a/test/timeline-impossible-date-8049.test.ts b/test/timeline-impossible-date-8049.test.tsnew file mode 100644index 0000000000..c8fde2d323--- /dev/null+++ b/test/timeline-impossible-date-8049.test.ts@@ -0,0 +1,65 @@+/**+ * #8049: a timeline bullet or heading whose date has the YYYY-MM-DD shape but is not a calendar date (`2026-02-30`,+ * month 13) used to reach `r.date::date` in the canonical timeline insert, so the page's publication threw+ * `date/time field value out of range` (a managed sync blocked, a file-drift preview aborted its batch). The+ * extractor now skips such dates, as parseTimelineEntries already did; the text stays in the page body.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { extractTimelineFromContent } from '../src/core/timeline-extract.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-8049-'));+let engine: PGLiteEngine;+function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++test('the extractor skips bullet and heading dates that are not calendar dates and keeps real ones', () => {+ const body = ['- **2026-02-30** | Source — impossible day', '- **2026-13-01** | impossible month', '### 2025-02-29 — not a leap year',+ '- **2024-02-29** | Source — a real leap day', '### 2026-01-05 — Kickoff'].join('\n');+ expect(extractTimelineFromContent(body, 'notes/a').map(e => e.date)).toEqual(['2024-02-29', '2026-01-05']);+});++// Value: protects=one page with an impossible timeline date neither blocks a managed sync nor fails its own publication (#8049);+// fails_when=extractTimelineFromContent hands a shape-valid, calendar-invalid date to the timeline_entries ::date cast;+// why_new=no test fed an impossible date through the canonical projection insert; seam=performManagedSync on PGLite;+// no_claim=engine-level add_timeline_entry callers that pass their own date.+test('a managed sync imports a page whose timeline holds an impossible date, and the page beside it', async () =>+ withEnv({ GBRAIN_HOME: home }, async () => {+ const sourceId = `t${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, 'notes', 'a.md'), '---\ntype: note\ntitle: A\n---\nBody.\n\n## Timeline\n\n- **2026-02-30** | Source — impossible day\n- **2026-01-05** | Source — kickoff\n');+ writeFileSync(join(root, 'notes', 'b.md'), '---\ntype: note\ntitle: B\n---\nOther page.\n');+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'pages');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');++ const result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true, noExtract: true });+ expect(result.failedFiles ?? 0).toBe(0);+ expect(result).toMatchObject({ status: 'first_sync', added: 2 });+ const rows = await engine.executeRaw<{ slug: string; date: string; timeline: string }>(+ `SELECT p.slug, te.date::text AS date, p.timeline FROM pages p JOIN timeline_entries te ON te.page_id=p.id WHERE p.source_id=$1 ORDER BY te.date`, [sourceId]);+ expect(rows.map(r => [r.slug, r.date])).toEqual([['notes/a', '2026-01-05']]);+ expect(rows[0]!.timeline).toContain('2026-02-30');+ }), 120_000);