@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
@@ -1,7 +1,8 @@
1
+ import { freezeMetadata, isMetadataSnapshot, sameMetadataStamp } from "./profile-marker-cache.ts";
1
2
  /** Metadata-only v3 admission. Publication still requires the complete journal/source/policy proof. */
2
3
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
4
  import { join } from "node:path";
4
- import { reportBindingRead } from "./binding-read-set.ts";
5
+ import { collectBindingReads, reportBindingRead } from "./binding-read-set.ts";
5
6
  import { canonicalJSON, hashJSON } from "./generation.ts";
6
7
  import { realPath } from "./platform.ts";
7
8
  import { homeIdentityHash } from "./home-identity.ts";
@@ -14,7 +15,6 @@ import { shardDir, userShardDir } from "./shard.ts";
14
15
 
15
16
  export interface ActivePlacementBinding { profile: PlacementProfile; shards: PlacementShards; epoch: PlacementEpoch; activation: SyncPlacementActivationPlan }
16
17
  function fail(): never { throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing"); }
17
- const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
18
18
  function owned(s: BigIntStats, directory = false): void {
19
19
  if (s.uid !== BigInt(process.getuid?.() ?? -1) || (s.mode & 0o077n) !== 0n || s.isSymbolicLink()
20
20
  || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1n)) fail();
@@ -26,7 +26,35 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
26
26
  if (canonicalJSON(before) !== canonicalJSON(after)) fail();
27
27
  const initialShards = { ...shards, selectorRevision: hashJSON(initial) };
28
28
  if (hashJSON(initialShards) !== activation.targetShardsHash) fail();
29
+ assertLivePruneAdvance(home, initial, profile);
30
+ }
31
+ function assertLivePruneAdvance(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
29
32
  if (initial.pruneInputSetHash === profile.pruneInputSetHash) return;
33
+ // #656: a fence check runs this per row. Reuse a positive answer only while every file and directory the full check read
34
+ // keeps its dev:ino:size:mtimeNs:ctimeNs stamp; a stat error or any change takes the full check again. Only a reused-proof
35
+ // fence check (inside withPlacementFenceMemo) uses the memo: every other reader, the brief fence included, reads in full.
36
+ if (fenceMemoDepth === 0) { assertLivePruneAdvanceUncached(home, initial, profile); return; }
37
+ const key = JSON.stringify([home, initial.pruneInputSetHash, profile.pruneInputSetHash, profile.generation]), cached = pruneAdvanceMemo.get(key);
38
+ if (cached && pathStamps(cached.paths) === cached.stamps) return;
39
+ pruneAdvanceMemo.delete(key);
40
+ const { paths } = collectBindingReads(() => assertLivePruneAdvanceUncached(home, initial, profile));
41
+ const stamps = pathStamps(paths);
42
+ // The stamps are taken after the read, so the check runs once more under them: a change between the read and the stamp is never memoized.
43
+ if (stamps !== undefined) assertLivePruneAdvanceUncached(home, initial, profile);
44
+ if (stamps !== undefined && pathStamps(paths) === stamps) { if (pruneAdvanceMemo.size >= 32) pruneAdvanceMemo.delete(pruneAdvanceMemo.keys().next().value!); pruneAdvanceMemo.set(key, { paths, stamps }); }
45
+ }
46
+ // ponytail: 32 entries across homes, keyed by resolved home; same-size in-place rewrites within one stat tick are not seen (profile-marker-cache ceiling).
47
+ const pruneAdvanceMemo = new Map<string, { paths: string[]; stamps: string }>();
48
+ let fenceMemoDepth = 0;
49
+ /** #656: run a cheap fence check whose prune-advance answer may be reused while its files keep their stamps. */
50
+ export function withPlacementFenceMemo<T>(work: () => T): T { fenceMemoDepth++; try { return work(); } finally { fenceMemoDepth--; } }
51
+ function pathStamps(paths: readonly string[]): string | undefined {
52
+ const out: string[] = [];
53
+ try { for (const path of paths) { const s = lstatSync(path, { bigint: true, throwIfNoEntry: false }); if (!s) return undefined; out.push([s.dev, s.ino, s.mode, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":")); } }
54
+ catch { return undefined; }
55
+ return JSON.stringify(out);
56
+ }
57
+ function assertLivePruneAdvanceUncached(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
30
58
  const oldView = readPublicPruneViewForActivation(home, initial.pruneInputSetHash, profile.generation);
31
59
  const nextView = readPublicPruneViewForActivation(home, profile.pruneInputSetHash, profile.generation);
32
60
  if (!Object.keys(oldView.realms).every(key => Object.hasOwn(nextView.realms, key))) fail();
@@ -37,16 +65,26 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
37
65
  if (old !== undefined && !chain.commitments.includes(old)) fail();
38
66
  }
39
67
  }
40
- /**
41
- * Last verified binding keyed by the lstat stamps of every object the full read checks (#420). A sync calls this several
42
- * times per fence check; an unchanged stamp is the same identity the full read already accepts between its own reads.
43
- * ponytail: one entry per process; drop it if a same-size rewrite inside one timestamp tick must be caught across calls.
44
- */
45
- const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
46
- let bindingMemo: { key: string; value: Pick<ActivePlacementBinding, "epoch" | "activation"> } | undefined;
68
+ // Only file-reader snapshots have stable identity. Arbitrary caller objects always take the full validator.
69
+ const shardProofs = new WeakMap<object, { input: object; proof: { profile: PlacementProfile; shards: PlacementShards } }>();
70
+ export function provePlacementShards(value: unknown, profileInput: unknown): { profile: PlacementProfile; shards: PlacementShards } {
71
+ const cached = isMetadataSnapshot(value) ? shardProofs.get(value) : undefined;
72
+ if (cached && cached.input === profileInput) return cached.proof;
73
+ const profile = validatePlacementProfile(profileInput);
74
+ const proof = { profile, shards: validatePlacementShards(value, profile) };
75
+ if (isMetadataSnapshot(value) && isMetadataSnapshot(profileInput)) {
76
+ shardProofs.set(value, { input: profileInput, proof: freezeMetadata(proof) });
77
+ }
78
+ return proof;
79
+ }
80
+
81
+ type BindingProof = Pick<ActivePlacementBinding, "epoch" | "activation">;
82
+ // ponytail: only one proof per parsed shard snapshot (bounded by the marker caches), plus one for arbitrary inputs.
83
+ const snapshotBindings = new WeakMap<object, { key: string; profileInput: object; value: BindingProof }>();
84
+ let valueBinding: { key: string; value: BindingProof } | undefined;
47
85
  /** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
48
86
  export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
49
- const profile = validatePlacementProfile(profileInput), shards = validatePlacementShards(shardsInput, profile);
87
+ const { profile, shards } = provePlacementShards(shardsInput, profileInput);
50
88
  const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
51
89
  const stampKey = () => {
52
90
  const dir = join(home, "sync-placement", "epochs", profile.placementHead), stamps: string[] = [];
@@ -56,11 +94,17 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
56
94
  reportBindingRead(file);
57
95
  stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
58
96
  }
59
- return canonicalJSON([home, canonicalJSON(profile), canonicalJSON(shards), stamps]);
97
+ return JSON.stringify([home, stamps]);
60
98
  }, memoKey = stampKey();
61
- if (memoKey !== undefined && bindingMemo?.key === memoKey) {
62
- assertPlacementViewAdvance(home, bindingMemo.value.activation, profile, shards);
63
- return { profile, shards, epoch: bindingMemo.value.epoch, activation: bindingMemo.value.activation };
99
+ const snapshot = isMetadataSnapshot(profileInput) && isMetadataSnapshot(shardsInput) ? { profileInput, shardsInput } : undefined;
100
+ const previous = snapshot && snapshotBindings.get(snapshot.shardsInput);
101
+ const valueKey = !snapshot && memoKey !== undefined ? canonicalJSON([memoKey, profile, shards]) : undefined;
102
+ const cached = previous && previous.key === memoKey && previous.profileInput === profileInput ? previous.value
103
+ : valueKey !== undefined && valueBinding?.key === valueKey ? valueBinding.value : undefined;
104
+ if (cached) {
105
+ // The binding stamps cover the static commitments. Prune artifacts can change independently.
106
+ assertLivePruneAdvance(home, cached.activation.targetProfile, profile);
107
+ return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, ...cached };
64
108
  }
65
109
  const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
66
110
  const directory = (dir: string): boolean => {
@@ -73,13 +117,13 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
73
117
  owned(before); if (before.size <= 0n || before.size > 262144n) fail();
74
118
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
75
119
  try {
76
- const s = fstatSync(fd, { bigint: true }); owned(s); if (!same(before, s)) fail();
120
+ const s = fstatSync(fd, { bigint: true }); owned(s); if (!sameMetadataStamp(before, s)) fail();
77
121
  const bytes = Buffer.alloc(Number(s.size) + 1); let at = 0;
78
122
  while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
79
- if (at !== Number(s.size) || !same(s, fstatSync(fd, { bigint: true })) || !same(s, lstatSync(file, { bigint: true }))) fail();
123
+ if (at !== Number(s.size) || !sameMetadataStamp(s, fstatSync(fd, { bigint: true })) || !sameMetadataStamp(s, lstatSync(file, { bigint: true }))) fail();
80
124
  const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, at)), value: unknown = JSON.parse(text);
81
125
  if (canonicalJSON(value) + "\n" !== text) fail();
82
- checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!same(s, now)) fail(); }); return { value, text };
126
+ checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!sameMetadataStamp(s, now)) fail(); }); return { value, text };
83
127
  } finally { closeSync(fd); }
84
128
  };
85
129
  if (!directory(join(home, "sync-placement")) || !directory(join(home, "sync-placement", "epochs"))) return undefined;
@@ -95,6 +139,10 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
95
139
  if (read(join(home, "profile.json"))?.text !== canonicalJSON(profile) + "\n" || read(join(home, "shards.json"))?.text !== canonicalJSON(shards) + "\n") fail();
96
140
  assertPlacementViewAdvance(home, activation, profile, shards);
97
141
  for (const check of checks) check();
98
- if (memoKey !== undefined && stampKey() === memoKey) bindingMemo = { key: memoKey, value: { epoch: freeze(epoch), activation: freeze(activation) } };
99
- return { profile, shards, epoch, activation };
142
+ if (memoKey !== undefined && stampKey() === memoKey) {
143
+ const value = { epoch: freezeMetadata(epoch), activation: freezeMetadata(activation) };
144
+ if (snapshot) snapshotBindings.set(snapshot.shardsInput, { key: memoKey, profileInput: snapshot.profileInput, value });
145
+ else if (valueKey !== undefined) valueBinding = { key: valueKey, value };
146
+ }
147
+ return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, epoch, activation };
100
148
  }
@@ -5,14 +5,36 @@ import type { SyncOptions } from "./sync.ts";
5
5
  * shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
6
6
  * fresh map to its own options object, and a publication reached with other options reads per run as before.
7
7
  * Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
8
+ *
9
+ * #656: the same run scope also holds the remote visibility answer by exact URL (one `gh repo view` per run, not per
10
+ * batch), and tells a publication to leave the placement storage memos for the driver to release in its finally.
8
11
  */
9
- const runs = new WeakMap<SyncOptions, Map<string, ReadonlyMap<string, string>>>();
12
+ interface PlacementRun { advertisement: Map<string, ReadonlyMap<string, string>>; visibility: Map<string, Promise<string>> }
13
+ const runs = new WeakMap<SyncOptions, PlacementRun>();
10
14
 
11
15
  export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
12
- runs.set(opts, new Map());
16
+ runs.set(opts, { advertisement: new Map(), visibility: new Map() });
13
17
  return opts;
14
18
  }
15
19
 
20
+ /** Ends the run scope: later publications with these options read visibility and release storage memos on their own again. */
21
+ export function releasePlacementRun(opts: SyncOptions): void { runs.delete(opts); }
22
+
16
23
  export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
17
- return runs.get(opts);
24
+ return runs.get(opts)?.advertisement;
25
+ }
26
+
27
+ /** Whether a publication with these options runs inside an inventory run that releases the storage memos itself. */
28
+ export function placementStorageCacheScope(opts: SyncOptions): boolean { return runs.has(opts); }
29
+
30
+ /**
31
+ * Remote visibility, read once per exact URL inside one inventory run. Only a "private" answer is kept: any other answer or a
32
+ * failed read is dropped, so the next publication asks again and the refusal stays before any lock or fetch.
33
+ */
34
+ export function placementVisibility(opts: SyncOptions, url: string, read: (url: string) => Promise<string>): Promise<string> {
35
+ const run = runs.get(opts); if (!run) return read(url);
36
+ const known = run.visibility.get(url); if (known) return known;
37
+ const pending = read(url).then(value => { if (value !== "private") run.visibility.delete(url); return value; },
38
+ error => { run.visibility.delete(url); throw error; });
39
+ run.visibility.set(url, pending); return pending;
18
40
  }
@@ -4,14 +4,13 @@
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";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { types } from "node:util";
10
9
  import { memoryPolicySnapshot } from "./policy.ts";
11
10
  import { realPath } from "./platform.ts";
12
11
  import { canonicalJSON } from "./generation.ts";
13
12
  import { assertFormatFloor, formatVersionBelow, readFormatFloors } from "./formats.ts";
14
- import { installVersion } from "./formats-raise.ts";
13
+ import { installAbsent, installVersion } from "./formats-raise.ts";
15
14
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
16
15
  import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS } from "./sync-placement-journal-format.ts";
17
16
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
@@ -46,7 +45,7 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
46
45
  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.",
47
46
  changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
48
47
  inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
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}.`,
48
+ 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) or use --discovered-writers, then preview again with ${CHECKPOINT_PREVIEW}.`,
50
49
  history: "",
51
50
  "writer-missing": "",
52
51
  };
@@ -138,7 +137,7 @@ export async function previewPlacementCheckpoint(homeInput: string, opts: { writ
138
137
  const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
139
138
  return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
140
139
  floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
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` };
140
+ nextStep: `${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every install (or --discovered-writers), then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json` };
142
141
  }
143
142
  async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
144
143
  const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
@@ -179,15 +178,8 @@ function reviewedHeadroom(value: unknown): unknown {
179
178
  if (!detached) throw new PlacementCheckpointError("changed");
180
179
  return detached;
181
180
  }
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
181
  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.`;
182
+ return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with ${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json.`;
191
183
  }
192
184
  function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
193
185
  if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
@@ -211,12 +203,14 @@ function checkWriterVersions(home: string, roots: PlacementCheckpointInput["root
211
203
  */
212
204
  export async function confirmPlacementCheckpoint(homeInput: string, value: unknown, opts: { writerRoots: readonly string[]; ownRoot: string; phase?: (phase: PlacementCheckpointPhase) => void }): Promise<{ window: number; renewed: true; planHash: string; nextStep: string }> {
213
205
  const home = realPath(homeInput), intent = checkpointPlanFrom(value), a = active(home), minReader = PLACEMENT_CHECKPOINT_MIN_READER;
206
+ // #660: without --writer-root the sealed plan names the roots; every one is still measured fresh here and under the fences.
207
+ const writerRoots = opts.writerRoots.length ? opts.writerRoots : intent.writerRevision.roots.map(root => root.root);
214
208
  if (intent.epochHash !== a.profile.placementHead) throw new PlacementCheckpointError("changed");
215
- checkFloor(home, undefined, minReader); checkFloor(home, measured(home, opts.writerRoots, opts.ownRoot), minReader);
209
+ checkFloor(home, undefined, minReader); checkFloor(home, measured(home, writerRoots, opts.ownRoot), minReader);
216
210
  const prospective = await checkpointHeadroom(home, intent);
217
211
  if (canonicalJSON(reviewedHeadroom(value)) !== canonicalJSON(prospective.headroom)) throw new PlacementCheckpointError("changed");
218
212
  return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
219
- const now = active(home), roots = measured(home, opts.writerRoots, opts.ownRoot);
213
+ const now = active(home), roots = measured(home, writerRoots, opts.ownRoot);
220
214
  if (canonicalJSON(now) !== canonicalJSON(a)) throw new PlacementCheckpointError("changed");
221
215
  prospective.assertCurrent();
222
216
  checkFloor(home, roots, minReader);
@@ -2,7 +2,7 @@
2
2
  import { lstatSync, opendirSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { hashJSON } from "./generation.ts";
5
- import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
5
+ import { readPlacementRuntimeMarkerSnapshots } from "./sync-placement-guard.ts";
6
6
  import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
7
7
  import { readPlacementWriterJournalAnchors, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
8
8
  import { readWriterHistory, isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
@@ -19,7 +19,7 @@ export interface EffectiveSyncPlacementWriters {
19
19
  }
20
20
  function fail():never{throw new SharedWriterRevisionError("changed");}
21
21
  function active(home:string):ActivePlacementBinding {
22
- const markers=readPlacementRuntimeMarkers(home),value=readActivePlacementBinding(home,markers.profile,markers.shards);if(!value)fail();return value;
22
+ const markers=readPlacementRuntimeMarkerSnapshots(home),value=readActivePlacementBinding(home,markers.profile,markers.shards);if(!value)fail();return value;
23
23
  }
24
24
  const key=(value:ActivePlacementBinding)=>hashJSON({epoch:value.epoch,activation:value.activation,head:value.profile.placementHead,generation:value.profile.generation});
25
25
  const fileStamp=(home:string)=>{
@@ -67,7 +67,8 @@ export function readEffectiveSyncPlacementWriters(home:string):EffectiveSyncPlac
67
67
  if(placementWriterJournalToken(home,epochHash)!==token)fail();anchorToken=token;
68
68
  };
69
69
  const assertCurrent=()=>{
70
- history.assertCurrent();if(key(active(home))!==bindingKey||fileStamp(home)!==initialStamp)fail();
70
+ // #656: one history pass per check, after the reads it brackets; the trailing pass covers the whole window.
71
+ if(key(active(home))!==bindingKey||fileStamp(home)!==initialStamp)fail();
71
72
  if(initial&&readInitialSyncPlacementWriterLocator(home).seal!==initial.seal)fail();
72
73
  if(history.sequence||history.window)requireWriterRenewalHomeFloor(home);
73
74
  anchors();history.assertCurrent();
@@ -1,4 +1,5 @@
1
- import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
1
+ import { metadataReader, sameMetadataStamp } from "./profile-marker-cache.ts";
2
+ import { provePlacementShards, readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
2
3
  import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
3
4
  import { AsyncLocalStorage } from "node:async_hooks";
4
5
  import { tmpdir } from "node:os";
@@ -11,7 +12,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
11
12
  import { join } from "node:path";
12
13
  import { LOCAL_METADATA_MAX_BYTES, legacyProfileMarkerShape, type BoundProfile } from "./generation.ts";
13
14
  import { legacyShardMarkerShape } from "./shard.ts";
14
- import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
15
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
15
16
  import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
16
17
  import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
17
18
 
@@ -66,8 +67,7 @@ export class SyncPlacementRuntimeError extends Error {
66
67
  constructor(reason: string) { super(reason); this.name = "SyncPlacementRuntimeError"; this.code = reason === PLACEMENT_STAGE1_REFUSAL ? "sync_placement_not_enabled" : "sync_placement_unavailable";rememberProfileLockError(this,reason); }
67
68
  }
68
69
  class MarkerChanged extends Error {}
69
- const same = (left: BigIntStats, right: BigIntStats) => left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
70
- function readMarker(file: string): unknown | undefined {
70
+ function readMarkerUncached(file: string): { stamp: BigIntStats; value: unknown } | undefined {
71
71
  for (let attempt = 0; attempt < 6; attempt++) {
72
72
  let fd: number | undefined;
73
73
  try {
@@ -76,20 +76,38 @@ function readMarker(file: string): unknown | undefined {
76
76
  if (!before.isFile() || before.isSymbolicLink() || before.size > BigInt(LOCAL_METADATA_MAX_BYTES)) throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
77
77
  fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
78
78
  const opened = fstatSync(fd, { bigint: true });
79
- if (!same(before, opened)) throw new MarkerChanged();
79
+ if (!sameMetadataStamp(before, opened)) throw new MarkerChanged();
80
80
  const bytes = Buffer.alloc(Number(opened.size) + 1); let count = 0;
81
81
  while (count < bytes.length) { const read = readSync(fd, bytes, count, bytes.length - count, count); if (!read) break; count += read; }
82
82
  const after = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true, throwIfNoEntry: false });
83
- if (count !== Number(opened.size) || !same(opened, after) || !named || named.isSymbolicLink() || !same(opened, named)) throw new MarkerChanged();
84
- return JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)));
83
+ if (count !== Number(opened.size) || !sameMetadataStamp(opened, after) || !named || named.isSymbolicLink() || !sameMetadataStamp(opened, named)) throw new MarkerChanged();
84
+ return { stamp: named, value: JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count))) as unknown };
85
85
  } catch (error) { if (error instanceof MarkerChanged && attempt < 5) continue; throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL); }
86
86
  finally { if (fd !== undefined) closeSync(fd); }
87
87
  }
88
88
  throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
89
89
  }
90
- export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
90
+ const readMarker = metadataReader(readMarkerUncached);
91
+ /** The shard reader reuses only parsed v3 markers. Legacy and malformed values keep their existing reader. */
92
+ export function readPlacementV3Marker(file: string): Record<string, unknown> | undefined {
93
+ let value: unknown;
94
+ try { value = readMarker(file); } catch { return undefined; }
95
+ const format = schema(value);
96
+ return format === PLACEMENT_PROFILE_SCHEMA || format === PLACEMENT_SHARDS_SCHEMA ? value as Record<string, unknown> : undefined;
97
+ }
98
+ function runtimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
91
99
  return { profile: readMarker(join(home, "profile.json")), shards: readMarker(join(home, "shards.json")) };
92
100
  }
101
+ export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
102
+ return structuredClone(runtimeMarkers(home));
103
+ }
104
+ /**
105
+ * #656, internal fence reads only: the reader's own frozen snapshots, uncloned, so the shard-proof and binding WeakMaps hit while the
106
+ * markers are unchanged. Callers never mutate or return them; anything handed outward still takes readPlacementRuntimeMarkers.
107
+ */
108
+ export function readPlacementRuntimeMarkerSnapshots(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
109
+ return runtimeMarkers(home);
110
+ }
93
111
  /** #551 AC2: whether a home is provably a placement home, provably not one, or unprovable from its own markers. */
94
112
  export type PlacementMarkerState = "placement" | "unverified" | "not placement";
95
113
  /**
@@ -99,7 +117,7 @@ export type PlacementMarkerState = "placement" | "unverified" | "not placement";
99
117
  */
100
118
  export function placementMarkerState(home: string): PlacementMarkerState {
101
119
  let markers: { profile: unknown | undefined; shards: unknown | undefined };
102
- try { markers = readPlacementRuntimeMarkers(home); } catch { return "unverified"; }
120
+ try { markers = runtimeMarkers(home); } catch { return "unverified"; }
103
121
  if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA || schema(markers.shards) === PLACEMENT_SHARDS_SCHEMA)
104
122
  return (markers.profile as { publicationFormat?: unknown } | undefined)?.publicationFormat === PLACEMENT_FORMAT ? "placement" : "unverified";
105
123
  // A missing marker or a recognizable legacy one is a home that never activated placement sync; any other shape is malformed.
@@ -120,7 +138,7 @@ function plainMarker(value: unknown): boolean {
120
138
  export function placementMarkerRefusal(profile: unknown, shards: unknown): string | undefined {
121
139
  if (!plainMarker(profile) || !plainMarker(shards)) return PLACEMENT_MARKER_REFUSAL;
122
140
  if (schema(profile) === PLACEMENT_PROFILE_SCHEMA || schema(shards) === PLACEMENT_SHARDS_SCHEMA) {
123
- try { validatePlacementShards(shards, validatePlacementProfile(profile)); }
141
+ try { provePlacementShards(shards, profile); }
124
142
  catch { return PLACEMENT_MARKER_REFUSAL; }
125
143
  return PLACEMENT_STAGE1_REFUSAL;
126
144
  }
@@ -158,7 +176,7 @@ function placementFencePresent(home: string): boolean {
158
176
  * The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
159
177
  export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
160
178
  if (doctorScratchBinding(home)) return undefined;
161
- try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = readPlacementRuntimeMarkers(home);
179
+ try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = runtimeMarkers(home);
162
180
  const refusal = placementMarkerRefusal(markers.profile, markers.shards);
163
181
  if (refusal === PLACEMENT_STAGE1_REFUSAL) {
164
182
  const active=readActivePlacementBinding(home,markers.profile,markers.shards);
@@ -14,7 +14,7 @@ import { existsSync, lstatSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
16
16
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
17
- import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
17
+ import { readPlacementJournal, releasePlacementStorageCaches } from "./sync-placement-journal-storage.ts";
18
18
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
19
19
  import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
20
20
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
@@ -22,7 +22,8 @@ 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
+ import { bindPlacementAdvertisement, releasePlacementRun } from "./sync-placement-advertisement.ts";
26
+ import { PLACEMENT_RETAINED_STOP_MESSAGE, placementStoppedMessage } from "./sync-placement-refusal.ts";
26
27
  import type { MemoryStore } from "./store.ts";
27
28
 
28
29
  const digest = (value: string) => createHash("sha256").update(value).digest("hex");
@@ -101,7 +102,12 @@ function journalRefusal(error: unknown): (SyncResult & { placementRealms: Placem
101
102
 
102
103
  export async function syncPlacementInventory(home: string, callerOpts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
103
104
  // #626: one remote advertisement per run, shared by its publications (never one a caller passed in).
105
+ // #656: the same scope keeps the visibility answer and the placement storage memos across batches; both end here, on every path.
104
106
  const opts: SyncOptions = bindPlacementAdvertisement({ ...callerOpts });
107
+ try { return await runPlacementInventory(home, opts, ports); }
108
+ finally { releasePlacementRun(opts); releasePlacementStorageCaches(); }
109
+ }
110
+ async function runPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
105
111
  let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
106
112
  try {
107
113
  // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
@@ -149,7 +155,15 @@ export async function syncPlacementInventory(home: string, callerOpts: SyncOptio
149
155
  for (const [index, batch] of batches.entries()) {
150
156
  if (!batch.length) continue;
151
157
  if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
152
- if (opts.signal?.aborted) { stopped = { ok: false, pushed: false, entries: 0, error: "stopped", failure: { cause: "stopped" } }; for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
158
+ if (opts.signal?.aborted) {
159
+ // #657: the first batch of a resumed run is a retained attempt that may already have published, so it stays unknown.
160
+ const retainedFirst = index === 0 && resumed !== undefined;
161
+ stopped = retainedFirst
162
+ ? { ok: false, pushed: false, entries: 0, error: PLACEMENT_RETAINED_STOP_MESSAGE, failure: { cause: "stopped" }, placementPublication: { outcome: "unknown", withheld: 0, exported: 0, policyCeiling: "last-positive-check-before-in-flight-push" } }
163
+ : { ok: false, pushed: false, entries: 0, error: placementStoppedMessage(results.length ? "between publications" : "start of the run"), failure: { cause: "stopped" } };
164
+ for (const realm of batch) realms.push({ realm: label(realm), outcome: retainedFirst ? "unknown" : "not-run", ...(retainedFirst ? { publication: index + 1 } : {}) });
165
+ continue;
166
+ }
153
167
  let result = await attempt(batch);
154
168
  // #578 Q2: by here the publication has returned, so its transport released every mutation and sync lock it took
155
169
  // (sync-placement-transport.ts finally) and `attempt` closed the stores it opened. The checkpoint fence takes those
@@ -161,7 +175,9 @@ export async function syncPlacementInventory(home: string, callerOpts: SyncOptio
161
175
  else result = { ...result, error: [result.error, ran.message].filter(Boolean).join(" "), failure: { cause: "checkpoint-refused" } };
162
176
  }
163
177
  results.push(result);
164
- const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown" : "failed";
178
+ // #657: a batch stopped before any attempt existed did not run; "not-run" keeps the sidecar readable by N-1 status readers.
179
+ const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown"
180
+ : result.failure?.cause === "stopped" ? "not-run" : "failed";
165
181
  for (const realm of batch) realms.push({ realm: label(realm), outcome, publication: index + 1 });
166
182
  if (!result.ok) stopped = result;
167
183
  else completed++;
@@ -20,7 +20,8 @@ import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
20
20
  import { realPath } from "./platform.ts";
21
21
  import { readShardDescriptor, assertCuratedShardLayout, shardDir } from "./shard.ts";
22
22
  import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
23
- import { withPlacementActivationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
23
+ import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
24
+ import { withPlacementMutationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
24
25
  import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
25
26
  import { previewOwnedSyncPlacementSources, previewSyncPlacementSources } from "./sync-placement-capture.ts";
26
27
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
@@ -74,7 +75,7 @@ export interface RealmAdmissionResult {
74
75
  }
75
76
  export class RealmAdmissionError extends Error {
76
77
  constructor(readonly causeClass: "readers" | "busy" | "changed" | "pending" | "committed" | "metadata", readonly retainedRealm?: string) {
77
- super(`Sync placement realm admission is ${causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
78
+ super(`Sync placement realm admission is ${causeClass === "readers" ? "blocked by live readers" : causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
78
79
  this.name = "RealmAdmissionError";
79
80
  }
80
81
  }
@@ -83,6 +84,7 @@ function action(causeClass: RealmAdmissionError["causeClass"]): string {
83
84
  if (causeClass === "committed") return "The extension chain no longer matches the frozen intent: run amem migrate --sync-placement --admit <project> --resume to complete or clean up the retained attempt, and keep --abandon --confirm for an append that never committed.";
84
85
  if (causeClass === "changed") return "Re-read the home with amem migrate --sync-placement --admit <project> --dry-run and apply the reviewed append.";
85
86
  if (causeClass === "metadata") return "Inspect the local placement and curated metadata it names, then run amem migrate --sync-placement --admit <project> --dry-run.";
87
+ if (causeClass === "busy") return "Wait for the operation holding the lock (amem sync --status), then run amem migrate --sync-placement --admit <project> --dry-run.";
86
88
  return "Close cooperating readers and writers, then run amem migrate --sync-placement --admit <project> --dry-run.";
87
89
  }
88
90
  function fail(causeClass: RealmAdmissionError["causeClass"]): never { throw new RealmAdmissionError(causeClass); }
@@ -95,6 +97,7 @@ function assertNoPendingAdmission(home: string, ownRealm?: string): void {
95
97
  function rethrow(error: unknown): never {
96
98
  if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError || error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error;
97
99
  if (error instanceof PlacementInventoryFenceError) fail(error.causeClass);
100
+ if (error instanceof Error && error.message === "profile lock held by a live or unknown owner") fail("busy");
98
101
  return fail("metadata");
99
102
  }
100
103
 
@@ -246,8 +249,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
246
249
  ...(plan.staged ? { staged: plan.staged } : {}), nextStep: "confirm amem migrate --sync-placement --admit <project> --abandon --confirm" };
247
250
  const stages = plan.staged ? inspectRealmIntentStages(home, realm) : undefined;
248
251
  if (plan.staged && stages?.length !== plan.staged) fail("changed");
249
- return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
250
- try {
252
+ try {
253
+ return await withPlacementMutationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
251
254
  assertCheckpointClear(home);
252
255
  const binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
253
256
  const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
@@ -264,8 +267,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
264
267
  clearRealmIntent(home, intent, proof);
265
268
  return { mode: "abandon" as const, state: "abandoned" as const, realm, sequence: intent.sequence, discarded,
266
269
  nextStep: "amem migrate --sync-placement --admit <project> --dry-run" };
267
- } catch (error) { return rethrow(error); }
268
- });
270
+ }, { surface: "admit" });
271
+ } catch (error) { return rethrow(error); }
269
272
  }
270
273
  if (options.mode === "apply") assertNoPendingAdmission(home);
271
274
  const planned = options.mode === "apply" ? inspectRealmAdmission(home, project) : undefined;
@@ -275,8 +278,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
275
278
  if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted", realm };
276
279
  throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
277
280
  }
278
- return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
279
- try {
281
+ try {
282
+ return await withPlacementMutationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
280
283
  assertCheckpointClear(home);
281
284
  if (options.mode === "apply") assertNoPendingAdmission(home);
282
285
  if (options.mode === "resume") assertNoPendingAdmission(home, realm);
@@ -343,10 +346,12 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
343
346
  await options.checkpoint?.("after-append");
344
347
  clearRealmIntent(home, frozen, proof);
345
348
  return { mode: options.mode, state: "admitted" as const, realm, sequence: frozen.sequence, headHash: record.seal, created };
346
- } catch (error) { return rethrow(error); }
347
- });
349
+ }, { surface: "admit" });
350
+ } catch (error) { return rethrow(error); }
348
351
  }
349
352
  function directories(home: string, projectPrefix: string): string[] {
350
353
  const realmDir = join(home, "projects", projectPrefix);
351
- return existsSync(realmDir) ? [realmDir] : [];
354
+ const active = placementFenceDirectories(home, activeBinding(home));
355
+ if (existsSync(realmDir)) active.push(realmDir);
356
+ return active;
352
357
  }
@@ -40,6 +40,13 @@ export function placementRefusalCategoryOf(error: unknown): PlacementRefusalCate
40
40
 
41
41
  export function placementRefusalNextStep(category: PlacementRefusalCategory): string { return NEXT[category]; }
42
42
 
43
+ /** A stop while a retained attempt may already have published: its outcome stays unknown until its receipts are rechecked. */
44
+ export const PLACEMENT_RETAINED_STOP_MESSAGE = "Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.";
45
+ /** #657: a stop before any publication attempt existed; it published nothing and names the command that finishes the run. */
46
+ export function placementStoppedMessage(phase: string): string {
47
+ return `Placement sync stopped before publication (phase ${phase}); nothing was published for this batch. Run amem sync to finish it.`;
48
+ }
49
+
43
50
  /** AC1/AC4: the person-facing refusal. `other` keeps the generic wording and still names the phase. */
44
51
  export function placementRefusalMessage(category: PlacementRefusalCategory, phase: SyncProgressPhase): string {
45
52
  const where = phase.replaceAll("-", " ");