@staix/agent-mem 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) 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 +161 -27
  5. package/src/commands-table.ts +17 -6
  6. package/src/index.ts +4 -1
  7. package/src/ingest-hosts.ts +440 -0
  8. package/src/mcp-bounds.ts +3 -0
  9. package/src/mcp-memory.ts +64 -10
  10. package/src/mcp.ts +36 -121
  11. package/src/memory/candidates.ts +33 -5
  12. package/src/memory/capture.ts +23 -0
  13. package/src/memory/commands.ts +6 -3
  14. package/src/memory/config.ts +26 -0
  15. package/src/memory/consolidation-clusters.ts +13 -2
  16. package/src/memory/doctor-text.ts +4 -1
  17. package/src/memory/doctor.ts +8 -5
  18. package/src/memory/formats-raise.ts +37 -16
  19. package/src/memory/formats.ts +37 -10
  20. package/src/memory/generation-sync.ts +1 -1
  21. package/src/memory/home-binding-fence.ts +2 -1
  22. package/src/memory/live-state.ts +85 -0
  23. package/src/memory/migrate.ts +3 -3
  24. package/src/memory/mutation.ts +6 -3
  25. package/src/memory/profile-marker-cache.ts +45 -0
  26. package/src/memory/public-prune-activation.ts +1 -1
  27. package/src/memory/public-prune-advance.ts +1 -1
  28. package/src/memory/public-prune-inputs.ts +1 -1
  29. package/src/memory/purge-intent.ts +27 -0
  30. package/src/memory/purge-matcher.ts +101 -0
  31. package/src/memory/purge-plan.ts +90 -0
  32. package/src/memory/read-curated-entries.ts +244 -0
  33. package/src/memory/reader-lease.ts +3 -0
  34. package/src/memory/search-fts.ts +55 -27
  35. package/src/memory/shard-migration.ts +3 -3
  36. package/src/memory/shard-sync.ts +3 -3
  37. package/src/memory/shard.ts +17 -14
  38. package/src/memory/store.ts +9 -72
  39. package/src/memory/sync-cadence.ts +8 -4
  40. package/src/memory/sync-placement-activation-locks.ts +39 -22
  41. package/src/memory/sync-placement-active.ts +69 -19
  42. package/src/memory/sync-placement-advertisement.ts +25 -3
  43. package/src/memory/sync-placement-checkpoint-person.ts +8 -14
  44. package/src/memory/sync-placement-effective-writers.ts +4 -3
  45. package/src/memory/sync-placement-guard.ts +31 -11
  46. package/src/memory/sync-placement-inventory.ts +20 -4
  47. package/src/memory/sync-placement-journal.ts +1 -1
  48. package/src/memory/sync-placement-realm-admission.ts +16 -11
  49. package/src/memory/sync-placement-refusal.ts +7 -0
  50. package/src/memory/sync-placement-remote-admission.ts +31 -13
  51. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  52. package/src/memory/sync-placement-remote-stage.ts +1 -1
  53. package/src/memory/sync-placement-transport.ts +36 -15
  54. package/src/memory/sync-placement-writer-listing.ts +38 -13
  55. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  56. package/src/memory/sync.ts +3 -2
  57. package/src/memory/topic.ts +14 -0
  58. package/src/setup-console.ts +49 -23
  59. package/src/setup-drift.ts +35 -4
  60. package/src/setup-owned.ts +9 -1
  61. package/src/setup-writer-roots.ts +1 -1
  62. package/src/setup.ts +102 -16
  63. package/src/sync-placement-writer-context.ts +1 -1
@@ -1,53 +1,75 @@
1
1
  /**
2
2
  * #639: a read-only listing of the placement writer inventory and the install roots a renewal must declare. It writes
3
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.
4
+ * install, the setup receipts and (#660) library hosts found from the process table or as ahub/vmem on PATH, then suggests
5
+ * the present roots and the saving-preview command built from them.
5
6
  */
6
- import { lstatSync } from "node:fs";
7
7
  import { realPath } from "./platform.ts";
8
- import { installVersion } from "./formats-raise.ts";
8
+ import { join } from "node:path";
9
+ import { embeddedAmemRoot, installAbsent, installVersion, runningAmemRoots } from "./formats-raise.ts";
9
10
  import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
10
11
  import { readSetupWriterLaunchers, type SetupTarget } from "../setup-writer-roots.ts";
11
12
 
12
13
  export const PLACEMENT_WRITERS_LISTING = "amem migrate --sync-placement --writers";
13
14
  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
+ export const PLACEMENT_WRITERS_NOTE = "Installs bundled inside other tools (agent-hub, vault-mem) appear here when they are in the inventory or a setup receipt, run in a live process, or sit behind ahub or vmem on PATH; add any other host bundle with another --writer-root.";
15
16
 
16
17
  export interface PlacementWriterListing {
17
18
  schema: typeof PLACEMENT_WRITERS_SCHEMA;
18
19
  inventory: { root: string; version: string | null; state: "present" | "missing" }[];
19
20
  running: { root: string; version: string | null; inInventory: boolean };
20
21
  receipts: { target: SetupTarget; root: string; state: "present" | "missing" }[];
22
+ /** #660, additive: amem roots loaded by a live process (`pid`) or behind ahub/vmem on PATH (`host` is the entry script). */
23
+ runningHosts?: { pid?: number; root: string; version: string | null; host?: string }[];
21
24
  suggestedRoots: string[];
22
25
  command: string;
23
26
  note: string;
24
27
  }
25
28
 
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
29
  /** POSIX single-quote shell quoting: the printed command is pasted into a shell as is. */
31
30
  export function shellQuote(value: string): string {
32
31
  return `'${value.replaceAll("'", `'\\''`)}'`;
33
32
  }
34
33
  export function placementWriterCommand(roots: readonly string[]): string {
35
34
  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`;
35
+ return `amem migrate --sync-placement --checkpoint ${flags} --out checkpoint-plan.json, then amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json`;
36
+ }
37
+
38
+ /** #660 discovery seams: the `pid args` process table, the embedded-package probe and the PATH to resolve ahub/vmem on. */
39
+ export interface PlacementWriterDiscovery { table?: () => string; embedded?: (dir: string) => boolean; path?: string }
40
+ function discoverHosts(own: string, discovery: PlacementWriterDiscovery): NonNullable<PlacementWriterListing["runningHosts"]> {
41
+ const out: NonNullable<PlacementWriterListing["runningHosts"]> = [], seen = new Set<string>();
42
+ const add = (root: string, extra: { pid?: number; host?: string }) => {
43
+ let canonical: string; try { canonical = realPath(root); } catch { return; }
44
+ if (canonical === own || seen.has(`${canonical}\0${extra.pid ?? ""}`)) return; seen.add(`${canonical}\0${extra.pid ?? ""}`);
45
+ out.push({ ...(extra.pid !== undefined ? { pid: extra.pid } : {}), root: canonical, version: installVersion(canonical), ...(extra.host ? { host: extra.host } : {}) });
46
+ };
47
+ // ponytail: a failed process listing finds no live hosts, and runningAmemRoots splits `ps` args on whitespace, so a script path
48
+ // with a space is missed; the PATH check and an explicit --writer-root still cover them. Upgrade: read argv per pid.
49
+ if (discovery.table) try { for (const row of runningAmemRoots(discovery.table, discovery.embedded)) add(row.root, { pid: row.pid, ...(row.host ? { host: row.host } : {}) }); } catch { /* no live hosts */ }
50
+ for (const dir of (discovery.path ?? "").split(":")) {
51
+ if (!dir.startsWith("/")) continue;
52
+ for (const name of ["ahub", "vmem"]) {
53
+ let script: string; try { script = realPath(join(dir, name)); } catch { continue; }
54
+ const root = embeddedAmemRoot(script, discovery.embedded); if (root) add(root, { host: script });
55
+ }
56
+ }
57
+ return out;
37
58
  }
38
59
 
39
- export function listPlacementWriters(home: string, ownRoot: string): PlacementWriterListing {
60
+ export function listPlacementWriters(home: string, ownRoot: string, discovery: PlacementWriterDiscovery = {}): PlacementWriterListing {
40
61
  const inventory = (readEffectiveSyncPlacementWriters(home).roots ?? []).map(root => {
41
- const state = absent(root) ? "missing" as const : "present" as const;
62
+ const state = installAbsent(root) ? "missing" as const : "present" as const;
42
63
  return { root, version: state === "present" ? installVersion(root) : null, state };
43
64
  });
44
65
  const own = realPath(ownRoot);
45
66
  const running = { root: own, version: installVersion(own), inInventory: inventory.some(row => row.root === own) };
46
- const receipts = readSetupWriterLaunchers(home);
67
+ const receipts = readSetupWriterLaunchers(home), runningHosts = discoverHosts(own, discovery);
47
68
  const present = new Set<string>([own]);
48
69
  for (const row of [...inventory, ...receipts]) if (row.state === "present") present.add(realPath(row.root));
70
+ for (const row of runningHosts) if (row.version !== null && !installAbsent(row.root)) present.add(row.root);
49
71
  const suggestedRoots = [...present].sort();
50
- return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
72
+ return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, runningHosts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
51
73
  }
52
74
 
53
75
  export function placementWritersText(listing: PlacementWriterListing): string {
@@ -58,6 +80,9 @@ export function placementWritersText(listing: PlacementWriterListing): string {
58
80
  lines.push("setup receipts:");
59
81
  for (const row of listing.receipts) lines.push(` ${row.target} ${row.state} ${row.root}`);
60
82
  if (!listing.receipts.length) lines.push(" (none)");
83
+ lines.push("library hosts:");
84
+ for (const row of listing.runningHosts ?? []) lines.push(` ${row.version ?? "unknown"} ${row.root}${row.pid !== undefined ? ` (pid ${row.pid})` : " (on PATH)"}`);
85
+ if (!listing.runningHosts?.length) lines.push(" (none found)");
61
86
  lines.push("roots to declare:");
62
87
  for (const root of listing.suggestedRoots) lines.push(` ${root}`);
63
88
  lines.push(`next: ${listing.command}`, `note: ${listing.note}`);
@@ -15,9 +15,7 @@ import { readWriterHistory, writeWriterRenewalIntent, writeWriterRevision, appen
15
15
  import { createWriterRevision, createWriterCommit, createWriterRenewalIntent, writerRevisionWriters, WRITER_REVISION_SCHEMA, WRITER_RENEWAL_INTENT_SCHEMA, WRITER_REVISION_LIMIT, WRITER_COMMIT_LOG, SharedWriterRevisionError, type WriterRenewalIntent } from "./sync-placement-writer-revision-format.ts";
16
16
  import { requireWriterRenewalHomeFloor } from "./sync-placement-prerequisites.ts";
17
17
  import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
18
- import { withPlacementActivationFences as activationFences } from "./sync-placement-activation-locks.ts";
19
- /** #624: renewal runs on an active inventory, so its readers refusal names the checkpoint continuation. */
20
- const withPlacementActivationFences: typeof activationFences = (home, directories, work) => activationFences(home, directories, work, { renewal: true });
18
+ import { withPlacementMutationFences } from "./sync-placement-activation-locks.ts";
21
19
  import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
22
20
  import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
23
21
  import { captureInspectionPendingPrunes } from "./sync-placement-inspection-pending.ts";
@@ -95,7 +93,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
95
93
  try{history=readWriterHistory(home,b,{allowPending:true});}catch(error){
96
94
  if(options.mode!=="abandon"||!error||typeof error!=="object"||types.isProxy(error)||!(error instanceof SharedWriterRevisionError)||Object.getOwnPropertyDescriptor(error,"code")?.value!=="staging")throw error;
97
95
  requireWriterRenewalHomeFloor(home);
98
- return withPlacementActivationFences(home,directories(home,initial),async(mutation,owner)=>{
96
+ return withPlacementMutationFences(home,directories(home,initial),async(mutation,owner)=>{
99
97
  const locator=readInitialSyncPlacementWriterLocator(home),seal=hashJSON({action:"abandon-unpublished-writer-staging",...b,initialLocatorHash:locator.seal});
100
98
  let authorized=false;try{authorized=options.authorize(Object.freeze({seal,generation:b.generation,homeHash:b.homeHash}))===true;}catch{}
101
99
  if(!authorized)throw new WriterRenewalError("authorization");
@@ -106,7 +104,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
106
104
  };
107
105
  const cleared=abandonUnpublishedWriterStaging(home,{...b,initialLocatorHash:locator.seal},{mutation,assertCurrent,assertCommittedHistory});
108
106
  return{mode:options.mode,active:true,abandoned:true,unpublishedStagingRemoved:cleared.removed,nextStep:"amem migrate --sync-placement --dry-run"};
109
- });
107
+ }, { surface: "renewal" });
110
108
  }
111
109
  if(!history.pending&&(options.mode==="resume"||options.mode==="abandon")&&history.sequence===0)return undefined;
112
110
  if(options.mode==="dry-run"){
@@ -132,7 +130,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
132
130
  // An unlocked refusal stays entirely passive; crashed owners must first be reclaimed by the real fences below.
133
131
  const passivePreflight=options.mode==="apply"||options.mode==="resume"&&history.pending&&!history.appendStarted&&!lstatSync(join(home,"profile.lock"),{throwIfNoEntry:false});
134
132
  let sourceCheck=passivePreflight?(journalClear(home,b.epochHash),pendingSources(home)):undefined;
135
- return withPlacementActivationFences(home,directories(home,initial),async(mutation,owner)=>{
133
+ return withPlacementMutationFences(home,directories(home,initial),async(mutation,owner)=>{
136
134
  if(options.mode==="resume"&&history.pending&&!history.appendStarted){journalClear(home,b.epochHash);sourceCheck=pendingSources(home,owner);}
137
135
  let intent=history.pending;
138
136
  const cleanupOnly=!intent&&options.mode==="resume"&&!!history.current;
@@ -185,5 +183,5 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
185
183
  check();writeWriterRenewalIntent(home,fixed,storage);writeWriterRevision(home,fixed,storage);appendWriterCommit(home,fixed,storage);
186
184
  clearWriterRenewalIntent(home,fixed,{...storage,assertCurrent:metadata});
187
185
  return{mode:options.mode,active:true,renewed:true,epochHash:b.epochHash,sequence:fixed.revision.sequence,revisionHash:fixed.commit.seal,remainingRevisions:WRITER_REVISION_LIMIT-fixed.revision.sequence};
188
- });
186
+ }, { surface: "renewal" });
189
187
  }
@@ -1,3 +1,4 @@
1
+ import { purgePublicationRefusal } from "./purge-intent.ts";
1
2
  import type { PlacementCapturePort } from "./sync-placement-capture.ts";
2
3
  import { placementRuntimeRefusal } from "./sync-placement-guard.ts";
3
4
  import { assertFormatFloor } from "./formats.ts";
@@ -287,7 +288,7 @@ function missingSyncRemote(store: MemoryStore): string | undefined {
287
288
 
288
289
  export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Promise<SyncResult> {
289
290
  assertFormatFloor(store.profile.home, "sync");
290
- const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
291
+ const placementRefusal = purgePublicationRefusal(store.profile.home) ?? placementRuntimeRefusal(store.profile.home, store.profile);
291
292
  if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
292
293
  if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") {
293
294
  // #450: the whole activated inventory, independent of the binding that opened `store`.
@@ -347,7 +348,7 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
347
348
  if (!release) return fail("another sync is running on this machine");
348
349
  let releaseMutation: (() => void) | undefined, releaseCurated: (() => void) | undefined;
349
350
  try {
350
- releaseMutation = acquireMutation(dir);
351
+ releaseMutation = acquireMutation(dir, store.profile.home);
351
352
  if (!releaseMutation) return fail("another memory mutation is running on this machine");
352
353
  releaseCurated = store.beginCuratedCacheUpdate();
353
354
  // Holding sync.lock, no other git runs in this repository: what a killed one left behind is stale.
@@ -0,0 +1,14 @@
1
+ /**
2
+ * #580: a caller-chosen key naming the subject a note states, carried as the `about` node `topic:<key>` (owner ruling
3
+ * 2026-11-28: no NoteEntry field and no format floor, since every reader already keeps and indexes `about` nodes).
4
+ */
5
+ export const TOPIC_FORM = "[a-z0-9][a-z0-9/-]{0,63}";
6
+ const TOPIC = new RegExp(`^${TOPIC_FORM}$`);
7
+ export const TOPIC_PREFIX = "topic:";
8
+ export const validTopic = (value: unknown): value is string => typeof value === "string" && TOPIC.test(value);
9
+ export const topicNode = (topic: string): string => `${TOPIC_PREFIX}${topic}`;
10
+ /** The note's topic, or null. A note carries at most one when written through amem; the first valid one wins otherwise. */
11
+ export function topicOf(view: { about: readonly string[] }): string | null {
12
+ for (const node of view.about) if (node.startsWith(TOPIC_PREFIX) && validTopic(node.slice(TOPIC_PREFIX.length))) return node.slice(TOPIC_PREFIX.length);
13
+ return null;
14
+ }
@@ -1,20 +1,29 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { join, resolve } from "node:path";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { isDeepStrictEqual } from "node:util";
7
+ import { acquireMutation } from "./memory/mutation.ts";
7
8
 
8
9
  export interface ConsoleSetup { file: string; module: string; change: "add" | "replace" | "unchanged" | "remove" | "none"; reason?: string }
9
10
 
11
+ /** `$AGENTHUB_HOME/console/plugins/amem.json`, the acon plugin manifest; doctor and `setup all` read the same path. */
12
+ export function consoleManifestFile(env: Readonly<Record<string, string | undefined>> = process.env): string {
13
+ const configured = env.AGENTHUB_HOME;
14
+ const family = configured?.trim() ? resolve(configured) : join(env.HOME?.trim() || homedir(), ".agenthub");
15
+ return join(family, "console", "plugins", "amem.json");
16
+ }
17
+
10
18
  /**
11
19
  * `amem setup console`: the acon plugin manifest `{api, tool, module, sha256}` at `$AGENTHUB_HOME/console/plugins/amem.json`, in a 0700 directory
12
20
  * and a 0600 file, which is what agent-console's scanPlugins accepts. Preview writes nothing; undo removes only a manifest that points at this install.
13
21
  */
14
22
  export function consoleSetup(mode: "preview" | "apply" | "undo", env: Readonly<Record<string, string | undefined>> = process.env,
15
- module = fileURLToPath(new URL("./ui/plugin.ts", import.meta.url))): ConsoleSetup {
16
- const family = env.AGENTHUB_HOME?.trim() ? resolve(env.AGENTHUB_HOME) : join(env.HOME?.trim() || homedir(), ".agenthub");
17
- const dir = join(family, "console", "plugins"), file = join(dir, "amem.json");
23
+ module = fileURLToPath(new URL("./ui/plugin.ts", import.meta.url)), opts: { existingOnly?: boolean } = {}): ConsoleSetup {
24
+ const file = consoleManifestFile(env), dir = dirname(file);
25
+ // #659: `setup all` only refreshes a manifest the person installed; an absent one (also one removed since the caller looked) is never created.
26
+ if ((opts.existingOnly || mode === "undo") && !lstatSync(file, { throwIfNoEntry: false })) return { file, module, change: "none", reason: "no console manifest" };
18
27
  // acon refuses a manifest directory or file that is a link, another kind of entry or another user's; so does setup, before writing anything.
19
28
  for (const [path, kind] of [[dir, "directory"], [file, "file"]] as const) {
20
29
  const info = lstatSync(path, { throwIfNoEntry: false });
@@ -22,27 +31,44 @@ export function consoleSetup(mode: "preview" | "apply" | "undo", env: Readonly<R
22
31
  if (kind === "directory" ? !info.isDirectory() : !info.isFile()) throw Error(`${path}: acon needs a real ${kind}, not a link or another entry`);
23
32
  if (typeof process.getuid === "function" && info.uid !== process.getuid()) throw Error(`${path} is owned by another user; acon would refuse it`);
24
33
  }
25
- const before = lstatSync(file, { throwIfNoEntry: false }) ? JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown> : undefined;
26
- if (mode === "undo") {
27
- if (!before) return { file, module, change: "none", reason: "no console manifest" };
28
- if (before.module !== module) throw Error(`${file} points at another amem install (${String(before.module)}); left as is`);
29
- unlinkSync(file);
30
- return { file, module, change: "remove" };
34
+ const next = mode === "undo" ? undefined : { api: 1, tool: "amem", module, sha256: createHash("sha256").update(readFileSync(module)).digest("hex") };
35
+ if (mode === "preview") return inspectAndUpdate();
36
+ if (mode === "apply" && !opts.existingOnly) mkdirSync(dir, { recursive: true, mode: 0o700 });
37
+ const directory = lstatSync(dir, { throwIfNoEntry: false });
38
+ if (!directory) return { file, module, change: "none", reason: "no console manifest" };
39
+ for (const suffix of ["", "-journal", "-wal", "-shm"]) {
40
+ const lock = lstatSync(join(dir, `mutation-lock.db${suffix}`), { throwIfNoEntry: false });
41
+ if (lock && (!lock.isFile() || lock.nlink !== 1 || lock.uid !== directory.uid || (lock.mode & 0o022) !== 0))
42
+ throw Error("console setup lock is unsafe; inspect the plugin directory before retrying");
31
43
  }
32
- const next = { api: 1, tool: "amem", module, sha256: createHash("sha256").update(readFileSync(module)).digest("hex") };
33
- const mode7 = (path: string, want: number) => (lstatSync(path, { throwIfNoEntry: false })?.mode ?? want) & 0o777;
34
- const modesOk = mode7(dir, 0o700) === 0o700 && mode7(file, 0o600) === 0o600;
35
- if (isDeepStrictEqual(before, next) && modesOk) return { file, module, change: "unchanged" };
36
- const change = before ? "replace" : "add";
37
- if (mode === "apply") {
38
- mkdirSync(dir, { recursive: true, mode: 0o700 });
39
- chmodSync(dir, 0o700);
40
- const temp = `${file}.${process.pid}.tmp`;
41
- writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
42
- renameSync(temp, file);
43
- chmodSync(file, 0o600);
44
+ const release = acquireMutation(dir, dir);
45
+ if (!release) throw Error("console setup is busy; retry after the active console setup exits");
46
+ try { return inspectAndUpdate(); }
47
+ finally { release(); }
48
+
49
+ function inspectAndUpdate(): ConsoleSetup {
50
+ const before = lstatSync(file, { throwIfNoEntry: false }) ? JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown> : undefined;
51
+ // ponytail: external or older writers bypass the console lock. A replace-only filesystem primitive would also exclude their unlink race.
52
+ if (opts.existingOnly && !before) return { file, module, change: "none", reason: "no console manifest" };
53
+ if (mode === "undo") {
54
+ if (!before) return { file, module, change: "none", reason: "no console manifest" };
55
+ if (before.module !== module) throw Error(`${file} points at another amem install (${String(before.module)}); left as is`);
56
+ unlinkSync(file);
57
+ return { file, module, change: "remove" };
58
+ }
59
+ const mode7 = (path: string, want: number) => (lstatSync(path, { throwIfNoEntry: false })?.mode ?? want) & 0o777;
60
+ const modesOk = mode7(dir, 0o700) === 0o700 && mode7(file, 0o600) === 0o600;
61
+ if (isDeepStrictEqual(before, next) && modesOk) return { file, module, change: "unchanged" };
62
+ const change = before ? "replace" : "add";
63
+ if (mode === "apply") {
64
+ chmodSync(dir, 0o700);
65
+ const temp = `${file}.${process.pid}.tmp`;
66
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
67
+ renameSync(temp, file);
68
+ chmodSync(file, 0o600);
69
+ }
70
+ return { file, module, change, ...(modesOk ? {} : { reason: "permissions: plugin directory 0700, manifest 0600" }) };
44
71
  }
45
- return { file, module, change, ...(modesOk ? {} : { reason: "permissions: plugin directory 0700, manifest 0600" }) };
46
72
  }
47
73
 
48
74
  export const consoleSetupText = (result: ConsoleSetup, mode: "preview" | "apply" | "undo"): string =>
@@ -1,5 +1,6 @@
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
6
  import { decodeReceipt, setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
@@ -8,10 +9,13 @@ import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries,
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;
@@ -92,7 +96,8 @@ function launch(record: unknown): string | undefined {
92
96
  }
93
97
 
94
98
  function expectedManagedHookCommands(target: SetupTarget, after: ConfigImage): { event: string; command: string }[] {
95
- if (["jcode", "opencode", "gemini", "agy"].includes(target)) return [];
99
+ if (["jcode", "opencode", "agy"].includes(target)) return [];
100
+ if (target === "gemini") { const base = launch(mcpRecord(target, after)); return base && amemCaptureHooks("gemini", after).length ? [{ event: "SessionEnd", command: `${base} ingest gemini --hook-input --json` }] : []; }
96
101
  const base = launch(mcpRecord(target, after));
97
102
  if (!base) return [];
98
103
  if (target === "claude") return HOOK_EVENTS.map(event => ({ event, command: `${base} hook ${event}` }));
@@ -204,6 +209,28 @@ export function listAgyReceiptLocations(home: string): { receipts: AgyReceiptLoc
204
209
  return { receipts, incomplete };
205
210
  }
206
211
 
212
+ 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";
213
+ /** The manifest and its module, read without following links and bounded. */
214
+ function consoleDrift(env: SetupEnvironment, budget: { remaining: number }): SetupDriftEntry | "absent" | "current" {
215
+ const file = consoleManifestFile(env), finding = (kind: SetupDriftEntry["kind"], reason: string): SetupDriftEntry => ({ target: "console", file, entry: "plugin manifest", reason, kind });
216
+ let manifest: Record<string, unknown>;
217
+ try {
218
+ const raw = safeImage(file, 64 * 1024, budget);
219
+ if (raw.bytes === null) return "absent";
220
+ const value: unknown = JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"));
221
+ if (!plain(value) || typeof value.module !== "string" || !isAbsolute(value.module) || typeof value.sha256 !== "string") return finding("drift", CONSOLE_DRIFT_REASON);
222
+ manifest = value;
223
+ } catch { return finding("unavailable", "the acon console plugin manifest cannot be read safely; inspect it or run amem setup console --apply"); }
224
+ try {
225
+ const module = safeImage(String(manifest.module), SETUP_CONFIG_BYTES, budget);
226
+ if (module.bytes === null || createHash("sha256").update(Buffer.from(module.bytes, "base64")).digest("hex") !== manifest.sha256) return finding("drift", CONSOLE_DRIFT_REASON);
227
+ } catch { return finding("unavailable", "the acon console plugin module cannot be read safely; run amem setup console --apply"); }
228
+ // An intact module from an older install still loads, but it serves that release's panels: refresh it to this one.
229
+ const theirs = installVersion(dirname(dirname(dirname(String(manifest.module))))), ours = installVersion(fileURLToPath(new URL("..", import.meta.url)));
230
+ 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`);
231
+ return "current";
232
+ }
233
+
207
234
  /** Read setup receipts and only the resolver-selected native config files. This function never writes. */
208
235
  export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
209
236
  const env = options.env ?? process.env;
@@ -263,7 +290,7 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
263
290
  if (!isDeepStrictEqual(expected, mcpRecord(target, current))) entries.push(entry(target, change.path, name, "managed MCP registration is missing or changed", "drift"));
264
291
  } catch { entries.push(entry(target, change.path, name, "managed MCP registration could not be checked", "unavailable")); unavailable = true; }
265
292
  }
266
- const hasHookSurface = target === "qwen" && change.key === `${target}:0` || target === "claude" && change.key === `${target}:1` || target === "codex" && change.key === `${target}:1` || target === "kimi" && change.key === `${target}:1`;
293
+ const hasHookSurface = (target === "qwen" || target === "gemini") && change.key === `${target}:0` || target === "claude" && change.key === `${target}:1` || target === "codex" && change.key === `${target}:1` || target === "kimi" && change.key === `${target}:1`;
267
294
  if (hasHookSurface) {
268
295
  try {
269
296
  const expected = expectedManagedHookCommands(target, receipt.changes[0]!.after);
@@ -273,7 +300,7 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
273
300
  } catch { entries.push(entry(target, change.path, "hooks", "managed hooks could not be checked", "unavailable")); unavailable = true; }
274
301
  }
275
302
  // #512: an amem capture hook whose launch path is gone fails on every session end. Named by target, file and event, never its command.
276
- const captureSurface = { codex: "codex:1", kimi: "kimi:1", qwen: "qwen:0", pi: "pi:1" }[target as string];
303
+ const captureSurface = { codex: "codex:1", kimi: "kimi:1", qwen: "qwen:0", pi: "pi:1", gemini: "gemini:0" }[target as string];
277
304
  if (captureSurface === change.key) {
278
305
  try {
279
306
  for (const row of amemCaptureHooks(target, current)) {
@@ -327,6 +354,10 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
327
354
  const install = installMissing("agy", receipt.changes[0]!.after);
328
355
  if (install) { entries.push(installEntry("agy", "setup receipt of another workspace", install)); if (install === "unavailable") unavailable = true; }
329
356
  }
357
+ // #659: an acon plugin manifest goes stale when amem moves or its UI module changes; only an existing manifest is checked.
358
+ const plugin = consoleDrift(env, budget);
359
+ if (plugin !== "absent") { anyReceipt = true; checked++; }
360
+ if (typeof plugin === "object") { if (plugin.kind === "unavailable") unavailable = true; entries.push(plugin); }
330
361
  const status: SetupDriftStatus = entries.some(value => value.kind === "drift" || value.kind === "review-needed") ? "attention"
331
362
  : unavailable ? "unavailable" : anyReceipt ? "ok" : "skipped";
332
363
  return { status, checked, entries, ...(!anyReceipt && !entries.length ? { reason: "no applied setup receipts found" } : {}) };
@@ -162,6 +162,8 @@ export function restoreOwned(target: string, index: number, before: ConfigImage,
162
162
  if (sameImage(current, before)) return current;
163
163
  // Qwen keeps both managed surfaces in one settings file and one receipt image.
164
164
  if (target === "qwen" && index === 0) return restoreJsonHooks(before, after, restoreMcpOwned(target, before, after, current), true);
165
+ // #647: Gemini's settings.json holds the MCP entry and the SessionEnd capture hook.
166
+ if (target === "gemini" && index === 0) return restoreJsonHooks(before, after, restoreMcpOwned(target, before, after, current));
165
167
  if (index === 0) return restoreMcpOwned(target, before, after, current);
166
168
  if (target === "claude" || target === "codex") return restoreJsonHooks(before, after, current);
167
169
  if (target === "kimi") return restoreKimi(before, after, current);
@@ -171,7 +173,7 @@ export function restoreOwned(target: string, index: number, before: ConfigImage,
171
173
  }
172
174
  /** Only removal of an original/adopted hook needs receipt v2; added-only receipts remain v1-readable. */
173
175
  export function retiresOriginalHook(target: string, index: number, before: ConfigImage, after: ConfigImage): boolean {
174
- if (target === "qwen" && index === 0 || ["claude", "codex"].includes(target) && index === 1) {
176
+ if ((target === "qwen" || target === "gemini") && index === 0 || ["claude", "codex"].includes(target) && index === 1) {
175
177
  const strict = target === "qwen";
176
178
  return added(hooks(json(after), strict), hooks(json(before), strict), row => row.id).length > 0;
177
179
  }
@@ -187,6 +189,10 @@ export function managedAfter(target: string, index: number, before: ConfigImage,
187
189
  return isDeepStrictEqual(mcpRecord(target, after), mcpRecord(target, current)) && needed.every(row => live.some(value => value.id === row.id))
188
190
  && retired.every(row => live.filter(value => value.id === row.id).length <= installed.filter(value => value.id === row.id).length);
189
191
  }
192
+ if (target === "gemini" && index === 0) {
193
+ const needed = added(hooks(json(before)), hooks(json(after)), row => row.id), live = hooks(json(current));
194
+ return isDeepStrictEqual(mcpRecord(target, after), mcpRecord(target, current)) && needed.every(row => live.some(value => value.id === row.id));
195
+ }
190
196
  if (index === 0) return isDeepStrictEqual(mcpRecord(target, after), mcpRecord(target, current));
191
197
  if (target === "jcode") return jcodeHooksManaged(before, after, current);
192
198
  if (target === "claude" || target === "codex") {
@@ -238,6 +244,8 @@ export function amemCaptureCommand(command: string): { target: string; bun: stri
238
244
  }
239
245
  tokens.push(token);
240
246
  }
247
+ // #647: Gemini's form reads its SessionEnd stdin: `ingest gemini --hook-input --json`.
248
+ if (tokens[4] === "gemini" && tokens[5] === "--hook-input") tokens.splice(5, 1);
241
249
  const [bun, smol, entry, verb, target, json, ...rest] = tokens;
242
250
  if (!bun || !entry || !target || smol !== "--smol" || verb !== "ingest" || rest.length || (json !== undefined && json !== "--json")) return undefined;
243
251
  if (!bun.startsWith("/") || !entry.startsWith("/") || !entry.endsWith("/@staix/agent-mem/bin/amem.js") || !/^[a-z]+$/.test(target)) return undefined;
@@ -45,7 +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
+ 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`;
49
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`;
50
50
  }
51
51
  /**