@staix/agent-mem 0.27.0 → 0.27.1

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.27.0",
3
+ "version": "0.27.1",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
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.27.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.27.1. 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; its memory reads use the screened policy and historical reads are refused. 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; `$EDITOR` opens only when a terminal is available.
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 only when `review walk` 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.
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
 
@@ -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 person-raised `home` or `curated` floor of 0.24.0 or later; code never changes that floor. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. Only an unmarked person `amem brief` 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, agent-marked CLI reads 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.
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 the person; 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.
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 have the person append the existing `home` reader floor at 0.23.0. 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. Core never writes `formats.json`; a floor prevents old participation rather than teaching old readers the event.
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.27.0",
3
+ "version": "0.27.1",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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
- if (path[0] === "machine" && options["--label"] === undefined) throw new AgentUsageError(`amem machine without --label is not available to an agent-marked session. ${AGENT_READS}`);
44
- // Write/preview/confirmation paths continue through the guarded administrative handlers.
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")) throw accepts("search", ["--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")) throw accepts("list", ["--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()) throw accepts("show", []);
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
- if (path[0] === "brief") {
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")) throw accepts("graph", ["--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) throw accepts("vault-candidates", ["--limit"]);
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()) throw accepts("capacity", []);
79
+ if (!only()) return undefined;
88
80
  return { tool: "amem_capacity", args: {} };
89
81
  }
90
- throw new AgentUsageError(`amem ${path.join(" ")} is not available to an agent-marked session. ${AGENT_READS}`);
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
@@ -85,6 +85,8 @@ export interface CliContext {
85
85
  edit?: (initial: string) => string | Promise<string>;
86
86
  /** Where `sync --progress` writes (default process.stderr) and whether that is a terminal; fixtures stand in for both. */
87
87
  stderr?: (text: string) => void; stderrTTY?: boolean;
88
+ /** Test seams for `amem formats raise`: the process table (`pid args` lines; default `ps -axo pid=,args=`) and the clock that dates the record. */
89
+ processTable?: () => string; now?: () => number; embeddedAmem?: (dir: string) => boolean;
88
90
  /** Test seam: the `sync --if-due` deadline in milliseconds (the CLI always uses 30 seconds). */
89
91
  syncDeadlineMs?: number;
90
92
  /** 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. */
@@ -389,7 +391,6 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
389
391
  const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
390
392
  if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
391
393
  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
394
  } else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined)) {
394
395
  throw new AgentUsageError("--writer-root and --abandon apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
395
396
  }
@@ -483,7 +484,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
483
484
  const result = await buildIntentBrief(createIntentBriefSource(store, project),
484
485
  { project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
485
486
  assertCurrent(); outputReady(result.items.map(view => view.id), project);
486
- if (actor === "person") store.prepareCuratedBriefs([project]);
487
+ store.prepareCuratedBriefs([project]);
487
488
  return options["--json"] ? JSON.stringify({ brief: result.text, bytes: result.bytes, truncated: result.truncated, state: result.state }, null, 2) : result.text;
488
489
  } finally { store.close(); }
489
490
  }
@@ -496,7 +497,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
496
497
  const { activateSyncPlacement } = await import("./memory/sync-placement-activation.ts");
497
498
  const result = await activateSyncPlacement({ memoryDir:memoryHome(),mode:options["--abandon"]?"abandon":mode as "dry-run"|"apply"|"resume",
498
499
  writerRoots:repeated(argv,"--writer-root"),ownRoot:fileURLToPath(new URL("..",import.meta.url)),
499
- authorize:()=>cliAttribution()?.actor==="person" });
500
+ authorize:()=>true });
500
501
  if (options["--json"] === true) return JSON.stringify(result,null,2);
501
502
  // Metadata only: the source reader and locator are never serialized into this receipt.
502
503
  return `sync placement: ${result.mode}; ${result.active?"active":"inactive"}; home-wide, forward-only (no deactivate)\n${JSON.stringify(result,null,2)}`;
@@ -535,6 +536,42 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
535
536
  ...shardMigrationStatus(where.home) };
536
537
  return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context));
537
538
  }
539
+ if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
540
+ const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
541
+ const { readSetupWriterRoots } = await import("./setup.ts"), { readEffectiveSyncPlacementWriterRoots } = await import("./memory/sync-placement-effective-writers.ts");
542
+ const [surface, minReader] = parsed.positionals;
543
+ if (!surface || !minReader || parsed.positionals.length !== 2) throw new Error("usage: amem formats raise <surface> <min-reader> [--confirm] [--json]");
544
+ const home = realPath(memoryHome()), own = realPath(fileURLToPath(new URL("..", import.meta.url)));
545
+ const inventory = (): import("./memory/formats-raise.ts").FormatWriterInventory => {
546
+ const writers: import("./memory/formats-raise.ts").FormatWriter[] = [], incomplete: string[] = [], seen = new Set<string>();
547
+ const add = (source: "setup" | "sync-placement" | "running" | "library-host" | "self", root: string, pid?: number, host?: string) => {
548
+ let canonical = root; try { canonical = realPath(root); } catch { /* a missing root reads as an unknown version */ }
549
+ const key = `${source}\0${canonical}\0${pid ?? ""}`; if (seen.has(key)) return; seen.add(key);
550
+ writers.push({ source, root: canonical, version: installVersion(canonical), ...(pid !== undefined ? { pid } : {}), ...(host !== undefined ? { host } : {}) });
551
+ };
552
+ add("self", own);
553
+ try { for (const root of readSetupWriterRoots(home)) add("setup", root); } catch (error) { incomplete.push(`setup receipts: ${(error as Error).message.split("\n")[0]}`); }
554
+ if ((readPlacementRuntimeMarkers(home).profile as { publicationFormat?: string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
555
+ try { for (const root of readEffectiveSyncPlacementWriterRoots(home)) add("sync-placement", root); } catch { incomplete.push("sync-placement writer roots unreadable"); }
556
+ }
557
+ try {
558
+ 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))();
559
+ for (const { pid, root, host } of runningAmemRoots(table, context.embeddedAmem)) add(host ? "library-host" : "running", root, pid, host);
560
+ } catch { incomplete.push("running processes could not be listed"); }
561
+ return { writers: writers.sort((a, b) => a.source.localeCompare(b.source) || a.root.localeCompare(b.root) || (a.pid ?? 0) - (b.pid ?? 0)), incomplete };
562
+ };
563
+ const now = context.now ? () => new Date(context.now!()) : undefined;
564
+ const plan = planFormatRaise(home, surface, minReader, inventory(), now);
565
+ if (options["--confirm"] !== true) {
566
+ const refusal = formatRaiseRefusal(plan);
567
+ if (options["--json"] === true) return JSON.stringify({ ...plan, refusal: refusal ?? null }, null, 2);
568
+ 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"}`,
569
+ `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}` : ""})` : ""}`),
570
+ refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
571
+ }
572
+ const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
573
+ return options["--json"] === true ? JSON.stringify({ appended: record, file: plan.file }, null, 2) : `appended ${JSON.stringify(record)} to ${plan.file}`;
574
+ }
538
575
  if (sub === "doctor") {
539
576
  // F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
540
577
  const where = resolveMemoryHome(), project = boundProject();
@@ -625,10 +662,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
625
662
  }
626
663
  if (review) {
627
664
  const id = parsed.positionals[0];
628
- if (sub !== "list" && sub !== "walk" && (!id || !/^[a-f0-9]{64}$/.test(id))) throw new Error("review accept/reject requires a full 64-character candidate id");
665
+ 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
666
  if (sub === "walk" && !(context.stdinTTY ?? process.stdin.isTTY)) throw Error("review walk requires a terminal on stdin; stdout must be a terminal too");
630
667
  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
668
  const project = boundProject(), aliases = aliasedKeys(memoryHome(), project), candidates = new CandidateStore(aliases.length ? { reconcile: { canonical: project, aliases } } : {});
633
669
  let overlapStore: MemoryStore | undefined;
634
670
  try {
@@ -658,6 +694,49 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
658
694
  const selected = candidates.get(id!, project);
659
695
  if (!selected || !candidatePermitted(selected)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
660
696
  }
697
+ const body = (candidate: import("./memory/candidates.ts").Candidate): string => { const input = candidate.input;
698
+ if (input.kind === "promotion") {
699
+ const viewStore = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
700
+ try {
701
+ const target = viewStore.get(input.target.id, project);
702
+ administrative({ candidate, target });
703
+ return target && target.id === input.target.id && candidateTargetRevision(target) === input.target.revision
704
+ ? `promotion. Goal goal:${input.goalId}, mem:${target.id}. ${target.title ? `${target.title}: ` : ""}${target.text}`
705
+ : `promotion. Goal goal:${input.goalId}, target mem:${input.target.id} changed or is unavailable; reject or skip`;
706
+ } finally { viewStore.close(); }
707
+ }
708
+ if (input.kind === "model-answer") return `Model answer (not evidence; cannot accept, author an independent note with amem note add). ${input.text}`;
709
+ if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
710
+ 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}`
711
+ : input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
712
+ if (sub === "decide") {
713
+ // #431 AC5: what `review walk` gives a person, one candidate at a time and without a terminal. The preview prints the
714
+ // candidate and its overlaps and stamps it shown (the caller read it); --confirm then applies exactly the named decision.
715
+ const decision = parsed.positionals[1];
716
+ if (decision !== "accept" && decision !== "reject" && decision !== "defer") throw new Error("usage: amem review decide <full-candidate-id> accept|reject|defer [--confirm]");
717
+ const candidate = candidates.get(id!, project);
718
+ if (!candidate || !candidatePermitted(candidate)) throw new Error("candidate unavailable");
719
+ if (candidate.status !== "pending") throw new Error(`candidate is ${candidate.status}, not pending`);
720
+ if (decision === "accept" && candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
721
+ if (decision === "accept" && candidate.input.kind === "model-answer") throw new Error("model answers cannot be accepted; author an independent note with amem note add");
722
+ if (options["--confirm"] !== true) {
723
+ const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
724
+ const preview = { candidateId: candidate.id, kind: candidate.input.kind, createdAt: candidate.createdAt, decision, body: shown,
725
+ overlaps: overlaps.map(overlap => ({ id: overlap.id, score: overlap.score, title: overlap.title ?? null })), next: `amem review decide ${candidate.id} ${decision} --confirm` };
726
+ administrative(preview);
727
+ markShown(realPath(candidates.dir), [project, ...aliases], Date.now(), [candidate.id]);
728
+ return options["--json"] ? JSON.stringify(preview, null, 2)
729
+ : [`${candidate.id} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${shown}`, ...preview.overlaps.map(overlap => ` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`),
730
+ `preview only: run ${preview.next} to ${decision} it`].join("\n");
731
+ }
732
+ if (decision === "defer") return options["--json"] ? JSON.stringify({ candidateId: candidate.id, status: "pending", decision }, null, 2) : `deferred candidate ${candidate.id}; it stays pending`;
733
+ if (decision === "reject") {
734
+ candidates.reject(candidate.id, { project, actor, verdict: "public" });
735
+ return options["--json"] ? JSON.stringify({ candidateId: candidate.id, status: "rejected" }, null, 2) : `rejected candidate ${candidate.id}`;
736
+ }
737
+ candidates.close(); overlapStore?.close(); overlapStore = undefined;
738
+ return runCli(["review", "accept", candidate.id, "--kind", candidate.input.kind, ...(options["--json"] === true ? ["--json"] : [])], context);
739
+ }
661
740
  if (sub === "walk") {
662
741
  // 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
742
  // 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,21 +751,6 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
672
751
  if (!rows.length) return "no candidates pending";
673
752
  const done = { accepted: 0, edited: 0, rejected: 0, skipped: 0, failed: 0 };
674
753
  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
754
  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
755
  for (const [index, candidate] of rows.entries()) {
692
756
  assertWalkCurrent();
@@ -1119,7 +1183,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1119
1183
  progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
1120
1184
  placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
1121
1185
  }
1122
- output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: identity.actor === "person", rankedSearch: identity.actor === "person" && !legacySearch, ...(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),
1186
+ 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
1187
  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
1188
  onBridgeStatus: status => { receipt.bridgeStatus = status; },
1125
1189
  // #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
@@ -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";
@@ -6,7 +6,23 @@ const scope = new AsyncLocalStorage<Readonly<CliAttribution>>();
6
6
 
7
7
  /** Preserve library defaults outside an ordinary CLI invocation, including concurrent calls. */
8
8
  export function cliAttribution(): Readonly<CliAttribution> | undefined { return scope.getStore(); }
9
- export function withCliAttribution<T>(identity: CliAttribution, work: () => T): T { return scope.run(Object.freeze({ ...identity, peer: identity.actor === "agent" && identity.peer === "person" ? "agent" : identity.peer }), work); }
9
+ /**
10
+ * Run `work` with `identity` in the attribution scope (root API, #431 / agent-hub#1522). Only library code that reads the scope is
11
+ * attributed: `rawMemoryCommand` promote, demote, forget, supersede, confirm and reject, every `rawGoalCommand` write and the
12
+ * `MemoryStore.dedupe` replacement record `identity.actor` as the operation actor (default `user`); notes written by `CandidateStore.accept`
13
+ * record `identity.peer` as their peer (default: the accept call's actor). Other writes, including a direct `MemoryStore.note`, are not
14
+ * attributed and keep what their caller passes. An agent scope also refuses withheld targets in those commands and screens
15
+ * `assertCliPolicy` values with `identity.policy`. Attribution only: it never authenticates, grants access or bypasses a screen.
16
+ * docs/contracts.md (Attribution scope) is the full list. It refuses before running `work` when it has no agent identity (no usable peer).
17
+ */
18
+ export function withCliAttribution<T>(identity: CliAttribution, work: () => T): T {
19
+ if (!identity || (identity.actor !== "person" && identity.actor !== "agent")) throw new Error("memory attribution needs actor person or agent");
20
+ const remedy = "Fix or unset AGENTHUB_PEER_ID, or pass a nonblank session peer id of at most 120 characters without control characters";
21
+ if (typeof identity.peer !== "string" || !identity.peer.trim()) throw new Error(`memory attribution peer is missing or blank; nothing was run. ${remedy}`);
22
+ if (identity.peer.length > 120) throw new Error(`memory attribution peer exceeds 120 characters; nothing was run. ${remedy}`);
23
+ if (/[\p{Cc}]/u.test(identity.peer)) throw new Error(`memory attribution peer contains a control character; nothing was run. ${remedy}`);
24
+ return scope.run(Object.freeze({ ...identity, peer: identity.actor === "agent" && identity.peer === "person" ? "agent" : identity.peer }), work);
25
+ }
10
26
 
11
27
  /** Display metadata derived from the existing peer field; never a claim of authentication. */
12
28
  export const noteDisplayActor = (peer: string): "person" | "agent" => peer === "person" ? "person" : "agent";
@@ -32,6 +32,8 @@ export interface MemoryCommandOptions {
32
32
  sync?: Omit<SyncOptions, "remote">;
33
33
  open: () => MemoryStore;
34
34
  readable: (notes: View[]) => View[];
35
+ /** #431: an agent-marked CLI graph is screened by `readable`; a host's raw graph stays an explicit person-only ceiling. */
36
+ screenGraph?: boolean;
35
37
  stale?: (view: View) => boolean | undefined;
36
38
  /** Prepared row ids only: the host must wait for successful output before recording rendered. */
37
39
  outputReady?: (notes: readonly View[]) => void;
@@ -188,7 +190,7 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
188
190
  if (hops !== 1 && hops !== 2) fail("--hops takes 1 or 2");
189
191
  const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
190
192
  const start = rest[0] ?? fail(`usage: ${names.memory} graph <id|node>`);
191
- const g = recallGraph(store, project, start, hops, { person: opts.person, history, asOf });
193
+ const g = recallGraph(store, project, start, hops, { person: opts.person, history, asOf }, opts.screenGraph ? rows => opts.readable(rows) : undefined);
192
194
  if ((!start.includes(":") || start.startsWith("mem:")) && !g.nodes.length) fail(`no memory entry ${start} (${names.memory} list shows the ids)`);
193
195
  const node = !start.includes(":") || start.startsWith("mem:") ? g.nodes[0]!.id : start;
194
196
  return json ? JSON.stringify(g, null, 2) : [`${g.nodes.length} nodes, ${g.edges.length} edges around ${node}`, ...g.edges.map((e) => `${e.from} -${e.rel}-> ${e.to}`)].join("\n");
@@ -33,7 +33,7 @@ async function invoke(model: ModelConsolidationOptions, input: ModelConsolidatio
33
33
  export async function proposeModelConsolidations(store: MemoryStore, candidates: CandidateStore, rows: readonly View[], model: ModelConsolidationOptions | undefined, guard: ModelConsolidationGuard): Promise<ModelConsolidationReport> {
34
34
  const report: ModelConsolidationReport = { state: model === undefined ? "disabled" : "known", ids: [], calls: 0, nonAnswers: 0, rejected: 0, oversized: 0, limited: false, timedOut: false, truncated: false };
35
35
  if (model === undefined) return report;
36
- if (guard.actor !== "person") throw Error("model consolidation requires person intent");
36
+ if (guard.actor !== "person" && guard.actor !== "agent") throw Error("model consolidation requires a person or an agent-marked session");
37
37
  try {
38
38
  if (!model || model.enabled !== true || typeof model.run !== "function" || !guard.project.trim() || guard.project.length > 400) throw Error("model consolidation unavailable");
39
39
  guard.check();
@@ -42,7 +42,7 @@ export async function proposeModelConsolidations(store: MemoryStore, candidates:
42
42
  const project = guard.project, sourceCurrent = store.beginRecallRead(), sources: ModelConsolidationNote[] = [], seen = new Set<string>();
43
43
  const check = (batch: readonly ModelConsolidationNote[]) => {
44
44
  guard.check(); sourceCurrent();
45
- if (guard.actor !== "person" || guard.project !== project) throw Error("model consolidation context changed");
45
+ if (guard.project !== project) throw Error("model consolidation context changed");
46
46
  const placements = batch.length ? store.entryPlacements(batch.map(row => row.id), project) : new Map<string, "local" | "synced">();
47
47
  store.withDeferredPromotions(() => {
48
48
  for (const row of batch) {
@@ -0,0 +1,114 @@
1
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync, renameSync, rmSync, writeFileSync, fsyncSync } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { dirname, join } from "node:path";
4
+ import { FORMAT_SURFACES, FORMATS_FILE, readFormatFloors, type FormatFloor } from "./formats.ts";
5
+ import { acquireMutation } from "./mutation.ts";
6
+ import { realPath } from "./platform.ts";
7
+
8
+ /**
9
+ * #431 AC6: `amem formats raise <surface> <minReader> [--confirm]`. The preview names the exact record and every writer this home
10
+ * knows about; the raise appends that one record and refuses while any known writer is below `minReader`. A writer whose version
11
+ * cannot be read refuses too: an unproven writer is treated as below. Records are never rewritten or removed.
12
+ */
13
+ const PLAIN = /^(\d+)\.(\d+)\.(\d+)$/;
14
+ const MAX_WRITERS = 256, PACKAGE_BYTES = 64 * 1024, MAX_ANCESTORS = 12;
15
+ export type FormatRaiseSurface = typeof FORMAT_SURFACES[number] | "home";
16
+ export interface FormatWriter { source: "setup" | "sync-placement" | "running" | "library-host" | "self"; root: string; version: string | null; pid?: number; host?: string }
17
+ export interface FormatWriterInventory { writers: FormatWriter[]; incomplete: string[] }
18
+ export interface FormatRaisePlan {
19
+ home: string; file: string; record: FormatFloor; writers: FormatWriter[]; below: FormatWriter[]; incomplete: string[];
20
+ existing: FormatFloor[]; alreadyAtLeast: boolean; ready: boolean;
21
+ }
22
+
23
+ const parts = (version: string) => PLAIN.exec(version)!.slice(1, 4).map(Number);
24
+ export function versionBelow(version: string, floor: string): boolean {
25
+ const a = parts(version), b = parts(floor);
26
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! < b[i]!;
27
+ return false;
28
+ }
29
+
30
+ /** The version of an amem install root, or null when it is not a readable `@staix/agent-mem` package with a plain release version. */
31
+ export function installVersion(root: string): string | null {
32
+ let fd: number | undefined;
33
+ try {
34
+ fd = openSync(join(root, "package.json"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
35
+ const stat = fstatSync(fd); if (!stat.isFile() || stat.size > PACKAGE_BYTES) return null;
36
+ const data = Buffer.alloc(stat.size); let at = 0;
37
+ while (at < data.length) { const n = readSync(fd, data, at, data.length - at, at); if (n <= 0) return null; at += n; }
38
+ const value = JSON.parse(data.toString("utf8")) as { name?: unknown; version?: unknown };
39
+ return value.name === "@staix/agent-mem" && typeof value.version === "string" && PLAIN.test(value.version) ? value.version : null;
40
+ } catch { return null; } finally { if (fd !== undefined) closeSync(fd); }
41
+ }
42
+
43
+ /**
44
+ * Install roots of running processes that load agent-mem: an amem CLI (`<root>/bin/amem.js` or `<root>/src/cli.ts`), or a host that embeds
45
+ * it as a library (ahub, vmem), found as `node_modules/@staix/agent-mem` in an ancestor of a script path on its command line. Bounded.
46
+ * `embedded(dir)` answers whether `dir/node_modules/@staix/agent-mem` exists; it defaults to the filesystem.
47
+ */
48
+ export function runningAmemRoots(table: () => string, embedded: (dir: string) => boolean = dir => existsSync(join(dir, "node_modules", "@staix", "agent-mem", "package.json"))): { pid: number; root: string; host?: string }[] {
49
+ const out: { pid: number; root: string; host?: string }[] = [], memo = new Map<string, string | null>();
50
+ const library = (script: string): string | null => {
51
+ let dir = dirname(script);
52
+ for (let depth = 0; depth < MAX_ANCESTORS && dir !== dirname(dir); depth++, dir = dirname(dir)) {
53
+ if (memo.has(dir)) return memo.get(dir)!;
54
+ let found: string | null = null;
55
+ try { if (embedded(dir)) found = join(dir, "node_modules", "@staix", "agent-mem"); } catch { /* unreadable: look further up */ }
56
+ if (found) { memo.set(dir, found); return found; }
57
+ }
58
+ return null;
59
+ };
60
+ for (const line of table().split("\n")) {
61
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line); if (!match) continue;
62
+ const pid = Number(match[1]); if (pid === process.pid) continue;
63
+ const tokens = match[2]!.split(/\s+/);
64
+ const cli = tokens.map(token => /^(\/.+)\/(?:bin\/amem\.js|src\/cli\.ts)$/.exec(token)).find(Boolean);
65
+ if (cli) out.push({ pid, root: cli[1]! });
66
+ else for (const token of tokens) {
67
+ if (!token.startsWith("/") || !/\.(?:[cm]?[jt]s)$/.test(token)) continue;
68
+ const root = library(token); if (!root) continue;
69
+ out.push({ pid, root, host: token }); break;
70
+ }
71
+ if (out.length >= MAX_WRITERS) break;
72
+ }
73
+ return out;
74
+ }
75
+
76
+ export function planFormatRaise(home: string, surface: string, minReader: string, inventory: FormatWriterInventory, now: () => Date = () => new Date()): FormatRaisePlan {
77
+ if (surface !== "home" && !(FORMAT_SURFACES as readonly string[]).includes(surface)) throw new Error(`unknown format surface ${surface}; use one of home, ${FORMAT_SURFACES.join(", ")}`);
78
+ if (!PLAIN.test(minReader)) throw new Error("minReader must be a plain release version such as 0.27.0");
79
+ const base = realPath(home), existing = readFormatFloors(base) ?? [];
80
+ const record: FormatFloor = { surface, minReader, since: now().toISOString().slice(0, 10) };
81
+ const below = inventory.writers.filter(writer => writer.version === null || versionBelow(writer.version, minReader));
82
+ const alreadyAtLeast = existing.some(floor => floor.surface === surface && PLAIN.test(floor.minReader) && !versionBelow(floor.minReader, minReader));
83
+ return { home: base, file: join(base, FORMATS_FILE), record, writers: inventory.writers, below, incomplete: inventory.incomplete, existing, alreadyAtLeast,
84
+ ready: !below.length && !inventory.incomplete.length && !alreadyAtLeast };
85
+ }
86
+
87
+ export function formatRaiseRefusal(plan: FormatRaisePlan): string | undefined {
88
+ if (plan.alreadyAtLeast) return `formats.json already records a ${plan.record.surface} floor at or above ${plan.record.minReader}; nothing to raise`;
89
+ if (plan.incomplete.length) return `the writer inventory is incomplete (${plan.incomplete.join("; ")}); fix it before raising a floor`;
90
+ if (plan.below.length) return `writers below ${plan.record.minReader}: ${plan.below.map(writer => `${writer.source} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""} at ${writer.version ?? "unknown version"}`).join("; ")}. Upgrade or stop them, then rerun`;
91
+ return undefined;
92
+ }
93
+
94
+ /** Appends the planned record under the home's mutation fence after rechecking the floors and the inventory are unchanged. */
95
+ export function applyFormatRaise(plan: FormatRaisePlan, recheck: () => FormatRaisePlan): FormatFloor {
96
+ const refusal = formatRaiseRefusal(plan); if (refusal) throw new Error(refusal);
97
+ const release = acquireMutation(plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
98
+ try {
99
+ const fresh = recheck();
100
+ if (JSON.stringify(fresh.existing) !== JSON.stringify(plan.existing) || JSON.stringify(fresh.writers) !== JSON.stringify(plan.writers)) throw new Error("formats.json or the writer inventory changed since the preview; rerun the preview");
101
+ const again = formatRaiseRefusal(fresh); if (again) throw new Error(again);
102
+ const stat = lstatSync(plan.file, { throwIfNoEntry: false });
103
+ if (stat && (stat.isSymbolicLink() || !stat.isFile())) throw new Error(`${plan.file} is not a regular file`);
104
+ const text = JSON.stringify([...plan.existing, plan.record], null, 2) + "\n", temporary = join(dirname(plan.file), `.${FORMATS_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
105
+ try {
106
+ writeFileSync(temporary, text, { mode: 0o600, flag: "wx" });
107
+ const fd = openSync(temporary, constants.O_RDONLY); try { fsyncSync(fd); } finally { closeSync(fd); }
108
+ renameSync(temporary, plan.file);
109
+ } catch (error) { rmSync(temporary, { force: true }); throw error; }
110
+ const read = readFormatFloors(plan.home) ?? [];
111
+ if (JSON.stringify(read.at(-1)) !== JSON.stringify(plan.record)) throw new Error("formats.json did not read back the appended record");
112
+ return plan.record;
113
+ } finally { release(); }
114
+ }