@staix/agent-mem 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFileSync, closeSync, fstatSync, lstatSync, openSync, readFileSync, readSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { Database } from "bun:sqlite";
5
+ import { effectiveAliases } from "./aliases.ts";
6
+ import { indexFileName } from "./index-file.ts";
7
+ import { realPath } from "./platform.ts";
8
+ import { memoryProjectKey } from "./project.ts";
9
+
10
+ /**
11
+ * #581: which project key each working directory resolved to last, on this machine. `roots.jsonl` in the memory home
12
+ * holds only `sha256(realPath(dir))`, never path text, and is never synced or exported. Append-only; the latest line
13
+ * per root wins. The only writer is the native SessionStart path (first sight, and a re-bind after an alias settled a
14
+ * transition); `amem project keep-separate --confirm` appends a `keep`. Status, doctor and MCP only read it.
15
+ */
16
+ export const ROOTS_SCHEMA = "agent-mem.roots/v1";
17
+ export const ROOTS_FILE = "roots.jsonl";
18
+ const READ_BOUND = 256 * 1024;
19
+
20
+ export interface RootLine { schema: typeof ROOTS_SCHEMA; op: "bind" | "keep"; root: string; key: string; prev?: string; at: string; machine?: string }
21
+ export interface ProjectTransition { state: "project_transition"; previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string }
22
+
23
+ /** The key every #581 reader and writer compares: the hook's own resolution, isolated from an inherited GIT_* environment. Raw, before alias resolution. */
24
+ export function transitionKey(cwd: string): string {
25
+ return memoryProjectKey(cwd, { repositoryIsolation: true });
26
+ }
27
+
28
+ export const rootsLogPath = (home: string): string => join(home, ROOTS_FILE);
29
+
30
+ /**
31
+ * The working root a directory belongs to: the nearest ancestor holding `.git` (a directory or a worktree's file),
32
+ * found by `lstat` alone so the hook spawns no git process; without one, the directory itself.
33
+ * ponytail: a submodule or nested repository is its own root, the same boundary `git rev-parse --show-toplevel` draws;
34
+ * a repository more than 32 levels up is not found and the directory stands for itself.
35
+ */
36
+ export function workingRoot(dir: string): string {
37
+ const start = realPath(dir);
38
+ for (let current = start, depth = 0; depth < 32; current = dirname(current), depth++) {
39
+ if (lstatSync(join(current, ".git"), { throwIfNoEntry: false })) return current;
40
+ if (dirname(current) === current) break;
41
+ }
42
+ return start;
43
+ }
44
+
45
+ /** sha256 hex of the working root's real path; the path text itself is never stored. */
46
+ export function rootHash(dir: string): string {
47
+ return createHash("sha256").update(workingRoot(dir)).digest("hex");
48
+ }
49
+
50
+ /** Latest line per root, from at most the last 256 KB. Missing, unreadable or malformed input yields fewer lines, never a throw. */
51
+ export function readRootBindings(home: string, maxBytes = READ_BOUND): Map<string, RootLine> {
52
+ const latest = new Map<string, RootLine>();
53
+ let text = "";
54
+ try {
55
+ const fd = openSync(rootsLogPath(home), "r");
56
+ try {
57
+ const size = fstatSync(fd).size, start = Math.max(0, size - maxBytes), buffer = Buffer.alloc(size - start);
58
+ readSync(fd, buffer, 0, buffer.length, start);
59
+ text = buffer.toString("utf8");
60
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1); // drop the cut first line
61
+ } finally { closeSync(fd); }
62
+ } catch { return latest; }
63
+ for (const raw of text.split("\n")) {
64
+ if (!raw) continue;
65
+ try {
66
+ const line = JSON.parse(raw) as RootLine;
67
+ if (line?.schema !== ROOTS_SCHEMA || (line.op !== "bind" && line.op !== "keep") || typeof line.root !== "string" || !/^[0-9a-f]{64}$/.test(line.root) || typeof line.key !== "string" || !line.key) continue;
68
+ latest.set(line.root, line);
69
+ } catch { /* a malformed line is skipped */ }
70
+ }
71
+ return latest;
72
+ }
73
+
74
+ const shellWord = (word: string) => /^[A-Za-z0-9@%+=:,./_-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
75
+ export const aliasCommandFor = (previousKey: string, key: string) => `amem alias add ${shellWord(previousKey)} ${shellWord(key)}`;
76
+ export const KEEP_COMMAND = "amem project keep-separate";
77
+
78
+ /** Two keys one alias hop apart (either direction, or both onto one canonical key) are already joined. */
79
+ function joined(aliases: Map<string, string>, a: string, b: string): boolean {
80
+ return (aliases.get(a) ?? a) === (aliases.get(b) ?? b);
81
+ }
82
+
83
+ /** The transition for this root, if its recorded key differs from `key` and nothing joins or keeps them apart. Never throws. */
84
+ export function projectTransition(home: string, dir: string, key: string, countCurated?: (key: string) => number | null): ProjectTransition | undefined {
85
+ try {
86
+ const line = readRootBindings(home).get(rootHash(dir));
87
+ if (!line || line.key === key) return undefined;
88
+ if (joined(effectiveAliases(home), line.key, key)) return undefined;
89
+ let previousCuratedNotes: number | null = null;
90
+ try { previousCuratedNotes = countCurated ? countCurated(line.key) : null; } catch { previousCuratedNotes = null; }
91
+ return { state: "project_transition", previousKey: line.key, key, previousCuratedNotes, aliasCommand: aliasCommandFor(line.key, key), keepCommand: KEEP_COMMAND };
92
+ } catch { return undefined; }
93
+ }
94
+
95
+ export function transitionNotice(t: ProjectTransition): string {
96
+ const count = t.previousCuratedNotes === null ? "" : ` (${t.previousCuratedNotes} curated notes)`;
97
+ return `amem: project key changed for this directory: was ${t.previousKey}${count}, now ${t.key}. Join: ${t.aliasCommand} Keep apart: ${t.keepCommand}`;
98
+ }
99
+
100
+ /** Curated notes a key holds, from its derived index read-only (busy 0); null when the index is absent, locked or unreadable. A bounded local read. */
101
+ export function curatedCount(home: string, key: string, shardDir: (home: string, key: string) => string): number | null {
102
+ // A curated shard's own index first, then a shared-v1 home's single index (which holds every project's rows).
103
+ for (const file of [indexFileName(false), indexFileName(true)].flatMap(name => [join(shardDir(home, key), name), join(home, name)])) {
104
+ let db: Database | undefined;
105
+ try {
106
+ if (!lstatSync(file, { throwIfNoEntry: false })) continue;
107
+ db = new Database(file, { readonly: true });
108
+ db.run("PRAGMA busy_timeout = 0");
109
+ return (db.query("SELECT COUNT(*) AS n FROM entries WHERE scope = 'project' AND project = ?").get(key) as { n: number }).n;
110
+ } catch { return null; } finally { db?.close(); }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ function machineOf(home: string): string | undefined {
116
+ try { const id = JSON.parse(readFileSync(join(home, "machine.json"), "utf8")).id; return typeof id === "string" ? id : undefined; } catch { return undefined; }
117
+ }
118
+
119
+ function append(home: string, line: RootLine): void {
120
+ appendFileSync(rootsLogPath(home), JSON.stringify(line) + "\n", { mode: 0o600 });
121
+ }
122
+
123
+ /**
124
+ * The SessionStart writer. Appends a `bind` on first sight of a root, and a re-bind when the recorded key is already
125
+ * alias-joined to the resolved one (so a later change names the middle key). A differing, unjoined key is left alone
126
+ * so the notice persists until a person settles it. Fail-open: a write or read error yields no line and no throw.
127
+ */
128
+ export function observeRoot(home: string, dir: string, key: string, now: () => number = Date.now): "appended" | "unchanged" | "transition" | "failed" {
129
+ try {
130
+ const root = rootHash(dir), line = readRootBindings(home).get(root);
131
+ if (line?.key === key) return "unchanged";
132
+ if (line && !joined(effectiveAliases(home), line.key, key)) return "transition";
133
+ const machine = machineOf(home);
134
+ append(home, { schema: ROOTS_SCHEMA, op: "bind", root, key, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) });
135
+ return "appended";
136
+ } catch { return "failed"; }
137
+ }
138
+
139
+ /** `amem project keep-separate --confirm`: record the resolved key for this root on purpose, ending the transition without joining. */
140
+ export function recordKeepSeparate(home: string, dir: string, transition: ProjectTransition, now: () => number = Date.now): RootLine {
141
+ const machine = machineOf(home);
142
+ const line: RootLine = { schema: ROOTS_SCHEMA, op: "keep", root: rootHash(dir), key: transition.key, prev: transition.previousKey, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) };
143
+ append(home, line);
144
+ return line;
145
+ }
@@ -9,6 +9,8 @@ export interface StatusView {
9
9
  active: boolean; generation?: string; phase?: string;
10
10
  pending: Record<string, unknown> & { rows: number };
11
11
  deadLeasesRemoved?: { lease: string; at: string }[]; refusals?: string[];
12
+ /** #581: present only while this working root last resolved to a different, unjoined key. */
13
+ projectTransition?: { previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string };
12
14
  }
13
15
 
14
16
  /** Human rendering options (#590): `--verbose` history lines, the wrap width and the version in the context line. */
@@ -68,7 +70,9 @@ export function statusText(status: StatusView, s: Style = PLAIN, opts: ReportTex
68
70
  if (interrupted) findings.push({ text: "a shard migration stopped after capture; authoring is refused until it activates", next: ["amem migrate --shards --resume"] });
69
71
  for (const reason of refusals) findings.push({ text: `migration refusal: ${reason}`, next: [] });
70
72
  if (status.pending.rows && !interrupted) findings.push({ text: `${plural(status.pending.rows, "old-layout row")} wait for the shard migration`, next: ["amem migrate --shards --dry-run", "amem migrate --shards --resume"] });
71
- const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" ? "attention" : "ok";
73
+ const transition = status.projectTransition;
74
+ if (transition) findings.push({ text: `this directory resolved to ${transition.previousKey}${transition.previousCuratedNotes === null ? "" : ` (${plural(transition.previousCuratedNotes, "curated note")})`} before and to ${transition.key} now`, next: [transition.aliasCommand, transition.keepCommand] });
75
+ const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" || transition ? "attention" : "ok";
72
76
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
73
77
  const limitFacts = Object.entries(limits).filter(([, value]) => value !== undefined && value !== null)
74
78
  .map(([key, value]) => typeof value === "number" && key.endsWith("Bytes") ? `${wordedKey(key)} ${humanBytes(value)}`
@@ -8,12 +8,14 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
8
8
  import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
9
9
  /** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
10
10
  export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
11
+ /** #624: only a writer renewal on an active inventory can continue through the checkpoint, which never waits for readers. */
12
+ export const PLACEMENT_RENEWAL_READERS_CONTINUATION = " To renew writers while sessions keep running, use the checkpoint instead, which does not wait for readers: %s.".replace("%s", "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");
11
13
  export class PlacementInventoryFenceError extends Error{
12
- constructor(readonly causeClass:"readers"|"busy",checkpoint=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.`);this.name="PlacementInventoryFenceError";}
14
+ constructor(readonly causeClass:"readers"|"busy",checkpoint=false,renewal=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.${renewal&&causeClass==="readers"?PLACEMENT_RENEWAL_READERS_CONTINUATION:""}`);this.name="PlacementInventoryFenceError";}
13
15
  }
14
16
  type FenceWork<T>=(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>;
15
- async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean},work:FenceWork<T>):Promise<T> {
16
- const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers);};
17
+ async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean;renewal?:boolean},work:FenceWork<T>):Promise<T> {
18
+ const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers,options.renewal===true);};
17
19
  return withProfileLock(home,async()=>{
18
20
  const releases:(()=>void)[]=[];
19
21
  try {
@@ -30,8 +32,8 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
30
32
  });
31
33
  }
32
34
  /** Activation, renewal and admission: every live reader lease refuses, as before. */
33
- export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
34
- return withFences(home,directories,{readers:true},work);
35
+ export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>,options:{renewal?:boolean}={}):Promise<T> {
36
+ return withFences(home,directories,{readers:true,renewal:options.renewal===true},work);
35
37
  }
36
38
  /**
37
39
  * #578 Q1: checkpoint confirm, resume and abandon exclude placement writers only (profile lock, every mutation and sync
@@ -0,0 +1,18 @@
1
+ import type { SyncOptions } from "./sync.ts";
2
+
3
+ /**
4
+ * #626, internal to one placement inventory run: the remote's advertised placement refs by remote URL, read once and
5
+ * shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
6
+ * fresh map to its own options object, and a publication reached with other options reads per run as before.
7
+ * Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
8
+ */
9
+ const runs = new WeakMap<SyncOptions, Map<string, ReadonlyMap<string, string>>>();
10
+
11
+ export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
12
+ runs.set(opts, new Map());
13
+ return opts;
14
+ }
15
+
16
+ export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
17
+ return runs.get(opts);
18
+ }
@@ -4,6 +4,7 @@
4
4
  * person-written floor record (`amem formats raise` is the one writer).
5
5
  */
6
6
  import { randomBytes } from "node:crypto";
7
+ import { lstatSync } from "node:fs";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { types } from "node:util";
9
10
  import { memoryPolicySnapshot } from "./policy.ts";
@@ -25,7 +26,7 @@ import { PLACEMENT_CHECKPOINT_LIMIT, PLACEMENT_CHECKPOINT_MIN_READER, validateCh
25
26
  import { withPlacementCheckpointFences } from "./sync-placement-activation-locks.ts";
26
27
  import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
27
28
  import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
28
- import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
29
+ import { initialPlacementWriterContext, placementWriterRefusalDetail } from "../sync-placement-writer-context.ts";
29
30
  import { readSetupWriterRoots, SetupWriterRootsError } from "../setup-writer-roots.ts";
30
31
  import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
31
32
  import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
@@ -35,7 +36,7 @@ const RESUME = `${CHECKPOINT_PREVIEW} --resume`, ABANDON = `${CHECKPOINT_PREVIEW
35
36
  const homeFloorAtLeast = (home: string, minimum: string): boolean =>
36
37
  (readFormatFloors(home) ?? []).some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, minimum));
37
38
 
38
- export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history";
39
+ export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history" | "writer-missing";
39
40
  const MESSAGES: Record<PlacementCheckpointCause, string> = {
40
41
  pending: PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
41
42
  "commit-started": `The placement checkpoint's commit line has started, so it can no longer be abandoned; run ${RESUME} to complete it.`,
@@ -45,8 +46,9 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
45
46
  obligation: "The placement journal has an unfinished append, publication, reservation, renewal or source recovery; finish it with amem sync (or the pending renewal with amem migrate --sync-placement --resume), then preview the checkpoint again.",
46
47
  changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
47
48
  inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
48
- candidate: `A checkpoint carries one writer renewal: pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
49
+ candidate: `A checkpoint carries one writer renewal: list the inventory and the roots to declare with amem migrate --sync-placement --writers, then pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
49
50
  history: "",
51
+ "writer-missing": "",
50
52
  };
51
53
  /** #567: the retained-history cause class and, for `bound`, which bound with its counts. Never a path, row or object id. */
52
54
  export interface PlacementCheckpointHistoryRefusal { category: "shard history"; cause: ShardHistoryCause; kind?: string; limit?: number; observed?: number }
@@ -62,7 +64,7 @@ export class PlacementCheckpointError extends Error {
62
64
  readonly history?: PlacementCheckpointHistoryRefusal;
63
65
  constructor(readonly causeClass: PlacementCheckpointCause, detail = "", history?: PlacementCheckpointHistoryRefusal) {
64
66
  super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.`
65
- : causeClass === "history" && history ? historyMessage(history) : MESSAGES[causeClass] + (detail ? ` ${detail}` : ""));
67
+ : causeClass === "history" && history ? historyMessage(history) : [MESSAGES[causeClass], detail].filter(Boolean).join(" "));
66
68
  this.name = "PlacementCheckpointError";
67
69
  if (causeClass === "history" && history) this.history = history;
68
70
  }
@@ -86,10 +88,17 @@ function input(home: string, a: ActivePlacementBinding, roots: PlacementCheckpoi
86
88
  }
87
89
  function measured(home: string, writerRoots: readonly string[], ownRoot: string): PlacementCheckpointInput["roots"] {
88
90
  if (!writerRoots.length) throw new PlacementCheckpointError("candidate");
89
- try { return initialPlacementWriterContext(home, writerRoots, ownRoot).measurement.roots; } catch { throw new PlacementCheckpointError("candidate"); }
91
+ // #634: name a removed install before measurement turns it into a generic inventory refusal; preview and confirm both pass here.
92
+ const missing = writerRoots.find(installAbsent);
93
+ if (missing !== undefined) throw new PlacementCheckpointError("writer-missing", missingWriterMessage(missing));
94
+ try { return initialPlacementWriterContext(home, writerRoots, ownRoot).measurement.roots; }
95
+ catch (error) {
96
+ const refusal = placementWriterRefusalDetail(error);
97
+ if (refusal && !(refusal.rootCategory === "running CLI" && refusal.causeClass === "missing")) throw error;
98
+ throw new PlacementCheckpointError("candidate");
99
+ }
90
100
  }
91
101
  function plan(home: string, epochHash: string, value: PlacementCheckpointInput): CheckpointIntent {
92
- if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
93
102
  try { return planPlacementCheckpoint(home, epochHash, value); }
94
103
  catch (error) {
95
104
  const code = error instanceof SyncPlacementJournalError ? Object.getOwnPropertyDescriptor(error, "code")?.value : undefined;
@@ -119,14 +128,17 @@ export interface PlacementCheckpointPreview {
119
128
  */
120
129
  export async function previewPlacementCheckpoint(homeInput: string, opts: { writerRoots: readonly string[]; ownRoot: string }): Promise<PlacementCheckpointPreview> {
121
130
  const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
122
- const roots = measured(home, opts.writerRoots, opts.ownRoot), intent = plan(home, epochHash, input(home, a, roots, randomBytes(32).toString("hex")));
131
+ const roots = measured(home, opts.writerRoots, opts.ownRoot);
132
+ if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
133
+ checkWriterVersions(home, roots);
134
+ const intent = plan(home, epochHash, input(home, a, roots, randomBytes(32).toString("hex")));
123
135
  const journal = readPlacementJournal(home, epochHash), window = resolvePlacementWindow(home, epochHash);
124
136
  const { headroom, journalObjects, assertCurrent } = await checkpointHeadroom(home, intent);
125
137
  assertCurrent();
126
138
  const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
127
139
  return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
128
140
  floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
129
- nextStep: `${CHECKPOINT_PREVIEW} --confirm --plan <saved preview JSON> --writer-root <install root> (repeat for every install)` };
141
+ nextStep: `(umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install, then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list` };
130
142
  }
131
143
  async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
132
144
  const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
@@ -167,13 +179,29 @@ function reviewedHeadroom(value: unknown): unknown {
167
179
  if (!detached) throw new PlacementCheckpointError("changed");
168
180
  return detached;
169
181
  }
182
+ /**
183
+ * #634: an install whose root no longer exists (ENOENT or ENOTDIR on the root itself). An existing root with a missing or
184
+ * unreadable package.json is not absent: it can still run, so the floor check keeps refusing it.
185
+ */
186
+ function installAbsent(root: string): boolean {
187
+ try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
188
+ }
189
+ function missingWriterMessage(root: string): string {
190
+ return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with (umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list.`;
191
+ }
170
192
  function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
171
193
  if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
172
194
  // This reader itself below the recorded floor cannot measure anything: name the writer cause, not the inventory.
173
195
  try { assertFormatFloor(home, "sync"); } catch { throw new PlacementCheckpointError("writer-below-floor"); }
174
- if (!roots) return;
196
+ if (roots) checkWriterVersions(home, roots);
197
+ }
198
+ function checkWriterVersions(home: string, roots: PlacementCheckpointInput["roots"]): void {
175
199
  const effective = readEffectiveSyncPlacementWriters(home).roots ?? [];
176
- const versions = [...roots.map(root => root.version), ...effective.map(root => installVersion(root))];
200
+ // #634: an inventoried install that is gone from disk and left out of the new plan can no longer write here; the
201
+ // renewal removes it. A root the new plan measures is checked through its measured version.
202
+ const renewed = new Set(roots.map(root => root.root));
203
+ const retained = effective.filter(root => !renewed.has(root) && !installAbsent(root));
204
+ const versions = [...roots.map(root => root.version), ...retained.map(root => installVersion(root))];
177
205
  const floors = (readFormatFloors(home) ?? []).filter(floor => floor.surface === "home" || floor.surface === "sync");
178
206
  if (versions.some(version => version === null || floors.some(floor => formatVersionBelow(version, floor.minReader)))) throw new PlacementCheckpointError("writer-below-floor");
179
207
  }
@@ -22,6 +22,7 @@ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userSh
22
22
  import { projectState } from "./lifecycle.ts";
23
23
  import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
24
24
  import type { SyncOptions, SyncResult } from "./sync.ts";
25
+ import { bindPlacementAdvertisement } from "./sync-placement-advertisement.ts";
25
26
  import type { MemoryStore } from "./store.ts";
26
27
 
27
28
  const digest = (value: string) => createHash("sha256").update(value).digest("hex");
@@ -98,7 +99,9 @@ function journalRefusal(error: unknown): (SyncResult & { placementRealms: Placem
98
99
  failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
99
100
  }
100
101
 
101
- export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
102
+ export async function syncPlacementInventory(home: string, callerOpts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
103
+ // #626: one remote advertisement per run, shared by its publications (never one a caller passed in).
104
+ const opts: SyncOptions = bindPlacementAdvertisement({ ...callerOpts });
102
105
  let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
103
106
  try {
104
107
  // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
@@ -4,6 +4,7 @@ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, open
4
4
  import { join } from "node:path";
5
5
  import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
+ import { placementAdvertisement } from "./sync-placement-advertisement.ts";
7
8
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
8
9
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
10
  import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
@@ -395,17 +396,45 @@ class PlacementTransport {
395
396
  const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["cat-file", "blob", object]), this.opts.signal, undefined, limit));
396
397
  if (result.code !== 0 || result.out.length < 1) refuse(); return Buffer.from(result.out);
397
398
  }
399
+ /**
400
+ * #626: the placement refs as the remote advertises them, read once per inventory run. One `ls-remote` costs a
401
+ * network round trip, and a run used to pay it once per target. The advertisement is the same read the per-ref call
402
+ * made, so each target still proves its tip against it; a ref this run's push moved is dropped from it (see finish).
403
+ */
404
+ async advertisement(): Promise<ReadonlyMap<string, string>> {
405
+ const shared = placementAdvertisement(this.opts);
406
+ const cached = shared?.get(this.url);
407
+ if (cached) return cached;
408
+ const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["ls-remote", "--refs", "origin", "refs/heads/amem/u", "refs/heads/amem/p/*"]), this.opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES));
409
+ if (result.code !== 0) refuse("remote");
410
+ let text: string; try { text = new TextDecoder("utf-8", { fatal: true }).decode(result.out); } catch { return refuse("remote"); }
411
+ const refs = new Map<string, string>();
412
+ for (const line of text.split("\n")) {
413
+ if (!line) continue;
414
+ const fields = line.split("\t"); if (fields.length !== 2 || !oid(fields[0]) || !/^refs\/heads\/amem\/(?:u|p\/[0-9a-f]{16})$/.test(fields[1]!) || refs.has(fields[1]!)) refuse("remote");
415
+ refs.set(fields[1]!, fields[0]!);
416
+ }
417
+ shared?.set(this.url, refs);
418
+ return refs;
419
+ }
398
420
  async fetch(): Promise<void> {
421
+ const advertisement = await this.advertisement();
399
422
  for (const target of this.targets) {
400
423
  const ref = shardSyncRef(target.realm); if ((await this.git(["symbolic-ref", "--quiet", ref])).code !== 1) refuse();
401
424
  const cached = await this.git(["rev-parse", "--verify", "--quiet", ref]);
402
425
  if (cached.code !== 0 && cached.code !== 1 || cached.code === 0 && !oid(cached.out)) refuse(); target.local = cached.code === 0 ? cached.out : undefined;
403
- const advertised = await this.git(["ls-remote", "--exit-code", "origin", ref]);
404
- if (advertised.code === 2) { if (target.local && !this.journal.publicationReservation) refuse(); target.remote = undefined; target.remoteHistory = undefined; continue; }
405
- const fields = advertised.out.split("\t"); if (advertised.code !== 0 || fields.length !== 2 || !oid(fields[0]) || fields[1] !== ref) refuse();
406
- const incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`; this.refs.push(incoming);
407
- await this.required(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "origin", `${ref}:${incoming}`]);
408
- const tip = await this.required(["rev-parse", "--verify", incoming]); if (!oid(tip) || tip !== fields[0]) refuse();
426
+ const advertised = advertisement.get(ref);
427
+ if (advertised === undefined) { if (target.local && !this.journal.publicationReservation) refuse(); target.remote = undefined; target.remoteHistory = undefined; continue; }
428
+ let tip: string;
429
+ if (target.local === advertised) {
430
+ // #626: the advertised tip is already the verified cached ref, so its objects are local; fetching it again only
431
+ // repeats a round trip. Equality with the advertisement is the same proof the fetched incoming ref gave.
432
+ tip = advertised;
433
+ } else {
434
+ const incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`; this.refs.push(incoming);
435
+ await this.required(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "origin", `${ref}:${incoming}`]);
436
+ tip = await this.required(["rev-parse", "--verify", incoming]); if (!oid(tip) || tip !== advertised) refuse();
437
+ }
409
438
  if (target.local && !await target.auditor.verifiedAncestor(target.local, tip) && !this.journal.publicationReservation) refuse();
410
439
  target.remote = tip; target.remoteHistory = await target.auditor.history(tip);
411
440
  target.rows = new Map(target.remoteHistory.rows); target.fetched = new Set(target.remoteHistory.rows.keys()); target.origins = new Map(target.remoteHistory.origins);
@@ -799,6 +828,8 @@ class PlacementTransport {
799
828
  this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
800
829
  const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
801
830
  this.attempted=participating.length>0;
831
+ // #626: a push moves advertised refs, so no later publication of this run may reuse the advertisement read before it.
832
+ if(this.attempted)placementAdvertisement(this.opts)?.delete(this.url);
802
833
  const sent=participating.length?await generationSyncGit(this.root,this.args(["push","--atomic","--no-follow-tags","-q",...participating.map(({target,index})=>`--force-with-lease=${shardSyncRef(this.targets[index]!.realm)}:${target.expectedRemoteHead??""}`),"origin",...participating.map(({target,index})=>`${target.commit}:${shardSyncRef(this.targets[index]!.realm)}`)]),this.opts.signal):{code:0};
803
834
  this.accepted=sent.code===0;await this.observe("cas-returned");
804
835
  if(!this.accepted)return this.result(false,"unknown","The placement publication outcome is unknown; retained receipts may have published. Recheck this exact attempt before retrying.");
@@ -0,0 +1,65 @@
1
+ /**
2
+ * #639: a read-only listing of the placement writer inventory and the install roots a renewal must declare. It writes
3
+ * nothing, takes no lock and never searches the filesystem for installs; it only reads the active inventory, the running
4
+ * install and the setup receipts, then suggests the present roots and the #625 saving-preview command built from them.
5
+ */
6
+ import { lstatSync } from "node:fs";
7
+ import { realPath } from "./platform.ts";
8
+ import { installVersion } from "./formats-raise.ts";
9
+ import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
10
+ import { readSetupWriterLaunchers, type SetupTarget } from "../setup-writer-roots.ts";
11
+
12
+ export const PLACEMENT_WRITERS_LISTING = "amem migrate --sync-placement --writers";
13
+ export const PLACEMENT_WRITERS_SCHEMA = "amem.placement-writers/v1";
14
+ export const PLACEMENT_WRITERS_NOTE = "Installs bundled inside other tools (agent-hub, vault-mem) appear here only when they are already in the inventory or a setup receipt; add a newly upgraded host bundle with another --writer-root.";
15
+
16
+ export interface PlacementWriterListing {
17
+ schema: typeof PLACEMENT_WRITERS_SCHEMA;
18
+ inventory: { root: string; version: string | null; state: "present" | "missing" }[];
19
+ running: { root: string; version: string | null; inInventory: boolean };
20
+ receipts: { target: SetupTarget; root: string; state: "present" | "missing" }[];
21
+ suggestedRoots: string[];
22
+ command: string;
23
+ note: string;
24
+ }
25
+
26
+ // ponytail: the same ENOENT/ENOTDIR test as the checkpoint's installAbsent (#634); one shared helper once #448 settles that file.
27
+ function absent(root: string): boolean {
28
+ try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
29
+ }
30
+ /** POSIX single-quote shell quoting: the printed command is pasted into a shell as is. */
31
+ export function shellQuote(value: string): string {
32
+ return `'${value.replaceAll("'", `'\\''`)}'`;
33
+ }
34
+ export function placementWriterCommand(roots: readonly string[]): string {
35
+ const flags = roots.map(root => `--writer-root ${shellQuote(root)}`).join(" ");
36
+ return `(umask 077; set -C; amem migrate --sync-placement --checkpoint ${flags} --json > checkpoint-plan.json), then amem migrate --sync-placement --checkpoint ${flags} --confirm --plan checkpoint-plan.json`;
37
+ }
38
+
39
+ export function listPlacementWriters(home: string, ownRoot: string): PlacementWriterListing {
40
+ const inventory = (readEffectiveSyncPlacementWriters(home).roots ?? []).map(root => {
41
+ const state = absent(root) ? "missing" as const : "present" as const;
42
+ return { root, version: state === "present" ? installVersion(root) : null, state };
43
+ });
44
+ const own = realPath(ownRoot);
45
+ const running = { root: own, version: installVersion(own), inInventory: inventory.some(row => row.root === own) };
46
+ const receipts = readSetupWriterLaunchers(home);
47
+ const present = new Set<string>([own]);
48
+ for (const row of [...inventory, ...receipts]) if (row.state === "present") present.add(realPath(row.root));
49
+ const suggestedRoots = [...present].sort();
50
+ return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
51
+ }
52
+
53
+ export function placementWritersText(listing: PlacementWriterListing): string {
54
+ const lines = ["sync placement writer inventory:"];
55
+ for (const row of listing.inventory) lines.push(` ${row.state} ${row.version ?? "unknown"} ${row.root}`);
56
+ if (!listing.inventory.length) lines.push(" (no inventory roots recorded)");
57
+ lines.push(`running install: ${listing.running.version ?? "unknown"} ${listing.running.root} (${listing.running.inInventory ? "in the inventory" : "not in the inventory"})`);
58
+ lines.push("setup receipts:");
59
+ for (const row of listing.receipts) lines.push(` ${row.target} ${row.state} ${row.root}`);
60
+ if (!listing.receipts.length) lines.push(" (none)");
61
+ lines.push("roots to declare:");
62
+ for (const root of listing.suggestedRoots) lines.push(` ${root}`);
63
+ lines.push(`next: ${listing.command}`, `note: ${listing.note}`);
64
+ return lines.join("\n");
65
+ }
@@ -15,7 +15,9 @@ 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 } from "./sync-placement-activation-locks.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 });
19
21
  import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
20
22
  import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
21
23
  import { captureInspectionPendingPrunes } from "./sync-placement-inspection-pending.ts";
@@ -18,6 +18,7 @@ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/p
18
18
  import { configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
19
19
  import { pendingLine, pendingSummary } from "./memory/candidate-pending.ts";
20
20
  import { memoryProjectKey } from "./memory/project.ts";
21
+ import { curatedCount, projectTransition, transitionNotice } from "./memory/roots.ts";
21
22
  import { registerReaderLease } from "./memory/reader-lease.ts";
22
23
  import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
23
24
  import { briefFailureReason } from "./memory/metrics.ts";
@@ -179,6 +180,14 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
179
180
  // F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
180
181
  // read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
181
182
  // same byte budget as everything else; when it does not fit it is left out.
183
+ // #581: one notice line when this working root last resolved to a different, unjoined key. A bounded local read
184
+ // (roots.jsonl tail, aliases.jsonl, one read-only index count); any failure yields no line. Reserved first.
185
+ let transitionLine: string | undefined;
186
+ if (!options.measureOnly) {
187
+ const transition = projectTransition(base, cwd, requested, key => curatedCount(base, key, shardDir));
188
+ const notice = transition ? transitionNotice(transition) : undefined;
189
+ if (notice !== undefined && Buffer.byteLength(notice) + 1 <= remaining) { remaining -= Buffer.byteLength(notice) + 1; transitionLine = notice; }
190
+ }
182
191
  let candidateLine: string | undefined;
183
192
  const line = pendingLine(pendingSummary(base, [project, ...aliases], (options.now ?? Date.now)()));
184
193
  if (line !== undefined && Buffer.byteLength(line) + 1 <= remaining) { remaining -= Buffer.byteLength(line) + 1; candidateLine = line; }
@@ -453,15 +462,20 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
453
462
  }
454
463
  }
455
464
  guard(true);
456
- let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
465
+ const notices = () => [...(transitionLine ? [transitionLine] : []), ...(candidateLine ? [candidateLine] : [])];
466
+ let context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
457
467
  while (Buffer.byteLength(context) > maximum && lines.length) {
458
468
  const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
459
469
  const removed = JSON.parse(lines.splice(repoIndex >= 0 ? repoIndex : lines.length - 1, 1)[0]!) as { section?: Section };
460
470
  if (removed.section && coverage[removed.section] === "complete") coverage[removed.section] = "partial";
461
- context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
471
+ context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
462
472
  }
463
473
  if (Buffer.byteLength(context) > maximum && candidateLine) {
464
474
  candidateLine = undefined;
475
+ context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
476
+ }
477
+ if (Buffer.byteLength(context) > maximum && transitionLine) {
478
+ transitionLine = undefined;
465
479
  context = [header(coverage, reasons), ...lines].join("\n");
466
480
  }
467
481
  if (Buffer.byteLength(context) > maximum) result = unavailable();