Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

Feat/self learning skill proposals (#57)

Sol Aitken1f3a218d551f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 44078698..cc3f06e3 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.29.0",
+ "version": "0.30.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.json
index 510b6bbf..c314866d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.29.0",
+ "version": "0.30.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.md
index 924492c3..c6227add 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,31 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.30.0] - 2026-06-01
+
+Self-learning procedural memory foundations. Open Second Brain can now detect repeatable workflows from continuity records, route them through a reviewable proposal queue, index procedural artifacts, and track recurrence/support evidence across scopes.
+
+### Added
+
+- Deterministic skill-proposal learning core (`repeated_action`, `structural_similarity`, `co_occurrence`, `temporal_routine`) with watermark tracking and duplicate suppression.
+- Proposal review lifecycle in core: accept/reject transitions, review notes, and accepted procedure artifact emission under `Brain/procedures/`.
+- Procedural memory reconciler with stable entry IDs, frontmatter metadata parsing, stale-entry pruning, and usage sidecar updates without rewriting source files.
+- Recurrence/support ledger with same-scope support increments, cross-scope recurrence evidence, threshold-based commitment diagnostics, and reference-counted forget/source purge behavior.
+- New Brain CLI verbs for the procedural-learning workflow:
+ - `o2b brain skill-proposals <learn|list|accept|reject>`
+ - `o2b brain procedural-memory <reconcile|list|mark-used>`
+ - `o2b brain recurrence <list|show|learn|forget|purge-source>`
+
+### Changed
+
+- Brain path contracts now include dedicated procedural-learning artifacts (`Brain/skill-proposals/*`, `Brain/procedures/`, `Brain/procedural-memory/*`, and recurrence ledger path helpers).
+- CLI help/verb registry now exposes procedural-learning surfaces in `o2b brain --help` and per-verb help.
+
+### Notes
+
+- Existing formatter-only baseline warnings remain warning-only (`oxlint`: 110 warnings, 0 errors).
+- Proposal learning and recurrence flows are deterministic and local-first by default; no network calls are required.
+
## [0.29.0] - 2026-05-31
Context continuity and receipt surfaces. Agent-facing context can now leave redacted receipts and telemetry behind, operators can inspect budget presets before applying them, and session transcripts can be imported into a continuity-backed recall DAG.
@@ -2310,7 +2335,7 @@ with `source_type: inline`, the source-file wikilink in `source`,
and a `dedup_hash`over the normalised payload. After capture
the source line is annotated`@osb✓ [[sig-...]]`(inline form)
or the info-string flips to`osb-checked`with a`<!-- @osb✓
- [[sig-...]] -->`comment line (block form), making re-runs
+ [[sig-...]] -->`comment line (block form), making re-runs
idempotent. Default ignore set covers`Brain/`, `.git`,
`node_modules`, `.obsidian`, `.trash`, `.stversions`,
`.open-second-brain`; additional excludes via `--exclude`,
@@ -3656,6 +3681,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.30.0]: https://github.com/itechmeat/open-second-brain/compare/v0.29.0...v0.30.0
[0.29.0]: https://github.com/itechmeat/open-second-brain/compare/v0.28.0...v0.29.0
[0.28.0]: https://github.com/itechmeat/open-second-brain/compare/v0.27.0...v0.28.0
[0.27.0]: https://github.com/itechmeat/open-second-brain/compare/v0.26.0...v0.27.0
diff --git a/docs/brainstorm/self-learning-skill-proposals/cli-output/claude.md b/docs/brainstorm/self-learning-skill-proposals/cli-output/claude.md
new file mode 100644
index 00000000..189d86d5
--- /dev/null
+++ b/docs/brainstorm/self-learning-skill-proposals/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Three Parallel Queue Modules (file-first, dream-adjacent)
+- **Approach**: Implement each board task as its own self-contained core module with its own artifact and CLI verb group, sharing only existing primitives (`log-jsonl` reader, `paths`, `types`). Skill proposals land in a new `Brain/proposals/` queue, the procedural index as a sidecar under `Brain/skills-index/`, and recurrence/reference counters as frontmatter fields on existing Brain entries. Each exposes an opt-in scan command that borrows the `dream` watermark pattern without modifying `dream` itself.
+- **Trade-offs**:
+ - Pro: Clean separation maps 1:1 to the three acceptance-criteria sets and their test suites; each ships and is reviewed independently.
+ - Pro: Zero regression risk to the existing preference-learning `dream` path; honors "companion workflow, not replacement."
+ - Pro: Smallest coherent first slice; easy to defer any one task without blocking the others.
+ - Con: Three watermark/scan loops mean some duplicated scan scaffolding (mitigated by a shared helper, not a shared engine).
+ - Con: Leaves synergy on the table — recurrence support counts do not automatically feed proposal confidence in the first slice.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Unified Procedural-Knowledge Engine with Shared Recurrence Ledger
+- **Approach**: Build one new subsystem centered on a content-hash recurrence ledger that becomes the common substrate for all three concerns. Skill proposals become derived views whose confidence is supplied by ledger support counts, installed skills become graph nodes in the same store carrying usage and recurrence counters, and scope-promotion/commitment escalation is one set of thresholded logic applied uniformly across preferences, proposals, and skills. A single scan and single watermark drive everything.
+- **Trade-offs**:
+ - Pro: Maximal reuse and a single source of truth for support/recurrence/confidence; strongest "the brain learns how it works" payoff.
+ - Pro: Cross-scope promotion naturally lifts proposals and procedural entries, not just preferences.
+ - Con: Large surface area; the three upstreams have genuinely different data shapes forced into one model, fighting KISS.
+ - Con: High coupling makes a coherent first slice hard to scope and a partial ship hard to test in isolation.
+ - Con: Highest regression and design-churn risk for an initial release.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Dream-Pipeline Phase Extension + Thin Review CLIs
+- **Approach**: Add three new deterministic phases to the existing multi-phase `dream` pass — proposal detection, procedural reconciliation, and recurrence/reference accounting — each emitting Brain artifacts with audit-log entries alongside the current preference promotion. Accept/reject/promote actions are handled by thin CLI and read/diagnostic MCP verbs layered over those artifacts, giving the operator one learning cadence.
+- **Trade-offs**:
+ - Pro: Reuses watermark, batch orchestration, audit-log, and scheduling infra; strong DRY.
+ - Pro: One operator mental model and one scheduled pass; preview-first falls out naturally from `dream`'s dry-run.
+ - Con: Meaningfully grows `dream` and couples three independent concerns to one scheduler cadence, risking regression to the protected preference path.
+ - Con: Per-task test isolation is harder when all phases share one pipeline entry point.
+ - Con: Procedural reconciliation (filesystem-driven, not journal-driven) is an awkward fit for a journal-watermark pipeline.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: The three tasks are distinct upstreams with different data shapes (journal-scanned proposals, filesystem-reconciled skills, hash-counted recurrence), so parallel modules respect KISS/SOLID far better than forcing a unified engine (Variant 2) and isolate each acceptance/test suite cleanly. It also fully preserves the protected `dream` preference path, which Variant 3 puts at regression risk by overloading one pipeline. A shared watermark helper covers the DRY concern, and the deferred synergy (recurrence feeding proposal confidence) is a natural Variant-2-style consolidation to pursue once all three modules exist and have proven their shapes in production.
diff --git a/docs/brainstorm/self-learning-skill-proposals/cli-output/prompt.md b/docs/brainstorm/self-learning-skill-proposals/cli-output/prompt.md
new file mode 100644
index 00000000..9c14551d
--- /dev/null
+++ b/docs/brainstorm/self-learning-skill-proposals/cli-output/prompt.md
@@ -0,0 +1,118 @@
+You are brainstorming architectural variants for the following multi-task feature release. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+## Scope
+
+Implement the Self-Learning Skill Proposal Queue scope for Open Second Brain. This scope combines three related board tasks:
+
+### t_ee819f4b P4 - [upstream:Sibyl-Memory] Self-learning skill proposal review queue
+
+Sibyl-Memory has a self-learning loop that scans its append-only journal for repeated agent behavior and creates reviewable skill proposals. The upstream implementation is intentionally deterministic by default: it scans new journal events since the last watermark, runs explainable detectors for `repeated_action`, `structural_similarity`, `co_occurrence`, and `temporal_routine`, deduplicates by slug, and writes pending proposals with confidence, evidence snippets, and a summarizer label. A human can accept or reject each proposal; accepted proposals become reference documents under `skill/<slug>`.
+
+Open Second Brain already learns preferences from repeated correction signals, but it does not currently turn repeated successful work patterns into reusable operator-reviewed skills or runbooks. This would make Open Second Brain more useful as a Second Brain because the system would learn not only what the user prefers, but also how the agent repeatedly solves tasks for this user and project. Examples: recurring release-note workflows, common triage patterns, repeated CodeRabbit remediation steps, or project-specific debugging recipes.
+
+Acceptance criteria:
+
+- A deterministic learning run can scan Brain log/session events since the last watermark and create pending skill proposals without network calls.
+- Proposals include pattern kind, confidence, evidence snippets, source event references, and a human-readable suggested skill body.
+- Duplicate pending proposals are suppressed by stable slug or payload hash.
+- Accepting a proposal creates an auditable skill/reference artifact and marks the proposal accepted.
+- Rejecting a proposal records a review note and prevents the same proposal from reappearing unchanged.
+- The workflow is covered by tests for repeated-action, structural-similarity, co-occurrence, temporal-routine, accept, reject, and watermark behavior.
+
+### t_02e22d4e P3 - [upstream:signetai] Procedural memory graph for installed skills and runbooks
+
+SignetAI treats installed skills as procedural memory. A reconciler scans installed `SKILL.md` files, parses frontmatter, creates graph entity nodes, stores skill metadata such as triggers/tags/permissions/source/version, generates embeddings for skill discovery, tracks usage fields, and can extract related entities from the skill body. Declarative memory answers what is true; procedural memory answers what should the agent do. Skills become searchable, inspectable, and eventually decayable graph nodes instead of passive files that only work when invoked by exact name.
+
+Open Second Brain already has a skills directory, repo-local skills, a schema-author skill, and a self-learning skill proposal task. What is missing is the installed-skill side of the lifecycle: once a runbook/skill exists, Open Second Brain should know when it is relevant, what triggers it, which entities or projects it touches, whether it has been used recently, and whether it should be surfaced in a context pack or operator dashboard.
+
+Acceptance criteria:
+
+- Open Second Brain can list installed procedural memory entries with source path, triggers, tags, and last-used metadata.
+- Skill metadata updates when the source file changes and removes stale entries when the file disappears.
+- Usage tracking updates a sidecar/index without rewriting `SKILL.md`.
+- Procedural entries can link to Brain entities/projects/tasks and appear in graph/export surfaces.
+- Tests cover frontmatter parsing, reconciliation, deletion, usage tracking, and graph/entity linking.
+
+### t_6d0fda95 P3 - [upstream:plur] Cross-scope recurrence promotion with reference-counted retirement
+
+PLUR treats repeated learning across scopes as signal. If the same content hash is learned again in the same scope, it increments a reference count and records another source rather than creating a duplicate. If the same knowledge is learned in a different scope, PLUR records cross-scope recurrence, appends source metadata, increments recurrence/reference counters, and can broaden the memory toward global scope while escalating commitment from exploring to leaning, decided, and locked. Forgetting decrements the reference count first; the memory retires only when the supporting references are gone.
+
+Open Second Brain is already multi-project and multi-agent. Some Brain knowledge should remain local to one project, while other lessons become global only after they recur in multiple places. Today Open Second Brain has source metadata, content hashing, visibility tags, and multi-vault/profile work, but the operator still needs to reason manually about when a repeated convention has become generally true.
+
+Acceptance criteria:
+
+- Same-scope duplicate writes increment support instead of creating duplicate Brain entries.
+- Cross-scope duplicate writes are detected and recorded as recurrence evidence.
+- Scope broadening and commitment escalation are thresholded, auditable, and configurable.
+- Forget/source-removal decrements support before retirement.
+- `why_retrieved` or diagnostics can show source/support/recurrence evidence.
+- Tests cover same-scope duplicate, cross-scope recurrence, scope promotion, locked-memory behavior, reference-counted forget, and source purge interactions.
+
+# Project context
+
+Project: Open Second Brain, a Bun/TypeScript CLI and MCP server for an Obsidian-native AI memory layer. Runtime: Bun, TypeScript, Markdown vault files under `Brain/`.
+
+Recent commits:
+
+- 0162d13 feat(brain): add context continuity and receipts suite (#56)
+- 3b7b3a5 feat(brain): add safety governance foundations (#55)
+- 794ee45 feat(search): ship recall control and trust surfaces (#54)
+- 40d4e2b feat: cjk schema lifecycle recovery - CJK search, schema admin, lifecycle hooks, watchdog (#53)
+- f62918c feat: runtime schema packs foundation - schema vocabulary, artifact taxonomy, schema inspection (#52)
+- 14d1ee1 feat: brain model semantics foundation - typed preference relations, memory labels, dry-run backfill (#51)
+- 3a5d5c3 feat: agent capability CLI integration - runtime MCP capabilities, inherited JSON, completions (#50)
+- a085bfa feat: vault portability + session economy - codec, sources dashboard, vault-map tokens, multi-vault profiles, graph export/import (#49)
+- 73e4a28 feat: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)
+- bd49cd5 feat: recall and ranking quality - Weibull recency, query intent, synonym expansion, recall budgets, query cache, pre-compress pack (#47)
+
+Related files and surfaces:
+
+- `src/core/brain/log.ts` and `src/core/brain/log-jsonl.ts`: append-only Brain log and machine-readable JSONL reader.
+- `src/core/brain/dream.ts`: deterministic batch mutation pipeline that promotes signals into preferences and writes audit log entries.
+- `src/core/brain/paths.ts`: canonical Brain layout constants and path constructors.
+- `src/core/brain/types.ts`: Brain frontmatter and event type contracts.
+- `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/help-text.ts`: CLI verb dispatch/help/export patterns.
+- `src/mcp/brain-tools.ts`: MCP Brain tool registry and handlers.
+- `skills/brain-memory/SKILL.md`, `skills/open-second-brain/SKILL.md`: current installed procedural guidance files.
+- `docs/idea.md`: explicitly separates event log as operational evidence from synthesized second-brain knowledge.
+- `docs/plans/2026-05-15-brain-roadmap.md`: has a related but deferred `skill-codify` idea; this release should remain review-first and should not auto-edit active skills without operator approval.
+
+Conventions:
+
+- Open Second Brain writes only under `Brain/` inside the user's vault.
+- Raw operational evidence belongs in `Brain/log/`; synthesized knowledge belongs in managed Brain artifacts.
+- Default behavior should be deterministic, local-first, opt-in or preview-first where risk exists.
+- No network calls or LLM calls in default learning/proposal paths.
+- User-facing public docs must use the full project name, not unexplained abbreviations.
+- CLI surfaces typically have `--json`, dry-run/preview behavior where writes could surprise the operator, and focused tests under `tests/cli/` plus core tests under `tests/core/brain/`.
+- MCP full-scope tools are read/diagnostic unless a writer-scope behavior is explicitly justified.
+
+Constraints:
+
+- Keep changes SOLID, KISS, DRY.
+- Do not auto-activate generated skills or mutate source `SKILL.md` files without explicit accept/review.
+- Preserve existing preference-learning `dream` behavior; skill proposals are a companion workflow, not a replacement.
+- Avoid adding external dependencies unless clearly necessary.
+- Prefer local Markdown/JSONL artifacts over a daemon or hidden database.
+- Keep the first release slice coherent; defer heavyweight embeddings or generic agent orchestration.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/self-learning-skill-proposals/design.md b/docs/brainstorm/self-learning-skill-proposals/design.md
new file mode 100644
index 00000000..4afe32b2
--- /dev/null
+++ b/docs/brainstorm/self-learning-skill-proposals/design.md
@@ -0,0 +1,60 @@
+# Self-Learning Skill Proposals - review-first procedural learning
+
+**Status:** draft
+**Author:** GitHub Copilot (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain currently learns durable user preferences from repeated correction signals, but it does not learn reusable procedures from repeated successful work patterns. The project also ships skills and runbooks as passive files; there is no Brain-native procedural index that can list them, track usage, or connect them to proposal/review history. Finally, repeated procedural knowledge across scopes is not counted as support, so the operator has to manually infer when a lesson has become broadly useful.
+
+## Scope
+
+- Add a deterministic self-learning skill proposal queue that scans Brain log/session-style events and writes reviewable Markdown proposal artifacts under `Brain/skill-proposals/`.
+- Add accept/reject lifecycle commands that keep pending/rejected/accepted proposal history auditable and write accepted runbooks into a Brain-owned procedures area rather than mutating repo `SKILL.md` files.
+- Add a procedural memory reconciler for Brain-owned procedures and installed skill/runbook roots, with metadata parsing, stale-entry pruning, and usage sidecar updates that do not rewrite source files.
+- Add a small recurrence/support ledger for procedural/proposal knowledge, so same-scope duplicates and cross-scope recurrence become visible evidence before any future automatic promotion.
+- Expose the workflow through focused CLI verbs and read/diagnostic MCP surfaces where useful.
+- Cover detector, lifecycle, reconciliation, usage, recurrence, and integration behavior with tests.
+
+## Out of scope
+
+- Auto-activating generated skills in any runtime.
+- Rewriting packaged `skills/*/SKILL.md` files from learned proposals.
+- Replacing `dream` preference promotion or changing existing preference-learning thresholds.
+- LLM summarization, embeddings, or network calls in the default proposal path.
+- Full graph-export/entity integration for procedural entries beyond stable metadata and explicit relation/source fields in this release.
+
+## Chosen approach
+
+Use the consultant's Variant 1: three dream-adjacent modules with shared helper primitives instead of one unified engine. Skill proposals, procedural memory, and recurrence support each get a clear core module, storage contract, and CLI/test slice. Shared code should stay limited to path helpers, deterministic hashing/slugging, frontmatter parsing/rendering, and watermark/scan utilities.
+
+## Design decisions
+
+- **Keep proposals as Markdown artifacts.** Pending, accepted, and rejected proposals should be inspectable and editable in Obsidian, matching the rest of Brain's local-first model.
+- **Accept writes Brain procedures, not active agent skills.** Accepted proposals become `Brain/procedures/proc-<slug>.md` runbook/reference artifacts. A future explicit install/promote workflow can copy or package them into runtime skills.
+- **Keep `dream` unchanged.** Proposal learning is a companion scan command. It reads Brain log/continuity/session evidence but does not enter the deterministic preference mutation pipeline.
+- **Use explicit status transitions.** Proposal files carry `status: pending|accepted|rejected`; commands move or rewrite only managed proposal/procedure files and append Brain log events for audit.
+- **Make recurrence diagnostic first.** The recurrence ledger records support, scope recurrence, and reference decrement behavior, but does not auto-broaden scope or lock rules in this release.
+- **Do not dirty source skill files on usage.** Procedural usage lands in a sidecar/ledger so installed `SKILL.md` and accepted procedure notes remain stable unless the operator edits them.
+
+## File changes
+
+Expected new or modified areas:
+
+- `src/core/brain/skill-proposals.ts` - proposal artifact parsing, rendering, detection, lifecycle.
+- `src/core/brain/procedural-memory.ts` - procedural metadata parsing/reconciliation/usage sidecar.
+- `src/core/brain/recurrence.ts` - support ledger and reference-counted source accounting.
+- `src/core/brain/paths.ts` - Brain path constants and constructors for proposals, procedures, procedural index, recurrence ledger.
+- `src/core/brain/types.ts` - log event kinds or shared enums if needed.
+- `src/cli/brain/verbs/*` and `src/cli/brain/help-text.ts` - CLI verbs for learning, proposal review, procedural listing/usage, recurrence diagnostics.
+- `src/mcp/brain-tools.ts` and MCP tests - read/diagnostic surfaces for proposals/procedural entries if the implementation slice warrants them.
+- `tests/core/brain/*`, `tests/cli/*`, `tests/mcp/*` - TDD coverage for each atomic unit.
+- `README.md`, `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md` - docs once implementation is complete.
+
+## Risks and open questions
+
+- Detector quality can become noisy. The first slice should prefer deterministic, explainable, conservative detectors over broad heuristic matching.
+- Recurrence support must not accidentally change existing preference semantics. Keep it opt-in/diagnostic until a later release proves the thresholds.
+- Procedural roots must be explicit and safe. The reconciler should scan known roots or caller-provided roots, never arbitrary home directories by default.
+- MCP surface count may require updating full-server tool listing tests if new full-scope read tools are added.
diff --git a/docs/brainstorm/self-learning-skill-proposals/plan.md b/docs/brainstorm/self-learning-skill-proposals/plan.md
new file mode 100644
index 00000000..f6818ea6
--- /dev/null
+++ b/docs/brainstorm/self-learning-skill-proposals/plan.md
@@ -0,0 +1,59 @@
+# Self-Learning Skill Proposals - implementation plan
+
+## Phase 0 outcome
+
+Recommended architecture: file-first, dream-adjacent modules for proposal learning, procedural memory, and recurrence support. The modules share deterministic helpers but do not merge into one engine and do not modify the existing `dream` preference path.
+
+## Phase 2 TDD plan
+
+1. **Brain path and artifact contracts**
+ - Add tests for proposal/procedure/procedural-index/recurrence paths staying inside `Brain/` and rejecting unsafe slugs.
+ - Implement path helpers and any narrow shared types.
+ - Commit: `feat(brain): add procedural learning artifact paths`.
+
+2. **Skill proposal storage and detectors**
+ - Add failing core tests for repeated-action, structural-similarity, co-occurrence, temporal-routine, duplicate suppression, and watermark advancement.
+ - Implement deterministic proposal scan over Brain log/session events with conservative detector rules and stable slug/hash behavior.
+ - Commit: `feat(brain): detect skill proposal patterns`.
+
+3. **Proposal review lifecycle**
+ - Add failing core and CLI tests for list/show/accept/reject, accepted procedure artifact creation, rejected proposal suppression, audit metadata, and JSON output.
+ - Implement proposal review core and CLI verbs.
+ - Commit: `feat(brain): add skill proposal review workflow`.
+
+4. **Procedural memory reconciler**
+ - Add failing tests for frontmatter parsing, scanning Brain procedures and installed skill/runbook roots, stale deletion, source-change updates, and stable IDs.
+ - Implement procedural index and CLI list/reconcile behavior.
+ - Commit: `feat(brain): index procedural memory entries`.
+
+5. **Procedural usage sidecar**
+ - Add failing tests proving usage updates do not rewrite source `SKILL.md`/procedure files and that last-used/count metadata appears in list/export output.
+ - Implement usage sidecar and CLI mark-used behavior.
+ - Commit: `feat(brain): track procedural memory usage`.
+
+6. **Recurrence support ledger**
+ - Add failing tests for same-scope duplicate support increment, cross-scope recurrence evidence, thresholded diagnostic promotion state, locked/no-auto-change behavior, reference-counted forget, and source purge.
+ - Implement recurrence ledger and diagnostics without mutating preferences or auto-promoting scope.
+ - Commit: `feat(brain): record procedural recurrence support`.
+
+7. **MCP and integration surfaces**
+ - Add focused MCP tests for read/diagnostic proposal/procedural surfaces if exposed.
+ - Implement handlers only for surfaces that remove meaningful CLI friction.
+ - Commit: `feat(mcp): expose procedural learning diagnostics` if needed.
+
+8. **Docs and versioning**
+ - Update CLI reference, MCP docs if applicable, README feature summary, CHANGELOG, and version files.
+ - Run formatter/linter before commit as requested.
+ - Commit: `docs: document procedural learning workflow` or version-specific release commit.
+
+## Validation checklist
+
+- Focused tests after each TDD unit.
+- `bun run fmt` and `bun run lint` before every commit.
+- Full QA before pre-push stop point: `bun run test`, `bun run typecheck`, `bun run lint`, version sync check if available, and `code_checker`.
+- Self-review compares branch diff against `main` and checks the implementation against the selected task acceptance criteria.
+
+## Stop points
+
+- Phase 6 pre-push chat stop-point with Russian `ask_report` before pushing.
+- Release/pre-release stop-point per feature-release-playbook after PR approval/merge flow.
diff --git a/docs/brainstorm/self-learning-skill-proposals/variants.md b/docs/brainstorm/self-learning-skill-proposals/variants.md
new file mode 100644
index 00000000..7fca6dba
--- /dev/null
+++ b/docs/brainstorm/self-learning-skill-proposals/variants.md
@@ -0,0 +1,45 @@
+# Self-Learning Skill Proposals - variants
+
+## Consultant variants
+
+### Variant 1: Three Parallel Queue Modules (file-first, dream-adjacent)
+
+- **Approach:** Implement each board task as its own self-contained core module with its own artifact and CLI verb group, sharing only existing primitives (`log-jsonl` reader, `paths`, `types`). Skill proposals land in a new `Brain/proposals/` queue, the procedural index as a sidecar under `Brain/skills-index/`, and recurrence/reference counters as frontmatter fields on existing Brain entries. Each exposes an opt-in scan command that borrows the `dream` watermark pattern without modifying `dream` itself.
+- **Trade-offs:**
+ - Pro: Clean separation maps 1:1 to the three acceptance-criteria sets and their test suites; each ships and is reviewed independently.
+ - Pro: Zero regression risk to the existing preference-learning `dream` path; honors "companion workflow, not replacement."
+ - Pro: Smallest coherent first slice; easy to defer any one task without blocking the others.
+ - Con: Three watermark/scan loops mean some duplicated scan scaffolding, mitigated by a shared helper, not a shared engine.
+ - Con: Leaves synergy on the table; recurrence support counts do not automatically feed proposal confidence in the first slice.
+- **Complexity:** medium
+- **Risk:** low
+
+### Variant 2: Unified Procedural-Knowledge Engine with Shared Recurrence Ledger
+
+- **Approach:** Build one new subsystem centered on a content-hash recurrence ledger that becomes the common substrate for all three concerns. Skill proposals become derived views whose confidence is supplied by ledger support counts, installed skills become graph nodes in the same store carrying usage and recurrence counters, and scope-promotion/commitment escalation is one set of thresholded logic applied uniformly across preferences, proposals, and skills. A single scan and single watermark drive everything.
+- **Trade-offs:**
+ - Pro: Maximal reuse and a single source of truth for support/recurrence/confidence; strongest "the brain learns how it works" payoff.
+ - Pro: Cross-scope promotion naturally lifts proposals and procedural entries, not just preferences.
+ - Con: Large surface area; the three upstreams have genuinely different data shapes forced into one model, fighting KISS.
+ - Con: High coupling makes a coherent first slice hard to scope and a partial ship hard to test in isolation.
+ - Con: Highest regression and design-churn risk for an initial release.
+- **Complexity:** large
+- **Risk:** high
+
+### Variant 3: Dream-Pipeline Phase Extension + Thin Review CLIs
+
+- **Approach:** Add three new deterministic phases to the existing multi-phase `dream` pass: proposal detection, procedural reconciliation, and recurrence/reference accounting. Each phase emits Brain artifacts with audit-log entries alongside the current preference promotion. Accept/reject/promote actions are handled by thin CLI and read/diagnostic MCP verbs layered over those artifacts, giving the operator one learning cadence.
+- **Trade-offs:**
+ - Pro: Reuses watermark, batch orchestration, audit-log, and scheduling infra; strong DRY.
+ - Pro: One operator mental model and one scheduled pass; preview-first falls out naturally from `dream`'s dry-run.
+ - Con: Meaningfully grows `dream` and couples three independent concerns to one scheduler cadence, risking regression to the protected preference path.
+ - Con: Per-task test isolation is harder when all phases share one pipeline entry point.
+ - Con: Procedural reconciliation, filesystem-driven rather than journal-driven, is an awkward fit for a journal-watermark pipeline.
+- **Complexity:** medium
+- **Risk:** medium
+
+## Orchestrator decision
+
+Recommended: Variant 1.
+
+The three board tasks have different source data and write semantics, so parallel modules keep the first release simpler and more testable than a shared procedural engine. This also minimizes risk to the existing deterministic `dream` preference path while leaving room to consolidate recurrence support into proposal confidence in a later release after the artifact shapes prove themselves.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 505f4ec4..aadf49c2 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.29.0",
+ "version": "0.30.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 3df09728..dd3dbf10 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.29.0",
+ "version": "0.30.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.yaml
index 5676b85a..6c24728e 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.29.0"
+version: "0.30.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index a7768506..0bd8ddd4 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.29.0",
+ "version": "0.30.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.yaml
index 47876fd1..5dc6fec1 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.29.0"
+version: "0.30.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 6223197c..797ecdc1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.29.0"
+version = "0.30.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index e748ab47..95d0a079 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -58,6 +58,9 @@ import {
cmdBrainContextPresets,
cmdBrainPreCompactExtract,
cmdBrainRecallTelemetry,
+ cmdBrainSkillProposals,
+ cmdBrainProceduralMemory,
+ cmdBrainRecurrence,
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
cmdBrainSessionGrep,
@@ -192,6 +195,12 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainPreCompactExtract(rest);
case "recall-telemetry":
return await cmdBrainRecallTelemetry(rest);
+ case "skill-proposals":
+ return await cmdBrainSkillProposals(rest);
+ case "procedural-memory":
+ return await cmdBrainProceduralMemory(rest);
+ case "recurrence":
+ return await cmdBrainRecurrence(rest);
case "session-grep":
return await cmdBrainSessionGrep(rest);
case "session-describe":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 92ee8692..74710789 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -60,6 +60,9 @@ Brain verbs (observing memory):
context-presets Show/suggest/diff read-only context budget presets
pre-compact-extract Extract typed continuity records from bounded text
recall-telemetry List/summarize opt-in recall telemetry records
+ skill-proposals Learn/list/review deterministic skill proposals
+ procedural-memory Reconcile/list procedural memory index and usage
+ recurrence Inspect and update recurrence/support diagnostics
session-grep Search imported session recall turns and summaries
session-describe Describe an imported session recall DAG
session-expand Expand a session recall node to source turns
@@ -361,6 +364,27 @@ export const VERB_HELP: Record<string, string> = {
"usage: o2b brain recall-telemetry list [--mode search|context_pack|pre_compress] [--status ok|empty|error|timeout] [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--vault <path>] [--json]\n" +
" o2b brain recall-telemetry summary [same filters] [--vault <path>] [--json]\n" +
"Read opt-in recall telemetry continuity records and aggregate coverage gaps.\n",
+ "skill-proposals":
+ "usage: o2b brain skill-proposals <learn|list|accept|reject> [args]\n" +
+ "Deterministic proposal queue lifecycle.\n" +
+ " learn [--min-support <n>] [--vault <path>] [--json]\n" +
+ " list [--vault <path>] [--json]\n" +
+ " accept <slug> [--note <text>] [--vault <path>] [--json]\n" +
+ " reject <slug> --note <text> [--vault <path>] [--json]\n",
+ "procedural-memory":
+ "usage: o2b brain procedural-memory <reconcile|list|mark-used> [args]\n" +
+ "Procedural index reconciliation and usage tracking sidecar.\n" +
+ " reconcile [--root <path> ...] [--vault <path>] [--json]\n" +
+ " list [--vault <path>] [--json]\n" +
+ " mark-used <entry-id> [--vault <path>] [--json]\n",
+ recurrence:
+ "usage: o2b brain recurrence <list|show|learn|forget|purge-source> [args]\n" +
+ "Recurrence/support diagnostics and reference-counted updates.\n" +
+ " list [--vault <path>] [--json]\n" +
+ " show <content-hash> [--vault <path>] [--json]\n" +
+ " learn --hash <h> --scope <scope> --source <id> [--vault <path>] [--json]\n" +
+ " forget --hash <h> --scope <scope> --source <id> [--vault <path>] [--json]\n" +
+ " purge-source --source <id> [--vault <path>] [--json]\n",
"session-grep":
"usage: o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--vault <path>] [--json]\n" +
"Search imported session recall raw turns and summary nodes.\n",
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index c1e465f0..30427387 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -45,6 +45,9 @@ export { cmdBrainContextReceipts } from "./context-receipts.ts";
export { cmdBrainContextPresets } from "./context-presets.ts";
export { cmdBrainPreCompactExtract } from "./pre-compact-extract.ts";
export { cmdBrainRecallTelemetry } from "./recall-telemetry.ts";
+export { cmdBrainSkillProposals } from "./skill-proposals.ts";
+export { cmdBrainProceduralMemory } from "./procedural-memory.ts";
+export { cmdBrainRecurrence } from "./recurrence.ts";
export {
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
diff --git a/src/cli/brain/verbs/pre-compact-extract.ts b/src/cli/brain/verbs/pre-compact-extract.ts
index 531b438b..5dfbd8a3 100644
--- a/src/cli/brain/verbs/pre-compact-extract.ts
+++ b/src/cli/brain/verbs/pre-compact-extract.ts
@@ -2,9 +2,7 @@ import { extractPreCompactRecords } from "../../../core/brain/pre-compact-extrac
import { CliError, parse } from "../helpers.ts";
import { inspect } from "node:util";
-export async function cmdBrainPreCompactExtract(
- argv: string[],
-): Promise<number> {
+export async function cmdBrainPreCompactExtract(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
json: { type: "boolean" },
vault: { type: "string" },
@@ -26,41 +24,27 @@ export async function cmdBrainPreCompactExtract(
turnStart,
turnEnd,
text,
- ...(stringOptional(flags["host"]) !== undefined
- ? { host: stringOptional(flags["host"]) }
- : {}),
- ...(maxChars !== undefined
- ? { maxChars: positiveInteger(maxChars, "--max-chars") }
- : {}),
+ ...(stringOptional(flags["host"]) !== undefined ? { host: stringOptional(flags["host"]) } : {}),
+ ...(maxChars !== undefined ? { maxChars: positiveInteger(maxChars, "--max-chars") } : {}),
});
- writeOutput(
- { count: result.records.length, ...result },
- flags["json"] === true,
- );
+ writeOutput({ count: result.records.length, ...result }, flags["json"] === true);
return 0;
}
-function stringRequired(
- value: string | boolean | string[] | undefined,
- label: string,
-): string {
+function stringRequired(value: string | boolean | string[] | undefined, label: string): string {
const parsed = stringOptional(value);
- if (parsed === undefined)
- throw new CliError(`brain pre-compact-extract: ${label} is required`);
+ if (parsed === undefined) throw new CliError(`brain pre-compact-extract: ${label} is required`);
return parsed;
}
-function stringOptional(
- value: string | boolean | string[] | undefined,
-): string | undefined {
+function stringOptional(value: string | boolean | string[] | undefined): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function positiveInteger(value: string, label: string): number {
- if (!/^[0-9]+$/.test(value))
- throw new CliError(`${label} must be a positive integer`);
+ if (!/^[0-9]+$/.test(value)) throw new CliError(`${label} must be a positive integer`);
const parsed = Number.parseInt(value, 10);
if (parsed < 1) throw new CliError(`${label} must be a positive integer`);
return parsed;
diff --git a/src/cli/brain/verbs/procedural-memory.ts b/src/cli/brain/verbs/procedural-memory.ts
new file mode 100644
index 00000000..fd8cefc3
--- /dev/null
+++ b/src/cli/brain/verbs/procedural-memory.ts
@@ -0,0 +1,126 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ listProceduralMemory,
+ markProceduralMemoryUsed,
+ reconcileProceduralMemory,
+} from "../../../core/brain/procedural-memory.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { join } from "node:path";
+
+export async function cmdBrainProceduralMemory(
+ argv: string[],
+): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ if (sub === "reconcile") return reconcile(rest);
+ if (sub === "list") return list(rest);
+ if (sub === "mark-used") return markUsed(rest);
+ throw new CliError(
+ "brain procedural-memory: expected reconcile, list, or mark-used",
+ );
+}
+
+function reconcile(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ root: { type: "string-array" },
+ });
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+ const roots = normalizeRoots(vault, flags["root"]);
+ const result = reconcileProceduralMemory(vault, { roots });
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `procedural-memory reconcile: total=${result.total} added=${result.added} updated=${result.updated} removed=${result.removed}\n`,
+ );
+ return 0;
+}
+
+function list(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+ const entries = listProceduralMemory(vault);
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ total: entries.length, entries }, null, 2) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(`${entries.length} procedural memory entr(y/ies):\n`);
+ for (const item of entries) {
+ process.stdout.write(
+ ` ${item.id} ${item.kind} used=${item.usedCount} ${item.sourcePath} triggers=${item.triggers.join(",") || "-"}\n`,
+ );
+ }
+ return 0;
+}
+
+function markUsed(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const id = trim(positional[0]);
+ if (!id)
+ throw new CliError(
+ "brain procedural-memory mark-used: entry id is required",
+ );
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+ const updated = markProceduralMemoryUsed(vault, id);
+ if (!updated)
+ throw new CliError(
+ `brain procedural-memory mark-used: unknown entry: ${id}`,
+ );
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(updated, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `marked used: ${updated.id} count=${updated.usedCount}\n`,
+ );
+ return 0;
+}
+
+function normalizeRoots(
+ vault: string,
+ raw: string | boolean | string[] | undefined,
+): string[] {
+ if (Array.isArray(raw)) {
+ const roots = raw
+ .map((value) => value.trim())
+ .filter((value) => value.length > 0);
+ if (roots.length > 0) return roots;
+ }
+ return [
+ join(vault, "Brain", "procedures"),
+ join(vault, "skills"),
+ join(vault, "runbooks"),
+ ];
+}
+
+function trim(value: string | undefined): string | undefined {
+ if (value === undefined) return undefined;
+ const t = value.trim();
+ return t.length > 0 ? t : undefined;
+}
diff --git a/src/cli/brain/verbs/recurrence.ts b/src/cli/brain/verbs/recurrence.ts
new file mode 100644
index 00000000..683a7c4c
--- /dev/null
+++ b/src/cli/brain/verbs/recurrence.ts
@@ -0,0 +1,122 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ applyRecurrenceEvidence,
+ getRecurrenceEntry,
+ listRecurrenceEntries,
+ purgeRecurrenceSource,
+} from "../../../core/brain/recurrence.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainRecurrence(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ if (sub === "list") return list(rest);
+ if (sub === "show") return show(rest);
+ if (sub === "learn") return mutate(rest, "learn");
+ if (sub === "forget") return mutate(rest, "forget");
+ if (sub === "purge-source") return purgeSource(rest);
+ throw new CliError("brain recurrence: expected list, show, learn, forget, or purge-source");
+}
+
+function list(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const entries = listRecurrenceEntries(vault);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ total: entries.length, entries }, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`${entries.length} recurrence entr(y/ies):\n`);
+ for (const entry of entries) {
+ process.stdout.write(
+ ` ${entry.contentHash} support=${entry.supportCount} recurrence=${entry.recurrenceCount} commitment=${entry.commitment}\n`,
+ );
+ }
+ return 0;
+}
+
+function show(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const hash = trim(positional[0]);
+ if (!hash) throw new CliError("brain recurrence show: content hash is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const entry = getRecurrenceEntry(vault, hash);
+ if (!entry) throw new CliError(`brain recurrence show: not found: ${hash}`);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(entry, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `${entry.contentHash} support=${entry.supportCount} recurrence=${entry.recurrenceCount} commitment=${entry.commitment}\n`,
+ );
+ return 0;
+}
+
+function mutate(argv: string[], action: "learn" | "forget"): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ hash: { type: "string", required: true },
+ scope: { type: "string", required: true },
+ source: { type: "string", required: true },
+ });
+
+ const hash = trim(flags["hash"]);
+ const scope = trim(flags["scope"]);
+ const source = trim(flags["source"]);
+ if (!hash || !scope || !source) {
+ throw new CliError(`brain recurrence ${action}: --hash, --scope, and --source are required`);
+ }
+
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const entry = applyRecurrenceEvidence(vault, {
+ contentHash: hash,
+ scope,
+ sourceId: source,
+ action,
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(entry, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`${action} ${hash}\n`);
+ return 0;
+}
+
+function purgeSource(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ source: { type: "string", required: true },
+ });
+ const source = trim(flags["source"]);
+ if (!source) throw new CliError("brain recurrence purge-source: --source is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ purgeRecurrenceSource(vault, source);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ ok: true, source }, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`purged source: ${source}\n`);
+ return 0;
+}
+
+function trim(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const t = value.trim();
+ return t.length > 0 ? t : undefined;
+}
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
new file mode 100644
index 00000000..91482500
--- /dev/null
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -0,0 +1,126 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ acceptSkillProposal,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ rejectSkillProposal,
+} from "../../../core/brain/skill-proposals.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ if (sub === "learn") return learn(rest);
+ if (sub === "list") return list(rest);
+ if (sub === "accept") return accept(rest);
+ if (sub === "reject") return reject(rest);
+ throw new CliError("brain skill-proposals: expected learn, list, accept, or reject");
+}
+
+function learn(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "min-support": { type: "string" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const minSupportRaw = trim(flags["min-support"]);
+ const minSupport = minSupportRaw
+ ? parsePositiveInteger(minSupportRaw, "--min-support")
+ : undefined;
+
+ const result =
+ minSupport !== undefined
+ ? learnSkillProposals(vault, { minSupport })
+ : learnSkillProposals(vault);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `skill-proposals learn: scanned=${result.scanned} created=${result.created.length} suppressed=${result.suppressed.length}\n`,
+ );
+ return 0;
+}
+
+function list(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const pending = listPendingSkillProposals(vault);
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ total: pending.length, proposals: pending }, null, 2) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(`${pending.length} pending skill proposal(s):\n`);
+ for (const item of pending) {
+ process.stdout.write(` ${item.id} ${item.patternKind} status=${item.status}\n`);
+ }
+ return 0;
+}
+
+function accept(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ note: { type: "string" },
+ });
+ const slug = trim(positional[0]);
+ if (!slug) throw new CliError("brain skill-proposals accept: slug is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const note = trim(flags["note"]);
+ const result = note
+ ? acceptSkillProposal(vault, slug, { note })
+ : acceptSkillProposal(vault, slug);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`accepted ${result.id}\n`);
+ return 0;
+}
+
+function reject(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ note: { type: "string", required: true },
+ });
+ const slug = trim(positional[0]);
+ if (!slug) throw new CliError("brain skill-proposals reject: slug is required");
+ const note = trim(flags["note"]);
+ if (!note) throw new CliError("brain skill-proposals reject: --note is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const result = rejectSkillProposal(vault, slug, { note });
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`rejected ${result.id}\n`);
+ return 0;
+}
+
+function trim(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const t = value.trim();
+ return t.length > 0 ? t : undefined;
+}
+
+function parsePositiveInteger(value: string, label: string): number {
+ if (!/^[0-9]+$/.test(value)) throw new CliError(`${label} must be a positive integer`);
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) throw new CliError(`${label} must be a positive integer`);
+ return parsed;
+}
diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.ts
index 8190798b..8a79cbc0 100644
--- a/src/core/brain/context-receipts.ts
+++ b/src/core/brain/context-receipts.ts
@@ -1,9 +1,6 @@
import { createHash } from "node:crypto";
-import {
- appendContinuityRecord,
- listContinuityRecords,
-} from "./continuity/store.ts";
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
import type { ContinuityRecord } from "./continuity/types.ts";
export type ContextReceiptTrigger = "context_pack" | "pre_compress";
@@ -66,9 +63,7 @@ export function emitContextReceipt(
...(item.tokens !== undefined ? { tokens: item.tokens } : {}),
...(item.tier ? { tier: item.tier } : {}),
...(item.trimmed !== undefined ? { trimmed: item.trimmed } : {}),
- ...(item.safetyFiltered !== undefined
- ? { safety_filtered: item.safetyFiltered }
- : {}),
+ ...(item.safetyFiltered !== undefined ? { safety_filtered: item.safetyFiltered } : {}),
...(item.text ? { text_hash: sha256(item.text) } : {}),
}));
const payload: Record<string, unknown> = {
@@ -102,9 +97,7 @@ function mergeReceiptExtra(
if (!extra) return;
for (const [key, value] of Object.entries(extra)) {
if (Object.hasOwn(payload, key)) {
- throw new Error(
- `context receipt extra key collides with payload field: ${key}`,
- );
+ throw new Error(`context receipt extra key collides with payload field: ${key}`);
}
payload[key] = value;
}
@@ -123,45 +116,30 @@ export function listContextReceipts(
return Object.freeze(receipts);
}
-export function getContextReceipt(
- vault: string,
- id: string,
-): ContinuityRecord | null {
+export function getContextReceipt(vault: string, id: string): ContinuityRecord | null {
return (
- listContinuityRecords(vault, { kind: "context_receipt" }).find(
- (record) => record.id === id,
- ) ?? null
+ listContinuityRecords(vault, { kind: "context_receipt" }).find((record) => record.id === id) ??
+ null
);
}
-export function summarizeContextReceipt(
- record: ContinuityRecord,
-): ContextReceiptSummary {
+export function summarizeContextReceipt(record: ContinuityRecord): ContextReceiptSummary {
const payload = record.payload;
return {
id: record.id,
created_at: record.createdAt,
- trigger: isContextReceiptTrigger(payload["trigger"])
- ? payload["trigger"]
- : null,
+ trigger: isContextReceiptTrigger(payload["trigger"]) ? payload["trigger"] : null,
host: typeof payload["host"] === "string" ? payload["host"] : null,
- ...(typeof payload["session_id"] === "string"
- ? { session_id: payload["session_id"] }
- : {}),
- ...(typeof payload["turn_id"] === "string"
- ? { turn_id: payload["turn_id"] }
- : {}),
- item_count:
- typeof payload["item_count"] === "number" ? payload["item_count"] : null,
+ ...(typeof payload["session_id"] === "string" ? { session_id: payload["session_id"] } : {}),
+ ...(typeof payload["turn_id"] === "string" ? { turn_id: payload["turn_id"] } : {}),
+ item_count: typeof payload["item_count"] === "number" ? payload["item_count"] : null,
source_count: record.sourceRefs.length,
private: record.private,
redacted: record.redacted,
};
}
-export function isContextReceiptTrigger(
- value: unknown,
-): value is ContextReceiptTrigger {
+export function isContextReceiptTrigger(value: unknown): value is ContextReceiptTrigger {
return value === "context_pack" || value === "pre_compress";
}
@@ -169,19 +147,10 @@ function sha256(text: string): string {
return createHash("sha256").update(text, "utf8").digest("hex");
}
-function matchesReceiptFilter(
- record: ContinuityRecord,
- filter: ContextReceiptFilter,
-): boolean {
+function matchesReceiptFilter(record: ContinuityRecord, filter: ContextReceiptFilter): boolean {
const payload = record.payload;
- if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger)
- return false;
- if (filter.host !== undefined && payload["host"] !== filter.host)
- return false;
- if (
- filter.sessionId !== undefined &&
- payload["session_id"] !== filter.sessionId
- )
- return false;
+ if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger) return false;
+ if (filter.host !== undefined && payload["host"] !== filter.host) return false;
+ if (filter.sessionId !== undefined && payload["session_id"] !== filter.sessionId) return false;
return true;
}
diff --git a/src/core/brain/context-transforms.ts b/src/core/brain/context-transforms.ts
index d6e11880..93b7819e 100644
--- a/src/core/brain/context-transforms.ts
+++ b/src/core/brain/context-transforms.ts
@@ -36,9 +36,7 @@ export function applyContextTransforms<T extends ContextTransformItem>(
}));
if (opts.cacheStableOrdering) {
ranked.sort(
- (a, b) =>
- compareStable(a.item.id, b.item.id) ||
- compareStable(a.item.path, b.item.path),
+ (a, b) => compareStable(a.item.id, b.item.id) || compareStable(a.item.path, b.item.path),
);
}
diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.ts
index 0e22dc1a..9a0a48f3 100644
--- a/src/core/brain/continuity/store.ts
+++ b/src/core/brain/continuity/store.ts
@@ -1,12 +1,5 @@
import { createHash } from "node:crypto";
-import {
- existsSync,
- mkdirSync,
- readFileSync,
- readdirSync,
- statSync,
- writeFileSync,
-} from "node:fs";
+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { BRAIN_LOG_REL, ensureInsideVault } from "../paths.ts";
@@ -46,12 +39,8 @@ const CONTINUITY_REL = `${BRAIN_LOG_REL}/continuity`;
const CURSOR_PREFIX = "offset:";
export function continuityLogPath(vault: string, month: string): string {
- if (!/^\d{4}-\d{2}$/.test(month))
- throw new Error(`invalid continuity month: ${month}`);
- return ensureInsideVault(
- join(vault, CONTINUITY_REL, `${month}.jsonl`),
- vault,
- );
+ if (!/^\d{4}-\d{2}$/.test(month)) throw new Error(`invalid continuity month: ${month}`);
+ return ensureInsideVault(join(vault, CONTINUITY_REL, `${month}.jsonl`), vault);
}
export function appendContinuityRecord(
@@ -80,9 +69,7 @@ export function listContinuityRecords(
vault: string,
filter: ContinuityRecordFilter = {},
): ReadonlyArray<ContinuityRecord> {
- return Object.freeze(
- readAllRecords(vault).filter((record) => matches(record, filter)),
- );
+ return Object.freeze(readAllRecords(vault).filter((record) => matches(record, filter)));
}
export function paginateContinuityRecords(
@@ -93,8 +80,7 @@ export function paginateContinuityRecords(
const start = parseCursor(opts.cursor);
const filtered = listContinuityRecords(vault, opts);
const records = filtered.slice(start, start + limit);
- const next =
- start + limit < filtered.length ? `${CURSOR_PREFIX}${start + limit}` : null;
+ const next = start + limit < filtered.length ? `${CURSOR_PREFIX}${start + limit}` : null;
return Object.freeze({ records: Object.freeze(records), nextCursor: next });
}
@@ -110,12 +96,7 @@ function buildRecord(
): ContinuityRecord {
const payloadResult = safeContinuityPayload(input.payload ?? {});
const sourceRefs = Object.freeze([...(input.sourceRefs ?? [])]);
- const id = recordId(
- input.kind,
- input.createdAt,
- sourceRefs,
- payloadResult.payload,
- );
+ const id = recordId(input.kind, input.createdAt, sourceRefs, payloadResult.payload);
return Object.freeze({
id,
kind: input.kind,
@@ -127,10 +108,7 @@ function buildRecord(
});
}
-function appendRecord(
- vault: string,
- record: ContinuityRecord,
-): ContinuityRecord {
+function appendRecord(vault: string, record: ContinuityRecord): ContinuityRecord {
const path = continuityLogPath(vault, record.createdAt.slice(0, 7));
mkdirSync(join(vault, CONTINUITY_REL), { recursive: true });
const handle = acquireLockSync(path);
@@ -168,22 +146,13 @@ function readAllRecords(vault: string): ContinuityRecord[] {
}
}
}
- records.sort(
- (a, b) =>
- a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
- );
+ records.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
return records;
}
-function matches(
- record: ContinuityRecord,
- filter: ContinuityRecordFilter,
-): boolean {
+function matches(record: ContinuityRecord, filter: ContinuityRecordFilter): boolean {
if (filter.kind && record.kind !== filter.kind) return false;
- if (
- filter.sourceId &&
- !record.sourceRefs.some((source) => source.id === filter.sourceId)
- ) {
+ if (filter.sourceId && !record.sourceRefs.some((source) => source.id === filter.sourceId)) {
return false;
}
if (filter.since && record.createdAt < filter.since) return false;
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 863c7d49..d43f50a9 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -45,6 +45,12 @@ export const BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");
export const BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");
export const BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");
export const BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");
+export const BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");
+export const BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");
+export const BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");
+export const BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");
+export const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");
+export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");
export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");
export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");
/**
@@ -164,6 +170,53 @@ export function retiredPath(vault: string, slug: string): string {
return ensureInsideVault(join(brainDirs(vault).retired, `ret-${s}.md`), vault);
}
+/** Pending skill-proposal path: `Brain/skill-proposals/pending/prop-<slug>.md`. */
+export function skillProposalPendingPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_PENDING_REL, `prop-${s}.md`), vault);
+}
+
+/** Accepted skill-proposal archive path: `Brain/skill-proposals/accepted/prop-<slug>.md`. */
+export function skillProposalAcceptedPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, `prop-${s}.md`), vault);
+}
+
+/** Rejected skill-proposal archive path: `Brain/skill-proposals/rejected/prop-<slug>.md`. */
+export function skillProposalRejectedPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REJECTED_REL, `prop-${s}.md`), vault);
+}
+
+/** Accepted procedure reference path: `Brain/procedures/proc-<slug>.md`. */
+export function procedurePath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_PROCEDURES_REL, `proc-${s}.md`), vault);
+}
+
+/** Procedural-memory index path: `Brain/procedural-memory/index.json`. */
+export function proceduralMemoryIndexPath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "index.json"), vault);
+}
+
+/** Procedural-memory usage sidecar path: `Brain/procedural-memory/usage.jsonl`. */
+export function proceduralMemoryUsagePath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "usage.jsonl"), vault);
+}
+
+/** Proposal scan watermark path: `Brain/procedural-memory/proposal-watermark.json`. */
+export function proposalWatermarkPath(vault: string): string {
+ return ensureInsideVault(
+ join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "proposal-watermark.json"),
+ vault,
+ );
+}
+
+/** Recurrence support ledger path: `Brain/log/recurrence-support.jsonl`. */
+export function proceduralRecurrencePath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_LOG_REL, "recurrence-support.jsonl"), vault);
+}
+
/** Log file for the given UTC date: `Brain/log/<YYYY-MM-DD>.md`. */
export function logPath(vault: string, date: string): string {
const d = validateIsoDate(date);
diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.ts
new file mode 100644
index 00000000..e8568c54
--- /dev/null
+++ b/src/core/brain/procedural-memory.ts
@@ -0,0 +1,323 @@
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+} from "node:fs";
+import { dirname, join, relative } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import { parseFrontmatter } from "../vault.ts";
+import {
+ proceduralMemoryIndexPath,
+ proceduralMemoryUsagePath,
+} from "./paths.ts";
+
+export type ProceduralEntryKind = "skill" | "runbook" | "procedure";
+
+export interface ProceduralMemoryEntry {
+ readonly id: string;
+ readonly kind: ProceduralEntryKind;
+ readonly sourcePath: string;
+ readonly title: string;
+ readonly triggers: ReadonlyArray<string>;
+ readonly tags: ReadonlyArray<string>;
+ readonly permissions: ReadonlyArray<string>;
+ readonly source: string | null;
+ readonly version: string | null;
+ readonly lastUsedAt: string | null;
+ readonly usedCount: number;
+}
+
+export interface ProceduralReconcileOptions {
+ readonly roots: ReadonlyArray<string>;
+}
+
+export interface ProceduralReconcileResult {
+ readonly total: number;
+ readonly added: number;
+ readonly updated: number;
+ readonly removed: number;
+}
+
+export function reconcileProceduralMemory(
+ vault: string,
+ opts: ProceduralReconcileOptions,
+): ProceduralReconcileResult {
+ const prev = new Map(
+ listProceduralMemory(vault).map((entry) => [entry.id, entry] as const),
+ );
+ const usage = readUsageMap(vault);
+ const next = collectEntries(vault, opts.roots).map((entry) => {
+ const old = prev.get(entry.id);
+ const used = usage.get(entry.id);
+ return {
+ ...entry,
+ lastUsedAt: used?.lastUsedAt ?? old?.lastUsedAt ?? null,
+ usedCount: used?.usedCount ?? old?.usedCount ?? 0,
+ } satisfies ProceduralMemoryEntry;
+ });
+
+ const nextById = new Map(next.map((entry) => [entry.id, entry] as const));
+ let added = 0;
+ let updated = 0;
+
+ for (const entry of next) {
+ const old = prev.get(entry.id);
+ if (!old) {
+ added++;
+ continue;
+ }
+ if (JSON.stringify(old) !== JSON.stringify(entry)) {
+ updated++;
+ }
+ }
+
+ let removed = 0;
+ for (const id of prev.keys()) {
+ if (!nextById.has(id)) removed++;
+ }
+
+ writeIndex(vault, next);
+ return { total: next.length, added, updated, removed };
+}
+
+export function listProceduralMemory(
+ vault: string,
+): ReadonlyArray<ProceduralMemoryEntry> {
+ const path = proceduralMemoryIndexPath(vault);
+ if (!existsSync(path)) return Object.freeze([]);
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as {
+ entries?: Array<ProceduralMemoryEntry>;
+ };
+ if (!Array.isArray(parsed.entries)) return Object.freeze([]);
+ return Object.freeze(parsed.entries);
+ } catch {
+ return Object.freeze([]);
+ }
+}
+
+export function markProceduralMemoryUsed(
+ vault: string,
+ id: string,
+ now: Date = new Date(),
+): ProceduralMemoryEntry | null {
+ const entries = listProceduralMemory(vault);
+ const target = entries.find((entry) => entry.id === id);
+ if (!target) return null;
+
+ const next = entries.map((entry) =>
+ entry.id === id
+ ? {
+ ...entry,
+ usedCount: entry.usedCount + 1,
+ lastUsedAt: now.toISOString(),
+ }
+ : entry,
+ );
+ writeIndex(vault, next);
+
+ const usage = readUsageMap(vault);
+ const prev = usage.get(id);
+ usage.set(id, {
+ usedCount: (prev?.usedCount ?? 0) + 1,
+ lastUsedAt: now.toISOString(),
+ });
+ writeUsageMap(vault, usage);
+
+ return next.find((entry) => entry.id === id) ?? null;
+}
+
+function collectEntries(
+ vault: string,
+ roots: ReadonlyArray<string>,
+): ProceduralMemoryEntry[] {
+ const out: ProceduralMemoryEntry[] = [];
+
+ for (const root of roots) {
+ const safeRoot = ensureInsideVault(root, vault);
+ if (!existsSync(safeRoot)) continue;
+
+ for (const filePath of walkMarkdown(safeRoot)) {
+ const rel = toVaultRelative(vault, filePath);
+ const detectedKind = detectKind(rel);
+ if (detectedKind === null) continue;
+
+ const [fm, body] = parseFrontmatter(filePath);
+ const title = extractTitle(body, rel);
+ const id = entryId(rel);
+ out.push({
+ id,
+ kind: detectedKind,
+ sourcePath: rel,
+ title,
+ triggers: asStringArray(fm["triggers"]),
+ tags: asStringArray(fm["tags"]),
+ permissions: asStringArray(fm["permissions"]),
+ source: asStringOrNull(fm["source"]),
+ version: asStringOrNull(fm["version"]),
+ lastUsedAt: null,
+ usedCount: 0,
+ });
+ }
+ }
+
+ return out.toSorted((left, right) =>
+ left.sourcePath.localeCompare(right.sourcePath),
+ );
+}
+
+function detectKind(vaultRelPath: string): ProceduralEntryKind | null {
+ if (vaultRelPath.startsWith("Brain/procedures/")) return "procedure";
+ if (vaultRelPath.endsWith("/SKILL.md")) return "skill";
+ if (
+ vaultRelPath.endsWith(".prompt.md") ||
+ vaultRelPath.endsWith("runbook.md")
+ )
+ return "runbook";
+ return null;
+}
+
+function extractTitle(body: string, fallbackPath: string): string {
+ for (const line of body.split("\n")) {
+ if (line.startsWith("# ")) {
+ const title = line.slice(2).trim();
+ if (title) return title;
+ }
+ }
+ const parts = fallbackPath.split("/");
+ return parts[parts.length - 1] ?? fallbackPath;
+}
+
+function walkMarkdown(root: string): string[] {
+ const out: string[] = [];
+ const stack: string[] = [root];
+
+ while (stack.length > 0) {
+ const dir = stack.pop()!;
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ let st;
+ try {
+ st = lstatSync(path);
+ } catch {
+ continue;
+ }
+ if (st.isSymbolicLink()) continue;
+ if (st.isDirectory()) {
+ stack.push(path);
+ } else if (st.isFile() && name.endsWith(".md")) {
+ out.push(path);
+ }
+ }
+ }
+
+ return out;
+}
+
+function toVaultRelative(vault: string, absPath: string): string {
+ const rel = relative(vault, absPath).replaceAll("\\", "/");
+ return rel;
+}
+
+function entryId(sourcePath: string): string {
+ const hash = createHash("sha256")
+ .update(sourcePath, "utf8")
+ .digest("hex")
+ .slice(0, 12);
+ return `pmem-${hash}`;
+}
+
+function asStringArray(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value.filter(
+ (item): item is string =>
+ typeof item === "string" && item.trim().length > 0,
+ );
+ }
+ if (typeof value === "string" && value.trim().length > 0)
+ return [value.trim()];
+ return [];
+}
+
+function asStringOrNull(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0
+ ? value.trim()
+ : null;
+}
+
+function writeIndex(
+ vault: string,
+ entries: ReadonlyArray<ProceduralMemoryEntry>,
+): void {
+ const path = proceduralMemoryIndexPath(vault);
+ mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ const payload = JSON.stringify(
+ {
+ schema_version: 1,
+ entries,
+ },
+ null,
+ 2,
+ );
+ atomicWriteFileSync(path, `${payload}\n`);
+}
+
+function readUsageMap(
+ vault: string,
+): Map<string, { usedCount: number; lastUsedAt: string | null }> {
+ const path = proceduralMemoryUsagePath(vault);
+ if (!existsSync(path)) return new Map();
+
+ const out = new Map<
+ string,
+ { usedCount: number; lastUsedAt: string | null }
+ >();
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const parsed = JSON.parse(line) as Record<string, unknown>;
+ const id = typeof parsed["id"] === "string" ? parsed["id"] : null;
+ if (!id) continue;
+ out.set(id, {
+ usedCount:
+ typeof parsed["usedCount"] === "number" ? parsed["usedCount"] : 0,
+ lastUsedAt:
+ typeof parsed["lastUsedAt"] === "string"
+ ? parsed["lastUsedAt"]
+ : null,
+ });
+ } catch {
+ continue;
+ }
+ }
+ return out;
+}
+
+function writeUsageMap(
+ vault: string,
+ usage: ReadonlyMap<string, { usedCount: number; lastUsedAt: string | null }>,
+): void {
+ const path = proceduralMemoryUsagePath(vault);
+ mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ const lines: string[] = [];
+ for (const [id, value] of [...usage.entries()].toSorted((left, right) =>
+ left[0].localeCompare(right[0]),
+ )) {
+ lines.push(
+ JSON.stringify({
+ id,
+ usedCount: value.usedCount,
+ lastUsedAt: value.lastUsedAt,
+ }),
+ );
+ }
+ atomicWriteFileSync(
+ path,
+ `${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`,
+ );
+}
diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.ts
new file mode 100644
index 00000000..7b3dbaae
--- /dev/null
+++ b/src/core/brain/recurrence.ts
@@ -0,0 +1,209 @@
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname } from "node:path";
+
+import { ensureInsideVault } from "../path-safety.ts";
+import { proceduralRecurrencePath } from "./paths.ts";
+
+export type RecurrenceCommitment =
+ | "exploring"
+ | "leaning"
+ | "decided"
+ | "locked";
+export type RecurrenceAction = "learn" | "forget";
+
+export interface RecurrenceThresholds {
+ readonly leaning: number;
+ readonly decided: number;
+ readonly locked: number;
+}
+
+export interface RecurrenceEventInput {
+ readonly contentHash: string;
+ readonly scope: string;
+ readonly sourceId: string;
+ readonly action: RecurrenceAction;
+ readonly at?: string;
+}
+
+export interface RecurrenceEntry {
+ readonly contentHash: string;
+ readonly supportCount: number;
+ readonly recurrenceCount: number;
+ readonly scopes: ReadonlyArray<{ scope: string; support: number }>;
+ readonly commitment: RecurrenceCommitment;
+ readonly sources: ReadonlyArray<{ sourceId: string; support: number }>;
+}
+
+interface RecurrenceEvent {
+ readonly kind: "support" | "purge-source";
+ readonly contentHash?: string;
+ readonly scope?: string;
+ readonly sourceId: string;
+ readonly action?: RecurrenceAction;
+ readonly at: string;
+}
+
+const DEFAULT_THRESHOLDS: RecurrenceThresholds = {
+ leaning: 3,
+ decided: 5,
+ locked: 8,
+};
+
+export function applyRecurrenceEvidence(
+ vault: string,
+ input: RecurrenceEventInput,
+): RecurrenceEntry | null {
+ appendEvent(vault, {
+ kind: "support",
+ contentHash: input.contentHash,
+ scope: input.scope,
+ sourceId: input.sourceId,
+ action: input.action,
+ at: input.at ?? new Date().toISOString(),
+ });
+ return getRecurrenceEntry(vault, input.contentHash);
+}
+
+export function purgeRecurrenceSource(
+ vault: string,
+ sourceId: string,
+ at?: string,
+): void {
+ appendEvent(vault, {
+ kind: "purge-source",
+ sourceId,
+ at: at ?? new Date().toISOString(),
+ });
+}
+
+export function getRecurrenceEntry(
+ vault: string,
+ contentHash: string,
+ thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,
+): RecurrenceEntry | null {
+ return (
+ listRecurrenceEntries(vault, thresholds).find(
+ (entry) => entry.contentHash === contentHash,
+ ) ?? null
+ );
+}
+
+export function listRecurrenceEntries(
+ vault: string,
+ thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,
+): ReadonlyArray<RecurrenceEntry> {
+ const events = readEvents(vault);
+ const state = new Map<
+ string,
+ { supportBySourceScope: Map<string, number> }
+ >();
+
+ for (const event of events) {
+ if (event.kind === "purge-source") {
+ for (const value of state.values()) {
+ for (const key of value.supportBySourceScope.keys()) {
+ if (key.endsWith(`\u0000${event.sourceId}`)) {
+ value.supportBySourceScope.delete(key);
+ }
+ }
+ }
+ continue;
+ }
+
+ if (!event.contentHash || !event.scope || !event.action) continue;
+ const bucket = state.get(event.contentHash) ?? {
+ supportBySourceScope: new Map<string, number>(),
+ };
+ const sourceScopeKey = `${event.scope}\u0000${event.sourceId}`;
+ const current = bucket.supportBySourceScope.get(sourceScopeKey) ?? 0;
+
+ if (event.action === "learn") {
+ bucket.supportBySourceScope.set(sourceScopeKey, current + 1);
+ } else {
+ if (current > 1)
+ bucket.supportBySourceScope.set(sourceScopeKey, current - 1);
+ else bucket.supportBySourceScope.delete(sourceScopeKey);
+ }
+
+ state.set(event.contentHash, bucket);
+ }
+
+ const out: RecurrenceEntry[] = [];
+ for (const [contentHash, bucket] of state) {
+ const supportByScope = new Map<string, number>();
+ const supportBySource = new Map<string, number>();
+ for (const [sourceScopeKey, support] of bucket.supportBySourceScope) {
+ if (support < 1) continue;
+ const [scope, sourceId] = splitSourceScopeKey(sourceScopeKey);
+ if (!scope || !sourceId) continue;
+ supportByScope.set(scope, (supportByScope.get(scope) ?? 0) + support);
+ supportBySource.set(
+ sourceId,
+ (supportBySource.get(sourceId) ?? 0) + support,
+ );
+ }
+
+ const scopes = [...supportByScope.entries()]
+ .filter((item) => item[1] > 0)
+ .map(([scope, support]) => ({ scope, support }))
+ .toSorted((left, right) => left.scope.localeCompare(right.scope));
+ const sources = [...supportBySource.entries()]
+ .filter((item) => item[1] > 0)
+ .map(([sourceId, support]) => ({ sourceId, support }))
+ .toSorted((left, right) => left.sourceId.localeCompare(right.sourceId));
+ const supportCount = scopes.reduce((sum, item) => sum + item.support, 0);
+ if (supportCount < 1) continue;
+
+ out.push({
+ contentHash,
+ supportCount,
+ recurrenceCount: scopes.length,
+ scopes: Object.freeze(scopes),
+ commitment: commitmentForSupport(supportCount, thresholds),
+ sources: Object.freeze(sources),
+ });
+ }
+
+ return Object.freeze(
+ out.toSorted((left, right) =>
+ left.contentHash.localeCompare(right.contentHash),
+ ),
+ );
+}
+
+function splitSourceScopeKey(value: string): [string, string] {
+ const idx = value.indexOf("\u0000");
+ if (idx < 0) return ["", ""];
+ return [value.slice(0, idx), value.slice(idx + 1)];
+}
+
+function commitmentForSupport(
+ supportCount: number,
+ thresholds: RecurrenceThresholds,
+): RecurrenceCommitment {
+ if (supportCount >= thresholds.locked) return "locked";
+ if (supportCount >= thresholds.decided) return "decided";
+ if (supportCount >= thresholds.leaning) return "leaning";
+ return "exploring";
+}
+
+function appendEvent(vault: string, event: RecurrenceEvent): void {
+ const path = proceduralRecurrencePath(vault);
+ mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ appendFileSync(path, `${JSON.stringify(event)}\n`, { encoding: "utf8" });
+}
+
+function readEvents(vault: string): RecurrenceEvent[] {
+ const path = proceduralRecurrencePath(vault);
+ if (!existsSync(path)) return [];
+ const out: RecurrenceEvent[] = [];
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ out.push(JSON.parse(line) as RecurrenceEvent);
+ } catch {
+ continue;
+ }
+ }
+ return out;
+}
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
new file mode 100644
index 00000000..df2e2cd9
--- /dev/null
+++ b/src/core/brain/skill-proposals.ts
@@ -0,0 +1,559 @@
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ unlinkSync,
+} from "node:fs";
+import { basename, dirname, join } from "node:path";
+
+import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import {
+ BRAIN_SKILL_PROPOSALS_REL,
+ procedurePath,
+ proposalWatermarkPath,
+ skillProposalAcceptedPath,
+ skillProposalPendingPath,
+ skillProposalRejectedPath,
+} from "./paths.ts";
+import {
+ listContinuityRecords,
+ type ContinuityRecord,
+} from "./continuity/store.ts";
+
+export type SkillProposalPatternKind =
+ | "repeated_action"
+ | "structural_similarity"
+ | "co_occurrence"
+ | "temporal_routine";
+
+export interface SkillProposalLearnOptions {
+ readonly now?: Date;
+ readonly minSupport?: number;
+}
+
+export interface SkillProposalLearnResult {
+ readonly watermarkFrom: string | null;
+ readonly watermarkTo: string | null;
+ readonly scanned: number;
+ readonly created: ReadonlyArray<string>;
+ readonly suppressed: ReadonlyArray<string>;
+}
+
+export interface SkillProposalReviewResult {
+ readonly id: string;
+ readonly slug: string;
+ readonly status: "accepted" | "rejected";
+ readonly proposalPath: string;
+ readonly procedurePath?: string;
+}
+
+interface ProposalCandidate {
+ readonly patternKind: SkillProposalPatternKind;
+ readonly key: string;
+ readonly confidence: number;
+ readonly records: ReadonlyArray<ContinuityRecord>;
+ readonly suggestedTitle: string;
+}
+
+interface WatermarkState {
+ readonly lastCreatedAt: string | null;
+ readonly lastId: string | null;
+}
+
+const DEFAULT_MIN_SUPPORT = 3;
+
+export function learnSkillProposals(
+ vault: string,
+ opts: SkillProposalLearnOptions = {},
+): SkillProposalLearnResult {
+ const now = opts.now ?? new Date();
+ const minSupport = Math.max(2, opts.minSupport ?? DEFAULT_MIN_SUPPORT);
+
+ const watermark = readWatermark(vault);
+ const records = listContinuityRecords(vault)
+ .filter((record) => {
+ if (watermark.lastCreatedAt === null) return true;
+ if (record.createdAt > watermark.lastCreatedAt) return true;
+ if (record.createdAt < watermark.lastCreatedAt) return false;
+ if (watermark.lastId === null) return true;
+ return record.id > watermark.lastId;
+ })
+ .toSorted(
+ (left, right) =>
+ left.createdAt.localeCompare(right.createdAt) ||
+ left.id.localeCompare(right.id),
+ );
+
+ if (records.length === 0) {
+ return {
+ watermarkFrom: watermark.lastCreatedAt,
+ watermarkTo: watermark.lastCreatedAt,
+ scanned: 0,
+ created: Object.freeze([]),
+ suppressed: Object.freeze([]),
+ };
+ }
+
+ const candidates = detectCandidates(records, minSupport);
+ const created: string[] = [];
+ const suppressed: string[] = [];
+
+ for (const candidate of candidates) {
+ const payloadHash = candidateHash(candidate);
+ const slug = proposalSlug(candidate, payloadHash);
+ const proposalId = `prop-${slug}`;
+
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ const acceptedPath = skillProposalAcceptedPath(vault, slug);
+ const rejectedPath = skillProposalRejectedPath(vault, slug);
+
+ if (
+ existsSync(pendingPath) ||
+ existsSync(acceptedPath) ||
+ existsSync(rejectedPath)
+ ) {
+ suppressed.push(proposalId);
+ continue;
+ }
+
+ writeFrontmatterAtomic(
+ pendingPath,
+ {
+ schema_version: 1,
+ kind: "brain-skill-proposal",
+ id: proposalId,
+ slug,
+ status: "pending",
+ pattern_kind: candidate.patternKind,
+ confidence: candidate.confidence.toFixed(3),
+ payload_hash: payloadHash,
+ created_at: now.toISOString(),
+ updated_at: now.toISOString(),
+ watermark_from: watermark.lastCreatedAt ?? "",
+ watermark_to: records[records.length - 1]!.createdAt,
+ evidence_count: String(candidate.records.length),
+ source_refs: candidate.records.flatMap((record) => [
+ record.id,
+ ...record.sourceRefs.map((src) => src.id),
+ ]),
+ },
+ renderProposalBody(candidate),
+ {
+ overwrite: false,
+ existsErrorKind: "skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+ created.push(proposalId);
+ }
+
+ const watermarkRecord = records[records.length - 1]!;
+ const watermarkTo = watermarkRecord.createdAt;
+ writeWatermark(vault, {
+ lastCreatedAt: watermarkTo,
+ lastId: watermarkRecord.id,
+ });
+
+ return {
+ watermarkFrom: watermark.lastCreatedAt,
+ watermarkTo,
+ scanned: records.length,
+ created: Object.freeze(created),
+ suppressed: Object.freeze(suppressed),
+ };
+}
+
+export function listPendingSkillProposals(vault: string): ReadonlyArray<{
+ id: string;
+ slug: string;
+ status: string;
+ patternKind: string;
+}> {
+ const dir = ensureInsideVault(
+ join(vault, BRAIN_SKILL_PROPOSALS_REL, "pending"),
+ vault,
+ );
+ if (!existsSync(dir)) return Object.freeze([]);
+
+ const out: Array<{
+ id: string;
+ slug: string;
+ status: string;
+ patternKind: string;
+ }> = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(".md")) continue;
+ const path = ensureInsideVault(join(dir, name), vault);
+ const [fm] = parseFrontmatter(path);
+ if (fm["kind"] !== "brain-skill-proposal") continue;
+ if (typeof fm["id"] !== "string") continue;
+ out.push({
+ id: fm["id"],
+ slug:
+ typeof fm["slug"] === "string"
+ ? fm["slug"]
+ : fm["id"].replace(/^prop-/, ""),
+ status: typeof fm["status"] === "string" ? fm["status"] : "pending",
+ patternKind:
+ typeof fm["pattern_kind"] === "string" ? fm["pattern_kind"] : "unknown",
+ });
+ }
+ return Object.freeze(out);
+}
+
+export function acceptSkillProposal(
+ vault: string,
+ slug: string,
+ opts: { now?: Date; note?: string } = {},
+): SkillProposalReviewResult {
+ const now = (opts.now ?? new Date()).toISOString();
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ if (!existsSync(pendingPath)) {
+ throw new Error(`pending skill proposal not found: ${slug}`);
+ }
+
+ const [fm, body] = parseFrontmatter(pendingPath);
+ if (fm["kind"] !== "brain-skill-proposal") {
+ throw new Error(`invalid skill proposal file: ${pendingPath}`);
+ }
+ const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
+ const acceptedPath = skillProposalAcceptedPath(vault, slug);
+ const procPath = procedurePath(vault, slug);
+
+ writeFrontmatterAtomic(
+ acceptedPath,
+ {
+ ...fm,
+ status: "accepted",
+ reviewed_at: now,
+ updated_at: now,
+ ...(opts.note ? { review_note: opts.note } : {}),
+ },
+ body,
+ {
+ overwrite: false,
+ existsErrorKind: "accepted skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ try {
+ writeFrontmatterAtomic(
+ procPath,
+ {
+ schema_version: 1,
+ kind: "brain-procedure",
+ id: `proc-${slug}`,
+ slug,
+ source_proposal: id,
+ created_at: now,
+ updated_at: now,
+ status: "active",
+ },
+ renderAcceptedProcedureBody(id, body),
+ {
+ overwrite: false,
+ existsErrorKind: "procedure",
+ vaultForRelativePath: vault,
+ },
+ );
+ } catch (error) {
+ if (existsSync(acceptedPath)) unlinkSync(acceptedPath);
+ throw error;
+ }
+
+ unlinkSync(pendingPath);
+ return {
+ id,
+ slug,
+ status: "accepted",
+ proposalPath: acceptedPath,
+ procedurePath: procPath,
+ };
+}
+
+export function rejectSkillProposal(
+ vault: string,
+ slug: string,
+ opts: { now?: Date; note: string },
+): SkillProposalReviewResult {
+ if (!opts.note.trim()) {
+ throw new Error("rejecting skill proposal requires a non-empty note");
+ }
+
+ const now = (opts.now ?? new Date()).toISOString();
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ if (!existsSync(pendingPath)) {
+ throw new Error(`pending skill proposal not found: ${slug}`);
+ }
+
+ const [fm, body] = parseFrontmatter(pendingPath);
+ if (fm["kind"] !== "brain-skill-proposal") {
+ throw new Error(`invalid skill proposal file: ${pendingPath}`);
+ }
+ const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
+ const rejectedPath = skillProposalRejectedPath(vault, slug);
+
+ writeFrontmatterAtomic(
+ rejectedPath,
+ {
+ ...fm,
+ status: "rejected",
+ reviewed_at: now,
+ updated_at: now,
+ review_note: opts.note,
+ },
+ body,
+ {
+ overwrite: false,
+ existsErrorKind: "rejected skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ unlinkSync(pendingPath);
+ return { id, slug, status: "rejected", proposalPath: rejectedPath };
+}
+
+function readWatermark(vault: string): WatermarkState {
+ const path = watermarkPath(vault);
+ if (!existsSync(path)) return { lastCreatedAt: null, lastId: null };
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ return {
+ lastCreatedAt:
+ typeof parsed["lastCreatedAt"] === "string"
+ ? parsed["lastCreatedAt"]
+ : null,
+ lastId: typeof parsed["lastId"] === "string" ? parsed["lastId"] : null,
+ };
+ } catch {
+ return { lastCreatedAt: null, lastId: null };
+ }
+}
+
+function writeWatermark(vault: string, state: WatermarkState): void {
+ const path = proposalWatermarkPath(vault);
+ const root = ensureInsideVault(dirname(path), vault);
+ mkdirSync(root, { recursive: true });
+ const payload = JSON.stringify(state, null, 2);
+ atomicWriteFileSync(path, `${payload}\n`);
+}
+
+function watermarkPath(vault: string): string {
+ return proposalWatermarkPath(vault);
+}
+
+function detectCandidates(
+ records: ReadonlyArray<ContinuityRecord>,
+ minSupport: number,
+): ProposalCandidate[] {
+ const out: ProposalCandidate[] = [];
+
+ const actionMap = new Map<string, ContinuityRecord[]>();
+ for (const record of records) {
+ const action = actionToken(record);
+ if (!action) continue;
+ const bucket = actionMap.get(action) ?? [];
+ bucket.push(record);
+ actionMap.set(action, bucket);
+ }
+ for (const [action, bucket] of actionMap) {
+ if (bucket.length < minSupport) continue;
+ out.push({
+ patternKind: "repeated_action",
+ key: action,
+ confidence: confidence(bucket.length, minSupport),
+ records: Object.freeze(bucket.slice(0, 6)),
+ suggestedTitle: `Repeated action: ${action}`,
+ });
+ }
+
+ const shapeMap = new Map<string, ContinuityRecord[]>();
+ for (const record of records) {
+ const shape = shapeSignature(record);
+ if (!shape) continue;
+ const bucket = shapeMap.get(shape) ?? [];
+ bucket.push(record);
+ shapeMap.set(shape, bucket);
+ }
+ for (const [shape, bucket] of shapeMap) {
+ if (bucket.length < minSupport) continue;
+ out.push({
+ patternKind: "structural_similarity",
+ key: shape,
+ confidence: confidence(bucket.length, minSupport),
+ records: Object.freeze(bucket.slice(0, 6)),
+ suggestedTitle: `Structural routine: ${shape}`,
+ });
+ }
+
+ const pairMap = new Map<string, ContinuityRecord[]>();
+ for (let i = 1; i < records.length; i++) {
+ const left = actionToken(records[i - 1]!);
+ const right = actionToken(records[i]!);
+ if (!left || !right || left === right) continue;
+ const pair = `${left} -> ${right}`;
+ const bucket = pairMap.get(pair) ?? [];
+ bucket.push(records[i - 1]!, records[i]!);
+ pairMap.set(pair, bucket);
+ }
+ for (const [pair, bucket] of pairMap) {
+ const support = Math.floor(bucket.length / 2);
+ if (support < minSupport) continue;
+ out.push({
+ patternKind: "co_occurrence",
+ key: pair,
+ confidence: confidence(support, minSupport),
+ records: Object.freeze(bucket.slice(0, 6)),
+ suggestedTitle: `Co-occurrence flow: ${pair}`,
+ });
+ }
+
+ const temporalMap = new Map<string, ContinuityRecord[]>();
+ for (const record of records) {
+ const action = actionToken(record);
+ if (!action) continue;
+ const hour = isoHour(record.createdAt);
+ if (hour === null) continue;
+ const key = `${action}@${hour}`;
+ const bucket = temporalMap.get(key) ?? [];
+ bucket.push(record);
+ temporalMap.set(key, bucket);
+ }
+ for (const [key, bucket] of temporalMap) {
+ const daySet = new Set(
+ bucket.map((record) => record.createdAt.slice(0, 10)),
+ );
+ if (daySet.size < minSupport) continue;
+ out.push({
+ patternKind: "temporal_routine",
+ key,
+ confidence: confidence(daySet.size, minSupport),
+ records: Object.freeze(bucket.slice(0, 6)),
+ suggestedTitle: `Temporal routine: ${key}`,
+ });
+ }
+
+ return out.toSorted(
+ (left, right) =>
+ left.patternKind.localeCompare(right.patternKind) ||
+ left.key.localeCompare(right.key),
+ );
+}
+
+function actionToken(record: ContinuityRecord): string | null {
+ const payload = record.payload as Record<string, unknown>;
+ for (const field of ["action", "command", "tool", "verb", "event"]) {
+ const value = payload[field];
+ if (typeof value === "string" && value.trim()) {
+ return value.trim().toLowerCase();
+ }
+ }
+ return null;
+}
+
+function shapeSignature(record: ContinuityRecord): string | null {
+ const keys = Object.keys(record.payload).toSorted();
+ if (keys.length === 0) return null;
+ return `${record.kind}:${keys.join(",")}`;
+}
+
+function isoHour(iso: string): string | null {
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return null;
+ return String(date.getUTCHours()).padStart(2, "0");
+}
+
+function confidence(support: number, minSupport: number): number {
+ const raw = Math.min(0.99, 0.55 + (support - minSupport) * 0.1);
+ return Math.max(0.55, Math.round(raw * 1000) / 1000);
+}
+
+function renderProposalBody(candidate: ProposalCandidate): string {
+ const evidence = candidate.records
+ .map((record) => {
+ const snippet = evidenceSnippet(record);
+ return `- ${record.createdAt} :: ${record.kind} :: ${record.id}${snippet ? ` :: ${snippet}` : ""}`;
+ })
+ .join("\n");
+
+ return [
+ `# ${candidate.suggestedTitle}`,
+ "",
+ "## Pattern",
+ `- kind: ${candidate.patternKind}`,
+ `- key: ${candidate.key}`,
+ "",
+ "## Suggested skill body",
+ `When pattern \`${candidate.key}\` appears, follow the observed repeatable workflow.`,
+ "Capture inputs first, execute steps in stable order, and emit audit-friendly outputs.",
+ "",
+ "## Evidence",
+ evidence,
+ ].join("\n");
+}
+
+function evidenceSnippet(record: ContinuityRecord): string {
+ const payload = record.payload as Record<string, unknown>;
+ for (const field of ["query", "summary", "note", "text"]) {
+ const value = payload[field];
+ if (typeof value === "string" && value.trim()) {
+ return value.trim().slice(0, 120);
+ }
+ }
+ return "";
+}
+
+function proposalSlug(
+ candidate: ProposalCandidate,
+ payloadHash: string,
+): string {
+ const keySlug = slugify(candidate.key).slice(0, 40);
+ return `${candidate.patternKind}-${keySlug}-${payloadHash.slice(0, 8)}`;
+}
+
+function candidateHash(candidate: ProposalCandidate): string {
+ return createHash("sha256")
+ .update(
+ JSON.stringify({
+ patternKind: candidate.patternKind,
+ key: candidate.key,
+ records: candidate.records.map((record) => record.id),
+ }),
+ "utf8",
+ )
+ .digest("hex");
+}
+
+function renderAcceptedProcedureBody(
+ proposalId: string,
+ proposalBody: string,
+): string {
+ const marker = "## Suggested skill body";
+ const idx = proposalBody.indexOf(marker);
+ const suggested =
+ idx >= 0
+ ? proposalBody.slice(idx + marker.length).trim()
+ : proposalBody.trim();
+ return [
+ "# Procedure",
+ "",
+ `Accepted from proposal: [[${proposalId}]]`,
+ "",
+ suggested || "No suggested body was captured.",
+ ].join("\n");
+}
+
+export function skillProposalSlugFromPath(path: string): string | null {
+ const name = basename(path);
+ if (!name.startsWith("prop-") || !name.endsWith(".md")) return null;
+ return name.slice("prop-".length, -".md".length);
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index d08c3f7b..8e3ae7fd 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -36,7 +36,7 @@
* one-way (Brain tools may grow their own coercion rules later).
*/
-import { isAbsolute, relative, resolve } from "node:path";
+import { isAbsolute, join, relative, resolve } from "node:path";
import { existsSync, readFileSync } from "node:fs";
@@ -99,6 +99,23 @@ import {
expandSessionRecall,
searchSessionRecall,
} from "../core/brain/session-recall.ts";
+import {
+ acceptSkillProposal,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ rejectSkillProposal,
+} from "../core/brain/skill-proposals.ts";
+import {
+ listProceduralMemory,
+ markProceduralMemoryUsed,
+ reconcileProceduralMemory,
+} from "../core/brain/procedural-memory.ts";
+import {
+ applyRecurrenceEvidence,
+ getRecurrenceEntry,
+ listRecurrenceEntries,
+ purgeRecurrenceSource,
+} from "../core/brain/recurrence.ts";
import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";
import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";
@@ -2151,6 +2168,120 @@ function telemetryOptionsFromArgs(
};
}
+async function toolBrainSkillProposals(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_skill_proposals", args, "operation");
+ if (operation === "learn") {
+ const minSupport = optionalPositiveInt(args, "min_support", "brain_skill_proposals");
+ const result =
+ minSupport !== undefined
+ ? learnSkillProposals(ctx.vault, { minSupport })
+ : learnSkillProposals(ctx.vault);
+ return { ...result };
+ }
+ if (operation === "list") {
+ const proposals = listPendingSkillProposals(ctx.vault);
+ return { total: proposals.length, proposals };
+ }
+ if (operation === "accept") {
+ const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ const note = optionalStringArg("brain_skill_proposals", args, "note");
+ const reviewed = note
+ ? acceptSkillProposal(ctx.vault, slug, { note })
+ : acceptSkillProposal(ctx.vault, slug);
+ return { ...reviewed };
+ }
+ if (operation === "reject") {
+ const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ const note = requiredStringArg("brain_skill_proposals", args, "note");
+ const reviewed = rejectSkillProposal(ctx.vault, slug, { note });
+ return { ...reviewed };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_skill_proposals: operation must be one of learn|list|accept|reject",
+ );
+}
+
+async function toolBrainProceduralMemory(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_procedural_memory", args, "operation");
+ if (operation === "reconcile") {
+ const roots = coerceStrList(args, "roots");
+ const effectiveRoots =
+ roots.length > 0
+ ? roots
+ : [
+ join(ctx.vault, "Brain", "procedures"),
+ join(ctx.vault, "skills"),
+ join(ctx.vault, "runbooks"),
+ ];
+ return {
+ ...reconcileProceduralMemory(ctx.vault, { roots: effectiveRoots }),
+ };
+ }
+ if (operation === "list") {
+ const entries = listProceduralMemory(ctx.vault);
+ return { total: entries.length, entries };
+ }
+ if (operation === "mark_used") {
+ const id = requiredStringArg("brain_procedural_memory", args, "id");
+ const updated = markProceduralMemoryUsed(ctx.vault, id);
+ if (!updated) {
+ throw new MCPError(INVALID_PARAMS, `brain_procedural_memory: unknown entry id: ${id}`);
+ }
+ return { ...updated };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_procedural_memory: operation must be one of reconcile|list|mark_used",
+ );
+}
+
+async function toolBrainRecurrence(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_recurrence", args, "operation");
+ if (operation === "list") {
+ const entries = listRecurrenceEntries(ctx.vault);
+ return { total: entries.length, entries };
+ }
+ if (operation === "show") {
+ const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
+ const entry = getRecurrenceEntry(ctx.vault, contentHash);
+ if (!entry) {
+ throw new MCPError(INVALID_PARAMS, `brain_recurrence: unknown content hash: ${contentHash}`);
+ }
+ return { ...entry };
+ }
+ if (operation === "learn" || operation === "forget") {
+ const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
+ const scope = requiredStringArg("brain_recurrence", args, "scope");
+ const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
+ const entry = applyRecurrenceEvidence(ctx.vault, {
+ contentHash,
+ scope,
+ sourceId,
+ action: operation,
+ });
+ return { operation, entry };
+ }
+ if (operation === "purge_source") {
+ const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
+ purgeRecurrenceSource(ctx.vault, sourceId);
+ return { ok: true, source_id: sourceId };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recurrence: operation must be one of list|show|learn|forget|purge_source",
+ );
+}
+
async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
const landscape = buildMcpLandscape(ctx.vault);
return {
@@ -2900,6 +3031,94 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainContextPresets,
},
+ {
+ name: "brain_skill_proposals",
+ description:
+ "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["learn", "list", "accept", "reject"],
+ description: "Tool operation.",
+ },
+ min_support: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional minimum evidence support for learn.",
+ },
+ slug: {
+ type: "string",
+ description: "Proposal slug for accept/reject.",
+ },
+ note: {
+ type: "string",
+ description: "Optional review note; required for reject.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSkillProposals,
+ },
+ {
+ name: "brain_procedural_memory",
+ description:
+ "Reconcile/list procedural memory index and update usage sidecar (reconcile, list, mark_used).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["reconcile", "list", "mark_used"],
+ description: "Tool operation.",
+ },
+ roots: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional root directories for reconcile.",
+ },
+ id: {
+ type: "string",
+ description: "Procedural entry id for mark_used.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainProceduralMemory,
+ },
+ {
+ name: "brain_recurrence",
+ description:
+ "Inspect and update recurrence/support diagnostics (list, show, learn, forget, purge_source).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "show", "learn", "forget", "purge_source"],
+ description: "Tool operation.",
+ },
+ content_hash: {
+ type: "string",
+ description: "Content hash for show/learn/forget.",
+ },
+ scope: {
+ type: "string",
+ description: "Scope for learn/forget.",
+ },
+ source_id: {
+ type: "string",
+ description: "Source id for learn/forget/purge_source.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainRecurrence,
+ },
{
name: "brain_pre_compact_extract",
description:
diff --git a/tests/cli/brain-procedural-learning.test.ts b/tests/cli/brain-procedural-learning.test.ts
new file mode 100644
index 00000000..1d5ffb92
--- /dev/null
+++ b/tests/cli/brain-procedural-learning.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-procedural-cli-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, "skills", "release"), { recursive: true });
+ writeFileSync(
+ join(vault, "skills", "release", "SKILL.md"),
+ [
+ "---",
+ "triggers: [release]",
+ "tags: [ops]",
+ "permissions: [read]",
+ "source: cli-test",
+ "version: 1",
+ "---",
+ "# Release skill",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("brain procedural learning verbs wire end-to-end", async () => {
+ seedContinuity(vault);
+
+ const learned = await runCli([
+ "brain",
+ "skill-proposals",
+ "learn",
+ "--vault",
+ vault,
+ "--json",
+ "--min-support",
+ "3",
+ ]);
+ expect(learned.returncode).toBe(0);
+ const learnedJson = JSON.parse(learned.stdout);
+ expect(learnedJson.created.length).toBeGreaterThanOrEqual(1);
+
+ const listed = await runCli(["brain", "skill-proposals", "list", "--vault", vault, "--json"]);
+ expect(listed.returncode).toBe(0);
+ const listJson = JSON.parse(listed.stdout);
+ expect(listJson.total).toBeGreaterThanOrEqual(1);
+ const slug = listJson.proposals[0]?.slug;
+ expect(typeof slug).toBe("string");
+
+ const accepted = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ slug,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(accepted.returncode).toBe(0);
+
+ const rec = await runCli(["brain", "procedural-memory", "reconcile", "--vault", vault, "--json"]);
+ expect(rec.returncode).toBe(0);
+ const recJson = JSON.parse(rec.stdout);
+ expect(recJson.total).toBeGreaterThanOrEqual(1);
+
+ const mem = await runCli(["brain", "procedural-memory", "list", "--vault", vault, "--json"]);
+ expect(mem.returncode).toBe(0);
+ const memJson = JSON.parse(mem.stdout);
+ expect(memJson.total).toBeGreaterThanOrEqual(1);
+
+ const id = memJson.entries[0]?.id;
+ expect(typeof id).toBe("string");
+ const mark = await runCli([
+ "brain",
+ "procedural-memory",
+ "mark-used",
+ id,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(mark.returncode).toBe(0);
+
+ const learnRecurrence = await runCli([
+ "brain",
+ "recurrence",
+ "learn",
+ "--hash",
+ "abc123",
+ "--scope",
+ "project-a",
+ "--source",
+ "src-1",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(learnRecurrence.returncode).toBe(0);
+
+ const showRecurrence = await runCli([
+ "brain",
+ "recurrence",
+ "show",
+ "abc123",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(showRecurrence.returncode).toBe(0);
+ const recShowJson = JSON.parse(showRecurrence.stdout);
+ expect(recShowJson.supportCount).toBe(1);
+});
+
+function seedContinuity(vaultPath: string): void {
+ for (const row of [
+ ["2026-06-01T08:00:00Z", "triage_inbox"],
+ ["2026-06-02T08:00:00Z", "triage_inbox"],
+ ["2026-06-03T08:00:00Z", "triage_inbox"],
+ ["2026-06-01T08:05:00Z", "prepare_release_notes"],
+ ["2026-06-02T08:05:00Z", "prepare_release_notes"],
+ ["2026-06-03T08:05:00Z", "prepare_release_notes"],
+ ] as const) {
+ appendContinuityRecord(vaultPath, {
+ kind: "session_turn",
+ createdAt: row[0],
+ sourceRefs: [{ id: `src-${row[0]}` }],
+ payload: {
+ action: row[1],
+ summary: `Investigate issue ${row[0]}`,
+ },
+ });
+ }
+}
diff --git a/tests/core/brain/context-receipts.test.ts b/tests/core/brain/context-receipts.test.ts
index 9044409d..5ab8c361 100644
--- a/tests/core/brain/context-receipts.test.ts
+++ b/tests/core/brain/context-receipts.test.ts
@@ -9,10 +9,7 @@ import { emitContextReceipt } from "../../../src/core/brain/context-receipts.ts"
import { brainActivePath } from "../../../src/core/brain/paths.ts";
import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
import { writePreference } from "../../../src/core/brain/preference.ts";
-import {
- BRAIN_CONFIDENCE,
- BRAIN_PREFERENCE_STATUS,
-} from "../../../src/core/brain/types.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
let vault: string;
@@ -29,12 +26,7 @@ afterEach(() => {
describe("context receipts", () => {
test("packContext can emit a redaction-safe receipt without changing selected items", () => {
- writePref(
- "alpha",
- "alpha topic",
- "Keep answers short",
- "Body with token=secret-value",
- );
+ writePref("alpha", "alpha topic", "Keep answers short", "Body with token=secret-value");
const pack = packContext(vault, {
maxTokens: 10_000,
@@ -71,10 +63,7 @@ describe("context receipts", () => {
});
test("buildPreCompressPack can emit a receipt for active head and preference items", () => {
- writeFileSync(
- brainActivePath(vault),
- "# Active\n\nUse project conventions.\n",
- );
+ writeFileSync(brainActivePath(vault), "# Active\n\nUse project conventions.\n");
writePref("bravo", "bravo topic", "Prefer concrete release notes", "Body");
const pack = buildPreCompressPack(vault, {
@@ -119,12 +108,7 @@ describe("context receipts", () => {
});
});
-function writePref(
- slug: string,
- topic: string,
- principle: string,
- body: string,
-): void {
+function writePref(slug: string, topic: string, principle: string, body: string): void {
writePreference(vault, {
slug,
topic,
diff --git a/tests/core/brain/continuity-store.test.ts b/tests/core/brain/continuity-store.test.ts
index b9ff3399..ae64f054 100644
--- a/tests/core/brain/continuity-store.test.ts
+++ b/tests/core/brain/continuity-store.test.ts
@@ -27,9 +27,7 @@ describe("continuity store", () => {
const record = appendContinuityRecord(vault, {
kind: "context_receipt",
createdAt: "2026-05-31T12:00:00Z",
- sourceRefs: [
- { id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" },
- ],
+ sourceRefs: [{ id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" }],
payload: {
query: "project setup",
text: "Keep this <private>do not persist</private> and token=secret-value",
@@ -68,19 +66,14 @@ describe("continuity store", () => {
}
const first = paginateContinuityRecords(vault, { limit: 2 });
- expect(first.records.map((record) => record.sourceRefs[0]!.id)).toEqual([
- "query-0",
- "query-1",
- ]);
+ expect(first.records.map((record) => record.sourceRefs[0]!.id)).toEqual(["query-0", "query-1"]);
expect(first.nextCursor).not.toBeNull();
const second = paginateContinuityRecords(vault, {
limit: 2,
cursor: first.nextCursor!,
});
- expect(second.records.map((record) => record.sourceRefs[0]!.id)).toEqual([
- "query-2",
- ]);
+ expect(second.records.map((record) => record.sourceRefs[0]!.id)).toEqual(["query-2"]);
expect(second.nextCursor).toBeNull();
});
@@ -127,9 +120,6 @@ describe("continuity store", () => {
const records = listContinuityRecords(vault, {
sourceId: "session-a#turn-1",
});
- expect(records.map((record) => record.kind)).toEqual([
- "session_turn",
- "source_invalidation",
- ]);
+ expect(records.map((record) => record.kind)).toEqual(["session_turn", "source_invalidation"]);
});
});
diff --git a/tests/core/brain/procedural-memory.test.ts b/tests/core/brain/procedural-memory.test.ts
new file mode 100644
index 00000000..21fe9ecd
--- /dev/null
+++ b/tests/core/brain/procedural-memory.test.ts
@@ -0,0 +1,129 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ listProceduralMemory,
+ markProceduralMemoryUsed,
+ reconcileProceduralMemory,
+} from "../../../src/core/brain/procedural-memory.ts";
+import { proceduralMemoryUsagePath } from "../../../src/core/brain/paths.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = join(
+ tmpdir(),
+ `o2b-procedural-memory-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ );
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("procedural memory reconciler", () => {
+ test("parses metadata, updates on source changes, and removes stale entries", () => {
+ const roots = seedProceduralSources(vault);
+
+ const first = reconcileProceduralMemory(vault, { roots });
+ expect(first.total).toBe(2);
+ expect(first.added).toBe(2);
+
+ const listed = listProceduralMemory(vault);
+ const skill = listed.find((entry) => entry.kind === "skill");
+ expect(skill).toBeDefined();
+ expect(skill?.triggers).toContain("release");
+ expect(skill?.tags).toContain("ops");
+
+ writeFileSync(
+ join(vault, "skills", "release", "SKILL.md"),
+ [
+ "---",
+ "version: 2",
+ "triggers: [release, changelog]",
+ "tags: [ops, ci]",
+ "permissions: [read, write]",
+ "source: test-suite",
+ "---",
+ "# Release Skill",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ const second = reconcileProceduralMemory(vault, { roots });
+ expect(second.updated).toBeGreaterThanOrEqual(1);
+
+ rmSync(join(vault, "Brain", "procedures", "proc-release-notes.md"));
+ const third = reconcileProceduralMemory(vault, { roots });
+ expect(third.removed).toBe(1);
+ expect(
+ listProceduralMemory(vault).some((entry) =>
+ entry.sourcePath.includes("proc-release-notes.md"),
+ ),
+ ).toBe(false);
+ });
+
+ test("usage tracking updates sidecar/index without rewriting source files", () => {
+ const roots = seedProceduralSources(vault);
+ reconcileProceduralMemory(vault, { roots });
+
+ const sourcePath = join(vault, "skills", "release", "SKILL.md");
+ const beforeSource = readFileSync(sourcePath, "utf8");
+ const beforeStat = statSync(sourcePath).mtimeMs;
+
+ const entry = listProceduralMemory(vault).find((item) => item.kind === "skill");
+ expect(entry).toBeDefined();
+
+ const updated = markProceduralMemoryUsed(vault, entry!.id, new Date("2026-06-01T15:00:00Z"));
+ expect(updated?.usedCount).toBe(1);
+ expect(updated?.lastUsedAt).toBe("2026-06-01T15:00:00.000Z");
+
+ const afterSource = readFileSync(sourcePath, "utf8");
+ const afterStat = statSync(sourcePath).mtimeMs;
+ expect(afterSource).toBe(beforeSource);
+ expect(afterStat).toBe(beforeStat);
+
+ const usage = readFileSync(proceduralMemoryUsagePath(vault), "utf8");
+ expect(usage).toContain(entry!.id);
+ });
+});
+
+function seedProceduralSources(vaultPath: string): string[] {
+ const proceduresDir = join(vaultPath, "Brain", "procedures");
+ const skillsDir = join(vaultPath, "skills", "release");
+ mkdirSync(proceduresDir, { recursive: true });
+ mkdirSync(skillsDir, { recursive: true });
+
+ writeFileSync(
+ join(proceduresDir, "proc-release-notes.md"),
+ [
+ "---",
+ "kind: brain-procedure",
+ "tags: [docs, release]",
+ "triggers: [release]",
+ "---",
+ "# Release notes procedure",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ writeFileSync(
+ join(skillsDir, "SKILL.md"),
+ [
+ "---",
+ "version: 1",
+ "triggers: [release]",
+ "tags: [ops]",
+ "permissions: [read]",
+ "source: test-suite",
+ "---",
+ "# Release Skill",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ return [join(vaultPath, "Brain", "procedures"), join(vaultPath, "skills")];
+}
diff --git a/tests/core/brain/procedural-paths.test.ts b/tests/core/brain/procedural-paths.test.ts
new file mode 100644
index 00000000..d497f0e2
--- /dev/null
+++ b/tests/core/brain/procedural-paths.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ procedurePath,
+ proceduralMemoryIndexPath,
+ proceduralMemoryUsagePath,
+ proceduralRecurrencePath,
+ skillProposalAcceptedPath,
+ skillProposalPendingPath,
+ skillProposalRejectedPath,
+} from "../../../src/core/brain/paths.ts";
+
+describe("procedural learning paths", () => {
+ const tmpRoots: string[] = [];
+
+ afterEach(() => {
+ for (const root of tmpRoots.splice(0)) {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test("builds vault-contained paths for proposal/procedure/index artifacts", () => {
+ const vault = mkdtempSync(join(tmpdir(), "o2b-procedural-paths-"));
+ tmpRoots.push(vault);
+
+ const pending = skillProposalPendingPath(vault, "release-notes");
+ const accepted = skillProposalAcceptedPath(vault, "release-notes");
+ const rejected = skillProposalRejectedPath(vault, "release-notes");
+ const procedure = procedurePath(vault, "release-notes");
+ const index = proceduralMemoryIndexPath(vault);
+ const usage = proceduralMemoryUsagePath(vault);
+ const recurrence = proceduralRecurrencePath(vault);
+
+ expect(pending).toBe(
+ join(vault, "Brain", "skill-proposals", "pending", "prop-release-notes.md"),
+ );
+ expect(accepted).toBe(
+ join(vault, "Brain", "skill-proposals", "accepted", "prop-release-notes.md"),
+ );
+ expect(rejected).toBe(
+ join(vault, "Brain", "skill-proposals", "rejected", "prop-release-notes.md"),
+ );
+ expect(procedure).toBe(join(vault, "Brain", "procedures", "proc-release-notes.md"));
+ expect(index).toBe(join(vault, "Brain", "procedural-memory", "index.json"));
+ expect(usage).toBe(join(vault, "Brain", "procedural-memory", "usage.jsonl"));
+ expect(recurrence).toBe(join(vault, "Brain", "log", "recurrence-support.jsonl"));
+ });
+
+ test("rejects unsafe slug input for proposal and procedure paths", () => {
+ const vault = mkdtempSync(join(tmpdir(), "o2b-procedural-paths-"));
+ tmpRoots.push(vault);
+
+ expect(() => skillProposalPendingPath(vault, "../escape")).toThrow(/slug must not contain/);
+ expect(() => procedurePath(vault, "bad/slug")).toThrow(/slug must not contain path separators/);
+ });
+});
diff --git a/tests/core/brain/recurrence.test.ts b/tests/core/brain/recurrence.test.ts
new file mode 100644
index 00000000..15fb0b59
--- /dev/null
+++ b/tests/core/brain/recurrence.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ applyRecurrenceEvidence,
+ getRecurrenceEntry,
+ listRecurrenceEntries,
+ purgeRecurrenceSource,
+} from "../../../src/core/brain/recurrence.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = join(tmpdir(), `o2b-recurrence-${Date.now()}-${Math.random().toString(16).slice(2)}`);
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("recurrence support ledger", () => {
+ test("same-scope duplicate learns increment support instead of creating duplicates", () => {
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-alpha",
+ scope: "project-a",
+ sourceId: "src-1",
+ action: "learn",
+ at: "2026-06-01T10:00:00Z",
+ });
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-alpha",
+ scope: "project-a",
+ sourceId: "src-2",
+ action: "learn",
+ at: "2026-06-01T10:01:00Z",
+ });
+
+ const all = listRecurrenceEntries(vault);
+ expect(all).toHaveLength(1);
+ expect(all[0]?.supportCount).toBe(2);
+ expect(all[0]?.recurrenceCount).toBe(1);
+ });
+
+ test("cross-scope recurrence increases recurrence evidence and commitment", () => {
+ for (const input of [
+ { scope: "project-a", sourceId: "src-1" },
+ { scope: "project-b", sourceId: "src-2" },
+ { scope: "project-c", sourceId: "src-3" },
+ { scope: "project-c", sourceId: "src-4" },
+ { scope: "project-a", sourceId: "src-5" },
+ ]) {
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-beta",
+ scope: input.scope,
+ sourceId: input.sourceId,
+ action: "learn",
+ });
+ }
+
+ const entry = getRecurrenceEntry(vault, "h-beta");
+ expect(entry).not.toBeNull();
+ expect(entry?.supportCount).toBe(5);
+ expect(entry?.recurrenceCount).toBe(3);
+ expect(entry?.commitment).toBe("decided");
+ });
+
+ test("reference-counted forget and source purge retire only after support is gone", () => {
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-gamma",
+ scope: "project-a",
+ sourceId: "src-1",
+ action: "learn",
+ });
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-gamma",
+ scope: "project-a",
+ sourceId: "src-1",
+ action: "learn",
+ });
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-gamma",
+ scope: "project-b",
+ sourceId: "src-2",
+ action: "learn",
+ });
+
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-gamma",
+ scope: "project-a",
+ sourceId: "src-1",
+ action: "forget",
+ });
+
+ let entry = getRecurrenceEntry(vault, "h-gamma");
+ expect(entry?.supportCount).toBe(2);
+
+ purgeRecurrenceSource(vault, "src-1");
+ entry = getRecurrenceEntry(vault, "h-gamma");
+ expect(entry?.supportCount).toBe(1);
+
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-gamma",
+ scope: "project-b",
+ sourceId: "src-2",
+ action: "forget",
+ });
+ entry = getRecurrenceEntry(vault, "h-gamma");
+ expect(entry).toBeNull();
+ });
+});
diff --git a/tests/core/brain/skill-proposals.test.ts b/tests/core/brain/skill-proposals.test.ts
new file mode 100644
index 00000000..8de09372
--- /dev/null
+++ b/tests/core/brain/skill-proposals.test.ts
@@ -0,0 +1,290 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
+import {
+ procedurePath,
+ proposalWatermarkPath,
+ skillProposalAcceptedPath,
+ skillProposalRejectedPath,
+} from "../../../src/core/brain/paths.ts";
+import {
+ acceptSkillProposal,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ rejectSkillProposal,
+} from "../../../src/core/brain/skill-proposals.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-skill-proposals-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("skill proposal learning", () => {
+ test("detects repeated action, structural similarity, co-occurrence, and temporal routine", () => {
+ seedCorePatterns(vault);
+
+ const result = learnSkillProposals(vault, {
+ now: new Date("2026-06-01T09:00:00Z"),
+ minSupport: 3,
+ });
+
+ expect(result.scanned).toBeGreaterThanOrEqual(12);
+ expect(result.created.length).toBeGreaterThanOrEqual(4);
+ const pending = listPendingSkillProposals(vault);
+ const kinds = pending.map((item) => item.patternKind).toSorted();
+ expect(kinds).toContain("repeated_action");
+ expect(kinds).toContain("structural_similarity");
+ expect(kinds).toContain("co_occurrence");
+ expect(kinds).toContain("temporal_routine");
+ });
+
+ test("advances watermark and suppresses unchanged reruns", () => {
+ seedCorePatterns(vault);
+
+ const first = learnSkillProposals(vault, {
+ now: new Date("2026-06-01T10:00:00Z"),
+ minSupport: 3,
+ });
+ expect(first.created.length).toBeGreaterThanOrEqual(1);
+ expect(first.watermarkTo).not.toBeNull();
+
+ const wmPath = proposalWatermarkPath(vault);
+ const wm = JSON.parse(readFileSync(wmPath, "utf8")) as {
+ lastCreatedAt: string | null;
+ lastId: string | null;
+ };
+ expect(wm.lastCreatedAt).toBe(first.watermarkTo);
+ expect(typeof wm.lastId).toBe("string");
+
+ const second = learnSkillProposals(vault, {
+ now: new Date("2026-06-01T11:00:00Z"),
+ minSupport: 3,
+ });
+ expect(second.scanned).toBe(0);
+ expect(second.created).toHaveLength(0);
+ expect(listPendingSkillProposals(vault).length).toBe(first.created.length);
+ });
+
+ test("replays same-timestamp records using watermark id cursor", () => {
+ seedCorePatterns(vault);
+
+ const first = learnSkillProposals(vault, {
+ now: new Date("2026-06-01T10:00:00Z"),
+ minSupport: 3,
+ });
+ expect(first.watermarkTo).not.toBeNull();
+
+ const wmPath = proposalWatermarkPath(vault);
+ const wm = JSON.parse(readFileSync(wmPath, "utf8")) as {
+ lastCreatedAt: string | null;
+ lastId: string | null;
+ };
+ expect(wm.lastCreatedAt).not.toBeNull();
+ expect(wm.lastId).not.toBeNull();
+
+ let appendedHigherId = false;
+ for (let i = 0; i < 256; i++) {
+ const rec = appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: wm.lastCreatedAt!,
+ sourceRefs: [{ id: `late-src-${i}` }],
+ payload: {
+ action: `late_action_${i}`,
+ summary: `late summary ${i}`,
+ },
+ });
+ if (rec.id > wm.lastId!) {
+ appendedHigherId = true;
+ break;
+ }
+ }
+ expect(appendedHigherId).toBe(true);
+
+ const second = learnSkillProposals(vault, {
+ now: new Date("2026-06-01T11:00:00Z"),
+ minSupport: 3,
+ });
+ expect(second.scanned).toBeGreaterThan(0);
+ });
+
+ test("accept moves proposal and creates procedure artifact", () => {
+ seedCorePatterns(vault);
+ learnSkillProposals(vault, {
+ now: new Date("2026-06-01T12:00:00Z"),
+ minSupport: 3,
+ });
+
+ const pending = listPendingSkillProposals(vault);
+ const target = pending.find(
+ (item) => item.patternKind === "repeated_action",
+ );
+ expect(target).toBeDefined();
+
+ const accepted = acceptSkillProposal(vault, target!.slug, {
+ now: new Date("2026-06-01T12:10:00Z"),
+ note: "looks stable",
+ });
+
+ expect(accepted.status).toBe("accepted");
+ expect(existsSync(skillProposalAcceptedPath(vault, target!.slug))).toBe(
+ true,
+ );
+ expect(existsSync(procedurePath(vault, target!.slug))).toBe(true);
+ expect(
+ listPendingSkillProposals(vault).some(
+ (item) => item.slug === target!.slug,
+ ),
+ ).toBe(false);
+ });
+
+ test("reject moves proposal and prevents unchanged reappearance", () => {
+ seedCorePatterns(vault);
+ learnSkillProposals(vault, {
+ now: new Date("2026-06-01T13:00:00Z"),
+ minSupport: 3,
+ });
+
+ const pending = listPendingSkillProposals(vault);
+ const target = pending.find((item) => item.patternKind === "co_occurrence");
+ expect(target).toBeDefined();
+
+ const rejected = rejectSkillProposal(vault, target!.slug, {
+ now: new Date("2026-06-01T13:10:00Z"),
+ note: "too noisy",
+ });
+
+ expect(rejected.status).toBe("rejected");
+ expect(existsSync(skillProposalRejectedPath(vault, target!.slug))).toBe(
+ true,
+ );
+ expect(
+ listPendingSkillProposals(vault).some(
+ (item) => item.slug === target!.slug,
+ ),
+ ).toBe(false);
+
+ const rerun = learnSkillProposals(vault, {
+ now: new Date("2026-06-02T13:00:00Z"),
+ minSupport: 3,
+ });
+ expect(rerun.created.some((id) => id === rejected.id)).toBe(false);
+ });
+});
+
+function seedCorePatterns(vaultPath: string): void {
+ const records = [
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-20T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 101 in module alpha",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-20T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 102 in module beta",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-21T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 103 in module gamma",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-21T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 104 in module delta",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-22T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 105 in module epsilon",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-22T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 106 in module zeta",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-23T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 107 in module eta",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-23T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 108 in module theta",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-24T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 109 in module iota",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-24T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 110 in module kappa",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-25T08:10:00Z",
+ payload: {
+ action: "triage_inbox",
+ summary: "Investigate issue 111 in module lambda",
+ },
+ },
+ {
+ kind: "session_turn" as const,
+ createdAt: "2026-05-25T08:12:00Z",
+ payload: {
+ action: "prepare_release_notes",
+ summary: "Investigate issue 112 in module mu",
+ },
+ },
+ ];
+
+ for (const record of records) {
+ appendContinuityRecord(vaultPath, {
+ kind: record.kind,
+ createdAt: record.createdAt,
+ sourceRefs: [{ id: `src-${record.createdAt}` }],
+ payload: record.payload,
+ });
+ }
+}
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 16eb6239..ccdb9dcb 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -228,6 +228,10 @@ describe("tool listing", () => {
"brain_session_grep",
"brain_session_describe",
"brain_session_expand",
+ // Procedural-learning surfaces (v0.30.0).
+ "brain_skill_proposals",
+ "brain_procedural_memory",
+ "brain_recurrence",
// Pay Memory (unchanged).
"payment_memory_init",
"payment_receipt_append",
@@ -491,7 +495,8 @@ describe("stdio loop", () => {
// + 9 schema admin tools + brain_watchdog = 57.
// + brain_recall_gate (v0.27.0) = 58.
// + 7 context continuity/session recall tools (v0.29.0) = 65.
- expect(list.result.tools.length).toBe(65);
+ // + 3 procedural-learning tools (v0.30.0) = 68.
+ expect(list.result.tools.length).toBe(68);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/procedural-learning-tools.test.ts b/tests/mcp/procedural-learning-tools.test.ts
new file mode 100644
index 00000000..847ed95c
--- /dev/null
+++ b/tests/mcp/procedural-learning-tools.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-mcp-procedural-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, "skills", "release"), { recursive: true });
+ writeFileSync(
+ join(vault, "skills", "release", "SKILL.md"),
+ [
+ "---",
+ "triggers: [release]",
+ "tags: [ops]",
+ "permissions: [read]",
+ "source: mcp-test",
+ "version: 1",
+ "---",
+ "# Release skill",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+ seedContinuity(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "procedural-tools-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callTool(
+ server: MCPServer,
+ name: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name, arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("procedural learning tool registration", () => {
+ test("new tools are in full scope only", () => {
+ for (const name of [
+ "brain_skill_proposals",
+ "brain_procedural_memory",
+ "brain_recurrence",
+ ] as const) {
+ expect(buildToolTable("full").find((tool) => tool.name === name)).toBeDefined();
+ expect(buildToolTable("writer").find((tool) => tool.name === name)).toBeUndefined();
+ }
+ });
+});
+
+describe("procedural learning MCP tools", () => {
+ test("skill proposals, procedural memory, and recurrence work end-to-end", async () => {
+ const server = new MCPServer({ vault });
+ await initialize(server);
+
+ const learned = await callTool(server, "brain_skill_proposals", {
+ operation: "learn",
+ min_support: 3,
+ });
+ expect((learned.created as unknown[]).length).toBeGreaterThanOrEqual(1);
+
+ const listed = await callTool(server, "brain_skill_proposals", {
+ operation: "list",
+ });
+ const proposals = listed.proposals as Array<Record<string, unknown>>;
+ expect(proposals.length).toBeGreaterThanOrEqual(1);
+ const slug = proposals[0]!["slug"] as string;
+
+ const accepted = await callTool(server, "brain_skill_proposals", {
+ operation: "accept",
+ slug,
+ note: "accepted in test",
+ });
+ expect(accepted.status).toBe("accepted");
+
+ const rec = await callTool(server, "brain_procedural_memory", {
+ operation: "reconcile",
+ roots: [join(vault, "Brain", "procedures"), join(vault, "skills")],
+ });
+ expect(rec.total).toBeGreaterThanOrEqual(1);
+
+ const mem = await callTool(server, "brain_procedural_memory", {
+ operation: "list",
+ });
+ const entries = mem.entries as Array<Record<string, unknown>>;
+ expect(entries.length).toBeGreaterThanOrEqual(1);
+
+ const marked = await callTool(server, "brain_procedural_memory", {
+ operation: "mark_used",
+ id: entries[0]!["id"],
+ });
+ expect(marked.usedCount).toBeGreaterThanOrEqual(1);
+
+ const recLearn = await callTool(server, "brain_recurrence", {
+ operation: "learn",
+ content_hash: "h-mcp",
+ scope: "project-a",
+ source_id: "src-1",
+ });
+ expect(recLearn.operation).toBe("learn");
+
+ const recShow = await callTool(server, "brain_recurrence", {
+ operation: "show",
+ content_hash: "h-mcp",
+ });
+ expect(recShow.supportCount).toBe(1);
+ });
+});
+
+function seedContinuity(vaultPath: string): void {
+ for (const row of [
+ ["2026-06-01T08:00:00Z", "triage_inbox"],
+ ["2026-06-02T08:00:00Z", "triage_inbox"],
+ ["2026-06-03T08:00:00Z", "triage_inbox"],
+ ["2026-06-01T08:05:00Z", "prepare_release_notes"],
+ ["2026-06-02T08:05:00Z", "prepare_release_notes"],
+ ["2026-06-03T08:05:00Z", "prepare_release_notes"],
+ ] as const) {
+ appendContinuityRecord(vaultPath, {
+ kind: "session_turn",
+ createdAt: row[0],
+ sourceRefs: [{ id: `src-${row[0]}` }],
+ payload: {
+ action: row[1],
+ summary: `Investigate issue ${row[0]}`,
+ },
+ });
+ }
+}
diff --git a/tests/mcp/recall-telemetry-tool.test.ts b/tests/mcp/recall-telemetry-tool.test.ts
index 5ab81225..d8e6e281 100644
--- a/tests/mcp/recall-telemetry-tool.test.ts
+++ b/tests/mcp/recall-telemetry-tool.test.ts
@@ -5,16 +5,9 @@ import { join } from "node:path";
import { emitRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
-import {
- BRAIN_CONFIDENCE,
- BRAIN_PREFERENCE_STATUS,
-} from "../../src/core/brain/types.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
-import {
- JSONRPC_VERSION,
- MCPServer,
- PROTOCOL_VERSION,
-} from "../../src/mcp/index.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
let tmp: string;
@@ -92,14 +85,10 @@ async function callTool(
describe("brain_recall_telemetry tool registration", () => {
test("registered in the full tool table only", () => {
expect(
- buildToolTable("full").find(
- (tool) => tool.name === "brain_recall_telemetry",
- ),
+ buildToolTable("full").find((tool) => tool.name === "brain_recall_telemetry"),
).toBeDefined();
expect(
- buildToolTable("writer").find(
- (tool) => tool.name === "brain_recall_telemetry",
- ),
+ buildToolTable("writer").find((tool) => tool.name === "brain_recall_telemetry"),
).toBeUndefined();
});
});
@@ -133,9 +122,7 @@ describe("brain_recall_telemetry tool", () => {
mode: "context_pack",
});
expect(list["total"]).toBe(1);
- expect(
- (list["records"] as Array<Record<string, unknown>>)[0]!["payload"],
- ).toMatchObject({
+ expect((list["records"] as Array<Record<string, unknown>>)[0]!["payload"]).toMatchObject({
mode: "context_pack",
result_count: 1,
});