@staix/agent-mem 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +2 -2
  3. package/package.json +4 -3
  4. package/src/cli.ts +161 -27
  5. package/src/commands-table.ts +17 -6
  6. package/src/index.ts +4 -1
  7. package/src/ingest-hosts.ts +440 -0
  8. package/src/mcp-bounds.ts +3 -0
  9. package/src/mcp-memory.ts +64 -10
  10. package/src/mcp.ts +36 -121
  11. package/src/memory/candidates.ts +33 -5
  12. package/src/memory/capture.ts +23 -0
  13. package/src/memory/commands.ts +6 -3
  14. package/src/memory/config.ts +26 -0
  15. package/src/memory/consolidation-clusters.ts +13 -2
  16. package/src/memory/doctor-text.ts +4 -1
  17. package/src/memory/doctor.ts +8 -5
  18. package/src/memory/formats-raise.ts +37 -16
  19. package/src/memory/formats.ts +37 -10
  20. package/src/memory/generation-sync.ts +1 -1
  21. package/src/memory/home-binding-fence.ts +2 -1
  22. package/src/memory/live-state.ts +85 -0
  23. package/src/memory/migrate.ts +3 -3
  24. package/src/memory/mutation.ts +6 -3
  25. package/src/memory/profile-marker-cache.ts +45 -0
  26. package/src/memory/public-prune-activation.ts +1 -1
  27. package/src/memory/public-prune-advance.ts +1 -1
  28. package/src/memory/public-prune-inputs.ts +1 -1
  29. package/src/memory/purge-intent.ts +27 -0
  30. package/src/memory/purge-matcher.ts +101 -0
  31. package/src/memory/purge-plan.ts +90 -0
  32. package/src/memory/read-curated-entries.ts +244 -0
  33. package/src/memory/reader-lease.ts +3 -0
  34. package/src/memory/search-fts.ts +55 -27
  35. package/src/memory/shard-migration.ts +3 -3
  36. package/src/memory/shard-sync.ts +3 -3
  37. package/src/memory/shard.ts +17 -14
  38. package/src/memory/store.ts +9 -72
  39. package/src/memory/sync-cadence.ts +8 -4
  40. package/src/memory/sync-placement-activation-locks.ts +39 -22
  41. package/src/memory/sync-placement-active.ts +69 -19
  42. package/src/memory/sync-placement-advertisement.ts +25 -3
  43. package/src/memory/sync-placement-checkpoint-person.ts +8 -14
  44. package/src/memory/sync-placement-effective-writers.ts +4 -3
  45. package/src/memory/sync-placement-guard.ts +31 -11
  46. package/src/memory/sync-placement-inventory.ts +20 -4
  47. package/src/memory/sync-placement-journal.ts +1 -1
  48. package/src/memory/sync-placement-realm-admission.ts +16 -11
  49. package/src/memory/sync-placement-refusal.ts +7 -0
  50. package/src/memory/sync-placement-remote-admission.ts +31 -13
  51. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  52. package/src/memory/sync-placement-remote-stage.ts +1 -1
  53. package/src/memory/sync-placement-transport.ts +36 -15
  54. package/src/memory/sync-placement-writer-listing.ts +38 -13
  55. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  56. package/src/memory/sync.ts +3 -2
  57. package/src/memory/topic.ts +14 -0
  58. package/src/setup-console.ts +49 -23
  59. package/src/setup-drift.ts +35 -4
  60. package/src/setup-owned.ts +9 -1
  61. package/src/setup-writer-roots.ts +1 -1
  62. package/src/setup.ts +102 -16
  63. package/src/sync-placement-writer-context.ts +1 -1
@@ -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,6 @@
1
- import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
1
+ import { PURGE_PENDING, purgePending } from "./purge-intent.ts";
2
+ import { metadataReader, sameMetadataStamp } from "./profile-marker-cache.ts";
3
+ import { provePlacementShards, readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
2
4
  import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
3
5
  import { AsyncLocalStorage } from "node:async_hooks";
4
6
  import { tmpdir } from "node:os";
@@ -11,7 +13,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
11
13
  import { join } from "node:path";
12
14
  import { LOCAL_METADATA_MAX_BYTES, legacyProfileMarkerShape, type BoundProfile } from "./generation.ts";
13
15
  import { legacyShardMarkerShape } from "./shard.ts";
14
- import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
16
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
15
17
  import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
16
18
  import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
17
19
 
@@ -66,8 +68,7 @@ export class SyncPlacementRuntimeError extends Error {
66
68
  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
69
  }
68
70
  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 {
71
+ function readMarkerUncached(file: string): { stamp: BigIntStats; value: unknown } | undefined {
71
72
  for (let attempt = 0; attempt < 6; attempt++) {
72
73
  let fd: number | undefined;
73
74
  try {
@@ -76,20 +77,38 @@ function readMarker(file: string): unknown | undefined {
76
77
  if (!before.isFile() || before.isSymbolicLink() || before.size > BigInt(LOCAL_METADATA_MAX_BYTES)) throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
77
78
  fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
78
79
  const opened = fstatSync(fd, { bigint: true });
79
- if (!same(before, opened)) throw new MarkerChanged();
80
+ if (!sameMetadataStamp(before, opened)) throw new MarkerChanged();
80
81
  const bytes = Buffer.alloc(Number(opened.size) + 1); let count = 0;
81
82
  while (count < bytes.length) { const read = readSync(fd, bytes, count, bytes.length - count, count); if (!read) break; count += read; }
82
83
  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)));
84
+ if (count !== Number(opened.size) || !sameMetadataStamp(opened, after) || !named || named.isSymbolicLink() || !sameMetadataStamp(opened, named)) throw new MarkerChanged();
85
+ return { stamp: named, value: JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count))) as unknown };
85
86
  } catch (error) { if (error instanceof MarkerChanged && attempt < 5) continue; throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL); }
86
87
  finally { if (fd !== undefined) closeSync(fd); }
87
88
  }
88
89
  throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
89
90
  }
90
- export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
91
+ const readMarker = metadataReader(readMarkerUncached);
92
+ /** The shard reader reuses only parsed v3 markers. Legacy and malformed values keep their existing reader. */
93
+ export function readPlacementV3Marker(file: string): Record<string, unknown> | undefined {
94
+ let value: unknown;
95
+ try { value = readMarker(file); } catch { return undefined; }
96
+ const format = schema(value);
97
+ return format === PLACEMENT_PROFILE_SCHEMA || format === PLACEMENT_SHARDS_SCHEMA ? value as Record<string, unknown> : undefined;
98
+ }
99
+ function runtimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
91
100
  return { profile: readMarker(join(home, "profile.json")), shards: readMarker(join(home, "shards.json")) };
92
101
  }
102
+ export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
103
+ return structuredClone(runtimeMarkers(home));
104
+ }
105
+ /**
106
+ * #656, internal fence reads only: the reader's own frozen snapshots, uncloned, so the shard-proof and binding WeakMaps hit while the
107
+ * markers are unchanged. Callers never mutate or return them; anything handed outward still takes readPlacementRuntimeMarkers.
108
+ */
109
+ export function readPlacementRuntimeMarkerSnapshots(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
110
+ return runtimeMarkers(home);
111
+ }
93
112
  /** #551 AC2: whether a home is provably a placement home, provably not one, or unprovable from its own markers. */
94
113
  export type PlacementMarkerState = "placement" | "unverified" | "not placement";
95
114
  /**
@@ -99,7 +118,7 @@ export type PlacementMarkerState = "placement" | "unverified" | "not placement";
99
118
  */
100
119
  export function placementMarkerState(home: string): PlacementMarkerState {
101
120
  let markers: { profile: unknown | undefined; shards: unknown | undefined };
102
- try { markers = readPlacementRuntimeMarkers(home); } catch { return "unverified"; }
121
+ try { markers = runtimeMarkers(home); } catch { return "unverified"; }
103
122
  if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA || schema(markers.shards) === PLACEMENT_SHARDS_SCHEMA)
104
123
  return (markers.profile as { publicationFormat?: unknown } | undefined)?.publicationFormat === PLACEMENT_FORMAT ? "placement" : "unverified";
105
124
  // A missing marker or a recognizable legacy one is a home that never activated placement sync; any other shape is malformed.
@@ -120,7 +139,7 @@ function plainMarker(value: unknown): boolean {
120
139
  export function placementMarkerRefusal(profile: unknown, shards: unknown): string | undefined {
121
140
  if (!plainMarker(profile) || !plainMarker(shards)) return PLACEMENT_MARKER_REFUSAL;
122
141
  if (schema(profile) === PLACEMENT_PROFILE_SCHEMA || schema(shards) === PLACEMENT_SHARDS_SCHEMA) {
123
- try { validatePlacementShards(shards, validatePlacementProfile(profile)); }
142
+ try { provePlacementShards(shards, profile); }
124
143
  catch { return PLACEMENT_MARKER_REFUSAL; }
125
144
  return PLACEMENT_STAGE1_REFUSAL;
126
145
  }
@@ -158,7 +177,8 @@ function placementFencePresent(home: string): boolean {
158
177
  * The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
159
178
  export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
160
179
  if (doctorScratchBinding(home)) return undefined;
161
- try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = readPlacementRuntimeMarkers(home);
180
+ if (purgePending(home)) return PURGE_PENDING;
181
+ try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = runtimeMarkers(home);
162
182
  const refusal = placementMarkerRefusal(markers.profile, markers.shards);
163
183
  if (refusal === PLACEMENT_STAGE1_REFUSAL) {
164
184
  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++;
@@ -48,7 +48,7 @@ function fenced<T>(capture: PlacementCapture, work: (homeMutation: MutationHandl
48
48
  try {
49
49
  let homeMutation: MutationHandle | undefined;
50
50
  for (const dir of capture.directories) {
51
- const handle = acquireMutation(dir); if (!handle) fail("busy");
51
+ const handle = acquireMutation(dir, capture.home); if (!handle) fail("busy");
52
52
  handles.push(handle); if (dir === capture.home) homeMutation = handle;
53
53
  }
54
54
  capture.assertCurrent(); if (!homeMutation) fail();
@@ -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("-", " ");
@@ -16,7 +16,9 @@ import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
16
16
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
17
17
  import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
18
18
  import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
19
- import { PlacementInventoryFenceError, withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
19
+ import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
20
+ import { assertNoLiveReaders } from "./reader-lease.ts";
21
+ import { PlacementInventoryFenceError, withPlacementMutationFences } from "./sync-placement-activation-locks.ts";
20
22
  import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
21
23
  import { previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
22
24
  import { activePlacementWriterContext } from "../sync-placement-writer-context.ts";
@@ -56,7 +58,13 @@ function assertCheckpointClear(home: string): void {
56
58
  catch (error) { if (error instanceof SyncPlacementJournalError && error.code === "pending") throw new SyncPlacementJournalError("checkpoint-pending"); throw error; }
57
59
  }
58
60
  function dirs(home: string, project: string): string[] {
59
- const dir = shardDir(home, project); return lstatSync(dir, { throwIfNoEntry: false }) ? [dir] : [];
61
+ const markers = readPlacementRuntimeMarkers(home);
62
+ const binding = readActivePlacementBinding(home, markers.profile, markers.shards);
63
+ if (!binding) return unavailable("epoch");
64
+ const directories = placementFenceDirectories(home, binding);
65
+ const target = shardDir(home, project);
66
+ if (lstatSync(target, { throwIfNoEntry: false })) directories.push(target);
67
+ return directories;
60
68
  }
61
69
  const nextSync = "amem sync";
62
70
 
@@ -72,6 +80,13 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
72
80
  // A private stage without any companion cannot be attributed to this operation or silently abandoned.
73
81
  if (!plan && !staged.length && pending.hashes.includes(realm)) return unavailable("staging");
74
82
  const admitted = () => active(home, realm);
83
+ const assertTargetIdle = () => {
84
+ if (admitted()) return;
85
+ const target = shardDir(home, project);
86
+ if (!lstatSync(target, { throwIfNoEntry: false })) return;
87
+ try { assertNoLiveReaders(target, { includeShards: true }); }
88
+ catch { unavailable("lock"); }
89
+ };
75
90
  if (options.mode === "dry-run") {
76
91
  if (plan || staged.length) return { state: "retained", realm, staged: staged.length, nextStep: "resume or review abandon" };
77
92
  if (admitted()) return { state: "already-admitted", realm, nextStep: nextSync };
@@ -81,19 +96,19 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
81
96
  }
82
97
  if (options.mode === "abandon" && staged.length) {
83
98
  if (!options.confirm) return { state: "retained", realm, staged: staged.length, nextStep: "confirm abandon" };
84
- await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
99
+ await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
85
100
  const proof = { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } };
86
101
  clearRemoteAdoptionPending(home, realm, staged, proof);
87
- });
102
+ }, { surface: "admit" });
88
103
  return { state: "abandoned", realm, staged: staged.length, nextStep: plan ? "resume or review abandon" : "preview admission" };
89
104
  }
90
105
  if (options.mode === "abandon" && !plan) return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
91
106
  if (options.mode === "abandon" && plan && !options.confirm) return { state: "retained", realm, nextStep: "confirm abandon" };
92
107
  if (options.mode === "apply" && (plan || staged.length) && !admitted()) return unavailable("pending");
93
108
  if (!plan && admitted()) {
94
- if (staged.length) await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
109
+ if (staged.length) await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
95
110
  clearRemoteAdoptionPending(home, realm, staged, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
96
- });
111
+ }, { surface: "admit" });
97
112
  return { state: "already-admitted", realm, nextStep: nextSync };
98
113
  }
99
114
  if (options.mode === "resume" && !plan && !staged.length) return admitted() ? { state: "already-admitted", realm, nextStep: nextSync } : unavailable();
@@ -105,11 +120,11 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
105
120
  }
106
121
  const frozen: RemoteAdoption = plan, files = packs!;
107
122
  const clearOwn = async () => {
108
- await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
123
+ await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
109
124
  const current = readRemoteAdoption(home, realm); if (!current) return;
110
125
  if (current.seal !== frozen.seal) return unavailable("staging");
111
126
  clearRemoteAdoption(home, frozen, files, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
112
- });
127
+ }, { surface: "admit" });
113
128
  };
114
129
  if (options.mode === "abandon") {
115
130
  const oldIntent = readRealmIntent(home, realm);
@@ -120,13 +135,15 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
120
135
  await applyRealmAdmission(home, project, { mode: "abandon", confirm: true });
121
136
  }
122
137
  }
123
- await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
138
+ await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
124
139
  const current = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); };
125
140
  const proof = { mutation, assertCurrent: current };
126
- if (!admitted() && remoteAdoptionLogMayBeInstalled(home, project, frozen))
141
+ if (!admitted() && remoteAdoptionLogMayBeInstalled(home, project, frozen)) {
142
+ assertTargetIdle();
127
143
  discardRemoteInstalledLog(home, project, frozen, { mutation, assertCurrent: () => { current(); if (admitted()) unavailable(); } });
144
+ }
128
145
  clearRemoteAdoption(home, frozen, files, proof);
129
- });
146
+ }, { surface: "admit" });
130
147
  return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
131
148
  }
132
149
  if (admitted()) {
@@ -134,8 +151,9 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
134
151
  await clearOwn();
135
152
  return { state: "already-admitted", realm, nextStep: nextSync };
136
153
  }
137
- await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
154
+ await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
138
155
  if (admitted()) return;
156
+ assertTargetIdle();
139
157
  const remotePending = pendingRemoteAdoptions(home); if (remotePending.unknown) return unavailable("staging"); if (remotePending.hashes.some(hash => hash !== realm)) return unavailable("pending");
140
158
  const pending = pendingRealmInventory(home); if (pending.unknown) return unavailable("staging"); if (pending.hashes.some(hash => hash !== realm)) return unavailable("pending");
141
159
  const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
@@ -162,7 +180,7 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
162
180
  const retained = readRealmIntent(home, realm);
163
181
  const completeMetadata = source.base.realms.some(item => item.scope === "project" && item.keyHash === realm);
164
182
  installRemoteAdoptionLog(home, project, frozen, proof, !!retained || completeMetadata); await options.checkpoint?.("after-install");
165
- });
183
+ }, { surface: "admit" });
166
184
  if (admitted()) {
167
185
  await clearOwn();
168
186
  return { state: "already-admitted", realm, nextStep: nextSync };
@@ -15,7 +15,7 @@ const messages: Record<RemoteRealmCause, string> = {
15
15
  };
16
16
  export class RemoteRealmRefusal extends Error {
17
17
  constructor(readonly causeClass: RemoteRealmCause, subpath?: string) {
18
- const safeName = subpath && subpath.length <= 128 && !/[\r\n]/.test(subpath) && /^(?:log|local|legacy|legacy-main|generation\.json|generation-seal\.json|migration-sources\.json|machine\.json|prune-translations\.jsonl|prune-plans|public-prune-objects|public-prune-inputs|public-prune-input-sets|index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?|search\.db(?:-wal|-shm|-journal)?)$/.test(subpath) ? subpath : undefined;
18
+ const safeName = subpath && subpath.length <= 128 && !/[\r\n]/.test(subpath) && /^(?:log|local|legacy|legacy-main|generation\.json|generation-seal\.json|migration-sources\.json|machine\.json|prune-translations\.jsonl|prune-plans|public-prune-objects|public-prune-inputs|public-prune-input-sets|index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?|search(?:-s[0-9]+)?\.db(?:-wal|-shm|-journal)?)$/.test(subpath) ? subpath : undefined;
19
19
  super(`Remote realm unavailable (${causeClass}): ${safeName ? `existing curated subpath: ${safeName}. ` : ""}${messages[causeClass]}`); this.name = "RemoteRealmRefusal";
20
20
  }
21
21
  }
@@ -30,7 +30,7 @@ function rejectExistingCurated(dir: string): void {
30
30
  "prune-translations.jsonl", "prune-plans", "public-prune-objects", "public-prune-inputs", "public-prune-input-sets"]);
31
31
  for (const name of readdirSync(dir)) {
32
32
  if (fixed.has(name) || /^index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?$/.test(name)
33
- || /^search\.db(?:-wal|-shm|-journal)?$/.test(name))
33
+ || /^search(?:-s[0-9]+)?\.db(?:-wal|-shm|-journal)?$/.test(name))
34
34
  throw new RemoteRealmRefusal("existing", name);
35
35
  }
36
36
  }
@@ -1,17 +1,18 @@
1
+ import { purgePublicationRefusal } from "./purge-intent.ts";
1
2
  /** Activated placement transport. The public sync entrypoint owns dispatch; this module never activates a profile. */
2
3
  import { createHash, randomBytes } from "node:crypto";
3
4
  import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync, type BigIntStats } from "node:fs";
4
5
  import { join } from "node:path";
5
6
  import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
7
  import { generationSyncLock } from "./generation-sync.ts";
7
- import { placementAdvertisement } from "./sync-placement-advertisement.ts";
8
+ import { placementAdvertisement, placementStorageCacheScope, placementVisibility } from "./sync-placement-advertisement.ts";
8
9
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
9
10
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
10
11
  import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
11
12
  import { memoryPolicySnapshot } from "./policy.ts";
12
13
  import { outboundPolicyEvaluator, rowScreenIdentity } from "./sync-screen.ts";
13
- import { readActivePlacementBinding } from "./sync-placement-active.ts";
14
- import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
14
+ import { readActivePlacementBinding, withPlacementFenceMemo } from "./sync-placement-active.ts";
15
+ import { readPlacementRuntimeMarkers, readPlacementRuntimeMarkerSnapshots } from "./sync-placement-guard.ts";
15
16
  import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
16
17
  import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
17
18
  import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
@@ -40,7 +41,7 @@ import { placementCacheConfigStamp, placementCacheRootStamp, placementCacheTreeP
40
41
  import { PlacementSyncBoundError, placementSyncBoundDetail, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
41
42
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
42
43
  import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
43
- import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
44
+ import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, placementStoppedMessage, PLACEMENT_RETAINED_STOP_MESSAGE, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
44
45
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
45
46
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
46
47
  import { listRemotePlacementRealms, REMOTE_REALM_ADVERTISEMENT_BYTES, type RemoteOnlyRealm } from "./sync-placement-realm-discovery.ts";
@@ -91,6 +92,8 @@ function directory(file: string): void { const s = lstatSync(file); if (!s.isDir
91
92
  function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
92
93
  /** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
93
94
  export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
95
+ const refusal = purgePublicationRefusal(store.profile.home);
96
+ if (refusal) return { ok: false, pushed: false, entries: 0, error: refusal };
94
97
  return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
95
98
  }
96
99
 
@@ -206,7 +209,7 @@ export async function prepareRemotePlacementRealm(homeInput: string, project: st
206
209
  catch { return refuse("source-selection"); }
207
210
  ctx.check();
208
211
  };
209
- check(); releaseRoot = acquireMutation(ctx.root); if (!releaseRoot) return refuse("lock");
212
+ check(); releaseRoot = acquireMutation(ctx.root, ctx.home); if (!releaseRoot) return refuse("lock");
210
213
  releaseSync = generationSyncLock(ctx.root); if (!releaseSync) return refuse("lock");
211
214
  const gitBytes = async (args: string[], max: number) => { check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
212
215
  const advertised = await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256);
@@ -265,14 +268,16 @@ class PlacementTransport {
265
268
  }
266
269
  if (this.homeMutation) assertMutationHandle(this.homeMutation, this.home);
267
270
  for (const target of this.targets) if (target.mutation) assertMutationHandle(target.mutation, target.store.dir);
268
- const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
271
+ // #656: the reader's frozen snapshots, so the binding memo hits while the markers are unchanged; nothing here mutates them.
272
+ const markers = readPlacementRuntimeMarkerSnapshots(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
269
273
  if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse("epoch");
270
274
  }
271
275
  verify(fresh: boolean): void {
272
- this.metadata();
276
+ const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
277
+ // #656: a reused-proof check may reuse the prune-advance answer while its files keep their stamps; a complete proof reads in full.
278
+ if (complete) this.metadata(); else withPlacementFenceMemo(() => this.metadata());
273
279
  if (this.factual) { this.progress?.alive(); return; }
274
280
  if (this.opts.signal?.aborted) refuse();
275
- const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
276
281
  if (complete) {
277
282
  this.provedAt = undefined; this.attest(); this.capture?.assertUnchanged(); this.provedAt = this.clock();
278
283
  if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
@@ -281,7 +286,8 @@ class PlacementTransport {
281
286
  if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse("policy");
282
287
  this.progress?.proof(complete);
283
288
  for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
284
- this.metadata();
289
+ // #656: a reused proof runs no file or host callout between the two reads, so the opening metadata() covers it.
290
+ if (complete) this.metadata();
285
291
  }
286
292
  /** Fence check inside a proof scope: reuses a complete proof no older than PLACEMENT_PROOF_REUSE_MS. */
287
293
  check = (): void => this.verify(false);
@@ -358,13 +364,13 @@ class PlacementTransport {
358
364
  if (!existing && !this.opts.remote) refuse("remote");
359
365
  this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
360
366
  if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
361
- if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
367
+ if (await this.call(() => placementVisibility(this.opts, this.url, this.opts.visibility ?? remoteVisibility)) !== "private") refuse("remote");
362
368
  await yieldTurn(); this.prove(); // a host callout ends any reusable proof
363
369
  if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
364
- const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
370
+ const transport = acquireMutation(this.root, this.home); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
365
371
  const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync); this.syncLockHeld=true;
366
372
  for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
367
- const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
373
+ const handle = acquireMutation(dir, this.home); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
368
374
  for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
369
375
  }
370
376
  // #450: each explicitly selected realm tracks and republishes its own curated cache.
@@ -478,8 +484,16 @@ class PlacementTransport {
478
484
  evaluate(value: unknown) {
479
485
  // The configured policy is read once; complete proofs on both sides bind that read to the captured policy hash.
480
486
  if (!this.evaluator) { this.prove(); this.evaluator = outboundPolicyEvaluator(this.home, this.opts.screen); this.prove(); }
481
- this.check(); const evaluate = this.evaluator, verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
487
+ const evaluate = this.evaluator;
488
+ // #656: no screen or a package-owned deterministic screen is pure and in memory, so the fence is checked once per 64-row
489
+ // slice; the closing prove() in materialize still binds every verdict before planning. A host callback keeps the per-row pair.
490
+ if (this.opts.screen === undefined || rowScreenIdentity(this.opts.screen) !== undefined) {
491
+ if (this.evaluated++ % 64 === 0) this.check();
492
+ return evaluate(structuredClone(value) as Record<string, unknown>);
493
+ }
494
+ this.check(); const verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
482
495
  }
496
+ evaluated = 0;
483
497
  nativeProofs(): Set<string> {
484
498
  const verified=new Set<string>();
485
499
  for(const target of this.targets){
@@ -734,7 +748,7 @@ class PlacementTransport {
734
748
  }
735
749
  async run():Promise<SyncResult>{
736
750
  let result:SyncResult;
737
- try{result=await this.execute();}finally{releasePlacementStorageCaches();} // #420 memos live for one sync only
751
+ try{result=await this.execute();}finally{if(!placementStorageCacheScope(this.opts))releasePlacementStorageCaches();} // #420 memos live for one sync only; #656: an inventory run releases them itself
738
752
  // Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
739
753
  if(result.ok)this.progress?.finish("succeeded");
740
754
  else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
@@ -827,6 +841,8 @@ class PlacementTransport {
827
841
  installedGuard();
828
842
  this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
829
843
  const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
844
+ const refusal = purgePublicationRefusal(this.home);
845
+ if (refusal) return this.result(false, this.attemptHash ? "unknown" : "not-needed", refusal);
830
846
  this.attempted=participating.length>0;
831
847
  // #626: a push moves advertised refs, so no later publication of this run may reuse the advertisement read before it.
832
848
  if(this.attempted)placementAdvertisement(this.opts)?.delete(this.url);
@@ -847,7 +863,12 @@ class PlacementTransport {
847
863
  // #288 step 1: the bound's own numbers-only clause is rebuilt from the receipt for the receipt's fields, so the
848
864
  // thrown error's detail is carried over explicitly; the result's error is what the person reads.
849
865
  if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
850
- if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
866
+ if(this.attemptHash)return this.result(false,"unknown",PLACEMENT_RETAINED_STOP_MESSAGE);
867
+ // #657: a stop before any attempt exists published nothing; it is reported as stopped in its phase, never as a refusal.
868
+ if(this.opts.signal?.aborted)return this.journal?.publicationReservation
869
+ // A reservation from an earlier run may have published even before this run read its attempt: keep it as unknown.
870
+ ?this.result(false,"unknown",PLACEMENT_RETAINED_STOP_MESSAGE)
871
+ :this.result(false,"not-needed",placementStoppedMessage(this.phaseNow.replaceAll("-"," ")));
851
872
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
852
873
  if (error instanceof LocalKeyOptInRefusal) { this.failureCause = "unavailable"; return this.result(false, "not-needed", error.message); }
853
874
  // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.