@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
@@ -1,42 +1,50 @@
1
1
  /** Activated placement transport. The public sync entrypoint owns dispatch; this module never activates a profile. */
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync } from "node:fs";
3
+ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync, type BigIntStats } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
7
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
8
8
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
- import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
9
+ import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
10
10
  import { memoryPolicySnapshot } from "./policy.ts";
11
11
  import { outboundPolicyEvaluator } from "./sync-screen.ts";
12
12
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
13
13
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
14
- import { captureSyncPlacementContextAsync, placementCaptureContextHash, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
14
+ import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
15
15
  import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
16
16
  import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
17
17
  import { types } from "node:util";
18
+ import { RemoteRealmRefusal, type RemoteRealmCause } from "./sync-placement-remote-refusal.ts";
18
19
  import type { PlannedGitObject } from "./sync-placement-git.ts";
19
- import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
20
- import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementHoldReason, type PlacementRecord } from "./sync-placement-journal-format.ts";
20
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError } from "./sync-placement-format.ts";
21
+ import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
21
22
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
22
- import { readPlacementJournal, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
+ import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
24
  import { formatFloorAtLeast } from "./formats.ts";
24
25
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
25
- import { planPlacementPublication, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
26
+ import { planPlacementPublication, planPlacementPublicationAsync, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
27
+ import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
26
28
  import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
27
29
  import { ShardSyncApplications } from "./shard-sync-applications.ts";
28
- import { shardSourceRows, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
30
+ import { ShardSourceChangedError, shardSourceRowsAsync, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
29
31
  import { shardSyncRef, SHARD_PACK_MAX_BYTES } from "./shard-sync-format.ts";
30
32
  import { assertPublisherBoundary, ensurePublisherBoundary, publisherPruneLineages } from "./prune-publisher-lineage.ts";
31
33
  import type { MemoryStore } from "./store.ts";
32
34
  import type { PruneRow } from "./prune.ts";
33
35
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
34
- import { cooperativeYield, PLACEMENT_APPEND_SLICE, yieldTurn } from "./sync-placement-yield.ts";
35
- import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
36
- import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
36
+ import { cooperativeYield, drainSteps, drainStepsAsync, PLACEMENT_APPEND_SLICE, yieldTurn, type CooperativeYield } from "./sync-placement-yield.ts";
37
+ import { placementCacheConfigStamp, placementCacheRootStamp, placementCacheTreePrivate, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
38
+ import { PlacementSyncBoundError, placementSyncBoundDetail, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
39
+ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
37
40
  import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
38
41
  import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
39
42
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
43
+ import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
44
+ import { listRemotePlacementRealms, REMOTE_REALM_ADVERTISEMENT_BYTES, type RemoteOnlyRealm } from "./sync-placement-realm-discovery.ts";
45
+ import { realPath } from "./platform.ts";
46
+ import { createRemoteAdoption, REMOTE_ADOPTION_SCHEMA, validateRemoteAdoption, type RemoteAdoption } from "./sync-placement-remote-adoption-format.ts";
47
+ import { remoteStagedPacks, selectRemoteMaterialization, type RemoteStagedPack } from "./sync-placement-remote-materialization.ts";
40
48
 
41
49
  /**
42
50
  * #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
@@ -55,10 +63,21 @@ const oid = (v: unknown): v is string => typeof v === "string" && v.length === 4
55
63
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
56
64
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
57
65
  function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
66
+ class LocalKeyOptInRefusal extends Error {}
67
+ function remoteRefusal(error: unknown, fallback: RemoteRealmCause = "other"): never {
68
+ if (error instanceof RemoteRealmRefusal) throw error;
69
+ if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") throw new RemoteRealmRefusal("epoch");
70
+ const category = placementRefusalCategoryOf(error) ?? classifyPlacementError(error);
71
+ const cause: RemoteRealmCause = category === "lock" ? "lock" : category === "epoch" ? "epoch"
72
+ : category === "remote" ? "remote" : category === "size-bound" ? "bound"
73
+ : category === "source-selection" || category === "policy" || category === "writer-pin" ? "drift" : fallback;
74
+ throw new RemoteRealmRefusal(cause);
75
+ }
58
76
  /** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
59
77
  export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
60
78
  try {
61
79
  if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
80
+ if (error instanceof ShardSourceChangedError) return "source-selection";
62
81
  if (error instanceof SharedWriterRevisionError) return "writer-pin";
63
82
  if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
64
83
  const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
@@ -72,6 +91,145 @@ function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map
72
91
  export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
73
92
  return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
74
93
  }
94
+
95
+ type RemoteReadOptions = Pick<SyncOptions, "signal" | "visibility">;
96
+ /** Shared configured-remote proof for discovery and audited read-only preview. */
97
+ async function configuredRemoteContext(homeInput: string, opts: RemoteReadOptions, requireVisibility = true) {
98
+ // Git tracing can write an arbitrary file outside the sync cache, which a read-only listing must not do.
99
+ if (Object.entries(process.env).some(([name, value]) => name.startsWith("GIT_TRACE") && !!value)) throw new RemoteRealmRefusal("environment");
100
+ const home = realPath(homeInput), markers = readPlacementRuntimeMarkers(home);
101
+ if (!markers.profile || typeof markers.profile !== "object" || Object.getOwnPropertyDescriptor(markers.profile, "schema")?.value !== PLACEMENT_PROFILE_SCHEMA) return refuse("epoch");
102
+ const active = readActivePlacementBinding(home, markers.profile, markers.shards);
103
+ if (!active) return refuse("epoch");
104
+ const inventory = readEffectiveRealmInventory(home, active), root = join(home, "shard-sync-placement"), cache = join(root, "objects.git");
105
+ let rootStamp: string, configStamp: string, initial: BigIntStats;
106
+ try { rootStamp = placementCacheRootStamp(home); configStamp = placementCacheConfigStamp(cache); initial = lstatSync(cache, { bigint: true }); }
107
+ catch { throw new RemoteRealmRefusal("cache"); }
108
+ if (!initial.isDirectory() || initial.isSymbolicLink() || initial.uid !== BigInt(process.getuid?.() ?? -1) || (initial.mode & 0o077n) !== 0n) throw new RemoteRealmRefusal("cache");
109
+ if (!placementCacheTreePrivate(cache)) throw new RemoteRealmRefusal("cache");
110
+ const forbidden = ["commondir", "shallow", "info/grafts", "objects/info/alternates", "objects/info/http-alternates", "config.worktree"];
111
+ try { if (forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined)) throw new RemoteRealmRefusal("cache"); }
112
+ catch { throw new RemoteRealmRefusal("cache"); }
113
+ const check = () => {
114
+ let stat: BigIntStats; try { stat = lstatSync(cache, { bigint: true }); } catch { throw new RemoteRealmRefusal("cache"); }
115
+ const nowMarkers = readPlacementRuntimeMarkers(home), now = readActivePlacementBinding(home, nowMarkers.profile, nowMarkers.shards);
116
+ if (!now || canonicalJSON(now.profile) !== canonicalJSON(active.profile) || canonicalJSON(now.shards) !== canonicalJSON(active.shards)) return refuse("source-selection");
117
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== initial.dev || stat.ino !== initial.ino
118
+ || !cacheUnchanged()) throw new RemoteRealmRefusal("cache");
119
+ try { inventory.assertCurrent(); } catch { return refuse("source-selection"); }
120
+ };
121
+ const cacheUnchanged = () => { try { return placementCacheRootStamp(home) === rootStamp && placementCacheConfigStamp(cache) === configStamp && !forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined); } catch { return false; } };
122
+ const args = (values: string[]) => ["--no-replace-objects", "--git-dir", cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...values];
123
+ check();
124
+ const config = await generationSyncGitBytes(root, args(["config", "--local", "--no-includes", "--null", "--list"]), opts.signal, undefined, 65536);
125
+ check(); if (config.code !== 0) throw new RemoteRealmRefusal("cache");
126
+ let settings: ReadonlyMap<string, string>; try { settings = validatePlacementCacheConfig(new TextDecoder("utf-8", { fatal: true }).decode(config.out)); } catch { throw new RemoteRealmRefusal("cache"); }
127
+ const url = settings.get("remote.origin.url");
128
+ if (settings.get("core.bare") !== "true" || settings.has("remote.origin.pushurl") && settings.get("remote.origin.pushurl") !== url) throw new RemoteRealmRefusal("cache");
129
+ if (!url || url.length > 4096 || url.startsWith("-") || /[\r\n\0]/.test(url)) return refuse("remote");
130
+ if (requireVisibility && await (opts.visibility ?? remoteVisibility)(url) !== "private") return refuse("remote");
131
+ check();
132
+ return { home, active, inventory, root, cache, url, args, check };
133
+ }
134
+
135
+ /** Read only the configured placement remote; discovery never initializes a cache or adopts a realm. */
136
+ export async function discoverRemotePlacementRealms(homeInput: string, opts: RemoteReadOptions = {}): Promise<RemoteOnlyRealm[]> {
137
+ try {
138
+ const context = await configuredRemoteContext(homeInput, opts);
139
+ const realms = await listRemotePlacementRealms(context.inventory, async () => {
140
+ const advertised = await generationSyncGitBytes(context.root, context.args(["ls-remote", "--refs", context.url, "refs/heads/amem/p/*"]), opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES);
141
+ context.check(); if (advertised.code !== 0) return refuse("remote");
142
+ return advertised.out;
143
+ });
144
+ context.check(); return realms;
145
+ } catch (error) { return remoteRefusal(error); }
146
+ }
147
+
148
+ /** Recheck the reviewed head and configured remote immediately before staging publication. */
149
+ export async function assertRemoteAdoptionCurrent(homeInput: string, project: string, plan: RemoteAdoption, opts: RemoteReadOptions = {}): Promise<void> {
150
+ try {
151
+ plan = validateRemoteAdoption(plan);
152
+ const ctx = await configuredRemoteContext(homeInput, opts), key = createHash("sha256").update(project).digest("hex");
153
+ if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
154
+ || ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
155
+ const ref = shardSyncRef({ scope: "project", key: project }), result = await generationSyncGitBytes(ctx.root,
156
+ ctx.args(["ls-remote", "--refs", ctx.url, ref]), opts.signal, undefined, 256);
157
+ ctx.check(); if (result.code !== 0 || new TextDecoder("utf-8", { fatal: true }).decode(result.out) !== `${plan.remoteHead}\t${ref}\n`) return refuse("remote");
158
+ } catch (error) { return remoteRefusal(error); }
159
+ }
160
+
161
+ export interface PreparedRemoteRealm { plan: RemoteAdoption; packs: RemoteStagedPack[] }
162
+ async function auditRemoteHistory(ctx: Awaited<ReturnType<typeof configuredRemoteContext>>, project: string, head: string, opts: RemoteReadOptions): Promise<ShardHistory> {
163
+ const gitBytes = async (args: string[], max: number) => { ctx.check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); ctx.check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
164
+ const auditor = new ShardHistoryAuditor({ realm: { scope: "project", key: project }, generation: ctx.active.epoch.generation, placement: true, publicPrune: true,
165
+ git: async args => { ctx.check(); const result = await generationSyncGit(ctx.root, ctx.args(args), opts.signal); ctx.check(); if (result.code !== 0) return refuse("remote"); return result.out; },
166
+ blob: async (oid, path) => gitBytes(["cat-file", "blob", oid], path === "shard.json" || path.startsWith("prune-witnesses/") ? 65536 : SHARD_PACK_MAX_BYTES),
167
+ object: async (oid, type) => {
168
+ const bytes = await gitBytes(["cat-file", type, oid], type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES);
169
+ if (createHash("sha1").update(`${type} ${bytes.length}\0`).update(bytes).digest("hex") !== oid) return refuse("remote"); return bytes;
170
+ },
171
+ });
172
+ return auditor.history(head);
173
+ }
174
+
175
+ /** Reconstruct frozen pack bytes from the existing cache without contacting the remote. */
176
+ export async function recoverRemoteStagedPacks(homeInput: string, project: string, plan: RemoteAdoption): Promise<RemoteStagedPack[]> {
177
+ try {
178
+ plan = validateRemoteAdoption(plan);
179
+ const ctx = await configuredRemoteContext(homeInput, {}, false), key = createHash("sha256").update(project).digest("hex");
180
+ if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
181
+ || ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
182
+ const selection = selectRemoteMaterialization(await auditRemoteHistory(ctx, project, plan.remoteHead, {})), packs = remoteStagedPacks(selection);
183
+ if (selection.omitted !== plan.omitted || canonicalJSON(packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length }))) !== canonicalJSON(plan.packs)) return refuse("source-selection");
184
+ ctx.check(); return packs;
185
+ } catch (error) { return remoteRefusal(error, "staging"); }
186
+ }
187
+ /** Fetch and audit one explicitly named remote-only realm into the existing private cache, never the live shard. */
188
+ export async function prepareRemotePlacementRealm(homeInput: string, project: string, opts: RemoteReadOptions = {}): Promise<PreparedRemoteRealm> {
189
+ let releaseRoot: (() => void) | undefined, releaseSync: (() => void) | undefined, incoming: string | undefined;
190
+ let context: Awaited<ReturnType<typeof configuredRemoteContext>> | undefined;
191
+ try {
192
+ if (!project || Buffer.byteLength(project) > 400 || /[\r\n\0]/.test(project)) return refuse("source-selection");
193
+ context = await configuredRemoteContext(homeInput, opts);
194
+ const ctx = context, keyHash = createHash("sha256").update(project).digest("hex");
195
+ // Ref names use only 16 hex characters; a prefix already bound to another full key is never adopted as a new realm.
196
+ if (ctx.inventory.realms.some(realm => realm.scope === "project" && realm.keyHash.slice(0, 16) === keyHash.slice(0, 16))) return refuse("source-selection");
197
+ const ref = shardSyncRef({ scope: "project", key: project }), source = previewSyncPlacementSources(ctx.home);
198
+ const writers = readEffectiveSyncPlacementWriters(ctx.home), journalToken = placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead);
199
+ const journal = readPlacementWriterJournalAnchors(ctx.home, ctx.active.profile.placementHead);
200
+ const journalHead = journal.sequence ? journal.records[journal.sequence - 1]!.seal : ctx.active.profile.placementHead;
201
+ const check = () => {
202
+ ctx.check();
203
+ try { writers.assertCurrent(); if (placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead) !== journalToken) return refuse("source-selection"); source.assertSourcesUnchanged(); }
204
+ catch { return refuse("source-selection"); }
205
+ ctx.check();
206
+ };
207
+ check(); releaseRoot = acquireMutation(ctx.root); if (!releaseRoot) return refuse("lock");
208
+ releaseSync = generationSyncLock(ctx.root); if (!releaseSync) return refuse("lock");
209
+ 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); };
210
+ const advertised = await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256);
211
+ const match = /^([a-f0-9]{40})\t([^\n]+)\n$/.exec(advertised.toString("utf8"));
212
+ if (!match || match[2] !== ref) return refuse("remote");
213
+ const head = match[1]!; incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`;
214
+ await gitBytes(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", ctx.url, `${ref}:${incoming}`], 65536);
215
+ const fetched = (await gitBytes(["rev-parse", "--verify", incoming], 128)).toString("utf8").trim(); if (fetched !== head) return refuse("remote");
216
+ const history = await auditRemoteHistory(ctx, project, head, opts), selection = selectRemoteMaterialization(history), packs = remoteStagedPacks(selection);
217
+ if (!(await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256)).equals(advertised)) return refuse("remote");
218
+ check();
219
+ const plan = createRemoteAdoption({ schema: REMOTE_ADOPTION_SCHEMA, homeHash: ctx.active.epoch.homeHash, epochHash: ctx.active.profile.placementHead,
220
+ generation: ctx.active.epoch.generation, keyHash, remoteHash: createHash("sha256").update(ctx.url).digest("hex"), remoteHead: head,
221
+ sourceHash: source.base.sourceHash, policyHash: source.base.policyHash, aliasesHash: source.base.aliasesHash,
222
+ writerHash: writers.revisionHash, inventoryHead: ctx.inventory.extensionHead, journalSequence: journal.sequence, journalHead, omitted: selection.omitted,
223
+ packs: packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length })) });
224
+ check(); return { plan, packs };
225
+ } catch (error) { return remoteRefusal(error); }
226
+ finally {
227
+ if (context && incoming) try {
228
+ context.check(); await generationSyncGit(context.root, context.args(["update-ref", "--no-deref", "-d", incoming]), undefined);
229
+ } catch { /* no authoritative state uses this private cache ref */ }
230
+ releaseSync?.(); releaseRoot?.();
231
+ }
232
+ }
75
233
  class PlacementTransport {
76
234
  readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
77
235
  readonly releases: (() => void)[] = []; readonly temporary: string[] = []; readonly refs: string[] = [];
@@ -83,6 +241,8 @@ class PlacementTransport {
83
241
  /** #462: a closed cause the catch block identified before `result` derives the rest. */
84
242
  failureCause?: SyncFailureCause;
85
243
  readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
244
+ /** #288 step 1: the journal-objects bound's own composition, numbers only, set where the bound is measured. */
245
+ journalObjects?: PlacementJournalObjectComposition;
86
246
  readonly selected?: readonly MemoryStore[];
87
247
  constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now(), selected?: readonly MemoryStore[]) { this.selected=selected; this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
88
248
  attest(): void {
@@ -145,7 +305,7 @@ class PlacementTransport {
145
305
  }
146
306
  async independent(): Promise<boolean> {
147
307
  if (!existsSync(this.cache)) return false; directory(this.cache); const initial=lstatSync(this.cache);
148
- const walk = (dir: string): void => { for (const name of readdirSync(dir)) { const file = join(dir, name), s = lstatSync(file); if (s.isSymbolicLink() || s.uid !== process.getuid?.() || !s.isFile() && !s.isDirectory() || s.isFile() && s.nlink !== 1 || name.endsWith(".promisor")) refuse(); if (s.isDirectory()) {directory(file);walk(file);} } }; walk(this.cache);
308
+ if (!placementCacheTreePrivate(this.cache)) refuse();
149
309
  if (existsSync(join(this.cache, "commondir")) || existsSync(join(this.cache, "objects", "info", "http-alternates")) || existsSync(join(this.cache, "objects", "info", "alternates")) || existsSync(join(this.cache, "shallow")) || existsSync(join(this.cache, "info", "grafts"))) refuse();
150
310
  if (await this.required(["rev-parse", "--is-bare-repository"]) !== "true" || await this.required(["rev-parse", "--show-object-format"]) !== "sha1" || (await this.git(["config", "--get", "core.worktree"])).code !== 1) refuse();
151
311
  if((await this.git(["config","--get","extensions.partialClone"])).code !== 1
@@ -171,7 +331,8 @@ class PlacementTransport {
171
331
  git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
172
332
  }
173
333
  if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
174
- if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
334
+ const local = this.targets.find(target => target.realm.scope === "project" && isLocalKey(target.realm.key));
335
+ if (local?.realm.scope === "project" && this.opts.remote === undefined) throw new LocalKeyOptInRefusal(localKeyOptInMessage(local.realm.key));
175
336
  if (existsSync(this.root)) placementCacheRootStamp(this.home);
176
337
  const existing = existsSync(this.root) ? await this.independent() : false;
177
338
  if (!existing && !this.opts.remote) refuse("remote");
@@ -232,9 +393,11 @@ class PlacementTransport {
232
393
  target.manifests = new Map(target.remoteHistory.manifests); target.eligible = new Set([...target.manifests.values()].filter(item => item.eligible).map(item => item.row.id));
233
394
  }
234
395
  }
235
- preflight(mergeLocal = true): void {
396
+ async preflight(mergeLocal = true): Promise<void> {
397
+ // #462: the collector yields inside the wire round trip, then re-proves the source metadata it exported.
398
+ const pause = cooperativeYield();
236
399
  for (const target of this.targets) {
237
- const source = shardSourceRows(target.store, target.realm); target.sources = source.sources; target.pending = source.pending;
400
+ const source = await shardSourceRowsAsync(target.store, target.realm, pause); target.sources = source.sources; target.pending = source.pending;
238
401
  target.localPrunes = new Map([...source.rows.filter((row): row is PruneRow => row.op === "prune"), ...source.pending.map(item => item.row)].map(row => [row.id,row]));
239
402
  if (mergeLocal) for (const row of source.rows) { const old = target.rows.get(row.id); if (old && hashJSON(old) !== hashJSON(row)) refuse(); target.rows.set(row.id, row); }
240
403
  }
@@ -306,9 +469,10 @@ class PlacementTransport {
306
469
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
307
470
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
308
471
  journal:frozen?.root.journal??{sequence:frontier.sequence,headHash:frontier.headHash},createdUnixSeconds,policySnapshotUnixMs:frozen?.root.policySnapshotUnixMs??this.lastPolicyCheckUnixMs??Date.now(),targets,reservedRecords:0,reservedRecordBytes:[] as number[]};
309
- let bundle=planPlacementPublication(body,{sources:capture.prefixes,decisions,objects});
472
+ const planPause=cooperativeYield();
473
+ let bundle=await planPlacementPublicationAsync(body,{sources:capture.prefixes,decisions,objects},planPause);
310
474
  await yieldTurn(); // #462: planning is pure; each step gets its own turn
311
- let scheduled=this.events(bundle,projection,old);
475
+ let scheduled=await this.eventsAsync(bundle,projection,old,planPause);
312
476
  await yieldTurn();
313
477
  if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
314
478
  throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
@@ -316,41 +480,18 @@ class PlacementTransport {
316
480
  const lengths:number[]=[],pause=cooperativeYield();
317
481
  for(const [index,event]of scheduled.events.entries()){await pause();const record=createPlacementRecord(this.epochHash,body.journal.sequence+index+1,head,event);head=record.seal;lengths.push(publicationBytes(record).length);}
318
482
  await yieldTurn();
319
- bundle=planPlacementPublication({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects});
483
+ bundle=await planPlacementPublicationAsync({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects},planPause);
320
484
  await yieldTurn();
321
- scheduled=this.events(bundle,projection,old);
485
+ scheduled=await this.eventsAsync(bundle,projection,old,planPause);
322
486
  if(frozen&&canonicalJSON(bundle)!==canonicalJSON(frozen))refuse();
323
487
  return{bundle,decisions,projection,old,...scheduled,exported:scheduled.events.filter(event=>event.kind==="publication-ambiguous").length,withheld:decisions.filter(decision=>!decision.eligible).length};
324
488
  }
325
489
  events(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[]):{events:PlacementEvent[];preCount:number;holdCount:number}{
326
- const decisions=bundle.chunks.filter(chunk=>chunk.kind==="decisions").flatMap(chunk=>chunk.items as PlacementPublicationDecision[]).sort((a,b)=>placementKeyId(a.key).localeCompare(placementKeyId(b.key)));
327
- const holds:PlacementEvent[]=[],known:PlacementEvent[]=[],ambiguous:PlacementEvent[]=[],committed:PlacementEvent[]=[];
328
- const root=bundle.root;
329
- const make=(decision:PlacementPublicationDecision,kind:PlacementEvent["kind"],commit?:string):PlacementEvent=>{
330
- const base={requestId:hashJSON({attempt:root.seal,key:decision.key,kind,commit:commit??null}),key:decision.key,sourcePlacement:decision.sourcePlacement,
331
- effectHash:hashJSON({attempt:root.seal,context:root.contextHash,key:decision.key,kind,commit:commit??null})};
332
- if(kind==="hold"){
333
- const reason=decision.reason;
334
- const hold:PlacementHoldReason=reason==="secret"||reason==="personal-data"||reason==="deny-path"||reason==="private-or-invalid"||reason==="host"||reason==="person-local"?reason:"related-local";
335
- return{...base,kind,reason:hold};
336
- }
337
- const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm));if(index<0)refuse();
338
- const outcome={attemptHash:root.seal,remoteHash:root.remoteHash,refHash:root.targets[index]!.refHash};
339
- if(kind==="publication-ambiguous")return{...base,kind,outcome};
340
- if(kind!=="publication-committed"||!commit)refuse();
341
- return{...base,kind,outcome:{...outcome,commit,proofHash:hashJSON({attempt:root.seal,key:decision.key,commit,remote:root.remoteHash,ref:root.targets[index]!.refHash})}};
342
- };
343
- for(const decision of decisions){
344
- const state=projection.get(decision.key);
345
- const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm)),target=root.targets[index];if(!target)refuse();
346
- const original=old[index]?.rows.get(decision.key.id),published=original&&hashJSON(original)===decision.key.rowHash;
347
- if(decision.hold)holds.push(make(decision,"hold"));
348
- if(published&&state?.exposure!=="published"&&target.expectedRemoteHead)known.push(make(decision,"publication-committed",target.expectedRemoteHead));
349
- if(decision.eligible&&target.publish&&!published){
350
- ambiguous.push(make(decision,"publication-ambiguous"));committed.push(make(decision,"publication-committed",target.commit!));
351
- }
352
- }
353
- return{events:[...holds,...known,...ambiguous,...committed],preCount:holds.length+known.length+ambiguous.length,holdCount:holds.length};
490
+ return drainSteps(placementPublicationEventSteps(bundle,projection,old));
491
+ }
492
+ /** #470: the same schedule, awaiting the caller's event loop between decisions; the event order is identical. */
493
+ eventsAsync(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[],pause?:CooperativeYield):Promise<{events:PlacementEvent[];preCount:number;holdCount:number}>{
494
+ return drainStepsAsync(placementPublicationEventSteps(bundle,projection,old),pause);
354
495
  }
355
496
  async frozenOld(bundle:PlacementPublicationBundle):(Promise<(ShardHistory|undefined)[]>){
356
497
  const values:(ShardHistory|undefined)[]=[];
@@ -495,7 +636,7 @@ class PlacementTransport {
495
636
  target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
496
637
  } else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
497
638
  }
498
- this.preflight(false);this.enter("import");
639
+ await this.preflight(false);this.enter("import");
499
640
  const applications=await this.applicationCoordinator();await applications.prepare();
500
641
  for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
501
642
  await applications.install();
@@ -536,7 +677,7 @@ class PlacementTransport {
536
677
  const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
537
678
  return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
538
679
  ...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
539
- placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
680
+ placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
540
681
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
541
682
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
542
683
  }
@@ -551,8 +692,16 @@ class PlacementTransport {
551
692
  }
552
693
  /** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
553
694
  assertPlanCapacity(bundle:PlacementPublicationBundle):void{
554
- const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>new Set([...io.names(),...publicationFileNames(bundle.root),...io.reservedJournalNames(bundle.root)]).size+1);
555
- if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects});
695
+ // The refusal's own report (#288 step 1): the same inputs the count uses, split by what holds each object.
696
+ let composition:PlacementJournalObjectComposition|undefined;
697
+ const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>{
698
+ const planned=publicationFileNames(bundle.root),reserved=io.reservedJournalNames(bundle.root),names=io.names();
699
+ composition=placementJournalObjectComposition({names:[...names,...planned,...reserved],plan:{root:bundle.root,reserved}});
700
+ return new Set([...names,...planned,...reserved]).size+1;
701
+ });
702
+ if(composition)this.journalObjects=composition;
703
+ if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects},
704
+ composition&&placementJournalObjectCompositionText(composition));
556
705
  }
557
706
  async execute():Promise<SyncResult>{
558
707
  try{
@@ -572,7 +721,7 @@ class PlacementTransport {
572
721
  }
573
722
  }
574
723
  this.enter("source-capture");
575
- try { await yieldTurn();this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
724
+ try { await yieldTurn();await this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
576
725
  catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
577
726
  if(retained){
578
727
  const root=retained.bundle.root;
@@ -610,15 +759,20 @@ class PlacementTransport {
610
759
  this.factual=true;return await this.finish(material);
611
760
  }catch(error){
612
761
  try { this.testOnlyError?.(error); } catch { /* Test observers never alter production results. */ }
762
+ // #288 step 3: a started checkpoint pauses every placement effect with its own cause and next step.
763
+ if(this.epochHash&&placementCheckpointPending(this.home,this.epochHash)){this.failureCause="checkpoint-pending";return this.result(false,this.attemptHash?"unknown":"not-needed",PLACEMENT_CHECKPOINT_PENDING_MESSAGE);}
613
764
  if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){
614
765
  const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
615
766
  if(code==="staging"||code==="pending"){this.failureCause="writer-renewal";return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);}
616
767
  }
617
768
  // #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
618
769
  const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
619
- if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
770
+ // #288 step 1: the bound's own numbers-only clause is rebuilt from the receipt for the receipt's fields, so the
771
+ // thrown error's detail is carried over explicitly; the result's error is what the person reads.
772
+ if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
620
773
  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.");
621
774
  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); }
775
+ if (error instanceof LocalKeyOptInRefusal) { this.failureCause = "unavailable"; return this.result(false, "not-needed", error.message); }
622
776
  // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
623
777
  this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
624
778
  return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));