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/procedural attention suite (#58)

Sol Aitkenb81335c27928
diff --git a/docs/brainstorm/procedural-attention-suite/cli-output/claude.md b/docs/brainstorm/procedural-attention-suite/cli-output/claude.md
new file mode 100644
index 00000000..71c2adbb
--- /dev/null
+++ b/docs/brainstorm/procedural-attention-suite/cli-output/claude.md
@@ -0,0 +1,38 @@
+### Variant 1: Additive In-Place Extension
+- **Approach**: Extend each existing module directly — `procedural-memory.ts` gains a sibling edge/entity index alongside its flat JSON, `recurrence.ts`/`context-pack.ts` emit prospective recall hints at write time, and a new `attention-recipes.ts` module plus new CLI verbs and MCP tools expose ingest scoping, filtered write, export, and introspection. Each capability is a discrete cohesive function wired through the surfaces that already exist, with no new cross-cutting abstraction.
+- **Trade-offs**:
+ - Pro: Smallest diff, each task maps to a self-contained change set ideal for atomic TDD commits.
+ - Pro: Lowest risk to existing public CLI/MCP APIs — everything is purely additive.
+ - Pro: Stays closest to current conventions; reviewers compare narrow, local deltas against main.
+ - Con: Provider-readiness is implicit — the Hermes adapter PR must later extract a port from scattered functions, i.e. some rework.
+ - Con: Graph/entity logic risks duplication across procedural-memory, recall hints, and recipes (DRY pressure).
+ - Con: Introspection/export surfaces read several ad-hoc shapes rather than one model.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Memory-Graph Kernel Behind a Provider Port
+- **Approach**: Introduce a single unified memory-graph core (nodes, edges, entities) with a formal provider interface (port), and re-express procedural memory, recall hints, and attention recipes as operations on that graph; OpenSecondBrain becomes the local-first adapter implementing the port. The Hermes-compatible provider later slots in behind the identical interface with no consumer changes.
+- **Trade-offs**:
+ - Pro: Maximally provider-ready — the next PR is a new adapter, zero consumer rework.
+ - Pro: One canonical model satisfies DRY; export/introspection are first-class graph reads.
+ - Pro: Strong SOLID dependency-inversion alignment.
+ - Con: Largest refactor; touches modules behind existing public APIs, raising regression and API-compat risk.
+ - Con: Builds an abstraction for a provider that does not yet exist (YAGNI / KISS tension) within a single release.
+ - Con: Harder to keep atomic — the port and its first adapter must land together to stay green.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Derived Graph Projection + Declarative Recipe Engine
+- **Approach**: Leave the flat markdown/frontmatter as the canonical source of truth and add a deterministically-derived graph projection sidecar (entity links and edges computed from existing files), plus a declarative recipe engine that renders open-loop/learning attention flows and write-time recall hints as derived, auditable artifacts. Export and introspection read the projection through one stable, documented read/write contract that a future provider maps onto.
+- **Trade-offs**:
+ - Pro: Append-only derivation preserves determinism, local-first behavior, and full auditability (rebuildable from source).
+ - Pro: The projection contract is a clean seam a provider adapter can implement without rewriting core modules — provider-ready without a full kernel rewrite.
+ - Pro: Recipes are declarative data, keeping logic DRY and feeding context surfaces uniformly; existing APIs stay untouched.
+ - Con: Two-layer (source + projection) model adds a rebuild/reconcile step to reason about.
+ - Con: Projection staleness must be handled explicitly (deterministic regeneration on write).
+ - Con: More moving parts than Variant 1, though far less invasive than Variant 2.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 3
+**Rationale**: It satisfies provider-readiness through an explicit, documented projection contract — the exact seam a Hermes adapter needs — without the large, high-risk kernel rewrite of Variant 2 or the implicit "extract it later" rework debt of Variant 1. The derived-projection model is the strongest fit for the project's deterministic, local-first, auditable conventions, and its declarative recipes plus additive surfaces let each task land as atomic, backwards-compatible, TDD-friendly commits.
diff --git a/docs/brainstorm/procedural-attention-suite/cli-output/prompt.md b/docs/brainstorm/procedural-attention-suite/cli-output/prompt.md
new file mode 100644
index 00000000..567e550a
--- /dev/null
+++ b/docs/brainstorm/procedural-attention-suite/cli-output/prompt.md
@@ -0,0 +1,87 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Implement a single cohesive release scope that fully completes these kanban tasks together:
+
+- t_ee819f4b
+- t_02e22d4e
+- t_2fe5cffa
+- t_25d4dbfb
+- t_5d63937b
+- t_f935fe84
+
+Operator constraints:
+
+- Full completion for the selected tasks, not partial delivery.
+- Keep architecture provider-ready so a next PR can adapt OpenSecondBrain as a Hermes-compatible memory provider without rework.
+- Follow SOLID, KISS, DRY.
+- Implementation by TDD with atomic commits.
+- Run formatter and linter before each commit.
+- Self-review must compare all changes to main.
+- Version must be bumped before push.
+
+Task intent summary:
+
+- Extend procedural memory from flat index to graph/entity-linked memory with export/introspection surfaces.
+- Add prospective recall hints generated at write time.
+- Add scoped ingest context and filtered write mode.
+- Add declarative attention flow recipes for open loops and learnings that can feed context surfaces.
+- Preserve deterministic/local-first behavior and auditability.
+
+# Project context
+
+open-second-brain; TypeScript + Bun; Obsidian-native markdown brain with CLI+MCP surfaces.
+
+Recent commits:
+
+- 1f3a218 Feat/self learning skill proposals (#57)
+- 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)
+
+Related files:
+
+- src/core/brain/skill-proposals.ts
+- src/core/brain/procedural-memory.ts
+- src/core/brain/recurrence.ts
+- src/core/brain/context-pack.ts
+- src/core/search/search.ts
+- src/mcp/brain-tools.ts
+- src/cli/brain/verbs/\*
+- tests/core/brain/\*
+- tests/mcp/\*
+
+Conventions:
+
+- Deterministic, local-first core behavior is preferred.
+- CLI and MCP both need first-class surfaces for new capabilities.
+- Tests are required for core/CLI/MCP paths.
+- Changelog versioned releases are maintained in CHANGELOG.md.
+- Bun toolchain (fmt/lint/test/typecheck) is standard.
+
+Constraints:
+
+- Do not break existing public CLI/MCP APIs unless additive and backwards-compatible.
+- Keep feature scope cohesive around procedural memory + attention/recall readiness.
+- Avoid introducing unnecessary external dependencies.
+- Keep migration paths explicit and auditable.
+
+# 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/procedural-attention-suite/design.md b/docs/brainstorm/procedural-attention-suite/design.md
new file mode 100644
index 00000000..1b8e3fbf
--- /dev/null
+++ b/docs/brainstorm/procedural-attention-suite/design.md
@@ -0,0 +1,73 @@
+# Procedural Attention Suite - derived graph and scoped ingest
+
+**Status:** draft
+**Author:** GitHub Copilot (feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain shipped procedural-learning foundations in v0.30.0, but the selected scope still lacks full graph/entity surfaces for procedural memory, write-time prospective recall hints, scoped ingest filtering, and declarative attention flows that can feed context outputs. The operator requires full delivery for six related tasks in one cohesive release and wants architecture that avoids rework when adding Hermes memory-provider compatibility in the next PR. The implementation must remain deterministic, local-first, additive, and auditable.
+
+## Scope
+
+- Add a derived procedural graph projection built from canonical procedural/proposal artifacts.
+- Add deterministic entity/link extraction for procedural entries and include links in projection/export.
+- Add CLI and MCP export/introspection surfaces for the procedural graph.
+- Add write-time prospective recall hints as derived artifacts.
+- Add scoped ingest context and filtered write mode for import/synthesis pipelines.
+- Add declarative attention-flow recipes (open loops/learnings) with evaluation + context-pack integration.
+- Add tests for core, CLI, and MCP for all new flows.
+
+## Out of scope
+
+- Full Hermes memory-provider plugin compatibility lifecycle (separate PR).
+- Non-deterministic/LLM-required hint or recipe generation.
+- Breaking changes to existing CLI/MCP contracts.
+
+## Chosen approach
+
+Use a deterministic derived-projection architecture: markdown/frontmatter artifacts remain canonical source-of-truth, while a derived projection persists graph nodes/edges/entities/hints for fast introspection and export. Declarative attention recipes read from the same projection and known runtime indexes. This creates a stable provider-ready seam (projection contract) without a high-risk kernel rewrite.
+
+## Design decisions
+
+- Projection-first seam: add a single read/write contract for procedural graph/hints so the next provider-adapter PR can target one boundary.
+- Deterministic derivation: projection can be rebuilt from canonical artifacts; no hidden remote state.
+- Additive CLI/MCP: new verbs/tools are appended; existing commands retain behavior.
+- Scoped ingest context as explicit input contract: filters and context-hints are optional, default behavior unchanged.
+- Declarative recipes as data: YAML recipes compiled/executed by bounded deterministic evaluator.
+- Backwards compatibility: existing procedural-memory index and skill-proposal flows remain valid.
+
+## File changes
+
+- Core
+ - src/core/brain/procedural-graph.ts (new)
+ - src/core/brain/procedural-hints.ts (new)
+ - src/core/brain/attention-flows.ts (new)
+ - src/core/brain/procedural-memory.ts (update)
+ - src/core/brain/skill-proposals.ts (update)
+ - src/core/brain/context-pack.ts (update)
+ - src/core/brain/paths.ts (update)
+ - src/core/brain/sessions/import.ts (update)
+- CLI
+ - src/cli/brain/verbs/procedural-graph.ts (new)
+ - src/cli/brain/verbs/attention-flows.ts (new)
+ - src/cli/brain/verbs/index.ts (update)
+ - src/cli/brain/help-text.ts (update)
+- MCP
+ - src/mcp/brain-tools.ts (update)
+- Tests
+ - tests/core/brain/procedural-graph.test.ts (new)
+ - tests/core/brain/procedural-hints.test.ts (new)
+ - tests/core/brain/attention-flows.test.ts (new)
+ - tests/cli/brain-procedural-graph.test.ts (new)
+ - tests/mcp/procedural-graph-tools.test.ts (new)
+ - existing related tests updated as needed
+
+## Risks and open questions
+
+- Risk: projection drift if updates are not triggered consistently.
+ - Mitigation: explicit reconcile hooks + tests for rebuild/idempotence.
+- Risk: over-broad ingest filters can hide required context.
+ - Mitigation: explicit diagnostics in JSON outputs and safe defaults.
+- Risk: recipe complexity creep.
+ - Mitigation: small bounded action set in v1 and strict schema validation.
diff --git a/docs/brainstorm/procedural-attention-suite/plan.md b/docs/brainstorm/procedural-attention-suite/plan.md
new file mode 100644
index 00000000..5d8e0e4a
--- /dev/null
+++ b/docs/brainstorm/procedural-attention-suite/plan.md
@@ -0,0 +1,51 @@
+# Procedural Attention Suite - implementation plan
+
+## Tasks
+
+### Task 1: Projection contract and paths
+
+- **Files**: src/core/brain/paths.ts, src/core/brain/procedural-graph.ts
+- **Acceptance**: projection read/write/rebuild primitives exist with deterministic ordering and schema version.
+- **Depends on**: none
+
+### Task 2: Procedural graph/entity linking
+
+- **Files**: src/core/brain/procedural-memory.ts, src/core/brain/skill-proposals.ts, src/core/brain/procedural-graph.ts
+- **Acceptance**: reconcile emits graph nodes/edges/entities; entity links appear in projection.
+- **Depends on**: Task 1
+
+### Task 3: Graph export and introspection surfaces
+
+- **Files**: src/cli/brain/verbs/procedural-graph.ts, src/cli/brain/verbs/index.ts, src/cli/brain/help-text.ts, src/mcp/brain-tools.ts
+- **Acceptance**: CLI/MCP expose list/show/export/rebuild operations for procedural graph.
+- **Depends on**: Task 2
+
+### Task 4: Prospective recall hints at write time
+
+- **Files**: src/core/brain/procedural-hints.ts, src/core/brain/procedural-memory.ts, src/core/brain/skill-proposals.ts, src/mcp/brain-tools.ts
+- **Acceptance**: derived hints are generated deterministically on writes/reconcile and queryable.
+- **Depends on**: Task 2
+
+### Task 5: Scoped ingest context and filtered write mode
+
+- **Files**: src/core/brain/sessions/import.ts, src/core/brain/context-pack.ts, src/mcp/brain-tools.ts, CLI import surfaces
+- **Acceptance**: ingest path accepts scoped filters/hints and reports applied filters; default behavior unchanged.
+- **Depends on**: Task 1
+
+### Task 6: Declarative attention flows
+
+- **Files**: src/core/brain/attention-flows.ts, src/core/brain/context-pack.ts, src/cli/brain/verbs/attention-flows.ts, src/mcp/brain-tools.ts
+- **Acceptance**: YAML recipes validate and execute bounded actions for open loops/learnings; outputs consumable by context-pack.
+- **Depends on**: Task 1, Task 2
+
+### Task 7: Test suite and compatibility hardening
+
+- **Files**: tests/core/brain/_, tests/cli/_, tests/mcp/\*
+- **Acceptance**: new core/CLI/MCP tests pass; existing procedural-learning tests remain green.
+- **Depends on**: Tasks 2-6
+
+### Task 8: Release/docs/version
+
+- **Files**: README.md, CHANGELOG.md, package.json + synced version files
+- **Acceptance**: docs updated, changelog entry added, version bumped and sync check passes.
+- **Depends on**: Task 7
diff --git a/docs/brainstorm/procedural-attention-suite/variants.md b/docs/brainstorm/procedural-attention-suite/variants.md
new file mode 100644
index 00000000..dc7bdb65
--- /dev/null
+++ b/docs/brainstorm/procedural-attention-suite/variants.md
@@ -0,0 +1,38 @@
+# Variants audit - procedural-attention-suite
+
+## Source
+
+- Prompt: docs/brainstorm/procedural-attention-suite/cli-output/prompt.md
+- Consultant output: docs/brainstorm/procedural-attention-suite/cli-output/claude.md
+
+## Variant 1: Additive In-Place Extension
+
+- Extend existing modules directly with minimal abstraction.
+- Pros: smallest diff, low API risk, fast landing.
+- Cons: provider-readiness becomes implicit, higher duplication risk.
+- Complexity: medium
+- Risk: low
+
+## Variant 2: Memory-Graph Kernel Behind a Provider Port
+
+- Introduce full graph kernel + provider port and adapt all features on top.
+- Pros: strongest DIP/provider seam.
+- Cons: biggest refactor and regression risk for one release.
+- Complexity: large
+- Risk: high
+
+## Variant 3: Derived Graph Projection + Declarative Recipe Engine
+
+- Keep canonical artifacts, add deterministic derived projection and declarative attention recipes.
+- Pros: provider-ready seam without full rewrite, deterministic and auditable, additive APIs.
+- Cons: requires projection reconcile discipline and bounded recipe design.
+- Complexity: medium
+- Risk: medium
+
+## Decision
+
+Chosen variant: Variant 3.
+
+### Rationale
+
+Variant 3 gives the best balance for the required six-task full scope: it enables graph/export and attention/hints flows on a shared projection contract while preserving local-first deterministic behavior and minimizing rewrite risk. It is explicitly provider-ready for the next PR by introducing a stable projection seam, but avoids the high-risk kernel refactor from Variant 2.
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 95d0a079..de4e8a8b 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -60,7 +60,9 @@ import {
cmdBrainRecallTelemetry,
cmdBrainSkillProposals,
cmdBrainProceduralMemory,
+ cmdBrainProceduralGraph,
cmdBrainRecurrence,
+ cmdBrainAttentionFlows,
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
cmdBrainSessionGrep,
@@ -199,8 +201,12 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainSkillProposals(rest);
case "procedural-memory":
return await cmdBrainProceduralMemory(rest);
+ case "procedural-graph":
+ return await cmdBrainProceduralGraph(rest);
case "recurrence":
return await cmdBrainRecurrence(rest);
+ case "attention-flows":
+ return await cmdBrainAttentionFlows(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 74710789..09e9d73f 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -62,7 +62,9 @@ Brain verbs (observing memory):
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
+ procedural-graph Rebuild/show procedural graph and hint projections
recurrence Inspect and update recurrence/support diagnostics
+ attention-flows Declarative attention recipes for open loops and learnings
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
@@ -266,6 +268,7 @@ export const VERB_HELP: Record<string, string> = {
"usage: o2b brain import-session <path> [--vault <vault>]\n" +
" [--format auto|<registered-adapter>]\n" +
" [--agent <name>] [--since <ISO>] [--dry-run] [--recall]\n" +
+ " [--ingest-scope <label>] [--filter-role <role> ...] [--filter-text <substring>]\n" +
" [--recall-session-id <id>] [--recall-summary-group-size <n>] [--json]\n" +
"Extract signals from a registered agent session .jsonl file (or\n" +
"directory of .jsonl files). Two extraction paths run in parallel:\n" +
@@ -377,6 +380,12 @@ export const VERB_HELP: Record<string, string> = {
" reconcile [--root <path> ...] [--vault <path>] [--json]\n" +
" list [--vault <path>] [--json]\n" +
" mark-used <entry-id> [--vault <path>] [--json]\n",
+ "procedural-graph":
+ "usage: o2b brain procedural-graph <rebuild|show|hints> [args]\n" +
+ "Read/write procedural graph and prospective-hints projections.\n" +
+ " rebuild [--vault <path>] [--json]\n" +
+ " show [--vault <path>] [--json]\n" +
+ " hints [--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" +
@@ -385,6 +394,12 @@ export const VERB_HELP: Record<string, string> = {
" 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",
+ "attention-flows":
+ "usage: o2b brain attention-flows <list|evaluate|render> [args]\n" +
+ "Declarative attention-flow recipes and evaluation surfaces.\n" +
+ " list [--vault <path>] [--json]\n" +
+ " evaluate <flow-id> [--vault <path>] [--json]\n" +
+ " render <flow-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/attention-flows.ts b/src/cli/brain/verbs/attention-flows.ts
new file mode 100644
index 00000000..d24b4509
--- /dev/null
+++ b/src/cli/brain/verbs/attention-flows.ts
@@ -0,0 +1,110 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ evaluateAttentionFlow,
+ listAttentionFlows,
+ renderAttentionFlow,
+} from "../../../core/brain/attention-flows.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainAttentionFlows(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ if (sub === "list") return list(rest);
+ if (sub === "evaluate") return evaluate(rest);
+ if (sub === "render") return render(rest);
+ throw new CliError(
+ "brain attention-flows: expected list, evaluate, or render",
+ );
+}
+
+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 flows = listAttentionFlows(vault);
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ total: flows.length, flows }, null, 2) + "\n",
+ );
+ return 0;
+ }
+ process.stdout.write(`${flows.length} attention flow(s):\n`);
+ for (const flow of flows) {
+ process.stdout.write(
+ ` ${flow.id} actions=${flow.actions.join(",") || "-"}\n`,
+ );
+ }
+ return 0;
+}
+
+function evaluate(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const flowId = positional[0];
+ if (!flowId)
+ throw new CliError("brain attention-flows evaluate: flow id is required");
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+ let report;
+ try {
+ report = evaluateAttentionFlow(vault, flowId);
+ } catch (error) {
+ throw mapAttentionFlowError(error, flowId);
+ }
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
+ return 0;
+ }
+ process.stdout.write(`${report.flow_id}: ${report.title}\n`);
+ for (const section of report.sections) {
+ process.stdout.write(` ${section.action}: ${section.items.length}\n`);
+ }
+ return 0;
+}
+
+function render(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const flowId = positional[0];
+ if (!flowId)
+ throw new CliError("brain attention-flows render: flow id is required");
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+ let text: string;
+ try {
+ text = renderAttentionFlow(vault, flowId);
+ } catch (error) {
+ throw mapAttentionFlowError(error, flowId);
+ }
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ flow_id: flowId, text }, null, 2) + "\n",
+ );
+ return 0;
+ }
+ process.stdout.write(text.endsWith("\n") ? text : text + "\n");
+ return 0;
+}
+
+function mapAttentionFlowError(error: unknown, flowId: string): CliError {
+ if (error instanceof Error) {
+ if (error.message.startsWith("attention flow not found:")) {
+ return new CliError(`brain attention-flows: unknown flow id: ${flowId}`);
+ }
+ return new CliError(error.message);
+ }
+ return new CliError("brain attention-flows: failed to evaluate flow");
+}
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
index 0698c59e..8a392423 100644
--- a/src/cli/brain/verbs/import-session.ts
+++ b/src/cli/brain/verbs/import-session.ts
@@ -31,6 +31,9 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
recall: { type: "boolean" },
"recall-session-id": { type: "string" },
"recall-summary-group-size": { type: "string" },
+ "ingest-scope": { type: "string" },
+ "filter-role": { type: "string-array" },
+ "filter-text": { type: "string" },
json: { type: "boolean" },
});
if (positional.length < 1) return fail("brain import-session requires a <path> argument");
@@ -50,6 +53,9 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
flags["recall-summary-group-size"],
"--recall-summary-group-size",
);
+ const ingestScope = normalizeFlagString(flags["ingest-scope"] as string | undefined);
+ const filterRoles = normalizeRoleFilter(flags["filter-role"] as string[] | undefined);
+ const filterText = normalizeFlagString(flags["filter-text"] as string | undefined);
const formatRaw = flags["format"] as string | undefined;
let format: SessionAdapterId | undefined;
@@ -81,6 +87,9 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
...(recallSummaryGroupSize !== undefined
? { recallSummaryGroupSize: recallSummaryGroupSize }
: {}),
+ ...(ingestScope !== null ? { ingestScope } : {}),
+ ...(filterRoles.length > 0 ? { filterRoles } : {}),
+ ...(filterText !== null ? { filterTextIncludes: filterText } : {}),
})
: {
files: [
@@ -94,6 +103,9 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
...(recallSummaryGroupSize !== undefined
? { recallSummaryGroupSize: recallSummaryGroupSize }
: {}),
+ ...(ingestScope !== null ? { ingestScope } : {}),
+ ...(filterRoles.length > 0 ? { filterRoles } : {}),
+ ...(filterText !== null ? { filterTextIncludes: filterText } : {}),
}),
],
warnings: [],
@@ -134,6 +146,7 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
signals_deduped: f.signals_deduped,
tool_replays: f.tool_replays,
malformed: f.malformed,
+ filtered_turns: f.filtered_turns,
recall_turns_imported: f.recall_turns_imported,
recall_summary_nodes: f.recall_summary_nodes,
errors: f.errors,
@@ -148,6 +161,7 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
ok(` signals_created: ${f.signals_created}`);
ok(` signals_deduped: ${f.signals_deduped}`);
ok(` tool_replays: ${f.tool_replays}`);
+ ok(` filtered_turns: ${f.filtered_turns}`);
if (flags["recall"]) {
ok(` recall_turns_imported: ${f.recall_turns_imported}`);
ok(` recall_summary_nodes: ${f.recall_summary_nodes}`);
@@ -168,6 +182,27 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
}
}
+function normalizeRoleFilter(
+ raw: string[] | undefined,
+): Array<"user" | "assistant" | "system" | "tool" | "meta"> {
+ if (!raw || raw.length === 0) return [];
+ const allowed = new Set(["user", "assistant", "system", "tool", "meta"] as const);
+ const out: Array<"user" | "assistant" | "system" | "tool" | "meta"> = [];
+ for (const value of raw) {
+ const normalized = value.trim().toLowerCase() as
+ | "user"
+ | "assistant"
+ | "system"
+ | "tool"
+ | "meta";
+ if (!allowed.has(normalized)) {
+ throw new CliError(`--filter-role contains unsupported value: ${value}`);
+ }
+ out.push(normalized);
+ }
+ return [...new Set(out)];
+}
+
function parsePositiveIntegerFlag(
value: string | boolean | string[] | undefined,
flag: string,
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 30427387..29bf7165 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -47,7 +47,9 @@ 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 { cmdBrainProceduralGraph } from "./procedural-graph.ts";
export { cmdBrainRecurrence } from "./recurrence.ts";
+export { cmdBrainAttentionFlows } from "./attention-flows.ts";
export {
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
diff --git a/src/cli/brain/verbs/procedural-graph.ts b/src/cli/brain/verbs/procedural-graph.ts
new file mode 100644
index 00000000..0f9aceef
--- /dev/null
+++ b/src/cli/brain/verbs/procedural-graph.ts
@@ -0,0 +1,96 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ readProceduralGraph,
+ rebuildProceduralGraph,
+} from "../../../core/brain/procedural-graph.ts";
+import {
+ readProceduralHints,
+ rebuildProceduralHints,
+} from "../../../core/brain/procedural-hints.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainProceduralGraph(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ if (sub === "rebuild") return rebuild(rest);
+ if (sub === "show") return show(rest);
+ if (sub === "hints") return hints(rest);
+ throw new CliError("brain procedural-graph: expected rebuild, show, or hints");
+}
+
+function rebuild(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const graph = rebuildProceduralGraph(vault);
+ const hintProjection = rebuildProceduralHints(vault, { graph });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ operation: "rebuild",
+ graph: {
+ nodes: graph.nodes.length,
+ edges: graph.edges.length,
+ generated_at: graph.generated_at,
+ },
+ hints: {
+ entries: hintProjection.entries.length,
+ generated_at: hintProjection.generated_at,
+ },
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `procedural-graph rebuilt: nodes=${graph.nodes.length} edges=${graph.edges.length} hints=${hintProjection.entries.length}\n`,
+ );
+ return 0;
+}
+
+function show(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const graph = readProceduralGraph(vault);
+ if (!graph) throw new CliError("brain procedural-graph show: graph projection not found");
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(graph, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `procedural-graph: nodes=${graph.nodes.length} edges=${graph.edges.length} generated_at=${graph.generated_at}\n`,
+ );
+ return 0;
+}
+
+function hints(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const projection = readProceduralHints(vault);
+ if (!projection) throw new CliError("brain procedural-graph hints: hints projection not found");
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(projection, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(
+ `procedural-hints: entries=${projection.entries.length} generated_at=${projection.generated_at}\n`,
+ );
+ return 0;
+}
diff --git a/src/cli/brain/verbs/procedural-memory.ts b/src/cli/brain/verbs/procedural-memory.ts
index fd8cefc3..fecc27b5 100644
--- a/src/cli/brain/verbs/procedural-memory.ts
+++ b/src/cli/brain/verbs/procedural-memory.ts
@@ -7,17 +7,13 @@ import {
import { CliError, parse, resolveBrainVault } from "../helpers.ts";
import { join } from "node:path";
-export async function cmdBrainProceduralMemory(
- argv: string[],
-): Promise<number> {
+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",
- );
+ throw new CliError("brain procedural-memory: expected reconcile, list, or mark-used");
}
function reconcile(argv: string[]): number {
@@ -26,10 +22,7 @@ function reconcile(argv: string[]): number {
json: { type: "boolean" },
root: { type: "string-array" },
});
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
const roots = normalizeRoots(vault, flags["root"]);
const result = reconcileProceduralMemory(vault, { roots });
@@ -49,16 +42,11 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
+ 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",
- );
+ process.stdout.write(JSON.stringify({ total: entries.length, entries }, null, 2) + "\n");
return 0;
}
@@ -77,46 +65,26 @@ function markUsed(argv: string[]): number {
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(),
- );
+ 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 (!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`,
- );
+ process.stdout.write(`marked used: ${updated.id} count=${updated.usedCount}\n`);
return 0;
}
-function normalizeRoots(
- vault: string,
- raw: string | boolean | string[] | undefined,
-): string[] {
+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);
+ 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"),
- ];
+ return [join(vault, "Brain", "procedures"), join(vault, "skills"), join(vault, "runbooks")];
}
function trim(value: string | undefined): string | undefined {
diff --git a/src/core/brain/attention-flows.ts b/src/core/brain/attention-flows.ts
new file mode 100644
index 00000000..af6ad6c8
--- /dev/null
+++ b/src/core/brain/attention-flows.ts
@@ -0,0 +1,167 @@
+import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { attentionFlowsDir } from "./paths.ts";
+import { listProceduralMemory } from "./procedural-memory.ts";
+import { listPendingSkillProposals } from "./skill-proposals.ts";
+import { listRecurrenceEntries } from "./recurrence.ts";
+
+export type AttentionFlowAction = "open_proposals" | "high_recurrence" | "active_procedures";
+
+export interface AttentionFlowRecipe {
+ readonly id: string;
+ readonly title: string;
+ readonly actions: ReadonlyArray<AttentionFlowAction>;
+ readonly sourcePath: string;
+}
+
+export interface AttentionFlowSection {
+ readonly action: AttentionFlowAction;
+ readonly items: ReadonlyArray<string>;
+}
+
+export interface AttentionFlowEvaluation {
+ readonly flow_id: string;
+ readonly title: string;
+ readonly sections: ReadonlyArray<AttentionFlowSection>;
+}
+
+export function ensureDefaultAttentionFlows(vault: string): void {
+ const dir = attentionFlowsDir(vault);
+ mkdirSync(dir, { recursive: true });
+ const defaultPath = join(dir, "open-loops.md");
+ if (existsSync(defaultPath)) return;
+ writeFrontmatterAtomic(
+ defaultPath,
+ {
+ kind: "brain-attention-flow",
+ id: "open-loops",
+ title: "Open loops and learnings",
+ actions: ["open_proposals", "high_recurrence", "active_procedures"],
+ status: "active",
+ },
+ [
+ "# Open loops and learnings",
+ "",
+ "Declarative flow for context surfaces:",
+ "- open proposals needing review",
+ "- strong recurrence candidates",
+ "- active procedural memory entries",
+ ].join("\n"),
+ {
+ overwrite: false,
+ existsErrorKind: "attention flow",
+ vaultForRelativePath: vault,
+ },
+ );
+}
+
+export function listAttentionFlows(vault: string): ReadonlyArray<AttentionFlowRecipe> {
+ ensureDefaultAttentionFlows(vault);
+ const dir = attentionFlowsDir(vault);
+ if (!existsSync(dir)) return Object.freeze([]);
+ const out: AttentionFlowRecipe[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(".md")) continue;
+ const path = join(dir, name);
+ try {
+ const [fm] = parseFrontmatter(path);
+ if (fm["kind"] !== "brain-attention-flow") continue;
+ const actions = normalizeActions(fm["actions"]);
+ out.push({
+ id: typeof fm["id"] === "string" ? fm["id"] : name.replace(/\.md$/, ""),
+ title: typeof fm["title"] === "string" ? fm["title"] : name.replace(/\.md$/, ""),
+ actions,
+ sourcePath: path,
+ });
+ } catch {
+ continue;
+ }
+ }
+ return Object.freeze(out);
+}
+
+export function evaluateAttentionFlow(vault: string, flowId: string): AttentionFlowEvaluation {
+ const flow = listAttentionFlows(vault).find((item) => item.id === flowId);
+ if (!flow) throw new Error(`attention flow not found: ${flowId}`);
+
+ const sections: AttentionFlowSection[] = [];
+ for (const action of flow.actions) {
+ if (action === "open_proposals") {
+ const items = listPendingSkillProposals(vault).map(
+ (item) => `${item.slug} (${item.patternKind})`,
+ );
+ sections.push({ action, items: Object.freeze(items) });
+ continue;
+ }
+ if (action === "high_recurrence") {
+ const items = listRecurrenceEntries(vault)
+ .filter((entry) => entry.supportCount >= 3)
+ .map((entry) => `${entry.contentHash} (${entry.supportCount})`);
+ sections.push({ action, items: Object.freeze(items) });
+ continue;
+ }
+ if (action === "active_procedures") {
+ const items = listProceduralMemory(vault)
+ .filter((entry) => entry.kind === "procedure" || entry.kind === "skill")
+ .map((entry) => `${entry.title} [${entry.kind}]`);
+ sections.push({ action, items: Object.freeze(items) });
+ }
+ }
+
+ return {
+ flow_id: flow.id,
+ title: flow.title,
+ sections: Object.freeze(sections.map((item) => Object.freeze(item))),
+ };
+}
+
+export function renderAttentionFlow(vault: string, flowId: string): string {
+ const report = evaluateAttentionFlow(vault, flowId);
+ const lines: string[] = [`# ${report.title}`, ""];
+ for (const section of report.sections) {
+ lines.push(`## ${section.action}`);
+ if (section.items.length === 0) {
+ lines.push("- (empty)");
+ } else {
+ for (const item of section.items) lines.push(`- ${item}`);
+ }
+ lines.push("");
+ }
+ return `${lines.join("\n").trimEnd()}\n`;
+}
+
+function normalizeActions(value: unknown): ReadonlyArray<AttentionFlowAction> {
+ const allowed = new Set<AttentionFlowAction>([
+ "open_proposals",
+ "high_recurrence",
+ "active_procedures",
+ ]);
+ const out: AttentionFlowAction[] = [];
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (typeof item !== "string") continue;
+ const action = item.trim() as AttentionFlowAction;
+ if (allowed.has(action)) out.push(action);
+ }
+ }
+ if (out.length === 0) return Object.freeze(["open_proposals", "high_recurrence"]);
+ return Object.freeze([...new Set(out)]);
+}
+
+export function buildAttentionContextBlock(
+ vault: string,
+ flowIds: ReadonlyArray<string>,
+): string | null {
+ const chunks: string[] = [];
+ for (const id of flowIds) {
+ try {
+ chunks.push(renderAttentionFlow(vault, id));
+ } catch {
+ continue;
+ }
+ }
+ if (chunks.length === 0) return null;
+ return chunks.join("\n");
+}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index e34c89c4..71969a47 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -27,8 +27,14 @@ import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
import { estimateTokens } from "./text/tokenizer.ts";
import { normalizeForDedup } from "./text/normalize.ts";
import { applyCharBudget } from "./recall-budget.ts";
-import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
-import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
+import {
+ emitContextReceipt,
+ type ContextReceiptOptions,
+} from "./context-receipts.ts";
+import {
+ emitRecallTelemetry,
+ type RecallTelemetryOptions,
+} from "./recall-telemetry.ts";
import {
applyContextTransforms,
type ContextTransformOptions,
@@ -40,6 +46,7 @@ import {
type ContextLaneName,
type ContextLanesReport,
} from "./context-lanes.ts";
+import { buildAttentionContextBlock } from "./attention-flows.ts";
const TIER_ORDER: ReadonlyArray<PageTier> = [
PAGE_TIER.core,
@@ -64,7 +71,11 @@ export interface ContextPackItem extends ContextTransformAnnotations {
export interface ContextPackSkipped {
readonly id: string;
readonly tokens: number;
- readonly reason: "over-budget" | "filter-miss" | "over-char-budget";
+ readonly reason:
+ | "over-budget"
+ | "filter-miss"
+ | "guard-blocked"
+ | "over-char-budget";
}
export interface ContextPackReport {
@@ -102,6 +113,8 @@ export interface ContextPackOptions {
readonly telemetry?: RecallTelemetryOptions;
/** Opt-in post-selection context transforms. Defaults preserve legacy order and bodies. */
readonly transforms?: ContextTransformOptions;
+ /** Optional declarative attention-flow ids to include as a synthetic context item. */
+ readonly attentionFlowIds?: ReadonlyArray<string>;
}
interface Candidate {
@@ -153,9 +166,11 @@ function collectCandidates(vault: string): Candidate[] {
} catch {
continue;
}
- const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
+ const id =
+ typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
const tier = readTier(meta);
- const created = typeof meta["created_at"] === "string" ? meta["created_at"] : "";
+ const created =
+ typeof meta["created_at"] === "string" ? meta["created_at"] : "";
let fallbackMtimeMs = 0;
if (!created) {
try {
@@ -166,7 +181,8 @@ function collectCandidates(vault: string): Candidate[] {
}
const createdAtMs = created ? Date.parse(created) : fallbackMtimeMs;
const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";
- const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";
+ const principle =
+ typeof meta["principle"] === "string" ? meta["principle"] : "";
const contextLane = normalizeContextLane(meta["context_lane"]);
const guarded = guardBrainContextSnippet(body, {
source: { id, path: full, metadata: meta },
@@ -189,14 +205,19 @@ function collectCandidates(vault: string): Candidate[] {
contextLane,
body: guarded.safeText,
tokens: estimateTokens(guarded.safeText),
- ...(contextSafetyReport(guarded) ? { safety: contextSafetyReport(guarded) } : {}),
+ ...(contextSafetyReport(guarded)
+ ? { safety: contextSafetyReport(guarded) }
+ : {}),
});
}
}
return out;
}
-export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport {
+export function packContext(
+ vault: string,
+ opts: ContextPackOptions,
+): ContextPackReport {
const startedAtMs = Date.now();
if (!Number.isFinite(opts.maxTokens) || opts.maxTokens <= 0) {
return finalizeContextPackReport(
@@ -262,6 +283,49 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
used += tokens;
}
+ if (opts.attentionFlowIds && opts.attentionFlowIds.length > 0) {
+ const attentionBody = buildAttentionContextBlock(
+ vault,
+ opts.attentionFlowIds,
+ );
+ if (attentionBody && attentionBody.trim()) {
+ const guarded = guardBrainContextSnippet(attentionBody, {
+ path: join(vault, "Brain", "attention", "flows"),
+ contextLane: "directive",
+ });
+ if (!guarded.allowed) {
+ skipped.push({
+ id: "attention-flows",
+ tokens: estimateTokens(attentionBody),
+ reason: "guard-blocked",
+ });
+ } else {
+ const safeAttentionBody = guarded.sanitized;
+ const tokens = estimateTokens(safeAttentionBody);
+ if (used + tokens <= opts.maxTokens) {
+ items.unshift({
+ id: "attention-flows",
+ path: join(vault, "Brain", "attention", "flows"),
+ tier: PAGE_TIER.core,
+ tokens,
+ body: safeAttentionBody,
+ principle: "Declarative attention flow output",
+ contextLane: "directive",
+ trimmed: false,
+ ...(guarded.report ? { safety: guarded.report } : {}),
+ });
+ used += tokens;
+ } else {
+ skipped.push({
+ id: "attention-flows",
+ tokens,
+ reason: "over-budget",
+ });
+ }
+ }
+ }
+ }
+
// Total recall character cap (v0.20.0): a second ceiling over the
// token-budgeted set. Applied via the shared primitive on the emitted
// items only (so query-missed pages never count), dropping the
@@ -304,7 +368,10 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
}
const finalItems = applyContextTransforms(items, opts.transforms);
- const finalTokensUsed = finalItems.reduce((sum, item) => sum + item.tokens, 0);
+ const finalTokensUsed = finalItems.reduce(
+ (sum, item) => sum + item.tokens,
+ 0,
+ );
return finalizeContextPackReport(
vault,
opts,
@@ -357,7 +424,9 @@ function finalizeContextPackReport(
status: report.items.length > 0 ? "ok" : "empty",
durationMs: Date.now() - startedAtMs,
resultCount: report.items.length,
- topArtifacts: report.items.slice(0, 10).map((item) => ({ id: item.id, path: item.path })),
+ topArtifacts: report.items
+ .slice(0, 10)
+ .map((item) => ({ id: item.id, path: item.path })),
gaps: contextPackGaps(report),
metadata: {
...(opts.telemetry.metadata ?? {}),
@@ -382,13 +451,17 @@ function contextPackBudgetMetadata(
...(opts.maxCharsPerMemory !== undefined
? { max_chars_per_memory: opts.maxCharsPerMemory }
: {}),
- ...(opts.maxTotalChars !== undefined ? { max_total_chars: opts.maxTotalChars } : {}),
+ ...(opts.maxTotalChars !== undefined
+ ? { max_total_chars: opts.maxTotalChars }
+ : {}),
};
}
function contextPackGaps(report: ContextPackReport): ReadonlyArray<string> {
const gaps = new Set<string>();
- if (report.items.length === 0 && report.skipped.length === 0) gaps.add("no_matching_context");
- for (const skipped of report.skipped) gaps.add(skipped.reason.replace(/-/g, "_"));
+ if (report.items.length === 0 && report.skipped.length === 0)
+ gaps.add("no_matching_context");
+ for (const skipped of report.skipped)
+ gaps.add(skipped.reason.replace(/-/g, "_"));
return [...gaps];
}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index d43f50a9..32bf7626 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -51,6 +51,7 @@ export const BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSA
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_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");
export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");
/**
@@ -204,6 +205,21 @@ export function proceduralMemoryUsagePath(vault: string): string {
return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "usage.jsonl"), vault);
}
+/** Procedural graph projection path: `Brain/procedural-memory/graph.json`. */
+export function proceduralGraphPath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "graph.json"), vault);
+}
+
+/** Prospective recall hints path: `Brain/procedural-memory/hints.json`. */
+export function proceduralHintsPath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "hints.json"), vault);
+}
+
+/** Declarative attention-flows directory: `Brain/attention/flows/`. */
+export function attentionFlowsDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_ATTENTION_REL, "flows"), vault);
+}
+
/** Proposal scan watermark path: `Brain/procedural-memory/proposal-watermark.json`. */
export function proposalWatermarkPath(vault: string): string {
return ensureInsideVault(
diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.ts
new file mode 100644
index 00000000..736de8fa
--- /dev/null
+++ b/src/core/brain/procedural-graph.ts
@@ -0,0 +1,303 @@
+import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import { parseFrontmatter } from "../vault.ts";
+import {
+ proceduralGraphPath,
+ proceduralMemoryIndexPath,
+ skillProposalAcceptedPath,
+ skillProposalPendingPath,
+ skillProposalRejectedPath,
+} from "./paths.ts";
+import type { ProceduralMemoryEntry } from "./procedural-memory.ts";
+
+export type ProceduralGraphNodeKind =
+ | "procedure"
+ | "skill"
+ | "runbook"
+ | "proposal"
+ | "entity";
+export type ProceduralGraphEdgeKind =
+ | "derived_from_proposal"
+ | "trigger_matches"
+ | "tag_matches"
+ | "source_mentions"
+ | "proposal_mentions";
+
+export interface ProceduralGraphNode {
+ readonly id: string;
+ readonly kind: ProceduralGraphNodeKind;
+ readonly title: string;
+ readonly sourcePath: string | null;
+ readonly metadata: Readonly<Record<string, unknown>>;
+}
+
+export interface ProceduralGraphEdge {
+ readonly from: string;
+ readonly to: string;
+ readonly kind: ProceduralGraphEdgeKind;
+}
+
+export interface ProceduralGraphProjection {
+ readonly schema_version: 1;
+ readonly generated_at: string;
+ readonly nodes: ReadonlyArray<ProceduralGraphNode>;
+ readonly edges: ReadonlyArray<ProceduralGraphEdge>;
+}
+
+export interface ProceduralGraphBuildOptions {
+ readonly now?: Date;
+}
+
+export function rebuildProceduralGraph(
+ vault: string,
+ opts: ProceduralGraphBuildOptions = {},
+): ProceduralGraphProjection {
+ const now = opts.now ?? new Date();
+ const nodes: ProceduralGraphNode[] = [];
+ const edges: ProceduralGraphEdge[] = [];
+
+ const entries = readProceduralIndex(vault);
+ const nodeById = new Set<string>();
+ for (const entry of entries) {
+ const node: ProceduralGraphNode = {
+ id: entry.id,
+ kind: entry.kind,
+ title: entry.title,
+ sourcePath: entry.sourcePath,
+ metadata: {
+ triggers: [...entry.triggers],
+ tags: [...entry.tags],
+ source: entry.source,
+ version: entry.version,
+ },
+ };
+ nodes.push(node);
+ nodeById.add(node.id);
+
+ if (entry.kind === "procedure") {
+ const proposalId = detectProcedureSourceProposal(vault, entry.sourcePath);
+ if (proposalId) {
+ edges.push({
+ from: node.id,
+ to: proposalId,
+ kind: "derived_from_proposal",
+ });
+ }
+ }
+
+ for (const trigger of entry.triggers) {
+ const entityId = entityNodeId(`trigger:${trigger}`);
+ ensureEntityNode(nodes, nodeById, entityId, `Trigger: ${trigger}`);
+ edges.push({ from: node.id, to: entityId, kind: "trigger_matches" });
+ }
+
+ for (const tag of entry.tags) {
+ const entityId = entityNodeId(`tag:${tag}`);
+ ensureEntityNode(nodes, nodeById, entityId, `Tag: ${tag}`);
+ edges.push({ from: node.id, to: entityId, kind: "tag_matches" });
+ }
+
+ for (const token of sourcePathTokens(entry.sourcePath)) {
+ const entityId = entityNodeId(`path:${token}`);
+ ensureEntityNode(nodes, nodeById, entityId, `Path: ${token}`);
+ edges.push({ from: node.id, to: entityId, kind: "source_mentions" });
+ }
+ }
+
+ for (const proposal of listProposals(vault)) {
+ nodes.push(proposal);
+ nodeById.add(proposal.id);
+ for (const token of sourcePathTokens(proposal.sourcePath ?? "")) {
+ const entityId = entityNodeId(`proposal-path:${token}`);
+ ensureEntityNode(nodes, nodeById, entityId, `Proposal Path: ${token}`);
+ edges.push({
+ from: proposal.id,
+ to: entityId,
+ kind: "proposal_mentions",
+ });
+ }
+ }
+
+ const projection: ProceduralGraphProjection = {
+ schema_version: 1,
+ generated_at: now.toISOString(),
+ nodes: Object.freeze(
+ nodes
+ .toSorted((left, right) => left.id.localeCompare(right.id))
+ .map((item) => Object.freeze(item)),
+ ),
+ edges: Object.freeze(
+ dedupeEdges(edges)
+ .toSorted(
+ (left, right) =>
+ left.from.localeCompare(right.from) ||
+ left.to.localeCompare(right.to) ||
+ left.kind.localeCompare(right.kind),
+ )
+ .map((item) => Object.freeze(item)),
+ ),
+ };
+
+ const path = proceduralGraphPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteFileSync(path, `${JSON.stringify(projection, null, 2)}\n`);
+ return projection;
+}
+
+export function readProceduralGraph(
+ vault: string,
+): ProceduralGraphProjection | null {
+ const path = proceduralGraphPath(vault);
+ if (!existsSync(path)) return null;
+ try {
+ const parsed = JSON.parse(
+ readFileSync(path, "utf8"),
+ ) as ProceduralGraphProjection;
+ if (parsed.schema_version !== 1) return null;
+ if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges))
+ return null;
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
+function readProceduralIndex(vault: string): ProceduralMemoryEntry[] {
+ const path = proceduralMemoryIndexPath(vault);
+ if (!existsSync(path)) return [];
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as {
+ schema_version?: unknown;
+ entries?: ProceduralMemoryEntry[];
+ };
+ if (parsed.schema_version !== 1) return [];
+ if (!Array.isArray(parsed.entries)) return [];
+ return parsed.entries;
+ } catch {
+ return [];
+ }
+}
+
+function detectProcedureSourceProposal(
+ vault: string,
+ sourcePath: string,
+): string | null {
+ if (!sourcePath.startsWith("Brain/procedures/")) return null;
+ let absPath: string;
+ try {
+ absPath = ensureInsideVault(join(vault, sourcePath), vault);
+ } catch {
+ return null;
+ }
+ if (!existsSync(absPath)) return null;
+ try {
+ const [fm] = parseFrontmatter(absPath);
+ if (
+ typeof fm["source_proposal"] === "string" &&
+ fm["source_proposal"].trim()
+ ) {
+ return fm["source_proposal"].trim();
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+function listProposals(vault: string): ProceduralGraphNode[] {
+ const out: ProceduralGraphNode[] = [];
+ for (const tuple of [
+ ["pending", skillProposalPendingPath],
+ ["accepted", skillProposalAcceptedPath],
+ ["rejected", skillProposalRejectedPath],
+ ] as const) {
+ const [status, builder] = tuple;
+ const dir = dirname(builder(vault, "sample"));
+ if (!existsSync(dir)) continue;
+ for (const name of readDirSorted(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const absPath = `${dir}/${name}`;
+ try {
+ const [fm] = parseFrontmatter(absPath);
+ if (fm["kind"] !== "brain-skill-proposal") continue;
+ const id =
+ typeof fm["id"] === "string"
+ ? fm["id"]
+ : `proposal-${basename(name, ".md")}`;
+ out.push({
+ id,
+ kind: "proposal",
+ title:
+ typeof fm["slug"] === "string"
+ ? `Proposal: ${fm["slug"]}`
+ : `Proposal: ${basename(name, ".md")}`,
+ sourcePath: `Brain/skill-proposals/${status}/${name}`,
+ metadata: {
+ status,
+ pattern_kind: fm["pattern_kind"] ?? null,
+ },
+ });
+ } catch {
+ continue;
+ }
+ }
+ }
+ return out;
+}
+
+function readDirSorted(dir: string): string[] {
+ try {
+ return readdirSync(dir).toSorted();
+ } catch {
+ return [];
+ }
+}
+
+function sourcePathTokens(path: string): string[] {
+ return path
+ .replaceAll("\\", "/")
+ .split("/")
+ .map((part) => part.trim().toLowerCase())
+ .filter((part) => part.length >= 3 && /^[a-z0-9._-]+$/.test(part));
+}
+
+function ensureEntityNode(
+ nodes: ProceduralGraphNode[],
+ nodeById: Set<string>,
+ id: string,
+ title: string,
+): void {
+ if (nodeById.has(id)) return;
+ nodes.push({
+ id,
+ kind: "entity",
+ title,
+ sourcePath: null,
+ metadata: {},
+ });
+ nodeById.add(id);
+}
+
+function entityNodeId(raw: string): string {
+ return `ent-${raw
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")}`;
+}
+
+function dedupeEdges(
+ edges: ReadonlyArray<ProceduralGraphEdge>,
+): ProceduralGraphEdge[] {
+ const out: ProceduralGraphEdge[] = [];
+ const seen = new Set<string>();
+ for (const edge of edges) {
+ const key = `${edge.from}\u0000${edge.to}\u0000${edge.kind}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(edge);
+ }
+ return out;
+}
diff --git a/src/core/brain/procedural-hints.ts b/src/core/brain/procedural-hints.ts
new file mode 100644
index 00000000..ae70cc83
--- /dev/null
+++ b/src/core/brain/procedural-hints.ts
@@ -0,0 +1,94 @@
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { proceduralHintsPath } from "./paths.ts";
+import {
+ readProceduralGraph,
+ type ProceduralGraphProjection,
+} from "./procedural-graph.ts";
+
+export interface ProceduralHintEntry {
+ readonly node_id: string;
+ readonly cues: ReadonlyArray<string>;
+}
+
+export interface ProceduralHintsProjection {
+ readonly schema_version: 1;
+ readonly generated_at: string;
+ readonly entries: ReadonlyArray<ProceduralHintEntry>;
+}
+
+export function rebuildProceduralHints(
+ vault: string,
+ opts: { now?: Date; graph?: ProceduralGraphProjection } = {},
+): ProceduralHintsProjection {
+ const graph = opts.graph ?? readProceduralGraph(vault);
+ const now = opts.now ?? new Date();
+ const entries: ProceduralHintEntry[] = [];
+ if (graph !== null) {
+ for (const node of graph.nodes) {
+ if (node.kind === "entity") continue;
+ const cues = new Set<string>();
+ for (const token of tokenizeCue(node.title)) cues.add(token);
+ if (node.sourcePath) {
+ for (const token of tokenizeCue(node.sourcePath)) cues.add(token);
+ }
+ for (const value of Object.values(node.metadata)) {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (typeof item === "string") {
+ for (const token of tokenizeCue(item)) cues.add(token);
+ }
+ }
+ } else if (typeof value === "string") {
+ for (const token of tokenizeCue(value)) cues.add(token);
+ }
+ }
+ entries.push({
+ node_id: node.id,
+ cues: Object.freeze(
+ [...cues].filter((item) => item.length >= 3).toSorted(),
+ ),
+ });
+ }
+ }
+
+ const projection: ProceduralHintsProjection = {
+ schema_version: 1,
+ generated_at: now.toISOString(),
+ entries: Object.freeze(
+ entries.toSorted((l, r) => l.node_id.localeCompare(r.node_id)),
+ ),
+ };
+
+ const path = proceduralHintsPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteFileSync(path, `${JSON.stringify(projection, null, 2)}\n`);
+ return projection;
+}
+
+export function readProceduralHints(
+ vault: string,
+): ProceduralHintsProjection | null {
+ const path = proceduralHintsPath(vault);
+ if (!existsSync(path)) return null;
+ try {
+ const parsed = JSON.parse(
+ readFileSync(path, "utf8"),
+ ) as ProceduralHintsProjection;
+ if (parsed.schema_version !== 1) return null;
+ if (!Array.isArray(parsed.entries)) return null;
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
+function tokenizeCue(input: string): string[] {
+ return input
+ .toLowerCase()
+ .split(/[^a-z0-9]+/g)
+ .map((item) => item.trim())
+ .filter((item) => item.length >= 3);
+}
diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.ts
index e8568c54..2e6ebd1a 100644
--- a/src/core/brain/procedural-memory.ts
+++ b/src/core/brain/procedural-memory.ts
@@ -1,20 +1,13 @@
import { createHash } from "node:crypto";
-import {
- existsSync,
- lstatSync,
- mkdirSync,
- readdirSync,
- readFileSync,
-} from "node:fs";
+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";
+import { rebuildProceduralHints } from "./procedural-hints.ts";
+import { rebuildProceduralGraph } from "./procedural-graph.ts";
+import { proceduralMemoryIndexPath, proceduralMemoryUsagePath } from "./paths.ts";
export type ProceduralEntryKind = "skill" | "runbook" | "procedure";
@@ -47,9 +40,7 @@ export function reconcileProceduralMemory(
vault: string,
opts: ProceduralReconcileOptions,
): ProceduralReconcileResult {
- const prev = new Map(
- listProceduralMemory(vault).map((entry) => [entry.id, entry] as const),
- );
+ 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);
@@ -82,12 +73,12 @@ export function reconcileProceduralMemory(
}
writeIndex(vault, next);
+ const graph = rebuildProceduralGraph(vault);
+ rebuildProceduralHints(vault, { graph });
return { total: next.length, added, updated, removed };
}
-export function listProceduralMemory(
- vault: string,
-): ReadonlyArray<ProceduralMemoryEntry> {
+export function listProceduralMemory(vault: string): ReadonlyArray<ProceduralMemoryEntry> {
const path = proceduralMemoryIndexPath(vault);
if (!existsSync(path)) return Object.freeze([]);
try {
@@ -128,14 +119,13 @@ export function markProceduralMemoryUsed(
lastUsedAt: now.toISOString(),
});
writeUsageMap(vault, usage);
+ const graph = rebuildProceduralGraph(vault);
+ rebuildProceduralHints(vault, { graph });
return next.find((entry) => entry.id === id) ?? null;
}
-function collectEntries(
- vault: string,
- roots: ReadonlyArray<string>,
-): ProceduralMemoryEntry[] {
+function collectEntries(vault: string, roots: ReadonlyArray<string>): ProceduralMemoryEntry[] {
const out: ProceduralMemoryEntry[] = [];
for (const root of roots) {
@@ -166,19 +156,13 @@ function collectEntries(
}
}
- return out.toSorted((left, right) =>
- left.sourcePath.localeCompare(right.sourcePath),
- );
+ 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";
+ if (vaultRelPath.endsWith(".prompt.md") || vaultRelPath.endsWith("runbook.md")) return "runbook";
return null;
}
@@ -225,35 +209,25 @@ function toVaultRelative(vault: string, absPath: string): string {
}
function entryId(sourcePath: string): string {
- const hash = createHash("sha256")
- .update(sourcePath, "utf8")
- .digest("hex")
- .slice(0, 12);
+ 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,
+ (item): item is string => typeof item === "string" && item.trim().length > 0,
);
}
- if (typeof value === "string" && value.trim().length > 0)
- return [value.trim()];
+ 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;
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
-function writeIndex(
- vault: string,
- entries: ReadonlyArray<ProceduralMemoryEntry>,
-): void {
+function writeIndex(vault: string, entries: ReadonlyArray<ProceduralMemoryEntry>): void {
const path = proceduralMemoryIndexPath(vault);
mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
const payload = JSON.stringify(
@@ -273,10 +247,7 @@ function readUsageMap(
const path = proceduralMemoryUsagePath(vault);
if (!existsSync(path)) return new Map();
- const out = new Map<
- string,
- { usedCount: number; lastUsedAt: string | null }
- >();
+ const out = new Map<string, { usedCount: number; lastUsedAt: string | null }>();
for (const line of readFileSync(path, "utf8").split("\n")) {
if (!line.trim()) continue;
try {
@@ -284,12 +255,8 @@ function readUsageMap(
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,
+ usedCount: typeof parsed["usedCount"] === "number" ? parsed["usedCount"] : 0,
+ lastUsedAt: typeof parsed["lastUsedAt"] === "string" ? parsed["lastUsedAt"] : null,
});
} catch {
continue;
@@ -316,8 +283,5 @@ function writeUsageMap(
}),
);
}
- atomicWriteFileSync(
- path,
- `${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`,
- );
+ atomicWriteFileSync(path, `${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`);
}
diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.ts
index 7b3dbaae..5773ec05 100644
--- a/src/core/brain/recurrence.ts
+++ b/src/core/brain/recurrence.ts
@@ -4,11 +4,7 @@ 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 RecurrenceCommitment = "exploring" | "leaning" | "decided" | "locked";
export type RecurrenceAction = "learn" | "forget";
export interface RecurrenceThresholds {
@@ -64,11 +60,7 @@ export function applyRecurrenceEvidence(
return getRecurrenceEntry(vault, input.contentHash);
}
-export function purgeRecurrenceSource(
- vault: string,
- sourceId: string,
- at?: string,
-): void {
+export function purgeRecurrenceSource(vault: string, sourceId: string, at?: string): void {
appendEvent(vault, {
kind: "purge-source",
sourceId,
@@ -82,9 +74,8 @@ export function getRecurrenceEntry(
thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,
): RecurrenceEntry | null {
return (
- listRecurrenceEntries(vault, thresholds).find(
- (entry) => entry.contentHash === contentHash,
- ) ?? null
+ listRecurrenceEntries(vault, thresholds).find((entry) => entry.contentHash === contentHash) ??
+ null
);
}
@@ -93,10 +84,7 @@ export function listRecurrenceEntries(
thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,
): ReadonlyArray<RecurrenceEntry> {
const events = readEvents(vault);
- const state = new Map<
- string,
- { supportBySourceScope: Map<string, number> }
- >();
+ const state = new Map<string, { supportBySourceScope: Map<string, number> }>();
for (const event of events) {
if (event.kind === "purge-source") {
@@ -120,8 +108,7 @@ export function listRecurrenceEntries(
if (event.action === "learn") {
bucket.supportBySourceScope.set(sourceScopeKey, current + 1);
} else {
- if (current > 1)
- bucket.supportBySourceScope.set(sourceScopeKey, current - 1);
+ if (current > 1) bucket.supportBySourceScope.set(sourceScopeKey, current - 1);
else bucket.supportBySourceScope.delete(sourceScopeKey);
}
@@ -137,10 +124,7 @@ export function listRecurrenceEntries(
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,
- );
+ supportBySource.set(sourceId, (supportBySource.get(sourceId) ?? 0) + support);
}
const scopes = [...supportByScope.entries()]
@@ -165,9 +149,7 @@ export function listRecurrenceEntries(
}
return Object.freeze(
- out.toSorted((left, right) =>
- left.contentHash.localeCompare(right.contentHash),
- ),
+ out.toSorted((left, right) => left.contentHash.localeCompare(right.contentHash)),
);
}
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index c398e44e..16a1336b 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -71,6 +71,12 @@ export interface ImportSessionOptions {
readonly recall?: boolean;
readonly recallSessionId?: string;
readonly recallSummaryGroupSize?: number;
+ /** Optional ingest scope label stamped into imported signal notes. */
+ readonly ingestScope?: string;
+ /** Optional role filter for write-side extraction. */
+ readonly filterRoles?: ReadonlyArray<SessionTurn["role"]>;
+ /** Optional case-insensitive substring filter on turn text. */
+ readonly filterTextIncludes?: string;
}
export interface ImportSessionResult {
@@ -81,6 +87,7 @@ export interface ImportSessionResult {
readonly signals_deduped: number;
readonly tool_replays: number;
readonly malformed: number;
+ readonly filtered_turns: number;
readonly recall_turns_imported: number;
readonly recall_summary_nodes: number;
readonly errors: ReadonlyArray<{ path: string; message: string }>;
@@ -140,7 +147,11 @@ export async function importSession(
let signalsDeduped = 0;
let toolReplays = 0;
let malformed = 0;
+ let filteredTurns = 0;
const recallTurns: SessionTurn[] = [];
+ const filterRoles =
+ opts.filterRoles && opts.filterRoles.length > 0 ? new Set(opts.filterRoles) : null;
+ const filterNeedle = opts.filterTextIncludes?.trim().toLowerCase() ?? null;
// Inline helper that wraps the writeSignal call with the consistent
// shape every session-imported signal shares.
@@ -179,7 +190,13 @@ export async function importSession(
source_type: BRAIN_SIGNAL_SOURCE_TYPE.session,
dedup_hash: input.dedupHash,
session_ref: sessionRef,
- ...(input.note ? { raw: input.note } : {}),
+ ...(input.note || opts.ingestScope
+ ? {
+ raw: [opts.ingestScope ? `[ingest_scope:${opts.ingestScope}]` : "", input.note ?? ""]
+ .filter((chunk) => chunk.length > 0)
+ .join("\n"),
+ }
+ : {}),
...(opts.rawCodec === true ? { rawCodec: true } : {}),
});
dedup.set(input.dedupHash, { id: res.id, path: res.path });
@@ -198,6 +215,17 @@ export async function importSession(
const t = Date.parse(turn.timestamp);
if (Number.isFinite(t) && t < sinceMs) continue;
}
+ if (filterRoles !== null && !filterRoles.has(turn.role)) {
+ filteredTurns++;
+ continue;
+ }
+ if (filterNeedle !== null) {
+ const haystack = turn.text?.toLowerCase() ?? "";
+ if (!haystack.includes(filterNeedle)) {
+ filteredTurns++;
+ continue;
+ }
+ }
if (opts.recall === true) recallTurns.push(turn);
// Path A — markers in text.
@@ -284,6 +312,7 @@ export async function importSession(
signals_deduped: signalsDeduped,
tool_replays: toolReplays,
malformed,
+ filtered_turns: filteredTurns,
recall_turns_imported: recallTurnsImported,
recall_summary_nodes: recallSummaryNodes,
errors: Object.freeze(errors),
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index df2e2cd9..a8bca46e 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -11,6 +11,9 @@ 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 { rebuildProceduralHints } from "./procedural-hints.ts";
+import { rebuildProceduralGraph } from "./procedural-graph.ts";
+import { reconcileProceduralMemory } from "./procedural-memory.ts";
import {
BRAIN_SKILL_PROPOSALS_REL,
procedurePath,
@@ -65,6 +68,7 @@ interface WatermarkState {
}
const DEFAULT_MIN_SUPPORT = 3;
+const DEFAULT_PROCEDURAL_ROOTS = ["Brain/procedures", "skills"] as const;
export function learnSkillProposals(
vault: string,
@@ -157,6 +161,8 @@ export function learnSkillProposals(
lastCreatedAt: watermarkTo,
lastId: watermarkRecord.id,
});
+ const graph = rebuildProceduralGraph(vault);
+ rebuildProceduralHints(vault, { graph });
return {
watermarkFrom: watermark.lastCreatedAt,
@@ -267,6 +273,11 @@ export function acceptSkillProposal(
}
unlinkSync(pendingPath);
+ reconcileProceduralMemory(vault, {
+ roots: DEFAULT_PROCEDURAL_ROOTS.map((root) => join(vault, root)),
+ });
+ const graph = rebuildProceduralGraph(vault);
+ rebuildProceduralHints(vault, { graph });
return {
id,
slug,
@@ -316,6 +327,11 @@ export function rejectSkillProposal(
);
unlinkSync(pendingPath);
+ reconcileProceduralMemory(vault, {
+ roots: DEFAULT_PROCEDURAL_ROOTS.map((root) => join(vault, root)),
+ });
+ const graph = rebuildProceduralGraph(vault);
+ rebuildProceduralHints(vault, { graph });
return { id, slug, status: "rejected", proposalPath: rejectedPath };
}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 8e3ae7fd..17f47746 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -110,12 +110,19 @@ import {
markProceduralMemoryUsed,
reconcileProceduralMemory,
} from "../core/brain/procedural-memory.ts";
+import { readProceduralGraph, rebuildProceduralGraph } from "../core/brain/procedural-graph.ts";
+import { readProceduralHints, rebuildProceduralHints } from "../core/brain/procedural-hints.ts";
import {
applyRecurrenceEvidence,
getRecurrenceEntry,
listRecurrenceEntries,
purgeRecurrenceSource,
} from "../core/brain/recurrence.ts";
+import {
+ evaluateAttentionFlow,
+ listAttentionFlows,
+ renderAttentionFlow,
+} from "../core/brain/attention-flows.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";
@@ -1750,6 +1757,7 @@ async function toolBrainContextPack(
const includeLanes = coerceBool(args, "lanes");
const cacheStable = coerceBool(args, "cache_stable");
const dedupRepeated = coerceBool(args, "dedup_repeated");
+ const attentionFlowIds = coerceStrList(args, "attention_flow_ids");
const maxCharsPerMemory = optionalPositiveInt(args, "max_chars_per_memory", "brain_context_pack");
const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_context_pack");
const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");
@@ -1770,6 +1778,7 @@ async function toolBrainContextPack(
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
...(telemetry !== undefined ? { telemetry } : {}),
+ ...(attentionFlowIds.length > 0 ? { attentionFlowIds } : {}),
});
return {
vault_path: ctx.vault,
@@ -2282,6 +2291,74 @@ async function toolBrainRecurrence(
);
}
+async function toolBrainProceduralGraph(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_procedural_graph", args, "operation");
+ if (operation === "rebuild") {
+ const graph = rebuildProceduralGraph(ctx.vault);
+ const hints = rebuildProceduralHints(ctx.vault, { graph });
+ return {
+ operation,
+ graph: {
+ nodes: graph.nodes.length,
+ edges: graph.edges.length,
+ generated_at: graph.generated_at,
+ },
+ hints: {
+ entries: hints.entries.length,
+ generated_at: hints.generated_at,
+ },
+ };
+ }
+ if (operation === "show") {
+ const graph = readProceduralGraph(ctx.vault);
+ if (!graph) {
+ throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: graph projection not found");
+ }
+ return { ...graph };
+ }
+ if (operation === "hints") {
+ const hints = readProceduralHints(ctx.vault);
+ if (!hints) {
+ throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: hints projection not found");
+ }
+ return { ...hints };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_procedural_graph: operation must be one of rebuild|show|hints",
+ );
+}
+
+async function toolBrainAttentionFlows(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_attention_flows", args, "operation");
+ if (operation === "list") {
+ const flows = listAttentionFlows(ctx.vault);
+ return { total: flows.length, flows };
+ }
+ if (operation === "evaluate") {
+ const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
+ const report = evaluateAttentionFlow(ctx.vault, flowId);
+ return { ...report };
+ }
+ if (operation === "render") {
+ const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
+ return {
+ flow_id: flowId,
+ text: renderAttentionFlow(ctx.vault, flowId),
+ };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_attention_flows: operation must be one of list|evaluate|render",
+ );
+}
+
async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
const landscape = buildMcpLandscape(ctx.vault);
return {
@@ -2878,6 +2955,12 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"When true, replace repeated context bodies with reference hints to an earlier emitted item.",
},
+ attention_flow_ids: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Optional declarative attention flow ids to inject as a synthetic context block.",
+ },
receipt: {
type: "boolean",
description: "When true, emit an opt-in context receipt for this context-pack run.",
@@ -3119,6 +3202,46 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainRecurrence,
},
+ {
+ name: "brain_procedural_graph",
+ description:
+ "Rebuild/show procedural graph projection and prospective hint projection (rebuild, show, hints).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["rebuild", "show", "hints"],
+ description: "Tool operation.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainProceduralGraph,
+ },
+ {
+ name: "brain_attention_flows",
+ description:
+ "List/evaluate/render declarative attention-flow recipes for open loops and learnings.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "evaluate", "render"],
+ description: "Tool operation.",
+ },
+ flow_id: {
+ type: "string",
+ description: "Flow id for evaluate/render operations.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainAttentionFlows,
+ },
{
name: "brain_pre_compact_extract",
description:
diff --git a/tests/cli/brain-procedural-learning.test.ts b/tests/cli/brain-procedural-learning.test.ts
index 1d5ffb92..f1163700 100644
--- a/tests/cli/brain-procedural-learning.test.ts
+++ b/tests/cli/brain-procedural-learning.test.ts
@@ -90,6 +90,67 @@ test("brain procedural learning verbs wire end-to-end", async () => {
]);
expect(mark.returncode).toBe(0);
+ const graphRebuild = await runCli([
+ "brain",
+ "procedural-graph",
+ "rebuild",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(graphRebuild.returncode).toBe(0);
+ const graphRebuildJson = JSON.parse(graphRebuild.stdout);
+ expect(graphRebuildJson.operation).toBe("rebuild");
+
+ const graphShow = await runCli(["brain", "procedural-graph", "show", "--vault", vault, "--json"]);
+ expect(graphShow.returncode).toBe(0);
+ const graphShowJson = JSON.parse(graphShow.stdout);
+ expect(graphShowJson.nodes.length).toBeGreaterThan(0);
+
+ const graphHints = await runCli([
+ "brain",
+ "procedural-graph",
+ "hints",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(graphHints.returncode).toBe(0);
+ const graphHintsJson = JSON.parse(graphHints.stdout);
+ expect(graphHintsJson.entries.length).toBeGreaterThan(0);
+
+ const flowsList = await runCli(["brain", "attention-flows", "list", "--vault", vault, "--json"]);
+ expect(flowsList.returncode).toBe(0);
+ const flowsListJson = JSON.parse(flowsList.stdout);
+ expect(flowsListJson.total).toBeGreaterThan(0);
+
+ const flowId = flowsListJson.flows[0]?.id;
+ expect(typeof flowId).toBe("string");
+
+ const flowEval = await runCli([
+ "brain",
+ "attention-flows",
+ "evaluate",
+ flowId,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(flowEval.returncode).toBe(0);
+
+ const flowRender = await runCli([
+ "brain",
+ "attention-flows",
+ "render",
+ flowId,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(flowRender.returncode).toBe(0);
+ const flowRenderJson = JSON.parse(flowRender.stdout);
+ expect(flowRenderJson.text).toContain("#");
+
const learnRecurrence = await runCli([
"brain",
"recurrence",
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index 998bc861..1e8fb4df 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -111,6 +111,27 @@ describe("importSession", () => {
);
});
+ test("supports filtered write mode by role", async () => {
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ filterRoles: ["user"],
+ });
+
+ expect(res.signals_created).toBe(1);
+ expect(res.tool_replays).toBe(0);
+ expect(res.filtered_turns).toBeGreaterThan(0);
+ });
+
+ test("supports filtered write mode by text substring", async () => {
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ filterTextIncludes: "no-match-substring",
+ });
+
+ expect(res.signals_created).toBe(0);
+ expect(res.filtered_turns).toBe(res.turns_scanned);
+ });
+
test("handles the codex fixture", async () => {
const res = await importSession(tmp, CODEX, { agent: "test" });
expect(res.format).toBe("codex");
diff --git a/tests/core/brain/attention-flows.test.ts b/tests/core/brain/attention-flows.test.ts
new file mode 100644
index 00000000..746652d1
--- /dev/null
+++ b/tests/core/brain/attention-flows.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ buildAttentionContextBlock,
+ evaluateAttentionFlow,
+ listAttentionFlows,
+ renderAttentionFlow,
+} from "../../../src/core/brain/attention-flows.ts";
+import { applyRecurrenceEvidence } from "../../../src/core/brain/recurrence.ts";
+import { reconcileProceduralMemory } from "../../../src/core/brain/procedural-memory.ts";
+import { writeFrontmatterAtomic } from "../../../src/core/vault.ts";
+import { skillProposalPendingPath } from "../../../src/core/brain/paths.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = join(
+ tmpdir(),
+ `o2b-attention-flows-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ );
+ mkdirSync(vault, { recursive: true });
+ seedSources(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("attention flow recipes", () => {
+ test("lists default flow and evaluates deterministic sections", () => {
+ const flows = listAttentionFlows(vault);
+ expect(flows.length).toBeGreaterThan(0);
+
+ const report = evaluateAttentionFlow(vault, flows[0]!.id);
+ expect(report.sections.length).toBeGreaterThan(0);
+ expect(renderAttentionFlow(vault, report.flow_id)).toContain("#");
+ });
+
+ test("builds context block for requested flow ids", () => {
+ const flows = listAttentionFlows(vault);
+ const block = buildAttentionContextBlock(vault, [flows[0]!.id]);
+ expect(block).not.toBeNull();
+ expect(block).toContain(flows[0]!.title);
+ });
+});
+
+function seedSources(vaultPath: string): void {
+ 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",
+ "triggers: [release, changelog]",
+ "tags: [ops, docs]",
+ "---",
+ "# 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",
+ );
+
+ reconcileProceduralMemory(vaultPath, {
+ roots: [join(vaultPath, "Brain", "procedures"), join(vaultPath, "skills")],
+ });
+
+ writeFrontmatterAtomic(
+ skillProposalPendingPath(vaultPath, "release-routine"),
+ {
+ kind: "brain-skill-proposal",
+ id: "prop-release-routine",
+ slug: "release-routine",
+ status: "pending",
+ pattern_kind: "repeated_action",
+ },
+ "# Proposal",
+ {
+ overwrite: false,
+ existsErrorKind: "skill proposal",
+ vaultForRelativePath: vaultPath,
+ },
+ );
+
+ applyRecurrenceEvidence(vaultPath, {
+ contentHash: "h-attn",
+ scope: "project-a",
+ sourceId: "src-1",
+ action: "learn",
+ });
+ applyRecurrenceEvidence(vaultPath, {
+ contentHash: "h-attn",
+ scope: "project-b",
+ sourceId: "src-2",
+ action: "learn",
+ });
+ applyRecurrenceEvidence(vaultPath, {
+ contentHash: "h-attn",
+ scope: "project-c",
+ sourceId: "src-3",
+ action: "learn",
+ });
+}
diff --git a/tests/core/brain/procedural-graph.test.ts b/tests/core/brain/procedural-graph.test.ts
new file mode 100644
index 00000000..99d5d6e1
--- /dev/null
+++ b/tests/core/brain/procedural-graph.test.ts
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import {
+ rebuildProceduralGraph,
+ readProceduralGraph,
+} from "../../../src/core/brain/procedural-graph.ts";
+import { proceduralGraphPath, skillProposalAcceptedPath } from "../../../src/core/brain/paths.ts";
+import { reconcileProceduralMemory } from "../../../src/core/brain/procedural-memory.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = join(
+ tmpdir(),
+ `o2b-procedural-graph-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ );
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("procedural graph projection", () => {
+ test("rebuilds graph with entry nodes, proposal nodes, and entity links", () => {
+ seedProceduralSources(vault);
+ reconcileProceduralMemory(vault, {
+ roots: [join(vault, "Brain", "procedures"), join(vault, "skills")],
+ });
+
+ const projection = rebuildProceduralGraph(vault, {
+ now: new Date("2026-06-02T10:00:00Z"),
+ });
+ expect(projection.schema_version).toBe(1);
+ expect(projection.nodes.length).toBeGreaterThanOrEqual(3);
+ expect(projection.edges.length).toBeGreaterThan(0);
+
+ const proposalNode = projection.nodes.find((node) => node.kind === "proposal");
+ expect(proposalNode).toBeDefined();
+
+ const entityNode = projection.nodes.find((node) => node.kind === "entity");
+ expect(entityNode).toBeDefined();
+
+ const restored = readProceduralGraph(vault);
+ expect(restored).not.toBeNull();
+ expect(restored?.generated_at).toBe("2026-06-02T10:00:00.000Z");
+ });
+
+ test("returns null when projection file does not exist", () => {
+ expect(readProceduralGraph(vault)).toBeNull();
+ expect(proceduralGraphPath(vault).endsWith("Brain/procedural-memory/graph.json")).toBe(true);
+ });
+});
+
+function seedProceduralSources(vaultPath: string): void {
+ 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",
+ "source_proposal: prop-release-notes",
+ "triggers: [release, changelog]",
+ "tags: [ops, docs]",
+ "---",
+ "# 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",
+ );
+
+ writeFileSync(
+ ensureParent(skillProposalAcceptedPath(vaultPath, "release-notes")),
+ [
+ "---",
+ "kind: brain-skill-proposal",
+ "id: prop-release-notes",
+ "slug: release-notes",
+ "status: accepted",
+ "pattern_kind: repeated_action",
+ "---",
+ "# Proposal release-notes",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+}
+
+function ensureParent(path: string): string {
+ mkdirSync(dirname(path), { recursive: true });
+ return path;
+}
diff --git a/tests/core/brain/procedural-hints.test.ts b/tests/core/brain/procedural-hints.test.ts
new file mode 100644
index 00000000..12f61b07
--- /dev/null
+++ b/tests/core/brain/procedural-hints.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ readProceduralHints,
+ rebuildProceduralHints,
+} from "../../../src/core/brain/procedural-hints.ts";
+import { rebuildProceduralGraph } from "../../../src/core/brain/procedural-graph.ts";
+import { reconcileProceduralMemory } from "../../../src/core/brain/procedural-memory.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = join(
+ tmpdir(),
+ `o2b-procedural-hints-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ );
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("procedural hints projection", () => {
+ test("builds deterministic hint cues from graph nodes", () => {
+ seedSources(vault);
+ reconcileProceduralMemory(vault, {
+ roots: [join(vault, "Brain", "procedures"), join(vault, "skills")],
+ });
+ const graph = rebuildProceduralGraph(vault, {
+ now: new Date("2026-06-02T12:00:00Z"),
+ });
+
+ const hints = rebuildProceduralHints(vault, {
+ graph,
+ now: new Date("2026-06-02T12:01:00Z"),
+ });
+
+ expect(hints.schema_version).toBe(1);
+ expect(hints.generated_at).toBe("2026-06-02T12:01:00.000Z");
+ expect(hints.entries.length).toBeGreaterThan(0);
+
+ const first = hints.entries[0]!;
+ expect(first.cues.length).toBeGreaterThan(0);
+ });
+
+ test("returns null when no projection exists", () => {
+ expect(readProceduralHints(vault)).toBeNull();
+ });
+});
+
+function seedSources(vaultPath: string): void {
+ 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",
+ "triggers: [release, changelog]",
+ "tags: [ops, docs]",
+ "---",
+ "# 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",
+ );
+}
diff --git a/tests/core/brain/skill-proposals.test.ts b/tests/core/brain/skill-proposals.test.ts
index 8de09372..a30bd83e 100644
--- a/tests/core/brain/skill-proposals.test.ts
+++ b/tests/core/brain/skill-proposals.test.ts
@@ -123,9 +123,7 @@ describe("skill proposal learning", () => {
});
const pending = listPendingSkillProposals(vault);
- const target = pending.find(
- (item) => item.patternKind === "repeated_action",
- );
+ const target = pending.find((item) => item.patternKind === "repeated_action");
expect(target).toBeDefined();
const accepted = acceptSkillProposal(vault, target!.slug, {
@@ -134,15 +132,9 @@ describe("skill proposal learning", () => {
});
expect(accepted.status).toBe("accepted");
- expect(existsSync(skillProposalAcceptedPath(vault, target!.slug))).toBe(
- true,
- );
+ 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);
+ expect(listPendingSkillProposals(vault).some((item) => item.slug === target!.slug)).toBe(false);
});
test("reject moves proposal and prevents unchanged reappearance", () => {
@@ -162,14 +154,8 @@ describe("skill proposal learning", () => {
});
expect(rejected.status).toBe("rejected");
- expect(existsSync(skillProposalRejectedPath(vault, target!.slug))).toBe(
- true,
- );
- expect(
- listPendingSkillProposals(vault).some(
- (item) => item.slug === target!.slug,
- ),
- ).toBe(false);
+ 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"),
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index ccdb9dcb..ea62b415 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -231,7 +231,9 @@ describe("tool listing", () => {
// Procedural-learning surfaces (v0.30.0).
"brain_skill_proposals",
"brain_procedural_memory",
+ "brain_procedural_graph",
"brain_recurrence",
+ "brain_attention_flows",
// Pay Memory (unchanged).
"payment_memory_init",
"payment_receipt_append",
@@ -496,7 +498,9 @@ describe("stdio loop", () => {
// + brain_recall_gate (v0.27.0) = 58.
// + 7 context continuity/session recall tools (v0.29.0) = 65.
// + 3 procedural-learning tools (v0.30.0) = 68.
- expect(list.result.tools.length).toBe(68);
+ // + brain_procedural_graph (v0.31.0) = 69.
+ // + brain_attention_flows (v0.31.0) = 70.
+ expect(list.result.tools.length).toBe(70);
});
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
index 847ed95c..112921eb 100644
--- a/tests/mcp/procedural-learning-tools.test.ts
+++ b/tests/mcp/procedural-learning-tools.test.ts
@@ -4,7 +4,11 @@ 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 {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
let vault: string;
@@ -70,16 +74,22 @@ describe("procedural learning tool registration", () => {
for (const name of [
"brain_skill_proposals",
"brain_procedural_memory",
+ "brain_procedural_graph",
"brain_recurrence",
+ "brain_attention_flows",
] as const) {
- expect(buildToolTable("full").find((tool) => tool.name === name)).toBeDefined();
- expect(buildToolTable("writer").find((tool) => tool.name === name)).toBeUndefined();
+ 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 () => {
+ test("skill proposals, procedural memory, procedural graph, and recurrence work end-to-end", async () => {
const server = new MCPServer({ vault });
await initialize(server);
@@ -121,6 +131,46 @@ describe("procedural learning MCP tools", () => {
});
expect(marked.usedCount).toBeGreaterThanOrEqual(1);
+ const graphRebuild = await callTool(server, "brain_procedural_graph", {
+ operation: "rebuild",
+ });
+ expect(graphRebuild.operation).toBe("rebuild");
+ expect(
+ (graphRebuild.graph as Record<string, unknown>).nodes as number,
+ ).toBeGreaterThan(0);
+
+ const graphShow = await callTool(server, "brain_procedural_graph", {
+ operation: "show",
+ });
+ expect((graphShow.nodes as unknown[]).length).toBeGreaterThan(0);
+
+ const graphHints = await callTool(server, "brain_procedural_graph", {
+ operation: "hints",
+ });
+ expect((graphHints.entries as unknown[]).length).toBeGreaterThan(0);
+
+ const flowsList = await callTool(server, "brain_attention_flows", {
+ operation: "list",
+ });
+ expect(flowsList.total).toBeGreaterThan(0);
+ const flowId = (flowsList.flows as Array<Record<string, unknown>>)[0]![
+ "id"
+ ] as string;
+
+ const flowsEval = await callTool(server, "brain_attention_flows", {
+ operation: "evaluate",
+ flow_id: flowId,
+ });
+ expect((flowsEval.sections as unknown[]).length).toBeGreaterThan(0);
+
+ const flowsRender = await callTool(server, "brain_attention_flows", {
+ operation: "render",
+ flow_id: flowId,
+ });
+ expect(flowsRender.flow_id).toBe(flowId);
+ expect(typeof flowsRender.text).toBe("string");
+ expect((flowsRender.text as string).length).toBeGreaterThan(0);
+
const recLearn = await callTool(server, "brain_recurrence", {
operation: "learn",
content_hash: "h-mcp",