@staix/agent-mem 0.29.0 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +9 -7
- package/package.json +3 -2
- package/src/cli.ts +69 -10
- package/src/commands-table.ts +4 -0
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/doctor.ts +17 -14
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +14 -2
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +5 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +202 -51
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +14 -0
- package/src/memory/sync.ts +4 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Shared pure event scheduling for sync and read-only prospective planning. */
|
|
2
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
3
|
+
import { placementKeyId, type PlacementEvent, type PlacementHoldReason, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
4
|
+
import type { PlacementProjection } from "./sync-placement-projection.ts";
|
|
5
|
+
import type { PlacementPublicationBundle, PlacementPublicationDecision } from "./sync-placement-publication-plan.ts";
|
|
6
|
+
import type { ShardHistory } from "./shard-sync-history.ts";
|
|
7
|
+
import { PlacementSyncRefusal } from "./sync-placement-refusal.ts";
|
|
8
|
+
const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
|
|
9
|
+
function refuse(): never { throw new PlacementSyncRefusal(); }
|
|
10
|
+
|
|
11
|
+
export function* placementPublicationEventSteps(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[]):Generator<void,{events:PlacementEvent[];preCount:number;holdCount:number},void>{
|
|
12
|
+
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)));
|
|
13
|
+
const holds:PlacementEvent[]=[],known:PlacementEvent[]=[],ambiguous:PlacementEvent[]=[],committed:PlacementEvent[]=[];
|
|
14
|
+
const root=bundle.root;
|
|
15
|
+
const make=(decision:PlacementPublicationDecision,kind:PlacementEvent["kind"],commit?:string):PlacementEvent=>{
|
|
16
|
+
const base={requestId:hashJSON({attempt:root.seal,key:decision.key,kind,commit:commit??null}),key:decision.key,sourcePlacement:decision.sourcePlacement,
|
|
17
|
+
effectHash:hashJSON({attempt:root.seal,context:root.contextHash,key:decision.key,kind,commit:commit??null})};
|
|
18
|
+
if(kind==="hold"){
|
|
19
|
+
const reason=decision.reason;
|
|
20
|
+
const hold:PlacementHoldReason=reason==="secret"||reason==="personal-data"||reason==="deny-path"||reason==="private-or-invalid"||reason==="host"||reason==="person-local"?reason:"related-local";
|
|
21
|
+
return{...base,kind,reason:hold};
|
|
22
|
+
}
|
|
23
|
+
const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm));if(index<0)refuse();
|
|
24
|
+
const outcome={attemptHash:root.seal,remoteHash:root.remoteHash,refHash:root.targets[index]!.refHash};
|
|
25
|
+
if(kind==="publication-ambiguous")return{...base,kind,outcome};
|
|
26
|
+
if(kind!=="publication-committed"||!commit)refuse();
|
|
27
|
+
return{...base,kind,outcome:{...outcome,commit,proofHash:hashJSON({attempt:root.seal,key:decision.key,commit,remote:root.remoteHash,ref:root.targets[index]!.refHash})}};
|
|
28
|
+
};
|
|
29
|
+
let stepped=0;
|
|
30
|
+
for(const decision of decisions){
|
|
31
|
+
if(++stepped>=64){stepped=0;yield;}
|
|
32
|
+
const state=projection.get(decision.key);
|
|
33
|
+
const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm)),target=root.targets[index];if(!target)refuse();
|
|
34
|
+
const original=old[index]?.rows.get(decision.key.id),published=original&&hashJSON(original)===decision.key.rowHash;
|
|
35
|
+
if(decision.hold)holds.push(make(decision,"hold"));
|
|
36
|
+
if(published&&state?.exposure!=="published"&&target.expectedRemoteHead)known.push(make(decision,"publication-committed",target.expectedRemoteHead));
|
|
37
|
+
if(decision.eligible&&target.publish&&!published){
|
|
38
|
+
ambiguous.push(make(decision,"publication-ambiguous"));committed.push(make(decision,"publication-committed",target.commit!));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return{events:[...holds,...known,...ambiguous,...committed],preCount:holds.length+known.length+ambiguous.length,holdCount:holds.length};
|
|
42
|
+
}
|
|
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
|
|
|
4
4
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
5
5
|
import { validatePlacementKey, placementKeyId, SyncPlacementJournalError, PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS,
|
|
6
6
|
PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES, type PlacementKey, type PlacementRealm, type PlacementHoldReason } from "./sync-placement-journal-format.ts";
|
|
7
|
+
import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
|
|
7
8
|
|
|
8
9
|
export const PLACEMENT_PUBLICATION_PLAN_SCHEMA = "agent-mem.sync-placement-publication-plan/v1";
|
|
9
10
|
export const PLACEMENT_PUBLICATION_CHUNK_SCHEMA = "agent-mem.sync-placement-publication-chunk/v1";
|
|
@@ -150,11 +151,26 @@ export function validatePlacementPublicationBundle(input: unknown): PlacementPub
|
|
|
150
151
|
export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
|
|
151
152
|
sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
|
|
152
153
|
}): PlacementPublicationBundle {
|
|
154
|
+
return drainSteps(planSteps(input, items));
|
|
155
|
+
}
|
|
156
|
+
/** #470: the same bundle, awaiting the caller's event loop between chunk items; chunk boundaries and hashes are identical. */
|
|
157
|
+
export async function planPlacementPublicationAsync(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
|
|
158
|
+
sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
|
|
159
|
+
}, yieldPoint?: CooperativeYield): Promise<PlacementPublicationBundle> {
|
|
160
|
+
return await drainStepsAsync(planSteps(input, items), yieldPoint);
|
|
161
|
+
}
|
|
162
|
+
/** Items between step boundaries: at most 64 canonicalized chunk items per uninterrupted stretch. */
|
|
163
|
+
const STEP_ITEMS = 64;
|
|
164
|
+
function* planSteps(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
|
|
165
|
+
sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
|
|
166
|
+
}): Generator<void, PlacementPublicationBundle, void> {
|
|
153
167
|
const values = object(items, kinds), chunks: PlacementPublicationChunk[] = [];
|
|
168
|
+
let stepped = 0;
|
|
154
169
|
for (const kind of kinds) {
|
|
155
170
|
let selected: PlacementPublicationChunk["items"] = [], selectedBytes = 0;
|
|
156
171
|
const flush = () => { if (selected.length) { chunks.push(validatePlacementPublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: selected })); selected = []; selectedBytes = 0; } };
|
|
157
172
|
for (const value of array(values[kind], PLACEMENT_JOURNAL_MAX_RECORDS)) {
|
|
173
|
+
if (++stepped >= STEP_ITEMS) { stepped = 0; yield; }
|
|
158
174
|
// #462: the candidate chunk's exact canonical size, summed per item instead of re-serializing the whole chunk per row
|
|
159
175
|
// (quadratic). canonicalJSON of an array is its items' canonical forms joined by commas, so the sum is identical.
|
|
160
176
|
const row = item(kind, value), rowBytes = Buffer.byteLength(canonicalJSON(row));
|
|
@@ -165,7 +181,8 @@ export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "
|
|
|
165
181
|
flush();
|
|
166
182
|
}
|
|
167
183
|
const body = { ...object(input, ["epochHash", "generation", "homeHash", "contextHash", "markerHash", "sourceHash", "aliasesHash", "policyHash", "remoteHash", "journal", "reservedRecords", "reservedRecordBytes", "createdUnixSeconds", "policySnapshotUnixMs", "targets"]), schema: PLACEMENT_PUBLICATION_PLAN_SCHEMA,
|
|
168
|
-
|
|
184
|
+
// #470: each chunk is serialized once here; the descriptor only needs its hash and length.
|
|
185
|
+
chunks: chunks.map(c => { const bytes = publicationBytes(c); return { kind: c.kind, index: c.index, hash: publicationHash(bytes), count: c.items.length, bytes: bytes.length }; }) };
|
|
169
186
|
const { seal: _seal, ...safeBody } = normalizedRoot({ ...body, seal: "0".repeat(64) }, false);
|
|
170
187
|
return validatePlacementPublicationBundle({ root: { ...safeBody, seal: hashJSON(safeBody) }, chunks });
|
|
171
188
|
}
|
|
@@ -25,6 +25,8 @@ import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-
|
|
|
25
25
|
import { previewOwnedSyncPlacementSources, previewSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
26
26
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
27
27
|
import { readPlacementWriterJournalAnchors } from "./sync-placement-journal-storage.ts";
|
|
28
|
+
import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
29
|
+
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
28
30
|
import { createRealmExtension, REALM_EXTENSION_SCHEMA, RealmExtensionFormatError, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
29
31
|
import { readRealmExtensionHistory, type RealmExtensionBinding, type RealmExtensionHistory } from "./sync-placement-realm-extension-storage.ts";
|
|
30
32
|
/** A zero-byte extension log is the pre-write state of a retained admission for this epoch, never an unknown chain. */
|
|
@@ -61,6 +63,8 @@ export type RealmAdmissionMode = "apply" | "resume" | "abandon";
|
|
|
61
63
|
export type RealmAdmissionStage = "after-intent" | "after-metadata" | "after-proof" | "after-append";
|
|
62
64
|
export interface RealmAdmissionOptions {
|
|
63
65
|
mode: RealmAdmissionMode; confirm?: boolean;
|
|
66
|
+
/** Internal remote-adoption anchors; callers without a staged remote retain the existing flow. */
|
|
67
|
+
expectedRemoteAnchors?: { writerHash: string; inventoryHead: string; journalSequence: number; journalHead: string };
|
|
64
68
|
/** Internal fault seam between durable steps; the CLI never supplies it. */
|
|
65
69
|
checkpoint?(stage: RealmAdmissionStage): void | Promise<void>;
|
|
66
70
|
}
|
|
@@ -89,7 +93,7 @@ function assertNoPendingAdmission(home: string, ownRealm?: string): void {
|
|
|
89
93
|
if (other) throw new RealmAdmissionError("pending", other);
|
|
90
94
|
}
|
|
91
95
|
function rethrow(error: unknown): never {
|
|
92
|
-
if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError) throw error;
|
|
96
|
+
if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError || error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error;
|
|
93
97
|
if (error instanceof PlacementInventoryFenceError) fail(error.causeClass);
|
|
94
98
|
return fail("metadata");
|
|
95
99
|
}
|
|
@@ -108,6 +112,11 @@ function activeBinding(home: string): ActivePlacementBinding {
|
|
|
108
112
|
if (!active) throw Error("sync placement is not active in this home; there is no inventory to admit a realm into");
|
|
109
113
|
return active;
|
|
110
114
|
}
|
|
115
|
+
function assertCheckpointClear(home: string): void {
|
|
116
|
+
const active = activeBinding(home);
|
|
117
|
+
try { if (resolvePlacementWindow(home, active.profile.placementHead).pending) throw new SyncPlacementJournalError("checkpoint-pending"); }
|
|
118
|
+
catch (error) { if (error instanceof SyncPlacementJournalError && error.code === "pending") throw new SyncPlacementJournalError("checkpoint-pending"); throw error; }
|
|
119
|
+
}
|
|
111
120
|
function machineIdentity(home: string): { id: string; label: string } {
|
|
112
121
|
const machine = readProfileJSON(join(home, "machine.json")) as { id?: unknown; label?: unknown } | undefined;
|
|
113
122
|
const id = machine?.id, label = machine?.label;
|
|
@@ -228,6 +237,7 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
228
237
|
let home: string;
|
|
229
238
|
try { home = realPath(homeInput); } catch { throw Error("Sync placement memory home is unavailable; select an existing private home and run amem migrate --sync-placement --admit <project> --dry-run."); }
|
|
230
239
|
const realm = digest(project), projectPrefix = realm.slice(0, 16);
|
|
240
|
+
assertCheckpointClear(home);
|
|
231
241
|
if (options.mode === "abandon") {
|
|
232
242
|
const plan = planRealmAbandon(home, project);
|
|
233
243
|
if (plan.state === "none") return { mode: "abandon", state: "already-admitted", realm, nextStep: plan.nextStep };
|
|
@@ -238,8 +248,9 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
238
248
|
if (plan.staged && stages?.length !== plan.staged) fail("changed");
|
|
239
249
|
return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
240
250
|
try {
|
|
251
|
+
assertCheckpointClear(home);
|
|
241
252
|
const binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
|
|
242
|
-
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); }, proof = { mutation, assertCurrent: check };
|
|
253
|
+
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
|
|
243
254
|
if (stages) {
|
|
244
255
|
readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: evidence => attributeTornRealmAppend(home, binding, evidence) });
|
|
245
256
|
clearRealmIntentStages(home, realm, stages, proof);
|
|
@@ -266,11 +277,15 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
266
277
|
}
|
|
267
278
|
return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
268
279
|
try {
|
|
280
|
+
assertCheckpointClear(home);
|
|
269
281
|
if (options.mode === "apply") assertNoPendingAdmission(home);
|
|
270
282
|
if (options.mode === "resume") assertNoPendingAdmission(home, realm);
|
|
271
283
|
const binding = realmBinding(activeBinding(home));
|
|
272
|
-
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); }, proof = { mutation, assertCurrent: check };
|
|
284
|
+
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
|
|
273
285
|
let intent = readRealmIntent(home, realm);
|
|
286
|
+
const expected = options.expectedRemoteAnchors;
|
|
287
|
+
if (intent && expected && (intent.writerHash !== expected.writerHash || intent.previousHash !== expected.inventoryHead
|
|
288
|
+
|| intent.journal.sequence !== expected.journalSequence || intent.journal.headHash !== expected.journalHead)) fail("changed");
|
|
274
289
|
if (intent && options.mode === "apply") fail("pending");
|
|
275
290
|
if (!intent && options.mode === "resume") {
|
|
276
291
|
if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted" as const, realm };
|
|
@@ -295,6 +310,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
295
310
|
const fixed = inspectRealmAdmission(home, project, owner);
|
|
296
311
|
if (fixed.state === "already-admitted") return { mode: options.mode, state: "already-admitted" as const, realm };
|
|
297
312
|
if (!fixed.next) fail("metadata");
|
|
313
|
+
if (expected && (fixed.next.writerHash !== expected.writerHash || fixed.next.previousHash !== expected.inventoryHead
|
|
314
|
+
|| fixed.next.journal.sequence !== expected.journalSequence || fixed.next.journal.headHash !== expected.journalHead)) fail("changed");
|
|
298
315
|
intent = intentFor(home, project, fixed.next, binding);
|
|
299
316
|
writeRealmIntent(home, intent, { mutation, assertCurrent: current });
|
|
300
317
|
await options.checkpoint?.("after-intent");
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Bounded, data-only parsing of the selected placement remote's advertised project refs. */
|
|
2
|
+
import type { SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
|
|
3
|
+
import type { EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
4
|
+
|
|
5
|
+
export const REMOTE_REALM_ADVERTISEMENT_BYTES = 256 * 1024;
|
|
6
|
+
const REF_COUNT = 4096;
|
|
7
|
+
export interface RemoteOnlyRealm { scope: "project"; keyHash: string }
|
|
8
|
+
const unavailable = (): never => { throw new Error("Remote placement realm listing is unavailable or exceeds its bound; inspect the remote before continuing."); };
|
|
9
|
+
|
|
10
|
+
/** Names are never inferred from ref hashes; invalid or ambiguous input refuses the entire listing. */
|
|
11
|
+
export function remoteOnlyPlacementRealms(bytes: Uint8Array, inventory: readonly SyncPlacementRealmBinding[]): RemoteOnlyRealm[] {
|
|
12
|
+
if (bytes.byteLength > REMOTE_REALM_ADVERTISEMENT_BYTES || inventory.length > REF_COUNT) return unavailable();
|
|
13
|
+
let text: string;
|
|
14
|
+
try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { return unavailable(); }
|
|
15
|
+
if (text && !text.endsWith("\n")) return unavailable();
|
|
16
|
+
const local = new Set<string>();
|
|
17
|
+
for (const realm of inventory) {
|
|
18
|
+
if (realm.scope === "user") continue;
|
|
19
|
+
if (realm.scope !== "project" || !/^[a-f0-9]{64}$/.test(realm.keyHash)) return unavailable();
|
|
20
|
+
const hash = realm.keyHash.slice(0, 16);
|
|
21
|
+
if (local.has(hash)) return unavailable();
|
|
22
|
+
local.add(hash);
|
|
23
|
+
}
|
|
24
|
+
const remote = new Set<string>(), lines = text ? text.slice(0, -1).split("\n") : [];
|
|
25
|
+
if (lines.length > REF_COUNT) return unavailable();
|
|
26
|
+
for (const line of lines) {
|
|
27
|
+
const match = /^([a-f0-9]{40})\trefs\/heads\/amem\/p\/([a-f0-9]{16})$/.exec(line);
|
|
28
|
+
if (!match || remote.has(match[2]!)) return unavailable();
|
|
29
|
+
remote.add(match[2]!);
|
|
30
|
+
}
|
|
31
|
+
return [...remote].filter(hash => !local.has(hash)).sort().map(keyHash => ({ scope: "project", keyHash }));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The transport owns the bounded remote call; inventory must remain current across the await. */
|
|
35
|
+
export async function listRemotePlacementRealms(inventory: EffectiveRealmInventory, advertise: () => Promise<Uint8Array>): Promise<RemoteOnlyRealm[]> {
|
|
36
|
+
inventory.assertCurrent();
|
|
37
|
+
const bytes = await advertise();
|
|
38
|
+
inventory.assertCurrent();
|
|
39
|
+
const realms = remoteOnlyPlacementRealms(bytes, inventory.realms);
|
|
40
|
+
inventory.assertCurrent();
|
|
41
|
+
return realms;
|
|
42
|
+
}
|
|
@@ -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
|
+
}
|