Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(graph): shared relationship note on ambient and compiled context; size ratchets, operations allowlist, catalog (GBRA-49 P1)
garrytanbc6723c856a2
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 2b62fb2724..25ff219388 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -112,11 +112,11 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S|---|---|---|---|---|| `add_link` | Create a typed link (edge) from one page to another in the same source. | write | | || `find_orphans` | Find disconnected pages. | read | | |-| `get_backlinks` | List links pointing to a page, such as who works at a company. | read | yes | |+| `get_backlinks` | List links pointing to a page. | read | yes | || `get_links` | List a page's outgoing links (typed edges to other pages). | read | | || `list_link_sources` | Link provenances in the brain (e.g. | read | yes | || `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |-| `traverse_graph` | Walk the link graph from a page along relationships that are true today (status: "all" walks history, as_of a past date). | read | yes | |+| `traverse_graph` | Walk the link graph from a page. | read | yes | |## loopsdiff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex e5f802ec41..0cc09769ea 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -107,6 +107,6 @@ rejection of serve-only flags before a brain opens.- `src/core/trajectory-format.ts` — shared `formatTrajectoryBlock(points, entitySlug, opts)` consumed by both `gbrain think` (production) and the LongMemEval harness (benchmark). Groups by `(metric ?? event_type)`, per-metric cap 20, total cap 100, knowledge_update intent annotates value-change rows with `(superseded prior)`. Emits a `<trajectory entity="...">` XML envelope — `INJECTION_PATTERNS` in `src/core/think/sanitize.ts` escapes `</trajectory>`, `<trajectory ...>` open tags, and attribute injection so adversarial fact text can't break out. Pinned by `test/trajectory-format.test.ts`.-- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.+- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. Budget through the cycle `BudgetMeter`. Pinned by `test/cycle-edge-contradictions.test.ts` and the managed phase matrix.diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.mdindex 2a3ce86c98..af25aea735 100644--- a/docs/guides/temporal-edges.md+++ b/docs/guides/temporal-edges.md@@ -90,6 +90,9 @@ relationships, "who worked at" / "used to" reads history, "former employees of"ended ones. Entity cards and `context_pack` keep every edge with its status and add arelationship note, for example`now: works_at widget-co (since 2025-03-01); ended: works_at acme-example (2025-03-01); summary may be stale: it still names acme-example`.+The same note follows a page into ambient turn context (appended to its synopsis) and into+compiled context files (a `relationships:` line under the excerpt), so an agent reading any+of them sees the ended relationship even when the summary has not been rewritten.## The nightly relationship checkdiff --git a/scripts/check-operations-filter-bypass.sh b/scripts/check-operations-filter-bypass.shindex 4d2734d2f8..77333445c6 100755--- a/scripts/check-operations-filter-bypass.sh+++ b/scripts/check-operations-filter-bypass.sh@@ -62,6 +62,8 @@ ALLOWED=("src/commands/enrich.ts" # local CLI tool; calls put_page handler with remote=false, not network-exposed"src/core/extract-takes-from-pages.ts" # local CLI extraction calls put_page with remote=false; it does not expose operations to a transport"src/commands/book-mirror.ts" # local CLI tool; not network-exposed+ "src/commands/edge-proposals.ts" # local CLI review of edge proposals; calls trusted handlers with remote=false, not network-exposed+ "src/core/cycle/edge-contradictions.ts" # dream phase appends closure lines via add_timeline_entry with remote=false; never exposes operations"src/commands/tools-json.ts" # gbrain --tools-json introspection; full op list IS the purpose"src/mcp/publish-gates.ts" # reads op.publishGateKey/name only to compute gate-DISABLED sets; never lists/exposes ops"src/mcp/tool-catalog.ts" # docs/TOOL_CATALOG.md renderer; filters !op.localOnly at the boundary; never a transport surfacediff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex e1d00035bd..c5caf39688 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -31,7 +31,7 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wavsrc/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane mergesrc/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle.ts runCycle 1255 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block+src/core/cycle.ts runCycle 1265 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stopsrc/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 49fde4b332..c74153e432 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/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)src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)-src/core/cycle.ts 3224 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224)+src/core/cycle.ts 3239 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts and link-relationships.ts)src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)src/core/engine.ts 2679 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 temporal typed edges: LinkReadScope import@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0src/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 refreshsrc/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 readsrc/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 1838 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)+src/core/config.ts 1839 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); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts)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 envsrc/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 optionsrc/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/core/context/compile-view.ts b/src/core/context/compile-view.tsindex 8a5ce80789..571529ca52 100644--- a/src/core/context/compile-view.ts+++ b/src/core/context/compile-view.ts@@ -43,6 +43,7 @@* whenever any entry fits.*/+import { loadRelationshipNotes, relationshipNoteKey } from '../link-relationship-notes.ts';import { createHash } from 'crypto';import { estimateTokens, packToBudget } from '../search/token-budget.ts';import { DEFAULT_SOURCE_BOOSTS } from '../search/source-boost.ts';@@ -96,6 +97,8 @@ export const COMPILED_CONTEXT_ENVELOPE =export interface CompileViewEngine {listPages(filters?: PageFilters): Promise<Page[]>;getPage(slug: string, opts?: GetPageOpts): Promise<Page | null>;+ /** Relationship notes (temporal typed edges); absent → entries render without them. */+ executeRaw?<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<R[]>;}export interface CompileViewInput {@@ -252,7 +255,7 @@ interface RenderedEntry {rendered: string;}-function renderEntry(page: Page): RenderedEntry {+function renderEntry(page: Page, relationshipNote?: string): RenderedEntry {const date = updatedDate(page);const excerpt = safeSynopsis({@@ -272,6 +275,7 @@ function renderEntry(page: Page): RenderedEntry {const title = page.title.replace(/\s+/g, ' ').trim();const lines = [`## ${title} (brain://${page.slug})`, `updated: ${date}`];if (excerpt) lines.push('', excerpt);+ if (relationshipNote) lines.push('', `relationships: ${relationshipNote}`);const block = lines.join('\n');return { slug: page.slug, date, block, rendered: `\n\n${block}` };}@@ -318,6 +322,12 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR// records the finding; a missing page (raced deletion) is a read error.const entries: RenderedEntry[] = [];const scanDrops: CompileViewScanDrop[] = [];+ const raw = input.engine.executeRaw?.bind(input.engine);+ const notes = !raw ? new Map<string, string>() : await loadRelationshipNotes(+ { executeRaw: raw },+ scored.map(({ c }) => ({ slug: c.page.slug, source_id: input.sourceId, summary: c.page.compiled_truth ?? '' })),+ { excludePrivate: true },+ ).catch(() => new Map<string, string>());for (const { c } of scored) {const page = await input.engine.getPage(c.page.slug, { sourceId: input.sourceId });if (!page) {@@ -325,7 +335,7 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR`compile-context: page ${c.page.slug} vanished mid-run (source ${input.sourceId}) — aborting, no partial output`,);}- const entry = renderEntry(page);+ const entry = renderEntry(page, notes.get(relationshipNoteKey(input.sourceId, page.slug)));const findings = scanSensitive(entry.rendered, input.scanConfig);if (findings.length > 0) {scanDrops.push({diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex eb0d8fb8df..88905ad710 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -24,6 +24,7 @@* Postgres engines; nothing here touches engine-specific SQL.*/+import { appendRelationshipNotes } from '../link-relationship-notes.ts';import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../operations.ts';import type { GBrainConfig } from '../config.ts';@@ -272,6 +273,7 @@ export async function assembleTurnContext(} catch {volunteered = [];}+ await appendRelationshipNotes(engine, [...pointers, ...volunteered]);return { pointers, volunteered };})();diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex ea676d1d9d..2bfc468a27 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -76,9 +76,7 @@ export type CyclePhase =// - calibration_profile: aggregates the resolved subset into 2-4// narrative pattern statements + active bias tags. Voice-gated.| 'propose_takes' | 'grade_takes' | 'calibration_profile'- // Temporal typed edges: an LLM flags live relationships that cannot both- // hold; date arithmetic decides which ended (proposals by default).- | 'edge_contradictions'+ | 'edge_contradictions' // temporal typed edges: LLM flags conflicts, date math closes// #2653 — drift detection (default OFF; dream.drift.enabled). LLM-judges// soft-band takes against recent timeline evidence; report-only in v1// (writes reports/drift-<date>; auto_update mutates nothing).@@ -170,10 +168,7 @@ export const ALL_PHASES: CyclePhase[] = ['propose_takes','grade_takes','calibration_profile',- // Temporal typed edges: proposes (or, for certified models, applies)- // closures for live relationships that cannot both hold. Runs after- // extract so it judges freshly derived relationship state.- 'edge_contradictions',+ 'edge_contradictions', // temporal typed edges; after extract so it judges fresh relationship state// #2653 — drift detection. Default OFF (dream.drift.enabled). Runs AFTER// the calibration trio (fresh take resolutions) and BEFORE embed so the// drift report page gets embedded same-cycle. Report-only in v1.@@ -338,8 +333,7 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['calibration_profile',// #2653 — writes the reports/drift-<date> page.'drift',- // Temporal typed edges — writes proposals and (apply mode) closure lines.- 'edge_contradictions',+ 'edge_contradictions', // writes proposals and (apply mode) closure lines// #5876 — writes event pages, projections and the chronicle ledger.'chronicle',// v0.41 T9 — extract_atoms writes atom-typed pages via put_page;@@ -616,8 +610,6 @@ export interface CycleOpts {* cap's worth drains incrementally across cycles (staleRemaining reports it).*/export const CYCLE_STALE_DRAIN_BUDGET_MS = 3 * 60 * 1000;-/** Relationship-state rows refreshed per cycle by the extract phase sweep (temporal typed edges). */-const RELATIONSHIP_SWEEP_LIMIT = 2000;const LEGACY_CYCLE_LOCK_ID = 'gbrain-cycle';// v0.41.19.0 (T2 of ops-fix-wave): dropped from 30 min to 5 min so a@@ -1405,20 +1397,8 @@ async function runPhaseExtract(} catch (e) {staleDetails = { stale_drain_error: e instanceof Error ? e.message : String(e) };}- // Temporal typed edges: relationships whose state is missing or older than- // their newest evidence (writers that bypass the engine, rows from before- // the upgrade) converge here, bounded per cycle. Zero LLM.- try {- const { staleRelationshipKeys, refreshRelationships } = await import('./link-relationships.ts');- const { maintenanceTransaction } = await import('./persistence/attribution.ts');- const keys = await staleRelationshipKeys(engine, RELATIONSHIP_SWEEP_LIMIT);- if (keys.length) {- const refreshed = await maintenanceTransaction(engine, tx => refreshRelationships(tx, keys));- staleDetails = { ...staleDetails, relationships_swept: keys.length, relationships_changed: refreshed };- }- } catch (e) {- staleDetails = { ...staleDetails, relationship_sweep_error: e instanceof Error ? e.message : String(e) };- }+ const { sweepStaleRelationships } = await import('./link-relationships.ts');+ staleDetails = { ...staleDetails, ...(await sweepStaleRelationships(engine)) };return {phase: 'extract',status: 'ok',@@ -2721,23 +2701,13 @@ export async function runCycle(}}- // ── Temporal typed edges: contradiction proposals ─────────────+ // Temporal typed edges: proposes (or, certified, applies) closures for live relationships that cannot both hold.if (phases.includes('edge_contradictions')) {checkAborted(cycleSignal);- if (!engine) {- phaseResults.push({ phase: 'edge_contradictions', status: 'skipped', duration_ms: 0, summary: 'no database connected', details: { reason: 'no_database' } });- } else {- progress.start('cycle.edge_contradictions');- const { runPhaseEdgeContradictions } = await import('./cycle/edge-contradictions.ts');- const { result, duration_ms } = await timePhase(async (): Promise<PhaseResult> => {- const r = await runPhaseEdgeContradictions(engine, { dryRun });- const status: PhaseStatus = r.status === 'complete' ? 'ok' : r.status === 'partial' ? 'warn' : r.status === 'failed' ? 'fail' : 'skipped';- return { phase: 'edge_contradictions', status, duration_ms: 0, summary: r.detail, details: { ...(r.totals ?? {}) } };- }, 'edge_contradictions');- result.duration_ms = duration_ms;- phaseResults.push(result);- progress.finish();- }+ progress.start('cycle.edge_contradictions');+ const { edgeContradictionsCyclePhase } = await import('./cycle/edge-contradictions.ts');+ const { result, duration_ms } = await timePhase(() => edgeContradictionsCyclePhase(engine, dryRun), 'edge_contradictions');+ result.duration_ms = duration_ms; phaseResults.push(result); progress.finish();await safeYield(opts.yieldBetweenPhases);}diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.tsindex afcd913903..5a23bce821 100644--- a/src/core/cycle/edge-contradictions.ts+++ b/src/core/cycle/edge-contradictions.ts@@ -23,6 +23,7 @@*/import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd } from './budget-meter.ts';import { resolveModel } from '../model-config.ts';import { closeContradiction, parseMultirange, relationSemantics, utcToday, dateKey, type Stint } from '../link-validity.ts';@@ -322,6 +323,14 @@ async function recordProposal(// ─── Apply / undo / revert detection ─────────────────────────────────────+/** Cycle adapter: maps the phase outcome onto the cycle's PhaseResult (duration filled by the caller). */+export async function edgeContradictionsCyclePhase(engine: BrainEngine | null, dryRun: boolean): Promise<PhaseResult> {+ if (!engine) return { phase: 'edge_contradictions', status: 'skipped', duration_ms: 0, summary: 'no database connected', details: { reason: 'no_database' } };+ const r = await runPhaseEdgeContradictions(engine, { dryRun });+ const status: PhaseResult['status'] = r.status === 'complete' ? 'ok' : r.status === 'partial' ? 'warn' : r.status === 'failed' ? 'fail' : 'skipped';+ return { phase: 'edge_contradictions', status, duration_ms: 0, summary: r.detail, details: { ...(r.totals ?? {}) } };+}+export type ApplyOutcome = { status: 'applied' | 'stale' | 'not_found' | 'refused' | 'undone' | 'rejected'; reason?: string };interface ProposalRow {diff --git a/src/core/link-relationship-notes.ts b/src/core/link-relationship-notes.tsnew file mode 100644index 0000000000..868369efc6--- /dev/null+++ b/src/core/link-relationship-notes.ts@@ -0,0 +1,110 @@+/**+ * Temporal typed edges: the relationship note shared by every surface that+ * shows a page summary (entity cards, context_pack, ambient turn context,+ * compiled context). One batched read of relationship state per call.+ *+ * "now: works_at widget-co (since 2025-03-01); ended: works_at acme-example+ * (2025-03-01)". Ended relationships the summary still names always appear+ * (with a stale-summary warning); other ended ones are capped at the latest+ * three. Only state relations (works_at, advises, …) take part, and a page+ * with no ended relationship gets no note.+ */++import {+ annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, TEMPORAL_LINK_TYPES, relationSemantics,+ type RelationshipStatus,+} from './link-validity.ts';+import { privateLinkOriginFilterFragment, privatePagesFilterFragment } from './search/private-visibility.ts';++const NOTE_ENDED_CAP = 3;++type RawExec = { executeRaw<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<R[]> };++export interface NoteSubject { slug: string; source_id: string; summary?: string | null }++interface NoteEdge { type: string; slug: string; title: string; status: RelationshipStatus | 'reference'; since: string | null; until: string | null }++export const relationshipNoteKey = (sourceId: string, slug: string): string => `${sourceId}\u0000${slug}`;++function renderNote(summary: string, edges: NoteEdge[]): string | undefined {+ const live = edges.filter(e => e.status === 'live' || e.status === 'disputed');+ const ended = edges.filter(e => e.status === 'ended' || e.status === 'ended_unknown_date');+ if (ended.length === 0) return undefined;+ const lower = summary.toLowerCase();+ const named = (e: NoteEdge) => {+ const title = e.title.trim().toLowerCase();+ return (title.length >= 3 && lower.includes(title)) || lower.includes(e.slug.split('/').pop()!.replace(/-/g, ' '));+ };+ const short = (e: NoteEdge) => e.slug.split('/').pop()!;+ const stale = ended.filter(named);+ const others = ended.filter(e => !named(e)).sort((a, b) => (b.until ?? '').localeCompare(a.until ?? '')).slice(0, NOTE_ENDED_CAP);+ const parts = [+ ...(live.length ? [`now: ${live.map(e => `${e.type} ${short(e)}${e.since ? ` (since ${e.since})` : ''}`).join(', ')}`] : []),+ `ended: ${[...stale, ...others].map(e => `${e.type} ${short(e)} (${e.until ?? 'date unknown'})`).join(', ')}`,+ ];+ if (stale.length) parts.push(`summary may be stale: it still names ${stale.map(short).join(', ')}`);+ return parts.join('; ');+}++/**+ * Notes keyed by `relationshipNoteKey(source_id, slug)`; subjects without an+ * ended relationship are absent. `excludePrivate` reads the world-scope state+ * and hides private targets and private-origin links, like remote graph reads.+ */+export async function loadRelationshipNotes(+ engine: RawExec,+ subjects: readonly NoteSubject[],+ opts: { excludePrivate: boolean },+): Promise<Map<string, string>> {+ const notes = new Map<string, string>();+ if (subjects.length === 0) return notes;+ const stateTypes = TEMPORAL_LINK_TYPES.filter(t => relationSemantics(t) === 'state');+ const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';+ const rows = await engine.executeRaw<{ from_slug: string; source_id: string; to_slug: string; to_title: string | null; link_type: string }>(+ `SELECT f.slug AS from_slug, f.source_id, t.slug AS to_slug, t.title AS to_title, l.link_type${TEMPORAL_LINK_SELECT_SQL}+ FROM links l+ JOIN pages f ON f.id = l.from_page_id+ JOIN pages t ON t.id = l.to_page_id+ ${temporalLinkJoinSql('l', opts.excludePrivate)}+ WHERE (f.source_id, f.slug) IN (SELECT s.source_id, s.slug FROM unnest($1::text[], $2::text[]) AS s(source_id, slug))+ AND l.link_type = ANY($3::text[]) AND lr_t.semantics = 'state' AND t.deleted_at IS NULL${privacy}`,+ [subjects.map(s => s.source_id), subjects.map(s => s.slug), stateTypes],+ );+ const bySubject = new Map<string, Map<string, NoteEdge>>();+ for (const raw of rows) {+ const r = annotateTemporalRow(raw);+ const key = relationshipNoteKey(r.source_id, r.from_slug);+ const edges = bySubject.get(key) ?? new Map<string, NoteEdge>();+ const last = r.stints?.[r.stints.length - 1];+ edges.set(`${r.link_type}\u0000${r.to_slug}`, {+ type: r.link_type, slug: r.to_slug, title: r.to_title ?? '', status: r.status,+ since: last?.from ?? null, until: last?.until ?? null,+ });+ bySubject.set(key, edges);+ }+ for (const s of subjects) {+ const key = relationshipNoteKey(s.source_id, s.slug);+ const edges = bySubject.get(key);+ const note = edges ? renderNote(s.summary ?? '', [...edges.values()]) : undefined;+ if (note) notes.set(key, note);+ }+ return notes;+}++/**+ * Ambient turn context: fold each page's note into its synopsis (world scope),+ * so the budget trimmer prices the rendered line. Fail-soft: an error leaves+ * the synopses unchanged.+ */+export async function appendRelationshipNotes(+ engine: RawExec,+ items: Array<{ slug: string; source_id: string; synopsis: string }>,+): Promise<void> {+ if (items.length === 0) return;+ const notes = await loadRelationshipNotes(engine, items.map(i => ({ slug: i.slug, source_id: i.source_id, summary: i.synopsis })), { excludePrivate: true })+ .catch(() => new Map<string, string>());+ for (const item of items) {+ const note = notes.get(relationshipNoteKey(item.source_id, item.slug));+ if (note) item.synopsis = item.synopsis ? `${item.synopsis} [${note}]` : `[${note}]`;+ }+}diff --git a/src/core/link-relationships.ts b/src/core/link-relationships.tsindex 57defc5dad..ad8fee393d 100644--- a/src/core/link-relationships.ts+++ b/src/core/link-relationships.ts@@ -17,6 +17,7 @@* as live, the same as an unrefreshed relationship).*/import { createHash } from 'node:crypto';+import type { BrainEngine } from './engine.ts';import { executeRawJsonb } from './sql-query.ts';import { privatePagesFilterFragment } from './search/private-visibility.ts';import {@@ -228,3 +229,20 @@ export async function staleRelationshipKeys(exec: RawExec, limit = 500): Promisereturn [...rows, ...orphans].map(r => ({ from_page_id: Number(r.from_page_id), to_page_id: Number(r.to_page_id), link_type: r.link_type }));}++/**+ * Extract-phase sweep: relationships whose state is missing, older than their+ * newest evidence, or orphaned converge here, bounded per cycle. Zero LLM.+ * Returns details for the phase result; never throws.+ */+export async function sweepStaleRelationships(engine: BrainEngine, limit = 2000): Promise<Record<string, unknown>> {+ try {+ const keys = await staleRelationshipKeys(engine, limit);+ if (!keys.length) return {};+ const { maintenanceTransaction } = await import('./persistence/attribution.ts');+ const changed = await maintenanceTransaction(engine, tx => refreshRelationships(tx, keys));+ return { relationships_swept: keys.length, relationships_changed: changed };+ } catch (e) {+ return { relationship_sweep_error: e instanceof Error ? e.message : String(e) };+ }+}diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 215d582795..4c342f4858 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -20,8 +20,9 @@* facts respect visibility for remote callers (world-only).*/-import { annotateTemporalRow, relationSemantics, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type TemporalAnnotation } from '../link-validity.ts';+import { annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type TemporalAnnotation } from '../link-validity.ts';import type { BrainEngine, FactRow } from '../engine.ts';+import { loadRelationshipNotes, relationshipNoteKey } from '../link-relationship-notes.ts';import { normalizeAlias } from '../search/alias-normalize.ts';import { slugify } from '../entities/resolve.ts';import { safeSynopsis } from '../context/retrieval-reflex.ts';@@ -351,7 +352,8 @@ async function assembleCard(...[...inCandidates].sort((a, b) => rank(a.status) - rank(b.status)),].slice(0, EDGE_CAP);const summary = safeSynopsis(row, { keepVisibility: remote ? ['world'] : ['private', 'world'] });- const relationshipNote = await buildRelationshipNote(engine, sourceId, summary, outCandidates).catch(() => undefined);+ const relationshipNote = await loadRelationshipNotes(engine, [{ slug: pageSlug, source_id: sourceId, summary }], { excludePrivate })+ .then(m => m.get(relationshipNoteKey(sourceId, pageSlug))).catch(() => undefined);// Open threads (best-effort v1): open-loop rows first (v0.47 — richest:// direction, due, loop_id), then active commitment facts NOT already@@ -439,40 +441,6 @@ async function assembleCard(};}-const NOTE_ENDED_CAP = 3;--/**- * "now: works_at widget-co (since 2025-03-01); ended: works_at acme-example- * (2025-03-01)". Ended relationships the summary still names always appear- * (with a stale-summary warning); other ended ones are capped at the latest- * three. Only state relations (works_at, advises, …) take part.- */-async function buildRelationshipNote(engine: BrainEngine, sourceId: string, summary: string, edges: EntityCardEdge[]): Promise<string | undefined> {- const state = edges.filter(e => relationSemantics(e.type) === 'state' && e.status);- if (state.length === 0) return undefined;- const live = state.filter(e => e.status === 'live' || e.status === 'disputed');- const ended = state.filter(e => e.status === 'ended' || e.status === 'ended_unknown_date');- if (ended.length === 0) return undefined;- const titles = new Map((await engine.executeRaw<{ slug: string; title: string | null }>(- `SELECT slug, title FROM pages WHERE source_id = $1 AND slug = ANY($2::text[])`, [sourceId, ended.map(e => e.slug)])).map(r => [r.slug, r.title ?? '']));- const lower = summary.toLowerCase();- const named = (e: EntityCardEdge) => {- const title = (titles.get(e.slug) ?? '').trim().toLowerCase();- const base = e.slug.split('/').pop()!.replace(/-/g, ' ');- return (title.length >= 3 && lower.includes(title)) || lower.includes(base);- };- const stale = ended.filter(named);- const others = ended.filter(e => !named(e)).sort((a, b) => (b.until ?? '').localeCompare(a.until ?? '')).slice(0, NOTE_ENDED_CAP);- const fmtLive = (e: EntityCardEdge) => `${e.type} ${e.slug.split('/').pop()}${e.since ? ` (since ${e.since})` : ''}`;- const fmtEnded = (e: EntityCardEdge) => `${e.type} ${e.slug.split('/').pop()} (${e.until ?? 'date unknown'})`;- const parts = [- ...(live.length ? [`now: ${live.map(fmtLive).join(', ')}`] : []),- `ended: ${[...stale, ...others].map(fmtEnded).join(', ')}`,- ];- if (stale.length) parts.push(`summary may be stale: it still names ${stale.map(e => e.slug.split('/').pop()).join(', ')}`);- return parts.join('; ');-}-/*** Near-miss suggestions on a total miss (E5 delight): keyword search top-N* with evidence-derived create_safety so a typo'd name becomes a next movediff --git a/test/link-temporal-reads.test.ts b/test/link-temporal-reads.test.tsindex 68b6f0073f..e169fcb03f 100644--- a/test/link-temporal-reads.test.ts+++ b/test/link-temporal-reads.test.ts@@ -14,6 +14,12 @@ import { resetGateway } from '../src/core/ai/gateway.ts';import { buildEntityCard } from '../src/core/verbs/entity-card.ts';import { renderCardLine } from '../src/core/context/turn-context.ts';import { buildRelationalArm } from '../src/core/search/relational-recall.ts';+import { appendRelationshipNotes, loadRelationshipNotes, relationshipNoteKey } from '../src/core/link-relationship-notes.ts';+import { compileView } from '../src/core/context/compile-view.ts';+import { loadSensitivityConfig } from '../src/core/context/sensitivity-scan.ts';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';setDefaultTimeout(60_000);let engine: PGLiteEngine;@@ -112,6 +118,26 @@ describe('entity cards and context_pack text', () => {});});+describe('relationship note on ambient and compiled context', () => {+ test('one batched loader; ambient synopses and compiled entries carry the note, world scope only', async () => {+ const notes = await loadRelationshipNotes(engine, [+ { slug: 'people/alice-example', source_id: 'default', summary: 'Alice is CTO of Acme.' },+ { slug: 'companies/widget-co', source_id: 'default', summary: 'Another company.' },+ ], { excludePrivate: true });+ expect(notes.get(relationshipNoteKey('default', 'people/alice-example'))).toContain('summary may be stale');+ expect(notes.has(relationshipNoteKey('default', 'companies/widget-co'))).toBe(false);++ const items = [{ slug: 'people/alice-example', source_id: 'default', synopsis: 'Alice is CTO of Acme.' }];+ await appendRelationshipNotes(engine, items);+ expect(items[0].synopsis).toMatch(/^Alice is CTO of Acme\. \[now: works_at widget-co .*ended: works_at acme-example \(2025-03-01\)/);++ const tmp = mkdtempSync(join(tmpdir(), 'temporal-compile-'));+ const scanConfig = loadSensitivityConfig({ workspaceRoot: tmp, blocklist: '', userPatternsPath: join(tmp, 'none.txt') });+ const { text } = await compileView({ engine, sourceId: 'default', target: 'claude-code', budget: 4000, scanConfig });+ expect(text).toContain('relationships: now: works_at widget-co');+ });+});+describe('relational search arm', () => {test('present tense asks for live relationships; "former" asks for ended ones', async () => {const now = await buildRelationalArm(engine, 'who works at acme-example', {});