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
refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)
Sol Aitken66512289a099
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex e06364cd..99b9714f 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.1",+ "version": "1.1.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 4ec65ec4..4f6f6a96 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.1",+ "version": "1.1.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d4ffd53..b7c1b980 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,7 @@ 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).-## [Unreleased]+## [1.1.0] - 2026-06-09Removal of the Pay Memory layer. The pay.sh integration and the entirepayment-memory subsystem it supported have been taken out of Open Second@@ -34,6 +34,34 @@ are unchanged. Historical records are preserved: this changelog, the datedsection, and the `payment` / `asset` surface-group prefixes are deleted. Theshared `vaultRelativePath` helper now imports from `core/path-safety`.+### Changed++- **Language-agnostic fact extraction**: the real-time fact extractor+ (`fact-extract.ts`) and the assertion-to-claim ingest (`truth/ingest.ts`) no+ longer rely on hardcoded English trigger phrases. Extraction now keeps only+ structurally detectable, language-neutral facts - URLs, e-mail addresses, and+ quantities bound to a currency glyph, ISO-4217 code, or percent - so a fact+ extracts identically whatever the surrounding language. This completes the+ language-agnostic work that made search and classification structural; the+ extractor was the last component carrying per-language word lists. Prose facts+ (name, preference, location) are no longer auto-captured by this real-time,+ LLM-free path: a deliberate, precision-safe recall reduction.+- **Quantity aggregation by unit**: `parseQuantityFact` no longer derives a+ prose `action` verb. The quantity claim keeps a nullable `action` for the+ explicit-label path (MCP ingest `quantity_action`), and `aggregateQuantities`+ / the `o2b brain truth aggregate` and `brain_truth` `action` argument are now+ optional - totals combine by entity + unit by default.+- **README** trimmed to user-facing value: the version-by-version feature+ catalog and the full CLI command dump moved behind the existing documentation+ links, leaving a compact "What you get" overview.++### Removed++- **`FactFamily` prose members**: `identity`, `preference`, `possession`,+ `location`, and `confirmation` are removed from the structural fact extractor;+ only `url`, `email`, and `quantity` remain. The matching English+ `STRUCTURERS` and `POSSESSION_RE` in `truth/ingest.ts` are deleted.+## [1.0.1] - 2026-06-07Hermes registration fix. The memory provider now advertises its curateddiff --git a/README.md b/README.mdindex c7526710..143c29a8 100644--- a/README.md+++ b/README.md@@ -74,103 +74,24 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`memEach non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.-## How rules accrete+## What you get-```mermaid-sequenceDiagram- actor You- participant Agent as Hermes Agent- participant Inbox as Brain/inbox- participant Pref as Brain/preferences- participant Log as Brain/log-- You->>Agent: "no, write full names instead of abbreviations"- Agent->>Inbox: brain_feedback (signal)- Note over Inbox: ... repeats over days ...- Inbox->>Pref: dream pass (counters + mv, no LLM)- Agent->>Log: brain_apply_evidence (applied | violated)- Note over Pref,Log: confidence grows from evidence,<br/>decays when nothing applies the rule- Pref-->>Agent: Brain/active.md injected at session start-```--Three repeat signals on the same topic graduate to a confirmed rule. Evidence shifts confidence up or down. Rules with zero recent evidence retire automatically. You can pin, merge, retire, or roll back with `o2b brain {pin,merge,reject,rollback}` - see [`docs/cli-reference.md`](docs/cli-reference.md).--## Top features--The capabilities you actually feel day to day:--| # | Feature | What it means for you |-| --- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 1 | Your memory, in your Obsidian vault | Every rule the agent learns about you is a Markdown file you can open, read, and edit. Wikilinks, backlinks, and the graph view in Obsidian all work — no separate UI to learn. |-| 2 | `dream` - the agent learns what you actually want | The nightly `dream` pass turns repeat corrections into rules: three signals on the same topic graduate to a confirmed preference. Its confidence rises every time the agent applies the rule and drops when it slips. No LLM inside the algorithm - counters and atomic file moves, nothing else. |-| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows; `brain_agent_query` and `brain_agent_diff` let you inspect which agent contributed what. |-| 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osb✓` checkmark so re-runs skip it. |-| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` / `monthly` summarise what changed; `o2b brain intent-review` previews whether signal clusters are ready before the next `dream`; `o2b brain retention` recommends keep/improve/park/prune actions without deleting anything. |-| 6 | Browse and govern your memory schema | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Preference files can declare typed relationships such as `depends_on:` and `refines:`, plus `memory_layer` / `memory_branch` labels and optional `schema_type:` taxonomy metadata; `o2b brain schema` stats, lint, graph, explain, orphans, and apply audit and mutate those tokens through locked, audited writes. Double-click a node — Obsidian opens the underlying note. |-| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |-| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |-| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open --evidence-pack --since 7d` — SQLite + FTS5 and an optional semantic layer, with CJK-aware token expansion for unspaced Chinese/Japanese/Korean text. Recall is sharpened by MMR diversity, link-graph traversal, entity boosting, structured query lanes, session focus, and header-anchored chunking; typed relations carry recall polarity (a `superseded_by` predecessor is demoted below its successor, `contradicts` warns without endorsing); `--since` / `--until` scope recall by time; `o2b search feedback` trains bounded, auditable learned weights; opt-in evidence packs show matched/missing terms, IDF-weighted coverage, per-token union records, a completeness verdict with a false-absence guard, abstention text, terminal-state downranks, and `why_retrieved` reasons. |--These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_brief view=morning` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.--The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`). The v0.43.0 surface adds the Entity Truth & Self-Improving Dream Suite: an append-only entity claim ledger under `Brain/truth/` (device-sharded JSONL claim events folded into per-`(entity, aspect)` slots with current value, superseded history, temporal-structural `value_conflict` detection that is always `ask_user`, exact-match quantity aggregation, and `o2b brain truth` / MCP `brain_truth` surfaces), deterministic atomic-fact decomposition (`o2b brain facts decompose`, markdown-structure splitting with an abbreviation guard and optional `--ingest` into the ledger), an actor-framed `quantity` fact family, a name-aware merge guard (`entity-guard` refusal with `--force` bypass) plus an `entity_contamination` deep-synthesis dimension, push-mode cross-agent collision triggers (`agent_collision` kind with cooldown dedup), outcome-tied apply-evidence (`outcome: success|failure|unknown` staging `outcome_regressions` with a deterministic confidence penalty), a markdown-first dead-end registry (`o2b brain dead-end`, MCP `brain_dead_ends` - negative knowledge FTS-recallable beside positive rules), surprisal novelty ranking on `brain_review_candidates` over the existing sqlite-vec index, a weekly `topSource` nomination in the weekly synthesis, and the Brain's first forward-looking fold (`o2b brain foresight`, MCP `brain_foresight` - recurrence cadences project next-due routines, open commitments and questions surface with sources). The v0.44.0 surface adds the Write-Time Integrity & Governance Suite: schema-pack ontology fields (controlled-vocabulary `labels`, per-link-type `link_constraints` endpoint pairs, per-type `attributes` descriptors, and a `frontmatter_tiers` map - all additive with audited mutations), fail-closed label classification (`o2b brain label`, MCP `brain_labels` - unknown dimensions and values are rejected with the declared vocabulary, persisted as a filterable frontmatter array plus a canonical label entity), link-type endpoint constraints enforced at index materialization (violating typed edges fall back to untyped links, surfaced by `schema lint` and restored automatically when the constraint is removed), per-type attribute fields whose validation errors teach the declared vocabulary (`o2b brain attr`), a four-level frontmatter tier guard (identity/system/business/user with built-in framework defaults, a tier-respecting merge in framework writers, index-time identity-drift detection that never absorbs a hand-edit, and the staged `o2b brain tiers check | restore | accept` repair surface, MCP `brain_tiers`), capability-gated secret custody (`o2b brain secret set | list | rm | run`, MCP `brain_secrets` - per-value AES-256-GCM ciphertext under the vault-local state dir, stdin-only ingestion, allowlist-gated subprocess env injection with redacted output, and a no-values audit trail in `Brain/log/secret-custody/`), and a quiet-window lease-guarded maintenance lane (`o2b brain maintenance run | status`, MCP `brain_maintenance` - a tz-aware hour window, a recall-telemetry busy gate, an expiring SQLite lease no second worker can grab, stale-first task ordering, and a bounded journal of every attempt including gate refusals). The v0.45.0 surface adds the Link & Recall Intelligence Suite: vault-wide frontmatter alias resolution materialized at index time (schema v7 `doc_aliases`, shadowing-safe, exact paths always win), orphan-first bridge discovery over the vec index (`o2b brain bridges discover | list | accept | dismiss`, MCP `brain_bridges` - embedding-near unlinked pairs land in a reviewable `Brain/proposals/bridges.md`, accept writes one `related:` wikilink honoring schema-pack link constraints, dismissals persist), deterministic graph-wide community detection with derived cluster digests (`o2b brain clusters run | list`, MCP `brain_clusters` - label propagation with a stable tie-break, `Brain/clusters/` notes regenerate per run, hand-written files untouched), a reproducible recall benchmark with a committed fixture dataset and CI thresholds (`o2b brain benchmark run`, MCP `brain_benchmark` - hit@k and MRR against the live hybrid pipeline), deterministic query expansion into the structured lex/vec/hyde lanes (`o2b search --expand` - stopword-stripped lex terms, entity-context vec line, template hyde passage, no model and no paid call), opt-in self-tuning recall judged by the benchmark (`o2b brain tune run | status | reset`, MCP `brain_tune` - a bounded replayable grid persisted to `Brain/search/tuning.json`, applied only under `search_self_tuning_enabled`), and a dashboard-ready run-level metrics layer (`Brain/metrics/<surface>.jsonl`, schema `o2b.metrics.v1`, contract in `docs/metrics.md`). The v1.0.0 surface is the Stability & Trust release: the public contracts freeze under `docs/stability.md` (the 18 hidden alias tools are removed with tombstones naming each replacement - migration table in `docs/updating.md`), every long-running operation runs under a cooperative safeguard deadline with clean abort semantics, the dream loop gains a staged stage/validate/apply lifecycle over a persisted reviewable bundle (`o2b brain dream stage`), configured-timezone rendering arrives at the presentation layer while storage stays canonical UTC, and the digest/daily/weekly surfaces persist machine-diffable snapshots with a deterministic since-last-run delta (`report_snapshots_enabled`).--## CLI--```bash-o2b status # Show config / vault status-o2b init # Bootstrap the vault profile-o2b doctor # Run vault + adapter checks-o2b brain dream # Deterministic consolidation pass (idempotent)-o2b brain digest # Recent transitions, markdown or JSON-o2b brain intent-review --json # Pre-dream signal readiness audit-o2b brain retention --json # Recommendation-only lifecycle review-o2b brain monthly --month 2026-05 --json # Month-level Brain synthesis-o2b brain audit pref-foo --json # Full mutation trail for one preference-o2b brain morning-brief --json # Session-start summary (prefs, open questions, notes)-o2b brain sources --json # Per-source signal dashboard-o2b brain entity set people "Ada Lovelace" --alias "the operator" # Canonical entity registry-o2b brain entity get "the operator" --json # Alias resolves to the canonical record-o2b brain schema lint --json # Runtime schema vocabulary + usage/admin findings-o2b brain watchdog --json # Brain probes + safe recovery recommendations-o2b brain graph-export --out graph.json # Export the vault knowledge graph-o2b brain semantics-backfill --json # Dry-run typed preference-edge repair proposals-o2b brain context-receipts list --json # Inspect opt-in prompt context receipts-o2b brain recall-telemetry summary --json # Aggregate opt-in recall/context telemetry-o2b brain context-presets suggest --model claude-sonnet-4 --context-window 200000 --json-o2b brain import-session session.jsonl --recall --json # Populate the session recall DAG-o2b brain session-grep --query "decision" --json # Search raw/session summary recall nodes-o2b vault profile switch work # Activate a named multi-vault profile-o2b brain agent-query --agent claude --json # Source-agent provenance query-o2b brain agent-diff --mode diff --agent claude --agent codex-o2b search "<query>" --evidence-pack # FTS5/hybrid search with matched/missing evidence-o2b search "<query>" --since 7d --until today # Time-scoped recall (event-time validity window, mtime fallback)-o2b search feedback --query "<q>" --result note.md --verdict up # Train learned recall weights-o2b search weights --json # Inspect base + learned ranking weights-o2b search focus set --query "current task" --path Notes/Project-o2b secrets list --json # Inspect $secret:NAME references without printing values-o2b help --json # Machine-readable command/flag manifest-o2b completions --shell zsh # Completion script for bash/zsh/fish/elvish/nushell/powershell-o2b mcp --probe --json --disable-tool second_brain_query # Capability-aware MCP probe-o2b update # Update across detected runtimes-```+- **Your memory as Markdown.** Every rule the agent learns about you is a file under `Brain/` you can open, edit, grep, and version. Obsidian wikilinks, backlinks, and the graph view just work - there is no separate UI to learn.+- **Memory that learns, and forgets, on its own.** A nightly `dream` pass turns repeated corrections into rules and retires the ones nothing uses any more. Deterministic by design: counters and atomic file moves, no LLM guessing inside your memory.+- **One brain, every agent.** Teach a rule in one agent and the next one already knows it - Hermes, Claude Code, Codex, Cursor, and the rest read and write the same vault.+- **You stay in control.** Pin, merge, retire, or roll back any rule from the `o2b` CLI. Every Brain mutation takes a verified snapshot first, so a bad change is one `o2b brain rollback` away.+- **Search that explains itself.** Keyword plus an optional semantic layer over your vault, with results that show why they surfaced and what was missing - not a black box.-Full list of verbs across `o2b`, `o2b brain`, `o2b vault`, and `o2b discipline` in [`docs/cli-reference.md`](docs/cli-reference.md).+That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.## Safety-- Plain Markdown on your filesystem. No daemon, no background writes.-- The MCP server is a stdio subprocess that exits with the parent runtime.-- MCP runtime capability flags (`--allow-tool`, `--disable-tool`, `--max-tools`) can narrow the advertised tool surface per process without widening the writer-only scope.-- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.-- `$secret:NAME` config references store only the reference and resolve from the local process environment; `o2b secrets list|status` reports availability without printing values.-- Automatically surfaced Brain snippets from `brain_context_pack` and `brain_pre_compress_pack` pass through a deterministic prompt-injection guard. Filtered outputs return a placeholder plus machine-readable reason codes; source Markdown is not rewritten.-- Context receipts and recall telemetry are opt-in and store redacted metadata, hashes, source refs, counters, and gap diagnostics rather than raw private prompt text.+- Plain Markdown on your filesystem. No daemon, no background writes. The MCP server is a stdio subprocess that exits with the parent runtime.+- Your vault is the only source of truth - no hidden state, no cloud copy.- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.-- Lifecycle review commands (`intent-review`, `retention`, `monthly`) are read-only. Retention emits recommendations only; it never deletes, moves, or edits Brain artifacts.-- Hooks (Claude Code, Codex) inject active context and capture explicit prompt markers / `brain_feedback` tool calls through the same signal dedup boundary; lifecycle observations are audited/logged and never block the runtime.-- `o2b brain watchdog` and `brain_watchdog` are probe-first. They recommend search-index repair and can create missing Brain directories only when remediation is explicit; snapshot restore is refused unless restore intent and force are both explicit.-- Text written through Brain redaction strips `<private>...</private>` regions before storage and masks secret-shaped assignments such as `api_key=...`.+- Secrets are not supposed to live in the vault. Daily logs and config exports run through a best-effort redactor, `$secret:NAME` references resolve from the local environment and are never stored, and Brain redaction strips `<private>...</private>` regions before storage.+- Automatically surfaced Brain context passes through a deterministic prompt-injection guard; filtered output returns a placeholder with a reason code and the source Markdown is never rewritten.+- Context receipts and recall telemetry are opt-in and store redacted metadata, hashes, and counters rather than raw prompt text.## Updatingdiff --git a/docs/brainstorm/language-agnostic-fact-extraction/cli-output/claude.md b/docs/brainstorm/language-agnostic-fact-extraction/cli-output/claude.mdnew file mode 100644index 00000000..45c5c5cd--- /dev/null+++ b/docs/brainstorm/language-agnostic-fact-extraction/cli-output/claude.md@@ -0,0 +1 @@+Warning: no stdin data received in 3s, proceeding without it. If piping from a slow command, redirect stdin explicitly: < /dev/null to skip, or wait longer.diff --git a/docs/brainstorm/language-agnostic-fact-extraction/cli-output/prompt.md b/docs/brainstorm/language-agnostic-fact-extraction/cli-output/prompt.mdnew file mode 100644index 00000000..416cf4ee--- /dev/null+++ b/docs/brainstorm/language-agnostic-fact-extraction/cli-output/prompt.md@@ -0,0 +1,69 @@+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++Make src/core/brain/fact-extract.ts language-agnostic. Today it extracts 7 families of facts from user turns in real time using regex patterns anchored on ENGLISH trigger phrases: "my name is", "I'm called", "I prefer / always use / never use", "I live/based in", "my site/blog/repo is", "my email is", a confirmation frame ("yes|correct|right|exactly" + "my|our|the" + "is|are"), generic possession ("my X is Y"), and a quantity family (English action verbs "spent|paid|earned|saved|billed|ran|completed|logged|worked|shipped" + number + optional unit). It also hardcodes English stop-words ("on","for","the",...) and an English possession-key blocklist ("name","email","blog",...).++The hardcoded English phrases must be removed. The system must not hardcode phrases for any specific human language (we cannot enumerate all world languages). Where non-English input must be handled, it must be handled ABSTRACTLY (structurally), not by adding another language's word list. The replacement must not introduce meaningless/misleading fallbacks.++This extractor is the real-time, LLM-free complement to a heavier pre-compaction extraction path. It feeds the truth subsystem (truth/ingest.ts, sessions/import.ts, session-lifecycle.ts) by writing `source_type: extracted` signals. Precision is valued over recall: a missed fact costs little, a hallucinated fact pollutes memory.++# Project context++Open Second Brain - an agent-owned Obsidian-compatible Markdown vault plugin. TypeScript run on Bun. Offline-first: search defaults to keyword-only; semantic/LLM features are opt-in via providers (openai-compat | local lexical baseline | disabled). The just-merged PR #84 already made SEARCH and CLASSIFICATION language-agnostic by removing hardcoded EN/RU word lists in favor of structural signals, corpus document-frequency (IDF), and explicit frontmatter. fact-extract.ts was the one deferred slice.++Recent commits:+9886d9a refactor: make search and classification language-agnostic (#84)+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)+72bac52 fix(hermes): advertise static tool schemas so the provider registers with its full tool set (#81)+ff43abd fix(ci): treat an existing release as success in the release workflow (#80)+957a403 feat!: Stability & Trust - 1.0.0 API freeze, deprecation sweep, safeguard, staged dream, timezone, report deltas (#79)+786b0f5 fix(openclaw): rebuild stale plugin bundle so the release verify gate passes (#78)+6d09d3c feat: Link & Recall Intelligence Suite - alias resolution, bridge discovery, communities, recall benchmark, self-tuning (#77)+789e3e3 feat: Write-Time Integrity & Governance Suite - schema ontology, tier guard, secret custody, maintenance lane (#76)+c03d569 fix(hermes): root cli.py shim completes the upstream CLI discovery contract (#75)+a0054dd feat: Entity Truth & Self-Improving Dream Suite - claim ledger, outcome-aware dream, foresight (#74)+b16c37d feat: Time-Aware Recall & Activation Suite - usage-aware ranking, event-time recall, two-pass recovery (#73)+c3a2fcc feat: Agent Write Contract Suite - write sessions, decision panel, backend boundary, shared namespace (#72)+7733f20 feat: Project History Suite - git history memory, ADR mining, architecture notes, query telemetry (#71)+8e8c0bc feat: Memory Observability Suite - versioned continuity contract, lazy telemetry, ATOF/ATIF export, recall benchmark (#70)+eb56c9f feat: Workspace Insight Suite - project pointers, cross-vault recall, trigger queue, proactive synthesis (#69)+707197a feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)+eda202d feat: Embedding Provider Suite - local embedder, provider registry, cost gate, RRF fusion (#67)+dee5ab7 feat: Memory Integrity Suite - canonical entities, conflict-free log shards, capture boundaries, fact extraction (#66)+5066e71 feat: Token Diet - budgeted injection, reminder cadence, consolidated MCP surface (#65)+c494fd8 feat(search): Recall Trust Suite - relation polarity, learned weights, time-aware and verified recall (#64)++Related files:+- src/core/brain/fact-extract.ts (the target)+- src/core/brain/truth/ingest.ts, src/core/brain/sessions/import.ts, src/core/brain/session-lifecycle.ts (consumers)+- src/core/brain/entities/canonical.ts (normalizeEntityName, used for entity anchoring)++Conventions:+- Offline-first; deterministic where possible; providers are opt-in (openai-compat | local | disabled).+- Precision over recall for real-time capture.+- SOLID / KISS / DRY; no hardcoded natural-language word lists; no meaningless fallbacks.+- The sibling search/classification refactor (PR #84) preferred: structural signals, Unicode-aware tokenization, explicit frontmatter fields, corpus IDF, and agent/LLM extraction where structure is insufficient.++Constraints:+- Do NOT hardcode phrases/words for any specific human language.+- Do NOT add a fallback that silently does nothing or misleads (e.g. "no provider -> pretend extraction happened").+- Keep the public exports stable where reasonable (extractFacts, parseQuantityFact, routeExtractedFacts, factDedupHash) - consumers depend on them.+- Real-time path must stay cheap; a per-turn synchronous LLM call on every user message is likely too heavy for the default offline mode.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences.+- **Trade-offs**: bullet list of pros and cons (include the recall regression risk explicitly).+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences considering the offline-first, precision-over-recall, no-fake-fallback context.++Output nothing outside of these sections.diff --git a/docs/brainstorm/language-agnostic-fact-extraction/design.md b/docs/brainstorm/language-agnostic-fact-extraction/design.mdnew file mode 100644index 00000000..b65c420a--- /dev/null+++ b/docs/brainstorm/language-agnostic-fact-extraction/design.md@@ -0,0 +1,85 @@+# Language-agnostic fact extraction - remove hardcoded human-language trigger phrases++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook; external consultant step waived by operator)+**Audience:** implementation++## Problem statement++`src/core/brain/fact-extract.ts` and `src/core/brain/truth/ingest.ts` detect facts in user+turns using regexes anchored on English trigger phrases ("my name is", "I prefer", a+"yes/correct/right/exactly ... is/are" confirmation frame, English quantity action verbs+"spent|paid|earned|...", English stop-words, an English possession-key blocklist, and+English `STRUCTURERS` like "based in"). PR #84 made search and classification+language-agnostic; this extraction path was the one deferred slice. We cannot enumerate the+world's languages, so any phrase list is a defect, not a feature.++## Scope++- Delete every hardcoded human-language phrase from the fact-extraction path: the prose+ family patterns in `fact-extract.ts` and the English `STRUCTURERS` / `POSSESSION_RE` in+ `truth/ingest.ts`.+- Keep only structurally detectable, language-neutral facts: URLs, e-mail addresses, and+ quantities expressed through language-neutral symbols (currency symbols / ISO codes,+ percent).+- Update `truth/ingest.ts` so no dead branch survives the family removals.++## Out of scope++- Re-introducing prose-fact capture through any other mechanism (explicit author labels or+ an LLM provider). Tracked as a follow-up if recall loss proves material.+- The `decision:`/`rule:` explicit-label markers in `pre-compact-extract.ts`. Those are an+ author-written structured-label convention (like `TODO:`), not natural-language detection;+ left as-is.+- Changing the persisted claim-ledger schema. The nullable `action` column stays for+ back-compat; we simply stop deriving it from English verbs.++## Chosen approach++Variant 1 (structural-only). `extractFacts` keeps three language-neutral families:++- `url` - bare `https?://...` match, no trigger phrase.+- `email` - bare RFC-ish address match, no trigger phrase.+- `quantity` - a number bound to a language-neutral measurement symbol (currency symbol,+ ISO-4217-style code, or percent). The English actor/action frame and stop-word list are+ removed; `parseQuantityFact` no longer emits a prose-derived `action`.++Everything that needed a human-language frame (identity, preference, location, possession,+confirmation) is removed. Prose facts in any language are not auto-captured by this+real-time, LLM-free path; that is an accepted, explicit recall reduction, consistent with+precision-over-recall and with PR #84's structural philosophy.++## Design decisions++- **Structural, not lexical.** A signal qualifies only if it is detectable without knowing+ any natural language (a URL, an `@`-address, a currency symbol). This is the same test+ PR #84 applied to search and classification.+- **No fake fallback.** We do not add a "no provider -> pretend" path. Removed families are+ removed, not stubbed.+- **`action` is no longer invented.** The quantity `action` was an English verb. It is set+ to `null` from this path; `truth/aggregate.ts` already buckets `action: string | null`, so+ quantities now aggregate by `unit`. The column stays nullable for back-compat and for a+ future explicit-label source.+- **Stable public API.** `extractFacts`, `parseQuantityFact`, `factDedupHash`,+ `routeExtractedFacts` keep their signatures; only behavior narrows. `FactFamily` loses the+ removed members.++## File changes++- `src/core/brain/fact-extract.ts` - replace `FAMILY_PATTERNS` with the three structural+ families; delete `QUANTITY_UNIT_STOPWORDS`, `POSSESSION_KEY_BLOCKLIST`, the English action+ verbs; narrow `FactFamily`; rework `parseQuantityFact` to structural quantity (no action).+- `src/core/brain/truth/ingest.ts` - delete `POSSESSION_RE`, the English `STRUCTURERS`+ (name/called/based-in); keep the structural email/website structurers; drop the+ `possession` branch; keep the `quantity` branch (`action` now null).+- Tests across `tests/core/brain/**` and `tests/**` that assert removed families.++## Risks and open questions++- **Recall regression (accepted).** English prose facts (name, preference, location) stop+ auto-extracting. Mitigation: explicit labels and the dream pass still feed memory; the+ loss is precision-safe.+- **Quantity precision.** Without an actor frame, quantity must stay tight (bound to a+ currency/percent symbol) to avoid matching arbitrary numbers. Covered by tests.+- **Downstream `action` consumers.** Confirm `truth/aggregate.ts` and `truth/store.ts`+ tolerate a null `action` end-to-end (they type it `string | null`).diff --git a/docs/brainstorm/language-agnostic-fact-extraction/plan.md b/docs/brainstorm/language-agnostic-fact-extraction/plan.mdnew file mode 100644index 00000000..b3fec6d6--- /dev/null+++ b/docs/brainstorm/language-agnostic-fact-extraction/plan.md@@ -0,0 +1,41 @@+# Language-agnostic fact extraction - implementation plan++## Tasks++### Task 1: Structural-only `fact-extract.ts`+- **Files**: `src/core/brain/fact-extract.ts`, `tests/core/brain/fact-extract.test.ts`+ (and any other test asserting removed families).+- **Changes**:+ - Narrow `FactFamily` to `"url" | "email" | "quantity"`.+ - Replace `FAMILY_PATTERNS` with three structural patterns: bare URL, bare+ e-mail, and a currency/percent-bound quantity.+ - Delete `QUANTITY_UNIT_STOPWORDS`, `POSSESSION_KEY_BLOCKLIST`, English+ action verbs.+ - `parseQuantityFact`: detect a number bound to a currency symbol, an+ ISO-4217-style 3-letter code, or `%`; drop the `action` field from+ `ParsedQuantityFact` (no language-neutral source).+- **Acceptance** (tests, written first, must fail before the change):+ - "my name is Bob" / "I prefer X" / "yes, the price is 5" extract NOTHING.+ - A URL, an e-mail, and a `$1,200` / `50%` / `3.5 USD` amount extract in+ any language context (assert with a non-Latin sentence wrapping them).+ - `parseQuantityFact("$42")` -> `{value: 42, unit: "usd"}`; bare "42"+ without a symbol -> `null`.++### Task 2: De-couple `truth/ingest.ts`+- **Files**: `src/core/brain/truth/ingest.ts`, `tests/core/brain/truth/ingest.test.ts`.+- **Depends on**: Task 1.+- **Changes**:+ - Delete `POSSESSION_RE` and the English `STRUCTURERS` (name/called/based-in).+ - Keep the structural e-mail and website structurers.+ - Remove the `possession` branch in `claimsFromAssertion`.+ - Quantity branch: pass `action: null` (field stays nullable in the ledger).+- **Acceptance**:+ - An assertion "my name is Bob" yields NO claim.+ - An assertion with an e-mail / URL / currency amount yields the+ corresponding structural claim.+ - `truth/aggregate.ts` + `truth/store.ts` still pass with `action: null`.++### Task 3: Suite sweep+- **Files**: any remaining test under `tests/**` referencing removed+ families, English fixtures, or `quantity.action`.+- **Acceptance**: full `bun test`, `bun run typecheck`, `bun run lint` green.diff --git a/docs/brainstorm/language-agnostic-fact-extraction/variants.md b/docs/brainstorm/language-agnostic-fact-extraction/variants.mdnew file mode 100644index 00000000..df1e465f--- /dev/null+++ b/docs/brainstorm/language-agnostic-fact-extraction/variants.md@@ -0,0 +1,60 @@+# Variants - language-agnostic fact extraction++The external CLI consultant step was waived by the operator (decisive+"remove without mercy" directive). Variants below were authored by the+orchestrator to record the alternatives considered and why one was chosen.++### Variant 1: Structural-only extraction++- **Approach**: Drop every family that needs a human-language frame+ (identity, preference, location, possession, confirmation) plus the+ English `STRUCTURERS`/`POSSESSION_RE` in `truth/ingest.ts`. Keep only+ language-neutral structural families: URL, e-mail, and quantity bound to+ a currency/percent symbol. Stop deriving the English `action` verb.+- **Trade-offs**:+ - Pro: zero language coupling; same philosophy as PR #84; deterministic+ and offline; no fake fallback; smallest, clearest surface.+ - Pro: works identically for every language - a Japanese or Arabic turn+ with a URL / `@`-address / currency amount extracts the same facts.+ - Con: real recall regression - English prose facts (name, preference,+ location) are no longer auto-captured by this path.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Explicit author-label markers++- **Approach**: Replace prose detection with explicit structured labels the+ agent/user writes (mirroring `pre-compact-extract.ts`'s `decision:` /+ `rule:`): e.g. `name:`, `prefers:`, `location:`. Detect `label: value`+ structurally.+- **Trade-offs**:+ - Pro: language-neutral (the label is a fixed token, not prose); higher+ precision than prose regex.+ - Con: labels are still English tokens (just a smaller, schema-like set) -+ only partially honors the directive; shifts behavior (capture now+ depends on authors using labels); larger doc/skill change to teach the+ convention.+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Provider-assisted extraction++- **Approach**: Route prose-fact extraction through the configured provider+ (openai-compat) when present; structural-only when `local`/`disabled`.+- **Trade-offs**:+ - Pro: highest recall, genuinely language-agnostic for prose.+ - Con: a synchronous per-turn LLM call is too heavy for the default+ offline hot path; the `disabled`/`local` branch is exactly the+ "meaningless fallback" the operator forbids unless framed as additive;+ largest blast radius and new failure modes.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1++**Rationale**: It is the only option that fully and immediately satisfies+"no hardcoded language phrases anywhere" without inventing a new English+label vocabulary (Variant 2) or coupling the offline hot path to a provider+(Variant 3). The recall loss is precision-safe and explicitly accepted; if it+proves material, Variant 2 or 3 can be layered later as an additive,+opt-in source rather than a hot-path dependency.diff --git a/docs/brainstorm/readme-user-value-slim/design.md b/docs/brainstorm/readme-user-value-slim/design.mdnew file mode 100644index 00000000..b334e060--- /dev/null+++ b/docs/brainstorm/readme-user-value-slim/design.md@@ -0,0 +1,49 @@+# README user-value slim - cut the agent-function wall-of-text++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook; consultant waived by operator)+**Audience:** implementation++## Problem statement++`README.md` (213 lines) reads as an exhaustive agent-function changelog rather+than a user-facing pitch. The worst offenders are the "Top features" section -+two multi-thousand-character paragraphs enumerating every release surface from+v0.12.0 to v1.0.0 - and the "CLI" section dumping ~35 commands. A reader cannot+tell in ten seconds what the plugin is for them.++## Scope++- Keep the value-first half verbatim: hero/poster, tagline, intro, "Why", the+ "One vault, many runtimes" diagram, "Quick start", "Other runtimes".+- Replace "Top features" (the version-by-version walls) with one compact+ "What you get" section of user-facing value bullets.+- Drop the "How rules accrete" sequence diagram and the full "CLI" command dump+ from the README; both are covered by the linked docs.+- Trim "Safety" to the points a user cares about.+- Keep "Documentation", "Updating", "Uninstalling", "License" - the docs table+ is where the full surface and every CLI verb already live.++## Out of scope++- Editing any `docs/*` target (they already hold the detail).+- Changing the poster image or install instructions.++## Chosen approach++The README answers "what is this for me, and how do I start". Depth moves behind+the existing Documentation table. No capability is lost - it is relocated, not+deleted - and the version-history prose stops living in the README (the+CHANGELOG and release notes own that).++## File changes++- `README.md` - rewrite the middle (sections "How rules accrete" through "CLI")+ into a single "What you get" section; trim "Safety"; leave the rest intact.++## Risks and open questions++- A reader wanting the exhaustive surface must follow a doc link. Acceptable: the+ Documentation table is immediately below and names every relevant doc.+- Mermaid "One vault, many runtimes" diagram is retained; confirm it still+ renders after the edit.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 4a61d894..cbf1dfb7 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": "1.0.1",+ "version": "1.1.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 8793e003..eab8255c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.1",+ "version": "1.1.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex dfba1bde..c85fb696 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.0.1"+version: "1.1.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 91fe8328..6308a7e7 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.1",+ "version": "1.1.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex dfba1bde..c85fb696 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.0.1"+version: "1.1.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex b5918b46..7d1667ff 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 = "1.0.1"+version = "1.1.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/truth.ts b/src/cli/brain/verbs/truth.tsindex 29236a05..401b51fc 100644--- a/src/cli/brain/verbs/truth.ts+++ b/src/cli/brain/verbs/truth.ts@@ -164,7 +164,7 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {case "aggregate": {const state = computeTruthStateWithConflicts(readClaimEvents(vault).events);const result = aggregateQuantities(state.slots, {- action: requireString(flags, "action"),+ ...(typeof flags["action"] === "string" ? { action: flags["action"] } : {}),unit: (flags["unit"] as string | undefined) ?? null,...(typeof flags["entity"] === "string" ? { entity: flags["entity"] } : {}),});@@ -172,7 +172,7 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {okJson({ ...result });} else {ok(- `${result.action}${result.unit !== null ? ` (${result.unit})` : ""}: ` ++ `${result.action ?? "all actions"}${result.unit !== null ? ` (${result.unit})` : ""}: ` +`total ${result.total} across ${result.count} value(s)`,);for (const c of result.contributions) {diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.tsindex 8d31d089..a17a7647 100644--- a/src/core/brain/fact-extract.ts+++ b/src/core/brain/fact-extract.ts@@ -1,20 +1,26 @@/**- * Regex fact extraction (Memory Integrity Suite, t_d0782ab2).+ * Structural fact extraction (Memory Integrity Suite, t_d0782ab2;+ * made language-agnostic in t_80cbefa1).*- * Seven precision-first pattern families capture structured facts- * from USER turns in real time, without an LLM call - complementing- * the heavier pre-compact extraction. The HANDOFF carve-out from the- * upstream design is applied at its conservative core: callers only- * feed user-authored text (role === "user"); bare assistant output is- * never auto-extracted. The capture boundary runs FIRST - suppressed- * or ignored input never reaches these patterns.+ * Captures structured facts from USER turns in real time, without an+ * LLM call. The families are deliberately limited to signals that can+ * be recognised WITHOUT knowing any human language: a URL, an e-mail+ * address, and a quantity bound to a language-neutral symbol (currency+ * symbol, ISO-4217 code, or percent). Prose-framed families that used+ * to depend on English trigger phrases ("my name is", "I prefer",+ * "yes, the X is ...") were removed: we cannot enumerate the world's+ * languages, so a per-language phrase list is a defect, not a feature+ * (see PR #84, which applied the same rule to search and classification).*- * Precision beats recall throughout: each family requires an explicit- * first-person or confirmation frame ("my X is", "I prefer", "yes,- * the X is ..."), fenced/inline code is stripped, and quoted lines- * (`> ...`) are dropped before matching. A missed fact costs nothing- * (the dream pass has other sources); a hallucinated fact pollutes- * memory.+ * The HANDOFF carve-out is applied at its conservative core: callers+ * only feed user-authored text (role === "user"); bare assistant+ * output is never auto-extracted. The capture boundary runs FIRST -+ * suppressed or ignored input never reaches these patterns.+ *+ * Precision beats recall: fenced/inline code is stripped, quoted lines+ * (`> ...`) are dropped, and a quantity needs an explicit unit symbol+ * so arbitrary numbers never match. A missed fact costs nothing (the+ * dream pass has other sources); a hallucinated fact pollutes memory.*/import { createHash } from "node:crypto";@@ -27,15 +33,7 @@ import { buildEntityIndex } from "./entities/index-builder.ts";import { normalizeEntityName } from "./entities/canonical.ts";import { BRAIN_ENTITY_STATUS } from "./entities/types.ts";-export type FactFamily =- | "identity"- | "preference"- | "possession"- | "location"- | "url"- | "email"- | "confirmation"- | "quantity";+export type FactFamily = "url" | "email" | "quantity";export interface ExtractedFact {readonly family: FactFamily;@@ -47,96 +45,72 @@ export interface ExtractedFact {const MAX_FACT_CHARS = 200;-// Possession keys that belong to a more specific family; the generic-// "my <thing> is <value>" pattern must not double-capture them.-const POSSESSION_KEY_BLOCKLIST = new Set([- "name",- "email",- "blog",- "site",- "website",- "repo",- "repository",- "homepage",- "page",-]);+// Defence-in-depth cap: extractFacts runs on raw user turns, so a single+// pathologically long line is never scanned in full. A real fact lives well+// within this bound; anything longer is sliced before matching so the capture+// hot path can never be turned into a CPU sink by crafted input.+const MAX_LINE_SCAN_CHARS = 4000;-// Family patterns. Every regex is line-scoped (callers split lines)-// and anchored on an explicit first-person / confirmation frame.-const FAMILY_PATTERNS: ReadonlyArray<readonly [FactFamily, RegExp]> = Object.freeze([- ["identity", /\bmy name is\s+[\w'-]+(?:\s+[A-Z][\w'-]+)*/giu],- ["identity", /\bI(?:'m| am) called\s+[A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)*/gu],- ["preference", /\bI (?:prefer|always use|never use)\s+[^\n.!?]{3,120}/gu],- ["location", /\bI (?:live|'m based|am based) in\s+[A-Z][\w-]+(?:\s+[A-Z][\w-]+)*/gu],- [- "url",- /\b(?:my|our) (?:(?:web)?site|blog|repo(?:sitory)?|homepage|page) is\s+https?:\/\/[^\s)>\]]+/giu,- ],- ["email", /\b(?:my|our) email(?: address)? is\s+[\w.+-]+@[\w.-]+\.\w{2,}/giu],- [- "confirmation",- /^(?:yes|correct|right|exactly)[,!.]?\s+(?:my|our|the)\s+[^\n]{3,120}\b(?:is|are)\b[^\n]{2,120}/giu,- ],- ["possession", /\bmy ([a-z][\w -]{1,40}?) is\s+[^\n.!?]{2,100}/giu],- // Quantitative family (t_220c313e): actor + measured action +- // numeric value (+ unit). First-person framed like every family -- // bare numbers without an actor never extract.- [- "quantity",- /\b(?:I|we)\s+(?:spent|paid|earned|saved|billed|ran|completed|logged|worked|shipped)\s+\$?\d+(?:\.\d+)?(?:\s+[a-z][\w-]{0,23})?[^\n.!?]{0,80}/giu,- ],-] as const);+// ----- Quantity structuring (t_220c313e; language-agnostic in t_80cbefa1) -----// ----- Quantity structuring (t_220c313e) -------------------------------------+// A number tied to a language-neutral unit: a leading currency glyph, or a+// trailing percent sign or ISO-4217-style 3-letter code. The English action+// verbs and grammar stop-word list that used to frame this were removed.+//+// The trailing-unit branch is anchored with `(?<![\d.])` so a match can only+// begin at the start of a number, never mid-run. Without it, a long digit run+// lets the engine retry the greedy `\d+` at every interior offset (each retry+// backtracks the whole run before failing the unit assertion), which is+// quadratic on untrusted input - extractFacts runs on raw user turns.+const QUANTITY_SPAN_RE = /([$€£¥])\d+(?:\.\d+)?|(?<![\d.])\d+(?:\.\d+)?\s?(%|[A-Z]{3}\b)/gu;-/** Words after a number that are grammar, not a measurement unit. */-const QUANTITY_UNIT_STOPWORDS = new Set([- "on",- "for",- "in",- "to",- "at",- "of",- "per",- "last",- "this",- "the",- "a",- "an",-]);+// Currency glyph -> canonical ISO-4217 code. These are standardised symbols,+// not natural-language words, so the map is language-neutral.+const CURRENCY_SYMBOLS: Readonly<Record<string, string>> = Object.freeze({+ $: "usd",+ "€": "eur",+ "£": "gbp",+ "¥": "jpy",+});-const QUANTITY_SPAN_RE =- /\b(spent|paid|earned|saved|billed|ran|completed|logged|worked|shipped)\s+(\$)?(\d+(?:\.\d+)?)(?:\s+([a-zA-Z][\w-]{0,23}))?/iu;+// Family patterns. Each regex is line-scoped (callers split lines) and+// recognises a language-neutral structural signal only - no human-language+// trigger words. Quantity must carry an explicit unit symbol (currency+// glyph, ISO-4217 code, or percent) so arbitrary numbers never match.+const FAMILY_PATTERNS: ReadonlyArray<readonly [FactFamily, RegExp]> = Object.freeze([+ ["url", /\bhttps?:\/\/[^\s)>\]]+/giu],+ ["email", /\b[\w.+-]+@[\w.-]+\.\w{2,}\b/giu],+ ["quantity", QUANTITY_SPAN_RE],+] as const);export interface ParsedQuantityFact {- /** Measured action, lowercased (`spent`, `ran`, ...). */- readonly action: string;readonly value: number;- /** Canonical unit token or null when unitless. */- readonly unit: string | null;+ /** Canonical unit token (`usd`, `eur`, `percent`, lowercased ISO code). */+ readonly unit: string;}/**- * Structure a quantity span into (action, value, unit). A `$` prefix- * normalizes to `usd`; a stop-word after the number ("paid 42 for…")- * leaves the unit null. Returns null when the text carries no- * actor-framed quantity - the caller treats that as "not a quantity".+ * Structure a quantity span into (value, unit). A leading currency glyph+ * maps to its ISO code; a trailing `%` normalizes to `percent`; a trailing+ * 3-letter code lowercases to the unit. Returns null when the text carries+ * no unit-bound number - the caller treats that as "not a quantity".*/export function parseQuantityFact(text: string): ParsedQuantityFact | null {if (!text || text.trim() === "") return null;- const m = QUANTITY_SPAN_RE.exec(text);+ const re = new RegExp(QUANTITY_SPAN_RE.source, "u");+ const m = re.exec(text);if (m === null) return null;- const action = m[1]!.toLowerCase();- const value = Number(m[3]!);+ const value = Number(m[0].replace(/[^\d.]/g, ""));if (!Number.isFinite(value)) return null;- let unit: string | null = null;- if (m[2] === "$") {- unit = "usd";- } else if (m[4] !== undefined) {- const word = m[4].toLowerCase();- unit = QUANTITY_UNIT_STOPWORDS.has(word) ? null : word;+ let unit: string;+ if (m[1] !== undefined) {+ unit = CURRENCY_SYMBOLS[m[1]] ?? m[1];+ } else if (m[2] === "%") {+ unit = "percent";+ } else {+ unit = m[2]!.toLowerCase();}- return Object.freeze({ action, value, unit });+ return Object.freeze({ value, unit });}/** Strip fenced code blocks, inline code, and quoted lines. */@@ -164,22 +138,28 @@ export function extractFacts(text: string): ExtractedFact[] {const seenSpans = new Set<string>();for (let i = 0; i < lines.length; i++) {- const line = lines[i]!;- if (line.trim().length === 0) continue;+ const raw = lines[i]!;+ if (raw.trim().length === 0) continue;+ const line = raw.length > MAX_LINE_SCAN_CHARS ? raw.slice(0, MAX_LINE_SCAN_CHARS) : raw;+ // URLs are matched first (family-table order); their character ranges are+ // recorded so the email and quantity passes never re-read inside a URL -+ // a `user:pass@host` userinfo is not an e-mail, and a `?n=50USD` query is+ // not a measured quantity.+ const urlRanges: Array<readonly [number, number]> = [];for (const [family, pattern] of FAMILY_PATTERNS) {pattern.lastIndex = 0;for (const m of line.matchAll(pattern)) {- if (family === "possession") {- const key = m[1]?.trim().toLowerCase() ?? "";- if (POSSESSION_KEY_BLOCKLIST.has(key)) continue;- }+ const start = m.index ?? 0;+ const end = start + m[0]!.length;+ if (family !== "url" && urlRanges.some(([s, e]) => start < e && end > s)) continue;const span = collapse(m[0]!);- if (span.length < 5) continue;+ if (span.length === 0) continue;// NUL separator cannot collide with sanitised span text; written// as an escape so the file stays text-diffable.const spanKey = `${family}\u0000${span.toLowerCase()}`;if (seenSpans.has(spanKey)) continue;seenSpans.add(spanKey);+ if (family === "url") urlRanges.push([start, end] as const);out.push(Object.freeze({ family, text: span, line: i + 1 }));}}diff --git a/src/core/brain/truth/aggregate.ts b/src/core/brain/truth/aggregate.tsindex 528af609..ccb0dfa1 100644--- a/src/core/brain/truth/aggregate.ts+++ b/src/core/brain/truth/aggregate.ts@@ -1,10 +1,15 @@/**- * Exact-match quantity aggregation (t_220c313e): "how much did I- * spend" answers combine ONLY values whose (entity, action, unit)- * tuple matches the query exactly after canonical normalization. A- * number that is merely nearby - a different unit, a different- * measured action, a text-kind slot - never pollutes a total. That- * structural exactness is the whole feature.+ * Exact-match quantity aggregation (t_220c313e): "how much" answers+ * combine ONLY values whose (entity, unit) tuple matches the query+ * exactly after canonical normalization, optionally narrowed to a+ * measured action. A number that is merely nearby - a different unit,+ * a text-kind slot - never pollutes a total. That structural exactness+ * is the whole feature.+ *+ * `action` is optional: it is no longer derived from prose (it used to+ * be an English verb), so by default a query aggregates across every+ * action for the entity+unit. A caller with an explicitly labelled+ * action can still narrow to it.*/import { normalizeEntityName } from "../entities/canonical.ts";@@ -13,8 +18,8 @@ import type { ClaimSlot } from "./types.ts";export interface AggregateQuery {/** Optional entity filter; omitted means every entity combines. */readonly entity?: string;- /** Measured action, exact match after normalization. */- readonly action: string;+ /** Optional measured action; omitted aggregates across all actions. */+ readonly action?: string;/** Unit token; null matches only unitless quantities. */readonly unit: string | null;}@@ -28,7 +33,8 @@ export interface AggregateContribution {}export interface AggregateResult {- readonly action: string;+ /** The action filter applied, or null when the query did not narrow by one. */+ readonly action: string | null;readonly unit: string | null;readonly total: number;readonly count: number;@@ -51,7 +57,7 @@ export function aggregateQuantities(query: AggregateQuery,): AggregateResult {const wantEntity = query.entity !== undefined ? normalizeEntityName(query.entity) : null;- const wantAction = normalizeEntityName(query.action);+ const wantAction = query.action !== undefined ? normalizeEntityName(query.action) : null;const wantUnit = normalizeUnit(query.unit);const contributions: AggregateContribution[] = [];@@ -60,7 +66,14 @@ export function aggregateQuantities(const current = slot.current;if (current.valueKind !== "quantity" || current.quantity === undefined) continue;const q = current.quantity;- if (q.action === null || normalizeEntityName(q.action) !== wantAction) continue;+ // Narrow by action only when the query asked for one; otherwise every+ // action (including the null actions extraction now produces) combines.+ if (+ wantAction !== null &&+ (q.action === null || normalizeEntityName(q.action) !== wantAction)+ ) {+ continue;+ }if (normalizeUnit(q.unit) !== wantUnit) continue;contributions.push(Object.freeze({diff --git a/src/core/brain/truth/ingest.ts b/src/core/brain/truth/ingest.tsindex 9ec6807f..ceddea93 100644--- a/src/core/brain/truth/ingest.ts+++ b/src/core/brain/truth/ingest.ts@@ -32,19 +32,16 @@ interface FamilyStructurer {readonly group: number;}-// Deterministic value structurers for the families with a clean-// (aspect, value) shape. Preference/confirmation spans carry no-// addressable aspect and never ingest.+// Deterministic value structurers for the structural fact families.+// Each regex is language-neutral (a bare e-mail / URL shape) - no+// human-language trigger words. The English-framed structurers (name,+// "called", "based in") and the "my X is Y" possession regex were+// removed in t_80cbefa1; we cannot enumerate the world's languages.const STRUCTURERS: ReadonlyArray<FamilyStructurer> = Object.freeze([- { re: /\bmy name is\s+([^\n.!?]{2,80})/iu, aspect: "name", group: 1 },- { re: /\bI(?:'m| am) called\s+([^\n.!?]{2,80})/u, aspect: "name", group: 1 },- { re: /\b(?:live|'m based|am based) in\s+([^\n.!?]{2,80})/iu, aspect: "location", group: 1 },{ re: /\b([\w.+-]+@[\w.-]+\.\w{2,})\b/u, aspect: "email", group: 1 },{ re: /\b(https?:\/\/[^\s)>\]]+)/u, aspect: "website", group: 1 },]);-const POSSESSION_RE = /\bmy ([a-z][\w -]{1,40}?) is\s+([^\n.!?]{2,100})/iu;-/*** Derive claim inputs from one assertion's facts. Quantity facts use* the normalized assertion text as the aspect, so re-ingesting the@@ -68,20 +65,11 @@ export function claimsFromAssertion(aspect: normalizeClaimValue(fact.text).slice(0, MAX_ASPECT_CHARS),value: String(quantity.value),valueKind: "quantity",- quantity: { value: quantity.value, unit: quantity.unit, action: quantity.action },- source: input.source,- });- continue;- }- if (fact.family === "possession") {- const m = POSSESSION_RE.exec(fact.text);- if (m === null) continue;- out.push({- ts: input.ts,- agent: input.agent,- entity: input.entity,- aspect: m[1]!.trim().toLowerCase(),- value: m[2]!.trim(),+ // `action` is no longer derived: it used to be an English verb+ // ("spent", "ran", ...). Quantities now aggregate by unit. The+ // ledger column stays nullable for back-compat and a future+ // explicit-label source.+ quantity: { value: quantity.value, unit: quantity.unit, action: null },source: input.source,});continue;diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 730899da..b7f05b1c 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -2722,7 +2722,7 @@ function toolBrainTruth(const state = computeTruthStateWithConflicts(events);return {...aggregateQuantities(state.slots, {- action: requireStr("action"),+ ...(typeof args["action"] === "string" ? { action: args["action"] as string } : {}),unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),}),diff --git a/tests/core/brain/fact-extract.test.ts b/tests/core/brain/fact-extract.test.tsindex 5a9e6003..8d69a1a8 100644--- a/tests/core/brain/fact-extract.test.ts+++ b/tests/core/brain/fact-extract.test.ts@@ -1,11 +1,11 @@/**- * Regex fact extraction (Memory Integrity Suite, t_d0782ab2).- *- * Seven precision-first pattern families over USER turn text:- * identity, preference, possession, location, url, email,- * confirmation. Deterministic - no LLM, no clock. Negative fixtures- * pin the precision contract: code blocks, quoted lines, and- * assistant-shaped prose never extract.+ * Structural fact extraction. After the language-agnostic refactor the+ * extractor keeps only families detectable WITHOUT knowing any human+ * language: url, email, quantity (a number bound to a currency symbol,+ * an ISO-4217 code, or percent). Prose families that needed an English+ * frame (identity, preference, possession, location, confirmation) are+ * gone. Negative fixtures pin precision: code blocks, quoted lines, and+ * bare numbers never extract.*/import { describe, expect, test } from "bun:test";@@ -16,101 +16,108 @@ function families(text: string): string[] {return extractFacts(text).map((f) => f.family);}-describe("extractFacts - positive fixtures", () => {- test("identity: my name is ...", () => {- const out = extractFacts("Hi, my name is Ada Lovelace and I work on the vault.");- expect(out.some((f) => f.family === "identity" && f.text.includes("Ada Lovelace"))).toBe(true);- });-- test("preference: I prefer / I always use", () => {- const out = extractFacts("For diagrams I prefer the vintage blueprint style.");- expect(out.some((f) => f.family === "preference")).toBe(true);- const out2 = extractFacts("I always use bun for this repository.");- expect(out2.some((f) => f.family === "preference")).toBe(true);- });-- test("possession: my <thing> is <value>", () => {- const out = extractFacts("my editor is Neovim with a custom config");- expect(out.some((f) => f.family === "possession" && f.text.includes("Neovim"))).toBe(true);- });-- test("location: I live in / I am based in", () => {- const out = extractFacts("These days I live in Lisbon most of the year.");- expect(out.some((f) => f.family === "location" && f.text.includes("Lisbon"))).toBe(true);- });-- test("url: possessively introduced site", () => {- const out = extractFacts("my blog is https://techmeat.dev and it runs on a static site");- expect(out.some((f) => f.family === "url" && f.text.includes("https://techmeat.dev"))).toBe(+describe("extractFacts - structural families (language-neutral)", () => {+ test("url: a bare URL extracts regardless of surrounding language", () => {+ const en = extractFacts("see the writeup at https://techmeat.dev/post for details");+ expect(en.some((f) => f.family === "url" && f.text.includes("https://techmeat.dev/post"))).toBe(+ true,+ );+ // Non-Latin wrapper: same structural signal, same extraction.+ const ru = extractFacts("мой сайт https://techmeat.dev живёт на статике");+ expect(ru.some((f) => f.family === "url" && f.text.includes("https://techmeat.dev"))).toBe(true,);});- test("email: my email is ...", () => {- const out = extractFacts("my email is [email protected] for anything urgent");- expect(out.some((f) => f.family === "email" && f.text.includes("[email protected]"))).toBe(true);+ test("email: a bare address extracts regardless of surrounding language", () => {+ const en = extractFacts("ping [email protected] for anything urgent");+ expect(en.some((f) => f.family === "email" && f.text.includes("[email protected]"))).toBe(true);+ const jp = extractFacts("連絡先は [email protected] です");+ expect(jp.some((f) => f.family === "email" && f.text.includes("[email protected]"))).toBe(true);});- test("confirmation: yes, the X is Y", () => {- const out = extractFacts("Correct, the production vault is on the VPS at /srv/vault.");- expect(out.some((f) => f.family === "confirmation")).toBe(true);+ test("quantity: currency symbol, ISO code, and percent extract", () => {+ expect(families("the invoice was $1200 this month")).toContain("quantity");+ expect(families("стоимость проекта составила $1200")).toContain("quantity");+ expect(families("budget is 3.5 USD per call")).toContain("quantity");+ expect(families("conversion improved to 50% last week")).toContain("quantity");});});describe("extractFacts - precision (negative fixtures)", () => {- test("plain assistant-shaped prose extracts nothing", () => {- expect(- families(- "The function resolves the vault path and returns the merged entries sorted by timestamp.",- ),- ).toEqual([]);+ test("English prose frames no longer extract (families removed)", () => {+ expect(families("Hi, my name is Ada Lovelace and I work here")).toEqual([]);+ expect(families("For diagrams I prefer the blueprint style")).toEqual([]);+ expect(families("my editor is Neovim with a custom config")).toEqual([]);+ expect(families("These days I live in Lisbon")).toEqual([]);+ expect(families("Correct, the production vault is on the VPS")).toEqual([]);+ });++ test("bare numbers without a unit never extract", () => {+ expect(families("we shipped 42 items and ran 7 jobs")).toEqual([]);+ expect(families("version 3 of the api")).toEqual([]);});test("code blocks never extract", () => {const text = ["Try this:","```ts",- 'const x = "my name is Bob";',- "// I prefer tabs",+ 'const url = "https://x.dev";',+ "const n = 50;","```",].join("\n");expect(families(text)).toEqual([]);});test("quoted lines never extract", () => {- expect(families("> my name is Bob, said the old book")).toEqual([]);+ expect(families("> reach me at [email protected], said the old book")).toEqual([]);+ });++ test("empty and whitespace input", () => {+ expect(extractFacts("")).toEqual([]);+ expect(extractFacts(" \n ")).toEqual([]);});+});- test("bare URLs without a possessive introduction never extract", () => {- expect(families("see https://example.com/docs for details")).toEqual([]);+describe("extractFacts - hardening", () => {+ test("a long digit run does not blow up (no quadratic backtracking)", () => {+ const huge = "note " + "1".repeat(100_000);+ const start = performance.now();+ const out = extractFacts(huge);+ const elapsedMs = performance.now() - start;+ // No unit symbol -> not a quantity; and it must finish fast, not hang.+ expect(out.filter((f) => f.family === "quantity")).toHaveLength(0);+ expect(elapsedMs).toBeLessThan(2000);});- test("bare 'yes' without a restated fact never extracts", () => {- expect(families("yes")).toEqual([]);- expect(families("yes, please do that now")).toEqual([]);+ test("a URL's userinfo is not extracted as a phantom email", () => {+ const out = extractFacts("login at https://user:[email protected]/path");+ expect(out.some((f) => f.family === "url")).toBe(true);+ expect(out.some((f) => f.family === "email")).toBe(false);});- test("empty and whitespace input", () => {- expect(extractFacts("")).toEqual([]);- expect(extractFacts(" \n ")).toEqual([]);+ test("a number inside a URL is not extracted as a phantom quantity", () => {+ const out = extractFacts("open https://x.dev/p?q=foo&n=50USD now");+ expect(out.some((f) => f.family === "url")).toBe(true);+ expect(out.some((f) => f.family === "quantity")).toBe(false);});});describe("fact dedup hashing", () => {test("same fact hashes identically across whitespace and case variants", () => {- const a = extractFacts("my name is Ada")[0]!;- const b = extractFacts("My name is ada")[0]!;+ const a = extractFacts("ping [email protected] now")[0]!;+ const b = extractFacts("ping [email protected] now")[0]!;expect(factDedupHash(a)).toBe(factDedupHash(b));});test("different families never collide on the same text", () => {- const id = extractFacts("my name is Lisbon")[0]!;- const loc = extractFacts("I live in Lisbon")[0]!;- expect(factDedupHash(id)).not.toBe(factDedupHash(loc));+ const url = { family: "url" as const, text: "https://x.dev", line: 1 };+ const email = { family: "email" as const, text: "https://x.dev", line: 1 };+ expect(factDedupHash(url)).not.toBe(factDedupHash(email));});test("extraction is deterministic", () => {- const text = "my name is Ada. I prefer dark themes. my email is [email protected]";+ const text = "site https://x.dev, mail [email protected], cost $5";expect(extractFacts(text)).toEqual(extractFacts(text));});});diff --git a/tests/core/brain/import-session.boundary.test.ts b/tests/core/brain/import-session.boundary.test.tsindex 5032ae4c..4a55b24f 100644--- a/tests/core/brain/import-session.boundary.test.ts+++ b/tests/core/brain/import-session.boundary.test.ts@@ -65,7 +65,7 @@ function writeClaudeSession(name: string, userTexts: string[]): string {describe("session-level boundary at import", () => {test("a file matching an ignore glob imports nothing", async () => {setSessionsPolicy(["sessions:", " ignore_patterns:", ' - "*cron-export*"']);- const path = writeClaudeSession("cron-export-1.jsonl", ["my name is Ada"]);+ const path = writeClaudeSession("cron-export-1.jsonl", ["ping [email protected]"]);const result = await importSession(vault, path, {agent: "tester",now: NOW,@@ -80,7 +80,7 @@ describe("session-level boundary at import", () => {test("a stateless file scans but writes nothing", async () => {setSessionsPolicy(["sessions:", " stateless_patterns:", ' - "*probe*"']);- const path = writeClaudeSession("probe-2.jsonl", ["my name is Ada"]);+ const path = writeClaudeSession("probe-2.jsonl", ["ping [email protected]"]);const result = await importSession(vault, path, {agent: "tester",now: NOW,@@ -97,8 +97,8 @@ describe("message-level boundary at import", () => {test("suppressed turns never reach marker or fact extraction", async () => {setSessionsPolicy(["sessions:", " ignore_message_patterns:", ' - "^\\[heartbeat\\]"']);const path = writeClaudeSession("normal.jsonl", [- "[heartbeat] my name is Ada",- "I prefer dark themes",+ "[heartbeat] ping [email protected]",+ "the project site is https://techmeat.dev",]);const result = await importSession(vault, path, {agent: "tester",@@ -107,16 +107,17 @@ describe("message-level boundary at import", () => {});expect(result.boundary_decision).toBe("capture");expect(result.suppressed_turns).toBe(1);- expect(result.facts_extracted).toBe(1); // only the preference fact+ expect(result.facts_extracted).toBe(1); // only the non-suppressed url factconst names = inboxSignals();- expect(names.some((n) => n.includes("fact-identity"))).toBe(false);- expect(names.some((n) => n.includes("fact-preference"))).toBe(true);+ // the suppressed heartbeat turn never reaches extraction+ expect(names.some((n) => n.includes("fact-email"))).toBe(false);+ expect(names.some((n) => n.includes("fact-url"))).toBe(true);});});describe("fact extraction at import", () => {test("user-turn facts import with dedup across re-imports", async () => {- const path = writeClaudeSession("facts.jsonl", ["my email is [email protected]"]);+ const path = writeClaudeSession("facts.jsonl", ["contact [email protected]"]);const first = await importSession(vault, path, { agent: "tester", now: NOW, format: "claude" });expect(first.facts_extracted).toBe(1);const second = await importSession(vault, path, {diff --git a/tests/core/brain/quantity-facts.test.ts b/tests/core/brain/quantity-facts.test.tsindex b3fe8def..d6b1c064 100644--- a/tests/core/brain/quantity-facts.test.ts+++ b/tests/core/brain/quantity-facts.test.ts@@ -1,9 +1,9 @@/**- * Quantitative fact family (t_220c313e): first-person framed numeric- * facts (actor + measured action + value + unit) join the extraction- * families, with a deterministic structurer that turns a captured- * span into a typed quantity. Precision-first like every other- * family: bare numbers without an actor frame never extract.+ * Quantity family (t_220c313e; language-agnostic in t_80cbefa1). A+ * quantity is a number bound to a language-neutral unit symbol: a+ * leading currency glyph, a trailing ISO-4217 code, or a percent sign.+ * The English actor/action frame and grammar stop-word list were+ * removed. Precision-first: a bare number with no unit never extracts.*/import { describe, expect, test } from "bun:test";@@ -11,69 +11,53 @@ import { describe, expect, test } from "bun:test";import { extractFacts, parseQuantityFact } from "../../../src/core/brain/fact-extract.ts";describe("extractFacts quantity family", () => {- test("first-person spend extracts as a quantity fact", () => {- const facts = extractFacts("I spent 120 USD on hosting last month.");- const quantity = facts.filter((f) => f.family === "quantity");- expect(quantity).toHaveLength(1);- expect(quantity[0]!.text).toContain("spent 120 USD on hosting");- });-- test("first-person counts and durations extract", () => {- const ran = extractFacts("We ran 3 deployments this week.");- expect(ran.some((f) => f.family === "quantity")).toBe(true);- const worked = extractFacts("I worked 6.5 hours on the migration.");- expect(worked.some((f) => f.family === "quantity")).toBe(true);- });-- test("bare numbers without an actor frame never extract", () => {- const facts = extractFacts("There are 3 ways to deploy. The build takes 12 minutes.");- expect(facts.filter((f) => f.family === "quantity")).toHaveLength(0);- });-- test("existing families keep extracting unchanged", () => {- const facts = extractFacts("My name is Ada Lovelace. I prefer tabs over spaces.");- expect(facts.some((f) => f.family === "identity")).toBe(true);- expect(facts.some((f) => f.family === "preference")).toBe(true);+ test("unit-bound amounts extract regardless of surrounding language", () => {+ expect(extractFacts("hosting cost $120 last month").some((f) => f.family === "quantity")).toBe(+ true,+ );+ expect(+ extractFacts("стоимость хостинга составила $120").some((f) => f.family === "quantity"),+ ).toBe(true);+ expect(extractFacts("budget is 3.5 USD per call").some((f) => f.family === "quantity")).toBe(+ true,+ );+ expect(extractFacts("conversion hit 50% this week").some((f) => f.family === "quantity")).toBe(+ true,+ );+ });++ test("bare numbers with no unit never extract", () => {+ expect(+ extractFacts("There are 3 ways to deploy. The build takes 12 minutes.").filter(+ (f) => f.family === "quantity",+ ),+ ).toHaveLength(0);+ // English action verbs no longer frame a quantity.+ expect(+ extractFacts("I spent 120 on hosting and ran 3 jobs").filter((f) => f.family === "quantity"),+ ).toHaveLength(0);});});describe("parseQuantityFact", () => {- test("structures action, value, and unit", () => {- expect(parseQuantityFact("I spent 120 USD on hosting")).toEqual({- action: "spent",- value: 120,- unit: "usd",- });- expect(parseQuantityFact("We ran 3 deployments this week")).toEqual({- action: "ran",- value: 3,- unit: "deployments",- });- expect(parseQuantityFact("I worked 6.5 hours on the migration")).toEqual({- action: "worked",- value: 6.5,- unit: "hours",- });+ test("leading currency glyph maps to its ISO code", () => {+ expect(parseQuantityFact("paid $42 for the domain")).toEqual({ value: 42, unit: "usd" });+ expect(parseQuantityFact("€50 budget")).toEqual({ value: 50, unit: "eur" });+ expect(parseQuantityFact("£9.99 plan")).toEqual({ value: 9.99, unit: "gbp" });+ expect(parseQuantityFact("¥1000 fee")).toEqual({ value: 1000, unit: "jpy" });});- test("dollar sign normalizes to usd", () => {- expect(parseQuantityFact("I paid $42 for the domain")).toEqual({- action: "paid",- value: 42,- unit: "usd",- });+ test("trailing ISO code lowercases to the unit", () => {+ expect(parseQuantityFact("budget is 3.5 USD per call")).toEqual({ value: 3.5, unit: "usd" });});- test("stop-words after the number leave the unit null", () => {- expect(parseQuantityFact("I paid 42 for the domain")).toEqual({- action: "paid",- value: 42,- unit: null,- });+ test("percent normalizes to percent", () => {+ expect(parseQuantityFact("up 50% this week")).toEqual({ value: 50, unit: "percent" });});- test("non-quantity text parses to null", () => {- expect(parseQuantityFact("I prefer tabs over spaces")).toBeNull();+ test("a number with no unit symbol parses to null", () => {+ expect(parseQuantityFact("I paid 42 for the domain")).toBeNull();+ expect(parseQuantityFact("there are 3 ways")).toBeNull();expect(parseQuantityFact("")).toBeNull();});});diff --git a/tests/core/brain/session-lifecycle.boundary.test.ts b/tests/core/brain/session-lifecycle.boundary.test.tsindex b57cabcb..9ea2f9c2 100644--- a/tests/core/brain/session-lifecycle.boundary.test.ts+++ b/tests/core/brain/session-lifecycle.boundary.test.ts@@ -116,7 +116,7 @@ describe("fact extraction at the live seam", () => {const payload = {hook_event_name: "UserPromptSubmit",session_id: "s1",- prompt: "By the way, my name is Ada and I prefer dark themes.",+ prompt: "By the way, reach me at [email protected] and the repo is https://techmeat.dev.",};const first = await captureSessionLifecycleEvent(vault, payload, {agent: "tester",@@ -125,8 +125,8 @@ describe("fact extraction at the live seam", () => {expect(first.facts_extracted).toBe(2);expect(first.facts_deduped).toBe(0);const names = inboxSignals();- expect(names.some((n) => n.includes("fact-identity"))).toBe(true);- expect(names.some((n) => n.includes("fact-preference"))).toBe(true);+ expect(names.some((n) => n.includes("fact-email"))).toBe(true);+ expect(names.some((n) => n.includes("fact-url"))).toBe(true);const second = await captureSessionLifecycleEvent(vault, payload, {agent: "tester",@@ -139,20 +139,25 @@ describe("fact extraction at the live seam", () => {test("extracted signals carry source_type extracted", async () => {await captureSessionLifecycleEvent(vault,- { hook_event_name: "UserPromptSubmit", session_id: "s1", prompt: "my name is Ada" },+ {+ hook_event_name: "UserPromptSubmit",+ session_id: "s1",+ prompt: "reach me at [email protected]",+ },{ agent: "tester", now: NOW },);- const name = inboxSignals().find((n) => n.includes("fact-identity"))!;+ const name = inboxSignals().find((n) => n.includes("fact-email"))!;const sig = parseSignal(join(brainDirs(vault).inbox, name));expect(sig.source_type).toBe("extracted");- expect(sig.principle).toContain("Ada");+ expect(sig.principle).toContain("[email protected]");});test("a fact naming a registered entity gets the canonical anchor", async () => {+ // The entity name must appear inside the structural fact's own text; a+ // URL host carries it without any natural-language framing.upsertEntity(vault, {category: "projects",- name: "Open Second Brain",- aliases: ["the vault project"],+ name: "techmeat",agent: "tester",now: NOW,});@@ -161,13 +166,13 @@ describe("fact extraction at the live seam", () => {{hook_event_name: "UserPromptSubmit",session_id: "s1",- prompt: "I prefer the vault project release diagrams in blueprint style",+ prompt: "the project site is https://techmeat.dev/blog",},{ agent: "tester", now: NOW },);- const name = inboxSignals().find((n) => n.includes("fact-preference"))!;+ const name = inboxSignals().find((n) => n.includes("fact-url"))!;const raw = readFileSync(join(brainDirs(vault).inbox, name), "utf8");- expect(raw).toContain("ent-projects-open-second-brain");+ expect(raw).toContain("ent-projects-techmeat");});test("assistant-shaped events without prompt text extract nothing", async () => {diff --git a/tests/e2e/entity-truth-dream.integration.test.ts b/tests/e2e/entity-truth-dream.integration.test.tsindex a7bdde60..70683ded 100644--- a/tests/e2e/entity-truth-dream.integration.test.ts+++ b/tests/e2e/entity-truth-dream.integration.test.ts@@ -100,9 +100,10 @@ test("the suite composes end to end on one vault", async () => {expect(state.conflicts).toHaveLength(1);expect(state.conflicts[0]!.resolution).toBe("ask_user");+ // Action is no longer derived from prose; quantities aggregate by+ // entity + unit. Both "$120"/"42 USD"-shaped spends combine here.const spend = aggregateQuantities(state.slots, {entity: "operator",- action: "spent",unit: "usd",});expect(spend.total).toBe(162);