Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG/v4.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **Keyword-triggered belief categories ([#1126](https://github.com/robotrocketscience/aelfrice/issues/1126)).** Group beliefs into named categories (repo-rules, git-workflow, prose-and-docs, …) and bind each to an activation trigger; when a category fires — it is always-on, or one of its keyword phrases appears in the prompt — the `UserPromptSubmit` hook **reranks the retrieval output** so that category's rules lead the `<aelfrice-memory>` block, prepends a one-line `<category-focus>` label, and surfaces a bounded set of members retrieval missed. The conditional, right-rule-at-the-right-moment complement to a static `CLAUDE.md`/`AGENTS.md`. It **reranks rather than injecting a second block**: R&D on the feature showed a separate block double-injects what retrieval (L0 + BM25) already returns and that category members are almost always already in the retrieval tail, so the value is prioritising + labelling the one block, not adding content. **Advisory, not enforcement** — it never blocks a tool call (per the #199 enforcement history and the fail-open hook contract); a hard-block lane is an explicit non-goal. Two additive tables (`categories` with a `trigger_json` config blob + a `belief_categories` M2M join modeled on `belief_documents`) — no `Belief` column, and additive DDL that passes the destructive-only migration-policy gate. New pure `aelfrice.category` module: deterministic keyword (case-insensitive, word-boundary, whitespace-tolerant) and cross-platform `fnmatch` glob matchers, stable trigger (de)serialization, and the default-off `is_enabled` gate (env `AELFRICE_BELIEF_CATEGORIES` > `[belief_categories] enabled` > `false`) — no embeddings, no model call, no clock (#605-clean). New `aelf category` verb (`init`/`add`/`list`/`show`/`set-trigger`/`assign`/`unassign`/`delete`) and `/aelf:category` slash command; assign at lock time with `aelf lock "<rule>" --category <name>`. `aelf category init` seeds a 5-category starter set. Membership is user-driven — no auto-classification. The tool/file trigger lanes are stored + matched but their `PreToolUse` wiring is a follow-up. Fail-soft throughout: any error leaves the retrieval hits unchanged and the hook returns exit 0.

### Changed

### Fixed
Expand Down
73 changes: 73 additions & 0 deletions docs/design/belief_categories.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Belief categories — keyword-triggered rule grouping (#1126)

Umbrella: [#1126](https://github.com/robotrocketscience/aelfrice/issues/1126). Status: v1 shipped (soft `UserPromptSubmit` injection lane).

## Problem

Rule-shaped beliefs (repo conventions, git-push rules, prose-style rules) are enforced today only by (a) being *locked*, which injects them unconditionally on every turn, or (b) living in a static `CLAUDE.md` / `AGENTS.md`. Neither injects **the right rules at the right moment**. A user wants to group beliefs into categories and have a category's rules surface *when they are relevant* — e.g. the git-workflow rules when the prompt says "commit and push".

## Prior-art constraint

The enforcement triad ([#199](https://github.com/robotrocketscience/aelfrice/issues/199), `v2_enforcement.md`) already litigated hook-level enforcement:

- **H1** (infer rule-shaped directives from prose) — deferred, bench-gated. `directive_detector.py` exists but is unwired.
- **H2** (a hook that runs a predicate to enforce) — dropped on shell-injection grounds (predicate text derives from belief content).
- **H3** (score locked rules vs the prompt) — superseded by [#379](https://github.com/robotrocketscience/aelfrice/issues/379): locks are the always-injected pool (L0).

Every aelfrice hook is fail-open / exit-0 and none emit `deny`/`ask`. This feature is therefore **advisory injection, not enforcement**. A hard-block lane is explicitly out of v1 scope.

## v1 design

### Categories (starter set)

`aelf category init` seeds five: `repo-rules` (always-on / locked), `git-workflow` (keyword / locked), `secrets-and-safety` (tool-match + always-on / locked), `prose-and-docs` (keyword / advisory), `testing` (file-glob or keyword / mixed). Design invariant used as a review check: always-on categories are almost entirely locked; keyword/tool categories hold the mix.

### Data model (two additive tables)

Additive `CREATE TABLE IF NOT EXISTS` in `store._SCHEMA` — invisible to the destructive-only `migration-policy-check` gate, present on every fresh store.

```sql
categories(name PK, always_on INT, trigger_json TEXT, default_lock TEXT, created_at TEXT)
belief_categories(belief_id → beliefs.id, category_name → categories.name,
created_at, PK(belief_id, category_name)) -- FK CASCADE both sides
```

`trigger_json` is one read-once JSON blob per category — `{keywords, tool_globs, file_globs}` — the same pattern as `onboard_sessions.candidates_json`. Membership is a many-to-many join modeled on `belief_documents` (#435); a belief may belong to several categories. There is **no** `category` column on `Belief` — the dataclass is untouched.

### Matching (`aelfrice.category`)

Pure, deterministic, stdlib-only (#605): keyword phrases compile to a case-insensitive, word-boundary alternation (internal whitespace relaxed to `\s+`); tool/file globs use `fnmatch`. `match_prompt(prompt, categories)` returns the categories that are `always_on` or keyword-matched, de-duplicated by name, in name-ASC order. No embeddings, no model call, no clock.

### Rerank-on-trigger lane (`hook._apply_category_boost`)

On `UserPromptSubmit`, when `category.is_enabled(toml)` (default-off; env `AELFRICE_BELIEF_CATEGORIES` > `[belief_categories] enabled` > `false`), a fired category does **not** emit a separate block. Instead it **reranks the single retrieval output**: its member beliefs are lifted to the top of the `<aelfrice-memory>` hits, a bounded set (`CATEGORY_BOOST_MAX_EXTRA`) of members retrieval missed is pulled in, and a one-line `<category-focus>` note is prepended naming the fired categories. Deterministic: categories name-ASC (`match_prompt`), members in stable store order, de-duplicated by belief id; the un-promoted remainder keeps retrieval order. Fail-soft: on disable / no-fire / error the hits pass through unchanged.

This design is the direct result of the R&D below — a separate injected block double-injected whatever retrieval already returns, so reranking the one block is the correct mechanism.

Only the **prompt keyword** lane (plus `always_on`) is wired in v1. `tool_globs` / `file_globs` are parsed, stored, and matched (`command_hit` / `paths_hit`, unit-tested) but the `PreToolUse` wiring that consumes them is a follow-up.

### R&D that shaped the design

The first cut emitted a separate `<belief-category-rules>` block ahead of the retrieval body. Empirical rounds against the real hook / a copy of a 45k-belief store refuted that approach:

- **R1 — double-injection (confirmed).** A locked rule in a fired keyword category appeared **twice**: once in the category block, once in the L0 `<aelfrice-memory>` block. All seed categories default `locked`, so every fired seed category duplicated content L0 already injects.
- **R2 — the block is redundant (confirmed).** Across every configuration tested — fresh/aged belief, tiny/45k store, token budget 200→2400 — a category member was **already present in the retrieval output**. No realistic case surfaced net-new content. (A methodological note: small synthetic stores over-retrieve, and a freshly-inserted belief ranks #0 for *any* query — both masked the effect until corrected for.) So the block's value is prioritising + labelling the one retrieval block, not adding a second.
- **R3 — keyword recall (quantified).** Literal-phrase matching missed ~39% of natural phrasings ("ship it", "get this merged", "land this change"). Expanding the `git-workflow` seed keyword set cut this to ~17%; the residual is the inherent floor of deterministic literal matching (chosen over fuzzy matching for determinism, #605).

The rerank-on-trigger design resolves R1 and R2 (one injection, no duplicate) and delivers the original "right rule at the right moment" intent by *ordering + labelling* rather than *adding*.

### CLI

`aelf category init|add|list|show|set-trigger|assign|unassign|delete` (visible verb, nested actions) and `aelf lock "<rule>" --category <name>`. Membership is user-driven — **no auto-classification** in v1.

## Non-goals (v1)

- **No hard `deny`/block lane.** A false-positive block wedges a real tool call; the codebase has never emitted deny. A strict-mode block is a separate future issue, default-off, with a false-positive escape hatch, and even then fail-**open** on hook error.
- **No auto-classification** of beliefs into categories.
- **No inference of rule-shaped directives from prose** (the bench-gated H1 path). Triggers are user-declared, not inferred.

## Follow-ups

- `PreToolUse:Bash` consumption of `tool_globs` (inject-on-command-match, still exit-0, no deny).
- File-glob lane wired to touched paths.
- Optional strict "block" mode behind its own default-off flag + escape hatch.
1 change: 1 addition & 0 deletions docs/user/COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ DB resolves from `$AELFRICE_DB`, then `<git-common-dir>/aelfrice/memory.db` when
| `stale [--older-than N] [--cold-for N] [--locked-only] [--limit N] [--json]` | (v3.5+, [#933](https://github.com/robotrocketscience/aelfrice/issues/933)) List beliefs with `created_at` older than N days (default 30) AND `last_retrieved_at` NULL or older than M days (default 14). No decay model — plain windows. `--limit` default 20. |
| `feed [--since DUR] [--limit N] [--json]` | (v3.5+, [#931](https://github.com/robotrocketscience/aelfrice/issues/931)) Read the belief-write event log at `<git-common-dir>/aelfrice/feed.jsonl` (lock / onboard / wonder-promote / feedback rows). `--since` takes durations like `5m` / `2h` / `1d`; `--limit 0` (default) shows all. |
| `speculative [--origin TAG] [--limit N] [--json]` | (v3.5+, [#937](https://github.com/robotrocketscience/aelfrice/issues/937)) List non-user-locked active beliefs sorted by α descending — the agent-inferred / ingested / wonder-generated layer. `--limit` default 20. |
| `category <action>` | (v4.x+, [#1126](https://github.com/robotrocketscience/aelfrice/issues/1126)) Manage keyword-triggered belief categories — named groups of beliefs bound to an activation trigger. Actions: `init` (seed the 5 starter categories idempotently), `add <name> [--always-on] [--keyword PHRASE]… [--tool-glob G]… [--file-glob G]… [--lock none\|locked\|advisory]`, `list`, `show <name>`, `set-trigger <name> [--keyword …]…`, `assign <belief_id> <name>`, `unassign <belief_id> <name>`, `delete <name>`. The `UserPromptSubmit` injection lane that surfaces a fired category's members is **default-off** (`AELFRICE_BELIEF_CATEGORIES=1` or `[belief_categories] enabled=true`) and advisory (never blocks a tool call). Assign at lock time with `lock "<rule>" --category <name>`. Membership is user-driven — no auto-classification. |
| `audit-claude-memory [--project PATH] [--json]` | (v3.5+, [#935](https://github.com/robotrocketscience/aelfrice/issues/935)) Read-only cross-store dedup audit between locked aelfrice beliefs and the host's auto-memory `MEMORY.md`. Reports potential duplicates, contradictions, and store-exclusive entries. |
| `reconcile-claude-memory [--project PATH] [--force]` | (v4.0+, [#1089](https://github.com/robotrocketscience/aelfrice/issues/1089)) Ingest the project's claude-memory fact files (`<memory-dir>/*.md`, excluding `MEMORY.md`) into the belief graph — the full-set sweep that complements the `PostToolUse` write-through mirror (#985). Normally runs once per project at `aelf setup` behind a sentinel; this is the manual re-run. Idempotent — content-derived ids mean a re-run corroborates, not duplicates. `--project` defaults to the current directory; `--force` re-runs past the per-project sentinel. One-way and non-authoritative — aelfrice never writes back to the memory files. |
| `export-obsidian <vault> [--scope all\|recent\|query] [--query TEXT] [--neighborhood-hops N] [--k N] [--max-notes N] [--force]` | (v3.0+) One-way DB→vault export: one Markdown note per belief under `<vault>/aelfrice/`, typed edges in YAML front-matter (Dataview-queryable) plus body wikilinks. Default cap 500 notes, hard ceiling 5000 without `--force`. |
Expand Down
26 changes: 26 additions & 0 deletions docs/user/CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ A single optional TOML file at the root of a project (or any ancestor). It expos
- `[onboard.llm]` (v1.3.0+) — direct-API onboard classifier gate; documented under [Keys § `[onboard.llm]`](#onboardllm-v130) below.
- `[cadence]`, `[implicit_feedback]`, and `[hook_audit]` — feedback-cadence scoring, deferred retrieval-exposure feedback, and the per-turn hook audit log. Recognised here but documented in their module docstrings (`src/aelfrice/cadence.py`, `src/aelfrice/deferred_feedback.py`, `src/aelfrice/hook.py`).
- `[feedback]` (v3.0+) — feedback-lane opt-ins. `sentiment_from_prose` (default `false`) wires the sentiment-feedback detector into `UserPromptSubmit` (#606).
- `[belief_categories]` (v4.x+) — keyword-triggered belief categories. `enabled` (default `false`) wires the category-injection lane into `UserPromptSubmit` (#1126). Manage categories with `aelf category`.
- `[user_prompt_submit_hook]` (v3.0+) — UPS hook knobs. `prompt_shape_gate_enabled` (default `true`) gates trivial-prompt and system-envelope short-circuits before BM25 retrieval runs (#674). `conversation_aware_query_enabled` (default `true`, v3.x #909) folds a small window of recent dialog turns into the BM25 query so paraphrase / pronoun / numeric-reference follow-ups still surface the load-bearing thread; tuned by `conversation_aware_turn_window` (default `4`) and `conversation_aware_prompt_weight` (default `3`).

Locks and the MCP tool surface are not affected. Hook behavior IS configurable here (`[user_prompt_submit_hook]`, `[feedback]`, `[cadence]`, `[hook_audit]`); the Bayesian update math itself is not.
Expand Down Expand Up @@ -220,6 +221,19 @@ l1 = 0.40
# docs/design/v3_sentiment_feedback_hook.md.
sentiment_from_prose = false

[belief_categories]
# v4.x+ (#1126). Default `false`, opt-in. When true, the
# UserPromptSubmit hook reranks the retrieval output so a fired
# category's rules lead the block (with a <category-focus> label), for
# every category that is always-on or has a keyword phrase in the
# prompt. Reranks rather than injecting a second block (a separate block
# double-injects what retrieval already returns — see the #1126 R&D).
# Advisory only — it never blocks a tool call. Deterministic (case-
# insensitive word-boundary literal-phrase matching, no embeddings),
# fail-soft. AELFRICE_BELIEF_CATEGORIES=1 env var overrides. Manage
# categories with `aelf category`. See docs/design/belief_categories.md.
enabled = false

[user_prompt_submit_hook]
# v3.0+ (#674). Default `true`. Short-circuits BM25 retrieval on two
# prompt shapes: system-envelope echoes (prompts that start with a
Expand Down Expand Up @@ -606,6 +620,18 @@ Boolean, default `false`. When `false` (default) the note is a passive surface

The trigger is skipped on prompt-shape-gated turns (#674) and is fully fail-soft: any error yields no note and never breaks the hook. Full spec: [phantom_trigger_generation.md](../design/phantom_trigger_generation.md).

## `[belief_categories]` (v4.x+)

Opt-in keyword-triggered belief categories (#1126). A *category* groups beliefs (repo-rules, git-workflow, prose-and-docs, …) and binds them to an activation trigger. When the lane is enabled and a category fires — it is always-on, or one of its keyword phrases appears in the prompt — the `UserPromptSubmit` hook **reranks the retrieval output** so that category's member rules lead the `<aelfrice-memory>` block, prepends a one-line `<category-focus>` note naming the fired categories, and surfaces a bounded set of members retrieval missed. This is the conditional, right-rule-at-the-right-moment complement to a static `CLAUDE.md` / `AGENTS.md`.

The lane **reranks rather than injecting a second block** — the #1126 R&D found a separate block double-injects what retrieval (L0 + BM25) already returns, and that category members are almost always already in the retrieval tail. So the value is prioritising + labelling the one block, not adding content. It is **advisory, not enforcement**: it never blocks a tool call. Per the enforcement history (#199) and the #605 determinism boundary, matching is pure-stdlib (case-insensitive, word-boundary, literal-phrase; no embeddings, no model call) and the hook is fail-soft (any error leaves the hits unchanged and returns exit 0). Because the lane reorders the existing hits, a locked member is still injected exactly once (with its L0 ground-truth framing) — just lifted to the top.

### `enabled`

Boolean, default `false`. Master opt-in. Precedence (first decisive wins): env var `AELFRICE_BELIEF_CATEGORIES=1`/`0` (truthy/falsy normalised) > TOML `[belief_categories] enabled` > default `false`. A fresh install is unaffected until enabled.

Manage categories and membership with the `aelf category` CLI (`init`/`add`/`list`/`show`/`set-trigger`/`assign`/`unassign`/`delete`) or `aelf lock "<rule>" --category <name>`. `aelf category init` seeds a 5-category starter set (repo-rules, git-workflow, secrets-and-safety, prose-and-docs, testing). Category assignment is user-driven — there is no auto-classification. Full spec: [belief_categories.md](../design/belief_categories.md).

## `[memory]` (v3.7.0+)

Controls the claude-memory mirror (#985) — a one-way `PostToolUse:Write|Edit|MultiEdit` hook that ingests host claude-memory fact-file writes into the belief graph so the two stores do not drift. The hook is installed default-on by `aelf setup` but **inert until the flag below is set**; when off it returns after three cheap checks (tool name, path shape, flag) and never imports the store. aelfrice is never authoritative over the memory files; the mirror never locks (L0 stays reserved for explicit `aelf lock`).
Expand Down
Loading
Loading