Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): typed line grammar — relation lines declare their link type; fact lines are read and reported

garrytan5be347a48607
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 911fcc92e3..55b2eefa39 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 2219 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)
src/commands/extract-conversation-facts.ts 2182 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)
-src/commands/extract.ts 2540 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
+src/commands/extract.ts 2545 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/jobs.ts 660 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)
src/commands/serve-http.ts 919 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)
src/core/ai/gateway.ts 4393 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)
@@ -31,12 +31,12 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle re
src/commands/bootstrap.ts 2142 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)
src/core/minions/worker.ts 1764 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
src/commands/sources.ts 2031 ratchet +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)
-src/core/link-extraction.ts 2180 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
+src/core/link-extraction.ts 2154 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)
src/core/embedding-migration.ts 1569 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
src/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
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1842 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); +4 P5: wanted_pages.enabled key row
+src/core/config.ts 1846 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); +4 P5: wanted_pages.enabled key row; +4 P5: line_grammar.enabled / allow_undeclared_types key rows
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)
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 6d0ee99773..4edff84e2e 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -48,6 +48,7 @@ import type { PageType } from '../core/types.ts';
import { parseMarkdown } from '../core/markdown.ts';
import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';
+import { lineGrammarOptions, statedRelationTypes } from '../core/line-grammar.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
@@ -494,7 +495,8 @@ async function loadSlugAliasTargets(engine: BrainEngine, sourceId: string, allSl
export async function extractLinksFromFile(
content: string, relPath: string, allSlugs: Set<string>,
opts?: { includeFrontmatter?: boolean; globalBasename?: boolean; pack?: LinkExtractionPack | null;
- pageTypes?: ReadonlyMap<string, string>; aliases?: ReadonlyMap<string, string> },
+ pageTypes?: ReadonlyMap<string, string>; aliases?: ReadonlyMap<string, string>;
+ lineGrammar?: { enabled?: boolean; allowUndeclaredTypes?: boolean } },
): Promise<ExtractedLink[]> {
const links: ExtractedLink[] = [];
// Renamed pages: `allSlugs` also holds their old slugs (see
@@ -519,6 +521,7 @@ export async function extractLinksFromFile(
// DB path, which goes through extractEntityRefs (which strips internally).
const scanContent = stripCodeBlocks(content);
const attendanceRanges = attendanceEvidenceRanges(content);
+ const statedType = statedRelationTypes(content, { ...opts?.lineGrammar, declaredVerbs: pack?.link_types.map(lt => lt.name) });
for (const { name, relTarget, index } of extractMarkdownLinks(scanContent, true)) {
const resolvedSlugs = resolveSlugAll(fileDir, relTarget, allSlugs, { globalBasename });
@@ -542,7 +545,9 @@ export async function extractLinksFromFile(
const targetType = opts?.pageTypes?.get(target) ?? parseMarkdown('', `${target}.md`, { activePack }).type;
const position = index ?? scanContent.indexOf(name);
const evidence = scanContent.slice(Math.max(0, position - 120), position + 240);
- let inferred = pack ? inferLinkTypeFromPack(pack, guessedPageType, evidence, packBudget, targetType) : null;
+ const stated = statedType(position);
+ let inferred = stated && !(stated === 'attended' && guessedPageType === 'meeting') ? stated
+ : pack ? inferLinkTypeFromPack(pack, guessedPageType, evidence, packBudget, targetType) : null;
if (inferred === 'attended' && guessedPageType === 'meeting' && !packOwnsAttendance) inferred = null;
const bareTarget = relTarget.endsWith('.md') ? relTarget.slice(0, -3) : relTarget;
const ambiguousAttendance = !inferred && guessedPageType === 'meeting' && targetType === 'person'
@@ -1884,7 +1889,7 @@ async function extractLinksFromDB(
// basename lookup; off by default for back-compat.
const extracted = await extractPageLinks(
slug, fullContent, page.frontmatter, page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, targetType: (targetSlug, targetSourceId) => {
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar: await lineGrammarOptions(engine), targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,
source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
@@ -2143,7 +2148,7 @@ export async function extractStaleFromDB(
const resolver = resolvers.get(page.source_id)!;
const extracted = await extractPageLinks(
page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, targetType: (targetSlug, targetSourceId) => {
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar: await lineGrammarOptions(engine), targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, page.slug,
page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 3229466bf9..bf5a4081ee 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -34,6 +34,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { loadActivePack } from '../core/schema-pack/load-active.ts';
import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';
import { safeCliToken, sanitizeTypeForDisplay, storedTypeMissesPack, type TypeUsagePack } from '../core/schema-pack/type-usage.ts';
+import { parseLineGrammar } from '../core/line-grammar.ts';
export interface LintIssue {
file: string;
@@ -127,6 +128,12 @@ export function lintContent(content: string, filePath: string, opts: LintContent
});
}
+ // Rule: line-grammar near-misses (a relation or fact line that will not be
+ // read as written). Read-only; the fix is in each message.
+ for (const d of parseLineGrammar(content).diagnostics) {
+ issues.push({ file: filePath, line: d.line, rule: 'line-grammar', message: `${d.message} (${d.reason})`, fixable: false });
+ }
+
// Rule: LLM preamble artifacts
for (const pattern of LLM_PREAMBLES) {
pattern.lastIndex = 0;
diff --git a/src/core/config.ts b/src/core/config.ts
index 81f12965c6..2c319fe677 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1573,6 +1573,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// when the target appears (src/core/wanted-links.ts). On by default; the
// off switch is `gbrain config set wanted_pages.enabled false`.
'wanted_pages.enabled',
+ // Line grammar (src/core/line-grammar.ts): typed relation lines on by default;
+ // undeclared relation types fall back to inference unless allowed.
+ 'line_grammar.enabled',
+ 'line_grammar.allow_undeclared_types',
// #5584: skillopt optimizer output cap (default 32000 thinking / 4096 otherwise).
'skillopt.reflect_max_tokens',
// #5585: skillopt strict model provenance (true|1|yes|on; other values count as on).
diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.ts
new file mode 100644
index 0000000000..c4421fdd7f
--- /dev/null
+++ b/src/core/line-grammar.ts
@@ -0,0 +1,341 @@
+/**
+ * Line grammar: typed facts and typed relations a human or an agent can type
+ * in any editor, read with zero LLM calls.
+ *
+ * - [preference] Prefers oat milk #coffee (since the almond allergy)
+ * - [event] @effective[2024-03,2024-09) Led the pricing rework
+ * - works_at [[companies/acme-example]] (since 2024)
+ * - "board member" @effective[2022,) [[companies/widget-co]]
+ *
+ * A fact line is a list item whose content starts with `[category]`; a
+ * relation line is a list item whose content is one relation type followed by
+ * exactly one link. Anything that does not match exactly stays ordinary text
+ * and keeps today's behavior (the link keeps its inferred type), so a
+ * sentence that happens to contain a link never invents a relation type.
+ *
+ * Guards keep transcripts, task lists and citations out: a category is one
+ * token that starts with a letter (so `[00:00:11]`, `[2024-01-01]`,
+ * `[Source: x]`, `[^1]` and `[ ]` never match), `[x]`/`[X]` task markers and a
+ * small stoplist are refused, and lines inside code, blockquotes, HTML
+ * comments, the Facts/Takes fences and machine-written sections (Timeline,
+ * See also, Related, Sources, ...) are never read.
+ *
+ * `@effective[start,end)` (alias `@valid`) is an inline validity range with
+ * ISO dates (`YYYY`, `YYYY-MM`, `YYYY-MM-DD`, UTC); `[`/`]` are inclusive and
+ * `(`/`)` exclusive, an empty side is open. Ranges normalize to a half-open
+ * `[from, until)` pair of dates. Natural-language and relative dates are
+ * refused and never peeled, so the text stays as written.
+ *
+ * Pure: no engine, no I/O. Offsets are UTF-16 code units into the input.
+ */
+import { stripCodeBlocks } from './markdown-code.ts';
+import { inSuppressedRange, rolePriorSuppressedRanges } from './machine-sections.ts';
+
+export type GrammarReason =
+ | 'prose_tail' | 'two_links' | 'stoplist_type' | 'undeclared_type'
+ | 'unknown_qualifier' | 'invalid_range';
+
+export interface EffectiveRange {
+ /** Inclusive start date `YYYY-MM-DD`, or null when open. */
+ from: string | null;
+ /** Exclusive end date `YYYY-MM-DD`, or null when open. */
+ until: string | null;
+ /** The qualifier exactly as written. */
+ raw: string;
+}
+
+export interface GrammarFact {
+ line: number;
+ category: string;
+ kind: 'event' | 'preference' | 'commitment' | 'belief' | 'fact' | 'idea';
+ claim: string;
+ tags: string[];
+ context: string | null;
+ effective: EffectiveRange | null;
+}
+
+export interface GrammarRelation {
+ line: number;
+ /** Offsets of the whole line in the input. */
+ start: number;
+ end: number;
+ type: string;
+ context: string | null;
+ effective: EffectiveRange | null;
+}
+
+export interface GrammarDiagnostic {
+ line: number;
+ reason: GrammarReason;
+ text: string;
+ message: string;
+}
+
+export interface LineGrammarResult {
+ facts: GrammarFact[];
+ relations: GrammarRelation[];
+ diagnostics: GrammarDiagnostic[];
+}
+
+const FACT_KINDS = new Set(['event', 'preference', 'commitment', 'belief', 'fact', 'idea']);
+const CATEGORY_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
+const TYPE_TOKEN_RE = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
+const CATEGORY_STOPLIST = new Set(['x', 'todo', 'done', 'wip']);
+const TYPE_STOPLIST = new Set(['see', 'also', 'cf', 'via', 'and', 'or', 'with', 'from', 're', 'by', 'to', 'per', 'and/or']);
+const LIST_ITEM_RE = /^([ \t]*)(?:[-*+]|\d{1,9}[.)])[ \t]+(.*)$/;
+const QUALIFIER_RE = /^@([A-Za-z][A-Za-z0-9_]*)([[(])([^\][()]*),([^\][()]*)([\])])(?=\s|$)/;
+const QUALIFIER_LIKE_RE = /^@([A-Za-z][A-Za-z0-9_]*)[[(:]/;
+const LINK_RE = /\[\[[^\]\n]+\]\]|\[[^\][\n]+\]\([^)\n]+\)/g;
+const LINE_TEXT_MAX = 160;
+
+/** Normalize a written relation type: `worksAt`, `works-at`, `"works at"` -> `works_at`. */
+export function normalizeRelationType(raw: string): string {
+ return raw.trim().replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().replace(/[\s-]+/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
+}
+
+function validDate(y: number, m: number, d: number): boolean {
+ const date = new Date(Date.UTC(y, m - 1, d));
+ return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
+}
+
+/** A date token at its stated precision: the period start plus the start of the next period. */
+function datePeriod(token: string): { start: string; next: string } | null {
+ const m = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/.exec(token.trim());
+ if (!m) return null;
+ const y = Number(m[1]); const mo = m[2] ? Number(m[2]) : null; const d = m[3] ? Number(m[3]) : null;
+ if (mo !== null && (mo < 1 || mo > 12)) return null;
+ if (d !== null && !validDate(y, mo!, d)) return null;
+ const iso = (date: Date) => date.toISOString().slice(0, 10);
+ if (d !== null) return { start: iso(new Date(Date.UTC(y, mo! - 1, d))), next: iso(new Date(Date.UTC(y, mo! - 1, d + 1))) };
+ if (mo !== null) return { start: iso(new Date(Date.UTC(y, mo - 1, 1))), next: iso(new Date(Date.UTC(y, mo, 1))) };
+ return { start: iso(new Date(Date.UTC(y, 0, 1))), next: iso(new Date(Date.UTC(y + 1, 0, 1))) };
+}
+
+type QualifierParse =
+ | { kind: 'none' }
+ | { kind: 'ok'; range: EffectiveRange; length: number }
+ | { kind: 'refused'; reason: 'unknown_qualifier' | 'invalid_range'; message: string };
+
+/**
+ * Parse an `@effective[...]` qualifier at the start of `text`. A qualifier-like
+ * token that is not an accepted range is refused (and never peeled); plain
+ * `@handles` and emails are not qualifiers at all.
+ */
+export function parseEffectiveQualifier(text: string): QualifierParse {
+ const m = QUALIFIER_RE.exec(text);
+ if (!m) {
+ const like = QUALIFIER_LIKE_RE.exec(text);
+ if (!like) return { kind: 'none' };
+ const known = like[1] === 'effective' || like[1] === 'valid';
+ return { kind: 'refused', reason: known ? 'invalid_range' : 'unknown_qualifier',
+ message: known
+ ? 'A validity range takes ISO dates: @effective[2024-01-01,2025-06-01) — [ ] inclusive, ( ) exclusive, an empty side is open.'
+ : `Only @effective[start,end) (alias @valid) is read; @${like[1]} stays plain text.` };
+ }
+ const [whole, kind, open, rawStart, rawEnd, close] = m;
+ if (kind !== 'effective' && kind !== 'valid') {
+ return { kind: 'refused', reason: 'unknown_qualifier', message: `Only @effective[start,end) (alias @valid) is read; @${kind} stays plain text.` };
+ }
+ const startTok = rawStart.trim(); const endTok = rawEnd.trim();
+ const start = startTok ? datePeriod(startTok) : null;
+ const end = endTok ? datePeriod(endTok) : null;
+ if ((startTok && !start) || (endTok && !end)) {
+ return { kind: 'refused', reason: 'invalid_range', message: 'Dates must be YYYY, YYYY-MM or YYYY-MM-DD (calendar-valid, UTC); natural-language and relative dates are not read.' };
+ }
+ const from = start ? (open === '[' ? start.start : start.next) : null;
+ const until = end ? (close === ']' ? end.next : end.start) : null;
+ if (from && until && from >= until) {
+ return { kind: 'refused', reason: 'invalid_range', message: 'The range ends before it starts; write @effective[start,end) with start before end.' };
+ }
+ return { kind: 'ok', range: { from, until, raw: whole }, length: whole.length };
+}
+
+/** Index of the `(` that opens a balanced group closing exactly at the end of `text`, or -1. */
+function trailingGroupStart(text: string): number {
+ if (!text.endsWith(')')) return -1;
+ let depth = 0;
+ for (let i = text.length - 1; i >= 0; i--) {
+ if (text[i] === ')') depth++;
+ else if (text[i] === '(') { depth--; if (depth === 0) return i; }
+ }
+ return -1;
+}
+
+/** A leading YAML frontmatter block (`---` ... `---` with at least one `key:` line), as a range. */
+function frontmatterRange(text: string): [number, number] | null {
+ const m = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
+ return m && /^[A-Za-z_][\w-]*:/m.test(m[1]) ? [0, m[0].length] : null;
+}
+
+function excludedRanges(text: string): Array<[number, number]> {
+ const ranges: Array<[number, number]> = [];
+ const frontmatter = frontmatterRange(text);
+ if (frontmatter) ranges.push(frontmatter);
+ const masked = stripCodeBlocks(text, { onHtmlComment: (start, end) => ranges.push([start, end]) });
+ ranges.push(...rolePriorSuppressedRanges(masked));
+ return ranges;
+}
+
+function lineText(line: string): string {
+ const t = line.trim();
+ return t.length > LINE_TEXT_MAX ? `${t.slice(0, LINE_TEXT_MAX - 1)}…` : t;
+}
+
+/**
+ * Parse every grammar line in a page body. `declaredTypes`, when given (the
+ * active schema pack's link verbs), gates relation types: an undeclared type
+ * falls back to inference and is reported with the nearest declared verb.
+ */
+export function parseLineGrammar(text: string, opts: { declaredTypes?: ReadonlySet<string> | null } = {}): LineGrammarResult {
+ const result: LineGrammarResult = { facts: [], relations: [], diagnostics: [] };
+ if (!text.includes('- ') && !text.includes('* ') && !text.includes('+ ') && !/\d[.)] /.test(text)) return result;
+ const masked = stripCodeBlocks(text, { onHtmlComment: () => {} });
+ const excluded = excludedRanges(text);
+ let offset = 0;
+ let lineNo = 0;
+ for (const rawLine of text.split('\n')) {
+ lineNo++;
+ const start = offset;
+ offset += rawLine.length + 1;
+ const line = rawLine.replace(/\r$/, '');
+ const visible = masked.slice(start, start + line.length);
+ if (!visible.trim() || /^\s*>/.test(visible) || inSuppressedRange(excluded, start)) continue;
+ const item = LIST_ITEM_RE.exec(visible);
+ if (!item) continue;
+ // Masking keeps offsets, so the item's content sits at the same place in
+ // the original line; structure is read from the masked text (links inside
+ // code are not links), the fact text from the original.
+ const visibleContent = item[2].trim();
+ const content = line.slice(line.length - item[2].length).trim();
+ if (!visibleContent || visibleContent.startsWith('\\')) continue;
+ const note = (reason: GrammarReason, message: string) => result.diagnostics.push({ line: lineNo, reason, text: lineText(line), message });
+ if (visibleContent.startsWith('[')) {
+ const fact = parseFactContent(content, note);
+ if (fact) result.facts.push({ line: lineNo, ...fact });
+ continue;
+ }
+ const relation = parseRelationContent(visibleContent, opts.declaredTypes ?? null, note);
+ if (relation) result.relations.push({ line: lineNo, start, end: start + line.length, ...relation });
+ }
+ return result;
+}
+
+function parseFactContent(content: string, note: (reason: GrammarReason, message: string) => void): Omit<GrammarFact, 'line'> | null {
+ const m = /^\[([^\][]*)\][ \t]+(\S.*)$/.exec(content);
+ if (!m) return null;
+ const category = m[1].trim();
+ if (!CATEGORY_RE.test(category)) return null;
+ if (CATEGORY_STOPLIST.has(category.toLowerCase())) return null;
+ let rest = m[2].trim();
+ let effective: EffectiveRange | null = null;
+ const q = parseEffectiveQualifier(rest);
+ if (q.kind === 'ok') { effective = q.range; rest = rest.slice(q.length).trim(); }
+ else if (q.kind === 'refused') note(q.reason, q.message);
+ let context: string | null = null;
+ const group = trailingGroupStart(rest);
+ if (group > 0) { context = rest.slice(group + 1, -1).trim() || null; rest = rest.slice(0, group).trim(); }
+ const tags = [...rest.matchAll(/(?:^|\s)#([A-Za-z][\w/-]*)/g)].map(t => t[1]);
+ const claim = rest.replace(/(?:^|\s)#[A-Za-z][\w/-]*/g, '').replace(/\s+/g, ' ').trim();
+ if (!claim) return null;
+ const lower = category.toLowerCase();
+ return { category, kind: (FACT_KINDS.has(lower) ? lower : 'fact') as GrammarFact['kind'], claim, tags, context, effective };
+}
+
+function nearest(type: string, declared: ReadonlySet<string>): string | null {
+ let best: string | null = null; let bestScore = Infinity;
+ for (const candidate of declared) {
+ const d = levenshtein(type, candidate);
+ if (d < bestScore) { bestScore = d; best = candidate; }
+ }
+ return best;
+}
+
+function levenshtein(a: string, b: string): number {
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
+ for (let i = 1; i <= a.length; i++) {
+ let prev = row[0]; row[0] = i;
+ for (let j = 1; j <= b.length; j++) {
+ const tmp = row[j];
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
+ prev = tmp;
+ }
+ }
+ return row[b.length];
+}
+
+function parseRelationContent(content: string, declared: ReadonlySet<string> | null,
+ note: (reason: GrammarReason, message: string) => void): Omit<GrammarRelation, 'line' | 'start' | 'end'> | null {
+ const links = [...content.matchAll(LINK_RE)];
+ if (!links.length) return null;
+ const first = links[0];
+ let prefix = content.slice(0, first.index).trim();
+ let effective: EffectiveRange | null = null;
+ // A qualifier may sit between the type and the link.
+ const qualifierAt = prefix.search(/\s@[A-Za-z]/);
+ let qualifierText = '';
+ if (qualifierAt > 0) { qualifierText = prefix.slice(qualifierAt).trim(); prefix = prefix.slice(0, qualifierAt).trim(); }
+ const quoted = /^(["'])([^"']+)\1$/.exec(prefix);
+ const tokenOk = quoted ? /^[A-Za-z][A-Za-z0-9 _-]{0,39}$/.test(quoted[2]) : TYPE_TOKEN_RE.test(prefix);
+ if (!tokenOk) return null;
+ const type = normalizeRelationType(quoted ? quoted[2] : prefix);
+ if (!type) return null;
+ const explicit = type.includes('_') || !!quoted || (declared?.has(type) ?? false);
+ if (TYPE_STOPLIST.has(type)) {
+ if (explicit) note('stoplist_type', `"${type}" is too generic to be a relation type, so the link keeps its inferred type.`);
+ return null;
+ }
+ if (links.length > 1) {
+ if (explicit) note('two_links', 'A relation line names exactly one link; write one line per target.');
+ return null;
+ }
+ let suffix = content.slice(first.index! + first[0].length).trim();
+ if (!qualifierText && suffix.startsWith('@')) {
+ const q = parseEffectiveQualifier(suffix);
+ if (q.kind === 'ok') { qualifierText = q.range.raw; suffix = suffix.slice(q.length).trim(); }
+ else if (q.kind === 'refused') { note(q.reason, q.message); return null; }
+ }
+ let context: string | null = null;
+ if (suffix) {
+ const group = trailingGroupStart(suffix);
+ if (group !== 0) {
+ if (explicit) note('prose_tail', `Text after the link makes this a sentence, so "${type}" is not applied. Put extra words in one trailing (context).`);
+ return null;
+ }
+ context = suffix.slice(1, -1).trim() || null;
+ }
+ if (qualifierText) {
+ const q = parseEffectiveQualifier(qualifierText);
+ if (q.kind === 'ok' && q.length === qualifierText.length) effective = q.range;
+ else { note(q.kind === 'refused' ? q.reason : 'invalid_range', q.kind === 'refused' ? q.message : 'Only one @effective[start,end) qualifier may follow the type.'); return null; }
+ }
+ if (declared && declared.size && !declared.has(type)) {
+ const near = nearest(type, declared);
+ note('undeclared_type', `"${type}" is not a link verb of the active schema pack, so the link keeps its inferred type.${near ? ` Did you mean ${near}?` : ''}`);
+ return null;
+ }
+ return { type, context, effective };
+}
+
+const FALSY = new Set(['false', '0', 'no', 'off']);
+
+/** `line_grammar.enabled` (default on) and `line_grammar.allow_undeclared_types` (default off). */
+export async function lineGrammarOptions(engine: { getConfig(key: string): Promise<string | null> }): Promise<{ enabled: boolean; allowUndeclaredTypes: boolean }> {
+ const read = (key: string) => engine.getConfig(key).catch(() => null);
+ const [enabled, allow] = await Promise.all([read('line_grammar.enabled'), read('line_grammar.allow_undeclared_types')]);
+ return { enabled: enabled == null || !FALSY.has(enabled.trim().toLowerCase()),
+ allowUndeclaredTypes: allow != null && ['true', '1', 'yes', 'on'].includes(allow.trim().toLowerCase()) };
+}
+
+/**
+ * The stated relation type for a link at `index` in `text`, for link
+ * extraction. `declaredVerbs` (the active pack's link verbs) gates types
+ * unless `allowUndeclaredTypes`; `enabled: false` turns stated types off.
+ */
+export function statedRelationTypes(text: string, opts: { enabled?: boolean; allowUndeclaredTypes?: boolean;
+ declaredVerbs?: readonly string[] }): (index?: number) => string | undefined {
+ if (opts.enabled === false) return () => undefined;
+ const declaredTypes = !opts.allowUndeclaredTypes && opts.declaredVerbs?.length ? new Set(opts.declaredVerbs) : null;
+ const lines = parseLineGrammar(text, { declaredTypes }).relations;
+ if (!lines.length) return () => undefined;
+ return index => index === undefined || index < 0 ? undefined : lines.find(line => index >= line.start && index < line.end)?.type;
+}
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 2915f1dee1..af51de3785 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -15,6 +15,8 @@ import type { BrainEngine, LinkBatchInput } from './engine.ts';
import type { PageType, EffectiveDateSource } from './types.ts';
import { ensureWellFormed } from './text-safe.ts';
import { stripCodeBlocks } from './markdown-code.ts';
+import { inSuppressedRange, rolePriorSuppressedRanges } from './machine-sections.ts';
+import { statedRelationTypes } from './line-grammar.ts';
import { isValidSourceId } from './source-id.ts';
import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
import { isMaterializedMarkerLine } from './timeline-marker.ts';
@@ -617,6 +619,21 @@ export interface LinkCandidate {
authoredRef?: AuthoredRef;
}
+export interface ExtractPageLinksOptions {
+ globalBasename?: boolean; skipFrontmatter?: boolean; pack?: LinkExtractionPack | null;
+ /** Typed relation lines (core/line-grammar.ts); on unless `enabled: false`. */
+ lineGrammar?: { enabled?: boolean; allowUndeclaredTypes?: boolean };
+ targetType?: (slug: string, sourceId?: string) => string | undefined;
+ onResolvedFrontmatterTarget?: (slug: string) => void;
+}
+
+/** The authored reference of a wikilink at `idx`: a slug path, or a bare name keyed by its basename. */
+function wikilinkAuthoredRef(target: string, idx: number): AuthoredRef | undefined {
+ if (target.includes('/')) return { key: `ref:${idx}`, kind: 'slug', target };
+ const name = normalizeBasename(target);
+ return name ? { key: `ref:${idx}`, kind: 'name', target: name } : undefined;
+}
+
/** One authored body reference, as recorded in `wanted_links` when it does not resolve. */
export interface AuthoredRef {
key: string;
@@ -661,9 +678,7 @@ export async function extractPageLinks(
frontmatter: Record<string, unknown>,
pageType: PageType,
resolver: SlugResolver,
- opts: { globalBasename?: boolean; skipFrontmatter?: boolean; pack?: LinkExtractionPack | null;
- targetType?: (slug: string, sourceId?: string) => string | undefined;
- onResolvedFrontmatterTarget?: (slug: string) => void } = {},
+ opts: ExtractPageLinksOptions = {},
): Promise<PageLinksResult> {
const candidates: LinkCandidate[] = [];
@@ -687,7 +702,10 @@ export async function extractPageLinks(
const attendancePending = new Set<number>();
const attendanceResolved = new Set<number>();
const attendanceAmbiguous = new Set<number>();
+ const statedType = statedRelationTypes(content, { ...opts.lineGrammar, declaredVerbs: pack?.link_types.map(lt => lt.name) });
const typeFor = (ctx: string, targetSlug: string, idx?: number, sourceId?: string, bodyReference = true): Pick<LinkCandidate, 'linkType' | 'canonicalAttendance'> => {
+ const stated = bodyReference ? statedType(idx) : undefined; // a typed relation line wins (core/line-grammar.ts)
+ if (stated && !(stated === 'attended' && pageType === 'meeting')) return { linkType: stated };
const targetType = opts.targetType?.(targetSlug, sourceId);
if (pack) {
const packVerb = inferLinkTypeFromPack(pack, pageType as string, ctx, packBudget, targetType);
@@ -835,9 +853,7 @@ export async function extractPageLinks(
const uniquePerson = personTargets.length === 1;
if (pageType === 'meeting' && opts.targetType && !uniquePerson
&& targets.filter(target => opts.targetType!(target) !== undefined).length > 1) attendanceAmbiguous.add(idx);
- const authoredRef: AuthoredRef | undefined = slashIdx === -1
- ? (normalizeBasename(ref.slug) ? { key: `ref:${idx}`, kind: 'name', target: normalizeBasename(ref.slug) } : undefined)
- : { key: `ref:${idx}`, kind: 'slug', target: ref.slug };
+ const authoredRef = wikilinkAuthoredRef(ref.slug, idx);
for (const target of bareDirect) {
const inferred = typeFor(context, target, idx);
candidates.push({ targetSlug: target,
@@ -1208,48 +1224,6 @@ const ADVISOR_ROLE_RE = /\b(?:full-time advisor|professional advisor|advises (?:
// pages mentioning their employees use the page-role layer differently.
const EMPLOYEE_ROLE_RE = /\b(?:is an? (?:senior|staff|principal|lead|backend|frontend|full-?stack|ML|data|security|DevOps|platform)? ?engineer at|is an? (?:senior|staff|principal|lead)? ?(?:developer|designer|product manager|engineering manager|director|VP) (?:at|of)|holds? the (?:CTO|CEO|CFO|COO|CMO|CRO|VP) (?:role|position|seat|title) at|is the (?:CTO|CEO|CFO|COO|CMO|CRO) of|employee at|on the team at|works on .{0,30} at)\b/i;
-/**
- * Content index ranges where the page-role prior must NOT apply: the
- * machine-written list sections — Timeline, See also, Related, Facts,
- * Sources, Links, Email mention links, Backlinks, Significant moments
- * (headingRe below is the one source of truth). Links there are list-shaped, per-event references
- * ("2026-05-12 — met with [[companies/x]]", Iron-Law back-links) — the
- * role prior is a statement about the AUTHOR's standing relationships, not
- * about every entity that passes through their timeline, so applying it
- * there mints unevidenced works_at/advises edges on every re-import (on
- * one 12k-page brain: ~7.4k such edges re-minted in a month, right after
- * a ~19.5k cleanup; same class as #3466). Per-edge verbs inside these
- * sections still type normally — only the globalContext fallback is
- * suppressed, so absent explicit evidence the edge stays 'mentions'.
- *
- * A range runs from its heading to the next heading of the same or higher
- * level (or EOF). Case-insensitive; matches "See also" / "See-also". Both
- * grammars require the ATX space after the `#`s, so a column-0 tag line
- * (`#links`) is neither an opener nor a closer.
- */
-function rolePriorSuppressedRanges(content: string): Array<[number, number]> {
- const ranges: Array<[number, number]> = [];
- const headingRe = /^(#{1,6})[ \t]+(?:timeline|see[ -]also|related|facts|sources|links|email mention links|backlinks|significant moments)\b[^\n]*$/gim;
- const anyHeadingRe = /^(#{1,6})[ \t]/gm;
- let m: RegExpExecArray | null;
- while ((m = headingRe.exec(content)) !== null) {
- const level = m[1].length;
- anyHeadingRe.lastIndex = m.index + m[0].length;
- // Deeper headings (`###` under `## Timeline`) stay inside the range; the
- // first same-or-higher one closes it.
- let next: RegExpExecArray | null;
- while ((next = anyHeadingRe.exec(content)) !== null && next[1].length > level) { /* nested subsection */ }
- ranges.push([m.index, next ? next.index : content.length]);
- }
- return ranges;
-}
-
-function inSuppressedRange(ranges: Array<[number, number]>, idx: number): boolean {
- for (const [start, end] of ranges) {
- if (idx >= start && idx < end) return true;
- }
- return false;
-}
/**
* Infer link_type from page context. Deterministic regex heuristics, no LLM.
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index 23dc665d80..73d86e7a61 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -6,6 +6,7 @@ import { parseMarkdown } from './markdown.ts';
import { isValidSourceId } from './source-id.ts';
import { buildSourceLocalReferenceIndex } from './source-local-reference-index.ts';
import { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';
+import { lineGrammarOptions } from './line-grammar.ts';
export interface LinkPageMetadata {
slug: string;
@@ -74,6 +75,7 @@ export async function reconcileSourceLinks(
const index = new Map(pages.map(page => [page.slug, page]));
const resolver = makeIndexedLinkResolver(pages, sourceId);
const wantedEnabled = await isWantedPagesEnabled(engine);
+ const lineGrammar = await lineGrammarOptions(engine);
const remaining = pages.filter(page => !opts.afterSlug || page.slug > opts.afterSlug)
.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
for (const metadata of remaining.slice(0, limit)) {
@@ -85,7 +87,7 @@ export async function reconcileSourceLinks(
}
const page = snapshot.page;
const extracted = await extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,
- page.type, resolver, { pack: opts.pack, globalBasename: opts.globalBasename,
+ page.type, resolver, { pack: opts.pack, globalBasename: opts.globalBasename, lineGrammar,
targetType: (slug, source) => !source || source === sourceId ? index.get(slug)?.type : undefined });
for (const ref of extracted.unresolved) {
const target = unwrapWikilink(ref.name);
diff --git a/src/core/machine-sections.ts b/src/core/machine-sections.ts
new file mode 100644
index 0000000000..3d06a63523
--- /dev/null
+++ b/src/core/machine-sections.ts
@@ -0,0 +1,50 @@
+/**
+ * Machine-written list sections of a page body (Timeline, See also, Related,
+ * Facts, Sources, Links, Email mention links, Backlinks, Significant moments).
+ * Link-type inference skips the page-role prior inside them, and the line
+ * grammar (src/core/line-grammar.ts) never reads a typed relation or a fact
+ * line inside them: writers fill these sections with per-event references.
+ */
+
+/**
+ * Content index ranges where the page-role prior must NOT apply: the
+ * machine-written list sections — Timeline, See also, Related, Facts,
+ * Sources, Links, Email mention links, Backlinks, Significant moments
+ * (headingRe below is the one source of truth). Links there are list-shaped, per-event references
+ * ("2026-05-12 — met with [[companies/x]]", Iron-Law back-links) — the
+ * role prior is a statement about the AUTHOR's standing relationships, not
+ * about every entity that passes through their timeline, so applying it
+ * there mints unevidenced works_at/advises edges on every re-import (on
+ * one 12k-page brain: ~7.4k such edges re-minted in a month, right after
+ * a ~19.5k cleanup; same class as #3466). Per-edge verbs inside these
+ * sections still type normally — only the globalContext fallback is
+ * suppressed, so absent explicit evidence the edge stays 'mentions'.
+ *
+ * A range runs from its heading to the next heading of the same or higher
+ * level (or EOF). Case-insensitive; matches "See also" / "See-also". Both
+ * grammars require the ATX space after the `#`s, so a column-0 tag line
+ * (`#links`) is neither an opener nor a closer.
+ */
+export function rolePriorSuppressedRanges(content: string): Array<[number, number]> {
+ const ranges: Array<[number, number]> = [];
+ const headingRe = /^(#{1,6})[ \t]+(?:timeline|see[ -]also|related|facts|sources|links|email mention links|backlinks|significant moments)\b[^\n]*$/gim;
+ const anyHeadingRe = /^(#{1,6})[ \t]/gm;
+ let m: RegExpExecArray | null;
+ while ((m = headingRe.exec(content)) !== null) {
+ const level = m[1].length;
+ anyHeadingRe.lastIndex = m.index + m[0].length;
+ // Deeper headings (`###` under `## Timeline`) stay inside the range; the
+ // first same-or-higher one closes it.
+ let next: RegExpExecArray | null;
+ while ((next = anyHeadingRe.exec(content)) !== null && next[1].length > level) { /* nested subsection */ }
+ ranges.push([m.index, next ? next.index : content.length]);
+ }
+ return ranges;
+}
+
+export function inSuppressedRange(ranges: Array<[number, number]>, idx: number): boolean {
+ for (const [start, end] of ranges) {
+ if (idx >= start && idx < end) return true;
+ }
+ return false;
+}
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index 46b9aafa88..a0ed1b4d53 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -7,6 +7,7 @@ import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled } from '../wanted-links.ts';
import { readFix } from '../ops/op-fix.ts';
+import { lineGrammarOptions } from '../line-grammar.ts';
async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {
if (!targets.length) return new Map();
@@ -25,7 +26,7 @@ async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: s
export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {
const resolver = makeResolver(engine, { mode: 'live', sourceId });
- const opts = { globalBasename: await isGlobalBasenameEnabled(engine),
+ const opts = { globalBasename: await isGlobalBasenameEnabled(engine), lineGrammar: await lineGrammarOptions(engine),
pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };
if (!opts.pack) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true,
apply: async () => ({ created: 0, removed: 0, errors: 1, unresolved_count: 1 }) };
diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.ts
index faaa349eed..a3901a10fc 100644
--- a/src/core/persistence/page-advisories.ts
+++ b/src/core/persistence/page-advisories.ts
@@ -4,6 +4,39 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { writerLintForPutPage } from '../output/post-write.ts';
import type { WriteRequest } from './model.ts';
import { prepareFactsBackstop } from './effect-facts.ts';
+import { lineGrammarOptions, parseLineGrammar } from '../line-grammar.ts';
+import { isAutoLinkEnabled } from '../link-extraction.ts';
+import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
+
+const LINE_GRAMMAR_FINDINGS_MAX = 5;
+
+/**
+ * What the line grammar read from this page body: typed relation lines and
+ * fact lines, with every near-miss explained. Absent when the page has none.
+ * Relations are stored with the page's links (or by the next sweep for a
+ * remote writer); fact lines stay page text and are not added to `facts`.
+ */
+async function lineGrammarAdvisory(engine: BrainEngine, row: WriteRequest, page: ParsedPage): Promise<Record<string, unknown> | undefined> {
+ const options = await lineGrammarOptions(engine);
+ if (!options.enabled) return undefined;
+ const pack = options.allowUndeclaredTypes ? null : (await loadActivePackForLocalEngine(engine, { sourceId: row.source_id }))?.manifest ?? null;
+ const declaredTypes = pack?.link_types.length ? new Set(pack.link_types.map(lt => lt.name)) : null;
+ const parsed = parseLineGrammar(page.compiled_truth, { declaredTypes });
+ if (!parsed.relations.length && !parsed.facts.length && !parsed.diagnostics.length) return undefined;
+ const relationsState = !(await isAutoLinkEnabled(engine)) ? 'auto_link_disabled'
+ : row.authority.remote && !row.authority.autoLinkTrusted ? 'pending_sweep' : 'stored';
+ return {
+ relations: parsed.relations.length,
+ relations_state: relationsState,
+ facts: parsed.facts.length,
+ ...(parsed.facts.length ? { facts_state: 'page_text_only',
+ facts_message: 'Fact lines are searchable page text; they are not added to recall facts. Use remember (or the page ## Facts table) for a fact recall must return.' } : {}),
+ findings: parsed.diagnostics.slice(0, LINE_GRAMMAR_FINDINGS_MAX).map(d => ({ severity: 'warning', validator: 'line-grammar',
+ line: d.line, reason: d.reason, text: d.text, message: d.message })),
+ total: parsed.diagnostics.length,
+ details_truncated: parsed.diagnostics.length > LINE_GRAMMAR_FINDINGS_MAX,
+ };
+}
const LINT_MESSAGES: Record<string,string> = { citation:'Paragraph has no citation marker.',
link:'A link target is unavailable.', 'back-link':'A reverse link is missing.', 'triple-hr':'An ambiguous timeline separator was found.' };
@@ -24,5 +57,7 @@ export async function preparePageAdvisories(engine: BrainEngine, row: WriteReque
top_findings: lint.top_findings.map(finding => ({ ...finding, message: LINT_MESSAGES[finding.validator] ?? `${finding.validator} validation finding.` })) } : lint;
const facts = ['put_page', 'capture', 'edit_page'].includes(row.operation)
? await prepareFactsBackstop(engine, row, page).catch(() => ({ skipped: 'backstop_error' })) : undefined;
- return { ...remoteLinkHint(row), ...(sanitized ? { writer_lint: sanitized } : {}), ...(facts ? { facts_backstop: facts } : {}) };
+ const grammar = await lineGrammarAdvisory(engine, row, visible).catch(() => undefined);
+ return { ...remoteLinkHint(row), ...(sanitized ? { writer_lint: sanitized } : {}), ...(facts ? { facts_backstop: facts } : {}),
+ ...(grammar ? { line_grammar: grammar } : {}) };
}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 522ea23968..db5ef483d2 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -1,5 +1,6 @@
import { lookupRefsForSlugs } from './link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled, type WantedLinkInput } from './wanted-links.ts';
+import { lineGrammarOptions } from './line-grammar.ts';
/**
* Serve-resident maintenance sweep [CX-P0.1, CX-P0.3, CX2-4].
*
@@ -412,6 +413,7 @@ async function runLinksTimelinePass(
const incomplete = new Set<string>();
const wantedBySlug = new Map<string, WantedLinkInput[]>();
const wantedEnabled = await isWantedPagesEnabled(engine);
+ const lineGrammar = await lineGrammarOptions(engine);
if (pageCandidates.length > 0) {
const needed = new Set<string>();
for (const { slug, candidates } of pageCandidates) {
@@ -442,7 +444,7 @@ async function runLinksTimelinePass(
for (const { slug } of pageCandidates) {
const page = snapshots.get(slug)!.page;
const { candidates, attendanceComplete } = await extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,
- page.type, resolver, { skipFrontmatter: true, globalBasename, pack, targetType: (targetSlug, targetSourceId) => {
+ page.type, resolver, { skipFrontmatter: true, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,
sourceId, allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId });
return resolved.ok ? endpointMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
diff --git a/test/line-grammar.test.ts b/test/line-grammar.test.ts
new file mode 100644
index 0000000000..907a116895
--- /dev/null
+++ b/test/line-grammar.test.ts
@@ -0,0 +1,179 @@
+/**
+ * Line grammar parser (src/core/line-grammar.ts): typed fact and relation
+ * lines, the guards that keep transcripts, task lists and citations out, and
+ * the `@effective[start,end)` validity qualifier. Pure, no engine.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { normalizeRelationType, parseEffectiveQualifier, parseLineGrammar } from '../src/core/line-grammar.ts';
+
+const facts = (text: string) => parseLineGrammar(text).facts;
+const relations = (text: string, declared?: string[]) =>
+ parseLineGrammar(text, { declaredTypes: declared ? new Set(declared) : null }).relations;
+const reasons = (text: string, declared?: string[]) =>
+ parseLineGrammar(text, { declaredTypes: declared ? new Set(declared) : null }).diagnostics.map(d => d.reason);
+
+describe('fact lines', () => {
+ test('category, claim, tags and context', () => {
+ expect(facts('- [preference] Prefers oat milk #coffee #morning (since the almond allergy)')).toEqual([{ line: 1,
+ category: 'preference', kind: 'preference', claim: 'Prefers oat milk', tags: ['coffee', 'morning'],
+ context: 'since the almond allergy', effective: null }]);
+ });
+
+ test('a category outside the six kinds is kept and the kind is fact', () => {
+ expect(facts('* [technique] Water at 205F extracts best')[0]).toMatchObject({ category: 'technique', kind: 'fact', claim: 'Water at 205F extracts best' });
+ });
+
+ test('numbered list items and nested items count', () => {
+ expect(facts('1. [idea] Ship weekly\n - [belief] Small teams win')).toHaveLength(2);
+ });
+
+ test('guards: timecodes, dates, task markers, citations, footnotes, links, images, multi-word brackets', () => {
+ for (const line of [
+ '- [00:00:11] Speaker one said hello',
+ '- [1:02:03.500] later',
+ '- [00:01 - 00:05] range',
+ '- [2024-01-01] dated',
+ '- [ ] open task',
+ '- [x] done task',
+ '- [X] done task',
+ '- [/] in progress',
+ '- [-] cancelled',
+ '- [>] deferred',
+ '- [?] question',
+ '- [Source: email 2024] cited claim',
+ '- [^1] footnote',
+ '- [Acme](companies/acme) is a company',
+ '- [Acme][ref] reference link',
+ '- ![chart](img.png) image',
+ '- [[people/alice]] wikilink',
+ '- [two words] not a category',
+ '- [todo] call bob',
+ '- [WIP] draft',
+ ]) expect(facts(line)).toEqual([]);
+ });
+
+ test('code, blockquotes, HTML comments, frontmatter and machine sections are never read', () => {
+ const text = [
+ '---', 'title: x', 'tags:', ' - [idea] in frontmatter', '---',
+ '```', '- [idea] in a fence', '```',
+ '> - [idea] in a quote',
+ '<!-- - [idea] in a comment -->',
+ '## Timeline', '- [event] in the timeline section',
+ '## Notes', '- [idea] counted',
+ ].join('\n');
+ expect(facts(text).map(f => f.claim)).toEqual(['counted']);
+ });
+
+ test('a backslash keeps the line literal', () => {
+ expect(facts('- \\[idea] escaped')).toEqual([]);
+ });
+
+ test('CRLF line endings', () => {
+ expect(facts('- [idea] one\r\n- [idea] two\r\n').map(f => f.claim)).toEqual(['one', 'two']);
+ });
+});
+
+describe('relation lines', () => {
+ test('type, link forms and context', () => {
+ expect(relations('- works_at [[companies/acme-example]] (since 2024)')).toMatchObject([{ type: 'works_at', context: 'since 2024', line: 1 }]);
+ expect(relations('- advises [Acme](companies/acme-example)')).toMatchObject([{ type: 'advises', context: null }]);
+ expect(relations('- invested_in [[fund-a:companies/acme-example|Acme]]')).toMatchObject([{ type: 'invested_in' }]);
+ });
+
+ test('type normalization: camelCase, kebab, quoted phrases', () => {
+ expect(normalizeRelationType('worksAt')).toBe('works_at');
+ expect(normalizeRelationType('works-at')).toBe('works_at');
+ expect(normalizeRelationType('Board Member')).toBe('board_member');
+ expect(relations('- "board member" [[companies/acme]]')).toMatchObject([{ type: 'board_member' }]);
+ expect(relations("- 'reports to' [[people/bob]]")).toMatchObject([{ type: 'reports_to' }]);
+ });
+
+ test('offsets cover the whole line so a link on it can be matched', () => {
+ const text = 'Intro.\n- works_at [[companies/acme]]\n';
+ const [r] = relations(text);
+ expect(text.slice(r.start, r.end)).toBe('- works_at [[companies/acme]]');
+ });
+
+ test('sentences fall back silently: multi-word prefix, generic words, prose without a typed attempt', () => {
+ expect(relations('- Met [[people/alice]] at the cafe')).toEqual([]);
+ expect(reasons('- Met [[people/alice]] at the cafe')).toEqual([]);
+ expect(relations('- works at [[companies/acme]]')).toEqual([]);
+ expect(relations('- See [[people/alice]]')).toEqual([]);
+ expect(reasons('- See [[people/alice]]')).toEqual([]);
+ expect(relations('- [[people/alice]]')).toEqual([]);
+ });
+
+ test('typed attempts that do not parse explain themselves', () => {
+ expect(reasons('- works_at [[companies/acme]] since 2024')).toEqual(['prose_tail']);
+ expect(reasons('- invested_in [[a]] and [[b]]')).toEqual(['two_links']);
+ expect(reasons('- "see" [[people/x]]')).toEqual(['stoplist_type']);
+ expect(relations('- works_at [[companies/acme]] (primary) and [[b]] (secondary)')).toEqual([]);
+ });
+
+ test('links inside code are not links', () => {
+ expect(relations('- works_at `[[companies/acme]]`')).toEqual([]);
+ });
+
+ test('declared vocabulary gate: undeclared types fall back with the nearest verb', () => {
+ expect(relations('- workz_at [[companies/a]]', ['works_at', 'invested_in'])).toEqual([]);
+ const [d] = parseLineGrammar('- workz_at [[companies/a]]', { declaredTypes: new Set(['works_at']) }).diagnostics;
+ expect(d).toMatchObject({ reason: 'undeclared_type' });
+ expect(d.message).toContain('Did you mean works_at?');
+ expect(relations('- works_at [[companies/a]]', ['works_at'])).toHaveLength(1);
+ expect(relations('- anything_goes [[companies/a]]')).toHaveLength(1);
+ });
+
+ test('machine sections are skipped', () => {
+ expect(relations('## See also\n- works_at [[companies/acme]]\n## Related\n- advises [[x]]')).toEqual([]);
+ });
+});
+
+describe('@effective qualifier', () => {
+ const range = (q: string) => { const r = parseEffectiveQualifier(q); return r.kind === 'ok' ? [r.range.from, r.range.until] : r.kind; };
+
+ test('precision and bound kinds normalize to half-open dates', () => {
+ expect(range('@effective[2024-03,2024-09)')).toEqual(['2024-03-01', '2024-09-01']);
+ expect(range('@effective[2022,2024]')).toEqual(['2022-01-01', '2025-01-01']);
+ expect(range('@effective(2024-01-31,2024-02-29]')).toEqual(['2024-02-01', '2024-03-01']);
+ expect(range('@valid[2024-12,)')).toEqual(['2024-12-01', null]);
+ expect(range('@effective[,2020)')).toEqual([null, '2020-01-01']);
+ });
+
+ test('invalid, reversed, natural-language and unknown qualifiers are refused', () => {
+ expect(range('@effective[2023-02-29,)')).toBe('refused');
+ expect(range('@effective[2024,2023)')).toBe('refused');
+ expect(range('@effective[2024,2024)')).toBe('refused');
+ expect(range('@effective[last spring,)')).toBe('refused');
+ expect(range('@occurred[2024,2025)')).toBe('refused');
+ expect(range('@occurred:2024-01-01')).toBe('refused');
+ });
+
+ test('handles and emails are not qualifiers', () => {
+ expect(range('@alice said hi')).toBe('none');
+ expect(range('[email protected]')).toBe('none');
+ });
+
+ test('on fact and relation lines; a refused qualifier is never peeled', () => {
+ expect(facts('- [event] @effective[2024-03,2024-09) Led the pricing rework')[0]).toMatchObject({
+ claim: 'Led the pricing rework', effective: { from: '2024-03-01', until: '2024-09-01' } });
+ expect(facts('- [event] @effective[last year,) Led it')[0]).toMatchObject({ claim: '@effective[last year,) Led it', effective: null });
+ expect(relations('- works_at @effective[2022,2024] [[companies/acme]]')[0]).toMatchObject({ type: 'works_at',
+ effective: { from: '2022-01-01', until: '2025-01-01' } });
+ expect(relations('- works_at [[companies/acme]] @effective[2022,) (CTO)')[0]).toMatchObject({ context: 'CTO',
+ effective: { from: '2022-01-01', until: null } });
+ expect(relations('- works_at [[companies/acme]] @occurred:2022')).toEqual([]);
+ expect(reasons('- works_at [[companies/acme]] @occurred:2022')).toEqual(['unknown_qualifier']);
+ });
+});
+
+test('adversarial input stays linear (bounded child process)', () => {
+ const script = `
+ const { parseLineGrammar } = await import(${JSON.stringify(new URL('../src/core/line-grammar.ts', import.meta.url).pathname)});
+ const evil = ['- ' + '['.repeat(20000) + 'x', '- works_at ' + '('.repeat(20000), '- [a] ' + '(('.repeat(10000) + ')',
+ '- t ' + '[[a]] '.repeat(5000), '- [idea] @effective[' + ','.repeat(20000)].join('\\n');
+ const t = performance.now(); parseLineGrammar(evil.repeat(5)); console.log(Math.round(performance.now() - t));`;
+ const run = spawnSync(process.execPath, ['-e', script], { timeout: 20_000, encoding: 'utf-8' });
+ expect(run.status, run.stderr).toBe(0);
+ expect(Number(run.stdout.trim())).toBeLessThan(5_000);
+}, 30_000);
diff --git a/test/link-extraction-line-grammar.test.ts b/test/link-extraction-line-grammar.test.ts
new file mode 100644
index 0000000000..b1e88cc213
--- /dev/null
+++ b/test/link-extraction-line-grammar.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Typed relation lines in link extraction: the stated type applies to the
+ * link on its own line only, pack vocabulary gates it, and content without
+ * relation lines extracts exactly as before. Pure, no engine.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { extractPageLinks, type LinkExtractionPack, type SlugResolver } from '../src/core/link-extraction.ts';
+import type { PageType } from '../src/core/types.ts';
+
+const nullResolver: SlugResolver = { resolve: async () => null };
+const types = async (content: string, opts: Parameters<typeof extractPageLinks>[5] = {}, pageType: PageType = 'person') =>
+ (await extractPageLinks('people/alice-example', content, {}, pageType, nullResolver, { skipFrontmatter: true, ...opts }))
+ .candidates.map(c => [c.targetSlug, c.linkType]);
+const pack = (verbs: string[]): LinkExtractionPack => ({ link_types: verbs.map(name => ({ name })) as never, frontmatter_links: [] });
+
+describe('typed relation lines', () => {
+ test('the stated type wins for the link on its line only', async () => {
+ const content = 'Alice mentions [[companies/acme-example]] in passing.\n\n- works_at [[companies/acme-example]] (since 2024)\n- invested_in [[companies/widget-co]]';
+ expect(await types(content)).toEqual([
+ ['companies/acme-example', 'mentions'],
+ ['companies/acme-example', 'works_at'],
+ ['companies/widget-co', 'invested_in'],
+ ]);
+ });
+
+ test('a sentence line keeps inference', async () => {
+ expect(await types('- works_at [[companies/acme-example]] since 2024')).toEqual([['companies/acme-example', 'mentions']]);
+ });
+
+ test('a machine section never applies stated types', async () => {
+ expect(await types('## See also\n- works_at [[companies/acme-example]]')).toEqual([['companies/acme-example', 'mentions']]);
+ });
+
+ test('pack vocabulary gate, and its opt-out', async () => {
+ const content = '- employed_by [[companies/acme-example]]';
+ expect(await types(content, { pack: pack(['works_at']) })).toEqual([['companies/acme-example', 'mentions']]);
+ expect(await types(content, { pack: pack(['works_at', 'employed_by']) })).toEqual([['companies/acme-example', 'employed_by']]);
+ expect(await types(content, { pack: pack(['works_at']), lineGrammar: { allowUndeclaredTypes: true } }))
+ .toEqual([['companies/acme-example', 'employed_by']]);
+ });
+
+ test('line_grammar disabled restores inference', async () => {
+ expect(await types('- works_at [[companies/acme-example]]', { lineGrammar: { enabled: false } }))
+ .toEqual([['companies/acme-example', 'mentions']]);
+ });
+
+ test('an attended line on a meeting page defers to canonical attendance evidence', async () => {
+ const content = 'Attendees: [[people/bob-example]]\n\n- attended [[people/carol-example]]';
+ const run = (enabled: boolean) => extractPageLinks('meetings/2026-01-02', content, {}, 'meeting' as PageType, nullResolver,
+ { skipFrontmatter: true, lineGrammar: { enabled } }).then(r => r.candidates.map(c => [c.targetSlug, c.linkType, c.canonicalAttendance ?? false]));
+ expect(await run(true)).toEqual(await run(false));
+ });
+});
+
+test('content without relation lines extracts byte-identically with the grammar on or off (BrainBench world-v1 shape)', async () => {
+ const fixtures = join(import.meta.dir, 'fixtures');
+ const pages = readdirSync(fixtures, { recursive: true }).map(String).filter(f => f.endsWith('.md')).slice(0, 80);
+ expect(pages.length).toBeGreaterThan(0);
+ for (const file of pages) {
+ const content = readFileSync(join(fixtures, file), 'utf-8');
+ if (/^\s*(?:[-*+]|\d+[.)])\s+["']?[A-Za-z][\w -]*["']?\s+(?:@\S+\s+)?\[/m.test(content)) continue;
+ const on = await extractPageLinks('notes/x', content, {}, 'note' as PageType, nullResolver, { skipFrontmatter: true });
+ const off = await extractPageLinks('notes/x', content, {}, 'note' as PageType, nullResolver, { skipFrontmatter: true, lineGrammar: { enabled: false } });
+ expect(on.candidates.map(c => [c.targetSlug, c.linkType])).toEqual(off.candidates.map(c => [c.targetSlug, c.linkType]));
+ }
+});
diff --git a/test/put-page-line-grammar.test.ts b/test/put-page-line-grammar.test.ts
new file mode 100644
index 0000000000..25e4ab2fd3
--- /dev/null
+++ b/test/put-page-line-grammar.test.ts
@@ -0,0 +1,41 @@
+/**
+ * put_page reports what the line grammar read: typed relation lines (stored
+ * with the page's links), fact lines (page text only) and near-misses with
+ * their fix. Managed PGLite brain.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const put = (ctx: OperationContext, slug: string, body: string, type = 'person') =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: ${type}\ntitle: ${slug}\n---\n\n${body}\n` } }) as Promise<Record<string, any>>;
+
+test('put_page types the stated relation, reports fact lines and explains near-misses', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'companies/acme-example', 'Acme.', 'company');
+ const written = await put(ctx, 'people/alice-example', [
+ 'Alice builds things.',
+ '',
+ '- works_at [[companies/acme-example]] (since 2024)',
+ '- [preference] Prefers oat milk #coffee',
+ '- works_at [[companies/acme-example]] since 2024',
+ ].join('\n'));
+ const grammar = (written.outcome ?? written).line_grammar;
+ expect(grammar).toMatchObject({ relations: 1, relations_state: 'stored', facts: 1, facts_state: 'page_text_only', total: 1,
+ details_truncated: false, findings: [{ severity: 'warning', validator: 'line-grammar', line: 5, reason: 'prose_tail' }] });
+ expect(grammar.facts_message).toContain('remember');
+ const edges = await engine.executeRaw<{ link_type: string }>(`SELECT l.link_type FROM links l JOIN pages f ON f.id=l.from_page_id
+ WHERE f.slug='people/alice-example' ORDER BY l.link_type`);
+ expect(edges.map(e => e.link_type)).toContain('works_at');
+ });
+}, 120_000);
+
+test('a page without grammar lines carries no line_grammar block', async () => {
+ await managedBrain(async ({ ctx }) => {
+ const written = await put(ctx, 'notes/plain', 'Just prose with [[people/someone]].', 'note');
+ expect((written.outcome ?? written).line_grammar).toBeUndefined();
+ });
+}, 120_000);