Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge pull request #1352 from lhzapata/fix/notapplicable-doc
AkitaOnRailsf9b70f7a2f3e
diff --cc CHANGELOG.mdindex 1f43d2a0,975a95dc..b0018937--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -12,140 -12,10 +12,145 @@@ version in [`docs/changelog/`](docs/cha## [Unreleased]### Fixed-- Fixed the `ExtractionState::NotApplicable` doc-comment, which described- `extraction_state: "not-applicable"` as a property of the tool. It now says- the value comes from an active policy dropping a search/list tool, or from- `ai-memory hook --check-capture` when no policy was evaluated. (#1352)++- Corrected the `ExtractionState::NotApplicable` documentation and aligned the++ generated OpenCode capture policy with the native evaluator: only an active++ policy dropping a search/list tool reports `not-applicable`; an invalid++ policy reports `extracted`. `ai-memory hook --check-capture` also uses++ `not-applicable` when no policy was evaluated. (#1352)+- `ai-memory auth login openai-oauth` and `auth login copilot` no longer print+ a failed endpoint's whole response body. Error bodies are bounded, scrubbed+ of secrets and terminal control sequences, then capped for display; provider+ errors, including OIDC login and refresh, use the same ordering so a secret+ at the display boundary is still redacted. (#1359)+- Fixed OIDC device login and refresh sending credential-bearing requests to+ non-TLS endpoints. Issuers and advertised or persisted device/token endpoints+ must now use `https` outside loopback, and authentication requests do not+ follow redirects. Plain `http` remains available for local test issuers on+ `localhost`, `127.0.0.1` and `::1`. (#1354)+- Fixed `install-instructions` printing a false "Claude Code reads <file> instead+ of AGENTS.md" note when `$HOME` is reached through a symlink. The home+ `.claude/CLAUDE.md` skip now compares with the same canonicalising+ `paths_match` helper the import check uses, so a symlinked home matches its+ resolved path. (#1345)+- Corrected stale claims in `docs/comparison.md` and `docs/competitive-parity.md`+ that said Windows has no service step and the Windows install is experimental.+ The 3.1 `install.ps1` + `setup` Windows service step is shipped production,+ not experimental; the "3.0 (unreleased)" observation-stream note is corrected+ to reflect the released 3.0 line. (#1271)+- Made the executable auto-improvement eval policy server-owned. Manual CLI and+ HTTP reviews now use `[auto_improve.eval]` from the server process, and legacy+ requests that try to supply an `eval` object fail closed with an upgrade+ message.+- Made managed cross-harness continuation survive quota exhaustion without a+ voluntary handoff. The startup packet now places its server-authored resume+ directive outside the untrusted transcript fence, and refreshed+ `CLAUDE.md` / `AGENTS.md` routing tells an incoming agent that "continue",+ "resume", and "pick up where we left off" must consult the private+ `AI_MEMORY_PREVIOUS_SESSION_HISTORY` dossier when the managed-run variables+ are present. The dossier remains untrusted evidence and stays local to the+ launcher machine.+- Fixed unbounded memory use in consolidation and auto-improve for long+ sessions: both paths now read a bounded projection of the session's+ observations instead of loading every row, keeping the LLM input+ byte-identical. Sessions with no observations in the consolidator's target+ scope (purged or foreign) are refused before any work, exactly as empty+ sessions were before. (#1363)+- Fixed the session page's uncapped `## Prompts` list. Above 500 prompts the+ page now lists the first 250 titles and the last 250, numbered by their real+ position, with one line between them saying how many were left out. The+ store reads at most 500 titles for it, and the page's prompt count and the+ digest stats still report the true total. (#1349)+- Fixed auto-improve approvals that failed because a `reject`-policy admission+ webhook was unreachable, timed out, rate-limited or answered 5xx being+ stored as rejections. The proposal is still marked `failed`, but the outage+ no longer enters the rejection buffer, so later reviews are not told to+ avoid a proposal nobody refused and rejection telemetry counts only real+ refusals. (#1358)+- Fixed consolidation persisting non-page `relations:` targets in YAML+ frontmatter on disk. Raw titles containing dots, directory paths, or stemless+ `.md` strings in `relations:` were previously written into frontmatter and+ retained by `prune_relations` when `extract_relation_links` returned an empty+ list, causing the wiki watcher to emit repeated warnings on every+ reconciliation pass. Targets are now validated through `extract_relation_links`+ before frontmatter assembly and during relation pruning. (#1353, #1366)+- Consolidation now also drops well-shaped same-project `relations:` targets+ that name no existing page. Relations among pages in the same atomic batch+ remain valid, and ordinary same-project body wikilinks may still point to a+ page that will be written later. (#1353)+- Verified target latest status and expiration in+ `ReaderPool::contradiction_edges`, so a contradiction pointing at a+ tombstoned or expired page is reported as unresolved instead of active, and+ expired source pages do not emit contradiction findings. (#1367)+- Verified target latest status and expiration in+ `ReaderPool::dangling_cross_project_links`, so cross-project links to+ tombstoned or expired pages are reported as dangling instead of resolved,+ and expired source pages do not emit dangling link findings. (#1368)+- Fixed the `/web` project tree and its recent-activity list, the namespace+ listing, and the `/api/v1` `pages` list and legacy `recent` array showing+ pages whose `expires_at` TTL had passed, which search, `memory_recent`, the+ incremental `recent` form and page history already hid. A project move and+ the curator still see every current page, and an exact-path read of an+ expired page still answers. (#1369)+- Fixed `memory_read_page` returning a page whose `expires_at` TTL had passed+ with nothing to say so. The TTL design keeps an exact-path read answering for+ such a page while `memory_query`, `memory_recent` and the briefing hide it,+ and promised the response would carry `expired: true`; the flag was never+ written. The response now carries `expired: true` for an expired page, on+ both the markdown and the DB-fallback branch, and is unchanged for a live+ one. (#1371)+- Fixed the `/web` page view showing a page whose `expires_at` TTL had passed+ exactly like a live one, although search and the project listings leave such+ a page out. The metadata row now carries an `expired` badge beside the tier+ and kind; a live page renders as before. (#1372)+- Fixed `GET /admin/read-page` and `ai-memory read-page` returning a page whose+ `expires_at` TTL had passed with nothing to say so, although `search` no+ longer lists such a page. The response now carries `expired: true` for an+ expired page, on both the markdown and the DB-fallback branch, and+ `read-page` prints an `expired: true` line (the field also appears in+ `--json`); a live page's output is unchanged. (#1373)+- Fixed web wikilink rendering generating dead links for directory and stemless+ targets. In markdown pages, wikilinks pointing to a directory (`[[notes/]]`) or+ a stemless target (`[[notes/.md]]`, `[[.md]]`) were rewritten into invalid+ page links that yielded 404 responses in the web browser. They now remain as+ literal text, aligning web wikilink preprocessing with the wiki engine's link+ extractor. (#1364)+- `install-mcp` now writes the absolute path of the `ai-memory` binary as the+ `command` of every stdio bridge entry (Claude Code's session-aware entry,+ Muse Code and the session-less bridge of the other clients), as hook+ commands already did. A client started without `~/.local/bin` on its `PATH`+ no longer fails to spawn the bridge. The Docker wrapper keeps the bare+ `ai-memory`, and existing entries with either form are still recognized.+ (#1362)++- Fixed the session-start brief hiding a page's body behind a longer+ frontmatter excerpt. When a pinned, `_rules/` or `_slots/` page had a+ `summary:` or `abstract:` longer than its body, the brief printed that+ excerpt instead of the body, however much of `[briefing] max_chars` was+ left, so a small wiki whose pages fit did not get every body whole. Such a+ body now shows whole: it is priced at its own size when the brief decides+ which pages fit, and the bytes it saves over the excerpt go to other pages.+ A page with an empty body keeps its excerpt. (#1360)+- Fixed `ai-memory setup` wiring OpenCode 2 with OpenCode 1 artifacts. A+ named `--agent opencode` (or `open-code`), or an OpenCode found by the+ session store both majors share, always got the V1 function plugin+ `plugins/ai-memory.ts` and a direct `mcp.ai-memory` entry, which OpenCode+ 2 does not load. `setup` now runs `opencode --version` once, as+ `install-mcp` and `install-hooks` already did for the generic spelling, and+ wires the V2 `{ id, setup }` plugin and nested `mcp.servers` entry when it+ reports major 2. A failed probe writes no OpenCode wiring and is reported+ as a setup problem; `--agent opencode2` still forces V2 without probing.+ (#1356)+- Fixed `ai-memory mcp-bridge` exiting when a client sent `server/discover`+ before `initialize`. A client that supports both the 2026-07-28 MCP revision+ and the older `initialize` handshake, such as Antigravity CLI 1.4 and the+ Antigravity 2.24 app, sends that probe first and falls back to `initialize`+ when the server answers with an error. The bridge ended the session instead,+ so the fallback found a closed pipe (`calling initialize: client is closing:+ EOF`) and the client never connected. Until `initialize` arrives, the bridge+ now answers every other request with a JSON-RPC Method not found error,+ ignores notifications such as the client cancelling its probe, and still+ answers `ping`. A client that starts with `initialize` sees no change.+ (#1355)## [3.1.0] - 2026-10-16diff --cc crates/ai-memory-cli/src/commands/render_shared.rsindex 3a5a2d0a,3a5a2d0a..efe19475--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@@ -623,7 -623,7 +623,7 @@@ function captureDecide(tool: CaptureTooconst captureRank: Record<CaptureDisposition, number> = { keep: 0, "metadata-only": 1, drop: 2 };// Every other marker governing a path the call names (a file-tool target or the files an `apply_patch` names, a search/list directory, file or path-like glob argument, or a shell argument with a separator resolved from its workdir, plus that directory) inspects it too, so a checkout's `ignore_paths` hold for a call made from elsewhere. Lexical; each directory is looked up once and remembered for every lookup that passes it; a glob location is looked up from its literal root (before the walk, whose one listing may spend the time budget) and, when that root lies outside the event's own checkout, every directory it could pass through is checked for a marker of its own; a glob whose `..` follows a `**` is looked up in every reading. Locations outside the own checkout come first: there unreadable targets, glob syntax the walk cannot follow, and anything past the bounds are unprovable, while running out of budget inside the own checkout ends the lookup. Mirrors `capture_lookup_locations` and `foreign_capture_decision`.function captureForeignConfigs(tool: CaptureTool, config: CaptureConfig, cwd: string | undefined, own: string | undefined): CaptureConfig[] { const invalid: CaptureConfig[] = [{ state: "invalid", patterns: [], base: config.base, windowsHost: config.windowsHost }]; const locations = new Set<string>(); let overflow = false; const add = (path: string, base: string): string[] | undefined => { const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path); if (!absolute && !base) return undefined; const readings = captureAllReadings(captureResolve(path, base, config.windowsHost), config.windowsHost); if (readings === false) { overflow = true; return undefined; } if (!readings) return undefined; return readings.map((candidate) => { const location = candidate.windows ? candidate.path.replace(/\//g, "\\") : candidate.path; locations.add(location); return location; }); }; if (tool.family === "file") { const paths = tool.paths ?? tool.patch; if (!paths) return invalid; for (const path of paths) if (add(path, config.base) === undefined) return invalid; } else if (tool.family === "search-list") { if (!tool.search) return invalid; const roots: string[] = []; for (const root of tool.search.roots) { const found = add(root, config.base); if (found === undefined) return invalid; roots.push(...found); } if (!roots.length) roots.push(config.base); for (const pattern of tool.search.patterns.filter((p) => /[\/\\]/.test(p))) for (const root of roots) if (add(pattern, root) === undefined) return invalid; } else if (tool.family === "non-file" && tool.command !== undefined) { if (captureCommandOversized(tool.command)) return invalid; const base = captureBase(config, tool.workdir); if (base) add(base, base); const home = homedir(); const split = captureShellSplit(tool.command, tool.powershell || config.windowsHost); for (const [word, tilde] of [...split.words, ...split.expanded]) for (const [argument] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if (/[\/\\]/.test(expanded)) add(expanded, base); } } if (overflow || locations.size > CAPTURE_MAX_LOOKUP_LOCATIONS) return invalid; const markers: string[] = []; const memo: CaptureMarkerMemo = { governing: new Map(), checkouts: new Map() }; let checkout: string | undefined; if (cwd) { const root = captureMemoCheckout(resolve(cwd), memo, { dirs: 0, entries: 0, deadline: Infinity, now: Date.now, probes: -Infinity }); checkout = root && captureOwnCheckout(root) ? root : undefined; captureMemoRemember(cwd, own, memo); if (statSync(resolve(cwd), { throwIfNoEntry: false })?.isDirectory()) captureMemoNote(cwd, memo); } const budget: CaptureGlobBudget = { dirs: 0, entries: 0, deadline: captureNow() + CAPTURE_MAX_GLOB_MS, now: captureNow, probes: 0 }; const remember = (marker: string | undefined): boolean => { if (!marker || marker === own || markers.includes(marker)) return true; if (markers.length === CAPTURE_MAX_FOREIGN_MARKERS) return false; markers.push(marker); return true; }; const insideOwn = (location: string) => checkout !== undefined && (location === checkout || location.startsWith(join(checkout, "x").slice(0, -1))); const ordered = [...locations].filter((location) => !insideOwn(location)); const insideFrom = ordered.length; ordered.push(...[...locations].filter(insideOwn).sort((a, b) => a.split(/[\\/]/).length - b.split(/[\\/]/).length)); for (let index = 0; index < ordered.length; index++) { const location = ordered[index]; const walk = captureGlobWalk(location); if (walk === undefined) return invalid; const lookup = walk ? walk.root : location; const dir = captureExistingDirWithin(lookup, memo, budget); if (dir === undefined) { if (index >= insideFrom) break; return invalid; } const marker = dir === null ? null : captureMemoMarker(dir, memo, budget); if (marker === undefined) { if (index >= insideFrom) break; return invalid; } if (!remember(marker ?? undefined)) return invalid; if (walk) { const found = captureMarkersBelow(walk.root, walk.steps, checkout, budget); if (!found) return invalid; for (const marker of found) if (!remember(marker)) return invalid; } } return markers.map((marker) => captureConfigAt(marker, cwd)); }--function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const own = findMarker(cwd); let config = captureConfigAt(own, cwd); const tool = captureTool(payload); let disposition = captureDecide(tool, config); if (disposition !== "drop" && tool.family !== "unknown") for (const other of captureForeignConfigs(tool, config, cwd, own)) { const decided = captureDecide(tool, other); if (captureRank[decided] > captureRank[disposition]) { disposition = decided; config = other; } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }++function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const own = findMarker(cwd); let config = captureConfigAt(own, cwd); const tool = captureTool(payload); let disposition = captureDecide(tool, config); if (disposition !== "drop" && tool.family !== "unknown") for (const other of captureForeignConfigs(tool, config, cwd, own)) { const decided = captureDecide(tool, other); if (captureRank[decided] > captureRank[disposition]) { disposition = decided; config = other; } } if (config.state === "inactive") return { disposition, payload }; const extraction = config.state === "active" && tool.family === "search-list" ? "not-applicable" : tool.extraction === "not-applicable" ? "extracted" : tool.extraction; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }"##;let names = |names: &[&str]| {let quoted: Vec<String> = names.iter().map(|name| ts_string_literal(name)).collect();@@@ -3249,6 -3249,6 +3249,8 @@@ emit({{ tool: "edit", args: {{ path: prconst malformedRequest = requests.at(-1) ?? "";const malformedQueued = JSON.stringify(queue.at(-1));check(JSON.parse(malformedRequest)._ai_memory_capture?.policy_state === "invalid", "malformed-quote-invalid-protocol");++const invalidSearch = capturePolicy({{ tool: "grep", args: {{ pattern: "x" }} }}, malformedQuoteCwd);++check(invalidSearch.protocol?.policy_state === "invalid" && invalidSearch.protocol.extraction_state === "extracted", "invalid-search-extraction-parity");for (const forbidden of [privatePath, privateBody]) check(!malformedQueued.includes(forbidden) && !malformedRequest.includes(forbidden), "malformed-quote-redaction");emit({{ tool: "edit", args: {{ path: "C:relative", nested: {{ path: privatePath, body: privateBody }} }}, output: privateBody, error: privateBody, sessionID: "session-safe", cwd: "/cwd-safe", tool_call_id: "call-safe" }}, gatedCwd);const metadata = requests.at(-1) ?? "";@@@ -3263,6 -3263,6 +3265,8 @@@ for (const forbidden of [privatePath, pconst inactivePayload = {{ tool: "edit", args: {{ path: privatePath }}, output: privateBody }};const inactive = capturePolicy(inactivePayload, "/no-marker");check(inactive.disposition === "keep" && inactive.payload === inactivePayload && !inactive.protocol, "inactive-preserves-object");++const activeSearch = capturePolicy({{ tool: "grep", args: {{ pattern: "x" }} }}, gatedCwd);++check(activeSearch.protocol?.policy_state === "active" && activeSearch.protocol.extraction_state === "not-applicable", "active-search-not-applicable");const activeKeep = capturePolicy({{ tool: "bash", args: {{ command: privateBody }} }}, gatedCwd);check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 && activeKeep.protocol.policy_state === "active", "active-keep-adds-protocol");// Windows spellings of an ignored file, and the POSIX sessions they must not touch (shared vectors; mirrors `windows_spelling_fixture_vectors`).