@staix/agent-mem 0.28.2 → 0.30.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 (73) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +17 -11
  3. package/package.json +3 -2
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +97 -17
  6. package/src/commands-table.ts +6 -0
  7. package/src/mcp-memory.ts +37 -9
  8. package/src/memory/bridge.ts +26 -1
  9. package/src/memory/capacity.ts +5 -2
  10. package/src/memory/catalog.ts +10 -1
  11. package/src/memory/commands.ts +5 -3
  12. package/src/memory/curated-cache-state.ts +10 -7
  13. package/src/memory/doctor.ts +32 -26
  14. package/src/memory/formats.ts +4 -3
  15. package/src/memory/generation-index.ts +79 -17
  16. package/src/memory/index-file.ts +2 -2
  17. package/src/memory/intent-brief.ts +34 -6
  18. package/src/memory/metrics.ts +174 -14
  19. package/src/memory/shard-bridge.ts +18 -6
  20. package/src/memory/shard-sync-format.ts +18 -0
  21. package/src/memory/shard-sync-history.ts +6 -0
  22. package/src/memory/shard-sync.ts +52 -4
  23. package/src/memory/shard.ts +33 -13
  24. package/src/memory/store.ts +147 -41
  25. package/src/memory/sync-placement-bound.ts +21 -4
  26. package/src/memory/sync-placement-cache.ts +16 -1
  27. package/src/memory/sync-placement-capture.ts +67 -19
  28. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  29. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  30. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  31. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  32. package/src/memory/sync-placement-checkpoint.ts +234 -0
  33. package/src/memory/sync-placement-dependencies.ts +42 -9
  34. package/src/memory/sync-placement-effective-writers.ts +12 -6
  35. package/src/memory/sync-placement-git.ts +17 -7
  36. package/src/memory/sync-placement-guard.ts +52 -1
  37. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  38. package/src/memory/sync-placement-inventory.ts +141 -0
  39. package/src/memory/sync-placement-journal-format.ts +4 -1
  40. package/src/memory/sync-placement-journal-storage.ts +148 -28
  41. package/src/memory/sync-placement-journal.ts +13 -4
  42. package/src/memory/sync-placement-materialize.ts +47 -22
  43. package/src/memory/sync-placement-projection.ts +7 -1
  44. package/src/memory/sync-placement-publication-events.ts +42 -0
  45. package/src/memory/sync-placement-publication-plan.ts +26 -5
  46. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  47. package/src/memory/sync-placement-realm-admission.ts +352 -0
  48. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  49. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  50. package/src/memory/sync-placement-realm-effective.ts +71 -0
  51. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  52. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  53. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  54. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  55. package/src/memory/sync-placement-realm-pending.ts +27 -0
  56. package/src/memory/sync-placement-realm-proof.ts +131 -0
  57. package/src/memory/sync-placement-realm-torn.ts +26 -0
  58. package/src/memory/sync-placement-remote-admission.ts +190 -0
  59. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  60. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  61. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  62. package/src/memory/sync-placement-remote-stage.ts +275 -0
  63. package/src/memory/sync-placement-transport.ts +268 -79
  64. package/src/memory/sync-placement-writer-history.ts +75 -17
  65. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  66. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  67. package/src/memory/sync-placement-yield.ts +44 -0
  68. package/src/memory/sync-progress.ts +47 -6
  69. package/src/memory/sync.ts +26 -1
  70. package/src/memory/work-lists.ts +129 -9
  71. package/src/session-brief.ts +34 -1
  72. package/src/sync-placement-writer-context.ts +5 -5
  73. package/src/ui/plugin.ts +1 -1
@@ -0,0 +1,190 @@
1
+ /** Explicit remote realm adoption, staged before the existing same-epoch admission. */
2
+ import { createHash } from "node:crypto";
3
+ import { lstatSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { realPath } from "./platform.ts";
7
+ import { assertMutationHandle } from "./mutation.ts";
8
+ import { shardDir } from "./shard.ts";
9
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
10
+ import { PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError } from "./sync-placement-format.ts";
11
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
12
+ import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
13
+ import { readRealmIntent } from "./sync-placement-realm-intent-storage.ts";
14
+ import { readPlacementWriterJournalAnchors, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
15
+ import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
16
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
17
+ import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
18
+ import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
19
+ import { PlacementInventoryFenceError, withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
20
+ import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
21
+ import { previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
22
+ import { activePlacementWriterContext } from "../sync-placement-writer-context.ts";
23
+ import { applyRealmAdmission, planRealmAbandon, previewRealmAdmission, RealmAdmissionError } from "./sync-placement-realm-admission.ts";
24
+ import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
25
+ import { assertRemoteAdoptionCurrent, prepareRemotePlacementRealm, recoverRemoteStagedPacks } from "./sync-placement-transport.ts";
26
+ import { assertRemoteAdoptionStageOwnership, clearRemoteAdoption, clearRemoteAdoptionPending, discardRemoteInstalledLog, inspectRemoteAdoptionPending, installRemoteAdoptionLog,
27
+ pendingRemoteAdoptions, readRemoteAdoption, remoteAdoptionLogMayBeInstalled, stageRemoteAdoption, writeRemoteAdoption } from "./sync-placement-remote-stage.ts";
28
+ import type { RemoteAdoption } from "./sync-placement-remote-adoption-format.ts";
29
+ import type { SyncOptions } from "./sync.ts";
30
+ import { RemoteRealmRefusal, type RemoteRealmCause } from "./sync-placement-remote-refusal.ts";
31
+
32
+ export type RemoteAdmissionMode = "dry-run" | "apply" | "resume" | "abandon";
33
+ export interface RemoteAdmissionOptions extends Pick<SyncOptions, "signal" | "visibility"> {
34
+ mode: RemoteAdmissionMode; confirm?: boolean;
35
+ /** Internal crash seam; never supplied by the CLI. */
36
+ checkpoint?(stage: "after-preview" | "after-companion" | "after-stage" | "after-install" | "after-intent" | "after-metadata" | "after-proof" | "after-append" | "after-admission"): void | Promise<void>;
37
+ }
38
+ export interface RemoteAdmissionResult {
39
+ state: "preview" | "admitted" | "already-admitted" | "retained" | "abandoned";
40
+ realm: string; remoteHead?: string; omitted?: number; staged?: number; nextStep?: string;
41
+ }
42
+ const unavailable = (cause: RemoteRealmCause = "other"): never => { throw new RemoteRealmRefusal(cause); };
43
+ const keyOf = (project: string) => createHash("sha256").update(project).digest("hex");
44
+ function active(home: string, keyHash: string): boolean {
45
+ const markers = readPlacementRuntimeMarkers(home);
46
+ if (!markers.profile || typeof markers.profile !== "object" || Object.getOwnPropertyDescriptor(markers.profile, "schema")?.value !== PLACEMENT_PROFILE_SCHEMA) return unavailable("epoch");
47
+ const binding = readActivePlacementBinding(home, markers.profile, markers.shards);
48
+ if (!binding) return unavailable("epoch");
49
+ const inventory = readEffectiveRealmInventory(home, binding), present = inventory.realms.some(realm => realm.scope === "project" && realm.keyHash === keyHash);
50
+ inventory.assertCurrent(); return present;
51
+ }
52
+ function assertCheckpointClear(home: string): void {
53
+ const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
54
+ if (!binding) return;
55
+ try { if (resolvePlacementWindow(home, binding.profile.placementHead).pending) throw new SyncPlacementJournalError("checkpoint-pending"); }
56
+ catch (error) { if (error instanceof SyncPlacementJournalError && error.code === "pending") throw new SyncPlacementJournalError("checkpoint-pending"); throw error; }
57
+ }
58
+ function dirs(home: string, project: string): string[] {
59
+ const dir = shardDir(home, project); return lstatSync(dir, { throwIfNoEntry: false }) ? [dir] : [];
60
+ }
61
+ const nextSync = "amem sync";
62
+
63
+ /** Returns identifiers/counts only. A callback is used only for the existing remote visibility check. */
64
+ async function remoteRealmAdmissionInner(homeInput: string, project: string, options: RemoteAdmissionOptions): Promise<RemoteAdmissionResult> {
65
+ const home = realPath(homeInput), realm = keyOf(project), transport = { ...(options.signal ? { signal: options.signal } : {}), ...(options.visibility ? { visibility: options.visibility } : {}) };
66
+ if (options.mode !== "dry-run") assertCheckpointClear(home);
67
+ const pending = pendingRemoteAdoptions(home);
68
+ if (pending.unknown) return unavailable("staging");
69
+ if (options.mode !== "abandon" && pending.hashes.some(hash => hash !== realm)) return unavailable("pending");
70
+ let plan = readRemoteAdoption(home, realm), staged = inspectRemoteAdoptionPending(home, realm);
71
+ if (plan) assertRemoteAdoptionStageOwnership(home, plan);
72
+ // A private stage without any companion cannot be attributed to this operation or silently abandoned.
73
+ if (!plan && !staged.length && pending.hashes.includes(realm)) return unavailable("staging");
74
+ const admitted = () => active(home, realm);
75
+ if (options.mode === "dry-run") {
76
+ if (plan || staged.length) return { state: "retained", realm, staged: staged.length, nextStep: "resume or review abandon" };
77
+ if (admitted()) return { state: "already-admitted", realm, nextStep: nextSync };
78
+ if (previewRealmAdmission(home, project).state !== "not-local") return unavailable();
79
+ const prepared = await prepareRemotePlacementRealm(home, project, transport);
80
+ return { state: "preview", realm, remoteHead: prepared.plan.remoteHead, omitted: prepared.plan.omitted };
81
+ }
82
+ if (options.mode === "abandon" && staged.length) {
83
+ if (!options.confirm) return { state: "retained", realm, staged: staged.length, nextStep: "confirm abandon" };
84
+ await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
85
+ const proof = { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } };
86
+ clearRemoteAdoptionPending(home, realm, staged, proof);
87
+ });
88
+ return { state: "abandoned", realm, staged: staged.length, nextStep: plan ? "resume or review abandon" : "preview admission" };
89
+ }
90
+ if (options.mode === "abandon" && !plan) return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
91
+ if (options.mode === "abandon" && plan && !options.confirm) return { state: "retained", realm, nextStep: "confirm abandon" };
92
+ if (options.mode === "apply" && (plan || staged.length) && !admitted()) return unavailable("pending");
93
+ if (!plan && admitted()) {
94
+ if (staged.length) await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
95
+ clearRemoteAdoptionPending(home, realm, staged, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
96
+ });
97
+ return { state: "already-admitted", realm, nextStep: nextSync };
98
+ }
99
+ if (options.mode === "resume" && !plan && !staged.length) return admitted() ? { state: "already-admitted", realm, nextStep: nextSync } : unavailable();
100
+
101
+ let packs = plan ? await recoverRemoteStagedPacks(home, project, plan) : undefined;
102
+ // A torn first companion can be completed only if the exact plan is reconstructed; a changed head refuses.
103
+ if (!plan) {
104
+ const prepared = await prepareRemotePlacementRealm(home, project, transport); plan = prepared.plan; packs = prepared.packs; await options.checkpoint?.("after-preview");
105
+ }
106
+ const frozen: RemoteAdoption = plan, files = packs!;
107
+ const clearOwn = async () => {
108
+ await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
109
+ const current = readRemoteAdoption(home, realm); if (!current) return;
110
+ if (current.seal !== frozen.seal) return unavailable("staging");
111
+ clearRemoteAdoption(home, frozen, files, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
112
+ });
113
+ };
114
+ if (options.mode === "abandon") {
115
+ const oldIntent = readRealmIntent(home, realm);
116
+ if (oldIntent) {
117
+ if (admitted()) await applyRealmAdmission(home, project, { mode: "resume" });
118
+ else {
119
+ if (planRealmAbandon(home, project).state !== "abandonable") return unavailable("staging");
120
+ await applyRealmAdmission(home, project, { mode: "abandon", confirm: true });
121
+ }
122
+ }
123
+ await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
124
+ const current = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); };
125
+ const proof = { mutation, assertCurrent: current };
126
+ if (!admitted() && remoteAdoptionLogMayBeInstalled(home, project, frozen))
127
+ discardRemoteInstalledLog(home, project, frozen, { mutation, assertCurrent: () => { current(); if (admitted()) unavailable(); } });
128
+ clearRemoteAdoption(home, frozen, files, proof);
129
+ });
130
+ return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
131
+ }
132
+ if (admitted()) {
133
+ if (readRealmIntent(home, realm)) await applyRealmAdmission(home, project, { mode: "resume" });
134
+ await clearOwn();
135
+ return { state: "already-admitted", realm, nextStep: nextSync };
136
+ }
137
+ await withPlacementActivationFences(home, dirs(home, project), async (mutation, owner) => {
138
+ if (admitted()) return;
139
+ const remotePending = pendingRemoteAdoptions(home); if (remotePending.unknown) return unavailable("staging"); if (remotePending.hashes.some(hash => hash !== realm)) return unavailable("pending");
140
+ const pending = pendingRealmInventory(home); if (pending.unknown) return unavailable("staging"); if (pending.hashes.some(hash => hash !== realm)) return unavailable("pending");
141
+ const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
142
+ if (!binding) return unavailable("epoch");
143
+ const inventory = readEffectiveRealmInventory(home, binding), expectedWriters = readEffectiveSyncPlacementWriters(home);
144
+ const journalToken = placementWriterJournalToken(home, frozen.epochHash), journal = readPlacementWriterJournalAnchors(home, frozen.epochHash);
145
+ const journalHead = journal.sequence ? journal.records[journal.sequence - 1]!.seal : frozen.epochHash;
146
+ if (inventory.extensionHead !== frozen.inventoryHead || expectedWriters.revisionHash !== frozen.writerHash
147
+ || journal.sequence !== frozen.journalSequence || journalHead !== frozen.journalHead) return unavailable("drift");
148
+ const writer = activePlacementWriterContext(home, fileURLToPath(new URL("../..", import.meta.url)));
149
+ const current = () => { try { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); writer.attest(); expectedWriters.assertCurrent(); inventory.assertCurrent();
150
+ if (placementWriterJournalToken(home, frozen.epochHash) !== journalToken) unavailable("drift"); assertPlacementActivationOwner(owner, home); } catch (error) { if (error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error; return unavailable("drift"); } };
151
+ current(); const source = previewOwnedSyncPlacementSources(home, owner), installed = remoteAdoptionLogMayBeInstalled(home, project, frozen);
152
+ if (source.base.homeHash !== frozen.homeHash || source.base.policyHash !== frozen.policyHash || source.base.aliasesHash !== frozen.aliasesHash
153
+ || !installed && source.base.sourceHash !== frozen.sourceHash) return unavailable("drift");
154
+ try { source.assertSourcesUnchanged(); } catch { return unavailable("drift"); }
155
+ await assertRemoteAdoptionCurrent(home, project, frozen, transport);
156
+ try { source.assertSourcesUnchanged(); } catch { return unavailable("drift"); }
157
+ current();
158
+ const proof = { mutation, assertCurrent: current };
159
+ assertRemoteAdoptionStageOwnership(home, frozen);
160
+ writeRemoteAdoption(home, frozen, proof); await options.checkpoint?.("after-companion");
161
+ if (!installed) { stageRemoteAdoption(home, frozen, files, proof); await options.checkpoint?.("after-stage"); }
162
+ const retained = readRealmIntent(home, realm);
163
+ const completeMetadata = source.base.realms.some(item => item.scope === "project" && item.keyHash === realm);
164
+ installRemoteAdoptionLog(home, project, frozen, proof, !!retained || completeMetadata); await options.checkpoint?.("after-install");
165
+ });
166
+ if (admitted()) {
167
+ await clearOwn();
168
+ return { state: "already-admitted", realm, nextStep: nextSync };
169
+ }
170
+ const existing = readRealmIntent(home, realm);
171
+ const result = await applyRealmAdmission(home, project, { mode: existing ? "resume" : "apply",
172
+ expectedRemoteAnchors: { writerHash: frozen.writerHash, inventoryHead: frozen.inventoryHead, journalSequence: frozen.journalSequence, journalHead: frozen.journalHead },
173
+ ...(options.checkpoint ? { checkpoint: options.checkpoint } : {}) });
174
+ await options.checkpoint?.("after-admission");
175
+ await clearOwn();
176
+ return { state: result.state === "already-admitted" ? "already-admitted" : "admitted", realm, omitted: frozen.omitted, nextStep: nextSync };
177
+ }
178
+
179
+ export async function remoteRealmAdmission(homeInput: string, project: string, options: RemoteAdmissionOptions): Promise<RemoteAdmissionResult> {
180
+ try { return await remoteRealmAdmissionInner(homeInput, project, options); }
181
+ catch (error) {
182
+ if (error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error;
183
+ if (error instanceof RemoteRealmRefusal) throw error;
184
+ if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") return unavailable("epoch");
185
+ if (error instanceof PlacementInventoryFenceError || error instanceof Error && error.message === "profile lock held by a live or unknown owner") return unavailable("lock");
186
+ if (error instanceof RealmAdmissionError) return unavailable(error.causeClass === "busy" || error.causeClass === "readers" ? "lock" : error.causeClass === "pending" ? "pending" : error.causeClass === "changed" ? "drift" : "staging");
187
+ if (error instanceof SharedWriterRevisionError) return unavailable("drift");
188
+ return unavailable();
189
+ }
190
+ }
@@ -0,0 +1,54 @@
1
+ /** Private local recovery evidence for an explicitly reviewed remote realm adoption. */
2
+ import { types } from "node:util";
3
+ import { canonicalJSON, hashJSON } from "./generation.ts";
4
+ import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
5
+ import { PLACEMENT_JOURNAL_MAX_RECORDS } from "./sync-placement-journal-format.ts";
6
+
7
+ const SCHEMA = "agent-mem.sync-placement-remote-adoption/v1", MAX_BYTES = 4 * 1024 * 1024;
8
+ export interface RemoteAdoptionBody {
9
+ schema: typeof SCHEMA;
10
+ homeHash: string; epochHash: string; generation: string; keyHash: string;
11
+ remoteHash: string; remoteHead: string; sourceHash: string; policyHash: string; aliasesHash: string;
12
+ writerHash: string; inventoryHead: string; journalSequence: number; journalHead: string;
13
+ omitted: number; packs: { name: string; bytes: number }[];
14
+ }
15
+ export interface RemoteAdoption extends RemoteAdoptionBody { seal: string }
16
+ const unavailable = (): never => { throw new Error("Remote placement adoption evidence is invalid or exceeds its bound; retain it for inspection."); };
17
+ function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
18
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value) || Object.getOwnPropertySymbols(value).length
19
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return unavailable();
20
+ const entries = Object.getOwnPropertyDescriptors(value);
21
+ if (Object.keys(entries).length !== keys.length || Object.getOwnPropertyNames(value).length !== keys.length) return unavailable();
22
+ const result: Record<string, unknown> = Object.create(null);
23
+ for (const key of keys) { const entry = entries[key]; if (!entry || !("value" in entry) || !entry.enumerable) return unavailable(); result[key] = entry.value; }
24
+ return result;
25
+ }
26
+ function hex(value: unknown, length: number): string {
27
+ if (typeof value !== "string" || value.length !== length || !/^[a-f0-9]+$/.test(value)) return unavailable(); return value;
28
+ }
29
+ function integer(value: unknown, maximum: number): number {
30
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > maximum) return unavailable(); return value;
31
+ }
32
+ function checked(value: unknown, sealed: boolean): RemoteAdoption {
33
+ const row = object(value, ["schema", "homeHash", "epochHash", "generation", "keyHash", "remoteHash", "remoteHead", "sourceHash", "policyHash", "aliasesHash", "writerHash", "inventoryHead", "journalSequence", "journalHead", "omitted", "packs", ...(sealed ? ["seal"] : [])]);
34
+ if (row.schema !== SCHEMA || !Array.isArray(row.packs) || row.packs.length > PLACEMENT_SOURCE_MAX_ROWS) return unavailable();
35
+ let previous = "", total = 0;
36
+ const packs = row.packs.map(item => {
37
+ const pack = object(item, ["name", "bytes"]);
38
+ if (typeof pack.name !== "string" || !/^sync-[a-f0-9]{64}\.jsonl$/.test(pack.name) || pack.name <= previous) return unavailable();
39
+ previous = pack.name; const bytes = integer(pack.bytes, PLACEMENT_SOURCE_MAX_BYTES); total += bytes;
40
+ if (!bytes || total > PLACEMENT_SOURCE_MAX_BYTES) return unavailable(); return { name: pack.name, bytes };
41
+ });
42
+ const body: RemoteAdoptionBody = { schema: SCHEMA, homeHash: hex(row.homeHash, 64), epochHash: hex(row.epochHash, 64), generation: hex(row.generation, 32),
43
+ keyHash: hex(row.keyHash, 64), remoteHash: hex(row.remoteHash, 64), remoteHead: hex(row.remoteHead, 40), sourceHash: hex(row.sourceHash, 64), policyHash: hex(row.policyHash, 64), aliasesHash: hex(row.aliasesHash, 64),
44
+ writerHash: hex(row.writerHash, 64), inventoryHead: hex(row.inventoryHead, 64), journalSequence: integer(row.journalSequence, PLACEMENT_JOURNAL_MAX_RECORDS), journalHead: hex(row.journalHead, 64),
45
+ omitted: integer(row.omitted, PLACEMENT_SOURCE_MAX_ROWS), packs };
46
+ const result = { ...body, seal: hashJSON(body) };
47
+ if (body.journalSequence === 0 && body.journalHead !== body.epochHash) return unavailable();
48
+ if (sealed && hex(row.seal, 64) !== result.seal || Buffer.byteLength(canonicalJSON(result) + "\n") > MAX_BYTES) return unavailable();
49
+ return result;
50
+ }
51
+ export function createRemoteAdoption(body: RemoteAdoptionBody): RemoteAdoption { return checked(body, false); }
52
+ export function validateRemoteAdoption(value: unknown): RemoteAdoption { return checked(value, true); }
53
+ export const REMOTE_ADOPTION_SCHEMA = SCHEMA;
54
+ export const REMOTE_ADOPTION_MAX_BYTES = MAX_BYTES;
@@ -0,0 +1,49 @@
1
+ /** Select only a safe pre-admission subset from an already audited remote history. */
2
+ import { canonicalJSON, hashJSON } from "./generation.ts";
3
+ import { createHash } from "node:crypto";
4
+ import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
5
+ import type { Entry } from "./store.ts";
6
+ import type { ShardHistory } from "./shard-sync-history.ts";
7
+ import { encodeShardPacks } from "./shard-sync-format.ts";
8
+
9
+ export interface RemoteMaterializationSelection { rows: Entry[]; omitted: number }
10
+ export interface RemoteStagedPack { name: string; bytes: Buffer }
11
+ const unavailable = (): never => { throw new Error("Remote placement realm cannot be materialized from complete verified proof within the source bounds."); };
12
+
13
+ /** Never stage a prune row or its target before the existing sync path activates the witness. */
14
+ export function selectRemoteMaterialization(history: ShardHistory): RemoteMaterializationSelection {
15
+ if (history.rows.size > PLACEMENT_SOURCE_MAX_ROWS) return unavailable();
16
+ const masks = new Map<string, string>(), witnessed = new Set<string>();
17
+ for (const manifest of history.manifests.values()) {
18
+ if (!manifest.eligible || !history.rows.has(manifest.row.id)) return unavailable();
19
+ witnessed.add(manifest.row.id);
20
+ for (const target of manifest.row.targets) {
21
+ const prior = masks.get(target.id);
22
+ if (prior !== undefined && prior !== target.rowHash) return unavailable();
23
+ masks.set(target.id, target.rowHash);
24
+ }
25
+ }
26
+ const rows: Entry[] = []; let omitted = 0, bytes = 0;
27
+ for (const row of history.rows.values()) {
28
+ bytes += Buffer.byteLength(canonicalJSON(row) + "\n");
29
+ if (bytes > PLACEMENT_SOURCE_MAX_BYTES) return unavailable();
30
+ if (row.op === "prune") { if (!witnessed.has(row.id)) return unavailable(); omitted++; continue; }
31
+ const mask = masks.get(row.id);
32
+ if (mask !== undefined) { if (hashJSON(row) !== mask) return unavailable(); omitted++; continue; }
33
+ rows.push(row);
34
+ }
35
+ return { rows, omitted };
36
+ }
37
+
38
+ /** Use the same canonical immutable pack encoding as sync, but keep it detached until publication. */
39
+ export function remoteStagedPacks(selection: RemoteMaterializationSelection): RemoteStagedPack[] {
40
+ if (!Number.isSafeInteger(selection.omitted) || selection.omitted < 0 || selection.rows.length > PLACEMENT_SOURCE_MAX_ROWS) return unavailable();
41
+ const packs = new Map<string, Buffer>(); let total = 0;
42
+ for (const bytes of encodeShardPacks(selection.rows).values()) {
43
+ total += bytes.length; if (total > PLACEMENT_SOURCE_MAX_BYTES) return unavailable();
44
+ const name = `sync-${createHash("sha256").update(bytes).digest("hex")}.jsonl`, previous = packs.get(name);
45
+ if (previous && !previous.equals(bytes)) return unavailable();
46
+ packs.set(name, Buffer.from(bytes));
47
+ }
48
+ return [...packs].sort(([a], [b]) => a.localeCompare(b)).map(([name, bytes]) => ({ name, bytes }));
49
+ }
@@ -0,0 +1,21 @@
1
+ /** Closed, data-free diagnoses for explicit remote realm discovery and admission. */
2
+ export type RemoteRealmCause = "lock" | "pending" | "drift" | "remote" | "environment" | "cache" | "epoch" | "staging" | "bound" | "existing" | "other";
3
+ const messages: Record<RemoteRealmCause, string> = {
4
+ lock: "Another sync or admission holds a lock; wait for it to finish, then retry.",
5
+ pending: "Another realm has a retained admission; resume or abandon it with amem migrate --sync-placement --admit <project> --resume or --abandon before retrying.",
6
+ drift: "Local sources, policy, aliases, writers or journal changed; finish pending sync work, then run amem migrate --sync-placement --admit <project> --from-remote --dry-run again.",
7
+ remote: "The remote head moved, or the configured remote is unreachable or not private; check the remote, then run amem migrate --sync-placement --admit <project> --from-remote --dry-run again.",
8
+ environment: "Git tracing is enabled and can write outside the cache; disable GIT_TRACE variables in this command's environment, then retry.",
9
+ cache: "The local placement Git cache or its configuration is unsafe, missing or changed; stop sync and inspect the private placement cache before retrying.",
10
+ epoch: "No valid active placement is available; review and activate placement with amem migrate --sync-placement --dry-run first.",
11
+ staging: "Remote admission staging cannot be attributed or verified; retain it for inspection and see docs/purge.md.",
12
+ bound: "The remote realm exceeds a supported bound; retain the evidence and run amem migrate --sync-placement --admit <project> --from-remote --dry-run to inspect the bound.",
13
+ existing: "Existing curated state prevents remote admission; inspect the local realm with amem migrate --sync-placement --admit <project> --dry-run.",
14
+ other: "Remote realm discovery or admission is unavailable; inspect the placement state and retry its --dry-run.",
15
+ };
16
+ export class RemoteRealmRefusal extends Error {
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;
19
+ super(`Remote realm unavailable (${causeClass}): ${safeName ? `existing curated subpath: ${safeName}. ` : ""}${messages[causeClass]}`); this.name = "RemoteRealmRefusal";
20
+ }
21
+ }
@@ -0,0 +1,275 @@
1
+ /** Private, fenced staging for remote placement adoption; never rewrites an existing curated log. */
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { canonicalJSON, fsyncDirectory } from "./generation.ts";
6
+ import { assertMutationHandle } from "./mutation.ts";
7
+ import { realPath } from "./platform.ts";
8
+ import { assertCuratedShardLayout, ensureShardDescriptor, shardDir } from "./shard.ts";
9
+ import type { RealmIntentProof } from "./sync-placement-realm-intent-storage.ts";
10
+ import { REMOTE_ADOPTION_MAX_BYTES, validateRemoteAdoption, type RemoteAdoption } from "./sync-placement-remote-adoption-format.ts";
11
+ import type { RemoteStagedPack } from "./sync-placement-remote-materialization.ts";
12
+ import { RemoteRealmRefusal } from "./sync-placement-remote-refusal.ts";
13
+
14
+ const fail = (): never => { throw new RemoteRealmRefusal("staging"); };
15
+ const sha = (bytes: Uint8Array | string) => createHash("sha256").update(bytes).digest("hex");
16
+ const stamp = (s: BigIntStats) => [s.dev, s.ino, s.uid, s.mode, s.nlink, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":");
17
+ const companion = (home: string, plan: RemoteAdoption) => join(home, `placement-remote-adoption-${plan.keyHash}.json`);
18
+ const staging = (home: string, plan: RemoteAdoption) => join(home, `.placement-remote-adoption-${plan.keyHash}-${plan.seal}.stage`);
19
+ function ownedFile(s: BigIntStats): void {
20
+ if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1n || s.uid !== BigInt(process.getuid?.() ?? -1) || (s.mode & 0o777n) !== 0o600n) fail();
21
+ }
22
+ function ownedDir(dir: string): BigIntStats {
23
+ const s = lstatSync(dir, { bigint: true });
24
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== BigInt(process.getuid?.() ?? -1) || (s.mode & 0o077n) !== 0n) fail();
25
+ return s;
26
+ }
27
+ /** A not-local scaffold may hold work/capture, but no pre-existing curated state may be replaced. */
28
+ function rejectExistingCurated(dir: string): void {
29
+ const fixed = new Set(["log", "local", "legacy", "legacy-main", "generation.json", "generation-seal.json", "migration-sources.json", "machine.json",
30
+ "prune-translations.jsonl", "prune-plans", "public-prune-objects", "public-prune-inputs", "public-prune-input-sets"]);
31
+ for (const name of readdirSync(dir)) {
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))
34
+ throw new RemoteRealmRefusal("existing", name);
35
+ }
36
+ }
37
+ function check(home: string, proof: RealmIntentProof): void {
38
+ assertMutationHandle(proof.mutation, home); proof.assertCurrent(); assertMutationHandle(proof.mutation, home);
39
+ }
40
+ function readOwned(file: string, max: number): Buffer | undefined {
41
+ const before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!before) return undefined;
42
+ ownedFile(before); if (before.size > BigInt(max)) return fail();
43
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
44
+ try {
45
+ const opened = fstatSync(fd, { bigint: true }); ownedFile(opened); if (stamp(opened) !== stamp(before)) fail();
46
+ const bytes = Buffer.alloc(Number(opened.size)); let at = 0;
47
+ while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) fail(); at += n; }
48
+ if (stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(file, { bigint: true })) !== stamp(opened)) fail();
49
+ return bytes;
50
+ } finally { closeSync(fd); }
51
+ }
52
+ /** Complete only an existing exact prefix or a file created exclusively by this operation. */
53
+ function complete(home: string, file: string, expected: Buffer, proof: RealmIntentProof): void {
54
+ check(home, proof);
55
+ let fd: number;
56
+ try { fd = openSync(file, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
57
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; fd = openSync(file, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
58
+ try {
59
+ const before = fstatSync(fd, { bigint: true }); ownedFile(before); if (before.size > BigInt(expected.length)) fail();
60
+ const saved = Buffer.alloc(Number(before.size)); let at = 0;
61
+ while (at < saved.length) { const n = readSync(fd, saved, at, saved.length - at, at); if (!n) fail(); at += n; }
62
+ if (!saved.equals(expected.subarray(0, saved.length)) || stamp(lstatSync(file, { bigint: true })) !== stamp(before)) fail();
63
+ check(home, proof);
64
+ for (let pos = saved.length; pos < expected.length;) { const n = writeSync(fd, expected, pos, expected.length - pos, pos); if (n <= 0) fail(); pos += n; }
65
+ fsyncSync(fd); const after = fstatSync(fd, { bigint: true }); ownedFile(after);
66
+ if (after.size !== BigInt(expected.length) || stamp(lstatSync(file, { bigint: true })) !== stamp(after)) fail();
67
+ } finally { closeSync(fd); }
68
+ check(home, proof);
69
+ if (!readOwned(file, expected.length)?.equals(expected)) fail();
70
+ }
71
+ function ensureDir(home: string, dir: string, parent: string, proof: RealmIntentProof): void {
72
+ check(home, proof); if (!lstatSync(dir, { throwIfNoEntry: false })) { mkdirSync(dir, { mode: 0o700 }); fsyncDirectory(parent); }
73
+ ownedDir(dir); check(home, proof);
74
+ }
75
+ export interface RemoteAdoptionPending { name: string; size: number; hash: string; stamp: string }
76
+ /** Metadata-only inventory; one remote adoption may remain outstanding per home. */
77
+ export function pendingRemoteAdoptions(homeInput: string): { hashes: readonly string[]; unknown: boolean } {
78
+ const home = realPath(homeInput), hashes = new Set<string>(); let unknown = false, count = 0;
79
+ try {
80
+ const dir = opendirSync(home);
81
+ try {
82
+ for (;;) {
83
+ const entry = dir.readSync(); if (!entry) break; if (++count > 20_000) return { hashes: [], unknown: true };
84
+ const hidden = entry.name.startsWith(".placement-remote-adoption-"), visible = entry.name.startsWith("placement-remote-adoption-");
85
+ if (!hidden && !visible) continue;
86
+ const match = hidden ? /^\.placement-remote-adoption-([a-f0-9]{64})-[a-f0-9]{64}\.stage$/.exec(entry.name)
87
+ : /^placement-remote-adoption-([a-f0-9]{64})\.json(?:\.[a-f0-9]{64}\.pending)?$/.exec(entry.name);
88
+ if (!match) { unknown = true; continue; }
89
+ hashes.add(match[1]!); if (hashes.size > 64) return { hashes: [], unknown: true };
90
+ try { if (hidden) ownedDir(join(home, entry.name)); else ownedFile(lstatSync(join(home, entry.name), { bigint: true })); }
91
+ catch { unknown = true; }
92
+ }
93
+ } finally { dir.closeSync(); }
94
+ } catch { return { hashes: [], unknown: true }; }
95
+ return { hashes: [...hashes].sort(), unknown };
96
+ }
97
+ /** A companion never claims another stage directory even when it names the same project. */
98
+ export function assertRemoteAdoptionStageOwnership(homeInput: string, value: RemoteAdoption): void {
99
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value), prefix = `.placement-remote-adoption-${plan.keyHash}-`, expected = staging(home, plan);
100
+ const dir = opendirSync(home); let count = 0;
101
+ try {
102
+ for (;;) {
103
+ const entry = dir.readSync(); if (!entry) break; if (++count > 20_000) fail();
104
+ if (entry.name.startsWith(prefix) && join(home, entry.name) !== expected) fail();
105
+ }
106
+ } finally { dir.closeSync(); }
107
+ }
108
+ /** A torn companion is private staging, not authority to materialize a realm. */
109
+ export function inspectRemoteAdoptionPending(homeInput: string, keyHash: string): RemoteAdoptionPending[] {
110
+ const home = realPath(homeInput); if (!/^[a-f0-9]{64}$/.test(keyHash)) return fail();
111
+ const prefix = `placement-remote-adoption-${keyHash}.json.`, result: RemoteAdoptionPending[] = []; let count = 0;
112
+ const dir = opendirSync(home);
113
+ try {
114
+ for (;;) {
115
+ const entry = dir.readSync(); if (!entry) break; if (++count > 20_000) return fail();
116
+ if (!entry.name.startsWith(prefix)) continue;
117
+ if (!/^[a-f0-9]{64}\.pending$/.test(entry.name.slice(prefix.length)) || result.length >= 64) return fail();
118
+ const file = join(home, entry.name), before = lstatSync(file, { bigint: true }), bytes = readOwned(file, REMOTE_ADOPTION_MAX_BYTES);
119
+ if (!bytes || stamp(lstatSync(file, { bigint: true })) !== stamp(before)) return fail();
120
+ result.push({ name: entry.name, size: bytes.length, hash: sha(bytes), stamp: stamp(before) });
121
+ }
122
+ } finally { dir.closeSync(); }
123
+ return result.sort((a, b) => a.name.localeCompare(b.name));
124
+ }
125
+ /** Explicitly confirmed cleanup rechecks the exact staged files and never removes an installed companion. */
126
+ export function clearRemoteAdoptionPending(homeInput: string, keyHash: string, expected: readonly RemoteAdoptionPending[], proof: RealmIntentProof): void {
127
+ const home = realPath(homeInput); check(home, proof);
128
+ if (canonicalJSON(inspectRemoteAdoptionPending(home, keyHash)) !== canonicalJSON(expected)) fail();
129
+ for (const stage of expected) {
130
+ const file = join(home, stage.name); check(home, proof);
131
+ const stat = lstatSync(file, { bigint: true }), bytes = readOwned(file, REMOTE_ADOPTION_MAX_BYTES);
132
+ if (!bytes || stamp(stat) !== stage.stamp || bytes.length !== stage.size || sha(bytes) !== stage.hash) fail();
133
+ unlinkSync(file); fsyncDirectory(home);
134
+ }
135
+ check(home, proof); if (inspectRemoteAdoptionPending(home, keyHash).length) fail();
136
+ }
137
+ export function readRemoteAdoption(homeInput: string, keyHash: string): RemoteAdoption | undefined {
138
+ const home = realPath(homeInput);
139
+ if (!/^[a-f0-9]{64}$/.test(keyHash)) return fail();
140
+ const bytes = readOwned(join(home, `placement-remote-adoption-${keyHash}.json`), REMOTE_ADOPTION_MAX_BYTES); if (!bytes) return undefined;
141
+ try {
142
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes), plan = validateRemoteAdoption(JSON.parse(text));
143
+ if (plan.keyHash !== keyHash || canonicalJSON(plan) + "\n" !== text) return fail(); return plan;
144
+ } catch { return fail(); }
145
+ }
146
+ /** Record reviewed metadata before creating any staged content. */
147
+ export function writeRemoteAdoption(homeInput: string, value: RemoteAdoption, proof: RealmIntentProof): void {
148
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value), expected = Buffer.from(canonicalJSON(plan) + "\n"), file = companion(home, plan);
149
+ check(home, proof); ownedDir(home);
150
+ const prior = readRemoteAdoption(home, plan.keyHash), pending = `${file}.${plan.seal}.pending`, stages = inspectRemoteAdoptionPending(home, plan.keyHash);
151
+ if (prior) { if (stages.length || canonicalJSON(prior) !== canonicalJSON(plan)) fail(); return; }
152
+ if (stages.some(item => join(home, item.name) !== pending)) fail();
153
+ complete(home, pending, expected, proof); check(home, proof);
154
+ if (lstatSync(file, { throwIfNoEntry: false })) fail();
155
+ renameSync(pending, file); fsyncDirectory(home); check(home, proof);
156
+ if (canonicalJSON(readRemoteAdoption(home, plan.keyHash)) !== canonicalJSON(plan)) fail();
157
+ }
158
+ /** Stage exact content-addressed packs in a private directory no old realm reader opens. */
159
+ export function stageRemoteAdoption(homeInput: string, value: RemoteAdoption, packs: readonly RemoteStagedPack[], proof: RealmIntentProof): void {
160
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value); check(home, proof);
161
+ if (canonicalJSON(readRemoteAdoption(home, plan.keyHash)) !== canonicalJSON(plan) || packs.length !== plan.packs.length) fail();
162
+ for (let i = 0; i < packs.length; i++) {
163
+ const expected = plan.packs[i], pack = packs[i];
164
+ if (!expected || !pack || expected.name !== pack.name || expected.bytes !== pack.bytes.length || `sync-${sha(pack.bytes)}.jsonl` !== pack.name) fail();
165
+ }
166
+ const root = staging(home, plan), log = join(root, "log"); ensureDir(home, root, home, proof); ensureDir(home, log, root, proof);
167
+ const names = new Set(plan.packs.map(pack => pack.name));
168
+ if (readdirSync(root).some(name => name !== "log") || readdirSync(log).some(name => !names.has(name))) fail();
169
+ for (const pack of packs) complete(home, join(log, pack.name), pack.bytes, proof);
170
+ fsyncDirectory(log); fsyncDirectory(root); check(home, proof);
171
+ }
172
+ /** A missing staged log with an existing destination is a possible completed rename, subject to full verification. */
173
+ export function remoteAdoptionLogMayBeInstalled(homeInput: string, project: string, value: RemoteAdoption): boolean {
174
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value);
175
+ if (!project || sha(project) !== plan.keyHash) return fail();
176
+ const root = staging(home, plan), stage = lstatSync(root, { throwIfNoEntry: false });
177
+ return !!stage && !lstatSync(join(root, "log"), { throwIfNoEntry: false }) && !!lstatSync(join(shardDir(home, project), "log"), { throwIfNoEntry: false });
178
+ }
179
+
180
+ /** Confirmed pre-admission abandon removes only exact unpublished packs this companion installed. */
181
+ export function discardRemoteInstalledLog(homeInput: string, project: string, value: RemoteAdoption, proof: RealmIntentProof): void {
182
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value);
183
+ if (!project || sha(project) !== plan.keyHash) fail(); check(home, proof);
184
+ if (canonicalJSON(readRemoteAdoption(home, plan.keyHash)) !== canonicalJSON(plan)) fail();
185
+ const root = staging(home, plan), staged = join(root, "log"), projectDir = shardDir(home, project), log = join(projectDir, "log");
186
+ ownedDir(root); if (lstatSync(staged, { throwIfNoEntry: false })) return;
187
+ if (readdirSync(root).length) fail();
188
+ const before = ownedDir(log);
189
+ const names = new Set(readdirSync(log)), allowed = new Set(plan.packs.map(pack => pack.name));
190
+ if ([...names].some(name => !allowed.has(name))) fail();
191
+ // A prior confirmed cleanup may have removed a strict subset before a crash.
192
+ const files = plan.packs.filter(pack => names.has(pack.name)).map(pack => {
193
+ const file = join(log, pack.name), bytes = readOwned(file, pack.bytes), stat = lstatSync(file, { bigint: true });
194
+ if (!bytes || bytes.length !== pack.bytes || `sync-${sha(bytes)}.jsonl` !== pack.name) return fail();
195
+ return { file, bytes, stamp: stamp(stat) };
196
+ });
197
+ for (const item of files) {
198
+ check(home, proof); if (stamp(lstatSync(item.file, { bigint: true })) !== item.stamp || !readOwned(item.file, item.bytes.length)?.equals(item.bytes)) fail();
199
+ unlinkSync(item.file);
200
+ }
201
+ fsyncDirectory(log); check(home, proof);
202
+ const current = ownedDir(log); if (current.dev !== before.dev || current.ino !== before.ino || readdirSync(log).length) fail();
203
+ // A completed #448 scaffold still needs its log directory, even if its extension was abandoned.
204
+ if (!lstatSync(join(projectDir, "generation.json"), { throwIfNoEntry: false })) rmdirSync(log);
205
+ fsyncDirectory(projectDir); check(home, proof);
206
+ }
207
+ /** Install the complete staged log as one same-filesystem rename; work and machine data stay in place. */
208
+ export function installRemoteAdoptionLog(homeInput: string, project: string, value: RemoteAdoption, proof: RealmIntentProof, allowRetainedMetadata = false): void {
209
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value);
210
+ if (!project || sha(project) !== plan.keyHash) fail();
211
+ check(home, proof); if (canonicalJSON(readRemoteAdoption(home, plan.keyHash)) !== canonicalJSON(plan)) fail();
212
+ const root = staging(home, plan), log = join(root, "log"), projectDir = shardDir(home, project), destination = join(projectDir, "log");
213
+ ownedDir(root);
214
+ const verifyLog = (dir: string) => {
215
+ ownedDir(dir); if (canonicalJSON(readdirSync(dir).sort()) !== canonicalJSON(plan.packs.map(pack => pack.name))) fail();
216
+ for (const pack of plan.packs) { const data = readOwned(join(dir, pack.name), pack.bytes); if (!data || data.length !== pack.bytes || `sync-${sha(data)}.jsonl` !== pack.name) fail(); }
217
+ };
218
+ // A crash after rename leaves the exact destination and an empty owned stage; never rename or truncate it again.
219
+ if (!lstatSync(log, { throwIfNoEntry: false })) {
220
+ if (readdirSync(root).length || !allowRetainedMetadata && lstatSync(join(projectDir, "generation.json"), { throwIfNoEntry: false })) fail();
221
+ assertCuratedShardLayout(home, { project }); ownedDir(projectDir); verifyLog(destination); check(home, proof); return;
222
+ }
223
+ const source = ownedDir(log);
224
+ if (readdirSync(root).some(name => name !== "log")) fail();
225
+ verifyLog(log);
226
+ check(home, proof);
227
+ const projects = join(home, "projects"); ownedDir(projects);
228
+ if (lstatSync(projectDir, { throwIfNoEntry: false })) {
229
+ ownedDir(projectDir); rejectExistingCurated(projectDir);
230
+ }
231
+ assertCuratedShardLayout(home, { project });
232
+ if (!lstatSync(projectDir, { throwIfNoEntry: false })) { mkdirSync(projectDir, { mode: 0o700 }); fsyncDirectory(projects); }
233
+ const target = ownedDir(projectDir);
234
+ rejectExistingCurated(projectDir);
235
+ ensureShardDescriptor(home, project); check(home, proof);
236
+ if (source.dev !== target.dev || lstatSync(destination, { throwIfNoEntry: false })) fail();
237
+ const currentTarget = ownedDir(projectDir);
238
+ if (stamp(ownedDir(log)) !== stamp(source) || currentTarget.dev !== target.dev || currentTarget.ino !== target.ino) fail();
239
+ renameSync(log, destination); fsyncDirectory(root); fsyncDirectory(projectDir); check(home, proof);
240
+ const installed = ownedDir(destination); if (installed.dev !== source.dev || installed.ino !== source.ino) fail();
241
+ }
242
+
243
+ /** Remove only this plan's attributable private staging; an installed curated log is never removed. */
244
+ export function clearRemoteAdoption(homeInput: string, value: RemoteAdoption, packs: readonly RemoteStagedPack[], proof: RealmIntentProof): void {
245
+ const home = realPath(homeInput), plan = validateRemoteAdoption(value); check(home, proof);
246
+ assertRemoteAdoptionStageOwnership(home, plan);
247
+ if (canonicalJSON(readRemoteAdoption(home, plan.keyHash)) !== canonicalJSON(plan) || packs.length !== plan.packs.length) fail();
248
+ for (let i = 0; i < packs.length; i++) {
249
+ const expected = plan.packs[i], pack = packs[i];
250
+ if (!expected || !pack || expected.name !== pack.name || expected.bytes !== pack.bytes.length || `sync-${sha(pack.bytes)}.jsonl` !== pack.name) fail();
251
+ }
252
+ const root = staging(home, plan), log = join(root, "log"), stage = lstatSync(root, { bigint: true, throwIfNoEntry: false });
253
+ if (stage) {
254
+ ownedDir(root); if (readdirSync(root).some(name => name !== "log")) fail();
255
+ if (lstatSync(log, { throwIfNoEntry: false })) {
256
+ ownedDir(log); const byName = new Map(packs.map(pack => [pack.name, pack.bytes]));
257
+ const names = readdirSync(log); if (names.some(name => !byName.has(name))) fail();
258
+ // First prove every remaining prefix, then recheck each one immediately before removal.
259
+ const saved = names.map(name => {
260
+ const file = join(log, name), expected = byName.get(name)!, bytes = readOwned(file, expected.length), stat = lstatSync(file, { bigint: true });
261
+ if (!bytes || !bytes.equals(expected.subarray(0, bytes.length))) return fail();
262
+ return { file, expected, bytes, stamp: stamp(stat) };
263
+ });
264
+ for (const item of saved) {
265
+ check(home, proof); if (stamp(lstatSync(item.file, { bigint: true })) !== item.stamp || !readOwned(item.file, item.expected.length)?.equals(item.bytes)) fail();
266
+ unlinkSync(item.file);
267
+ }
268
+ fsyncDirectory(log); check(home, proof); rmdirSync(log); fsyncDirectory(root);
269
+ }
270
+ check(home, proof); if (readdirSync(root).length) fail(); rmdirSync(root); fsyncDirectory(home);
271
+ }
272
+ const file = companion(home, plan), expected = Buffer.from(canonicalJSON(plan) + "\n"), before = lstatSync(file, { bigint: true });
273
+ check(home, proof); if (!readOwned(file, REMOTE_ADOPTION_MAX_BYTES)?.equals(expected) || stamp(lstatSync(file, { bigint: true })) !== stamp(before)) fail();
274
+ unlinkSync(file); fsyncDirectory(home); check(home, proof);
275
+ }