@staix/agent-mem 0.29.0 → 0.31.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 (71) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +20 -574
  3. package/package.json +3 -2
  4. package/src/cli-agent-reads.ts +17 -2
  5. package/src/cli.ts +178 -21
  6. package/src/commands-table.ts +14 -2
  7. package/src/index.ts +1 -0
  8. package/src/ingest.ts +7 -5
  9. package/src/mcp-memory.ts +36 -8
  10. package/src/memory/bridge.ts +26 -1
  11. package/src/memory/candidates.ts +17 -1
  12. package/src/memory/capacity.ts +5 -2
  13. package/src/memory/catalog.ts +10 -1
  14. package/src/memory/commands.ts +2 -1
  15. package/src/memory/config.ts +13 -1
  16. package/src/memory/decay-review.ts +20 -0
  17. package/src/memory/doctor.ts +133 -47
  18. package/src/memory/eval-audit.ts +442 -0
  19. package/src/memory/eval.ts +66 -0
  20. package/src/memory/formats.ts +4 -3
  21. package/src/memory/intent-brief.ts +34 -6
  22. package/src/memory/metrics.ts +173 -14
  23. package/src/memory/native-roots.ts +28 -0
  24. package/src/memory/platform.ts +9 -1
  25. package/src/memory/review-targets.ts +69 -0
  26. package/src/memory/shard-bridge.ts +18 -6
  27. package/src/memory/shard-migration.ts +14 -1
  28. package/src/memory/shard-sync-format.ts +18 -0
  29. package/src/memory/shard-sync.ts +52 -4
  30. package/src/memory/shard.ts +4 -0
  31. package/src/memory/store.ts +4 -2
  32. package/src/memory/sync-placement-bound.ts +21 -4
  33. package/src/memory/sync-placement-cache.ts +16 -1
  34. package/src/memory/sync-placement-capture.ts +14 -2
  35. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  36. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  37. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  38. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  39. package/src/memory/sync-placement-checkpoint.ts +234 -0
  40. package/src/memory/sync-placement-dependencies.ts +42 -9
  41. package/src/memory/sync-placement-effective-writers.ts +12 -6
  42. package/src/memory/sync-placement-git.ts +17 -7
  43. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  44. package/src/memory/sync-placement-inventory.ts +38 -11
  45. package/src/memory/sync-placement-journal-format.ts +4 -1
  46. package/src/memory/sync-placement-journal-storage.ts +129 -26
  47. package/src/memory/sync-placement-materialize.ts +33 -19
  48. package/src/memory/sync-placement-projection.ts +7 -1
  49. package/src/memory/sync-placement-publication-events.ts +42 -0
  50. package/src/memory/sync-placement-publication-plan.ts +18 -1
  51. package/src/memory/sync-placement-realm-admission.ts +20 -3
  52. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  53. package/src/memory/sync-placement-remote-admission.ts +190 -0
  54. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  55. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  56. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  57. package/src/memory/sync-placement-remote-stage.ts +275 -0
  58. package/src/memory/sync-placement-transport.ts +207 -53
  59. package/src/memory/sync-placement-writer-history.ts +75 -17
  60. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  61. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  62. package/src/memory/sync-placement-yield.ts +14 -0
  63. package/src/memory/sync-progress.ts +1 -1
  64. package/src/memory/sync.ts +5 -2
  65. package/src/memory/use-telemetry.ts +15 -7
  66. package/src/setup-drift.ts +12 -2
  67. package/src/setup-owned.ts +42 -0
  68. package/src/setup.ts +32 -11
  69. package/src/sync-placement-writer-context.ts +5 -5
  70. package/src/ui/plugin.ts +26 -11
  71. package/src/ui/snapshot-cache.ts +24 -11
@@ -6,6 +6,7 @@ import { validatePruneRow } from "./prune.ts";
6
6
  import { SUGGESTED } from "./store.ts";
7
7
  import { placementKeyId, validatePlacementKey, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
8
8
  import type { OutboundVerdict, SyncPolicyCategory } from "./sync-screen.ts";
9
+ import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
9
10
  import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
10
11
 
11
12
  export interface DependencySource {
@@ -154,9 +155,17 @@ function visible(from: Node, to: Node): boolean {
154
155
  /** Pure, body-free dependency decisions. The caller supplies authoritative coalesced physical rows and
155
156
  * mandatory policy/journal verdicts; this function performs no screening, hydration, I/O or publication. */
156
157
  export function compilePlacementDependencies(raw: PlacementDependencyInput): DependencyDecision[] {
157
- try { return compile(raw); } catch (error) { if (error instanceof PlacementDependencyInputError) throw error; return fail(); }
158
+ try { return drainSteps(compileSteps(raw)); } catch (error) { if (error instanceof PlacementDependencyInputError) throw error; return fail(); }
158
159
  }
159
- function compile(raw: PlacementDependencyInput): DependencyDecision[] {
160
+ /** #470: the same decisions, awaiting the caller's event loop between row chunks; the checks and their order are identical. */
161
+ export async function compilePlacementDependenciesAsync(raw: PlacementDependencyInput, yieldPoint?: CooperativeYield): Promise<DependencyDecision[]> {
162
+ try { return await drainStepsAsync(compileSteps(raw), yieldPoint); } catch (error) { if (error instanceof PlacementDependencyInputError) throw error; return fail(); }
163
+ }
164
+ /** Rows (and decisions) between step boundaries: one chunk stays well inside the 250 ms bound on the 8,000-row fixture. */
165
+ const STEP_ROWS = 64;
166
+ /** A single decision's fan-out is bounded the same way: a goal with thousands of dependents must not block the loop. */
167
+ const STEP_REFS = 64;
168
+ function* compileSteps(raw: PlacementDependencyInput): Generator<void, DependencyDecision[], void> {
160
169
  preflight(raw);
161
170
  const input = object(copyInput(raw)); keys(input, ["generation", "selectedRealms", "rows"], ["publicEndpoints", "verifiedPrunes"]);
162
171
  if (!fullId(input.generation) || !Array.isArray(input.selectedRealms) || input.selectedRealms.length > 256 || !Array.isArray(input.rows)
@@ -184,9 +193,10 @@ function compile(raw: PlacementDependencyInput): DependencyDecision[] {
184
193
  held: output ? item.held as boolean : false, public: !output, syntaxValid: false, refs: [] };
185
194
  nodes.push(node); byKey.set(id, node); byId.set(key.id, [...(byId.get(key.id) ?? []), node]);
186
195
  };
187
- for (const value of input.rows) add(value, true);
196
+ let stepped = 0;
197
+ for (const value of input.rows) { add(value, true); if (++stepped >= STEP_ROWS) { stepped = 0; yield; } }
188
198
  const endpoints = input.publicEndpoints as unknown[] | undefined;
189
- if ((endpoints?.length ?? 0) > 20000) fail(); for (const value of endpoints ?? []) add(value, false);
199
+ if ((endpoints?.length ?? 0) > 20000) fail(); for (const value of endpoints ?? []) { add(value, false); if (++stepped >= STEP_ROWS) { stepped = 0; yield; } }
190
200
  const proofs = input.verifiedPrunes as unknown[] | undefined;
191
201
  if ((proofs?.length ?? 0) > 20000) fail();
192
202
  const verified = new Set((proofs ?? []).map(value => { const key = validatePlacementKey(value); if (!selected.has(realmId(key.realm))) fail(); return placementKeyId(key); }));
@@ -199,6 +209,7 @@ function compile(raw: PlacementDependencyInput): DependencyDecision[] {
199
209
  };
200
210
  for (const node of nodes) {
201
211
  const row = node.row;
212
+ if (++stepped >= STEP_ROWS) { stepped = 0; yield; }
202
213
  node.syntaxValid = syntax(node, input.generation);
203
214
  if (!node.syntaxValid) { node.reason = "unsupported-reference"; continue; }
204
215
  if (node.sourcePlacement === "local" || row.op === "settle" || row.op === "vault_link" || row.op === "note" && row.tier === "short") node.reason = "source-local";
@@ -240,18 +251,40 @@ function compile(raw: PlacementDependencyInput): DependencyDecision[] {
240
251
  return !heldIds.has(to.key.id) && !policyHolds.has(to.key.id) && !to.reason;
241
252
  });
242
253
  const reverse = new Map<string, Set<Node>>();
243
- for (const node of nodes) for (const ref of node.refs) {
244
- let dependents = reverse.get(ref.id); if (!dependents) reverse.set(ref.id, dependents = new Set()); dependents.add(node);
254
+ for (const node of nodes) {
255
+ for (const ref of node.refs) {
256
+ let dependents = reverse.get(ref.id); if (!dependents) reverse.set(ref.id, dependents = new Set()); dependents.add(node);
257
+ }
258
+ if (++stepped >= STEP_ROWS) { stepped = 0; yield; }
245
259
  }
246
260
  const queue = [...nodes];
247
261
  for (let at = 0; at < queue.length; at++) {
262
+ if (++stepped >= STEP_ROWS) { stepped = 0; yield; }
248
263
  const node = queue[at]!; if (node.reason) continue;
249
264
  const endpoints = node.refs.map(ref => usable(node, ref));
250
265
  let good = endpoints.every(Boolean);
251
266
  if (good && node.row.op === "supersede") good = endpoints[0]!.row.scope !== "shared" || endpoints[1]!.row.scope === "shared";
252
267
  if (!good) { node.reason = "related-local"; for (const dependent of reverse.get(node.key.id) ?? []) queue.push(dependent); }
253
268
  }
254
- return nodes.filter(node => node.output).map(node => ({ key: validatePlacementKey(node.key), eligible: !node.reason,
255
- ...(node.reason ? { reason: node.reason } : {}), dependencies: [...new Map(node.refs.flatMap(ref => candidates(node, ref).map(to => [placementKeyId(to.key), to.key] as const))).values()].sort((a,b) => placementKeyId(a).localeCompare(placementKeyId(b))).map(validatePlacementKey) }))
256
- .sort((a,b) => placementKeyId(a.key).localeCompare(placementKeyId(b.key)));
269
+ // #470: each decision's id is computed once and the id itself is what the sort compares. Recomputing placementKeyId
270
+ // inside both comparators made ordering the dominant cost of this phase (1.79 s of one gap on the 8,000-row fixture),
271
+ // and a comparator cannot yield, so the decoration is where the work is bounded and the sort stays over strings.
272
+ const ordered: { id: string; decision: DependencyDecision }[] = [];
273
+ for (const node of nodes) {
274
+ if (!node.output) continue;
275
+ if (++stepped >= STEP_ROWS) { stepped = 0; yield; }
276
+ // One decision's dependency set is the union of its refs' candidates; a wide fan-out yields per ref chunk.
277
+ const related = new Map<string, PlacementKey>();
278
+ let refs = 0;
279
+ for (const ref of node.refs) {
280
+ if (++refs >= STEP_REFS) { refs = 0; yield; }
281
+ for (const to of candidates(node, ref)) { const id = placementKeyId(to.key); if (!related.has(id)) related.set(id, to.key); }
282
+ }
283
+ const key = validatePlacementKey(node.key);
284
+ ordered.push({ id: placementKeyId(key), decision: { key, eligible: !node.reason,
285
+ ...(node.reason ? { reason: node.reason } : {}),
286
+ dependencies: [...related].sort(([a],[b]) => a.localeCompare(b)).map(([, value]) => validatePlacementKey(value)) } });
287
+ }
288
+ ordered.sort((a, b) => a.id.localeCompare(b.id));
289
+ return ordered.map(entry => entry.decision);
257
290
  }
@@ -9,6 +9,7 @@ import { readWriterHistory, isWriterRenewalIntentTempName } from "./sync-placeme
9
9
  import { SharedWriterRevisionError, writerRevisionWriters, WRITER_RENEWAL_INTENT_FILE } from "./sync-placement-writer-revision-format.ts";
10
10
  import { readInitialSyncPlacementWriterLocator, SYNC_PLACEMENT_WRITER_ROOTS_FILE } from "./sync-placement-writer-roots.ts";
11
11
  import { requireWriterRenewalHomeFloor } from "./sync-placement-prerequisites.ts";
12
+ import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
12
13
  import type { SyncPlacementWriterAttestation } from "./sync-placement-plan.ts";
13
14
 
14
15
  export interface EffectiveSyncPlacementWriters {
@@ -39,21 +40,24 @@ export function writerInventoryEvidence(home:string,epochHash:string):boolean{
39
40
  dir=join(dir,part);const s=lstatSync(dir,{throwIfNoEntry:false});if(!s)return outside;
40
41
  if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o077)!==0)throw new SharedWriterRevisionError("invalid");
41
42
  }
42
- return scan(dir,255,name=>name.startsWith("writer-"))||outside;
43
+ // #288: a committed checkpoint is itself writer evidence (its (W, 1) renewal); the live window comes from the resolver.
44
+ let window;try{window=resolvePlacementWindow(home,epochHash);}catch{throw new SharedWriterRevisionError("invalid");}
45
+ if(window.window||window.pending)return true;
46
+ return scan(window.dir,255,name=>name.startsWith("writer-"))||outside;
43
47
  }
44
48
  export function readEffectiveSyncPlacementWriters(home:string):EffectiveSyncPlacementWriters {
45
49
  const binding=active(home),bindingKey=key(binding),epochHash=binding.profile.placementHead;
46
50
  writerInventoryEvidence(home,epochHash);
47
51
  const history=readWriterHistory(home,{epochHash,activationHash:binding.activation.seal,homeHash:binding.epoch.homeHash,generation:binding.epoch.generation});
48
52
  const initialStamp=fileStamp(home),initial=initialStamp===undefined?undefined:readInitialSyncPlacementWriterLocator(home);
49
- if(history.sequence){
53
+ if(history.sequence||history.window){
50
54
  requireWriterRenewalHomeFloor(home);
51
55
  if(!initial||history.current?.initialLocatorHash!==initial.seal)fail();
52
56
  }
53
57
  let anchorToken:string|undefined;
54
58
  // ponytail: native inode/size/ctime identity permits prefix reuse; hostile same-user rewrites need immutable snapshot blocks.
55
59
  const anchors=()=>{
56
- if(!history.sequence)return;
60
+ if(!history.sequence&&!history.window)return;
57
61
  const token=placementWriterJournalToken(home,epochHash);if(token===anchorToken)return;
58
62
  const journal=readPlacementWriterJournalAnchors(home,epochHash);
59
63
  if(journal.epoch.homeHash!==binding.epoch.homeHash||journal.activation.seal!==binding.activation.seal)fail();
@@ -65,13 +69,15 @@ export function readEffectiveSyncPlacementWriters(home:string):EffectiveSyncPlac
65
69
  const assertCurrent=()=>{
66
70
  history.assertCurrent();if(key(active(home))!==bindingKey||fileStamp(home)!==initialStamp)fail();
67
71
  if(initial&&readInitialSyncPlacementWriterLocator(home).seal!==initial.seal)fail();
68
- if(history.sequence)requireWriterRenewalHomeFloor(home);
72
+ if(history.sequence||history.window)requireWriterRenewalHomeFloor(home);
69
73
  anchors();history.assertCurrent();
70
74
  };
71
75
  anchors();assertCurrent();
72
76
  const roots=history.current?.roots.map(root=>root.root)??initial?.roots.map(root=>root.root);
73
- return{epochHash,activationHash:binding.activation.seal,revisionSequence:history.sequence,revisionHash:history.headHash,
74
- writers:history.current?writerRevisionWriters(history.current):binding.activation.writers,
77
+ // #288: the logical revision count spans every window; the head is the live window's last commit.
78
+ return{epochHash,activationHash:binding.activation.seal,revisionSequence:history.commits.length,revisionHash:history.headHash,
79
+ // The revision was chain-checked against its own window genesis by readWriterHistory.
80
+ writers:history.current?writerRevisionWriters(history.current,history.current.sequence===1?history.current.previousHash:undefined):binding.activation.writers,
75
81
  ...(roots?{roots}:{}),...(initial?{initialLocatorHash:initial.seal}:{}),assertCurrent};
76
82
  }
77
83
  /** Locators only; these paths and expected pins never replace a fresh callback. */
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
3
3
  import { types } from "node:util";
4
4
  import { PUBLIC_PRUNE_REPLAY_MAX_BYTES } from "./public-prune-input-chain.ts";
5
5
  import { decodePlacementTransportDescriptor, decodeShardManifest, isShardManifestPath, SHARD_PACK_MAX_BYTES, type ShardSyncRealm } from "./shard-sync-format.ts";
6
+ import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
6
7
 
7
8
  export interface PlannedGitObject { type: "blob" | "tree" | "commit"; oid: string; bytes: Buffer; path: string | null }
8
9
  export interface PlacementGitObjects { objects: PlannedGitObject[]; tree: string; commit: string }
@@ -27,10 +28,17 @@ function object(type: PlannedGitObject["type"], bytes: Buffer, path: string | nu
27
28
  * Retained public bytes share the existing replay bound; new source's separate 8MiB allowance is the caller's proof. */
28
29
  export function compilePlacementGitObjects(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
29
30
  previous?: { tree: string; commit: string }): PlacementGitObjects {
30
- try { return compile(files, parent, createdUnixSeconds, previous); } catch { return fail(); }
31
+ try { return drainSteps(compileSteps(files, parent, createdUnixSeconds, previous)); } catch { return fail(); }
31
32
  }
32
- function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
33
- previous?: { tree: string; commit: string }): PlacementGitObjects {
33
+ /** #470: the same objects, awaiting the caller's event loop between entries and tree nodes; bytes and ids are identical. */
34
+ export async function compilePlacementGitObjectsAsync(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
35
+ previous?: { tree: string; commit: string }, yieldPoint?: CooperativeYield): Promise<PlacementGitObjects> {
36
+ try { return await drainStepsAsync(compileSteps(files, parent, createdUnixSeconds, previous), yieldPoint); } catch { return fail(); }
37
+ }
38
+ /** Objects between step boundaries: at most 128 blob hashes per uninterrupted stretch. */
39
+ const STEP_OBJECTS = 128;
40
+ function* compileSteps(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
41
+ previous?: { tree: string; commit: string }): Generator<void, PlacementGitObjects, void> {
34
42
  if (!files || typeof files !== "object" || types.isProxy(files) || Object.getPrototypeOf(files) !== Map.prototype
35
43
  || !Number.isSafeInteger(createdUnixSeconds) || createdUnixSeconds < 0 || parent !== null && !oid(parent)) return fail();
36
44
  const count = mapSize.call(files);
@@ -42,9 +50,10 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
42
50
  || !oid(fields.tree.value) || !oid(fields.commit.value)) return fail();
43
51
  previous = { tree: fields.tree.value, commit: fields.commit.value };
44
52
  }
45
- const entries: { path: string; bytes: Buffer }[] = []; let total = 0;
53
+ const entries: { path: string; bytes: Buffer }[] = []; let total = 0, stepped = 0;
46
54
  for (const [path, value] of Map.prototype.entries.call(files) as Iterable<[unknown, unknown]>) {
47
55
  if (typeof path !== "string" || types.isProxy(value) || !(value instanceof Uint8Array)) return fail();
56
+ if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
48
57
  const pack = PACK.exec(path), validPack = pack?.[0] === path;
49
58
  if (path !== "shard.json" && !validPack && !isShardManifestPath(path)) return fail();
50
59
  const length = getLength.call(value) as number, maximum = validPack ? SHARD_PACK_MAX_BYTES : 64 * 1024;
@@ -70,10 +79,11 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
70
79
  for (const name of parts.slice(0, -1)) { if (target.blobs.has(name)) return fail(); let next = target.directories.get(name); if (!next) target.directories.set(name, next = node()); target = next; }
71
80
  const name = parts.at(-1)!; if (target.directories.has(name) || target.blobs.has(name)) return fail(); target.blobs.set(name, blob.oid);
72
81
  }
73
- const buildTree = (tree: TreeNode, path: string): string => {
82
+ const buildTree = function* (tree: TreeNode, path: string): Generator<void, string, void> {
74
83
  const children: { name: string; oid: string; directory: boolean }[] = [...tree.blobs].map(([name, id]) => ({ name, oid: id, directory: false }));
84
+ if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
75
85
  for (const [name, directory] of [...tree.directories].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))
76
- children.push({ name, oid: buildTree(directory, path ? `${path}/${name}` : name), directory: true });
86
+ children.push({ name, oid: yield* buildTree(directory, path ? `${path}/${name}` : name), directory: true });
77
87
  children.sort((a,b) => Buffer.compare(Buffer.from(a.name + (a.directory ? "/" : "")), Buffer.from(b.name + (b.directory ? "/" : ""))));
78
88
  let length = 0; const chunks: Buffer[] = [];
79
89
  for (const child of children) {
@@ -82,7 +92,7 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
82
92
  }
83
93
  const result = object("tree", Buffer.concat(chunks, length), path); trees.push(result); return result.oid;
84
94
  };
85
- const tree = buildTree(root, "");
95
+ const tree = yield* buildTree(root, "");
86
96
  trees.sort((a,b) => (b.path ? b.path.split("/").length : 0) - (a.path ? a.path.split("/").length : 0)
87
97
  || (a.path! < b.path! ? -1 : a.path! > b.path! ? 1 : 0));
88
98
  objects.push(...trees);
@@ -29,7 +29,7 @@ export function captureInspectionJournal(home: string, epochHash: string): Inspe
29
29
  const captured = capturePlacementPublicationMetadata(home, epochHash, io => {
30
30
  const journal = io.journal();
31
31
  if (journal.pending) throw new SyncPlacementJournalError("pending");
32
- const attempts = new Set<string>();
32
+ const attempts = new Set<string>(io.archivedPublications());
33
33
  for (const name of io.names()) {
34
34
  const match = /^publication-([a-f0-9]{64})-/.exec(name);
35
35
  if (match) attempts.add(match[1]!);
@@ -15,11 +15,12 @@ import { join } from "node:path";
15
15
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
16
16
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
17
17
  import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
18
+ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
18
19
  import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
19
20
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
20
- import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
21
+ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
21
22
  import { projectState } from "./lifecycle.ts";
22
- import type { PlacementRealm } from "./sync-placement-journal-format.ts";
23
+ import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
23
24
  import type { SyncOptions, SyncResult } from "./sync.ts";
24
25
  import type { MemoryStore } from "./store.ts";
25
26
 
@@ -28,7 +29,7 @@ const PUBLICATION_TARGETS = 2;
28
29
 
29
30
  /** One activated realm with its local key (the project key is resolved from the local descriptor; user has none). */
30
31
  export type InventoryRealm = { scope: "user" } | { scope: "project"; key: string; keyHash: string };
31
- export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive";
32
+ export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held";
32
33
  /** Per-realm receipt: identifiers only (the user realm or the full key hash), never a project name, row or path. */
33
34
  export interface PlacementRealmResult { realm: "user" | string; outcome: PlacementRealmOutcome; publication?: number }
34
35
 
@@ -85,18 +86,44 @@ function retainedRealms(home: string): string[] | undefined {
85
86
  return readPlacementPublication(home, active.profile.placementHead, reservation.attemptHash).bundle.root.targets.map(target => label(target.realm));
86
87
  }
87
88
 
89
+ /** #492: one retained-journal refusal reads as the run's own failure. `unavailable` is the closed vocabulary's term for
90
+ * a refusal before an attempt (activation, inventory or I/O); a checkpoint's own cause keeps it, as it already does above.
91
+ */
92
+ function journalRefusal(error: unknown): (SyncResult & { placementRealms: PlacementRealmResult[] }) | undefined {
93
+ if (!error || typeof error !== "object" || !(error instanceof SyncPlacementJournalError)) return undefined;
94
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
95
+ return { ok: false, pushed: false, entries: 0, error: error.message,
96
+ failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
97
+ }
98
+
88
99
  export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
89
- const { local, missing, inactive } = placementInventory(home);
90
- const retained = retainedRealms(home);
100
+ let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
101
+ try {
102
+ // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
103
+ const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
104
+ if (binding && placementCheckpointPending(home, binding.profile.placementHead))
105
+ return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
106
+ ({ local, missing, inactive } = placementInventory(home));
107
+ retained = retainedRealms(home);
108
+ } catch (error) {
109
+ // #492: the inventory is the retained epoch's first reader, so its refusal there (an unknown epoch member, a torn
110
+ // chunk) is answered as this run's own failure before any effect, never thrown past the caller's result shape.
111
+ const refused = journalRefusal(error); if (refused) return refused; throw error;
112
+ }
113
+ const held = opts.remote === undefined ? local.filter((realm): realm is Extract<InventoryRealm, { scope: "project" }> => realm.scope === "project" && isLocalKey(realm.key)) : [];
114
+ const resumed = retained;
115
+ const retainedHeld = held.find(realm => resumed?.includes(label(realm)));
116
+ if (retainedHeld) return { ok: false, pushed: false, entries: 0, error: `Retained publication cannot resume. ${localKeyOptInMessage(retainedHeld.key)}`, failure: { cause: "unavailable" }, placementRealms: [{ realm: label(retainedHeld), outcome: "held" }] };
117
+ local = local.filter(realm => !held.includes(realm as Extract<InventoryRealm, { scope: "project" }>));
91
118
  let order = local;
92
- if (retained) {
119
+ if (resumed) {
93
120
  // The retained plan names its own realms; it runs first, exactly as recorded, then the rest in the usual order.
94
- const first = retained.map(name => local.find(realm => label(realm) === name));
121
+ const first = resumed.map(name => local.find(realm => label(realm) === name));
95
122
  if (first.some(realm => !realm)) throw new Error("a retained placement publication names a realm without a local curated shard; inspect it before continuing");
96
- order = [...first as InventoryRealm[], ...local.filter(realm => !retained.includes(label(realm)))];
123
+ order = [...first as InventoryRealm[], ...local.filter(realm => !resumed.includes(label(realm)))];
97
124
  }
98
- const batches = retained ? [order.slice(0, retained.length), ...placementInventoryBatches(order.slice(retained.length))] : placementInventoryBatches(order);
99
- const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const }))];
125
+ const batches = resumed ? [order.slice(0, resumed.length), ...placementInventoryBatches(order.slice(resumed.length))] : placementInventoryBatches(order);
126
+ const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const })), ...held.map(realm => ({ realm: label(realm), outcome: "held" as const }))];
100
127
  const progress = opts.progress, total = batches.filter(batch => batch.length).length;
101
128
  // One reporter for the whole run: each publication reports its phases, but only this driver reports the terminal state.
102
129
  const report = (completed: number) => progress?.inventory({ publications: total, completed, realms: order.length,
@@ -132,5 +159,5 @@ export async function syncPlacementInventory(home: string, opts: SyncOptions, po
132
159
  const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
133
160
  return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
134
161
  ...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
135
- ...(stopped?.error !== undefined ? { error: stopped.error } : {}), placementRealms: realms };
162
+ ...(stopped?.error !== undefined ? { error: stopped.error } : {}), ...(held.length ? { warning: [base.warning, ...held.map(realm => localKeyOptInMessage(realm.key))].filter(Boolean).join(" ") } : {}), placementRealms: realms };
136
163
  }
@@ -8,13 +8,16 @@ export const PLACEMENT_RECORD_SCHEMA = "agent-mem.sync-placement-record/v1";
8
8
  export const PLACEMENT_ACTIVE_FENCE_SCHEMA = "agent-mem.sync-placement-fence/v1";
9
9
  export const PLACEMENT_JOURNAL_MAX_RECORDS = 20_000, PLACEMENT_JOURNAL_MAX_OBJECTS = 256;
10
10
  export const PLACEMENT_JOURNAL_CHUNK_MAX_BYTES = 64 * 1024, PLACEMENT_JOURNAL_ROOT_MAX_BYTES = 256 * 1024;
11
- export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "changed" | "authorization" | "policy" | "local" | "busy";
11
+ export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "checkpoint-pending" | "changed" | "authorization" | "policy" | "local" | "busy";
12
+ export const PLACEMENT_CHECKPOINT_COMMAND = "amem migrate --sync-placement --checkpoint";
13
+ export const PLACEMENT_CHECKPOINT_PENDING_MESSAGE = `A placement checkpoint is pending; placement effects are paused until it finishes. Run ${PLACEMENT_CHECKPOINT_COMMAND} --resume to complete its recorded bytes, or ${PLACEMENT_CHECKPOINT_COMMAND} --abandon if its commit line has not started.`;
12
14
  const messages: Record<SyncPlacementJournalErrorCode, string> = {
13
15
  invalid: "Sync placement journal data is invalid or unsupported; inspect the retained state and use a compatible runtime.",
14
16
  corrupt: "Sync placement journal evidence is incomplete or inconsistent; restore the exact retained evidence before continuing.",
15
17
  bound: "Sync placement journal exceeds its supported bounds; a person-reviewed bounded epoch transition is required.",
16
18
  conflict: "Sync placement journal identity or request conflicts with retained evidence; inspect the exact request before retrying.",
17
19
  pending: "Sync placement journal has an unfinished transaction; resume its exact recorded request before continuing.",
20
+ "checkpoint-pending": PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
18
21
  changed: "Sync placement journal or source bindings changed; capture and review a fresh request before continuing.",
19
22
  authorization: "Sync placement change requires explicit person authorization of the exact reviewed request.",
20
23
  policy: "Current mandatory policy refuses this sync placement change; inspect its safe policy classification.",