@staix/agent-mem 0.40.0 → 0.42.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 +172 -30
- package/src/commands-table.ts +16 -4
- package/src/index.ts +2 -1
- 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 +21 -5
- 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 +7 -1
- package/src/memory/formats-raise.ts +36 -15
- package/src/memory/formats.ts +26 -10
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/reader-lease.ts +37 -1
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +5 -3
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +27 -19
- package/src/memory/sync-placement-active.ts +67 -19
- package/src/memory/sync-placement-advertisement.ts +25 -3
- package/src/memory/sync-placement-checkpoint-person.ts +35 -13
- package/src/memory/sync-placement-effective-writers.ts +4 -3
- package/src/memory/sync-placement-guard.ts +29 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- 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 +28 -12
- package/src/memory/sync-placement-writer-listing.ts +90 -0
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +92 -21
- package/src/setup-writer-roots.ts +17 -3
- package/src/setup.ts +71 -11
- 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.42.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.42.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.4.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";
|
|
@@ -79,6 +80,7 @@ import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./
|
|
|
79
80
|
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";
|
|
83
|
+
import { listAgyReceiptLocations } from "./setup-drift.ts";
|
|
82
84
|
import { doctorReport } from "./memory/doctor.ts";
|
|
83
85
|
import { doctorText } from "./memory/doctor-text.ts";
|
|
84
86
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
@@ -182,6 +184,29 @@ function assertSpoolReplayArguments(path: readonly string[], options: Record<str
|
|
|
182
184
|
}
|
|
183
185
|
}
|
|
184
186
|
/** Realm admission receipts name hashes and counts only; the project key is the caller's own argument. */
|
|
187
|
+
function resolveAdmissionProject(home: string, cwd: string, input: string): string {
|
|
188
|
+
if (input === ".") {
|
|
189
|
+
try {
|
|
190
|
+
const directory = realPath(cwd);
|
|
191
|
+
const git = memoryGitSync(["-C", directory, "rev-parse", "--git-dir"], {
|
|
192
|
+
encoding: "utf8", env: memoryGitEnv(process.env, { repositoryIsolation: true }),
|
|
193
|
+
});
|
|
194
|
+
if (git.status !== 0 || !git.stdout.trim()) throw new Error("Git project unavailable");
|
|
195
|
+
return resolveAlias(home, memoryProjectKey(directory, { strictGitErrors: true, repositoryIsolation: true }));
|
|
196
|
+
} catch {
|
|
197
|
+
throw new AgentUsageError("--admit . requires a readable Git project in the current directory. Run from that project or pass its canonical project key.");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (!input || /^(?:\.\.?(?:[/\\]|$)|[/\\]|[a-z]:[/\\])/i.test(input)) {
|
|
201
|
+
throw new AgentUsageError("--admit requires a canonical project key. Run from the project and use --admit . to resolve it.");
|
|
202
|
+
}
|
|
203
|
+
if (/^github\.com\//i.test(input) && input !== input.toLowerCase()) {
|
|
204
|
+
const hint = /^github\.com\/[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(input) ? input.toLowerCase() : "github.com/<owner>/<repo>";
|
|
205
|
+
throw new AgentUsageError(`--admit requires a lowercase GitHub project key. Use ${hint}.`);
|
|
206
|
+
}
|
|
207
|
+
return input;
|
|
208
|
+
}
|
|
209
|
+
|
|
185
210
|
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 {
|
|
186
211
|
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"}`;
|
|
187
212
|
if (result.state === "admitted") return `; appended record ${result.sequence} ${result.headHash}${result.created ? "; wrote the realm's empty curated metadata first" : ""}`;
|
|
@@ -317,7 +342,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
|
|
|
317
342
|
|
|
318
343
|
/** Some commands write files despite having no mutates entry; preserve their existing effectful error/receipt treatment. */
|
|
319
344
|
function markedReadOnly(parsed: ReturnType<typeof parseCommand>): boolean {
|
|
320
|
-
return parsed.definition.mutates === undefined && parsed.path[0] !== "setup"
|
|
345
|
+
return parsed.definition.mutates === undefined && (parsed.path[0] !== "setup" || parsed.options["--list"] === true)
|
|
321
346
|
&& !(parsed.path[0] === "eval" && parsed.path[1] === "audit" && parsed.path[2] === "sample")
|
|
322
347
|
&& !(parsed.path[0] === "project" && parsed.path[1] === "export");
|
|
323
348
|
}
|
|
@@ -365,7 +390,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
365
390
|
if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
|
|
366
391
|
const parsed = parseCommand(argv);
|
|
367
392
|
// Audit outputs and review targets are screened whole for marked reads.
|
|
368
|
-
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") {
|
|
393
|
+
if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup" && parsed.options["--list"] !== true || parsed.path[0] === "eval" && parsed.path[1] === "audit" || parsed.path[0] === "review" && parsed.path[1] === "targets") {
|
|
369
394
|
let receipt: unknown = output;
|
|
370
395
|
// Import receipts contain fixed counters named `pii`; they are not row privacy flags.
|
|
371
396
|
// Screen the complete rendered receipt, including every key and value, as text.
|
|
@@ -407,13 +432,17 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
407
432
|
if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
|
|
408
433
|
// #578 Q3: a placement fence refusal is a fixed cause class and next step (no path, pid, row or project).
|
|
409
434
|
if (marked && error instanceof Error && error.name === "PlacementInventoryFenceError" && error instanceof (await import("./memory/sync-placement-activation-locks.ts")).PlacementInventoryFenceError) throw new Error(error.message);
|
|
435
|
+
if (marked && error instanceof Error && error.name === "RealmAdmissionError"
|
|
436
|
+
&& error instanceof (await import("./memory/sync-placement-realm-admission.ts")).RealmAdmissionError && error.causeClass === "busy") throw new Error(error.message);
|
|
410
437
|
const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
|
|
411
438
|
// #520/#551: a placement refusal keeps its fixed data - the receipt case its target and remedy, every other case its
|
|
412
439
|
// category, cause class and remedy - so a marked session prints that instead of the masked line. Every other placement
|
|
413
440
|
// and sync failure keeps the generic masked refusal below.
|
|
441
|
+
// #657: a deadline-stopped sync keeps its fixed numbers-only note on the refusal or masked line a marked session sees.
|
|
442
|
+
const deadline = marked ? markedDeadline(error) : undefined, withDeadline = (text: string) => deadline ? `${text} ${deadline}` : text;
|
|
414
443
|
if (marked) {
|
|
415
444
|
const refusal = (await import("./sync-placement-writer-context.ts")).placementWriterRefusalText(error);
|
|
416
|
-
if (refusal) throw new Error(refusal);
|
|
445
|
+
if (refusal) throw new Error(withDeadline(refusal));
|
|
417
446
|
}
|
|
418
447
|
if (marked) {
|
|
419
448
|
// parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
|
|
@@ -433,7 +462,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
433
462
|
}
|
|
434
463
|
}
|
|
435
464
|
// Marked administrative failures must not reveal a target's private state or native errors.
|
|
436
|
-
if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
|
|
465
|
+
if (marked) throw Error(withDeadline("Memory operation unavailable or refused; no partial result is shown."));
|
|
437
466
|
throw error;
|
|
438
467
|
}).then(output => {
|
|
439
468
|
// Preserve the value and the policy-screened result; only the JSON presentation changes.
|
|
@@ -471,7 +500,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
471
500
|
const originSession = captureSessionKey(env.AMEM_ORIGIN_SESSION), originPeer = env.AGENTHUB_PEER_ID?.trim() || undefined;
|
|
472
501
|
const constructDone = observeMcpPhase(base, peaks, "construct");
|
|
473
502
|
let memory: ReturnType<typeof createMemoryMcp>;
|
|
474
|
-
try { memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base, peaks,
|
|
503
|
+
try { memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base, peaks, boundSearchResults: true,
|
|
475
504
|
...(originSession || originPeer ? { origin: () => ({ ...(originSession ? { session: originSession } : {}), ...(originPeer ? { peer: originPeer } : {}) }) } : {}) }); } finally { constructDone(); }
|
|
476
505
|
await serveMcp({ tools: memory.tools, close: memory.close, onEmitted: memory.onEmitted, version: VERSION });
|
|
477
506
|
return "";
|
|
@@ -523,10 +552,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
523
552
|
const identity = cliAttribution() ?? { actor: "person" as const, peer: "person" }, actor = identity.actor;
|
|
524
553
|
if (parsed.path[0] === "migrate" && options["--sync-placement"] === true) {
|
|
525
554
|
const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
|
|
555
|
+
// #660: the saved-plan file and root discovery belong to the checkpoint preview only.
|
|
556
|
+
if ((options["--out"] !== undefined || options["--discovered-writers"] !== undefined)
|
|
557
|
+
&& (options["--checkpoint"] !== true || ["--confirm","--resume","--abandon","--json"].some(key => options[key] !== undefined && key !== "--json") || options["--discovered-writers"] !== undefined && options["--writer-root"] !== undefined))
|
|
558
|
+
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.");
|
|
526
559
|
if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
|
|
527
560
|
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.");
|
|
528
561
|
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))
|
|
529
562
|
throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
|
|
563
|
+
if (options["--writers"] === true && (modes.length || ["--admit","--list-remote","--from-remote","--writer-root","--confirm","--checkpoint","--checkpoint-on-bound","--plan"].some(key=>options[key]!==undefined)))
|
|
564
|
+
throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
|
|
530
565
|
if (options["--from-remote"] === true && options["--admit"] === undefined)
|
|
531
566
|
throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
|
|
532
567
|
if (options["--checkpoint-on-bound"] !== undefined) {
|
|
@@ -537,7 +572,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
537
572
|
const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
|
|
538
573
|
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)
|
|
539
574
|
|| (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
|
|
540
|
-
throw new AgentUsageError("A placement checkpoint previews with --sync-placement --checkpoint --writer-root <install root> (repeat), saves the plan with
|
|
575
|
+
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.");
|
|
541
576
|
} else if (options["--plan"] !== undefined) {
|
|
542
577
|
throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
|
|
543
578
|
} else if (options["--admit"] !== undefined) {
|
|
@@ -546,8 +581,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
546
581
|
} else if (options["--confirm"] === true) {
|
|
547
582
|
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.");
|
|
548
583
|
}
|
|
549
|
-
} else if (parsed.path[0] === "migrate" &&
|
|
550
|
-
throw new
|
|
584
|
+
} else if (parsed.path[0] === "migrate" && options["--writers"] !== undefined) {
|
|
585
|
+
throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
|
|
586
|
+
} 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)) {
|
|
587
|
+
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.");
|
|
551
588
|
}
|
|
552
589
|
if (parsed.path[0] === "skills" && parsed.path[1] === "export") {
|
|
553
590
|
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem skills export <dir> [--json]");
|
|
@@ -559,8 +596,37 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
559
596
|
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");
|
|
560
597
|
}
|
|
561
598
|
if (parsed.path[0] === "setup") {
|
|
599
|
+
if (options["--refresh"] === true) {
|
|
600
|
+
const { refreshAgyWorkspaces, agyRefreshText, setupMemoryHome } = await import("./setup.ts");
|
|
601
|
+
const mode = options["--apply"] === true ? "apply" : "preview", env = context.env ?? process.env;
|
|
602
|
+
const result = refreshAgyWorkspaces(mode, { env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY,
|
|
603
|
+
...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}), ...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}) });
|
|
604
|
+
if (result.workspaces.some(row => row.change === "refused")) context.onExitCode?.(1);
|
|
605
|
+
const output = options["--json"] === true ? JSON.stringify(result, null, 2) : agyRefreshText(result, mode);
|
|
606
|
+
if (actor === "agent") {
|
|
607
|
+
const policy = configuredPolicy(setupMemoryHome(env), context.cwd ?? process.cwd());
|
|
608
|
+
assertAgentAdministrative(result, policy);
|
|
609
|
+
assertAgentAdministrative(output, policy);
|
|
610
|
+
}
|
|
611
|
+
return output;
|
|
612
|
+
}
|
|
613
|
+
if (options["--list"] === true) {
|
|
614
|
+
const { setupMemoryHome } = await import("./setup.ts");
|
|
615
|
+
const home = setupMemoryHome(context.env ?? process.env);
|
|
616
|
+
const result = listAgyReceiptLocations(home);
|
|
617
|
+
const lines = result.receipts.flatMap(receipt => [`${receipt.state}: ${receipt.workspace}`, ` ${receipt.apply}`, ` ${receipt.undo}`]);
|
|
618
|
+
if (result.incomplete) lines.push("Some Antigravity setup receipts could not be listed safely.");
|
|
619
|
+
else if (!lines.length) lines.push("No Antigravity setup receipts found.");
|
|
620
|
+
const output = options["--json"] === true ? JSON.stringify(result, null, 2) : lines.join("\n");
|
|
621
|
+
if (actor === "agent") {
|
|
622
|
+
const policy = configuredPolicy(home, context.cwd ?? process.cwd());
|
|
623
|
+
assertAgentAdministrative(result, policy);
|
|
624
|
+
assertAgentAdministrative(output, policy);
|
|
625
|
+
}
|
|
626
|
+
return output;
|
|
627
|
+
}
|
|
562
628
|
if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
|
|
563
|
-
|| 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]");
|
|
629
|
+
|| 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]");
|
|
564
630
|
if (parsed.positionals[0] === "console") {
|
|
565
631
|
const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
|
|
566
632
|
const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
|
|
@@ -669,6 +735,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
669
735
|
if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
|
|
670
736
|
const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
|
|
671
737
|
if (options["--sync-placement"] === true) {
|
|
738
|
+
if (options["--writers"] === true) {
|
|
739
|
+
const { listPlacementWriters, placementWritersText } = await import("./memory/sync-placement-writer-listing.ts");
|
|
740
|
+
const listing = listPlacementWriters(memoryHome(), fileURLToPath(new URL("..", import.meta.url)), placementDiscovery(context));
|
|
741
|
+
return options["--json"] === true ? JSON.stringify(listing, null, 2) : placementWritersText(listing);
|
|
742
|
+
}
|
|
672
743
|
if (options["--list-remote"] === true) {
|
|
673
744
|
const { discoverRemotePlacementRealms } = await import("./memory/sync-placement-transport.ts");
|
|
674
745
|
const realms = await discoverRemotePlacementRealms(memoryHome(), { ...(context.visibility ? { visibility: context.visibility } : {}) });
|
|
@@ -682,14 +753,30 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
682
753
|
}
|
|
683
754
|
if (options["--checkpoint"] === true) {
|
|
684
755
|
const person = await import("./memory/sync-placement-checkpoint-person.ts");
|
|
685
|
-
const
|
|
686
|
-
// #
|
|
687
|
-
|
|
688
|
-
|
|
756
|
+
const ownRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
757
|
+
// #660: --discovered-writers measures the roots --writers suggests; the preview prints them before anything is confirmed.
|
|
758
|
+
const writerRoots = options["--discovered-writers"] === true
|
|
759
|
+
? (await import("./memory/sync-placement-writer-listing.ts")).listPlacementWriters(memoryHome(), ownRoot, placementDiscovery(context)).suggestedRoots
|
|
760
|
+
: repeated(argv, "--writer-root");
|
|
761
|
+
// Human output keeps the fixed refusal text. Classified JSON failures exit 1 and carry their safe own fields.
|
|
762
|
+
const checkpointRefusalJson = async (error: unknown): Promise<string> => {
|
|
689
763
|
if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "history" && error.history) {
|
|
690
764
|
context.onExitCode?.(1);
|
|
691
765
|
return JSON.stringify({ ok: false, refusal: error.history, message: error.message, nextStep: error.history.cause === "bound" ? "retain the history; a window this large needs the multi-plan checkpoint work (#288)" : person.CHECKPOINT_PREVIEW }, null, 2);
|
|
692
766
|
}
|
|
767
|
+
if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "writer-below-floor") {
|
|
768
|
+
context.onExitCode?.(1);
|
|
769
|
+
return JSON.stringify({ ok: false, refusal: { cause: error.causeClass }, message: error.message }, null, 2);
|
|
770
|
+
}
|
|
771
|
+
if (options["--json"] === true) {
|
|
772
|
+
const { placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
|
|
773
|
+
const refusal = placementWriterRefusalDetail(error);
|
|
774
|
+
const message = refusal && placementWriterRefusalText(error);
|
|
775
|
+
if (refusal && message) {
|
|
776
|
+
context.onExitCode?.(1);
|
|
777
|
+
return JSON.stringify({ ok: false, refusal: { category: refusal.rootCategory, cause: refusal.causeClass }, message }, null, 2);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
693
780
|
throw error;
|
|
694
781
|
};
|
|
695
782
|
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`; }
|
|
@@ -697,12 +784,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
697
784
|
if (options["--confirm"] === true) {
|
|
698
785
|
let saved: unknown;
|
|
699
786
|
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."); }
|
|
700
|
-
const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot }).catch(
|
|
787
|
+
const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot }).catch(checkpointRefusalJson);
|
|
701
788
|
if (typeof r === "string") return r;
|
|
702
789
|
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`;
|
|
703
790
|
}
|
|
704
|
-
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(
|
|
791
|
+
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(checkpointRefusalJson);
|
|
705
792
|
if (typeof preview === "string") return preview;
|
|
793
|
+
const out = typeof options["--out"] === "string" ? options["--out"] : undefined;
|
|
794
|
+
// A marked session's plan and its destination pass the policy screen before any file exists (#660).
|
|
795
|
+
if (out !== undefined) assertAgentAdministrative({ out, preview }, configuredPolicy(memoryHome(), context.cwd ?? process.cwd()));
|
|
796
|
+
if (out !== undefined) { writePrivatePlan(out, JSON.stringify(preview, null, 2) + "\n"); preview.nextStep = `${person.CHECKPOINT_PREVIEW} --confirm --plan ${shellQuoteArg(out)}`; }
|
|
706
797
|
if (options["--json"] === true) return JSON.stringify(preview, null, 2);
|
|
707
798
|
const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
|
|
708
799
|
// Counts and hashes only; the sealed plan itself is in --json for the confirm step.
|
|
@@ -711,11 +802,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
711
802
|
+ `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`
|
|
712
803
|
+ `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`
|
|
713
804
|
+ `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`
|
|
805
|
+
+ `writer roots measured:\n${preview.plan.writerRevision.roots.map(root => ` ${root.root}`).join("\n")}\n`
|
|
806
|
+
+ (out !== undefined ? `plan saved: ${out}\n` : "")
|
|
714
807
|
+ `next: ${preview.nextStep}\n`;
|
|
715
808
|
}
|
|
716
809
|
if (options["--admit"] !== undefined) {
|
|
717
810
|
const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
|
|
718
|
-
const project = String(options["--admit"]);
|
|
811
|
+
const project = resolveAdmissionProject(memoryHome(), context.cwd ?? process.cwd(), String(options["--admit"]));
|
|
719
812
|
const { readRemoteAdoption, inspectRemoteAdoptionPending, pendingRemoteAdoptions } = await import("./memory/sync-placement-remote-stage.ts");
|
|
720
813
|
const realm = createHash("sha256").update(project).digest("hex"), recovery = options["--resume"] === true || options["--abandon"] === true;
|
|
721
814
|
const pending = recovery ? pendingRemoteAdoptions(memoryHome()) : undefined;
|
|
@@ -800,11 +893,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
800
893
|
if ((readPlacementRuntimeMarkers(home).profile as { publicationFormat?: string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
801
894
|
try { for (const root of readEffectiveSyncPlacementWriterRoots(home)) add("sync-placement", root); } catch { incomplete.push("sync-placement writer roots unreadable"); }
|
|
802
895
|
}
|
|
896
|
+
let processArgs: string[] | undefined;
|
|
803
897
|
try {
|
|
804
|
-
const
|
|
805
|
-
for (const { pid, root, host } of runningAmemRoots(
|
|
898
|
+
const rows = processTable(context)();
|
|
899
|
+
for (const { pid, root, host } of runningAmemRoots(() => rows, context.embeddedAmem)) add(host ? "library-host" : "running", root, pid, host);
|
|
900
|
+
processArgs = rows.split("\n");
|
|
806
901
|
} catch { incomplete.push("running processes could not be listed"); }
|
|
807
|
-
return { writers: writers.sort((a, b) => a.source.localeCompare(b.source) || a.root.localeCompare(b.root) || (a.pid ?? 0) - (b.pid ?? 0)), incomplete };
|
|
902
|
+
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 } : {}) };
|
|
808
903
|
};
|
|
809
904
|
const now = context.now ? () => new Date(context.now!()) : undefined;
|
|
810
905
|
const plan = planFormatRaise(home, surface, minReader, inventory(), now);
|
|
@@ -815,11 +910,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
815
910
|
out.header("amem", "Format floor"); out.section("Preview"); out.bullet("pending", "Review the proposed floor before confirming.");
|
|
816
911
|
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"]]);
|
|
817
912
|
out.section("Writers", String(plan.writers.length));
|
|
818
|
-
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);
|
|
913
|
+
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);
|
|
819
914
|
else out.note("No writers found.");
|
|
915
|
+
// #660: a removed install cannot open this home, so it is shown but never counted as a writer below the floor.
|
|
916
|
+
if (plan.absent.length) out.note(`${plan.absent.length} removed install${plan.absent.length === 1 ? "" : "s"} (absent on disk, no live process) not counted.`);
|
|
820
917
|
if (refusal) { out.section("Attention"); out.bullet("warn", refusal); }
|
|
821
918
|
else out.next(`amem formats raise ${surface} ${minReader} --confirm`);
|
|
822
|
-
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");
|
|
919
|
+
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");
|
|
823
920
|
return screenedLegacy(legacy, out.render(s.color).join("\n"));
|
|
824
921
|
}
|
|
825
922
|
const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
|
|
@@ -1005,6 +1102,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1005
1102
|
}
|
|
1006
1103
|
if (input.kind === "model-answer") return `Model answer (not evidence; cannot accept, author an independent note with amem note add). ${input.text}`;
|
|
1007
1104
|
if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
|
|
1105
|
+
// #580: a topic correction shows the note it replaces beside the new text; several matches are listed for the person to pick.
|
|
1106
|
+
if (input.kind === "correction" && input.topic !== undefined) {
|
|
1107
|
+
const viewStore = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
1108
|
+
try {
|
|
1109
|
+
const target = viewStore.get(input.target.id, project);
|
|
1110
|
+
administrative({ candidate, target });
|
|
1111
|
+
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)";
|
|
1112
|
+
return `topic correction (${input.topic}). Old mem:${input.target.id}: ${old} New: ${input.proposedText} Reason: ${input.reason}`;
|
|
1113
|
+
} finally { viewStore.close(); }
|
|
1114
|
+
}
|
|
1115
|
+
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}`;
|
|
1008
1116
|
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}`
|
|
1009
1117
|
: input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
|
|
1010
1118
|
// #323 item 4: can the origin still be re-checked against capture? An expired session is reported as such, never as a failed check.
|
|
@@ -1555,7 +1663,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1555
1663
|
}
|
|
1556
1664
|
}
|
|
1557
1665
|
// 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).
|
|
1558
|
-
const stampSync = (error: string | undefined, cause?: StopCause) => { if (syncOutcome(error, cause) !== "local") recordSyncAttempt(syncHome, error === undefined, Date.now()); };
|
|
1666
|
+
const stampSync = (error: string | undefined, cause?: StopCause) => { if (syncOutcome(error, cause) !== "local") recordSyncAttempt(syncHome, error === undefined, Date.now(), cause === "deadline"); };
|
|
1667
|
+
// #657: a run the --if-due deadline stopped says so, and names the command that runs without one.
|
|
1668
|
+
const deadlineNote = (text: string, cause?: StopCause) => cause === "deadline" && !text.includes("--if-due stopped")
|
|
1669
|
+
? `${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;
|
|
1559
1670
|
const captureImport = sub === "import" && parsed.path[1] === "claude-mem", captureDays = options["--capture-days"] === undefined ? undefined : Number(options["--capture-days"]);
|
|
1560
1671
|
if (captureImport && captureDays !== undefined && (!Number.isSafeInteger(captureDays) || captureDays <= 0)) throw new Error("--capture-days takes a positive integer");
|
|
1561
1672
|
const captureArgs = new Set<number>();
|
|
@@ -1591,7 +1702,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1591
1702
|
const refusal = placementWriterRefusalText(error);
|
|
1592
1703
|
if (refusal === undefined || !options["--json"]) throw error;
|
|
1593
1704
|
stampSync(refusal, stop?.cause());
|
|
1594
|
-
|
|
1705
|
+
// #657: a deadline that already fired during setup keeps its note after the fixed refusal text.
|
|
1706
|
+
return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: deadlineNote(refusal, stop?.cause()) }, null, 2);
|
|
1595
1707
|
}
|
|
1596
1708
|
const attest = placementWriters.attest;
|
|
1597
1709
|
attestPlacement = () => {
|
|
@@ -1609,15 +1721,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1609
1721
|
}
|
|
1610
1722
|
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),
|
|
1611
1723
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1612
|
-
sync: { ...(attestPlacement ? { placementAttestation: attestPlacement, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: deterministicRowScreen(configuredPolicyOptions(memoryHome(), policyCwd)), policyVersion: (
|
|
1724
|
+
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
|
|
1613
1725
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1614
1726
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1615
1727
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
1616
1728
|
} catch (error) {
|
|
1617
1729
|
if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
|
|
1618
1730
|
if (sub === "sync") stampSync((error as Error).message, stop?.cause());
|
|
1619
|
-
|
|
1620
|
-
|
|
1731
|
+
const failure = sub === "sync" && placementWriters?.lastRefusal ? (await import("./sync-placement-writer-context.ts")).placementSyncFailure(placementWriters.lastRefusal, error) : error;
|
|
1732
|
+
if (sub === "sync" && failure instanceof Error && stop?.cause() === "deadline") withSyncDeadline(failure, deadlineNote("", "deadline").trim());
|
|
1733
|
+
throw failure;
|
|
1621
1734
|
}
|
|
1622
1735
|
finally {
|
|
1623
1736
|
// A run that never reached the transport's receipt (an early refusal) must not stay "running".
|
|
@@ -1634,7 +1747,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1634
1747
|
const result = JSON.parse(output) as { ok?: unknown; error?: unknown };
|
|
1635
1748
|
if (result.ok === false) {
|
|
1636
1749
|
failure = typeof result.error === "string" ? result.error : "sync failed";
|
|
1637
|
-
if (placementWriters?.lastRefusal)
|
|
1750
|
+
if (placementWriters?.lastRefusal) result.error = `${placementWriters.lastRefusal.message} ${failure}`;
|
|
1751
|
+
if (stop?.cause() === "deadline") result.error = deadlineNote(String(result.error ?? failure), "deadline");
|
|
1752
|
+
if (placementWriters?.lastRefusal || stop?.cause() === "deadline") output = JSON.stringify(result,null,2);
|
|
1638
1753
|
}
|
|
1639
1754
|
} catch { /* not a sync result */ } }
|
|
1640
1755
|
stampSync(failure, stop?.cause());
|
|
@@ -1653,6 +1768,33 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1653
1768
|
? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
|
|
1654
1769
|
}
|
|
1655
1770
|
|
|
1771
|
+
/** #657: appends the deadline note to a sync failure and carries it, numbers only, for a marked session's fixed text. */
|
|
1772
|
+
export function withSyncDeadline<T extends Error>(error: T, note: string): T {
|
|
1773
|
+
if (!error.message.includes(note)) error.message = `${error.message} ${note}`;
|
|
1774
|
+
Object.defineProperty(error, "syncDeadlineNote", { value: note }); return error;
|
|
1775
|
+
}
|
|
1776
|
+
/** The deadline note a sync failure carries as an own property, accepted only in its fixed numbers-only form. */
|
|
1777
|
+
export function markedDeadline(error: unknown): string | undefined {
|
|
1778
|
+
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
1779
|
+
const note: unknown = Object.getOwnPropertyDescriptor(error, "syncDeadlineNote")?.value;
|
|
1780
|
+
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;
|
|
1781
|
+
}
|
|
1782
|
+
/** #660: the checkpoint preview saved for its confirm step: a new private file, never an existing path or a link, synced before return. */
|
|
1783
|
+
function writePrivatePlan(file: string, text: string): void {
|
|
1784
|
+
let fd: number;
|
|
1785
|
+
try { fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
1786
|
+
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.`); }
|
|
1787
|
+
try { writeSync(fd, text); fsyncSync(fd); } finally { closeSync(fd); }
|
|
1788
|
+
}
|
|
1789
|
+
const shellQuoteArg = (value: string) => /^[A-Za-z0-9_./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
1790
|
+
/** The `pid args` process table `formats raise` and `--writers` read; `context.processTable` is the test seam. */
|
|
1791
|
+
function processTable(context: CliContext): () => string {
|
|
1792
|
+
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);
|
|
1793
|
+
}
|
|
1794
|
+
/** #660: what `--writers` and `--discovered-writers` search for library hosts: live processes and ahub/vmem on PATH. */
|
|
1795
|
+
function placementDiscovery(context: CliContext): import("./memory/sync-placement-writer-listing.ts").PlacementWriterDiscovery {
|
|
1796
|
+
return { table: processTable(context), ...(context.embeddedAmem ? { embedded: context.embeddedAmem } : {}), path: (context.env ?? process.env).PATH ?? "" };
|
|
1797
|
+
}
|
|
1656
1798
|
/** Color for human output only on an interactive stdout without NO_COLOR or TERM=dumb (#125). */
|
|
1657
1799
|
/**
|
|
1658
1800
|
* #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
|
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"],
|
|
52
|
-
options: { ...json("the setup plan"), "--
|
|
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.") },
|
|
@@ -237,13 +238,16 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
237
238
|
"--public-prune-view": flag("Enable the v2 public prune view on a split", "Forward-only, on an active split."),
|
|
238
239
|
"--sync-placement": flag("Activate placement sync on this memory home", "Forward-only. Previews by default and applies with --apply; no automatic migration or renewal."),
|
|
239
240
|
"--list-remote": flag("List remote project refs outside the inventory", "By hash, outside the active inventory."),
|
|
241
|
+
"--writers": flag("List writer installs and the roots to declare", "Read-only: inventory, running install, setup receipts and the saving-preview command."),
|
|
240
242
|
"--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."),
|
|
241
|
-
"--admit": text("Admit one new curated project realm", "A realm that appeared after activation, into the same epoch. Previews without --apply."),
|
|
243
|
+
"--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."),
|
|
242
244
|
"--from-remote": flag("Admit the named remote-only realm", "Uses the configured placement sync remote."),
|
|
243
245
|
"--confirm": flag("Confirm the previewed abandonment or checkpoint"),
|
|
244
246
|
"--checkpoint": flag("Preview a placement checkpoint", "Person-reviewed: preview by default, then --confirm --plan, --resume or --abandon."),
|
|
245
247
|
"--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." },
|
|
246
|
-
"--plan": path("Saved --checkpoint
|
|
248
|
+
"--plan": path("Saved --checkpoint preview to confirm", "The plan names its writer roots; --writer-root is then optional and must match it."),
|
|
249
|
+
"--out": path("Save the checkpoint preview to a new 0600 file", "Checkpoint preview only; refuses an existing path or a link."),
|
|
250
|
+
"--discovered-writers": flag("Measure the roots --writers suggests", "Checkpoint preview only, instead of --writer-root; the preview prints every measured root."),
|
|
247
251
|
"--writer-root": path("Writer inventory install root (repeatable)", "An absolute amem install root; repeat it for the complete local writer inventory."),
|
|
248
252
|
} },
|
|
249
253
|
status: { group: "read", description: "Show the memory home, policy and migration state", examples: ["amem status", "amem status --verbose"],
|
|
@@ -341,6 +345,14 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
|
|
|
341
345
|
const argument = definition.args?.[i];
|
|
342
346
|
if (argument?.values && !argument.values.includes(positionals[i]!)) throw new CommandUsageError(`${argument.name} takes ${argument.values.join(" or ")}`);
|
|
343
347
|
}
|
|
348
|
+
if (path[0] === "setup" && options["--list"] === true && options["--help"] !== true
|
|
349
|
+
&& (positionals[0] !== "agy" || ["--apply", "--undo", "--root", "--adopt-current", "--verbose"].some(flag => options[flag] !== undefined))) {
|
|
350
|
+
throw new CommandUsageError("usage: amem setup agy --list [--json]");
|
|
351
|
+
}
|
|
352
|
+
if (path[0] === "setup" && options["--refresh"] === true && options["--help"] !== true
|
|
353
|
+
&& (positionals[0] !== "agy" || ["--undo", "--list", "--verbose"].some(flag => options[flag] !== undefined))) {
|
|
354
|
+
throw new CommandUsageError("usage: amem setup agy --refresh [--root <abs path>] [--apply [--adopt-current]] [--json]");
|
|
355
|
+
}
|
|
344
356
|
const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
|
|
345
357
|
for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
|
|
346
358
|
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";
|