@staix/agent-mem 0.29.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/.claude-plugin/plugin.json +1 -1
- package/README.md +20 -574
- package/package.json +3 -2
- package/src/cli-agent-reads.ts +17 -2
- package/src/cli.ts +178 -21
- package/src/commands-table.ts +14 -2
- package/src/index.ts +1 -0
- package/src/ingest.ts +7 -5
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/candidates.ts +17 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +2 -1
- package/src/memory/config.ts +13 -1
- package/src/memory/decay-review.ts +20 -0
- package/src/memory/doctor.ts +133 -47
- package/src/memory/eval-audit.ts +442 -0
- package/src/memory/eval.ts +66 -0
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- package/src/memory/native-roots.ts +28 -0
- package/src/memory/platform.ts +9 -1
- package/src/memory/review-targets.ts +69 -0
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-migration.ts +14 -1
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +4 -0
- package/src/memory/store.ts +4 -2
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +14 -2
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +38 -11
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +207 -53
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +14 -0
- package/src/memory/sync-progress.ts +1 -1
- package/src/memory/sync.ts +5 -2
- package/src/memory/use-telemetry.ts +15 -7
- package/src/setup-drift.ts +12 -2
- package/src/setup-owned.ts +42 -0
- package/src/setup.ts +32 -11
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +26 -11
- package/src/ui/snapshot-cache.ts +24 -11
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@staix/agent-mem",
|
|
3
|
-
"version": "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",
|
|
@@ -27,7 +27,8 @@
|
|
|
27
27
|
"bun-types-host-1-4-2": "npm:bun-types@1.4.2",
|
|
28
28
|
"@staix/agent-mem-v0220": "npm:@staix/agent-mem@0.22.0",
|
|
29
29
|
"@types/bun-host-1-4-2": "npm:@types/bun@1.4.2",
|
|
30
|
-
"@staix/agent-mem-v0221": "npm:@staix/agent-mem@0.22.1"
|
|
30
|
+
"@staix/agent-mem-v0221": "npm:@staix/agent-mem@0.22.1",
|
|
31
|
+
"@staix/agent-mem-v0290": "npm:@staix/agent-mem@0.29.0"
|
|
31
32
|
},
|
|
32
33
|
"exports": {
|
|
33
34
|
".": "./src/index.ts",
|
package/src/cli-agent-reads.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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,9 +3,9 @@ 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
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
9
9
|
import type { Writable } from "node:stream";
|
|
10
10
|
import { buildIntentBrief } from "./memory/intent-brief.ts";
|
|
11
11
|
import { proposeConsolidation } from "./memory/consolidate.ts";
|
|
@@ -13,9 +13,10 @@ 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
|
+
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-journal-format.ts";
|
|
19
20
|
import { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
|
|
20
21
|
import { createStandalonePolicy } from "./memory/policy.ts";
|
|
21
22
|
import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
|
|
@@ -30,7 +31,7 @@ import { originLine, originRecheck } from "./memory/candidate-origin.ts";
|
|
|
30
31
|
import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
|
|
31
32
|
import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
|
|
32
33
|
import { memoryProjectKey } from "./memory/project.ts";
|
|
33
|
-
import { CandidateStore, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
|
|
34
|
+
import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
|
|
34
35
|
import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
|
|
35
36
|
import { openCuratedForRead } from "./memory/curated-read.ts";
|
|
36
37
|
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
@@ -41,6 +42,7 @@ import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
|
|
|
41
42
|
import { completionScript } from "./completion.ts";
|
|
42
43
|
import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
|
|
43
44
|
import { realPath } from "./memory/platform.ts";
|
|
45
|
+
import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
|
|
44
46
|
import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
|
|
45
47
|
import { migrate, migrationText } from "./memory/migrate.ts";
|
|
46
48
|
import { migrateShards, shardMigrationStatus, shardMigrationText } from "./memory/shard-migration.ts";
|
|
@@ -122,13 +124,13 @@ const planFileIO: PrunePlanFileIO = {
|
|
|
122
124
|
};
|
|
123
125
|
|
|
124
126
|
/** Open once: pathname replacement cannot redirect the read and growth cannot exceed the fixed byte budget. */
|
|
125
|
-
export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO): string {
|
|
127
|
+
export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO, maximum = PRUNE_PLAN_MAX_BYTES): string {
|
|
126
128
|
try {
|
|
127
129
|
const fd = io.open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
128
130
|
try {
|
|
129
131
|
const before = io.stat(fd);
|
|
130
|
-
if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size < 0 || before.size >
|
|
131
|
-
const data = Buffer.alloc(
|
|
132
|
+
if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size < 0 || before.size > maximum) throw new Error();
|
|
133
|
+
const data = Buffer.alloc(maximum + 1);
|
|
132
134
|
let length = 0;
|
|
133
135
|
while (length < data.length) {
|
|
134
136
|
const n = io.read(fd, data, length, data.length - length, length);
|
|
@@ -136,7 +138,7 @@ export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO
|
|
|
136
138
|
if (n === 0) break;
|
|
137
139
|
length += n;
|
|
138
140
|
}
|
|
139
|
-
if (length >
|
|
141
|
+
if (length > maximum) throw new Error();
|
|
140
142
|
const after = io.stat(fd);
|
|
141
143
|
if (!after.isFile() || after.size !== before.size || length !== before.size) throw new Error();
|
|
142
144
|
return new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, length));
|
|
@@ -197,7 +199,7 @@ function assertAgentAdministrative(value: unknown, policy: ReturnType<typeof con
|
|
|
197
199
|
if (cliAttribution()?.actor !== "agent") return;
|
|
198
200
|
let plain: unknown;
|
|
199
201
|
try { plain = JSON.parse(JSON.stringify(value)); } catch { throw Error("Memory operation unavailable or refused; no partial result is shown."); }
|
|
200
|
-
if (!policy.screenStandalone(plain)) throw
|
|
202
|
+
if (!policy.screenStandalone(plain)) throw new ReadPolicyWithheld();
|
|
201
203
|
}
|
|
202
204
|
function shardStatePresent(): boolean {
|
|
203
205
|
try { lstatSync(join(memoryHome(), "shards.json")); return true; }
|
|
@@ -275,7 +277,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
|
|
|
275
277
|
cause = "setup_receipt_orca_profile"; next = "The receipt was written from an Orca Claude profile; rerun setup from that Orca profile."; partial = false;
|
|
276
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") {
|
|
277
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;
|
|
278
|
-
} 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"
|
|
279
281
|
|| text === "previous-runtime hook settings are customized; review hook configuration before retrying setup"
|
|
280
282
|
|| /^setup receipt (?:does not match this installation|target mismatch|invalid|directory ownership invalid)$/.test(text)) {
|
|
281
283
|
cause = "setup_ownership_conflict"; next = "Review the managed entries and saved setup receipt before retrying; keep unrelated configuration intact."; partial = false;
|
|
@@ -297,6 +299,20 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
|
|
|
297
299
|
return safe;
|
|
298
300
|
}
|
|
299
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
|
+
|
|
300
316
|
export async function runCli(argv: readonly string[], context: CliContext = {}): Promise<string> {
|
|
301
317
|
// Native capture and the MCP server retain their existing surfaces and attribution.
|
|
302
318
|
if (argv[0] === "hook" || argv[0] === "ingest" || argv.length === 1 && argv[0] === "mcp") return runCliCommand(argv, context);
|
|
@@ -307,7 +323,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
307
323
|
const output = await runCliCommand(argv, context);
|
|
308
324
|
if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
|
|
309
325
|
const parsed = parseCommand(argv);
|
|
310
|
-
|
|
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") {
|
|
311
328
|
let receipt: unknown = output;
|
|
312
329
|
// Import receipts contain fixed counters named `pii`; they are not row privacy flags.
|
|
313
330
|
// Screen the complete rendered receipt, including every key and value, as text.
|
|
@@ -315,7 +332,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
315
332
|
try { receipt = JSON.parse(output); } catch { /* human receipts remain strings */ }
|
|
316
333
|
}
|
|
317
334
|
try { assertAgentAdministrative(receipt, configuredPolicy(parsed.path[0] === "setup" ? memoryHome({ ...process.env, ...env }) : memoryHome(), context.cwd ?? process.cwd())); }
|
|
318
|
-
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();
|
|
319
341
|
// The command returned successfully: withholding its receipt cannot undo its effects.
|
|
320
342
|
const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
|
|
321
343
|
return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
|
|
@@ -324,7 +346,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
324
346
|
}
|
|
325
347
|
}
|
|
326
348
|
return output;
|
|
327
|
-
}).catch((error: unknown) => {
|
|
349
|
+
}).catch(async (error: unknown) => {
|
|
328
350
|
// Preserve the authoritative partial outcome, without exposing a cause or a withheld target.
|
|
329
351
|
if (marked && error instanceof DecayApplyError) {
|
|
330
352
|
let readable = false;
|
|
@@ -333,7 +355,14 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
333
355
|
const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
|
|
334
356
|
}
|
|
335
357
|
// Data-free errors (decided before any store or file is opened) keep their own message.
|
|
336
|
-
if (marked && error instanceof AgentUsageError) throw error;
|
|
358
|
+
if (marked && (error instanceof AgentUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
|
|
359
|
+
if (marked && error instanceof RemoteRealmRefusal) throw error;
|
|
360
|
+
// The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
|
|
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);
|
|
364
|
+
// #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
|
|
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);
|
|
337
366
|
const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
|
|
338
367
|
if (marked) {
|
|
339
368
|
// parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
|
|
@@ -342,6 +371,11 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
342
371
|
if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
|
|
343
372
|
const setupError = parsed && markedSetupApplyError(parsed, error);
|
|
344
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
|
+
}
|
|
345
379
|
}
|
|
346
380
|
// Marked administrative failures must not reveal a target's private state or native errors.
|
|
347
381
|
if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
@@ -408,14 +442,26 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
408
442
|
const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
|
|
409
443
|
if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
|
|
410
444
|
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.");
|
|
411
|
-
if (options["--admit"] !== undefined)
|
|
445
|
+
if (options["--list-remote"] === true && (modes.length || options["--admit"] !== undefined || options["--from-remote"] === true || options["--writer-root"] !== undefined || options["--confirm"] === true || options["--checkpoint"] === true || options["--plan"] !== undefined))
|
|
446
|
+
throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
|
|
447
|
+
if (options["--from-remote"] === true && options["--admit"] === undefined)
|
|
448
|
+
throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
|
|
449
|
+
if (options["--checkpoint"] === true) {
|
|
450
|
+
// #288 step 3: preview (default), --confirm --plan, --resume or --abandon; one mode at a time.
|
|
451
|
+
const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
|
|
452
|
+
if (options["--admit"] !== undefined || options["--list-remote"] === true || options["--from-remote"] === true || options["--apply"] === true || options["--dry-run"] === true || chosen > 1 || (options["--confirm"] === true) !== (options["--plan"] !== undefined)
|
|
453
|
+
|| (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
|
|
454
|
+
throw new AgentUsageError("A placement checkpoint uses --sync-placement --checkpoint --writer-root <install root> (repeat) to preview, then --confirm --plan <saved preview JSON> with the same writer roots, or --resume / --abandon alone.");
|
|
455
|
+
} else if (options["--plan"] !== undefined) {
|
|
456
|
+
throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
|
|
457
|
+
} else if (options["--admit"] !== undefined) {
|
|
412
458
|
if (options["--writer-root"] !== undefined || options["--confirm"] === true && options["--abandon"] !== true)
|
|
413
459
|
throw new AgentUsageError("Admitting one realm uses only --sync-placement --admit <project> with --dry-run, --apply, --resume or --abandon --confirm; writer roots belong to initial activation.");
|
|
414
460
|
} else if (options["--confirm"] === true) {
|
|
415
|
-
throw new AgentUsageError("--confirm applies only to --sync-placement --admit <project> --abandon
|
|
461
|
+
throw new AgentUsageError("--confirm applies only to --sync-placement --admit <project> --abandon or --sync-placement --checkpoint --plan <file>; other placement modes keep their own confirmation.");
|
|
416
462
|
}
|
|
417
|
-
} else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined||options["--admit"]!==undefined)) {
|
|
418
|
-
throw new AgentUsageError("--writer-root, --abandon and --
|
|
463
|
+
} else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined||options["--admit"]!==undefined||options["--list-remote"]!==undefined||options["--from-remote"]!==undefined||options["--checkpoint"]!==undefined||options["--plan"]!==undefined)) {
|
|
464
|
+
throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --plan apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
|
|
419
465
|
}
|
|
420
466
|
if (parsed.path[0] === "setup") {
|
|
421
467
|
if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
|
|
@@ -518,9 +564,49 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
518
564
|
if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
|
|
519
565
|
const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
|
|
520
566
|
if (options["--sync-placement"] === true) {
|
|
567
|
+
if (options["--list-remote"] === true) {
|
|
568
|
+
const { discoverRemotePlacementRealms } = await import("./memory/sync-placement-transport.ts");
|
|
569
|
+
const realms = await discoverRemotePlacementRealms(memoryHome(), { ...(context.visibility ? { visibility: context.visibility } : {}) });
|
|
570
|
+
const nextStep = "amem migrate --sync-placement --admit <project> --from-remote --dry-run";
|
|
571
|
+
return options["--json"] === true ? JSON.stringify({ realms, nextStep }, null, 2) : `${realms.map(realm => `scope=${realm.scope} keyHash=${realm.keyHash}; next ${nextStep}`).join("\n") || "no remote-only placement realms"}`;
|
|
572
|
+
}
|
|
573
|
+
if (options["--checkpoint"] === true) {
|
|
574
|
+
const person = await import("./memory/sync-placement-checkpoint-person.ts");
|
|
575
|
+
const writerRoots = repeated(argv, "--writer-root"), ownRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
576
|
+
if (options["--resume"] === true) { const r = await person.resumePlacementCheckpointPerson(memoryHome()); return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: ${r.resumed ? "resumed" : "nothing pending"}; window ${r.window}\nnext: ${r.nextStep}\n`; }
|
|
577
|
+
if (options["--abandon"] === true) { const r = await person.abandonPlacementCheckpointPerson(memoryHome()); return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: ${r.abandoned ? `abandoned (${r.removed} staged files removed)` : "nothing pending"}\nnext: ${r.nextStep}\n`; }
|
|
578
|
+
if (options["--confirm"] === true) {
|
|
579
|
+
let saved: unknown;
|
|
580
|
+
try { saved = JSON.parse(readPrunePlanFile(String(options["--plan"]), undefined, 4 * 1024 * 1024)); } catch { throw new Error("The checkpoint --plan file is unreadable or not the saved preview JSON; rerun amem migrate --sync-placement --checkpoint --json with the writer roots and save its output."); }
|
|
581
|
+
const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot });
|
|
582
|
+
return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: committed window ${r.window} with one writer renewal (plan ${r.planHash})\nnext: ${r.nextStep}\n`;
|
|
583
|
+
}
|
|
584
|
+
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot });
|
|
585
|
+
if (options["--json"] === true) return JSON.stringify(preview, null, 2);
|
|
586
|
+
const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
|
|
587
|
+
// Counts and hashes only; the sealed plan itself is in --json for the confirm step.
|
|
588
|
+
return `sync placement checkpoint preview: window ${preview.window} -> ${preview.nextWindow}; ${preview.currentObjects} of ${h.limit} live objects now\n`
|
|
589
|
+
+ `${placementJournalObjectCompositionText(preview.journalObjects)}\n`
|
|
590
|
+
+ `completed plan: ${h.completedPlan.slots} slots + ${h.completedPlan.reservedJournalChunks} reserved journal chunks; prospective plan: ${h.prospectivePlan.state === "cache-only" ? `${h.prospectivePlan.slots} slots + ${h.prospectivePlan.reservedJournalChunks} reserved journal chunks (cache-only; remote may have changed)` : h.prospectivePlan.state === "none" ? "none" : "unavailable without current remote evidence; using completed history"}\n`
|
|
591
|
+
+ `headroom after checkpoint: ${h.remaining} of ${h.limit} (live ${h.liveAfter}, next renewal ${h.nextRenewal}, largest plan ${h.largestPlan.slots} + ${h.largestPlan.reservedJournalChunks} reserved journal chunks)\n`
|
|
592
|
+
+ `home floor ${preview.requiredHomeFloor}: ${preview.floorReady ? "ready" : `missing; preview amem formats raise home ${preview.requiredHomeFloor}, then --confirm it`}; writers ${preview.writers}; plan ${preview.planHash}\n`
|
|
593
|
+
+ `next: save this preview with --json, then ${preview.nextStep}\n`;
|
|
594
|
+
}
|
|
521
595
|
if (options["--admit"] !== undefined) {
|
|
522
596
|
const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
|
|
523
597
|
const project = String(options["--admit"]);
|
|
598
|
+
const { readRemoteAdoption, inspectRemoteAdoptionPending, pendingRemoteAdoptions } = await import("./memory/sync-placement-remote-stage.ts");
|
|
599
|
+
const realm = createHash("sha256").update(project).digest("hex"), recovery = options["--resume"] === true || options["--abandon"] === true;
|
|
600
|
+
const pending = recovery ? pendingRemoteAdoptions(memoryHome()) : undefined;
|
|
601
|
+
const remotePending = recovery && (!!readRemoteAdoption(memoryHome(), realm) || inspectRemoteAdoptionPending(memoryHome(), realm).length > 0 || !!pending?.unknown || !!pending?.hashes.includes(realm));
|
|
602
|
+
if (options["--from-remote"] === true || remotePending) {
|
|
603
|
+
const { remoteRealmAdmission } = await import("./memory/sync-placement-remote-admission.ts");
|
|
604
|
+
const result = await remoteRealmAdmission(memoryHome(), project, { mode: options["--apply"] === true ? "apply" : options["--resume"] === true ? "resume" : options["--abandon"] === true ? "abandon" : "dry-run",
|
|
605
|
+
...(options["--confirm"] === true ? { confirm: true } : {}), ...(context.visibility ? { visibility: context.visibility } : {}) });
|
|
606
|
+
if (result.state === "preview") result.nextStep = "amem migrate --sync-placement --admit <project> --from-remote --apply";
|
|
607
|
+
if (options["--json"] === true) return JSON.stringify(result, null, 2);
|
|
608
|
+
return `sync placement remote admission: ${result.state}; realm ${result.realm}${result.remoteHead ? `; remote head ${result.remoteHead}` : ""}${result.omitted !== undefined ? `; omitted ${result.omitted}` : ""}${result.nextStep ? `; next ${result.nextStep}` : ""}\n`;
|
|
609
|
+
}
|
|
524
610
|
const result = options["--apply"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "apply" })
|
|
525
611
|
: options["--resume"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "resume" })
|
|
526
612
|
: options["--abandon"] === true ? options["--confirm"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "abandon", confirm: true })
|
|
@@ -648,11 +734,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
648
734
|
if (sub === "decay") {
|
|
649
735
|
const applying = options["--apply"] === true && options["--confirm"] === true;
|
|
650
736
|
if (options["--confirm"] === true && options["--apply"] !== true) throw new Error("decay --confirm requires --apply");
|
|
651
|
-
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");
|
|
652
738
|
const project = boundProject(), base = memoryHome(), aliases = aliasedKeys(base, project);
|
|
653
739
|
const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
|
|
654
740
|
try {
|
|
655
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
|
+
}
|
|
656
755
|
const selected = parsed.positionals.length ? parsed.positionals : undefined;
|
|
657
756
|
if (options["--days"] !== undefined && !/^[1-9][0-9]*$/.test(String(options["--days"]))) throw new Error("decay days must be a positive decimal integer");
|
|
658
757
|
const days = options["--days"] === undefined ? DECAY_DEFAULT_DAYS : Number(options["--days"]);
|
|
@@ -697,6 +796,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
697
796
|
} finally { store.close(); }
|
|
698
797
|
}
|
|
699
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
|
+
}
|
|
700
817
|
const id = parsed.positionals[0];
|
|
701
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`);
|
|
702
819
|
if (sub === "walk" && !(context.stdinTTY ?? process.stdin.isTTY)) throw Error("review walk requires a terminal on stdin; stdout must be a terminal too");
|
|
@@ -765,7 +882,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
765
882
|
const candidate = candidates.get(id!, project);
|
|
766
883
|
if (!candidate || !candidatePermitted(candidate)) throw new Error("candidate unavailable");
|
|
767
884
|
if (candidate.status !== "pending") throw new Error(`candidate is ${candidate.status}, not pending`);
|
|
768
|
-
if (decision === "accept" && candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use
|
|
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");
|
|
769
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");
|
|
770
887
|
if (options["--confirm"] !== true) {
|
|
771
888
|
const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
|
|
@@ -860,7 +977,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
860
977
|
const candidate = candidates.get(id!, project);
|
|
861
978
|
if (!candidate) throw new Error("candidate unavailable");
|
|
862
979
|
if (options["--kind"] !== undefined && candidate.input.kind !== options["--kind"]) throw new Error("candidate kind does not match --kind");
|
|
863
|
-
if (candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use
|
|
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");
|
|
864
981
|
const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
|
|
865
982
|
try {
|
|
866
983
|
const assertCurrent = commandBinding(store.profile.home, project);
|
|
@@ -872,6 +989,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
872
989
|
// #368: a Record candidate quotes capture rows, so acceptance point-reads exactly those turns of its shard,
|
|
873
990
|
// rather than the brief window a candidate can outlive.
|
|
874
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
|
+
},
|
|
875
998
|
});
|
|
876
999
|
return options["--json"] ? JSON.stringify(result, null, 2) : `accepted candidate ${id} as ${candidate.input.kind === "promotion" ? "promoted" : "ordinary"} note ${result.noteId}`;
|
|
877
1000
|
} finally { store.close(); }
|
|
@@ -891,6 +1014,40 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
891
1014
|
}
|
|
892
1015
|
if (sub === "eval") {
|
|
893
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
|
+
}
|
|
894
1051
|
const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
|
|
895
1052
|
const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
|
|
896
1053
|
const builtin = file === undefined ? undefined : builtinSet(file);
|
package/src/commands-table.ts
CHANGED
|
@@ -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,16 +122,20 @@ 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"),
|
|
121
129
|
"--shards": flag("Migrate the curated home into project and user shards"),
|
|
122
130
|
"--public-prune-view": flag("Enable the forward-only v2 public prune view on an active split"),
|
|
123
131
|
"--sync-placement": flag("Person-only forward-only placement activation on this memory home; no automatic migration or renewal"),
|
|
132
|
+
"--list-remote": flag("List remote placement project refs outside the active inventory by hash"),
|
|
124
133
|
"--abandon": flag("Person-only: discard an interrupted sync-placement attempt only before either v3 marker is installed"),
|
|
125
134
|
"--admit": text("Admit one curated project realm that appeared after activation into the same epoch; previews without --apply"),
|
|
135
|
+
"--from-remote": flag("Admit the named remote-only realm using the configured placement sync remote"),
|
|
126
136
|
"--confirm": flag("Confirm the previewed realm admission abandonment"),
|
|
137
|
+
"--checkpoint": flag("Person-reviewed placement checkpoint: preview by default, then --confirm --plan, --resume or --abandon"),
|
|
138
|
+
"--plan": { description: "Saved --checkpoint --json preview to confirm", value: "path" },
|
|
127
139
|
"--writer-root": { description: "Repeatable absolute amem install root in the complete local writer inventory", value: "path" },
|
|
128
140
|
} },
|
|
129
141
|
status: { description: "Report shard migration and pending old-layout appends", options: json },
|
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
|
|
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)
|
|
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
|
|