@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.
Files changed (43) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +2 -2
  3. package/package.json +4 -3
  4. package/src/cli.ts +172 -30
  5. package/src/commands-table.ts +16 -4
  6. package/src/index.ts +2 -1
  7. package/src/mcp-bounds.ts +3 -0
  8. package/src/mcp-memory.ts +64 -10
  9. package/src/mcp.ts +36 -121
  10. package/src/memory/candidates.ts +21 -5
  11. package/src/memory/commands.ts +6 -3
  12. package/src/memory/config.ts +26 -0
  13. package/src/memory/consolidation-clusters.ts +13 -2
  14. package/src/memory/doctor-text.ts +7 -1
  15. package/src/memory/formats-raise.ts +36 -15
  16. package/src/memory/formats.ts +26 -10
  17. package/src/memory/profile-marker-cache.ts +45 -0
  18. package/src/memory/reader-lease.ts +37 -1
  19. package/src/memory/search-fts.ts +55 -27
  20. package/src/memory/shard.ts +17 -14
  21. package/src/memory/store.ts +5 -3
  22. package/src/memory/sync-cadence.ts +8 -4
  23. package/src/memory/sync-placement-activation-locks.ts +27 -19
  24. package/src/memory/sync-placement-active.ts +67 -19
  25. package/src/memory/sync-placement-advertisement.ts +25 -3
  26. package/src/memory/sync-placement-checkpoint-person.ts +35 -13
  27. package/src/memory/sync-placement-effective-writers.ts +4 -3
  28. package/src/memory/sync-placement-guard.ts +29 -11
  29. package/src/memory/sync-placement-inventory.ts +20 -4
  30. package/src/memory/sync-placement-realm-admission.ts +16 -11
  31. package/src/memory/sync-placement-refusal.ts +7 -0
  32. package/src/memory/sync-placement-remote-admission.ts +31 -13
  33. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  34. package/src/memory/sync-placement-remote-stage.ts +1 -1
  35. package/src/memory/sync-placement-transport.ts +28 -12
  36. package/src/memory/sync-placement-writer-listing.ts +90 -0
  37. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  38. package/src/memory/topic.ts +14 -0
  39. package/src/setup-console.ts +49 -23
  40. package/src/setup-drift.ts +92 -21
  41. package/src/setup-writer-roots.ts +17 -3
  42. package/src/setup.ts +71 -11
  43. package/src/sync-placement-writer-context.ts +1 -1
@@ -1,17 +1,21 @@
1
1
  import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opendirSync, openSync, readSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { createHash } from "node:crypto";
4
5
  import { isDeepStrictEqual } from "node:util";
5
- import { setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
6
+ import { decodeReceipt, setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
6
7
  import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
8
  import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
8
9
  import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
9
10
  import { HOOK_EVENTS } from "./hook-contract.ts";
10
11
  import { realPath } from "./memory/platform.ts";
12
+ import { consoleManifestFile } from "./setup-console.ts";
13
+ import { installVersion, versionBelow } from "./memory/formats-raise.ts";
11
14
 
12
15
  export type SetupDriftStatus = "ok" | "attention" | "skipped" | "unavailable";
13
16
  export interface SetupDriftEntry {
14
- target: SetupTarget;
17
+ /** `console` is the acon plugin manifest (#659), which has no setup receipt. */
18
+ target: SetupTarget | "console";
15
19
  file: string;
16
20
  entry: string;
17
21
  reason: string;
@@ -150,6 +154,82 @@ function installEntry(target: SetupTarget, file: string, state: "missing" | "una
150
154
  : entry(target, file, "amem install", installUnavailable(target), "unavailable");
151
155
  }
152
156
 
157
+ /** Match the placement writer inventory's 256-name bound, including non-receipt entries. */
158
+ function agyReceiptNames(directory: string): string[] | undefined {
159
+ const names: string[] = [];
160
+ let scanned = 0, overflow = false, dir: Dir | undefined;
161
+ try {
162
+ // The writer inventory refuses a linked or non-directory setup/; never enumerate through one.
163
+ const stat = lstatSync(directory, { throwIfNoEntry: false });
164
+ if (stat && !stat.isDirectory()) throw Object.assign(Error("setup is not a plain directory"), { code: "ENOTPLAIN" });
165
+ if (stat) dir = opendirSync(directory);
166
+ for (;dir;) {
167
+ const item = dir.readSync(); if (!item) break;
168
+ if (++scanned > 256) { overflow = true; break; }
169
+ if (/^agy-[a-f0-9]{64}\.json$/.test(item.name)) names.push(item.name);
170
+ }
171
+ } catch (error) {
172
+ const code = (error as NodeJS.ErrnoException).code;
173
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
174
+ } finally { dir?.closeSync(); }
175
+ return overflow ? undefined : names.sort();
176
+ }
177
+
178
+ type AgyReceiptLocation = { workspace: string; state: "current" | "stale"; apply: string; undo: string };
179
+
180
+ /** Explicit setup listing: only receipt metadata and launcher roots, never native config files. */
181
+ export function listAgyReceiptLocations(home: string): { receipts: AgyReceiptLocation[]; incomplete: boolean } {
182
+ const directory = join(home, "setup"), budget = { remaining: READ_BYTES };
183
+ const receipts: AgyReceiptLocation[] = [];
184
+ let names: string[] | undefined;
185
+ try { names = agyReceiptNames(directory); }
186
+ catch { return { receipts, incomplete: true }; }
187
+ if (!names) return { receipts, incomplete: true };
188
+ let incomplete = false;
189
+ for (const name of names) {
190
+ try {
191
+ const raw = safeImage(join(directory, name), JOURNAL_BYTES, budget);
192
+ if (raw.bytes === null) continue;
193
+ const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw.bytes, "base64")));
194
+ if (!plain(value)) throw Error("invalid receipt");
195
+ const receipt = decodeReceipt(value, "agy", 1, true);
196
+ if (receipt.phase !== "applied") throw Error("pending receipt");
197
+ const change = receipt.changes[0]!;
198
+ const workspace = dirname(dirname(change.path));
199
+ if (change.path !== resolveSetupPaths({}, workspace, workspace).paths.agy[0] || name !== `agy-${hash(workspace)}.json`
200
+ || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(workspace)) throw Error("invalid workspace");
201
+ const install = installMissing("agy", change.after);
202
+ if (install === "unavailable") throw Error("unavailable install");
203
+ const command = `cd ${shellQuote(workspace)} && amem setup agy`;
204
+ receipts.push({ workspace, state: install === "missing" ? "stale" : "current", apply: `${command} --apply`, undo: `${command} --undo` });
205
+ } catch { incomplete = true; }
206
+ }
207
+ receipts.sort((a, b) => a.workspace.localeCompare(b.workspace));
208
+ return { receipts, incomplete };
209
+ }
210
+
211
+ export const CONSOLE_DRIFT_REASON = "the acon console plugin manifest names a missing module or one whose hash changed; run amem setup console --apply to refresh it or amem setup console --undo to remove it";
212
+ /** The manifest and its module, read without following links and bounded. */
213
+ function consoleDrift(env: SetupEnvironment, budget: { remaining: number }): SetupDriftEntry | "absent" | "current" {
214
+ const file = consoleManifestFile(env), finding = (kind: SetupDriftEntry["kind"], reason: string): SetupDriftEntry => ({ target: "console", file, entry: "plugin manifest", reason, kind });
215
+ let manifest: Record<string, unknown>;
216
+ try {
217
+ const raw = safeImage(file, 64 * 1024, budget);
218
+ if (raw.bytes === null) return "absent";
219
+ const value: unknown = JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"));
220
+ if (!plain(value) || typeof value.module !== "string" || !isAbsolute(value.module) || typeof value.sha256 !== "string") return finding("drift", CONSOLE_DRIFT_REASON);
221
+ manifest = value;
222
+ } catch { return finding("unavailable", "the acon console plugin manifest cannot be read safely; inspect it or run amem setup console --apply"); }
223
+ try {
224
+ const module = safeImage(String(manifest.module), SETUP_CONFIG_BYTES, budget);
225
+ if (module.bytes === null || createHash("sha256").update(Buffer.from(module.bytes, "base64")).digest("hex") !== manifest.sha256) return finding("drift", CONSOLE_DRIFT_REASON);
226
+ } catch { return finding("unavailable", "the acon console plugin module cannot be read safely; run amem setup console --apply"); }
227
+ // An intact module from an older install still loads, but it serves that release's panels: refresh it to this one.
228
+ const theirs = installVersion(dirname(dirname(dirname(String(manifest.module))))), ours = installVersion(fileURLToPath(new URL("..", import.meta.url)));
229
+ if (theirs !== null && ours !== null && versionBelow(theirs, ours)) return finding("drift", `the acon console plugin manifest names amem ${theirs}, older than this amem ${ours}; run amem setup console --apply to refresh it`);
230
+ return "current";
231
+ }
232
+
153
233
  /** Read setup receipts and only the resolver-selected native config files. This function never writes. */
154
234
  export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
155
235
  const env = options.env ?? process.env;
@@ -252,26 +332,13 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
252
332
  // #520: placement sync reads every `agy-<hash>.json` under setup/, so another workspace's receipt whose install is gone
253
333
  // blocks it too. Only that receipt and its launcher root are read; the other workspace's native files are never opened.
254
334
  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
335
  const incomplete = (reason: string) => { entries.push(entry("agy", "setup receipt of another workspace", "receipts", reason, "unavailable")); unavailable = true; };
258
- let scanned = 0, overflow = false, dir: Dir | undefined;
259
- try {
260
- // The writer inventory refuses a linked or non-directory setup/; never enumerate through one.
261
- const stat = lstatSync(join(options.home, "setup"), { throwIfNoEntry: false });
262
- if (stat && !stat.isDirectory()) throw Object.assign(Error("setup is not a plain directory"), { code: "ENOTPLAIN" });
263
- if (stat) dir = opendirSync(join(options.home, "setup"));
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()) {
336
+ let names: string[] | undefined = [];
337
+ try { names = agyReceiptNames(join(options.home, "setup")); }
338
+ catch { incomplete("the setup receipt directory could not be listed; placement sync may refuse until it is readable"); }
339
+ 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");
340
+ else for (const name of names) {
341
+ if (name === ownAgy) continue;
275
342
  let raw: ConfigImage;
276
343
  try { raw = safeImage(join(options.home, "setup", name), JOURNAL_BYTES, budget); }
277
344
  catch { incomplete("an agy setup receipt of another workspace cannot be read safely; placement sync refuses until it is readable"); continue; }
@@ -286,6 +353,10 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
286
353
  const install = installMissing("agy", receipt.changes[0]!.after);
287
354
  if (install) { entries.push(installEntry("agy", "setup receipt of another workspace", install)); if (install === "unavailable") unavailable = true; }
288
355
  }
356
+ // #659: an acon plugin manifest goes stale when amem moves or its UI module changes; only an existing manifest is checked.
357
+ const plugin = consoleDrift(env, budget);
358
+ if (plugin !== "absent") { anyReceipt = true; checked++; }
359
+ if (typeof plugin === "object") { if (plugin.kind === "unavailable") unavailable = true; entries.push(plugin); }
289
360
  const status: SetupDriftStatus = entries.some(value => value.kind === "drift" || value.kind === "review-needed") ? "attention"
290
361
  : unavailable ? "unavailable" : anyReceipt ? "ok" : "skipped";
291
362
  return { status, checked, entries, ...(!anyReceipt && !entries.length ? { reason: "no applied setup receipts found" } : {}) };
@@ -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 --refresh --apply to refresh every receipted repository, or 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 roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
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
- roots.add(root); launchers.push({ entry: runtime.entry, root });
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 [...roots].sort();
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
@@ -18,11 +18,13 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import { isDeepStrictEqual, types } from "node:util";
20
20
  import { HOOK_EVENTS } from "./hook-contract.ts";
21
- import { decodeReceipt, JOURNAL_MAX, readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type Receipt, type SetupTarget } from "./setup-writer-roots.ts";
21
+ import { decodeReceipt, JOURNAL_MAX, readSetupWriterLaunchers, readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type Receipt, type SetupTarget } from "./setup-writer-roots.ts";
22
22
  export { readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type SetupTarget };
23
23
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
24
24
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
25
25
  import { memoryHome } from "./memory/home.ts";
26
+ import { listAgyReceiptLocations } from "./setup-drift.ts";
27
+ import { consoleSetup, consoleSetupText, type ConsoleSetup } from "./setup-console.ts";
26
28
  import { PLAIN, singleLine, type Style } from "./memory/style.ts";
27
29
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
28
30
 
@@ -142,6 +144,10 @@ function workspaceBinding(options: SetupContext): WorkspaceBinding {
142
144
  if (![0, 1].includes(ignored.status ?? -1) || ignored.error) throw Error("Antigravity setup cannot verify configuration ignore status");
143
145
  return { root, ignored: ignored.status === 0, assertCurrent };
144
146
  }
147
+ export function setupMemoryHome(env: NodeJS.ProcessEnv, home = realPath(resolve(env.HOME?.trim() || homedir()))): string {
148
+ return canonicalPath(memoryHome({ ...env, AGENTHUB_HOME: env.AGENTHUB_HOME?.trim() || join(home, ".agenthub") }));
149
+ }
150
+
145
151
  function context(options: SetupContext, workspace?: WorkspaceBinding) {
146
152
  const env = options.env ?? process.env, home = realPath(resolve(env.HOME?.trim() || homedir()));
147
153
  const { paths, legacyPaths, redirects } = resolveSetupPaths(env, home, workspace?.root);
@@ -154,7 +160,7 @@ function context(options: SetupContext, workspace?: WorkspaceBinding) {
154
160
  const roots = [resolve(tmpdir()), realPath(tmpdir())], entries = [resolve(entry), realPath(entry)];
155
161
  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
162
  }
157
- return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(canonicalPath(memoryHome({ ...env, AGENTHUB_HOME: env.AGENTHUB_HOME?.trim() || join(home, ".agenthub") })), "setup") };
163
+ return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(setupMemoryHome(env, home), "setup") };
158
164
  }
159
165
  export interface InstallRoot { path: string; version: string }
160
166
  const PACKAGE_JSON_MAX = 64 * 1024;
@@ -255,7 +261,7 @@ const lifecycle = (target: SetupTarget) => target === "opencode" || target === "
255
261
  * as such with the renewal step to take first; an inventory that cannot be read is reported as unverified, never as a missing
256
262
  * entry. It writes nothing, refuses nothing and returns undefined on a home that is not activated for placement sync.
257
263
  */
258
- function placementWriterInventoryNote(root: string, home: string): string | undefined {
264
+ function placementWriterInventoryNote(root: string, home: string, repairing = false): string | undefined {
259
265
  // #551 AC2: only a proven non-placement home stays silent. Markers that cannot be read or parsed prove nothing either way,
260
266
  // so they fall through to the inventory read below, which reports the state as unverified instead of as a missing root.
261
267
  if (placementMarkerState(home) === "not placement") return undefined;
@@ -265,8 +271,10 @@ function placementWriterInventoryNote(root: string, home: string): string | unde
265
271
  let canonical: string;
266
272
  try { canonical = realPath(root); } catch { return undefined; }
267
273
  if (roots.includes(canonical)) return undefined;
274
+ // #660 AC4: refreshing a receipt whose recorded install is gone is the repair the refusal asked for; the renewal comes after it.
275
+ if (repairing) return `WARNING: this install root is not yet in the active placement writer inventory. Finish applying setup to repair the stale receipt, then renew the inventory: list the roots with amem migrate --sync-placement --writers and run the command it prints. Setup writes no inventory entry and never refuses on this alone.`;
268
276
  // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
269
- return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person, through the checkpoint while sessions keep running - save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root ${quote(canonical)} --json > checkpoint-plan.json), adding --writer-root for every other install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list; only if the checkpoint preview refuses, close every amem session and run amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
277
+ return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory with the person while sessions keep running. Run amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, adding --writer-root for every other install root, then use --apply with the same roots. If the live window needs compaction, save the preview with amem migrate --sync-placement --checkpoint --writer-root ${quote(canonical)} --out checkpoint-plan.json, adding the same other roots, and confirm with amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json. Rerun setup after renewal. Setup writes no inventory entry and never refuses on this alone.`;
270
278
  }
271
279
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
272
280
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
@@ -300,7 +308,9 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
300
308
  }
301
309
  if (c.root) pluginNotes.push(`Registers the install root ${c.root.path} (amem ${c.root.version}) for hooks and MCP; current registrations change only on --apply.`);
302
310
  // #551: the root this plan registers may not be in the home's active placement inventory, which stops sync in writer verification.
303
- const placementWriter = placementWriterInventoryNote(c.root?.path ?? fileURLToPath(new URL("..", import.meta.url)), dirname(c.state));
311
+ let repairing = false;
312
+ try { repairing = mode !== "undo" ? readSetupWriterLaunchers(dirname(c.state)).some(row => row.state === "missing" && targets.includes(row.target)) : false; } catch { repairing = false; }
313
+ const placementWriter = placementWriterInventoryNote(c.root?.path ?? fileURLToPath(new URL("..", import.meta.url)), dirname(c.state), repairing);
304
314
  if (placementWriter) pluginNotes.push(placementWriter);
305
315
  if (target === "all") pluginNotes.push("Antigravity is repository-scoped and excluded from all; run amem setup agy explicitly inside its repository.");
306
316
  if (targets.includes("jcode")) pluginNotes.push("Launch Jcode with JCODE_DISABLE_CLAUDE_MCP=1 and without a same-name project override: imported Claude stdio entries can replace this private amem binding with a shared daemon-cwd server. Use a new workspace-bound session when changing projects.");
@@ -761,10 +771,8 @@ function setupWriterCommands(plan: SetupPlan): string[] {
761
771
  const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
762
772
  if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
763
773
  const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
764
- // #624: the checkpoint renews while sessions keep running. Its preview is saved as the JSON plan confirm reads, in a new
765
- // 0600 file (umask 077, noclobber); dry-run/apply is the fallback, which needs every amem session closed.
766
- return [`(umask 077; set -C; amem migrate --sync-placement --checkpoint ${flags} --json > checkpoint-plan.json)`, `amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json ${flags}`,
767
- `amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
774
+ return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`,
775
+ `amem migrate --sync-placement --checkpoint ${flags} --out checkpoint-plan.json`, "amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json"];
768
776
  } catch { return ["amem doctor"]; }
769
777
  }
770
778
 
@@ -843,6 +851,44 @@ function setupResultText(result: SetupResult, s: Style, plan: SetupPlan, options
843
851
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
844
852
  export function setupConfirmationText(plan: SetupPlan, json: boolean, s: Style = PLAIN): string { return json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s); }
845
853
 
854
+ export interface AgyRefreshRow { workspace: string; change: "update" | "unchanged" | "missing-workspace" | "refused"; reason?: string }
855
+ /**
856
+ * #659: `amem setup agy --refresh [--apply]` previews, then refreshes, every applied Antigravity receipt in one run, each through the
857
+ * same per-workspace plan and apply as `cd <workspace> && amem setup agy --apply`. Only receipted workspaces are touched; one
858
+ * workspace's refusal is reported and never stops the others.
859
+ */
860
+ export function refreshAgyWorkspaces(mode: "preview" | "apply", options: SetupContext = {}): { workspaces: AgyRefreshRow[]; incomplete: boolean } {
861
+ const listed = listAgyReceiptLocations(setupMemoryHome((options.env ?? process.env) as NodeJS.ProcessEnv));
862
+ const agent = cliAttribution()?.actor === "agent";
863
+ const workspaces = listed.receipts.map(({ workspace }): AgyRefreshRow => {
864
+ try {
865
+ if (!lstatSync(workspace, { throwIfNoEntry: false })?.isDirectory())
866
+ return { workspace, change: "missing-workspace", reason: "the repository directory no longer exists; restore it, then run amem setup agy --undo there to remove its receipt" };
867
+ const context = { ...options, cwd: workspace };
868
+ // Each plan must still bind exactly the receipt's workspace; one that now resolves elsewhere is that row's refusal.
869
+ const planned = (planMode: "preview" | "apply") => {
870
+ const plan = planSetup("agy", planMode, context);
871
+ if (plan.actions.length !== 1 || plan.actions[0]!.cwd !== workspace) throw Error("the receipt's repository no longer resolves to the same workspace; run amem setup agy --list and repair it from that repository");
872
+ // The agent screen `amem setup agy --apply` applies before any write, per workspace.
873
+ if (agent && !configuredPolicy(memoryHome(options.env ?? process.env), workspace).screenStandalone(JSON.parse(JSON.stringify(plan)))) throw Error("Memory operation unavailable or refused; no partial result is shown.");
874
+ return plan;
875
+ };
876
+ if (planned("preview").actions.every(action => action.mcpChange === "unchanged")) return { workspace, change: "unchanged" };
877
+ if (mode === "apply") applySetup(planned("apply"), context);
878
+ return { workspace, change: "update" };
879
+ } catch (error) { return { workspace, change: "refused", reason: singleLine((error as Error).message) }; }
880
+ });
881
+ return { workspaces, incomplete: listed.incomplete };
882
+ }
883
+ export function agyRefreshText(result: ReturnType<typeof refreshAgyWorkspaces>, mode: "preview" | "apply"): string {
884
+ const verb = (row: AgyRefreshRow) => row.change === "update" && mode === "preview" ? "would update" : row.change === "update" ? "updated" : row.change;
885
+ const lines = result.workspaces.map(row => `${verb(row)}: ${row.workspace}${row.reason ? ` (${row.reason})` : ""}`);
886
+ if (!lines.length) lines.push("No Antigravity setup receipts found.");
887
+ if (result.incomplete) lines.push("Some Antigravity setup receipts could not be listed safely; run amem setup agy --list.");
888
+ if (mode === "preview" && result.workspaces.some(row => row.change === "update")) lines.push("Preview only; run amem setup agy --refresh --apply to update them.");
889
+ return lines.join("\n");
890
+ }
891
+
846
892
  export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style; columns?: number; verbose?: boolean } = {}): Promise<string> {
847
893
  const plan = planSetup(target, mode, options), s = options.json ? PLAIN : options.style ?? PLAIN;
848
894
  const renderOptions: SetupRenderOptions = { columns: options.columns, verbose: options.verbose, ...(!options.json && mode !== "undo" && plan.placementWriter ? { writerCommands: setupWriterCommands(plan) } : {}) };
@@ -850,9 +896,23 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
850
896
  const policy = configuredPolicy(memoryHome(options.env ?? process.env), options.cwd ?? process.cwd());
851
897
  if (!policy.screenStandalone(JSON.parse(JSON.stringify(plan))) || (renderOptions.writerCommands && !policy.screenStandalone(renderOptions.writerCommands))) throw Error("Memory operation unavailable or refused; no partial result is shown.");
852
898
  }
853
- if (mode === "preview") return options.json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s, renderOptions);
899
+ if (mode === "preview") return withConsole(options.json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s, renderOptions));
854
900
  const result = mode === "apply" ? applySetup(plan, options) : undoSetup(plan, options);
855
- return options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s, plan, renderOptions);
901
+ return withConsole(options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s, plan, renderOptions));
902
+ // #659: `setup all` keeps an acon plugin manifest the person already installed in step, from the same install root; it never
903
+ // creates one, and undo leaves it to `setup console --undo`. A refresh error after setup applied is a note, never a throw.
904
+ function withConsole(output: string): string {
905
+ const env = options.env ?? process.env;
906
+ if (target !== "all" || mode === "undo") return output;
907
+ let plugin: ConsoleSetup | { error: string };
908
+ // The inspection is part of the optional refresh: any error here, after native setup may have applied, is a note.
909
+ try {
910
+ plugin = consoleSetup(mode, env, plan.root ? join(plan.root.path, "src", "ui", "plugin.ts") : undefined, { existingOnly: true });
911
+ if (plugin.change === "none") return output;
912
+ } catch (error) { plugin = { error: `console plugin not refreshed: ${singleLine((error as Error).message)}; run amem setup console --apply after fixing it` }; }
913
+ if (options.json) return JSON.stringify({ ...JSON.parse(output), console: plugin }, null, 2);
914
+ return `${output}\n${"error" in plugin ? plugin.error : consoleSetupText(plugin, mode)}`;
915
+ }
856
916
  }
857
917
 
858
918
 
@@ -33,7 +33,7 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
33
33
  const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
34
34
  if(phase==="initial")return `Sync placement initial writer proof is ${causeClass} (${category} category${cause}); ${receipt??(category==="setup receipt"?"upgrade or repair the managed amem install and its host exact pin, then rerun amem setup <target> --apply":"upgrade or repair the amem install and its host exact pin")}. Declare the complete writer roots and rerun amem migrate --sync-placement --dry-run.`;
35
35
  if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); Placement sync refused [cause: setup_receipt_missing_install]: ${receipt}; then rerun the sync.`;
36
- return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it through the checkpoint while sessions keep running: save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list. Only if the checkpoint preview refuses (an open obligation, no headroom, or a home floor below 0.30.0), close every amem session (agent sessions, hub peers and their amem mcp servers), then, if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
36
+ return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it while sessions keep running. If needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved. Run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, then run --apply after the exact apply command is approved. When the live window needs compaction, save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list.`;
37
37
  }
38
38
  export class PlacementWriterContextError extends Error {
39
39
  constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending",readonly setupTarget?:SetupTarget) {