Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: Time-Aware Recall & Activation Suite - usage-aware ranking, event-time recall, two-pass recovery (#73)
Sol Aitkenb16c37dc7e10
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex fbd12525..34fc6ad5 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.41.0",+ "version": "0.42.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 97d71dda..02716fea 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.41.0",+ "version": "0.42.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 88b8b302..1f0c914f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,70 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.42.0] - 2026-06-04++Time-Aware Recall & Activation Suite: ranking that reflects what the+agent actually keeps using, and time filters that respect when things+happened rather than when files were written. Recorded accesses+reinforce a per-document activation that decays by content-type+half-life (preferences and decisions never fade), habitual companions+boost each other through co-access edges, preference pages carry a+dream-stamped freshness trend that biases recall, `since`/`until`+filters obey declared `valid_from`/`valid_until` validity windows,+time-scoped traversal bridges in causes and consequences from a padded+event-time neighbourhood, and a zero-candidate evidence query runs one+broadened retry instead of dead-ending in an abstention. Everything is+deterministic, bounded, and explainable; a vault without the new data+ranks bit-identically. MCP tool count is unchanged (66).++### Added++- **Access-reinforced activation** (`Brain/search/activation/`).+ CLI/MCP searches record which documents they surfaced (one JSON file+ per access, query hashed, never raw text; `--no-record-access` /+ `record_access: false` opt out, cross-vault and cached queries never+ record); the derived activation state is a replayable fold, and a+ bounded `activation` ranking boost (cap 0.04) decays the stored+ strength by a content-type half-life table - preferences, decisions,+ and antipatterns never decay, projects ~120d, handoffs/sessions+ ~30d, notes 60d. Reinforcement is miss-driven: a query-cache hit+ returns early and records nothing. `o2b brain activation+ status|sweep` inspects and compacts the event store+ (`search_activation_enabled` is the kill switch).+- **Co-access reinforcement edges**. Documents habitually surfaced+ together gain pairwise counts in the same fold; when one appears in+ a candidate pool with its companions, each gains a bounded+ `co_access` boost (cap 0.03, pairs seen fewer than twice are noise).+- **Freshness-trend classification on preferences**. The dream refresh+ classifies every preference's evidence time distribution into+ `new | strengthening | stable | weakening | stale` and stamps+ `freshness_trend` into frontmatter; recall multiplies the relevance+ portion (strengthening 1.05, weakening 0.93, stale 0.85) with an+ explainable reason, and the belief-evolution envelope carries the+ live classification.+- **Event-time recall discipline**. Documents declaring `valid_from` /+ `valid_until` pass `since`/`until` filters by validity-window+ overlap - storage mtime is only the fallback, so an old file about a+ recent event is found and a fresh file about a closed-out past event+ is excluded. Unparseable values warn and fall back to mtime.+- **Temporal-bridge traversal**. With an active time range, link-graph+ traversal keeps an expansion document only when its event time falls+ within a padded neighbourhood of the window (default 7d) and decays+ its score by temporal proximity (`temporal_bridge` reason) - causes+ and consequences bridge in, arbitrary old neighbours do not.+- **Self-correcting two-pass recall**. In evidence-pack mode a+ zero-candidate first pass (implicit-AND too strict) triggers exactly+ one broadened OR retry; recovered results carry a `second_pass`+ reason and the envelope reports `secondPass: {triggered, reason,+ added}` (`search_two_pass_enabled` is the kill switch).++### Changed++- The Hermes plugin entrypoint dropped its file-path self-bootstrap:+ the upstream loader now registers the synthetic parent namespace for+ user-installed providers, so the root `__init__.py` is a plain+ relative re-export of `plugins/hermes`.+## [0.41.0] - 2026-06-04Agent Write Contract Suite: how external agents write into and@@ -4452,6 +4516,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.42.0]: https://github.com/itechmeat/open-second-brain/compare/v0.41.0...v0.42.0[0.41.0]: https://github.com/itechmeat/open-second-brain/compare/v0.40.0...v0.41.0[0.40.0]: https://github.com/itechmeat/open-second-brain/compare/v0.39.0...v0.40.0[0.39.0]: https://github.com/itechmeat/open-second-brain/compare/v0.38.0...v0.39.0diff --git a/README.md b/README.mdindex 04019ad6..ef87c267 100644--- a/README.md+++ b/README.md@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution).+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`).## CLI@@ -145,7 +145,7 @@ o2b vault profile switch work # Activate a named multi-vault profileo2b brain agent-query --agent claude --json # Source-agent provenance queryo2b brain agent-diff --mode diff --agent claude --agent codexo2b search "<query>" --evidence-pack # FTS5/hybrid search with matched/missing evidence-o2b search "<query>" --since 7d --until today # Time-scoped recall (mtime window)+o2b search "<query>" --since 7d --until today # Time-scoped recall (event-time validity window, mtime fallback)o2b search feedback --query "<q>" --result note.md --verdict up # Train learned recall weightso2b search weights --json # Inspect base + learned ranking weightso2b search focus set --query "current task" --path Notes/Projectdiff --git a/__init__.py b/__init__.pyindex 0a3cce83..1398d5e1 100644--- a/__init__.py+++ b/__init__.py@@ -3,69 +3,28 @@Hermes installs Git plugins by cloning the repository and treating therepository root as the plugin directory, so this file is the entry the gatewayloads first. The ``OpenSecondBrainMemoryProvider`` implementation and its-``register``/health surface live in ``plugins/hermes``.--Self-bootstrap loading------------------------This entrypoint loads the implementation package from ``plugins/hermes`` by-file path under a private, collision-free package name, with-``submodule_search_locations`` set so the implementation's own relative imports-(``from . import config``, ``from ._base import ...``) resolve against it. This-is the plugin's single, intentional, host-agnostic load path.--Owning the bootstrap is deliberate. A host runtime that imports the plugin-under a synthetic package without also registering that parent namespace cannot-load a provider written with ordinary relative or absolute imports -- the first-relative import raises ``ModuleNotFoundError`` for the missing parent. Hermes'-external memory-provider loader behaves exactly this way today (it imports-user-installed plugins as ``_hermes_user_memory.<name>`` without registering-``_hermes_user_memory``). Bootstrapping our own package sidesteps that entirely-and stays valid whether or not the host registers the parent, so the-implementation keeps its small single-responsibility modules instead of being-collapsed into one file to dodge the loader. ``OpenSecondBrainMemoryProvider``-is referenced below so Hermes' text-scan discovery heuristic still recognises-this file as a memory provider.+``register``/health surface live in ``plugins/hermes``; this module re-exports+them through an ordinary relative import.++The relative import is the whole integration. Hermes' external memory-provider+loader imports a user-installed plugin as ``_hermes_user_memory.<name>`` and+registers that synthetic parent namespace in ``sys.modules`` before executing+the plugin (hermes-agent PR #37366), so a provider written with plain relative+imports - including an implementation nested behind the ``plugins/`` namespace+directory - resolves without any loader workaround on the plugin side. The+``OpenSecondBrainMemoryProvider`` name appearing in this file also keeps+Hermes' text-scan discovery heuristic recognising it as a memory provider."""from __future__ import annotations-import importlib.util as _importlib_util-import os as _os-import sys as _sys--_IMPL_DIR = _os.path.join(- _os.path.dirname(_os.path.abspath(__file__)), "plugins", "hermes"+from .plugins.hermes import (+ OpenSecondBrainMemoryProvider,+ check_health,+ health,+ register,+ register_cli,)-_IMPL_PKG = "_osb_hermes_impl"---def _load_impl():- """Import ``plugins/hermes`` by file path under a private package name.-- Idempotent: a second import in the same process reuses the cached module,- so a host that loads this entrypoint more than once gets one implementation.- """- module = _sys.modules.get(_IMPL_PKG)- if module is not None:- return module- spec = _importlib_util.spec_from_file_location(- _IMPL_PKG,- _os.path.join(_IMPL_DIR, "__init__.py"),- submodule_search_locations=[_IMPL_DIR],- )- module = _importlib_util.module_from_spec(spec)- _sys.modules[_IMPL_PKG] = module- spec.loader.exec_module(module)- return module---_impl = _load_impl()--OpenSecondBrainMemoryProvider = _impl.OpenSecondBrainMemoryProvider-check_health = _impl.check_health-health = _impl.health-register = _impl.register-register_cli = _impl.register_cli__all__ = ["OpenSecondBrainMemoryProvider",diff --git a/docs/brainstorm/time-aware-recall-activation/cli-output/claude.md b/docs/brainstorm/time-aware-recall-activation/cli-output/claude.mdnew file mode 100644index 00000000..5313bc1a--- /dev/null+++ b/docs/brainstorm/time-aware-recall-activation/cli-output/claude.md@@ -0,0 +1,35 @@+### Variant 1: In-place layer extension+- **Approach**: Treat the six tasks as six surgical edits to the files they already name — `ranker.ts` gains an activation term computed from `usedCount` plus an access-time log; `belief-evolution.ts` emits a freshness-trend field; `time-range.ts`/`search.ts` swap `mtimeInRange` for a validity-window check; `traversal.ts` accepts temporal seeds; `evidence-pack.ts`'s abstention drives a re-query wrapper in `search.ts`. Co-access edges become a derived fold over the existing `Brain/search/feedback/` per-event JSON pattern, reusing the link-boost machinery. No new module; each scoring layer adds its own `reasons` entry behind a neutral default.+- **Trade-offs**:+ - Pro: smallest per-file diff, lowest blast radius, each task ships and tests independently within its own file.+ - Pro: trivially honors the neutral-default / bit-identical-when-absent rule layer by layer.+ - Pro: zero or one new MCP tool; mostly new CLI verbs + optional result fields.+ - Con: shared temporal concepts (decay curve, half-life table, days-since-access, validity resolution) get duplicated or re-derived across `ranker`, `belief-evolution`, `time-range`, and `traversal`.+ - Con: no single source of truth for "memory activation"; future tuning means touching many files; Task 1↔4 and Task 3↔5 parent/child coupling is implicit rather than expressed.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Unified temporal-recall engine (centralized logic, conventional storage)+- **Approach**: Introduce one core module (e.g. `src/core/search/activation/`) that owns the shared primitives: the content-type half-life table, ACT-R reactivation decay, the validity-window resolver, the freshness-trend classifier, and the co-access edge graph. State storage stays on the established patterns — access and co-access events are one-JSON-per-event files under `Brain/search/` with a replayable derived-cache fold (mirroring `feedback.ts`); freshness trend is computed from existing evidence events. The ranker calls a single composed `temporalScore(candidate, ctx)` hook (emitting `reasons`); `search.ts` gets a two-pass controller and routes time-range filtering and causal traversal through the module's window resolver so graph + temporal finally compose.+- **Trade-offs**:+ - Pro: single home for decay/half-life/validity/co-access — no duplication, consistent semantics, one place to tune and test the bi-temporal logic.+ - Pro: keeps OSB's conflict-free per-event-file + replayable-fold convention; no SQLite hot-path writes; determinism and O(candidates) preserved via in-memory edge/activation maps over the candidate set.+ - Pro: expresses the Task 1↔4 and Task 3↔5 relationships as shared primitives rather than implicit cross-file contracts.+ - Con: larger new surface and more upfront design than Variant 1; the six tasks become somewhat coupled through one module.+ - Con: a bug in the shared engine has wider reach than an isolated layer edit; needs careful neutral-default gating so the composed hook is inert when no data exists.+- **Complexity**: large+- **Risk**: medium++### Variant 3: SQLite event-sourced activation projection+- **Approach**: Push temporal state into the store. An additive migration (schema v6) adds append-only `access_events` and `coaccess_edges` tables plus a validity-window column and a materialized freshness-trend column on preference chunks. Activation, co-access, and trend become indexed SQL aggregates joined at the `hydrateChunks` stage; the ranker reads precomputed values off hydrated rows. Recall accesses and co-activation pairs are written to SQLite at recall time.+- **Trade-offs**:+ - Pro: strongest O(candidates) guarantee — activation/co-access are indexed lookups, not folds; telemetry and inspection come for free via SQL.+ - Pro: fits the "additive migration, inert until reindex" convention cleanly for the read path.+ - Con: writing access/co-access rows on the recall hot path adds write amplification and a determinism hazard, and diverges from the documented conflict-free per-vault-file storage pattern (the vault, not SQLite, is the source of truth).+ - Con: state lives in a derived DB rather than replayable vault files; rebuilding or auditing requires a reindex, and concurrent CLI/MCP readers complicate hot-path writes.+ - Con: heaviest migration and SQL surface of the three; freshness trend must be recomputed on reindex rather than read live.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 2+**Rationale**: The six tasks all manipulate the same handful of temporal primitives (decay, half-life, validity windows, access reinforcement), so a single core module eliminates the duplication and semantic drift that Variant 1 would scatter across `ranker`, `belief-evolution`, `time-range`, and `traversal`, while still letting each task land as a thin, neutral-default-gated layer. Unlike Variant 3 it keeps state in the conventional per-event-file + replayable-fold form and avoids hot-path SQLite writes, preserving the deterministic-core and conflict-free-write constraints and the O(candidates) budget via in-memory maps. It is the only variant that naturally lets graph traversal and temporal seeding compose (Task 5) and gives the two-pass controller (Task 6) a clean place to re-rank against shared activation logic.diff --git a/docs/brainstorm/time-aware-recall-activation/cli-output/prompt.md b/docs/brainstorm/time-aware-recall-activation/cli-output/prompt.mdnew file mode 100644index 00000000..4a750ffe--- /dev/null+++ b/docs/brainstorm/time-aware-recall-activation/cli-output/prompt.md@@ -0,0 +1,89 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Implement the "Time-Aware Recall & Activation Suite" for Open Second Brain: six related kanban tasks shipping as one release. All six upgrade the recall ranking / temporal layer.++## Task 1 (t_2bc79017, p4): Access-reinforced, type-aware activation decay in recall ranking++Each memory should carry a retrieval activation that decays toward a floor with days-since-access and is bumped (capped) on every recall access (ACT-R reactivation), plus a content-type-specific half-life table (e.g. preferences/decisions never decay, projects ~120d, handoffs ~30d). Today OSB recency is a single Weibull curve over file mtime (src/core/search/ranker.ts recencyBoost + src/core/search/recency.ts): a constantly-useful preference and an untouched note of equal age rank identically. usedCount is recorded in procedural-memory but unused in ranking. The activation signal must be deterministic and explainable (a `reasons` entry).++## Task 2 (t_ee09a6ce, p4): Freshness-trend classification on preferences folded into recall++Tag every preference with a computed freshness trend (new / strengthening / stable / weakening / stale) derived from the time-distribution of its applied/violated/outdated evidence events (src/core/brain/temporal/belief-evolution.ts collectEvidence has runningApplied/Violated/Outdated; stale-watch.ts has only a binary ageDays threshold). The trend should be a first-class computed field surfaced on temporal/brain surfaces AND bias recall ranking (down-rank weakening/stale preference pages, slightly up-rank strengthening ones).++## Task 3 (t_b7191486, p4): Event-time vs storage-time discipline in time-aware recall++OSB stores bi-temporal fields (valid_from / valid_until / recorded_at exist in temporal event types and as documented frontmatter keys) but time-range recall filters on chunk mtime only (src/core/search/search.ts mtimeInRange(h.mtime, timeRange) at the hydrate stage; time-range.ts parses since/until). Make the validity window the authority for time-aware recall: a document whose frontmatter declares valid_from/valid_until should be in/out of a since/until window based on event time, falling back to mtime when no validity fields exist. Never infer event dates from storage timestamps when explicit ones exist.++## Task 4 (t_c5ef25a3, p2, child of Task 1): Co-access reinforcement edges between co-retrieved memories++Record a co-activation signal: documents frequently surfaced together in the same retrieval gain a pairwise reinforcement edge, so recalling one boosts its habitual companions. Edges form automatically at recall time, bounded and deterministic. Today each chunk ranks independently and only author-written wikilinks feed the link boost.++## Task 5 (t_c3871f0c, p2, child of Task 3): Causal-temporal traversal reconstructing event stories from a time window++A bounded BFS over wikilink + timeline-adjacency edges seeded from a temporal window so "what happened around X" recall pulls in causes and consequences, not just notes dated inside the window. OSB has link-graph traversal (src/core/search/traversal.ts expandByTraversal, seeded from ranked hits), a TimelineIndex (src/core/brain/temporal/types.ts), and Weibull recency - but graph traversal and temporal filtering never compose.++## Task 6 (t_ef92dfdc, p3): Self-correcting two-pass recall: re-query on insufficient evidence++When the first recall pass yields insufficient evidence (the existing evidence-pack coverage / abstention signal in src/core/search/evidence-pack.ts fires), run a second broader retrieval pass with a relaxed semantic threshold and fallback query terms, merge with the original candidate pool, and re-rank - instead of returning an empty/low-coverage result. Deterministic trigger, bounded retry (one extra pass).++# Project context++Open Second Brain: TypeScript on Bun, SQLite (bun:sqlite + sqlite-vec), Markdown/Obsidian vault as source of truth. CLI (`o2b`) + MCP server + OpenClaw/Hermes plugin surfaces. v0.41.0, ~3760 tests, strict tsc, oxlint.++Recent commits:+c3a2fcc feat: Agent Write Contract Suite - write sessions, decision panel, backend boundary, shared namespace (#72)+7733f20 feat: Project History Suite - git history memory, ADR mining, architecture notes, query telemetry (#71)+8e8c0bc feat: Memory Observability Suite - versioned continuity contract, lazy telemetry, ATOF/ATIF export, recall benchmark (#70)+eb56c9f feat: Workspace Insight Suite - project pointers, cross-vault recall, trigger queue, proactive synthesis (#69)+707197a feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)++Related files:+- src/core/search/ranker.ts - pure ranking fn: normalized BM25 + cosine + link/tag boost + Weibull recency + tier multiplier + entity boost + session focus; explainable `reasons` array; weightProfile multipliers (intent x learned weights)+- src/core/search/recency.ts - pure weibullDecay(ageDays, {shape, scale, amplitude})+- src/core/search/search.ts - orchestrator: keyword+semantic lanes, hydrate, time-range filter (mtime), entity expansion, MMR, traversal, property/visibility filters, evidence pack, query cache (skipped when timeRange set)+- src/core/search/time-range.ts - parseTimePoint/resolveTimeRange/mtimeInRange (pure, injected clock)+- src/core/search/traversal.ts - pure expandByTraversal (hop decay, caps); search.ts applyTraversal fetches adjacency level-by-level+- src/core/search/feedback.ts - recall feedback events, one JSON file per event under Brain/search/feedback/, learned weights = pure fold, derived cache file+- src/core/search/evidence-pack.ts - coverage report, abstention, completeness verdict+- src/core/search/schema.ts - SQLite migrations v1-v5 (additive ALTER/CREATE, LATEST_SCHEMA_VERSION=5); store.ts owns the connection+- src/core/search/store.ts - all SQL; hydrateChunks, inboundLinkSources, outboundLinkTargets, chunkEntityMatches, semanticTopK+- src/core/search/property-filter.ts - post-FTS frontmatter filter via injected reader+- src/core/brain/temporal/types.ts - TemporalEvent (validFrom/validUntil/recordedAt), TimelineIndex, TimelineWindow+- src/core/brain/temporal/belief-evolution.ts - collectEvidence with runningApplied/Violated/Outdated per event+- src/core/brain/temporal/stale-watch.ts - binary ageDays threshold scan+- src/core/brain/page-meta/tier.ts - PageTier + tierWeight multiplier+- src/cli/brain/verbs/ + src/mcp/brain-tools.ts - CLI/MCP surfaces (65 MCP tools; registry guard caps tool count growth and description length <= 300 chars)++Conventions:+- Deterministic core: no LLM calls in src/core; injected clocks (nowMs / now options) for all time-dependent logic; pure functions preferred, I/O at orchestrator edges+- Conflict-free vault writes: one small JSON/md file per event (Brain/inbox/, Brain/search/feedback/ pattern); derived caches are replayable folds+- Backward compatibility: absent config/data must keep ranking bit-identical to prior behaviour (the "neutral default" rule seen in tier, entity, weightProfile, RRF layers)+- SQLite migrations are additive; new columns/tables default to inert until a reindex populates them+- Explainable recall: every scoring layer that fires must surface a `reasons` entry+- Every feature lands with bun tests; CLI verbs + MCP tools updated together; MCP tool budget guarded (prefer extending existing tools with ops over adding many new tools)++Constraints:+- Do not change existing public APIs incompatibly (CLI flags, MCP tool contracts, search result shape may gain optional fields only)+- No new external dependencies+- No LLM calls anywhere in the new code (deterministic suite)+- Keep the per-query hot path fast: activation/co-access lookups must be O(candidates), not O(vault)+- MCP tool count growth must stay minimal (0-1 new tools; prefer ops on existing tools / new CLI verbs)++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/time-aware-recall-activation/design.md b/docs/brainstorm/time-aware-recall-activation/design.mdnew file mode 100644index 00000000..c9f768ae--- /dev/null+++ b/docs/brainstorm/time-aware-recall-activation/design.md@@ -0,0 +1,81 @@+# Time-Aware Recall & Activation Suite - usage-aware, event-time-correct recall++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain ranks every candidate with a single Weibull curve over file mtime: a constantly-recalled preference and an untouched note of equal age rank identically, a confirmed rule decays at the same rate as throwaway prose, and `since`/`until` filters confuse storage time with event time - the largest LongMemEval failure category. Recall also treats each chunk independently (no notion that two memories are habitually used together) and dead-ends on low-coverage queries instead of broadening once and retrying.++## Scope++- **Activation kernel** (`src/core/search/activation/`): pure ACT-R-style decay math with a content-type half-life table (preferences/decisions never decay; projects ~120d; handoffs/sessions ~30d; notes 60d), access-event recording, a replayable fold into a derived activation state, and a bounded sweep. (t_2bc79017)+- **Activation ranking layer**: bounded `activation` boost in the ranker, surfaced as a `reasons` entry; access recording happens at the CLI/MCP orchestrator edge, never inside the pure core by default. (t_2bc79017)+- **Co-access reinforcement**: pairwise co-retrieval counts derived from the same access events; companions of a strong hit gain a bounded `co_access` boost. (t_c5ef25a3)+- **Freshness-trend classifier** (`src/core/brain/temporal/freshness-trend.ts`): pure classification of every preference into `new | strengthening | stable | weakening | stale` from the time distribution of its evidence events; surfaced in the belief-evolution envelope, stamped into preference frontmatter by the dream refresh pass. (t_ee09a6ce)+- **Trend ranking bias**: preference pages carrying a stamped `freshness_trend` get a bounded multiplier (strengthening 1.05, weakening 0.93, stale 0.85) on the relevance portion, with a `reasons` entry. (t_ee09a6ce)+- **Event-time discipline** (`src/core/search/validity.ts`): when a document declares `valid_from` / `valid_until` frontmatter, the `since`/`until` filter tests the validity window (interval overlap); mtime stays the fallback for documents without validity fields. (t_b7191486)+- **Temporal-bridge traversal**: when a time range is active, traversal expansion docs are kept only within a padded event-time neighbourhood of the window and scored with temporal-proximity decay, labelled `temporal_bridge` - causes and consequences, not arbitrary leakage. (t_c3871f0c)+- **Two-pass recall**: in evidence-pack mode, an abstention/low-IDF-coverage verdict triggers exactly one broader second pass (uncovered rare terms OR'd onto the query, larger overfetch), merged and re-ranked, reported in the envelope. (t_ef92dfdc)+- **Surfaces**: `o2b brain activation status|sweep` CLI verb; `--no-record-access` search flag; optional `record_access` arg on the `brain_search` MCP tool. MCP tool count stays at 66.++## Out of scope++- LLM-based anything: the whole suite is deterministic (no model calls, injected clocks).+- SQLite schema changes: activation/co-access state lives in vault files (conflict-free one-file-per-event + replayable fold), not in the search index.+- Per-memory importance/valence fields (YantrikDB-style) - only access reinforcement and type half-life ship now.+- Spreading-activation scoring inside the timeline index; temporal-bridge traversal composes the existing wikilink adjacency only.+- Note-level contradiction detection, claim slots, and the rest of the entity-truth cluster (separate suite).+- Changing `select-events` filtering semantics in brain/temporal (documented as a known boundary; search-side discipline is the contract here).++## Chosen approach++Consultant Variant 2 (unified temporal-recall engine) with two containment refinements:++1. **Recording stays at the orchestrator edge.** The pure `search()` core never writes by default; CLI/MCP surfaces pass `recordAccess: true` explicitly. A cached query result does not record. This keeps the read path deterministic and tests hermetic.+2. **The freshness-trend classifier lives in `src/core/brain/temporal/`**, not in the search module: it is a preference-evidence concept consumed by belief-evolution and the dream refresh. Search consumes only the stamped frontmatter field through the existing injected-reader pattern - no brain->search import cycle.++Everything time-and-usage shaped in the search layer (half-life table, decay, activation fold, co-access graph, validity resolver, temporal-bridge math) lives under `src/core/search/activation/` + two sibling pure modules, with one storage convention: one JSON file per access event under `Brain/search/activation/`, a derived `Brain/search/activation-state.json` cache that is a pure fold of the retained events, and a deterministic sweep.++## Design decisions++- **Activation math (plur/ACT-R approximation):** per path, `strength` += 0.1 per access (capped 1.0); effective activation = `strength * 2^(-daysSinceLastAccess / halfLife(type))`. Infinite half-life types (preference, decision, antipattern) never decay. Type resolves from frontmatter `kind:` with path-prefix fallbacks (`Brain/preferences/` -> preference) and default `note`.+- **Bounded boosts, neutral defaults:** activation boost caps at 0.04, co-access at 0.03 - re-rankers, never floaters. A vault with no activation events ranks bit-identically to v0.41.0 (the tier/entity/RRF precedent). Kill switch: `recall.activationEnabled` (default true; boost is zero without data anyway).+- **Access event shape:** one file `<ts>-<hash>.json` per recorded search: query hash (FNV-1a, never raw text), top surfaced doc paths (cap 10). Co-access pairs derive from the same files - no second event stream.+- **Sweep semantics are part of the model:** events older than 90 days or beyond the 5000 most recent are dropped by sweep; because activation decays toward the type floor anyway, dropping old events approximates the limit rather than corrupting it. The derived state file is a cache - deleting it loses nothing.+- **Trend windows:** recent 30d vs prior 30d evidence counts; `stale` when last evidence is older than 60d; `new` when the preference is younger than 14d with no prior-window evidence; strengthening/weakening compare windowed applied/violated; else stable. Pure function over `(events, nowMs)`.+- **Trend is stamped, not recomputed per query:** the dream refresh pass writes `freshness_trend` into preference frontmatter (Hindsight's "refreshed on each consolidation" contract); ranking reads it via the injected frontmatter reader (O(candidates)); belief-evolution computes it live for its envelope. One classifier, two call sites.+- **Validity overlap semantics:** a document with `valid_from`/`valid_until` passes a `since`/`until` filter iff the validity interval intersects the query window; a document with only one bound treats the other side as open. Bare ISO dates resolve in UTC via the existing `time-range.ts` rules. Storage time is never consulted when explicit event time exists.+- **Temporal bridge pad:** expansion docs must carry an event time (validity start, else mtime) within `windowPad` (default 7d) of the query window; score multiplies by `hopDecay^hop * proximityDecay(deltaDays)`. Off when no time range is active - plain traversal is untouched.+- **Two-pass trigger is the existing signal:** `abstention !== null` or `idfWeightedCoverage < 0.5` from the evidence pack. The second pass ORs uncovered rare terms onto the FTS query, doubles the overfetch, merges pools (first-pass score wins on dupes), re-ranks once, and reports `secondPass: { triggered, reason, added }`. Exactly one retry, config kill switch `recall.twoPassEnabled` (default true; only fires in evidence-pack mode where the trigger exists).+- **No new MCP tool:** `brain_search` gains the optional `record_access` boolean; activation maintenance is CLI-only (`o2b brain activation`). The registry-guard budget stays at 66 tools.++## File changes++New:+- `src/core/search/activation/types.ts`, `decay.ts`, `store.ts` (events + fold + sweep), `index.ts`+- `src/core/search/validity.ts`+- `src/core/search/temporal-bridge.ts`+- `src/core/brain/temporal/freshness-trend.ts`+- `src/cli/brain/verbs/activation.ts`+- tests: `tests/core/search/activation-*.test.ts`, `tests/core/search/validity.test.ts`, `tests/core/search/temporal-bridge.test.ts`, `tests/core/search/two-pass.test.ts`, `tests/core/brain/freshness-trend.test.ts`, `tests/cli/brain-activation.test.ts`, `tests/e2e/time-aware-recall.integration.test.ts`++Modified:+- `src/core/search/ranker.ts` (activation + co-access + trend inputs, reasons)+- `src/core/search/search.ts` (activation lookup, recordAccess, validity filter, temporal bridge, two-pass controller)+- `src/core/search/types.ts` (ResolvedRecallConfig + envelope fields)+- `src/core/search/index.ts` (`resolveSearchConfig`: new recall keys `search_activation_enabled`, `search_two_pass_enabled`)+- `src/core/brain/temporal/belief-evolution.ts` (trend in envelope)+- `src/core/brain/dream.ts` (stamp freshness_trend during refresh)+- `src/cli/brain/verbs/index.ts`, `brain.ts`, `help-text.ts`, `command-manifest.ts` (activation verb)+- CLI search surface (record-access flag), `src/mcp/brain-tools.ts` (record_access arg)+- docs: README, CHANGELOG, docs/cli-reference.md, docs/how-it-works.md++## Risks and open questions++- **Hot-path file reads:** the derived activation state is one JSON read per query (cached per call); co-access lookups are map hits. Validity/trend reads reuse the per-query frontmatter reader cache the property filter already uses - verify it is shared, not re-parsed.+- **Query cache interaction:** activation changes over time, so cached results could go stale; mitigated because the cache key already includes a learned-weights fingerprint - add an activation-state fingerprint the same way.+- **Trend stamping touches dream:** keep the stamp additive (absent field = neutral) so old vaults and dry runs stay byte-identical.+- **Traversal leakage today:** current behaviour may already let out-of-window expansion docs in; the temporal bridge makes that explicit and bounded - regression-test both modes.+- **Two-pass result shape:** merging pools must preserve determinism (stable tie-breaks) and never exceed the configured limit.diff --git a/docs/brainstorm/time-aware-recall-activation/plan.md b/docs/brainstorm/time-aware-recall-activation/plan.mdnew file mode 100644index 00000000..71cf0c76--- /dev/null+++ b/docs/brainstorm/time-aware-recall-activation/plan.md@@ -0,0 +1,63 @@+# Time-Aware Recall & Activation Suite - implementation plan++## Tasks++### Task 1: Activation kernel (pure math)+- **Files**: `src/core/search/activation/types.ts`, `src/core/search/activation/decay.ts`, `tests/core/search/activation-decay.test.ts`+- **Acceptance**: pure tests for the half-life table (infinite for preference/decision/antipattern, 120d project, 30d handoff/session, 60d default), strength bump (+0.1 capped at 1.0), effective activation `strength * 2^(-days/halfLife)`, type resolution from `kind:` frontmatter with path-prefix fallback, and injected-clock determinism.+- **Depends on**: none++### Task 2: Activation store (events + fold + sweep)+- **Files**: `src/core/search/activation/store.ts`, `src/core/search/activation/index.ts`, `tests/core/search/activation-store.test.ts`+- **Acceptance**: recording one access event writes one `<ts>-<hash>.json` under `Brain/search/activation/` (query hash + capped doc paths, idempotent re-record); the fold derives per-path `{strength, lastAccessAt, accessCount}` and bounded co-access pair counts deterministically (order-insensitive); the derived `activation-state.json` is replayable (delete + refold = identical); sweep drops events beyond 90d/5000 and malformed files never break the fold.+- **Depends on**: Task 1++### Task 3: Activation ranking layer+- **Files**: `src/core/search/ranker.ts`, `src/core/search/search.ts`, `src/core/search/types.ts`, `src/core/search/index.ts` (resolveSearchConfig), `tests/core/search/activation-ranking.test.ts`+- **Acceptance**: candidates with activation state gain a capped (0.04) `activation: 0.0xx` reason; a vault without events ranks bit-identically to before; `recordAccess: true` records the top surfaced paths after ranking (never affecting the current query, never on cache hits); query-cache key gains an activation-state fingerprint; `recall.activationEnabled` kill switch works.+- **Depends on**: Task 2++### Task 4: Co-access companion boost+- **Files**: `src/core/search/ranker.ts`, `src/core/search/search.ts`, `tests/core/search/co-access.test.ts`+- **Acceptance**: when a candidate is a frequent co-access companion of a higher-ranked candidate in the same result set, it gains a capped (0.03) `co_access: 0.0xx` reason; pairs below a minimum count threshold contribute nothing; no events = bit-identical ranking.+- **Depends on**: Task 3++### Task 5: Freshness-trend classifier + surfaces+- **Files**: `src/core/brain/temporal/freshness-trend.ts`, `src/core/brain/temporal/belief-evolution.ts`, `src/core/brain/dream.ts`, `tests/core/brain/freshness-trend.test.ts`+- **Acceptance**: pure classifier maps evidence-event time distributions to `new|strengthening|stable|weakening|stale` per the documented windows; belief-evolution envelope carries `freshnessTrend`; dream refresh stamps `freshness_trend` into preference frontmatter additively (dry-run untouched, absent field elsewhere = neutral).+- **Depends on**: none++### Task 6: Trend ranking multiplier+- **Files**: `src/core/search/ranker.ts`, `src/core/search/search.ts`, `tests/core/search/trend-ranking.test.ts`+- **Acceptance**: preference pages stamped `weakening`/`stale` are demoted (0.93/0.85 on the relevance portion), `strengthening` boosted (1.05), with a `freshness_trend` reason; unstamped pages and non-preference paths are untouched (bit-identical).+- **Depends on**: Task 5++### Task 7: Event-time validity filter+- **Files**: `src/core/search/validity.ts`, `src/core/search/search.ts`, `tests/core/search/validity.test.ts`+- **Acceptance**: documents declaring `valid_from`/`valid_until` pass a `since`/`until` filter by interval overlap (open sides honoured, UTC, bad values fall back to mtime with a warning); documents without validity fields keep mtime semantics byte-identically; storage time never consulted when event time exists.+- **Depends on**: none++### Task 8: Temporal-bridge traversal+- **Files**: `src/core/search/temporal-bridge.ts`, `src/core/search/search.ts`, `tests/core/search/temporal-bridge.test.ts`+- **Acceptance**: with an active time range, traversal expansion docs outside the padded event-time neighbourhood are dropped; in-pad docs score `parentScore * hopDecay^hop * proximityDecay(deltaDays)` with a `temporal_bridge` reason; no time range = existing traversal behaviour bit-identical.+- **Depends on**: Task 7++### Task 9: Two-pass recall controller+- **Files**: `src/core/search/search.ts`, `src/core/search/types.ts`, `src/core/search/evidence-pack.ts` (envelope field), `tests/core/search/two-pass.test.ts`+- **Acceptance**: in evidence-pack mode an abstention or `idfWeightedCoverage < 0.5` triggers exactly one broader pass (uncovered rare terms OR'd, doubled overfetch), merged deterministically (first-pass score wins on dupes, stable tie-breaks, limit respected), reported as `secondPass: {triggered, reason, added}`; high-coverage queries never trigger; `recall.twoPassEnabled: false` disables.+- **Depends on**: none++### Task 10: CLI + MCP surfaces+- **Files**: `src/cli/brain/verbs/activation.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/brain.ts`, `src/cli/brain/help-text.ts`, `src/cli/command-manifest.ts`, CLI search flag site, `src/mcp/brain-tools.ts`, `tests/cli/brain-activation.test.ts`, `tests/mcp/mcp.test.ts`+- **Acceptance**: `o2b brain activation status|sweep` round-trips with `--json` envelopes and exit codes (0 ok / 2 usage); search surfaces accept `--no-record-access`; `brain_search` accepts optional `record_access`; MCP tool count stays 66 and registry-guard passes.+- **Depends on**: Tasks 3, 4++### Task 11: End-to-end integration test+- **Files**: `tests/e2e/time-aware-recall.integration.test.ts`+- **Acceptance**: one vault exercises the whole suite: repeated recalls raise activation and co-access of a working set; a preference stamped `weakening` ranks below its prior position; a `valid_from` document is found by event-time window and excluded by storage-time expectations; a low-coverage query triggers the second pass and surfaces a previously-missed record.+- **Depends on**: Tasks 1-10++### Task 12: Docs+- **Files**: `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/how-it-works.md`+- **Acceptance**: CHANGELOG `[0.42.0]` entry (4 Added bullets + compare link); README capability paragraph; CLI reference for the activation verb and search flags; how-it-works section on activation/event-time/two-pass semantics.+- **Depends on**: Tasks 1-11diff --git a/docs/brainstorm/time-aware-recall-activation/variants.md b/docs/brainstorm/time-aware-recall-activation/variants.mdnew file mode 100644index 00000000..f1cc0581--- /dev/null+++ b/docs/brainstorm/time-aware-recall-activation/variants.md@@ -0,0 +1,50 @@+# Time-Aware Recall & Activation Suite - variant audit trail++Consultant: Claude Code (`claude -p`), prompt in `cli-output/prompt.md`, raw output in `cli-output/claude.md`. Fallback (Codex) not needed: the primary returned three parseable variants plus a recommendation.++## Variant 1: In-place layer extension++- **Approach**: Six surgical edits to the files the tasks already name - `ranker.ts` gains an activation term computed from `usedCount` plus an access-time log; `belief-evolution.ts` emits a freshness-trend field; `time-range.ts`/`search.ts` swap `mtimeInRange` for a validity-window check; `traversal.ts` accepts temporal seeds; `evidence-pack.ts`'s abstention drives a re-query wrapper in `search.ts`. Co-access edges become a derived fold over the existing `Brain/search/feedback/` per-event JSON pattern, reusing the link-boost machinery. No new module; each scoring layer adds its own `reasons` entry behind a neutral default.+- **Trade-offs**:+ - Pro: smallest per-file diff, lowest blast radius, each task ships and tests independently within its own file.+ - Pro: trivially honors the neutral-default / bit-identical-when-absent rule layer by layer.+ - Pro: zero or one new MCP tool; mostly new CLI verbs + optional result fields.+ - Con: shared temporal concepts (decay curve, half-life table, days-since-access, validity resolution) get duplicated or re-derived across `ranker`, `belief-evolution`, `time-range`, and `traversal`.+ - Con: no single source of truth for "memory activation"; future tuning means touching many files; Task 1<->4 and Task 3<->5 parent/child coupling is implicit rather than expressed.+- **Complexity**: medium+- **Risk**: low++## Variant 2: Unified temporal-recall engine (centralized logic, conventional storage)++- **Approach**: One core module (e.g. `src/core/search/activation/`) owns the shared primitives: the content-type half-life table, ACT-R reactivation decay, the validity-window resolver, the freshness-trend classifier, and the co-access edge graph. State storage stays on the established patterns - access and co-access events are one-JSON-per-event files under `Brain/search/` with a replayable derived-cache fold (mirroring `feedback.ts`); freshness trend is computed from existing evidence events. The ranker calls a single composed `temporalScore(candidate, ctx)` hook (emitting `reasons`); `search.ts` gets a two-pass controller and routes time-range filtering and causal traversal through the module's window resolver so graph + temporal finally compose.+- **Trade-offs**:+ - Pro: single home for decay/half-life/validity/co-access - no duplication, consistent semantics, one place to tune and test the bi-temporal logic.+ - Pro: keeps the conflict-free per-event-file + replayable-fold convention; no SQLite hot-path writes; determinism and O(candidates) preserved via in-memory edge/activation maps over the candidate set.+ - Pro: expresses the Task 1<->4 and Task 3<->5 relationships as shared primitives rather than implicit cross-file contracts.+ - Con: larger new surface and more upfront design than Variant 1; the six tasks become somewhat coupled through one module.+ - Con: a bug in the shared engine has wider reach than an isolated layer edit; needs careful neutral-default gating so the composed hook is inert when no data exists.+- **Complexity**: large+- **Risk**: medium++## Variant 3: SQLite event-sourced activation projection++- **Approach**: Push temporal state into the store. An additive migration (schema v6) adds append-only `access_events` and `coaccess_edges` tables plus a validity-window column and a materialized freshness-trend column on preference chunks. Activation, co-access, and trend become indexed SQL aggregates joined at the `hydrateChunks` stage; the ranker reads precomputed values off hydrated rows. Recall accesses and co-activation pairs are written to SQLite at recall time.+- **Trade-offs**:+ - Pro: strongest O(candidates) guarantee - activation/co-access are indexed lookups, not folds; telemetry and inspection come for free via SQL.+ - Pro: fits the "additive migration, inert until reindex" convention cleanly for the read path.+ - Con: writing access/co-access rows on the recall hot path adds write amplification and a determinism hazard, and diverges from the documented conflict-free per-vault-file storage pattern (the vault, not SQLite, is the source of truth).+ - Con: state lives in a derived DB rather than replayable vault files; rebuilding or auditing requires a reindex, and concurrent CLI/MCP readers complicate hot-path writes.+ - Con: heaviest migration and SQL surface of the three; freshness trend must be recomputed on reindex rather than read live.+- **Complexity**: large+- **Risk**: high++## Consultant recommendation: Variant 2++**Rationale (verbatim)**: The six tasks all manipulate the same handful of temporal primitives (decay, half-life, validity windows, access reinforcement), so a single core module eliminates the duplication and semantic drift that Variant 1 would scatter across `ranker`, `belief-evolution`, `time-range`, and `traversal`, while still letting each task land as a thin, neutral-default-gated layer. Unlike Variant 3 it keeps state in the conventional per-event-file + replayable-fold form and avoids hot-path SQLite writes, preserving the deterministic-core and conflict-free-write constraints and the O(candidates) budget via in-memory maps. It is the only variant that naturally lets graph traversal and temporal seeding compose (Task 5) and gives the two-pass controller (Task 6) a clean place to re-rank against shared activation logic.++## Orchestrator decision: Variant 2, with two containment refinements++Accepted the recommendation. Refinements (rationale in `design.md`):++1. **Recording at the orchestrator edge.** The consultant's engine would let `search()` itself persist access events; that makes a read path write and breaks test hermeticity. Instead the pure core records only when the surface passes `recordAccess: true`, cache hits never record, and the current query's own ranking is never affected by its own recording.+2. **Freshness-trend classifier placed in `src/core/brain/temporal/`,** not inside the search module. It is a preference-evidence concept consumed by belief-evolution and the dream refresh; search consumes only the stamped `freshness_trend` frontmatter field through the existing injected-reader pattern. This keeps the brain temporal surfaces from importing search code and keeps the classifier testable against `TimelineIndex` fixtures.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 6d887551..f6c736ef 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -172,6 +172,15 @@ o2b brain panel open <topic...> [--personas a,b,c] [--target T] [-Envelopes are stable JSON with `--json` (`status`, `step`, `prompt`, `errors`, `attempts_left`, `expires_at`, `target_path`, `existing`) - the same contract the MCP `brain_write_session` tool returns. `create` intent never overwrites an existing target; `merge` appends a session-stamped delimited section; reserved namespaces (`Brain/preferences/`, `Brain/log/`, `Brain/_brain.yaml`, dot-stores) are refused. The Brain never generates content - the calling agent does.+### Recall activation (since v0.42.0)++```text+o2b brain activation status [--top N] - folded activation state: event/path/co-access counts plus the strongest paths+ sweep [--retention-days N] [--max-events N] - drop access events outside the retention window or beyond the newest-N cap and refold (--max-events 0 clears every retained event)+```++CLI and MCP searches record which documents they surfaced as one JSON event per access under `Brain/search/activation/` (query hashed, never raw text). `o2b search <query> --no-record-access` suppresses recording for one query; the MCP `brain_search` tool accepts `record_access: false`. Cross-vault (`--global`) and query-cache-hit searches never record, so reinforcement is miss-driven. The derived `Brain/search/activation-state.json` is a replayable fold - deleting it loses nothing. `search_activation_enabled: false` disables both the boost and recording; `search_two_pass_enabled: false` disables the evidence-pack broadened retry.+## Vault scopeSingle exclusion policy for every vault walker.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 6d1832d6..64410763 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -945,6 +945,18 @@ The decision panel is the first consumer of the kernel: persona steps (operator-Two adjacent seams complete the contract. The memory backend boundary (`memory_backend` config key) routes memory import through a format-adapter registry - the Claude Code adapter is the default and byte-identical to the pre-seam behavior, and a second runtime becomes one self-contained module. The shared namespace (`shared_namespace` config key) mirrors explicit remember-writes into a second vault after the primary write succeeds, attributed by agent and origin vault; mirroring is fail-soft by contract, so a broken shared vault degrades to a reported `mirror: "failed"` and the primary write never notices.+## Time-aware recall and activation (since v0.42.0)++Recency used to be one Weibull curve over file mtime: a constantly-useful preference and an untouched note of equal age ranked identically, and `since`/`until` filters confused when a file was written with when its content happened. The Time-Aware Recall & Activation Suite splits those concerns into deterministic, bounded layers.++**Activation.** Every CLI/MCP search that surfaces results records one small JSON event under `Brain/search/activation/` - the query as an FNV-1a hash (never raw text) plus the surfaced paths. The derived activation state is a pure fold over the retained events (delete it, refold, identical), and at query time each candidate's stored strength decays by a content-type half-life: preferences, decisions, and antipatterns never decay, projects fade over ~120 days, handoffs and sessions over ~30, plain notes over 60. The result is a capped `activation` boost that keeps habitually-recalled memories hot without ever floating an irrelevant one. Recording happens AFTER ranking at the orchestrator edge - a query is never affected by its own recording, cache hits never record, and a vault with no events ranks bit-identically to before. Documents repeatedly surfaced together also accumulate co-access pairs in the same fold; when companions land in one candidate pool they reinforce each other with a capped `co_access` boost (single co-occurrences are noise and ignored).++**Freshness trends.** The dream refresh classifies every preference's evidence time distribution - recent 30 days against the prior 30 - into `new | strengthening | stable | weakening | stale` and stamps the label into frontmatter. Recall reads the stamp off preference pages and multiplies the relevance portion (strengthening 1.05, weakening 0.93, stale 0.85), so a rule that keeps earning `applied` events outranks one drifting toward retirement. The belief-evolution envelope carries the live classification with the windowed counts.++**Event time over storage time.** A document declaring `valid_from` / `valid_until` passes a `since`/`until` filter when its validity interval OVERLAPS the query window - storage mtime is only the fallback for documents without event time. An old file describing yesterday's migration window is found by `--since 7d`; a freshly-synced file describing a long-closed event is not. With a time range active, link-graph traversal applies the same discipline: an expansion document bridges in only when its event time falls within a padded neighbourhood of the window (default 7 days), scored by temporal proximity with a `temporal_bridge` reason - causes and consequences, not arbitrary link leakage.++**Two-pass recovery.** Keyword matching is implicit-AND, so a multi-term evidence query whose terms live in different documents can return nothing. In evidence-pack mode that dead end now triggers exactly one broadened retry - the first significant term stays the base group, the rest OR in as alternatives - and the recovered results flow through the normal ranking and a recomputed evidence pack, labelled `second_pass` with a `secondPass` envelope report. Plain searches never broaden; `search_two_pass_enabled: false` turns the retry off entirely.+## Safety propertiesThese are invariants of the system, not configuration to enable.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 00044276..3fcb34ee 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.41.0",+ "version": "0.42.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 43e80899..74520c2e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.41.0",+ "version": "0.42.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex c4ea9af2..41f6b6e9 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.41.0"+version: "0.42.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex b12f1a25..6035141e 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.41.0",+ "version": "0.42.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex c4ea9af2..41f6b6e9 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.41.0"+version: "0.42.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex d39a9a8d..8d92973e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.41.0"+version = "0.42.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex fd1a743d..61ccca65 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -32,6 +32,7 @@ import {cmdBrainWatchdog,cmdBrainHealth,cmdBrainHistory,+ cmdBrainActivation,cmdBrainAudit,cmdBrainMorningBrief,cmdBrainCodec,@@ -164,6 +165,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainHealth(rest);case "history":return await cmdBrainHistory(rest);+ case "activation":+ return await cmdBrainActivation(rest);case "audit":return await cmdBrainAudit(rest);case "morning-brief":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 92f70919..0ba680c5 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -39,6 +39,7 @@ Brain verbs (observing memory):watchdog Probe Brain health and plan safe recovery (--remediate, --restore, --force-restore)health Semantic-health report: contradictions, concept gaps, stale claimshistory Render a preference's edit-history timeline+ activation Activation event store: status and sweepaudit Render a preference's full mutation audit trailmorning-brief Session-start summary: top prefs, open questions, recent notescodec Compress/expand session prose with the deterministic codec (stdin/--in)@@ -207,6 +208,12 @@ export const VERB_HELP: Record<string, string> = {"usage: o2b brain history <slug> [--vault <path>] [--json]\n" +"Render a preference's edit-history timeline (one entry per content\n" +"mutation: principle/scope/status before -> after). Read-only.\n",+ activation:+ "usage: o2b brain activation <status|sweep> [--top N] [--retention-days N] [--max-events N] [--vault <path>] [--json]\n" ++ "Operator surface over the recall activation event store (Brain/search/activation/).\n" ++ "status reports the folded per-path activation and co-access pairs; sweep drops\n" ++ "events outside the retention window or beyond the newest-N cap and refolds\n" ++ "(--max-events 0 clears every retained event).\n",audit:"usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +"Render a preference's full mutation audit trail (create / promote /\n" +diff --git a/src/cli/brain/verbs/activation.ts b/src/cli/brain/verbs/activation.tsnew file mode 100644index 00000000..f1a43335--- /dev/null+++ b/src/cli/brain/verbs/activation.ts@@ -0,0 +1,116 @@+/**+ * `o2b brain activation <op>` (Time-Aware Recall & Activation Suite,+ * t_2bc79017): operator surface over the activation event store -+ * `status` reports the folded state, `sweep` drops events outside the+ * retention window / newest-N cap and refolds.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import {+ ACCESS_EVENT_MAX_COUNT,+ ACCESS_EVENT_RETENTION_DAYS,+ computeActivationState,+ loadAccessEvents,+ sweepActivationEvents,+} from "../../../core/search/activation/store.ts";+import { defaultConfigPath } from "../../../core/config.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const USAGE =+ "usage: o2b brain activation <status|sweep> " ++ "[--top N] [--retention-days N] [--max-events N] [--vault V] [--json]";++const TOP_DEFAULT = 10;++function parsePositiveInt(raw: unknown, name: string, fallback: number): number {+ if (raw === undefined) return fallback;+ const n = Number(raw);+ if (!Number.isInteger(n) || n < 0) {+ throw new Error(`--${name} must be a non-negative integer`);+ }+ return n;+}++export async function cmdBrainActivation(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ top: { type: "string" },+ "retention-days": { type: "string" },+ "max-events": { type: "string" },+ json: { type: "boolean" },+ });+ const op = positional[0];+ if (op !== "status" && op !== "sweep") {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const asJson = flags["json"] === true;+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());++ try {+ if (op === "status") {+ const top = parsePositiveInt(flags["top"], "top", TOP_DEFAULT);+ const state = computeActivationState(loadAccessEvents(vault));+ const rows = Object.entries(state.paths)+ .map(([path, row]) => ({+ path,+ strength: row.strength,+ access_count: row.accessCount,+ last_access_at: new Date(row.lastAccessAt).toISOString(),+ }))+ .toSorted(+ (a, b) =>+ b.strength - a.strength ||+ b.access_count - a.access_count ||+ a.path.localeCompare(b.path),+ )+ .slice(0, top);+ const body = {+ events: state.events,+ paths: Object.keys(state.paths).length,+ co_access_pairs: state.coAccess.length,+ updated_at: state.updatedAt,+ top: rows,+ };+ if (asJson) {+ okJson(body);+ } else {+ ok(+ `activation: ${body.events} event(s), ${body.paths} path(s), ` ++ `${body.co_access_pairs} co-access pair(s)`,+ );+ for (const r of rows) {+ ok(` ${r.strength.toFixed(2)} x${r.access_count} ${r.path}`);+ }+ }+ return 0;+ }++ const retentionDays = parsePositiveInt(+ flags["retention-days"],+ "retention-days",+ ACCESS_EVENT_RETENTION_DAYS,+ );+ const maxEvents = parsePositiveInt(flags["max-events"], "max-events", ACCESS_EVENT_MAX_COUNT);+ const outcome = sweepActivationEvents(vault, {+ nowMs: Date.now(),+ retentionDays,+ maxEvents,+ });+ if (asJson) {+ okJson({ removed: outcome.removed, kept: outcome.kept });+ } else {+ ok(`activation sweep: removed ${outcome.removed}, kept ${outcome.kept}`);+ }+ return 0;+ } catch (exc) {+ const message = `activation ${op} failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex e4c88a44..6621c27a 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -19,6 +19,7 @@ export { cmdBrainDoctor } from "./doctor.ts";export { cmdBrainWatchdog } from "./watchdog.ts";export { cmdBrainHealth } from "./health.ts";export { cmdBrainHistory } from "./history.ts";+export { cmdBrainActivation } from "./activation.ts";export { cmdBrainAudit } from "./audit.ts";export { cmdBrainMorningBrief } from "./morning-brief.ts";export { cmdBrainCodec } from "./codec.ts";diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 6194f7d6..3422d8a7 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -113,6 +113,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("watchdog", "Probe Brain recovery status"),command("health", "Render semantic Brain health"),command("history", "Render preference edit history"),+ command("activation", "Activation event store: status and sweep"),command("audit", "Render mutation audit trail"),command("morning-brief", "Render session-start summary"),command("codec", "Compress or expand session prose"),diff --git a/src/cli/search.ts b/src/cli/search.tsindex 51c92c96..7191fef3 100644--- a/src/cli/search.ts+++ b/src/cli/search.ts@@ -418,6 +418,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {since: { type: "string" },until: { type: "string" },global: { type: "boolean" },+ "no-record-access": { type: "boolean" },json: { type: "boolean" },verbose: { type: "boolean" },});@@ -478,6 +479,12 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {...(flags["include-superseded"] === true ? { includeSuperseded: true } : {}),...(typeof flags["since"] === "string" ? { since: flags["since"] as string } : {}),...(typeof flags["until"] === "string" ? { until: flags["until"] as string } : {}),+ // Access recording (Time-Aware Recall & Activation Suite): the CLI+ // surface opts in by default; --no-record-access suppresses it, and+ // cross-vault union never records (results span foreign vaults).+ ...(flags["global"] !== true && flags["no-record-access"] !== true+ ? { recordAccess: true }+ : {}),};// Cross-vault union (t_72a22658): explicit per-call opt-in fans the// query out over profiles and read-only sources with origin labels.diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex b677cf6f..c48823ff 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -49,6 +49,7 @@ import {import { extractTemporalConstraints } from "./temporal-extract.ts";import { runHealEnrichment } from "./heal-run.ts";import { collectEvidenceForSlug } from "./evidence.ts";+import { classifyFreshnessTrend } from "./temporal/freshness-trend.ts";import { buildIntentReview, type BrainIntentReviewEntry } from "./intent-review.ts";import { writePreferenceTxn } from "./preference-txn.ts";import { appendLogEvent, type BrainLogEntry } from "./log.ts";@@ -500,6 +501,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {});// Same txn route as the newUnconfirmed loop: auto-stamps// _revision (existing+1) and _content_hash on confirmed status.+ // The freshness trend was classified at PLAN time (planRefresh)+ // so the no-op pre-flight rendered these exact bytes.writePreferenceTxn(vault,{@@ -519,6 +522,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {pinned: update.pinned,recentApplied: ev.applied,recentViolated: ev.violated,+ ...(update.freshness_trend !== undefined+ ? { freshness_trend: update.freshness_trend }+ : {}),...(update.scope ? { scope: update.scope } : {}),},[],@@ -1570,6 +1576,16 @@ interface RefreshUpdate {readonly confidence: BrainConfidence;readonly confidence_value: number;readonly pinned: boolean;+ /**+ * Freshness trend (t_ee09a6ce), computed at PLAN time so the no-op+ * pre-flight (`wouldRewritePreference`) renders the same bytes the+ * write loop will stamp. Computing it only in the write loop would+ * make every stamped pref look like "needs rewrite" forever. Absent+ * when the stamp is withheld: a pref that has never carried the+ * field and is not being rewritten anyway stays byte-identical, so+ * legacy vaults keep their no-op dream guarantees.+ */+ readonly freshness_trend?: string;}/**@@ -1796,6 +1812,32 @@ function planRefresh(confidence.band !== rec.pref.confidence ||valueDifferent;+ // Freshness trend (t_ee09a6ce): classified at PLAN time so the+ // no-op pre-flight below and the write loop render identical+ // bytes. The stamp is OPPORTUNISTIC: it lands when the pref is+ // being rewritten anyway (counters changed) or already carries+ // the field (then it refreshes on every consolidation pass, the+ // Hindsight contract). A never-stamped pref with unchanged+ // counters is left byte-identical so legacy vaults keep their+ // no-op dream guarantees.+ const stampTrend = countersChanged || rec.pref.freshness_trend !== undefined;+ let trendLabel: string | undefined;+ if (stampTrend) {+ const trendEv = collectEvidenceForSlug(vault, slug, {+ sinceIso: rec.pref.created_at,+ maxApplied: 1000,+ maxViolated: 1000,+ });+ trendLabel = classifyFreshnessTrend({+ createdAt: rec.pref.created_at,+ events: [...trendEv.applied, ...trendEv.violated].map((r) => ({+ at: r.timestamp,+ result: r.result,+ })),+ nowMs: now.getTime(),+ }).trend;+ }+const prospective = {slug,topic: rec.pref.topic,@@ -1812,6 +1854,7 @@ function planRefresh(confidence: confidence.band,confidence_value: confidence.value,pinned: rec.pref.pinned,+ ...(trendLabel !== undefined ? { freshness_trend: trendLabel } : {}),};if (!countersChanged) {diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex 3420e0d6..574c7057 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -127,6 +127,14 @@ export interface WritePreferenceInput {*/readonly tier?: PageTier;readonly pinned?: boolean;+ /**+ * Directional freshness trend (Time-Aware Recall & Activation Suite,+ * t_ee09a6ce). Stamped by the dream refresh pass from the evidence+ * time distribution; emitted only when supplied so legacy fixtures+ * stay byte-identical. Recall reads it as a bounded ranking+ * multiplier; absent means neutral.+ */+ readonly freshness_trend?: string;/*** Brain Integrity Suite (v0.12.0). Optional monotonic write counter* persisted as `_revision`. `writePreferenceTxn` auto-stamps the@@ -411,6 +419,9 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma// callers stay byte-identical.if (input.valid_from?.trim()) metadata["valid_from"] = input.valid_from.trim();if (input.valid_until?.trim()) metadata["valid_until"] = input.valid_until.trim();+ // Freshness trend (t_ee09a6ce): stamped by the dream refresh pass;+ // emitted only when supplied so legacy callers stay byte-identical.+ if (input.freshness_trend?.trim()) metadata["freshness_trend"] = input.freshness_trend.trim();return metadata;}@@ -622,6 +633,9 @@ export function parsePreference(...(optionalScalarString(meta, "scope") !== undefined? { scope: optionalScalarString(meta, "scope") }: {}),+ ...(optionalScalarString(meta, "freshness_trend") !== undefined+ ? { freshness_trend: optionalScalarString(meta, "freshness_trend") }+ : {}),...(optionalScalarString(meta, "supersedes") !== undefined? { supersedes: optionalScalarString(meta, "supersedes") }: {}),diff --git a/src/core/brain/temporal/belief-evolution.ts b/src/core/brain/temporal/belief-evolution.tsindex ec870040..c2038972 100644--- a/src/core/brain/temporal/belief-evolution.ts+++ b/src/core/brain/temporal/belief-evolution.ts@@ -26,6 +26,7 @@ import { join } from "node:path";import { parseFrontmatter } from "../../vault.ts";import { brainDirs } from "./../paths.ts";import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND, type BrainApplyResult } from "./../types.ts";+import { classifyFreshnessTrend, type FreshnessTrendReport } from "./freshness-trend.ts";import { extractId } from "./period-common.ts";import { selectEvents } from "./select-events.ts";import type { TemporalEvent, TimelineIndex } from "./types.ts";@@ -72,6 +73,13 @@ export interface BeliefEvolutionEnvelope {readonly transitions: ReadonlyArray<BeliefTransition>;readonly evidence: ReadonlyArray<BeliefEvidenceRow>;readonly retirements: ReadonlyArray<BeliefRetirement>;+ /**+ * Directional freshness trend computed live from the evidence rows+ * (Time-Aware Recall & Activation Suite, t_ee09a6ce). Absent only+ * when the window holds no signal at all (no transitions and no+ * evidence), so empty envelopes stay shaped as before.+ */+ readonly freshnessTrend?: FreshnessTrendReport;readonly generatedAt: string;}@@ -85,18 +93,33 @@ export function buildBeliefEvolution(target: BeliefEvolutionTarget,opts: BuildBeliefEvolutionOptions = {},): BeliefEvolutionEnvelope {- const generatedAt = (opts.now ?? new Date()).toISOString();+ const now = opts.now ?? new Date();+ const generatedAt = now.toISOString();const targetIdSet = resolveTargetIds(index, vault, target);const transitions = collectTransitions(index, targetIdSet);const evidence = collectEvidence(index, targetIdSet);const retirements = collectRetirements(vault, target, targetIdSet);+ // Freshness trend (t_ee09a6ce): classified live from the evidence+ // rows. `createdAt` comes from the creation transition when the+ // window saw one; otherwise the classifier treats age as unknown.+ const creation = transitions.find((t) => t.kind === "creation");+ const freshnessTrend =+ transitions.length > 0 || evidence.length > 0+ ? classifyFreshnessTrend({+ createdAt: creation?.at ?? null,+ events: evidence.map((e) => ({ at: e.at, result: e.result })),+ nowMs: now.getTime(),+ })+ : undefined;+return Object.freeze({target,transitions: Object.freeze(transitions),evidence: Object.freeze(evidence),retirements: Object.freeze(retirements),+ ...(freshnessTrend !== undefined ? { freshnessTrend } : {}),generatedAt,});}diff --git a/src/core/brain/temporal/freshness-trend.ts b/src/core/brain/temporal/freshness-trend.tsnew file mode 100644index 00000000..b0496c72--- /dev/null+++ b/src/core/brain/temporal/freshness-trend.ts@@ -0,0 +1,151 @@+/**+ * Freshness-trend classification (Time-Aware Recall & Activation+ * Suite, t_ee09a6ce).+ *+ * Classifies a preference's evidence history into a directional trend+ * label - `new | strengthening | stable | weakening | stale` - from+ * the TIME DISTRIBUTION of its applied/violated/outdated events, not+ * just a last-touched timestamp. The window comparison (recent 30d vs+ * prior 30d) is the whole model: more recent applies than prior means+ * the rule is gaining evidence, rising violations or fading applies+ * means it is losing trust, and a long evidence silence means it needs+ * re-verification before being relied on.+ *+ * Pure function over `(events, createdAt, nowMs)` - no I/O, injected+ * clock, deterministic. Two call sites consume it: the belief-evolution+ * envelope (computed live) and the dream refresh pass (stamped into+ * preference frontmatter as `freshness_trend`, the Hindsight+ * "refreshed on each consolidation" contract).+ */++import type { BrainApplyResult } from "../types.ts";++export type FreshnessTrend = "new" | "strengthening" | "stable" | "weakening" | "stale";++/** All trend labels, for validation at parse boundaries. */+export const FRESHNESS_TRENDS: ReadonlyArray<FreshnessTrend> = Object.freeze([+ "new",+ "strengthening",+ "stable",+ "weakening",+ "stale",+]);++/** One evidence event the classifier consumes. */+export interface TrendEvidenceEvent {+ /** ISO-8601 UTC timestamp. */+ readonly at: string;+ readonly result: BrainApplyResult;+}++export interface TrendWindows {+ /** Width of the recent and prior comparison windows, in days. */+ readonly recentDays: number;+ /** Evidence silence beyond this many days reads as stale. */+ readonly staleDays: number;+ /** Preferences younger than this with no prior evidence read as new. */+ readonly newDays: number;+}++export const DEFAULT_TREND_WINDOWS: TrendWindows = Object.freeze({+ recentDays: 30,+ staleDays: 60,+ newDays: 14,+});++export interface ClassifyFreshnessTrendInput {+ /** Preference `created_at` (ISO), or null when unknown. */+ readonly createdAt: string | null;+ readonly events: ReadonlyArray<TrendEvidenceEvent>;+ /** Injected clock (unix ms). */+ readonly nowMs: number;+ readonly windows?: TrendWindows;+}++export interface FreshnessTrendReport {+ readonly trend: FreshnessTrend;+ readonly recentApplied: number;+ readonly recentViolated: number;+ readonly priorApplied: number;+ readonly priorViolated: number;+ /** ISO timestamp of the newest evidence event, or null. */+ readonly lastEvidenceAt: string | null;+}++const DAY_MS = 24 * 60 * 60 * 1000;++function parseMs(at: string): number | null {+ const ms = Date.parse(at);+ return Number.isFinite(ms) ? ms : null;+}++/**+ * Classify one preference's evidence history. Violated and outdated+ * results both count against the rule (the same grouping the evidence+ * collector uses). Events with unparseable timestamps are skipped.+ */+export function classifyFreshnessTrend(input: ClassifyFreshnessTrendInput): FreshnessTrendReport {+ const w = input.windows ?? DEFAULT_TREND_WINDOWS;+ const recentStart = input.nowMs - w.recentDays * DAY_MS;+ const priorStart = input.nowMs - 2 * w.recentDays * DAY_MS;++ let recentApplied = 0;+ let recentViolated = 0;+ let priorApplied = 0;+ let priorViolated = 0;+ let lastEvidenceMs: number | null = null;+ let lastEvidenceAt: string | null = null;++ for (const ev of input.events) {+ const ms = parseMs(ev.at);+ if (ms === null || ms > input.nowMs) continue;+ if (lastEvidenceMs === null || ms > lastEvidenceMs) {+ lastEvidenceMs = ms;+ lastEvidenceAt = ev.at;+ }+ const against = ev.result === "violated" || ev.result === "outdated";+ if (ms >= recentStart) {+ if (against) recentViolated++;+ else recentApplied++;+ } else if (ms >= priorStart) {+ if (against) priorViolated++;+ else priorApplied++;+ }+ }++ const createdMs = input.createdAt !== null ? parseMs(input.createdAt) : null;+ const isYoung = createdMs !== null && input.nowMs - createdMs < w.newDays * DAY_MS;++ let trend: FreshnessTrend;+ if (lastEvidenceMs === null) {+ trend = isYoung ? "new" : "stale";+ } else if (input.nowMs - lastEvidenceMs > w.staleDays * DAY_MS) {+ trend = "stale";+ } else if (isYoung && priorApplied === 0 && priorViolated === 0) {+ trend = "new";+ } else if (recentViolated > priorViolated || recentApplied < priorApplied) {+ trend = "weakening";+ } else if (recentApplied > priorApplied) {+ trend = "strengthening";+ } else {+ trend = "stable";+ }++ return Object.freeze({+ trend,+ recentApplied,+ recentViolated,+ priorApplied,+ priorViolated,+ lastEvidenceAt,+ });+}++/** Parse a frontmatter `freshness_trend` value; junk reads as null. */+export function parseFreshnessTrend(raw: unknown): FreshnessTrend | null {+ if (typeof raw !== "string") return null;+ const value = raw.trim().toLowerCase();+ return (FRESHNESS_TRENDS as ReadonlyArray<string>).includes(value)+ ? (value as FreshnessTrend)+ : null;+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 1caf6855..7e9e4bff 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -453,6 +453,13 @@ export interface BrainPreference {* `drift_detected` event in the log.*/readonly content_hash?: string;+ /**+ * Directional freshness trend (Time-Aware Recall & Activation Suite,+ * t_ee09a6ce): `new | strengthening | stable | weakening | stale`,+ * stamped by the dream refresh from the evidence time distribution.+ * Absent on never-refreshed files; readers treat absent as neutral.+ */+ readonly freshness_trend?: string;/** Optional wikilink to a retired pref this one replaces. */readonly supersedes?: string;readonly aliases?: ReadonlyArray<string>;diff --git a/src/core/search/activation/decay.ts b/src/core/search/activation/decay.tsnew file mode 100644index 00000000..fd7b57b6--- /dev/null+++ b/src/core/search/activation/decay.ts@@ -0,0 +1,91 @@+/**+ * Activation kernel math (Time-Aware Recall & Activation Suite,+ * t_2bc79017).+ *+ * Pure ACT-R-style reactivation: every recorded access bumps a+ * per-document strength by a fixed step (capped at 1.0), and the+ * effective activation read at query time decays the stored strength by+ * a content-type half-life. Habitually-recalled memories stay hot;+ * unused ones fade without manual cleanup - and the types that encode+ * durable judgement (preferences, decisions, antipatterns) never decay+ * at all.+ *+ * No I/O and no clock: callers pass days-since-access, so the time+ * source stays injectable at the store/ranker boundary (the same rule+ * `recency.ts` follows).+ */++/** Strength gained per recorded access. */+export const ACTIVATION_STRENGTH_STEP = 0.1;+/** Ceiling for the stored strength. */+export const ACTIVATION_STRENGTH_MAX = 1;+/** Half-life for kinds the table does not name (plain notes). */+export const DEFAULT_HALF_LIFE_DAYS = 60;++/**+ * Content-type half-life table, keyed by the resolved activation kind.+ * `null` means "never decays" - the kinds that encode durable judgement+ * keep their full strength regardless of idle time. Values align with+ * the schema-pack vocabulary rather than inventing a parallel taxonomy.+ */+export const HALF_LIFE_DAYS: ReadonlyMap<string, number | null> = new Map<string, number | null>([+ ["preference", null],+ ["decision", null],+ ["antipattern", null],+ ["project", 120],+ ["handoff", 30],+ ["session", 30],+ ["note", DEFAULT_HALF_LIFE_DAYS],+]);++/** Path prefixes that imply a kind when frontmatter declares none. */+const PATH_KIND_PREFIXES: ReadonlyArray<readonly [string, string]> = [+ ["Brain/preferences/", "preference"],+ ["Brain/decisions/", "decision"],+];++/**+ * Resolve the activation kind for a document: normalized frontmatter+ * `kind:` first (the framework `brain-` prefix is stripped, so+ * `kind: brain-preference` resolves to `preference`), then framework+ * path prefixes, then `note`.+ */+export function resolveActivationKind(frontmatterKind: string | null, path: string): string {+ const raw = frontmatterKind?.trim().toLowerCase() ?? "";+ const fromFrontmatter = raw.startsWith("brain-") ? raw.slice("brain-".length) : raw;+ if (fromFrontmatter !== "") return fromFrontmatter;+ for (const [prefix, kind] of PATH_KIND_PREFIXES) {+ if (path.startsWith(prefix)) return kind;+ }+ return "note";+}++/** Half-life in days for a kind; unknown kinds use the note default. */+export function halfLifeDays(kind: string): number | null {+ const entry = HALF_LIFE_DAYS.get(kind);+ return entry === undefined ? DEFAULT_HALF_LIFE_DAYS : entry;+}++/** One access: add a step, cap at the maximum. Junk reads as zero. */+export function bumpStrength(prev: number): number {+ const base = Number.isFinite(prev) && prev > 0 ? prev : 0;+ return Math.min(ACTIVATION_STRENGTH_MAX, base + ACTIVATION_STRENGTH_STEP);+}++/**+ * Effective activation at read time: the stored strength decayed by the+ * type half-life. Infinite half-life (null) returns the strength as-is;+ * future access times clamp to age zero; non-finite inputs yield 0.+ */+export function effectiveActivation(+ strength: number,+ daysSinceLastAccess: number,+ halfLife: number | null,+): number {+ if (!Number.isFinite(strength) || strength <= 0) return 0;+ if (halfLife === null) return strength;+ if (!(halfLife > 0)) return 0;+ if (!Number.isFinite(daysSinceLastAccess)) return 0;+ const age = Math.max(0, daysSinceLastAccess);+ return strength * Math.pow(2, -age / halfLife);+}diff --git a/src/core/search/activation/store.ts b/src/core/search/activation/store.tsnew file mode 100644index 00000000..a0b146ce--- /dev/null+++ b/src/core/search/activation/store.ts@@ -0,0 +1,286 @@+/**+ * Activation event store (Time-Aware Recall & Activation Suite,+ * t_2bc79017 + t_c5ef25a3).+ *+ * Storage follows the `feedback.ts` convention exactly: one small JSON+ * file per recorded access under `Brain/search/activation/` (the+ * conflict-free one-file-per-signal pattern), and a derived+ * `Brain/search/activation-state.json` that is a PURE FOLD over the+ * retained events - deterministic, order-insensitive, replayable, and+ * safe to delete.+ *+ * Sweep semantics are part of the activation model, not an+ * afterthought: activation decays toward the type floor anyway, so+ * dropping events older than the retention window (or beyond the+ * newest-N cap) approximates the limit instead of corrupting it.+ *+ * Privacy: events carry an FNV-1a hash of the query, never raw text.+ */++import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, existsSync } from "node:fs";+import { join } from "node:path";++import { fnv1aHex } from "../feedback.ts";+import { bumpStrength } from "./decay.ts";+import type {+ ActivationAccessEvent,+ ActivationPathState,+ ActivationState,+ ActivationSweepOutcome,+ CoAccessPair,+} from "./types.ts";++/** Cap on surfaced paths stored per access event. */+export const ACCESS_EVENT_PATHS_CAP = 10;+/** Default retention window for access events, in days. */+export const ACCESS_EVENT_RETENTION_DAYS = 90;+/** Default cap on retained access events. */+export const ACCESS_EVENT_MAX_COUNT = 5000;+/** Cap on co-access pairs kept in the derived state. */+export const CO_ACCESS_MAX_PAIRS = 500;+/** Pairs seen fewer times than this are noise and never boost. */+export const CO_ACCESS_MIN_COUNT = 2;++const DAY_MS = 24 * 60 * 60 * 1000;++export function activationDir(vault: string): string {+ return join(vault, "Brain", "search", "activation");+}++export function activationStatePath(vault: string): string {+ return join(vault, "Brain", "search", "activation-state.json");+}++/**+ * Record one access event as its own file and refresh the derived+ * state. The filename derives from the timestamp plus a content hash,+ * so recording the identical event twice is idempotent.+ */+export function recordAccessEvent(vault: string, event: ActivationAccessEvent): string {+ const dir = activationDir(vault);+ mkdirSync(dir, { recursive: true });+ const bounded: ActivationAccessEvent = {+ ts: event.ts,+ queryHash: event.queryHash,+ paths: event.paths.slice(0, ACCESS_EVENT_PATHS_CAP),+ };+ const body = JSON.stringify(bounded, null, 2) + "\n";+ const file = join(dir, `${bounded.ts}-${fnv1aHex(body)}.json`);+ writeFileSync(file, body);+ writeActivationState(vault, computeActivationState(loadAccessEvents(vault)));+ return file;+}++/** Load all retained access events, sorted by ts then filename. */+export function loadAccessEvents(vault: string): ActivationAccessEvent[] {+ const dir = activationDir(vault);+ let files: string[];+ try {+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));+ } catch {+ return [];+ }+ const out: ActivationAccessEvent[] = [];+ for (const f of files.toSorted()) {+ try {+ const parsed = JSON.parse(readFileSync(join(dir, f), "utf8")) as ActivationAccessEvent;+ const pathsValid =+ Array.isArray(parsed.paths) && parsed.paths.every((p) => typeof p === "string");+ if (+ typeof parsed.ts === "number" &&+ Number.isFinite(parsed.ts) &&+ typeof parsed.queryHash === "string" &&+ pathsValid+ ) {+ out.push(parsed);+ }+ } catch {+ // One malformed file never breaks the fold.+ }+ }+ out.sort((a, b) => a.ts - b.ts);+ return out;+}++/**+ * The deterministic fold. Per path: strength is `bumpStrength` applied+ * once per access (a pure function of the access COUNT, so the fold is+ * order-insensitive by construction), `lastAccessAt` is the max ts.+ * Co-access pairs count events that surfaced both paths together,+ * bounded to the top {@link CO_ACCESS_MAX_PAIRS} by count then key.+ */+export function computeActivationState(+ events: ReadonlyArray<ActivationAccessEvent>,+): ActivationState {+ const counts = new Map<string, { count: number; lastAccessAt: number }>();+ const pairCounts = new Map<string, number>();+ let latestTs = 0;++ for (const e of events) {+ if (e.ts > latestTs) latestTs = e.ts;+ const unique = Array.from(new Set(e.paths)).toSorted();+ for (const p of unique) {+ const row = counts.get(p) ?? { count: 0, lastAccessAt: 0 };+ row.count++;+ if (e.ts > row.lastAccessAt) row.lastAccessAt = e.ts;+ counts.set(p, row);+ }+ for (let i = 0; i < unique.length; i++) {+ for (let j = i + 1; j < unique.length; j++) {+ const key = `${unique[i]}\n${unique[j]}`;+ pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);+ }+ }+ }++ const paths: Record<string, ActivationPathState> = {};+ for (const p of Array.from(counts.keys()).toSorted()) {+ const row = counts.get(p)!;+ let strength = 0;+ for (let i = 0; i < row.count; i++) strength = bumpStrength(strength);+ paths[p] = Object.freeze({+ strength: Math.round(strength * 1e6) / 1e6,+ lastAccessAt: row.lastAccessAt,+ accessCount: row.count,+ });+ }++ const coAccess: CoAccessPair[] = Array.from(pairCounts.entries())+ .map(([key, count]) => {+ const [a, b] = key.split("\n") as [string, string];+ return Object.freeze({ a, b, count });+ })+ .toSorted((x, y) => y.count - x.count || x.a.localeCompare(y.a) || x.b.localeCompare(y.b))+ .slice(0, CO_ACCESS_MAX_PAIRS);++ return Object.freeze({+ version: 1,+ events: events.length,+ updatedAt: latestTs > 0 ? new Date(latestTs).toISOString() : null,+ paths: Object.freeze(paths),+ coAccess: Object.freeze(coAccess),+ });+}++export function writeActivationState(vault: string, state: ActivationState): void {+ mkdirSync(join(vault, "Brain", "search"), { recursive: true });+ writeFileSync(activationStatePath(vault), JSON.stringify(state, null, 2) + "\n");+}++function isPathState(v: unknown): v is ActivationPathState {+ if (v === null || typeof v !== "object") return false;+ const row = v as Record<string, unknown>;+ return (+ typeof row["strength"] === "number" &&+ Number.isFinite(row["strength"]) &&+ typeof row["lastAccessAt"] === "number" &&+ Number.isFinite(row["lastAccessAt"]) &&+ typeof row["accessCount"] === "number" &&+ Number.isInteger(row["accessCount"]) &&+ (row["accessCount"] as number) >= 0+ );+}++function isCoAccessPair(v: unknown): v is CoAccessPair {+ if (v === null || typeof v !== "object") return false;+ const p = v as Record<string, unknown>;+ return (+ typeof p["a"] === "string" &&+ typeof p["b"] === "string" &&+ typeof p["count"] === "number" &&+ Number.isInteger(p["count"]) &&+ (p["count"] as number) >= 0+ );+}++/**+ * Read the derived state; structurally invalid content reads as null -+ * including corrupt NESTED rows, which would otherwise feed NaN into+ * ranking. A null read falls back to the replayable event fold.+ */+export function readActivationState(vault: string): ActivationState | null {+ try {+ const parsed = JSON.parse(readFileSync(activationStatePath(vault), "utf8")) as ActivationState;+ if (parsed.version !== 1) return null;+ if (!Number.isInteger(parsed.events) || parsed.events < 0) return null;+ if (!(parsed.updatedAt === null || typeof parsed.updatedAt === "string")) return null;+ if (parsed.paths === null || typeof parsed.paths !== "object") return null;+ if (!Array.isArray(parsed.coAccess)) return null;+ for (const row of Object.values(parsed.paths as Record<string, unknown>)) {+ if (!isPathState(row)) return null;+ }+ for (const pair of parsed.coAccess as ReadonlyArray<unknown>) {+ if (!isCoAccessPair(pair)) return null;+ }+ return parsed;+ } catch {+ return null;+ }+}++/**+ * Stable fingerprint of the activation state for the query-cache key:+ * "off" when no derived file exists, else a hash of its content.+ */+export function activationStateFingerprint(vault: string): string {+ const path = activationStatePath(vault);+ if (!existsSync(path)) return "off";+ try {+ return fnv1aHex(readFileSync(path, "utf8"));+ } catch {+ return "off";+ }+}++export interface ActivationSweepOptions {+ /** Injected clock (unix ms). */+ readonly nowMs: number;+ /** Events older than this many days are dropped. */+ readonly retentionDays?: number;+ /** At most this many newest events are kept. */+ readonly maxEvents?: number;+}++/**+ * Drop events outside the retention window or beyond the newest-N cap,+ * then refold the derived state from what remains.+ */+export function sweepActivationEvents(+ vault: string,+ opts: ActivationSweepOptions,+): ActivationSweepOutcome {+ const retentionDays = opts.retentionDays ?? ACCESS_EVENT_RETENTION_DAYS;+ const maxEvents = opts.maxEvents ?? ACCESS_EVENT_MAX_COUNT;+ const cutoff = opts.nowMs - retentionDays * DAY_MS;++ const dir = activationDir(vault);+ let files: string[];+ try {+ files = readdirSync(dir)+ .filter((f) => f.endsWith(".json"))+ .toSorted();+ } catch {+ // No event directory: refold a derived state that still exists so+ // stale boosts never outlive their events.+ if (existsSync(activationStatePath(vault))) {+ writeActivationState(vault, computeActivationState([]));+ }+ return Object.freeze({ removed: 0, kept: 0 });+ }++ // Filename prefix is the event ts; malformed names parse as NaN and+ // are treated as expired so junk never survives a sweep.+ const withTs = files.map((f) => ({ f, ts: Number(f.split("-")[0]) }));+ const fresh = withTs.filter((x) => Number.isFinite(x.ts) && x.ts >= cutoff);+ const expired = withTs.filter((x) => !Number.isFinite(x.ts) || x.ts < cutoff);++ fresh.sort((a, b) => a.ts - b.ts || a.f.localeCompare(b.f));+ const overflow = fresh.length > maxEvents ? fresh.slice(0, fresh.length - maxEvents) : [];+ const keep = fresh.slice(Math.max(0, fresh.length - maxEvents));++ for (const x of [...expired, ...overflow]) {+ rmSync(join(dir, x.f), { force: true });+ }+ writeActivationState(vault, computeActivationState(loadAccessEvents(vault)));+ return Object.freeze({ removed: expired.length + overflow.length, kept: keep.length });+}diff --git a/src/core/search/activation/types.ts b/src/core/search/activation/types.tsnew file mode 100644index 00000000..f4daa339--- /dev/null+++ b/src/core/search/activation/types.ts@@ -0,0 +1,54 @@+/**+ * Activation store types (Time-Aware Recall & Activation Suite,+ * t_2bc79017 + t_c5ef25a3).+ */++/** One recorded retrieval: which documents one search surfaced. */+export interface ActivationAccessEvent {+ /** Unix-ms timestamp the access was recorded. */+ readonly ts: number;+ /** FNV-1a hash of the normalised query - never the raw query text. */+ readonly queryHash: string;+ /** Vault-relative paths of the surfaced documents (bounded). */+ readonly paths: ReadonlyArray<string>;+}++/** Folded per-document activation. */+export interface ActivationPathState {+ /** Accumulated strength in [0, 1] (step per access, capped). */+ readonly strength: number;+ /** Unix-ms timestamp of the most recent access. */+ readonly lastAccessAt: number;+ /** Total recorded accesses. */+ readonly accessCount: number;+}++/** One unordered co-access pair (a < b lexicographically). */+export interface CoAccessPair {+ readonly a: string;+ readonly b: string;+ /** Number of events that surfaced both paths together. */+ readonly count: number;+}++/**+ * Derived activation state - a pure fold over the retained access+ * events. The file is a cache: deleting it loses nothing.+ */+export interface ActivationState {+ readonly version: 1;+ /** Number of events the fold consumed. */+ readonly events: number;+ /** ISO timestamp of the most recent event, or null when empty. */+ readonly updatedAt: string | null;+ /** Per-path activation, keys sorted for determinism. */+ readonly paths: Readonly<Record<string, ActivationPathState>>;+ /** Bounded co-access pairs, sorted by count desc then keys asc. */+ readonly coAccess: ReadonlyArray<CoAccessPair>;+}++/** Outcome of an activation-event sweep. */+export interface ActivationSweepOutcome {+ readonly removed: number;+ readonly kept: number;+}diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex 8182a639..d336582a 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -487,6 +487,16 @@ export function resolveSearchConfig(opts: {false,"search_learned_weights_enabled",);+ const activationEnabled = parseBool(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_ACTIVATION", "search_activation_enabled"),+ true,+ "search_activation_enabled",+ );+ const twoPassEnabled = parseBool(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_TWO_PASS", "search_two_pass_enabled"),+ true,+ "search_two_pass_enabled",+ );const recall: ResolvedRecallConfig = Object.freeze({mmrLambda,maxHops,@@ -502,6 +512,8 @@ export function resolveSearchConfig(opts: {cacheTtlSeconds,relationPolarityEnabled,learnedWeightsEnabled,+ activationEnabled,+ twoPassEnabled,});const base: ResolvedSearchConfig = Object.freeze({diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.tsindex 209e52b8..5f981c8d 100644--- a/src/core/search/ranker.ts+++ b/src/core/search/ranker.ts@@ -38,8 +38,40 @@ export interface RankerInputs {* populated by a reindex.*/readonly entityMatchByChunk?: ReadonlyMap<number, number>;+ /**+ * Optional per-chunk effective activation in [0, 1] (Time-Aware+ * Recall & Activation Suite): access-reinforced strength already+ * decayed by the content-type half-life. Missing entries (and the+ * absent map) contribute zero boost, so a vault without recorded+ * accesses ranks bit-identically to pre-activation behaviour.+ */+ readonly activationByChunk?: ReadonlyMap<number, number>;+ /**+ * Optional co-access companions per chunk (t_c5ef25a3): for each+ * chunkId, the OTHER document ids habitually co-retrieved with its+ * document, with the recorded pair count. Only companions that are+ * also in the current candidate pool contribute (the same+ * pool-membership rule the link boost uses), so the boost re-ranks a+ * working set without floating unrelated documents.+ */+ readonly coAccessByChunk?: ReadonlyMap<number, ReadonlyMap<number, number>>;+ /**+ * Optional freshness trend per documentId (t_ee09a6ce), read from+ * the `freshness_trend` frontmatter the dream refresh stamps on+ * preference pages. Maps to a bounded multiplier on the relevance+ * portion (strengthening 1.05, weakening 0.93, stale 0.85); absent+ * entries (and the absent map) stay neutral.+ */+ readonly trendByDoc?: ReadonlyMap<number, string>;}+/** Freshness-trend multipliers on the relevance portion. */+const TREND_MULTIPLIERS: ReadonlyMap<string, number> = new Map([+ ["strengthening", 1.05],+ ["weakening", 0.93],+ ["stale", 0.85],+]);+export interface RankerOptions {readonly keywordWeight: number;readonly semanticWeight: number;@@ -140,6 +172,10 @@ function buildReasons(parts: {recency: number;tierMul: number;entityBoost?: number;+ activationBoost?: number;+ coAccessBoost?: number;+ trend?: string;+ trendMul?: number;sessionFocus?: number;rrf?: number;}): ReadonlyArray<string> {@@ -150,6 +186,15 @@ function buildReasons(parts: {if (parts.entityBoost && parts.entityBoost > 0) {reasons.push(`entity_match: ${fmt(parts.entityBoost)}`);}+ if (parts.activationBoost && parts.activationBoost > 0) {+ reasons.push(`activation: ${fmt(parts.activationBoost)}`);+ }+ if (parts.coAccessBoost && parts.coAccessBoost > 0) {+ reasons.push(`co_access: ${fmt(parts.coAccessBoost)}`);+ }+ if (parts.trend !== undefined && parts.trendMul !== undefined && parts.trendMul !== 1) {+ reasons.push(`freshness_trend: ${parts.trend} x${fmt(parts.trendMul)}`);+ }if (parts.linkBoost > 0) reasons.push(`link_boost: ${fmt(parts.linkBoost)}`);if (parts.recency > 0) reasons.push(`recency: ${fmt(parts.recency)}`);if (parts.tierMul !== 1) reasons.push(`tier: ${fmt(parts.tierMul)}`);@@ -293,13 +338,45 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea// `supporting` → 1.0 keeps untagged vaults bit-identical.const tier = inputs.tierByDoc?.get(c.documentId) ?? PAGE_TIER_DEFAULT;const tierMul = tierWeight(tier);+ // Freshness-trend multiplier (t_ee09a6ce): like tier, it scales the+ // relevance portion only. Unstamped documents (and unknown labels)+ // stay at the neutral 1.0.+ const trend = inputs.trendByDoc?.get(c.documentId);+ const trendMul = trend !== undefined ? (TREND_MULTIPLIERS.get(trend) ?? 1) : 1;// Entity boost: capped contribution from shared query entities.// Per-match 0.02, capped at 0.04 so it only re-ranks an already// relevant set - never enough to float an irrelevant chunk.const entityMatches = inputs.entityMatchByChunk?.get(c.chunkId) ?? 0;const entityBoost = Math.min(0.04, entityMatches * 0.02 * entMul);+ // Activation boost (Time-Aware Recall & Activation Suite): the+ // effective (type-decayed) activation scales into a capped 0.04+ // contribution - a re-ranker for habitually-recalled memories,+ // never enough to float an irrelevant chunk.+ const activation = clamp01(inputs.activationByChunk?.get(c.chunkId) ?? 0);+ const activationBoost = Math.min(0.04, activation * 0.04);+ // Co-access companion boost (t_c5ef25a3): per habitual companion+ // that is ALSO in the candidate pool, 0.005 per recorded pair+ // count, capped at 0.03 - surfaces the rest of a recurring working+ // set without floating unrelated documents.+ let coAccessRaw = 0;+ const companions = inputs.coAccessByChunk?.get(c.chunkId);+ if (companions !== undefined) {+ for (const [docId, count] of companions) {+ if (docId === c.documentId) continue;+ if (candidateDocIds.has(docId)) coAccessRaw += count * 0.005;+ }+ }+ const coAccessBoost = Math.min(0.03, coAccessRaw);const sessionFocus = scoreSessionFocusTarget(hyd, opts.sessionFocus, nowMs);- const score = clamp01(weighted * tierMul + linkBoost + recency + entityBoost + sessionFocus);+ const score = clamp01(+ weighted * tierMul * trendMul ++ linkBoost ++ recency ++ entityBoost ++ activationBoost ++ coAccessBoost ++ sessionFocus,+ );ranked.push(Object.freeze({@@ -323,6 +400,9 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSearecency,tierMul,entityBoost,+ activationBoost,+ coAccessBoost,+ ...(trend !== undefined ? { trend, trendMul } : {}),sessionFocus,rrf: rrfByChunk !== null ? rrf : 0,}),diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex ddd9eff0..3a368270 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -9,6 +9,7 @@* the store but the public surface stays uniform.*/+import { statSync } from "node:fs";import { join } from "node:path";import { parseFrontmatter } from "../vault.ts";@@ -16,11 +17,21 @@ import { isVisible, normalizeVisibilityScope, pageVisibility } from "../graph/viimport { makeProvider } from "./embeddings/provider.ts";import {composeWeightProfiles,+ fnv1aHex,isNeutralLearnedWeights,learnedWeightsFingerprint,learnedWeightsReason,readLearnedWeights,} from "./feedback.ts";+import { parseFreshnessTrend } from "../brain/temporal/freshness-trend.ts";+import { effectiveActivation, halfLifeDays, resolveActivationKind } from "./activation/decay.ts";+import {+ ACCESS_EVENT_PATHS_CAP,+ CO_ACCESS_MIN_COUNT,+ activationStateFingerprint,+ readActivationState,+ recordAccessEvent,+} from "./activation/store.ts";import { extractEntities } from "./entities.ts";import { expandQueryEntities } from "./entity-alias.ts";import { buildCoverageReport, significantTerms, termIncludedIn } from "./coverage.ts";@@ -35,7 +46,9 @@ import { filterByProperties } from "./property-filter.ts";import { applyRelationPolarity } from "./relation-polarity.ts";import { rankResults } from "./ranker.ts";import { readActiveSessionFocus } from "./session-focus.ts";-import { mtimeInRange, resolveTimeRange } from "./time-range.ts";+import { applyTemporalBridge } from "./temporal-bridge.ts";+import { resolveTimeRange } from "./time-range.ts";+import { eventTimeInRange, parseValidityWindow, type ValidityWindow } from "./validity.ts";import { expandByTraversal, type TraversalOptions } from "./traversal.ts";import { Store } from "./store.ts";import { SearchError } from "./types.ts";@@ -254,10 +267,15 @@ export async function search(const lwFp = config.recall.learnedWeightsEnabled? learnedWeightsFingerprint(config.vault): "off";+ // The activation state evolves with recorded accesses the same+ // way, so its fingerprint joins too (Time-Aware Recall Suite).+ const actFp = config.recall.activationEnabled+ ? activationStateFingerprint(config.vault)+ : "off";cacheKey = buildCacheKey(keyOpts,basePlan.planHash,- `${configFingerprint(config)}|lw:${lwFp}`,+ `${configFingerprint(config)}|lw:${lwFp}|act:${actFp}`,);const hit = getCachedOutcome(store, cacheKey, generation, ttlMs, Date.now());if (hit) return hit;@@ -342,7 +360,38 @@ export async function search(const allChunkIds = new Set<number>();for (const h of kwHits) allChunkIds.add(h.chunkId);for (const h of semHits) allChunkIds.add(h.chunkId);- const idsList = Array.from(allChunkIds);+ let idsList = Array.from(allChunkIds);++ // Self-correcting two-pass recall (t_ef92dfdc): a zero-candidate+ // first pass in evidence-pack mode means the implicit-AND keyword+ // match was too strict - the classic abstention dead end. Instead+ // of returning empty, run EXACTLY ONE broadened retry that keeps+ // the first significant term as the base group and ORs the rest in+ // as alternatives, then let the merged pool flow through the normal+ // ranking, filters, and a recomputed evidence pack.+ let secondPass: SearchOutcome["secondPass"];+ if (idsList.length === 0 && opts.evidencePack === true && config.recall.twoPassEnabled) {+ const terms = significantTerms(query);+ if (terms.length >= 2) {+ const broadened = runFtsQueryDetailed(store, terms[0]!, {+ expandedTerms: terms.slice(1),+ limit: Math.max(limit * 5, 50),+ pathPrefix: pathPrefix ?? null,+ });+ for (const w of broadened.warnings) warnings.push(w);+ if (broadened.hits.length > 0) {+ kwHits = broadened.hits;+ for (const h of kwHits) allChunkIds.add(h.chunkId);+ idsList = Array.from(allChunkIds);+ secondPass = Object.freeze({+ triggered: true,+ reason: "zero-candidate first pass; broadened OR retry",+ added: kwHits.length,+ });+ }+ }+ }+if (idsList.length === 0) {const evidencePack =opts.evidencePack === true@@ -363,10 +412,37 @@ export async function search(// Time-aware recall (recall-trust-suite): drop out-of-range// candidates BEFORE ranking so every later phase (traversal seeds,// MMR, relation polarity) sees only in-range candidates.+ // Event-time discipline (t_b7191486): a document declaring+ // `valid_from` / `valid_until` is tested by validity-window+ // OVERLAP - storage mtime is the fallback, never the authority,+ // when explicit event time exists. One cached frontmatter read per+ // candidate path; an unparseable declared value warns once and+ // falls back to mtime.+ const validityWindowCache = new Map<string, ValidityWindow | null>();+ const validityWindowFor = (path: string): ValidityWindow | null => {+ if (validityWindowCache.has(path)) return validityWindowCache.get(path) ?? null;+ let window: ValidityWindow | null = null;+ try {+ const [meta] = parseFrontmatter(join(config.vault, path));+ window = parseValidityWindow(meta as Record<string, unknown>);+ } catch {+ window = null;+ }+ validityWindowCache.set(path, window);+ return window;+ };if (timeRange !== null) {+ const warnedInvalid = new Set<string>();+ const windowFor = validityWindowFor;const inRange = (chunkId: number): boolean => {const h = hydrated.get(chunkId);- return h !== undefined && mtimeInRange(h.mtime, timeRange);+ if (h === undefined) return false;+ const window = windowFor(h.path);+ if (window?.invalid === true && !warnedInvalid.has(h.path)) {+ warnedInvalid.add(h.path);+ warnings.push(`validity: unparseable valid_from/valid_until in ${h.path}; using mtime`);+ }+ return eventTimeInRange(window, h.mtime, timeRange);};kwHits = kwHits.filter((h) => inRange(h.chunkId));semHits = semHits.filter((h) => inRange(h.chunkId));@@ -395,6 +471,111 @@ export async function search(? store.chunkEntityMatches(idsList, entityExpansion.added): undefined;+ // Access-reinforced activation (Time-Aware Recall & Activation+ // Suite): map the derived activation state onto the candidate set.+ // O(candidates): one state read per query, one frontmatter read per+ // candidate path that actually carries activation. The type+ // half-life decays the stored strength at read time, so a vault+ // without recorded events contributes nothing and ranks+ // bit-identically.+ let activationByChunk: ReadonlyMap<number, number> | undefined;+ let coAccessByChunk: ReadonlyMap<number, ReadonlyMap<number, number>> | undefined;+ if (config.recall.activationEnabled) {+ const activationState = readActivationState(config.vault);+ if (activationState !== null && Object.keys(activationState.paths).length > 0) {+ const nowActivationMs = Date.now();+ const kindCache = new Map<string, string>();+ const kindFor = (path: string): string => {+ const cached = kindCache.get(path);+ if (cached !== undefined) return cached;+ let fmKind: string | null = null;+ try {+ const [meta] = parseFrontmatter(join(config.vault, path));+ const raw = (meta as Record<string, unknown>)["kind"];+ fmKind = typeof raw === "string" ? raw : null;+ } catch {+ fmKind = null;+ }+ const kind = resolveActivationKind(fmKind, path);+ kindCache.set(path, kind);+ return kind;+ };+ const byChunk = new Map<number, number>();+ for (const chunkId of idsList) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ const row = activationState.paths[h.path];+ if (row === undefined) continue;+ const days = (nowActivationMs - row.lastAccessAt) / (24 * 60 * 60 * 1000);+ const act = effectiveActivation(row.strength, days, halfLifeDays(kindFor(h.path)));+ if (act > 0) byChunk.set(chunkId, act);+ }+ if (byChunk.size > 0) activationByChunk = byChunk;+ }+ // Co-access companions (t_c5ef25a3): restrict the recorded pairs+ // to documents present in this candidate set, then hand each+ // chunk its companion documentIds with pair counts. Pairs seen+ // fewer than CO_ACCESS_MIN_COUNT times are noise and skipped.+ if (activationState !== null && activationState.coAccess.length > 0) {+ const docIdByPath = new Map<string, number>();+ const chunksByDocId = new Map<number, number[]>();+ for (const chunkId of idsList) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ docIdByPath.set(h.path, h.documentId);+ const list = chunksByDocId.get(h.documentId) ?? [];+ list.push(chunkId);+ chunksByDocId.set(h.documentId, list);+ }+ const companionsByChunk = new Map<number, Map<number, number>>();+ const addCompanion = (ownDoc: number, otherDoc: number, count: number): void => {+ for (const chunkId of chunksByDocId.get(ownDoc) ?? []) {+ const m = companionsByChunk.get(chunkId) ?? new Map<number, number>();+ m.set(otherDoc, Math.max(m.get(otherDoc) ?? 0, count));+ companionsByChunk.set(chunkId, m);+ }+ };+ for (const pair of activationState.coAccess) {+ if (pair.count < CO_ACCESS_MIN_COUNT) continue;+ const docA = docIdByPath.get(pair.a);+ const docB = docIdByPath.get(pair.b);+ if (docA === undefined || docB === undefined) continue;+ addCompanion(docA, docB, pair.count);+ addCompanion(docB, docA, pair.count);+ }+ if (companionsByChunk.size > 0) coAccessByChunk = companionsByChunk;+ }+ }++ // Freshness-trend bias (t_ee09a6ce): preference pages stamped with+ // a `freshness_trend` by the dream refresh get a bounded relevance+ // multiplier. Restricted to Brain/preferences/ paths - the stamp is+ // a preference-lifecycle field, not a generic page property - and+ // O(candidate preference pages) frontmatter reads.+ // Cache note: like the tier signal, the stamp is read from+ // frontmatter at query time and is NOT part of the query-cache key;+ // a dream re-stamp reaches cached queries on the next reindex (the+ // content change bumps the corpus generation).+ let trendByDoc: ReadonlyMap<number, string> | undefined;+ {+ const byDoc = new Map<number, string>();+ const seenDocs = new Set<number>();+ for (const chunkId of idsList) {+ const h = hydrated.get(chunkId);+ if (h === undefined || seenDocs.has(h.documentId)) continue;+ seenDocs.add(h.documentId);+ if (!h.path.startsWith("Brain/preferences/")) continue;+ try {+ const [meta] = parseFrontmatter(join(config.vault, h.path));+ const trend = parseFreshnessTrend((meta as Record<string, unknown>)["freshness_trend"]);+ if (trend !== null) byDoc.set(h.documentId, trend);+ } catch {+ // Unreadable frontmatter stays neutral.+ }+ }+ if (byDoc.size > 0) trendByDoc = byDoc;+ }+// When a property filter is active, overfetch the ranked// candidates so the post-filter result set still has a chance// of producing `limit` matching rows. Without this, the@@ -446,6 +627,9 @@ export async function search(inboundLinkSources,tagsByDoc,...(entityMatchByChunk !== undefined ? { entityMatchByChunk } : {}),+ ...(activationByChunk !== undefined ? { activationByChunk } : {}),+ ...(coAccessByChunk !== undefined ? { coAccessByChunk } : {}),+ ...(trendByDoc !== undefined ? { trendByDoc } : {}),},{keywordWeight: opts.keywordWeight ?? config.keywordWeight,@@ -474,6 +658,27 @@ export async function search(hopDecay: config.recall.hopDecay,maxExpansionPerHit: config.recall.maxExpansionPerHit,});+ // Temporal bridge (t_c3871f0c): with an active time range,+ // traversal expansions must stay within a padded event-time+ // neighbourhood of the window - linked causes/consequences+ // bridge in with proximity-decayed scores, arbitrary old+ // neighbours do not. Event time = validity start, else mtime.+ if (timeRange !== null) {+ ranked = applyTemporalBridge(ranked, {+ range: timeRange,+ eventTimeMs: (path) => {+ const w = validityWindowFor(path);+ if (w !== null && !w.invalid && (w.validFromMs !== null || w.validUntilMs !== null)) {+ return w.validFromMs ?? w.validUntilMs!;+ }+ try {+ return statSync(join(config.vault, path)).mtimeMs;+ } catch {+ return Number.NEGATIVE_INFINITY;+ }+ },+ });+ }}// Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.if (mmrActive) {@@ -555,10 +760,22 @@ export async function search(: r,): withStructuredReasons;+ // Two-pass attribution (t_ef92dfdc): every surfaced result of a+ // broadened retry says so - the operator can tell recovered+ // evidence from a first-pass hit.+ const withSecondPassReasons =+ secondPass !== undefined+ ? withCanonicalReasons.map((r) =>+ Object.freeze({+ ...r,+ reasons: Object.freeze([...r.reasons, "second_pass: or-broadened retry"]),+ }),+ )+ : withCanonicalReasons;const finalResults =opts.evidencePack === true- ? downrankTerminalEvidenceResults(withCanonicalReasons)- : withCanonicalReasons;+ ? downrankTerminalEvidenceResults(withSecondPassReasons)+ : withSecondPassReasons;const evidencePack =opts.evidencePack === true? buildEvidencePack(@@ -568,12 +785,35 @@ export async function search(): undefined;+ // Access recording (Time-Aware Recall & Activation Suite): the+ // orchestrator edge opted in, so persist which documents this query+ // surfaced - AFTER ranking, so the current query is never affected+ // by its own recording. Cache hits return earlier and never reach+ // this point. Best-effort: a failed write never breaks the search.+ if (opts.recordAccess === true && config.recall.activationEnabled && finalResults.length > 0) {+ const surfacedPaths = Array.from(new Set(finalResults.map((r) => r.path))).slice(+ 0,+ ACCESS_EVENT_PATHS_CAP,+ );+ const normalized = query.trim().replace(/\s+/gu, " ").toLowerCase();+ try {+ recordAccessEvent(config.vault, {+ ts: Date.now(),+ queryHash: fnv1aHex(normalized),+ paths: surfacedPaths,+ });+ } catch {+ warnings.push("activation: failed to record access event");+ }+ }+return finalize(Object.freeze({results: Object.freeze(finalResults),warnings: Object.freeze(warnings),total: finalResults.length,...(evidencePack !== undefined ? { evidencePack } : {}),+ ...(secondPass !== undefined ? { secondPass } : {}),}),);} finally {diff --git a/src/core/search/temporal-bridge.ts b/src/core/search/temporal-bridge.tsnew file mode 100644index 00000000..a36c3b95--- /dev/null+++ b/src/core/search/temporal-bridge.ts@@ -0,0 +1,101 @@+/**+ * Temporal-bridge traversal (Time-Aware Recall & Activation Suite,+ * t_c3871f0c).+ *+ * Link-graph traversal and time-range filtering used to be separate+ * concerns: candidates were filtered to the window BEFORE ranking, but+ * traversal expansions were fetched fresh and never time-checked, so a+ * time-scoped query could leak arbitrarily old linked documents. This+ * module makes the composition intentional: an expansion document is+ * kept only when its EVENT time (validity start, else mtime) falls+ * within a padded neighbourhood of the query window, and its score+ * decays linearly with the distance - "what happened around X" pulls+ * in causes and consequences, not the whole link neighbourhood.+ *+ * Pure function: `search.ts` supplies the resolved range and an+ * event-time resolver; relevance hits (non-`link` results) are never+ * touched.+ */++import type { ResolvedTimeRange } from "./time-range.ts";+import type { BrainSearchResult } from "./types.ts";++/** Default event-time pad around the query window, in days. */+export const DEFAULT_WINDOW_PAD_DAYS = 7;++const DAY_MS = 24 * 60 * 60 * 1000;++/**+ * Temporal proximity of an event time to a window, in [0, 1]. Inside+ * the window (or past an open edge) is 1; outside, the proximity falls+ * linearly to `1 / (pad + 1)` at exactly `pad` days out and 0 beyond.+ */+export function temporalProximity(+ eventMs: number,+ range: ResolvedTimeRange,+ windowPadDays: number,+): number {+ let distanceMs = 0;+ if (range.sinceMs !== null && eventMs < range.sinceMs) {+ distanceMs = range.sinceMs - eventMs;+ } else if (range.untilMs !== null && eventMs > range.untilMs) {+ distanceMs = eventMs - range.untilMs;+ }+ if (distanceMs === 0) return 1;+ const deltaDays = distanceMs / DAY_MS;+ if (deltaDays > windowPadDays) return 0;+ return (windowPadDays + 1 - deltaDays) / (windowPadDays + 1);+}++export interface TemporalBridgeOptions {+ readonly range: ResolvedTimeRange;+ /** Pad in days; defaults to {@link DEFAULT_WINDOW_PAD_DAYS}. */+ readonly windowPadDays?: number;+ /** Event time (unix ms) for a path: validity start, else mtime. */+ readonly eventTimeMs: (path: string) => number;+}++/**+ * Apply the bridge to a traversal-expanded result list: drop link+ * expansions beyond the pad, decay the rest by temporal proximity with+ * an explainable `temporal_bridge` reason, and re-sort by score.+ */+export function applyTemporalBridge(+ results: ReadonlyArray<BrainSearchResult>,+ opts: TemporalBridgeOptions,+): BrainSearchResult[] {+ const pad = opts.windowPadDays ?? DEFAULT_WINDOW_PAD_DAYS;+ const out: BrainSearchResult[] = [];+ for (const r of results) {+ if (r.searchType !== "link") {+ out.push(r);+ continue;+ }+ const eventMs = opts.eventTimeMs(r.path);+ const proximity = temporalProximity(eventMs, opts.range, pad);+ if (proximity === 0) continue;+ if (proximity === 1) {+ out.push(r);+ continue;+ }+ let distanceMs = 0;+ if (opts.range.sinceMs !== null && eventMs < opts.range.sinceMs) {+ distanceMs = opts.range.sinceMs - eventMs;+ } else if (opts.range.untilMs !== null && eventMs > opts.range.untilMs) {+ distanceMs = eventMs - opts.range.untilMs;+ }+ const deltaDays = distanceMs / DAY_MS;+ out.push(+ Object.freeze({+ ...r,+ score: r.score * proximity,+ reasons: Object.freeze([+ ...r.reasons,+ `temporal_bridge: ${deltaDays.toFixed(1)}d x${proximity.toFixed(3)}`,+ ]),+ }),+ );+ }+ out.sort((a, b) => b.score - a.score || a.chunkId - b.chunkId);+ return out;+}diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex aabaed9b..7786d032 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -232,6 +232,15 @@ export interface SearchOptions {readonly focusSession?: string;/** Opt-in verified evidence pack diagnostics. Omitted preserves the legacy search outcome shape. */readonly evidencePack?: boolean;+ /**+ * Access recording (Time-Aware Recall & Activation Suite). When true,+ * the surfaced result paths are recorded as one activation access+ * event AFTER ranking completes - the current query's own ranking is+ * never affected by its own recording, and cache hits never record.+ * Default false: the pure core stays read-only; CLI/MCP surfaces opt+ * in explicitly.+ */+ readonly recordAccess?: boolean;/*** History mode for relation polarity (recall-trust-suite). When true a* matched predecessor (`superseded_by` declarer) keeps its rank and no@@ -264,6 +273,17 @@ export interface SearchOutcome {readonly warnings: ReadonlyArray<string>;readonly total: number;readonly evidencePack?: EvidencePack;+ /**+ * Self-correcting two-pass recall (Time-Aware Recall & Activation+ * Suite, t_ef92dfdc). Present only when a zero-candidate first pass+ * in evidence-pack mode triggered the single broadened OR retry.+ */+ readonly secondPass?: {+ readonly triggered: true;+ readonly reason: string;+ /** Candidate hits the broadened pass contributed. */+ readonly added: number;+ };}export interface ResolvedEmbeddingConfig {@@ -351,6 +371,22 @@ export interface ResolvedRecallConfig {* resettable — see `feedback.ts`.*/readonly learnedWeightsEnabled: boolean;+ /**+ * Access-reinforced activation (Time-Aware Recall & Activation+ * Suite). On by default: recorded access events under+ * `Brain/search/activation/` feed a bounded, type-decayed activation+ * boost and co-access companion boost. A vault without recorded+ * events ranks bit-identically either way; this switch exists as the+ * explicit kill switch.+ */+ readonly activationEnabled: boolean;+ /**+ * Self-correcting two-pass recall (t_ef92dfdc). On by default: a+ * zero-candidate first pass in evidence-pack mode runs exactly one+ * broadened OR retry instead of dead-ending in an abstention.+ * Plain (non-evidence-pack) searches never broaden either way.+ */+ readonly twoPassEnabled: boolean;}export interface ResolvedSearchConfig {diff --git a/src/core/search/validity.ts b/src/core/search/validity.tsnew file mode 100644index 00000000..67613d8f--- /dev/null+++ b/src/core/search/validity.ts@@ -0,0 +1,106 @@+/**+ * Event-time validity windows (Time-Aware Recall & Activation Suite,+ * t_b7191486).+ *+ * OSB stores bi-temporal frontmatter (`valid_from` / `valid_until` =+ * event time, file mtime = storage time) but time-range recall used to+ * filter on mtime alone - the classic storage-vs-event-time confusion+ * (the largest LongMemEval failure category). This module makes the+ * declared validity window the authority: a document passes a+ * `since`/`until` filter iff its validity interval INTERSECTS the query+ * window. Storage time is consulted only when no parseable event time+ * exists.+ *+ * Pure functions; the orchestrator (`search.ts`) supplies frontmatter+ * and the resolved range. Accepted value forms are bare ISO dates+ * (day-start for `valid_from`, day-end for `valid_until`, UTC) and ISO+ * datetimes - never relative phrases, which would make stored+ * frontmatter clock-dependent.+ */++import type { ResolvedTimeRange } from "./time-range.ts";+import { mtimeInRange } from "./time-range.ts";++export interface ValidityWindow {+ /** Event-time start (unix ms), or null when open / undeclared. */+ readonly validFromMs: number | null;+ /** Event-time end (unix ms, inclusive), or null when open / undeclared. */+ readonly validUntilMs: number | null;+ /** True when a declared value failed to parse (mtime fallback applies). */+ readonly invalid: boolean;+}++const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;+const DAY_MS = 24 * 60 * 60 * 1000;++/** Parse one frontmatter validity value. `edge` picks day-bound snapping. */+function parseValidityPoint(raw: unknown, edge: "from" | "until"): number | null {+ if (typeof raw !== "string") {+ // YAML may parse a bare date into a Date object.+ if (raw instanceof Date && Number.isFinite(raw.getTime())) return raw.getTime();+ return null;+ }+ const text = raw.trim();+ if (text === "") return null;+ const date = ISO_DATE_RE.exec(text);+ if (date) {+ const ms = Date.UTC(Number(date[1]), Number(date[2]) - 1, Number(date[3]));+ const check = new Date(ms);+ if (+ check.getUTCFullYear() !== Number(date[1]) ||+ check.getUTCMonth() !== Number(date[2]) - 1 ||+ check.getUTCDate() !== Number(date[3])+ ) {+ return null;+ }+ return edge === "from" ? ms : ms + DAY_MS - 1;+ }+ if (text.includes("T") || text.includes("t")) {+ const hasOffset = /(?:z|[+-]\d{2}:?\d{2})$/i.test(text);+ const parsed = Date.parse(hasOffset ? text : `${text}Z`);+ if (Number.isFinite(parsed)) return parsed;+ }+ return null;+}++/**+ * Read the validity window off a document's frontmatter. Returns null+ * when neither field is declared; `invalid: true` when a declared+ * value failed to parse (the caller falls back to mtime and warns).+ */+export function parseValidityWindow(meta: Record<string, unknown>): ValidityWindow | null {+ const hasFrom = meta["valid_from"] !== undefined && meta["valid_from"] !== null;+ const hasUntil = meta["valid_until"] !== undefined && meta["valid_until"] !== null;+ if (!hasFrom && !hasUntil) return null;+ const validFromMs = hasFrom ? parseValidityPoint(meta["valid_from"], "from") : null;+ const validUntilMs = hasUntil ? parseValidityPoint(meta["valid_until"], "until") : null;+ const invalid = (hasFrom && validFromMs === null) || (hasUntil && validUntilMs === null);+ return Object.freeze({ validFromMs, validUntilMs, invalid });+}++/**+ * Event-time range test: the validity interval must intersect the+ * query window. A null window (no validity fields) and an invalid one+ * both fall back to the mtime rule - never silently dropped.+ */+export function eventTimeInRange(+ window: ValidityWindow | null,+ mtimeSeconds: number,+ range: ResolvedTimeRange,+): boolean {+ if (window === null || window.invalid) return mtimeInRange(mtimeSeconds, range);+ // Interval overlap with open sides: the document's event span is+ // [validFrom, validUntil] (either side open), the query window is+ // [since, until] (either side open).+ if (range.untilMs !== null && window.validFromMs !== null && window.validFromMs > range.untilMs) {+ return false;+ }+ if (+ range.sinceMs !== null &&+ window.validUntilMs !== null &&+ window.validUntilMs < range.sinceMs+ ) {+ return false;+ }+ return true;+}diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex fbd52b94..9c4175a5 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -70,6 +70,11 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {limit: { type: "integer", minimum: 1, maximum: MCP_LIMIT_MAX },semantic: { type: "boolean" },keyword_only: { type: "boolean" },+ record_access: {+ type: "boolean",+ description:+ "Record the surfaced paths as one activation access event (feeds the usage-aware ranking layer). Default true; never recorded for global searches.",+ },global: {type: "boolean",description:@@ -288,6 +293,7 @@ async function toolBrainSearch(const includeSuperseded = coerceBoolOptional(args, "include_superseded") ?? false;const since = coerceStringOptional(args, "since", 64);const until = coerceStringOptional(args, "until", 64);+ const recordAccess = coerceBoolOptional(args, "record_access") ?? true;const telemetry = coerceBoolOptional(args, "telemetry") ?? false;const telemetryHost = coerceStringOptional(args, "telemetry_host", 200) ?? "mcp";const telemetrySessionId = coerceStringOptional(args, "session_id", 512);@@ -332,6 +338,10 @@ async function toolBrainSearch(...(includeSuperseded ? { includeSuperseded: true } : {}),...(since !== undefined ? { since } : {}),...(until !== undefined ? { until } : {}),+ // Access recording (Time-Aware Recall & Activation Suite): the MCP+ // surface opts in by default; record_access=false suppresses it,+ // and cross-vault union never records (results span foreign vaults).+ ...(recordAccess && !globalSearch ? { recordAccess: true } : {}),};try {// Cross-vault union (t_72a22658): explicit per-call opt-in.diff --git a/tests/cli/brain-activation.test.ts b/tests/cli/brain-activation.test.tsnew file mode 100644index 00000000..c92dccdd--- /dev/null+++ b/tests/cli/brain-activation.test.ts@@ -0,0 +1,89 @@+/**+ * `o2b brain activation` CLI surface (Time-Aware Recall & Activation+ * Suite, t_2bc79017): status and sweep over the activation event store.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { recordAccessEvent } from "../../src/core/search/activation/store.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-activation-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("status reports the folded activation state", async () => {+ const now = Date.now();+ recordAccessEvent(vault, {+ ts: now - 1000,+ queryHash: "abcd0001",+ paths: ["Brain/notes/a.md", "Brain/notes/b.md"],+ });+ recordAccessEvent(vault, {+ ts: now,+ queryHash: "abcd0002",+ paths: ["Brain/notes/a.md"],+ });+ const res = await runCli(["brain", "activation", "status", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ events: number;+ paths: number;+ co_access_pairs: number;+ top: Array<{ path: string; access_count: number }>;+ };+ expect(body.events).toBe(2);+ expect(body.paths).toBe(2);+ expect(body.co_access_pairs).toBe(1);+ expect(body.top[0]?.path).toBe("Brain/notes/a.md");+ expect(body.top[0]?.access_count).toBe(2);+});++test("status on an empty vault is a zero envelope, not an error", async () => {+ const res = await runCli(["brain", "activation", "status", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { events: number };+ expect(body.events).toBe(0);+});++test("sweep drops events beyond the cap and reports counts", async () => {+ const now = Date.now();+ for (let i = 0; i < 5; i++) {+ recordAccessEvent(vault, {+ ts: now - i * 1000,+ queryHash: "abcd0003",+ paths: [`Brain/n${i}.md`],+ });+ }+ const res = await runCli([+ "brain",+ "activation",+ "sweep",+ "--max-events",+ "2",+ "--vault",+ vault,+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { removed: number; kept: number };+ expect(body.removed).toBe(3);+ expect(body.kept).toBe(2);+});++test("an unknown operation exits 2 with usage", async () => {+ const res = await runCli(["brain", "activation", "bogus", "--vault", vault]);+ expect(res.returncode).toBe(2);+});diff --git a/tests/cli/brain-procedural-learning.test.ts b/tests/cli/brain-procedural-learning.test.tsindex f1163700..594a3094 100644--- a/tests/cli/brain-procedural-learning.test.ts+++ b/tests/cli/brain-procedural-learning.test.ts@@ -179,7 +179,9 @@ test("brain procedural learning verbs wire end-to-end", async () => {expect(showRecurrence.returncode).toBe(0);const recShowJson = JSON.parse(showRecurrence.stdout);expect(recShowJson.supportCount).toBe(1);-});+ // The end-to-end chain spawns many sequential CLI processes and can+ // exceed bun's 5s default per-test timeout on a loaded machine.+}, 20000);function seedContinuity(vaultPath: string): void {for (const row of [diff --git a/tests/cli/brain.snapshot-diff.test.ts b/tests/cli/brain.snapshot-diff.test.tsindex 19ba4abf..4e728d93 100644--- a/tests/cli/brain.snapshot-diff.test.ts+++ b/tests/cli/brain.snapshot-diff.test.ts@@ -241,7 +241,9 @@ pinned: falseexpect(r.returncode).toBe(0);expect(r.stdout).toContain(`- A: ${first}`);expect(r.stdout).toContain(`- B: ${second}`);- });+ // Seven sequential CLI invocations legitimately exceed bun's 5s+ // default per-test timeout on a loaded machine.+ }, 20000);test("--json returns parseable JSON", async () => {await bootstrap();diff --git a/tests/cli/search.test.ts b/tests/cli/search.test.tsindex 6e11c00a..017d6c2c 100644--- a/tests/cli/search.test.ts+++ b/tests/cli/search.test.ts@@ -253,8 +253,11 @@ test("search --evidence-pack --json exposes verification fields (union, completewriteVaultFile("zephyr-note.md", "# Zephyr\n\nthe zephyr daemon owns the import pipeline");await runCli(["search", "index"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });+ // Two-pass recall would now recover results for this AND dead end;+ // disable it - this test exercises the zero-result union/completeness+ // verification fields themselves.const out = await runCli(["search", "alpha zephyr", "--evidence-pack", "--json"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },+ env: { OPEN_SECOND_BRAIN_CONFIG: config, OPEN_SECOND_BRAIN_SEARCH_TWO_PASS: "false" },});expect(out.returncode).toBe(0);const json = JSON.parse(out.stdout) as {diff --git a/tests/core/brain/freshness-trend.test.ts b/tests/core/brain/freshness-trend.test.tsnew file mode 100644index 00000000..4d5d2ae3--- /dev/null+++ b/tests/core/brain/freshness-trend.test.ts@@ -0,0 +1,201 @@+/**+ * Freshness-trend classification (Time-Aware Recall & Activation+ * Suite, t_ee09a6ce): pure classifier over evidence-event time+ * distributions, surfaced on the belief-evolution envelope and stamped+ * into preference frontmatter by the dream refresh pass.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { preferencePath } from "../../../src/core/brain/paths.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { buildBeliefEvolution } from "../../../src/core/brain/temporal/belief-evolution.ts";+import { buildTimelineIndex } from "../../../src/core/brain/temporal/build-index.ts";+import {+ classifyFreshnessTrend,+ type FreshnessTrend,+} from "../../../src/core/brain/temporal/freshness-trend.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const NOW = Date.UTC(2026, 5, 1, 12, 0, 0); // 2026-06-01T12:00:00Z+const DAY = 24 * 60 * 60 * 1000;++function iso(offsetDays: number): string {+ return new Date(NOW - offsetDays * DAY).toISOString();+}++function applied(atDaysAgo: number): { at: string; result: "applied" } {+ return { at: iso(atDaysAgo), result: "applied" };+}++function violated(atDaysAgo: number): { at: string; result: "violated" } {+ return { at: iso(atDaysAgo), result: "violated" };+}++function evidenceLine(ts: string, result: string): string {+ return JSON.stringify({+ ts,+ kind: "apply-evidence",+ payload: { preference: "pref-foo", result, artifact: "[[x]]" },+ });+}++describe("classifyFreshnessTrend (pure)", () => {+ test("a young preference with no prior evidence is new", () => {+ const r = classifyFreshnessTrend({ createdAt: iso(3), events: [], nowMs: NOW });+ expect(r.trend).toBe("new" as FreshnessTrend);+ });++ test("no evidence on an old preference is stale", () => {+ const r = classifyFreshnessTrend({ createdAt: iso(200), events: [], nowMs: NOW });+ expect(r.trend).toBe("stale");+ });++ test("last evidence older than the stale window is stale", () => {+ const r = classifyFreshnessTrend({+ createdAt: iso(200),+ events: [applied(90), applied(75)],+ nowMs: NOW,+ });+ expect(r.trend).toBe("stale");+ });++ test("more recent applies than prior-window applies is strengthening", () => {+ const r = classifyFreshnessTrend({+ createdAt: iso(200),+ events: [applied(45), applied(20), applied(10), applied(2)],+ nowMs: NOW,+ });+ expect(r.trend).toBe("strengthening");+ expect(r.recentApplied).toBe(3);+ expect(r.priorApplied).toBe(1);+ });++ test("rising violations or fading applies is weakening", () => {+ const violations = classifyFreshnessTrend({+ createdAt: iso(200),+ events: [applied(45), applied(40), applied(10), violated(5), violated(2)],+ nowMs: NOW,+ });+ expect(violations.trend).toBe("weakening");+ const fading = classifyFreshnessTrend({+ createdAt: iso(200),+ events: [applied(50), applied(45), applied(40), applied(20)],+ nowMs: NOW,+ });+ expect(fading.trend).toBe("weakening");+ });++ test("a steady cadence is stable", () => {+ const r = classifyFreshnessTrend({+ createdAt: iso(200),+ events: [applied(45), applied(35), applied(20), applied(10)],+ nowMs: NOW,+ });+ expect(r.trend).toBe("stable");+ });++ test("deterministic against the injected clock", () => {+ const events = [applied(45), applied(10)];+ const a = classifyFreshnessTrend({ createdAt: iso(200), events, nowMs: NOW });+ const b = classifyFreshnessTrend({ createdAt: iso(200), events, nowMs: NOW });+ expect(a).toEqual(b);+ });+});++describe("belief-evolution envelope carries the trend", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-trend-evo-"));+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ test("freshnessTrend reflects the evidence distribution", () => {+ writeFileSync(+ join(vault, "Brain", "log", "2026-05-25.jsonl"),+ evidenceLine("2026-05-25T08:00:00Z", "applied") + "\n",+ );+ writeFileSync(+ join(vault, "Brain", "log", "2026-05-30.jsonl"),+ evidenceLine("2026-05-30T08:00:00Z", "applied") + "\n",+ );+ const idx = buildTimelineIndex(vault, {});+ const evo = buildBeliefEvolution(+ idx,+ vault,+ { prefId: "pref-foo" },+ {+ now: new Date(NOW),+ },+ );+ expect(evo.freshnessTrend).toBeDefined();+ expect(evo.freshnessTrend?.trend).toBe("strengthening");+ });+});++describe("dream refresh stamps freshness_trend", () => {+ let vault: string;+ let configHome: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-trend-dream-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-trend-cfg-"));+ atomicWriteFileSync(join(configHome, "config.yaml"), `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath: join(configHome, "config.yaml") });+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ });++ test("a refreshed preference carries the computed trend in frontmatter", () => {+ const topic = "trend-stamp";+ for (let i = 0; i < 3; i++) {+ writeSignal(vault, {+ topic,+ signal: "positive",+ agent: "claude",+ principle: "Stamp freshness trends on refresh.",+ created_at: `2026-05-12T0${i + 1}:00:00Z`,+ date: "2026-05-12",+ slug: `seed-${i}`,+ scope: "coding",+ });+ }+ dream(vault, { now: new Date("2026-05-12T10:00:00Z") });+ appendApplyEvidence(+ vault,+ {+ pref_id: `pref-${topic}`,+ artifact: "[[src/lib/example.ts]]",+ result: "applied",+ agent: "claude",+ },+ { now: new Date("2026-05-20T10:00:00Z") },+ );+ dream(vault, { now: new Date("2026-05-21T10:00:00Z") });+ const raw = readFileSync(preferencePath(vault, topic), "utf8");+ expect(raw).toMatch(/freshness_trend: (new|strengthening|stable|weakening|stale)/);++ // No-op rerun stays a no-op: the trend is classified at PLAN time,+ // so the pre-flight render matches the stamped bytes and a rerun+ // with identical state reports changed=false (CodeRabbit PR #73).+ const rerun = dream(vault, { now: new Date("2026-05-21T10:00:00Z") });+ expect(rerun.changed).toBe(false);+ expect(readFileSync(preferencePath(vault, topic), "utf8")).toBe(raw);+ });+});diff --git a/tests/core/search/activation-decay.test.ts b/tests/core/search/activation-decay.test.tsnew file mode 100644index 00000000..506fadbf--- /dev/null+++ b/tests/core/search/activation-decay.test.ts@@ -0,0 +1,96 @@+/**+ * Activation kernel math (Time-Aware Recall & Activation Suite,+ * t_2bc79017): pure ACT-R-style strength bump and type-aware half-life+ * decay. No I/O, injected ages only.+ */++import { describe, expect, test } from "bun:test";++import {+ ACTIVATION_STRENGTH_MAX,+ ACTIVATION_STRENGTH_STEP,+ DEFAULT_HALF_LIFE_DAYS,+ bumpStrength,+ effectiveActivation,+ halfLifeDays,+ resolveActivationKind,+} from "../../../src/core/search/activation/decay.ts";++describe("half-life table", () => {+ test("preference, decision, and antipattern never decay", () => {+ expect(halfLifeDays("preference")).toBeNull();+ expect(halfLifeDays("decision")).toBeNull();+ expect(halfLifeDays("antipattern")).toBeNull();+ });++ test("project, handoff, session, and note carry the documented half-lives", () => {+ expect(halfLifeDays("project")).toBe(120);+ expect(halfLifeDays("handoff")).toBe(30);+ expect(halfLifeDays("session")).toBe(30);+ expect(halfLifeDays("note")).toBe(DEFAULT_HALF_LIFE_DAYS);+ });++ test("an unknown kind falls back to the note default", () => {+ expect(halfLifeDays("totally-custom-kind")).toBe(DEFAULT_HALF_LIFE_DAYS);+ });+});++describe("resolveActivationKind", () => {+ test("frontmatter kind wins over the path", () => {+ expect(resolveActivationKind("Decision", "Brain/notes/x.md")).toBe("decision");+ expect(resolveActivationKind("handoff", "Brain/preferences/pref-x.md")).toBe("handoff");+ });++ test("the framework brain- prefix is stripped", () => {+ expect(resolveActivationKind("brain-preference", "Brain/preferences/pref-x.md")).toBe(+ "preference",+ );+ expect(resolveActivationKind("Brain-Decision", "Brain/notes/x.md")).toBe("decision");+ });++ test("path prefixes resolve framework directories without frontmatter", () => {+ expect(resolveActivationKind(null, "Brain/preferences/pref-x.md")).toBe("preference");+ expect(resolveActivationKind(null, "Brain/decisions/panels/p.md")).toBe("decision");+ });++ test("everything else defaults to note", () => {+ expect(resolveActivationKind(null, "Projects/atlas/overview.md")).toBe("note");+ expect(resolveActivationKind("", "Daily/2026.06.04.md")).toBe("note");+ });+});++describe("bumpStrength", () => {+ test("adds one step and caps at the maximum", () => {+ expect(bumpStrength(0)).toBeCloseTo(ACTIVATION_STRENGTH_STEP, 10);+ expect(bumpStrength(0.35)).toBeCloseTo(0.45, 10);+ expect(bumpStrength(ACTIVATION_STRENGTH_MAX)).toBe(ACTIVATION_STRENGTH_MAX);+ expect(bumpStrength(0.95)).toBe(ACTIVATION_STRENGTH_MAX);+ });++ test("junk input is treated as zero strength", () => {+ expect(bumpStrength(Number.NaN)).toBeCloseTo(ACTIVATION_STRENGTH_STEP, 10);+ expect(bumpStrength(-5)).toBeCloseTo(ACTIVATION_STRENGTH_STEP, 10);+ });+});++describe("effectiveActivation", () => {+ test("an infinite half-life never decays", () => {+ expect(effectiveActivation(0.8, 0, null)).toBe(0.8);+ expect(effectiveActivation(0.8, 3650, null)).toBe(0.8);+ });++ test("a finite half-life halves the strength every half-life", () => {+ expect(effectiveActivation(0.8, 0, 30)).toBeCloseTo(0.8, 10);+ expect(effectiveActivation(0.8, 30, 30)).toBeCloseTo(0.4, 10);+ expect(effectiveActivation(0.8, 60, 30)).toBeCloseTo(0.2, 10);+ });++ test("future access times clamp to age zero", () => {+ expect(effectiveActivation(0.6, -10, 30)).toBeCloseTo(0.6, 10);+ });++ test("non-finite inputs yield zero", () => {+ expect(effectiveActivation(Number.NaN, 10, 30)).toBe(0);+ expect(effectiveActivation(0.5, Number.POSITIVE_INFINITY, 30)).toBe(0);+ });+});diff --git a/tests/core/search/activation-ranking.test.ts b/tests/core/search/activation-ranking.test.tsnew file mode 100644index 00000000..e1026bf9--- /dev/null+++ b/tests/core/search/activation-ranking.test.ts@@ -0,0 +1,155 @@+/**+ * Activation ranking layer (Time-Aware Recall & Activation Suite,+ * t_2bc79017): effective activation becomes a bounded, explainable+ * ranking boost; access recording happens at the orchestrator edge and+ * never affects the query that produced it.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";++import { loadAccessEvents, recordAccessEvent } from "../../../src/core/search/activation/store.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++const QUERY = "perimeter calibration";++function activationReason(reasons: ReadonlyArray<string>): number | null {+ const entry = reasons.find((r) => r.startsWith("activation: "));+ if (entry === undefined) return null;+ return Number(entry.slice("activation: ".length));+}++async function seed(): Promise<void> {+ writeMd(+ vault,+ "Brain/notes/alpha.md",+ "# Alpha\n\nPerimeter calibration baseline notes for the alpha array.\n",+ );+ writeMd(+ vault,+ "Brain/notes/beta.md",+ "# Beta\n\nPerimeter calibration baseline notes for the beta array.\n",+ );+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("activation-rank"));+});++afterEach(() => {+ cleanup();+});++describe("activation boost", () => {+ test("a vault without access events ranks identically to the layer being off", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const off = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1, activationEnabled: false });+ const a = await search(config, { query: QUERY });+ const b = await search(off, { query: QUERY });+ // Same order, same reasons; scores match to recency-drift precision+ // (the Weibull recency layer reads the real clock, so two calls a+ // few ms apart differ in the 9th decimal regardless of activation).+ expect(a.results.map((r) => r.path)).toEqual(b.results.map((r) => r.path));+ a.results.forEach((r, i) => expect(r.score).toBeCloseTo(b.results[i]!.score, 6));+ expect(a.results.every((r) => activationReason(r.reasons) === null)).toBe(true);+ });++ test("recorded accesses surface as a bounded activation reason", async () => {+ await seed();+ const now = Date.now();+ for (let i = 0; i < 5; i++) {+ recordAccessEvent(vault, {+ ts: now - i * 1000,+ queryHash: "cafe0001",+ paths: ["Brain/notes/beta.md"],+ });+ }+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: QUERY });+ const beta = outcome.results.find((r) => r.path === "Brain/notes/beta.md");+ const alpha = outcome.results.find((r) => r.path === "Brain/notes/alpha.md");+ const betaBoost = activationReason(beta!.reasons);+ expect(betaBoost).not.toBeNull();+ expect(betaBoost!).toBeGreaterThan(0);+ expect(betaBoost!).toBeLessThanOrEqual(0.04);+ expect(activationReason(alpha!.reasons)).toBeNull();+ });++ test("preference pages outlast notes after long idle (type half-life)", async () => {+ writeMd(+ vault,+ "Brain/preferences/pref-calibration.md",+ "---\nkind: brain-preference\n---\n\n# Pref\n\nPerimeter calibration rule.\n",+ );+ await seed();+ const old = Date.now() - 90 * 24 * 60 * 60 * 1000;+ for (const p of ["Brain/preferences/pref-calibration.md", "Brain/notes/beta.md"]) {+ recordAccessEvent(vault, { ts: old, queryHash: "cafe0002", paths: [p] });+ }+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: QUERY, limit: 10 });+ const pref = outcome.results.find((r) => r.path.startsWith("Brain/preferences/"));+ const beta = outcome.results.find((r) => r.path === "Brain/notes/beta.md");+ const prefBoost = activationReason(pref!.reasons);+ const betaBoost = activationReason(beta!.reasons);+ expect(prefBoost).not.toBeNull();+ // The note decayed (60d half-life, 90d idle); the preference did not.+ expect(prefBoost!).toBeGreaterThan(betaBoost ?? 0);+ });++ test("the kill switch suppresses the layer even with events present", async () => {+ await seed();+ recordAccessEvent(vault, {+ ts: Date.now(),+ queryHash: "cafe0003",+ paths: ["Brain/notes/beta.md"],+ });+ const off = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1, activationEnabled: false });+ const outcome = await search(off, { query: QUERY });+ expect(outcome.results.every((r) => activationReason(r.reasons) === null)).toBe(true);+ });+});++describe("access recording at the orchestrator edge", () => {+ test("recordAccess writes one event with the surfaced paths", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: QUERY, recordAccess: true });+ expect(outcome.results.length).toBeGreaterThan(0);+ const events = loadAccessEvents(vault);+ expect(events).toHaveLength(1);+ expect(events[0]?.paths).toContain("Brain/notes/alpha.md");+ expect(events[0]?.paths).toContain("Brain/notes/beta.md");+ // Privacy: the event stores a hash, never the raw query.+ expect(JSON.stringify(events[0])).not.toContain("perimeter");+ });++ test("recording is off by default and never affects the current query", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const plain = await search(config, { query: QUERY });+ expect(loadAccessEvents(vault)).toHaveLength(0);+ const recorded = await search(config, { query: QUERY, recordAccess: true });+ expect(plain.results.map((r) => r.path)).toEqual(recorded.results.map((r) => r.path));+ // The recording call's own ranking carries no activation layer (the+ // event lands after ranking); scores match to recency-drift precision.+ plain.results.forEach((r, i) => expect(r.score).toBeCloseTo(recorded.results[i]!.score, 6));+ expect(recorded.results.every((r) => activationReason(r.reasons) === null)).toBe(true);+ });++ test("a zero-result query records nothing", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await search(config, { query: "zzzqxv nonexistent", recordAccess: true });+ expect(loadAccessEvents(vault)).toHaveLength(0);+ });+});diff --git a/tests/core/search/activation-store.test.ts b/tests/core/search/activation-store.test.tsnew file mode 100644index 00000000..e51f0be7--- /dev/null+++ b/tests/core/search/activation-store.test.ts@@ -0,0 +1,173 @@+/**+ * Activation event store (Time-Aware Recall & Activation Suite,+ * t_2bc79017 + t_c5ef25a3): one JSON file per recorded access under+ * `Brain/search/activation/`, a replayable fold into the derived+ * activation state, and a bounded sweep.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ ACCESS_EVENT_PATHS_CAP,+ activationDir,+ activationStateFingerprint,+ activationStatePath,+ computeActivationState,+ loadAccessEvents,+ readActivationState,+ recordAccessEvent,+ sweepActivationEvents,+} from "../../../src/core/search/activation/store.ts";+import type { ActivationAccessEvent } from "../../../src/core/search/activation/types.ts";++let vault: string;++const T0 = Date.UTC(2026, 5, 1, 10, 0, 0);+const DAY = 24 * 60 * 60 * 1000;++function ev(ts: number, paths: string[]): ActivationAccessEvent {+ return { ts, queryHash: "deadbeef", paths };+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-activation-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("recordAccessEvent", () => {+ test("writes one event file and refreshes the derived state", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/notes/a.md", "Brain/notes/b.md"]));+ expect(readdirSync(activationDir(vault)).filter((f) => f.endsWith(".json"))).toHaveLength(1);+ const state = readActivationState(vault);+ expect(state?.events).toBe(1);+ expect(state?.paths["Brain/notes/a.md"]?.accessCount).toBe(1);+ });++ test("recording the identical event twice is idempotent", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/notes/a.md"]));+ recordAccessEvent(vault, ev(T0, ["Brain/notes/a.md"]));+ expect(loadAccessEvents(vault)).toHaveLength(1);+ });++ test("surfaced paths are capped per event", () => {+ const many = Array.from({ length: 25 }, (_, i) => `Brain/notes/n${i}.md`);+ recordAccessEvent(vault, ev(T0, many));+ const events = loadAccessEvents(vault);+ expect(events[0]?.paths).toHaveLength(ACCESS_EVENT_PATHS_CAP);+ });+});++describe("computeActivationState", () => {+ test("strength accumulates per access and caps at 1.0", () => {+ const events = Array.from({ length: 12 }, (_, i) => ev(T0 + i * 1000, ["Brain/notes/hot.md"]));+ const state = computeActivationState(events);+ expect(state.paths["Brain/notes/hot.md"]?.strength).toBe(1);+ expect(state.paths["Brain/notes/hot.md"]?.accessCount).toBe(12);+ expect(state.paths["Brain/notes/hot.md"]?.lastAccessAt).toBe(T0 + 11 * 1000);+ });++ test("the fold is order-insensitive", () => {+ const a = ev(T0, ["Brain/x.md", "Brain/y.md"]);+ const b = ev(T0 + 1000, ["Brain/y.md", "Brain/z.md"]);+ const c = ev(T0 + 2000, ["Brain/x.md"]);+ expect(computeActivationState([a, b, c])).toEqual(computeActivationState([c, a, b]));+ });++ test("co-access pairs count unordered companions", () => {+ const state = computeActivationState([+ ev(T0, ["Brain/x.md", "Brain/y.md"]),+ ev(T0 + 1000, ["Brain/y.md", "Brain/x.md"]),+ ev(T0 + 2000, ["Brain/x.md", "Brain/z.md"]),+ ]);+ const xy = state.coAccess.find((p) => p.a === "Brain/x.md" && p.b === "Brain/y.md");+ expect(xy?.count).toBe(2);+ const xz = state.coAccess.find((p) => p.a === "Brain/x.md" && p.b === "Brain/z.md");+ expect(xz?.count).toBe(1);+ });++ test("empty input yields the neutral state", () => {+ const state = computeActivationState([]);+ expect(state.events).toBe(0);+ expect(Object.keys(state.paths)).toHaveLength(0);+ expect(state.coAccess).toHaveLength(0);+ });+});++describe("replayability and robustness", () => {+ test("deleting the derived state and refolding reproduces it exactly", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/x.md", "Brain/y.md"]));+ recordAccessEvent(vault, ev(T0 + 1000, ["Brain/y.md"]));+ const first = readActivationState(vault);+ rmSync(activationStatePath(vault));+ const refolded = computeActivationState(loadAccessEvents(vault));+ expect(refolded).toEqual(first!);+ });++ test("a malformed event file never breaks the fold", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/x.md"]));+ writeFileSync(join(activationDir(vault), "zz-junk.json"), "{not json");+ writeFileSync(join(activationDir(vault), "zz-shape.json"), JSON.stringify({ ts: "no" }));+ expect(loadAccessEvents(vault)).toHaveLength(1);+ });++ test("corrupt nested rows in the derived state read as null (fail closed)", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/x.md"]));+ const good = readActivationState(vault)!;+ const poisonPath = {+ ...good,+ paths: { "Brain/x.md": { strength: "NaN", lastAccessAt: T0, accessCount: 1 } },+ };+ writeFileSync(activationStatePath(vault), JSON.stringify(poisonPath));+ expect(readActivationState(vault)).toBeNull();+ const poisonPair = { ...good, coAccess: [{ a: "Brain/x.md", count: 2 }] };+ writeFileSync(activationStatePath(vault), JSON.stringify(poisonPair));+ expect(readActivationState(vault)).toBeNull();+ });++ test("fingerprint is 'off' without state and stable with it", () => {+ expect(activationStateFingerprint(vault)).toBe("off");+ recordAccessEvent(vault, ev(T0, ["Brain/x.md"]));+ const fp = activationStateFingerprint(vault);+ expect(fp).not.toBe("off");+ expect(activationStateFingerprint(vault)).toBe(fp);+ });+});++describe("sweepActivationEvents", () => {+ test("drops events older than the retention window and refolds", () => {+ recordAccessEvent(vault, ev(T0 - 120 * DAY, ["Brain/old.md"]));+ recordAccessEvent(vault, ev(T0, ["Brain/new.md"]));+ const outcome = sweepActivationEvents(vault, { nowMs: T0 + 1000 });+ expect(outcome.removed).toBe(1);+ expect(outcome.kept).toBe(1);+ const state = readActivationState(vault);+ expect(state?.paths["Brain/old.md"]).toBeUndefined();+ expect(state?.paths["Brain/new.md"]).toBeDefined();+ });++ test("keeps only the newest events beyond the count cap", () => {+ for (let i = 0; i < 7; i++) {+ recordAccessEvent(vault, ev(T0 + i * 1000, [`Brain/n${i}.md`]));+ }+ const outcome = sweepActivationEvents(vault, { nowMs: T0 + DAY, maxEvents: 3 });+ expect(outcome.removed).toBe(4);+ expect(outcome.kept).toBe(3);+ expect(loadAccessEvents(vault).map((e) => e.ts)).toEqual([T0 + 4000, T0 + 5000, T0 + 6000]);+ });++ test("a missing event directory refolds a leftover derived state to empty", () => {+ recordAccessEvent(vault, ev(T0, ["Brain/x.md"]));+ rmSync(activationDir(vault), { recursive: true, force: true });+ const outcome = sweepActivationEvents(vault, { nowMs: T0 + DAY });+ expect(outcome).toEqual({ removed: 0, kept: 0 });+ const state = readActivationState(vault);+ expect(state?.events).toBe(0);+ expect(Object.keys(state?.paths ?? { x: 1 })).toHaveLength(0);+ });+});diff --git a/tests/core/search/co-access.test.ts b/tests/core/search/co-access.test.tsnew file mode 100644index 00000000..4ee002f4--- /dev/null+++ b/tests/core/search/co-access.test.ts@@ -0,0 +1,89 @@+/**+ * Co-access reinforcement (Time-Aware Recall & Activation Suite,+ * t_c5ef25a3): documents habitually surfaced together gain a bounded+ * companion boost when they appear in the same candidate pool.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";++import { recordAccessEvent } from "../../../src/core/search/activation/store.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++const QUERY = "lattice resonance";++function coAccessReason(reasons: ReadonlyArray<string>): number | null {+ const entry = reasons.find((r) => r.startsWith("co_access: "));+ if (entry === undefined) return null;+ return Number(entry.slice("co_access: ".length));+}++async function seed(): Promise<void> {+ writeMd(vault, "Brain/notes/alpha.md", "# Alpha\n\nLattice resonance survey, alpha rig.\n");+ writeMd(vault, "Brain/notes/beta.md", "# Beta\n\nLattice resonance survey, beta rig.\n");+ writeMd(vault, "Brain/notes/gamma.md", "# Gamma\n\nLattice resonance survey, gamma rig.\n");+ writeMd(vault, "Brain/notes/offside.md", "# Offside\n\nUnrelated marsh cartography.\n");+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+}++function coAccess(times: number, paths: string[]): void {+ const now = Date.now();+ for (let i = 0; i < times; i++) {+ recordAccessEvent(vault, { ts: now - i * 1000, queryHash: "feed0001", paths });+ }+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("co-access"));+});++afterEach(() => {+ cleanup();+});++describe("co-access companion boost", () => {+ test("habitual companions in the same pool gain a bounded co_access reason", async () => {+ await seed();+ coAccess(3, ["Brain/notes/beta.md", "Brain/notes/gamma.md"]);+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: QUERY, limit: 10 });+ const beta = outcome.results.find((r) => r.path === "Brain/notes/beta.md");+ const gamma = outcome.results.find((r) => r.path === "Brain/notes/gamma.md");+ const alpha = outcome.results.find((r) => r.path === "Brain/notes/alpha.md");+ expect(coAccessReason(beta!.reasons)).toBeGreaterThan(0);+ expect(coAccessReason(gamma!.reasons)).toBeGreaterThan(0);+ expect(coAccessReason(beta!.reasons)!).toBeLessThanOrEqual(0.03);+ expect(coAccessReason(alpha!.reasons)).toBeNull();+ });++ test("a single co-occurrence is below the noise threshold", async () => {+ await seed();+ coAccess(1, ["Brain/notes/beta.md", "Brain/notes/gamma.md"]);+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: QUERY, limit: 10 });+ expect(outcome.results.every((r) => coAccessReason(r.reasons) === null)).toBe(true);+ });++ test("a companion outside the candidate pool contributes nothing", async () => {+ await seed();+ coAccess(3, ["Brain/notes/beta.md", "Brain/notes/offside.md"]);+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: QUERY, limit: 10 });+ expect(outcome.results.some((r) => r.path === "Brain/notes/offside.md")).toBe(false);+ expect(outcome.results.every((r) => coAccessReason(r.reasons) === null)).toBe(true);+ });++ test("the kill switch suppresses companion boosts", async () => {+ await seed();+ coAccess(3, ["Brain/notes/beta.md", "Brain/notes/gamma.md"]);+ const off = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1, activationEnabled: false });+ const outcome = await search(off, { query: QUERY, limit: 10 });+ expect(outcome.results.every((r) => coAccessReason(r.reasons) === null)).toBe(true);+ });+});diff --git a/tests/core/search/completeness.test.ts b/tests/core/search/completeness.test.tsindex 315f9659..7c272dde 100644--- a/tests/core/search/completeness.test.ts+++ b/tests/core/search/completeness.test.ts@@ -82,7 +82,9 @@ test("a fully covered query yields a complete verdict in the pack", async () =>test("zero results over terms the corpus contains trips the false-absence guard", async () => {writeMd(vault, "alpha-note.md", "# Alpha\n\nthe alpha subsystem owns the export pipeline");writeMd(vault, "zephyr-note.md", "# Zephyr\n\nthe zephyr daemon owns the import pipeline");- const cfg = makeConfig({ vault, dbPath });+ // Two-pass recall would now recover results for this AND dead end;+ // disable it - this test exercises the false-absence guard itself.+ const cfg = makeConfig({ vault, dbPath, twoPassEnabled: false });await indexVault(cfg);// AND semantics: no document holds both terms → zero results, butdiff --git a/tests/core/search/coverage.test.ts b/tests/core/search/coverage.test.tsindex 6e136a55..fd3bdf2d 100644--- a/tests/core/search/coverage.test.ts+++ b/tests/core/search/coverage.test.ts@@ -98,7 +98,9 @@ test("per-token union gathers records for terms the ranked set left uncovered",writeMd(vault, "alpha-note.md", "# Alpha\n\nthe alpha subsystem owns the export pipeline");writeMd(vault, "zephyr-note.md", "# Zephyr\n\nthe zephyr daemon owns the import pipeline");writeMd(vault, "filler.md", "# Filler\n\nunrelated prose about gardening");- const cfg = makeConfig({ vault, dbPath });+ // Two-pass recall would now recover results for this AND dead end;+ // disable it - this test exercises the zero-result union machinery.+ const cfg = makeConfig({ vault, dbPath, twoPassEnabled: false });await indexVault(cfg);// FTS joins tokens with implicit AND: no document contains both terms,diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.tsindex 5cd98d32..a36c759b 100644--- a/tests/core/search/store.test.ts+++ b/tests/core/search/store.test.ts@@ -53,6 +53,8 @@ function makeConfig(overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchCocacheTtlSeconds: 300,relationPolarityEnabled: true,learnedWeightsEnabled: false,+ activationEnabled: true,+ twoPassEnabled: true,}),...overrides,});diff --git a/tests/core/search/store.vec.test.ts b/tests/core/search/store.vec.test.tsindex 57c3de78..2777596f 100644--- a/tests/core/search/store.vec.test.ts+++ b/tests/core/search/store.vec.test.ts@@ -56,6 +56,8 @@ function semanticConfig(cacheTtlSeconds: 300,relationPolarityEnabled: true,learnedWeightsEnabled: false,+ activationEnabled: true,+ twoPassEnabled: true,}),...overrides,});diff --git a/tests/core/search/temporal-bridge.test.ts b/tests/core/search/temporal-bridge.test.tsnew file mode 100644index 00000000..f685c5db--- /dev/null+++ b/tests/core/search/temporal-bridge.test.ts@@ -0,0 +1,191 @@+/**+ * Temporal-bridge traversal (Time-Aware Recall & Activation Suite,+ * t_c3871f0c): with an active time range, traversal expansions are kept+ * only inside a padded event-time neighbourhood of the window and are+ * scored with temporal-proximity decay - causes and consequences, not+ * arbitrary link leakage.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";+import { utimesSync } from "node:fs";++import {+ applyTemporalBridge,+ temporalProximity,+} from "../../../src/core/search/temporal-bridge.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import type { BrainSearchResult } from "../../../src/core/search/types.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++const DAY = 24 * 60 * 60 * 1000;+const NOW = Date.UTC(2026, 5, 1, 12, 0, 0);++function linkResult(path: string, score: number): BrainSearchResult {+ return Object.freeze({+ documentId: path.length,+ chunkId: path.length * 10,+ path,+ title: null,+ content: "linked",+ startLine: 1,+ endLine: 1,+ score,+ keywordScore: 0,+ semanticScore: 0,+ linkBoost: 0,+ recencyBoost: 0,+ searchType: "link" as const,+ reasons: Object.freeze(["link_traversal: hop 1 from seed.md"]),+ });+}++function hitResult(path: string, score: number): BrainSearchResult {+ return Object.freeze({+ documentId: path.length,+ chunkId: path.length * 10,+ path,+ title: null,+ content: "hit",+ startLine: 1,+ endLine: 1,+ score,+ keywordScore: 0.5,+ semanticScore: 0,+ linkBoost: 0,+ recencyBoost: 0,+ searchType: "keyword" as const,+ reasons: Object.freeze(["fts5_bm25: 0.500"]),+ });+}++describe("temporalProximity (pure)", () => {+ const range = { sinceMs: NOW - 7 * DAY, untilMs: NOW };++ test("inside the window is full proximity", () => {+ expect(temporalProximity(NOW - 2 * DAY, range, 7)).toBe(1);+ });++ test("outside decays linearly with distance and dies past the pad", () => {+ const threeOut = temporalProximity(NOW - 10 * DAY, range, 7);+ const sevenOut = temporalProximity(NOW - 14 * DAY, range, 7);+ expect(threeOut).toBeGreaterThan(sevenOut);+ expect(sevenOut).toBeGreaterThan(0);+ expect(temporalProximity(NOW - 15 * DAY, range, 7)).toBe(0);+ });++ test("an open edge never excludes", () => {+ const openSince = { sinceMs: null, untilMs: NOW };+ expect(temporalProximity(NOW - 365 * DAY, openSince, 7)).toBe(1);+ });+});++describe("applyTemporalBridge (pure)", () => {+ const range = { sinceMs: NOW - 7 * DAY, untilMs: NOW };+ const eventTimes = new Map<string, number>([+ ["near.md", NOW - 10 * DAY],+ ["far.md", NOW - 60 * DAY],+ ["inside.md", NOW - 1 * DAY],+ ]);+ const resolver = (path: string): number => eventTimes.get(path) ?? NOW;++ test("keeps padded neighbours with decayed scores, drops the rest", () => {+ const out = applyTemporalBridge(+ [hitResult("seed.md", 0.9), linkResult("near.md", 0.4), linkResult("far.md", 0.4)],+ { range, windowPadDays: 7, eventTimeMs: resolver },+ );+ const paths = out.map((r) => r.path);+ expect(paths).toContain("near.md");+ expect(paths).not.toContain("far.md");+ const near = out.find((r) => r.path === "near.md")!;+ expect(near.score).toBeLessThan(0.4);+ expect(near.reasons.some((x) => x.startsWith("temporal_bridge: "))).toBe(true);+ });++ test("expansions inside the window keep their score", () => {+ const out = applyTemporalBridge([linkResult("inside.md", 0.4)], {+ range,+ windowPadDays: 7,+ eventTimeMs: resolver,+ });+ expect(out[0]?.score).toBe(0.4);+ });++ test("relevance hits are never touched", () => {+ const out = applyTemporalBridge([hitResult("far.md", 0.8)], {+ range,+ windowPadDays: 7,+ eventTimeMs: resolver,+ });+ expect(out).toHaveLength(1);+ expect(out[0]?.score).toBe(0.8);+ });+});++describe("search() composes traversal with the time window", () => {+ let vault: string;+ let dbPath: string;+ let cleanup: () => void;++ beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("temporal-bridge"));+ });++ afterEach(() => {+ cleanup();+ });++ test("a linked neighbour within the pad bridges in; a distant one does not", async () => {+ const now = Date.now();+ writeMd(+ vault,+ "Brain/notes/incident.md",+ "# Incident\n\nReactor coolant excursion timeline.\n\n" ++ "[[Brain/notes/prep-work.md|prep]] [[Brain/notes/ancient-history.md|ancient]]\n",+ );+ const prep = writeMd(vault, "Brain/notes/prep-work.md", "# Prep\n\nValve maintenance log.\n");+ const ancient = writeMd(+ vault,+ "Brain/notes/ancient-history.md",+ "# Ancient\n\nCommissioning-era notes.\n",+ );+ const prepDate = new Date(now - 10 * DAY);+ const ancientDate = new Date(now - 90 * DAY);+ utimesSync(prep, prepDate, prepDate);+ utimesSync(ancient, ancientDate, ancientDate);+ const config = makeConfig({ vault, dbPath, maxHops: 1, mmrLambda: 1 });+ await indexVault(config);++ const outcome = await search(config, { query: "reactor coolant excursion", since: "7d" });+ const paths = outcome.results.map((r) => r.path);+ expect(paths).toContain("Brain/notes/incident.md");+ expect(paths).toContain("Brain/notes/prep-work.md");+ expect(paths).not.toContain("Brain/notes/ancient-history.md");+ const bridge = outcome.results.find((r) => r.path === "Brain/notes/prep-work.md");+ expect(bridge!.reasons.some((x) => x.startsWith("temporal_bridge: "))).toBe(true);+ });++ test("without a time range traversal behaviour is untouched", async () => {+ const now = Date.now();+ writeMd(+ vault,+ "Brain/notes/incident.md",+ "# Incident\n\nReactor coolant excursion timeline.\n\n" ++ "[[Brain/notes/ancient-history.md|ancient]]\n",+ );+ const ancient = writeMd(+ vault,+ "Brain/notes/ancient-history.md",+ "# Ancient\n\nCommissioning-era notes.\n",+ );+ const ancientDate = new Date(now - 90 * DAY);+ utimesSync(ancient, ancientDate, ancientDate);+ const config = makeConfig({ vault, dbPath, maxHops: 1, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: "reactor coolant excursion" });+ expect(outcome.results.map((r) => r.path)).toContain("Brain/notes/ancient-history.md");+ expect(+ outcome.results.every((r) => !r.reasons.some((x) => x.startsWith("temporal_bridge: "))),+ ).toBe(true);+ });+});diff --git a/tests/core/search/trend-ranking.test.ts b/tests/core/search/trend-ranking.test.tsnew file mode 100644index 00000000..03ca8b85--- /dev/null+++ b/tests/core/search/trend-ranking.test.ts@@ -0,0 +1,82 @@+/**+ * Freshness-trend ranking bias (Time-Aware Recall & Activation Suite,+ * t_ee09a6ce): preference pages stamped with a `freshness_trend` get a+ * bounded multiplier on the relevance portion of their score.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++const QUERY = "gearbox lubrication policy";++function trendReason(reasons: ReadonlyArray<string>): string | null {+ return reasons.find((r) => r.startsWith("freshness_trend: ")) ?? null;+}++function prefBody(trend: string | null): string {+ const trendLine = trend === null ? "" : `freshness_trend: ${trend}\n`;+ return (+ `---\nkind: brain-preference\n${trendLine}---\n\n` ++ "# Rule\n\nGearbox lubrication policy applies before deployment.\n"+ );+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("trend-rank"));+});++afterEach(() => {+ cleanup();+});++describe("freshness-trend multiplier", () => {+ test("weakening and stale preferences are demoted below an unstamped twin", async () => {+ writeMd(vault, "Brain/preferences/pref-plain.md", prefBody(null));+ writeMd(vault, "Brain/preferences/pref-weak.md", prefBody("weakening"));+ writeMd(vault, "Brain/preferences/pref-stale.md", prefBody("stale"));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: QUERY, limit: 10 });+ const score = (path: string): number => outcome.results.find((r) => r.path === path)!.score;+ expect(score("Brain/preferences/pref-weak.md")).toBeLessThan(+ score("Brain/preferences/pref-plain.md"),+ );+ expect(score("Brain/preferences/pref-stale.md")).toBeLessThan(+ score("Brain/preferences/pref-weak.md"),+ );+ const weak = outcome.results.find((r) => r.path === "Brain/preferences/pref-weak.md");+ expect(trendReason(weak!.reasons)).toContain("weakening");+ });++ test("a strengthening preference is boosted above an unstamped twin", async () => {+ writeMd(vault, "Brain/preferences/pref-plain.md", prefBody(null));+ writeMd(vault, "Brain/preferences/pref-strong.md", prefBody("strengthening"));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: QUERY, limit: 10 });+ const strong = outcome.results.find((r) => r.path === "Brain/preferences/pref-strong.md");+ const plain = outcome.results.find((r) => r.path === "Brain/preferences/pref-plain.md");+ expect(strong!.score).toBeGreaterThan(plain!.score);+ expect(trendReason(strong!.reasons)).toContain("strengthening");+ });++ test("stable and new trends stay neutral, as do non-preference pages", async () => {+ writeMd(vault, "Brain/preferences/pref-stable.md", prefBody("stable"));+ writeMd(+ vault,+ "Brain/notes/imposter.md",+ "---\nfreshness_trend: stale\n---\n\n# Note\n\nGearbox lubrication policy memo.\n",+ );+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: QUERY, limit: 10 });+ expect(outcome.results.every((r) => trendReason(r.reasons) === null)).toBe(true);+ });+});diff --git a/tests/core/search/two-pass.test.ts b/tests/core/search/two-pass.test.tsnew file mode 100644index 00000000..731bfe59--- /dev/null+++ b/tests/core/search/two-pass.test.ts@@ -0,0 +1,93 @@+/**+ * Self-correcting two-pass recall (Time-Aware Recall & Activation+ * Suite, t_ef92dfdc): a zero-candidate first pass in evidence-pack+ * mode triggers exactly one broadened OR retry instead of dead-ending+ * in an abstention.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++async function seed(): Promise<void> {+ writeMd(vault, "Brain/notes/fennel.md", "# Fennel\n\nFennel inventory ledger for the cellar.\n");+ writeMd(+ vault,+ "Brain/notes/warehouse.md",+ "# Warehouse\n\nWarehouse rotation schedule, bay seven.\n",+ );+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("two-pass"));+});++afterEach(() => {+ cleanup();+});++describe("two-pass recall", () => {+ test("a zero-candidate evidence query broadens once and recovers results", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ // Implicit-AND keyword matching finds no chunk with BOTH terms.+ const strict = await search(config, { query: "fennel warehouse" });+ expect(strict.results).toHaveLength(0);+ // Evidence-pack mode converts the dead end into a broadened retry.+ const outcome = await search(config, { query: "fennel warehouse", evidencePack: true });+ const paths = outcome.results.map((r) => r.path);+ expect(paths).toContain("Brain/notes/fennel.md");+ expect(paths).toContain("Brain/notes/warehouse.md");+ expect(outcome.secondPass?.triggered).toBe(true);+ expect(outcome.secondPass?.added).toBeGreaterThan(0);+ expect(outcome.results.every((r) => r.reasons.some((x) => x.startsWith("second_pass: ")))).toBe(+ true,+ );+ // The pack is recomputed over the recovered results.+ expect(outcome.evidencePack?.records.length).toBeGreaterThan(0);+ });++ test("plain searches never broaden", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: "fennel warehouse" });+ expect(outcome.results).toHaveLength(0);+ expect(outcome.secondPass).toBeUndefined();+ });++ test("the kill switch disables the retry", async () => {+ await seed();+ const off = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1, twoPassEnabled: false });+ const outcome = await search(off, { query: "fennel warehouse", evidencePack: true });+ expect(outcome.results).toHaveLength(0);+ expect(outcome.secondPass).toBeUndefined();+ expect(outcome.evidencePack?.abstention).not.toBeNull();+ });++ test("a single-term query has nothing to broaden", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: "zubrowka", evidencePack: true });+ expect(outcome.results).toHaveLength(0);+ expect(outcome.secondPass).toBeUndefined();+ });++ test("a successful first pass never triggers the retry", async () => {+ await seed();+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ const outcome = await search(config, { query: "fennel inventory", evidencePack: true });+ expect(outcome.results.length).toBeGreaterThan(0);+ expect(outcome.secondPass).toBeUndefined();+ expect(+ outcome.results.every((r) => !r.reasons.some((x) => x.startsWith("second_pass: "))),+ ).toBe(true);+ });+});diff --git a/tests/core/search/validity.test.ts b/tests/core/search/validity.test.tsnew file mode 100644index 00000000..bd004d60--- /dev/null+++ b/tests/core/search/validity.test.ts@@ -0,0 +1,130 @@+/**+ * Event-time vs storage-time discipline (Time-Aware Recall &+ * Activation Suite, t_b7191486): documents declaring `valid_from` /+ * `valid_until` are filtered by their validity window (interval+ * overlap), never by storage mtime; documents without validity fields+ * keep the mtime fallback byte-identically.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";+import { utimesSync } from "node:fs";++import { eventTimeInRange, parseValidityWindow } from "../../../src/core/search/validity.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++const DAY = 24 * 60 * 60 * 1000;++describe("parseValidityWindow (pure)", () => {+ test("absent fields mean no window", () => {+ expect(parseValidityWindow({})).toBeNull();+ expect(parseValidityWindow({ other: "x" })).toBeNull();+ });++ test("bare ISO dates resolve to day bounds in UTC", () => {+ const w = parseValidityWindow({ valid_from: "2026-05-01", valid_until: "2026-05-03" });+ expect(w?.validFromMs).toBe(Date.UTC(2026, 4, 1));+ expect(w?.validUntilMs).toBe(Date.UTC(2026, 4, 4) - 1);+ expect(w?.invalid).toBe(false);+ });++ test("one-sided windows leave the other edge open", () => {+ const from = parseValidityWindow({ valid_from: "2026-05-01T10:00:00Z" });+ expect(from?.validFromMs).toBe(Date.UTC(2026, 4, 1, 10));+ expect(from?.validUntilMs).toBeNull();+ const until = parseValidityWindow({ valid_until: "2026-05-01" });+ expect(until?.validFromMs).toBeNull();+ });++ test("junk values flag the window invalid", () => {+ const w = parseValidityWindow({ valid_from: "soonish" });+ expect(w?.invalid).toBe(true);+ });+});++describe("eventTimeInRange (pure)", () => {+ const range = { sinceMs: Date.UTC(2026, 4, 10), untilMs: Date.UTC(2026, 4, 20) };++ test("overlap semantics: any intersection passes", () => {+ const before = parseValidityWindow({ valid_from: "2026-05-01", valid_until: "2026-05-05" });+ const spanning = parseValidityWindow({ valid_from: "2026-05-05", valid_until: "2026-05-15" });+ const inside = parseValidityWindow({ valid_from: "2026-05-12", valid_until: "2026-05-13" });+ expect(eventTimeInRange(before, 0, range)).toBe(false);+ expect(eventTimeInRange(spanning, 0, range)).toBe(true);+ expect(eventTimeInRange(inside, 0, range)).toBe(true);+ });++ test("no window falls back to mtime", () => {+ const inRangeMtime = Date.UTC(2026, 4, 15) / 1000;+ const outRangeMtime = Date.UTC(2026, 4, 1) / 1000;+ expect(eventTimeInRange(null, inRangeMtime, range)).toBe(true);+ expect(eventTimeInRange(null, outRangeMtime, range)).toBe(false);+ });++ test("an invalid window also falls back to mtime", () => {+ const w = parseValidityWindow({ valid_from: "garbage" });+ expect(eventTimeInRange(w, Date.UTC(2026, 4, 15) / 1000, range)).toBe(true);+ expect(eventTimeInRange(w, Date.UTC(2026, 4, 1) / 1000, range)).toBe(false);+ });+});++describe("search() event-time discipline", () => {+ let vault: string;+ let dbPath: string;+ let cleanup: () => void;++ beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("validity"));+ });++ afterEach(() => {+ cleanup();+ });++ test("event time is the authority over storage time, both directions", async () => {+ const now = Date.now();+ const recentEvent = new Date(now - 2 * DAY).toISOString();+ const oldEvent = new Date(now - 200 * DAY).toISOString();+ // Old file describing a recent event: must be FOUND by since=7d.+ const oldFile = writeMd(+ vault,+ "Brain/notes/old-file-recent-event.md",+ `---\nvalid_from: ${recentEvent}\n---\n\n# Recent\n\nHarbor dredging incident report.\n`,+ );+ // Fresh file describing an old, closed event: must be EXCLUDED.+ writeMd(+ vault,+ "Brain/notes/new-file-old-event.md",+ `---\nvalid_from: ${oldEvent}\nvalid_until: ${oldEvent}\n---\n\n# Old\n\nHarbor dredging incident report.\n`,+ );+ // No validity fields: mtime fallback keeps it in range.+ writeMd(vault, "Brain/notes/plain.md", "# Plain\n\nHarbor dredging incident report.\n");+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ // Make the event-recent file's mtime ancient AFTER indexing the+ // content (the index stores mtime at index time, so reindex).+ const ancient = new Date(now - 300 * DAY);+ utimesSync(oldFile, ancient, ancient);+ await indexVault(config);++ const outcome = await search(config, { query: "harbor dredging incident", since: "7d" });+ const paths = outcome.results.map((r) => r.path);+ expect(paths).toContain("Brain/notes/old-file-recent-event.md");+ expect(paths).not.toContain("Brain/notes/new-file-old-event.md");+ expect(paths).toContain("Brain/notes/plain.md");+ });++ test("an unparseable validity value warns and falls back to mtime", async () => {+ writeMd(+ vault,+ "Brain/notes/broken.md",+ "---\nvalid_from: not-a-date\n---\n\n# Broken\n\nHarbor dredging incident report.\n",+ );+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);+ const outcome = await search(config, { query: "harbor dredging incident", since: "7d" });+ expect(outcome.results.map((r) => r.path)).toContain("Brain/notes/broken.md");+ expect(outcome.warnings.some((w) => w.includes("validity"))).toBe(true);+ });+});diff --git a/tests/e2e/time-aware-recall.integration.test.ts b/tests/e2e/time-aware-recall.integration.test.tsnew file mode 100644index 00000000..16fe8034--- /dev/null+++ b/tests/e2e/time-aware-recall.integration.test.ts@@ -0,0 +1,115 @@+/**+ * Time-Aware Recall & Activation Suite - end-to-end integration over+ * one vault: access-reinforced activation with co-access companions+ * (t_2bc79017 + t_c5ef25a3), freshness-trend ranking bias+ * (t_ee09a6ce), event-time recall discipline with temporal bridging+ * (t_b7191486 + t_c3871f0c), and the self-correcting two-pass retry+ * (t_ef92dfdc).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { utimesSync } from "node:fs";++import { loadAccessEvents } from "../../src/core/search/activation/store.ts";+import { indexVault } from "../../src/core/search/indexer.ts";+import { search } from "../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../helpers/search-fixtures.ts";++const DAY = 24 * 60 * 60 * 1000;++let vault: string;+let dbPath: string;+let cleanup: () => void;++function prefBody(trend: string | null): string {+ return (+ `---\nkind: brain-preference\n${trend ? `freshness_trend: ${trend}\n` : ""}---\n\n` ++ "# Rule\n\nGlacier deploy approvals are mandatory.\n"+ );+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("time-aware-e2e"));+});++afterEach(() => {+ cleanup();+});++test("the suite composes end to end on one vault", async () => {+ const now = Date.now();++ // -- Fixtures -------------------------------------------------------+ // A recurring working set: two notes habitually recalled together.+ writeMd(vault, "Brain/notes/runbook.md", "# Runbook\n\nGlacier deploy runbook steps.\n");+ writeMd(vault, "Brain/notes/checklist.md", "# Checklist\n\nGlacier deploy checklist items.\n");+ // Preferences: one weakening, one unstamped twin.+ writeMd(vault, "Brain/preferences/pref-fresh.md", prefBody(null));+ writeMd(vault, "Brain/preferences/pref-fading.md", prefBody("weakening"));+ // Event-time discipline: an old file describing a recent event.+ const oldFileRecentEvent = writeMd(+ vault,+ "Brain/notes/migration-window.md",+ `---\nvalid_from: ${new Date(now - 1 * DAY).toISOString()}\n---\n\n# Window\n\nGlacier migration window agreed.\n`,+ );+ // Temporal bridge: in-window incident linking to near-past prep work.+ writeMd(+ vault,+ "Brain/notes/incident.md",+ "# Incident\n\nGlacier migration window incident.\n\n[[Brain/notes/prep.md|prep]]\n",+ );+ const prep = writeMd(vault, "Brain/notes/prep.md", "# Prep\n\nPre-freeze valve work.\n");+ // Two-pass: terms split across documents (implicit AND finds nothing).+ writeMd(vault, "Brain/notes/permafrost.md", "# Permafrost\n\nPermafrost sensor archive.\n");+ writeMd(vault, "Brain/notes/turbine.md", "# Turbine\n\nTurbine maintenance ledger.\n");++ const config = makeConfig({ vault, dbPath, maxHops: 1, mmrLambda: 1 });+ await indexVault(config);+ // Age the event-time and bridge fixtures AFTER content indexing.+ const ancient = new Date(now - 200 * DAY);+ utimesSync(oldFileRecentEvent, ancient, ancient);+ const prepDate = new Date(now - 10 * DAY);+ utimesSync(prep, prepDate, prepDate);+ await indexVault(config);++ // -- Activation + co-access (t_2bc79017 + t_c5ef25a3) ---------------+ // Recall the working set repeatedly with recording on. Sequential on+ // purpose: each recording must land before the next query so the+ // event files carry distinct timestamps.+ await search(config, { query: "glacier deploy", recordAccess: true, limit: 5 });+ await search(config, { query: "glacier deploy", recordAccess: true, limit: 5 });+ await search(config, { query: "glacier deploy", recordAccess: true, limit: 5 });+ await search(config, { query: "glacier deploy", recordAccess: true, limit: 5 });+ expect(loadAccessEvents(vault).length).toBeGreaterThanOrEqual(1);+ const activated = await search(config, { query: "glacier deploy", limit: 10 });+ const runbook = activated.results.find((r) => r.path === "Brain/notes/runbook.md");+ expect(runbook).toBeDefined();+ expect(runbook!.reasons.some((x) => x.startsWith("activation: "))).toBe(true);+ expect(runbook!.reasons.some((x) => x.startsWith("co_access: "))).toBe(true);++ // -- Freshness-trend bias (t_ee09a6ce) ------------------------------+ const prefs = await search(config, { query: "glacier deploy approvals", limit: 10 });+ const fresh = prefs.results.find((r) => r.path === "Brain/preferences/pref-fresh.md");+ const fading = prefs.results.find((r) => r.path === "Brain/preferences/pref-fading.md");+ expect(fading!.score).toBeLessThan(fresh!.score);+ expect(fading!.reasons.some((x) => x.includes("weakening"))).toBe(true);++ // -- Event-time discipline + temporal bridge (t_b7191486 + t_c3871f0c)+ const windowed = await search(config, { query: "glacier migration window", since: "7d" });+ const windowedPaths = windowed.results.map((r) => r.path);+ // The 200-day-old FILE is found because its EVENT time is yesterday.+ expect(windowedPaths).toContain("Brain/notes/migration-window.md");+ // The linked prep work (10d out, within the 7d pad) bridges in.+ expect(windowedPaths).toContain("Brain/notes/prep.md");+ const bridged = windowed.results.find((r) => r.path === "Brain/notes/prep.md");+ expect(bridged!.reasons.some((x) => x.startsWith("temporal_bridge: "))).toBe(true);++ // -- Two-pass recovery (t_ef92dfdc) ---------------------------------+ const strict = await search(config, { query: "permafrost turbine" });+ expect(strict.results).toHaveLength(0);+ const recovered = await search(config, { query: "permafrost turbine", evidencePack: true });+ expect(recovered.secondPass?.triggered).toBe(true);+ const recoveredPaths = recovered.results.map((r) => r.path);+ expect(recoveredPaths).toContain("Brain/notes/permafrost.md");+ expect(recoveredPaths).toContain("Brain/notes/turbine.md");+});diff --git a/tests/helpers/search-fixtures.ts b/tests/helpers/search-fixtures.tsindex 2a12f094..7183db89 100644--- a/tests/helpers/search-fixtures.ts+++ b/tests/helpers/search-fixtures.ts@@ -65,6 +65,10 @@ export function makeConfig(opts: {relationPolarityEnabled?: boolean;/** Learned recall weights from feedback; defaults to false (opt-in). */learnedWeightsEnabled?: boolean;+ /** Access-reinforced activation; defaults to true (neutral without events). */+ activationEnabled?: boolean;+ /** Two-pass broadened retry in evidence-pack mode; defaults to true. */+ twoPassEnabled?: boolean;/** Rank-fusion mode; defaults to "linear". */fusionMode?: "linear" | "rrf";/** RRF damping constant; defaults to 60. */@@ -116,6 +120,8 @@ export function makeConfig(opts: {cacheTtlSeconds: 300,relationPolarityEnabled: opts.relationPolarityEnabled ?? true,learnedWeightsEnabled: opts.learnedWeightsEnabled ?? false,+ activationEnabled: opts.activationEnabled ?? true,+ twoPassEnabled: opts.twoPassEnabled ?? true,}),});}diff --git a/tests/python/test_hermes_plugin.py b/tests/python/test_hermes_plugin.pyindex c084b381..c65c9db9 100644--- a/tests/python/test_hermes_plugin.py+++ b/tests/python/test_hermes_plugin.py@@ -9,6 +9,7 @@ entrypoint re-export, and the identity-reminder template source of truth.import importlib.utilimport sys+import typesimport unittestfrom pathlib import Path@@ -93,55 +94,27 @@ class RegisterTests(unittest.TestCase):self.assertEqual(registered[0].name, PLUGIN_NAME)-class SelfBootstrapTests(unittest.TestCase):- """Locks the root entrypoint's single self-bootstrap load path.+class HermesLoaderContractTests(unittest.TestCase):+ """Locks the entrypoint against the updated Hermes loader contract.- The root ``__init__.py`` loads ``plugins/hermes`` by file path under a- private package name with ``submodule_search_locations`` so the- implementation's own relative imports resolve against it. This is the- plugin's one intentional, host-agnostic load path -- it does not depend on- the host runtime registering a parent namespace package for the plugin.- These tests pin that behaviour.+ Since hermes-agent PR #37366 the external memory-provider loader+ registers the synthetic ``_hermes_user_memory`` parent namespace in+ ``sys.modules`` before executing a user-installed plugin, so the+ entrypoint uses ordinary relative imports (no file-path self-bootstrap).+ This test mimics that exact loader sequence - parent shell registered,+ plugin executed under the synthetic dotted name - and asserts the+ entrypoint yields a working provider and ``register`` through the+ ``plugins/`` namespace intermediate directory."""- def test_filepath_load_of_impl_yields_provider(self):- impl_dir = ROOT / "plugins" / "hermes"- spec = importlib.util.spec_from_file_location(- "_osb_hermes_impl_test",- impl_dir / "__init__.py",- submodule_search_locations=[str(impl_dir)],- )- self.assertIsNotNone(spec)- module = importlib.util.module_from_spec(spec)- sys.modules[spec.name] = module- try:- spec.loader.exec_module(module)- provider = module.OpenSecondBrainMemoryProvider()- self.assertEqual(provider.name, PLUGIN_NAME)- self.assertTrue(callable(module.register))- finally:- for name in list(sys.modules):- if name == spec.name or name.startswith(spec.name + "."):- sys.modules.pop(name, None)+ SYNTHETIC_PARENT = "_hermes_user_memory"- def test_entrypoint_loads_without_parent_namespace_registered(self):- """Regression for the stock-Hermes load path.-- Hermes' external memory-provider loader imports a user-installed plugin- as ``_hermes_user_memory.<name>`` but does NOT register the- ``_hermes_user_memory`` parent in ``sys.modules``. A provider written- with ordinary relative/absolute imports fails there with- ``ModuleNotFoundError: No module named '_hermes_user_memory'``. The- self-bootstrap must load regardless, so this mimics that exact loader- condition (synthetic child name, parent intentionally absent) and- asserts the entrypoint still yields a working provider and ``register``.- """- synthetic = "_hermes_user_memory.open-second-brain"- self.assertNotIn(- "_hermes_user_memory",- sys.modules,- "parent namespace must be absent to reproduce the stock loader",- )+ def test_entrypoint_loads_under_synthetic_name_with_parent_registered(self):+ synthetic = f"{self.SYNTHETIC_PARENT}.{PLUGIN_NAME}"+ # Mirror the loader: an empty namespace shell for the parent.+ parent = types.ModuleType(self.SYNTHETIC_PARENT)+ parent.__path__ = [] # mark it a package so child imports resolve+ sys.modules[self.SYNTHETIC_PARENT] = parentspec = importlib.util.spec_from_file_location(synthetic,ROOT / "__init__.py",@@ -150,12 +123,22 @@ class SelfBootstrapTests(unittest.TestCase):module = importlib.util.module_from_spec(spec)sys.modules[synthetic] = moduletry:- spec.loader.exec_module(module) # must not raise ModuleNotFoundError+ spec.loader.exec_module(module)provider = module.OpenSecondBrainMemoryProvider()self.assertEqual(provider.name, PLUGIN_NAME)self.assertTrue(callable(module.register))+ self.assertTrue(callable(module.register_cli))finally:- sys.modules.pop(synthetic, None)+ for name in list(sys.modules):+ if name == self.SYNTHETIC_PARENT or name.startswith(self.SYNTHETIC_PARENT + "."):+ sys.modules.pop(name, None)++ def test_entrypoint_has_no_selfbootstrap_machinery(self):+ """The crutch is gone: no private package name, no file-path import."""+ source = (ROOT / "__init__.py").read_text(encoding="utf-8")+ self.assertNotIn("_osb_hermes_impl", source)+ self.assertNotIn("spec_from_file_location", source)+ self.assertIn("from .plugins.hermes import", source)def test_register_does_not_raise_on_minimal_context(self):class Context: