@staix/agent-mem 0.40.0 → 0.41.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 +1 -1
- package/package.json +1 -1
- package/src/cli.ts +45 -8
- package/src/commands-table.ts +7 -2
- package/src/memory/doctor-text.ts +4 -1
- package/src/memory/reader-lease.ts +37 -1
- package/src/memory/sync-placement-checkpoint-person.ts +37 -9
- package/src/memory/sync-placement-writer-listing.ts +65 -0
- package/src/setup-drift.ts +61 -20
- package/src/setup-writer-roots.ts +17 -3
- package/src/setup.ts +5 -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.41.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -79,6 +79,7 @@ import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./
|
|
|
79
79
|
import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
|
|
80
80
|
import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
|
|
81
81
|
import { runEditor } from "./memory/editor.ts";
|
|
82
|
+
import { listAgyReceiptLocations } from "./setup-drift.ts";
|
|
82
83
|
import { doctorReport } from "./memory/doctor.ts";
|
|
83
84
|
import { doctorText } from "./memory/doctor-text.ts";
|
|
84
85
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
@@ -317,7 +318,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
|
|
|
317
318
|
|
|
318
319
|
/** Some commands write files despite having no mutates entry; preserve their existing effectful error/receipt treatment. */
|
|
319
320
|
function markedReadOnly(parsed: ReturnType<typeof parseCommand>): boolean {
|
|
320
|
-
return parsed.definition.mutates === undefined && parsed.path[0] !== "setup"
|
|
321
|
+
return parsed.definition.mutates === undefined && (parsed.path[0] !== "setup" || parsed.options["--list"] === true)
|
|
321
322
|
&& !(parsed.path[0] === "eval" && parsed.path[1] === "audit" && parsed.path[2] === "sample")
|
|
322
323
|
&& !(parsed.path[0] === "project" && parsed.path[1] === "export");
|
|
323
324
|
}
|
|
@@ -365,7 +366,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
365
366
|
if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
|
|
366
367
|
const parsed = parseCommand(argv);
|
|
367
368
|
// 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") {
|
|
369
|
+
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
370
|
let receipt: unknown = output;
|
|
370
371
|
// Import receipts contain fixed counters named `pii`; they are not row privacy flags.
|
|
371
372
|
// Screen the complete rendered receipt, including every key and value, as text.
|
|
@@ -527,6 +528,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
527
528
|
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
529
|
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
530
|
throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
|
|
531
|
+
if (options["--writers"] === true && (modes.length || ["--admit","--list-remote","--from-remote","--writer-root","--confirm","--checkpoint","--checkpoint-on-bound","--plan"].some(key=>options[key]!==undefined)))
|
|
532
|
+
throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
|
|
530
533
|
if (options["--from-remote"] === true && options["--admit"] === undefined)
|
|
531
534
|
throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
|
|
532
535
|
if (options["--checkpoint-on-bound"] !== undefined) {
|
|
@@ -546,6 +549,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
546
549
|
} else if (options["--confirm"] === true) {
|
|
547
550
|
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
551
|
}
|
|
552
|
+
} else if (parsed.path[0] === "migrate" && options["--writers"] !== undefined) {
|
|
553
|
+
throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
|
|
549
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)) {
|
|
550
555
|
throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --plan apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
|
|
551
556
|
}
|
|
@@ -559,8 +564,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
559
564
|
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
565
|
}
|
|
561
566
|
if (parsed.path[0] === "setup") {
|
|
567
|
+
if (options["--list"] === true) {
|
|
568
|
+
const { setupMemoryHome } = await import("./setup.ts");
|
|
569
|
+
const home = setupMemoryHome(context.env ?? process.env);
|
|
570
|
+
const result = listAgyReceiptLocations(home);
|
|
571
|
+
const lines = result.receipts.flatMap(receipt => [`${receipt.state}: ${receipt.workspace}`, ` ${receipt.apply}`, ` ${receipt.undo}`]);
|
|
572
|
+
if (result.incomplete) lines.push("Some Antigravity setup receipts could not be listed safely.");
|
|
573
|
+
else if (!lines.length) lines.push("No Antigravity setup receipts found.");
|
|
574
|
+
const output = options["--json"] === true ? JSON.stringify(result, null, 2) : lines.join("\n");
|
|
575
|
+
if (actor === "agent") {
|
|
576
|
+
const policy = configuredPolicy(home, context.cwd ?? process.cwd());
|
|
577
|
+
assertAgentAdministrative(result, policy);
|
|
578
|
+
assertAgentAdministrative(output, policy);
|
|
579
|
+
}
|
|
580
|
+
return output;
|
|
581
|
+
}
|
|
562
582
|
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]");
|
|
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]");
|
|
564
584
|
if (parsed.positionals[0] === "console") {
|
|
565
585
|
const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
|
|
566
586
|
const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
|
|
@@ -669,6 +689,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
669
689
|
if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
|
|
670
690
|
const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
|
|
671
691
|
if (options["--sync-placement"] === true) {
|
|
692
|
+
if (options["--writers"] === true) {
|
|
693
|
+
const { listPlacementWriters, placementWritersText } = await import("./memory/sync-placement-writer-listing.ts");
|
|
694
|
+
const listing = listPlacementWriters(memoryHome(), fileURLToPath(new URL("..", import.meta.url)));
|
|
695
|
+
return options["--json"] === true ? JSON.stringify(listing, null, 2) : placementWritersText(listing);
|
|
696
|
+
}
|
|
672
697
|
if (options["--list-remote"] === true) {
|
|
673
698
|
const { discoverRemotePlacementRealms } = await import("./memory/sync-placement-transport.ts");
|
|
674
699
|
const realms = await discoverRemotePlacementRealms(memoryHome(), { ...(context.visibility ? { visibility: context.visibility } : {}) });
|
|
@@ -683,13 +708,25 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
683
708
|
if (options["--checkpoint"] === true) {
|
|
684
709
|
const person = await import("./memory/sync-placement-checkpoint-person.ts");
|
|
685
710
|
const writerRoots = repeated(argv, "--writer-root"), ownRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
686
|
-
//
|
|
687
|
-
|
|
688
|
-
const historyJson = (error: unknown): string => {
|
|
711
|
+
// Human output keeps the fixed refusal text. Classified JSON failures exit 1 and carry their safe own fields.
|
|
712
|
+
const checkpointRefusalJson = async (error: unknown): Promise<string> => {
|
|
689
713
|
if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "history" && error.history) {
|
|
690
714
|
context.onExitCode?.(1);
|
|
691
715
|
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
716
|
}
|
|
717
|
+
if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "writer-below-floor") {
|
|
718
|
+
context.onExitCode?.(1);
|
|
719
|
+
return JSON.stringify({ ok: false, refusal: { cause: error.causeClass }, message: error.message }, null, 2);
|
|
720
|
+
}
|
|
721
|
+
if (options["--json"] === true) {
|
|
722
|
+
const { placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
|
|
723
|
+
const refusal = placementWriterRefusalDetail(error);
|
|
724
|
+
const message = refusal && placementWriterRefusalText(error);
|
|
725
|
+
if (refusal && message) {
|
|
726
|
+
context.onExitCode?.(1);
|
|
727
|
+
return JSON.stringify({ ok: false, refusal: { category: refusal.rootCategory, cause: refusal.causeClass }, message }, null, 2);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
693
730
|
throw error;
|
|
694
731
|
};
|
|
695
732
|
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,11 +734,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
697
734
|
if (options["--confirm"] === true) {
|
|
698
735
|
let saved: unknown;
|
|
699
736
|
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(
|
|
737
|
+
const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot }).catch(checkpointRefusalJson);
|
|
701
738
|
if (typeof r === "string") return r;
|
|
702
739
|
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
740
|
}
|
|
704
|
-
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(
|
|
741
|
+
const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(checkpointRefusalJson);
|
|
705
742
|
if (typeof preview === "string") return preview;
|
|
706
743
|
if (options["--json"] === true) return JSON.stringify(preview, null, 2);
|
|
707
744
|
const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
|
package/src/commands-table.ts
CHANGED
|
@@ -48,8 +48,8 @@ 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"), "--apply": flag("Apply the previewed setup"), "--undo": flag("Restore the original configuration"),
|
|
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."), "--apply": flag("Apply the previewed setup"), "--undo": flag("Restore the original configuration"),
|
|
53
53
|
"--verbose": flag("Show static notes and history lines (human output only)"),
|
|
54
54
|
"--root": path("Register this absolute install root", "Such as <install>/releases/<version>/, resolved to its real path, instead of the running one."),
|
|
55
55
|
"--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,6 +237,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
237
237
|
"--public-prune-view": flag("Enable the v2 public prune view on a split", "Forward-only, on an active split."),
|
|
238
238
|
"--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
239
|
"--list-remote": flag("List remote project refs outside the inventory", "By hash, outside the active inventory."),
|
|
240
|
+
"--writers": flag("List writer installs and the roots to declare", "Read-only: inventory, running install, setup receipts and the saving-preview command."),
|
|
240
241
|
"--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
242
|
"--admit": text("Admit one new curated project realm", "A realm that appeared after activation, into the same epoch. Previews without --apply."),
|
|
242
243
|
"--from-remote": flag("Admit the named remote-only realm", "Uses the configured placement sync remote."),
|
|
@@ -341,6 +342,10 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
|
|
|
341
342
|
const argument = definition.args?.[i];
|
|
342
343
|
if (argument?.values && !argument.values.includes(positionals[i]!)) throw new CommandUsageError(`${argument.name} takes ${argument.values.join(" or ")}`);
|
|
343
344
|
}
|
|
345
|
+
if (path[0] === "setup" && options["--list"] === true && options["--help"] !== true
|
|
346
|
+
&& (positionals[0] !== "agy" || ["--apply", "--undo", "--root", "--adopt-current", "--verbose"].some(flag => options[flag] !== undefined))) {
|
|
347
|
+
throw new CommandUsageError("usage: amem setup agy --list [--json]");
|
|
348
|
+
}
|
|
344
349
|
const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
|
|
345
350
|
for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
|
|
346
351
|
const outputOptionIndexes = new Set<number>();
|
|
@@ -60,7 +60,10 @@ export function hintFinding(name: string, hint: string, section: Record<string,
|
|
|
60
60
|
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
61
61
|
const reason = String(section.reason ?? "");
|
|
62
62
|
// #624: the checkpoint renewal comes first. Its saving preview is a subshell, so the finding names the bare checkpoint command; the reason keeps the saving form.
|
|
63
|
-
const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:checkpoint|dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
63
|
+
const commands = reason.includes("amem setup agy --list") ? ["amem setup agy --list"] : [...reason.matchAll(/amem (?:migrate --sync-placement --(?:checkpoint|dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
64
|
+
// #639: a renewal needs the complete root list, so the read-only listing that prints it comes first. A stale agy receipt
|
|
65
|
+
// (#636) is fixed first, so its single command stays alone.
|
|
66
|
+
if (commands.includes("amem migrate --sync-placement --checkpoint")) commands.unshift("amem migrate --sync-placement --writers");
|
|
64
67
|
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
65
68
|
}
|
|
66
69
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { lstatSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
3
|
import { readProfileJSON, writeProfileJSON } from "./generation.ts";
|
|
4
4
|
import { readerAdmissionDatabase } from "./mutation.ts";
|
|
5
5
|
import { processLiveness, processSignature, realPath } from "./platform.ts";
|
|
@@ -48,6 +48,40 @@ function ownedLease(memoryDir: string, file: string, signature: string, scope: L
|
|
|
48
48
|
if (!lease || lease.pid !== process.pid || lease.signature !== signature) throw new Error("reader lease ownership is unavailable");
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/** #632: how many lease names one registration scans; later registrations clear what a large backlog leaves. */
|
|
52
|
+
const GONE_LEASE_SCAN_LIMIT = 256;
|
|
53
|
+
|
|
54
|
+
/** One syscall, no identity probe: only ESRCH proves the recorded process is gone. */
|
|
55
|
+
function pidIsGone(pid: number): boolean {
|
|
56
|
+
try { process.kill(pid, 0); return false; }
|
|
57
|
+
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** #632: a registration clears leases of processes that are provably gone in its own scope, so doctor's
|
|
61
|
+
* `readers` attention state does not need a migration. The caller holds the admission fence, and each
|
|
62
|
+
* candidate is re-read there: a pid that exists (reused included), an unreadable or unverifiable file,
|
|
63
|
+
* a link or any non-regular file stays exactly as it is, and nothing here throws. Migration admission
|
|
64
|
+
* keeps its pid-plus-signature test, which is what clears a reused pid's lease. */
|
|
65
|
+
function removeGoneLeases(memoryDir: string, scope: LeaseScope, own: string): void {
|
|
66
|
+
const dir = join(memoryDir, leaseFolder(scope));
|
|
67
|
+
let names: string[];
|
|
68
|
+
try { names = readdirSync(dir).filter(name => name.endsWith(".json")).sort().slice(0, GONE_LEASE_SCAN_LIMIT); }
|
|
69
|
+
catch { return; }
|
|
70
|
+
for (const name of names) {
|
|
71
|
+
if (name === own) continue;
|
|
72
|
+
const file = join(dir, name);
|
|
73
|
+
try {
|
|
74
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
75
|
+
if (!stat || !stat.isFile()) continue;
|
|
76
|
+
const lease = readLease(memoryDir, file, scope);
|
|
77
|
+
if (!lease || !pidIsGone(lease.pid)) continue;
|
|
78
|
+
const again = readLease(memoryDir, file, scope);
|
|
79
|
+
if (!again || again.pid !== lease.pid) continue;
|
|
80
|
+
rmSync(file);
|
|
81
|
+
} catch { /* unreadable or unverifiable evidence, or a file that moved under us, stays as it is */ }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
51
85
|
function admitReader(memoryDir: string): void {
|
|
52
86
|
// The profile lock is created under the same reader admission fence, then held across migration awaits.
|
|
53
87
|
// Even a malformed or stale marker refuses admission; only the profile-lock owner may reclaim it.
|
|
@@ -89,6 +123,8 @@ export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?
|
|
|
89
123
|
}
|
|
90
124
|
const dir = checkReadersDir(memoryDir, scope);
|
|
91
125
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
126
|
+
// #632: a first registration for this file clears leases of provably gone processes; nested readers returned above.
|
|
127
|
+
removeGoneLeases(memoryDir, scope, basename(file));
|
|
92
128
|
// A failed earlier close may have retained evidence. Never overwrite an unverifiable replacement.
|
|
93
129
|
const existing = readLease(memoryDir, file, scope);
|
|
94
130
|
if (existing && (existing.pid !== process.pid || existing.signature !== signature)) throw new Error("reader lease ownership is unavailable");
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* person-written floor record (`amem formats raise` is the one writer).
|
|
5
5
|
*/
|
|
6
6
|
import { randomBytes } from "node:crypto";
|
|
7
|
+
import { lstatSync } from "node:fs";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
9
|
import { types } from "node:util";
|
|
9
10
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
@@ -25,7 +26,7 @@ import { PLACEMENT_CHECKPOINT_LIMIT, PLACEMENT_CHECKPOINT_MIN_READER, validateCh
|
|
|
25
26
|
import { withPlacementCheckpointFences } from "./sync-placement-activation-locks.ts";
|
|
26
27
|
import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
27
28
|
import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
|
|
28
|
-
import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
|
|
29
|
+
import { initialPlacementWriterContext, placementWriterRefusalDetail } from "../sync-placement-writer-context.ts";
|
|
29
30
|
import { readSetupWriterRoots, SetupWriterRootsError } from "../setup-writer-roots.ts";
|
|
30
31
|
import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
|
|
31
32
|
import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
|
|
@@ -35,7 +36,7 @@ const RESUME = `${CHECKPOINT_PREVIEW} --resume`, ABANDON = `${CHECKPOINT_PREVIEW
|
|
|
35
36
|
const homeFloorAtLeast = (home: string, minimum: string): boolean =>
|
|
36
37
|
(readFormatFloors(home) ?? []).some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, minimum));
|
|
37
38
|
|
|
38
|
-
export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history";
|
|
39
|
+
export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history" | "writer-missing";
|
|
39
40
|
const MESSAGES: Record<PlacementCheckpointCause, string> = {
|
|
40
41
|
pending: PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
|
|
41
42
|
"commit-started": `The placement checkpoint's commit line has started, so it can no longer be abandoned; run ${RESUME} to complete it.`,
|
|
@@ -45,8 +46,9 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
|
|
|
45
46
|
obligation: "The placement journal has an unfinished append, publication, reservation, renewal or source recovery; finish it with amem sync (or the pending renewal with amem migrate --sync-placement --resume), then preview the checkpoint again.",
|
|
46
47
|
changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
|
|
47
48
|
inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
|
|
48
|
-
candidate: `A checkpoint carries one writer renewal: pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
|
|
49
|
+
candidate: `A checkpoint carries one writer renewal: list the inventory and the roots to declare with amem migrate --sync-placement --writers, then pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
|
|
49
50
|
history: "",
|
|
51
|
+
"writer-missing": "",
|
|
50
52
|
};
|
|
51
53
|
/** #567: the retained-history cause class and, for `bound`, which bound with its counts. Never a path, row or object id. */
|
|
52
54
|
export interface PlacementCheckpointHistoryRefusal { category: "shard history"; cause: ShardHistoryCause; kind?: string; limit?: number; observed?: number }
|
|
@@ -62,7 +64,7 @@ export class PlacementCheckpointError extends Error {
|
|
|
62
64
|
readonly history?: PlacementCheckpointHistoryRefusal;
|
|
63
65
|
constructor(readonly causeClass: PlacementCheckpointCause, detail = "", history?: PlacementCheckpointHistoryRefusal) {
|
|
64
66
|
super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.`
|
|
65
|
-
: causeClass === "history" && history ? historyMessage(history) : MESSAGES[causeClass]
|
|
67
|
+
: causeClass === "history" && history ? historyMessage(history) : [MESSAGES[causeClass], detail].filter(Boolean).join(" "));
|
|
66
68
|
this.name = "PlacementCheckpointError";
|
|
67
69
|
if (causeClass === "history" && history) this.history = history;
|
|
68
70
|
}
|
|
@@ -86,10 +88,17 @@ function input(home: string, a: ActivePlacementBinding, roots: PlacementCheckpoi
|
|
|
86
88
|
}
|
|
87
89
|
function measured(home: string, writerRoots: readonly string[], ownRoot: string): PlacementCheckpointInput["roots"] {
|
|
88
90
|
if (!writerRoots.length) throw new PlacementCheckpointError("candidate");
|
|
89
|
-
|
|
91
|
+
// #634: name a removed install before measurement turns it into a generic inventory refusal; preview and confirm both pass here.
|
|
92
|
+
const missing = writerRoots.find(installAbsent);
|
|
93
|
+
if (missing !== undefined) throw new PlacementCheckpointError("writer-missing", missingWriterMessage(missing));
|
|
94
|
+
try { return initialPlacementWriterContext(home, writerRoots, ownRoot).measurement.roots; }
|
|
95
|
+
catch (error) {
|
|
96
|
+
const refusal = placementWriterRefusalDetail(error);
|
|
97
|
+
if (refusal && !(refusal.rootCategory === "running CLI" && refusal.causeClass === "missing")) throw error;
|
|
98
|
+
throw new PlacementCheckpointError("candidate");
|
|
99
|
+
}
|
|
90
100
|
}
|
|
91
101
|
function plan(home: string, epochHash: string, value: PlacementCheckpointInput): CheckpointIntent {
|
|
92
|
-
if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
|
|
93
102
|
try { return planPlacementCheckpoint(home, epochHash, value); }
|
|
94
103
|
catch (error) {
|
|
95
104
|
const code = error instanceof SyncPlacementJournalError ? Object.getOwnPropertyDescriptor(error, "code")?.value : undefined;
|
|
@@ -119,7 +128,10 @@ export interface PlacementCheckpointPreview {
|
|
|
119
128
|
*/
|
|
120
129
|
export async function previewPlacementCheckpoint(homeInput: string, opts: { writerRoots: readonly string[]; ownRoot: string }): Promise<PlacementCheckpointPreview> {
|
|
121
130
|
const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
|
|
122
|
-
const roots = measured(home, opts.writerRoots, opts.ownRoot)
|
|
131
|
+
const roots = measured(home, opts.writerRoots, opts.ownRoot);
|
|
132
|
+
if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
|
|
133
|
+
checkWriterVersions(home, roots);
|
|
134
|
+
const intent = plan(home, epochHash, input(home, a, roots, randomBytes(32).toString("hex")));
|
|
123
135
|
const journal = readPlacementJournal(home, epochHash), window = resolvePlacementWindow(home, epochHash);
|
|
124
136
|
const { headroom, journalObjects, assertCurrent } = await checkpointHeadroom(home, intent);
|
|
125
137
|
assertCurrent();
|
|
@@ -167,13 +179,29 @@ function reviewedHeadroom(value: unknown): unknown {
|
|
|
167
179
|
if (!detached) throw new PlacementCheckpointError("changed");
|
|
168
180
|
return detached;
|
|
169
181
|
}
|
|
182
|
+
/**
|
|
183
|
+
* #634: an install whose root no longer exists (ENOENT or ENOTDIR on the root itself). An existing root with a missing or
|
|
184
|
+
* unreadable package.json is not absent: it can still run, so the floor check keeps refusing it.
|
|
185
|
+
*/
|
|
186
|
+
function installAbsent(root: string): boolean {
|
|
187
|
+
try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
|
|
188
|
+
}
|
|
189
|
+
function missingWriterMessage(root: string): string {
|
|
190
|
+
return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with (umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list.`;
|
|
191
|
+
}
|
|
170
192
|
function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
|
|
171
193
|
if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
|
|
172
194
|
// This reader itself below the recorded floor cannot measure anything: name the writer cause, not the inventory.
|
|
173
195
|
try { assertFormatFloor(home, "sync"); } catch { throw new PlacementCheckpointError("writer-below-floor"); }
|
|
174
|
-
if (
|
|
196
|
+
if (roots) checkWriterVersions(home, roots);
|
|
197
|
+
}
|
|
198
|
+
function checkWriterVersions(home: string, roots: PlacementCheckpointInput["roots"]): void {
|
|
175
199
|
const effective = readEffectiveSyncPlacementWriters(home).roots ?? [];
|
|
176
|
-
|
|
200
|
+
// #634: an inventoried install that is gone from disk and left out of the new plan can no longer write here; the
|
|
201
|
+
// renewal removes it. A root the new plan measures is checked through its measured version.
|
|
202
|
+
const renewed = new Set(roots.map(root => root.root));
|
|
203
|
+
const retained = effective.filter(root => !renewed.has(root) && !installAbsent(root));
|
|
204
|
+
const versions = [...roots.map(root => root.version), ...retained.map(root => installVersion(root))];
|
|
177
205
|
const floors = (readFormatFloors(home) ?? []).filter(floor => floor.surface === "home" || floor.surface === "sync");
|
|
178
206
|
if (versions.some(version => version === null || floors.some(floor => formatVersionBelow(version, floor.minReader)))) throw new PlacementCheckpointError("writer-below-floor");
|
|
179
207
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #639: a read-only listing of the placement writer inventory and the install roots a renewal must declare. It writes
|
|
3
|
+
* nothing, takes no lock and never searches the filesystem for installs; it only reads the active inventory, the running
|
|
4
|
+
* install and the setup receipts, then suggests the present roots and the #625 saving-preview command built from them.
|
|
5
|
+
*/
|
|
6
|
+
import { lstatSync } from "node:fs";
|
|
7
|
+
import { realPath } from "./platform.ts";
|
|
8
|
+
import { installVersion } from "./formats-raise.ts";
|
|
9
|
+
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
10
|
+
import { readSetupWriterLaunchers, type SetupTarget } from "../setup-writer-roots.ts";
|
|
11
|
+
|
|
12
|
+
export const PLACEMENT_WRITERS_LISTING = "amem migrate --sync-placement --writers";
|
|
13
|
+
export const PLACEMENT_WRITERS_SCHEMA = "amem.placement-writers/v1";
|
|
14
|
+
export const PLACEMENT_WRITERS_NOTE = "Installs bundled inside other tools (agent-hub, vault-mem) appear here only when they are already in the inventory or a setup receipt; add a newly upgraded host bundle with another --writer-root.";
|
|
15
|
+
|
|
16
|
+
export interface PlacementWriterListing {
|
|
17
|
+
schema: typeof PLACEMENT_WRITERS_SCHEMA;
|
|
18
|
+
inventory: { root: string; version: string | null; state: "present" | "missing" }[];
|
|
19
|
+
running: { root: string; version: string | null; inInventory: boolean };
|
|
20
|
+
receipts: { target: SetupTarget; root: string; state: "present" | "missing" }[];
|
|
21
|
+
suggestedRoots: string[];
|
|
22
|
+
command: string;
|
|
23
|
+
note: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ponytail: the same ENOENT/ENOTDIR test as the checkpoint's installAbsent (#634); one shared helper once #448 settles that file.
|
|
27
|
+
function absent(root: string): boolean {
|
|
28
|
+
try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
|
|
29
|
+
}
|
|
30
|
+
/** POSIX single-quote shell quoting: the printed command is pasted into a shell as is. */
|
|
31
|
+
export function shellQuote(value: string): string {
|
|
32
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
33
|
+
}
|
|
34
|
+
export function placementWriterCommand(roots: readonly string[]): string {
|
|
35
|
+
const flags = roots.map(root => `--writer-root ${shellQuote(root)}`).join(" ");
|
|
36
|
+
return `(umask 077; set -C; amem migrate --sync-placement --checkpoint ${flags} --json > checkpoint-plan.json), then amem migrate --sync-placement --checkpoint ${flags} --confirm --plan checkpoint-plan.json`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function listPlacementWriters(home: string, ownRoot: string): PlacementWriterListing {
|
|
40
|
+
const inventory = (readEffectiveSyncPlacementWriters(home).roots ?? []).map(root => {
|
|
41
|
+
const state = absent(root) ? "missing" as const : "present" as const;
|
|
42
|
+
return { root, version: state === "present" ? installVersion(root) : null, state };
|
|
43
|
+
});
|
|
44
|
+
const own = realPath(ownRoot);
|
|
45
|
+
const running = { root: own, version: installVersion(own), inInventory: inventory.some(row => row.root === own) };
|
|
46
|
+
const receipts = readSetupWriterLaunchers(home);
|
|
47
|
+
const present = new Set<string>([own]);
|
|
48
|
+
for (const row of [...inventory, ...receipts]) if (row.state === "present") present.add(realPath(row.root));
|
|
49
|
+
const suggestedRoots = [...present].sort();
|
|
50
|
+
return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function placementWritersText(listing: PlacementWriterListing): string {
|
|
54
|
+
const lines = ["sync placement writer inventory:"];
|
|
55
|
+
for (const row of listing.inventory) lines.push(` ${row.state} ${row.version ?? "unknown"} ${row.root}`);
|
|
56
|
+
if (!listing.inventory.length) lines.push(" (no inventory roots recorded)");
|
|
57
|
+
lines.push(`running install: ${listing.running.version ?? "unknown"} ${listing.running.root} (${listing.running.inInventory ? "in the inventory" : "not in the inventory"})`);
|
|
58
|
+
lines.push("setup receipts:");
|
|
59
|
+
for (const row of listing.receipts) lines.push(` ${row.target} ${row.state} ${row.root}`);
|
|
60
|
+
if (!listing.receipts.length) lines.push(" (none)");
|
|
61
|
+
lines.push("roots to declare:");
|
|
62
|
+
for (const root of listing.suggestedRoots) lines.push(` ${root}`);
|
|
63
|
+
lines.push(`next: ${listing.command}`, `note: ${listing.note}`);
|
|
64
|
+
return lines.join("\n");
|
|
65
|
+
}
|
package/src/setup-drift.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opend
|
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
|
-
import { setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
|
|
5
|
+
import { decodeReceipt, setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
|
|
6
6
|
import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
|
|
7
7
|
import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
|
|
8
8
|
import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
|
|
@@ -150,6 +150,60 @@ function installEntry(target: SetupTarget, file: string, state: "missing" | "una
|
|
|
150
150
|
: entry(target, file, "amem install", installUnavailable(target), "unavailable");
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
/** Match the placement writer inventory's 256-name bound, including non-receipt entries. */
|
|
154
|
+
function agyReceiptNames(directory: string): string[] | undefined {
|
|
155
|
+
const names: string[] = [];
|
|
156
|
+
let scanned = 0, overflow = false, dir: Dir | undefined;
|
|
157
|
+
try {
|
|
158
|
+
// The writer inventory refuses a linked or non-directory setup/; never enumerate through one.
|
|
159
|
+
const stat = lstatSync(directory, { throwIfNoEntry: false });
|
|
160
|
+
if (stat && !stat.isDirectory()) throw Object.assign(Error("setup is not a plain directory"), { code: "ENOTPLAIN" });
|
|
161
|
+
if (stat) dir = opendirSync(directory);
|
|
162
|
+
for (;dir;) {
|
|
163
|
+
const item = dir.readSync(); if (!item) break;
|
|
164
|
+
if (++scanned > 256) { overflow = true; break; }
|
|
165
|
+
if (/^agy-[a-f0-9]{64}\.json$/.test(item.name)) names.push(item.name);
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
169
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
|
|
170
|
+
} finally { dir?.closeSync(); }
|
|
171
|
+
return overflow ? undefined : names.sort();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
type AgyReceiptLocation = { workspace: string; state: "current" | "stale"; apply: string; undo: string };
|
|
175
|
+
|
|
176
|
+
/** Explicit setup listing: only receipt metadata and launcher roots, never native config files. */
|
|
177
|
+
export function listAgyReceiptLocations(home: string): { receipts: AgyReceiptLocation[]; incomplete: boolean } {
|
|
178
|
+
const directory = join(home, "setup"), budget = { remaining: READ_BYTES };
|
|
179
|
+
const receipts: AgyReceiptLocation[] = [];
|
|
180
|
+
let names: string[] | undefined;
|
|
181
|
+
try { names = agyReceiptNames(directory); }
|
|
182
|
+
catch { return { receipts, incomplete: true }; }
|
|
183
|
+
if (!names) return { receipts, incomplete: true };
|
|
184
|
+
let incomplete = false;
|
|
185
|
+
for (const name of names) {
|
|
186
|
+
try {
|
|
187
|
+
const raw = safeImage(join(directory, name), JOURNAL_BYTES, budget);
|
|
188
|
+
if (raw.bytes === null) continue;
|
|
189
|
+
const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw.bytes, "base64")));
|
|
190
|
+
if (!plain(value)) throw Error("invalid receipt");
|
|
191
|
+
const receipt = decodeReceipt(value, "agy", 1, true);
|
|
192
|
+
if (receipt.phase !== "applied") throw Error("pending receipt");
|
|
193
|
+
const change = receipt.changes[0]!;
|
|
194
|
+
const workspace = dirname(dirname(change.path));
|
|
195
|
+
if (change.path !== resolveSetupPaths({}, workspace, workspace).paths.agy[0] || name !== `agy-${hash(workspace)}.json`
|
|
196
|
+
|| /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(workspace)) throw Error("invalid workspace");
|
|
197
|
+
const install = installMissing("agy", change.after);
|
|
198
|
+
if (install === "unavailable") throw Error("unavailable install");
|
|
199
|
+
const command = `cd ${shellQuote(workspace)} && amem setup agy`;
|
|
200
|
+
receipts.push({ workspace, state: install === "missing" ? "stale" : "current", apply: `${command} --apply`, undo: `${command} --undo` });
|
|
201
|
+
} catch { incomplete = true; }
|
|
202
|
+
}
|
|
203
|
+
receipts.sort((a, b) => a.workspace.localeCompare(b.workspace));
|
|
204
|
+
return { receipts, incomplete };
|
|
205
|
+
}
|
|
206
|
+
|
|
153
207
|
/** Read setup receipts and only the resolver-selected native config files. This function never writes. */
|
|
154
208
|
export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
|
|
155
209
|
const env = options.env ?? process.env;
|
|
@@ -252,26 +306,13 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
|
|
|
252
306
|
// #520: placement sync reads every `agy-<hash>.json` under setup/, so another workspace's receipt whose install is gone
|
|
253
307
|
// blocks it too. Only that receipt and its launcher root are read; the other workspace's native files are never opened.
|
|
254
308
|
const ownAgy = root === undefined ? undefined : `agy-${hash(root)}.json`;
|
|
255
|
-
// Bounded the way the writer inventory is: more than 256 names in setup/ refuses there, so it is reported here, never sliced away.
|
|
256
|
-
const foreign: string[] = [];
|
|
257
309
|
const incomplete = (reason: string) => { entries.push(entry("agy", "setup receipt of another workspace", "receipts", reason, "unavailable")); unavailable = true; };
|
|
258
|
-
let
|
|
259
|
-
try {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
if (
|
|
264
|
-
for (;dir;) {
|
|
265
|
-
const item = dir.readSync(); if (!item) break;
|
|
266
|
-
if (++scanned > 256) { overflow = true; break; }
|
|
267
|
-
if (/^agy-[a-f0-9]{64}\.json$/.test(item.name) && item.name !== ownAgy) foreign.push(item.name);
|
|
268
|
-
}
|
|
269
|
-
} catch (error) {
|
|
270
|
-
const code = (error as NodeJS.ErrnoException).code;
|
|
271
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") incomplete("the setup receipt directory could not be listed; placement sync may refuse until it is readable");
|
|
272
|
-
} finally { dir?.closeSync(); }
|
|
273
|
-
if (overflow) incomplete("the setup receipt directory holds more entries than the inventory bound; placement sync refuses until receipts are removed with amem setup <target> --undo");
|
|
274
|
-
else for (const name of foreign.sort()) {
|
|
310
|
+
let names: string[] | undefined = [];
|
|
311
|
+
try { names = agyReceiptNames(join(options.home, "setup")); }
|
|
312
|
+
catch { incomplete("the setup receipt directory could not be listed; placement sync may refuse until it is readable"); }
|
|
313
|
+
if (!names) incomplete("the setup receipt directory holds more entries than the inventory bound; placement sync refuses until receipts are removed with amem setup <target> --undo");
|
|
314
|
+
else for (const name of names) {
|
|
315
|
+
if (name === ownAgy) continue;
|
|
275
316
|
let raw: ConfigImage;
|
|
276
317
|
try { raw = safeImage(join(options.home, "setup", name), JOURNAL_BYTES, budget); }
|
|
277
318
|
catch { incomplete("an agy setup receipt of another workspace cannot be read safely; placement sync refuses until it is readable"); continue; }
|
|
@@ -45,6 +45,7 @@ export function decodeReceipt(value: Record<string, unknown>, target: SetupTarge
|
|
|
45
45
|
* sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
|
|
46
46
|
*/
|
|
47
47
|
export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
|
|
48
|
+
if (target === "agy") return `the ${applied ? "applied " : ""}agy setup receipt names an amem install that no longer exists; run amem setup agy --list, then from each listed stale repository run amem setup agy --apply to refresh its receipt or amem setup agy --undo to remove it`;
|
|
48
49
|
return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
|
|
49
50
|
}
|
|
50
51
|
/**
|
|
@@ -63,6 +64,18 @@ export class SetupWriterRootsError extends Error {
|
|
|
63
64
|
}
|
|
64
65
|
/** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
|
|
65
66
|
export function readSetupWriterRoots(home: string): string[] {
|
|
67
|
+
return [...new Set(setupWriterLaunchers(home, false).map(row => row.root))].sort();
|
|
68
|
+
}
|
|
69
|
+
/** One applied receipt's launcher install: its target, root, and whether the install still exists (#639). */
|
|
70
|
+
export interface SetupWriterLauncher { target: SetupTarget; root: string; state: "present" | "missing" }
|
|
71
|
+
/**
|
|
72
|
+
* #639: the same bounded, stamp-checked walk for the read-only writer listing. A launcher root positively absent
|
|
73
|
+
* (ENOENT/ENOTDIR) is reported as missing with its recorded path instead of refusing; every other refusal is unchanged.
|
|
74
|
+
*/
|
|
75
|
+
export function readSetupWriterLaunchers(home: string): SetupWriterLauncher[] {
|
|
76
|
+
return setupWriterLaunchers(home, true);
|
|
77
|
+
}
|
|
78
|
+
function setupWriterLaunchers(home: string, reportMissing: boolean): SetupWriterLauncher[] {
|
|
66
79
|
function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
|
|
67
80
|
try {
|
|
68
81
|
const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
|
|
@@ -84,7 +97,7 @@ export function readSetupWriterRoots(home: string): string[] {
|
|
|
84
97
|
if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
|
|
85
98
|
totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
|
|
86
99
|
} } finally { iterator.closeSync(); }
|
|
87
|
-
const
|
|
100
|
+
const rows: SetupWriterLauncher[] = [], launchers: { entry: string; root: string }[] = [];
|
|
88
101
|
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
89
102
|
const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
|
|
90
103
|
if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
|
|
@@ -110,11 +123,12 @@ export function readSetupWriterRoots(home: string): string[] {
|
|
|
110
123
|
try { root = realPath(dirname(dirname(runtime.entry))); }
|
|
111
124
|
catch (error) {
|
|
112
125
|
const code = (error as NodeJS.ErrnoException).code;
|
|
126
|
+
if ((code === "ENOENT" || code === "ENOTDIR") && reportMissing) { rows.push({ target, root: dirname(dirname(runtime.entry)), state: "missing" }); continue; }
|
|
113
127
|
if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
|
|
114
128
|
fail("unavailable");
|
|
115
129
|
}
|
|
116
130
|
if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
|
|
117
|
-
|
|
131
|
+
rows.push({ target, root, state: "present" }); launchers.push({ entry: runtime.entry, root });
|
|
118
132
|
}
|
|
119
133
|
const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
|
|
120
134
|
if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
|
|
@@ -124,7 +138,7 @@ export function readSetupWriterRoots(home: string): string[] {
|
|
|
124
138
|
if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
|
|
125
139
|
for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
|
|
126
140
|
for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
|
|
127
|
-
return
|
|
141
|
+
return rows;
|
|
128
142
|
} catch (error) {
|
|
129
143
|
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
|
|
130
144
|
const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
|
package/src/setup.ts
CHANGED
|
@@ -142,6 +142,10 @@ function workspaceBinding(options: SetupContext): WorkspaceBinding {
|
|
|
142
142
|
if (![0, 1].includes(ignored.status ?? -1) || ignored.error) throw Error("Antigravity setup cannot verify configuration ignore status");
|
|
143
143
|
return { root, ignored: ignored.status === 0, assertCurrent };
|
|
144
144
|
}
|
|
145
|
+
export function setupMemoryHome(env: NodeJS.ProcessEnv, home = realPath(resolve(env.HOME?.trim() || homedir()))): string {
|
|
146
|
+
return canonicalPath(memoryHome({ ...env, AGENTHUB_HOME: env.AGENTHUB_HOME?.trim() || join(home, ".agenthub") }));
|
|
147
|
+
}
|
|
148
|
+
|
|
145
149
|
function context(options: SetupContext, workspace?: WorkspaceBinding) {
|
|
146
150
|
const env = options.env ?? process.env, home = realPath(resolve(env.HOME?.trim() || homedir()));
|
|
147
151
|
const { paths, legacyPaths, redirects } = resolveSetupPaths(env, home, workspace?.root);
|
|
@@ -154,7 +158,7 @@ function context(options: SetupContext, workspace?: WorkspaceBinding) {
|
|
|
154
158
|
const roots = [resolve(tmpdir()), realPath(tmpdir())], entries = [resolve(entry), realPath(entry)];
|
|
155
159
|
if (roots.some(root => entries.some(file => { const part = relative(root, file); return part !== ".." && !part.startsWith("../") && !isAbsolute(part); }))) throw Error("setup refuses a temporary package entry; install amem in a persistent location first");
|
|
156
160
|
}
|
|
157
|
-
return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(
|
|
161
|
+
return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(setupMemoryHome(env, home), "setup") };
|
|
158
162
|
}
|
|
159
163
|
export interface InstallRoot { path: string; version: string }
|
|
160
164
|
const PACKAGE_JSON_MAX = 64 * 1024;
|