@staix/agent-mem 0.30.0 → 0.31.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
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",
@@ -6,6 +6,11 @@ import { memoryHome } from "./memory/home.ts";
6
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
+ export const READ_FAILURE = "Memory read failed [cause: read_failed]; no partial result is shown. Ask the person to inspect the command and memory state.";
10
+ export class AgentReadFailure extends Error { constructor() { super(READ_FAILURE); this.name = "AgentReadFailure"; } }
11
+ export class AgentReadAmbiguous extends Error {
12
+ constructor() { super("Memory read unavailable [cause: unavailable]; failure and policy withholding cannot be distinguished. Ask the person to run the same command from their own shell."); this.name = "AgentReadAmbiguous"; }
13
+ }
9
14
  const RESULT_BYTES = 262_144;
10
15
 
11
16
  /** A refusal decided from the parsed command alone, before any store or file is opened: safe to show as is. */
@@ -47,15 +52,20 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
47
52
  const flags = Object.keys(options).filter(key => key !== "--json" && key !== "--policy-free");
48
53
  const only = (...allowed: string[]) => flags.every(flag => allowed.includes(flag));
49
54
  const limit = positiveLimit(options["--limit"]);
50
- if (options["--limit"] !== undefined && limit === undefined) throw new AgentUsageError("--limit takes a whole number from 1 to 100.");
55
+ const checkedLimit = () => {
56
+ if (options["--limit"] !== undefined && limit === undefined) throw new AgentUsageError("--limit takes a whole number from 1 to 100.");
57
+ return limit;
58
+ };
51
59
 
52
60
  if (path[0] === "search") {
53
61
  if (!only("--limit", "--since", "--explain")) return undefined;
62
+ checkedLimit();
54
63
  if (!positionals.join(" ").trim()) throw new AgentUsageError("agent-marked search needs a query.");
55
64
  return { tool: "amem_search", args: { query: positionals.join(" "), ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}), ...(options["--explain"] === true ? { explain: true } : {}) } };
56
65
  }
57
66
  if (path[0] === "list") {
58
67
  if (!only("--limit", "--since")) return undefined;
68
+ checkedLimit();
59
69
  return { tool: "amem_timeline", args: { ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}) } };
60
70
  }
61
71
  if (path[0] === "show") {
@@ -73,6 +83,7 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
73
83
  }
74
84
  if (path[0] === "vault-candidates") {
75
85
  if (!only("--limit") || options["--all-projects"] !== undefined || options["--project"] !== undefined) return undefined;
86
+ checkedLimit();
76
87
  return { tool: "amem_vault_candidates", args: limit === undefined ? {} : { limit } };
77
88
  }
78
89
  if (path[0] === "capacity" && path.length === 1) {
@@ -106,7 +117,11 @@ export async function agentCliRead(
106
117
  return output;
107
118
  } catch (error) {
108
119
  if(safeProfileLockMessage(error))throw error;
109
- throw new Error(UNAVAILABLE);
120
+ // The MCP handler deliberately uses one refusal for policy and operational guards; do not guess which occurred.
121
+ let ambiguous = false;
122
+ try { ambiguous = error instanceof Error && Object.getOwnPropertyDescriptor(error, "message")?.value === "memory operation unavailable"; } catch { /* An opaque error remains a generic failure. */ }
123
+ if (ambiguous) throw new AgentReadAmbiguous();
124
+ throw new AgentReadFailure();
110
125
  } finally {
111
126
  try { memory?.close(); } catch { /* close failures do not expose partial reads */ }
112
127
  }
package/src/cli.ts CHANGED
@@ -3,7 +3,7 @@ import { assertFormatFloor } from "./memory/formats.ts";
3
3
  import { placementRuntimeRefusal, readPlacementRuntimeMarkers } from "./memory/sync-placement-guard.ts";
4
4
  import { readActivePlacementBinding } from "./memory/sync-placement-active.ts";
5
5
  import { activatePublicPruneView } from "./memory/public-prune-activation.ts";
6
- import { AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
6
+ import { AgentReadAmbiguous, AgentReadFailure, AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
7
7
  import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import type { Writable } from "node:stream";
@@ -13,7 +13,7 @@ import { recordCaptureLookup, recordSourceCheck, recordWindow } from "./memory/r
13
13
  import { createIntentBriefSource, recallViewIsLive } from "./memory/recall.ts";
14
14
  import { createRecallStalenessProbe } from "./memory/recall-staleness.ts";
15
15
  import { recordMemoryUse } from "./memory/use-telemetry.ts";
16
- import { DecayApplyError } from "./memory/decay-review.ts";
16
+ import { DecayApplyError, UNUSED_INJECTION_REASON } from "./memory/decay-review.ts";
17
17
  import { createMemoryMcp } from "./mcp-memory.ts";
18
18
  import { safeProfileLockMessage } from "./memory/profile-lock-diagnostic.ts";
19
19
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-journal-format.ts";
@@ -31,7 +31,7 @@ import { originLine, originRecheck } from "./memory/candidate-origin.ts";
31
31
  import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
32
32
  import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
33
33
  import { memoryProjectKey } from "./memory/project.ts";
34
- import { CandidateStore, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
34
+ import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
35
35
  import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
36
36
  import { openCuratedForRead } from "./memory/curated-read.ts";
37
37
  import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
@@ -199,7 +199,7 @@ function assertAgentAdministrative(value: unknown, policy: ReturnType<typeof con
199
199
  if (cliAttribution()?.actor !== "agent") return;
200
200
  let plain: unknown;
201
201
  try { plain = JSON.parse(JSON.stringify(value)); } catch { throw Error("Memory operation unavailable or refused; no partial result is shown."); }
202
- if (!policy.screenStandalone(plain)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
202
+ if (!policy.screenStandalone(plain)) throw new ReadPolicyWithheld();
203
203
  }
204
204
  function shardStatePresent(): boolean {
205
205
  try { lstatSync(join(memoryHome(), "shards.json")); return true; }
@@ -277,7 +277,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
277
277
  cause = "setup_receipt_orca_profile"; next = "The receipt was written from an Orca Claude profile; rerun setup from that Orca profile."; partial = false;
278
278
  } else if (text === "setup receipt is stale: its managed entries were replaced at another amem install root; rerun with --adopt-current to adopt the current wiring") {
279
279
  cause = "setup_receipt_stale"; next = "The receipt's managed entries were replaced at another amem install root outside setup; rerun with --apply --adopt-current to keep the receipt aside and adopt the current wiring, which --undo then restores."; partial = false;
280
- } else if (/^setup-owned .+ changed; refusing to overwrite it$/.test(text) || text === "Pi amem-session extension already exists and is not this setup's file"
280
+ } else if (/^setup-owned .+ changed; refusing to overwrite it$/.test(text) || text === "Pi amem-session extension already exists and is not this setup's file; inspect it, move your changes to another extension file or remove it, then rerun setup"
281
281
  || text === "previous-runtime hook settings are customized; review hook configuration before retrying setup"
282
282
  || /^setup receipt (?:does not match this installation|target mismatch|invalid|directory ownership invalid)$/.test(text)) {
283
283
  cause = "setup_ownership_conflict"; next = "Review the managed entries and saved setup receipt before retrying; keep unrelated configuration intact."; partial = false;
@@ -299,6 +299,20 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
299
299
  return safe;
300
300
  }
301
301
 
302
+ /** Some commands write files despite having no mutates entry; preserve their existing effectful error/receipt treatment. */
303
+ function markedReadOnly(parsed: ReturnType<typeof parseCommand>): boolean {
304
+ return parsed.definition.mutates === undefined && parsed.path[0] !== "setup"
305
+ && !(parsed.path[0] === "eval" && parsed.path[1] === "audit" && parsed.path[2] === "sample")
306
+ && !(parsed.path[0] === "project" && parsed.path[1] === "export");
307
+ }
308
+
309
+ class ReadPolicyWithheld extends Error {
310
+ constructor() { super("Memory read withheld [cause: policy_withheld]; no partial result is shown. Ask the person to check the configured policy."); }
311
+ }
312
+
313
+ /** #326: a marked score read the policy refuses names its cause class and where to check it, never the matched value. */
314
+ export const AUDIT_SCORE_REFUSED = "Audit score refused [cause: policy_denied]: the configured policy denies a value in the rendered score (its seed, as-of or project digest); no partial result is shown. Next step: check the policy (amem.config.json in the memory home, narrowed by the repository's .amem/config) against those values, or sample again with a different --seed.";
315
+
302
316
  export async function runCli(argv: readonly string[], context: CliContext = {}): Promise<string> {
303
317
  // Native capture and the MCP server retain their existing surfaces and attribution.
304
318
  if (argv[0] === "hook" || argv[0] === "ingest" || argv.length === 1 && argv[0] === "mcp") return runCliCommand(argv, context);
@@ -309,7 +323,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
309
323
  const output = await runCliCommand(argv, context);
310
324
  if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
311
325
  const parsed = parseCommand(argv);
312
- if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup") {
326
+ // Audit outputs and review targets are screened whole for marked reads.
327
+ if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup" || parsed.path[0] === "eval" && parsed.path[1] === "audit" || parsed.path[0] === "review" && parsed.path[1] === "targets") {
313
328
  let receipt: unknown = output;
314
329
  // Import receipts contain fixed counters named `pii`; they are not row privacy flags.
315
330
  // Screen the complete rendered receipt, including every key and value, as text.
@@ -317,7 +332,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
317
332
  try { receipt = JSON.parse(output); } catch { /* human receipts remain strings */ }
318
333
  }
319
334
  try { assertAgentAdministrative(receipt, configuredPolicy(parsed.path[0] === "setup" ? memoryHome({ ...process.env, ...env }) : memoryHome(), context.cwd ?? process.cwd())); }
320
- catch {
335
+ catch (error) {
336
+ if (markedReadOnly(parsed) && !(error instanceof ReadPolicyWithheld)) throw error;
337
+ // A score leaves nothing behind, so an output the policy refuses refuses the read; a sample has written its private sheet already, and withholding
338
+ // the receipt reports exactly that without naming the file.
339
+ if (parsed.path[0] === "eval" && parsed.path[2] === "score") throw Error(AUDIT_SCORE_REFUSED);
340
+ if (markedReadOnly(parsed)) throw new ReadPolicyWithheld();
321
341
  // The command returned successfully: withholding its receipt cannot undo its effects.
322
342
  const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
323
343
  return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
@@ -335,10 +355,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
335
355
  const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
336
356
  }
337
357
  // Data-free errors (decided before any store or file is opened) keep their own message.
338
- if (marked && error instanceof AgentUsageError) throw error;
358
+ if (marked && (error instanceof AgentUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
339
359
  if (marked && error instanceof RemoteRealmRefusal) throw error;
340
360
  // The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
341
361
  if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
362
+ // #326: the audit score refusal is a fixed cause-class string that names no matched value.
363
+ if (marked && error instanceof Error && error.message === AUDIT_SCORE_REFUSED) throw new Error(AUDIT_SCORE_REFUSED);
342
364
  // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
343
365
  if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
344
366
  const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
@@ -349,6 +371,11 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
349
371
  if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
350
372
  const setupError = parsed && markedSetupApplyError(parsed, error);
351
373
  if (setupError) throw setupError;
374
+ if (parsed && markedReadOnly(parsed)) {
375
+ if (error instanceof ReadPolicyWithheld) throw error;
376
+ if (error instanceof Error && error.message === "Memory operation unavailable or refused; no partial result is shown.") throw Error(error.message);
377
+ throw new AgentReadFailure();
378
+ }
352
379
  }
353
380
  // Marked administrative failures must not reveal a target's private state or native errors.
354
381
  if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
@@ -707,11 +734,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
707
734
  if (sub === "decay") {
708
735
  const applying = options["--apply"] === true && options["--confirm"] === true;
709
736
  if (options["--confirm"] === true && options["--apply"] !== true) throw new Error("decay --confirm requires --apply");
710
- const { decayPreview, applyDecay, readDecayCounters, DECAY_DEFAULT_DAYS, assertExactDecayForget } = await import("./memory/decay-review.ts");
737
+ const { decayPreview, applyDecay, readDecayCounters, DECAY_DEFAULT_DAYS, assertExactDecayForget, unusedInjectionTargets } = await import("./memory/decay-review.ts");
711
738
  const project = boundProject(), base = memoryHome(), aliases = aliasedKeys(base, project);
712
739
  const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
713
740
  try {
714
741
  const assertCurrent = commandBinding(store.profile.home, project);
742
+ if (options["--propose"] === true) {
743
+ if (options["--apply"] || options["--confirm"] || options["--forget"] || options["--days"] || parsed.positionals.length) throw Error("decay --propose cannot be combined with apply, age or ids; run it alone to queue candidates");
744
+ const { readReviewSnapshot, REVIEW_DEFAULTS } = await import("./memory/review-targets.ts");
745
+ const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
746
+ const candidates = new CandidateStore({ memoryDir: base, reconcile: { canonical: project, aliases } });
747
+ try {
748
+ const targets = unusedInjectionTargets(store, project, readReviewSnapshot(base, [project, ...aliases]), { now: store.readNow(), days: settings?.unused_days ?? REVIEW_DEFAULTS.unused_days, threshold: settings?.unused_rendered ?? REVIEW_DEFAULTS.unused_rendered, aliases, screen: view => policyOf().screenStandalone(view), exclude: target => candidates.get(candidateInputId({ project, kind: "decay", target, reason: UNUSED_INJECTION_REASON }), project) !== undefined });
749
+ assertCurrent();
750
+ for (const entry of targets) candidates.put({ project, kind: "decay", target: entry.target, reason: UNUSED_INJECTION_REASON }, "public");
751
+ const receipt = { unusedInjection: targets.length };
752
+ return options["--json"] ? JSON.stringify(receipt) : `queued ${targets.length} unused-injection decay candidates; review with amem review list`;
753
+ } finally { candidates.close(); }
754
+ }
715
755
  const selected = parsed.positionals.length ? parsed.positionals : undefined;
716
756
  if (options["--days"] !== undefined && !/^[1-9][0-9]*$/.test(String(options["--days"]))) throw new Error("decay days must be a positive decimal integer");
717
757
  const days = options["--days"] === undefined ? DECAY_DEFAULT_DAYS : Number(options["--days"]);
@@ -756,6 +796,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
756
796
  } finally { store.close(); }
757
797
  }
758
798
  if (review) {
799
+ if (sub === "targets") {
800
+ const { reviewTargets, readReviewSnapshot, reviewUse, noRecentReview, REVIEW_DEFAULTS } = await import("./memory/review-targets.ts");
801
+ const base = memoryHome(), bound = boundProject(), project = options["--project"] === undefined ? bound : resolveAlias(base, String(options["--project"]));
802
+ if (project !== bound) throw Error("review targets can screen only the current project's policy; run it from that project's checkout");
803
+ const rawLimit = options["--limit"] === undefined ? "50" : String(options["--limit"]);
804
+ if (!/^[1-9][0-9]*$/.test(rawLimit) || Number(rawLimit) > 500) throw Error("review targets --limit must be from 1 to 500; pass a limit in that range");
805
+ const aliases = aliasedKeys(base, project), snapshot = readReviewSnapshot(base, [project, ...aliases]);
806
+ const store = openCuratedForRead(base, project);
807
+ if (!store) return options["--json"] ? "[]" : "no review targets";
808
+ try {
809
+ const policy = policyOf(), root = boundRepoRoot(policyCwd, base, project), stale = createRecallStalenessProbe({ cwd: root ?? policyCwd, rootConfirmed: root !== undefined, policy: () => policy });
810
+ const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
811
+ const rows = store.withDeferredPromotions(() => store.list({ project, limit: 5000 })).filter(row => actor !== "agent" || policy.screenStandalone(row));
812
+ const result = reviewTargets(rows, { now: store.readNow(), recheckDays: settings?.recheck_days ?? REVIEW_DEFAULTS.recheck_days, limit: Number(rawLimit), stale,
813
+ use: row => reviewUse(snapshot, [project, ...aliases], row.id), eligibleForRecheck: (row, cutoff) => noRecentReview(snapshot, row.id, cutoff) });
814
+ return options["--json"] ? JSON.stringify(result, null, 2) : result.length ? result.map(row => `${row.id} ${row.reason} ${row.ageDays}d rendered ${row.counts.rendered ?? "unknown"} delivered ${row.counts.delivered ?? "unknown"} cited ${row.counts.cited ?? "unknown"}`).join("\n") : "no review targets";
815
+ } finally { store.close(); }
816
+ }
759
817
  const id = parsed.positionals[0];
760
818
  if (sub !== "list" && sub !== "walk" && (!id || !/^[a-f0-9]{64}$/.test(id))) throw new Error(`review ${sub} requires a full 64-character candidate id`);
761
819
  if (sub === "walk" && !(context.stdinTTY ?? process.stdin.isTTY)) throw Error("review walk requires a terminal on stdin; stdout must be a terminal too");
@@ -824,7 +882,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
824
882
  const candidate = candidates.get(id!, project);
825
883
  if (!candidate || !candidatePermitted(candidate)) throw new Error("candidate unavailable");
826
884
  if (candidate.status !== "pending") throw new Error(`candidate is ${candidate.status}, not pending`);
827
- if (decision === "accept" && candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
885
+ if (decision === "accept" && candidate.input.kind === "decay" && candidate.input.reason !== UNUSED_INJECTION_REASON) throw new Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
828
886
  if (decision === "accept" && candidate.input.kind === "model-answer") throw new Error("model answers cannot be accepted; author an independent note with amem note add");
829
887
  if (options["--confirm"] !== true) {
830
888
  const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
@@ -919,7 +977,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
919
977
  const candidate = candidates.get(id!, project);
920
978
  if (!candidate) throw new Error("candidate unavailable");
921
979
  if (options["--kind"] !== undefined && candidate.input.kind !== options["--kind"]) throw new Error("candidate kind does not match --kind");
922
- if (candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
980
+ if (candidate.input.kind === "decay" && candidate.input.reason !== UNUSED_INJECTION_REASON) throw new Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
923
981
  const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
924
982
  try {
925
983
  const assertCurrent = commandBinding(store.profile.home, project);
@@ -931,6 +989,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
931
989
  // #368: a Record candidate quotes capture rows, so acceptance point-reads exactly those turns of its shard,
932
990
  // rather than the brief window a candidate can outlive.
933
991
  recordSource: recordSourceCheck(recordCaptureLookup(realPath(store.profile.home), policyCwd)),
992
+ unusedEligible: view => {
993
+ const { readReviewSnapshot, REVIEW_DEFAULTS } = require("./memory/review-targets.ts") as typeof import("./memory/review-targets.ts");
994
+ const { unusedInjectionTargets } = require("./memory/decay-review.ts") as typeof import("./memory/decay-review.ts");
995
+ const settings = loadAmemConfig(store.profile.home, repoConfigRoot(policyCwd)).config.review;
996
+ return unusedInjectionTargets(store, project, readReviewSnapshot(store.profile.home, [project, ...aliases]), { now: store.readNow(), days: settings?.unused_days ?? REVIEW_DEFAULTS.unused_days, threshold: settings?.unused_rendered ?? REVIEW_DEFAULTS.unused_rendered, aliases, id: view.id, screen: row => policyOf().screenStandalone(row) }).some(entry => entry.target.id === view.id);
997
+ },
934
998
  });
935
999
  return options["--json"] ? JSON.stringify(result, null, 2) : `accepted candidate ${id} as ${candidate.input.kind === "promotion" ? "promoted" : "ordinary"} note ${result.noteId}`;
936
1000
  } finally { store.close(); }
@@ -950,6 +1014,40 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
950
1014
  }
951
1015
  if (sub === "eval") {
952
1016
  // F13: read-only. A set with entries is scored against a throwaway store seeded with them (touches no memory home); one without scores the bound project's real entries.
1017
+ if (parsed.path[1] === "audit") {
1018
+ // #326: a private local sheet plus a content-free score. Judging happens outside amem, so nothing on this path calls a model or the network.
1019
+ const audit = await import("./memory/eval-audit.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
1020
+ if (parsed.path[2] === "sample") {
1021
+ const n = options["--n"] === undefined ? 40 : Number(options["--n"]), seed = typeof options["--seed"] === "string" ? options["--seed"] : "";
1022
+ if (!Number.isInteger(n) || n < 1 || n > MAX_AUDIT_NOTES) throw new Error(`--n must be an integer from 1 to ${MAX_AUDIT_NOTES}`);
1023
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(seed)) throw new Error("--seed is required: 1 to 64 letters, digits, '.', '_' or '-', so the same seed and store draw the same sample");
1024
+ // Anchors are checked against this cwd's work tree, so another project's key would silently check them against the wrong repository: the audit only
1025
+ // samples the project bound here or one of its aliases, and names the checkout to run it from.
1026
+ const cwd = context.cwd ?? process.cwd(), home = memoryHome(), bound = boundProject();
1027
+ const project = options["--project"] === undefined ? bound : resolveAlias(home, String(options["--project"]));
1028
+ if (project !== bound && !aliasedKeys(home, bound).includes(project)) throw new Error(`the audit checks note anchors against the git work tree of ${cwd}, so it samples only the project bound there (${bound}); run \`amem eval audit sample\` from that project's checkout to audit that project`);
1029
+ const root = audit.auditRoot(cwd);
1030
+ // The age buckets the draw stratifies by are measured at one explicit instant, recorded in the sheet: the same seed, store and as-of draw the same sample.
1031
+ const asOf = options["--as-of"] === undefined ? Date.now() : audit.auditAsOf(String(options["--as-of"]), Date.now());
1032
+ const store = curatedStore(project, { deferPromotions: true });
1033
+ let sheet;
1034
+ // The configured policy screens each frame member before the sheet's first write, for a person and an agent-marked session alike (like `project export`).
1035
+ // It screens the complete view, not the fields the sheet copies: a denied pattern in `task`, `peer` or `source` is a denial of that note.
1036
+ // It is read once: the screen runs per frame member, and the policy reads the config files when it is built.
1037
+ const screen = policyOf();
1038
+ try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
1039
+ const out = typeof options["--out"] === "string" ? options["--out"] : join(memoryHome(), "eval", `audit-${project.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 80)}-${seed}.json`);
1040
+ const file = audit.writeAuditSheet(out, sheet);
1041
+ return options["--json"] === true ? JSON.stringify({ file, project: sheet.project, seed: sheet.seed, asOf: sheet.asOf, frame: sheet.frame, drawn: sheet.drawn, truncated: sheet.truncated, withheld: sheet.withheld }, null, 2) : audit.auditSheetText(sheet, file);
1042
+ }
1043
+ if (parsed.path[2] === "score") {
1044
+ const [sheet] = parsed.positionals;
1045
+ if (!sheet) throw new Error("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
1046
+ const score = audit.auditScore(audit.readAuditSheet(sheet));
1047
+ return options["--json"] === true ? JSON.stringify(score, null, 2) : audit.auditScoreText(score);
1048
+ }
1049
+ throw new Error("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
1050
+ }
953
1051
  const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
954
1052
  const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
955
1053
  const builtin = file === undefined ? undefined : builtinSet(file);
@@ -43,7 +43,14 @@ export const COMMANDS: Record<string, CommandDefinition> = {
43
43
  projects: { description: "List the project shards of this memory home (#15 D3)", options: { ...json, "--all": flag("Include forgotten projects (archived ones are always listed)") } },
44
44
  usage: { description: "Totals and the largest project shards", options: { ...json, "--limit": text("Largest shards to list (1..100)"), "--all": flag("Include forgotten projects") } },
45
45
  eval: { description: "Replay a local question set against ranked store.search and report recall@k and MRR (no model, no network; the built-in synthetic set without --set, `--set ko` for the built-in Korean one)", options: { ...json,
46
- "--set": { description: "`ko` (the built-in Korean set) or a question set file (amem.eval/v1); with entries it is self-contained, without them its ids name entries of this project", value: "path" }, "--k": text("Cutoffs, comma separated (default 1,5,10; each 1..100)") } },
46
+ "--set": { description: "`ko` (the built-in Korean set) or a question set file (amem.eval/v1); with entries it is self-contained, without them its ids name entries of this project", value: "path" }, "--k": text("Cutoffs, comma separated (default 1,5,10; each 1..100)") }, commands: {
47
+ audit: { description: "Audit whether stored notes are still right (#326): sample a private sheet, judge it outside amem, then score it (no model, no network)", options: json, commands: {
48
+ sample: { description: "Draw a seeded, stratified sample of this project's curated notes into a private 0600 sheet with anchor status and empty judge columns", options: { ...json,
49
+ "--project": text("The project key to audit (default: this directory's project)"), "--n": text("Notes to draw (1..200, default 40)"), "--seed": text("Required: 1..64 letters, digits, '.', '_' or '-' - the same seed and store draw the same sample"),
50
+ "--as-of": text("The instant the notes' ages are measured at (canonical UTC date or timestamp; default: now), recorded in the sheet so the same seed and as-of draw the same sample"),
51
+ "--out": { description: "Sheet path (default: this home's eval/ directory); never overwritten, always 0600", value: "path" } } },
52
+ score: { description: "Score a filled sheet into content-free counts, per kind/age/anchor, and Cohen's kappa; refuses any leak of note text or a path", options: json, args: [{ name: "sheet" }] },
53
+ } } } },
47
54
  spool: { description: "Off-hook hook-spool maintenance (#217)", options: json, commands: {
48
55
  replay: { description: "Preview (read-only, no record bodies) or apply a replay of orphaned or parked hook records; --apply takes the saved preview", mutates: "apply", options: { ...json,
49
56
  "--source": { description: "Absolute path of a private parked directory to read instead of this home's hook spool", value: "path" },
@@ -103,6 +110,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
103
110
  take: { description: "Take a goal lease", options: { "--force": flag("Override the prior lease") }, args: [{ name: "id" }], mutates: true },
104
111
  } },
105
112
  review: { description: "Review machine-local non-evidentiary candidates", options: json, defaultCommand: "list", commands: {
113
+ targets: { description: "List notes to re-check in deterministic priority order", options: { ...json, "--project": text("Current project or alias"), "--limit": text("Maximum targets (1..500, default 50)") } },
106
114
  list: { description: "List review candidates", options: {
107
115
  "--status": { description: "Candidate status", value: ["pending", "accepting", "accepted", "rejected", "all"] },
108
116
  "--kind": { description: "Candidate kind", value: ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] }, "--limit": text("Maximum candidates (1..500)"),
@@ -114,7 +122,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
114
122
  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"] } } },
115
123
  } },
116
124
  decay: { description: "Preview old live long-term notes unprotected by open goals; apply only with --apply --confirm", mutates: "apply", options: {
117
- ...json, "--days": text("Age in whole days (default 90)"), "--apply": flag("Preview exact revisions; combine with --confirm to apply"), "--confirm": flag("Apply the exact revision preview with --apply"), "--forget": flag("Explicitly forget instead of demoting; confirmation names this action") }, args: [{ name: "id", variadic: true }] },
125
+ ...json, "--days": text("Age in whole days (default 90)"), "--propose": flag("Queue unused-injection candidates for review"), "--apply": flag("Preview exact revisions; combine with --confirm to apply"), "--confirm": flag("Apply the exact revision preview with --apply"), "--forget": flag("Explicitly forget instead of demoting; confirmation names this action") }, args: [{ name: "id", variadic: true }] },
118
126
  migrate: { description: "Preview a generation migration; apply only with --apply, or deactivate it explicitly", mutates: "apply", options: {
119
127
  ...json, "--apply": flag("Apply the previewed migration"), "--dry-run": flag("Read-only migration receipt (default; kept as an alias)"), "--generation": text("Explicit 32-hex generation ID"),
120
128
  "--resume": flag("Resume the recorded migration"), "--deactivate": flag("Select shared v1 without deleting a generation"),
package/src/index.ts CHANGED
@@ -60,6 +60,7 @@ export * from "./memory/recall-staleness.ts";
60
60
  export * from "./memory/intent-brief.ts";
61
61
  export * from "./memory/plan-guard.ts";
62
62
  export * from "./memory/use-telemetry.ts";
63
+ export * from "./memory/review-targets.ts";
63
64
  export * from "./memory/consolidate.ts";
64
65
  export * from "./memory/record-candidates.ts";
65
66
  export * from "./memory/consolidation-clusters.ts";
package/src/ingest.ts CHANGED
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
5
5
  import { dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { CaptureStore, type CaptureInput } from "./memory/capture.ts";
7
7
  import { memoryHome } from "./memory/home.ts";
8
+ import { inspectNativeRoot, nativeRoots } from "./memory/native-roots.ts";
8
9
  import { canonicalPath, processLiveness, processSignature, realPath } from "./memory/platform.ts";
9
10
  import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
10
11
  import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
@@ -141,10 +142,7 @@ function lease(file: string): { position: Position; save(value: Position): void;
141
142
  /** Native roots only. Discovery never follows a directory symlink or enters an unbounded tree. */
142
143
  function discover(kind: IngestKind): { files: string[]; bounded: boolean; unavailable: boolean } {
143
144
  if (kind === "qwen") return discoverQwen();
144
- const root = kind === "codex" ? process.env.CODEX_HOME?.trim() || join(homedir(), ".codex")
145
- : kind === "kimi" ? process.env.KIMI_CODE_HOME?.trim() || join(homedir(), ".kimi-code")
146
- : process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), ".pi", "agent");
147
- const roots = [join(root, "sessions"), ...(kind === "codex" ? [join(root, "archived_sessions")] : [])];
145
+ const roots = nativeRoots(kind), seen = new Set<string>();
148
146
  const files: string[] = []; let visited = 0, bounded = false, rootsRead = 0;
149
147
  const walk = (folder: string, depth: number) => {
150
148
  if (depth > MAX_DEPTH) { bounded = true; return; }
@@ -161,7 +159,11 @@ function discover(kind: IngestKind): { files: string[]; bounded: boolean; unavai
161
159
  }
162
160
  } finally { dir.closeSync(); }
163
161
  };
164
- for (const folder of roots) walk(folder, 0);
162
+ for (const { folder } of roots) {
163
+ const root = inspectNativeRoot(folder);
164
+ if (root.state !== "ready" || seen.has(root.path)) continue;
165
+ seen.add(root.path); walk(root.path, 0);
166
+ }
165
167
  return { files: files.sort(), bounded, unavailable: rootsRead === 0 };
166
168
  }
167
169
 
@@ -27,6 +27,7 @@ export class ConsolidationReviewLimit extends Error {
27
27
  }
28
28
  }
29
29
  export const COUNTER_RETENTION = { count: 10_000, ageMs: 90 * 86400_000 } as const;
30
+ export const UNUSED_INJECTION_REASON = "Unused injection: frequent rendered or delivered notes have no reported citations in the review window.";
30
31
  export type CandidateVerdict = "public" | "private" | "pii" | "unknown";
31
32
  export interface CandidateTarget { id: string; revision: string }
32
33
  /** One capture `Record` row a candidate was derived from: the session hash, its row time and the hash of the stored line. */
@@ -73,6 +74,7 @@ export interface CandidateAcceptance {
73
74
  * prove the source, and accepting such a candidate refuses instead of writing memory from a row nobody verified.
74
75
  */
75
76
  recordSource?: (project: string, binding: RecordSourceBinding) => "present" | "changed" | "missing";
77
+ unusedEligible?: (view: View) => boolean;
76
78
  }
77
79
  export interface CandidateAcceptanceResult { candidateId: string; noteId: string; alreadyAccepted: boolean }
78
80
 
@@ -436,7 +438,7 @@ export class CandidateStore {
436
438
  if (candidate.status !== "pending") throw new Error("candidate is rejected or acceptance was interrupted; no automatic replay");
437
439
  const data = candidate.input;
438
440
  if (data.kind === "model-answer") throw Error("model answers cannot become curated memory; use amem note add to author an independent note");
439
- if (data.kind === "decay") throw new Error("decay candidates are listing-only; no automatic mutation is available");
441
+ if (data.kind === "decay") return this.acceptDecay(candidate, data, context);
440
442
  if (data.kind === "promotion") return this.acceptPromotion(candidate, data, context);
441
443
  if (data.kind === "consolidation") return this.acceptConsolidation(candidate, data, context);
442
444
  // #368: a Record-derived candidate quotes capture rows. Absent proof, or a row that moved since the queue, refuses
@@ -490,6 +492,20 @@ export class CandidateStore {
490
492
  if (!current || current.id !== target.id || candidateTargetRevision(current) !== target.revision) throw new Error("candidate target revision is stale");
491
493
  return context.store.withCurrentEntries([target.id], context.project, execute);
492
494
  }
495
+ private acceptDecay(candidate: Candidate, data: Extract<CandidateInput, { kind: "decay" }>, context: CandidateAcceptance): CandidateAcceptanceResult {
496
+ if (data.reason !== UNUSED_INJECTION_REASON || !context.unusedEligible) throw Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
497
+ return context.store.withCurrentEntries([data.target.id], context.project, () => {
498
+ const target = context.store.get(data.target.id, context.project);
499
+ if (!target || target.tier !== "long" || target.kind === "preference" || target.supersededBy || candidateTargetRevision(target) !== data.target.revision || !context.unusedEligible!(target)) throw Error("decay candidate is no longer eligible; run amem decay --propose again");
500
+ const note: NoteInput = { op: "note", project: target.project, scope: target.scope, tier: target.tier, kind: target.kind, peer: target.peer, source: target.source as NoteInput["source"], about: target.about, text: target.text };
501
+ if (!context.policy(structuredClone(candidate), structuredClone(target), note)) throw Error("decay candidate refused by current policy; review the policy before accepting");
502
+ const replay = this.beginAcceptance(candidate.id, context.project); if (replay) return { candidateId: candidate.id, noteId: replay, alreadyAccepted: true };
503
+ // ponytail: the sidecar receipt and append are not atomic; interrupted acceptance requires inspection, not automatic replay.
504
+ if (!context.store.demote(target.id, context.actor, context.project)) throw Error("decay demotion outcome unavailable; inspect the accepting candidate");
505
+ this.db.query("UPDATE candidates SET status = 'accepted', note_id = ? WHERE id = ? AND project IN (SELECT value FROM json_each(?))").run(target.id, candidate.id, this.scope(context.project));
506
+ return { candidateId: candidate.id, noteId: target.id, alreadyAccepted: false };
507
+ });
508
+ }
493
509
  private acceptConsolidation(candidate: Candidate, data: Extract<CandidateInput, { kind: "consolidation" }>, context: CandidateAcceptance): CandidateAcceptanceResult {
494
510
  if (typeof context.policyVersion !== "function") throw Error("consolidation requires a policy revision guard");
495
511
  const boundStore = context.store, boundProject = context.project, boundActor = context.actor, boundPolicy = context.policy;
@@ -176,7 +176,8 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
176
176
  case "show": {
177
177
  const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
178
178
  const id = rest[0] ?? fail(`usage: ${names.memory} show <id>`), shown = recallShow(store, project, id, { person: opts.person, history, asOf });
179
- if (!shown.ids.length) return fail(`no memory entry ${id} (${names.memory} list shows the ids)`);
179
+ if (!shown.ids.length) return cliAttribution()?.actor === "agent" ? fail("Memory operation unavailable or refused; no partial result is shown.") : fail(`no memory entry ${id} (${names.memory} list shows the ids)`);
180
+ if (cliAttribution()?.actor === "agent" && (!shown.entry || !opts.readable([shown.entry]).some(view => view.id === shown.entry!.id))) fail("Memory operation unavailable or refused; no partial result is shown.");
180
181
  if (shown.state) {
181
182
  const rows = opts.readable(shown.state.views), ids = new Set(rows.map(view => view.id)); ready(rows);
182
183
  const state = { ...recallForViews(shown.state, rows), views: rows.map(decorated), relations: shown.state.relations.filter(edge => ids.has(edge.from) && ids.has(edge.to)) };
@@ -17,10 +17,11 @@ export const CONFIG_FILE = "amem.config.json";
17
17
  export const REPO_CONFIG_DIR = ".amem";
18
18
  export const REPO_CONFIG_FILE = "config";
19
19
  const MAX_CONFIG_BYTES = 64 * 1024;
20
- const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes"] as const;
20
+ const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes", "review"] as const;
21
21
  const REPO_KEYS = ["denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "records"] as const;
22
22
 
23
23
  export interface AmemConfig {
24
+ review?: { recheck_days?: number; unused_rendered?: number; unused_days?: number };
24
25
  /** Static SessionStart record instruction; absent means enabled. Repository false only narrows. */
25
26
  records?: boolean;
26
27
  /** The memory home, when the file moves it (a pointer file: see `configuredHome`). `AMEM_HOME` still wins. Machine file only. */
@@ -111,6 +112,16 @@ function parseFile(raw: unknown, label: string, keys: readonly string[]): Partia
111
112
  if (capMb !== undefined) out.capture.capMb = capMb;
112
113
  if (retentionDays !== undefined) out.capture.retentionDays = retentionDays;
113
114
  }
115
+ if (body.review !== undefined) {
116
+ if (!body.review || typeof body.review !== "object" || Array.isArray(body.review) || Object.keys(body.review).some(key => !["recheck_days", "unused_rendered", "unused_days"].includes(key))) return fail(label, "review takes only recheck_days, unused_rendered and unused_days");
117
+ const rawReview = body.review as Record<string, unknown>;
118
+ const review: NonNullable<AmemConfig["review"]> = {};
119
+ for (const key of ["recheck_days", "unused_rendered", "unused_days"] as const) {
120
+ const value = countOf(rawReview[key], `review.${key}`, label, key === "unused_rendered" ? 1_000_000 : key === "unused_days" ? 90 : 36_500);
121
+ if (value !== undefined) review[key] = value;
122
+ }
123
+ out.review = review;
124
+ }
114
125
  return out;
115
126
  }
116
127
 
@@ -163,6 +174,7 @@ export function loadAmemConfig(base: string, repoRoot?: string): LoadedConfig {
163
174
  if (denyPaths.length > 64) fail(machinePath, "denyPaths and the repository's denyPaths name more than 64 entries together");
164
175
  if (piiPatterns.length > 64) fail(machinePath, "piiPatterns and the repository's piiPatterns name more than 64 entries together");
165
176
  const config: AmemConfig = { denyPaths, piiPatterns, capture: { ...(machine?.capture ?? {}) } };
177
+ if (machine?.review !== undefined) config.review = { ...machine.review };
166
178
  if (machine?.home !== undefined) config.home = machine.home;
167
179
  if (machine?.privateRemotes?.length) config.privateRemotes = machine.privateRemotes;
168
180
  if (machine?.records !== undefined || repo?.records !== undefined) config.records = machine?.records !== false && repo?.records !== false;
@@ -3,7 +3,27 @@ import { lstatSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { hashJSON } from "./generation.ts";
5
5
  import { candidateTargetRevision, type CandidateTarget, type Counter } from "./candidates.ts";
6
+ export { UNUSED_INJECTION_REASON } from "./candidates.ts";
6
7
  import { MemoryStore, type View } from "./store.ts";
8
+ import { reviewUse, type ReviewSnapshot } from "./review-targets.ts";
9
+
10
+ /** Select proposals only; caller must explicitly queue and accept them. */
11
+ export function unusedInjectionTargets(store: MemoryStore, project: string, snapshot: ReviewSnapshot, options: { now: number; days: number; threshold: number; aliases?: readonly string[]; screen?: (view: View) => boolean; id?: string; exclude?: (target: CandidateTarget) => boolean }): DecayEntry[] {
12
+ const goals = store.goals(project).filter(goal => ["open", "active", "blocked"].includes(goal.state));
13
+ const tasks = new Set(goals.flatMap(goal => goal.links.map(link => link.task))), goalNodes = new Set(goals.map(goal => `goal:${goal.id}`));
14
+ const since = options.now - options.days * 86400_000;
15
+ return store.withDeferredPromotions(() => {
16
+ const rows = options.id ? [store.get(options.id, project)].filter((view): view is View => view !== undefined) : store.list({ project, tier: "long", limit: DECAY_SCAN_LIMIT + 1 });
17
+ if (rows.length > DECAY_SCAN_LIMIT) throw Error("unused-injection scan exceeds 5000 notes; narrow the project before retrying");
18
+ return rows.flatMap(view => {
19
+ if (view.project !== project || view.kind === "preference" || view.supersededBy || view.task && tasks.has(view.task) || view.about.some(node => goalNodes.has(node) || node.startsWith("task:") && tasks.has(node.slice(5))) || options.screen && !options.screen(view)) return [];
20
+ const counts = reviewUse(snapshot, [project, ...options.aliases ?? []], view.id, since);
21
+ if (counts.delivered === null || counts.cited === null || counts.cited !== 0 || Math.max(counts.rendered ?? 0, counts.delivered) < options.threshold) return [];
22
+ const target = { id: view.id, revision: candidateTargetRevision(view) };
23
+ return options.exclude?.(target) ? [] : [{ target, view }];
24
+ }).slice(0, DECAY_PREVIEW_LIMIT);
25
+ });
26
+ }
7
27
 
8
28
  export const DECAY_DEFAULT_DAYS = 90, DECAY_PREVIEW_LIMIT = 64, DECAY_SCAN_LIMIT = 5000;
9
29
  export interface DecayEntry { target: CandidateTarget; view: View }