@staix/agent-mem 0.41.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 (42) 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 +129 -24
  5. package/src/commands-table.ts +11 -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 +4 -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/search-fts.ts +55 -27
  19. package/src/memory/shard.ts +17 -14
  20. package/src/memory/store.ts +5 -3
  21. package/src/memory/sync-cadence.ts +8 -4
  22. package/src/memory/sync-placement-activation-locks.ts +27 -19
  23. package/src/memory/sync-placement-active.ts +67 -19
  24. package/src/memory/sync-placement-advertisement.ts +25 -3
  25. package/src/memory/sync-placement-checkpoint-person.ts +8 -14
  26. package/src/memory/sync-placement-effective-writers.ts +4 -3
  27. package/src/memory/sync-placement-guard.ts +29 -11
  28. package/src/memory/sync-placement-inventory.ts +20 -4
  29. package/src/memory/sync-placement-realm-admission.ts +16 -11
  30. package/src/memory/sync-placement-refusal.ts +7 -0
  31. package/src/memory/sync-placement-remote-admission.ts +31 -13
  32. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  33. package/src/memory/sync-placement-remote-stage.ts +1 -1
  34. package/src/memory/sync-placement-transport.ts +28 -12
  35. package/src/memory/sync-placement-writer-listing.ts +38 -13
  36. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  37. package/src/memory/topic.ts +14 -0
  38. package/src/setup-console.ts +49 -23
  39. package/src/setup-drift.ts +31 -1
  40. package/src/setup-writer-roots.ts +1 -1
  41. package/src/setup.ts +66 -10
  42. package/src/sync-placement-writer-context.ts +1 -1
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
 
@@ -259,7 +261,7 @@ const lifecycle = (target: SetupTarget) => target === "opencode" || target === "
259
261
  * as such with the renewal step to take first; an inventory that cannot be read is reported as unverified, never as a missing
260
262
  * entry. It writes nothing, refuses nothing and returns undefined on a home that is not activated for placement sync.
261
263
  */
262
- function placementWriterInventoryNote(root: string, home: string): string | undefined {
264
+ function placementWriterInventoryNote(root: string, home: string, repairing = false): string | undefined {
263
265
  // #551 AC2: only a proven non-placement home stays silent. Markers that cannot be read or parsed prove nothing either way,
264
266
  // so they fall through to the inventory read below, which reports the state as unverified instead of as a missing root.
265
267
  if (placementMarkerState(home) === "not placement") return undefined;
@@ -269,8 +271,10 @@ function placementWriterInventoryNote(root: string, home: string): string | unde
269
271
  let canonical: string;
270
272
  try { canonical = realPath(root); } catch { return undefined; }
271
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.`;
272
276
  // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
273
- 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.`;
274
278
  }
275
279
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
276
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]");
@@ -304,7 +308,9 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
304
308
  }
305
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.`);
306
310
  // #551: the root this plan registers may not be in the home's active placement inventory, which stops sync in writer verification.
307
- 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);
308
314
  if (placementWriter) pluginNotes.push(placementWriter);
309
315
  if (target === "all") pluginNotes.push("Antigravity is repository-scoped and excluded from all; run amem setup agy explicitly inside its repository.");
310
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.");
@@ -765,10 +771,8 @@ function setupWriterCommands(plan: SetupPlan): string[] {
765
771
  const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
766
772
  if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
767
773
  const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
768
- // #624: the checkpoint renews while sessions keep running. Its preview is saved as the JSON plan confirm reads, in a new
769
- // 0600 file (umask 077, noclobber); dry-run/apply is the fallback, which needs every amem session closed.
770
- 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}`,
771
- `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"];
772
776
  } catch { return ["amem doctor"]; }
773
777
  }
774
778
 
@@ -847,6 +851,44 @@ function setupResultText(result: SetupResult, s: Style, plan: SetupPlan, options
847
851
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
848
852
  export function setupConfirmationText(plan: SetupPlan, json: boolean, s: Style = PLAIN): string { return json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s); }
849
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
+
850
892
  export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style; columns?: number; verbose?: boolean } = {}): Promise<string> {
851
893
  const plan = planSetup(target, mode, options), s = options.json ? PLAIN : options.style ?? PLAIN;
852
894
  const renderOptions: SetupRenderOptions = { columns: options.columns, verbose: options.verbose, ...(!options.json && mode !== "undo" && plan.placementWriter ? { writerCommands: setupWriterCommands(plan) } : {}) };
@@ -854,9 +896,23 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
854
896
  const policy = configuredPolicy(memoryHome(options.env ?? process.env), options.cwd ?? process.cwd());
855
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.");
856
898
  }
857
- 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));
858
900
  const result = mode === "apply" ? applySetup(plan, options) : undoSetup(plan, options);
859
- 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
+ }
860
916
  }
861
917
 
862
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) {