@staix/agent-mem 0.41.0 → 0.43.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 +2 -2
- package/package.json +4 -3
- package/src/cli.ts +161 -27
- package/src/commands-table.ts +17 -6
- package/src/index.ts +4 -1
- package/src/ingest-hosts.ts +440 -0
- package/src/mcp-bounds.ts +3 -0
- package/src/mcp-memory.ts +64 -10
- package/src/mcp.ts +36 -121
- package/src/memory/candidates.ts +33 -5
- package/src/memory/capture.ts +23 -0
- package/src/memory/commands.ts +6 -3
- package/src/memory/config.ts +26 -0
- package/src/memory/consolidation-clusters.ts +13 -2
- package/src/memory/doctor-text.ts +4 -1
- package/src/memory/doctor.ts +8 -5
- package/src/memory/formats-raise.ts +37 -16
- package/src/memory/formats.ts +37 -10
- package/src/memory/generation-sync.ts +1 -1
- package/src/memory/home-binding-fence.ts +2 -1
- package/src/memory/live-state.ts +85 -0
- package/src/memory/migrate.ts +3 -3
- package/src/memory/mutation.ts +6 -3
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/public-prune-activation.ts +1 -1
- package/src/memory/public-prune-advance.ts +1 -1
- package/src/memory/public-prune-inputs.ts +1 -1
- package/src/memory/purge-intent.ts +27 -0
- package/src/memory/purge-matcher.ts +101 -0
- package/src/memory/purge-plan.ts +90 -0
- package/src/memory/read-curated-entries.ts +244 -0
- package/src/memory/reader-lease.ts +3 -0
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard-migration.ts +3 -3
- package/src/memory/shard-sync.ts +3 -3
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +9 -72
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +39 -22
- package/src/memory/sync-placement-active.ts +69 -19
- package/src/memory/sync-placement-advertisement.ts +25 -3
- package/src/memory/sync-placement-checkpoint-person.ts +8 -14
- package/src/memory/sync-placement-effective-writers.ts +4 -3
- package/src/memory/sync-placement-guard.ts +31 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- package/src/memory/sync-placement-journal.ts +1 -1
- package/src/memory/sync-placement-realm-admission.ts +16 -11
- package/src/memory/sync-placement-refusal.ts +7 -0
- package/src/memory/sync-placement-remote-admission.ts +31 -13
- package/src/memory/sync-placement-remote-refusal.ts +1 -1
- package/src/memory/sync-placement-remote-stage.ts +1 -1
- package/src/memory/sync-placement-transport.ts +36 -15
- package/src/memory/sync-placement-writer-listing.ts +38 -13
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/sync.ts +3 -2
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +35 -4
- package/src/setup-owned.ts +9 -1
- package/src/setup-writer-roots.ts +1 -1
- package/src/setup.ts +102 -16
- package/src/sync-placement-writer-context.ts +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.
|
|
6
|
+
Version: 0.43.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output, @staix/mcp-stdio.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -62,7 +62,7 @@ Run `amem --help` or `amem <command> --help` for every option.
|
|
|
62
62
|
| `amem_graph` | yes | Read the screened curated-memory neighbourhood. |
|
|
63
63
|
| `amem_work_state_read` | yes | Read project work lists; closed lists/items can be included explicitly. |
|
|
64
64
|
| `amem_work_state_write` | no | Append scalar project work-list fields; null clears, task selects an item, list status done closes. |
|
|
65
|
-
| `amem_remember` | no | Propose a memory candidate (text, optional kind/title), or kind=fail with approach, symptom, cause, evidenceRefs and retryWhen. |
|
|
65
|
+
| `amem_remember` | no | Propose a memory candidate (text, optional kind/title/topic), or kind=fail with approach, symptom, cause, evidenceRefs and retryWhen. |
|
|
66
66
|
| `amem_correct` | no | Propose a correction to an exact curated entry id visible in this project. |
|
|
67
67
|
| `amem_vault_candidates` | yes | List screened durable curated notes for review before moving them to a vault. |
|
|
68
68
|
| `amem_capacity` | yes | Read this machine's bounded capture capacity proposal; applying it requires the matching CLI preview and `--confirm`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@staix/agent-mem",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.43.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",
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
"bun": ">=1.4.2"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@staix/cli-output": "0.1.
|
|
15
|
+
"@staix/cli-output": "0.1.4",
|
|
16
|
+
"@staix/mcp-stdio": "0.5.0"
|
|
16
17
|
},
|
|
17
18
|
"devDependencies": {
|
|
18
19
|
"@staix/agent-console": "0.1.3",
|
|
@@ -51,6 +52,6 @@
|
|
|
51
52
|
"LICENSE"
|
|
52
53
|
],
|
|
53
54
|
"scripts": {
|
|
54
|
-
"check": "bun x tsc --noEmit && bun scripts/check-boundary.ts && bun scripts/readme-facts.ts && bun scripts/check-docs.ts && bun test --timeout 20000"
|
|
55
|
+
"check": "bun x tsc --noEmit && bun scripts/check-boundary.ts && bun scripts/refusal-inventory.ts && bun scripts/readme-facts.ts && bun scripts/check-docs.ts && bun test --timeout 20000"
|
|
55
56
|
}
|
|
56
57
|
}
|
package/src/cli.ts
CHANGED
|
@@ -21,12 +21,13 @@ import { safeProfileLockMessage } from "./memory/profile-lock-diagnostic.ts";
|
|
|
21
21
|
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-journal-format.ts";
|
|
22
22
|
import { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
|
|
23
23
|
import { createStandalonePolicy } from "./memory/policy.ts";
|
|
24
|
-
import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
|
|
24
|
+
import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, policyVersionReader, repoConfigRoot } from "./memory/config.ts";
|
|
25
25
|
import { deterministicRowScreen } from "./memory/sync-screen.ts";
|
|
26
26
|
import { vaultCandidates, vaultCandidatesText, vaultCandidatesAllText } from "./memory/vault.ts";
|
|
27
27
|
import type { IngestKind, IngestReceipt } from "./ingest.ts";
|
|
28
28
|
import { importClaudeMemCapture, importClaudeMemWorkState } from "./memory/import.ts";
|
|
29
|
-
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
|
|
29
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, readSync, rmSync, writeFileSync, writeSync } from "node:fs";
|
|
30
|
+
import { types } from "node:util";
|
|
30
31
|
import { isAbsolute, join, resolve } from "node:path";
|
|
31
32
|
import { fileURLToPath } from "node:url";
|
|
32
33
|
import { captureSessionKey } from "./memory/capture-input.ts";
|
|
@@ -47,7 +48,7 @@ import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type Captu
|
|
|
47
48
|
import { COMMANDS, CommandUsageError, commandHelp, commandPath, parseCommand, usageLine } from "./commands-table.ts";
|
|
48
49
|
import { completionScript } from "./completion.ts";
|
|
49
50
|
import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
|
|
50
|
-
import { realPath } from "./memory/platform.ts";
|
|
51
|
+
import { memoryGitEnv, memoryGitSync, realPath } from "./memory/platform.ts";
|
|
51
52
|
import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
|
|
52
53
|
import { placementSyncBoundMessage, placementSyncBoundReceipt } from "./memory/sync-placement-bound.ts";
|
|
53
54
|
import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
|
|
@@ -80,6 +81,7 @@ import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
|
|
|
80
81
|
import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
|
|
81
82
|
import { runEditor } from "./memory/editor.ts";
|
|
82
83
|
import { listAgyReceiptLocations } from "./setup-drift.ts";
|
|
84
|
+
import { PURGE_INTENT_FILE, purgePending } from "./memory/purge-intent.ts";
|
|
83
85
|
import { doctorReport } from "./memory/doctor.ts";
|
|
84
86
|
import { doctorText } from "./memory/doctor-text.ts";
|
|
85
87
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
@@ -183,6 +185,29 @@ function assertSpoolReplayArguments(path: readonly string[], options: Record<str
|
|
|
183
185
|
}
|
|
184
186
|
}
|
|
185
187
|
/** Realm admission receipts name hashes and counts only; the project key is the caller's own argument. */
|
|
188
|
+
function resolveAdmissionProject(home: string, cwd: string, input: string): string {
|
|
189
|
+
if (input === ".") {
|
|
190
|
+
try {
|
|
191
|
+
const directory = realPath(cwd);
|
|
192
|
+
const git = memoryGitSync(["-C", directory, "rev-parse", "--git-dir"], {
|
|
193
|
+
encoding: "utf8", env: memoryGitEnv(process.env, { repositoryIsolation: true }),
|
|
194
|
+
});
|
|
195
|
+
if (git.status !== 0 || !git.stdout.trim()) throw new Error("Git project unavailable");
|
|
196
|
+
return resolveAlias(home, memoryProjectKey(directory, { strictGitErrors: true, repositoryIsolation: true }));
|
|
197
|
+
} catch {
|
|
198
|
+
throw new AgentUsageError("--admit . requires a readable Git project in the current directory. Run from that project or pass its canonical project key.");
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (!input || /^(?:\.\.?(?:[/\\]|$)|[/\\]|[a-z]:[/\\])/i.test(input)) {
|
|
202
|
+
throw new AgentUsageError("--admit requires a canonical project key. Run from the project and use --admit . to resolve it.");
|
|
203
|
+
}
|
|
204
|
+
if (/^github\.com\//i.test(input) && input !== input.toLowerCase()) {
|
|
205
|
+
const hint = /^github\.com\/[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(input) ? input.toLowerCase() : "github.com/<owner>/<repo>";
|
|
206
|
+
throw new AgentUsageError(`--admit requires a lowercase GitHub project key. Use ${hint}.`);
|
|
207
|
+
}
|
|
208
|
+
return input;
|
|
209
|
+
}
|
|
210
|
+
|
|
186
211
|
function realmAdmissionDetail(result: { state: string; next?: { sequence: number; mode: "new" | "existing" }; sequence?: number; headHash?: string; created?: boolean; discarded?: number; discards?: number; staged?: number; nextStep?: string }): string {
|
|
187
212
|
if (result.staged) return `; ${result.state === "abandoned" ? "removed" : "would remove"} ${result.staged} private intent stage(s), ${result.discarded ?? result.discards ?? 0} bytes${result.state === "abandoned" ? "" : "; rerun with --confirm"}`;
|
|
188
213
|
if (result.state === "admitted") return `; appended record ${result.sequence} ${result.headHash}${result.created ? "; wrote the realm's empty curated metadata first" : ""}`;
|
|
@@ -408,13 +433,17 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
408
433
|
if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
|
|
409
434
|
// #578 Q3: a placement fence refusal is a fixed cause class and next step (no path, pid, row or project).
|
|
410
435
|
if (marked && error instanceof Error && error.name === "PlacementInventoryFenceError" && error instanceof (await import("./memory/sync-placement-activation-locks.ts")).PlacementInventoryFenceError) throw new Error(error.message);
|
|
436
|
+
if (marked && error instanceof Error && error.name === "RealmAdmissionError"
|
|
437
|
+
&& error instanceof (await import("./memory/sync-placement-realm-admission.ts")).RealmAdmissionError && error.causeClass === "busy") throw new Error(error.message);
|
|
411
438
|
const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
|
|
412
439
|
// #520/#551: a placement refusal keeps its fixed data - the receipt case its target and remedy, every other case its
|
|
413
440
|
// category, cause class and remedy - so a marked session prints that instead of the masked line. Every other placement
|
|
414
441
|
// and sync failure keeps the generic masked refusal below.
|
|
442
|
+
// #657: a deadline-stopped sync keeps its fixed numbers-only note on the refusal or masked line a marked session sees.
|
|
443
|
+
const deadline = marked ? markedDeadline(error) : undefined, withDeadline = (text: string) => deadline ? `${text} ${deadline}` : text;
|
|
415
444
|
if (marked) {
|
|
416
445
|
const refusal = (await import("./sync-placement-writer-context.ts")).placementWriterRefusalText(error);
|
|
417
|
-
if (refusal) throw new Error(refusal);
|
|
446
|
+
if (refusal) throw new Error(withDeadline(refusal));
|
|
418
447
|
}
|
|
419
448
|
if (marked) {
|
|
420
449
|
// parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
|
|
@@ -434,7 +463,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
434
463
|
}
|
|
435
464
|
}
|
|
436
465
|
// Marked administrative failures must not reveal a target's private state or native errors.
|
|
437
|
-
if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
466
|
+
if (marked) throw Error(withDeadline("Memory operation unavailable or refused; no partial result is shown."));
|
|
438
467
|
throw error;
|
|
439
468
|
}).then(output => {
|
|
440
469
|
// Preserve the value and the policy-screened result; only the JSON presentation changes.
|
|
@@ -472,7 +501,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
472
501
|
const originSession = captureSessionKey(env.AMEM_ORIGIN_SESSION), originPeer = env.AGENTHUB_PEER_ID?.trim() || undefined;
|
|
473
502
|
const constructDone = observeMcpPhase(base, peaks, "construct");
|
|
474
503
|
let memory: ReturnType<typeof createMemoryMcp>;
|
|
475
|
-
try { memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base, peaks,
|
|
504
|
+
try { memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base, peaks, boundSearchResults: true,
|
|
476
505
|
...(originSession || originPeer ? { origin: () => ({ ...(originSession ? { session: originSession } : {}), ...(originPeer ? { peer: originPeer } : {}) }) } : {}) }); } finally { constructDone(); }
|
|
477
506
|
await serveMcp({ tools: memory.tools, close: memory.close, onEmitted: memory.onEmitted, version: VERSION });
|
|
478
507
|
return "";
|
|
@@ -486,7 +515,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
486
515
|
const parsed = parseCommand(argv);
|
|
487
516
|
if (parsed.options["--help"] === true) return commandHelp(argv);
|
|
488
517
|
const kind = parsed.positionals[0];
|
|
489
|
-
if (parsed.positionals.length !== 1 || !["codex", "kimi", "pi", "qwen"].includes(kind ?? "")) throw new Error("usage: amem ingest codex|kimi|pi|qwen [--since ISO] [--json]");
|
|
518
|
+
if (parsed.positionals.length !== 1 || !["codex", "kimi", "pi", "qwen", "opencode", "gemini", "agy"].includes(kind ?? "")) throw new Error("usage: amem ingest codex|kimi|pi|qwen|opencode|gemini|agy [--since ISO] [--json]");
|
|
519
|
+
if (kind === "opencode" || kind === "gemini" || kind === "agy") {
|
|
520
|
+
const { ingestHost } = await import("./ingest-hosts.ts");
|
|
521
|
+
// #647: the Gemini SessionEnd hook passes its JSON on stdin; only transcript_path is read from it, and a bad input ingests nothing.
|
|
522
|
+
let transcript: string | undefined;
|
|
523
|
+
if (parsed.options["--hook-input"] === true) {
|
|
524
|
+
if (kind !== "gemini") throw new Error("--hook-input applies only to amem ingest gemini");
|
|
525
|
+
try {
|
|
526
|
+
const input = JSON.parse((context.stdin ?? (() => readFileSync(0, "utf8")))().slice(0, 64 * 1024)) as { transcript_path?: unknown };
|
|
527
|
+
if (typeof input.transcript_path === "string" && input.transcript_path.startsWith("/")) transcript = input.transcript_path;
|
|
528
|
+
} catch { /* fail open: no transcript, nothing ingested */ }
|
|
529
|
+
if (transcript === undefined) return parsed.options["--json"] === true ? JSON.stringify({ files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0 }, null, 2) : "";
|
|
530
|
+
}
|
|
531
|
+
const result = await ingestHost(kind, { cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env), env: context.env ?? process.env,
|
|
532
|
+
...(transcript ? { transcript } : {}), ...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}) });
|
|
533
|
+
return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind, result as IngestReceipt, outputStyle(context, parsed.options), reportWidth(context));
|
|
534
|
+
}
|
|
490
535
|
const { ingestTranscript } = await import("./ingest.ts");
|
|
491
536
|
const result = await ingestTranscript(kind as IngestKind, {
|
|
492
537
|
cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
|
|
@@ -524,6 +569,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
524
569
|
const identity = cliAttribution() ?? { actor: "person" as const, peer: "person" }, actor = identity.actor;
|
|
525
570
|
if (parsed.path[0] === "migrate" && options["--sync-placement"] === true) {
|
|
526
571
|
const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
|
|
572
|
+
// #660: the saved-plan file and root discovery belong to the checkpoint preview only.
|
|
573
|
+
if ((options["--out"] !== undefined || options["--discovered-writers"] !== undefined)
|
|
574
|
+
&& (options["--checkpoint"] !== true || ["--confirm","--resume","--abandon","--json"].some(key => options[key] !== undefined && key !== "--json") || options["--discovered-writers"] !== undefined && options["--writer-root"] !== undefined))
|
|
575
|
+
throw new AgentUsageError("--out <file> and --discovered-writers apply only to a checkpoint preview: amem migrate --sync-placement --checkpoint --discovered-writers --out checkpoint-plan.json (or --writer-root <install root>, repeated, instead of --discovered-writers), then amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json.");
|
|
527
576
|
if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
|
|
528
577
|
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.");
|
|
529
578
|
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))
|
|
@@ -540,7 +589,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
540
589
|
const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
|
|
541
590
|
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)
|
|
542
591
|
|| (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
|
|
543
|
-
throw new AgentUsageError("A placement checkpoint previews with --sync-placement --checkpoint --writer-root <install root> (repeat), saves the plan with
|
|
592
|
+
throw new AgentUsageError("A placement checkpoint previews with --sync-placement --checkpoint --writer-root <install root> (repeat) or --discovered-writers, saves the plan with --out checkpoint-plan.json, then confirms with amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json (the plan names its writer roots), or uses --resume / --abandon alone.");
|
|
544
593
|
} else if (options["--plan"] !== undefined) {
|
|
545
594
|
throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
|
|
546
595
|
} else if (options["--admit"] !== undefined) {
|
|
@@ -551,8 +600,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
551
600
|
}
|
|
552
601
|
} else if (parsed.path[0] === "migrate" && options["--writers"] !== undefined) {
|
|
553
602
|
throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
|
|
554
|
-
} 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)) {
|
|
555
|
-
throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --
|
|
603
|
+
} 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||options["--out"]!==undefined||options["--discovered-writers"]!==undefined)) {
|
|
604
|
+
throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint, --plan, --out and --discovered-writers apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
|
|
556
605
|
}
|
|
557
606
|
if (parsed.path[0] === "skills" && parsed.path[1] === "export") {
|
|
558
607
|
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem skills export <dir> [--json]");
|
|
@@ -564,6 +613,20 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
564
613
|
return [`amem skills export: ${report.root}${report.linkedFrom ? ` (linked from ${report.linkedFrom})` : ""}`, "NAME CHANGE PATH / REASON", ...report.actions.map(a => `${a.name.padEnd(20)} ${a.change.padEnd(10)} ${a.path}${a.reason ? ` / ${a.reason}` : ""}`)].join("\n");
|
|
565
614
|
}
|
|
566
615
|
if (parsed.path[0] === "setup") {
|
|
616
|
+
if (options["--refresh"] === true) {
|
|
617
|
+
const { refreshAgyWorkspaces, agyRefreshText, setupMemoryHome } = await import("./setup.ts");
|
|
618
|
+
const mode = options["--apply"] === true ? "apply" : "preview", env = context.env ?? process.env;
|
|
619
|
+
const result = refreshAgyWorkspaces(mode, { env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY,
|
|
620
|
+
...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}), ...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}) });
|
|
621
|
+
if (result.workspaces.some(row => row.change === "refused")) context.onExitCode?.(1);
|
|
622
|
+
const output = options["--json"] === true ? JSON.stringify(result, null, 2) : agyRefreshText(result, mode);
|
|
623
|
+
if (actor === "agent") {
|
|
624
|
+
const policy = configuredPolicy(setupMemoryHome(env), context.cwd ?? process.cwd());
|
|
625
|
+
assertAgentAdministrative(result, policy);
|
|
626
|
+
assertAgentAdministrative(output, policy);
|
|
627
|
+
}
|
|
628
|
+
return output;
|
|
629
|
+
}
|
|
567
630
|
if (options["--list"] === true) {
|
|
568
631
|
const { setupMemoryHome } = await import("./setup.ts");
|
|
569
632
|
const home = setupMemoryHome(context.env ?? process.env);
|
|
@@ -580,7 +643,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
580
643
|
return output;
|
|
581
644
|
}
|
|
582
645
|
if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
|
|
583
|
-
|| options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new CommandUsageError("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all|console [--root <abs path>] [--apply [--adopt-current]|--undo] | amem setup agy --list [--json]");
|
|
646
|
+
|| options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new CommandUsageError("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all|console [--root <abs path>] [--apply [--adopt-current]|--undo] | amem setup agy --list [--json] | amem setup agy --refresh [--root <abs path>] [--apply [--adopt-current]] [--json]");
|
|
584
647
|
if (parsed.positionals[0] === "console") {
|
|
585
648
|
const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
|
|
586
649
|
const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
|
|
@@ -691,7 +754,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
691
754
|
if (options["--sync-placement"] === true) {
|
|
692
755
|
if (options["--writers"] === true) {
|
|
693
756
|
const { listPlacementWriters, placementWritersText } = await import("./memory/sync-placement-writer-listing.ts");
|
|
694
|
-
const listing = listPlacementWriters(memoryHome(), fileURLToPath(new URL("..", import.meta.url)));
|
|
757
|
+
const listing = listPlacementWriters(memoryHome(), fileURLToPath(new URL("..", import.meta.url)), placementDiscovery(context));
|
|
695
758
|
return options["--json"] === true ? JSON.stringify(listing, null, 2) : placementWritersText(listing);
|
|
696
759
|
}
|
|
697
760
|
if (options["--list-remote"] === true) {
|
|
@@ -707,7 +770,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
707
770
|
}
|
|
708
771
|
if (options["--checkpoint"] === true) {
|
|
709
772
|
const person = await import("./memory/sync-placement-checkpoint-person.ts");
|
|
710
|
-
const
|
|
773
|
+
const ownRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
774
|
+
// #660: --discovered-writers measures the roots --writers suggests; the preview prints them before anything is confirmed.
|
|
775
|
+
const writerRoots = options["--discovered-writers"] === true
|
|
776
|
+
? (await import("./memory/sync-placement-writer-listing.ts")).listPlacementWriters(memoryHome(), ownRoot, placementDiscovery(context)).suggestedRoots
|
|
777
|
+
: repeated(argv, "--writer-root");
|
|
711
778
|
// Human output keeps the fixed refusal text. Classified JSON failures exit 1 and carry their safe own fields.
|
|
712
779
|
const checkpointRefusalJson = async (error: unknown): Promise<string> => {
|
|
713
780
|
if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "history" && error.history) {
|
|
@@ -740,6 +807,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
740
807
|
}
|
|
741
808
|
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(checkpointRefusalJson);
|
|
742
809
|
if (typeof preview === "string") return preview;
|
|
810
|
+
const out = typeof options["--out"] === "string" ? options["--out"] : undefined;
|
|
811
|
+
// A marked session's plan and its destination pass the policy screen before any file exists (#660).
|
|
812
|
+
if (out !== undefined) assertAgentAdministrative({ out, preview }, configuredPolicy(memoryHome(), context.cwd ?? process.cwd()));
|
|
813
|
+
if (out !== undefined) { writePrivatePlan(out, JSON.stringify(preview, null, 2) + "\n"); preview.nextStep = `${person.CHECKPOINT_PREVIEW} --confirm --plan ${shellQuoteArg(out)}`; }
|
|
743
814
|
if (options["--json"] === true) return JSON.stringify(preview, null, 2);
|
|
744
815
|
const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
|
|
745
816
|
// Counts and hashes only; the sealed plan itself is in --json for the confirm step.
|
|
@@ -748,11 +819,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
748
819
|
+ `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`
|
|
749
820
|
+ `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`
|
|
750
821
|
+ `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`
|
|
822
|
+
+ `writer roots measured:\n${preview.plan.writerRevision.roots.map(root => ` ${root.root}`).join("\n")}\n`
|
|
823
|
+
+ (out !== undefined ? `plan saved: ${out}\n` : "")
|
|
751
824
|
+ `next: ${preview.nextStep}\n`;
|
|
752
825
|
}
|
|
753
826
|
if (options["--admit"] !== undefined) {
|
|
754
827
|
const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
|
|
755
|
-
const project = String(options["--admit"]);
|
|
828
|
+
const project = resolveAdmissionProject(memoryHome(), context.cwd ?? process.cwd(), String(options["--admit"]));
|
|
756
829
|
const { readRemoteAdoption, inspectRemoteAdoptionPending, pendingRemoteAdoptions } = await import("./memory/sync-placement-remote-stage.ts");
|
|
757
830
|
const realm = createHash("sha256").update(project).digest("hex"), recovery = options["--resume"] === true || options["--abandon"] === true;
|
|
758
831
|
const pending = recovery ? pendingRemoteAdoptions(memoryHome()) : undefined;
|
|
@@ -837,11 +910,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
837
910
|
if ((readPlacementRuntimeMarkers(home).profile as { publicationFormat?: string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
838
911
|
try { for (const root of readEffectiveSyncPlacementWriterRoots(home)) add("sync-placement", root); } catch { incomplete.push("sync-placement writer roots unreadable"); }
|
|
839
912
|
}
|
|
913
|
+
let processArgs: string[] | undefined;
|
|
840
914
|
try {
|
|
841
|
-
const
|
|
842
|
-
for (const { pid, root, host } of runningAmemRoots(
|
|
915
|
+
const rows = processTable(context)();
|
|
916
|
+
for (const { pid, root, host } of runningAmemRoots(() => rows, context.embeddedAmem)) add(host ? "library-host" : "running", root, pid, host);
|
|
917
|
+
processArgs = rows.split("\n");
|
|
843
918
|
} catch { incomplete.push("running processes could not be listed"); }
|
|
844
|
-
return { writers: writers.sort((a, b) => a.source.localeCompare(b.source) || a.root.localeCompare(b.root) || (a.pid ?? 0) - (b.pid ?? 0)), incomplete };
|
|
919
|
+
return { writers: writers.sort((a, b) => a.source.localeCompare(b.source) || a.root.localeCompare(b.root) || (a.pid ?? 0) - (b.pid ?? 0)), incomplete, ...(processArgs ? { processArgs } : {}) };
|
|
845
920
|
};
|
|
846
921
|
const now = context.now ? () => new Date(context.now!()) : undefined;
|
|
847
922
|
const plan = planFormatRaise(home, surface, minReader, inventory(), now);
|
|
@@ -852,11 +927,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
852
927
|
out.header("amem", "Format floor"); out.section("Preview"); out.bullet("pending", "Review the proposed floor before confirming.");
|
|
853
928
|
out.kv([["Surface", plan.record.surface], ["Minimum reader", plan.record.minReader], ["Since", plan.record.since], ["File", plan.file], ["Existing", plan.existing.length ? plan.existing.map(floor => `${floor.surface} >= ${floor.minReader}`).join(", ") : "none"]]);
|
|
854
929
|
out.section("Writers", String(plan.writers.length));
|
|
855
|
-
if (plan.writers.length) out.table(["SOURCE", "VERSION", "INSTALL"], plan.writers.map(writer => [writer.source, writer.version ?? "?", `${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`]), 2);
|
|
930
|
+
if (plan.writers.length) out.table(["SOURCE", "VERSION", "INSTALL"], plan.writers.map(writer => [writer.source, writer.version ?? (plan.absent.includes(writer) ? "absent" : "?"), `${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`]), 2);
|
|
856
931
|
else out.note("No writers found.");
|
|
932
|
+
// #660: a removed install cannot open this home, so it is shown but never counted as a writer below the floor.
|
|
933
|
+
if (plan.absent.length) out.note(`${plan.absent.length} removed install${plan.absent.length === 1 ? "" : "s"} (absent on disk, no live process) not counted.`);
|
|
857
934
|
if (refusal) { out.section("Attention"); out.bullet("warn", refusal); }
|
|
858
935
|
else out.next(`amem formats raise ${surface} ${minReader} --confirm`);
|
|
859
|
-
const legacy = [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`, `writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? "unknown"} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`), refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
|
|
936
|
+
const legacy = [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`, `writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? (plan.absent.includes(writer) ? "absent" : "unknown")} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`), refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
|
|
860
937
|
return screenedLegacy(legacy, out.render(s.color).join("\n"));
|
|
861
938
|
}
|
|
862
939
|
const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
|
|
@@ -867,11 +944,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
867
944
|
}
|
|
868
945
|
if (sub === "doctor") {
|
|
869
946
|
// F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
|
|
870
|
-
const where = resolveMemoryHome()
|
|
947
|
+
const where = resolveMemoryHome();
|
|
948
|
+
if (purgePending(where.home)) {
|
|
949
|
+
const purge = { status: "pending", file: PURGE_INTENT_FILE,
|
|
950
|
+
next: "Keep this home closed and retain the barrier for recovery. See docs/purge-design.md, Placement cut and recovery." };
|
|
951
|
+
return options["--json"] ? JSON.stringify({ purge }, null, 2) : `Local purge pending (${purge.file}). ${purge.next}`;
|
|
952
|
+
}
|
|
953
|
+
const project = boundProject();
|
|
871
954
|
const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
|
|
872
955
|
openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
|
|
873
956
|
return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options), reportOptions(context, options));
|
|
874
957
|
}
|
|
958
|
+
if (sub === "purge") {
|
|
959
|
+
const { planPurge } = await import("./memory/purge-plan.ts");
|
|
960
|
+
const matchFile = options["--match-file"];
|
|
961
|
+
const plan = administrative(planPurge(memoryHome(), { entryId: parsed.positionals[0] ?? "", ...(typeof matchFile === "string" ? { matchFile: resolve(context.cwd ?? process.cwd(), matchFile) } : {}) }));
|
|
962
|
+
return JSON.stringify(plan, null, 2);
|
|
963
|
+
}
|
|
875
964
|
if (sub === "prune") {
|
|
876
965
|
const applying = options["--apply"] === true;
|
|
877
966
|
if (applying ? options["--dry-run"] || options["--cutoff"] || !options["--plan"] : !options["--dry-run"] || !options["--cutoff"] || options["--plan"]) throw new Error("usage: amem prune [--user] --cutoff <UTC> --dry-run | [--user] --apply --plan <file>");
|
|
@@ -1042,6 +1131,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1042
1131
|
}
|
|
1043
1132
|
if (input.kind === "model-answer") return `Model answer (not evidence; cannot accept, author an independent note with amem note add). ${input.text}`;
|
|
1044
1133
|
if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
|
|
1134
|
+
// #580: a topic correction shows the note it replaces beside the new text; several matches are listed for the person to pick.
|
|
1135
|
+
if (input.kind === "correction" && input.topic !== undefined) {
|
|
1136
|
+
const viewStore = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
1137
|
+
try {
|
|
1138
|
+
const target = viewStore.get(input.target.id, project);
|
|
1139
|
+
administrative({ candidate, target });
|
|
1140
|
+
const old = target && target.id === input.target.id && candidateTargetRevision(target) === input.target.revision ? `${target.title ? `${target.title}: ` : ""}${target.text}` : "(changed or unavailable; reject or skip)";
|
|
1141
|
+
return `topic correction (${input.topic}). Old mem:${input.target.id}: ${old} New: ${input.proposedText} Reason: ${input.reason}`;
|
|
1142
|
+
} finally { viewStore.close(); }
|
|
1143
|
+
}
|
|
1144
|
+
if (input.kind === "memory" && input.topicMatches) return `topic ${input.topic} is on ${input.topicMatches.length} live notes (${input.topicMatches.map(target => `mem:${target.id}`).join(", ")}); accepting adds a note and supersedes none, or correct one with amem_correct. ${input.title ? `${input.title}: ` : ""}${input.text}`;
|
|
1045
1145
|
return input.kind === "memory" ? `${input.title ? `${input.title}: ` : ""}${input.text}` : input.kind === "fail" ? `fail. Approach: ${input.approach} Symptom: ${input.symptom} Cause: ${input.cause} Retry when: ${input.retryWhen}`
|
|
1046
1146
|
: input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
|
|
1047
1147
|
// #323 item 4: can the origin still be re-checked against capture? An expired session is reported as such, never as a failed check.
|
|
@@ -1592,7 +1692,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1592
1692
|
}
|
|
1593
1693
|
}
|
|
1594
1694
|
// Only a real attempt is stamped: a local refusal (lock held, no remote, policy, usage) is not, and a future stamp is no history (src/memory/sync-cadence.ts).
|
|
1595
|
-
const stampSync = (error: string | undefined, cause?: StopCause) => { if (syncOutcome(error, cause) !== "local") recordSyncAttempt(syncHome, error === undefined, Date.now()); };
|
|
1695
|
+
const stampSync = (error: string | undefined, cause?: StopCause) => { if (syncOutcome(error, cause) !== "local") recordSyncAttempt(syncHome, error === undefined, Date.now(), cause === "deadline"); };
|
|
1696
|
+
// #657: a run the --if-due deadline stopped says so, and names the command that runs without one.
|
|
1697
|
+
const deadlineNote = (text: string, cause?: StopCause) => cause === "deadline" && !text.includes("--if-due stopped")
|
|
1698
|
+
? `${text} sync --if-due stopped at its ${Math.round((context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS) / 1000)} s deadline; run amem sync to finish without one.` : text;
|
|
1596
1699
|
const captureImport = sub === "import" && parsed.path[1] === "claude-mem", captureDays = options["--capture-days"] === undefined ? undefined : Number(options["--capture-days"]);
|
|
1597
1700
|
if (captureImport && captureDays !== undefined && (!Number.isSafeInteger(captureDays) || captureDays <= 0)) throw new Error("--capture-days takes a positive integer");
|
|
1598
1701
|
const captureArgs = new Set<number>();
|
|
@@ -1628,7 +1731,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1628
1731
|
const refusal = placementWriterRefusalText(error);
|
|
1629
1732
|
if (refusal === undefined || !options["--json"]) throw error;
|
|
1630
1733
|
stampSync(refusal, stop?.cause());
|
|
1631
|
-
|
|
1734
|
+
// #657: a deadline that already fired during setup keeps its note after the fixed refusal text.
|
|
1735
|
+
return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: deadlineNote(refusal, stop?.cause()) }, null, 2);
|
|
1632
1736
|
}
|
|
1633
1737
|
const attest = placementWriters.attest;
|
|
1634
1738
|
attestPlacement = () => {
|
|
@@ -1646,15 +1750,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1646
1750
|
}
|
|
1647
1751
|
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), ...(options["--json"] !== true ? { [CLI_MEMORY_RENDER]: { render: { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, ...(actor === "agent" ? { renderLegacy: (legacy: string, formatted: string) => { priorRead = legacy; return sub === "sync" ? screenedReceipt(legacy, formatted) : screenedReadPair(legacy, formatted); } } : {}) } } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1648
1752
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1649
|
-
sync: { ...(attestPlacement ? { placementAttestation: attestPlacement, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: deterministicRowScreen(configuredPolicyOptions(memoryHome(), policyCwd)), policyVersion: (
|
|
1753
|
+
sync: { ...(attestPlacement ? { placementAttestation: attestPlacement, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: deterministicRowScreen(configuredPolicyOptions(memoryHome(), policyCwd)), policyVersion: policyVersionReader(memoryHome, policyCwd), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1650
1754
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1651
1755
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1652
1756
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
1653
1757
|
} catch (error) {
|
|
1654
1758
|
if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
|
|
1655
1759
|
if (sub === "sync") stampSync((error as Error).message, stop?.cause());
|
|
1656
|
-
|
|
1657
|
-
|
|
1760
|
+
const failure = sub === "sync" && placementWriters?.lastRefusal ? (await import("./sync-placement-writer-context.ts")).placementSyncFailure(placementWriters.lastRefusal, error) : error;
|
|
1761
|
+
if (sub === "sync" && failure instanceof Error && stop?.cause() === "deadline") withSyncDeadline(failure, deadlineNote("", "deadline").trim());
|
|
1762
|
+
throw failure;
|
|
1658
1763
|
}
|
|
1659
1764
|
finally {
|
|
1660
1765
|
// A run that never reached the transport's receipt (an early refusal) must not stay "running".
|
|
@@ -1671,7 +1776,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1671
1776
|
const result = JSON.parse(output) as { ok?: unknown; error?: unknown };
|
|
1672
1777
|
if (result.ok === false) {
|
|
1673
1778
|
failure = typeof result.error === "string" ? result.error : "sync failed";
|
|
1674
|
-
if (placementWriters?.lastRefusal)
|
|
1779
|
+
if (placementWriters?.lastRefusal) result.error = `${placementWriters.lastRefusal.message} ${failure}`;
|
|
1780
|
+
if (stop?.cause() === "deadline") result.error = deadlineNote(String(result.error ?? failure), "deadline");
|
|
1781
|
+
if (placementWriters?.lastRefusal || stop?.cause() === "deadline") output = JSON.stringify(result,null,2);
|
|
1675
1782
|
}
|
|
1676
1783
|
} catch { /* not a sync result */ } }
|
|
1677
1784
|
stampSync(failure, stop?.cause());
|
|
@@ -1690,6 +1797,33 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1690
1797
|
? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
|
|
1691
1798
|
}
|
|
1692
1799
|
|
|
1800
|
+
/** #657: appends the deadline note to a sync failure and carries it, numbers only, for a marked session's fixed text. */
|
|
1801
|
+
export function withSyncDeadline<T extends Error>(error: T, note: string): T {
|
|
1802
|
+
if (!error.message.includes(note)) error.message = `${error.message} ${note}`;
|
|
1803
|
+
Object.defineProperty(error, "syncDeadlineNote", { value: note }); return error;
|
|
1804
|
+
}
|
|
1805
|
+
/** The deadline note a sync failure carries as an own property, accepted only in its fixed numbers-only form. */
|
|
1806
|
+
export function markedDeadline(error: unknown): string | undefined {
|
|
1807
|
+
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
1808
|
+
const note: unknown = Object.getOwnPropertyDescriptor(error, "syncDeadlineNote")?.value;
|
|
1809
|
+
return typeof note === "string" && /^sync --if-due stopped at its \d{1,6} s deadline; run amem sync to finish without one\.$/.test(note) ? note : undefined;
|
|
1810
|
+
}
|
|
1811
|
+
/** #660: the checkpoint preview saved for its confirm step: a new private file, never an existing path or a link, synced before return. */
|
|
1812
|
+
function writePrivatePlan(file: string, text: string): void {
|
|
1813
|
+
let fd: number;
|
|
1814
|
+
try { fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
1815
|
+
catch (error) { throw new Error(`The checkpoint plan was not saved: ${(error as NodeJS.ErrnoException).code === "EEXIST" ? "the --out path already exists" : "the --out path cannot be created"}; choose a new --out file and preview again.`); }
|
|
1816
|
+
try { writeSync(fd, text); fsyncSync(fd); } finally { closeSync(fd); }
|
|
1817
|
+
}
|
|
1818
|
+
const shellQuoteArg = (value: string) => /^[A-Za-z0-9_./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
1819
|
+
/** The `pid args` process table `formats raise` and `--writers` read; `context.processTable` is the test seam. */
|
|
1820
|
+
function processTable(context: CliContext): () => string {
|
|
1821
|
+
return context.processTable ?? (() => require("node:child_process").execFileSync("ps", ["-axo", "pid=,args="], { encoding: "utf8", maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }) as string);
|
|
1822
|
+
}
|
|
1823
|
+
/** #660: what `--writers` and `--discovered-writers` search for library hosts: live processes and ahub/vmem on PATH. */
|
|
1824
|
+
function placementDiscovery(context: CliContext): import("./memory/sync-placement-writer-listing.ts").PlacementWriterDiscovery {
|
|
1825
|
+
return { table: processTable(context), ...(context.embeddedAmem ? { embedded: context.embeddedAmem } : {}), path: (context.env ?? process.env).PATH ?? "" };
|
|
1826
|
+
}
|
|
1693
1827
|
/** Color for human output only on an interactive stdout without NO_COLOR or TERM=dumb (#125). */
|
|
1694
1828
|
/**
|
|
1695
1829
|
* #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
|
|
@@ -1722,7 +1856,7 @@ function reportWidth(context: CliContext): number | undefined {
|
|
|
1722
1856
|
}
|
|
1723
1857
|
|
|
1724
1858
|
/** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
|
|
1725
|
-
export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
|
|
1859
|
+
export function ingestText(kind: IngestKind | "opencode" | "gemini" | "agy", result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
|
|
1726
1860
|
const state = result.errors || result.remaining || result.spooled ? "attention" : result.files || result.read ? "complete" : "skipped";
|
|
1727
1861
|
const reason: string | undefined = result.reason;
|
|
1728
1862
|
const actions: Record<string, string> = {
|
package/src/commands-table.ts
CHANGED
|
@@ -48,8 +48,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
48
48
|
options: { ...json("the queued candidates"), "--project": text("This project's key", "Another project is refused; run from its directory.") } },
|
|
49
49
|
setup: { group: "setup", description: "Preview or apply MCP setup and capture hooks",
|
|
50
50
|
details: "Covers native coding CLIs, or the acon console plugin manifest (console). Apply and undo use explicit flags.",
|
|
51
|
-
examples: ["amem setup claude", "amem setup all --apply", "amem setup agy --list"],
|
|
52
|
-
options: { ...json("the setup plan or receipt list"), "--list": flag("List agy receipt workspaces and repair commands", "Use only with the agy target."),
|
|
51
|
+
examples: ["amem setup claude", "amem setup all --apply", "amem setup agy --list", "amem setup agy --refresh --apply"],
|
|
52
|
+
options: { ...json("the setup plan or receipt list"), "--list": flag("List agy receipt workspaces and repair commands", "Use only with the agy target."),
|
|
53
|
+
"--refresh": flag("Refresh every receipted agy workspace", "Use only with the agy target. Previews without --apply; touches only workspaces that already have a receipt."), "--apply": flag("Apply the previewed setup"), "--undo": flag("Restore the original configuration"),
|
|
53
54
|
"--verbose": flag("Show static notes and history lines (human output only)"),
|
|
54
55
|
"--root": path("Register this absolute install root", "Such as <install>/releases/<version>/, resolved to its real path, instead of the running one."),
|
|
55
56
|
"--adopt-current": flag("With --apply: adopt the current wiring", "Keeps a stale setup receipt aside (its entries were replaced at another install root) and adopts the current wiring, which --undo restores.") },
|
|
@@ -61,8 +62,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
61
62
|
examples: ["amem manifest --json"], options: json("the manifest") },
|
|
62
63
|
hook: { group: "setup", description: "Run a fail-open, context-only capture hook", examples: ["amem hook SessionStart"], args: [{ name: "event", values: [...HOOK_EVENTS, "jcode"] }] },
|
|
63
64
|
ingest: { group: "setup", description: "Capture native session transcripts incrementally", details: "Runs once per call; no watcher.",
|
|
64
|
-
examples: ["amem ingest codex", "amem ingest pi --since 2026-11-01"], options: { ...json("the ingest receipt"), "--since": date("Only transcripts since this ISO date or time")
|
|
65
|
-
|
|
65
|
+
examples: ["amem ingest codex", "amem ingest pi --since 2026-11-01", "amem ingest opencode"], options: { ...json("the ingest receipt"), "--since": date("Only transcripts since this ISO date or time"),
|
|
66
|
+
"--hook-input": flag("Read a Gemini SessionEnd hook's transcript_path from stdin", "Setup writes this flag into the Gemini hook; it never blocks or denies.") },
|
|
67
|
+
args: [{ name: "kind", values: ["codex", "kimi", "pi", "qwen", "opencode", "gemini", "agy"] }] },
|
|
66
68
|
"vault-candidates": { group: "read", description: "List screened durable vault candidates", details: "Per project, or across projects with --all-projects.",
|
|
67
69
|
examples: ["amem vault-candidates", "amem vault-candidates --all-projects --limit 20"],
|
|
68
70
|
options: { ...json("the candidates"), "--limit": number("Maximum candidates per project (1..100)"),
|
|
@@ -239,12 +241,14 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
239
241
|
"--list-remote": flag("List remote project refs outside the inventory", "By hash, outside the active inventory."),
|
|
240
242
|
"--writers": flag("List writer installs and the roots to declare", "Read-only: inventory, running install, setup receipts and the saving-preview command."),
|
|
241
243
|
"--abandon": flag("Discard an interrupted placement attempt", "Pre-commit only. Initial activation requires both markers to match their original v2 bytes; realm admission requires --confirm."),
|
|
242
|
-
"--admit": text("Admit one new curated project realm", "A realm that appeared after activation, into the same epoch. Previews without --apply."),
|
|
244
|
+
"--admit": text("Admit one new curated project realm", "A realm that appeared after activation, into the same epoch. Use a canonical project key or . for the current Git project. Previews without --apply."),
|
|
243
245
|
"--from-remote": flag("Admit the named remote-only realm", "Uses the configured placement sync remote."),
|
|
244
246
|
"--confirm": flag("Confirm the previewed abandonment or checkpoint"),
|
|
245
247
|
"--checkpoint": flag("Preview a placement checkpoint", "Person-reviewed: preview by default, then --confirm --plan, --resume or --abandon."),
|
|
246
248
|
"--checkpoint-on-bound": { description: "Preview the sync-run checkpoint opt-in", value: ["on", "off"], details: "Turns the home opt-in on or off; --confirm writes it to amem.config.json." },
|
|
247
|
-
"--plan": path("Saved --checkpoint
|
|
249
|
+
"--plan": path("Saved --checkpoint preview to confirm", "The plan names its writer roots; --writer-root is then optional and must match it."),
|
|
250
|
+
"--out": path("Save the checkpoint preview to a new 0600 file", "Checkpoint preview only; refuses an existing path or a link."),
|
|
251
|
+
"--discovered-writers": flag("Measure the roots --writers suggests", "Checkpoint preview only, instead of --writer-root; the preview prints every measured root."),
|
|
248
252
|
"--writer-root": path("Writer inventory install root (repeatable)", "An absolute amem install root; repeat it for the complete local writer inventory."),
|
|
249
253
|
} },
|
|
250
254
|
status: { group: "read", description: "Show the memory home, policy and migration state", examples: ["amem status", "amem status --verbose"],
|
|
@@ -259,6 +263,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
259
263
|
doctor: { group: "read", description: "Check this project's memory health, read-only",
|
|
260
264
|
details: "Duplicates and stale notes, pending candidates, capture freshness per CLI, the brief's token cost, index equals rebuild, reader leases, the policy in effect, and ingest and sync cadence.",
|
|
261
265
|
examples: ["amem doctor", "amem doctor --json"], options: { ...json("the doctor report"), "--verbose": flag("Show static notes and history lines (human output only)") } },
|
|
266
|
+
purge: { group: "maintenance", description: "Preview a local purge of an exact curated entry", args: [{ name: "id" }],
|
|
267
|
+
examples: ["amem purge <id>", "amem purge <id> --match-file matcher.txt"],
|
|
268
|
+
options: { ...json("the sealed purge preview"), "--match-file": path("Private file with literal capture and candidate text") } },
|
|
262
269
|
prune: { group: "maintenance", description: "Plan or apply exact-entry expiry in a generation", examples: ["amem prune --dry-run --cutoff 2026-01-01", "amem prune --apply --plan plan.json"], mutates: true,
|
|
263
270
|
options: { ...json("the prune plan or receipt"), "--cutoff": date("Canonical UTC expiry cutoff"), "--dry-run": flag("Print a local sealed plan without writes"),
|
|
264
271
|
"--user": flag("Select the user shard after a curated split", "Default: the current project."),
|
|
@@ -346,6 +353,10 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
|
|
|
346
353
|
&& (positionals[0] !== "agy" || ["--apply", "--undo", "--root", "--adopt-current", "--verbose"].some(flag => options[flag] !== undefined))) {
|
|
347
354
|
throw new CommandUsageError("usage: amem setup agy --list [--json]");
|
|
348
355
|
}
|
|
356
|
+
if (path[0] === "setup" && options["--refresh"] === true && options["--help"] !== true
|
|
357
|
+
&& (positionals[0] !== "agy" || ["--undo", "--list", "--verbose"].some(flag => options[flag] !== undefined))) {
|
|
358
|
+
throw new CommandUsageError("usage: amem setup agy --refresh [--root <abs path>] [--apply [--adopt-current]] [--json]");
|
|
359
|
+
}
|
|
349
360
|
const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
|
|
350
361
|
for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
|
|
351
362
|
const outputOptionIndexes = new Set<number>();
|
package/src/index.ts
CHANGED
|
@@ -46,7 +46,8 @@ export { pruneText } from "./memory/prune-text.ts";
|
|
|
46
46
|
export * from "./memory/shard-migration.ts";
|
|
47
47
|
export { shardMigrationText } from "./memory/shard-migration-text.ts";
|
|
48
48
|
|
|
49
|
-
export
|
|
49
|
+
export { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
|
|
50
|
+
export type { McpHandlers, McpOptions, McpToolName } from "./mcp.ts";
|
|
50
51
|
export * from "./mcp-memory.ts";
|
|
51
52
|
export * from "./memory/policy.ts";
|
|
52
53
|
export { configuredPolicy, recordsEnabled } from "./memory/config.ts";
|
|
@@ -99,3 +100,5 @@ export { readRecordInstruction, RECORD_INSTRUCTION_FILE } from "./memory/record-
|
|
|
99
100
|
export { groupByTask, taskGroupKey } from "./memory/task-group.ts";
|
|
100
101
|
|
|
101
102
|
export { SKILL_NAMES, installSkills, exportSkills, skillRoot, type SkillAction, type SkillInstallReport } from "./skills-install.ts";
|
|
103
|
+
// #680: read-only curated lookup by id for read-only hosts; its presence is the capability signal.
|
|
104
|
+
export { readCuratedEntries, READ_CURATED_MAX_IDS, type ReadCuratedEntriesOptions, type ReadCuratedEntriesResult } from "./memory/read-curated-entries.ts";
|