From 92c9f2cb8b4c89a74fe534ac2b8ae456a7fe3a11 Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:45:16 -0500 Subject: [PATCH 01/12] feat(learn): add cross-project learned tail and GAP promotion Write durable notes into harness policy and list only exact cross-project matches for promotion, keeping similar embeddings from manufacturing evidence. --- agent-skills/AGENTS.md | 2 +- agent-skills/do-recall-promote/SKILL.md | 67 ++ bun.lock | 9 + docs/agent-skills.md | 11 + docs/cli-reference.md | 18 +- docs/hosts/FOR_CLAUDE.md | 1 + hooks/RecallExtract.ts | 50 + hooks/lib/learned-tail.ts | 1049 +++++++++++++++++ .../skills/do-recall-promote/SKILL.md | 67 ++ .../recall/skills/do-recall-promote/SKILL.md | 75 ++ lib/install-lib.sh | 2 +- package.json | 1 + packaging/uninstall.sh | 134 +++ scripts/build-codex-plugin.ts | 1 + scripts/e2e-claude-plugin.ts | 6 +- scripts/e2e-pi-integration.ts | 1 + src/commands/doctor.ts | 48 + src/commands/learn.ts | 141 +++ src/commands/promote.ts | 149 +++ src/index.ts | 25 +- src/lib/learned-tail.ts | 46 + tests/hooks/learned-tail-stop.test.ts | 114 ++ tests/install/npm-pack.test.ts | 10 +- tests/install/uninstall.test.ts | 39 + tests/learned-tail-embedding.test.ts | 96 ++ tests/learned-tail.test.ts | 499 ++++++++ tests/plugins/claude-plugin.test.ts | 2 +- tests/plugins/codex-plugin.test.ts | 2 +- todo.txt | 14 +- tsconfig.json | 2 +- 30 files changed, 2665 insertions(+), 16 deletions(-) create mode 100644 agent-skills/do-recall-promote/SKILL.md create mode 100644 hooks/lib/learned-tail.ts create mode 100644 hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md create mode 100644 hosts/plugins/recall/skills/do-recall-promote/SKILL.md create mode 100644 src/commands/learn.ts create mode 100644 src/commands/promote.ts create mode 100644 src/lib/learned-tail.ts create mode 100644 tests/hooks/learned-tail-stop.test.ts create mode 100644 tests/learned-tail-embedding.test.ts create mode 100644 tests/learned-tail.test.ts diff --git a/agent-skills/AGENTS.md b/agent-skills/AGENTS.md index f8061732..f4f15f2f 100644 --- a/agent-skills/AGENTS.md +++ b/agent-skills/AGENTS.md @@ -8,7 +8,7 @@ Agent Skill definitions (one `SKILL.md` per skill directory, per the [agentskill ## Ownership -`do-recall-add`, `do-recall-doctor`, `do-recall-dump`, `do-recall-loa`, `do-recall-recent`, `do-recall-scout`, `do-recall-search`, `do-recall-stats`, `do-recall-update` — each a directory containing `SKILL.md`. +`do-recall-add`, `do-recall-doctor`, `do-recall-dump`, `do-recall-loa`, `do-recall-promote`, `do-recall-recent`, `do-recall-scout`, `do-recall-search`, `do-recall-stats`, `do-recall-update` — each a directory containing `SKILL.md`. ## Local Contracts diff --git a/agent-skills/do-recall-promote/SKILL.md b/agent-skills/do-recall-promote/SKILL.md new file mode 100644 index 00000000..3bfd7b0d --- /dev/null +++ b/agent-skills/do-recall-promote/SKILL.md @@ -0,0 +1,67 @@ +--- +name: "do-recall-promote" +description: "Promote learned-tail notes that hold across projects into GAP by opening a pull request. Never writes main and never runs gap sync." +--- + +Turn Recall notes that hold across projects into a reviewed change to the shared GAP policy. This skill only opens a pull request. The user reviews and merges it, then runs `gap sync` themselves. + +## What this does + +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. +3. Opens a pull request and stops. + +## Never + +- Never commit to `main` or `master`, and never push to either. +- Never edit a published harness file (`~/.claude/CLAUDE.md` and the rest). `gap sync` is what publishes, and only the user runs it. +- Never run `gap sync`, `gap remove`, or any command that writes a harness file. +- Never promote a note the user did not accept, and never invent text the JSON did not return. + +## Steps + +1. **List the candidates.** + + ```bash + recall promote --json + ``` + + The JSON has `gap`, `candidates`, and `skipped`. Each candidate carries `text`, `records` (`table` and `id`), `projects`, `firstSeen`, `lastSeen`, and `daysInTail`. + + Stop and tell the user when `gap` is false (GAP is not installed), when `candidates` is empty, or when the command exits non-zero. There is nothing to promote. + +2. **Ask which notes to promote.** Show each candidate's text, projects, record ids, and first/last seen dates. Promote only the ones the user accepts. If they accept none, stop. + +3. **Find the GAP checkout.** Ask `gap` where it publishes from. Do not search the filesystem for another clone and do not clone the repo. + + ```bash + GAP_SRC="$(gap source)" && test -f "$GAP_SRC/global/AGENTS.md" + ``` + + If `gap source` fails or is unknown (a `gap` older than this command), stop and tell the user to update gap. + +4. **Branch off the published branch in a worktree.** The checkout may be on another branch or hold uncommitted work, so never switch it, stash, reset, or clean it. + + ```bash + BRANCH="recall-promote-$(date +%Y-%m-%d)" + git -C "$GAP_SRC" fetch origin + git -C "$GAP_SRC" worktree add "$GAP_SRC/.worktrees/$BRANCH" -b "$BRANCH" origin/HEAD + WT="$GAP_SRC/.worktrees/$BRANCH" + ``` + + `origin/HEAD` is the branch `gap sync` publishes. If the branch or worktree already exists, stop and ask. + +5. **Edit `$WT/global/AGENTS.md` only.** Add each accepted note as its own short bullet under the existing `## Work` list, in the user's words from `text`. Do not add a new section, do not touch `global/docs/agents/`, and do not edit any other file. Keep the file's style: no em dashes. + +6. **Commit on the branch and open the pull request.** + + ```bash + git -C "$WT" add global/AGENTS.md + git -C "$WT" commit -m "docs(policy): promote recall notes" + git -C "$WT" push -u origin "$BRANCH" + (cd "$WT" && gh pr create --title "Promote recall notes into the shared policy" --body "") + ``` + + The pull request body lists every promoted note with its record ids (`decisions#123`) and projects, and says the user merges it and then runs `gap sync`. + +7. **Stop.** Report the pull request URL and the worktree path (`$WT`), which the user removes with `git -C "$GAP_SRC" worktree remove "$WT"` after the merge. Do not merge it and do not run `gap sync`. After the user does both, the next `recall learn` sees the rule in the GAP block and drops it from the tail. diff --git a/bun.lock b/bun.lock index df4314ad..06be8156 100644 --- a/bun.lock +++ b/bun.lock @@ -11,6 +11,7 @@ "zod": "^3.24.0", }, "devDependencies": { + "@plannotator/sem-jiff": "^0.2.0", "@types/bun": "^1.3.14", "@types/node": "^22.10.0", "fast-check": "^4.8.0", @@ -85,6 +86,8 @@ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.25.3", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "jose": "^6.1.1", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.0" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-vsAMBMERybvYgKbg/l4L1rhS7VXV1c0CtyJg72vwxONVX0l4ZfKVAnZEWTQixJGTzKnELjQ59e4NbdFDALRiAQ=="], + "@plannotator/sem-jiff": ["@plannotator/sem-jiff@0.2.0", "", { "dependencies": { "@vscode/diff": "^0.0.2-133", "diff": "^8.0.4", "web-tree-sitter": "^0.27.1" }, "bin": { "sem-jiff-copy-wasm": "dist/copy-wasm-bin.js" } }, "sha512-nyYab7XU25LqQMTqJL29eYDvoa9092ivWsJRoSLAQJz9dniKuovXYPA5qbgAHjvaoHn2a/6NGu5Q24uEetdn/g=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.57.1", "", { "os": "android", "cpu": "arm" }, "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg=="], "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.57.1", "", { "os": "android", "cpu": "arm64" }, "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w=="], @@ -155,6 +158,8 @@ "@vitest/utils": ["@vitest/utils@2.1.9", "", { "dependencies": { "@vitest/pretty-format": "2.1.9", "loupe": "^3.1.2", "tinyrainbow": "^1.2.0" } }, "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ=="], + "@vscode/diff": ["@vscode/diff@0.0.2-145", "", {}, "sha512-atPcmNrAU4B8OsbrmqYlHbZREt//m8z52o400YA8uuvq3Be5wnmIhLoLqhMum7Jv7kRC0FE+m3WAUbaZF681wg=="], + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="], @@ -211,6 +216,8 @@ "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], @@ -465,6 +472,8 @@ "vitest": ["vitest@2.1.9", "", { "dependencies": { "@vitest/expect": "2.1.9", "@vitest/mocker": "2.1.9", "@vitest/pretty-format": "^2.1.9", "@vitest/runner": "2.1.9", "@vitest/snapshot": "2.1.9", "@vitest/spy": "2.1.9", "@vitest/utils": "2.1.9", "chai": "^5.1.2", "debug": "^4.3.7", "expect-type": "^1.1.0", "magic-string": "^0.30.12", "pathe": "^1.1.2", "std-env": "^3.8.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.1", "tinypool": "^1.0.1", "tinyrainbow": "^1.2.0", "vite": "^5.0.0", "vite-node": "2.1.9", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/node": "^18.0.0 || >=20.0.0", "@vitest/browser": "2.1.9", "@vitest/ui": "2.1.9", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q=="], + "web-tree-sitter": ["web-tree-sitter@0.27.2", "", {}, "sha512-ZRo86GKI4aOSBAqOrPmCtriExI3xIzu1sNw/V6v3b4QGxrEmO19FGwbMNdyhw3MJLAZIw0xAV0oSpqX361eAyQ=="], + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], diff --git a/docs/agent-skills.md b/docs/agent-skills.md index fa974372..5718524c 100644 --- a/docs/agent-skills.md +++ b/docs/agent-skills.md @@ -15,6 +15,7 @@ Flush the current session to the database and capture a Library of Alexandria en **Usage:** `/do-recall-dump Session Title Here` What it does: + 1. Imports the current session's messages into SQLite 2. Creates a Curated LoA entry via the fabric Extractor (or a basic summary with `--skip-fabric`) 3. Makes everything immediately searchable @@ -35,11 +36,20 @@ Searches messages, LoA entries, decisions, learnings, and breadcrumbs. The skill Rule of thumb: use `-t` when you want only one table; use `--bias-type` when you want one table first without hiding other context. +### do-recall-promote + +Promote learned-tail notes that hold across projects into the shared GAP policy, as a pull request. + +**Usage:** `/do-recall-promote` + +Runs `recall promote --json`, then edits `global/AGENTS.md` in the GAP checkout (`~/.gap/checkout`) on a new branch and opens a pull request. It never commits to `main` or `master`, never edits a published harness file, and never runs `gap sync`. The user reviews and merges the pull request, then runs `gap sync`. + ### do-recall-recent Show recent memory records. **Usage:** + - `/do-recall-recent` — all tables - `/do-recall-recent decisions` — specific table @@ -48,6 +58,7 @@ Show recent memory records. Memory-first orientation for an unfamiliar codebase. Searches Recall before touching git history or source, then produces a structured scout report in chat. **Usage:** + - `/do-recall-scout` — scout the whole repo - `/do-recall-scout auth` — narrow the scout to a subsystem, path, or question diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 10608412..e6612ea4 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -169,13 +169,17 @@ recall recent # Recent records across all tables recall recent decisions # Recent decisions only recall show decisions 5 # Full record for decision #5 recall stats # Database statistics +recall browse # Read-only terminal dashboard +recall browse -p myproject # Same dashboard, one project recall doctor # Health check all subsystems ``` -`recall recent` accepts any table name: `decisions`, `learnings`, `breadcrumbs`, `loa`, `sessions`, `docs`, `telos`. +`recall recent` accepts any table name: `messages`, `decisions`, `learnings`, `breadcrumbs`, `loa`, `sessions`, `docs`, `telos`. `recall show` displays the full record for a single row. The first argument is the table name, the second is the row ID. +`recall browse` is a read-only dashboard: `1`–`5` switch table, typing filters the current table, `enter` opens a row, `q` quits. It never writes. Piped or non-terminal output prints the decision list instead of taking over the screen. The web dashboard stays tracked in [#221](https://github.com/edheltzel/Recall/issues/221). + --- ## Import @@ -624,3 +628,15 @@ recall cluster --execute --threshold 0.9 ``` `--threshold` is 0.85 by default (0-1). + +### Learned tail + +`recall learn` writes Recall's best notes (active, high confidence, importance 8+ or user-authored, at most 15 bullets and 600 tokens) into a `` ... `` block in each global harness file. With GAP installed it writes to GAP's published policy files; otherwise to the built-in harness files that already exist. Only the Recall block changes, and a rerun with no change writes nothing. The Stop hook refreshes it on its own. + +`recall promote` is read-only. It lists notes seen in 3+ projects that have been in the written tail for 14+ days and are not already in the GAP block. The `do-recall-promote` skill turns the accepted ones into a GAP pull request. + +```bash +recall learn --dry-run +recall learn --json +recall promote --json +``` diff --git a/docs/hosts/FOR_CLAUDE.md b/docs/hosts/FOR_CLAUDE.md index f44ee8c1..ddb7570d 100644 --- a/docs/hosts/FOR_CLAUDE.md +++ b/docs/hosts/FOR_CLAUDE.md @@ -125,6 +125,7 @@ These skills are available in any Claude Code session (the former `/Recall:*` sl | `/do-recall-doctor` | Health check all subsystems | | `/do-recall-update` | Check-only: prints current vs. latest GitHub release + `cd && ./packaging/update.sh` recipe. Never rebuilds mid-session. | | `/do-recall-loa` | Browse Library of Alexandria entries | +| `/do-recall-promote` | Open a pull request promoting cross-project learned-tail notes into GAP `global/AGENTS.md`. Never writes main and never runs `gap sync`. | ## Codebase Scouting diff --git a/hooks/RecallExtract.ts b/hooks/RecallExtract.ts index 63844f15..1a878f26 100644 --- a/hooks/RecallExtract.ts +++ b/hooks/RecallExtract.ts @@ -48,6 +48,14 @@ import { getDbPath } from './lib/sqlite-writers'; import type { DualWriteResult } from './lib/extraction-parsers'; import { runExtractCore } from './lib/extract-core'; import { scrub } from './lib/write-safety'; +import { + countRecordsSince, + planLearnedTail, + readTailState, + recordTailRefresh, + tailStatePath, + writeLearnedTail, +} from './lib/learned-tail'; const EXTRACT_LOG = join(process.env.HOME!, '.claude', 'MEMORY', 'EXTRACT_LOG.txt'); @@ -544,6 +552,42 @@ function appendErrors(fabricOutput: string, sessionLabel: string, timestamp: str console.error(`[FabricExtract] Appended ${added} new error patterns (${lines.length - added} skipped as duplicates)`); } +// Stop-hook learned-tail refresh (#279). Refreshes on the first Stop, once 20 +// decision + learning rows landed since the last refresh (counted in the DB, so +// concurrent Stops never lose a count), or once the last refresh is 24h old. A +// refused write keeps the old refresh time so the next Stop retries. Runs on +// every Stop (parent, before any early exit) and again after a successful +// extraction lands new rows. Never runs from a session-start hook. Fail-soft: a refresh error is logged and never +// fails the extraction that already landed. +const TAIL_RECORD_INTERVAL = 20; +const TAIL_REFRESH_WINDOW_MS = 24 * 60 * 60 * 1000; + +function maybeRefreshLearnedTail(): void { + try { + const dbPath = getDbPath(); + if (!existsSync(dbPath)) return; + const statePath = tailStatePath(dbPath); + const state = readTailState(statePath); + const now = Date.now(); + const due = + state.refreshedAt === 0 || + now - state.refreshedAt >= TAIL_REFRESH_WINDOW_MS || + countRecordsSince(state.refreshedAt, dbPath) >= TAIL_RECORD_INTERVAL; + if (!due) return; + const plan = planLearnedTail({ dbPath }); + const writes = writeLearnedTail(plan); + const refused = writes.filter((w) => w.status === 'refused'); + if (refused.length > 0) { + logExtract(`LEARNED_TAIL: refused ${refused.map((w) => `${w.path} (${w.reason})`).join(', ')}; retrying next Stop`); + } + if (recordTailRefresh(statePath, plan, writes, new Date(now))) { + logExtract('LEARNED_TAIL: refreshed'); + } + } catch (error) { + logExtract(`LEARNED_TAIL: ${error}`); + } +} + /** Log the SQLite dual-write outcome (per-writer failures + per-table summary). */ function logDualWrite(result: DualWriteResult): void { if (Object.keys(result.failures).length > 0) { @@ -695,6 +739,7 @@ async function extractAndAppend(conversationPath: string, cwd: string): Promise< return; } markAsExtracted(convHash); + maybeRefreshLearnedTail(); logExtract(`SUCCESS: All memory files updated for session=${sessionLabel}`); @@ -837,6 +882,7 @@ async function extractAndAppendMarkdown(mdPath: string, cwd: string): Promise ... block into each global harness file. +// Self-contained: never imports from src/ (hooks/AGENTS.md). src/lib/learned-tail.ts re-exports it. +// Only the Recall pair is ever replaced; every other byte of a destination stays as it was. + +import { Database } from "bun:sqlite"; +import { createHash, randomBytes } from "node:crypto"; +import { + accessSync, + chmodSync, + closeSync, + constants, + existsSync, + fsyncSync, + lstatSync, + openSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + relative, +} from "node:path"; +import { resolveDbPath } from "./db-path"; +import { detectThreats } from "./threat-detect"; +import { scrub } from "./write-safety"; + +export const RECALL_BEGIN = ""; +export const RECALL_END = ""; +export const GAP_BEGIN = ""; +export const GAP_END = ""; +export const MAX_TAIL_TOKENS = 600; +export const MAX_TAIL_BULLETS = 15; +export const MAX_BULLET_CHARS = 200; +export const MIN_TAIL_IMPORTANCE = 8; +export const TAIL_HEADER_PREFIX = "Written by Recall, last updated "; +export const BUILTIN_TAIL_FILES = [ + ".claude/CLAUDE.md", + ".codex/AGENTS.md", + ".pi/agent/APPEND_SYSTEM.md", + ".omp/agent/APPEND_SYSTEM.md", + ".empryo/EMPRYO.md", +]; + +const HEADER_RE = /^Written by Recall, last updated (\d{4}-\d{2}-\d{2})\.$/; + +export type TailTable = "decisions" | "learnings"; + +export interface TailCandidate { + table: TailTable; + id: number; + text: string; + importance: number; + provenance: string | null; + confidence: string | null; + accessCount: number; + sessionId: string | null; + project: string | null; + createdAt: string; +} + +export interface TailRecordRef { + table: TailTable; + id: number; +} + +export interface TailNote { + key: string; + text: string; + importance: number; + sessions: number; + accessCount: number; + records: TailRecordRef[]; + projects: string[]; + firstSeen: string; + lastSeen: string; +} + +export type TailDropReason = + "secret" | "threat" | "unsafe" | "length" | "duplicate" | "covered" | "cap"; + +export interface DroppedTailNote { + key: string; + reason: TailDropReason; + detail?: string; +} + +export interface TailSelection { + notes: TailNote[]; + dropped: DroppedTailNote[]; + tokens: number; +} + +export type BulletCheck = + | { ok: true; text: string } + | { ok: false; reason: TailDropReason; detail?: string }; + +export interface TailEnv { + home?: string; + path?: string; +} + +export interface TailDestination { + path: string; + source: "gap" | "builtin"; +} + +export interface SkippedTailDestination { + path: string; + reason: string; +} + +export interface TailDestinationScan { + gap: boolean; + destinations: TailDestination[]; + skipped: SkippedTailDestination[]; +} + +export interface RecallBlockInfo { + present: boolean; + malformed: boolean; + updated: string | null; + bullets: string[]; + tokens: number; +} + +export type SpliceResult = + { ok: true; text: string; changed: boolean } | { ok: false; reason: string }; + +export interface TailDestinationPlan { + path: string; + source: "gap" | "builtin"; + before: string; + after: string; + beforeHash: string; + changed: boolean; + refused?: string; +} + +export interface TailPlan { + date: string; + gap: boolean; + selection: TailSelection; + block: string | null; + destinations: TailDestinationPlan[]; + skipped: SkippedTailDestination[]; +} + +export interface TailWriteResult { + path: string; + status: "written" | "unchanged" | "refused"; + reason?: string; +} + +export interface PlanTailOptions extends TailEnv { + dbPath?: string; + now?: Date; + candidates?: TailCandidate[]; +} + +interface TableSpec { + table: TailTable; + text: string; + columns: string[]; +} + +const TABLE_SPECS: TableSpec[] = [ + { table: "decisions", text: "t.decision", columns: ["decision"] }, + { + table: "learnings", + text: "COALESCE(NULLIF(TRIM(t.prevention), ''), NULLIF(TRIM(t.solution), ''))", + columns: ["prevention", "solution"], + }, +]; + +const REQUIRED_COLUMNS = [ + "id", + "importance", + "provenance", + "confidence", + "access_count", + "session_id", + "project", + "created_at", +]; + +export function estimateTailTokens(text: string): number { + return Math.ceil(text.length / 4); +} + +export function formatTailDate(now: Date): string { + const pad = (n: number) => String(n).padStart(2, "0"); + return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`; +} + +function sha256(bytes: Buffer | string): string { + return createHash("sha256").update(bytes).digest("hex"); +} + +export function loadTailCandidates( + dbPath: string = resolveDbPath(), +): TailCandidate[] { + if (!existsSync(dbPath)) + throw new Error(`Recall database not found: ${dbPath}`); + const db = new Database(dbPath, { readonly: true }); + try { + const tables = new Set( + ( + db + .query("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() as { name: string }[] + ).map((r) => r.name), + ); + const out: TailCandidate[] = []; + for (const spec of TABLE_SPECS) { + if (!tables.has(spec.table)) continue; + const cols = new Set( + ( + db.query(`PRAGMA table_info(${spec.table})`).all() as { + name: string; + }[] + ).map((r) => r.name), + ); + if (![...REQUIRED_COLUMNS, ...spec.columns].every((c) => cols.has(c))) + continue; + const where = [ + "t.confidence = 'high'", + `(t.importance >= ${MIN_TAIL_IMPORTANCE} OR t.provenance = 'user_authored')`, + ]; + if (cols.has("status")) where.push("t.status = 'active'"); + if (tables.has("dedup_lineage")) { + where.push( + `NOT EXISTS (SELECT 1 FROM dedup_lineage dl WHERE dl.duplicate_table = '${spec.table}' AND dl.duplicate_id = t.id AND dl.status = 'marked')`, + ); + } + const rows = db + .query( + `SELECT t.id AS id, ${spec.text} AS text, t.importance AS importance, t.provenance AS provenance, + t.confidence AS confidence, t.access_count AS access_count, t.session_id AS session_id, + t.project AS project, t.created_at AS created_at + FROM ${spec.table} t WHERE ${where.join(" AND ")} ORDER BY t.id`, + ) + .all() as Array<{ + id: number; + text: string | null; + importance: number | null; + provenance: string | null; + confidence: string | null; + access_count: number | null; + session_id: string | null; + project: string | null; + created_at: string | null; + }>; + for (const r of rows) { + if (typeof r.text !== "string" || !r.text.trim()) continue; + out.push({ + table: spec.table, + id: r.id, + text: r.text, + importance: r.importance ?? 0, + provenance: r.provenance, + confidence: r.confidence, + accessCount: r.access_count ?? 0, + sessionId: r.session_id, + project: r.project, + createdAt: r.created_at ?? "", + }); + } + } + return out; + } finally { + db.close(); + } +} + +export function sanitizeTailBullet(raw: string): BulletCheck { + const scrubbed = scrub(raw); + if (scrubbed.redactions.length > 0) + return { + ok: false, + reason: "secret", + detail: scrubbed.redactions.join(", "), + }; + if (scrubbed.text !== raw) + return { ok: false, reason: "unsafe", detail: "invisible unicode" }; + const threats = detectThreats(raw); + if (threats.length > 0) { + return { + ok: false, + reason: "threat", + detail: [...new Set(threats.map((t) => t.category))].join(", "), + }; + } + if (//.test(raw)) + return { ok: false, reason: "unsafe", detail: "comment marker" }; + if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(raw)) { + return { ok: false, reason: "unsafe", detail: "control character" }; + } + let text = raw + .replace(/\s+/g, " ") + .trim() + .replace(/^(?:[#>]+\s*|[-*+]\s+)+/, "") + .trim(); + if (!text) return { ok: false, reason: "unsafe", detail: "empty" }; + if (text.length > MAX_BULLET_CHARS) { + const first = text.split(/(?<=[.!?])\s+/)[0] ?? ""; + if (first.length === 0 || first.length > MAX_BULLET_CHARS) { + return { ok: false, reason: "length", detail: `${text.length} chars` }; + } + text = first; + } + return { ok: true, text }; +} + +function matchForm(text: string): string { + return text + .normalize("NFKC") + .toLowerCase() + .trim() + .replace(/^(?:[-*+]|\d+[.)])\s+/, "") + .replace(/[.!?;:,]+$/, "") + .replace(/\s+/g, " ") + .trim(); +} + +export function isCoveredByGap(note: string, gapText: string): boolean { + const n = matchForm(note); + if (!n) return false; + return gapText + .split(/\r?\n+/) + .flatMap((line) => [line, ...line.split(/(?<=[.!?])\s+/)]) + .some((unit) => matchForm(unit) === n); +} + +function candidateKey(c: { table: TailTable; id: number }): string { + return `${c.table}:${c.id}`; +} + +function compareText(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function renderOrder(a: TailNote, b: TailNote): number { + return ( + b.importance - a.importance || + compareText(a.firstSeen, b.firstSeen) || + compareText(a.key, b.key) + ); +} + +export function renderTailBlock(notes: TailNote[], date: string): string { + const bullets = notes.map((n) => `- ${n.text}`).join("\n"); + return `${RECALL_BEGIN}\n${TAIL_HEADER_PREFIX}${date}.\n\n${bullets}\n${RECALL_END}\n`; +} + +export function selectTail( + candidates: TailCandidate[], + options: { gapText?: string; cap?: boolean } = {}, +): TailSelection { + const gapText = options.gapText ?? ""; + const cap = options.cap ?? true; + const dropped: DroppedTailNote[] = []; + const safe: Array = []; + for (const c of candidates) { + const check = sanitizeTailBullet(c.text); + if (check.ok) safe.push({ ...c, clean: check.text }); + else + dropped.push({ + key: candidateKey(c), + reason: check.reason, + detail: check.detail, + }); + } + safe.sort( + (a, b) => + b.importance - a.importance || + b.accessCount - a.accessCount || + compareText(a.createdAt, b.createdAt) || + compareText(candidateKey(a), candidateKey(b)), + ); + + const clusters: Array<{ + lead: TailCandidate & { clean: string }; + form: string; + members: TailCandidate[]; + }> = []; + for (const c of safe) { + const form = matchForm(c.clean); + // Same normalized text only. Embedding similarity is not a merge: + // distinct rules with close vectors would be dropped, and their + // projects would count toward the survivor's promotion bar. + const home = clusters.find((k) => k.form === form); + if (home) { + home.members.push(c); + dropped.push({ + key: candidateKey(c), + reason: "duplicate", + detail: `merged into ${candidateKey(home.lead)}`, + }); + } else { + clusters.push({ lead: c, form, members: [c] }); + } + } + + const ranked: TailNote[] = clusters + .map(({ lead, members }) => { + const created = members.map((m) => m.createdAt).sort(compareText); + return { + key: candidateKey(lead), + text: lead.clean, + importance: Math.max(...members.map((m) => m.importance)), + sessions: new Set(members.map((m) => m.sessionId ?? candidateKey(m))) + .size, + accessCount: members.reduce((sum, m) => sum + m.accessCount, 0), + records: members.map((m) => ({ table: m.table, id: m.id })), + projects: [ + ...new Set( + members.map((m) => m.project).filter((p): p is string => !!p), + ), + ].sort(compareText), + firstSeen: created[0] ?? "", + lastSeen: created[created.length - 1] ?? "", + }; + }) + .sort( + (a, b) => + b.importance - a.importance || + b.sessions - a.sessions || + b.accessCount - a.accessCount || + compareText(a.firstSeen, b.firstSeen) || + compareText(a.key, b.key), + ); + + const chosen: TailNote[] = []; + for (const note of ranked) { + if (isCoveredByGap(note.text, gapText)) { + dropped.push({ + key: note.key, + reason: "covered", + detail: "already in the GAP block", + }); + continue; + } + if (!cap) { + chosen.push(note); + continue; + } + if (chosen.length >= MAX_TAIL_BULLETS) { + dropped.push({ + key: note.key, + reason: "cap", + detail: `${MAX_TAIL_BULLETS} bullets`, + }); + continue; + } + const trial = [...chosen, note].sort(renderOrder); + if ( + estimateTailTokens(renderTailBlock(trial, "0000-00-00")) > MAX_TAIL_TOKENS + ) { + dropped.push({ + key: note.key, + reason: "cap", + detail: `${MAX_TAIL_TOKENS} tokens`, + }); + continue; + } + chosen.push(note); + } + const notes = chosen.sort(renderOrder); + return { + notes, + dropped, + tokens: notes.length + ? estimateTailTokens(renderTailBlock(notes, "0000-00-00")) + : 0, + }; +} + +function findMarkerLine( + text: string, + marker: string, + from: number, +): [number, number] | null { + while (from < text.length) { + let i = text.indexOf(marker, from); + if (i < 0) return null; + const after = i + marker.length; + if (i > 0 && text[i - 1] !== "\n") { + from = i + 1; + continue; + } + if (after === text.length) return [i, after]; + if (text[after] === "\n") return [i, after + 1]; + if (text[after] === "\r" && text[after + 1] === "\n") return [i, after + 2]; + from = i + 1; + } + return null; +} + +function allMarkerLines(text: string, marker: string): Array<[number, number]> { + const out: Array<[number, number]> = []; + for (let from = 0; ;) { + const hit = findMarkerLine(text, marker, from); + if (!hit) return out; + out.push(hit); + from = hit[1]; + } +} + +function gapSpan( + text: string, +): { start: number; innerStart: number; innerEnd: number; end: number } | null { + let span: { + start: number; + innerStart: number; + innerEnd: number; + end: number; + } | null = null; + for (let from = 0; ;) { + let begin = findMarkerLine(text, GAP_BEGIN, from); + if (!begin) return span; + const end = findMarkerLine(text, GAP_END, begin[1]); + if (!end) return span; + for (;;) { + const next = findMarkerLine(text, GAP_BEGIN, begin[1]); + if (!next || next[0] >= end[0]) break; + begin = next; + } + span = { + start: begin[0], + innerStart: begin[1], + innerEnd: end[0], + end: end[1], + }; + from = end[1]; + } +} + +export function gapBlockText(text: string): string | null { + const span = gapSpan(text); + return span ? text.slice(span.innerStart, span.innerEnd) : null; +} + +type RecallSpan = + | { kind: "none" } + | { kind: "malformed"; reason: string } + | { + kind: "found"; + start: number; + innerStart: number; + innerEnd: number; + end: number; + }; + +function recallSpan(text: string): RecallSpan { + const begins = allMarkerLines(text, RECALL_BEGIN); + const ends = allMarkerLines(text, RECALL_END); + if (begins.length === 0 && ends.length === 0) return { kind: "none" }; + if (begins.length !== 1 || ends.length !== 1) { + return { + kind: "malformed", + reason: `expected one Recall marker pair, found ${begins.length} begin and ${ends.length} end`, + }; + } + const [begin] = begins; + const [end] = ends; + if (end[0] < begin[1]) + return { + kind: "malformed", + reason: "Recall end marker comes before its begin marker", + }; + const gapMarks = [ + ...allMarkerLines(text, GAP_BEGIN), + ...allMarkerLines(text, GAP_END), + ]; + if (gapMarks.some(([at]) => at >= begin[0] && at < end[1])) { + return { + kind: "malformed", + reason: "Recall block wraps a GAP marker", + }; + } + const gap = gapSpan(text); + if ( + gap && + ((begin[0] >= gap.start && begin[0] < gap.end) || + (end[0] >= gap.start && end[0] < gap.end)) + ) { + return { + kind: "malformed", + reason: "Recall marker sits inside the GAP block", + }; + } + return { + kind: "found", + start: begin[0], + innerStart: begin[1], + innerEnd: end[0], + end: end[1], + }; +} + +export function readRecallBlock(text: string): RecallBlockInfo { + const span = recallSpan(text); + if (span.kind === "none") + return { + present: false, + malformed: false, + updated: null, + bullets: [], + tokens: 0, + }; + if (span.kind === "malformed") + return { + present: true, + malformed: true, + updated: null, + bullets: [], + tokens: 0, + }; + const inner = text.slice(span.innerStart, span.innerEnd); + const lines = inner.split(/\r?\n/); + const header = lines.map((l) => HEADER_RE.exec(l)).find((m) => m !== null); + return { + present: true, + malformed: false, + updated: header ? header[1] : null, + bullets: lines.filter((l) => l.startsWith("- ")).map((l) => l.slice(2)), + tokens: estimateTailTokens(text.slice(span.start, span.end)), + }; +} + +function blockEndsFile(text: string, end: number): boolean { + return end === text.length && !text.endsWith("\n"); +} + +function removeSpan(text: string, start: number, end: number): string { + const sep = + start >= 2 && text[start - 1] === "\n" && text[start - 2] === "\n"; + const cut = !sep ? start : blockEndsFile(text, end) ? start - 2 : start - 1; + return text.slice(0, cut) + text.slice(end); +} + +export function removeRecallBlock(text: string): SpliceResult { + const span = recallSpan(text); + if (span.kind === "malformed") return { ok: false, reason: span.reason }; + if (span.kind === "none") return { ok: true, text, changed: false }; + return { + ok: true, + text: removeSpan(text, span.start, span.end), + changed: true, + }; +} + +export function spliceRecallBlock( + text: string, + notes: TailNote[], + date: string, +): SpliceResult { + const span = recallSpan(text); + if (span.kind === "malformed") return { ok: false, reason: span.reason }; + if (notes.length === 0) { + if (span.kind === "none") return { ok: true, text, changed: false }; + return { + ok: true, + text: removeSpan(text, span.start, span.end), + changed: true, + }; + } + const block = renderTailBlock(notes, date); + if (span.kind === "none") { + if (text === "") return { ok: true, text: block, changed: true }; + if (text.endsWith("\n")) + return { ok: true, text: `${text}\n${block}`, changed: true }; + return { + ok: true, + text: `${text}\n\n${block.slice(0, -1)}`, + changed: true, + }; + } + const existing = readRecallBlock(text); + const same = + existing.updated !== null && + existing.bullets.length === notes.length && + existing.bullets.every((b, i) => b === notes[i].text); + if (same) return { ok: true, text, changed: false }; + const fitted = blockEndsFile(text, span.end) ? block.slice(0, -1) : block; + const next = text.slice(0, span.start) + fitted + text.slice(span.end); + return { ok: true, text: next, changed: next !== text }; +} + +function isExecutableFile(path: string): boolean { + try { + if (!statSync(path).isFile()) return false; + accessSync(path, constants.X_OK); + return true; + } catch { + return false; + } +} + +export function gapOnPath(pathEnv: string): boolean { + return pathEnv + .split(delimiter) + .filter((dir) => dir !== "") + .some((dir) => isExecutableFile(join(dir, "gap"))); +} + +export function readGapLedger(home: string): Record | null { + try { + const parsed: unknown = JSON.parse( + readFileSync(join(home, ".gap", "published.json"), "utf8"), + ); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : null; + } catch { + return null; + } +} + +function regularFileProblem(path: string): string | null { + try { + const st = lstatSync(path); + if (st.isSymbolicLink()) return "symlink"; + if (!st.isFile()) return "not a regular file"; + return null; + } catch { + return "missing"; + } +} + +function insideHome(home: string, path: string): boolean { + const rel = relative(home, path); + return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); +} + +function resolveEnv(env: TailEnv): { home: string; pathEnv: string } { + return { + home: + env.home ?? (process.env.HOME || process.env.USERPROFILE || homedir()), + pathEnv: env.path ?? process.env.PATH ?? "", + }; +} + +export function findTailDestinations(env: TailEnv = {}): TailDestinationScan { + const { home, pathEnv } = resolveEnv(env); + const ledger = gapOnPath(pathEnv) ? readGapLedger(home) : null; + const destinations: TailDestination[] = []; + const skipped: SkippedTailDestination[] = []; + if (ledger) { + for (const path of Object.keys(ledger).sort(compareText)) { + const value = ledger[path]; + if (value === "cleaned") { + skipped.push({ path, reason: "cleaned ledger entry" }); + continue; + } + if ( + typeof value !== "string" || + !isAbsolute(path) || + !insideHome(home, path) + ) { + skipped.push({ path, reason: "not a ledger path under HOME" }); + continue; + } + const problem = regularFileProblem(path); + if (problem) { + skipped.push({ path, reason: problem }); + continue; + } + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch { + skipped.push({ path, reason: "unreadable" }); + continue; + } + if (gapSpan(text) === null) { + skipped.push({ path, reason: "no GAP block (command file)" }); + continue; + } + destinations.push({ path, source: "gap" }); + } + return { gap: true, destinations, skipped }; + } + for (const rel of BUILTIN_TAIL_FILES) { + const path = join(home, rel); + const problem = regularFileProblem(path); + if (problem) skipped.push({ path, reason: problem }); + else destinations.push({ path, source: "builtin" }); + } + return { gap: false, destinations, skipped }; +} + +export function readGapCoverageText(paths: string[]): string { + const seen = new Set(); + for (const path of paths) { + try { + const inner = gapBlockText(readFileSync(path, "utf8")); + if (inner) seen.add(inner); + } catch { + continue; + } + } + return [...seen].join("\n"); +} + +function readUtf8Exact( + path: string, +): { text: string; hash: string } | { error: string } { + const problem = regularFileProblem(path); + if (problem) return { error: problem }; + const bytes = readFileSync(path); + const text = bytes.toString("utf8"); + if (!Buffer.from(text, "utf8").equals(bytes)) + return { error: "not valid UTF-8" }; + return { text, hash: sha256(bytes) }; +} + +export const TAIL_STATE_FILE = "learned-tail-state.json"; + +export interface TailState { + refreshedAt: number; + tailSince: Record; +} + +export function tailNoteKey(text: string): string { + return matchForm(text); +} + +export function tailStatePath(dbPath: string = resolveDbPath()): string { + return join(dirname(dbPath), TAIL_STATE_FILE); +} + +export function readTailState(path: string): TailState { + try { + const parsed = JSON.parse(readFileSync(path, "utf8")); + const since: Record = {}; + if (parsed?.tailSince && typeof parsed.tailSince === "object") { + for (const [k, v] of Object.entries(parsed.tailSince)) { + if (typeof v === "string" && !Number.isNaN(Date.parse(v))) since[k] = v; + } + } + return { + refreshedAt: + Number.isFinite(parsed?.refreshedAt) && parsed.refreshedAt > 0 + ? parsed.refreshedAt + : 0, + tailSince: since, + }; + } catch { + return { refreshedAt: 0, tailSince: {} }; + } +} + +export function writeTailState(path: string, state: TailState): void { + const tmp = join( + dirname(path), + `.${basename(path)}.${process.pid}-${randomBytes(6).toString("hex")}.tmp`, + ); + const fd = openSync(tmp, "wx", 0o600); + try { + writeSync(fd, JSON.stringify(state)); + fsyncSync(fd); + } finally { + closeSync(fd); + } + try { + renameSync(tmp, path); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } +} + +export function nextTailState( + state: TailState, + notes: TailNote[], + now: Date, +): TailState { + const tailSince: Record = {}; + for (const note of notes) { + const key = tailNoteKey(note.text); + tailSince[key] = state.tailSince[key] ?? now.toISOString(); + } + return { refreshedAt: now.getTime(), tailSince }; +} + +export function recordTailRefresh( + path: string, + plan: TailPlan, + writes: TailWriteResult[], + now: Date = new Date(), +): boolean { + if (writes.some((w) => w.status === "refused")) return false; + const landed = writes.some( + (w) => w.status === "written" || w.status === "unchanged", + ); + writeTailState( + path, + nextTailState(readTailState(path), landed ? plan.selection.notes : [], now), + ); + return true; +} + +export function countRecordsSince( + sinceMs: number, + dbPath: string = resolveDbPath(), +): number { + if (!existsSync(dbPath)) return 0; + const db = new Database(dbPath, { readonly: true }); + try { + const tables = new Set( + ( + db + .query("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() as { name: string }[] + ).map((r) => r.name), + ); + const since = new Date(sinceMs).toISOString(); + let total = 0; + for (const spec of TABLE_SPECS) { + if (!tables.has(spec.table)) continue; + const row = db + .query( + `SELECT COUNT(*) AS n FROM ${spec.table} WHERE julianday(created_at) > julianday(?)`, + ) + .get(since) as { n: number } | null; + total += row?.n ?? 0; + } + return total; + } finally { + db.close(); + } +} + +export function planLearnedTail(options: PlanTailOptions = {}): TailPlan { + const scan = findTailDestinations(options); + const date = formatTailDate(options.now ?? new Date()); + const gapText = readGapCoverageText(scan.destinations.map((d) => d.path)); + const candidates = options.candidates ?? loadTailCandidates(options.dbPath); + const selection = selectTail(candidates, { gapText }); + const destinations: TailDestinationPlan[] = scan.destinations.map((d) => { + let read: { text: string; hash: string } | { error: string }; + try { + read = readUtf8Exact(d.path); + } catch (err) { + read = { error: err instanceof Error ? err.message : String(err) }; + } + if ("error" in read) { + return { + ...d, + before: "", + after: "", + beforeHash: "", + changed: false, + refused: read.error, + }; + } + const spliced = spliceRecallBlock(read.text, selection.notes, date); + if (!spliced.ok) { + return { + ...d, + before: read.text, + after: read.text, + beforeHash: read.hash, + changed: false, + refused: spliced.reason, + }; + } + return { + ...d, + before: read.text, + after: spliced.text, + beforeHash: read.hash, + changed: spliced.changed, + }; + }); + return { + date, + gap: scan.gap, + selection, + block: selection.notes.length + ? renderTailBlock(selection.notes, date) + : null, + destinations, + skipped: scan.skipped, + }; +} + +function currentHash(path: string): string | null { + if (regularFileProblem(path)) return null; + return sha256(readFileSync(path)); +} + +export function writeIfUnchanged( + path: string, + expectedHash: string, + content: string, +): TailWriteResult { + let tmp: string | null = null; + try { + if (currentHash(path) !== expectedHash) + return { path, status: "refused", reason: "changed since it was read" }; + const mode = lstatSync(path).mode & 0o7777; + tmp = join( + dirname(path), + `.${basename(path)}.recall-${process.pid}-${randomBytes(6).toString("hex")}.tmp`, + ); + const fd = openSync(tmp, "wx", 0o600); + try { + writeSync(fd, content); + fsyncSync(fd); + } finally { + closeSync(fd); + } + chmodSync(tmp, mode); + if (currentHash(path) !== expectedHash) { + rmSync(tmp, { force: true }); + return { path, status: "refused", reason: "changed during the write" }; + } + renameSync(tmp, path); + tmp = null; + return { path, status: "written" }; + } catch (err) { + if (tmp) rmSync(tmp, { force: true }); + return { + path, + status: "refused", + reason: err instanceof Error ? err.message : String(err), + }; + } +} + +export function writeLearnedTail(plan: TailPlan): TailWriteResult[] { + return plan.destinations.map((d) => { + if (d.refused) + return { path: d.path, status: "refused", reason: d.refused }; + if (!d.changed) return { path: d.path, status: "unchanged" }; + return writeIfUnchanged(d.path, d.beforeHash, d.after); + }); +} diff --git a/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md b/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md new file mode 100644 index 00000000..3bfd7b0d --- /dev/null +++ b/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md @@ -0,0 +1,67 @@ +--- +name: "do-recall-promote" +description: "Promote learned-tail notes that hold across projects into GAP by opening a pull request. Never writes main and never runs gap sync." +--- + +Turn Recall notes that hold across projects into a reviewed change to the shared GAP policy. This skill only opens a pull request. The user reviews and merges it, then runs `gap sync` themselves. + +## What this does + +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. +3. Opens a pull request and stops. + +## Never + +- Never commit to `main` or `master`, and never push to either. +- Never edit a published harness file (`~/.claude/CLAUDE.md` and the rest). `gap sync` is what publishes, and only the user runs it. +- Never run `gap sync`, `gap remove`, or any command that writes a harness file. +- Never promote a note the user did not accept, and never invent text the JSON did not return. + +## Steps + +1. **List the candidates.** + + ```bash + recall promote --json + ``` + + The JSON has `gap`, `candidates`, and `skipped`. Each candidate carries `text`, `records` (`table` and `id`), `projects`, `firstSeen`, `lastSeen`, and `daysInTail`. + + Stop and tell the user when `gap` is false (GAP is not installed), when `candidates` is empty, or when the command exits non-zero. There is nothing to promote. + +2. **Ask which notes to promote.** Show each candidate's text, projects, record ids, and first/last seen dates. Promote only the ones the user accepts. If they accept none, stop. + +3. **Find the GAP checkout.** Ask `gap` where it publishes from. Do not search the filesystem for another clone and do not clone the repo. + + ```bash + GAP_SRC="$(gap source)" && test -f "$GAP_SRC/global/AGENTS.md" + ``` + + If `gap source` fails or is unknown (a `gap` older than this command), stop and tell the user to update gap. + +4. **Branch off the published branch in a worktree.** The checkout may be on another branch or hold uncommitted work, so never switch it, stash, reset, or clean it. + + ```bash + BRANCH="recall-promote-$(date +%Y-%m-%d)" + git -C "$GAP_SRC" fetch origin + git -C "$GAP_SRC" worktree add "$GAP_SRC/.worktrees/$BRANCH" -b "$BRANCH" origin/HEAD + WT="$GAP_SRC/.worktrees/$BRANCH" + ``` + + `origin/HEAD` is the branch `gap sync` publishes. If the branch or worktree already exists, stop and ask. + +5. **Edit `$WT/global/AGENTS.md` only.** Add each accepted note as its own short bullet under the existing `## Work` list, in the user's words from `text`. Do not add a new section, do not touch `global/docs/agents/`, and do not edit any other file. Keep the file's style: no em dashes. + +6. **Commit on the branch and open the pull request.** + + ```bash + git -C "$WT" add global/AGENTS.md + git -C "$WT" commit -m "docs(policy): promote recall notes" + git -C "$WT" push -u origin "$BRANCH" + (cd "$WT" && gh pr create --title "Promote recall notes into the shared policy" --body "") + ``` + + The pull request body lists every promoted note with its record ids (`decisions#123`) and projects, and says the user merges it and then runs `gap sync`. + +7. **Stop.** Report the pull request URL and the worktree path (`$WT`), which the user removes with `git -C "$GAP_SRC" worktree remove "$WT"` after the merge. Do not merge it and do not run `gap sync`. After the user does both, the next `recall learn` sees the rule in the GAP block and drops it from the tail. diff --git a/hosts/plugins/recall/skills/do-recall-promote/SKILL.md b/hosts/plugins/recall/skills/do-recall-promote/SKILL.md new file mode 100644 index 00000000..5e6fd433 --- /dev/null +++ b/hosts/plugins/recall/skills/do-recall-promote/SKILL.md @@ -0,0 +1,75 @@ +--- +name: "do-recall-promote" +description: "Promote learned-tail notes that hold across projects into GAP by opening a pull request. Never writes main and never runs gap sync." +--- + + + +## Codex routing + +This opens a pull request on GAP and nothing else. Run `recall promote --json`, edit only GAP global/AGENTS.md in a worktree branch, and never write main or run `gap sync`. + +The canonical workflow below remains authoritative, but equivalent behavior is not assumed across hosts. + +Turn Recall notes that hold across projects into a reviewed change to the shared GAP policy. This skill only opens a pull request. The user reviews and merges it, then runs `gap sync` themselves. + +## What this does + +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. +3. Opens a pull request and stops. + +## Never + +- Never commit to `main` or `master`, and never push to either. +- Never edit a published harness file (`~/.claude/CLAUDE.md` and the rest). `gap sync` is what publishes, and only the user runs it. +- Never run `gap sync`, `gap remove`, or any command that writes a harness file. +- Never promote a note the user did not accept, and never invent text the JSON did not return. + +## Steps + +1. **List the candidates.** + + ```bash + recall promote --json + ``` + + The JSON has `gap`, `candidates`, and `skipped`. Each candidate carries `text`, `records` (`table` and `id`), `projects`, `firstSeen`, `lastSeen`, and `daysInTail`. + + Stop and tell the user when `gap` is false (GAP is not installed), when `candidates` is empty, or when the command exits non-zero. There is nothing to promote. + +2. **Ask which notes to promote.** Show each candidate's text, projects, record ids, and first/last seen dates. Promote only the ones the user accepts. If they accept none, stop. + +3. **Find the GAP checkout.** Ask `gap` where it publishes from. Do not search the filesystem for another clone and do not clone the repo. + + ```bash + GAP_SRC="$(gap source)" && test -f "$GAP_SRC/global/AGENTS.md" + ``` + + If `gap source` fails or is unknown (a `gap` older than this command), stop and tell the user to update gap. + +4. **Branch off the published branch in a worktree.** The checkout may be on another branch or hold uncommitted work, so never switch it, stash, reset, or clean it. + + ```bash + BRANCH="recall-promote-$(date +%Y-%m-%d)" + git -C "$GAP_SRC" fetch origin + git -C "$GAP_SRC" worktree add "$GAP_SRC/.worktrees/$BRANCH" -b "$BRANCH" origin/HEAD + WT="$GAP_SRC/.worktrees/$BRANCH" + ``` + + `origin/HEAD` is the branch `gap sync` publishes. If the branch or worktree already exists, stop and ask. + +5. **Edit `$WT/global/AGENTS.md` only.** Add each accepted note as its own short bullet under the existing `## Work` list, in the user's words from `text`. Do not add a new section, do not touch `global/docs/agents/`, and do not edit any other file. Keep the file's style: no em dashes. + +6. **Commit on the branch and open the pull request.** + + ```bash + git -C "$WT" add global/AGENTS.md + git -C "$WT" commit -m "docs(policy): promote recall notes" + git -C "$WT" push -u origin "$BRANCH" + (cd "$WT" && gh pr create --title "Promote recall notes into the shared policy" --body "") + ``` + + The pull request body lists every promoted note with its record ids (`decisions#123`) and projects, and says the user merges it and then runs `gap sync`. + +7. **Stop.** Report the pull request URL and the worktree path (`$WT`), which the user removes with `git -C "$GAP_SRC" worktree remove "$WT"` after the merge. Do not merge it and do not run `gap sync`. After the user does both, the next `recall learn` sees the rule in the GAP block and drops it from the tail. diff --git a/lib/install-lib.sh b/lib/install-lib.sh index 15b7acfe..d3bf8955 100644 --- a/lib/install-lib.sh +++ b/lib/install-lib.sh @@ -810,7 +810,7 @@ recall_prompt_db_path() { if [[ -n "${HAS_GUM:-}" ]] && [[ "$HAS_GUM" == "true" ]]; then # gum input doesn't honor an empty default, so we pre-seed the field. - chosen="$(gum input --value "$default_path" --prompt "Database path: " 2>/dev/null || echo "")" + chosen="$(gum input --value "$default_path" --prompt "Database path: " || echo "")" else printf "Database path [%s]: " "$default_short" read -r chosen diff --git a/package.json b/package.json index 9542b1bb..e4af0583 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "zod": "^3.24.0" }, "devDependencies": { + "@plannotator/sem-jiff": "^0.2.0", "@types/bun": "^1.3.14", "@types/node": "^22.10.0", "fast-check": "^4.8.0", diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index a28b7791..cc4195a1 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -117,6 +117,7 @@ RECALL_HOOK_LIB_FILES=( "$CLAUDE_DIR/hooks/lib/markdown-drop.ts" "$CLAUDE_DIR/hooks/lib/extraction-parsers.ts" "$CLAUDE_DIR/hooks/lib/jev.ts" + "$CLAUDE_DIR/hooks/lib/learned-tail.ts" "$CLAUDE_DIR/hooks/lib/sqlite-writers.ts" "$CLAUDE_DIR/hooks/lib/session-progress.ts" "$CLAUDE_DIR/hooks/lib/threat-detect.ts" @@ -153,6 +154,7 @@ RECALL_SKILL_NAMES=( do-recall-doctor do-recall-dump do-recall-loa + do-recall-promote do-recall-recent do-recall-scout do-recall-search @@ -183,6 +185,7 @@ print_summary() { echo " • ~/.claude/hooks/*.ts (Recall-managed symlinks only)" echo " • ~/.claude/hooks/lib/*.ts (Recall-managed symlinks only)" echo " • Recall-generated ## MEMORY section in ~/.claude/CLAUDE.md (external sections stay)" + echo " • Recall learned-tail block ( ... ) in destination files" echo " • ~/.claude/MEMORY/extract_prompt.md (symlink → ~/.agents/Recall/shared/)" [[ "$SKIP_OPENCODE" != "true" ]] && echo " • OpenCode MCP entry + plugin symlinks" [[ "$SKIP_PI" != "true" ]] && echo " • Pi MCP entry + Recall package + Recall-generated AGENTS.md MEMORY section" @@ -391,6 +394,119 @@ remove_extract_prompt_if_unmodified() { fi } +# Every harness file the learned tail may ever have written: each GAP ledger +# path under HOME (cleaned ones too, since GAP may have been installed or +# removed after a write) plus every built-in file. Only the Recall pair is +# removed from each, and a missing file is skipped by remove_recall_block. +recall_learned_tail_files() { + RECALL_TAIL_HOME="$HOME" bun -e ' + const fs = require("fs"); + const path = require("path"); + const home = process.env.RECALL_TAIL_HOME; + const builtin = [ + ".claude/CLAUDE.md", + ".codex/AGENTS.md", + ".pi/agent/APPEND_SYSTEM.md", + ".omp/agent/APPEND_SYSTEM.md", + ".empryo/EMPRYO.md", + ]; + let ledger = null; + try { + const parsed = JSON.parse(fs.readFileSync(path.join(home, ".gap", "published.json"), "utf8")); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) ledger = parsed; + } catch { /* no GAP ledger — built-in files */ } + const out = new Set(); + for (const file of Object.keys(ledger ?? {}).sort()) { + if (typeof ledger[file] !== "string" || !path.isAbsolute(file)) continue; + const rel = path.relative(home, file); + if (rel && !rel.startsWith("..") && !path.isAbsolute(rel)) out.add(file); + } + for (const rel of builtin) out.add(path.join(home, rel)); + process.stdout.write([...out].join("\n")); + ' +} + +# Remove only the ... pair. +# Everything outside that pair, including a GAP block, stays byte for byte. +# A file with no pair is left untouched. A malformed pair (nested, reversed, +# or more than one) is left untouched and reported. +remove_recall_block() { + local file="$1" + [[ -f "$file" && ! -L "$file" ]] || return 0 + if [[ "$DRY_RUN" == "true" ]]; then + if grep -q '' "$file" 2>/dev/null; then + echo " [dry-run] would remove Recall learned-tail block from $file" + fi + return 0 + fi + local status=0 + RECALL_BLOCK_FILE="$file" bun -e ' + const fs = require("fs"); + const file = process.env.RECALL_BLOCK_FILE; + const BEGIN = ""; + const END = ""; + const src = fs.readFileSync(file); + const text = src.toString("utf8"); + if (!Buffer.from(text, "utf8").equals(src)) process.exit(0); + function markerLines(marker) { + const out = []; + let from = 0; + while (from < text.length) { + const i = text.indexOf(marker, from); + if (i < 0) break; + const after = i + marker.length; + const ownLine = (i === 0 || text[i - 1] === "\n") && + (after === text.length || text[after] === "\n" || + (text[after] === "\r" && text[after + 1] === "\n")); + if (ownLine) { + let end = after; + if (text[after] === "\n") end = after + 1; + else if (text[after] === "\r") end = after + 2; + out.push([i, end]); + from = end; + } else { + from = i + 1; + } + } + return out; + } + const begins = markerLines(BEGIN); + const ends = markerLines(END); + if (begins.length === 0 && ends.length === 0) process.exit(0); + if (begins.length !== 1 || ends.length !== 1 || ends[0][0] < begins[0][1]) { + process.stderr.write("malformed Recall block in " + file + "\n"); + process.exit(2); + } + let cut = begins[0][0]; + const end = ends[0][1]; + const gapBegins = markerLines(""); + const gapEnds = markerLines(""); + const wraps = [...gapBegins, ...gapEnds].some(([at]) => at >= cut && at < end); + const inside = gapBegins.some(([gb], i) => { + const ge = gapEnds.find(([at]) => at > gb); + return ge && ((cut > gb && cut < ge[0]) || (ends[0][0] > gb && ends[0][0] < ge[0])); + }); + if (wraps || inside) { + process.stderr.write("Recall block overlaps the GAP block in " + file + "\n"); + process.exit(2); + } + if (cut >= 2 && text[cut - 1] === "\n" && text[cut - 2] === "\n") { + cut -= end === text.length && !text.endsWith("\n") ? 2 : 1; + } + const next = text.slice(0, cut) + text.slice(end); + if (next !== text) fs.writeFileSync(file, next); + ' || status=$? + if [[ "$status" -eq 2 ]]; then + log_warn "Preserved $file (malformed Recall learned-tail block)" + return 0 + fi + if [[ "$status" -ne 0 ]]; then + log_error "Failed to remove Recall learned-tail block from $file" + return 1 + fi + return 0 +} + # Remove only Recall-generated "## MEMORY" sections through the shared # ownership classifier in lib/install-lib.sh. remove_memory_section() { @@ -771,6 +887,24 @@ main() { remove_memory_section "$CLAUDE_DIR/CLAUDE.md" claude echo "" + log_info "Removing learned-tail blocks..." + local tail_file + local tail_files + if ! command -v bun &>/dev/null; then + log_warn "bun not found; learned-tail blocks left in place (remove the ... lines by hand)" + elif ! tail_files="$(recall_learned_tail_files)"; then + log_warn "Could not list learned-tail files; blocks left in place" + lifecycle_failed=true + else + while IFS= read -r tail_file; do + [[ -n "$tail_file" ]] || continue + if ! remove_recall_block "$tail_file"; then + lifecycle_failed=true + fi + done <<< "$tail_files" + fi + echo "" + if [[ "$SKIP_OPENCODE" != "true" ]]; then log_info "Removing OpenCode integration..." if ! remove_opencode; then diff --git a/scripts/build-codex-plugin.ts b/scripts/build-codex-plugin.ts index 4733041a..89839171 100644 --- a/scripts/build-codex-plugin.ts +++ b/scripts/build-codex-plugin.ts @@ -17,6 +17,7 @@ export const routes: Record = { 'do-recall-doctor': 'This remains a local CLI diagnostic. Run `recall doctor`; the Codex plugin does not rewrite Codex-owned configuration.', 'do-recall-dump': 'Codex lifecycle hooks capture supported transcripts automatically. Use `memory_dump` only for an explicit supplemental snapshot of visible messages.', 'do-recall-loa': 'Prefer `loa_show` for a known entry and `memory_recall` to browse recent entries. Use CLI-only quote/list variants when needed.', + 'do-recall-promote': 'This opens a pull request on GAP and nothing else. Run `recall promote --json`, edit only GAP global/AGENTS.md in a worktree branch, and never write main or run `gap sync`.', 'do-recall-recent': 'Prefer `memory_recall` for recent cross-table context. Use the CLI when an exact table-specific recent listing is required.', 'do-recall-scout': 'Use the plugin MCP tools `memory_search`, `memory_hybrid_search`, and `context_for_agent` for the memory-first steps; keep the workflow sensitive-data boundary intact.', 'do-recall-search': 'Prefer `memory_search`; use `memory_hybrid_search` for natural-language semantic retrieval. The CLI remains an explicit fallback.', diff --git a/scripts/e2e-claude-plugin.ts b/scripts/e2e-claude-plugin.ts index b46c2483..33a96244 100644 --- a/scripts/e2e-claude-plugin.ts +++ b/scripts/e2e-claude-plugin.ts @@ -97,8 +97,8 @@ async function main(): Promise { // ── A legacy lifecycle install, exactly as today's users have it ─────────── const installRoot = join(testRecallHome, 'install-root'); const canonicalSkills = join(installRoot, 'shared', 'skills'); - const skillNames = ['do-recall-add', 'do-recall-doctor', 'do-recall-dump', 'do-recall-loa', 'do-recall-recent', - 'do-recall-scout', 'do-recall-search', 'do-recall-stats', 'do-recall-update']; + const skillNames = ['do-recall-add', 'do-recall-doctor', 'do-recall-dump', 'do-recall-loa', 'do-recall-promote', + 'do-recall-recent', 'do-recall-scout', 'do-recall-search', 'do-recall-stats', 'do-recall-update']; // Seeded by the installer's own linker rather than hand-rolled symlinks, so the // migration is tested against whatever format recall_link actually produces and // this test cannot drift from production. @@ -156,7 +156,7 @@ async function main(): Promise { const details = runClaude(['plugin', 'details', 'recall'], env); const skillCount = Number(details.match(/Skills \((\d+)\)/)?.[1]); - if (skillCount !== 9) throw new Error(`expected 9 plugin skills, got ${skillCount}\n${details}`); + if (skillCount !== 10) throw new Error(`expected 10 plugin skills, got ${skillCount}\n${details}`); if (!/MCP servers \(1\)\s+recall-memory/.test(details)) { throw new Error(`plugin did not contribute the recall-memory MCP server\n${details}`); } diff --git a/scripts/e2e-pi-integration.ts b/scripts/e2e-pi-integration.ts index 255a26dd..a5141304 100644 --- a/scripts/e2e-pi-integration.ts +++ b/scripts/e2e-pi-integration.ts @@ -272,6 +272,7 @@ export default function (pi) { 'skill:do-recall-doctor', 'skill:do-recall-dump', 'skill:do-recall-loa', + 'skill:do-recall-promote', 'skill:do-recall-recent', 'skill:do-recall-scout', 'skill:do-recall-search', diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index 0524d77e..0a586fb1 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -20,6 +20,7 @@ import { validateClaudeMcpConfigShape, writeJsonAtomic, } from '../../lib/jsonc-mcp.js'; +import { findTailDestinations, readRecallBlock, type RecallBlockInfo, type TailDestinationScan } from '../lib/learned-tail.js'; export interface DoctorOptions { fix?: boolean; } @@ -255,6 +256,43 @@ function checkExtractLog(): CheckResult { } } +// ───────────────────────────────────────── +// Check: learned tail (#279) +// ───────────────────────────────────────── +// For each harness file the learned tail writes, report whether the Recall pair +// is present, when it was last updated, and how many tokens it occupies. A +// missing block is INFO (recall learn has not run); a malformed pair is WARN. +// Exported and path-injected so tests never touch the real HOME. +export function probeLearnedTail(scan: TailDestinationScan, read: (path: string) => string | null): CheckResult[] { + if (scan.destinations.length === 0) { + return [{ label: 'Learned tail', status: 'INFO', message: 'No learned-tail destinations' }]; + } + return scan.destinations.map((dest) => { + const label = `Learned tail (${basename(dest.path)})`; + let text: string | null; + try { + text = read(dest.path); + } catch { + text = null; + } + if (text === null) return { label, status: 'WARN', message: `unreadable ${dest.path}` }; + const info = readRecallBlock(text); + return { label, status: learnedTailStatus(info), message: formatLearnedTail(info, dest.path) }; + }); +} + +function learnedTailStatus(info: RecallBlockInfo): Status { + if (info.malformed) return 'WARN'; + if (info.present) return 'PASS'; + return 'INFO'; +} + +function formatLearnedTail(info: RecallBlockInfo, path: string): string { + if (info.malformed) return `malformed Recall block in ${path}`; + if (!info.present) return `block absent in ${path}`; + return `block present, last updated ${info.updated ?? 'unknown'}, ${info.tokens} tokens`; +} + // ───────────────────────────────────────── // Check 6: Extraction tracker lockouts // ───────────────────────────────────────── @@ -1079,6 +1117,16 @@ export async function runDoctor(opts: DoctorOptions = {}): Promise { // re-running ./packaging/install.sh converges; doctor does not auto-repair it. results.push(probeInstallSentinel(join(getRecallHome(), '.install-incomplete'))); + results.push( + ...probeLearnedTail(findTailDestinations(), (path) => { + try { + return readFileSync(path, 'utf8'); + } catch { + return null; + } + }), + ); + // Print all results for (const r of results) { printResult(r); diff --git a/src/commands/learn.ts b/src/commands/learn.ts new file mode 100644 index 00000000..7ff2b2f4 --- /dev/null +++ b/src/commands/learn.ts @@ -0,0 +1,141 @@ +// recall learn — write Recall's learned tail into each global harness file (#279). +// Selection, destinations and the splice live in hooks/lib/learned-tail.ts. +// This command only prints the plan and writes when a destination's content changes. + +import { + planLearnedTail, + recordTailRefresh, + tailStatePath, + writeLearnedTail, +} from "../lib/learned-tail.js"; +import type { + TailDestinationPlan, + TailPlan, + TailWriteResult, +} from "../lib/learned-tail.js"; + +export interface LearnOptions { + dryRun?: boolean; + json?: boolean; +} + +function fileDiff(plan: TailDestinationPlan): string { + if (plan.refused) return `refused: ${plan.refused}`; + if (!plan.changed) return "unchanged"; + const before = plan.before.endsWith("\n") ? plan.before : `${plan.before}\n`; + const after = plan.after.endsWith("\n") ? plan.after : `${plan.after}\n`; + const a = before.split("\n"); + const b = after.split("\n"); + const out = [`--- ${plan.path}`, `+++ ${plan.path}`]; + let i = 0; + while (i < a.length || i < b.length) { + let run = i; + while (run < a.length && run < b.length && a[run] === b[run]) run++; + if (run > i) { + out.push(` ${a[i]}`); + if (run > i + 1) out.push(` ... ${run - i - 1} unchanged`); + if (run - 1 > i) out.push(` ${a[run - 1]}`); + } + let end = run; + while (end < a.length && end < b.length && a[end] !== b[end]) end++; + if (end === run && (run < a.length || run < b.length)) + end = Math.max(a.length, b.length); + for (let n = run; n < end && n < a.length; n++) out.push(`-${a[n]}`); + for (let n = run; n < end && n < b.length; n++) out.push(`+${b[n]}`); + i = end; + } + return out.join("\n"); +} + +function printText(plan: TailPlan, writes: TailWriteResult[] | null): void { + const { selection } = plan; + console.log( + `Learned tail ${plan.date} ${plan.gap ? "GAP destinations" : "built-in destinations"}`, + ); + console.log( + `Selected ${selection.notes.length} (${selection.tokens} tokens), dropped ${selection.dropped.length}`, + ); + for (const note of selection.notes) { + console.log(` - ${note.text}`); + } + if (selection.dropped.length > 0) { + console.log("Dropped:"); + for (const drop of selection.dropped) { + console.log(` ${drop.reason}${drop.detail ? ` (${drop.detail})` : ""}`); + } + } + console.log(""); + console.log("Destinations:"); + for (const dest of plan.destinations) { + const write = writes?.find((w) => w.path === dest.path); + const state = + write?.status ?? + (dest.refused ? "refused" : dest.changed ? "would write" : "unchanged"); + console.log( + ` ${dest.path} [${dest.source}] ${state}${write?.reason ? `: ${write.reason}` : ""}`, + ); + if (dest.changed || dest.refused) + console.log(fileDiff(dest).replace(/^/gm, " ")); + } + for (const skip of plan.skipped) { + console.log(` ${skip.path} skipped: ${skip.reason}`); + } + if (!writes) console.log("\n[DRY RUN] No files were written."); +} + +function jsonReport(plan: TailPlan, writes: TailWriteResult[] | null) { + return { + date: plan.date, + gap: plan.gap, + dryRun: writes === null, + selection: { + tokens: plan.selection.tokens, + notes: plan.selection.notes.map((n) => ({ + text: n.text, + importance: n.importance, + sessions: n.sessions, + projects: n.projects, + records: n.records, + })), + dropped: plan.selection.dropped, + }, + destinations: plan.destinations.map((d) => ({ + path: d.path, + source: d.source, + changed: d.changed, + refused: d.refused ?? null, + status: writes?.find((w) => w.path === d.path)?.status ?? null, + diff: d.changed || d.refused ? fileDiff(d) : null, + })), + skipped: plan.skipped, + }; +} + +export function runLearn(options: LearnOptions = {}): void { + let plan: TailPlan; + try { + plan = planLearnedTail(); + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)); + process.exitCode = 1; + return; + } + const dryRun = options.dryRun === true; + const writes = dryRun ? null : writeLearnedTail(plan); + if (writes?.some((w) => w.status === "refused")) process.exitCode = 1; + else if (writes) { + try { + recordTailRefresh(tailStatePath(), plan, writes); + } catch (err) { + console.error( + `learned tail written, but its state was not saved: ${err instanceof Error ? err.message : String(err)}`, + ); + process.exitCode = 1; + } + } + if (options.json) { + console.log(JSON.stringify(jsonReport(plan, writes), null, 2)); + return; + } + printText(plan, writes); +} diff --git a/src/commands/promote.ts b/src/commands/promote.ts new file mode 100644 index 00000000..8977ea20 --- /dev/null +++ b/src/commands/promote.ts @@ -0,0 +1,149 @@ +// recall promote — read-only list of learned-tail notes that meet the Lane B bar (#279). +// A note qualifies when it has been in the written tail for 14+ days (tracked in +// learned-tail-state.json) and has been seen in 3+ distinct projects, +// and the published GAP policy text does not already cover it. This command writes nothing. + +import { + findTailDestinations, + isCoveredByGap, + loadTailCandidates, + readGapCoverageText, + readTailState, + selectTail, + tailNoteKey, + tailStatePath, +} from "../lib/learned-tail.js"; +import type { TailCandidate, TailNote } from "../lib/learned-tail.js"; + +export const MIN_PROMOTE_PROJECTS = 3; +export const MIN_TAIL_DAYS = 14; +const DAY_MS = 24 * 60 * 60 * 1000; + +export interface PromoteOptions { + json?: boolean; + now?: Date; + home?: string; + path?: string; + dbPath?: string; +} + +export interface PromotionCandidate { + text: string; + records: Array<{ table: string; id: number }>; + projects: string[]; + firstSeen: string; + lastSeen: string; + daysInTail: number; +} + +export interface PromoteReport { + gap: boolean; + candidates: PromotionCandidate[]; + skipped: Array<{ text: string; reason: string }>; +} + +function seenMs(value: string): number | null { + const ms = Date.parse( + value.includes("T") ? value : value.replace(" ", "T") + "Z", + ); + return Number.isNaN(ms) ? null : ms; +} + +export function daysInTail(firstSeen: string, now: Date): number | null { + const ms = seenMs(firstSeen); + if (ms === null) return null; + return Math.floor((now.getTime() - ms) / DAY_MS); +} + +export function promotionCandidates( + notes: TailNote[], + gapText: string, + now: Date, + tailSince: Record = {}, +): { kept: PromotionCandidate[]; skipped: PromoteReport["skipped"] } { + const kept: PromotionCandidate[] = []; + const skipped: PromoteReport["skipped"] = []; + for (const note of notes) { + const since = tailSince[tailNoteKey(note.text)]; + const days = since ? daysInTail(since, now) : null; + const reason = + note.projects.length < MIN_PROMOTE_PROJECTS + ? `${note.projects.length} project${note.projects.length === 1 ? "" : "s"} (need ${MIN_PROMOTE_PROJECTS})` + : days === null + ? "not in the written tail yet" + : days < MIN_TAIL_DAYS + ? `${days} day${days === 1 ? "" : "s"} in the tail (need ${MIN_TAIL_DAYS})` + : isCoveredByGap(note.text, gapText) + ? "already covered by the GAP block" + : null; + if (reason) { + skipped.push({ text: note.text, reason }); + continue; + } + kept.push({ + text: note.text, + records: note.records, + projects: note.projects, + firstSeen: note.firstSeen, + lastSeen: note.lastSeen, + daysInTail: days as number, + }); + } + return { kept, skipped }; +} + +// Every qualifying note is listed so `skipped` explains each one; tail membership +// itself comes from the state file that each successful write records. +export function tailNotes(candidates: TailCandidate[]): TailNote[] { + return selectTail(candidates, { gapText: "", cap: false }).notes; +} + +export function planPromotion(options: PromoteOptions = {}): PromoteReport { + const now = options.now ?? new Date(); + const scan = findTailDestinations(options); + if (!scan.gap) return { gap: false, candidates: [], skipped: [] }; + const gapText = readGapCoverageText(scan.destinations.map((d) => d.path)); + const notes = tailNotes(loadTailCandidates(options.dbPath)); + const { tailSince } = readTailState(tailStatePath(options.dbPath)); + const { kept, skipped } = promotionCandidates(notes, gapText, now, tailSince); + return { gap: true, candidates: kept, skipped }; +} + +function printText(report: PromoteReport): void { + if (!report.gap) { + console.log( + "GAP is not installed. Promotion is a pull request on GAP, so there is nothing to list.", + ); + return; + } + console.log( + `${report.candidates.length} promotion candidate${report.candidates.length === 1 ? "" : "s"}`, + ); + for (const c of report.candidates) { + console.log(`- ${c.text}`); + console.log( + ` records: ${c.records.map((r) => `${r.table}#${r.id}`).join(", ")}`, + ); + console.log(` projects: ${c.projects.join(", ")}`); + console.log( + ` first seen: ${c.firstSeen} last seen: ${c.lastSeen} ${c.daysInTail} days`, + ); + } + if (report.candidates.length === 0) console.log("Nothing meets the bar."); +} + +export function runPromote(options: PromoteOptions = {}): void { + let report: PromoteReport; + try { + report = planPromotion(options); + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)); + process.exitCode = 1; + return; + } + if (options.json) { + console.log(JSON.stringify(report, null, 2)); + return; + } + printText(report); +} diff --git a/src/index.ts b/src/index.ts index ed9485ef..d7e4827d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,8 @@ import { runAge } from './commands/age.js'; import { runConsolidate } from './commands/consolidate.js'; import { DEFAULT_WINDOW_DAYS, DEFAULT_MIN_CLUSTER_SIZE } from './lib/consolidate.js'; import { runCluster } from './commands/cluster.js'; +import { runLearn } from './commands/learn.js'; +import { runPromote } from './commands/promote.js'; import { runEmbedBackfill, runRebackfill, runReindex, runSemanticSearch, runEmbedStats, runHybridSearch } from './commands/embed.js'; import { resolveQueryHarness, unqualifiedQueryRoute } from './lib/query-harness.js'; import { runDoctor } from './commands/doctor.js'; @@ -239,6 +241,27 @@ program closeDb(); }); +// recall learn — write the learned tail into each global harness file (#279). +// Dry-run prints the selection, destinations and diff and writes nothing. +program + .command('learn') + .description('Write the learned tail into each global harness file (writes only when the content changes)') + .option('--dry-run', 'Print the selection, destinations and diff without writing') + .option('--json', 'JSON output for scripting') + .action((options) => { + runLearn({ dryRun: options.dryRun, json: options.json }); + closeDb(); + }); + +// recall promote — read-only list of tail notes ready for a GAP pull request (#279). +program + .command('promote') + .description('List learned-tail notes that hold across projects and are ready to promote into GAP (read-only)') + .option('--json', 'JSON output for scripting') + .action((options) => { + runPromote({ json: options.json }); + closeDb(); + }); // recall search program .command('search ') @@ -918,7 +941,7 @@ program .option('-v, --vector', 'Use vector search only (semantic)') .option('--show-provenance', 'Show provenance for every result (default: only unknown provenance is flagged)') .action(async (query, options) => { - if (query && !['init', 'add', 'search', 'recent', 'show', 'stats', 'import', 'import-conversations', 'loa', 'telos', 'docs', 'dump', 'embed', 'semantic', 'hybrid', 'doctor', 'importance', 'provenance', 'pin', 'unpin', 'decision', 'prune', 'age', 'consolidate', 'cluster', 'import-legacy', 'scrub-archive', 'benchmark', 'onboard', 'migrate', 'path', 'export', 'dedup', 'repair', 'start', 'capture'].includes(query)) { + if (query && !['init', 'add', 'search', 'recent', 'show', 'stats', 'import', 'import-conversations', 'loa', 'telos', 'docs', 'dump', 'embed', 'semantic', 'hybrid', 'doctor', 'importance', 'provenance', 'pin', 'unpin', 'decision', 'prune', 'age', 'consolidate', 'cluster', 'learn', 'promote', 'import-legacy', 'scrub-archive', 'benchmark', 'onboard', 'migrate', 'path', 'export', 'dedup', 'repair', 'start', 'capture'].includes(query)) { const route = unqualifiedQueryRoute(options); if (route === 'keyword') { runSearch(query, { diff --git a/src/lib/learned-tail.ts b/src/lib/learned-tail.ts new file mode 100644 index 00000000..e7620eb8 --- /dev/null +++ b/src/lib/learned-tail.ts @@ -0,0 +1,46 @@ +// Single-source seam for the learned tail (#279) on the CLI + MCP (src/) side. +// The canonical implementation lives in hooks/lib/learned-tail.ts so the Stop hook +// can refresh the tail without importing src/. Import it from here on the src/ side; +// never reach into hooks/ directly and never duplicate the selection or splice logic. +export { + BUILTIN_TAIL_FILES, + GAP_BEGIN, + GAP_END, + MAX_BULLET_CHARS, + MAX_TAIL_BULLETS, + MAX_TAIL_TOKENS, + MIN_TAIL_IMPORTANCE, + RECALL_BEGIN, + RECALL_END, + TAIL_HEADER_PREFIX, + countRecordsSince, + findTailDestinations, + loadTailCandidates, + isCoveredByGap, + planLearnedTail, + readGapCoverageText, + readRecallBlock, + readTailState, + recordTailRefresh, + removeRecallBlock, + selectTail, + spliceRecallBlock, + tailNoteKey, + tailStatePath, + writeLearnedTail, +} from "../../hooks/lib/learned-tail.js"; +export type { + DroppedTailNote, + PlanTailOptions, + RecallBlockInfo, + SpliceResult, + TailCandidate, + TailDestination, + TailDestinationPlan, + TailDestinationScan, + TailNote, + TailPlan, + TailSelection, + TailState, + TailWriteResult, +} from "../../hooks/lib/learned-tail.js"; diff --git a/tests/hooks/learned-tail-stop.test.ts b/tests/hooks/learned-tail-stop.test.ts new file mode 100644 index 00000000..59cff5c8 --- /dev/null +++ b/tests/hooks/learned-tail-stop.test.ts @@ -0,0 +1,114 @@ +// The Stop hook refreshes the learned tail (#279) on every Stop, including the +// exits that never reach extraction, and a refused write keeps the old state. +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'child_process'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; +import { homedir, tmpdir } from 'os'; +import { join } from 'path'; + +const REPO = join(import.meta.dir, '..', '..'); +const CLI = join(REPO, 'src', 'index.ts'); +const HOOKS = join(REPO, 'hooks'); +const PRODUCTION_DB = join(homedir(), '.agents', 'Recall', 'recall.db'); +const NOTE = 'Run the migration dry-run before every schema change.'; +const DAY = 86_400_000; + +const roots: string[] = []; +const productionBefore = metadata(PRODUCTION_DB); + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); + expect(metadata(PRODUCTION_DB)).toEqual(productionBefore); +}); + +function metadata(path: string): { exists: boolean; size?: number; mtimeMs?: number } { + if (!existsSync(path)) return { exists: false }; + const stat = statSync(path); + return { exists: true, size: stat.size, mtimeMs: stat.mtimeMs }; +} + +function setup() { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-stop-')); + roots.push(root); + const hooks = join(root, 'installed', 'hooks'); + cpSync(HOOKS, hooks, { recursive: true }); + const bin = join(root, 'empty-bin'); + mkdirSync(bin, { recursive: true }); + // A minimal env: other suites leave Recall/Claude variables set in this process. + const env: NodeJS.ProcessEnv = { + TMPDIR: tmpdir(), + HOME: root, + PATH: `${bin}:${join(process.execPath, '..')}:/usr/bin:/bin`, + RECALL_DB_PATH: join(root, 'recall.db'), + RECALL_HOME: join(root, 'recall-home'), + RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', + }; + expect(spawnSync(process.execPath, [CLI, 'init'], { env, encoding: 'utf-8' }).status).toBe(0); + // Seed in a child process: other suites mock modules in this one. + const seed = spawnSync( + process.execPath, + [ + '-e', + `const { Database } = require('bun:sqlite'); + const db = new Database(process.argv[1]); + db.query("INSERT INTO decisions (created_at, project, decision, status, importance, provenance, access_count, confidence) VALUES (datetime('now'), 'alpha', ?, 'active', 9, 'extracted', 1, 'high')").run(process.argv[2]); + db.close();`, + join(root, 'recall.db'), + NOTE, + ], + { env, encoding: 'utf-8' }, + ); + expect(seed.status).toBe(0); + const claude = join(root, '.claude', 'CLAUDE.md'); + mkdirSync(join(root, '.claude'), { recursive: true }); + writeFileSync(claude, '# Mine\n'); + const nowhere = join(root, 'no-conversation'); + mkdirSync(nowhere, { recursive: true }); + const statePath = join(root, 'learned-tail-state.json'); + const stop = () => + spawnSync(process.execPath, [join(hooks, 'RecallExtract.ts')], { + input: JSON.stringify({ hook_event_name: 'Stop', session_id: 'tail-stop', cwd: nowhere }), + env, + encoding: 'utf-8', + timeout: 30_000, + }); + const state = () => JSON.parse(readFileSync(statePath, 'utf-8')) as { refreshedAt: number; tailSince: Record }; + return { claude, statePath, stop, state }; +} + +describe('learned tail from the Stop hook', () => { + test('a Stop with no conversation still refreshes, and a recent refresh is not repeated', () => { + const { claude, statePath, stop, state } = setup(); + expect(stop().status).toBe(0); + expect(readFileSync(claude, 'utf-8')).toContain(`- ${NOTE}`); + expect(readFileSync(claude, 'utf-8').startsWith('# Mine\n')).toBe(true); + const first = state(); + expect(first.refreshedAt).toBeGreaterThan(0); + expect(Object.keys(first.tailSince)).toHaveLength(1); + + writeFileSync(claude, '# Mine\n'); + expect(stop().status).toBe(0); + expect(readFileSync(claude, 'utf-8')).toBe('# Mine\n'); + + writeFileSync(statePath, JSON.stringify({ ...first, refreshedAt: Date.now() - 2 * DAY })); + expect(stop().status).toBe(0); + expect(readFileSync(claude, 'utf-8')).toContain(`- ${NOTE}`); + expect(state().tailSince).toEqual(first.tailSince); + }, 60_000); + + test('a refused write keeps the old refresh time so the next Stop retries', () => { + const { claude, statePath, stop, state } = setup(); + const old = Date.now() - 2 * DAY; + writeFileSync(statePath, JSON.stringify({ refreshedAt: old, tailSince: {} })); + const broken = '\n\n\n'; + writeFileSync(claude, broken); + expect(stop().status).toBe(0); + expect(readFileSync(claude, 'utf-8')).toBe(broken); + expect(state()).toEqual({ refreshedAt: old, tailSince: {} }); + + writeFileSync(claude, '# Mine\n'); + expect(stop().status).toBe(0); + expect(readFileSync(claude, 'utf-8')).toContain(`- ${NOTE}`); + expect(state().refreshedAt).toBeGreaterThan(old); + }, 60_000); +}); diff --git a/tests/install/npm-pack.test.ts b/tests/install/npm-pack.test.ts index 3bacb88f..0a911e32 100644 --- a/tests/install/npm-pack.test.ts +++ b/tests/install/npm-pack.test.ts @@ -74,12 +74,12 @@ describe('npm package: files whitelist', () => { // #235: the agent skills are the sole command surface since #228, so the pack // must ship every one — a partial pack (the pre-#230 failure mode) silently - // blanks the surface. Enumerate all 9 explicitly rather than trusting the - // agent-skills/ prefix alone (which passes with just 1 of 9 present). - test('bundles all 9 agent-skills//SKILL.md', () => { + // blanks the surface. Enumerate all 10 explicitly rather than trusting the + // agent-skills/ prefix alone (which passes with just 1 of 10 present). + test('bundles all 10 agent-skills//SKILL.md', () => { const skills = [ - 'do-recall-add', 'do-recall-doctor', 'do-recall-dump', 'do-recall-loa', 'do-recall-recent', - 'do-recall-scout', 'do-recall-search', 'do-recall-stats', 'do-recall-update', + 'do-recall-add', 'do-recall-doctor', 'do-recall-dump', 'do-recall-loa', 'do-recall-promote', + 'do-recall-recent', 'do-recall-scout', 'do-recall-search', 'do-recall-stats', 'do-recall-update', ]; for (const name of skills) { expect(has(`agent-skills/${name}/SKILL.md`)).toBe(true); diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 8034acee..0266a503 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -997,3 +997,42 @@ Preserve this. expect(result.stdout).not.toContain('Recall uninstalled successfully'); }); }); + +describe('learned-tail block removal', () => { + test('removes only the Recall pair from ledger and built-in files, skips paths outside HOME, and keeps a block that wraps GAP', () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-uninstall-')); + const home = join(root, 'home'); + const outside = join(root, 'outside', 'AGENTS.md'); + const inside = join(home, '.claude', 'rules', 'policy.md'); + const wrapped = join(home, '.pi', 'agent', 'APPEND_SYSTEM.md'); + const gap = '\nPolicy.\n\n'; + const pair = '\n- note\n\n'; + for (const file of [outside, inside, wrapped]) mkdirSync(dirname(file), { recursive: true }); + writeFileSync(inside, `# Head\n\n${gap}\n${pair}`); + writeFileSync(outside, `${gap}\n${pair}`); + const wrappedText = `\n- note\n${gap}\n`; + writeFileSync(wrapped, wrappedText); + const builtin = join(home, '.claude', 'CLAUDE.md'); + const cleaned = join(home, '.cursor', 'rules', 'old.mdc'); + for (const file of [builtin, cleaned]) mkdirSync(dirname(file), { recursive: true }); + writeFileSync(builtin, `# Mine\n\n${pair}`); + writeFileSync(cleaned, `# Old\n\n${pair}`); + const bare = join(home, '.codex', 'AGENTS.md'); + mkdirSync(dirname(bare), { recursive: true }); + writeFileSync(bare, `# Bare\n\n${pair.slice(0, -1)}`); + mkdirSync(join(home, '.gap'), { recursive: true }); + writeFileSync( + join(home, '.gap', 'published.json'), + JSON.stringify({ [inside]: 'h1', [outside]: 'h2', [wrapped]: 'h3', [cleaned]: 'cleaned' }), + ); + const result = runUninstall(home, join(root, 'backups')); + expect(result.status).toBe(0); + expect(readFileSync(inside, 'utf-8')).toBe(`# Head\n\n${gap}`); + expect(readFileSync(outside, 'utf-8')).toBe(`${gap}\n${pair}`); + expect(readFileSync(wrapped, 'utf-8')).toBe(wrappedText); + expect(readFileSync(builtin, 'utf-8')).toBe('# Mine\n'); + expect(readFileSync(cleaned, 'utf-8')).toBe('# Old\n'); + expect(readFileSync(bare, 'utf-8')).toBe('# Bare'); + expect(result.stdout + result.stderr).toContain('Preserved'); + }); +}); diff --git a/tests/learned-tail-embedding.test.ts b/tests/learned-tail-embedding.test.ts new file mode 100644 index 00000000..750d5f64 --- /dev/null +++ b/tests/learned-tail-embedding.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { closeDb, getDb } from "../src/db/connection.js"; +import { readTailState, tailNoteKey } from "../src/lib/learned-tail.js"; +import { + isolateTestHome, + setupTestDb, + teardownTestDb, +} from "./helpers/setup.js"; + +test("identical embeddings cannot merge contradictory rules or manufacture promotion projects", () => { + const restoreHome = isolateTestHome(); + const saved = { + PATH: process.env.PATH, + RECALL_HOME: process.env.RECALL_HOME, + }; + try { + const dbPath = setupTestDb(); + const home = process.env.HOME!; + process.env.RECALL_HOME = join(home, ".agents", "Recall"); + mkdirSync(process.env.RECALL_HOME, { recursive: true }); + const bin = join(home, "bin"); + mkdirSync(bin); + writeFileSync(join(bin, "gap"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.PATH = bin; + const policy = join(home, ".gap", "policy.md"); + mkdirSync(dirname(policy), { recursive: true }); + writeFileSync( + policy, + "\nKeep commands reliable.\n\n", + ); + writeFileSync( + join(home, ".gap", "published.json"), + JSON.stringify({ [policy]: "published" }), + ); + const db = getDb(); + const texts = [ + "Run tests before deploying production.", + "Run tests after deploying production.", + "Run tests after deploying production.", + ]; + const projects = ["alpha", "bravo", "charlie"]; + const vector = new Float32Array([1, 0, 0]); + for (let i = 0; i < texts.length; i++) { + const row = db + .query( + "INSERT INTO decisions (project, decision, status, importance, provenance, confidence) VALUES (?, ?, 'active', 9, 'user_authored', 'high')", + ) + .run(projects[i]!, texts[i]!); + db.query( + "INSERT INTO embeddings (source_table, source_id, dimensions, embedding) VALUES ('decisions', ?, 3, ?)", + ).run(row.lastInsertRowid, new Uint8Array(vector.buffer)); + } + closeDb(); + const cli = (args: string[]) => { + const result = spawnSync( + process.execPath, + [join(process.cwd(), "src/index.ts"), ...args], + { env: process.env, encoding: "utf8", timeout: 30_000 }, + ); + expect(result.status).toBe(0); + return JSON.parse(result.stdout); + }; + const learned = cli(["learn", "--json"]); + expect(learned.selection.notes).toHaveLength(2); + for (const text of new Set(texts)) + expect(readFileSync(policy, "utf8")).toContain(text); + const statePath = join(dirname(dbPath), "learned-tail-state.json"); + const state = readTailState(statePath); + const since = new Date(Date.now() - 20 * 86_400_000).toISOString(); + writeFileSync( + statePath, + JSON.stringify({ + ...state, + tailSince: Object.fromEntries( + texts.map((text) => [tailNoteKey(text), since]), + ), + }), + ); + const promoted = cli(["promote", "--json"]); + expect(promoted.candidates).toEqual([]); + expect( + promoted.skipped.map((note: { reason: string }) => note.reason).sort(), + ).toEqual(["1 project (need 3)", "2 projects (need 3)"]); + } finally { + closeDb(); + teardownTestDb(); + restoreHome(); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +}); diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts new file mode 100644 index 00000000..779de020 --- /dev/null +++ b/tests/learned-tail.test.ts @@ -0,0 +1,499 @@ +// End-to-end learned tail (#279) through the real `recall` CLI. +// Disposable HOME, RECALL_HOME and RECALL_DB_PATH; the production database +// hash is proven unchanged. See tests/AGENTS.md. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { delimiter, dirname, join } from "node:path"; +import { closeDb, getDb } from "../src/db/connection.js"; +import { + countRecordsSince, + isCoveredByGap, + readTailState, + selectTail, + recordTailRefresh, + removeRecallBlock, + spliceRecallBlock, + tailNoteKey, +} from "../src/lib/learned-tail.js"; +import type { TailCandidate, TailPlan } from "../src/lib/learned-tail.js"; +import { + isolateTestHome, + setupTestDb, + teardownTestDb, +} from "./helpers/setup.js"; + +const REPO = process.cwd(); +const CLI = join(REPO, "src/index.ts"); +const NOTE = "Validate user input at the boundary before processing."; +const FIRST_SEEN = "2026-10-01 12:00:00"; + +const PRODUCTION_DB = join( + process.env.HOME ?? "", + ".agents", + "Recall", + "recall.db", +); + +let restoreHome: () => void; +let home: string; +let dbPath: string; +let bin: string; +let productionHash: string | null; +let savedEnv: { PATH?: string; RECALL_HOME?: string }; + +function sha256(path: string): string | null { + try { + return createHash("sha256").update(readFileSync(path)).digest("hex"); + } catch { + return null; + } +} + +function recall( + args: string[], + env: NodeJS.ProcessEnv = process.env, +): { status: number | null; stdout: string; stderr: string } { + const result = spawnSync(process.execPath, [CLI, ...args], { + cwd: REPO, + encoding: "utf8", + env, + timeout: 30_000, + }); + return { + status: result.status, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; +} + +function seed(): void { + const db = getDb(); + const insert = db.query( + `INSERT INTO decisions + (created_at, project, decision, status, importance, provenance, access_count, confidence) + VALUES (?, ?, ?, 'active', 9, 'extracted', 1, 'high')`, + ); + for (const project of ["alpha", "bravo", "charlie"]) { + insert.run(FIRST_SEEN, project, NOTE); + } + closeDb(); +} + +function writePolicy( + file: string, + gapBody = "Keep commands reliable.", +): Buffer { + mkdirSync(dirname(file), { recursive: true }); + const bytes = Buffer.from( + `# Project policy\n\n\n${gapBody}\n\n\nUser-owned tail.\n`, + "utf8", + ); + writeFileSync(file, bytes); + return bytes; +} + +function publish(file: string): void { + const dir = join(home, ".gap"); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, "published.json"), + JSON.stringify({ [file]: "published" }), + ); +} + +function existsFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} + +describe("learned tail end to end", () => { + beforeEach(() => { + productionHash = sha256(PRODUCTION_DB); + savedEnv = { PATH: process.env.PATH, RECALL_HOME: process.env.RECALL_HOME }; + restoreHome = isolateTestHome(); + home = process.env.HOME as string; + dbPath = setupTestDb(); + const recallHome = join(home, ".agents", "Recall"); + mkdirSync(recallHome, { recursive: true }); + process.env.RECALL_HOME = recallHome; + bin = join(home, "bin"); + mkdirSync(bin, { recursive: true }); + writeFileSync(join(bin, "gap"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.PATH = `${bin}${delimiter}${dirname(process.execPath)}`; + seed(); + }); + + afterEach(() => { + expect(sha256(PRODUCTION_DB)).toBe(productionHash); + teardownTestDb(); + restoreHome(); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + + test("(a)(b) learn writes the Recall pair, and a second learn with no change writes nothing", () => { + const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const original = writePolicy(policy); + publish(policy); + + const first = recall(["learn", "--json"]); + expect(first.status).toBe(0); + const written = readFileSync(policy); + const text = written.toString("utf8"); + const begin = text.indexOf(""); + const end = text.indexOf(""); + expect(begin).toBeGreaterThan(-1); + expect(end).toBeGreaterThan(begin); + expect(text.slice(begin, end)).toContain(`- ${NOTE}`); + // The pair is appended after the original file, which already ends in a newline. + expect(written.subarray(0, original.length).equals(original)).toBe(true); + + const plan = JSON.parse(first.stdout) as { + gap: boolean; + destinations: Array<{ + path: string; + source: string; + status: string | null; + }>; + }; + expect(plan.gap).toBe(true); + expect(plan.destinations.map((d) => [d.path, d.source, d.status])).toEqual([ + [policy, "gap", "written"], + ]); + + const mtime = statSync(policy).mtimeMs; + const second = recall(["learn", "--json"]); + expect(second.status).toBe(0); + expect(readFileSync(policy).equals(written)).toBe(true); + expect(statSync(policy).mtimeMs).toBe(mtime); + const again = JSON.parse(second.stdout) as { + destinations: Array<{ status: string | null; changed: boolean }>; + }; + expect(again.destinations).toEqual([ + expect.objectContaining({ status: "unchanged", changed: false }), + ]); + }); + + test("(c) with no gap on PATH only an existing built-in harness file changes", () => { + const claude = join(home, ".claude", "CLAUDE.md"); + const unrelated = join(home, "notes.md"); + mkdirSync(dirname(claude), { recursive: true }); + writeFileSync(claude, "Claude instructions\n"); + writeFileSync(unrelated, "Leave this alone\n"); + const empty = join(home, "empty-path"); + mkdirSync(empty, { recursive: true }); + + const result = recall(["learn", "--json"], { + ...process.env, + PATH: `${empty}${delimiter}${dirname(process.execPath)}`, + }); + expect(result.status).toBe(0); + const report = JSON.parse(result.stdout) as { + gap: boolean; + destinations: Array<{ path: string; status: string | null }>; + }; + expect(report.gap).toBe(false); + expect(report.destinations.map((d) => d.path)).toEqual([claude]); + expect(report.destinations[0]?.status).toBe("written"); + expect(readFileSync(claude, "utf8")).toContain(""); + expect(readFileSync(claude, "utf8")).toContain(NOTE); + expect(readFileSync(unrelated, "utf8")).toBe("Leave this alone\n"); + for (const rel of [ + ".codex/AGENTS.md", + ".pi/agent/APPEND_SYSTEM.md", + ".omp/agent/APPEND_SYSTEM.md", + ".empryo/EMPRYO.md", + ]) { + expect(existsFile(join(home, rel))).toBe(false); + } + }); + + test("(d) promote needs 14 days in the written tail, and learn drops a note once the GAP block covers it", () => { + const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + writePolicy(policy); + publish(policy); + const statePath = join(dirname(dbPath), "learned-tail-state.json"); + + const before = JSON.parse(recall(["promote", "--json"]).stdout) as { + candidates: unknown[]; + skipped: Array<{ text: string; reason: string }>; + }; + expect(before.candidates).toEqual([]); + expect(before.skipped).toEqual([ + { text: NOTE, reason: "not in the written tail yet" }, + ]); + + expect(recall(["learn"]).status).toBe(0); + const state = readTailState(statePath); + const key = tailNoteKey(NOTE); + expect(Object.keys(state.tailSince)).toEqual([key]); + + const fresh = JSON.parse(recall(["promote", "--json"]).stdout) as { + candidates: unknown[]; + skipped: Array<{ text: string; reason: string }>; + }; + expect(fresh.candidates).toEqual([]); + expect(fresh.skipped[0]?.reason).toBe("0 days in the tail (need 14)"); + + const since = new Date(Date.now() - 20 * 86_400_000).toISOString(); + writeFileSync( + statePath, + JSON.stringify({ ...state, tailSince: { [key]: since } }), + ); + const listed = recall(["promote", "--json"]); + expect(listed.status).toBe(0); + const report = JSON.parse(listed.stdout) as { + gap: boolean; + candidates: Array<{ + text: string; + projects: string[]; + daysInTail: number; + }>; + }; + expect(report.gap).toBe(true); + const hit = report.candidates.find((c) => c.text === NOTE); + expect(hit?.projects).toEqual(["alpha", "bravo", "charlie"]); + expect(hit?.daysInTail).toBe(20); + + writePolicy(policy, `Keep commands reliable.\n\n- ${NOTE}`); + const learned = recall(["learn", "--json"]); + expect(learned.status).toBe(0); + const plan = JSON.parse(learned.stdout) as { + selection: { + notes: Array<{ text: string }>; + dropped: Array<{ reason: string }>; + }; + destinations: Array<{ changed: boolean }>; + }; + expect(plan.selection.notes).toEqual([]); + expect(plan.selection.dropped.some((d) => d.reason === "covered")).toBe( + true, + ); + expect(readFileSync(policy, "utf8")).not.toContain(""); + expect(readTailState(statePath).tailSince).toEqual({}); + + const after = JSON.parse(recall(["promote", "--json"]).stdout) as { + candidates: unknown[]; + skipped: Array<{ text: string; reason: string }>; + }; + expect(after.candidates).toEqual([]); + expect(after.skipped).toEqual([ + { text: NOTE, reason: "not in the written tail yet" }, + ]); + }); + + test("(f) a Recall block wrapped around the GAP block is refused and the file is untouched", () => { + const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + mkdirSync(dirname(policy), { recursive: true }); + const wrapped = + "\n- old\n\nPolicy.\n\n\n"; + writeFileSync(policy, wrapped); + publish(policy); + const result = recall(["learn", "--json"]); + expect(result.status).toBe(1); + const report = JSON.parse(result.stdout) as { + destinations: Array<{ refused: string | null; status: string | null }>; + }; + expect(report.destinations[0]?.refused).toContain("wraps a GAP marker"); + expect(report.destinations[0]?.status).toBe("refused"); + expect(readFileSync(policy, "utf8")).toBe(wrapped); + expect(removeRecallBlock(wrapped).ok).toBe(false); + expect(spliceRecallBlock(wrapped, [], "2026-01-01").ok).toBe(false); + expect(existsFile(join(dirname(dbPath), "learned-tail-state.json"))).toBe( + false, + ); + }); + + test("(g) coverage needs the same rule, ignoring only case, spacing, list marker and end punctuation", () => { + const gap = "Always disable cert checks in local fixtures."; + expect( + isCoveredByGap("Never disable cert checks in local fixtures.", gap), + ).toBe(false); + expect( + isCoveredByGap("Don't disable cert checks in local fixtures.", gap), + ).toBe(false); + expect(isCoveredByGap("Disable cert checks in local fixtures.", gap)).toBe( + false, + ); + expect( + isCoveredByGap("disable cert checks", "Never disable cert checks."), + ).toBe(false); + expect( + isCoveredByGap( + "Never disable cert checks.", + "Never disable cert checks.", + ), + ).toBe(true); + const after = "Run tests after deploying production."; + expect( + isCoveredByGap("Run tests before deploying production.", after), + ).toBe(false); + expect( + isCoveredByGap( + "Deploying production before run tests.", + "Run tests before deploying production.", + ), + ).toBe(false); + expect( + isCoveredByGap( + "Run tests before deploying production.", + `- ${after}\n- Run tests before deploying production.`, + ), + ).toBe(true); + expect( + isCoveredByGap("Use == for comparisons.", "Use === for comparisons."), + ).toBe(false); + expect( + isCoveredByGap("Use === for comparisons.", "Use == for comparisons."), + ).toBe(false); + expect(isCoveredByGap("Use `x!` here.", "Use `x?` here.")).toBe(false); + expect( + isCoveredByGap( + "use === FOR comparisons", + "1. Use === for comparisons.", + ), + ).toBe(true); + expect( + isCoveredByGap("Keep it short.", "Plan first. Keep it short. Ship."), + ).toBe(true); + }); + + test("(j) close wording of a different rule stays its own note, with its own projects", () => { + const base = { + importance: 9, + provenance: "user_authored", + confidence: "high", + accessCount: 1, + sessionId: "s", + createdAt: FIRST_SEEN, + }; + const row = (id: number, text: string, project: string): TailCandidate => ({ + ...base, + table: "learnings", + id, + text, + project, + }); + const { notes, dropped } = selectTail( + [ + row(1, "Use == for comparisons.", "alpha"), + row(2, "Use === for comparisons.", "bravo"), + row(3, "Use === for comparisons.", "charlie"), + ], + { cap: false }, + ); + const texts = notes.map((n) => n.text).sort(); + expect(texts).toEqual([ + "Use == for comparisons.", + "Use === for comparisons.", + ]); + expect( + notes.find((n) => n.text === "Use === for comparisons.")?.projects, + ).toEqual(["bravo", "charlie"]); + expect( + notes.find((n) => n.text === "Use == for comparisons.")?.projects, + ).toEqual(["alpha"]); + expect(dropped.filter((d) => d.reason === "duplicate")).toHaveLength(1); + }); + + test("(i) a file without a final newline round-trips byte for byte through write, rewrite and removal", () => { + const one = [{ text: "Use === for comparisons." }] as unknown as Parameters< + typeof spliceRecallBlock + >[1]; + const two = [ + { text: "Use === for comparisons." }, + { text: "Keep it short." }, + ] as unknown as Parameters[1]; + const gap = "\nPolicy.\n"; + for (const original of [ + "", + "# Mine", + "# Mine\n", + "# Mine\n\n", + gap, + `${gap}\n`, + "a\r\nb", + ]) { + const first = spliceRecallBlock(original, one, "2026-01-01"); + if (!first.ok) throw new Error(first.reason); + expect(first.text.startsWith(original)).toBe(true); + const again = spliceRecallBlock(first.text, one, "2026-01-02"); + expect(again.ok && again.changed).toBe(false); + const rewritten = spliceRecallBlock(first.text, two, "2026-01-03"); + if (!rewritten.ok) throw new Error(rewritten.reason); + for (const text of [first.text, rewritten.text]) { + const removed = removeRecallBlock(text); + expect(removed.ok && removed.text).toBe(original); + const emptied = spliceRecallBlock(text, [], "2026-01-04"); + expect(emptied.ok && emptied.text).toBe(original); + } + } + }); + + test("(h) refresh counts records from the database, a refused write keeps the old state, and only a landed write starts a note's tail age", () => { + const statePath = join(dirname(dbPath), "learned-tail-state.json"); + expect(countRecordsSince(0, dbPath)).toBe(3); + expect(countRecordsSince(Date.now() + 60_000, dbPath)).toBe(0); + const plan = { + selection: { notes: [], dropped: [], tokens: 0 }, + } as unknown as TailPlan; + expect( + recordTailRefresh(statePath, plan, [ + { path: "/x", status: "refused", reason: "changed" }, + ]), + ).toBe(false); + expect(existsFile(statePath)).toBe(false); + const withNote = { + selection: { notes: [{ text: NOTE }], dropped: [], tokens: 0 }, + } as unknown as TailPlan; + expect(recordTailRefresh(statePath, withNote, [])).toBe(true); + expect(readTailState(statePath).refreshedAt).toBeGreaterThan(0); + expect(readTailState(statePath).tailSince).toEqual({}); + expect( + recordTailRefresh(statePath, withNote, [ + { path: "/x", status: "written" }, + ]), + ).toBe(true); + expect(Object.keys(readTailState(statePath).tailSince)).toEqual([ + tailNoteKey(NOTE), + ]); + }); + + test("(e) uninstall block removal leaves the surrounding bytes byte for byte", () => { + const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const original = writePolicy(policy); + publish(policy); + expect(recall(["learn"]).status).toBe(0); + + const withBlock = readFileSync(policy); + const text = withBlock.toString("utf8"); + const removed = removeRecallBlock(text); + expect(removed.ok).toBe(true); + if (!removed.ok) return; + const out = Buffer.from(removed.text, "utf8"); + + const marker = Buffer.from(""); + const at = withBlock.indexOf(marker); + expect(at).toBeGreaterThan(1); + const head = at - 1; + expect(withBlock.subarray(0, head).equals(original.subarray(0, head))).toBe( + true, + ); + expect(out.subarray(0, head).equals(original.subarray(0, head))).toBe(true); + const tail = original.subarray(head); + expect( + withBlock.subarray(withBlock.length - tail.length).equals(tail), + ).toBe(true); + expect(out.subarray(out.length - tail.length).equals(tail)).toBe(true); + expect(out.equals(Buffer.concat([original.subarray(0, head), tail]))).toBe( + true, + ); + }); +}); diff --git a/tests/plugins/claude-plugin.test.ts b/tests/plugins/claude-plugin.test.ts index 69f46735..3e98fe57 100644 --- a/tests/plugins/claude-plugin.test.ts +++ b/tests/plugins/claude-plugin.test.ts @@ -44,7 +44,7 @@ describe('Claude native plugin package', () => { test('checked-in skills are byte-verbatim copies of the canonical sources', () => { tempDir = mkdtempSync(join(tmpdir(), 'recall-claude-skills-')); const names = generateClaudePluginSkills(tempDir); - expect(names).toHaveLength(9); + expect(names).toHaveLength(10); for (const name of names) { const canonical = readFileSync(join(repoRoot, 'agent-skills', name, 'SKILL.md'), 'utf-8'); const generated = readFileSync(join(tempDir, name, 'SKILL.md'), 'utf-8'); diff --git a/tests/plugins/codex-plugin.test.ts b/tests/plugins/codex-plugin.test.ts index 55cbea90..1a987139 100644 --- a/tests/plugins/codex-plugin.test.ts +++ b/tests/plugins/codex-plugin.test.ts @@ -57,7 +57,7 @@ describe('Codex native plugin package', () => { test('checked-in Codex skill adapters exactly match generated output', () => { tempDir = mkdtempSync(join(tmpdir(), 'recall-codex-skills-')); const names = generateCodexPluginSkills(tempDir); - expect(names).toHaveLength(9); + expect(names).toHaveLength(10); for (const name of names) { const expected = readFileSync(join(tempDir, name, 'SKILL.md'), 'utf-8'); const actual = readFileSync( diff --git a/todo.txt b/todo.txt index d4dd8a6e..616af259 100644 --- a/todo.txt +++ b/todo.txt @@ -3,7 +3,7 @@ 2026-10-09 Optional hook: Sentinel session capture and LOA score. Idea; optional Sentinel hook. +recall @outstanding issue:286 2026-10-09 Recall Telos interview slash (copy PAI process, not the stack). Parked per spec; no wiring. +recall @outstanding issue:281 2026-10-09 Slash-export windowed learnings to a user-chosen Obsidian folder. Parked; learnings-only export. +recall @outstanding issue:280 -2026-10-09 Learn prefs into global AGENTS.md (and CLAUDE.md) below a Recall marker. Not started. +recall @outstanding issue:279 +2026-10-09 Learn prefs into global AGENTS.md (#279): built and tested, uncommitted. Ship: commit Recall + GAP branch recall-block-rule, PR, then go install gap and recall update +recall @outstanding issue:279 note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-20-learned-tail-and-gap-promote-plan.md x 2026-10-17 2026-10-09 CREATE_TABLES lags migrations: decisions/learnings missing confidence. Confirmed on main: decisions/learnings CREATE TABLE lack confidence. +recall @outstanding issue:278 pr:https://github.com/edheltzel/Recall/pull/332 x 2026-10-19 2026-10-09 templates/mcp.json.template still registers mem-mcp. Confirmed on main: templates/mcp.json.template still uses mem-mcp. +recall @outstanding issue:277 @waiting gate parked pr:https://github.com/edheltzel/Recall/pull/338 2026-10-09 Collapse host identity lists toward SESSION_SOURCES. #282 added cursor to SESSION_SOURCES only; lists not collapsed. +recall @outstanding issue:269 @@ -72,3 +72,15 @@ x 2026-10-19 2026-10-19 Commit the omp Curated LoA convergence fix and push feat 2026-10-19 Empryo: installer registers recall-memory MCP in ~/.empryo/config.json (array mcpServers) +recall branch:feat/empryo-adapter note:/Users/ed/Developer/Atlas/Recall/docs/EMPRYO_INTEGRATION.md 2026-10-19 Empryo: verify whether SessionStart additionalContext from RecallStart reaches the model +recall note:/Users/ed/Developer/Atlas/Recall/docs/EMPRYO_INTEGRATION.md 2026-10-19 recall search: hyphenated query (Atlas-Key) fails with FTS 'no such column: Key' +recall +2026-10-19 Reproduce and fix archive-scrub test TZ mismatch (bun test UTC vs spawned hook local) +recall note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-10-19-archive-scrub-tz-repro-plan.md +2026-10-19 Empryo Stop: replace the 10-minute recent-tab window with a per-session sent-turn watermark +recall note:/Users/ed/Developer/Atlas/Recall/docs/EMPRYO_INTEGRATION.md +2026-10-24 Drive recall browse in a real terminal: arrow keys, filter, open a row. Web dashboard stays issue:221. +recall +x 2026-11-06 2026-11-06 After site PR approval, create the recall Pages app building Recall site/ +recall @cloudflare note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-06-site-cloudflare-cutover.md +x 2026-11-06 2026-11-06 Move recall.edheltzel.codes to the recall Pages app and verify HTTPS, docs, redirects +recall @cloudflare note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-06-site-cloudflare-cutover.md +x 2026-11-06 2026-11-06 Redirect recall-site-0n5.pages.dev to recall.edheltzel.codes, then archive edheltzel/recall-site +recall note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-06-site-cloudflare-cutover.md +2026-11-11 Commit and publish the gum input fix: Database path prompt was invisible (2>/dev/null hid gum UI) +recall +2026-11-11 Install Recall via GAP once the GAP component API ships: gap.toml install --yes, guard recall update inside ~/.gap/store, re-pin to main +recall @waiting GAP component API (gap-component.toml) not built yet +x 2026-11-20 2026-11-20 Confirm #279 decisions: begin/end pair, 600-token cap, Lane B bar, PR-only promote +recall id:recall-tail-decide issue:279 note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-20-learned-tail-and-gap-promote-plan.md +x 2026-11-20 2026-11-20 Build learned tail core + recall learn (Phase 1) +recall id:recall-tail dep:recall-tail-decide issue:279 note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-20-learned-tail-and-gap-promote-plan.md +x 2026-11-20 2026-11-20 Build recall promote + do-recall-promote skill (Phase 2) +recall id:recall-promote dep:recall-tail issue:279 note:/Users/ed/Developer/Atlas/Recall/.agents/atlas/plans/2026-11-20-learned-tail-and-gap-promote-plan.md +x 2026-11-21 2026-11-21 Fix learned-tail embedding merges and false promotion evidence; CLI regression with identical vectors; 1836 Bun tests and lint pass +recall issue:279 id:recall-tail-dedup-fix GAP full go test ./... also passes (281s; earlier limits were too short) diff --git a/tsconfig.json b/tsconfig.json index d5011cd2..b367a819 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,7 +8,7 @@ "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "dist", - "rootDir": "src", + "rootDir": ".", "declaration": true, "declarationDir": "dist", "resolveJsonModule": true From 59e02c4809ab4ae4f71858479a3c9348af178c83 Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:03:33 -0500 Subject: [PATCH 02/12] fix(learn): address Pullfrog review of the learned tail - tail: qualify extracted notes that recur in 2+ sessions; Stop test goes through real extraction - promote: count tail age only while the note is in a Recall block written now; reset it on write-back - tail: keep case inside backticks when grouping, checking GAP coverage and keying age - tail: write only to GAP policy destinations, honoring absolute CODEX_HOME and JCODE_HOME - uninstall: reuse the learn parser and checked temp-file rename; refuse pairs inside any GAP block Co-authored-by: Mr. ED --- agent-skills/do-recall-promote/SKILL.md | 2 +- docs/cli-reference.md | 4 +- hooks/lib/learned-tail.ts | 219 ++++++++++++++---- .../skills/do-recall-promote/SKILL.md | 2 +- .../recall/skills/do-recall-promote/SKILL.md | 2 +- packaging/uninstall.sh | 110 ++------- src/commands/promote.ts | 22 +- src/lib/learned-tail.ts | 9 + tests/hooks/learned-tail-stop.test.ts | 80 ++++++- tests/install/uninstall.test.ts | 32 ++- tests/learned-tail-embedding.test.ts | 3 +- tests/learned-tail.test.ts | 167 ++++++++++++- 12 files changed, 485 insertions(+), 167 deletions(-) diff --git a/agent-skills/do-recall-promote/SKILL.md b/agent-skills/do-recall-promote/SKILL.md index 3bfd7b0d..5b4e3874 100644 --- a/agent-skills/do-recall-promote/SKILL.md +++ b/agent-skills/do-recall-promote/SKILL.md @@ -7,7 +7,7 @@ Turn Recall notes that hold across projects into a reviewed change to the shared ## What this does -1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, seen in 3 or more distinct projects, in a Recall block written now and for 14 or more days, and not already covered by a published GAP policy file. 2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. 3. Opens a pull request and stops. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index e6612ea4..d94941eb 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -631,9 +631,9 @@ recall cluster --execute --threshold 0.9 ### Learned tail -`recall learn` writes Recall's best notes (active, high confidence, importance 8+ or user-authored, at most 15 bullets and 600 tokens) into a `` ... `` block in each global harness file. With GAP installed it writes to GAP's published policy files; otherwise to the built-in harness files that already exist. Only the Recall block changes, and a rerun with no change writes nothing. The Stop hook refreshes it on its own. +`recall learn` writes Recall's best notes into a `` ... `` block in each global harness file, at most 15 bullets and 600 tokens. A note qualifies when it is active, not low confidence, and either has a high-confidence record at importance 8+ (or user-authored) or recurs word for word in 2+ sessions, which is how notes saved at session end reach the tail. Text in backticks keeps its case when notes are compared. With GAP installed it writes to the policy files GAP publishes (`CODEX_HOME` and `JCODE_HOME` included), never to its command files; otherwise to the built-in harness files that already exist. Only the Recall block changes, and a rerun with no change writes nothing. The Stop hook refreshes it on its own. -`recall promote` is read-only. It lists notes seen in 3+ projects that have been in the written tail for 14+ days and are not already in the GAP block. The `do-recall-promote` skill turns the accepted ones into a GAP pull request. +`recall promote` is read-only. It lists notes seen in 3+ projects that are in a Recall block written now, have been there for 14+ days, and are not already in the GAP block. A note removed from every destination starts a new 14 days when it is written back. The `do-recall-promote` skill turns the accepted ones into a GAP pull request. ```bash recall learn --dry-run diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 05087f50..f2de7720 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -27,7 +27,6 @@ import { dirname, isAbsolute, join, - relative, } from "node:path"; import { resolveDbPath } from "./db-path"; import { detectThreats } from "./threat-detect"; @@ -41,7 +40,15 @@ export const MAX_TAIL_TOKENS = 600; export const MAX_TAIL_BULLETS = 15; export const MAX_BULLET_CHARS = 200; export const MIN_TAIL_IMPORTANCE = 8; +export const MIN_TAIL_SESSIONS = 2; export const TAIL_HEADER_PREFIX = "Written by Recall, last updated "; +export const GAP_POLICY_FILES = [ + ".claude/rules/global-agent-policy.md", + ".pi/agent/APPEND_SYSTEM.md", + ".omp/agent/APPEND_SYSTEM.md", + ".cursor/rules/global-agent-policy.mdc", + ".empryo/EMPRYO.md", +]; export const BUILTIN_TAIL_FILES = [ ".claude/CLAUDE.md", ".codex/AGENTS.md", @@ -85,7 +92,14 @@ export interface TailNote { } export type TailDropReason = - "secret" | "threat" | "unsafe" | "length" | "duplicate" | "covered" | "cap"; + | "secret" + | "threat" + | "unsafe" + | "length" + | "duplicate" + | "unproven" + | "covered" + | "cap"; export interface DroppedTailNote { key: string; @@ -106,6 +120,8 @@ export type BulletCheck = export interface TailEnv { home?: string; path?: string; + codexHome?: string; + jcodeHome?: string; } export interface TailDestination { @@ -231,10 +247,7 @@ export function loadTailCandidates( ); if (![...REQUIRED_COLUMNS, ...spec.columns].every((c) => cols.has(c))) continue; - const where = [ - "t.confidence = 'high'", - `(t.importance >= ${MIN_TAIL_IMPORTANCE} OR t.provenance = 'user_authored')`, - ]; + const where = ["t.confidence IN ('high', 'medium')"]; if (cols.has("status")) where.push("t.status = 'active'"); if (tables.has("dedup_lineage")) { where.push( @@ -320,10 +333,15 @@ export function sanitizeTailBullet(raw: string): BulletCheck { return { ok: true, text }; } -function matchForm(text: string): string { +function foldCase(text: string): string { return text - .normalize("NFKC") - .toLowerCase() + .split(/(`[^`]*`)/) + .map((part, i) => (i % 2 === 1 ? part : part.toLowerCase())) + .join(""); +} + +function matchForm(text: string): string { + return foldCase(text.normalize("NFKC")) .trim() .replace(/^(?:[-*+]|\d+[.)])\s+/, "") .replace(/[.!?;:,]+$/, "") @@ -340,6 +358,13 @@ export function isCoveredByGap(note: string, gapText: string): boolean { .some((unit) => matchForm(unit) === n); } +function provenRecord(c: TailCandidate): boolean { + return ( + c.confidence === "high" && + (c.importance >= MIN_TAIL_IMPORTANCE || c.provenance === "user_authored") + ); +} + function candidateKey(c: { table: TailTable; id: number }): string { return `${c.table}:${c.id}`; } @@ -410,7 +435,19 @@ export function selectTail( } } - const ranked: TailNote[] = clusters + const proven = clusters.filter(({ lead, members }) => { + const sessions = new Set(members.map((m) => m.sessionId ?? candidateKey(m))); + if (members.some(provenRecord) || sessions.size >= MIN_TAIL_SESSIONS) + return true; + dropped.push({ + key: candidateKey(lead), + reason: "unproven", + detail: `1 session, needs ${MIN_TAIL_SESSIONS} or a high-confidence note at importance ${MIN_TAIL_IMPORTANCE}+`, + }); + return false; + }); + + const ranked: TailNote[] = proven .map(({ lead, members }) => { const created = members.map((m) => m.createdAt).sort(compareText); return { @@ -515,35 +552,39 @@ function allMarkerLines(text: string, marker: string): Array<[number, number]> { } } -function gapSpan( - text: string, -): { start: number; innerStart: number; innerEnd: number; end: number } | null { - let span: { - start: number; - innerStart: number; - innerEnd: number; - end: number; - } | null = null; +interface GapSpan { + start: number; + innerStart: number; + innerEnd: number; + end: number; +} + +function gapSpans(text: string): GapSpan[] { + const spans: GapSpan[] = []; for (let from = 0; ;) { let begin = findMarkerLine(text, GAP_BEGIN, from); - if (!begin) return span; + if (!begin) return spans; const end = findMarkerLine(text, GAP_END, begin[1]); - if (!end) return span; + if (!end) return spans; for (;;) { const next = findMarkerLine(text, GAP_BEGIN, begin[1]); if (!next || next[0] >= end[0]) break; begin = next; } - span = { + spans.push({ start: begin[0], innerStart: begin[1], innerEnd: end[0], end: end[1], - }; + }); from = end[1]; } } +function gapSpan(text: string): GapSpan | null { + return gapSpans(text).at(-1) ?? null; +} + export function gapBlockText(text: string): string | null { const span = gapSpan(text); return span ? text.slice(span.innerStart, span.innerEnd) : null; @@ -587,12 +628,9 @@ function recallSpan(text: string): RecallSpan { reason: "Recall block wraps a GAP marker", }; } - const gap = gapSpan(text); - if ( - gap && - ((begin[0] >= gap.start && begin[0] < gap.end) || - (end[0] >= gap.start && end[0] < gap.end)) - ) { + const inside = (at: number) => + gapSpans(text).some((gap) => at >= gap.start && at < gap.end); + if (inside(begin[0]) || inside(end[0])) { return { kind: "malformed", reason: "Recall marker sits inside the GAP block", @@ -737,11 +775,6 @@ function regularFileProblem(path: string): string | null { } } -function insideHome(home: string, path: string): boolean { - const rel = relative(home, path); - return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); -} - function resolveEnv(env: TailEnv): { home: string; pathEnv: string } { return { home: @@ -750,24 +783,59 @@ function resolveEnv(env: TailEnv): { home: string; pathEnv: string } { }; } +function harnessHome( + value: string | undefined, + fallback: string, + refuseEmpty: boolean, +): string | null { + if (value === undefined) return fallback; + if (value === "") return refuseEmpty ? null : fallback; + return isAbsolute(value) ? value : null; +} + +export function gapPolicyDestinations(env: TailEnv = {}): string[] { + const { home } = resolveEnv(env); + const out = GAP_POLICY_FILES.map((rel) => join(home, rel)); + const codex = harnessHome( + env.codexHome ?? process.env.CODEX_HOME, + join(home, ".codex"), + false, + ); + if (codex) out.push(join(codex, "gap", "global-agent-policy.md")); + const jcode = harnessHome( + env.jcodeHome ?? process.env.JCODE_HOME, + join(home, ".jcode"), + true, + ); + if (jcode) out.push(join(jcode, "prompt-overlay.md")); + return [...new Set(out)].sort(compareText); +} + +export function learnedTailCleanupPaths(env: TailEnv = {}): string[] { + const { home } = resolveEnv(env); + return [ + ...new Set([ + ...gapPolicyDestinations(env), + ...BUILTIN_TAIL_FILES.map((rel) => join(home, rel)), + ]), + ].sort(compareText); +} + export function findTailDestinations(env: TailEnv = {}): TailDestinationScan { const { home, pathEnv } = resolveEnv(env); const ledger = gapOnPath(pathEnv) ? readGapLedger(home) : null; const destinations: TailDestination[] = []; const skipped: SkippedTailDestination[] = []; if (ledger) { - for (const path of Object.keys(ledger).sort(compareText)) { + for (const path of gapPolicyDestinations(env)) { const value = ledger[path]; + if (value === undefined) continue; if (value === "cleaned") { skipped.push({ path, reason: "cleaned ledger entry" }); continue; } - if ( - typeof value !== "string" || - !isAbsolute(path) || - !insideHome(home, path) - ) { - skipped.push({ path, reason: "not a ledger path under HOME" }); + if (typeof value !== "string") { + skipped.push({ path, reason: "unreadable ledger entry" }); continue; } const problem = regularFileProblem(path); @@ -783,7 +851,7 @@ export function findTailDestinations(env: TailEnv = {}): TailDestinationScan { continue; } if (gapSpan(text) === null) { - skipped.push({ path, reason: "no GAP block (command file)" }); + skipped.push({ path, reason: "no GAP block" }); continue; } destinations.push({ path, source: "gap" }); @@ -880,15 +948,39 @@ export function writeTailState(path: string, state: TailState): void { } } +export function readWrittenTailKeys(texts: string[]): Set { + const keys = new Set(); + for (const text of texts) { + const block = readRecallBlock(text); + if (block.malformed) continue; + for (const bullet of block.bullets) keys.add(tailNoteKey(bullet)); + } + return keys; +} + +export function readWrittenTailKeysFrom(paths: string[]): Set { + const texts: string[] = []; + for (const path of paths) { + try { + texts.push(readFileSync(path, "utf8")); + } catch { + continue; + } + } + return readWrittenTailKeys(texts); +} + export function nextTailState( state: TailState, notes: TailNote[], now: Date, + written: Set = new Set(), ): TailState { const tailSince: Record = {}; for (const note of notes) { const key = tailNoteKey(note.text); - tailSince[key] = state.tailSince[key] ?? now.toISOString(); + const since = written.has(key) ? state.tailSince[key] : undefined; + tailSince[key] = since ?? now.toISOString(); } return { refreshedAt: now.getTime(), tailSince }; } @@ -903,9 +995,17 @@ export function recordTailRefresh( const landed = writes.some( (w) => w.status === "written" || w.status === "unchanged", ); + const written = readWrittenTailKeys( + (plan.destinations ?? []).map((d) => d.before), + ); writeTailState( path, - nextTailState(readTailState(path), landed ? plan.selection.notes : [], now), + nextTailState( + readTailState(path), + landed ? plan.selection.notes : [], + now, + written, + ), ); return true; } @@ -1039,6 +1139,37 @@ export function writeIfUnchanged( } } + +export type RecallRemovalPlan = + | { path: string; beforeHash: string; after: string; changed: boolean } + | { path: string; refused: string }; + +export function planRecallBlockRemoval(path: string): RecallRemovalPlan { + let read: { text: string; hash: string } | { error: string }; + try { + read = readUtf8Exact(path); + } catch (err) { + read = { error: err instanceof Error ? err.message : String(err) }; + } + if ("error" in read) return { path, refused: read.error }; + const removed = removeRecallBlock(read.text); + if (!removed.ok) return { path, refused: removed.reason }; + return { + path, + beforeHash: read.hash, + after: removed.text, + changed: removed.changed, + }; +} + +export function removeRecallBlockFromFile(path: string): TailWriteResult { + const plan = planRecallBlockRemoval(path); + if ("refused" in plan) + return { path, status: "refused", reason: plan.refused }; + if (!plan.changed) return { path, status: "unchanged" }; + return writeIfUnchanged(path, plan.beforeHash, plan.after); +} + export function writeLearnedTail(plan: TailPlan): TailWriteResult[] { return plan.destinations.map((d) => { if (d.refused) diff --git a/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md b/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md index 3bfd7b0d..5b4e3874 100644 --- a/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md +++ b/hosts/plugins/recall-claude/skills/do-recall-promote/SKILL.md @@ -7,7 +7,7 @@ Turn Recall notes that hold across projects into a reviewed change to the shared ## What this does -1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, seen in 3 or more distinct projects, in a Recall block written now and for 14 or more days, and not already covered by a published GAP policy file. 2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. 3. Opens a pull request and stops. diff --git a/hosts/plugins/recall/skills/do-recall-promote/SKILL.md b/hosts/plugins/recall/skills/do-recall-promote/SKILL.md index 5e6fd433..42ae0e9d 100644 --- a/hosts/plugins/recall/skills/do-recall-promote/SKILL.md +++ b/hosts/plugins/recall/skills/do-recall-promote/SKILL.md @@ -15,7 +15,7 @@ Turn Recall notes that hold across projects into a reviewed change to the shared ## What this does -1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, high confidence, seen in 3 or more distinct projects, in the tail for 14 or more days, and not already covered by a published GAP policy file. +1. Runs `recall promote --json`. That command is read-only: it lists tail notes that are active, seen in 3 or more distinct projects, in a Recall block written now and for 14 or more days, and not already covered by a published GAP policy file. 2. On a new branch of the GAP checkout, adds the accepted notes to `global/AGENTS.md`. 3. Opens a pull request and stops. diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index cc4195a1..1f7cc92d 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -394,42 +394,25 @@ remove_extract_prompt_if_unmodified() { fi } -# Every harness file the learned tail may ever have written: each GAP ledger -# path under HOME (cleaned ones too, since GAP may have been installed or -# removed after a write) plus every built-in file. Only the Recall pair is -# removed from each, and a missing file is skipped by remove_recall_block. +# Every harness file the learned tail may ever have written: each GAP policy +# destination (CODEX_HOME and JCODE_HOME included, whatever the ledger says now, +# since GAP may have been installed or removed after a write) plus every built-in +# file. The list and the marker rules come from hooks/lib/learned-tail.ts, the +# same code `recall learn` uses. A missing file is skipped by remove_recall_block. +RECALL_TAIL_LIB="$SCRIPT_DIR/../hooks/lib/learned-tail.ts" + recall_learned_tail_files() { - RECALL_TAIL_HOME="$HOME" bun -e ' - const fs = require("fs"); - const path = require("path"); - const home = process.env.RECALL_TAIL_HOME; - const builtin = [ - ".claude/CLAUDE.md", - ".codex/AGENTS.md", - ".pi/agent/APPEND_SYSTEM.md", - ".omp/agent/APPEND_SYSTEM.md", - ".empryo/EMPRYO.md", - ]; - let ledger = null; - try { - const parsed = JSON.parse(fs.readFileSync(path.join(home, ".gap", "published.json"), "utf8")); - if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) ledger = parsed; - } catch { /* no GAP ledger — built-in files */ } - const out = new Set(); - for (const file of Object.keys(ledger ?? {}).sort()) { - if (typeof ledger[file] !== "string" || !path.isAbsolute(file)) continue; - const rel = path.relative(home, file); - if (rel && !rel.startsWith("..") && !path.isAbsolute(rel)) out.add(file); - } - for (const rel of builtin) out.add(path.join(home, rel)); - process.stdout.write([...out].join("\n")); + RECALL_TAIL_LIB="$RECALL_TAIL_LIB" RECALL_TAIL_HOME="$HOME" bun -e ' + const { learnedTailCleanupPaths } = require(process.env.RECALL_TAIL_LIB); + process.stdout.write(learnedTailCleanupPaths({ home: process.env.RECALL_TAIL_HOME }).join("\n")); ' } -# Remove only the ... pair. -# Everything outside that pair, including a GAP block, stays byte for byte. -# A file with no pair is left untouched. A malformed pair (nested, reversed, -# or more than one) is left untouched and reported. +# Remove only the ... pair through the +# learn parser and its checked write: a temp file renamed over the original, and +# only when the file still matches what was read. A pair the parser refuses +# (malformed, or overlapping any GAP block) or a file edited mid-write is left +# untouched and reported. remove_recall_block() { local file="$1" [[ -f "$file" && ! -L "$file" ]] || return 0 @@ -440,64 +423,17 @@ remove_recall_block() { return 0 fi local status=0 - RECALL_BLOCK_FILE="$file" bun -e ' - const fs = require("fs"); - const file = process.env.RECALL_BLOCK_FILE; - const BEGIN = ""; - const END = ""; - const src = fs.readFileSync(file); - const text = src.toString("utf8"); - if (!Buffer.from(text, "utf8").equals(src)) process.exit(0); - function markerLines(marker) { - const out = []; - let from = 0; - while (from < text.length) { - const i = text.indexOf(marker, from); - if (i < 0) break; - const after = i + marker.length; - const ownLine = (i === 0 || text[i - 1] === "\n") && - (after === text.length || text[after] === "\n" || - (text[after] === "\r" && text[after + 1] === "\n")); - if (ownLine) { - let end = after; - if (text[after] === "\n") end = after + 1; - else if (text[after] === "\r") end = after + 2; - out.push([i, end]); - from = end; - } else { - from = i + 1; - } - } - return out; - } - const begins = markerLines(BEGIN); - const ends = markerLines(END); - if (begins.length === 0 && ends.length === 0) process.exit(0); - if (begins.length !== 1 || ends.length !== 1 || ends[0][0] < begins[0][1]) { - process.stderr.write("malformed Recall block in " + file + "\n"); - process.exit(2); - } - let cut = begins[0][0]; - const end = ends[0][1]; - const gapBegins = markerLines(""); - const gapEnds = markerLines(""); - const wraps = [...gapBegins, ...gapEnds].some(([at]) => at >= cut && at < end); - const inside = gapBegins.some(([gb], i) => { - const ge = gapEnds.find(([at]) => at > gb); - return ge && ((cut > gb && cut < ge[0]) || (ends[0][0] > gb && ends[0][0] < ge[0])); - }); - if (wraps || inside) { - process.stderr.write("Recall block overlaps the GAP block in " + file + "\n"); + local reason + reason="$(RECALL_TAIL_LIB="$RECALL_TAIL_LIB" RECALL_BLOCK_FILE="$file" bun -e ' + const { removeRecallBlockFromFile } = require(process.env.RECALL_TAIL_LIB); + const result = removeRecallBlockFromFile(process.env.RECALL_BLOCK_FILE); + if (result.status === "refused") { + process.stdout.write(result.reason ?? "refused"); process.exit(2); } - if (cut >= 2 && text[cut - 1] === "\n" && text[cut - 2] === "\n") { - cut -= end === text.length && !text.endsWith("\n") ? 2 : 1; - } - const next = text.slice(0, cut) + text.slice(end); - if (next !== text) fs.writeFileSync(file, next); - ' || status=$? + ')" || status=$? if [[ "$status" -eq 2 ]]; then - log_warn "Preserved $file (malformed Recall learned-tail block)" + log_warn "Preserved $file ($reason)" return 0 fi if [[ "$status" -ne 0 ]]; then diff --git a/src/commands/promote.ts b/src/commands/promote.ts index 8977ea20..909dc97f 100644 --- a/src/commands/promote.ts +++ b/src/commands/promote.ts @@ -1,7 +1,8 @@ // recall promote — read-only list of learned-tail notes that meet the Lane B bar (#279). -// A note qualifies when it has been in the written tail for 14+ days (tracked in -// learned-tail-state.json) and has been seen in 3+ distinct projects, -// and the published GAP policy text does not already cover it. This command writes nothing. +// A note qualifies when it is in the Recall block of a GAP destination now, has been +// in the written tail for 14+ days (tracked in learned-tail-state.json), has been seen +// in 3+ distinct projects, and the published GAP policy text does not already cover it. +// This command writes nothing. import { findTailDestinations, @@ -9,6 +10,7 @@ import { loadTailCandidates, readGapCoverageText, readTailState, + readWrittenTailKeysFrom, selectTail, tailNoteKey, tailStatePath, @@ -92,8 +94,8 @@ export function promotionCandidates( return { kept, skipped }; } -// Every qualifying note is listed so `skipped` explains each one; tail membership -// itself comes from the state file that each successful write records. +// Every qualifying note is listed so `skipped` explains each one. A note's age comes +// from the state file, and only counts while the note is in a Recall block written now. export function tailNotes(candidates: TailCandidate[]): TailNote[] { return selectTail(candidates, { gapText: "", cap: false }).notes; } @@ -102,9 +104,15 @@ export function planPromotion(options: PromoteOptions = {}): PromoteReport { const now = options.now ?? new Date(); const scan = findTailDestinations(options); if (!scan.gap) return { gap: false, candidates: [], skipped: [] }; - const gapText = readGapCoverageText(scan.destinations.map((d) => d.path)); + const paths = scan.destinations.map((d) => d.path); + const gapText = readGapCoverageText(paths); const notes = tailNotes(loadTailCandidates(options.dbPath)); - const { tailSince } = readTailState(tailStatePath(options.dbPath)); + const written = readWrittenTailKeysFrom(paths); + const tailSince = Object.fromEntries( + Object.entries(readTailState(tailStatePath(options.dbPath)).tailSince).filter( + ([key]) => written.has(key), + ), + ); const { kept, skipped } = promotionCandidates(notes, gapText, now, tailSince); return { gap: true, candidates: kept, skipped }; } diff --git a/src/lib/learned-tail.ts b/src/lib/learned-tail.ts index e7620eb8..851663d2 100644 --- a/src/lib/learned-tail.ts +++ b/src/lib/learned-tail.ts @@ -6,32 +6,41 @@ export { BUILTIN_TAIL_FILES, GAP_BEGIN, GAP_END, + GAP_POLICY_FILES, MAX_BULLET_CHARS, MAX_TAIL_BULLETS, MAX_TAIL_TOKENS, MIN_TAIL_IMPORTANCE, + MIN_TAIL_SESSIONS, RECALL_BEGIN, RECALL_END, TAIL_HEADER_PREFIX, countRecordsSince, findTailDestinations, + gapPolicyDestinations, + learnedTailCleanupPaths, loadTailCandidates, isCoveredByGap, planLearnedTail, + planRecallBlockRemoval, readGapCoverageText, readRecallBlock, readTailState, + readWrittenTailKeysFrom, recordTailRefresh, removeRecallBlock, + removeRecallBlockFromFile, selectTail, spliceRecallBlock, tailNoteKey, tailStatePath, + writeIfUnchanged, writeLearnedTail, } from "../../hooks/lib/learned-tail.js"; export type { DroppedTailNote, PlanTailOptions, + RecallRemovalPlan, RecallBlockInfo, SpliceResult, TailCandidate, diff --git a/tests/hooks/learned-tail-stop.test.ts b/tests/hooks/learned-tail-stop.test.ts index 59cff5c8..9c905c83 100644 --- a/tests/hooks/learned-tail-stop.test.ts +++ b/tests/hooks/learned-tail-stop.test.ts @@ -1,8 +1,11 @@ // The Stop hook refreshes the learned tail (#279) on every Stop, including the // exits that never reach extraction, and a refused write keeps the old state. +// Notes come from real Stop extraction (`--extract`, the hook's own child mode) +// with a fake `claude` CLI, so they carry the importance and provenance +// extraction actually writes. import { afterEach, describe, expect, test } from 'bun:test'; import { spawnSync } from 'child_process'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; import { homedir, tmpdir } from 'os'; import { join } from 'path'; @@ -11,6 +14,8 @@ const CLI = join(REPO, 'src', 'index.ts'); const HOOKS = join(REPO, 'hooks'); const PRODUCTION_DB = join(homedir(), '.agents', 'Recall', 'recall.db'); const NOTE = 'Run the migration dry-run before every schema change.'; +const ONE_OFF = 'Pin the alpha dev server to port 4100 for local runs.'; +const UNSURE = 'Maybe split the settings page into two tabs later on.'; const DAY = 86_400_000; const roots: string[] = []; @@ -44,27 +49,33 @@ function setup() { RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', }; expect(spawnSync(process.execPath, [CLI, 'init'], { env, encoding: 'utf-8' }).status).toBe(0); - // Seed in a child process: other suites mock modules in this one. - const seed = spawnSync( + mkdirSync(join(root, '.claude', 'MEMORY'), { recursive: true }); + const statePath = join(root, 'learned-tail-state.json'); + extract(root, hooks, env, 'session-one', 'alpha', [NOTE, ONE_OFF], [UNSURE]); + extract(root, hooks, env, 'session-two', 'bravo', [NOTE], [UNSURE]); + const rows = spawnSync( process.execPath, [ '-e', `const { Database } = require('bun:sqlite'); - const db = new Database(process.argv[1]); - db.query("INSERT INTO decisions (created_at, project, decision, status, importance, provenance, access_count, confidence) VALUES (datetime('now'), 'alpha', ?, 'active', 9, 'extracted', 1, 'high')").run(process.argv[2]); - db.close();`, + const db = new Database(process.argv[1], { readonly: true }); + process.stdout.write(JSON.stringify(db.query("SELECT decision, importance, provenance, confidence FROM decisions ORDER BY id").all()));`, join(root, 'recall.db'), - NOTE, ], { env, encoding: 'utf-8' }, ); - expect(seed.status).toBe(0); + expect(JSON.parse(rows.stdout)).toEqual([ + { decision: NOTE, importance: 5, provenance: 'extracted', confidence: 'high' }, + { decision: ONE_OFF, importance: 5, provenance: 'extracted', confidence: 'high' }, + { decision: UNSURE, importance: 5, provenance: 'extracted', confidence: 'low' }, + { decision: NOTE, importance: 5, provenance: 'extracted', confidence: 'high' }, + { decision: UNSURE, importance: 5, provenance: 'extracted', confidence: 'low' }, + ]); + rmSync(statePath, { force: true }); const claude = join(root, '.claude', 'CLAUDE.md'); - mkdirSync(join(root, '.claude'), { recursive: true }); writeFileSync(claude, '# Mine\n'); const nowhere = join(root, 'no-conversation'); mkdirSync(nowhere, { recursive: true }); - const statePath = join(root, 'learned-tail-state.json'); const stop = () => spawnSync(process.execPath, [join(hooks, 'RecallExtract.ts')], { input: JSON.stringify({ hook_event_name: 'Stop', session_id: 'tail-stop', cwd: nowhere }), @@ -76,11 +87,56 @@ function setup() { return { claude, statePath, stop, state }; } +function extraction(sure: string[], unsure: string[]): string { + return [ + '## ONE SENTENCE SUMMARY', + 'We tightened the schema change workflow so every migration is rehearsed before it touches a shared database.', + '', + '## MAIN IDEAS', + '- Schema changes are rehearsed against a dry-run before they reach any shared database copy', + '- The migration tooling reports every statement it would run so reviewers can read the plan', + '- Local development servers keep fixed ports so the fixtures stay reproducible across runs', + '', + '## DECISIONS MADE', + ...sure.map((d) => `- ${d} (confidence: HIGH)`), + ...unsure.map((d) => `- ${d} (confidence: LOW)`), + '', + '## SESSION CONTEXT', + 'A workflow hardening session for database migrations.', + ].join('\n'); +} + +function extract(root: string, hooks: string, env: NodeJS.ProcessEnv, session: string, project: string, sure: string[], unsure: string[]): void { + const bin = join(root, '.local', 'bin'); + mkdirSync(bin, { recursive: true }); + const claude = join(bin, 'claude'); + writeFileSync(claude, `#!/usr/bin/env bun\ntry { require('fs').readFileSync(0, 'utf-8'); } catch {}\nprocess.stdout.write(${JSON.stringify(extraction(sure, unsure))});\n`); + chmodSync(claude, 0o755); + const cwd = join(root, 'work', project); + mkdirSync(cwd, { recursive: true }); + const conversation = join(root, 'conversations', `${session}.jsonl`); + mkdirSync(join(root, 'conversations'), { recursive: true }); + const lines: string[] = []; + for (let i = 0; i < 80; i++) { + lines.push(JSON.stringify({ type: 'user', message: { role: 'user', content: 'please help me with the migration' } })); + lines.push(JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'here is a detailed answer about the migration' }] } })); + } + writeFileSync(conversation, lines.join('\n') + '\n'); + const run = spawnSync(process.execPath, ['run', join(hooks, 'RecallExtract.ts'), '--extract', conversation, cwd], { + env, + encoding: 'utf-8', + timeout: 60_000, + }); + expect(run.status).toBe(0); +} + describe('learned tail from the Stop hook', () => { test('a Stop with no conversation still refreshes, and a recent refresh is not repeated', () => { const { claude, statePath, stop, state } = setup(); expect(stop().status).toBe(0); expect(readFileSync(claude, 'utf-8')).toContain(`- ${NOTE}`); + expect(readFileSync(claude, 'utf-8')).not.toContain(ONE_OFF); + expect(readFileSync(claude, 'utf-8')).not.toContain(UNSURE); expect(readFileSync(claude, 'utf-8').startsWith('# Mine\n')).toBe(true); const first = state(); expect(first.refreshedAt).toBeGreaterThan(0); @@ -93,7 +149,9 @@ describe('learned tail from the Stop hook', () => { writeFileSync(statePath, JSON.stringify({ ...first, refreshedAt: Date.now() - 2 * DAY })); expect(stop().status).toBe(0); expect(readFileSync(claude, 'utf-8')).toContain(`- ${NOTE}`); - expect(state().tailSince).toEqual(first.tailSince); + const [key] = Object.keys(first.tailSince); + expect(Object.keys(state().tailSince)).toEqual([key]); + expect(Date.parse(state().tailSince[key])).toBeGreaterThan(Date.parse(first.tailSince[key])); }, 60_000); test('a refused write keeps the old refresh time so the next Stop retries', () => { diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 0266a503..0bd802fa 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -93,6 +93,8 @@ function runUninstall( // the developer's live `recall` link. RECALL_SKIP_BUN_UNLINK: 'true', RECALL_CRONTAB_BIN: '', + CODEX_HOME: '', + JCODE_HOME: '', ...extraEnv, }, }, @@ -122,6 +124,8 @@ function runPurge(claudeDir: string, backupBase: string): RunResult { PATH: `${stubBin}:${process.env.PATH ?? ''}`, RECALL_SKIP_BUN_UNLINK: 'true', RECALL_CRONTAB_BIN: '', + CODEX_HOME: '', + JCODE_HOME: '', }, }, ); @@ -999,21 +1003,30 @@ Preserve this. }); describe('learned-tail block removal', () => { - test('removes only the Recall pair from ledger and built-in files, skips paths outside HOME, and keeps a block that wraps GAP', () => { + test('removes only the Recall pair from GAP policy and built-in files through a checked rename, and keeps any pair the learn parser refuses', () => { const root = mkdtempSync(join(tmpdir(), 'recall-tail-uninstall-')); const home = join(root, 'home'); const outside = join(root, 'outside', 'AGENTS.md'); - const inside = join(home, '.claude', 'rules', 'policy.md'); + const inside = join(home, '.claude', 'rules', 'global-agent-policy.md'); + const codexHome = join(root, 'codex-home'); + const codexPolicy = join(codexHome, 'gap', 'global-agent-policy.md'); + const command = join(home, '.claude', 'commands', 'example.md'); + const nested = join(home, '.omp', 'agent', 'APPEND_SYSTEM.md'); const wrapped = join(home, '.pi', 'agent', 'APPEND_SYSTEM.md'); const gap = '\nPolicy.\n\n'; const pair = '\n- note\n\n'; - for (const file of [outside, inside, wrapped]) mkdirSync(dirname(file), { recursive: true }); - writeFileSync(inside, `# Head\n\n${gap}\n${pair}`); + for (const file of [outside, inside, wrapped, codexPolicy, command, nested]) mkdirSync(dirname(file), { recursive: true }); + writeFileSync(inside, `# Head\n\n${gap}\n${pair}`, { mode: 0o640 }); + const insideInode = lstatSync(inside).ino; writeFileSync(outside, `${gap}\n${pair}`); + writeFileSync(codexPolicy, `${gap}\n${pair}`); + writeFileSync(command, `${gap}\n${pair}`); + const nestedText = `\nA.\n${pair}\n\n${gap}`; + writeFileSync(nested, nestedText); const wrappedText = `\n- note\n${gap}\n`; writeFileSync(wrapped, wrappedText); const builtin = join(home, '.claude', 'CLAUDE.md'); - const cleaned = join(home, '.cursor', 'rules', 'old.mdc'); + const cleaned = join(home, '.cursor', 'rules', 'global-agent-policy.mdc'); for (const file of [builtin, cleaned]) mkdirSync(dirname(file), { recursive: true }); writeFileSync(builtin, `# Mine\n\n${pair}`); writeFileSync(cleaned, `# Old\n\n${pair}`); @@ -1023,11 +1036,16 @@ describe('learned-tail block removal', () => { mkdirSync(join(home, '.gap'), { recursive: true }); writeFileSync( join(home, '.gap', 'published.json'), - JSON.stringify({ [inside]: 'h1', [outside]: 'h2', [wrapped]: 'h3', [cleaned]: 'cleaned' }), + JSON.stringify({ [inside]: 'h1', [outside]: 'h2', [wrapped]: 'h3', [cleaned]: 'cleaned', [codexPolicy]: 'h4', [command]: 'h5', [nested]: 'h6' }), ); - const result = runUninstall(home, join(root, 'backups')); + const result = runUninstall(home, join(root, 'backups'), [], { CODEX_HOME: codexHome }); expect(result.status).toBe(0); expect(readFileSync(inside, 'utf-8')).toBe(`# Head\n\n${gap}`); + expect(lstatSync(inside).ino).not.toBe(insideInode); + expect(lstatSync(inside).mode & 0o777).toBe(0o640); + expect(readFileSync(codexPolicy, 'utf-8')).toBe(gap); + expect(readFileSync(command, 'utf-8')).toBe(`${gap}\n${pair}`); + expect(readFileSync(nested, 'utf-8')).toBe(nestedText); expect(readFileSync(outside, 'utf-8')).toBe(`${gap}\n${pair}`); expect(readFileSync(wrapped, 'utf-8')).toBe(wrappedText); expect(readFileSync(builtin, 'utf-8')).toBe('# Mine\n'); diff --git a/tests/learned-tail-embedding.test.ts b/tests/learned-tail-embedding.test.ts index 750d5f64..3f447574 100644 --- a/tests/learned-tail-embedding.test.ts +++ b/tests/learned-tail-embedding.test.ts @@ -25,12 +25,13 @@ test("identical embeddings cannot merge contradictory rules or manufacture promo mkdirSync(bin); writeFileSync(join(bin, "gap"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); process.env.PATH = bin; - const policy = join(home, ".gap", "policy.md"); + const policy = join(home, ".claude", "rules", "global-agent-policy.md"); mkdirSync(dirname(policy), { recursive: true }); writeFileSync( policy, "\nKeep commands reliable.\n\n", ); + mkdirSync(join(home, ".gap"), { recursive: true }); writeFileSync( join(home, ".gap", "published.json"), JSON.stringify({ [policy]: "published" }), diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 779de020..54da62c0 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -4,18 +4,29 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { delimiter, dirname, join } from "node:path"; import { closeDb, getDb } from "../src/db/connection.js"; import { countRecordsSince, + findTailDestinations, isCoveredByGap, + planRecallBlockRemoval, readTailState, selectTail, recordTailRefresh, removeRecallBlock, spliceRecallBlock, tailNoteKey, + writeIfUnchanged, } from "../src/lib/learned-tail.js"; import type { TailCandidate, TailPlan } from "../src/lib/learned-tail.js"; import { @@ -103,6 +114,19 @@ function publish(file: string): void { ); } +function policyPath(): string { + return join(home, ".claude", "rules", "global-agent-policy.md"); +} + +function promote(env: NodeJS.ProcessEnv = process.env): { + candidates: Array<{ text: string }>; + skipped: Array<{ text: string; reason: string }>; +} { + const result = recall(["promote", "--json"], env); + expect(result.status).toBe(0); + return JSON.parse(result.stdout); +} + function existsFile(path: string): boolean { try { return statSync(path).isFile(); @@ -139,7 +163,7 @@ describe("learned tail end to end", () => { }); test("(a)(b) learn writes the Recall pair, and a second learn with no change writes nothing", () => { - const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const policy = policyPath(); const original = writePolicy(policy); publish(policy); @@ -216,7 +240,7 @@ describe("learned tail end to end", () => { }); test("(d) promote needs 14 days in the written tail, and learn drops a note once the GAP block covers it", () => { - const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const policy = policyPath(); writePolicy(policy); publish(policy); const statePath = join(dirname(dbPath), "learned-tail-state.json"); @@ -290,7 +314,7 @@ describe("learned tail end to end", () => { }); test("(f) a Recall block wrapped around the GAP block is refused and the file is untouched", () => { - const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const policy = policyPath(); mkdirSync(dirname(policy), { recursive: true }); const wrapped = "\n- old\n\nPolicy.\n\n\n"; @@ -467,7 +491,7 @@ describe("learned tail end to end", () => { }); test("(e) uninstall block removal leaves the surrounding bytes byte for byte", () => { - const policy = join(home, ".gap-policies", "global", "AGENTS.md"); + const policy = policyPath(); const original = writePolicy(policy); publish(policy); expect(recall(["learn"]).status).toBe(0); @@ -496,4 +520,137 @@ describe("learned tail end to end", () => { true, ); }); + + test("(k) promote only offers a note in a tail written now, and a note written back starts a new age", () => { + const policy = policyPath(); + writePolicy(policy); + publish(policy); + const statePath = join(dirname(dbPath), "learned-tail-state.json"); + expect(recall(["learn"]).status).toBe(0); + const key = tailNoteKey(NOTE); + const old = new Date(Date.now() - 20 * 86_400_000).toISOString(); + writeFileSync( + statePath, + JSON.stringify({ ...readTailState(statePath), tailSince: { [key]: old } }), + ); + expect(promote().candidates.map((c) => c.text)).toEqual([NOTE]); + + const removed = removeRecallBlock(readFileSync(policy, "utf8")); + if (!removed.ok) throw new Error(removed.reason); + writeFileSync(policy, removed.text); + const gone = promote(); + expect(gone.candidates).toEqual([]); + expect(gone.skipped).toEqual([ + { text: NOTE, reason: "not in the written tail yet" }, + ]); + + expect(recall(["learn"]).status).toBe(0); + expect(readTailState(statePath).tailSince[key]).not.toBe(old); + expect(promote().skipped).toEqual([ + { text: NOTE, reason: "0 days in the tail (need 14)" }, + ]); + }); + + test("(l) identifiers in backticks keep their case for grouping, GAP coverage and tail age", () => { + const row = (id: number, text: string, project: string): TailCandidate => ({ + table: "decisions", + id, + text, + project, + importance: 9, + provenance: "user_authored", + confidence: "high", + accessCount: 1, + sessionId: `s${id}`, + createdAt: FIRST_SEEN, + }); + const upper = "Use `PATH` in the fixture."; + const lower = "Use `path` in the fixture."; + const { notes } = selectTail( + [row(1, upper, "alpha"), row(2, lower, "bravo"), row(3, lower, "charlie")], + { cap: false }, + ); + expect(notes.map((n) => [n.text, n.projects])).toEqual([ + [upper, ["alpha"]], + [lower, ["bravo", "charlie"]], + ]); + expect(isCoveredByGap(upper, `- ${lower}`)).toBe(false); + expect(isCoveredByGap(lower, `- ${upper}`)).toBe(false); + expect(isCoveredByGap("USE `PATH` IN THE FIXTURE", `- ${upper}`)).toBe(true); + expect(tailNoteKey(upper)).not.toBe(tailNoteKey(lower)); + }); + + test("(m) only GAP policy destinations get the tail: a ledgered command file is skipped, and an absolute CODEX_HOME or JCODE_HOME outside HOME is used", () => { + const outside = mkdtempSync(join(tmpdir(), "recall-tail-homes-")); + try { + const command = join(home, ".claude", "commands", "gap-example.md"); + mkdirSync(dirname(command), { recursive: true }); + const commandText = + "Example policy file:\n\n\nPolicy.\n\n"; + writeFileSync(command, commandText); + const codexHome = join(outside, "codex"); + const jcodeHome = join(outside, "jcode"); + const codexPolicy = join(codexHome, "gap", "global-agent-policy.md"); + const jcodePolicy = join(jcodeHome, "prompt-overlay.md"); + const stray = join(outside, "AGENTS.md"); + for (const file of [codexPolicy, jcodePolicy, stray]) writePolicy(file); + mkdirSync(join(home, ".gap"), { recursive: true }); + writeFileSync( + join(home, ".gap", "published.json"), + JSON.stringify({ + [command]: "c", + [codexPolicy]: "p", + [jcodePolicy]: "p", + [stray]: "p", + }), + ); + const env = { ...process.env, CODEX_HOME: codexHome, JCODE_HOME: jcodeHome }; + const result = recall(["learn", "--json"], env); + expect(result.status).toBe(0); + const report = JSON.parse(result.stdout) as { + destinations: Array<{ path: string; status: string | null }>; + }; + expect(report.destinations.map((d) => [d.path, d.status])).toEqual([ + [codexPolicy, "written"], + [jcodePolicy, "written"], + ]); + expect(readFileSync(command, "utf8")).toBe(commandText); + expect(readFileSync(stray, "utf8")).not.toContain(""); + expect(readFileSync(codexPolicy, "utf8")).toContain(`- ${NOTE}`); + const scan = findTailDestinations({ + home, + path: process.env.PATH, + codexHome: "relative/codex", + jcodeHome: "", + }); + expect(scan.destinations).toEqual([]); + } finally { + rmSync(outside, { recursive: true, force: true }); + } + }); + + test("(n) a Recall pair inside any GAP block is refused, and removal never overwrites a later edit", () => { + const policy = policyPath(); + mkdirSync(dirname(policy), { recursive: true }); + const nested = + "\nA.\n\n- old\n\n\n\n\nB.\n\n"; + writeFileSync(policy, nested); + publish(policy); + expect(removeRecallBlock(nested).ok).toBe(false); + expect(spliceRecallBlock(nested, [], "2026-01-01").ok).toBe(false); + const learned = recall(["learn", "--json"]); + expect(learned.status).toBe(1); + expect(readFileSync(policy, "utf8")).toBe(nested); + const removal = planRecallBlockRemoval(policy); + expect(removal).toEqual(expect.objectContaining({ refused: "Recall marker sits inside the GAP block" })); + + const pair = "# Mine\n\n\n- old\n\n"; + writeFileSync(policy, pair); + const plan = planRecallBlockRemoval(policy); + if ("refused" in plan) throw new Error(plan.refused); + expect(plan.after).toBe("# Mine\n"); + writeFileSync(policy, `${pair}edited\n`); + expect(writeIfUnchanged(policy, plan.beforeHash, plan.after).status).toBe("refused"); + expect(readFileSync(policy, "utf8")).toBe(`${pair}edited\n`); + }); }); From 0e2ffbe86a1662fb94799545b37fdc4562b14c1e Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:19:10 -0500 Subject: [PATCH 03/12] fix(learn): count known sessions and track written tail destinations - tail: count only distinct known session IDs toward recurrence and ranking - tail: record each destination a write landed in, so uninstall finds blocks after CODEX_HOME or JCODE_HOME changes - test: expose the running Bun as `bun` in the Stop fixture for npm installs Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 58 ++++++++++++++++++++++----- packaging/uninstall.sh | 5 ++- tests/hooks/learned-tail-stop.test.ts | 8 ++-- tests/install/uninstall.test.ts | 44 ++++++++++++++++++++ tests/learned-tail.test.ts | 37 +++++++++++++++++ 5 files changed, 138 insertions(+), 14 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index f2de7720..3eaf568b 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -365,6 +365,12 @@ function provenRecord(c: TailCandidate): boolean { ); } +function knownSessions(members: TailCandidate[]): number { + return new Set( + members.map((m) => m.sessionId).filter((s): s is string => !!s), + ).size; +} + function candidateKey(c: { table: TailTable; id: number }): string { return `${c.table}:${c.id}`; } @@ -436,8 +442,7 @@ export function selectTail( } const proven = clusters.filter(({ lead, members }) => { - const sessions = new Set(members.map((m) => m.sessionId ?? candidateKey(m))); - if (members.some(provenRecord) || sessions.size >= MIN_TAIL_SESSIONS) + if (members.some(provenRecord) || knownSessions(members) >= MIN_TAIL_SESSIONS) return true; dropped.push({ key: candidateKey(lead), @@ -454,8 +459,7 @@ export function selectTail( key: candidateKey(lead), text: lead.clean, importance: Math.max(...members.map((m) => m.importance)), - sessions: new Set(members.map((m) => m.sessionId ?? candidateKey(m))) - .size, + sessions: knownSessions(members), accessCount: members.reduce((sum, m) => sum + m.accessCount, 0), records: members.map((m) => ({ table: m.table, id: m.id })), projects: [ @@ -811,12 +815,16 @@ export function gapPolicyDestinations(env: TailEnv = {}): string[] { return [...new Set(out)].sort(compareText); } -export function learnedTailCleanupPaths(env: TailEnv = {}): string[] { +export function learnedTailCleanupPaths( + env: TailEnv & { dbPath?: string } = {}, +): string[] { const { home } = resolveEnv(env); + const written = readTailState(tailStatePath(env.dbPath)).destinations; return [ ...new Set([ ...gapPolicyDestinations(env), ...BUILTIN_TAIL_FILES.map((rel) => join(home, rel)), + ...written, ]), ].sort(compareText); } @@ -897,6 +905,7 @@ export const TAIL_STATE_FILE = "learned-tail-state.json"; export interface TailState { refreshedAt: number; tailSince: Record; + destinations: string[]; } export function tailNoteKey(text: string): string { @@ -916,15 +925,21 @@ export function readTailState(path: string): TailState { if (typeof v === "string" && !Number.isNaN(Date.parse(v))) since[k] = v; } } + const destinations = Array.isArray(parsed?.destinations) + ? parsed.destinations.filter( + (p: unknown): p is string => typeof p === "string" && isAbsolute(p), + ) + : []; return { refreshedAt: Number.isFinite(parsed?.refreshedAt) && parsed.refreshedAt > 0 ? parsed.refreshedAt : 0, tailSince: since, + destinations, }; } catch { - return { refreshedAt: 0, tailSince: {} }; + return { refreshedAt: 0, tailSince: {}, destinations: [] }; } } @@ -982,7 +997,26 @@ export function nextTailState( const since = written.has(key) ? state.tailSince[key] : undefined; tailSince[key] = since ?? now.toISOString(); } - return { refreshedAt: now.getTime(), tailSince }; + return { + refreshedAt: now.getTime(), + tailSince, + destinations: state.destinations, + }; +} + +function landedDestinations( + previous: string[], + plan: TailPlan, + writes: TailWriteResult[], +): string[] { + const out = new Set(previous); + for (const w of writes) { + if (w.status !== "written" && w.status !== "unchanged") continue; + const after = plan.destinations?.find((d) => d.path === w.path)?.after; + if (after !== undefined && readRecallBlock(after).present) out.add(w.path); + else out.delete(w.path); + } + return [...out].sort(compareText); } export function recordTailRefresh( @@ -991,7 +1025,13 @@ export function recordTailRefresh( writes: TailWriteResult[], now: Date = new Date(), ): boolean { - if (writes.some((w) => w.status === "refused")) return false; + const state = readTailState(path); + const destinations = landedDestinations(state.destinations, plan, writes); + const moved = destinations.join("\n") !== state.destinations.join("\n"); + if (writes.some((w) => w.status === "refused")) { + if (moved) writeTailState(path, { ...state, destinations }); + return false; + } const landed = writes.some( (w) => w.status === "written" || w.status === "unchanged", ); @@ -1001,7 +1041,7 @@ export function recordTailRefresh( writeTailState( path, nextTailState( - readTailState(path), + { ...state, destinations }, landed ? plan.selection.notes : [], now, written, diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index 1f7cc92d..a762a0b3 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -396,8 +396,9 @@ remove_extract_prompt_if_unmodified() { # Every harness file the learned tail may ever have written: each GAP policy # destination (CODEX_HOME and JCODE_HOME included, whatever the ledger says now, -# since GAP may have been installed or removed after a write) plus every built-in -# file. The list and the marker rules come from hooks/lib/learned-tail.ts, the +# since GAP may have been installed or removed after a write), every built-in +# file, and each destination learned-tail-state.json recorded a write to (so a +# block written under a since-changed CODEX_HOME or JCODE_HOME is still found). The list and the marker rules come from hooks/lib/learned-tail.ts, the # same code `recall learn` uses. A missing file is skipped by remove_recall_block. RECALL_TAIL_LIB="$SCRIPT_DIR/../hooks/lib/learned-tail.ts" diff --git a/tests/hooks/learned-tail-stop.test.ts b/tests/hooks/learned-tail-stop.test.ts index 9c905c83..b38b4e3a 100644 --- a/tests/hooks/learned-tail-stop.test.ts +++ b/tests/hooks/learned-tail-stop.test.ts @@ -5,7 +5,7 @@ // extraction actually writes. import { afterEach, describe, expect, test } from 'bun:test'; import { spawnSync } from 'child_process'; -import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'; import { homedir, tmpdir } from 'os'; import { join } from 'path'; @@ -37,13 +37,15 @@ function setup() { roots.push(root); const hooks = join(root, 'installed', 'hooks'); cpSync(HOOKS, hooks, { recursive: true }); - const bin = join(root, 'empty-bin'); + const bin = join(root, 'bin'); mkdirSync(bin, { recursive: true }); + // npm installs Bun as `bun.exe`, so the running binary is exposed as `bun`. + symlinkSync(process.execPath, join(bin, 'bun')); // A minimal env: other suites leave Recall/Claude variables set in this process. const env: NodeJS.ProcessEnv = { TMPDIR: tmpdir(), HOME: root, - PATH: `${bin}:${join(process.execPath, '..')}:/usr/bin:/bin`, + PATH: `${bin}:/usr/bin:/bin`, RECALL_DB_PATH: join(root, 'recall.db'), RECALL_HOME: join(root, 'recall-home'), RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 0bd802fa..67f8b14a 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -1053,4 +1053,48 @@ describe('learned-tail block removal', () => { expect(readFileSync(bare, 'utf-8')).toBe('# Bare'); expect(result.stdout + result.stderr).toContain('Preserved'); }); +test('removes a block written under a CODEX_HOME override after the override is unset', () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-moved-')); + const home = join(root, 'home'); + const bin = join(root, 'bin'); + const dbPath = join(root, 'recall.db'); + const codexHome = join(root, 'codex-home'); + const codexPolicy = join(codexHome, 'gap', 'global-agent-policy.md'); + const gap = '\nPolicy.\n\n'; + for (const dir of [home, bin, dirname(codexPolicy), join(home, '.gap')]) mkdirSync(dir, { recursive: true }); + writeFileSync(join(bin, 'gap'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + writeFileSync(codexPolicy, gap); + writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify({ [codexPolicy]: 'h1' })); + const env: NodeJS.ProcessEnv = { + TMPDIR: tmpdir(), + HOME: home, + PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin`, + RECALL_DB_PATH: dbPath, + RECALL_HOME: join(home, '.agents', 'Recall'), + RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', + CODEX_HOME: codexHome, + }; + const cli = join(REPO, 'src', 'index.ts'); + expect(spawnSync(process.execPath, [cli, 'init'], { env, encoding: 'utf-8' }).status).toBe(0); + const seed = spawnSync( + process.execPath, + [ + '-e', + `const { Database } = require('bun:sqlite'); + const db = new Database(process.argv[1]); + db.query("INSERT INTO decisions (project, decision, status, importance, provenance, confidence) VALUES ('alpha', 'Keep the release notes short.', 'active', 9, 'user_authored', 'high')").run(); + db.close();`, + dbPath, + ], + { env, encoding: 'utf-8' }, + ); + expect(seed.status).toBe(0); + expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(0); + expect(readFileSync(codexPolicy, 'utf-8')).toContain('- Keep the release notes short.'); + + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: dbPath, CODEX_HOME: '' }); + expect(result.status).toBe(0); + expect(readFileSync(codexPolicy, 'utf-8')).toBe(gap); + }); }); + diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 54da62c0..540a3d10 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -653,4 +653,41 @@ describe("learned tail end to end", () => { expect(writeIfUnchanged(policy, plan.beforeHash, plan.after).status).toBe("refused"); expect(readFileSync(policy, "utf8")).toBe(`${pair}edited\n`); }); +test("(o) rows with no session ID are not separate sessions, so two CLI adds of one rule stay out of the tail", () => { + const rule = "Rebuild the plugin bundles after editing a skill."; + for (const project of ["alpha", "bravo"]) { + expect( + recall(["add", "learning", "Stale plugin bundle", rule, "-p", project]).status, + ).toBe(0); + } + const plan = JSON.parse(recall(["learn", "--dry-run", "--json"]).stdout) as { + selection: { + notes: Array<{ text: string; sessions: number }>; + dropped: Array<{ reason: string }>; + }; + }; + expect(plan.selection.notes.map((n) => n.text)).toEqual([NOTE]); + expect(plan.selection.notes[0]?.sessions).toBe(0); + expect(plan.selection.dropped.some((d) => d.reason === "unproven")).toBe( + true, + ); + + const row = (id: number, sessionId: string | null): TailCandidate => ({ + table: "learnings", + id, + text: rule, + project: "alpha", + importance: 5, + provenance: "extracted", + confidence: "medium", + accessCount: 0, + sessionId, + createdAt: FIRST_SEEN, + }); + const known = selectTail([row(1, "s1"), row(2, "s2"), row(3, null)], { + cap: false, + }); + expect(known.notes.map((n) => [n.text, n.sessions])).toEqual([[rule, 2]]); + }); }); + From ce6eea11d64b721e8a45ea023673950a9e39228f Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:33:46 -0500 Subject: [PATCH 04/12] fix(learn): keep an install-scoped inventory of written tail destinations - tail: record landed destinations in ~/.agents/Recall/learned-tail-destinations.json, independent of RECALL_DB_PATH - learn: record destinations on partly refused runs without advancing the refresh state - uninstall: read that inventory, so a block is found after CODEX_HOME, JCODE_HOME or RECALL_DB_PATH changes Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 71 ++++++++++++++++++--------------- packaging/uninstall.sh | 5 ++- src/commands/learn.ts | 2 +- src/lib/learned-tail.ts | 2 + tests/install/uninstall.test.ts | 17 +++++--- 5 files changed, 56 insertions(+), 41 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 3eaf568b..09b27a7c 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -13,6 +13,7 @@ import { existsSync, fsyncSync, lstatSync, + mkdirSync, openSync, readFileSync, renameSync, @@ -163,6 +164,7 @@ export interface TailDestinationPlan { export interface TailPlan { date: string; + inventory?: string; gap: boolean; selection: TailSelection; block: string | null; @@ -815,11 +817,9 @@ export function gapPolicyDestinations(env: TailEnv = {}): string[] { return [...new Set(out)].sort(compareText); } -export function learnedTailCleanupPaths( - env: TailEnv & { dbPath?: string } = {}, -): string[] { +export function learnedTailCleanupPaths(env: TailEnv = {}): string[] { const { home } = resolveEnv(env); - const written = readTailState(tailStatePath(env.dbPath)).destinations; + const written = readTailInventory(tailInventoryPath(env)); return [ ...new Set([ ...gapPolicyDestinations(env), @@ -905,7 +905,23 @@ export const TAIL_STATE_FILE = "learned-tail-state.json"; export interface TailState { refreshedAt: number; tailSince: Record; - destinations: string[]; +} + +export const TAIL_INVENTORY_FILE = "learned-tail-destinations.json"; + +export function tailInventoryPath(env: TailEnv = {}): string { + return join(resolveEnv(env).home, ".agents", "Recall", TAIL_INVENTORY_FILE); +} + +export function readTailInventory(path: string): string[] { + try { + const parsed: unknown = JSON.parse(readFileSync(path, "utf8")); + return Array.isArray(parsed) + ? parsed.filter((p): p is string => typeof p === "string" && isAbsolute(p)) + : []; + } catch { + return []; + } } export function tailNoteKey(text: string): string { @@ -925,32 +941,27 @@ export function readTailState(path: string): TailState { if (typeof v === "string" && !Number.isNaN(Date.parse(v))) since[k] = v; } } - const destinations = Array.isArray(parsed?.destinations) - ? parsed.destinations.filter( - (p: unknown): p is string => typeof p === "string" && isAbsolute(p), - ) - : []; return { refreshedAt: Number.isFinite(parsed?.refreshedAt) && parsed.refreshedAt > 0 ? parsed.refreshedAt : 0, tailSince: since, - destinations, }; } catch { - return { refreshedAt: 0, tailSince: {}, destinations: [] }; + return { refreshedAt: 0, tailSince: {} }; } } -export function writeTailState(path: string, state: TailState): void { +function writeJsonFile(path: string, value: unknown): void { + mkdirSync(dirname(path), { recursive: true }); const tmp = join( dirname(path), `.${basename(path)}.${process.pid}-${randomBytes(6).toString("hex")}.tmp`, ); const fd = openSync(tmp, "wx", 0o600); try { - writeSync(fd, JSON.stringify(state)); + writeSync(fd, JSON.stringify(value)); fsyncSync(fd); } finally { closeSync(fd); @@ -997,18 +1008,15 @@ export function nextTailState( const since = written.has(key) ? state.tailSince[key] : undefined; tailSince[key] = since ?? now.toISOString(); } - return { - refreshedAt: now.getTime(), - tailSince, - destinations: state.destinations, - }; + return { refreshedAt: now.getTime(), tailSince }; } -function landedDestinations( - previous: string[], - plan: TailPlan, +export function recordTailDestinations( + path: string, + plan: Pick, writes: TailWriteResult[], -): string[] { +): void { + const previous = readTailInventory(path); const out = new Set(previous); for (const w of writes) { if (w.status !== "written" && w.status !== "unchanged") continue; @@ -1016,7 +1024,8 @@ function landedDestinations( if (after !== undefined && readRecallBlock(after).present) out.add(w.path); else out.delete(w.path); } - return [...out].sort(compareText); + const next = [...out].sort(compareText); + if (next.join("\n") !== previous.join("\n")) writeJsonFile(path, next); } export function recordTailRefresh( @@ -1025,23 +1034,18 @@ export function recordTailRefresh( writes: TailWriteResult[], now: Date = new Date(), ): boolean { - const state = readTailState(path); - const destinations = landedDestinations(state.destinations, plan, writes); - const moved = destinations.join("\n") !== state.destinations.join("\n"); - if (writes.some((w) => w.status === "refused")) { - if (moved) writeTailState(path, { ...state, destinations }); - return false; - } + if (plan.inventory) recordTailDestinations(plan.inventory, plan, writes); + if (writes.some((w) => w.status === "refused")) return false; const landed = writes.some( (w) => w.status === "written" || w.status === "unchanged", ); const written = readWrittenTailKeys( (plan.destinations ?? []).map((d) => d.before), ); - writeTailState( + writeJsonFile( path, nextTailState( - { ...state, destinations }, + readTailState(path), landed ? plan.selection.notes : [], now, written, @@ -1125,6 +1129,7 @@ export function planLearnedTail(options: PlanTailOptions = {}): TailPlan { }); return { date, + inventory: tailInventoryPath(options), gap: scan.gap, selection, block: selection.notes.length diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index a762a0b3..8b87758f 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -397,8 +397,9 @@ remove_extract_prompt_if_unmodified() { # Every harness file the learned tail may ever have written: each GAP policy # destination (CODEX_HOME and JCODE_HOME included, whatever the ledger says now, # since GAP may have been installed or removed after a write), every built-in -# file, and each destination learned-tail-state.json recorded a write to (so a -# block written under a since-changed CODEX_HOME or JCODE_HOME is still found). The list and the marker rules come from hooks/lib/learned-tail.ts, the +# file, and each destination recorded in ~/.agents/Recall/learned-tail-destinations.json +# (so a block written under a since-changed CODEX_HOME, JCODE_HOME or RECALL_DB_PATH +# is still found). The list and the marker rules come from hooks/lib/learned-tail.ts, the # same code `recall learn` uses. A missing file is skipped by remove_recall_block. RECALL_TAIL_LIB="$SCRIPT_DIR/../hooks/lib/learned-tail.ts" diff --git a/src/commands/learn.ts b/src/commands/learn.ts index 7ff2b2f4..b9821b83 100644 --- a/src/commands/learn.ts +++ b/src/commands/learn.ts @@ -123,7 +123,7 @@ export function runLearn(options: LearnOptions = {}): void { const dryRun = options.dryRun === true; const writes = dryRun ? null : writeLearnedTail(plan); if (writes?.some((w) => w.status === "refused")) process.exitCode = 1; - else if (writes) { + if (writes) { try { recordTailRefresh(tailStatePath(), plan, writes); } catch (err) { diff --git a/src/lib/learned-tail.ts b/src/lib/learned-tail.ts index 851663d2..62f0297a 100644 --- a/src/lib/learned-tail.ts +++ b/src/lib/learned-tail.ts @@ -25,6 +25,7 @@ export { planRecallBlockRemoval, readGapCoverageText, readRecallBlock, + readTailInventory, readTailState, readWrittenTailKeysFrom, recordTailRefresh, @@ -33,6 +34,7 @@ export { selectTail, spliceRecallBlock, tailNoteKey, + tailInventoryPath, tailStatePath, writeIfUnchanged, writeLearnedTail, diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 67f8b14a..7c47c857 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -1053,7 +1053,8 @@ describe('learned-tail block removal', () => { expect(readFileSync(bare, 'utf-8')).toBe('# Bare'); expect(result.stdout + result.stderr).toContain('Preserved'); }); -test('removes a block written under a CODEX_HOME override after the override is unset', () => { + + test('removes blocks a partly refused learn wrote under CODEX_HOME and RECALL_DB_PATH overrides after both are unset', () => { const root = mkdtempSync(join(tmpdir(), 'recall-tail-moved-')); const home = join(root, 'home'); const bin = join(root, 'bin'); @@ -1061,10 +1062,13 @@ test('removes a block written under a CODEX_HOME override after the override is const codexHome = join(root, 'codex-home'); const codexPolicy = join(codexHome, 'gap', 'global-agent-policy.md'); const gap = '\nPolicy.\n\n'; - for (const dir of [home, bin, dirname(codexPolicy), join(home, '.gap')]) mkdirSync(dir, { recursive: true }); + const claudePolicy = join(home, '.claude', 'rules', 'global-agent-policy.md'); + const malformed = `${gap}\n\n\n`; + for (const dir of [home, bin, dirname(codexPolicy), dirname(claudePolicy), join(home, '.gap')]) mkdirSync(dir, { recursive: true }); writeFileSync(join(bin, 'gap'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); writeFileSync(codexPolicy, gap); - writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify({ [codexPolicy]: 'h1' })); + writeFileSync(claudePolicy, malformed); + writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify({ [codexPolicy]: 'h1', [claudePolicy]: 'h2' })); const env: NodeJS.ProcessEnv = { TMPDIR: tmpdir(), HOME: home, @@ -1089,12 +1093,15 @@ test('removes a block written under a CODEX_HOME override after the override is { env, encoding: 'utf-8' }, ); expect(seed.status).toBe(0); - expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(0); + expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(1); expect(readFileSync(codexPolicy, 'utf-8')).toContain('- Keep the release notes short.'); + expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); + expect(existsSync(join(root, 'learned-tail-state.json'))).toBe(false); - const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: dbPath, CODEX_HOME: '' }); + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); expect(result.status).toBe(0); expect(readFileSync(codexPolicy, 'utf-8')).toBe(gap); + expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); }); }); From f078d29e66e5ee4787f5fa9dc05b5885cd4275c8 Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:48:33 -0500 Subject: [PATCH 05/12] fix(learn): register tail destinations before writing them - tail: append each destination to an install-scoped inventory before its block is written, so concurrent refreshes never drop one - tail: refuse a write whose destination cannot be recorded for uninstall - uninstall: clean the known files and report incomplete cleanup when the inventory is unreadable Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 70 ++++++++++++++++++------------- packaging/uninstall.sh | 27 +++++++++--- src/lib/learned-tail.ts | 1 + tests/install/uninstall.test.ts | 73 +++++++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 34 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 09b27a7c..321f36f7 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -7,6 +7,7 @@ import { Database } from "bun:sqlite"; import { createHash, randomBytes } from "node:crypto"; import { accessSync, + appendFileSync, chmodSync, closeSync, constants, @@ -817,16 +818,27 @@ export function gapPolicyDestinations(env: TailEnv = {}): string[] { return [...new Set(out)].sort(compareText); } -export function learnedTailCleanupPaths(env: TailEnv = {}): string[] { +export function learnedTailCleanupPaths(env: TailEnv = {}): { + paths: string[]; + inventoryError: string | null; +} { const { home } = resolveEnv(env); - const written = readTailInventory(tailInventoryPath(env)); - return [ + const inventory = tailInventoryPath(env); + let written: string[] = []; + let inventoryError: string | null = null; + try { + written = readTailInventory(inventory); + } catch (err) { + inventoryError = `${inventory}: ${err instanceof Error ? err.message : String(err)}`; + } + const paths = [ ...new Set([ ...gapPolicyDestinations(env), ...BUILTIN_TAIL_FILES.map((rel) => join(home, rel)), ...written, ]), ].sort(compareText); + return { paths, inventoryError }; } export function findTailDestinations(env: TailEnv = {}): TailDestinationScan { @@ -907,21 +919,30 @@ export interface TailState { tailSince: Record; } -export const TAIL_INVENTORY_FILE = "learned-tail-destinations.json"; +export const TAIL_INVENTORY_FILE = "learned-tail-destinations.txt"; export function tailInventoryPath(env: TailEnv = {}): string { return join(resolveEnv(env).home, ".agents", "Recall", TAIL_INVENTORY_FILE); } export function readTailInventory(path: string): string[] { + let text: string; try { - const parsed: unknown = JSON.parse(readFileSync(path, "utf8")); - return Array.isArray(parsed) - ? parsed.filter((p): p is string => typeof p === "string" && isAbsolute(p)) - : []; - } catch { - return []; + text = readFileSync(path, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return []; + throw err; } + return [ + ...new Set(text.split("\n").filter((p) => p !== "" && isAbsolute(p))), + ].sort(compareText); +} + +export function registerTailDestination(inventory: string, path: string): void { + if (/[\r\n]/.test(path)) throw new Error("path contains a line break"); + if (readTailInventory(inventory).includes(path)) return; + mkdirSync(dirname(inventory), { recursive: true }); + appendFileSync(inventory, `${path}\n`, { mode: 0o600 }); } export function tailNoteKey(text: string): string { @@ -1011,30 +1032,12 @@ export function nextTailState( return { refreshedAt: now.getTime(), tailSince }; } -export function recordTailDestinations( - path: string, - plan: Pick, - writes: TailWriteResult[], -): void { - const previous = readTailInventory(path); - const out = new Set(previous); - for (const w of writes) { - if (w.status !== "written" && w.status !== "unchanged") continue; - const after = plan.destinations?.find((d) => d.path === w.path)?.after; - if (after !== undefined && readRecallBlock(after).present) out.add(w.path); - else out.delete(w.path); - } - const next = [...out].sort(compareText); - if (next.join("\n") !== previous.join("\n")) writeJsonFile(path, next); -} - export function recordTailRefresh( path: string, plan: TailPlan, writes: TailWriteResult[], now: Date = new Date(), ): boolean { - if (plan.inventory) recordTailDestinations(plan.inventory, plan, writes); if (writes.some((w) => w.status === "refused")) return false; const landed = writes.some( (w) => w.status === "written" || w.status === "unchanged", @@ -1219,6 +1222,17 @@ export function writeLearnedTail(plan: TailPlan): TailWriteResult[] { return plan.destinations.map((d) => { if (d.refused) return { path: d.path, status: "refused", reason: d.refused }; + if (plan.inventory && readRecallBlock(d.after).present) { + try { + registerTailDestination(plan.inventory, d.path); + } catch (err) { + return { + path: d.path, + status: "refused", + reason: `cannot record it for uninstall: ${err instanceof Error ? err.message : String(err)}`, + }; + } + } if (!d.changed) return { path: d.path, status: "unchanged" }; return writeIfUnchanged(d.path, d.beforeHash, d.after); }); diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index 8b87758f..98ea87cf 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -397,16 +397,23 @@ remove_extract_prompt_if_unmodified() { # Every harness file the learned tail may ever have written: each GAP policy # destination (CODEX_HOME and JCODE_HOME included, whatever the ledger says now, # since GAP may have been installed or removed after a write), every built-in -# file, and each destination recorded in ~/.agents/Recall/learned-tail-destinations.json -# (so a block written under a since-changed CODEX_HOME, JCODE_HOME or RECALL_DB_PATH -# is still found). The list and the marker rules come from hooks/lib/learned-tail.ts, the -# same code `recall learn` uses. A missing file is skipped by remove_recall_block. +# file, and each destination recorded in ~/.agents/Recall/learned-tail-destinations.txt +# before a block was written there (so a block written under a since-changed +# CODEX_HOME, JCODE_HOME or RECALL_DB_PATH is still found). The list and the marker +# rules come from hooks/lib/learned-tail.ts, the same code `recall learn` uses. A +# missing file is skipped by remove_recall_block. Exit 3 means the inventory could +# not be read: the listed files are still cleaned, but cleanup is incomplete. RECALL_TAIL_LIB="$SCRIPT_DIR/../hooks/lib/learned-tail.ts" recall_learned_tail_files() { RECALL_TAIL_LIB="$RECALL_TAIL_LIB" RECALL_TAIL_HOME="$HOME" bun -e ' const { learnedTailCleanupPaths } = require(process.env.RECALL_TAIL_LIB); - process.stdout.write(learnedTailCleanupPaths({ home: process.env.RECALL_TAIL_HOME }).join("\n")); + const { paths, inventoryError } = learnedTailCleanupPaths({ home: process.env.RECALL_TAIL_HOME }); + process.stdout.write(paths.join("\n")); + if (inventoryError) { + process.stderr.write(inventoryError + "\n"); + process.exit(3); + } ' } @@ -828,12 +835,20 @@ main() { log_info "Removing learned-tail blocks..." local tail_file local tail_files + local tail_status=0 + if command -v bun &>/dev/null; then + tail_files="$(recall_learned_tail_files)" || tail_status=$? + fi if ! command -v bun &>/dev/null; then log_warn "bun not found; learned-tail blocks left in place (remove the ... lines by hand)" - elif ! tail_files="$(recall_learned_tail_files)"; then + elif [[ "$tail_status" -ne 0 && "$tail_status" -ne 3 ]]; then log_warn "Could not list learned-tail files; blocks left in place" lifecycle_failed=true else + if [[ "$tail_status" -eq 3 ]]; then + log_warn "Could not read the learned-tail inventory; blocks written under a changed CODEX_HOME, JCODE_HOME or RECALL_DB_PATH may remain" + lifecycle_failed=true + fi while IFS= read -r tail_file; do [[ -n "$tail_file" ]] || continue if ! remove_recall_block "$tail_file"; then diff --git a/src/lib/learned-tail.ts b/src/lib/learned-tail.ts index 62f0297a..bcaa9372 100644 --- a/src/lib/learned-tail.ts +++ b/src/lib/learned-tail.ts @@ -26,6 +26,7 @@ export { readGapCoverageText, readRecallBlock, readTailInventory, + registerTailDestination, readTailState, readWrittenTailKeysFrom, recordTailRefresh, diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 7c47c857..9971b149 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -1103,5 +1103,78 @@ describe('learned-tail block removal', () => { expect(readFileSync(codexPolicy, 'utf-8')).toBe(gap); expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); }); +function tailHome(root: string) { + const home = join(root, 'home'); + const bin = join(root, 'bin'); + for (const dir of [home, bin, join(home, '.gap')]) mkdirSync(dir, { recursive: true }); + writeFileSync(join(bin, 'gap'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + const gap = '\nPolicy.\n\n'; + const cli = join(REPO, 'src', 'index.ts'); + const policies: string[] = []; + const learnEnv = (name: string): { env: NodeJS.ProcessEnv; policy: string } => { + const codexHome = join(root, `codex-${name}`); + const policy = join(codexHome, 'gap', 'global-agent-policy.md'); + mkdirSync(dirname(policy), { recursive: true }); + writeFileSync(policy, gap); + policies.push(policy); + writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify(Object.fromEntries(policies.map((p) => [p, 'h'])))); + const dbPath = join(root, `${name}.db`); + const env: NodeJS.ProcessEnv = { + TMPDIR: tmpdir(), + HOME: home, + PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin`, + RECALL_DB_PATH: dbPath, + RECALL_HOME: join(home, '.agents', 'Recall'), + RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', + CODEX_HOME: codexHome, + }; + expect(spawnSync(process.execPath, [cli, 'init'], { env, encoding: 'utf-8' }).status).toBe(0); + const seed = spawnSync( + process.execPath, + [ + '-e', + `const { Database } = require('bun:sqlite'); + const db = new Database(process.argv[1]); + db.query("INSERT INTO decisions (project, decision, status, importance, provenance, confidence) VALUES ('alpha', 'Keep the release notes short.', 'active', 9, 'user_authored', 'high')").run(); + db.close();`, + dbPath, + ], + { env, encoding: 'utf-8' }, + ); + expect(seed.status).toBe(0); + return { env, policy }; + }; + return { home, gap, cli, learnEnv }; + } + + test('keeps every destination recorded when refreshes for different harness homes run at once', async () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-race-')); + const { home, gap, cli, learnEnv } = tailHome(root); + const runs = ['a', 'b', 'c', 'd', 'e', 'f'].map(learnEnv); + const exits = await Promise.all( + runs.map(({ env }) => Bun.spawn([process.execPath, cli, 'learn'], { env, stdout: 'ignore', stderr: 'ignore' }).exited), + ); + expect(exits).toEqual(runs.map(() => 0)); + for (const { policy } of runs) expect(readFileSync(policy, 'utf-8')).toContain('- Keep the release notes short.'); + + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); + expect(result.status).toBe(0); + for (const { policy } of runs) expect(readFileSync(policy, 'utf-8')).toBe(gap); + }); + + test('refuses a write it cannot record for cleanup, and uninstall reports an unreadable inventory as incomplete', () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-inventory-')); + const { home, gap, cli, learnEnv } = tailHome(root); + mkdirSync(join(home, '.agents', 'Recall', 'learned-tail-destinations.txt'), { recursive: true }); + const { env, policy } = learnEnv('a'); + const learn = spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }); + expect(learn.status).toBe(1); + expect(readFileSync(policy, 'utf-8')).toBe(gap); + + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); + expect(result.status).not.toBe(0); + expect(result.stdout + result.stderr).toContain('learned-tail inventory'); + expect(result.stdout).toContain('Uninstall Incomplete'); + }); }); From 6eef1a4ceee64296ddc5f459f70595709b10a76f Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:03:19 -0500 Subject: [PATCH 06/12] fix(learn): delimit each tail inventory record on both sides - tail: write each registration as its own line, so an unterminated fragment from a failed append cannot absorb it - tail: confirm the registration reads back before writing the block - test: share one learned-tail uninstall fixture across the inventory tests Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 4 +- tests/install/uninstall.test.ts | 95 ++++++++++++++------------------- 2 files changed, 43 insertions(+), 56 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 321f36f7..e85cd445 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -942,7 +942,9 @@ export function registerTailDestination(inventory: string, path: string): void { if (/[\r\n]/.test(path)) throw new Error("path contains a line break"); if (readTailInventory(inventory).includes(path)) return; mkdirSync(dirname(inventory), { recursive: true }); - appendFileSync(inventory, `${path}\n`, { mode: 0o600 }); + appendFileSync(inventory, `\n${path}\n`, { mode: 0o600 }); + if (!readTailInventory(inventory).includes(path)) + throw new Error("registration did not land"); } export function tailNoteKey(text: string): string { diff --git a/tests/install/uninstall.test.ts b/tests/install/uninstall.test.ts index 9971b149..5ab95e4e 100644 --- a/tests/install/uninstall.test.ts +++ b/tests/install/uninstall.test.ts @@ -1054,70 +1054,21 @@ describe('learned-tail block removal', () => { expect(result.stdout + result.stderr).toContain('Preserved'); }); - test('removes blocks a partly refused learn wrote under CODEX_HOME and RECALL_DB_PATH overrides after both are unset', () => { - const root = mkdtempSync(join(tmpdir(), 'recall-tail-moved-')); - const home = join(root, 'home'); - const bin = join(root, 'bin'); - const dbPath = join(root, 'recall.db'); - const codexHome = join(root, 'codex-home'); - const codexPolicy = join(codexHome, 'gap', 'global-agent-policy.md'); - const gap = '\nPolicy.\n\n'; - const claudePolicy = join(home, '.claude', 'rules', 'global-agent-policy.md'); - const malformed = `${gap}\n\n\n`; - for (const dir of [home, bin, dirname(codexPolicy), dirname(claudePolicy), join(home, '.gap')]) mkdirSync(dir, { recursive: true }); - writeFileSync(join(bin, 'gap'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); - writeFileSync(codexPolicy, gap); - writeFileSync(claudePolicy, malformed); - writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify({ [codexPolicy]: 'h1', [claudePolicy]: 'h2' })); - const env: NodeJS.ProcessEnv = { - TMPDIR: tmpdir(), - HOME: home, - PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin`, - RECALL_DB_PATH: dbPath, - RECALL_HOME: join(home, '.agents', 'Recall'), - RECALL_SKIP_LEGACY_DATA_MIGRATIONS: '1', - CODEX_HOME: codexHome, - }; - const cli = join(REPO, 'src', 'index.ts'); - expect(spawnSync(process.execPath, [cli, 'init'], { env, encoding: 'utf-8' }).status).toBe(0); - const seed = spawnSync( - process.execPath, - [ - '-e', - `const { Database } = require('bun:sqlite'); - const db = new Database(process.argv[1]); - db.query("INSERT INTO decisions (project, decision, status, importance, provenance, confidence) VALUES ('alpha', 'Keep the release notes short.', 'active', 9, 'user_authored', 'high')").run(); - db.close();`, - dbPath, - ], - { env, encoding: 'utf-8' }, - ); - expect(seed.status).toBe(0); - expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(1); - expect(readFileSync(codexPolicy, 'utf-8')).toContain('- Keep the release notes short.'); - expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); - expect(existsSync(join(root, 'learned-tail-state.json'))).toBe(false); - - const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); - expect(result.status).toBe(0); - expect(readFileSync(codexPolicy, 'utf-8')).toBe(gap); - expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); - }); -function tailHome(root: string) { + function tailHome(root: string) { const home = join(root, 'home'); const bin = join(root, 'bin'); for (const dir of [home, bin, join(home, '.gap')]) mkdirSync(dir, { recursive: true }); writeFileSync(join(bin, 'gap'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); const gap = '\nPolicy.\n\n'; const cli = join(REPO, 'src', 'index.ts'); - const policies: string[] = []; + const ledger: string[] = []; const learnEnv = (name: string): { env: NodeJS.ProcessEnv; policy: string } => { const codexHome = join(root, `codex-${name}`); const policy = join(codexHome, 'gap', 'global-agent-policy.md'); mkdirSync(dirname(policy), { recursive: true }); writeFileSync(policy, gap); - policies.push(policy); - writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify(Object.fromEntries(policies.map((p) => [p, 'h'])))); + ledger.push(policy); + writeFileSync(join(home, '.gap', 'published.json'), JSON.stringify(Object.fromEntries(ledger.map((p) => [p, 'h'])))); const dbPath = join(root, `${name}.db`); const env: NodeJS.ProcessEnv = { TMPDIR: tmpdir(), @@ -1144,9 +1095,29 @@ function tailHome(root: string) { expect(seed.status).toBe(0); return { env, policy }; }; - return { home, gap, cli, learnEnv }; + return { home, gap, cli, ledger, learnEnv }; } + test('removes blocks a partly refused learn wrote under CODEX_HOME and RECALL_DB_PATH overrides after both are unset', () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-moved-')); + const { home, gap, cli, ledger, learnEnv } = tailHome(root); + const claudePolicy = join(home, '.claude', 'rules', 'global-agent-policy.md'); + const malformed = `${gap}\n\n\n`; + mkdirSync(dirname(claudePolicy), { recursive: true }); + writeFileSync(claudePolicy, malformed); + ledger.push(claudePolicy); + const { env, policy } = learnEnv('a'); + expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(1); + expect(readFileSync(policy, 'utf-8')).toContain('- Keep the release notes short.'); + expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); + expect(existsSync(join(root, 'learned-tail-state.json'))).toBe(false); + + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); + expect(result.status).toBe(0); + expect(readFileSync(policy, 'utf-8')).toBe(gap); + expect(readFileSync(claudePolicy, 'utf-8')).toBe(malformed); + }); + test('keeps every destination recorded when refreshes for different harness homes run at once', async () => { const root = mkdtempSync(join(tmpdir(), 'recall-tail-race-')); const { home, gap, cli, learnEnv } = tailHome(root); @@ -1176,5 +1147,19 @@ function tailHome(root: string) { expect(result.stdout + result.stderr).toContain('learned-tail inventory'); expect(result.stdout).toContain('Uninstall Incomplete'); }); -}); + test('a registration left unterminated by a failed append does not swallow the next one', () => { + const root = mkdtempSync(join(tmpdir(), 'recall-tail-short-')); + const { home, gap, cli, learnEnv } = tailHome(root); + const inventory = join(home, '.agents', 'Recall', 'learned-tail-destinations.txt'); + mkdirSync(dirname(inventory), { recursive: true }); + writeFileSync(inventory, join(root, 'codex-old', 'gap', 'global-agent')); + const { env, policy } = learnEnv('b'); + expect(spawnSync(process.execPath, [cli, 'learn'], { env, encoding: 'utf-8' }).status).toBe(0); + expect(readFileSync(policy, 'utf-8')).toContain('- Keep the release notes short.'); + + const result = runUninstall(home, join(root, 'backups'), [], { RECALL_DB_PATH: '', CODEX_HOME: '' }); + expect(result.status).toBe(0); + expect(readFileSync(policy, 'utf-8')).toBe(gap); + }); +}); From 4db9084d67c9dc09fa0655d4002c4180931f50fa Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:15:55 -0500 Subject: [PATCH 07/12] fix(learn): keep case inside code spans of any backtick length - tail: match inline code spans with any opening backtick run, not only single backticks Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 11 +++++++---- tests/learned-tail.test.ts | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index e85cd445..e3b5c4ed 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -337,10 +337,13 @@ export function sanitizeTailBullet(raw: string): BulletCheck { } function foldCase(text: string): string { - return text - .split(/(`[^`]*`)/) - .map((part, i) => (i % 2 === 1 ? part : part.toLowerCase())) - .join(""); + let out = ""; + let at = 0; + for (const span of text.matchAll(/(`+)[\s\S]*?[^`]\1(?!`)/g)) { + out += text.slice(at, span.index).toLowerCase() + span[0]; + at = span.index + span[0].length; + } + return out + text.slice(at).toLowerCase(); } function matchForm(text: string): string { diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 540a3d10..652b8251 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -578,6 +578,12 @@ describe("learned tail end to end", () => { expect(isCoveredByGap(lower, `- ${upper}`)).toBe(false); expect(isCoveredByGap("USE `PATH` IN THE FIXTURE", `- ${upper}`)).toBe(true); expect(tailNoteKey(upper)).not.toBe(tailNoteKey(lower)); + expect(tailNoteKey("Run ``A`b`` first.")).not.toBe( + tailNoteKey("Run ``a`b`` first."), + ); + expect(tailNoteKey("RUN ``A`b`` FIRST.")).toBe( + tailNoteKey("run ``A`b`` first."), + ); }); test("(m) only GAP policy destinations get the tail: a ledgered command file is skipped, and an absolute CODEX_HOME or JCODE_HOME outside HOME is used", () => { From 27eac69cfcad5318a748ff2cb3df656e62106cfa Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:28:29 -0500 Subject: [PATCH 08/12] fix(learn): pair only complete equal-length backtick runs as code spans - tail: treat an unmatched backtick run as prose so it cannot consume the next span's opener Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 19 ++++++++++++++----- tests/learned-tail.test.ts | 9 +++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index e3b5c4ed..dc8cd205 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -337,13 +337,22 @@ export function sanitizeTailBullet(raw: string): BulletCheck { } function foldCase(text: string): string { + const runs = [...text.matchAll(/`+/g)].map((m) => ({ + start: m.index, + length: m[0].length, + })); let out = ""; let at = 0; - for (const span of text.matchAll(/(`+)[\s\S]*?[^`]\1(?!`)/g)) { - out += text.slice(at, span.index).toLowerCase() + span[0]; - at = span.index + span[0].length; - } - return out + text.slice(at).toLowerCase(); + for (let i = 0; i < runs.length; i++) { + const open = runs[i]; + const close = runs.findIndex((r, j) => j > i && r.length === open.length); + if (close < 0) continue; + const end = runs[close].start + runs[close].length; + out += text.slice(at, open.start).toLowerCase() + text.slice(open.start, end); + at = end; + i = close; + } + return out + text.slice(at).toLowerCase(); } function matchForm(text: string): string { diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 652b8251..1c8873a4 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -584,6 +584,15 @@ describe("learned tail end to end", () => { expect(tailNoteKey("RUN ``A`b`` FIRST.")).toBe( tailNoteKey("run ``A`b`` first."), ); + expect(tailNoteKey("Log `` before checking `PATH`.")).not.toBe( + tailNoteKey("Log `` before checking `path`."), + ); + expect(tailNoteKey("LOG `` BEFORE checking `PATH`.")).toBe( + tailNoteKey("log `` before checking `PATH`."), + ); + expect(tailNoteKey("Use ```A`` and `B`.")).not.toBe( + tailNoteKey("Use ```A`` and `b`."), + ); }); test("(m) only GAP policy destinations get the tail: a ledgered command file is skipped, and an absolute CODEX_HOME or JCODE_HOME outside HOME is used", () => { From 925137fe9861cb42f1206ea6fbd84877760b2b68 Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:41:22 -0500 Subject: [PATCH 09/12] fix(learn): skip a backslash-escaped backtick when finding a code span opener - tail: drop an escaped leading backtick from an opener run in prose; closers inside code stay literal Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 14 +++++++++++--- tests/learned-tail.test.ts | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index dc8cd205..4eba9d89 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -344,11 +344,19 @@ function foldCase(text: string): string { let out = ""; let at = 0; for (let i = 0; i < runs.length; i++) { - const open = runs[i]; - const close = runs.findIndex((r, j) => j > i && r.length === open.length); + let { start, length } = runs[i]; + let slashes = 0; + while (start - slashes - 1 >= at && text[start - slashes - 1] === "\\") + slashes++; + if (slashes % 2 === 1) { + start++; + length--; + } + if (length === 0) continue; + const close = runs.findIndex((r, j) => j > i && r.length === length); if (close < 0) continue; const end = runs[close].start + runs[close].length; - out += text.slice(at, open.start).toLowerCase() + text.slice(open.start, end); + out += text.slice(at, start).toLowerCase() + text.slice(start, end); at = end; i = close; } diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 1c8873a4..f280fe96 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -590,6 +590,25 @@ describe("learned tail end to end", () => { expect(tailNoteKey("LOG `` BEFORE checking `PATH`.")).toBe( tailNoteKey("log `` before checking `PATH`."), ); + const escaped = "Use \\``PATH` in the fixture."; + const escapedLower = "Use \\``path` in the fixture."; + expect(tailNoteKey(escaped)).not.toBe(tailNoteKey(escapedLower)); + expect(isCoveredByGap(escaped, `- ${escapedLower}`)).toBe(false); + expect( + selectTail( + [row(4, escaped, "alpha"), row(5, escapedLower, "bravo"), row(6, escapedLower, "charlie")], + { cap: false }, + ).notes.map((n) => [n.text, n.projects]), + ).toEqual([ + [escaped, ["alpha"]], + [escapedLower, ["bravo", "charlie"]], + ]); + expect(tailNoteKey("Run \\\\`PATH` now.")).not.toBe( + tailNoteKey("Run \\\\`path` now."), + ); + expect(tailNoteKey("Run `a\\` THEN `B`.")).toBe( + tailNoteKey("Run `a\\` then `B`."), + ); expect(tailNoteKey("Use ```A`` and `B`.")).not.toBe( tailNoteKey("Use ```A`` and `b`."), ); From 54788f130f53141dc57c88caae1f0a61dd70003d Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:54:02 -0500 Subject: [PATCH 10/12] fix(learn): find code spans in the original text before NFKC - tail: detect backtick runs and escapes on the raw note, then normalize each prose and code slice separately Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 10 +++++++--- tests/learned-tail.test.ts | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 4eba9d89..df85e641 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -336,6 +336,10 @@ export function sanitizeTailBullet(raw: string): BulletCheck { return { ok: true, text }; } +function prose(text: string): string { + return text.normalize("NFKC").toLowerCase(); +} + function foldCase(text: string): string { const runs = [...text.matchAll(/`+/g)].map((m) => ({ start: m.index, @@ -356,15 +360,15 @@ function foldCase(text: string): string { const close = runs.findIndex((r, j) => j > i && r.length === length); if (close < 0) continue; const end = runs[close].start + runs[close].length; - out += text.slice(at, start).toLowerCase() + text.slice(start, end); + out += prose(text.slice(at, start)) + text.slice(start, end).normalize("NFKC"); at = end; i = close; } - return out + text.slice(at).toLowerCase(); + return out + prose(text.slice(at)); } function matchForm(text: string): string { - return foldCase(text.normalize("NFKC")) + return foldCase(text) .trim() .replace(/^(?:[-*+]|\d+[.)])\s+/, "") .replace(/[.!?;:,]+$/, "") diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index f280fe96..aaa3b8a1 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -603,6 +603,21 @@ describe("learned tail end to end", () => { [escaped, ["alpha"]], [escapedLower, ["bravo", "charlie"]], ]); + const wide = "Use \uFF3C`PATH` in the fixture."; + const wideLower = "Use \uFF3C`path` in the fixture."; + expect(tailNoteKey(wide)).not.toBe(tailNoteKey(wideLower)); + expect(isCoveredByGap(wide, `- ${wideLower}`)).toBe(false); + expect( + selectTail( + [row(7, wide, "alpha"), row(8, wideLower, "bravo"), row(9, wideLower, "charlie")], + { cap: false }, + ).notes.map((n) => [n.text, n.projects]), + ).toEqual([ + [wide, ["alpha"]], + [wideLower, ["bravo", "charlie"]], + ]); + expect(tailNoteKey("Use \uFF21\uFF22 now")).toBe(tailNoteKey("use ab now")); + expect(tailNoteKey("Use `\uFF21` now")).toBe(tailNoteKey("use `A` now")); expect(tailNoteKey("Run \\\\`PATH` now.")).not.toBe( tailNoteKey("Run \\\\`path` now."), ); From 63a6c70f028428f9e427dae13db036f583b1ce59 Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:07:41 -0500 Subject: [PATCH 11/12] fix(learn): mark code spans in the match key so normalized prose cannot pose as code - tail: wrap each code slice in a control-character mark and strip that mark from prose Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 10 ++++++++-- tests/learned-tail.test.ts | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index df85e641..02ab79b4 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -336,8 +336,14 @@ export function sanitizeTailBullet(raw: string): BulletCheck { return { ok: true, text }; } +const CODE_MARK = "\u0001"; + function prose(text: string): string { - return text.normalize("NFKC").toLowerCase(); + return text.normalize("NFKC").toLowerCase().replaceAll(CODE_MARK, ""); +} + +function code(text: string): string { + return `${CODE_MARK}${text.normalize("NFKC")}${CODE_MARK}`; } function foldCase(text: string): string { @@ -360,7 +366,7 @@ function foldCase(text: string): string { const close = runs.findIndex((r, j) => j > i && r.length === length); if (close < 0) continue; const end = runs[close].start + runs[close].length; - out += prose(text.slice(at, start)) + text.slice(start, end).normalize("NFKC"); + out += prose(text.slice(at, start)) + code(text.slice(start, end)); at = end; i = close; } diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index aaa3b8a1..8f33d730 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -617,6 +617,21 @@ describe("learned tail end to end", () => { [wideLower, ["bravo", "charlie"]], ]); expect(tailNoteKey("Use \uFF21\uFF22 now")).toBe(tailNoteKey("use ab now")); + const graves = "Set \uFF40PATH\uFF40 before testing."; + const real = "Set `path` before testing."; + expect(tailNoteKey(graves)).not.toBe(tailNoteKey(real)); + expect(isCoveredByGap(graves, `- ${real}`)).toBe(false); + expect(isCoveredByGap(real, `- ${graves}`)).toBe(false); + expect(tailNoteKey(graves)).toBe(tailNoteKey("set \uFF40path\uFF40 before testing.")); + expect( + selectTail( + [row(10, graves, "alpha"), row(11, real, "bravo"), row(12, real, "charlie")], + { cap: false }, + ).notes.map((n) => [n.text, n.projects]), + ).toEqual([ + [graves, ["alpha"]], + [real, ["bravo", "charlie"]], + ]); expect(tailNoteKey("Use `\uFF21` now")).toBe(tailNoteKey("use `A` now")); expect(tailNoteKey("Run \\\\`PATH` now.")).not.toBe( tailNoteKey("Run \\\\`path` now."), From a5059beff48ba5b0b05b072678cb31568558e8fd Mon Sep 17 00:00:00 2001 From: Atlas-Key <296298943+Atlas-Key@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:27:41 -0500 Subject: [PATCH 12/12] fix(learn): restart tail age for notes a partly refused refresh writes back - tail: on a refused refresh, reset the age of each note that landed without being in a block before, keeping the refresh time Co-authored-by: Mr. ED --- hooks/lib/learned-tail.ts | 42 +++++++++++++++++++++++--------------- tests/learned-tail.test.ts | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 17 deletions(-) diff --git a/hooks/lib/learned-tail.ts b/hooks/lib/learned-tail.ts index 02ab79b4..63a87bd4 100644 --- a/hooks/lib/learned-tail.ts +++ b/hooks/lib/learned-tail.ts @@ -1070,23 +1070,31 @@ export function recordTailRefresh( writes: TailWriteResult[], now: Date = new Date(), ): boolean { - if (writes.some((w) => w.status === "refused")) return false; - const landed = writes.some( - (w) => w.status === "written" || w.status === "unchanged", - ); - const written = readWrittenTailKeys( - (plan.destinations ?? []).map((d) => d.before), - ); - writeJsonFile( - path, - nextTailState( - readTailState(path), - landed ? plan.selection.notes : [], - now, - written, - ), - ); - return true; + const landed = writes.some( + (w) => w.status === "written" || w.status === "unchanged", + ); + const written = readWrittenTailKeys( + (plan.destinations ?? []).map((d) => d.before), + ); + const state = readTailState(path); + if (writes.some((w) => w.status === "refused")) { + if (!landed) return false; + const tailSince = { ...state.tailSince }; + let restarted = false; + for (const note of plan.selection.notes) { + const key = tailNoteKey(note.text); + if (written.has(key) || !(key in tailSince)) continue; + tailSince[key] = now.toISOString(); + restarted = true; + } + if (restarted) writeJsonFile(path, { ...state, tailSince }); + return false; + } + writeJsonFile( + path, + nextTailState(state, landed ? plan.selection.notes : [], now, written), + ); + return true; } export function countRecordsSince( diff --git a/tests/learned-tail.test.ts b/tests/learned-tail.test.ts index 8f33d730..e7154e3b 100644 --- a/tests/learned-tail.test.ts +++ b/tests/learned-tail.test.ts @@ -753,5 +753,41 @@ test("(o) rows with no session ID are not separate sessions, so two CLI adds of }); expect(known.notes.map((n) => [n.text, n.sessions])).toEqual([[rule, 2]]); }); +test("(p) a partly refused refresh still restarts the age of a note it writes back", () => { + const policy = policyPath(); + const other = join(home, ".pi", "agent", "APPEND_SYSTEM.md"); + writePolicy(policy); + writePolicy(other); + mkdirSync(join(home, ".gap"), { recursive: true }); + writeFileSync( + join(home, ".gap", "published.json"), + JSON.stringify({ [policy]: "p", [other]: "p" }), + ); + const statePath = join(dirname(dbPath), "learned-tail-state.json"); + expect(recall(["learn"]).status).toBe(0); + const key = tailNoteKey(NOTE); + const old = new Date(Date.now() - 20 * 86_400_000).toISOString(); + const before = readTailState(statePath); + writeFileSync( + statePath, + JSON.stringify({ ...before, tailSince: { [key]: old } }), + ); + const removed = removeRecallBlock(readFileSync(policy, "utf8")); + if (!removed.ok) throw new Error(removed.reason); + writeFileSync(policy, removed.text); + writeFileSync( + other, + `${readFileSync(other, "utf8")}\n`, + ); + + expect(recall(["learn"]).status).toBe(1); + expect(readFileSync(policy, "utf8")).toContain(`- ${NOTE}`); + const after = readTailState(statePath); + expect(after.refreshedAt).toBe(before.refreshedAt); + expect(after.tailSince[key]).not.toBe(old); + expect(promote().skipped).toEqual([ + { text: NOTE, reason: "0 days in the tail (need 14)" }, + ]); + }); });