Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

line grammar: helpers keep extract/config/doctor within size ratchets; guide documents guards, toggles and grammar_diagnostics

garrytan3d5ea85d0b73
diff --git a/docs/guides/line-grammar.md b/docs/guides/line-grammar.md
index 36420bb884..047c21e8c5 100644
--- a/docs/guides/line-grammar.md
+++ b/docs/guides/line-grammar.md
@@ -22,7 +22,7 @@ states that link's type:
```markdown
- works_at [[companies/acme-example]] (since 2024)
-- "board member" [[companies/widget-co]] @effective[2022,)
+- advises @effective[2022,) [[companies/widget-co]]
```
The stated type wins over inference for the link on that line, on every
@@ -30,11 +30,58 @@ extraction path (local writes, sync, `gbrain extract`, the serve sweep). The
page is the subject. A line with words after the link is a sentence and keeps
the inferred type. Types must be verbs the active schema pack declares, the
same rule `add_link` follows; set `line_grammar.allow_undeclared_types true`
-to accept any snake_case verb. The full convention for agents is
+to accept any snake_case verb, or declare a custom verb in the pack first:
+
+```yaml
+link_types:
+ - name: board_member
+```
+
+```markdown
+- board_member [[companies/widget-co]]
+```
+
+The full convention for agents is
[`skills/conventions/line-grammar.md`](../../skills/conventions/line-grammar.md).
**Say to your agent:** *"Turn on typed relation lines, then record that alice-example works at acme-example since 2024 as a typed line on her page."*
+### Turning it on or off
+
+`gbrain config set line_grammar.enabled true|false` (and `config unset`)
+saves the setting and the time it changed together. Every page whose links
+were extracted before that time re-extracts once, with zero model calls:
+managed link extraction (the dream cycle, managed sync, a running
+`gbrain serve`) finishes it in the background, and `gbrain extract --stale`
+finishes it now. The command prints how many pages are queued;
+`gbrain doctor --json` reports `links_extraction_lag` 0 when they are done.
+Turning the grammar off therefore restores inferred types on every page.
+Setting the same effective value again changes nothing. A gbrain process
+started before the change keeps the old setting until it restarts.
+
+## Lines the grammar does not read
+
+These stay page text and are never read as fact lines:
+
+| Line | Why |
+|---|---|
+| `- [Time] - [Event]`, `- [Name]: [Role]` | another bare `[Slot]` on the line: an unfilled template |
+| `- [Date] — Kickoff`, `- [Day] \| Morning` | the claim starts with a separator: a template or table row |
+| `- [Item] TBD`, `- [Value] <fill in>` | the claim is only a placeholder |
+| `- [noun] a thing`, `- [informal] gonna` | a dictionary usage label, not a category |
+| `- [ ] task`, `- [00:00:11] said`, `- [2024-01-01] dated`, `- [^1] note`, `- [TODO] x` | task boxes, timecodes, dates, citations and markers |
+
+Links, wikilinks, escaped brackets and inline code inside a claim are not
+slots: `- [fact] see [the guide](https://example.invalid)` is a fact line.
+Each line is read on its own, so editing one line never changes how another
+is read. On a page that also uses the grammar, a refused line gets a finding
+that says why and how to write a real fact line; template and dictionary pages
+without grammar lines stay quiet.
+
+A relation type wrapped in formatting or followed by a colon
+(`- **works_at** [[x]]`, `` - `works_at` [[x]] ``, `- works_at: [[x]]`) is not
+read; the finding gives the bare form.
+
## Fact lines
`- [category] claim #tag (context)` lines are read, linted and counted:
@@ -65,15 +112,24 @@ Ranges are stored only while the line grammar is on.
"relations": 1, "relations_state": "stored",
"facts": 1, "facts_state": "page_text_only",
"findings": [{ "severity": "warning", "validator": "line-grammar", "line": 5,
- "reason": "prose_tail", "text": "- works_at [[companies/acme-example]] since 2024",
- "message": "Text after the link makes this a sentence, so \"works_at\" is not applied. Put extra words in one trailing (context)." }],
- "total": 1, "details_truncated": false
+ "code": "type_punctuation", "reason": "type_punctuation", "text": "- **works_at** [[companies/acme-example]]",
+ "message": "Page saved; line 5 was not read as written. \"works_at\" is wrapped in formatting or followed by a colon, ...",
+ "why": "A relation type is read only when written bare, without formatting or a colon.",
+ "canonical": "- works_at [[companies/acme-example]]",
+ "verify": { "mcp": { "tool": "get_page", "arguments": { "slug": "people/alice-example", "grammar_diagnostics": true } } } }],
+ "total": 1, "details_truncated": false, "pack": "gbrain-base"
}
```
`relations_state` is `pending_sweep` for a remote writer (links are reconciled
by the serve sweep), and `auto_link_disabled` when `auto_link` is off. Line
-numbers count from the start of the page body.
+numbers count from the start of the page body. At most five findings come back;
+`more` names the call that lists all of them: `get_page` with
+`grammar_diagnostics: true` (CLI: `gbrain get <slug> --grammar-diagnostics`),
+which reads the brain's settings and the source's schema pack. `gbrain lint`
+checks files syntax-only. If the settings or pack cannot be read, the block is
+`{ "state": "diagnostics_failed", ... }` with a `gbrain doctor` step, never an
+ungated reading. Undeclared types get a "did you mean" only for a likely typo.
## Wanted pages
@@ -121,3 +177,7 @@ Turn off again: `gbrain config set put_page.similar_pages false`.
frontmatter keys, fact categories and relation types the pages use. A field on
every sampled page is listed as required, one on at least a quarter of them as
optional.
+
+## Changelog
+
+- Q2 parser gaps: template, separator, placeholder and usage-label lines are no longer read as fact lines; decorated relation types are diagnosed; findings follow the agent operator contract and `get_page grammar_diagnostics` lists all of them; turning the grammar on or off re-extracts every page so the graph follows the setting.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 28fc737b55..9888939734 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilo
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2204 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +22 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)
-src/commands/extract.ts 2558 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan
+src/commands/extract.ts 2567 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)
src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)
@@ -39,7 +39,7 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in
src/core/config.ts 1891 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
+src/core/ops/pages.ts 664 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts)
src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)
src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)
src/commands/doctor/checks/extraction-sync.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 65823d760b..f068738a75 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -378,6 +378,23 @@ async function changeLineGrammarConfig(engine: BrainEngine, mutate: (tx: BrainEn
for (const line of (await describeLineGrammarChange(engine, change)).lines) console.error(`[config] ${line}`);
}
+/**
+ * Delete config rows; line-grammar keys commit with the extraction generation in one transaction.
+ * `_internal.*` keys are gbrain's own state: a single unset refuses one, a pattern unset skips them.
+ */
+async function unsetConfigKeys(engine: BrainEngine, keys: string[], opts: { single?: boolean } = {}): Promise<number> {
+ const { isInternalConfigKey, isLineGrammarKey } = await import('../core/line-grammar-config.ts');
+ if (opts.single && keys.some(isInternalConfigKey)) {
+ console.error(`[config] ${keys[0]} is internal state gbrain maintains itself; it cannot be unset.`);
+ process.exit(1);
+ }
+ let deleted = 0;
+ for (const k of keys.filter(k => !isLineGrammarKey(k) && !isInternalConfigKey(k))) deleted += Math.max(0, await engine.unsetConfig(k));
+ const grammarKeys = keys.filter(isLineGrammarKey);
+ if (grammarKeys.length) await changeLineGrammarConfig(engine, async tx => { for (const k of grammarKeys) deleted += await tx.unsetConfig(k); });
+ return deleted;
+}
+
async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value: string, force = false): Promise<void> {
const { isInternalConfigKey, isLineGrammarKey, invalidLineGrammarValue } = await import('../core/line-grammar-config.ts');
if (isInternalConfigKey(key)) {
@@ -694,8 +711,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.error('Usage: gbrain config unset --pattern <prefix>');
process.exit(1);
}
- const { isInternalConfigKey, isLineGrammarKey } = await import('../core/line-grammar-config.ts');
- const keys = (await engine.listConfigKeys(prefix)).filter(k => !isInternalConfigKey(k));
+ const keys = (await engine.listConfigKeys(prefix)).filter(k => !k.startsWith('_internal.'));
// Dual-plane keys matching the prefix must ALSO leave the file mirror
// (codex re-review, this wave): a DB-only pattern delete would report
// success while the engine-free Stop hook keeps reading the mirror's
@@ -725,15 +741,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.log(`No keys match prefix "${prefix}".`);
return;
}
- let deleted = 0;
- const grammarKeys = keys.filter(isLineGrammarKey);
- for (const k of keys.filter(k => !isLineGrammarKey(k))) {
- const n = await engine.unsetConfig(k);
- if (n > 0) deleted += n;
- }
- if (grammarKeys.length) {
- await changeLineGrammarConfig(engine, async tx => { for (const k of grammarKeys) deleted += await tx.unsetConfig(k); });
- }
+ const deleted = await unsetConfigKeys(engine, keys);
console.log(`Unset ${deleted} key(s) matching "${prefix}":`);
for (const k of keys) console.log(` - ${k}`);
for (const k of fileSwept) {
@@ -849,14 +857,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
return;
}
- const { isInternalConfigKey, isLineGrammarKey } = await import('../core/line-grammar-config.ts');
- if (isInternalConfigKey(key)) {
- console.error(`[config] ${key} is internal state gbrain maintains itself; it cannot be unset.`);
- process.exit(1);
- }
- let n = 0;
- if (isLineGrammarKey(key)) await changeLineGrammarConfig(engine, async tx => { n = await tx.unsetConfig(key); });
- else n = await engine.unsetConfig(key);
+ const n = await unsetConfigKeys(engine, [key], { single: true });
if (n > 0) {
console.log(`Unset ${key}${key === 'auto_chronicle' ? AUTO_CHRONICLE_UNSET_NOTE : ''}`);
if (key === 'facts.default_visibility') await restampVisibilityPosture(null);
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index bfd2a2d4d7..ae39808a04 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -13,7 +13,7 @@ import { probeSourceGitState } from '../../../core/git-head.ts';
import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';
import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';
import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';
-import { effectiveLinkExtractorWatermark } from '../../../core/link-extraction-watermark.ts';
+import { effectiveLinkExtractorWatermark, smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';
import { previewMentionPass } from '../../../core/mentions/stale.ts';
import { isUndefinedColumnError } from '../../../core/utils.ts';
import {
@@ -120,9 +120,7 @@ export async function checkLinksExtractionLag(
// Vacuous-skip tiny brains unless explicitly source-scoped. Shared floor
// const so the sync nudge (D6/C4) skips on the exact same predicate.
if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) {
- // Too few pages to grade a percentage, but the exact backlog still tells an operator whether a re-extraction finished.
- const pending = await engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) }).catch(() => null);
- return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)${pending ? `; ${pending} page(s) pending link extraction (gbrain extract --stale finishes them)` : ''}` };
+ return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)${await smallBrainBacklogNote(engine)}` };
}
// #5761: a page left stale only by an unresolved attendee, and not edited
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 91ed374069..4bedd80d0a 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -50,7 +50,7 @@ import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetada
import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';
import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammar.ts';
import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';
-import { DerivedLinkSettingsChangedError } from '../core/derived-links.ts';
+import { replaceDerivedLinksUnlessSettingsChanged, settingsChangedSkipLine } from '../core/derived-links.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
@@ -1873,9 +1873,7 @@ async function extractLinksFromDB(
// links_extraction_lag doctor signal. Non-dry-run only.
const processedRefs: Array<{ slug: string; source_id: string }> = [];
- // One line-grammar settings snapshot for the run; publication refuses a page if the settings move meanwhile.
- const grammar = await readLineGrammarSettings(engine);
- const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
+ const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
let skippedSettingsChanged = 0;
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('extract.links_db', walkRefs.length);
@@ -1955,18 +1953,13 @@ async function extractLinksFromDB(
frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: source_id,
crossSourceAllowed: federatedSourceIds.has(source_id) || crossSource, resolve: c => resolveCandidateSources(c, slug, source_id,
allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];
- const written = await engine.replaceDerivedLinks({ slug, sourceId: source_id, expectedRevision: snapshot.revision,
+ const written = await replaceDerivedLinksUnlessSettingsChanged(engine, { slug, sourceId: source_id, expectedRevision: snapshot.revision,
sourceIncarnation: snapshot.sourceIncarnation }, batch, { includeFrontmatter, lineGrammar: grammar,
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },
expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) });
+ if (!written) { skippedSettingsChanged++; progress.tick(1); continue; }
created += written.created;
} catch (error) {
- if (error instanceof DerivedLinkSettingsChangedError) {
- // The line-grammar settings changed mid-run: this page stays stale and the next extraction derives it.
- skippedSettingsChanged++;
- progress.tick(1);
- continue;
- }
if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: batch.length, code: 'graph_write_failed' }) + '\n');
throw error;
}
@@ -1992,7 +1985,7 @@ async function extractLinksFromDB(
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${processed} pages (db source)`);
if (skippedAttendanceIncomplete) console.log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
- if (skippedSettingsChanged) console.log(`Skipped ${skippedSettingsChanged} page(s) because the line-grammar settings changed during this run; they stay stale. Run \`gbrain extract --stale\` to finish them.`);
+ if (skippedSettingsChanged) console.log(settingsChangedSkipLine(skippedSettingsChanged));
if (skippedMissingTarget > 0) {
console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2017,8 +2010,7 @@ async function extractLinksFromDB(
// #2589: the counters ride the return value so machine consumers (and the
// --json path, which has no summary event on this path) can see the drops —
// "counted, never silent" must hold beyond human-mode console lines.
- return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete,
- ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}) };
+ return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete, ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}) };
}
/**
@@ -2061,9 +2053,7 @@ export async function extractStaleFromDB(
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;
- // One line-grammar settings snapshot for the run: it fixes the watermark and how relation lines are read.
- const grammar = await readLineGrammarSettings(engine);
- const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
+ const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
const versionTs = linkExtractorWatermarkFor(grammar.generation);
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
@@ -2145,8 +2135,7 @@ export async function extractStaleFromDB(
// in a source other than the origin's or 'default' — default-deny by
// design (source isolation) unless the #3908 flag is on, but distinct
// from a genuinely missing target.
- let skippedCrossSource = 0;
- let skippedChanged = 0;
+ let skippedCrossSource = 0, skippedChanged = 0;
const wantedEnabled = await isWantedPagesEnabled(engine);
for (;;) {
@@ -2207,14 +2196,8 @@ export async function extractStaleFromDB(
const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };
const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;
- let written: { created: number; removed: number };
- try {
- written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);
- } catch (error) {
- // The line-grammar settings changed mid-run: the page stays stale (not stamped) and the next run derives it.
- if (error instanceof DerivedLinkSettingsChangedError) { skippedChanged++; continue; }
- throw error;
- }
+ const written = await replaceDerivedLinksUnlessSettingsChanged(engine, origin, linkRows, linkOpts);
+ if (!written) { skippedChanged++; continue; } // settings moved mid-run: not stamped, re-extracts next run
linksCreated += written.created;
await retractRemovedTimelineEntries(engine, page.slug, page.source_id, fullContent);
for (const entry of parseTimelineEntries(fullContent)) {
@@ -2271,7 +2254,7 @@ export async function extractStaleFromDB(
else log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
if (mentionLine) log(mentionLine);
if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
- if (skippedChanged) log(`Skipped ${skippedChanged} page(s) because the line-grammar settings changed during this run; they stay stale. Re-run \`gbrain extract --stale\` to finish them.`);
+ if (skippedChanged) log(settingsChangedSkipLine(skippedChanged));
if (skippedMissingTarget > 0) {
log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2286,8 +2269,7 @@ export async function extractStaleFromDB(
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),
- ...(skippedChanged ? { skipped_changed: skippedChanged } : {}), ...mentionJsonFields(mentions),
+ ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}), ...mentionJsonFields(mentions),
}) + '\n');
}
return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index d60edba567..480324a808 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -47,6 +47,17 @@ export class DerivedLinkSettingsChangedError extends DerivedLinkEndpointChangedE
constructor() { super('Line-grammar settings changed after these links were prepared'); this.name = 'DerivedLinkSettingsChangedError'; }
}
+/** replaceDerivedLinks, or null when the line-grammar settings moved since preparation (the page stays stale). */
+export async function replaceDerivedLinksUnlessSettingsChanged(engine: Pick<BrainEngine, 'replaceDerivedLinks'>,
+ ...args: Parameters<BrainEngine['replaceDerivedLinks']>): Promise<{ created: number; removed: number } | null> {
+ try { return await engine.replaceDerivedLinks(...args); }
+ catch (error) { if (error instanceof DerivedLinkSettingsChangedError) return null; throw error; }
+}
+
+/** The operator line for pages a settings change left stale mid-run. */
+export const settingsChangedSkipLine = (n: number) =>
+ `Skipped ${n} page(s) because the line-grammar settings changed during this run; they stay stale. Run \`gbrain extract --stale\` to finish them.`;
+
export async function applyAttendanceDelta(tx: Pick<BrainEngine, 'executeRaw' | 'addLinksBatch'>,
origin: { id: string; slug: string; source_id: string; type: string }, remove: string[], additions: LinkBatchInput[]) {
if (origin.type !== 'meeting' || remove.length > 512 || additions.length > 256
diff --git a/src/core/link-extraction-watermark.ts b/src/core/link-extraction-watermark.ts
index 3c1e9267ba..9812766e98 100644
--- a/src/core/link-extraction-watermark.ts
+++ b/src/core/link-extraction-watermark.ts
@@ -30,6 +30,12 @@ export function linkExtractorWatermarkFor(generation: string | null | undefined)
return laterInstant(LINK_EXTRACTOR_VERSION_TS, generation);
}
+/** Doctor's note for a brain too small to grade: the exact link-extraction backlog, or '' when there is none. */
+export async function smallBrainBacklogNote(engine: { getConfig(key: string): Promise<string | null>; countStalePagesForExtraction(o: { versionTs: string }): Promise<number> }): Promise<string> {
+ const pending = await engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) }).catch(() => 0);
+ return pending ? `; ${pending} page(s) pending link extraction (gbrain extract --stale finishes them)` : '';
+}
+
export async function effectiveLinkExtractorWatermark(engine: { getConfig(key: string): Promise<string | null> }): Promise<string> {
return linkExtractorWatermarkFor(await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY));
}
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index e18518270d..6de7a68dee 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -204,10 +204,8 @@ const get_page: Operation = {
// it would double every reader's payload for the round-trip minority.
const timelineEntries = includeTimelineEntries
? await ctx.engine.getTimeline(page.slug, await readPolicyOpts(ctx, { sourceId: page.source_id })) : undefined;
- // Read-only, over the same visibility-filtered body the reader gets (core/line-grammar-report.ts).
- const lineGrammar = (p.grammar_diagnostics as boolean) === true
- ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth })
- : undefined;
+ // Read-only, over the same visibility-filtered body the reader gets.
+ const lineGrammar = p.grammar_diagnostics === true ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth }) : undefined;
const projected = projectGetPage(visibleBody, {
revision: snapshot!.revision, tags, includeContent, contentOnly: (p.content_only as boolean) === true, resolved_slug, content_flag,
...(timelineEntries ? { timeline_entries: timelineEntries } : {}),