@staix/agent-mem 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +9 -9
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +11 -19
- package/src/cli.ts +121 -26
- package/src/commands-table.ts +6 -0
- package/src/index.ts +2 -0
- package/src/mcp-memory.ts +19 -6
- package/src/memory/candidate-origin.ts +63 -0
- package/src/memory/candidates.ts +30 -10
- package/src/memory/capture.ts +25 -0
- package/src/memory/cli-attribution.ts +17 -1
- package/src/memory/commands.ts +3 -1
- package/src/memory/consolidate.ts +15 -3
- package/src/memory/consolidation-model.ts +10 -4
- package/src/memory/formats-raise.ts +114 -0
- package/src/memory/sync-placement-batch-intent.ts +100 -0
- package/src/memory/sync-placement-journal-storage.ts +83 -12
- package/src/memory/sync-placement-transport.ts +17 -3
- package/src/ui/panel.js +7 -2
- package/src/ui/plugin.ts +2 -0
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.
|
|
6
|
+
Version: 0.28.0. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -92,11 +92,11 @@ Memory commands: `list`, `search`, `show`, `graph`, `suggestions`, `confirm`, `r
|
|
|
92
92
|
|
|
93
93
|
`amem import codex` reads Codex's Markdown memory as review candidates. It supports both on-disk layouts: memories v1 under `$CODEX_HOME/memories` (else `~/.codex/memories`) and memories v2, the default for fresh profiles since Codex 0.165.0, under the sibling `memories_v2/` (`memory_summary.md`, `rollout_summaries/`, `extensions/`; v2 titles start with `memories_v2/`). The v2 SQLite state is never read. With `--from` only the given directory is read. When neither layout exists, the receipt names the locations it checked.
|
|
94
94
|
|
|
95
|
-
Agent markers are honest-session identity context, not authentication. Marked `amem note add` writes use the existing peer field for attribution
|
|
95
|
+
Agent markers are honest-session identity context, not authentication. Marked `amem note add` writes use the existing peer field for attribution. An agent-marked session runs every amem command a person runs (#431): `doctor`, `project export`, history and as-of reads, `migrate --sync-placement` and the rest, with the same preview and `--confirm`/`--apply` steps; its reads keep the configured policy screen. Outbound publication (npm publish, release tags) still needs the person. Unmarked reads retain their existing unscreened behavior. `amem mcp` remains scoped to its startup project and can write only candidate and work-list data; hooks and ingest append capture only. Curated candidate acceptance and other CLI writes use the current configured policy. The CLI no longer has a general agent-marker refusal or stdin-TTY gate; use each command's explicit preview and `--confirm`/`--apply` flow where provided. `amem review walk` stays interactive and requires terminal input and output; `amem review decide <id> accept|reject|defer` is its non-interactive form: without `--confirm` it prints the candidate and its overlaps and marks it shown, and `--confirm` applies that one decision; `$EDITOR` opens only when a terminal is available.
|
|
96
96
|
|
|
97
97
|
## Configuration and privacy policy
|
|
98
98
|
|
|
99
|
-
The configured privacy policy screens capture, MCP reads, the SessionStart brief, candidate acceptance, promotion, import, sync, repo promotion and vault-candidate selection. Agent-marked CLI memory reads use the same screened boundary as MCP. Unmarked CLI reads (`list`, `search`, `show`) retain their existing unscreened behavior. The policy combines the built-in secret and personal-data screen with your configured rules.
|
|
99
|
+
The configured privacy policy screens capture, MCP reads, the SessionStart brief, candidate acceptance, promotion, import, sync, repo promotion and vault-candidate selection. Agent-marked CLI memory reads use the same screened boundary as MCP: reads that fit an MCP read handler use it, and the rest run the person handler with the configured policy screen on their output. Unmarked CLI reads (`list`, `search`, `show`) retain their existing unscreened behavior. The policy combines the built-in secret and personal-data screen with your configured rules.
|
|
100
100
|
|
|
101
101
|
The machine-local file `amem.config.json` in the memory home (see `amem status` for where that is) holds your own policy:
|
|
102
102
|
|
|
@@ -130,7 +130,7 @@ If the screen misses a secret or personal data, `amem forget <id>` hides the ent
|
|
|
130
130
|
|
|
131
131
|
`amem note add [--kind decision|finding|contract|fail|preference] [--tier short|long] [--scope project|shared] [--title T] [text... | -]` writes one curated note with CLI peer attribution (agent-mem#40 F6). The text is the arguments, `-` to read stdin through end of input, or nothing to open `$VISUAL` (an empty one is skipped) or `$EDITOR` on a private temporary file when a terminal is available (the command is run without a shell: an existing path with spaces works as is, otherwise quotes and backslashes split it, and Ctrl-C reaches the editor while it runs). A `fail` note takes its five fields instead of free text: `--approach`, `--symptom`, `--cause`, `--evidence` (repeatable) and `--retry-when`. All five are required, and the command names the ones that are missing; with none given it opens a labelled template in the editor. A `preference` is a standing instruction such as "always answer in Korean": it is long-term, shown by its own slot in both briefs (up to five current ones, project plus shared, newest first, whole lines only), and refused until the memory home's `formats.json` records a `curated` or `home` floor of at least `0.25.0`, because a release older than that drops the row and then refuses its whole sync publish over it (agent-mem#370). The configured policy screens the title and text before anything is written, and a refusal never echoes them.
|
|
132
132
|
|
|
133
|
-
The SessionStart brief carries one line when candidates wait, for example `2 candidates pending, oldest expires in 27 days` (agent-mem#40 F7). It holds numbers only, is read-only (the hook never marks anything shown), comes out of the brief's own byte budget, and is left out when it does not fit. `amem status --json` adds a `candidates` object (bare `amem status` shows the same as a labelled row and next action) (or `unavailable` when `candidates.db` exists but cannot be read, never a false zero) and a warning when any is within 7 days of expiry. `amem review walk` needs a terminal on both stdin and stdout (it refuses when stdout is redirected to a file or a pipe, because nobody would see what it asks about). It prints each pending candidate, oldest first, and only then asks accept, edit, reject, skip or quit: accept goes through the normal policy, edit opens the text in your editor and writes it as a note under the current CLI actor (a candidate proposed as a fail note opens the labelled template), and what it prints has control characters removed. Nothing expires unseen: a candidate counts as shown
|
|
133
|
+
The SessionStart brief carries one line when candidates wait, for example `2 candidates pending, oldest expires in 27 days` (agent-mem#40 F7). It holds numbers only, is read-only (the hook never marks anything shown), comes out of the brief's own byte budget, and is left out when it does not fit. `amem status --json` adds a `candidates` object (bare `amem status` shows the same as a labelled row and next action) (or `unavailable` when `candidates.db` exists but cannot be read, never a false zero) and a warning when any is within 7 days of expiry. `amem review walk` needs a terminal on both stdin and stdout (it refuses when stdout is redirected to a file or a pipe, because nobody would see what it asks about). It prints each pending candidate, oldest first, and only then asks accept, edit, reject, skip or quit: accept goes through the normal policy, edit opens the text in your editor and writes it as a note under the current CLI actor (a candidate proposed as a fail note opens the labelled template), and what it prints has control characters removed. Nothing expires unseen: a candidate counts as shown when `review walk` or a `review decide` preview has printed it (the plain `review list` prints no content and runs in scripts, and the brief line cannot know you read it, so neither marks anything). A candidate is kept past its 30 days until it has been shown, and then for 7 more days. When 500 unseen candidates wait, a new one is refused with a named error (an MCP tool returns a fixed queue-full response) instead of dropping an unseen one.
|
|
134
134
|
|
|
135
135
|
## Candidate review
|
|
136
136
|
|
|
@@ -173,7 +173,7 @@ The manifest holds the absolute path and sha256 of `src/ui/plugin.ts` (of the `-
|
|
|
173
173
|
|
|
174
174
|
- Reads are screened. Search, Timeline and Work lists call the in-process `amem_search`, `amem_timeline` and `amem_work_state_read` handlers for the chosen project and forward every option the tool declares, so console search returns exactly the `amem_search` set for the same query. Goals and the review queue pass the configured policy; a candidate that fails it, or whose target fails it, is not shown (the panel counts it and points to `amem review walk`). The console never shows unscreened content, also not to the person. It runs in no repository, so a repository's `.amem/config` narrowing does not apply; the machine's `amem.config.json` does.
|
|
175
175
|
- Recap computes the current SessionStart brief only on its own panel snapshots, using machine policy. Curated and work inputs use bounded private scratch copies; capture is read-only, and no live reader lease is taken. It shows the full context, coverage, partial status, token upper bound and generation time; it is not a stored copy of a prior session's injected brief. The console has no repository binding, so the repository section is absent. No recap or new capture field is stored in the memory home.
|
|
176
|
-
- Review shows the candidate kind, proposal, correction diff, stored evidence references, target-note quotes with dates and similar memories.
|
|
176
|
+
- Review shows the candidate kind, proposal, correction diff, stored evidence references, target-note quotes with dates and similar memories. Since 0.28.0 a candidate records the origin its proposer supplied (#323): the capture session key, the proposing peer, the time and an optional turn id, as ids only. Review, `review list`, `review decide`, `review walk` and the panel show it, or `unavailable` when the proposer supplied none and `unknown` for a candidate proposed before 0.28.0; nothing is inferred from capture data. An accepted note keeps the origin as `session:`, `peer:`, `origin-at:` and `turn:` graph edges; a goal promotion keeps its origin on the candidate instead. Re-checking a note against its origin works only while that capture session is retained (capture is machine-local and expires); only a confirmed absence from a readable capture store reads as `origin expired` (shown by `review decide`); a missing, cold or policy-withheld capture reads as `unavailable`, never as a failed check. `amem show capture:<id>` prints a capture row with its session and time. An MCP server records origin when its host sets `AMEM_ORIGIN_SESSION` (hashed like capture) and `AGENTHUB_PEER_ID`. An explicitly unavailable project is refused instead of falling back to another project.
|
|
177
177
|
- Review actions are the CLI's. Accept runs the same acceptance as `amem review accept` and writes the same note, edit-then-accept is `review walk`'s edit (the person's own note, then the candidate closed), reject is `review reject`. The console stamps the person as the actor (peer `person`). A privacy-screen hit refuses with a named reason and writes nothing. agent-mem keeps no reject reason, so a reason typed in the console is not recorded, and the reply says so.
|
|
178
178
|
- Acon displays the Undo offer for 10 seconds; the plugin accepts a matching undo record for 60 seconds within its current provider instance. Undo stays bound to the candidate action: undoing an accept forgets the accepted note (an append-only forget op; a note a correction replaced shows again), undoing a reject makes the candidate pending again. A promotion has no undo. `merge_into` is not offered: the library has no merge operation.
|
|
179
179
|
- Destructive forms (`gc`, `capacity_apply`, `project_forget`, `decay_apply`, `prune`) answer `needsConfirm` with the preview and `changes[]` and never write on the first call. The console's single-use confirm token carries the fingerprint back; the plugin recomputes the preview and writes only when it still matches. `prune` needs a generation home, as `amem prune` does.
|
|
@@ -297,7 +297,7 @@ amem capacity apply --split [--confirm] # each shard's share of the global cap
|
|
|
297
297
|
- `capacity` also prints a per-shard split of the global disk-share budget. Each shard's weight halves every 14 days since its last capture, so recently used projects keep more capture and cold ones shrink first; the split never exceeds the budget, gives every shard at least 1 MB, keeps every shard at what it holds whenever the total fits, never proposes a retention shorter than a shard's idle time plus 30 days, and says when the budget forces a shard below what it holds. When the budget holds fewer whole MB than there are shards, no split is proposed and `capacity` says why (`splitRefused`). It proposes capture bounds only, and never evicts curated notes, goals or work lists. `capacity apply --split` previews, then `--confirm` writes exactly the previewed values to each shard's `config.json`, and only if the preview is under an hour old and the set of shards and every shard's config are unchanged since then (a `--disk-share` given only to `--confirm` changes nothing that is written).
|
|
298
298
|
- amem lists vault candidates and never writes the vault.
|
|
299
299
|
|
|
300
|
-
Resource budgets are acceptance criteria, measured by `bun scripts/measure-budget.ts` in CI on Ubuntu and macOS: a hook-like append (including the spool-and-exit path under contention) must stay under 150 ms p95 wall time and 100 MB RSS (R2), the search path under 100 MB idle and 200 MB peak RSS (R3), and no amem process may remain after exit (R1). For the actual-hook scripts (`measure-hooks-budget.ts`, `measure-transcript-budget.ts`, `measure-full-spool-budget.ts`) R2 is three gates: a 150 MB ceiling on every invocation, a regression gate of +10% over a committed per-runner p95 baseline (`docs/bench/r2-baseline.json`), and a 300 ms per-invocation maximum on the handler's own wall, with the outer CLI wall reported only (the transcript harness enforces it too since #226); see [docs/contracts.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/contracts.md) (#228). The script prints a machine-readable verdict per budget and its CI log is also the FTS5 availability evidence for Linux (R5). The AC4 retrieval re-check of the frozen P0 query set is in [docs/p1-ac4-recheck.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/p1-ac4-recheck.md).
|
|
300
|
+
Resource budgets are acceptance criteria, measured by `bun scripts/measure-budget.ts` in CI on Ubuntu and macOS: a hook-like append (including the spool-and-exit path under contention) must stay under 150 ms p95 wall time and 100 MB RSS (R2), the search path under 100 MB idle and 200 MB peak RSS (R3), and no amem process may remain after exit (R1). For the actual-hook scripts (`measure-hooks-budget.ts`, `measure-transcript-budget.ts`, `measure-full-spool-budget.ts`) R2 is three gates: a 150 MB ceiling on every invocation, a regression gate of +10% over a committed per-runner p95 baseline (`docs/bench/r2-baseline.json`), and a 300 ms per-invocation maximum on the handler's own wall, with the outer CLI wall reported only (the transcript harness enforces it too since #226); see [docs/contracts.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/contracts.md) (#228). The script prints a machine-readable verdict per budget and its CI log is also the FTS5 availability evidence for Linux (R5). The hosted budget measurement steps still run and retain their own assertions, but their failures are advisory. Validation steps in those jobs still gate the required check, and a cancelled or missing measurement job remains an error. A green required check alone does not mean the measured budgets passed. The AC4 retrieval re-check of the frozen P0 query set is in [docs/p1-ac4-recheck.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/p1-ac4-recheck.md).
|
|
301
301
|
|
|
302
302
|
## Claude Code hooks and SessionStart context
|
|
303
303
|
|
|
@@ -323,7 +323,7 @@ Known-format pending records whose cwd is positively absent can retire after one
|
|
|
323
323
|
|
|
324
324
|
If both replayable tiers fill, or SessionStart's reserve alone fills, the current event can be dropped. The library receipt reports `dropped: true`, `dropReason: "spool_full"`, `dropCount: 1`, and the metric reports `captureDrops: 1` with `captureDropReason: "spool_full"`. Non-SessionStart native stdout remains empty. Native SessionStart emits only `hookSpecificOutput`, placing a bounded notice with reason counts from the last 200 metric samples after its untrusted-data header inside `additionalContext`, not in new top-level fields. These are rolling-window counts, not all-time totals. The header stays before all memory data even when the brief is otherwise unavailable; the optional trusted Record instruction precedes it. The combined instruction and context stay within the same byte bound. Finite-capacity and retirement losses are observable rather than reported as captured. Exact-once replay applies to positively bound retained records that can progress; unlimited lossless intake is not promised. Soft-cap overshoot, unpublished `.writing/` leftovers and power-loss durability retain the [contracts ceiling](docs/contracts.md#p3-hook-and-native-intake-boundaries-13).
|
|
325
325
|
|
|
326
|
-
SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a
|
|
326
|
+
SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a `home` or `curated` floor of 0.24.0 or later, raised explicitly with `amem formats raise` after checking writers. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. A CLI `amem brief`, including an agent-marked call, or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
|
|
327
327
|
|
|
328
328
|
SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The default R2 wall limit remains 150 ms p95, with the scoped hosted-runner exceptions in [the R2 contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228), including 181 ms for hosted macOS M1 transcript hooks. The production handler budget remains 140 ms; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
|
|
329
329
|
|
|
@@ -542,7 +542,7 @@ Run `amem consolidate [--project <current-key>]` (another project is refused) to
|
|
|
542
542
|
|
|
543
543
|
The same run also proposes curated candidates from the newest 32 capture `Record` rows of the project, so a decision, contract, fix or fail an agent recorded in its final answer reaches review without retyping. Each candidate cites up to eight rows and is grouped by kind and anchors, or by kind and text when the Record carried `-` anchors. A group already queued or already decided is not queued again, and acceptance point-reads the rows the candidate cites, so it still works after newer Records have pushed them out of the window.
|
|
544
544
|
|
|
545
|
-
The CLI runs the deterministic pass only. A library host may explicitly enable an injected model callback for
|
|
545
|
+
The CLI runs the deterministic pass only. A library host may explicitly enable an injected model callback for a person or agent; no provider is built in. It has batch, byte, deadline and persistent daily limits. Model answers remain marked machine-local candidates that cannot be accepted; `amem note add` is the separate path for an independently authored note. A non-answer is never saved.
|
|
546
546
|
|
|
547
547
|
Agents use `amem_evidence` with a question to get cited, live curated entries, not an answer. The complete JSON bundle is byte-capped (`maxBytes`, default 4096, range 256..8192); excerpted entries retain an exact `mem:` reference for fetching the full note. Capture, repository-only rows, pending candidates and model answers are excluded. amem makes no model call for this tool. Rendering a citation in the bundle records only `rendered` after successful output, never `delivered` or `cited`.
|
|
548
548
|
|
|
@@ -596,7 +596,7 @@ Records stay machine-local capture, not curated evidence; `amem consolidate` can
|
|
|
596
596
|
|
|
597
597
|
The brief puts up to five recent, screened main-session Records bound to this project before summaries and raw capture lines, using the same remaining byte budget. Repository-relative anchors must match the stored paths; `-` is valid only for project-bound decision/contract Records. Subagent or malformed Records stay out. Large legacy stores read only the newest 128 rows until an off-hook search prepares the separate Record partial index; hooks do not build it above 128 rows. Search weights Record at 1.5 versus 1.25 for conversational capture without changing curated slots or session grouping. MCP preserves the canonical line and paths, and the existing all-project CLI capture display keeps the complete Record line and anchors.
|
|
598
598
|
|
|
599
|
-
Before relying on Record capture, upgrade every amem sharing the home or
|
|
599
|
+
Before relying on Record capture, upgrade every amem sharing the home or raise the `home` reader floor to 0.23.0 with `amem formats raise home 0.23.0` (preview, then `--confirm`). An old 0.22.1 hook drain silently discards a Record format-3 spool record without a counted loss, and its config parser refuses `records` as an unknown key, even when false. Set `records: false` only after every participating install is upgraded. Only an explicitly confirmed `amem formats raise` writes `formats.json`; a floor prevents old participation rather than teaching old readers the event.
|
|
600
600
|
|
|
601
601
|
## Initial sync placement activation
|
|
602
602
|
|
package/package.json
CHANGED
package/src/cli-agent-reads.ts
CHANGED
|
@@ -7,7 +7,6 @@ import type { ParsedCommand } from "./commands-table.ts";
|
|
|
7
7
|
|
|
8
8
|
const UNAVAILABLE = "Memory operation unavailable or refused; no partial result is shown.";
|
|
9
9
|
const RESULT_BYTES = 262_144;
|
|
10
|
-
const AGENT_READS = "Agent reads: search, list, show, brief, graph, vault-candidates, capacity.";
|
|
11
10
|
|
|
12
11
|
/** A refusal decided from the parsed command alone, before any store or file is opened: safe to show as is. */
|
|
13
12
|
export class AgentUsageError extends Error {
|
|
@@ -40,11 +39,10 @@ function positiveLimit(value: string | boolean | undefined): number | undefined
|
|
|
40
39
|
function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undefined {
|
|
41
40
|
const { path, options, positionals, definition } = parsed;
|
|
42
41
|
|
|
43
|
-
|
|
44
|
-
//
|
|
42
|
+
// #431: an agent-marked session runs every command a person runs. Only reads whose options fit the startup-bound MCP read
|
|
43
|
+
// handlers take that route; every other command, and a read with other options (history, as-of, tier, kind), continues
|
|
44
|
+
// through the person handler with its own preview/--confirm or --apply steps and policy screens.
|
|
45
45
|
if (definition.mutates !== undefined) return undefined;
|
|
46
|
-
if (path[0] === "project" && path[1] === "export") throw new AgentUsageError(`amem project export is not available to an agent-marked session. ${AGENT_READS}`);
|
|
47
|
-
if (path[0] === "setup") return undefined;
|
|
48
46
|
|
|
49
47
|
const flags = Object.keys(options).filter(key => key !== "--json" && key !== "--policy-free");
|
|
50
48
|
const only = (...allowed: string[]) => flags.every(flag => allowed.includes(flag));
|
|
@@ -52,42 +50,36 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
|
|
|
52
50
|
if (options["--limit"] !== undefined && limit === undefined) throw new AgentUsageError("--limit takes a whole number from 1 to 100.");
|
|
53
51
|
|
|
54
52
|
if (path[0] === "search") {
|
|
55
|
-
if (!only("--limit", "--since", "--explain"))
|
|
53
|
+
if (!only("--limit", "--since", "--explain")) return undefined;
|
|
56
54
|
if (!positionals.join(" ").trim()) throw new AgentUsageError("agent-marked search needs a query.");
|
|
57
55
|
return { tool: "amem_search", args: { query: positionals.join(" "), ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}), ...(options["--explain"] === true ? { explain: true } : {}) } };
|
|
58
56
|
}
|
|
59
57
|
if (path[0] === "list") {
|
|
60
|
-
if (!only("--limit", "--since"))
|
|
58
|
+
if (!only("--limit", "--since")) return undefined;
|
|
61
59
|
return { tool: "amem_timeline", args: { ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}) } };
|
|
62
60
|
}
|
|
63
61
|
if (path[0] === "show") {
|
|
64
|
-
if (!only())
|
|
62
|
+
if (!only()) return undefined;
|
|
65
63
|
if (positionals.length !== 1 || !positionals[0]!.trim()) throw new AgentUsageError("agent-marked show takes exactly one id.");
|
|
66
64
|
return { tool: "amem_show", args: { id: positionals[0] } };
|
|
67
65
|
}
|
|
68
|
-
|
|
69
|
-
if (!only("--for", "--paths", "--symbols", "--bytes")) throw accepts("brief", ["--for", "--paths", "--symbols", "--bytes"]);
|
|
70
|
-
if (typeof options["--for"] !== "string") throw new AgentUsageError("agent-marked brief needs --for.");
|
|
71
|
-
const rawBytes = options["--bytes"];
|
|
72
|
-
if (rawBytes !== undefined && !/^[1-9][0-9]*$/.test(String(rawBytes))) throw new AgentUsageError("--bytes takes a positive whole number.");
|
|
73
|
-
return { tool: "amem_brief", args: { intent: options["--for"], paths: values(argv, "--paths"), symbols: values(argv, "--symbols"), ...(rawBytes === undefined ? {} : { maxBytes: Number(rawBytes) }) } };
|
|
74
|
-
}
|
|
66
|
+
// #431 AC2: `brief --for` runs the person handler, which screens with the configured policy and prepares the curated brief cache.
|
|
75
67
|
if (path[0] === "graph") {
|
|
76
|
-
if (!only("--hops"))
|
|
68
|
+
if (!only("--hops")) return undefined;
|
|
77
69
|
if (positionals.length !== 1) throw new AgentUsageError("agent-marked graph takes exactly one start id.");
|
|
78
70
|
const hops = options["--hops"] === undefined ? 1 : Number(options["--hops"]);
|
|
79
71
|
if (hops !== 1 && hops !== 2) throw new AgentUsageError("--hops takes 1 or 2.");
|
|
80
72
|
return { tool: "amem_graph", args: { start: positionals[0], ...(options["--hops"] === undefined ? {} : { hops }) } };
|
|
81
73
|
}
|
|
82
74
|
if (path[0] === "vault-candidates") {
|
|
83
|
-
if (!only("--limit") || options["--all-projects"] !== undefined || options["--project"] !== undefined)
|
|
75
|
+
if (!only("--limit") || options["--all-projects"] !== undefined || options["--project"] !== undefined) return undefined;
|
|
84
76
|
return { tool: "amem_vault_candidates", args: limit === undefined ? {} : { limit } };
|
|
85
77
|
}
|
|
86
78
|
if (path[0] === "capacity" && path.length === 1) {
|
|
87
|
-
if (!only())
|
|
79
|
+
if (!only()) return undefined;
|
|
88
80
|
return { tool: "amem_capacity", args: {} };
|
|
89
81
|
}
|
|
90
|
-
|
|
82
|
+
return undefined;
|
|
91
83
|
}
|
|
92
84
|
|
|
93
85
|
/** Route marked-agent read commands through the same startup-bound MCP policy and handlers. */
|
package/src/cli.ts
CHANGED
|
@@ -24,6 +24,8 @@ import { importClaudeMemCapture, importClaudeMemWorkState } from "./memory/impor
|
|
|
24
24
|
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { isAbsolute, join } from "node:path";
|
|
26
26
|
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { captureSessionKey } from "./memory/capture-input.ts";
|
|
28
|
+
import { originLine, originRecheck } from "./memory/candidate-origin.ts";
|
|
27
29
|
import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
|
|
28
30
|
import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
|
|
29
31
|
import { memoryProjectKey } from "./memory/project.ts";
|
|
@@ -32,7 +34,7 @@ import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-ov
|
|
|
32
34
|
import { openCuratedForRead } from "./memory/curated-read.ts";
|
|
33
35
|
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
34
36
|
import { capacityReport, capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity.ts";
|
|
35
|
-
import { readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
37
|
+
import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
36
38
|
|
|
37
39
|
import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
|
|
38
40
|
import { completionScript } from "./completion.ts";
|
|
@@ -85,6 +87,8 @@ export interface CliContext {
|
|
|
85
87
|
edit?: (initial: string) => string | Promise<string>;
|
|
86
88
|
/** Where `sync --progress` writes (default process.stderr) and whether that is a terminal; fixtures stand in for both. */
|
|
87
89
|
stderr?: (text: string) => void; stderrTTY?: boolean;
|
|
90
|
+
/** Test seams for `amem formats raise`: the process table (`pid args` lines; default `ps -axo pid=,args=`) and the clock that dates the record. */
|
|
91
|
+
processTable?: () => string; now?: () => number; embeddedAmem?: (dir: string) => boolean;
|
|
88
92
|
/** Test seam: the `sync --if-due` deadline in milliseconds (the CLI always uses 30 seconds). */
|
|
89
93
|
syncDeadlineMs?: number;
|
|
90
94
|
/** Called with the signal name when a person's signal ended `sync --if-due`, after its handlers are removed. `main` re-raises it once the output is written; absent, nothing happens. */
|
|
@@ -344,7 +348,11 @@ const preloadMcp = () => Promise.all([import("./memory/store.ts"), import("./mem
|
|
|
344
348
|
async function runCliCommand(argv: readonly string[], context: CliContext): Promise<string> {
|
|
345
349
|
if (argv.length === 1 && argv[0] === "mcp") {
|
|
346
350
|
await preloadMcp();
|
|
347
|
-
|
|
351
|
+
// #323: a host that knows the proposing session passes it; the CLI keys it like capture does, so a candidate points at the same session rows.
|
|
352
|
+
const env = context.env ?? process.env;
|
|
353
|
+
const originSession = captureSessionKey(env.AMEM_ORIGIN_SESSION), originPeer = env.AGENTHUB_PEER_ID?.trim() || undefined;
|
|
354
|
+
const memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base: memoryHome(env),
|
|
355
|
+
...(originSession || originPeer ? { origin: () => ({ ...(originSession ? { session: originSession } : {}), ...(originPeer ? { peer: originPeer } : {}) }) } : {}) });
|
|
348
356
|
await serveMcp({ tools: memory.tools, close: memory.close, onEmitted: memory.onEmitted, version: VERSION });
|
|
349
357
|
return "";
|
|
350
358
|
}
|
|
@@ -389,7 +397,6 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
389
397
|
const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
|
|
390
398
|
if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
|
|
391
399
|
throw new AgentUsageError("Sync placement is a home-wide forward-only migration; use only --sync-placement with --dry-run, --apply, --resume or pre-marker --abandon and the writer roots, never combine migration families or deactivate.");
|
|
392
|
-
if (actor === "agent") throw new AgentUsageError("Sync placement activation requires a person; ask the person to run amem migrate --sync-placement --dry-run and review the home-wide forward-only transition.");
|
|
393
400
|
} else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined)) {
|
|
394
401
|
throw new AgentUsageError("--writer-root and --abandon apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
|
|
395
402
|
}
|
|
@@ -462,7 +469,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
462
469
|
const assertCurrent = () => { binding(); assertProjectActive(base, project); if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")) throw Error("consolidation project binding changed"); };
|
|
463
470
|
candidates = new CandidateStore({ memoryDir: base, reconcile: { canonical: project, aliases } });
|
|
464
471
|
const readRecords = recordWindow(base, project, policyCwd);
|
|
465
|
-
const
|
|
472
|
+
const origin = { peer: identity.peer, at: new Date().toISOString(), ...(captureSessionKey((context.env ?? process.env).AMEM_ORIGIN_SESSION) ? { session: captureSessionKey((context.env ?? process.env).AMEM_ORIGIN_SESSION)! } : {}) };
|
|
473
|
+
const report = await proposeConsolidation(store, candidates, { project, actor, origin, policy: policyOf, policyVersion: policyKey, assertCurrent, ...(readRecords ? { records: readRecords } : {}) });
|
|
466
474
|
return options["--json"] ? JSON.stringify(report, null, 2) : `${report.candidates.length} consolidation candidates queued for amem review; no curated notes changed${report.records ? `; ${report.records.queued} of ${report.records.found} Record(s)${report.records.truncated ? " in the newest 32" : ""}` : ""}${report.alreadyReviewed ? `; ${report.alreadyReviewed} already reviewed` : ""}${report.truncated ? "; scan truncated" : ""}${report.oversized ? `; ${report.oversized} proposals too large` : ""}${report.localExcluded ? `; ${report.localExcluded} local sources excluded` : ""}`;
|
|
467
475
|
} finally { candidates?.close(); store.close(); }
|
|
468
476
|
}
|
|
@@ -483,7 +491,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
483
491
|
const result = await buildIntentBrief(createIntentBriefSource(store, project),
|
|
484
492
|
{ project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
|
|
485
493
|
assertCurrent(); outputReady(result.items.map(view => view.id), project);
|
|
486
|
-
|
|
494
|
+
store.prepareCuratedBriefs([project]);
|
|
487
495
|
return options["--json"] ? JSON.stringify({ brief: result.text, bytes: result.bytes, truncated: result.truncated, state: result.state }, null, 2) : result.text;
|
|
488
496
|
} finally { store.close(); }
|
|
489
497
|
}
|
|
@@ -496,7 +504,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
496
504
|
const { activateSyncPlacement } = await import("./memory/sync-placement-activation.ts");
|
|
497
505
|
const result = await activateSyncPlacement({ memoryDir:memoryHome(),mode:options["--abandon"]?"abandon":mode as "dry-run"|"apply"|"resume",
|
|
498
506
|
writerRoots:repeated(argv,"--writer-root"),ownRoot:fileURLToPath(new URL("..",import.meta.url)),
|
|
499
|
-
authorize:()=>
|
|
507
|
+
authorize:()=>true });
|
|
500
508
|
if (options["--json"] === true) return JSON.stringify(result,null,2);
|
|
501
509
|
// Metadata only: the source reader and locator are never serialized into this receipt.
|
|
502
510
|
return `sync placement: ${result.mode}; ${result.active?"active":"inactive"}; home-wide, forward-only (no deactivate)\n${JSON.stringify(result,null,2)}`;
|
|
@@ -535,6 +543,42 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
535
543
|
...shardMigrationStatus(where.home) };
|
|
536
544
|
return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context));
|
|
537
545
|
}
|
|
546
|
+
if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
|
|
547
|
+
const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
|
|
548
|
+
const { readSetupWriterRoots } = await import("./setup.ts"), { readEffectiveSyncPlacementWriterRoots } = await import("./memory/sync-placement-effective-writers.ts");
|
|
549
|
+
const [surface, minReader] = parsed.positionals;
|
|
550
|
+
if (!surface || !minReader || parsed.positionals.length !== 2) throw new Error("usage: amem formats raise <surface> <min-reader> [--confirm] [--json]");
|
|
551
|
+
const home = realPath(memoryHome()), own = realPath(fileURLToPath(new URL("..", import.meta.url)));
|
|
552
|
+
const inventory = (): import("./memory/formats-raise.ts").FormatWriterInventory => {
|
|
553
|
+
const writers: import("./memory/formats-raise.ts").FormatWriter[] = [], incomplete: string[] = [], seen = new Set<string>();
|
|
554
|
+
const add = (source: "setup" | "sync-placement" | "running" | "library-host" | "self", root: string, pid?: number, host?: string) => {
|
|
555
|
+
let canonical = root; try { canonical = realPath(root); } catch { /* a missing root reads as an unknown version */ }
|
|
556
|
+
const key = `${source}\0${canonical}\0${pid ?? ""}`; if (seen.has(key)) return; seen.add(key);
|
|
557
|
+
writers.push({ source, root: canonical, version: installVersion(canonical), ...(pid !== undefined ? { pid } : {}), ...(host !== undefined ? { host } : {}) });
|
|
558
|
+
};
|
|
559
|
+
add("self", own);
|
|
560
|
+
try { for (const root of readSetupWriterRoots(home)) add("setup", root); } catch (error) { incomplete.push(`setup receipts: ${(error as Error).message.split("\n")[0]}`); }
|
|
561
|
+
if ((readPlacementRuntimeMarkers(home).profile as { publicationFormat?: string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
562
|
+
try { for (const root of readEffectiveSyncPlacementWriterRoots(home)) add("sync-placement", root); } catch { incomplete.push("sync-placement writer roots unreadable"); }
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
const table = () => (context.processTable ?? (() => require("node:child_process").execFileSync("ps", ["-axo", "pid=,args="], { encoding: "utf8", maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }) as string))();
|
|
566
|
+
for (const { pid, root, host } of runningAmemRoots(table, context.embeddedAmem)) add(host ? "library-host" : "running", root, pid, host);
|
|
567
|
+
} catch { incomplete.push("running processes could not be listed"); }
|
|
568
|
+
return { writers: writers.sort((a, b) => a.source.localeCompare(b.source) || a.root.localeCompare(b.root) || (a.pid ?? 0) - (b.pid ?? 0)), incomplete };
|
|
569
|
+
};
|
|
570
|
+
const now = context.now ? () => new Date(context.now!()) : undefined;
|
|
571
|
+
const plan = planFormatRaise(home, surface, minReader, inventory(), now);
|
|
572
|
+
if (options["--confirm"] !== true) {
|
|
573
|
+
const refusal = formatRaiseRefusal(plan);
|
|
574
|
+
if (options["--json"] === true) return JSON.stringify({ ...plan, refusal: refusal ?? null }, null, 2);
|
|
575
|
+
return [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`,
|
|
576
|
+
`writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? "unknown"} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`),
|
|
577
|
+
refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
|
|
578
|
+
}
|
|
579
|
+
const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
|
|
580
|
+
return options["--json"] === true ? JSON.stringify({ appended: record, file: plan.file }, null, 2) : `appended ${JSON.stringify(record)} to ${plan.file}`;
|
|
581
|
+
}
|
|
538
582
|
if (sub === "doctor") {
|
|
539
583
|
// F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
|
|
540
584
|
const where = resolveMemoryHome(), project = boundProject();
|
|
@@ -625,10 +669,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
625
669
|
}
|
|
626
670
|
if (review) {
|
|
627
671
|
const id = parsed.positionals[0];
|
|
628
|
-
if (sub !== "list" && sub !== "walk" && (!id || !/^[a-f0-9]{64}$/.test(id))) throw new Error(
|
|
672
|
+
if (sub !== "list" && sub !== "walk" && (!id || !/^[a-f0-9]{64}$/.test(id))) throw new Error(`review ${sub} requires a full 64-character candidate id`);
|
|
629
673
|
if (sub === "walk" && !(context.stdinTTY ?? process.stdin.isTTY)) throw Error("review walk requires a terminal on stdin; stdout must be a terminal too");
|
|
630
674
|
if (sub === "walk" && context.write === undefined && !(context.stdoutTTY ?? process.stdout.isTTY)) throw new Error("review walk prints each candidate and asks about it, so stdout must be a terminal (not redirected to a file or a pipe)");
|
|
631
|
-
if (sub === "walk" && actor === "agent") throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
632
675
|
const project = boundProject(), aliases = aliasedKeys(memoryHome(), project), candidates = new CandidateStore(aliases.length ? { reconcile: { canonical: project, aliases } } : {});
|
|
633
676
|
let overlapStore: MemoryStore | undefined;
|
|
634
677
|
try {
|
|
@@ -658,6 +701,62 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
658
701
|
const selected = candidates.get(id!, project);
|
|
659
702
|
if (!selected || !candidatePermitted(selected)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
660
703
|
}
|
|
704
|
+
const body = (candidate: import("./memory/candidates.ts").Candidate): string => { const input = candidate.input;
|
|
705
|
+
if (input.kind === "promotion") {
|
|
706
|
+
const viewStore = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
707
|
+
try {
|
|
708
|
+
const target = viewStore.get(input.target.id, project);
|
|
709
|
+
administrative({ candidate, target });
|
|
710
|
+
return target && target.id === input.target.id && candidateTargetRevision(target) === input.target.revision
|
|
711
|
+
? `promotion. Goal goal:${input.goalId}, mem:${target.id}. ${target.title ? `${target.title}: ` : ""}${target.text}`
|
|
712
|
+
: `promotion. Goal goal:${input.goalId}, target mem:${input.target.id} changed or is unavailable; reject or skip`;
|
|
713
|
+
} finally { viewStore.close(); }
|
|
714
|
+
}
|
|
715
|
+
if (input.kind === "model-answer") return `Model answer (not evidence; cannot accept, author an independent note with amem note add). ${input.text}`;
|
|
716
|
+
if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
|
|
717
|
+
return input.kind === "memory" ? `${input.title ? `${input.title}: ` : ""}${input.text}` : input.kind === "fail" ? `fail. Approach: ${input.approach} Symptom: ${input.symptom} Cause: ${input.cause} Retry when: ${input.retryWhen}`
|
|
718
|
+
: input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
|
|
719
|
+
// #323 item 4: can the origin still be re-checked against capture? An expired session is reported as such, never as a failed check.
|
|
720
|
+
const recheckOf = (candidate: import("./memory/candidates.ts").Candidate) => {
|
|
721
|
+
// Read-only: a preview never creates or migrates capture storage; a missing or cold shard is unavailable, not expired.
|
|
722
|
+
let capture: import("./memory/capture.ts").CaptureStore | undefined;
|
|
723
|
+
try {
|
|
724
|
+
const policy = policyOf();
|
|
725
|
+
return originRecheck(candidate.origin, candidate.originKnown, session => {
|
|
726
|
+
const opened = capture ??= new CaptureStore({ memoryDir: memoryHome(), project, cwd: policyCwd, readOnly: true, recentReadRows: true, maxReadRows: 128 });
|
|
727
|
+
return opened.sessionState(session, row => policy.screenStandalone(row));
|
|
728
|
+
});
|
|
729
|
+
} catch { return "unavailable" as const; } finally { capture?.close(); }
|
|
730
|
+
};
|
|
731
|
+
if (sub === "decide") {
|
|
732
|
+
// #431 AC5: what `review walk` gives a person, one candidate at a time and without a terminal. The preview prints the
|
|
733
|
+
// candidate and its overlaps and stamps it shown (the caller read it); --confirm then applies exactly the named decision.
|
|
734
|
+
const decision = parsed.positionals[1];
|
|
735
|
+
if (decision !== "accept" && decision !== "reject" && decision !== "defer") throw new Error("usage: amem review decide <full-candidate-id> accept|reject|defer [--confirm]");
|
|
736
|
+
const candidate = candidates.get(id!, project);
|
|
737
|
+
if (!candidate || !candidatePermitted(candidate)) throw new Error("candidate unavailable");
|
|
738
|
+
if (candidate.status !== "pending") throw new Error(`candidate is ${candidate.status}, not pending`);
|
|
739
|
+
if (decision === "accept" && candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
|
|
740
|
+
if (decision === "accept" && candidate.input.kind === "model-answer") throw new Error("model answers cannot be accepted; author an independent note with amem note add");
|
|
741
|
+
if (options["--confirm"] !== true) {
|
|
742
|
+
const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
|
|
743
|
+
const preview = { candidateId: candidate.id, kind: candidate.input.kind, createdAt: candidate.createdAt, decision, body: shown,
|
|
744
|
+
origin: candidate.originKnown ? candidate.origin ?? null : "unknown", originRecheck: recheckOf(candidate),
|
|
745
|
+
overlaps: overlaps.map(overlap => ({ id: overlap.id, score: overlap.score, title: overlap.title ?? null })), next: `amem review decide ${candidate.id} ${decision} --confirm` };
|
|
746
|
+
administrative(preview);
|
|
747
|
+
markShown(realPath(candidates.dir), [project, ...aliases], Date.now(), [candidate.id]);
|
|
748
|
+
return options["--json"] ? JSON.stringify(preview, null, 2)
|
|
749
|
+
: [`${candidate.id} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${shown}`, ` ${originLine(candidate.origin, candidate.originKnown)} (recheck: ${preview.originRecheck})`, ...preview.overlaps.map(overlap => ` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`),
|
|
750
|
+
`preview only: run ${preview.next} to ${decision} it`].join("\n");
|
|
751
|
+
}
|
|
752
|
+
if (decision === "defer") return options["--json"] ? JSON.stringify({ candidateId: candidate.id, status: "pending", decision }, null, 2) : `deferred candidate ${candidate.id}; it stays pending`;
|
|
753
|
+
if (decision === "reject") {
|
|
754
|
+
candidates.reject(candidate.id, { project, actor, verdict: "public" });
|
|
755
|
+
return options["--json"] ? JSON.stringify({ candidateId: candidate.id, status: "rejected" }, null, 2) : `rejected candidate ${candidate.id}`;
|
|
756
|
+
}
|
|
757
|
+
candidates.close(); overlapStore?.close(); overlapStore = undefined;
|
|
758
|
+
return runCli(["review", "accept", candidate.id, "--kind", candidate.input.kind, ...(options["--json"] === true ? ["--json"] : [])], context);
|
|
759
|
+
}
|
|
661
760
|
if (sub === "walk") {
|
|
662
761
|
// F7 / AC4: each candidate is stamped shown as it is put in front of the person, then accepted, edited (written as the person's own note and the candidate closed), rejected or skipped.
|
|
663
762
|
// The candidate is WRITTEN to the terminal before the question, and stamped shown only after that write succeeded: a person who answers a/e/r must have seen what it is, and a Ctrl-C
|
|
@@ -672,26 +771,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
672
771
|
if (!rows.length) return "no candidates pending";
|
|
673
772
|
const done = { accepted: 0, edited: 0, rejected: 0, skipped: 0, failed: 0 };
|
|
674
773
|
const lines = { push: (...texts: string[]) => { for (const text of texts) write(text); return 0; } };
|
|
675
|
-
const body = (candidate: (typeof rows)[number]): string => { const input = candidate.input;
|
|
676
|
-
if (input.kind === "promotion") {
|
|
677
|
-
const viewStore = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
678
|
-
try {
|
|
679
|
-
const target = viewStore.get(input.target.id, project);
|
|
680
|
-
administrative({ candidate, target });
|
|
681
|
-
return target && target.id === input.target.id && candidateTargetRevision(target) === input.target.revision
|
|
682
|
-
? `promotion. Goal goal:${input.goalId}, mem:${target.id}. ${target.title ? `${target.title}: ` : ""}${target.text}`
|
|
683
|
-
: `promotion. Goal goal:${input.goalId}, target mem:${input.target.id} changed or is unavailable; reject or skip`;
|
|
684
|
-
} finally { viewStore.close(); }
|
|
685
|
-
}
|
|
686
|
-
if (input.kind === "model-answer") return `Model answer (not evidence; cannot accept, author an independent note with amem note add). ${input.text}`;
|
|
687
|
-
if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
|
|
688
|
-
return input.kind === "memory" ? `${input.title ? `${input.title}: ` : ""}${input.text}` : input.kind === "fail" ? `fail. Approach: ${input.approach} Symptom: ${input.symptom} Cause: ${input.cause} Retry when: ${input.retryWhen}`
|
|
689
|
-
: input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
|
|
690
774
|
const step = async (args: string[]) => { try { await runCli(args, context); return true; } catch (error) { lines.push(` ${(error as Error).message.split("\n")[0]}`); done.failed++; return false; } };
|
|
691
775
|
for (const [index, candidate] of rows.entries()) {
|
|
692
776
|
assertWalkCurrent();
|
|
693
777
|
if (!candidatePermitted(candidate)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
694
|
-
lines.push(`${index + 1}/${rows.length} ${candidate.id.slice(0, 12)} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${terminalSafe(body(candidate))}`);
|
|
778
|
+
lines.push(`${index + 1}/${rows.length} ${candidate.id.slice(0, 12)} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${originLine(candidate.origin, candidate.originKnown)}`, ` ${terminalSafe(body(candidate))}`);
|
|
695
779
|
for (const overlap of await overlapsFor(candidate)) lines.push(` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`);
|
|
696
780
|
assertWalkCurrent();
|
|
697
781
|
markShown(base, scope, Date.now(), [candidate.id]); // after the write: shown means the person could read it
|
|
@@ -738,7 +822,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
738
822
|
if (JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)) !== revision) throw Error("overlap policy changed");
|
|
739
823
|
return JSON.stringify(hinted, null, 2);
|
|
740
824
|
}
|
|
741
|
-
return rows.length ? rows.map(candidate => `${candidate.id} ${candidate.input.kind} ${candidate.status} ${candidate.createdAt}`).join("\n") : "no candidates waiting for review";
|
|
825
|
+
return rows.length ? rows.map(candidate => `${candidate.id} ${candidate.input.kind} ${candidate.status} ${candidate.createdAt} ${originLine(candidate.origin, candidate.originKnown)}`).join("\n") : "no candidates waiting for review";
|
|
742
826
|
}
|
|
743
827
|
if (sub === "reject") {
|
|
744
828
|
candidates.reject(id!, { project, actor, verdict: "public" });
|
|
@@ -1014,6 +1098,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1014
1098
|
return [...preview, `appended to ${written.path}. amem does not commit or push: review and commit it yourself.`,
|
|
1015
1099
|
...(repoLogIgnored(root) ? ["WARNING: git ignores .amem/log.jsonl here, so `git status` will not show it and it cannot be committed until you un-ignore it (a .gitignore or .git/info/exclude rule)."] : [])].join("\n");
|
|
1016
1100
|
}
|
|
1101
|
+
if (sub === "show" && /^capture:[1-9][0-9]*$/.test(parsed.positionals[0] ?? "") && options["--history"] !== true && options["--as-of"] === undefined) {
|
|
1102
|
+
// #323 item 3: a capture row (a Record included) by id, through the screened MCP read, with its session and row time.
|
|
1103
|
+
const memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base: memoryHome() });
|
|
1104
|
+
try {
|
|
1105
|
+
const shown = await memory.tools.amem_show({ id: parsed.positionals[0]! }) as { capture?: import("./memory/capture.ts").CaptureRow } | null;
|
|
1106
|
+
const row = shown?.capture; if (!row) throw new Error(`no capture row ${parsed.positionals[0]} in this project (capture is machine-local and expires; inspect the current project timeline and retention)`);
|
|
1107
|
+
return options["--json"] === true ? JSON.stringify(row, null, 2)
|
|
1108
|
+
: [`capture:${row.id} ${row.event}${row.tool ? ` ${row.tool}` : ""}, ${row.at}, agent ${row.agent}, session ${row.session ?? "unavailable"}${row.subagent ? ", subagent" : ""}`,
|
|
1109
|
+
...(row.paths.length ? [`paths: ${row.paths.join(", ")}`] : []), "", terminalSafe(row.excerpt)].join("\n");
|
|
1110
|
+
} finally { memory.close(); }
|
|
1111
|
+
}
|
|
1017
1112
|
if (sub === "show" && /^repo:/.test(parsed.positionals[0] ?? "")) {
|
|
1018
1113
|
const project = boundProject(), root = boundRepoRoot(repoCwd, memoryHome(), project), scoped = root ? repoReadPolicy(root) : undefined;
|
|
1019
1114
|
const rows = root && scoped && !("reason" in scoped) ? (await readRepoScope(root, scoped.policy)).views : [];
|
|
@@ -1119,7 +1214,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1119
1214
|
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
|
|
1120
1215
|
placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
|
|
1121
1216
|
}
|
|
1122
|
-
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person:
|
|
1217
|
+
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1123
1218
|
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1124
1219
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1125
1220
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
package/src/commands-table.ts
CHANGED
|
@@ -109,6 +109,8 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
109
109
|
} },
|
|
110
110
|
accept: { description: "Accept one candidate through the current memory policy", options: { ...policy, "--kind": { description: "Require the selected candidate kind", value: ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] } }, args: [{ name: "full-candidate-id" }], mutates: true, policyFree: true },
|
|
111
111
|
reject: { description: "Reject one candidate", args: [{ name: "full-candidate-id" }], mutates: true },
|
|
112
|
+
decide: { description: "Non-interactive review of one candidate: preview it (stamped shown) without --confirm; accept, reject or defer it with --confirm", options: { ...json, ...policy, "--confirm": flag("Apply the previewed decision") },
|
|
113
|
+
args: [{ name: "full-candidate-id" }, { name: "decision", values: ["accept", "reject", "defer"] }], mutates: "confirm", policyFree: true },
|
|
112
114
|
walk: { description: "Walk the pending candidates one by one: accept, edit (as a new note), reject, skip or quit", mutates: true, options: { "--kind": { description: "Candidate kind", value: ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] } } },
|
|
113
115
|
} },
|
|
114
116
|
decay: { description: "Preview old live long-term notes unprotected by open goals; apply only with --apply --confirm", mutates: "apply", options: {
|
|
@@ -123,6 +125,10 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
123
125
|
"--writer-root": { description: "Repeatable absolute amem install root in the complete local writer inventory", value: "path" },
|
|
124
126
|
} },
|
|
125
127
|
status: { description: "Report shard migration and pending old-layout appends", options: json },
|
|
128
|
+
formats: { description: "Format floors in formats.json", commands: {
|
|
129
|
+
raise: { description: "Preview the record and the writer inventory; append it to formats.json only with --confirm, refused while any known writer is below the floor", mutates: "confirm",
|
|
130
|
+
options: { ...json, "--confirm": flag("Append the previewed record") }, args: [{ name: "surface", values: ["home", "curated", "capture", "hook-spool", "candidates", "work-lists", "sync"] }, { name: "min-reader" }] },
|
|
131
|
+
} },
|
|
126
132
|
doctor: { description: "One read-only report (F15): duplicates and stale notes, pending candidates, capture freshness per CLI, the brief's token cost, index equals rebuild, reader leases, the policy in effect, ingest and sync cadence", options: json },
|
|
127
133
|
prune: { description: "Plan or apply exact-entry durable expiry in a generation", mutates: true, options: {
|
|
128
134
|
...json, "--cutoff": text("Canonical UTC expiry cutoff"), "--dry-run": flag("Print a local sealed plan without writes"),
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export * from "./memory/store.ts";
|
|
2
|
+
// #431 / agent-hub#1522: hosts that run amem on an agent's behalf attribute its writes to that agent.
|
|
3
|
+
export { withCliAttribution, cliAttribution, noteDisplayActor, type CliAttribution } from "./memory/cli-attribution.ts";
|
|
2
4
|
export type { ScoreFactors } from "./memory/search-score.ts";
|
|
3
5
|
export * from "./memory/capture.ts";
|
|
4
6
|
export { fts5Available, ftsTerms, SearchIndex, captureSearch } from "./memory/search-fts.ts";
|
package/src/mcp-memory.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { projectState } from "./memory/lifecycle.ts";
|
|
|
25
25
|
import { boundRepoRoot, readRepoScope, repoReadPolicy, type RepoView } from "./memory/repo-scope.ts";
|
|
26
26
|
import { MemoryStore, openShardStore, type Graph, type View } from "./memory/store.ts";
|
|
27
27
|
import { vaultCandidates } from "./memory/vault.ts";
|
|
28
|
+
import { validOrigin, type CandidateOrigin } from "./memory/candidate-origin.ts";
|
|
28
29
|
import { groupByTask } from "./memory/task-group.ts";
|
|
29
30
|
/** #423: how many ranked hits per requested slot a grouped search reads, so folded same-task hits do not empty the page. */
|
|
30
31
|
const TASK_GROUP_WINDOW = 4;
|
|
@@ -36,7 +37,10 @@ export const MCP_SCAN_LIMIT = 5000;
|
|
|
36
37
|
const SEARCH_CANDIDATES = 5000;
|
|
37
38
|
const READ_PAGE = 256;
|
|
38
39
|
type SearchValue = { source: "curated"; evidence: true; view: View } | { source: "repo"; evidence: false; view: RepoView } | { source: "capture"; evidence: false; capture: CaptureRow };
|
|
39
|
-
export interface MemoryMcpOptions {
|
|
40
|
+
export interface MemoryMcpOptions {
|
|
41
|
+
/** #323: ids the host knows about the proposing session, read on each proposal; nothing is inferred when absent. */
|
|
42
|
+
origin?: () => { session?: string; peer?: string; turn?: string } | undefined;
|
|
43
|
+
cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void }
|
|
40
44
|
export interface MemoryMcp { tools: McpHandlers; close(): void; onEmitted: NonNullable<McpOptions["onEmitted"]> }
|
|
41
45
|
const unavailable = (): never => { throw new Error("memory operation unavailable"); };
|
|
42
46
|
const bound = (args: Record<string, unknown>, keys: string[]) => { if (Object.keys(args).some(key => !keys.includes(key))) unavailable(); };
|
|
@@ -154,16 +158,25 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
|
|
|
154
158
|
const revision = target && candidateTargetRevision(target);
|
|
155
159
|
const currentPolicy = () => createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
|
|
156
160
|
const check = () => { guard(); if (target && candidateTargetRevision(correctionTarget(target.id)) !== revision) unavailable(); };
|
|
157
|
-
|
|
161
|
+
let supplied: ReturnType<NonNullable<MemoryMcpOptions["origin"]>>;
|
|
162
|
+
try { supplied = options.origin?.(); } catch { supplied = undefined; }
|
|
163
|
+
// Ids only and bounded (validOrigin, secret screen included); an invalid host value records no origin rather than refusing.
|
|
164
|
+
let origin: CandidateOrigin | undefined;
|
|
165
|
+
try { origin = validOrigin(supplied ? { ...supplied, at: new Date(store.readNow()).toISOString() } : undefined); } catch { origin = undefined; }
|
|
166
|
+
// AC3: the origin is screened with the proposal by the full host policy, then by the final synchronous snapshot that fences the append.
|
|
167
|
+
// A declined origin is dropped and the proposal alone is screened again on both paths, so the proposal still stands.
|
|
168
|
+
const completeOf = (withOrigin: boolean) => ({ ...(target ? { ...input, targetView: target } : input), ...(withOrigin && origin ? { origin } : {}) });
|
|
158
169
|
check();
|
|
159
|
-
if (!await currentPolicy().screen(
|
|
170
|
+
if (origin && !await currentPolicy().screen(completeOf(true))) origin = undefined;
|
|
171
|
+
if (!await currentPolicy().screen(completeOf(false))) unavailable();
|
|
160
172
|
check();
|
|
161
173
|
const overlaps = includeOverlaps ? (await candidateOverlaps(candidates.get(candidateInputId(input), project) ?? { status: "pending", input }, store,
|
|
162
174
|
{ project, policy: currentPolicy, policyVersion: policyRevisionForCall, assertCurrent: check })).map(row => row.id) : undefined;
|
|
163
|
-
// Config can tighten while the host screen awaits. Its synchronous check fences the final append.
|
|
164
|
-
if (!currentPolicy().screenStandalone(
|
|
175
|
+
// Config can tighten while the host screen awaits. Its synchronous check fences the final append, origin included.
|
|
176
|
+
if (!currentPolicy().screenStandalone(completeOf(false))) unavailable();
|
|
177
|
+
if (origin && !currentPolicy().screenStandalone(completeOf(true))) origin = undefined;
|
|
165
178
|
check();
|
|
166
|
-
return { id: candidates.put(input, "public"), ...(overlaps === undefined ? {} : { overlaps }) };
|
|
179
|
+
return { id: candidates.put(input, "public", origin), ...(overlaps === undefined ? {} : { overlaps }) };
|
|
167
180
|
};
|
|
168
181
|
const tools: McpHandlers = {
|
|
169
182
|
async amem_evidence(args) {
|