@staix/agent-mem 0.30.0 → 0.32.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.
@@ -1,5 +1,6 @@
1
1
  import { HOOK_EVENTS } from "./hook-contract.ts";
2
2
  import { GOAL_STATES, KINDS } from "./memory/store.ts";
3
+ import { wrapReport } from "./memory/style.ts";
3
4
 
4
5
  export interface OptionDefinition { description: string; value?: "text" | "path" | readonly string[] }
5
6
  export interface ArgumentDefinition { name: string; values?: readonly string[]; path?: boolean; variadic?: boolean }
@@ -21,7 +22,7 @@ const policy = { "--policy-free": flag("Accepted and ignored: the configured pri
21
22
  const filters = { ...json, "--tier": { description: "Memory tier", value: ["short", "long"] } as OptionDefinition,
22
23
  "--kind": { description: "Note kind", value: KINDS }, "--peer": text("Author peer"), "--machine": text("Machine ID"),
23
24
  "--since": text("ISO date or time"), "--limit": text("Maximum results") };
24
- export const GLOBAL_OPTIONS = { "--help": flag("Show help") };
25
+ export const GLOBAL_OPTIONS = { "--help": flag("Show help"), "--color": { description: "Color output: auto, always or never", value: ["auto", "always", "never"] } as OptionDefinition, "--ascii": flag("Use ASCII markers") };
25
26
  export const ROOT_OPTIONS = { "--version": flag("Show version"), ...json };
26
27
  export const COMMANDS: Record<string, CommandDefinition> = {
27
28
  consolidate: { description: "Queue deterministic project-local consolidation candidates; curated notes change only after explicit acceptance", mutates: true, options: { ...json, "--project": text("The current project's key; another project is refused (run from its directory)") } },
@@ -43,7 +44,14 @@ export const COMMANDS: Record<string, CommandDefinition> = {
43
44
  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
45
  usage: { description: "Totals and the largest project shards", options: { ...json, "--limit": text("Largest shards to list (1..100)"), "--all": flag("Include forgotten projects") } },
45
46
  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)") } },
47
+ "--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: {
48
+ 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: {
49
+ 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,
50
+ "--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"),
51
+ "--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"),
52
+ "--out": { description: "Sheet path (default: this home's eval/ directory); never overwritten, always 0600", value: "path" } } },
53
+ 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" }] },
54
+ } } } },
47
55
  spool: { description: "Off-hook hook-spool maintenance (#217)", options: json, commands: {
48
56
  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
57
  "--source": { description: "Absolute path of a private parked directory to read instead of this home's hook spool", value: "path" },
@@ -103,6 +111,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
103
111
  take: { description: "Take a goal lease", options: { "--force": flag("Override the prior lease") }, args: [{ name: "id" }], mutates: true },
104
112
  } },
105
113
  review: { description: "Review machine-local non-evidentiary candidates", options: json, defaultCommand: "list", commands: {
114
+ 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
115
  list: { description: "List review candidates", options: {
107
116
  "--status": { description: "Candidate status", value: ["pending", "accepting", "accepted", "rejected", "all"] },
108
117
  "--kind": { description: "Candidate kind", value: ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] }, "--limit": text("Maximum candidates (1..500)"),
@@ -114,7 +123,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
114
123
  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
124
  } },
116
125
  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 }] },
126
+ ...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
127
  migrate: { description: "Preview a generation migration; apply only with --apply, or deactivate it explicitly", mutates: "apply", options: {
119
128
  ...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
129
  "--resume": flag("Resume the recorded migration"), "--deactivate": flag("Select shared v1 without deleting a generation"),
@@ -169,6 +178,7 @@ export function completionDefinitions(): CompletionDefinition[] {
169
178
  walk(COMMANDS, [], GLOBAL_OPTIONS); return rows;
170
179
  }
171
180
  export interface ParsedCommand { path: string[]; definition: CommandDefinition; options: Record<string, string | boolean>; positionals: string[]; rawArgs: string[] }
181
+ export class CommandUsageError extends Error { readonly exitCode = 2; }
172
182
 
173
183
  /** Pure validation, shared definitions with help/completion; no store, files or network. */
174
184
  export function parseCommand(argv: readonly string[]): ParsedCommand {
@@ -184,16 +194,16 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
184
194
  const token = tokens[i]!;
185
195
  if (token.startsWith("--")) {
186
196
  const option = available[token];
187
- if (!option) throw new Error(`unknown option ${token}`);
197
+ if (!option) throw new CommandUsageError(`unknown option ${token}`);
188
198
  if (option.value !== undefined) {
189
199
  const value = tokens[++i];
190
- if (value === undefined || value.startsWith("--")) throw new Error(`${token} needs a value`);
191
- if (Array.isArray(option.value) && !option.value.includes(value)) throw new Error(`${token} takes ${option.value.join(" or ")}`);
200
+ if (value === undefined || value.startsWith("--")) throw new CommandUsageError(`${token} needs a value`);
201
+ if (Array.isArray(option.value) && !option.value.includes(value)) throw new CommandUsageError(`${token} takes ${option.value.join(" or ")}`);
192
202
  options[token] = value;
193
203
  } else options[token] = true;
194
204
  } else if (definition.commands) {
195
205
  const child: CommandDefinition | undefined = Object.hasOwn(definition.commands, token) ? definition.commands[token] : undefined;
196
- if (!child) throw new Error(`unknown command ${[...path, token].join(" ")}`);
206
+ if (!child) throw new CommandUsageError(`unknown command ${[...path, token].join(" ")}`);
197
207
  commandIndexes.add(i);
198
208
  definition = { ...definition, ...child }; path.push(token);
199
209
  // Child metadata inherits policy, but its command children belong only to that child.
@@ -208,14 +218,19 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
208
218
  if (definition.defaultCommand && definition.commands) {
209
219
  const name = definition.defaultCommand; definition = { ...definition, ...definition.commands[name]!, commands: undefined }; path.push(name);
210
220
  }
211
- if (positionals.length > (definition.args?.length ?? 0) && !definition.args?.at(-1)?.variadic) throw new Error(`too many arguments for ${path.join(" ")}`);
221
+ if (positionals.length > (definition.args?.length ?? 0) && !definition.args?.at(-1)?.variadic) throw new CommandUsageError(`too many arguments for ${path.join(" ")}`);
212
222
  for (let i = 0; i < positionals.length; i++) {
213
223
  const argument = definition.args?.[i];
214
- if (argument?.values && !argument.values.includes(positionals[i]!)) throw new Error(`${argument.name} takes ${argument.values.join(" or ")}`);
224
+ if (argument?.values && !argument.values.includes(positionals[i]!)) throw new CommandUsageError(`${argument.name} takes ${argument.values.join(" or ")}`);
215
225
  }
216
226
  const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
217
- for (const name of Object.keys(options)) if (!allowed[name]) throw new Error(`unknown option ${name} for ${path.join(" ")}`);
218
- const rawArgs = [...(path[0] === "goal" ? path.slice(1) : path), ...tokens.filter((arg, index) => arg !== "--policy-free" && !commandIndexes.has(index))];
227
+ for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
228
+ const outputOptionIndexes = new Set<number>();
229
+ for (let i = 0; i < tokens.length; i++) {
230
+ if (tokens[i] === "--color") { outputOptionIndexes.add(i); outputOptionIndexes.add(++i); }
231
+ else if (tokens[i] === "--ascii") outputOptionIndexes.add(i);
232
+ }
233
+ const rawArgs = [...(path[0] === "goal" ? path.slice(1) : path), ...tokens.filter((arg, index) => arg !== "--policy-free" && !commandIndexes.has(index) && !outputOptionIndexes.has(index))];
219
234
  return { path, definition, options, positionals, rawArgs };
220
235
  }
221
236
 
@@ -247,8 +262,16 @@ export function commandHelp(argv: readonly string[] = []): string {
247
262
  if (command && path[0] !== "help") {
248
263
  const lines = [`usage: amem ${usageRow(row)}`, "", command.description, "", "options:", ...described(Object.entries(row.options).map(([name, option]) => [optionLabel(name, option), option.description]))];
249
264
  if (command.commands) lines.push("", "commands:", ...described(Object.entries(command.commands).map(([name, child]) => [name, child.description])));
250
- return lines.join("\n");
265
+ return wrapReport(lines.join("\n"), 80);
251
266
  }
252
- return ["usage: amem <command> [options]", " [--help] [--version] [--json]", ...completionDefinitions().filter(row => row.path.length).map(row => ` ${usageRow(row)}`),
253
- "--policy-free: accepted and ignored; the configured privacy policy (amem.config.json in the memory home, narrowed by .amem/config) always applies.", "Agent-marked reads use the MCP privacy ceiling. Explicit apply/confirm flags do not require a terminal; review walk and the note editor remain interactive."].join("\n");
267
+ const overview = Object.entries(COMMANDS).map(([name, item]) => {
268
+ const description = item.description.split("\n")[0] ?? "";
269
+ const limit = 76 - name.length - Math.max(1, 20 - name.length);
270
+ const summary = description.length > limit ? `${description.slice(0, limit - 3).trimEnd()}...` : description;
271
+ return ` ${name.padEnd(20)} ${summary}`;
272
+ });
273
+ return ["usage: amem <command> [options]", " [--help] [--version] [--json]", "", "Commands:", ...overview,
274
+ "--policy-free is accepted and ignored; the configured privacy policy applies.",
275
+ "Agent-marked reads use the MCP privacy ceiling. Apply and confirm need no TTY;",
276
+ "review walk and the note editor remain interactive."].join("\n");
254
277
  }
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
 
package/src/mcp-memory.ts CHANGED
@@ -67,6 +67,10 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
67
67
  const currentPolicy = () => calls.getStore()?.policy ?? createStandalonePolicy(policyOptions());
68
68
  const policyRevisionForCall = () => { const revision = policyKey(policyOptions()), active = calls.getStore(); if (active && active.revision !== revision) return unavailable(); return revision; };
69
69
  const policy = currentPolicy(), release = registerReaderLease(base);
70
+ // #354: a work read's per-row and per-view screens take this call's own snapshot, so a policy tightened after the
71
+ // server started still reaches them; outside a call it stays the startup policy, exactly as before, and no policy
72
+ // is built per row.
73
+ const screenPolicy = () => calls.getStore()?.policy ?? policy;
70
74
  const closers: (() => void)[] = [release]; let closed = false;
71
75
  const close = () => { if (closed) return; closed = true; let failure: unknown; for (const closer of closers.reverse()) { try { closer(); } catch (error) { failure ??= error; } } if (failure) throw failure; };
72
76
  try {
@@ -87,7 +91,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
87
91
  return read.state === "ok" ? read.views : [];
88
92
  };
89
93
  const candidates = new CandidateStore({ memoryDir: base, ...(reconcile ? { reconcile } : {}) }); closers.push(() => candidates.close());
90
- const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
94
+ const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await screenPolicy().screen(row); guard(); return permitted; } }); closers.push(() => work.close());
91
95
  const fullGuard = () => {
92
96
  if (!permitted()) unavailable();
93
97
  if (closed) unavailable(); options.assertCurrent?.();
@@ -311,7 +315,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
311
315
  // Reduce complete views before policy: individually public appends can compose into private state.
312
316
  const result = await work.read(textOf(args, "list", true), true);
313
317
  const permitted: typeof result = [];
314
- for (const view of result) if (await policy.screen(view)) permitted.push(view);
318
+ for (const view of result) if (await screenPolicy().screen(view)) permitted.push(view);
315
319
  guard();
316
320
  return args.includeClosed === true ? permitted : permitted.filter(view => !view.closed).map(view => ({ ...view, items: view.items.filter(item => item.fields.status !== "done" && item.fields.status !== "dropped") }));
317
321
  },
@@ -381,6 +385,21 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
381
385
  throw error;
382
386
  }
383
387
  };
388
+ // #354: the work read runs the same per-call context as the read tools, so its per-row guard() takes the cheap
389
+ // path instead of verifying the whole placement once per row. It is not one of the #485 sampled read tools, so it
390
+ // takes neither the metrics sample nor the recall-source preparation; the checks around the call are the read
391
+ // wrapper's: one full guard at entry, one after, and a policy revision that moved during the call refuses.
392
+ exposed.amem_work_state_read = async args => {
393
+ fullGuard();
394
+ const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
395
+ if (policyKey(policyOptions()) !== revision) return unavailable();
396
+ return calls.run({ policy: snapshot, revision, configured }, async () => {
397
+ const value = await tools.amem_work_state_read(args);
398
+ fullGuard();
399
+ if (policyKey(policyOptions()) !== revision) return unavailable();
400
+ return value;
401
+ });
402
+ };
384
403
  return { tools: exposed, close, onEmitted };
385
404
  } catch (error) { close(); throw error; }
386
405
  }
@@ -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;
@@ -1,9 +1,9 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { indexFileName } from "./index-file.ts";
3
- import { chmodSync, existsSync, lstatSync, readdirSync } from "node:fs";
3
+ import { chmodSync, existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { memoryBase } from "./home.ts";
6
- import { effectiveAliases, readShardDescriptor, SHARDED_SCHEMA, SHARDED_V2_SCHEMA } from "./shard.ts";
6
+ import { effectiveAliases, readShardDescriptor, SHARD_SCHEMA, SHARDED_SCHEMA, SHARDED_V2_SCHEMA } from "./shard.ts";
7
7
  import { readProfileJSON, validGeneration } from "./generation.ts";
8
8
  import { captureShardStats, readCaptureConfig } from "./capture.ts";
9
9
  import { openShardStore } from "./store.ts";
@@ -102,6 +102,33 @@ export function walkShards(base: string): { hash: string; key: string; local: bo
102
102
  return out;
103
103
  }
104
104
 
105
+ /**
106
+ * #359: the catalog's project keys, in scanCatalog's order, without per-shard stats (no store open, no SQLite read, no directory sizing).
107
+ * It keeps scanCatalog's placement selection guard, so a home scanCatalog refuses is refused here too. For pickers; `amem projects`/usage keep scanCatalog.
108
+ */
109
+ export function catalogKeys(base: string): string[] {
110
+ capturedSelection(base);
111
+ // Unlike walkShards, a read failure other than absence throws: a picker cache must never keep an inventory a transient error cut short.
112
+ const projectsDir = join(base, "projects");
113
+ let hashes: string[];
114
+ try { hashes = readdirSync(projectsDir, { withFileTypes: true }).filter((e) => e.isDirectory() && /^[0-9a-f]{16}$/.test(e.name)).map((e) => e.name); }
115
+ catch (e) { if (absent(e)) return []; throw e; }
116
+ const keys: string[] = [];
117
+ for (const hash of hashes) {
118
+ // One read: a transient failure throws instead of reading as a skipped shard. Absent or readable-but-invalid stays skipped, as in walkShards.
119
+ let text: string;
120
+ try { text = readFileSync(join(projectsDir, hash, "project.json"), "utf8"); }
121
+ catch (e) { if (absent(e)) continue; throw e; }
122
+ let d: unknown;
123
+ try { d = JSON.parse(text); } catch { continue; }
124
+ const v = d as { schema?: unknown; key?: unknown; local?: unknown } | null;
125
+ if (v?.schema === SHARD_SCHEMA && typeof v.key === "string" && typeof v.local === "boolean") keys.push(v.key);
126
+ }
127
+ return keys.sort((a, b) => a.localeCompare(b));
128
+ }
129
+
130
+ const absent = (e: unknown): boolean => (e as NodeJS.ErrnoException)?.code === "ENOENT" || (e as NodeJS.ErrnoException)?.code === "ENOTDIR";
131
+
105
132
  /** What the shards and the alias log say, before anything is persisted. */
106
133
  export function scanCatalog(base: string): CatalogProject[] {
107
134
  const captured = capturedSelection(base);
@@ -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 }
@@ -100,7 +120,7 @@ export class DecayApplyError extends Error {
100
120
  get failed(): string { return this.report.failed; }
101
121
  get remaining(): readonly string[] { return this.report.remaining; }
102
122
  render(): string {
103
- if (this.jsonOutput) return JSON.stringify({ ok: false, ...this.report, failedMayHaveChanged: this.failedMayHaveChanged });
123
+ if (this.jsonOutput) return JSON.stringify({ ok: false, ...this.report, failedMayHaveChanged: this.failedMayHaveChanged }, null, 2);
104
124
  return `${this.message}; applied: ${this.report.applied.join(", ") || "none"}; failed: ${this.report.failed}; remaining: ${this.report.remaining.join(", ") || "none"}${this.report.expiresAt ? `; completed demotions expire: ${this.report.expiresAt}` : ""}`;
105
125
  }
106
126
  }