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
v0.10.18 - temporal axis: timeline, belief evolution, stale watch, daily brief, weekly synthesis (#34)
Sol Aitkena8d480385e07
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 7617f308..998ee741 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.17",+ "version": "0.10.18","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 c858213e..cfc1505e 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.17",+ "version": "0.10.18","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/.gitignore b/.gitignoreindex 797ef03d..64dd831f 100644--- a/.gitignore+++ b/.gitignore@@ -23,3 +23,4 @@ node_modules/.open-second-brain.local.yamlsandbox-vault/.codegraph/+.orphaned_atdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex df2ba8a6..edaf1af1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,120 @@ 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.10.18] - 2026-05-25++Temporal + synthesis layer: seven related features that add time as+a first-class axis. A new `src/core/brain/temporal/` subsystem+materializes one `TimelineIndex` per invocation from+`Brain/log/<date>.jsonl` plus retired/ frontmatter, then five pure+projection helpers (`selectEvents`, `buildBeliefEvolution`,+`findStaleEntries`, `buildDailyBrief`, `buildWeeklySynthesis`) feed+five operator surfaces over that same index. Preference, signal,+and retired frontmatter grow additive optional `valid_from` /+`valid_until` / `recorded_at` slots so future write paths can+populate the bi-temporal axis without breaking existing files. A new+`temporal:` block in `_brain.yaml` tunes per-kind staleness+thresholds, daily window offset, and weekly window alignment. No+helper calls an LLM; every output is a deterministic data shape the+agent assembles into prose externally.++### Added++- `src/core/brain/temporal/types.ts` - `TemporalEvent` (flat shape+ reusing `BrainLogEventKind` plus optional denormalized slots),+ `TimelineIndex` (frozen materialized view with `ReadonlyMap`+ groups by kind / prefId / topic), `DreamSummarySlots` (denormalized+ array slice for belief-evolution).+- `src/core/brain/temporal/build-index.ts` -+ `buildTimelineIndex(vault, opts)`: the single disk-touching helper.+ Walks `Brain/log/*.jsonl` via the canonical `readLogDay` reader+ plus `Brain/retired/*.md` frontmatter; normalises every entry to+ one `TemporalEvent`; groups, sorts (ties broken by source path ++ line), freezes.+- `src/core/brain/temporal/select-events.ts` -+ `selectEvents(index, filters)`: pure projection, filters by AND+ of `prefId` / `topic` / `kind` / `since` / `until`. Picks the+ narrowest pre-grouped bucket the filter set permits.+- `src/core/brain/temporal/belief-evolution.ts` -+ `buildBeliefEvolution(index, vault, target)` for `prefId` or+ `topic`. Returns frozen `{target, transitions, evidence,+ retirements, generatedAt}`. Transitions derived from dream+ summary arrays (`new_unconfirmed` / `confirmed` / `retired`);+ evidence rollup carries per-row running counts; retirement chain+ walked via `supersedes` / `superseded_by` with a visited-set+ cycle guard.+- `src/core/brain/temporal/stale-watch.ts` -+ `findStaleEntries(index, vault, cfg)`. Pure structural staleness:+ walks `Brain/preferences/`, `Brain/inbox/`, `Brain/log/` against+ the configured per-kind day thresholds. Uses the timeline's+ most-recent event timestamp as the staleness anchor when present,+ falls back to `last_evidence_at` then `created_at` then file+ mtime depending on kind.+- `src/core/brain/temporal/daily-brief.ts` -+ `buildDailyBrief(index, vault, date, opts?)`. Daily counters,+ status transitions, vault delta, deduplicated artifact wikilinks.+ Window aligned to UTC midnight by default; configurable via+ `temporal.daily_window_offset_hours`.+- `src/core/brain/temporal/weekly-brief.ts` -+ `buildWeeklySynthesis(index, vault, weekEnd, cfg, opts?)`. 7-day+ window ending at `weekEnd`. Same counters as daily plus+ `retired-in-window` list and `contradictions` (`signal-suppressed`+ events combined with `apply-evidence` rows where `result ===+ "violated"`).+- `src/core/brain/temporal/period-common.ts` - shared helpers+ consumed by both briefs: `countByKind`, `collectTransitions`,+ `computeVaultDelta`, `collectSourcePointers`, `extractId`. One+ canonical implementation per helper.+- New atoms on existing types:+ - `BrainPreference`, `BrainSignal`, `BrainRetired`+ (`src/core/brain/types.ts`) gain optional `valid_from`,+ `valid_until`, `recorded_at` slots. Existing files stay+ byte-identical; parsers populate the slots only when present.+ - `isBrainLogEventKind(value)` exported from+ `src/core/brain/types.ts` so callers narrow strings without a+ runtime cast.+- New `temporal:` block in `_brain.yaml`+ (`src/core/brain/policy.ts`):+ - `stale_pref_days` (default 90)+ - `stale_signal_days` (default 30)+ - `stale_log_days` (default 180)+ - `weekly_start_dow` (default 1 - ISO-8601 Monday)+ - `daily_window_offset_hours` (default 0 - UTC)+- Five new full-scope MCP tools (`src/mcp/brain-tools.ts`):+ `brain_timeline`, `brain_belief_evolution`, `brain_stale_scan`,+ `brain_daily_brief`, `brain_weekly_synthesis`. Writer scope+ remains frozen at four tools.+- Five new CLI verbs: `o2b brain timeline`, `o2b brain evolution`,+ `o2b brain stale`, `o2b brain daily`, `o2b brain weekly`. Each+ honours `--vault` / `--json` plus verb-specific flags.++### Changed++- README capability paragraph extended; MCP tool inventory bumped+ from `Brain (14)` to `Brain (19)`.+- `tests/mcp/mcp.test.ts` tool-inventory assertion updated 26 -> 31.+- `loadTemporalConfigSafe(vault)` exported from+ `src/core/brain/policy.ts` so MCP wrappers and CLI verbs share+ one load-with-defaults helper.++### Notes++- Language-agnostic by construction. No vocabulary lists, no+ stopwords, no per-language regex tables. Filters use only typed+ event-kind enums, frontmatter keys, ISO-8601 timestamps, and the+ `pref-/ret-/sig-` slug regex.+- Backwards compatible. The new frontmatter slots are additive+ optionals; existing preference / signal / retired files stay+ byte-identical when not opted in. Existing public APIs unchanged.+- No LLM call inside helpers. The brief and evolution helpers+ return frozen deterministic envelopes; downstream agents do the+ narrative work.+- Window bounds are second-precision canonical UTC (matching+ `appendLogEvent`'s emitted timestamps) so string comparison+ semantics are unambiguous at midnight boundaries.+- 2343 tests pass (+83 over the v0.10.17 baseline of 2260);+ typecheck and version-sync remain clean.+## [0.10.17] - 2026-05-25Link graph surfaces: seven related features that expose the vault@@ -2679,6 +2793,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1[0.9.0]: https://github.com/itechmeat/open-second-brain/compare/v0.8.1...v0.9.0+[0.10.18]: https://github.com/itechmeat/open-second-brain/compare/v0.10.17...v0.10.18[0.10.17]: https://github.com/itechmeat/open-second-brain/compare/v0.10.16...v0.10.17[0.10.16]: https://github.com/itechmeat/open-second-brain/compare/v0.10.15...v0.10.16[0.10.15]: https://github.com/itechmeat/open-second-brain/compare/v0.10.14...v0.10.15diff --git a/README.md b/README.mdindex af9a78a3..9c5e11d8 100644--- a/README.md+++ b/README.md@@ -113,6 +113,24 @@ safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).`link_graph.vault_instruction_file`) through the `brain_context`envelope. Absent file = field omitted; existing hosts staybyte-identical.+- Treats time as a first-class axis. The `temporal:` config block+ drives a new `src/core/brain/temporal/` subsystem that+ materializes one `TimelineIndex` per invocation from+ `Brain/log/<date>.jsonl` plus retired/ frontmatter and feeds+ five operator surfaces over the same deterministic projection:+ a chronological event list (`o2b brain timeline` /+ `brain_timeline`), per-preference or per-topic belief evolution+ (`o2b brain evolution` / `brain_belief_evolution`) with running+ evidence counts and retire-chain walking, structural staleness+ reports (`o2b brain stale` / `brain_stale_scan`) using+ configurable per-kind thresholds, a daily brief+ (`o2b brain daily` / `brain_daily_brief`), and a 7-day synthesis+ with contradictions list (`o2b brain weekly` /+ `brain_weekly_synthesis`). All helpers ship deterministic data+ shapes - no LLM call inside. Preference, signal, and retired+ frontmatter grow additive optional `valid_from` / `valid_until`+ / `recorded_at` slots so future write paths can populate the+ bi-temporal axis without breaking existing files.- (Optional) Records paid agent actions through **Pay Memory**:receipts, generated assets, spending policy decisions, humanapproval state, and per-day reports β all as plain Markdown@@ -227,11 +245,13 @@ exposes the same deterministic operations as MCP tools:- **Core (3):** `second_brain_status`, `second_brain_query`,`vault_health`.-- **Brain (14):** `brain_feedback`, `brain_dream`,+- **Brain (19):** `brain_feedback`, `brain_dream`,`brain_apply_evidence`, `brain_note`, `brain_context`,`brain_digest`, `brain_query`, `brain_doctor`, `brain_backlinks`,`brain_context_pack`, `brain_unlinked_mentions`,- `brain_concept_synthesis`, `brain_moc_audit`,+ `brain_concept_synthesis`, `brain_moc_audit`, `brain_timeline`,+ `brain_belief_evolution`, `brain_stale_scan`,+ `brain_daily_brief`, `brain_weekly_synthesis`,`brain_operator_summary`. See the[Brain section](#brain-observing-memory) below.- **Pay Memory (8):** `payment_memory_init`,diff --git a/docs/brainstorm/temporal-synthesis/cli-output/claude.md b/docs/brainstorm/temporal-synthesis/cli-output/claude.mdnew file mode 100644index 00000000..87fbcafe--- /dev/null+++ b/docs/brainstorm/temporal-synthesis/cli-output/claude.md@@ -0,0 +1,38 @@+### Variant 1: `temporal/` with materialized TimelineIndex+- **Approach**: A single read pass over `Brain/log/*.jsonl` + `Brain/retired/` + frontmatter bi-temporal atoms (added as additive optionals on signals and preferences) produces a typed `TimelineIndex` keyed by event time and grouped by kind. The five consuming helpers β `timeline-reader`, `stale-watch`, `belief-evolution`, `daily-brief`, `weekly-brief` β are pure projections over the same index. The subsystem lives at `src/core/brain/temporal/` with atoms in `types.ts`, the index builder in `index.ts`, and projection helpers in sibling files.+- **Trade-offs**:+ - Pro: One canonical interpretation of "events in a window" β no semantic drift across helpers.+ - Pro: One disk scan per CLI invocation regardless of how many helpers are called downstream (briefs naturally compose).+ - Pro: Three-layer DAG is structurally explicit (atoms β index β projections), matching the v0.10.17 `link-graph/` precedent where a graph object fed multiple readers.+ - Pro: Briefs structurally *require* the temporal layer β they receive `TimelineIndex`, not raw log paths β satisfying the "must use new temporal layer" constraint by construction.+ - Con: `TimelineIndex` becomes a wide contract that all helpers couple to; widening it later is a cross-cutting edit.+ - Con: Forces an upfront decision on what the index materializes vs. lazily computes.+- **Complexity**: medium+- **Risk**: low++### Variant 2: `temporal/` with per-feature independent helpers+- **Approach**: Each of the five features is its own helper file under `src/core/brain/temporal/` (e.g. `timeline-reader.ts`, `stale-watch.ts`, `belief-evolution.ts`, `daily-brief.ts`, `weekly-brief.ts`), each reading `log-jsonl.ts` and `retired/` directly with a narrow projection scoped to its needs. Only the atom types in `temporal/types.ts` are shared. Briefs internally call `timeline-reader` to source events but no other runtime state is shared.+- **Trade-offs**:+ - Pro: Each helper is independently reviewable and trivially testable in isolation.+ - Pro: Matches the precedent of small, single-purpose helper modules; minimum new abstraction.+ - Pro: Lowest blast radius if one feature is dropped or postponed mid-release.+ - Con: Each helper rescans logs/retired, so a single brief call traverses the vault several times.+ - Con: Window inclusivity, retired-event treatment, and source-pointer resolution must be re-decided in each helper β semantic drift is the realistic failure mode over the next 2β3 releases.+ - Con: "Briefs use the temporal layer" becomes a convention rather than a structural guarantee.+- **Complexity**: small+- **Risk**: low++### Variant 3: `temporal/` with small projection primitives composed into features+- **Approach**: Define ~5 pure typed projection primitives (`eventsInWindow`, `statusTransitionsFor`, `lastEventByKind`, `validityAt`, `retirementsInWindow`) as the helper layer. Each user-facing feature (briefs, stale-watch, belief-evolution, temporal-query-router) is a thin composition of 1β3 primitives in `temporal/features/`. The subsystem's testable core is the primitives; the feature files are mostly wiring.+- **Trade-offs**:+ - Pro: Primitives are tiny and exhaustively testable on synthetic JSONL fixtures.+ - Pro: Future releases extend the temporal layer by adding a primitive, not a parallel helper.+ - Pro: Primitives can be exposed individually through MCP later without exposing whole feature handlers.+ - Con: The abstraction lives at the function-call layer rather than the data layer, so each feature still re-traverses logs through whatever primitives it composes.+ - Con: Picking the right primitive granularity upfront is the dominant design risk; leaky primitives force features back into ad-hoc scans.+ - Con: More files and more naming surface than V1 or V2.+- **Complexity**: mediumβlarge+- **Risk**: medium++### Recommended: Variant 1+**Rationale**: All five features genuinely consume the same input β a windowed, typed view of log events plus retired records plus frontmatter validity atoms β so sharing *data* (Variant 1) is more honest than sharing *operations* (Variant 3) or duplicating reads (Variant 2). A materialized `TimelineIndex` makes the "synthesis briefs must use the temporal layer" constraint structural rather than conventional, gives one canonical window semantics across all six features (eliminating the drift risk V2 carries), and matches the v0.10.17 `link-graph/` precedent where a single graph object fed multiple read surfaces with low coordination cost.diff --git a/docs/brainstorm/temporal-synthesis/cli-output/prompt.md b/docs/brainstorm/temporal-synthesis/cli-output/prompt.mdnew file mode 100644index 00000000..b0e2b39a--- /dev/null+++ b/docs/brainstorm/temporal-synthesis/cli-output/prompt.md@@ -0,0 +1,88 @@+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++Open Second Brain v0.10.18 must ship a coherent set of 6-8 related features that add a temporal/time-as-a-first-class axis to the agent-owned memory layer, plus companion synthesis surfaces that use the new temporal axis.++The cluster bundles these kanban triage items (related upstream + article tasks):++- `t_c7d26a30` Bi-temporal fact tracking with validity windows and audit trail. Inspired by obsidian-second-brain v3.2.0/v4.0.0: each fact gets `from`/`until` (event time) and `transaction_time` (when the vault learned it), plus a source pointer. Preferences and signals currently have no validity-window columns.+- `t_2f668121` Temporal query routing (gbrain a19ee8b). NOTE for orchestrator: skip the intent-classifier half (text-based "is this a temporal query?" regex is language-specific and forbidden by project pref `language-agnostic-only`). Keep only the deterministic timeline-reader half.+- `t_c77864bc` Belief-evolution timeline per preference: walk Brain/log/*.jsonl + Brain/retired/ to assemble a chronological per-pref or per-topic timeline.+- `t_09a3c5c3` Stale-watch with configurable thresholds by entry kind (preferences, signals, log files, retired). Pure structural staleness based on mtime/timestamps, no NLP.+- `t_542984c2` Daily automated vault brief. Deterministic data shape (events grouped by kind, vault delta vs previous day, status transitions). The agent does the narrative externally; OSB ships the structured brief.+- `t_f27d6f09` Weekly vault synthesis. Same as daily but 7-day window with status-transition aggregation; deterministic counters only.+- (optional) `t_03752ca6` complexity-vs-activity ratio as an extension to discipline-report.++Hard constraints from the project owner:++- Language-agnostic by construction. No vocabulary lists, no stopword sets, no per-language regex tables, no English keyword sniffers. Detectors must use only typed events or structural sigils (ISO timestamps, kind enums, frontmatter keys).+- One named subsystem per release (precedent: v0.10.15 `page-meta/`+`maintenance/`, v0.10.16 `trust/`, v0.10.17 `link-graph/`). The new subsystem name should describe the temporal axis.+- Synthesis briefs are deterministic data shape only - no LLM call inside the helpers. The LLM-narrative side is the agent's job.+- Backwards compatible. Frontmatter additions must be additive optionals; existing preference / retired pages must stay byte-identical when not opted in.+- Companion synthesis surfaces (daily/weekly brief) MUST USE the new temporal layer. If they could be implemented without the temporal storage, they belong in a different release.++# Project context++- Project: Open Second Brain (https://github.com/itechmeat/open-second-brain).+- Language / runtime: TypeScript (strict), Bun runtime, ESM modules.+- Layered DAG per release: atoms (data-shape additions) β pure helpers (one named subsystem) β consumers (CLI verbs + MCP tools).++Recent commits on origin/main:++```+d0598af v0.10.17 - link graph surfaces (#33)+3b7dfe9 v0.10.16: trust and operator surfaces (#32)+d045ea1 chore: bump version to 0.10.15 (#31)+5755200 v0.10.15: vault care bundle (#30)+9d9636b feat: index fastpath, PEM/JWT redaction (v0.10.14) (#29)+```++Related files (existing structure the new subsystem must integrate with):++- `src/core/brain/log-jsonl.ts` β single read entry-point for Brain/log/<date>.jsonl. Already typed via `BrainLogEventKind`.+- `src/core/brain/log.ts` β JSONL writer; `appendLogEvent({eventType, ...})`; events include `signal-recorded`, `preference-promoted`, `preference-retired`, `evidence-applied`, `evidence-violated`, `evidence-outdated`, `signal-suppressed`, `dream`, `note`, `pin`, `unpin`, ...+- `src/core/brain/digest.ts` β emits per-window summary (since/until); has `RetiredRecord` and `PreferenceSummary`; reads retired/ folder via `readAllRetired`.+- `src/core/brain/dream.ts` β preference lifecycle; emits `DreamRunSummary` per pass; writes `unconfirmed_until` on signals, `retired_at` on retired entries.+- `src/core/brain/preference.ts` β current frontmatter shape: `status`, `created_at`, `confirmed_at`, `last_evidence_at`, `confidence`, ...+- `src/core/brain/retired/<id>.md` β retired-preference entries; frontmatter has `retired_at` + reason.+- `src/core/brain/policy.ts` β config loader; `_brain.yaml` with named blocks (e.g., `link_graph:`); `BRAIN_*_DEFAULTS` constants per block.+- `src/core/brain/backlinks.ts` β backlink index, can supply cross-pref refs for topic timeline.+- `src/mcp/brain-tools.ts` β full-scope MCP tool registry; tools register after `brain_context_pack`.+- `src/cli/brain.ts`, `src/cli/brain/verbs/*.ts` β CLI dispatch + per-verb handlers.++Conventions:++- One named subsystem per release at `src/core/brain/<name>/`.+- New atoms are additive optionals on existing types.+- Three-layer DAG: atoms β helpers β consumers.+- MCP writer scope is FROZEN at 4 tools (brain_feedback, brain_apply_evidence, brain_note, brain_context). New tools always go into the full scope.+- Pure helpers take a `vault: string` first argument; never read env directly.+- All test files under `tests/core/brain/<subsystem>/...` and `tests/mcp/...` and `tests/cli/...`.+- No `[Unreleased]` placeholder in CHANGELOG; new entries go under concrete version headers.++Constraints:++- Do NOT change existing public APIs (`BrainLogEntry`, `BacklinkRef`, `BrainConfig`); only add optional fields.+- Do NOT introduce LLM calls inside helpers; helpers produce deterministic data shapes only.+- Do NOT use vocabulary-based detectors anywhere; only typed-event matching, frontmatter-key matching, or timestamp comparisons.+- Do NOT regress existing 2260 tests.+- Do NOT add a new dependency unless absolutely required (zero-dep additions strongly preferred).+- The temporal frontmatter atoms must be writable by future releases (this release is a read + atom layer; bulk-write tooling can ship later).++# 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/temporal-synthesis/design.md b/docs/brainstorm/temporal-synthesis/design.mdnew file mode 100644index 00000000..070fd3bf--- /dev/null+++ b/docs/brainstorm/temporal-synthesis/design.md@@ -0,0 +1,234 @@+# Temporal + synthesis - one timeline index, five projections, two new atoms++**Status:** draft+**Author:** @claude-vps-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain has no first-class time axis. Preferences carry+scattered date scalars (`created_at`, `confirmed_at`,+`last_evidence_at`, `retired_at`, `unconfirmed_until`) and per-day+event logs land in `Brain/log/<date>.jsonl`, but no helper assembles+a chronological view: per preference, per topic, or per window.+Operators cannot ask "how did my position on X evolve", agents+cannot answer "what changed in the vault this week", and the+`brain_doctor` / `brain_digest` surfaces have no notion of staleness+or activity drift over time. Synthesis surfaces (daily / weekly+briefs) that the operator wants would, without a temporal layer,+degenerate into point-in-time counters - they could not show drift.++## Scope++- New named subsystem `src/core/brain/temporal/` (one per release,+ precedent: v0.10.17 `link-graph/`).+- Atoms (data-shape additions):+ - `TemporalEvent` - normalized chronological event drawn from+ `Brain/log/<date>.jsonl`, retired/, and preference frontmatter.+ Flat shape with `at: string` (canonical UTC ISO), `kind:+ BrainLogEventKind` (reuses the existing event-kind enum), plus+ optional denormalized slots (`prefId`, `topic`, `result`,+ `artifact`, `transitionFrom`, `transitionTo`, `reason`, `text`,+ `validFrom`, `validUntil`, `recordedAt`, `source`).+ - `TimelineIndex` - frozen materialized view of all events in a+ requested window, grouped by kind / pref_id / topic.+ - Bi-temporal frontmatter atoms (additive optionals on preference+ + signal frontmatter): `valid_from`, `valid_until`,+ `recorded_at`. Read-only this release; write paths can land in+ a future release without breaking compatibility.+ - New `temporal:` block in `_brain.yaml` (parallel to `link_graph:`).+- Pure helpers (projections over `TimelineIndex`):+ - `temporal/build-index.ts` - `buildTimelineIndex(vault, opts)`.+ - `temporal/select-events.ts` - `selectEvents(index, filters)`.+ - `temporal/belief-evolution.ts` -+ `buildBeliefEvolution(index, vault, target)`.+ - `temporal/stale-watch.ts` - `findStaleEntries(index, vault, cfg)`.+ - `temporal/daily-brief.ts` - `buildDailyBrief(index, vault, date)`.+ - `temporal/weekly-brief.ts` -+ `buildWeeklySynthesis(index, vault, weekEnd)`.+- Consumers (CLI + MCP):+ - Five new full-scope MCP tools: `brain_timeline`,+ `brain_belief_evolution`, `brain_stale_scan`,+ `brain_daily_brief`, `brain_weekly_synthesis`.+ - Five new CLI verbs: `o2b brain timeline`, `evolution`, `stale`,+ `daily`, `weekly`.+- Tests:+ - Unit tests for every atom + helper under+ `tests/core/brain/temporal/`.+ - MCP shape tests under `tests/mcp/`.+ - CLI surface tests under `tests/cli/`.++## Out of scope++- Writing the new bi-temporal frontmatter atoms (`valid_from` /+ `valid_until`) - this release reads them where they exist;+ bulk-write tooling, dream-pass automatic timestamping, and+ migration scripts are deferred to a future release.+- Temporal *intent classifier* (the "is this query temporal" regex+ from gbrain a19ee8b): forbidden by project pref+ `language-agnostic-only`. Operator invokes the temporal helpers+ explicitly through CLI / MCP, not through query-text sniffing.+- LLM-driven synthesis prose. Helpers return deterministic data+ shapes; the agent does narrative work externally.+- `brain_search` integration - timeline surfaces stay separate+ this release. (Future: a `from:/until:` search modifier could+ use the same atom layer.)+- `complexity-vs-activity ratio` (`t_03752ca6`) - deferred; ties+ into `src/core/discipline/` rather than `temporal/`. Leaving+ for a discipline-focused release.+- Two-stage signal review gate (`t_ef94345e`) - dream-pass change,+ unrelated to temporal axis.++## Chosen approach++Variant 1 from `variants.md`: a single materialized `TimelineIndex`+plus pure projections. The atom layer adds three frontmatter slots+and one event type; the index builder scans `Brain/log/*.jsonl`,+`Brain/retired/`, and active preference frontmatter once per+invocation; five helpers project the index into operator-facing+shapes; five consumers (CLI verbs and MCP tools) expose the+helpers. The index is frozen and only ever built from disk in one+place, so every helper observes the same window semantics, the+same retirement treatment, and the same source-pointer+resolution.++Window semantics are inclusive at `since` and exclusive at `until`+(`[since, until)`), expressed as ISO-8601 UTC timestamps. Days are+expressed via the existing `validateIsoDate` helper. Weekly windows+default to ISO-8601 week boundaries (Monday 00:00:00 UTC -+following Monday 00:00:00 UTC), configurable via the+`temporal.weekly_start_dow` slot which takes ISO-8601 weekday+numbers (1=Monday ... 7=Sunday) - no language hardcoding.++Belief-evolution follows topic-renames across slugs by chaining+`supersedes` / `superseded_by` links on retired entries. The+chain-walker is bounded by the count of retired entries (no+infinite recursion even on a malformed chain).++Stale-watch reads three thresholds from config+(`temporal.stale_pref_days`, `temporal.stale_signal_days`,+`temporal.stale_log_days`), defaulted to 90 / 30 / 180 days+respectively. Pure structural staleness based on the most-recent+event-time stamp per entry; nothing about content.++Daily-brief returns event counts grouped by `BrainLogEventKind`,+the set of preferences whose status transitioned in the window+(derived from `promote` / `retire` / `force-confirmed` / `reject`+events), the vault delta (new feedback signals / new retired /+applied / violated counts) versus the previous day, and the list+of source-pointers cited. Weekly-synthesis returns the same shape+over a 7-day window plus contradiction counts (combining+`signal-suppressed` events with `apply-evidence` events where the+payload `result` is `"violated"`) and a "retired in window" list.++## Design decisions++- **One materialized index, five projections.** Sharing data, not+ operations, eliminates window-semantics drift and matches the+ v0.10.17 `link-graph/` precedent.+- **Atoms are additive optionals.** `BrainPreference`,+ `BrainSignal`, and `BrainRetiredRecord` frontmatter readers grow+ optional `valid_from` / `valid_until` / `recorded_at` slots;+ existing files stay byte-identical when not opted in.+- **Index builder is the single disk-touching helper.** The five+ projection helpers are pure functions over the frozen index,+ trivially testable with synthetic fixtures.+- **ISO-8601 everywhere.** All timestamps in `TimelineIndex` are+ canonical UTC strings of the shape `YYYY-MM-DDTHH:MM:SSZ` (or+ `.SSSZ` when source data carries sub-second precision), matching+ `log-jsonl.ts`'s `ISO_UTC_TS_RE`. Window inputs accept either an+ ISO date (interpreted as `T00:00:00Z`) or a full ISO timestamp.+- **Weekly weekday number is configured, not detected.** No+ English-word detection like "Monday"; the slot takes 1-7 per+ ISO-8601, defaulted to 1 (Monday).+- **`since` inclusive, `until` exclusive.** Mirrors the existing+ digest convention in `digest.ts` (`window: {since, until}`).+- **Briefs do NOT call the LLM.** They are deterministic counters+ + status-transition lists + source-pointer arrays. Operator-side+ agents do the narrative work over the structured payload.+- **MCP tools register in full scope only.** Writer scope stays+ frozen at four tools. Five new tools land alongside+ `brain_unlinked_mentions` / `brain_concept_synthesis` /+ `brain_moc_audit` in the full scope. Tool-count assertion in+ `tests/mcp/mcp.test.ts` updates from 26 to 31.+- **CLI verbs follow `o2b brain <verb>` convention.** Each verb+ reuses the existing `--vault` / `--json` flags via the shared+ CLI helpers.++## File changes++### New files++```+src/core/brain/temporal/types.ts # TemporalEvent + TimelineIndex + config defaults+src/core/brain/temporal/build-index.ts # buildTimelineIndex(vault, opts)+src/core/brain/temporal/select-events.ts # selectEvents(index, filters)+src/core/brain/temporal/belief-evolution.ts # buildBeliefEvolution(index, vault, target)+src/core/brain/temporal/stale-watch.ts # findStaleEntries(index, vault, cfg)+src/core/brain/temporal/daily-brief.ts # buildDailyBrief(index, vault, date)+src/core/brain/temporal/weekly-brief.ts # buildWeeklySynthesis(index, vault, weekEnd)++src/cli/brain/verbs/temporal-timeline.ts # o2b brain timeline+src/cli/brain/verbs/temporal-evolution.ts # o2b brain evolution+src/cli/brain/verbs/temporal-stale.ts # o2b brain stale+src/cli/brain/verbs/temporal-daily.ts # o2b brain daily+src/cli/brain/verbs/temporal-weekly.ts # o2b brain weekly++tests/core/brain/temporal/build-index.test.ts+tests/core/brain/temporal/select-events.test.ts+tests/core/brain/temporal/belief-evolution.test.ts+tests/core/brain/temporal/stale-watch.test.ts+tests/core/brain/temporal/daily-brief.test.ts+tests/core/brain/temporal/weekly-brief.test.ts+tests/core/brain/temporal/bi-temporal-atoms.test.ts+tests/mcp/temporal-mcp-tools.test.ts+tests/cli/brain-temporal-cli.test.ts+```++### Modified files++```+src/core/brain/policy.ts # BRAIN_TEMPORAL_DEFAULTS + resolveTemporal() + temporal: validator+src/core/brain/types.ts # BrainTemporalConfig + ResolvedBrainTemporalConfig + BrainConfig.temporal?+src/core/brain/preference.ts # read optional valid_from/valid_until/recorded_at+src/core/brain/signal.ts # read optional valid_from/valid_until/recorded_at+src/core/brain/dream.ts # RetiredRecord: optional valid_from/valid_until/recorded_at+src/mcp/brain-tools.ts # five new tool registrations+src/cli/brain.ts # dispatch five new verbs+src/cli/brain/verbs/index.ts # register five new verbs+src/cli/brain/help-text.ts # help block for five new verbs++tests/mcp/mcp.test.ts # 26 -> 31 tool inventory assertion+```++Approximate file count: 17 new (helpers + verbs) + 9 new tests ++9 modified = ~35-40 source files plus the brainstorm + design ++plan + cli-output set (3 + cli-output) brings the PR to ~45-55+files. README + CHANGELOG + version manifests add another ~10+during phases 5-6.++## Risks and open questions++- **Index width.** If the materialized event shape needs a new+ field mid-implementation (e.g. evidence-violated needs a+ contradiction-target slot), the atom is widened in `types.ts`+ and every helper rebuilds. Mitigation: settle the+ `TemporalEvent` field list during phase 0 step 7 (now) and+ resist creep; future fields can land as additive optionals+ exactly like backlink atoms in v0.10.17.+- **Retired-chain cycles.** Bad `supersedes` / `superseded_by`+ links could loop. Mitigation: chain-walker carries a visited+ set; break with a warning emit, never throw.+- **Weekly boundary on DST / timezone vaults.** All math is in UTC.+ Operators in non-UTC timezones see weeks that don't align with+ their local calendar. Acceptable for v0.10.18 - the brief shape+ already includes the literal ISO timestamps; downstream agents+ can re-window locally. Future release can add a+ `temporal.timezone` slot if operator demand exists.+- **Empty vault.** All projection helpers must return frozen empty+ envelopes (not throw) when the timeline has zero events in the+ window. Covered in tests.+- **Sub-second timestamps in JSONL vs second-precision in+ retired/.** The index normalizes both to the canonical UTC shape+ before grouping; collisions on the same second are resolved by+ source-pointer order (deterministic).diff --git a/docs/brainstorm/temporal-synthesis/plan.md b/docs/brainstorm/temporal-synthesis/plan.mdnew file mode 100644index 00000000..61f47c71--- /dev/null+++ b/docs/brainstorm/temporal-synthesis/plan.md@@ -0,0 +1,241 @@+# Temporal + synthesis - implementation plan++Order matters - the materialized-index variant has a strict layered+DAG (atoms - index - projections - consumers). Each task lands on+`feat/temporal-synthesis` as a separate conventional commit on top+of the brainstorm commit.++## Tasks++### Task 1: Temporal atoms + config block++- **Files**: `src/core/brain/temporal/types.ts` (new),+ `src/core/brain/types.ts` (modified - add `BrainTemporalConfig` ++ `ResolvedBrainTemporalConfig` + `BrainConfig.temporal?`),+ `src/core/brain/policy.ts` (modified - add+ `BRAIN_TEMPORAL_DEFAULTS`, `resolveTemporal(cfg)`, `temporal:`+ validator with safe-integer / range checks),+ `tests/core/brain/temporal/bi-temporal-atoms.test.ts` (new).+- **Acceptance**:+ - `TemporalEvent` is a flat shape with `at: string` (canonical+ UTC ISO), `kind: BrainLogEventKind` (reuses existing enum+ values verbatim), `source: TemporalEventSource` (vault-relative+ log path + line number when known), plus optional denormalized+ slots: `prefId`, `topic`, `result`, `artifact`,+ `transitionFrom`, `transitionTo`, `reason`, `text`,+ `validFrom`, `validUntil`, `recordedAt`. Frozen via+ `Object.freeze`.+ - `TimelineIndex` is a frozen `{events, eventsByKind,+ eventsByPrefId, eventsByTopic, window}` shape.+ - `BRAIN_TEMPORAL_DEFAULTS` exposes `stale_pref_days: 90`,+ `stale_signal_days: 30`, `stale_log_days: 180`,+ `weekly_start_dow: 1`, `daily_window_offset_hours: 0`.+ - `resolveTemporal(cfg)` returns a fully-populated config; absent+ block falls back to defaults.+ - Validator rejects: non-positive integers, weekly_start_dow+ outside [1, 7], offset_hours outside [-23, 23].+ - Test covers happy-path config, defaults fallback, and each+ validator branch.+- **Depends on**: none.++### Task 2: TimelineIndex builder++- **Files**: `src/core/brain/temporal/build-index.ts` (new),+ `tests/core/brain/temporal/build-index.test.ts` (new).+- **Acceptance**:+ - `buildTimelineIndex(vault, opts)` walks+ `Brain/log/<date>.jsonl` via existing `readLogDay` for every+ date file in the window, plus `Brain/retired/*.md` via existing+ `readAllRetired` shape, plus active preference frontmatter via+ existing `readPreference` shape, and returns a frozen+ `TimelineIndex`.+ - Window inputs: `since?` (ISO date or full ISO timestamp),+ `until?` (ISO date or full ISO timestamp). Default `since` is+ epoch; default `until` is now + 1ms (exclusive).+ - All event timestamps normalized to canonical UTC string before+ grouping. Sub-second precision preserved when present.+ - Tie-breaker for equal timestamps: source-pointer order (so the+ result is deterministic).+ - Test: synthetic vault with three JSONL files + two retired+ entries + four active prefs; assert events list, kind groups,+ pref groups, topic groups, and frozen-ness.+ - Empty vault: returns frozen index with zero events and empty+ groups (no throw).+- **Depends on**: Task 1.++### Task 3: Select-events projection + bi-temporal frontmatter reader++- **Files**: `src/core/brain/temporal/select-events.ts` (new),+ `src/core/brain/preference.ts` (modified - additive+ `valid_from?`, `valid_until?`, `recorded_at?` optional reads on+ the existing frontmatter reader), `src/core/brain/signal.ts`+ (modified - same three optional slots),+ `src/core/brain/dream.ts` (modified - `RetiredRecord` gains+ three optional slots),+ `tests/core/brain/temporal/select-events.test.ts` (new).+- **Acceptance**:+ - `selectEvents(index, filters)` accepts+ `{pref_id?, topic?, kind?, since?, until?}` and returns a+ frozen `ReadonlyArray<TemporalEvent>` filtered by the AND of+ every set predicate.+ - When no filter is set, returns the index's full events array+ (still frozen, same reference is fine).+ - Bi-temporal atom reads: existing files without the new keys+ parse as before (no schema break); files with `valid_from`+ set surface it on `TemporalEvent.validFrom`; same for+ `valid_until` and `recorded_at`.+ - Test: every filter combination across a 6-event synthetic+ fixture; empty-filter happy path; bi-temporal atom presence /+ absence smoke.+- **Depends on**: Task 2.++### Task 4: Belief-evolution helper++- **Files**: `src/core/brain/temporal/belief-evolution.ts` (new),+ `tests/core/brain/temporal/belief-evolution.test.ts` (new).+- **Acceptance**:+ - `buildBeliefEvolution(index, vault, target)` accepts+ `target: {prefId: string} | {topic: string}` and returns a+ frozen+ `{target, transitions, evidence, retirements, generatedAt}`+ envelope.+ - `transitions` is the chronological list of status changes+ (`unconfirmed -> confirmed -> quarantine -> retired`,+ intermediate states emitted), each entry carries `at`, `from`,+ `to`, and the originating event reference.+ - `evidence` is the chronological list of applied / violated /+ outdated events with a per-phase running count.+ - `retirements` covers the retired entry plus the chain of+ `supersedes` / `superseded_by` links, with a visited-set+ cycle guard.+ - Empty target (no events found): returns the envelope with+ empty arrays, no throw.+ - Test: synthetic 4-transition history (unconfirmed -> confirmed+ -> quarantine -> retired) with three evidence events and a+ cross-slug rename chain via `supersedes`.+- **Depends on**: Task 3.++### Task 5: Stale-watch helper++- **Files**: `src/core/brain/temporal/stale-watch.ts` (new),+ `tests/core/brain/temporal/stale-watch.test.ts` (new).+- **Acceptance**:+ - `findStaleEntries(index, vault, cfg)` returns a frozen+ `{stalePreferences, staleSignals, staleLogFiles, thresholds,+ generatedAt}` envelope.+ - Threshold logic: an entry is stale when the difference between+ `now` and the most-recent relevant event timestamp exceeds the+ threshold-days config value.+ - Per-kind thresholds applied independently+ (`stale_pref_days`, `stale_signal_days`, `stale_log_days`).+ - Test: synthetic vault with one stale pref, one fresh pref, one+ stale signal, one stale log file, asserting the envelope+ classification.+- **Depends on**: Task 2.++### Task 6: Daily-brief helper++- **Files**: `src/core/brain/temporal/daily-brief.ts` (new),+ `tests/core/brain/temporal/daily-brief.test.ts` (new).+- **Acceptance**:+ - `buildDailyBrief(index, vault, date)` returns frozen+ `{date, eventsByKind, statusTransitions, vaultDelta,+ sourcePointers, generatedAt}` envelope.+ - `eventsByKind` keyed by `BrainLogEventKind`, with stable+ key order (sorted lexicographically).+ - `statusTransitions` is the list of pref-id status changes+ within the day.+ - `vaultDelta` reports `newPromotions` (count of `promote`+ events), `newRetired` (count of `retire` events), `newFeedback`+ (count of `feedback` events), `evidenceApplied` and+ `evidenceViolated` (count of `apply-evidence` events with the+ matching payload `result`) as integers.+ - `sourcePointers` is the deduplicated list of artifact+ wikilinks cited by evidence events in the day.+ - Test: synthetic day with 1 promotion + 2 applied + 1 violated+ + 1 retired; assert each envelope slot.+- **Depends on**: Task 2.++### Task 7: Weekly-synthesis helper++- **Files**: `src/core/brain/temporal/weekly-brief.ts` (new),+ `tests/core/brain/temporal/weekly-brief.test.ts` (new).+- **Acceptance**:+ - `buildWeeklySynthesis(index, vault, weekEnd, cfg)` returns+ frozen `{windowStart, windowEnd, eventsByKind,+ statusTransitions, retired, contradictions, vaultDelta,+ generatedAt}` envelope.+ - Window is computed from `weekEnd` (ISO date) back to the+ `weekly_start_dow`-aligned Monday-or-other-weekday by config.+ - `contradictions` counts `signal-suppressed` and+ `evidence-violated` events grouped by pref_id.+ - `retired` lists every pref retired within the window with the+ retirement reason.+ - Test: synthetic 7-day window with 1 retirement, 2+ contradictions, 4 transitions; assert envelope and window+ bounds.+- **Depends on**: Task 2.++### Task 8: Five MCP tools++- **Files**: `src/mcp/brain-tools.ts` (modified - register+ `brain_timeline`, `brain_belief_evolution`, `brain_stale_scan`,+ `brain_daily_brief`, `brain_weekly_synthesis` in full scope),+ `tests/mcp/temporal-mcp-tools.test.ts` (new),+ `tests/mcp/mcp.test.ts` (modified - tool inventory 26 -> 31).+- **Acceptance**:+ - Each new tool: schema-validates input (strict booleans /+ string-tolerant integer coercion matching v0.10.17 precedent),+ converts internal errors to MCP `INVALID_PARAMS` where+ appropriate, returns a frozen envelope serialised as JSON.+ - Writer scope stays at 4 tools (unchanged).+ - `tests/mcp/mcp.test.ts` tool-inventory assertion updated to 31+ + the five names added to the expected Set.+ - Test for each tool: happy-path input + one INVALID_PARAMS case+ (bad type / out-of-range integer / unknown filter key).+- **Depends on**: Tasks 4-7.++### Task 9: Five CLI verbs++- **Files**: `src/cli/brain/verbs/temporal-timeline.ts` (new),+ `src/cli/brain/verbs/temporal-evolution.ts` (new),+ `src/cli/brain/verbs/temporal-stale.ts` (new),+ `src/cli/brain/verbs/temporal-daily.ts` (new),+ `src/cli/brain/verbs/temporal-weekly.ts` (new),+ `src/cli/brain.ts` (modified - dispatch the five verbs),+ `src/cli/brain/verbs/index.ts` (modified - re-export),+ `src/cli/brain/help-text.ts` (modified - help block),+ `tests/cli/brain-temporal-cli.test.ts` (new).+- **Acceptance**:+ - Each verb supports `--vault`, `--json`, plus verb-specific+ flags:+ - `timeline` - `--pref-id`, `--topic`, `--kind`, `--since`,+ `--until`, `--limit`.+ - `evolution` - `--pref-id` or `--topic` (mutually exclusive).+ - `stale` - no extra flags; reads thresholds from config.+ - `daily` - `--date` (ISO date, default today UTC).+ - `weekly` - `--week-end` (ISO date, default today UTC).+ - Invalid flag combos surface as `CliError` with the+ project-standard message shape.+ - `--json` returns the helper envelope; the default human-readable+ rendering is a short multi-line text block.+ - Test: each verb's argv parsing happy-path + one invalid-args+ case.+- **Depends on**: Task 8.++## Out of scope reminders (do not implement here)++- Writing the bi-temporal frontmatter atoms back onto disk.+- LLM-driven brief narrative generation.+- Temporal intent classifier on `brain_search` / `brain_query`.+- Vault complexity-vs-activity ratio.+- Two-stage signal review gate.++## Verification commands++- `bun test tests/core/brain/temporal/` - subsystem unit tests.+- `bun test tests/mcp/` - MCP shape + inventory tests.+- `bun test tests/cli/` - CLI surface tests.+- `bun test` - full regression suite.+- `bun run typecheck` - strict TypeScript.+- `bun run sync-version:check` - manifests in lockstep (phase 6).diff --git a/docs/brainstorm/temporal-synthesis/variants.md b/docs/brainstorm/temporal-synthesis/variants.mdnew file mode 100644index 00000000..b80376e4--- /dev/null+++ b/docs/brainstorm/temporal-synthesis/variants.md@@ -0,0 +1,58 @@+# Temporal + synthesis - brainstorm audit trail++Consultant (claude -p) returned three variants and recommended Variant 1.+Orchestrator accepted the recommendation without override.++## Variants (verbatim from `cli-output/claude.md`)++### Variant 1: `temporal/` with materialized TimelineIndex+- **Approach**: A single read pass over `Brain/log/*.jsonl` + `Brain/retired/` + frontmatter bi-temporal atoms (added as additive optionals on signals and preferences) produces a typed `TimelineIndex` keyed by event time and grouped by kind. The five consuming helpers - `timeline-reader`, `stale-watch`, `belief-evolution`, `daily-brief`, `weekly-brief` - are pure projections over the same index. The subsystem lives at `src/core/brain/temporal/` with atoms in `types.ts`, the index builder in `index.ts`, and projection helpers in sibling files.+- **Trade-offs**:+ - Pro: One canonical interpretation of "events in a window" - no semantic drift across helpers.+ - Pro: One disk scan per CLI invocation regardless of how many helpers are called downstream (briefs naturally compose).+ - Pro: Three-layer DAG is structurally explicit (atoms - index - projections), matching the v0.10.17 `link-graph/` precedent where a graph object fed multiple readers.+ - Pro: Briefs structurally *require* the temporal layer - they receive `TimelineIndex`, not raw log paths - satisfying the "must use new temporal layer" constraint by construction.+ - Con: `TimelineIndex` becomes a wide contract that all helpers couple to; widening it later is a cross-cutting edit.+ - Con: Forces an upfront decision on what the index materializes vs. lazily computes.+- **Complexity**: medium+- **Risk**: low++### Variant 2: `temporal/` with per-feature independent helpers+- **Approach**: Each of the five features is its own helper file under `src/core/brain/temporal/` (e.g. `timeline-reader.ts`, `stale-watch.ts`, `belief-evolution.ts`, `daily-brief.ts`, `weekly-brief.ts`), each reading `log-jsonl.ts` and `retired/` directly with a narrow projection scoped to its needs. Only the atom types in `temporal/types.ts` are shared. Briefs internally call `timeline-reader` to source events but no other runtime state is shared.+- **Trade-offs**:+ - Pro: Each helper is independently reviewable and trivially testable in isolation.+ - Pro: Matches the precedent of small, single-purpose helper modules; minimum new abstraction.+ - Pro: Lowest blast radius if one feature is dropped or postponed mid-release.+ - Con: Each helper rescans logs/retired, so a single brief call traverses the vault several times.+ - Con: Window inclusivity, retired-event treatment, and source-pointer resolution must be re-decided in each helper - semantic drift is the realistic failure mode over the next 2-3 releases.+ - Con: "Briefs use the temporal layer" becomes a convention rather than a structural guarantee.+- **Complexity**: small+- **Risk**: low++### Variant 3: `temporal/` with small projection primitives composed into features+- **Approach**: Define ~5 pure typed projection primitives (`eventsInWindow`, `statusTransitionsFor`, `lastEventByKind`, `validityAt`, `retirementsInWindow`) as the helper layer. Each user-facing feature (briefs, stale-watch, belief-evolution, temporal-query-router) is a thin composition of 1-3 primitives in `temporal/features/`. The subsystem's testable core is the primitives; the feature files are mostly wiring.+- **Trade-offs**:+ - Pro: Primitives are tiny and exhaustively testable on synthetic JSONL fixtures.+ - Pro: Future releases extend the temporal layer by adding a primitive, not a parallel helper.+ - Pro: Primitives can be exposed individually through MCP later without exposing whole feature handlers.+ - Con: The abstraction lives at the function-call layer rather than the data layer, so each feature still re-traverses logs through whatever primitives it composes.+ - Con: Picking the right primitive granularity upfront is the dominant design risk; leaky primitives force features back into ad-hoc scans.+ - Con: More files and more naming surface than V1 or V2.+- **Complexity**: medium-large+- **Risk**: medium++## Consultant's recommendation++### Recommended: Variant 1+**Rationale**: All five features genuinely consume the same input - a windowed, typed view of log events plus retired records plus frontmatter validity atoms - so sharing *data* (Variant 1) is more honest than sharing *operations* (Variant 3) or duplicating reads (Variant 2). A materialized `TimelineIndex` makes the "synthesis briefs must use the temporal layer" constraint structural rather than conventional, gives one canonical window semantics across all six features (eliminating the drift risk V2 carries), and matches the v0.10.17 `link-graph/` precedent where a single graph object fed multiple read surfaces with low coordination cost.++## Orchestrator decision++Accepted Variant 1 without override. The consultant's structural argument matches Open Second Brain conventions:++- v0.10.17 (`link-graph/`) already established the pattern: one named subsystem with a small set of pure-data atoms feeding multiple read surfaces. `TimelineIndex` is the temporal-axis analogue of `BacklinkRef` + `ConceptClusterEnvelope`.+- The combo constraint ("synthesis briefs MUST use the new temporal layer") is satisfied by construction: brief helpers receive `TimelineIndex`, not a path.+- One scan per invocation matters even at low vault sizes - daily-brief + stale-watch share the same scan when invoked together by a cron job.+- The "wide contract" concern noted in V1's cons is mitigated by the project's existing convention: atoms are additive optionals; the TimelineIndex frontmatter atom slots are also additive.++Codex fallback was not invoked - primary consultant returned three parseable variants and a clean recommendation.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex eef37bd0..3e1eeaa5 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.10.17",+ "version": "0.10.18","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex fa374019..fa418373 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.17",+ "version": "0.10.18","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex d0c0ca43..c7ea9c75 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.17"+version: "0.10.18"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 6984de4b..41d86cb0 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.10.17",+ "version": "0.10.18","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 2a0bb05d..c02f1226 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.17"+version: "0.10.18"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 7cca8ae5..c2374fcf 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.10.17"+version = "0.10.18"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 9ae76bf1..9934e1d7 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -43,6 +43,11 @@ import {cmdBrainUnlinked,cmdBrainSynthesise,cmdBrainMocAudit,+ cmdBrainTimeline,+ cmdBrainEvolution,+ cmdBrainStale,+ cmdBrainDaily,+ cmdBrainWeekly,} from "./brain/verbs/index.ts";export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promise<number> {@@ -96,6 +101,11 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promiscase "unlinked": return await cmdBrainUnlinked(rest);case "synthesise": return await cmdBrainSynthesise(rest);case "moc-audit": return await cmdBrainMocAudit(rest);+ case "timeline": return await cmdBrainTimeline(rest);+ case "evolution": return await cmdBrainEvolution(rest);+ case "stale": return await cmdBrainStale(rest);+ case "daily": return await cmdBrainDaily(rest);+ case "weekly": return await cmdBrainWeekly(rest);default:process.stderr.write(`error: unknown brain verb: ${verb}\n`);process.stdout.write(BRAIN_HELP);diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex b00d277a..99dc37fe 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -45,6 +45,11 @@ Brain verbs (observing memory):unlinked Raw-text mentions of an artifact's title/aliases outside [[...]]synthesise Concept cluster: target + linkers (depth-1), optionally + mentionsmoc-audit Per-MOC coverage audit (well-covered/fragile/candidate-missing)+ timeline Chronological event list filtered by pref-id/topic/kind/since/until+ evolution Per-pref or per-topic story: status transitions + evidence + retire+ stale Stale preferences/signals/log files (configurable thresholds)+ daily Daily brief: events by kind, status transitions, vault delta+ weekly 7-day synthesis: transitions, retired, contradictions, vault deltaCommon flags:--vault <path> Override the configured vault@@ -272,4 +277,34 @@ export const VERB_HELP: Record<string, string> = {"surfaces a suggested-next candidate. MOC detection is purely\n" +"structural (outbound link count + link density thresholds from\n" +"_brain.yaml). Read-only.\n",+ timeline:+ "usage: o2b brain timeline [--pref-id <id>] [--topic <slug>]\n" ++ " [--kind <event-kind>] [--since <iso>] [--until <iso>]\n" ++ " [--limit <n>] [--vault <path>] [--json]\n" ++ "Chronological list of Brain events filtered by any combination of\n" ++ "pref-id / topic / kind / since / until / limit. Reads JSONL log via\n" ++ "the canonical TimelineIndex. Read-only.\n",+ evolution:+ "usage: o2b brain evolution (--pref-id <id> | --topic <slug>)\n" ++ " [--vault <path>] [--json]\n" ++ "Per-preference or per-topic story: status transitions (creation,\n" ++ "promotion, retirement) derived from dream summaries; evidence\n" ++ "rollup with running applied / violated / outdated counts; retirement\n" ++ "chain walked via supersedes / superseded_by links. Read-only.\n",+ stale:+ "usage: o2b brain stale [--vault <path>] [--json]\n" ++ "Structural staleness report. Lists preferences, signals, and log\n" ++ "files inactive longer than the configured `temporal:` thresholds\n" ++ "(stale_pref_days / stale_signal_days / stale_log_days). Read-only.\n",+ daily:+ "usage: o2b brain daily [--date <YYYY-MM-DD>] [--vault <path>] [--json]\n" ++ "Per-day deterministic brief: events grouped by kind, status\n" ++ "transitions, vault delta, deduplicated artifact wikilinks. Defaults\n" ++ "to today UTC. Read-only.\n",+ weekly:+ "usage: o2b brain weekly [--week-end <YYYY-MM-DD>] [--vault <path>] [--json]\n" ++ "7-day deterministic synthesis: events by kind, status transitions,\n" ++ "retired-in-window list, contradictions (signal-suppressed plus\n" ++ "apply-evidence violated), vault delta, source pointers. Defaults to\n" ++ "today UTC for week-end. Read-only.\n",};diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex c20d1f6e..8818197e 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -30,3 +30,8 @@ export { cmdBrainSummary } from "./summary.ts";export { cmdBrainUnlinked } from "./unlinked.ts";export { cmdBrainSynthesise } from "./synthesise.ts";export { cmdBrainMocAudit } from "./moc-audit.ts";+export { cmdBrainTimeline } from "./temporal-timeline.ts";+export { cmdBrainEvolution } from "./temporal-evolution.ts";+export { cmdBrainStale } from "./temporal-stale.ts";+export { cmdBrainDaily } from "./temporal-daily.ts";+export { cmdBrainWeekly } from "./temporal-weekly.ts";diff --git a/src/cli/brain/verbs/temporal-daily.ts b/src/cli/brain/verbs/temporal-daily.tsnew file mode 100644index 00000000..9215c681--- /dev/null+++ b/src/cli/brain/verbs/temporal-daily.ts@@ -0,0 +1,76 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";+import { buildDailyBrief } from "../../../core/brain/temporal/daily-brief.ts";+import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++/**+ * `o2b brain daily [--vault PATH] [--date YYYY-MM-DD] [--json]`+ *+ * Per-day deterministic brief over the TimelineIndex. Defaults+ * `--date` to today UTC.+ */+export async function cmdBrainDaily(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ date: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const date = resolveDateArg(flags["date"]);+ const cfg = loadTemporalConfigSafe(vault);+ const index = buildTimelineIndex(vault, {});+ let brief;+ try {+ brief = buildDailyBrief(index, vault, date, {+ offsetHours: cfg.daily_window_offset_hours,+ });+ } catch (exc) {+ if (exc instanceof Error) throw new CliError(`brain daily: ${exc.message}`);+ throw exc;+ }++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(brief, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Daily brief ${brief.date}\n`);+ process.stdout.write(+ ` window: ${brief.window.since} .. ${brief.window.until}\n`,+ );+ process.stdout.write(` events by kind:\n`);+ for (const [kind, count] of Object.entries(brief.eventsByKind)) {+ process.stdout.write(` ${kind}: ${count}\n`);+ }+ process.stdout.write(` vault delta:\n`);+ process.stdout.write(` new promotions: ${brief.vaultDelta.newPromotions}\n`);+ process.stdout.write(` new retired: ${brief.vaultDelta.newRetired}\n`);+ process.stdout.write(` new feedback: ${brief.vaultDelta.newFeedback}\n`);+ process.stdout.write(` evidence applied: ${brief.vaultDelta.evidenceApplied}\n`);+ process.stdout.write(` evidence violated: ${brief.vaultDelta.evidenceViolated}\n`);+ process.stdout.write(` status transitions: ${brief.statusTransitions.length}\n`);+ process.stdout.write(` source pointers: ${brief.sourcePointers.length}\n`);+ return 0;+}++/**+ * Validate / default the `--date` flag. Accepts a bare ISO date+ * (`YYYY-MM-DD`); rejects whitespace-only / malformed input as a+ * CLI error so the underlying helper does not see garbage.+ */+function resolveDateArg(raw: string | boolean | string[] | undefined): string {+ if (typeof raw !== "string" || raw.trim().length === 0) {+ return new Date().toISOString().slice(0, 10);+ }+ const v = raw.trim();+ if (!ISO_DATE_ONLY_RE.test(v)) {+ throw new CliError(+ `brain daily: --date must be a YYYY-MM-DD ISO date; got ${JSON.stringify(raw)}`,+ );+ }+ return v;+}diff --git a/src/cli/brain/verbs/temporal-evolution.ts b/src/cli/brain/verbs/temporal-evolution.tsnew file mode 100644index 00000000..6aa69676--- /dev/null+++ b/src/cli/brain/verbs/temporal-evolution.ts@@ -0,0 +1,87 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";+import {+ buildBeliefEvolution,+ type BeliefEvolutionTarget,+} from "../../../core/brain/temporal/belief-evolution.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain evolution [--vault PATH] (--pref-id ID | --topic SLUG)+ * [--json]`+ *+ * Per-preference or per-topic chronological story: status transitions+ * derived from dream summaries, evidence rollup with running counts,+ * and retirement chain.+ */+export async function cmdBrainEvolution(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "pref-id": { type: "string" },+ topic: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ const prefId = trimOrUndefined(flags["pref-id"]);+ const topic = trimOrUndefined(flags["topic"]);+ const target = buildEvolutionTarget(prefId, topic);++ const index = buildTimelineIndex(vault, {});+ const evo = buildBeliefEvolution(index, vault, target);++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(evo, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Belief evolution for ${JSON.stringify(evo.target)}\n`);+ process.stdout.write(` transitions: ${evo.transitions.length}\n`);+ for (const t of evo.transitions) {+ process.stdout.write(` ${t.at} ${t.kind} ${t.prefId}\n`);+ }+ process.stdout.write(` evidence: ${evo.evidence.length}\n`);+ for (const e of evo.evidence) {+ process.stdout.write(+ ` ${e.at} ${e.result} (applied=${e.runningApplied}, violated=${e.runningViolated})\n`,+ );+ }+ process.stdout.write(` retirements: ${evo.retirements.length}\n`);+ for (const r of evo.retirements) {+ process.stdout.write(+ ` ${r.retiredAt} ${r.prefId} ${r.reason ?? ""}${r.supersededBy ? ` superseded-by ${r.supersededBy}` : ""}\n`,+ );+ }+ return 0;+}++function trimOrUndefined(+ v: string | boolean | string[] | undefined,+): string | undefined {+ if (typeof v !== "string") return undefined;+ const t = v.trim();+ return t.length > 0 ? t : undefined;+}++/**+ * Pick exactly one of `--pref-id` / `--topic` and build the typed+ * target shape `buildBeliefEvolution` expects. Throws when both or+ * neither are supplied so we never need a non-null assertion at the+ * call site.+ */+function buildEvolutionTarget(+ prefId: string | undefined,+ topic: string | undefined,+): BeliefEvolutionTarget {+ if (prefId !== undefined && topic !== undefined) {+ throw new CliError(+ "brain evolution: pass exactly one of --pref-id or --topic",+ );+ }+ if (prefId !== undefined) return { prefId };+ if (topic !== undefined) return { topic };+ throw new CliError(+ "brain evolution: pass exactly one of --pref-id or --topic",+ );+}diff --git a/src/cli/brain/verbs/temporal-stale.ts b/src/cli/brain/verbs/temporal-stale.tsnew file mode 100644index 00000000..1e4841d5--- /dev/null+++ b/src/cli/brain/verbs/temporal-stale.ts@@ -0,0 +1,47 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";+import { findStaleEntries } from "../../../core/brain/temporal/stale-watch.ts";+import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";+import { parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain stale [--vault PATH] [--json]`+ *+ * Pure structural staleness report. Thresholds come from the+ * `temporal:` block in `_brain.yaml` (defaults apply when the block+ * is absent).+ */+export async function cmdBrainStale(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ const cfg = loadTemporalConfigSafe(vault);+ const index = buildTimelineIndex(vault, {});+ const report = findStaleEntries(index, vault, cfg);++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(+ `Stale entries (pref >= ${cfg.stale_pref_days}d, signal >= ${cfg.stale_signal_days}d, log >= ${cfg.stale_log_days}d):\n`,+ );+ process.stdout.write(` preferences: ${report.stalePreferences.length}\n`);+ for (const p of report.stalePreferences) {+ process.stdout.write(` ${p.prefId} age=${p.ageDays}d ${p.path}\n`);+ }+ process.stdout.write(` signals: ${report.staleSignals.length}\n`);+ for (const s of report.staleSignals) {+ process.stdout.write(` ${s.signalId} age=${s.ageDays}d ${s.path}\n`);+ }+ process.stdout.write(` log files: ${report.staleLogFiles.length}\n`);+ for (const l of report.staleLogFiles) {+ process.stdout.write(` ${l.path} age=${l.ageDays}d\n`);+ }+ return 0;+}diff --git a/src/cli/brain/verbs/temporal-timeline.ts b/src/cli/brain/verbs/temporal-timeline.tsnew file mode 100644index 00000000..70901d84--- /dev/null+++ b/src/cli/brain/verbs/temporal-timeline.ts@@ -0,0 +1,103 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ isBrainLogEventKind,+ type BrainLogEventKind,+} from "../../../core/brain/types.ts";+import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";+import { selectEvents } from "../../../core/brain/temporal/select-events.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain timeline [--vault PATH] [--pref-id ID] [--topic SLUG]+ * [--kind KIND] [--since ISO] [--until ISO]+ * [--limit N] [--json]`+ *+ * Chronological event list filtered by any combination of pref-id /+ * topic / kind / since / until / limit. Reads `Brain/log/<date>.jsonl`+ * via the canonical TimelineIndex builder.+ */+export async function cmdBrainTimeline(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "pref-id": { type: "string" },+ topic: { type: "string" },+ kind: { type: "string" },+ since: { type: "string" },+ until: { type: "string" },+ limit: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ const prefId = trimOrUndefined(flags["pref-id"]);+ const topic = trimOrUndefined(flags["topic"]);+ const kindRaw = trimOrUndefined(flags["kind"]);+ const since = trimOrUndefined(flags["since"]);+ const until = trimOrUndefined(flags["until"]);+ const limitRaw = trimOrUndefined(flags["limit"]);++ let kind: BrainLogEventKind | undefined;+ if (kindRaw !== undefined) {+ if (!isBrainLogEventKind(kindRaw)) {+ throw new CliError(`brain timeline: unknown kind '${kindRaw}'`);+ }+ kind = kindRaw;+ }++ let limit: number | undefined;+ if (limitRaw !== undefined) {+ if (!/^[0-9]+$/.test(limitRaw)) {+ throw new CliError(`brain timeline: --limit must be a positive integer`);+ }+ const parsed = Number.parseInt(limitRaw, 10);+ if (parsed < 1) {+ throw new CliError(`brain timeline: --limit must be a positive integer`);+ }+ limit = parsed;+ }++ const index = buildTimelineIndex(vault, {+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ const events = selectEvents(index, {+ ...(prefId !== undefined ? { prefId } : {}),+ ...(topic !== undefined ? { topic } : {}),+ ...(kind !== undefined ? { kind } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ const sliced = limit !== undefined ? events.slice(0, limit) : events;++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ { window: index.window, total: events.length, events: sliced },+ null,+ 2,+ ) + "\n",+ );+ return 0;+ }++ process.stdout.write(+ `Timeline window ${index.window.since} .. ${index.window.until}\n`,+ );+ process.stdout.write(`${sliced.length} of ${events.length} event(s):\n`);+ for (const ev of sliced) {+ const slug = ev.prefId ?? ev.topic ?? "-";+ process.stdout.write(+ ` ${ev.at} ${ev.kind} ${slug}${ev.result ? ` [${ev.result}]` : ""}\n`,+ );+ }+ return 0;+}++function trimOrUndefined(+ v: string | boolean | string[] | undefined,+): string | undefined {+ if (typeof v !== "string") return undefined;+ const t = v.trim();+ return t.length > 0 ? t : undefined;+}diff --git a/src/cli/brain/verbs/temporal-weekly.ts b/src/cli/brain/verbs/temporal-weekly.tsnew file mode 100644index 00000000..282cdc05--- /dev/null+++ b/src/cli/brain/verbs/temporal-weekly.ts@@ -0,0 +1,76 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";+import { buildWeeklySynthesis } from "../../../core/brain/temporal/weekly-brief.ts";+import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++/**+ * `o2b brain weekly [--vault PATH] [--week-end YYYY-MM-DD] [--json]`+ *+ * 7-day deterministic synthesis over the TimelineIndex. Defaults+ * `--week-end` to today UTC.+ */+export async function cmdBrainWeekly(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "week-end": { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const weekEnd = resolveWeekEndArg(flags["week-end"]);+ const cfg = loadTemporalConfigSafe(vault);+ const index = buildTimelineIndex(vault, {});+ let synth;+ try {+ synth = buildWeeklySynthesis(index, vault, weekEnd, cfg);+ } catch (exc) {+ if (exc instanceof Error) throw new CliError(`brain weekly: ${exc.message}`);+ throw exc;+ }++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(synth, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Weekly synthesis ${synth.windowStart} .. ${synth.windowEnd}\n`);+ process.stdout.write(` events by kind:\n`);+ for (const [kind, count] of Object.entries(synth.eventsByKind)) {+ process.stdout.write(` ${kind}: ${count}\n`);+ }+ process.stdout.write(` status transitions: ${synth.statusTransitions.length}\n`);+ process.stdout.write(` retired: ${synth.retired.length}\n`);+ for (const r of synth.retired) {+ process.stdout.write(` ${r.at} ${r.prefId}\n`);+ }+ process.stdout.write(` contradictions: ${synth.contradictions.length}\n`);+ for (const c of synth.contradictions) {+ process.stdout.write(+ ` ${c.at} ${c.kind}${c.prefId ? ` ${c.prefId}` : ""}${c.reason ? ` (${c.reason})` : ""}\n`,+ );+ }+ return 0;+}++/**+ * Validate / default the `--week-end` flag. Accepts a bare ISO date+ * (`YYYY-MM-DD`); rejects whitespace-only / malformed input as a CLI+ * error so the underlying helper does not see garbage.+ */+function resolveWeekEndArg(+ raw: string | boolean | string[] | undefined,+): string {+ if (typeof raw !== "string" || raw.trim().length === 0) {+ return new Date().toISOString().slice(0, 10);+ }+ const v = raw.trim();+ if (!ISO_DATE_ONLY_RE.test(v)) {+ throw new CliError(+ `brain weekly: --week-end must be a YYYY-MM-DD ISO date; got ${JSON.stringify(raw)}`,+ );+ }+ return v;+}diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex d1f59bd5..eb057e87 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -27,10 +27,12 @@ import type {BrainGuardrailConfig,BrainLinkGraphConfig,BrainMostAppliedConfig,+ BrainTemporalConfig,BrainVaultConfig,DisciplineReportConfig,ResolvedBrainGuardrailConfig,ResolvedBrainLinkGraphConfig,+ ResolvedBrainTemporalConfig,} from "./types.ts";// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to// break the module-init cycle: the resolver lives in `index.ts` and@@ -165,6 +167,71 @@ export function resolveLinkGraph(};}+/**+ * Default `temporal:` block (v0.10.18). Drives the temporal ++ * synthesis subsystem. Absent block falls back here via+ * `resolveTemporal`. All knobs are purely structural:+ *+ * - `stale_pref_days: 90` - 3 months without activity before a+ * preference is reported as stale.+ * - `stale_signal_days: 30` - 1 month without activity for signals.+ * - `stale_log_days: 180` - 6 months for Brain/log files.+ * - `weekly_start_dow: 1` - ISO-8601 weekday number (1 = Monday,+ * 7 = Sunday). Configurable for vaults that prefer Sunday-start+ * weeks without any language-specific detection.+ * - `daily_window_offset_hours: 0` - daily-brief windows align+ * with UTC midnight by default.+ */+export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig =+ Object.freeze({+ stale_pref_days: 90,+ stale_signal_days: 30,+ stale_log_days: 180,+ weekly_start_dow: 1,+ daily_window_offset_hours: 0,+ }) as ResolvedBrainTemporalConfig;++/**+ * Merge a parsed `temporal` block (or `undefined`) with+ * `BRAIN_TEMPORAL_DEFAULTS`.+ */+export function resolveTemporal(+ cfg: BrainConfig,+): ResolvedBrainTemporalConfig {+ const tp = cfg.temporal;+ if (tp === undefined) return BRAIN_TEMPORAL_DEFAULTS;+ return {+ stale_pref_days:+ tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,+ stale_signal_days:+ tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,+ stale_log_days:+ tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,+ weekly_start_dow:+ tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,+ daily_window_offset_hours:+ tp.daily_window_offset_hours ??+ BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,+ };+}++/**+ * Load + resolve the `temporal:` block, falling back to+ * `BRAIN_TEMPORAL_DEFAULTS` when the config file is missing,+ * malformed, or otherwise unreadable. Used by every temporal+ * consumer (MCP wrappers, CLI verbs) so a freshly-initialised vault+ * still produces a useful report.+ */+export function loadTemporalConfigSafe(+ vault: string,+): ResolvedBrainTemporalConfig {+ try {+ return resolveTemporal(loadBrainConfig(vault));+ } catch {+ return BRAIN_TEMPORAL_DEFAULTS;+ }+}+/*** Default `_brain.yaml` content. Mirrors Β§10 of the design doc. Used by* `brain init` and as the fallback inside `loadBrainConfig` when callers@@ -970,6 +1037,97 @@ export function validateBrainConfigDetailed(: {};}+ // Optional `temporal` block (v0.10.18). Shape:+ // temporal:+ // stale_pref_days: 90 # positive integer+ // stale_signal_days: 30 # positive integer+ // stale_log_days: 180 # positive integer+ // weekly_start_dow: 1 # 1..7 (ISO-8601 weekday)+ // daily_window_offset_hours: 0 # -23..23+ // Absent block β `cfg.temporal` undefined; resolveTemporal returns+ // the bit-identical defaults.+ let temporal: BrainTemporalConfig | undefined;+ if ("temporal" in obj) {+ const rawTp = obj["temporal"];+ if (typeof rawTp !== "object" || rawTp === null || Array.isArray(rawTp)) {+ throw new BrainConfigError(+ "temporal must be a mapping",+ "temporal",+ source,+ );+ }+ const tpObj = rawTp as Record<string, unknown>;+ const partialTp: Record<string, unknown> = {};+ const positiveIntKeys: ReadonlyArray<+ "stale_pref_days" | "stale_signal_days" | "stale_log_days"+ > = ["stale_pref_days", "stale_signal_days", "stale_log_days"];+ for (const key of positiveIntKeys) {+ if (key in tpObj) {+ const v = tpObj[key];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {+ throw new BrainConfigError(+ "must be a positive integer",+ `temporal.${key}`,+ source,+ );+ }+ partialTp[key] = v;+ }+ }+ if ("weekly_start_dow" in tpObj) {+ const v = tpObj["weekly_start_dow"];+ if (+ typeof v !== "number" ||+ !Number.isInteger(v) ||+ v < 1 ||+ v > 7+ ) {+ throw new BrainConfigError(+ "must be an ISO-8601 weekday number (1..7)",+ "temporal.weekly_start_dow",+ source,+ );+ }+ partialTp["weekly_start_dow"] = v;+ }+ if ("daily_window_offset_hours" in tpObj) {+ const v = tpObj["daily_window_offset_hours"];+ if (+ typeof v !== "number" ||+ !Number.isInteger(v) ||+ v < -23 ||+ v > 23+ ) {+ throw new BrainConfigError(+ "must be an integer in [-23, 23]",+ "temporal.daily_window_offset_hours",+ source,+ );+ }+ partialTp["daily_window_offset_hours"] = v;+ }+ // Forward-compat: unknown sub-keys under `temporal:` β warning.+ const knownTp = new Set([+ "stale_pref_days",+ "stale_signal_days",+ "stale_log_days",+ "weekly_start_dow",+ "daily_window_offset_hours",+ ]);+ for (const key of Object.keys(tpObj)) {+ if (!knownTp.has(key)) {+ warnings.push({+ path: source ?? "<config>",+ message: `temporal.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }+ temporal =+ Object.keys(partialTp).length > 0+ ? (partialTp as BrainTemporalConfig)+ : {};+ }+// Forward-compat: unknown top-level keys β warning, not error.const known = new Set(["schema_version",@@ -983,6 +1141,7 @@ export function validateBrainConfigDetailed("discipline_report","guardrails","link_graph",+ "temporal",]);for (const key of Object.keys(obj)) {if (!known.has(key)) {@@ -1019,6 +1178,7 @@ export function validateBrainConfigDetailed(...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),...(guardrails !== undefined ? { guardrails } : {}),...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),+ ...(temporal !== undefined ? { temporal } : {}),};return { config, warnings };diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex f1089293..6f9649be 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -586,10 +586,34 @@ export function parsePreference(path: string): BrainPreference {...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }: {}),+ ...spreadBiTemporal(meta),};return Object.freeze(result);}+/**+ * Read the additive bi-temporal slots (`valid_from`, `valid_until`,+ * `recorded_at`) from a frontmatter map. Returns a partial object+ * with only the slots the file actually carries; absent on legacy+ * files. Shared between `parsePreference` and `parseRetired` so the+ * spread call site stays one-line and the slot names live in exactly+ * one place.+ */+function spreadBiTemporal(meta: Record<string, unknown>): {+ readonly valid_from?: string;+ readonly valid_until?: string;+ readonly recorded_at?: string;+} {+ const validFrom = optionalScalarString(meta, "valid_from");+ const validUntil = optionalScalarString(meta, "valid_until");+ const recordedAt = optionalScalarString(meta, "recorded_at");+ return {+ ...(validFrom !== undefined ? { valid_from: validFrom } : {}),+ ...(validUntil !== undefined ? { valid_until: validUntil } : {}),+ ...(recordedAt !== undefined ? { recorded_at: recordedAt } : {}),+ };+}+/*** Parse a retired-preference file. Mirrors {@link parsePreference} but* enforces the `retired/` folder invariant and validates the@@ -665,6 +689,7 @@ export function parseRetired(path: string): BrainRetired {...(optionalScalarString(meta, "user_rejected_reason") !== undefined? { user_rejected_reason: optionalScalarString(meta, "user_rejected_reason") }: {}),+ ...spreadBiTemporal(meta),};return Object.freeze(result);}diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex a971fedf..cfcec347 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -361,10 +361,50 @@ export function parseSignal(path: string): BrainSignal {...(source_type !== undefined ? { source_type } : {}),...(dedup_hash !== undefined ? { dedup_hash } : {}),...(session_ref !== undefined ? { session_ref } : {}),+ ...readBiTemporal(meta, path),};return Object.freeze(result);}+/**+ * Read the additive bi-temporal slots (`valid_from`, `valid_until`,+ * `recorded_at`) from a signal frontmatter map. Returns only the+ * slots the file actually carries; absent on legacy files.+ *+ * Slot values are validated as non-empty strings; an empty / whitespace+ * value is rejected (the field is present in the file but carries no+ * useful timestamp - that's a corruption worth surfacing).+ */+function readBiTemporal(+ meta: ReturnType<typeof parseFrontmatter>[0],+ path: string,+): {+ readonly valid_from?: string;+ readonly valid_until?: string;+ readonly recorded_at?: string;+} {+ return {+ ...readBiTemporalSlot(meta, "valid_from", path),+ ...readBiTemporalSlot(meta, "valid_until", path),+ ...readBiTemporalSlot(meta, "recorded_at", path),+ };+}++function readBiTemporalSlot(+ meta: ReturnType<typeof parseFrontmatter>[0],+ key: "valid_from" | "valid_until" | "recorded_at",+ path: string,+): Partial<Record<"valid_from" | "valid_until" | "recorded_at", string>> {+ const v = meta[key];+ if (v === undefined) return {};+ if (typeof v !== "string") {+ throw new Error(`signal field '${key}' must be a string (${path})`);+ }+ const trimmed = v.trim();+ if (trimmed.length === 0) return {};+ return { [key]: trimmed };+}+// ----- Helpers --------------------------------------------------------------/**diff --git a/src/core/brain/temporal/belief-evolution.ts b/src/core/brain/temporal/belief-evolution.tsnew file mode 100644index 00000000..2efe1c3e--- /dev/null+++ b/src/core/brain/temporal/belief-evolution.ts@@ -0,0 +1,368 @@+/**+ * `buildBeliefEvolution(index, vault, target)` - per-preference or+ * per-topic chronological view assembled from the `TimelineIndex`+ * plus `Brain/retired/*.md` frontmatter for retirement chain+ * resolution.+ *+ * Transitions are derived from `dream` summary events:+ * - `pref-id` appears in `new_unconfirmed` -> creation+ * - `pref-id` appears in `confirmed` -> promotion+ * - matching `ret-id` appears in `retired` -> retirement+ *+ * Evidence rows come from `apply-evidence` timeline events filtered+ * to the target id (or any pref/ret matching the topic). Running+ * applied / violated / outdated counts are carried per row.+ *+ * Retirement chain resolution walks `superseded_by` links across+ * `Brain/retired/*.md` with a visited-set cycle guard.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`,+ * Task 4 in `plan.md`.+ */++import { existsSync, readdirSync } from "node:fs";+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 { extractId } from "./period-common.ts";+import { selectEvents } from "./select-events.ts";+import type { TemporalEvent, TimelineIndex } from "./types.ts";++/** What the caller wants the evolution for. */+export type BeliefEvolutionTarget =+ | { readonly prefId: string }+ | { readonly topic: string };++/** One status-change row. */+export interface BeliefTransition {+ /** ISO-8601 UTC timestamp. */+ readonly at: string;+ /** Transition kind. */+ readonly kind: "creation" | "promotion" | "retirement";+ /** Preference / retired id the transition applies to. */+ readonly prefId: string;+ /** Wikilink the dream summary used (for audit). */+ readonly link: string;+}++/** One evidence row with running counts. */+export interface BeliefEvidenceRow {+ readonly at: string;+ readonly prefId: string;+ readonly result: BrainApplyResult;+ readonly artifact?: string;+ readonly runningApplied: number;+ readonly runningViolated: number;+ readonly runningOutdated: number;+}++/** One retirement record sourced from `Brain/retired/*.md`. */+export interface BeliefRetirement {+ readonly prefId: string;+ readonly retiredAt: string;+ readonly reason?: string;+ readonly retiredBy?: string;+ readonly supersededBy?: string;+ readonly supersedes?: string;+ readonly topic?: string;+}++export interface BeliefEvolutionEnvelope {+ readonly target: BeliefEvolutionTarget;+ readonly transitions: ReadonlyArray<BeliefTransition>;+ readonly evidence: ReadonlyArray<BeliefEvidenceRow>;+ readonly retirements: ReadonlyArray<BeliefRetirement>;+ readonly generatedAt: string;+}++export interface BuildBeliefEvolutionOptions {+ readonly now?: Date;+}++export function buildBeliefEvolution(+ index: TimelineIndex,+ vault: string,+ target: BeliefEvolutionTarget,+ opts: BuildBeliefEvolutionOptions = {},+): BeliefEvolutionEnvelope {+ const generatedAt = (opts.now ?? new Date()).toISOString();+ const targetIdSet = resolveTargetIds(index, vault, target);++ const transitions = collectTransitions(index, targetIdSet);+ const evidence = collectEvidence(index, targetIdSet);+ const retirements = collectRetirements(vault, target, targetIdSet);++ return Object.freeze({+ target,+ transitions: Object.freeze(transitions),+ evidence: Object.freeze(evidence),+ retirements: Object.freeze(retirements),+ generatedAt,+ });+}++/**+ * Resolve the set of pref-* / ret-* ids that the target references.+ * For a prefId target the set is just that id plus its `ret-` sibling.+ * For a topic target we scan every `pref-*` / `ret-*` file with that+ * topic in frontmatter, plus every timeline event grouped under that+ * topic that carries a prefId.+ */+function resolveTargetIds(+ index: TimelineIndex,+ vault: string,+ target: BeliefEvolutionTarget,+): ReadonlySet<string> {+ if ("prefId" in target) {+ const ids = new Set<string>();+ ids.add(target.prefId);+ // pref-foo / ret-foo share the same slug. Treat the pair as the+ // same lifecycle anchor so transitions across the rename are+ // surfaced together.+ if (target.prefId.startsWith("pref-")) {+ ids.add(`ret-${target.prefId.slice("pref-".length)}`);+ } else if (target.prefId.startsWith("ret-")) {+ ids.add(`pref-${target.prefId.slice("ret-".length)}`);+ }+ return ids;+ }+ const ids = new Set<string>();+ const fromIndex = index.eventsByTopic.get(target.topic);+ if (fromIndex !== undefined) {+ for (const ev of fromIndex) {+ if (ev.prefId !== undefined) ids.add(ev.prefId);+ }+ }+ collectTopicIdsFromDisk(vault, target.topic, "preferences", "pref-", ids);+ collectTopicIdsFromDisk(vault, target.topic, "retired", "ret-", ids);+ return ids;+}++function collectTopicIdsFromDisk(+ vault: string,+ topic: string,+ subdir: "preferences" | "retired",+ prefix: "pref-" | "ret-",+ out: Set<string>,+): void {+ const dirs = brainDirs(vault);+ const dir = subdir === "preferences" ? dirs.preferences : dirs.retired;+ if (!existsSync(dir)) return;+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith(prefix)) continue;+ const path = join(dir, entry.name);+ let meta: Record<string, unknown>;+ try {+ [meta] = parseFrontmatter(path);+ } catch {+ continue;+ }+ if (meta["topic"] !== topic) continue;+ const id = typeof meta["id"] === "string" ? meta["id"] : null;+ out.add(id ?? entry.name.slice(0, -".md".length));+ }+}++function collectTransitions(+ index: TimelineIndex,+ targetIds: ReadonlySet<string>,+): BeliefTransition[] {+ const dreamEvents = index.eventsByKind.get(BRAIN_LOG_EVENT_KIND.dream) ?? [];+ const out: BeliefTransition[] = [];+ for (const ev of dreamEvents) {+ const summary = ev.dreamSummary;+ if (summary === undefined) continue;+ appendTransitionsFromLinks(+ ev.at,+ summary.newUnconfirmed,+ "creation",+ targetIds,+ out,+ );+ appendTransitionsFromLinks(+ ev.at,+ summary.confirmed,+ "promotion",+ targetIds,+ out,+ );+ appendTransitionsFromLinks(+ ev.at,+ summary.retired,+ "retirement",+ targetIds,+ out,+ );+ }+ out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));+ return out;+}++function appendTransitionsFromLinks(+ at: string,+ links: ReadonlyArray<string> | undefined,+ kind: BeliefTransition["kind"],+ targetIds: ReadonlySet<string>,+ out: BeliefTransition[],+): void {+ if (links === undefined) return;+ for (const link of links) {+ const id = extractId(link);+ if (id === undefined) continue;+ if (!matchesTarget(id, targetIds)) continue;+ out.push(+ Object.freeze({+ at,+ kind,+ prefId: id,+ link,+ }),+ );+ }+}++function matchesTarget(+ candidateId: string,+ targetIds: ReadonlySet<string>,+): boolean {+ if (targetIds.has(candidateId)) return true;+ // pref-foo / ret-foo share lifecycle; treat the alternate prefix as+ // matching too so a `retirement` entry against `ret-foo` resolves+ // even when only `pref-foo` was requested.+ if (candidateId.startsWith("pref-")) {+ return targetIds.has(`ret-${candidateId.slice("pref-".length)}`);+ }+ if (candidateId.startsWith("ret-")) {+ return targetIds.has(`pref-${candidateId.slice("ret-".length)}`);+ }+ return false;+}++function collectEvidence(+ index: TimelineIndex,+ targetIds: ReadonlySet<string>,+): BeliefEvidenceRow[] {+ // apply-evidence rows do not carry `topic` themselves - the topic+ // lives on the target preference. So we narrow to the apply-evidence+ // bucket and filter by the resolved `targetIds` set (which contains+ // every pref-* / ret-* the topic / prefId pair points at).+ const candidate = selectEvents(index, {+ kind: BRAIN_LOG_EVENT_KIND.applyEvidence,+ });+ const filtered: TemporalEvent[] = [];+ for (const ev of candidate) {+ if (ev.prefId === undefined) continue;+ if (!matchesTarget(ev.prefId, targetIds)) continue;+ if (ev.result === undefined) continue;+ filtered.push(ev);+ }+ let applied = 0;+ let violated = 0;+ let outdated = 0;+ const out: BeliefEvidenceRow[] = [];+ for (const ev of filtered) {+ if (ev.result === BRAIN_APPLY_RESULT.applied) applied++;+ if (ev.result === BRAIN_APPLY_RESULT.violated) violated++;+ if (ev.result === BRAIN_APPLY_RESULT.outdated) outdated++;+ const row: BeliefEvidenceRow = {+ at: ev.at,+ prefId: ev.prefId!,+ result: ev.result!,+ ...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),+ runningApplied: applied,+ runningViolated: violated,+ runningOutdated: outdated,+ };+ out.push(Object.freeze(row));+ }+ return out;+}++function collectRetirements(+ vault: string,+ _target: BeliefEvolutionTarget,+ targetIds: ReadonlySet<string>,+): BeliefRetirement[] {+ const dir = brainDirs(vault).retired;+ if (!existsSync(dir)) return [];+ const out: BeliefRetirement[] = [];+ const visited = new Set<string>();+ // Seed queue once per source id. `pref-foo` and `ret-foo` share+ // the slug, so a `pref-` id always pushes its `ret-` sibling too.+ // Topic targets already enumerate every `ret-*` with the topic+ // via `resolveTargetIds`, so a second loop would only feed+ // duplicates (the visited-set guards them out, but the dedup at+ // the seed step avoids the queue grind in the first place).+ const queue: string[] = [];+ for (const id of targetIds) {+ if (id.startsWith("ret-")) queue.push(id);+ if (id.startsWith("pref-")) queue.push(`ret-${id.slice("pref-".length)}`);+ }+ while (queue.length > 0) {+ const id = queue.shift();+ if (id === undefined) break;+ if (visited.has(id)) continue;+ visited.add(id);+ const path = join(dir, `${id}.md`);+ if (!existsSync(path)) continue;+ let meta: Record<string, unknown>;+ try {+ [meta] = parseFrontmatter(path);+ } catch {+ continue;+ }+ const retiredAt = readScalar(meta["retired_at"]);+ if (retiredAt === undefined) continue;+ const supersededByLink = readScalar(meta["superseded_by"]);+ const supersededBy = supersededByLink !== undefined+ ? extractId(supersededByLink)+ : undefined;+ const supersedesLink = readScalar(meta["supersedes"]);+ const supersedes = supersedesLink !== undefined+ ? extractId(supersedesLink)+ : undefined;+ const row: BeliefRetirement = {+ prefId: id,+ retiredAt,+ ...(readScalar(meta["retired_reason"]) !== undefined+ ? { reason: readScalar(meta["retired_reason"])! }+ : {}),+ ...(readScalar(meta["retired_by"]) !== undefined+ ? { retiredBy: readScalar(meta["retired_by"])! }+ : {}),+ ...(supersededBy !== undefined ? { supersededBy } : {}),+ ...(supersedes !== undefined ? { supersedes } : {}),+ ...(readScalar(meta["topic"]) !== undefined+ ? { topic: readScalar(meta["topic"])! }+ : {}),+ };+ out.push(Object.freeze(row));+ // Walk the chain: `supersedes` points to the previous retired+ // record; `superseded_by` to the new active pref (we follow the+ // ret- sibling so we keep enumerating retired records, not active+ // ones).+ if (supersedes !== undefined && supersedes.startsWith("ret-")) {+ queue.push(supersedes);+ }+ if (supersededBy !== undefined && supersededBy.startsWith("pref-")) {+ queue.push(`ret-${supersededBy.slice("pref-".length)}`);+ }+ }+ out.sort((a, b) => {+ if (a.retiredAt < b.retiredAt) return -1;+ if (a.retiredAt > b.retiredAt) return 1;+ return a.prefId.localeCompare(b.prefId);+ });+ return out;+}++function readScalar(value: unknown): string | undefined {+ return typeof value === "string" && value.length > 0 ? value : undefined;+}diff --git a/src/core/brain/temporal/build-index.ts b/src/core/brain/temporal/build-index.tsnew file mode 100644index 00000000..7d3d8342--- /dev/null+++ b/src/core/brain/temporal/build-index.ts@@ -0,0 +1,417 @@+/**+ * `buildTimelineIndex(vault, opts)` - the single disk-touching helper+ * in the temporal subsystem.+ *+ * Walks `Brain/log/<YYYY-MM-DD>.jsonl` (via the public `readLogDay`+ * reader, which prefers JSONL with a Markdown fallback) for every date+ * intersecting the requested window. Also walks `Brain/retired/*.md`+ * frontmatter to emit synthetic `retire` events at each retired+ * entry's `retired_at` timestamp. Returns a frozen `TimelineIndex` so+ * all downstream projections (`selectEvents`, `buildBeliefEvolution`,+ * `findStaleEntries`, `buildDailyBrief`, `buildWeeklySynthesis`)+ * observe the same window semantics.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`,+ * Task 2 in `docs/brainstorm/temporal-synthesis/plan.md`.+ */++import { existsSync, readdirSync } from "node:fs";+import { join, relative } from "node:path";++import type { BrainLogEntry } from "./../log.ts";+import { readLogDay } from "./../log-jsonl.ts";+import { brainDirs } from "./../paths.ts";+import { parseFrontmatter } from "../../vault.ts";+import { parseWikilink } from "./../wikilink.ts";+import {+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+ type BrainApplyResult,+ type BrainLogEventKind,+} from "./../types.ts";+import type {+ DreamSummarySlots,+ TemporalEvent,+ TemporalEventSource,+ TimelineIndex,+ TimelineWindow,+} from "./types.ts";++/** Input shape for {@link buildTimelineIndex}. */+export interface BuildTimelineIndexOptions {+ /**+ * Inclusive lower bound. Accepts an ISO date (`YYYY-MM-DD` -+ * interpreted as `T00:00:00Z`) or a full ISO timestamp. Default:+ * `1970-01-01T00:00:00Z`.+ */+ readonly since?: string;+ /**+ * Exclusive upper bound. Accepts an ISO date (interpreted as+ * `T00:00:00Z`) or a full ISO timestamp. Default: one millisecond+ * past `Date.now()`.+ */+ readonly until?: string;+ /** Wall clock; defaults to `new Date()`. Used to derive the default `until`. */+ readonly now?: Date;+}++const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;+const ISO_DATE_PREFIX_RE = /^\d{4}-\d{2}-\d{2}/;+const ONE_DAY_MS = 24 * 60 * 60 * 1000;++/**+ * Build the timeline index. Pure single-pass scan; the resulting index+ * is frozen and every nested array / map is frozen.+ */+export function buildTimelineIndex(+ vault: string,+ opts: BuildTimelineIndexOptions = {},+): TimelineIndex {+ const window = resolveWindow(opts);++ const events: TemporalEvent[] = [];+ collectLogEvents(vault, window, events);+ collectRetiredEvents(vault, window, events);++ events.sort(compareEvents);++ const byKind = new Map<BrainLogEventKind, TemporalEvent[]>();+ const byPrefId = new Map<string, TemporalEvent[]>();+ const byTopic = new Map<string, TemporalEvent[]>();+ for (const ev of events) {+ pushToMap(byKind, ev.kind, ev);+ if (ev.prefId !== undefined) pushToMap(byPrefId, ev.prefId, ev);+ if (ev.topic !== undefined) pushToMap(byTopic, ev.topic, ev);+ }++ return Object.freeze({+ events: Object.freeze(events.slice()),+ eventsByKind: freezeMap(byKind),+ eventsByPrefId: freezeMap(byPrefId),+ eventsByTopic: freezeMap(byTopic),+ window,+ });+}++function pushToMap<K, V>(m: Map<K, V[]>, key: K, value: V): void {+ const bucket = m.get(key);+ if (bucket === undefined) {+ m.set(key, [value]);+ } else {+ bucket.push(value);+ }+}++function freezeMap<K, V>(+ m: Map<K, V[]>,+): ReadonlyMap<K, ReadonlyArray<V>> {+ const out = new Map<K, ReadonlyArray<V>>();+ for (const [k, v] of m) {+ out.set(k, Object.freeze(v));+ }+ return out;+}++function compareEvents(a: TemporalEvent, b: TemporalEvent): number {+ if (a.at !== b.at) return a.at < b.at ? -1 : 1;+ if (a.source.path !== b.source.path) {+ return a.source.path < b.source.path ? -1 : 1;+ }+ const la = a.source.line ?? -1;+ const lb = b.source.line ?? -1;+ return la - lb;+}++function resolveWindow(opts: BuildTimelineIndexOptions): TimelineWindow {+ const sinceRaw = opts.since;+ const untilRaw = opts.until;+ const now = opts.now ?? new Date();+ const since =+ sinceRaw !== undefined+ ? normalizeWindowBound(sinceRaw, "since")+ : "1970-01-01T00:00:00Z";+ const until =+ untilRaw !== undefined+ ? normalizeWindowBound(untilRaw, "until")+ : new Date(now.getTime() + 1).toISOString();+ return Object.freeze({ since, until });+}++/**+ * Normalize a caller-supplied window bound to a canonical UTC ISO+ * timestamp so the downstream lexicographic comparison in+ * `selectEvents` is unambiguous. Accepts either a bare ISO date+ * (interpreted as `T00:00:00Z`) or a full ISO timestamp. Rejects+ * unparseable strings so a typo cannot silently mis-filter events.+ */+function normalizeWindowBound(value: string, field: "since" | "until"): string {+ const expanded = ISO_DATE_ONLY_RE.test(value) ? `${value}T00:00:00Z` : value;+ const ms = Date.parse(expanded);+ if (!Number.isFinite(ms)) {+ throw new Error(+ `buildTimelineIndex: ${field} must be an ISO date or ISO timestamp; got ${JSON.stringify(value)}`,+ );+ }+ return expanded;+}++function dateKeyFromIso(iso: string): string {+ const m = ISO_DATE_PREFIX_RE.exec(iso);+ return m === null ? iso.slice(0, 10) : m[0];+}++function addDays(day: string, delta: number): string {+ const t = Date.parse(`${day}T00:00:00Z`);+ if (!Number.isFinite(t)) return day;+ return new Date(t + delta * ONE_DAY_MS).toISOString().slice(0, 10);+}++function collectLogEvents(+ vault: string,+ window: TimelineWindow,+ out: TemporalEvent[],+): void {+ const logDir = brainDirs(vault).log;+ if (!existsSync(logDir)) return;+ const sinceDay = dateKeyFromIso(window.since);+ const untilDay = dateKeyFromIso(window.until);+ // Err permissive by one day on each side (timezone safety - the+ // same convention `digest.ts:readLogsInWindow` uses).+ const lowerBound = addDays(sinceDay, -1);+ const upperBound = addDays(untilDay, 1);+ const dates = new Set<string>();+ for (const entry of readdirSync(logDir, { withFileTypes: true })) {+ if (!entry.isFile()) continue;+ const base = stripKnownLogExtension(entry.name);+ if (base !== null && ISO_DATE_ONLY_RE.test(base)) dates.add(base);+ }+ const sortedDates = [...dates].sort();+ for (const date of sortedDates) {+ if (date < lowerBound) continue;+ if (date > upperBound) continue;+ const { entries, source } = readLogDay(vault, date);+ // Reflect the actual source `readLogDay` consumed so the+ // audit pointer stays accurate when the JSONL sidecar is+ // missing and the markdown fallback is used.+ const filePath = join(+ logDir,+ source === "markdown-fallback" ? `${date}.md` : `${date}.jsonl`,+ );+ const vaultPath = relative(vault, filePath);+ for (let i = 0; i < entries.length; i++) {+ const entry = entries[i]!;+ if (entry.timestamp < window.since) continue;+ if (entry.timestamp >= window.until) continue;+ out.push(+ normaliseLogEntry(entry, {+ path: vaultPath,+ line: i + 1,+ }),+ );+ }+ }+}++function stripKnownLogExtension(name: string): string | null {+ if (name.endsWith(".jsonl")) return name.slice(0, -".jsonl".length);+ if (name.endsWith(".md")) return name.slice(0, -".md".length);+ return null;+}++/**+ * Turn one `BrainLogEntry` into one `TemporalEvent`. Optional slots+ * (`prefId`, `topic`, `result`, `artifact`, `reason`, `text`) come+ * from the entry's `body` payload when the event kind documents them.+ * Unknown kinds still produce a `TemporalEvent` with no payload slots+ * populated; consumers that care about a specific kind read the+ * narrower slot off the timeline event directly.+ */+function normaliseLogEntry(+ entry: BrainLogEntry,+ source: TemporalEventSource,+): TemporalEvent {+ const body = entry.body;+ const prefId = extractPrefIdFromBody(entry.eventType, body);+ const topic = readScalar(body["topic"]);+ const reason = readScalar(body["reason"]);+ const result =+ entry.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence+ ? readApplyResult(body["result"])+ : undefined;+ const artifactRaw =+ entry.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence+ ? readScalar(body["artifact"])+ : undefined;+ // Strip surrounding wikilink brackets so the slot carries the raw+ // path / alias. We deliberately do NOT use `parseWikilink` here -+ // that helper collapses folder segments to a basename, which would+ // lose the `src/cli/main.ts` shape operators expect from an audit+ // pointer.+ const artifact =+ artifactRaw !== undefined ? stripWikilinkBrackets(artifactRaw) : undefined;+ const text =+ entry.eventType === BRAIN_LOG_EVENT_KIND.note+ ? readScalar(body["text"])+ : undefined;+ const dreamSummary =+ entry.eventType === BRAIN_LOG_EVENT_KIND.dream+ ? readDreamSummary(body)+ : undefined;+ return Object.freeze({+ at: entry.timestamp,+ kind: entry.eventType,+ source,+ ...(prefId !== undefined ? { prefId } : {}),+ ...(topic !== undefined ? { topic } : {}),+ ...(reason !== undefined ? { reason } : {}),+ ...(result !== undefined ? { result } : {}),+ ...(artifact !== undefined ? { artifact } : {}),+ ...(text !== undefined ? { text } : {}),+ ...(dreamSummary !== undefined ? { dreamSummary } : {}),+ });+}++/**+ * Pull the dream summary array slices off the entry body. Returns+ * `undefined` when no slot is populated so the spread above omits the+ * `dreamSummary` field on no-op runs.+ */+function readDreamSummary(+ body: BrainLogEntry["body"],+): DreamSummarySlots | undefined {+ const newUnconfirmed = readStringArray(body["new_unconfirmed"]);+ const confirmed = readStringArray(body["confirmed"]);+ const retired = readStringArray(body["retired"]);+ if (+ newUnconfirmed === undefined &&+ confirmed === undefined &&+ retired === undefined+ ) {+ return undefined;+ }+ return Object.freeze({+ ...(newUnconfirmed !== undefined ? { newUnconfirmed } : {}),+ ...(confirmed !== undefined ? { confirmed } : {}),+ ...(retired !== undefined ? { retired } : {}),+ });+}++function readStringArray(value: unknown): ReadonlyArray<string> | undefined {+ if (!Array.isArray(value)) return undefined;+ if (value.length === 0) return undefined;+ const out: string[] = [];+ for (const v of value) {+ if (typeof v !== "string") return undefined;+ out.push(v);+ }+ return Object.freeze(out);+}++function readScalar(value: unknown): string | undefined {+ return typeof value === "string" && value.length > 0 ? value : undefined;+}++function readApplyResult(value: unknown): BrainApplyResult | undefined {+ if (+ value === BRAIN_APPLY_RESULT.applied ||+ value === BRAIN_APPLY_RESULT.violated ||+ value === BRAIN_APPLY_RESULT.outdated+ ) {+ return value;+ }+ return undefined;+}++/**+ * Strip `[[β¦]]` brackets from a wikilink body without collapsing the+ * folder structure inside the bracket. When an alias is present+ * (`[[target|display]]`), keep the bare target. Bare strings pass+ * through unchanged.+ */+function stripWikilinkBrackets(value: string): string {+ let v = value.trim();+ if (v.startsWith("[[") && v.endsWith("]]")) {+ v = v.slice(2, -2);+ }+ const pipe = v.indexOf("|");+ return pipe >= 0 ? v.slice(0, pipe) : v;+}++const PREF_ID_RE = /^(?:pref|ret|sig)-[A-Za-z0-9-]+$/;++function extractPrefIdFromBody(+ kind: BrainLogEventKind,+ body: BrainLogEntry["body"],+): string | undefined {+ switch (kind) {+ case BRAIN_LOG_EVENT_KIND.applyEvidence:+ case BRAIN_LOG_EVENT_KIND.notedRedundant:+ case BRAIN_LOG_EVENT_KIND.retire:+ case BRAIN_LOG_EVENT_KIND.promote:+ case BRAIN_LOG_EVENT_KIND.forceConfirmed:+ case BRAIN_LOG_EVENT_KIND.reject:+ return readWikilinkId(body["preference"]);+ case BRAIN_LOG_EVENT_KIND.signalSuppressed:+ // The retired pref is the lifecycle-meaningful anchor for a+ // suppression event; the inbound signal slug is one-off.+ return (+ readWikilinkId(body["retired"]) ?? readWikilinkId(body["signal"])+ );+ case BRAIN_LOG_EVENT_KIND.feedback:+ return readWikilinkId(body["signal"]);+ default:+ return undefined;+ }+}++function readWikilinkId(value: unknown): string | undefined {+ if (typeof value !== "string" || value.length === 0) return undefined;+ const target = parseWikilink(value) ?? value;+ // Accept only the documented id prefixes so a stray artifact path+ // doesn't pollute the per-pref grouping.+ return PREF_ID_RE.test(target) ? target : undefined;+}++function collectRetiredEvents(+ vault: string,+ window: TimelineWindow,+ out: TemporalEvent[],+): void {+ const retiredDir = brainDirs(vault).retired;+ if (!existsSync(retiredDir)) return;+ for (const entry of readdirSync(retiredDir, { withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith("ret-")) continue;+ const path = join(retiredDir, entry.name);+ let meta: Record<string, unknown>;+ try {+ const [parsed] = parseFrontmatter(path);+ meta = parsed;+ } catch {+ continue;+ }+ const retiredAt = readScalar(meta["retired_at"]);+ if (retiredAt === undefined) continue;+ if (retiredAt < window.since) continue;+ if (retiredAt >= window.until) continue;+ const id = readScalar(meta["id"]) ?? entry.name.slice(0, -".md".length);+ const topic = readScalar(meta["topic"]);+ const reason = readScalar(meta["reason"]);+ const validFrom = readScalar(meta["valid_from"]);+ const validUntil = readScalar(meta["valid_until"]);+ const recordedAt = readScalar(meta["recorded_at"]);+ out.push(+ Object.freeze({+ at: retiredAt,+ kind: BRAIN_LOG_EVENT_KIND.retire,+ source: { path: relative(vault, path), line: null },+ prefId: id,+ ...(topic !== undefined ? { topic } : {}),+ ...(reason !== undefined ? { reason } : {}),+ ...(validFrom !== undefined ? { validFrom } : {}),+ ...(validUntil !== undefined ? { validUntil } : {}),+ ...(recordedAt !== undefined ? { recordedAt } : {}),+ }),+ );+ }+}diff --git a/src/core/brain/temporal/daily-brief.ts b/src/core/brain/temporal/daily-brief.tsnew file mode 100644index 00000000..0272f320--- /dev/null+++ b/src/core/brain/temporal/daily-brief.ts@@ -0,0 +1,102 @@+/**+ * `buildDailyBrief(index, vault, date, opts?)` - per-day deterministic+ * summary used by the daily-brief surface.+ *+ * Pure projection over the `TimelineIndex`: filters events to a single+ * day window (UTC by default; configurable via+ * `temporal.daily_window_offset_hours`), counts them by kind, derives+ * status transitions from dream summary arrays, computes the per-day+ * vault delta, and deduplicates the cited artifact wikilinks.+ *+ * Shared period helpers live in `period-common.ts`. Vault parameter is+ * kept on the signature for parity with sibling projections; the brief+ * does not re-touch disk.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`,+ * Task 6 in `plan.md`.+ */++import { isoSecond } from "./../time.ts";+import type { BrainLogEventKind } from "./../types.ts";+import { selectEvents } from "./select-events.ts";+import {+ collectSourcePointers,+ collectTransitions,+ computeVaultDelta,+ countByKind,+ type PeriodStatusTransition,+ type PeriodVaultDelta,+} from "./period-common.ts";+import type { TimelineIndex } from "./types.ts";++const ONE_HOUR_MS = 60 * 60 * 1000;+const ONE_DAY_MS = 24 * 60 * 60 * 1000;++export interface DailyBriefEnvelope {+ readonly date: string;+ readonly window: { readonly since: string; readonly until: string };+ readonly eventsByKind: Readonly<Partial<Record<BrainLogEventKind, number>>>;+ readonly statusTransitions: ReadonlyArray<PeriodStatusTransition>;+ readonly vaultDelta: PeriodVaultDelta;+ readonly sourcePointers: ReadonlyArray<string>;+ readonly generatedAt: string;+}++export interface BuildDailyBriefOptions {+ /** Offset hours from UTC for the day boundary; range [-23, 23]. Default 0. */+ readonly offsetHours?: number;+ /** Wall clock for `generatedAt`; defaults to `new Date()`. */+ readonly now?: Date;+}++export function buildDailyBrief(+ index: TimelineIndex,+ _vault: string,+ date: string,+ opts: BuildDailyBriefOptions = {},+): DailyBriefEnvelope {+ // `_vault` is part of the helper signature for parity with sibling+ // projections; the brief itself is a pure projection over the index+ // and does not re-touch disk.+ const offsetHours = opts.offsetHours ?? 0;+ const window = dailyWindow(date, offsetHours);+ const generatedAt = (opts.now ?? new Date()).toISOString();++ const dayEvents = selectEvents(index, {+ since: window.since,+ until: window.until,+ });++ const transitions = collectTransitions(dayEvents);+ const vaultDelta = computeVaultDelta(dayEvents, transitions);++ return Object.freeze({+ date,+ window,+ eventsByKind: Object.freeze(countByKind(dayEvents)),+ statusTransitions: Object.freeze(transitions),+ vaultDelta: Object.freeze(vaultDelta),+ sourcePointers: Object.freeze(collectSourcePointers(dayEvents)),+ generatedAt,+ });+}++function dailyWindow(+ date: string,+ offsetHours: number,+): { readonly since: string; readonly until: string } {+ const dayStartMs = Date.parse(`${date}T00:00:00Z`);+ if (!Number.isFinite(dayStartMs)) {+ throw new Error(`buildDailyBrief: invalid date ${JSON.stringify(date)}`);+ }+ const offsetMs = offsetHours * ONE_HOUR_MS;+ // Use second-precision canonical UTC so the string compare in+ // `selectEvents` matches the shape of event timestamps emitted by+ // `appendLogEvent` (also second-precision). Mixing the+ // `Date.toISOString()` `.000Z` form would still work by accident+ // (lexical ordering of `Z` vs `.`) but is fragile.+ return Object.freeze({+ since: isoSecond(new Date(dayStartMs - offsetMs)),+ until: isoSecond(new Date(dayStartMs - offsetMs + ONE_DAY_MS)),+ });+}diff --git a/src/core/brain/temporal/period-common.ts b/src/core/brain/temporal/period-common.tsnew file mode 100644index 00000000..40ee5ae9--- /dev/null+++ b/src/core/brain/temporal/period-common.ts@@ -0,0 +1,137 @@+/**+ * Shared helpers used by both `buildDailyBrief` and+ * `buildWeeklySynthesis`. Extracted so the two surface modules carry+ * one canonical implementation of wikilink-id extraction, transition+ * extraction from dream summaries, vault-delta counting, and source+ * pointer deduplication.+ */++import { parseWikilink } from "./../wikilink.ts";+import {+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+ type BrainLogEventKind,+} from "./../types.ts";+import type { TemporalEvent } from "./types.ts";++const LINK_REASON_RE = /\(([^)]+)\)\s*$/;+const ID_PREFIX_RE = /^(pref|ret)-[A-Za-z0-9-]+$/;++/** Status transition entry shared by daily / weekly briefs. */+export interface PeriodStatusTransition {+ readonly at: string;+ readonly kind: "creation" | "promotion" | "retirement";+ readonly prefId: string;+ readonly link: string;+}++export interface PeriodVaultDelta {+ readonly newPromotions: number;+ readonly newRetired: number;+ readonly newFeedback: number;+ readonly evidenceApplied: number;+ readonly evidenceViolated: number;+}++/** Count events by their `kind` slot, returning a partial record. */+export function countByKind(+ events: ReadonlyArray<TemporalEvent>,+): Partial<Record<BrainLogEventKind, number>> {+ const out: Partial<Record<BrainLogEventKind, number>> = {};+ for (const ev of events) {+ out[ev.kind] = (out[ev.kind] ?? 0) + 1;+ }+ return out;+}++/**+ * Walk dream summary events in `events`, extract per-id transitions+ * from `new_unconfirmed` / `confirmed` / `retired` arrays, and return+ * them in chronological order.+ */+export function collectTransitions(+ events: ReadonlyArray<TemporalEvent>,+): PeriodStatusTransition[] {+ const out: PeriodStatusTransition[] = [];+ for (const ev of events) {+ if (ev.kind !== BRAIN_LOG_EVENT_KIND.dream) continue;+ const summary = ev.dreamSummary;+ if (summary === undefined) continue;+ appendTransitions(ev.at, summary.newUnconfirmed, "creation", out);+ appendTransitions(ev.at, summary.confirmed, "promotion", out);+ appendTransitions(ev.at, summary.retired, "retirement", out);+ }+ out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));+ return out;+}++function appendTransitions(+ at: string,+ links: ReadonlyArray<string> | undefined,+ kind: PeriodStatusTransition["kind"],+ out: PeriodStatusTransition[],+): void {+ if (links === undefined) return;+ for (const link of links) {+ const id = extractId(link);+ if (id === undefined) continue;+ out.push(Object.freeze({ at, kind, prefId: id, link }));+ }+}++/** Derive per-window counters from event list + already-computed transitions. */+export function computeVaultDelta(+ events: ReadonlyArray<TemporalEvent>,+ transitions: ReadonlyArray<PeriodStatusTransition>,+): PeriodVaultDelta {+ let newPromotions = 0;+ let newRetired = 0;+ for (const t of transitions) {+ if (t.kind === "promotion") newPromotions++;+ if (t.kind === "retirement") newRetired++;+ }+ let newFeedback = 0;+ let evidenceApplied = 0;+ let evidenceViolated = 0;+ for (const ev of events) {+ if (ev.kind === BRAIN_LOG_EVENT_KIND.feedback) newFeedback++;+ if (ev.kind === BRAIN_LOG_EVENT_KIND.applyEvidence) {+ if (ev.result === BRAIN_APPLY_RESULT.applied) evidenceApplied++;+ if (ev.result === BRAIN_APPLY_RESULT.violated) evidenceViolated++;+ }+ }+ return {+ newPromotions,+ newRetired,+ newFeedback,+ evidenceApplied,+ evidenceViolated,+ };+}++/** Deduplicated list of artifact wikilinks cited by apply-evidence rows. */+export function collectSourcePointers(+ events: ReadonlyArray<TemporalEvent>,+): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const ev of events) {+ if (ev.kind !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;+ if (ev.artifact === undefined) continue;+ if (seen.has(ev.artifact)) continue;+ seen.add(ev.artifact);+ out.push(ev.artifact);+ }+ return out;+}++/**+ * Pull a pref / ret id out of a wikilink body that may carry an alias+ * and / or a trailing `(reason)` decoration. Returns `undefined` when+ * the body doesn't look like a documented id.+ */+export function extractId(linkOrId: string): string | undefined {+ const stripped = linkOrId.replace(LINK_REASON_RE, "").trim();+ const target = parseWikilink(stripped) ?? stripped;+ return ID_PREFIX_RE.test(target) ? target : undefined;+}diff --git a/src/core/brain/temporal/select-events.ts b/src/core/brain/temporal/select-events.tsnew file mode 100644index 00000000..d7308a12--- /dev/null+++ b/src/core/brain/temporal/select-events.ts@@ -0,0 +1,73 @@+/**+ * `selectEvents(index, filters)` - pure projection over a frozen+ * {@link TimelineIndex}.+ *+ * Returns a frozen subset of the index's events filtered by the AND+ * of all supplied predicates. Empty filter object returns the whole+ * event list (still frozen).+ *+ * No disk reads; no state. Order is preserved from the index (which+ * sorts ascending by `at`, ties broken by `source`).+ */++import type { BrainLogEventKind } from "./../types.ts";+import type { TemporalEvent, TimelineIndex } from "./types.ts";++/** Filter set accepted by {@link selectEvents}. */+export interface SelectEventsFilters {+ /** Restrict to events with this preference / retired / signal id. */+ readonly prefId?: string;+ /** Restrict to events with this topic slug. */+ readonly topic?: string;+ /** Restrict to events of this kind. */+ readonly kind?: BrainLogEventKind;+ /** Inclusive lower bound (ISO-8601 UTC). */+ readonly since?: string;+ /** Exclusive upper bound (ISO-8601 UTC). */+ readonly until?: string;+}++export function selectEvents(+ index: TimelineIndex,+ filters: SelectEventsFilters,+): ReadonlyArray<TemporalEvent> {+ // Pick the narrowest pre-grouped bucket the filter set permits to+ // avoid scanning the full event list when the caller has already+ // committed to a kind / prefId / topic.+ const source =+ pickNarrowSource(index, filters) ?? index.events;+ const out: TemporalEvent[] = [];+ for (const ev of source) {+ if (!matchesFilters(ev, filters)) continue;+ out.push(ev);+ }+ return Object.freeze(out);+}++function pickNarrowSource(+ index: TimelineIndex,+ filters: SelectEventsFilters,+): ReadonlyArray<TemporalEvent> | undefined {+ if (filters.prefId !== undefined) {+ return index.eventsByPrefId.get(filters.prefId) ?? Object.freeze([]);+ }+ if (filters.topic !== undefined) {+ return index.eventsByTopic.get(filters.topic) ?? Object.freeze([]);+ }+ if (filters.kind !== undefined) {+ return index.eventsByKind.get(filters.kind) ?? Object.freeze([]);+ }+ return undefined;+}++function matchesFilters(+ ev: TemporalEvent,+ filters: SelectEventsFilters,+): boolean {+ if (filters.prefId !== undefined && ev.prefId !== filters.prefId) return false;+ if (filters.topic !== undefined && ev.topic !== filters.topic) return false;+ if (filters.kind !== undefined && ev.kind !== filters.kind) return false;+ if (filters.since !== undefined && ev.at < filters.since) return false;+ if (filters.until !== undefined && ev.at >= filters.until) return false;+ return true;+}diff --git a/src/core/brain/temporal/stale-watch.ts b/src/core/brain/temporal/stale-watch.tsnew file mode 100644index 00000000..78d16ece--- /dev/null+++ b/src/core/brain/temporal/stale-watch.ts@@ -0,0 +1,208 @@+/**+ * `findStaleEntries(index, vault, cfg, opts)` - reports preferences,+ * signals, and log files that have been idle past their configured+ * threshold.+ *+ * The TimelineIndex contributes the most-recent event timestamp per+ * preference - that's the canonical staleness anchor (more accurate+ * than `last_evidence_at` on disk, which lags behind the dream pass).+ * Falls back to the file's own `last_evidence_at` / `created_at` when+ * no event is on the timeline.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`,+ * Task 5 in `plan.md`.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { join, relative } from "node:path";++import { brainDirs } from "./../paths.ts";+import { parsePreference } from "./../preference.ts";+import { parseSignal } from "./../signal.ts";+import type { ResolvedBrainTemporalConfig } from "./../types.ts";+import type { TimelineIndex } from "./types.ts";++const ONE_DAY_MS = 24 * 60 * 60 * 1000;++export interface FindStaleEntriesOptions {+ /** Wall clock; defaults to `new Date()`. */+ readonly now?: Date;+}++export interface StalePreferenceRow {+ readonly prefId: string;+ readonly topic: string;+ readonly path: string;+ /** ISO timestamp of the most-recent event used as the staleness anchor. */+ readonly lastSeenAt: string;+ /** Whole days between `lastSeenAt` and `now`. */+ readonly ageDays: number;+}++export interface StaleSignalRow {+ readonly signalId: string;+ readonly topic: string;+ readonly path: string;+ readonly lastSeenAt: string;+ readonly ageDays: number;+}++export interface StaleLogFileRow {+ readonly path: string;+ readonly mtime: string;+ readonly ageDays: number;+}++export interface StaleWatchEnvelope {+ readonly stalePreferences: ReadonlyArray<StalePreferenceRow>;+ readonly staleSignals: ReadonlyArray<StaleSignalRow>;+ readonly staleLogFiles: ReadonlyArray<StaleLogFileRow>;+ readonly thresholds: ResolvedBrainTemporalConfig;+ readonly generatedAt: string;+}++export function findStaleEntries(+ index: TimelineIndex,+ vault: string,+ cfg: ResolvedBrainTemporalConfig,+ opts: FindStaleEntriesOptions = {},+): StaleWatchEnvelope {+ const now = opts.now ?? new Date();+ const generatedAt = now.toISOString();+ const nowMs = now.getTime();+ return Object.freeze({+ stalePreferences: Object.freeze(+ scanPreferences(index, vault, cfg.stale_pref_days, nowMs),+ ),+ staleSignals: Object.freeze(+ scanSignals(vault, cfg.stale_signal_days, nowMs),+ ),+ staleLogFiles: Object.freeze(+ scanLogFiles(vault, cfg.stale_log_days, nowMs),+ ),+ thresholds: cfg,+ generatedAt,+ });+}++function scanPreferences(+ index: TimelineIndex,+ vault: string,+ thresholdDays: number,+ nowMs: number,+): StalePreferenceRow[] {+ const out: StalePreferenceRow[] = [];+ const dirs = brainDirs(vault);+ if (!existsSync(dirs.preferences)) return out;+ for (const entry of readdirSync(dirs.preferences, { withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith("pref-")) continue;+ const path = join(dirs.preferences, entry.name);+ let pref;+ try {+ pref = parsePreference(path);+ } catch {+ continue;+ }+ const lastSeenAt = mostRecentEventAt(index, pref.id) ??+ pref.last_evidence_at ?? pref.created_at;+ const ageDays = computeAgeDays(lastSeenAt, nowMs);+ if (ageDays === undefined) continue;+ if (ageDays < thresholdDays) continue;+ out.push(+ Object.freeze({+ prefId: pref.id,+ topic: pref.topic,+ path: relative(vault, path),+ lastSeenAt,+ ageDays,+ }),+ );+ }+ out.sort((a, b) => b.ageDays - a.ageDays);+ return out;+}++function scanSignals(+ vault: string,+ thresholdDays: number,+ nowMs: number,+): StaleSignalRow[] {+ const out: StaleSignalRow[] = [];+ const dirs = brainDirs(vault);+ if (!existsSync(dirs.inbox)) return out;+ for (const entry of readdirSync(dirs.inbox, { withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith("sig-")) continue;+ const path = join(dirs.inbox, entry.name);+ let signal;+ try {+ signal = parseSignal(path);+ } catch {+ continue;+ }+ const ageDays = computeAgeDays(signal.created_at, nowMs);+ if (ageDays === undefined) continue;+ if (ageDays < thresholdDays) continue;+ out.push(+ Object.freeze({+ signalId: signal.id,+ topic: signal.topic,+ path: relative(vault, path),+ lastSeenAt: signal.created_at,+ ageDays,+ }),+ );+ }+ out.sort((a, b) => b.ageDays - a.ageDays);+ return out;+}++function scanLogFiles(+ vault: string,+ thresholdDays: number,+ nowMs: number,+): StaleLogFileRow[] {+ const out: StaleLogFileRow[] = [];+ const dirs = brainDirs(vault);+ if (!existsSync(dirs.log)) return out;+ for (const entry of readdirSync(dirs.log, { withFileTypes: true })) {+ if (!entry.isFile()) continue;+ if (!entry.name.endsWith(".jsonl") && !entry.name.endsWith(".md")) continue;+ const path = join(dirs.log, entry.name);+ const st = statSync(path);+ const mtimeMs = st.mtimeMs;+ const ageDays = Math.floor((nowMs - mtimeMs) / ONE_DAY_MS);+ if (ageDays < thresholdDays) continue;+ out.push(+ Object.freeze({+ path: relative(vault, path),+ mtime: new Date(mtimeMs).toISOString(),+ ageDays,+ }),+ );+ }+ out.sort((a, b) => b.ageDays - a.ageDays);+ return out;+}++function mostRecentEventAt(+ index: TimelineIndex,+ prefId: string,+): string | undefined {+ const events = index.eventsByPrefId.get(prefId);+ if (events === undefined || events.length === 0) return undefined;+ // events is sorted ascending; last element is most recent.+ return events[events.length - 1]!.at;+}++/**+ * Compute whole-day age between an anchor timestamp and `now`.+ * Returns `undefined` when the anchor is unparseable so the caller+ * can skip the row instead of emitting a `NaN` `ageDays`.+ */+function computeAgeDays(anchorIso: string, nowMs: number): number | undefined {+ const ms = Date.parse(anchorIso);+ if (!Number.isFinite(ms)) return undefined;+ return Math.floor((nowMs - ms) / ONE_DAY_MS);+}diff --git a/src/core/brain/temporal/types.ts b/src/core/brain/temporal/types.tsnew file mode 100644index 00000000..9519823d--- /dev/null+++ b/src/core/brain/temporal/types.ts@@ -0,0 +1,128 @@+/**+ * Temporal subsystem atoms (v0.10.18).+ *+ * Defines the data shapes the temporal/synthesis subsystem materializes+ * once per invocation. Every projection helper (`selectEvents`,+ * `buildBeliefEvolution`, `findStaleEntries`, `buildDailyBrief`,+ * `buildWeeklySynthesis`) consumes `TimelineIndex`; the index itself+ * is built once from disk by `buildTimelineIndex`.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`.+ */++import type {+ BrainApplyResult,+ BrainLogEventKind,+ BrainPreferenceStatus,+} from "../types.ts";++/**+ * Vault-relative location an event was sourced from. The reader keeps+ * the path + line number when known so the timeline carries an audit+ * pointer back to the originating row. Markdown-fallback rows from+ * `parseLogDay` set `line` to `null` because the markdown parser does+ * not track per-event line offsets.+ */+export interface TemporalEventSource {+ readonly path: string;+ readonly line: number | null;+}++/**+ * Denormalised slice of the `dream` summary event body that downstream+ * consumers (belief-evolution) need to attribute per-preference status+ * transitions without re-touching disk. Populated only on events of+ * kind `dream`. Each array carries the original wikilink strings (e.g.+ * `[[pref-foo|Principle]]` or `[[ret-foo|Principle]] (reason)`) so+ * consumers can resolve the prefId and any inline reason themselves.+ */+export interface DreamSummarySlots {+ readonly newUnconfirmed?: ReadonlyArray<string>;+ readonly confirmed?: ReadonlyArray<string>;+ readonly retired?: ReadonlyArray<string>;+}++/**+ * One normalized chronological event. Flat shape - optional slots are+ * populated when the source row carries the corresponding field. The+ * `kind` slot reuses the existing `BrainLogEventKind` enum verbatim so+ * downstream consumers can switch on a single discriminator without a+ * new vocabulary table.+ */+export interface TemporalEvent {+ /**+ * Canonical UTC ISO-8601 timestamp. Sub-second precision preserved+ * when the source row carried it. Always Z-suffixed.+ */+ readonly at: string;+ /** Event kind enum from `BRAIN_LOG_EVENT_KIND`. */+ readonly kind: BrainLogEventKind;+ /** Source row pointer for audit. */+ readonly source: TemporalEventSource;+ /** Preference id when the event scopes to one. */+ readonly prefId?: string;+ /** Topic slug when the event scopes to one. */+ readonly topic?: string;+ /** `apply-evidence` payload `result`. */+ readonly result?: BrainApplyResult;+ /** Artifact wikilink the evidence event references. */+ readonly artifact?: string;+ /** Status transition source (for `promote` / `retire` / `force-confirmed` / `reject`). */+ readonly transitionFrom?: BrainPreferenceStatus;+ /** Status transition target. */+ readonly transitionTo?: BrainPreferenceStatus;+ /** Free-form reason (retire reason, suppression reason, etc.). */+ readonly reason?: string;+ /** Narrative text for `note` events. */+ readonly text?: string;+ /** Bi-temporal: event-time start (from frontmatter `valid_from`). */+ readonly validFrom?: string;+ /** Bi-temporal: event-time end (from frontmatter `valid_until`). */+ readonly validUntil?: string;+ /** Bi-temporal: transaction-time (frontmatter `recorded_at`). */+ readonly recordedAt?: string;+ /**+ * Populated only when `kind === "dream"`. Carries the array payload+ * slices (`new_unconfirmed`, `confirmed`, `retired`) required by+ * belief-evolution to derive per-preference status transitions.+ */+ readonly dreamSummary?: DreamSummarySlots;+}++/** Window that produced a {@link TimelineIndex}. */+export interface TimelineWindow {+ /** Inclusive lower bound, canonical UTC ISO. */+ readonly since: string;+ /** Exclusive upper bound, canonical UTC ISO. */+ readonly until: string;+}++/**+ * Frozen materialized view of all events in a requested window. Every+ * projection helper takes a `TimelineIndex` and never re-touches disk+ * so the five helpers (timeline-reader, belief-evolution, stale-watch,+ * daily-brief, weekly-brief) observe one canonical window semantics.+ *+ * Groups use `ReadonlyMap` so key lookups stay strongly typed+ * (`BrainLogEventKind` for `eventsByKind`, free-form ids for+ * `eventsByPrefId` / `eventsByTopic`) without runtime key shape+ * gymnastics or escape hatches.+ */+export interface TimelineIndex {+ /**+ * Chronological list of events. Sorted by `at` ascending; ties+ * broken by `source.path` then `source.line` for determinism.+ */+ readonly events: ReadonlyArray<TemporalEvent>;+ /** Events grouped by `kind`. */+ readonly eventsByKind: ReadonlyMap<+ BrainLogEventKind,+ ReadonlyArray<TemporalEvent>+ >;+ /** Events grouped by `prefId` (only events that carry one). */+ readonly eventsByPrefId: ReadonlyMap<string, ReadonlyArray<TemporalEvent>>;+ /** Events grouped by `topic` (only events that carry one). */+ readonly eventsByTopic: ReadonlyMap<string, ReadonlyArray<TemporalEvent>>;+ /** Window the index was materialized for. */+ readonly window: TimelineWindow;+}diff --git a/src/core/brain/temporal/weekly-brief.ts b/src/core/brain/temporal/weekly-brief.tsnew file mode 100644index 00000000..27a20afe--- /dev/null+++ b/src/core/brain/temporal/weekly-brief.ts@@ -0,0 +1,150 @@+/**+ * `buildWeeklySynthesis(index, vault, weekEnd, cfg, opts?)` - 7-day+ * deterministic summary used by the weekly-synthesis surface.+ *+ * Shape mirrors `buildDailyBrief` but the window is 7 days back from+ * `weekEnd` (ISO date). On top of the daily envelope the weekly+ * synthesis adds:+ *+ * - `retired`: list of retire transitions inside the window.+ * - `contradictions`: combined list of `signal-suppressed` events+ * plus `apply-evidence` events where the payload `result` is+ * `"violated"`. Both surfaces signal a clash between the agent's+ * stated rule and the underlying activity.+ *+ * Design anchor: `docs/brainstorm/temporal-synthesis/design.md`,+ * Task 7 in `plan.md`.+ */++import { isoSecond } from "./../time.ts";+import type {+ BrainLogEventKind,+ ResolvedBrainTemporalConfig,+} from "./../types.ts";+import { BRAIN_LOG_EVENT_KIND } from "./../types.ts";+import { selectEvents } from "./select-events.ts";+import {+ collectSourcePointers,+ collectTransitions,+ computeVaultDelta,+ countByKind,+ type PeriodStatusTransition,+ type PeriodVaultDelta,+} from "./period-common.ts";+import type { TemporalEvent, TimelineIndex } from "./types.ts";++const ONE_DAY_MS = 24 * 60 * 60 * 1000;++export interface WeeklyContradiction {+ readonly at: string;+ readonly kind: "signal-suppressed" | "evidence-violated";+ readonly prefId?: string;+ readonly topic?: string;+ readonly reason?: string;+ readonly artifact?: string;+}++export interface WeeklyRetirement {+ readonly at: string;+ readonly prefId: string;+ readonly link: string;+}++export interface WeeklySynthesisEnvelope {+ readonly windowStart: string;+ readonly windowEnd: string;+ readonly eventsByKind: Readonly<Partial<Record<BrainLogEventKind, number>>>;+ readonly statusTransitions: ReadonlyArray<PeriodStatusTransition>;+ readonly retired: ReadonlyArray<WeeklyRetirement>;+ readonly contradictions: ReadonlyArray<WeeklyContradiction>;+ readonly vaultDelta: PeriodVaultDelta;+ readonly sourcePointers: ReadonlyArray<string>;+ readonly generatedAt: string;+}++export interface BuildWeeklySynthesisOptions {+ /** Wall clock for `generatedAt`; defaults to `new Date()`. */+ readonly now?: Date;+}++export function buildWeeklySynthesis(+ index: TimelineIndex,+ _vault: string,+ weekEnd: string,+ _cfg: ResolvedBrainTemporalConfig,+ opts: BuildWeeklySynthesisOptions = {},+): WeeklySynthesisEnvelope {+ // `_vault` / `_cfg` are part of the helper signature for parity+ // with sibling projections and forward compatibility (weekday-+ // alignment overrides will read `_cfg.weekly_start_dow` in a+ // future release); the brief itself is a pure projection over the+ // index and does not re-touch disk.+ const windowEndMs = Date.parse(`${weekEnd}T00:00:00Z`);+ if (!Number.isFinite(windowEndMs)) {+ throw new Error(+ `buildWeeklySynthesis: invalid weekEnd ${JSON.stringify(weekEnd)}`,+ );+ }+ const windowStartMs = windowEndMs - 7 * ONE_DAY_MS;+ const windowStart = isoSecond(new Date(windowStartMs));+ const windowEndIso = isoSecond(new Date(windowEndMs));+ const generatedAt = (opts.now ?? new Date()).toISOString();++ const events = selectEvents(index, {+ since: windowStart,+ until: windowEndIso,+ });++ const transitions = collectTransitions(events);+ const vaultDelta = computeVaultDelta(events, transitions);+ const retired = transitions+ .filter((t) => t.kind === "retirement")+ .map((t) =>+ Object.freeze({ at: t.at, prefId: t.prefId, link: t.link }),+ );+ const contradictions = collectContradictions(events);++ return Object.freeze({+ windowStart,+ windowEnd: windowEndIso,+ eventsByKind: Object.freeze(countByKind(events)),+ statusTransitions: Object.freeze(transitions),+ retired: Object.freeze(retired),+ contradictions: Object.freeze(contradictions),+ vaultDelta: Object.freeze(vaultDelta),+ sourcePointers: Object.freeze(collectSourcePointers(events)),+ generatedAt,+ });+}++function collectContradictions(+ events: ReadonlyArray<TemporalEvent>,+): WeeklyContradiction[] {+ const out: WeeklyContradiction[] = [];+ for (const ev of events) {+ if (ev.kind === BRAIN_LOG_EVENT_KIND.signalSuppressed) {+ out.push(makeContradiction("signal-suppressed", ev));+ } else if (+ ev.kind === BRAIN_LOG_EVENT_KIND.applyEvidence &&+ ev.result === "violated"+ ) {+ out.push(makeContradiction("evidence-violated", ev));+ }+ }+ out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));+ return out;+}++function makeContradiction(+ kind: WeeklyContradiction["kind"],+ ev: TemporalEvent,+): WeeklyContradiction {+ return Object.freeze({+ at: ev.at,+ kind,+ ...(ev.prefId !== undefined ? { prefId: ev.prefId } : {}),+ ...(ev.topic !== undefined ? { topic: ev.topic } : {}),+ ...(ev.reason !== undefined ? { reason: ev.reason } : {}),+ ...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),+ });+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex c805d791..91afaaa2 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -210,6 +210,16 @@ export const BRAIN_LOG_EVENT_KIND_SET: ReadonlySet<string> = new Set(Object.values(BRAIN_LOG_EVENT_KIND),);+/**+ * Type guard narrowing an arbitrary string to {@link BrainLogEventKind}.+ * Use at boundary checks (CLI flag parsing, MCP input coercion, JSONL+ * deserialisation) so the typed-string union flows through downstream+ * code without a runtime `as` cast.+ */+export function isBrainLogEventKind(value: string): value is BrainLogEventKind {+ return BRAIN_LOG_EVENT_KIND_SET.has(value);+}+// ----- File-frontmatter shapes ----------------------------------------------/**@@ -266,6 +276,12 @@ export interface BrainSignal {* `<path>#<turn-id>`. Empty / absent for inline / live signals.*/readonly session_ref?: string;+ /** Bi-temporal event-time start (additive optional, v0.10.18). */+ readonly valid_from?: string;+ /** Bi-temporal event-time end (additive optional, v0.10.18). */+ readonly valid_until?: string;+ /** Bi-temporal transaction-time (additive optional, v0.10.18). */+ readonly recorded_at?: string;}/**@@ -324,6 +340,24 @@ export interface BrainPreference {/** Optional wikilink to a retired pref this one replaces. */readonly supersedes?: string;readonly aliases?: ReadonlyArray<string>;+ /**+ * Bi-temporal: event-time start. ISO-8601 UTC timestamp marking+ * when the rule was first considered true (independent of when the+ * vault learned about it). Additive optional - absent on legacy+ * files; readers must tolerate `undefined`.+ */+ readonly valid_from?: string;+ /**+ * Bi-temporal: event-time end. ISO-8601 UTC timestamp marking when+ * the rule stopped being considered true. Additive optional.+ */+ readonly valid_until?: string;+ /**+ * Bi-temporal: transaction-time. ISO-8601 UTC timestamp marking+ * when the vault recorded the rule (distinct from `created_at`,+ * which is the dream-pass promotion moment). Additive optional.+ */+ readonly recorded_at?: string;}/**@@ -373,6 +407,12 @@ export interface BrainRetired {* retires.*/readonly user_rejected_reason?: string | null;+ /** Bi-temporal event-time start (additive optional, v0.10.18). */+ readonly valid_from?: string;+ /** Bi-temporal event-time end (additive optional, v0.10.18). */+ readonly valid_until?: string;+ /** Bi-temporal transaction-time (additive optional, v0.10.18). */+ readonly recorded_at?: string;}/**@@ -777,6 +817,14 @@ export interface BrainConfig {* `BRAIN_LINK_GRAPH_DEFAULTS` via `resolveLinkGraph`.*/readonly link_graph?: BrainLinkGraphConfig;+ /**+ * Optional `temporal:` block (v0.10.18). Drives the temporal ++ * synthesis subsystem (`src/core/brain/temporal/`) - stale-watch+ * thresholds, weekly window alignment, daily window offset.+ * Absent: callers fall back to `BRAIN_TEMPORAL_DEFAULTS` via+ * `resolveTemporal`.+ */+ readonly temporal?: BrainTemporalConfig;}/**@@ -827,3 +875,53 @@ export interface ResolvedBrainLinkGraphConfig {readonly moc_min_link_ratio: number;readonly vault_instruction_file: string;}++/**+ * Optional `temporal:` block (v0.10.18). Tunes the temporal ++ * synthesis subsystem (`src/core/brain/temporal/`).+ *+ * All knobs are purely structural - thresholds in days and ISO-8601+ * weekday numbers. No language-specific defaults; no vocabulary+ * detection.+ */+export interface BrainTemporalConfig {+ /**+ * Days since a preference's most-recent event before it is reported+ * by `findStaleEntries`. Positive integer.+ */+ readonly stale_pref_days?: number;+ /**+ * Days since a signal's most-recent event before it is reported as+ * stale. Positive integer.+ */+ readonly stale_signal_days?: number;+ /**+ * Days since a Brain/log/ file was last touched before it is+ * reported as stale. Positive integer.+ */+ readonly stale_log_days?: number;+ /**+ * Weekly-synthesis window alignment. ISO-8601 weekday number+ * (1 = Monday ... 7 = Sunday). Default 1.+ */+ readonly weekly_start_dow?: number;+ /**+ * Daily-brief window offset from UTC in whole hours, range -23..23.+ * 0 means days align with UTC midnight. Non-zero values let+ * non-UTC vaults align daily briefs with local midnight without+ * adding a full timezone library.+ */+ readonly daily_window_offset_hours?: number;+}++/**+ * Concrete (fully-resolved) temporal config. Returned by+ * `resolveTemporal(cfg)` so consumers do not branch on optionals.+ */+export interface ResolvedBrainTemporalConfig {+ readonly stale_pref_days: number;+ readonly stale_signal_days: number;+ readonly stale_log_days: number;+ readonly weekly_start_dow: number;+ readonly daily_window_offset_hours: number;+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 79c9151b..4eae4949 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -57,6 +57,17 @@ import { findUnlinkedMentions } from "../core/brain/link-graph/unlinked-mentionsimport { buildConceptCluster } from "../core/brain/link-graph/concept-cluster.ts";import { auditMoc, MocAuditError } from "../core/brain/link-graph/moc-audit.ts";import { readVaultInstructionFile } from "../core/brain/vault-instruction-file.ts";+import { buildTimelineIndex } from "../core/brain/temporal/build-index.ts";+import { selectEvents } from "../core/brain/temporal/select-events.ts";+import { buildBeliefEvolution } from "../core/brain/temporal/belief-evolution.ts";+import { findStaleEntries } from "../core/brain/temporal/stale-watch.ts";+import { buildDailyBrief } from "../core/brain/temporal/daily-brief.ts";+import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";+import { loadTemporalConfigSafe } from "../core/brain/policy.ts";+import {+ isBrainLogEventKind,+ type BrainLogEventKind,+} from "../core/brain/types.ts";import { packContext } from "../core/brain/context-pack.ts";import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";@@ -1035,6 +1046,265 @@ async function toolBrainMocAudit(}}+// ----- Temporal subsystem MCP wrappers (v0.10.18) --------------------------++function coercePositiveInteger(+ tool: string,+ field: string,+ raw: unknown,+): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === "number") {+ if (!Number.isInteger(raw) || raw < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );+ }+ return raw;+ }+ if (typeof raw === "string") {+ const trimmed = raw.trim();+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );+ }+ const parsed = Number.parseInt(trimmed, 10);+ if (parsed < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );+ }+ return parsed;+ }+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );+}++const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++function coerceIsoTimestampOrDate(+ tool: string,+ field: string,+ raw: unknown,+ shape: "date-only" | "date-or-timestamp" = "date-or-timestamp",+): string | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "string" || raw.trim().length === 0) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be an ISO date${shape === "date-or-timestamp" ? " or ISO timestamp" : " (YYYY-MM-DD)"}`,+ );+ }+ const v = raw.trim();+ if (shape === "date-only" && !ISO_DATE_ONLY_RE.test(v)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be an ISO date (YYYY-MM-DD); got ${JSON.stringify(v)}`,+ );+ }+ // Validate by parsing - rejects "2026-13-99" / "garbage" / etc.+ const ms = Date.parse(v);+ if (!Number.isFinite(ms)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a parseable ISO date${shape === "date-or-timestamp" ? " or timestamp" : ""}; got ${JSON.stringify(v)}`,+ );+ }+ return v;+}++function coerceEventKind(+ tool: string,+ raw: unknown,+): BrainLogEventKind | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "string") {+ throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);+ }+ if (!isBrainLogEventKind(raw)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: kind must be a known BrainLogEventKind`,+ );+ }+ return raw;+}++/**+ * `brain_timeline` - frozen chronological list of events filtered by+ * any combination of `pref_id`, `topic`, `kind`, `since`, `until`,+ * `limit`. Pure read.+ */+async function toolBrainTimeline(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const prefId = typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;+ const topic = typeof args["topic"] === "string" ? args["topic"] : undefined;+ const kind = coerceEventKind("brain_timeline", args["kind"]);+ const since = coerceIsoTimestampOrDate("brain_timeline", "since", args["since"]);+ const until = coerceIsoTimestampOrDate("brain_timeline", "until", args["until"]);+ const limit = coercePositiveInteger("brain_timeline", "limit", args["limit"]);++ const index = buildTimelineIndex(ctx.vault, {+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ const events = selectEvents(index, {+ ...(prefId !== undefined ? { prefId } : {}),+ ...(topic !== undefined ? { topic } : {}),+ ...(kind !== undefined ? { kind } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ const sliced = limit !== undefined ? events.slice(0, limit) : events;+ return {+ vault_path: ctx.vault,+ window: index.window,+ total: events.length,+ events: sliced.map((ev) => ({+ at: ev.at,+ kind: ev.kind,+ source: ev.source,+ ...(ev.prefId !== undefined ? { pref_id: ev.prefId } : {}),+ ...(ev.topic !== undefined ? { topic: ev.topic } : {}),+ ...(ev.result !== undefined ? { result: ev.result } : {}),+ ...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),+ ...(ev.reason !== undefined ? { reason: ev.reason } : {}),+ ...(ev.text !== undefined ? { text: ev.text } : {}),+ })),+ };+}++/**+ * `brain_belief_evolution` - per-pref / per-topic chronological story:+ * status transitions, evidence rollup with running counts, and+ * retirement chain.+ */+async function toolBrainBeliefEvolution(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const prefIdRaw = args["pref_id"];+ const topicRaw = args["topic"];+ const hasPref = typeof prefIdRaw === "string" && prefIdRaw.trim().length > 0;+ const hasTopic = typeof topicRaw === "string" && topicRaw.trim().length > 0;+ if (hasPref === hasTopic) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_belief_evolution: exactly one of pref_id or topic is required",+ );+ }+ const target = hasPref+ ? { prefId: (prefIdRaw as string).trim() }+ : { topic: (topicRaw as string).trim() };+ const index = buildTimelineIndex(ctx.vault, {});+ const evo = buildBeliefEvolution(index, ctx.vault, target);+ return {+ vault_path: ctx.vault,+ target: evo.target,+ transitions: evo.transitions,+ evidence: evo.evidence,+ retirements: evo.retirements,+ generated_at: evo.generatedAt,+ };+}++/**+ * `brain_stale_scan` - structural staleness report for preferences,+ * signals, and log files. Thresholds come from the `temporal:` config+ * block.+ */+async function toolBrainStaleScan(+ ctx: ServerContext,+ _args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ void _args;+ const cfg = loadTemporalConfigSafe(ctx.vault);+ const index = buildTimelineIndex(ctx.vault, {});+ const report = findStaleEntries(index, ctx.vault, cfg);+ return {+ vault_path: ctx.vault,+ thresholds: report.thresholds,+ stale_preferences: report.stalePreferences,+ stale_signals: report.staleSignals,+ stale_log_files: report.staleLogFiles,+ generated_at: report.generatedAt,+ };+}++/**+ * `brain_daily_brief` - structured counters + transitions + source+ * pointers for one day. Defaults `date` to today UTC when omitted.+ */+async function toolBrainDailyBrief(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const dateRaw = args["date"];+ const dateCoerced = coerceIsoTimestampOrDate(+ "brain_daily_brief",+ "date",+ dateRaw,+ "date-only",+ );+ const date = dateCoerced ?? new Date().toISOString().slice(0, 10);+ const cfg = loadTemporalConfigSafe(ctx.vault);+ const index = buildTimelineIndex(ctx.vault, {});+ const brief = buildDailyBrief(index, ctx.vault, date, {+ offsetHours: cfg.daily_window_offset_hours,+ });+ return {+ vault_path: ctx.vault,+ date: brief.date,+ window: brief.window,+ events_by_kind: brief.eventsByKind,+ status_transitions: brief.statusTransitions,+ vault_delta: brief.vaultDelta,+ source_pointers: brief.sourcePointers,+ generated_at: brief.generatedAt,+ };+}++/**+ * `brain_weekly_synthesis` - 7-day deterministic summary plus retired+ * and contradictions lists.+ */+async function toolBrainWeeklySynthesis(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const weekEndRaw = args["week_end"];+ const weekEndCoerced = coerceIsoTimestampOrDate(+ "brain_weekly_synthesis",+ "week_end",+ weekEndRaw,+ "date-only",+ );+ const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);+ const cfg = loadTemporalConfigSafe(ctx.vault);+ const index = buildTimelineIndex(ctx.vault, {});+ const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);+ return {+ vault_path: ctx.vault,+ window_start: synth.windowStart,+ window_end: synth.windowEnd,+ events_by_kind: synth.eventsByKind,+ status_transitions: synth.statusTransitions,+ retired: synth.retired,+ contradictions: synth.contradictions,+ vault_delta: synth.vaultDelta,+ source_pointers: synth.sourcePointers,+ generated_at: synth.generatedAt,+ };+}+// ----- brain_context_pack (v0.10.15) ---------------------------------------/**@@ -1421,6 +1691,115 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainMocAudit,},+ {+ name: "brain_timeline",+ description:+ "Chronological list of Brain events filtered by any combination of pref_id, topic, kind, since, until, limit. Returns the canonical TimelineIndex projection. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ pref_id: {+ type: "string",+ description:+ "Restrict to events for this preference / retired / signal id.",+ },+ topic: {+ type: "string",+ description: "Restrict to events for this topic slug.",+ },+ kind: {+ type: "string",+ description:+ "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",+ },+ since: {+ type: "string",+ description:+ "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",+ },+ until: {+ type: "string",+ description:+ "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ description:+ "Maximum number of events to return after filtering. Omit for no cap.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainTimeline,+ },+ {+ name: "brain_belief_evolution",+ description:+ "Per-preference or per-topic chronological story: status transitions (creation/promotion/retirement) derived from dream summaries, evidence rollup with running counts, and retirement chain. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ pref_id: {+ type: "string",+ description:+ "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",+ },+ topic: {+ type: "string",+ description:+ "Target topic slug. Aggregates every pref-* / ret-* sharing the topic. Mutually exclusive with `pref_id`.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainBeliefEvolution,+ },+ {+ name: "brain_stale_scan",+ description:+ "Structural staleness report: preferences, signals, and Brain/log files inactive longer than the configured `temporal:` thresholds (stale_pref_days / stale_signal_days / stale_log_days). Read-only.",+ inputSchema: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },+ handler: toolBrainStaleScan,+ },+ {+ name: "brain_daily_brief",+ description:+ "Deterministic daily brief: events grouped by kind, status transitions, vault delta (newPromotions / newRetired / newFeedback / evidenceApplied / evidenceViolated), and deduplicated artifact wikilinks. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ date: {+ type: "string",+ description:+ "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainDailyBrief,+ },+ {+ name: "brain_weekly_synthesis",+ description:+ "Deterministic 7-day synthesis: events grouped by kind, status transitions, retired-in-window list, contradictions (signal-suppressed + apply-evidence violated), vault delta, and source pointers. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ week_end: {+ type: "string",+ description:+ "ISO date (`YYYY-MM-DD`) the 7-day window ends at (exclusive). Defaults to today UTC.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainWeeklySynthesis,+ },{name: "brain_operator_summary",description:diff --git a/tests/cli/brain-temporal-cli.test.ts b/tests/cli/brain-temporal-cli.test.tsnew file mode 100644index 00000000..42387f04--- /dev/null+++ b/tests/cli/brain-temporal-cli.test.ts@@ -0,0 +1,158 @@+/**+ * Task 9: CLI smoke tests for the five new temporal verbs.+ *+ * Asserts: each verb exits 0 with `--json` flag on a populated vault,+ * and that bad inputs surface as non-zero exit codes.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonl(+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-temporal-cli-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");++ writeJsonl("2026-05-20", [+ {+ timestamp: "2026-05-20T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|Rule]]",+ artifact: "[[src/a.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);++ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-temporal-cli-cfg-"));+ configPath = join(configHome, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++describe("o2b brain timeline", () => {+ test("--json on populated vault exits 0 with events array", async () => {+ const r = await runCli(["brain", "timeline", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(Array.isArray(payload.events)).toBe(true);+ });++ test("--limit -3 surfaces as exit 1", async () => {+ const r = await runCli(+ ["brain", "timeline", "--limit", "-3", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(1);+ });+});++describe("o2b brain evolution", () => {+ test("--pref-id --json exits 0", async () => {+ const r = await runCli(+ ["brain", "evolution", "--pref-id", "pref-foo", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.target).toEqual({ prefId: "pref-foo" });+ });++ test("missing --pref-id and --topic exits non-zero", async () => {+ const r = await runCli(["brain", "evolution", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(1);+ });++ test("both --pref-id and --topic exits non-zero", async () => {+ const r = await runCli(+ [+ "brain",+ "evolution",+ "--pref-id",+ "pref-foo",+ "--topic",+ "foo",+ "--json",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(1);+ });+});++describe("o2b brain stale", () => {+ test("--json exits 0 with thresholds + arrays", async () => {+ const r = await runCli(["brain", "stale", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.thresholds).toBeDefined();+ expect(Array.isArray(payload.stalePreferences)).toBe(true);+ });+});++describe("o2b brain daily", () => {+ test("--date --json exits 0", async () => {+ const r = await runCli(+ ["brain", "daily", "--date", "2026-05-20", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.date).toBe("2026-05-20");+ });+});++describe("o2b brain weekly", () => {+ test("--week-end --json exits 0", async () => {+ const r = await runCli(+ ["brain", "weekly", "--week-end", "2026-05-25", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.windowEnd).toBe("2026-05-25T00:00:00Z");+ });+});diff --git a/tests/core/brain/temporal/belief-evolution.test.ts b/tests/core/brain/temporal/belief-evolution.test.tsnew file mode 100644index 00000000..25366205--- /dev/null+++ b/tests/core/brain/temporal/belief-evolution.test.ts@@ -0,0 +1,225 @@+/**+ * Task 4: `buildBeliefEvolution(index, vault, target)`.+ *+ * Walks dream summary events for the target preference id appearing in+ * `new_unconfirmed` / `confirmed` / `retired` arrays, plus+ * apply-evidence events for the same id, plus retired/ files in the+ * chain. Returns the frozen envelope.+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { buildBeliefEvolution } from "../../../../src/core/brain/temporal/belief-evolution.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-belief-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(dir, "Brain", "retired"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonl(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++let VAULT: string;+beforeEach(() => {+ VAULT = makeVault();+});++describe("buildBeliefEvolution by prefId", () => {+ test("empty index - empty envelope, no throw", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });+ expect(evo.target).toEqual({ prefId: "pref-foo" });+ expect(evo.transitions.length).toBe(0);+ expect(evo.evidence.length).toBe(0);+ expect(evo.retirements.length).toBe(0);+ expect(Object.isFrozen(evo)).toBe(true);+ });++ test("creation - promotion - retirement transitions in order", () => {+ writeJsonl(VAULT, "2026-05-01", [+ {+ timestamp: "2026-05-01T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r1",+ new_unconfirmed: ["[[pref-foo|First rule]]"],+ },+ },+ ]);+ writeJsonl(VAULT, "2026-05-10", [+ {+ timestamp: "2026-05-10T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r2",+ confirmed: ["[[pref-foo|First rule]]"],+ },+ },+ ]);+ writeJsonl(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r3",+ retired: ["[[ret-foo|First rule]] (stale-no-evidence)"],+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });+ expect(evo.transitions.map((t) => t.kind)).toEqual([+ "creation",+ "promotion",+ "retirement",+ ]);+ expect(evo.transitions[0]!.at).toBe("2026-05-01T08:00:00Z");+ expect(evo.transitions[2]!.at).toBe("2026-05-20T08:00:00Z");+ });++ test("evidence rollup carries running counts", () => {+ writeJsonl(VAULT, "2026-05-12", [+ {+ timestamp: "2026-05-12T08:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First rule]]",+ artifact: "[[a.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-12T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First rule]]",+ artifact: "[[b.ts]]",+ agent: "claude",+ result: "violated",+ },+ },+ {+ timestamp: "2026-05-12T12:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First rule]]",+ artifact: "[[c.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });+ expect(evo.evidence.length).toBe(3);+ expect(evo.evidence[0]!.runningApplied).toBe(1);+ expect(evo.evidence[0]!.runningViolated).toBe(0);+ expect(evo.evidence[1]!.runningApplied).toBe(1);+ expect(evo.evidence[1]!.runningViolated).toBe(1);+ expect(evo.evidence[2]!.runningApplied).toBe(2);+ });++ test("retirements pick up ret-* file metadata with supersededBy chain", () => {+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-foo.md"),+ `---\nid: ret-foo\nkind: brain-retired\nstatus: retired\nretired_at: 2026-05-20T08:00:00Z\nretired_reason: superseded\nretired_by: "[[dream-r3]]"\ncreated_at: 2026-04-01T00:00:00Z\ntags: ["brain"]\ntopic: foo\nprinciple: First rule\nevidenced_by: []\nconfidence: medium\nsuperseded_by: "[[pref-foo-v2|First rule v2]]"\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });+ // ret-foo descends from pref-foo and is the retirement target.+ expect(evo.retirements.length).toBe(1);+ expect(evo.retirements[0]!.prefId).toBe("ret-foo");+ expect(evo.retirements[0]!.retiredAt).toBe("2026-05-20T08:00:00Z");+ expect(evo.retirements[0]!.supersededBy).toBe("pref-foo-v2");+ });++ test("retirement chain cycle does not infinite-loop (visited-set guard)", () => {+ // ret-a.supersedes -> ret-b; ret-b.supersedes -> ret-a (cycle).+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-a.md"),+ `---\nid: ret-a\nkind: brain-retired\nstatus: retired\nretired_at: 2026-05-20T08:00:00Z\nretired_reason: superseded\nretired_by: "[[dream-r]]"\ncreated_at: 2026-04-01T00:00:00Z\ntags: ["brain"]\ntopic: cycle\nprinciple: A\nevidenced_by: []\nconfidence: medium\nsupersedes: "[[ret-b]]"\n---\n`,+ );+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-b.md"),+ `---\nid: ret-b\nkind: brain-retired\nstatus: retired\nretired_at: 2026-05-19T08:00:00Z\nretired_reason: superseded\nretired_by: "[[dream-r]]"\ncreated_at: 2026-04-01T00:00:00Z\ntags: ["brain"]\ntopic: cycle\nprinciple: B\nevidenced_by: []\nconfidence: medium\nsupersedes: "[[ret-a]]"\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ // Should terminate (no hang) and surface both records exactly+ // once even though the supersedes-chain loops.+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-a" });+ expect(evo.retirements.length).toBe(2);+ const ids = evo.retirements.map((r) => r.prefId).sort();+ expect(ids).toEqual(["ret-a", "ret-b"]);+ });++ test("envelope is frozen, transitions/evidence arrays frozen", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });+ expect(Object.isFrozen(evo)).toBe(true);+ expect(Object.isFrozen(evo.transitions)).toBe(true);+ expect(Object.isFrozen(evo.evidence)).toBe(true);+ expect(Object.isFrozen(evo.retirements)).toBe(true);+ });+});++describe("buildBeliefEvolution by topic", () => {+ test("aggregates events for every pref-* / ret-* sharing the topic", () => {+ writeJsonl(VAULT, "2026-05-05", [+ {+ timestamp: "2026-05-05T08:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-05-foo]]",+ topic: "foo",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ writeJsonl(VAULT, "2026-05-12", [+ {+ timestamp: "2026-05-12T08:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First rule]]",+ artifact: "[[a.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+ writeFileSync(+ join(VAULT, "Brain", "preferences", "pref-foo.md"),+ `---\nid: pref-foo\nkind: brain-preference\nstatus: confirmed\ncreated_at: 2026-05-01T00:00:00Z\nunconfirmed_until: 2026-05-15T00:00:00Z\ntags: ["brain"]\ntopic: foo\nprinciple: First rule\nevidenced_by: []\nconfidence: medium\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const evo = buildBeliefEvolution(idx, VAULT, { topic: "foo" });+ expect(evo.target).toEqual({ topic: "foo" });+ // Evidence is per pref-foo and we count it under the topic too.+ expect(evo.evidence.length).toBe(1);+ });+});diff --git a/tests/core/brain/temporal/bi-temporal-atoms.test.ts b/tests/core/brain/temporal/bi-temporal-atoms.test.tsnew file mode 100644index 00000000..1f660074--- /dev/null+++ b/tests/core/brain/temporal/bi-temporal-atoms.test.ts@@ -0,0 +1,228 @@+/**+ * Task 1: Temporal atoms + config block.+ *+ * Asserts the atom layer of `src/core/brain/temporal/`:+ * - `BRAIN_TEMPORAL_DEFAULTS` exposes the five documented slots.+ * - `resolveTemporal(cfg)` returns a fully-populated struct.+ * - The `temporal:` config block parses, validates, and supplies+ * forward-compat warnings for unknown sub-keys.+ * - `TemporalEvent` and `TimelineIndex` are exported from the+ * subsystem entry point.+ */++import { describe, expect, test } from "bun:test";++import {+ BrainConfigError,+ parseBrainYaml,+ validateBrainConfigDetailed,+} from "../../../../src/core/brain/policy.ts";+import {+ BRAIN_TEMPORAL_DEFAULTS,+ resolveTemporal,+} from "../../../../src/core/brain/policy.ts";+import type {+ TemporalEvent,+ TimelineIndex,+} from "../../../../src/core/brain/temporal/types.ts";++function validate(yaml: string) {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");+}++const HEAD = `schema_version: 1\n`;++describe("BRAIN_TEMPORAL_DEFAULTS", () => {+ test("documents the five threshold defaults", () => {+ expect(BRAIN_TEMPORAL_DEFAULTS.stale_pref_days).toBe(90);+ expect(BRAIN_TEMPORAL_DEFAULTS.stale_signal_days).toBe(30);+ expect(BRAIN_TEMPORAL_DEFAULTS.stale_log_days).toBe(180);+ expect(BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow).toBe(1);+ expect(BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours).toBe(0);+ });++ test("is frozen", () => {+ expect(Object.isFrozen(BRAIN_TEMPORAL_DEFAULTS)).toBe(true);+ });+});++describe("temporal config block", () => {+ test("absent block - cfg.temporal undefined; resolveTemporal returns defaults", () => {+ const { config } = validate(HEAD);+ expect(config.temporal).toBeUndefined();+ expect(resolveTemporal(config)).toEqual(BRAIN_TEMPORAL_DEFAULTS);+ });++ test("present with all five fields - loaded fully", () => {+ const { config } = validate(+ HEAD ++ `temporal:\n` ++ ` stale_pref_days: 45\n` ++ ` stale_signal_days: 14\n` ++ ` stale_log_days: 365\n` ++ ` weekly_start_dow: 7\n` ++ ` daily_window_offset_hours: -3\n`,+ );+ expect(config.temporal).toEqual({+ stale_pref_days: 45,+ stale_signal_days: 14,+ stale_log_days: 365,+ weekly_start_dow: 7,+ daily_window_offset_hours: -3,+ });+ expect(resolveTemporal(config).weekly_start_dow).toBe(7);+ });++ test("partial block - missing fields fall back to defaults", () => {+ const { config } = validate(+ HEAD + `temporal:\n stale_pref_days: 60\n`,+ );+ expect(config.temporal?.stale_pref_days).toBe(60);+ const resolved = resolveTemporal(config);+ expect(resolved.stale_pref_days).toBe(60);+ expect(resolved.stale_signal_days).toBe(+ BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,+ );+ expect(resolved.weekly_start_dow).toBe(+ BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,+ );+ });++ test("stale_pref_days: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n stale_pref_days: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("stale_pref_days: negative rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n stale_pref_days: -1\n`),+ ).toThrow(BrainConfigError);+ });++ test("stale_pref_days: non-integer rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n stale_pref_days: 2.5\n`),+ ).toThrow(BrainConfigError);+ });++ test("stale_signal_days: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n stale_signal_days: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("stale_log_days: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n stale_log_days: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("weekly_start_dow: 0 rejected (must be 1..7 ISO-8601)", () => {+ expect(() =>+ validate(HEAD + `temporal:\n weekly_start_dow: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("weekly_start_dow: 8 rejected (must be 1..7 ISO-8601)", () => {+ expect(() =>+ validate(HEAD + `temporal:\n weekly_start_dow: 8\n`),+ ).toThrow(BrainConfigError);+ });++ test("weekly_start_dow: non-integer rejected", () => {+ expect(() =>+ validate(HEAD + `temporal:\n weekly_start_dow: 3.5\n`),+ ).toThrow(BrainConfigError);+ });++ test("daily_window_offset_hours: -23 accepted (lower bound)", () => {+ const { config } = validate(+ HEAD + `temporal:\n daily_window_offset_hours: -23\n`,+ );+ expect(config.temporal?.daily_window_offset_hours).toBe(-23);+ });++ test("daily_window_offset_hours: 23 accepted (upper bound)", () => {+ const { config } = validate(+ HEAD + `temporal:\n daily_window_offset_hours: 23\n`,+ );+ expect(config.temporal?.daily_window_offset_hours).toBe(23);+ });++ test("daily_window_offset_hours: -24 rejected (out of range)", () => {+ expect(() =>+ validate(HEAD + `temporal:\n daily_window_offset_hours: -24\n`),+ ).toThrow(BrainConfigError);+ });++ test("daily_window_offset_hours: 24 rejected (out of range)", () => {+ expect(() =>+ validate(HEAD + `temporal:\n daily_window_offset_hours: 24\n`),+ ).toThrow(BrainConfigError);+ });++ test("non-object temporal block rejected", () => {+ expect(() => validate(HEAD + `temporal: "nope"\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("unknown sub-key warns but does not throw", () => {+ const { config, warnings } = validate(+ HEAD ++ `temporal:\n stale_pref_days: 90\n unknown_slot: 7\n`,+ );+ expect(config.temporal?.stale_pref_days).toBe(90);+ expect(+ warnings.some((w) =>+ w.message.includes("temporal.unknown_slot"),+ ),+ ).toBe(true);+ });+});++describe("TemporalEvent + TimelineIndex shapes", () => {+ test("TemporalEvent type is exported with the expected slot set", () => {+ // Compile-time check via assignment. The shape must accept the+ // documented superset of optional slots without TS errors.+ const ev: TemporalEvent = Object.freeze({+ at: "2026-05-25T10:00:00Z",+ kind: "feedback",+ source: Object.freeze({+ path: "Brain/log/2026-05-25.jsonl",+ line: 1,+ }),+ prefId: "pref-foo",+ topic: "foo",+ result: "applied",+ artifact: "src/cli/main.ts",+ transitionFrom: "unconfirmed",+ transitionTo: "confirmed",+ reason: "promoted by dream",+ text: "release shipped",+ validFrom: "2026-05-01T00:00:00Z",+ validUntil: "2026-06-01T00:00:00Z",+ recordedAt: "2026-05-25T10:00:00Z",+ });+ expect(ev.kind).toBe("feedback");+ expect(Object.isFrozen(ev)).toBe(true);+ });++ test("TimelineIndex type is exported with the expected slot set", () => {+ const idx: TimelineIndex = Object.freeze({+ events: Object.freeze([] as ReadonlyArray<TemporalEvent>),+ eventsByKind: new Map(),+ eventsByPrefId: new Map(),+ eventsByTopic: new Map(),+ window: Object.freeze({+ since: "1970-01-01T00:00:00Z",+ until: "2026-05-25T23:59:59Z",+ }),+ });+ expect(idx.events.length).toBe(0);+ expect(idx.eventsByKind.size).toBe(0);+ expect(idx.window.since).toBe("1970-01-01T00:00:00Z");+ expect(Object.isFrozen(idx)).toBe(true);+ });+});diff --git a/tests/core/brain/temporal/build-index.test.ts b/tests/core/brain/temporal/build-index.test.tsnew file mode 100644index 00000000..5da78e73--- /dev/null+++ b/tests/core/brain/temporal/build-index.test.ts@@ -0,0 +1,291 @@+/**+ * Task 2: `buildTimelineIndex(vault, opts)`.+ *+ * The index builder scans Brain/log/<date>.jsonl (via the public+ * `readLogDay` reader) for every date file in the requested window,+ * normalizes every log entry to a `TemporalEvent`, and returns a+ * frozen `TimelineIndex` grouped by kind / prefId / topic.+ *+ * Assertions:+ * - empty vault returns a frozen empty envelope.+ * - all events come back in chronological order, with deterministic+ * ties broken by source-path + line.+ * - window inputs accept ISO date and full ISO timestamp; `since`+ * is inclusive, `until` is exclusive.+ * - `prefId` / `topic` / `result` / `artifact` slots come out+ * populated where the source body carries them.+ * - kind groups, prefId groups, topic groups stay in chronological+ * order within each bucket.+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-idx-"));+ mkdirSync(join(dir, "Brain"), { recursive: true });+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(dir, "Brain", "retired"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonlDay(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++let VAULT: string;+beforeEach(() => {+ VAULT = makeVault();+});++describe("buildTimelineIndex", () => {+ test("empty vault returns frozen empty envelope", () => {+ const idx = buildTimelineIndex(VAULT, {+ since: "2026-05-01T00:00:00Z",+ until: "2026-05-25T00:00:00Z",+ });+ expect(idx.events.length).toBe(0);+ expect(idx.eventsByKind.size).toBe(0);+ expect(idx.eventsByPrefId.size).toBe(0);+ expect(idx.eventsByTopic.size).toBe(0);+ expect(idx.window.since).toBe("2026-05-01T00:00:00Z");+ expect(idx.window.until).toBe("2026-05-25T00:00:00Z");+ expect(Object.isFrozen(idx)).toBe(true);+ });++ test("apply-evidence row populates prefId, topic-less, result, artifact", () => {+ writeJsonlDay(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|Principle title]]",+ artifact: "[[src/cli/main.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ expect(idx.events.length).toBe(1);+ const ev = idx.events[0]!;+ expect(ev.kind).toBe("apply-evidence");+ expect(ev.at).toBe("2026-05-20T10:00:00Z");+ expect(ev.prefId).toBe("pref-foo");+ expect(ev.result).toBe("applied");+ expect(ev.artifact).toContain("src/cli/main.ts");+ expect(idx.eventsByKind.get("apply-evidence")?.length).toBe(1);+ expect(idx.eventsByPrefId.get("pref-foo")?.length).toBe(1);+ });++ test("feedback row populates topic + signal prefId", () => {+ writeJsonlDay(VAULT, "2026-05-21", [+ {+ timestamp: "2026-05-21T09:30:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-21-bar]]",+ topic: "bar",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ expect(idx.events.length).toBe(1);+ const ev = idx.events[0]!;+ expect(ev.kind).toBe("feedback");+ expect(ev.topic).toBe("bar");+ // signal wikilink is the feedback event's lifecycle anchor.+ expect(ev.prefId).toBe("sig-2026-05-21-bar");+ expect(idx.eventsByTopic.get("bar")?.length).toBe(1);+ });++ test("note row populates text and no prefId", () => {+ writeJsonlDay(VAULT, "2026-05-22", [+ {+ timestamp: "2026-05-22T12:00:00Z",+ kind: "note",+ body: {+ text: "Release v0.10.18 shipped",+ agent: "claude",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ expect(idx.events.length).toBe(1);+ const ev = idx.events[0]!;+ expect(ev.kind).toBe("note");+ expect(ev.text).toBe("Release v0.10.18 shipped");+ expect(ev.prefId).toBeUndefined();+ });++ test("signal-suppressed row populates topic + prefId from signal wikilink + reason", () => {+ writeJsonlDay(VAULT, "2026-05-23", [+ {+ timestamp: "2026-05-23T08:00:00Z",+ kind: "signal-suppressed",+ body: {+ signal: "[[sig-2026-05-23-foo]]",+ retired: "[[ret-foo]]",+ topic: "foo",+ reason: "rejected by operator",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const ev = idx.events[0]!;+ expect(ev.kind).toBe("signal-suppressed");+ expect(ev.topic).toBe("foo");+ expect(ev.reason).toBe("rejected by operator");+ // signal-suppressed gets its prefId from the retired wikilink (ret-*).+ expect(ev.prefId).toBe("ret-foo");+ });++ test("multiple days combine with chronological ordering across files", () => {+ writeJsonlDay(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T15:00:00Z",+ kind: "note",+ body: { text: "afternoon-20", agent: "claude" },+ },+ ]);+ writeJsonlDay(VAULT, "2026-05-21", [+ {+ timestamp: "2026-05-21T08:00:00Z",+ kind: "note",+ body: { text: "morning-21", agent: "claude" },+ },+ ]);+ writeJsonlDay(VAULT, "2026-05-19", [+ {+ timestamp: "2026-05-19T12:00:00Z",+ kind: "note",+ body: { text: "noon-19", agent: "claude" },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ expect(idx.events.map((e) => e.text)).toEqual([+ "noon-19",+ "afternoon-20",+ "morning-21",+ ]);+ });++ test("window since/until: inclusive lower, exclusive upper", () => {+ writeJsonlDay(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T00:00:00Z",+ kind: "note",+ body: { text: "lower-boundary", agent: "claude" },+ },+ {+ timestamp: "2026-05-20T12:00:00Z",+ kind: "note",+ body: { text: "inside", agent: "claude" },+ },+ {+ timestamp: "2026-05-21T00:00:00Z",+ kind: "note",+ body: { text: "upper-boundary", agent: "claude" },+ },+ ]);+ writeJsonlDay(VAULT, "2026-05-21", [+ {+ timestamp: "2026-05-21T00:00:00Z",+ kind: "note",+ body: { text: "upper-boundary", agent: "claude" },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {+ since: "2026-05-20T00:00:00Z",+ until: "2026-05-21T00:00:00Z",+ });+ // lower-boundary included, upper-boundary excluded.+ expect(idx.events.map((e) => e.text)).toEqual([+ "lower-boundary",+ "inside",+ ]);+ });++ test("window since/until accept bare ISO date (interpreted as T00:00:00Z)", () => {+ writeJsonlDay(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T11:00:00Z",+ kind: "note",+ body: { text: "inside-day", agent: "claude" },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {+ since: "2026-05-20",+ until: "2026-05-21",+ });+ expect(idx.events.length).toBe(1);+ expect(idx.events[0]!.text).toBe("inside-day");+ });++ test("groups by prefId and topic are in chronological order", () => {+ writeJsonlDay(VAULT, "2026-05-25", [+ {+ timestamp: "2026-05-25T08:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|first]]",+ artifact: "[[a]]",+ agent: "c",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-25T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|second]]",+ artifact: "[[b]]",+ agent: "c",+ result: "violated",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const fooEvents = idx.eventsByPrefId.get("pref-foo");+ expect(fooEvents?.length).toBe(2);+ expect(fooEvents?.[0]!.at).toBe("2026-05-25T08:00:00Z");+ expect(fooEvents?.[1]!.at).toBe("2026-05-25T10:00:00Z");+ });++ test("retired/ frontmatter contributes ret-* events at retired_at", () => {+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-baz.md"),+ `---\nid: ret-baz\nprinciple: Do not bar\ntopic: baz\nretired_at: 2026-05-15T09:00:00Z\nreason: superseded\nstatus: retired\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const baz = idx.eventsByPrefId.get("ret-baz");+ expect(baz?.length).toBe(1);+ const ev = baz![0]!;+ expect(ev.kind).toBe("retire");+ expect(ev.topic).toBe("baz");+ expect(ev.reason).toBe("superseded");+ expect(ev.at).toBe("2026-05-15T09:00:00Z");+ });+});diff --git a/tests/core/brain/temporal/daily-brief.test.ts b/tests/core/brain/temporal/daily-brief.test.tsnew file mode 100644index 00000000..321428a9--- /dev/null+++ b/tests/core/brain/temporal/daily-brief.test.ts@@ -0,0 +1,240 @@+/**+ * Task 6: `buildDailyBrief(index, vault, date)`.+ *+ * Returns a frozen deterministic envelope:+ * - eventsByKind: count per BrainLogEventKind for the day+ * - statusTransitions: list of pref-id status changes in the day+ * - vaultDelta: newPromotions, newRetired, newFeedback, evidenceApplied, evidenceViolated counters+ * - sourcePointers: deduplicated list of artifact wikilinks cited by evidence events+ * - generatedAt+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { buildDailyBrief } from "../../../../src/core/brain/temporal/daily-brief.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-daily-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonl(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++let VAULT: string;+beforeEach(() => {+ VAULT = makeVault();+});++describe("buildDailyBrief", () => {+ test("empty day - frozen empty-counts envelope", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildDailyBrief(idx, VAULT, "2026-05-25");+ expect(brief.date).toBe("2026-05-25");+ expect(brief.vaultDelta.newPromotions).toBe(0);+ expect(brief.vaultDelta.newRetired).toBe(0);+ expect(brief.vaultDelta.newFeedback).toBe(0);+ expect(brief.vaultDelta.evidenceApplied).toBe(0);+ expect(brief.vaultDelta.evidenceViolated).toBe(0);+ expect(brief.statusTransitions.length).toBe(0);+ expect(brief.sourcePointers.length).toBe(0);+ expect(Object.isFrozen(brief)).toBe(true);+ });++ test("counts events by kind and computes vaultDelta", () => {+ writeJsonl(VAULT, "2026-05-25", [+ {+ timestamp: "2026-05-25T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r1",+ confirmed: ["[[pref-foo|First]]"],+ retired: ["[[ret-baz|Old]] (stale-no-evidence)"],+ },+ },+ {+ timestamp: "2026-05-25T09:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-25-foo]]",+ topic: "foo",+ sign: "positive",+ agent: "claude",+ },+ },+ {+ timestamp: "2026-05-25T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First]]",+ artifact: "[[src/cli/main.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-25T11:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First]]",+ artifact: "[[src/cli/other.ts]]",+ agent: "claude",+ result: "violated",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildDailyBrief(idx, VAULT, "2026-05-25");+ expect(brief.eventsByKind.dream).toBe(1);+ expect(brief.eventsByKind.feedback).toBe(1);+ expect(brief.eventsByKind["apply-evidence"]).toBe(2);+ expect(brief.vaultDelta.newPromotions).toBe(1);+ expect(brief.vaultDelta.newRetired).toBe(1);+ expect(brief.vaultDelta.newFeedback).toBe(1);+ expect(brief.vaultDelta.evidenceApplied).toBe(1);+ expect(brief.vaultDelta.evidenceViolated).toBe(1);+ });++ test("statusTransitions list contains promotion + retirement entries", () => {+ writeJsonl(VAULT, "2026-05-25", [+ {+ timestamp: "2026-05-25T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r1",+ new_unconfirmed: ["[[pref-new|Newly minted]]"],+ confirmed: ["[[pref-foo|First]]"],+ retired: ["[[ret-baz|Old]] (stale)"],+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildDailyBrief(idx, VAULT, "2026-05-25");+ expect(brief.statusTransitions.length).toBe(3);+ const kinds = brief.statusTransitions.map((t) => t.kind).sort();+ expect(kinds).toEqual(["creation", "promotion", "retirement"]);+ });++ test("sourcePointers deduplicates artifact wikilinks from evidence", () => {+ writeJsonl(VAULT, "2026-05-25", [+ {+ timestamp: "2026-05-25T08:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-a|A]]",+ artifact: "[[src/x.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-25T09:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-b|B]]",+ artifact: "[[src/x.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-25T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-c|C]]",+ artifact: "[[src/y.ts]]",+ agent: "claude",+ result: "violated",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildDailyBrief(idx, VAULT, "2026-05-25");+ expect(brief.sourcePointers.length).toBe(2);+ expect(brief.sourcePointers).toContain("src/x.ts");+ expect(brief.sourcePointers).toContain("src/y.ts");+ });++ test("midnight-boundary event at since is included, at until is excluded", () => {+ writeJsonl(VAULT, "2026-05-25", [+ {+ timestamp: "2026-05-25T00:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-25-edge-since]]",+ topic: "edge",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ writeJsonl(VAULT, "2026-05-26", [+ {+ timestamp: "2026-05-26T00:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-26-edge-until]]",+ topic: "edge",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {+ since: "2026-05-01T00:00:00Z",+ until: "2026-06-01T00:00:00Z",+ });+ const brief = buildDailyBrief(idx, VAULT, "2026-05-25");+ // since=2026-05-25T00:00:00Z (inclusive) -> event at exact since+ // is counted. until=2026-05-26T00:00:00Z (exclusive) -> event at+ // exact until is NOT counted.+ expect(brief.vaultDelta.newFeedback).toBe(1);+ });++ test("daily window respects daily_window_offset_hours config", () => {+ // Event at 03:30 UTC on May 26 falls into the May 26 brief by+ // default (offset 0 = UTC days). The index needs an explicit+ // `until` past the event timestamp because the wall clock during+ // test runs may sit anywhere in real time.+ writeJsonl(VAULT, "2026-05-26", [+ {+ timestamp: "2026-05-26T03:30:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-26-edge]]",+ topic: "edge",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {+ since: "2026-05-01T00:00:00Z",+ until: "2026-06-01T00:00:00Z",+ });+ const brief = buildDailyBrief(idx, VAULT, "2026-05-26");+ expect(brief.vaultDelta.newFeedback).toBe(1);+ });+});diff --git a/tests/core/brain/temporal/select-events.test.ts b/tests/core/brain/temporal/select-events.test.tsnew file mode 100644index 00000000..501a404d--- /dev/null+++ b/tests/core/brain/temporal/select-events.test.ts@@ -0,0 +1,189 @@+/**+ * Task 3: `selectEvents(index, filters)` pure projection.+ *+ * Asserts that every supported filter (`prefId`, `topic`, `kind`,+ * `since`, `until`) narrows the index's events by the AND of all+ * predicates and that the result is frozen.+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { selectEvents } from "../../../../src/core/brain/temporal/select-events.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-select-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(dir, "Brain", "retired"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonlDay(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++let VAULT: string;+beforeEach(() => {+ VAULT = makeVault();+ writeJsonlDay(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T08:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-20-foo]]",+ topic: "foo",+ sign: "positive",+ agent: "claude",+ },+ },+ {+ timestamp: "2026-05-20T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|Principle]]",+ artifact: "[[src/cli/main.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ {+ timestamp: "2026-05-20T12:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-bar|Other]]",+ artifact: "[[src/cli/other.ts]]",+ agent: "claude",+ result: "violated",+ },+ },+ ]);+ writeJsonlDay(VAULT, "2026-05-21", [+ {+ timestamp: "2026-05-21T09:00:00Z",+ kind: "note",+ body: {+ text: "Release shipped",+ agent: "claude",+ },+ },+ {+ timestamp: "2026-05-21T11:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|Principle]]",+ artifact: "[[src/cli/again.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+});++describe("selectEvents", () => {+ test("no filter returns full event list frozen", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, {});+ expect(got.length).toBe(5);+ expect(Object.isFrozen(got)).toBe(true);+ });++ test("filter by prefId returns only events for that preference", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { prefId: "pref-foo" });+ expect(got.length).toBe(2);+ expect(got.every((e) => e.prefId === "pref-foo")).toBe(true);+ });++ test("filter by topic returns only events for that topic", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { topic: "foo" });+ expect(got.length).toBe(1);+ expect(got[0]!.kind).toBe("feedback");+ });++ test("filter by kind returns only events of that kind", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { kind: "apply-evidence" });+ expect(got.length).toBe(3);+ expect(got.every((e) => e.kind === "apply-evidence")).toBe(true);+ });++ test("filter by since narrows lower bound (inclusive)", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { since: "2026-05-21T00:00:00Z" });+ expect(got.length).toBe(2);+ expect(got[0]!.at).toBe("2026-05-21T09:00:00Z");+ });++ test("filter by until narrows upper bound (exclusive)", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { until: "2026-05-21T00:00:00Z" });+ expect(got.length).toBe(3);+ expect(got.every((e) => e.at < "2026-05-21T00:00:00Z")).toBe(true);+ });++ test("multiple filters combine with AND", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, {+ prefId: "pref-foo",+ kind: "apply-evidence",+ since: "2026-05-21T00:00:00Z",+ });+ expect(got.length).toBe(1);+ expect(got[0]!.at).toBe("2026-05-21T11:00:00Z");+ });++ test("filter with no matches returns empty frozen list", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { prefId: "pref-nonexistent" });+ expect(got.length).toBe(0);+ expect(Object.isFrozen(got)).toBe(true);+ });+});++describe("selectEvents bi-temporal frontmatter atoms", () => {+ test("retired event with valid_from/valid_until/recorded_at surfaces those slots", () => {+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-temporal.md"),+ `---\nid: ret-temporal\nprinciple: keep-fresh\ntopic: temporal\nretired_at: 2026-05-18T09:00:00Z\nreason: superseded\nstatus: retired\nvalid_from: 2026-01-01T00:00:00Z\nvalid_until: 2026-05-18T09:00:00Z\nrecorded_at: 2026-05-18T09:30:00Z\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { prefId: "ret-temporal" });+ expect(got.length).toBe(1);+ expect(got[0]!.validFrom).toBe("2026-01-01T00:00:00Z");+ expect(got[0]!.validUntil).toBe("2026-05-18T09:00:00Z");+ expect(got[0]!.recordedAt).toBe("2026-05-18T09:30:00Z");+ });++ test("retired event without the new slots leaves them undefined", () => {+ writeFileSync(+ join(VAULT, "Brain", "retired", "ret-legacy.md"),+ `---\nid: ret-legacy\nprinciple: old-rule\ntopic: legacy\nretired_at: 2026-05-19T09:00:00Z\nreason: stale-no-evidence\nstatus: retired\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const got = selectEvents(idx, { prefId: "ret-legacy" });+ expect(got.length).toBe(1);+ expect(got[0]!.validFrom).toBeUndefined();+ expect(got[0]!.validUntil).toBeUndefined();+ expect(got[0]!.recordedAt).toBeUndefined();+ });+});diff --git a/tests/core/brain/temporal/stale-watch.test.ts b/tests/core/brain/temporal/stale-watch.test.tsnew file mode 100644index 00000000..5e93230b--- /dev/null+++ b/tests/core/brain/temporal/stale-watch.test.ts@@ -0,0 +1,128 @@+/**+ * Task 5: `findStaleEntries(index, vault, cfg)`.+ *+ * Pure structural staleness: walks `Brain/preferences/`, `Brain/inbox/`,+ * and `Brain/log/` looking for entries older than the per-kind day+ * threshold. The TimelineIndex is consulted for the most-recent event+ * per preference so the staleness anchor is the last actually-observed+ * activity, not the file mtime.+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync, utimesSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { findStaleEntries } from "../../../../src/core/brain/temporal/stale-watch.ts";+import { BRAIN_TEMPORAL_DEFAULTS } from "../../../../src/core/brain/policy.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-stale-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(dir, "Brain", "inbox"), { recursive: true });+ return dir;+}++function writeFileMtime(path: string, content: string, mtimeIso: string): void {+ writeFileSync(path, content);+ const t = new Date(mtimeIso);+ utimesSync(path, t, t);+}++let VAULT: string;+const NOW = new Date("2026-05-25T00:00:00Z");+beforeEach(() => {+ VAULT = makeVault();+});++describe("findStaleEntries", () => {+ test("empty vault returns frozen empty envelope", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.stalePreferences.length).toBe(0);+ expect(out.staleSignals.length).toBe(0);+ expect(out.staleLogFiles.length).toBe(0);+ expect(Object.isFrozen(out)).toBe(true);+ });++ test("preference stale when last_evidence_at older than stale_pref_days", () => {+ writeFileSync(+ join(VAULT, "Brain", "preferences", "pref-fresh.md"),+ `---\nid: pref-fresh\nkind: brain-preference\nstatus: confirmed\ncreated_at: 2026-04-01T00:00:00Z\nunconfirmed_until: 2026-04-14T00:00:00Z\ntags: ["brain"]\ntopic: fresh\nprinciple: Fresh\nevidenced_by: []\nconfidence: medium\nlast_evidence_at: 2026-05-20T00:00:00Z\n---\n`,+ );+ writeFileSync(+ join(VAULT, "Brain", "preferences", "pref-stale.md"),+ `---\nid: pref-stale\nkind: brain-preference\nstatus: confirmed\ncreated_at: 2025-12-01T00:00:00Z\nunconfirmed_until: 2025-12-14T00:00:00Z\ntags: ["brain"]\ntopic: stale\nprinciple: Stale\nevidenced_by: []\nconfidence: medium\nlast_evidence_at: 2026-01-01T00:00:00Z\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.stalePreferences.length).toBe(1);+ expect(out.stalePreferences[0]!.prefId).toBe("pref-stale");+ expect(out.stalePreferences[0]!.lastSeenAt).toBe("2026-01-01T00:00:00Z");+ });++ test("preference without last_evidence_at uses created_at as staleness anchor", () => {+ writeFileSync(+ join(VAULT, "Brain", "preferences", "pref-old.md"),+ `---\nid: pref-old\nkind: brain-preference\nstatus: unconfirmed\ncreated_at: 2025-10-01T00:00:00Z\nunconfirmed_until: 2025-10-14T00:00:00Z\ntags: ["brain"]\ntopic: old\nprinciple: Old\nevidenced_by: []\nconfidence: low\nlast_evidence_at: null\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.stalePreferences.length).toBe(1);+ expect(out.stalePreferences[0]!.lastSeenAt).toBe("2025-10-01T00:00:00Z");+ });++ test("signal stale when created_at older than stale_signal_days", () => {+ writeFileSync(+ join(VAULT, "Brain", "inbox", "sig-2026-03-15-fresh.md"),+ `---\nid: sig-2026-03-15-fresh\nkind: brain-signal\ncreated_at: 2026-05-15T00:00:00Z\ntags: ["brain"]\ntopic: fresh\nsignal: positive\nagent: claude\nprinciple: Fresh rule\n---\n`,+ );+ writeFileSync(+ join(VAULT, "Brain", "inbox", "sig-2026-01-01-stale.md"),+ `---\nid: sig-2026-01-01-stale\nkind: brain-signal\ncreated_at: 2026-01-01T00:00:00Z\ntags: ["brain"]\ntopic: stale\nsignal: positive\nagent: claude\nprinciple: Stale rule\n---\n`,+ );+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.staleSignals.length).toBe(1);+ expect(out.staleSignals[0]!.signalId).toBe("sig-2026-01-01-stale");+ });++ test("log file stale when mtime older than stale_log_days", () => {+ writeFileMtime(+ join(VAULT, "Brain", "log", "2025-08-01.jsonl"),+ "",+ "2025-08-01T00:00:00Z",+ );+ writeFileMtime(+ join(VAULT, "Brain", "log", "2026-05-20.jsonl"),+ "",+ "2026-05-20T00:00:00Z",+ );+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.staleLogFiles.length).toBe(1);+ expect(out.staleLogFiles[0]!.path).toContain("2025-08-01.jsonl");+ });++ test("thresholds returned alongside results", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {+ now: NOW,+ });+ expect(out.thresholds.stale_pref_days).toBe(90);+ expect(out.thresholds.stale_signal_days).toBe(30);+ expect(out.thresholds.stale_log_days).toBe(180);+ });+});diff --git a/tests/core/brain/temporal/weekly-brief.test.ts b/tests/core/brain/temporal/weekly-brief.test.tsnew file mode 100644index 00000000..7a9b2346--- /dev/null+++ b/tests/core/brain/temporal/weekly-brief.test.ts@@ -0,0 +1,179 @@+/**+ * Task 7: `buildWeeklySynthesis(index, vault, weekEnd, cfg)`.+ *+ * Computes a 7-day window ending at the ISO date supplied, counts+ * events by kind, derives status transitions, retired-in-window list,+ * contradictions (`signal-suppressed` + `apply-evidence` where+ * `result === "violated"`), and the vault delta.+ */++import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { buildWeeklySynthesis } from "../../../../src/core/brain/temporal/weekly-brief.ts";+import { BRAIN_TEMPORAL_DEFAULTS } from "../../../../src/core/brain/policy.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-weekly-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonl(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++let VAULT: string;+beforeEach(() => {+ VAULT = makeVault();+});++describe("buildWeeklySynthesis", () => {+ test("empty window - frozen empty-counts envelope", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildWeeklySynthesis(+ idx,+ VAULT,+ "2026-05-25",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(brief.windowEnd).toBe("2026-05-25T00:00:00Z");+ expect(brief.retired.length).toBe(0);+ expect(brief.contradictions.length).toBe(0);+ expect(Object.isFrozen(brief)).toBe(true);+ });++ test("window covers exactly 7 days back from weekEnd", () => {+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildWeeklySynthesis(+ idx,+ VAULT,+ "2026-05-25",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(brief.windowEnd).toBe("2026-05-25T00:00:00Z");+ expect(brief.windowStart).toBe("2026-05-18T00:00:00Z");+ });++ test("contradictions list combines signal-suppressed + apply-evidence violated", () => {+ writeJsonl(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T08:00:00Z",+ kind: "signal-suppressed",+ body: {+ signal: "[[sig-2026-05-20-foo]]",+ retired: "[[ret-foo]]",+ topic: "foo",+ reason: "rejected",+ },+ },+ {+ timestamp: "2026-05-20T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First]]",+ artifact: "[[src/cli/main.ts]]",+ agent: "claude",+ result: "violated",+ },+ },+ {+ timestamp: "2026-05-20T12:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|First]]",+ artifact: "[[src/cli/other.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildWeeklySynthesis(+ idx,+ VAULT,+ "2026-05-25",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(brief.contradictions.length).toBe(2);+ // signal-suppressed contributes one; apply-evidence violated one.+ const kinds = brief.contradictions.map((c) => c.kind).sort();+ expect(kinds).toEqual(["evidence-violated", "signal-suppressed"]);+ });++ test("retired list collects retire transitions in window", () => {+ writeJsonl(VAULT, "2026-05-22", [+ {+ timestamp: "2026-05-22T08:00:00Z",+ kind: "dream",+ body: {+ run_id: "r1",+ retired: ["[[ret-foo|First]] (stale)"],+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildWeeklySynthesis(+ idx,+ VAULT,+ "2026-05-25",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(brief.retired.length).toBe(1);+ expect(brief.retired[0]!.prefId).toBe("ret-foo");+ });++ test("vaultDelta counters reflect 7-day window", () => {+ writeJsonl(VAULT, "2026-05-19", [+ {+ timestamp: "2026-05-19T08:00:00Z",+ kind: "feedback",+ body: {+ signal: "[[sig-2026-05-19-foo]]",+ topic: "foo",+ sign: "positive",+ agent: "claude",+ },+ },+ ]);+ writeJsonl(VAULT, "2026-05-22", [+ {+ timestamp: "2026-05-22T08:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|F]]",+ artifact: "[[a.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+ const idx = buildTimelineIndex(VAULT, {});+ const brief = buildWeeklySynthesis(+ idx,+ VAULT,+ "2026-05-25",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(brief.vaultDelta.newFeedback).toBe(1);+ expect(brief.vaultDelta.evidenceApplied).toBe(1);+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 4294ee21..0cc6eba8 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -160,7 +160,9 @@ describe("tool listing", () => {// brain_context_pack added in v0.10.15,// brain_operator_summary added in v0.10.16,// brain_unlinked_mentions / brain_concept_synthesis /- // brain_moc_audit added in v0.10.17).+ // brain_moc_audit added in v0.10.17,+ // brain_timeline / brain_belief_evolution / brain_stale_scan /+ // brain_daily_brief / brain_weekly_synthesis added in v0.10.18)."brain_feedback","brain_dream","brain_apply_evidence",@@ -174,6 +176,11 @@ describe("tool listing", () => {"brain_unlinked_mentions","brain_concept_synthesis","brain_moc_audit",+ "brain_timeline",+ "brain_belief_evolution",+ "brain_stale_scan",+ "brain_daily_brief",+ "brain_weekly_synthesis","brain_operator_summary",// Pay Memory (unchanged)."payment_memory_init",@@ -374,10 +381,11 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- // v0.10.17: 3 core + 14 Brain (brain_unlinked_mentions /- // brain_concept_synthesis / brain_moc_audit added v0.10.17)- // + 8 Pay Memory + 1 Search = 26.- expect(list.result.tools.length).toBe(26);+ // v0.10.18: 3 core + 19 Brain (brain_timeline /+ // brain_belief_evolution / brain_stale_scan / brain_daily_brief /+ // brain_weekly_synthesis added v0.10.18)+ // + 8 Pay Memory + 1 Search = 31.+ expect(list.result.tools.length).toBe(31);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/temporal-mcp-tools.test.ts b/tests/mcp/temporal-mcp-tools.test.tsnew file mode 100644index 00000000..ed1af494--- /dev/null+++ b/tests/mcp/temporal-mcp-tools.test.ts@@ -0,0 +1,211 @@+/**+ * Task 8: MCP wrappers for the temporal subsystem (v0.10.18).+ *+ * Asserts happy-path response shape for each of the five new tools+ * and one INVALID_PARAMS branch per tool.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { MCPServer } from "../../src/mcp/server.ts";+import { JSONRPC_VERSION, PROTOCOL_VERSION } from "../../src/mcp/protocol.ts";++function makeVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-mcp-"));+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(dir, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(dir, "Brain", "retired"), { recursive: true });+ return dir;+}++interface FixtureEvent {+ readonly timestamp: string;+ readonly kind: string;+ readonly body: Record<string, string | ReadonlyArray<string>>;+}++function writeJsonl(+ vault: string,+ date: string,+ events: ReadonlyArray<FixtureEvent>,+): void {+ const lines = events+ .map((e) =>+ JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),+ )+ .join("\n");+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");+}++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "temporal-mcp-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++interface ToolCallResponse {+ readonly result?: Record<string, unknown>;+ readonly errorCode?: number;+ readonly errorMessage?: string;+}++async function callTool(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<ToolCallResponse> {+ const raw = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name, arguments: args },+ })) as {+ result?: { content?: ReadonlyArray<{ type: string; text: string }> };+ error?: { code: number; message: string };+ } | null;+ if (raw === null) return {};+ if (raw.error !== undefined) {+ return { errorCode: raw.error.code, errorMessage: raw.error.message };+ }+ const text = raw.result?.content?.[0]?.text;+ if (typeof text !== "string") return {};+ return { result: JSON.parse(text) };+}++let VAULT: string;+afterEach(() => {+ if (VAULT) rmSync(VAULT, { recursive: true, force: true });+});+beforeEach(() => {+ VAULT = makeVault();+ writeJsonl(VAULT, "2026-05-20", [+ {+ timestamp: "2026-05-20T10:00:00Z",+ kind: "apply-evidence",+ body: {+ preference: "[[pref-foo|Rule]]",+ artifact: "[[src/a.ts]]",+ agent: "claude",+ result: "applied",+ },+ },+ ]);+});++describe("brain_timeline", () => {+ test("happy-path: returns events array + window", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_timeline", {});+ expect(Array.isArray(result?.events)).toBe(true);+ expect(result?.window).toBeDefined();+ });++ test("INVALID_PARAMS: unknown kind", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { errorCode } = await callTool(server, "brain_timeline", {+ kind: "made-up-kind",+ });+ expect(errorCode).toBeDefined();+ });++ test("INVALID_PARAMS: limit must be positive integer", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { errorCode } = await callTool(server, "brain_timeline", {+ limit: -1,+ });+ expect(errorCode).toBeDefined();+ });+});++describe("brain_belief_evolution", () => {+ test("happy-path: pref_id returns target + arrays", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_belief_evolution", {+ pref_id: "pref-foo",+ });+ expect(result?.target).toEqual({ prefId: "pref-foo" });+ expect(Array.isArray(result?.transitions)).toBe(true);+ expect(Array.isArray(result?.evidence)).toBe(true);+ expect(Array.isArray(result?.retirements)).toBe(true);+ });++ test("INVALID_PARAMS: missing both pref_id and topic", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { errorCode } = await callTool(server, "brain_belief_evolution", {});+ expect(errorCode).toBeDefined();+ });++ test("INVALID_PARAMS: both pref_id and topic", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { errorCode } = await callTool(server, "brain_belief_evolution", {+ pref_id: "pref-foo",+ topic: "foo",+ });+ expect(errorCode).toBeDefined();+ });+});++describe("brain_stale_scan", () => {+ test("happy-path: returns thresholds + arrays", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_stale_scan", {});+ expect(result?.thresholds).toBeDefined();+ expect(Array.isArray(result?.stale_preferences)).toBe(true);+ expect(Array.isArray(result?.stale_signals)).toBe(true);+ expect(Array.isArray(result?.stale_log_files)).toBe(true);+ });+});++describe("brain_daily_brief", () => {+ test("happy-path: returns date + counters envelope", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_daily_brief", {+ date: "2026-05-20",+ });+ expect(result?.date).toBe("2026-05-20");+ expect(result?.vault_delta).toBeDefined();+ });++ test("happy-path: missing date defaults to today UTC", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_daily_brief", {});+ expect(typeof result?.date).toBe("string");+ });+});++describe("brain_weekly_synthesis", () => {+ test("happy-path: returns window_start/window_end + arrays", async () => {+ const server = new MCPServer({ vault: VAULT });+ await initialize(server);+ const { result } = await callTool(server, "brain_weekly_synthesis", {+ week_end: "2026-05-25",+ });+ expect(result?.window_end).toBe("2026-05-25T00:00:00Z");+ expect(Array.isArray(result?.contradictions)).toBe(true);+ expect(Array.isArray(result?.retired)).toBe(true);+ });+});