@staix/agent-mem 0.28.1 → 0.29.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 +11 -7
- package/package.json +1 -1
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +34 -3
- package/src/commands-table.ts +2 -0
- package/src/mcp-memory.ts +1 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +15 -12
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/metrics.ts +1 -0
- package/src/memory/public-prune-advance.ts +2 -1
- package/src/memory/shard-sync-applications.ts +1 -1
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard.ts +41 -14
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-capture.ts +53 -17
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inventory.ts +136 -0
- package/src/memory/sync-placement-journal-storage.ts +21 -4
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +14 -3
- package/src/memory/sync-placement-publication-plan.ts +8 -4
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +335 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-transport.ts +70 -31
- package/src/memory/sync-placement-yield.ts +30 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +23 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Preview and apply a same-epoch realm admission (#448 AC2-AC4).
|
|
3
|
+
*
|
|
4
|
+
* A curated realm that appeared after activation is admitted by a person command: a dry-run report first, then one
|
|
5
|
+
* explicit apply. The report reads the activation, the extension chain, the writer history, the journal anchors and the
|
|
6
|
+
* target realm's own source facts and writes nothing. Apply re-reads every one of those facts under the live profile and
|
|
7
|
+
* mutation fences, retains a frozen intent, completes the realm's empty curated metadata and appends one extension
|
|
8
|
+
* record carrying the same proofs activation used for the realms it named.
|
|
9
|
+
*
|
|
10
|
+
* The record is the shape activation produced, so a later reader needs no new verification: an admitted realm is
|
|
11
|
+
* indistinguishable from an activated one. Retained activation metadata is never rewritten, nothing is appended twice,
|
|
12
|
+
* and a chain that no longer matches the frozen intent fails closed with the cause and the recovery command.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { existsSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { hashJSON, readProfileJSON } from "./generation.ts";
|
|
19
|
+
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
20
|
+
import { realPath } from "./platform.ts";
|
|
21
|
+
import { readShardDescriptor, assertCuratedShardLayout, shardDir } from "./shard.ts";
|
|
22
|
+
import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
23
|
+
import { withPlacementActivationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
|
|
24
|
+
import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
25
|
+
import { previewOwnedSyncPlacementSources, previewSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
26
|
+
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
27
|
+
import { readPlacementWriterJournalAnchors } from "./sync-placement-journal-storage.ts";
|
|
28
|
+
import { createRealmExtension, REALM_EXTENSION_SCHEMA, RealmExtensionFormatError, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
29
|
+
import { readRealmExtensionHistory, type RealmExtensionBinding, type RealmExtensionHistory } from "./sync-placement-realm-extension-storage.ts";
|
|
30
|
+
/** A zero-byte extension log is the pre-write state of a retained admission for this epoch, never an unknown chain. */
|
|
31
|
+
const emptyLogAllowed = (home: string, binding: RealmExtensionBinding): boolean => retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash);
|
|
32
|
+
import { readEffectiveRealmInventory, retainedAdmissionCoversEmptyLog } from "./sync-placement-realm-effective.ts";
|
|
33
|
+
import { createRealmIntent, REALM_INTENT_SCHEMA, type RealmIntent } from "./sync-placement-realm-intent-format.ts";
|
|
34
|
+
import { clearRealmIntent, clearRealmIntentStages, inspectRealmIntentStages, readRealmIntent, writeRealmIntent } from "./sync-placement-realm-intent-storage.ts";
|
|
35
|
+
import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
|
|
36
|
+
import { clearRealmProof, hasRealmProofStage, inspectRealmProofStage, readRealmProof, writeRealmProof } from "./sync-placement-realm-proof.ts";
|
|
37
|
+
import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
|
|
38
|
+
import { appendRealmExtension, discardRealmExtensionTail, ensureCuratedRealmMetadata } from "./sync-placement-realm-admission-storage.ts";
|
|
39
|
+
import { readWriterHistory } from "./sync-placement-writer-history.ts";
|
|
40
|
+
import { activePlacementWriterContext } from "../sync-placement-writer-context.ts";
|
|
41
|
+
import { writerInventoryGenesis } from "./sync-placement-writer-revision-format.ts";
|
|
42
|
+
import type { SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
|
|
43
|
+
|
|
44
|
+
const digest = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
|
|
45
|
+
const empty = digest("");
|
|
46
|
+
const MACHINE_ID = /^[0-9a-f]{16}$/;
|
|
47
|
+
|
|
48
|
+
/** `not-local` is a state both 0.28.2 and the #450 driver already report: no curated shard yet, so nothing to admit yet. */
|
|
49
|
+
export type RealmAdmissionState = "admissible" | "already-admitted" | "not-local" | "unavailable";
|
|
50
|
+
/** Everything the intent and record would pin; identifiers and hashes only, never a project key or a row. */
|
|
51
|
+
export interface RealmAdmissionNext {
|
|
52
|
+
mode: "new" | "existing";
|
|
53
|
+
sequence: number; previousHash: string; previousLogBytes: number; previousLogHash: string;
|
|
54
|
+
writerHash: string; journal: { sequence: number; headHash: string };
|
|
55
|
+
bindingHash?: string; descriptorHash?: string; sourceHash?: string;
|
|
56
|
+
aliasesHash: string; policyHash: string;
|
|
57
|
+
}
|
|
58
|
+
export interface RealmAdmissionPreview { realm: string; state: RealmAdmissionState; next?: RealmAdmissionNext }
|
|
59
|
+
export interface RealmAbandonPlan { realm: string; state: "abandonable" | "committed" | "none" | "unavailable"; sequence?: number; discards?: number; staged?: number; nextStep?: string }
|
|
60
|
+
export type RealmAdmissionMode = "apply" | "resume" | "abandon";
|
|
61
|
+
export type RealmAdmissionStage = "after-intent" | "after-metadata" | "after-proof" | "after-append";
|
|
62
|
+
export interface RealmAdmissionOptions {
|
|
63
|
+
mode: RealmAdmissionMode; confirm?: boolean;
|
|
64
|
+
/** Internal fault seam between durable steps; the CLI never supplies it. */
|
|
65
|
+
checkpoint?(stage: RealmAdmissionStage): void | Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
export interface RealmAdmissionResult {
|
|
68
|
+
mode: RealmAdmissionMode; state: "admitted" | "already-admitted" | "abandoned" | "retained";
|
|
69
|
+
realm: string; sequence?: number; headHash?: string; created?: boolean; discarded?: number; staged?: number; nextStep?: string;
|
|
70
|
+
}
|
|
71
|
+
export class RealmAdmissionError extends Error {
|
|
72
|
+
constructor(readonly causeClass: "readers" | "busy" | "changed" | "pending" | "committed" | "metadata", readonly retainedRealm?: string) {
|
|
73
|
+
super(`Sync placement realm admission is ${causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
|
|
74
|
+
this.name = "RealmAdmissionError";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function action(causeClass: RealmAdmissionError["causeClass"]): string {
|
|
78
|
+
if (causeClass === "pending") return "An admission intent is retained: run amem migrate --sync-placement --admit <project> --resume, or review amem migrate --sync-placement --admit <project> --abandon before confirming it.";
|
|
79
|
+
if (causeClass === "committed") return "The extension chain no longer matches the frozen intent: run amem migrate --sync-placement --admit <project> --resume to complete or clean up the retained attempt, and keep --abandon --confirm for an append that never committed.";
|
|
80
|
+
if (causeClass === "changed") return "Re-read the home with amem migrate --sync-placement --admit <project> --dry-run and apply the reviewed append.";
|
|
81
|
+
if (causeClass === "metadata") return "Inspect the local placement and curated metadata it names, then run amem migrate --sync-placement --admit <project> --dry-run.";
|
|
82
|
+
return "Close cooperating readers and writers, then run amem migrate --sync-placement --admit <project> --dry-run.";
|
|
83
|
+
}
|
|
84
|
+
function fail(causeClass: RealmAdmissionError["causeClass"]): never { throw new RealmAdmissionError(causeClass); }
|
|
85
|
+
function assertNoPendingAdmission(home: string, ownRealm?: string): void {
|
|
86
|
+
const pending = pendingRealmInventory(home);
|
|
87
|
+
if (pending.unknown) fail("pending");
|
|
88
|
+
const other = pending.hashes.find(key => key !== ownRealm);
|
|
89
|
+
if (other) throw new RealmAdmissionError("pending", other);
|
|
90
|
+
}
|
|
91
|
+
function rethrow(error: unknown): never {
|
|
92
|
+
if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError) throw error;
|
|
93
|
+
if (error instanceof PlacementInventoryFenceError) fail(error.causeClass);
|
|
94
|
+
return fail("metadata");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function realmBinding(active: ActivePlacementBinding): RealmExtensionBinding {
|
|
98
|
+
return { epochHash: active.profile.placementHead, activationHash: active.activation.seal, homeHash: active.epoch.homeHash,
|
|
99
|
+
generation: active.epoch.generation,
|
|
100
|
+
initialProjectHashes: active.activation.realms.flatMap(realm => realm.scope === "project" ? [realm.keyHash] : []) };
|
|
101
|
+
}
|
|
102
|
+
/** The writer history reads exactly four identity fields; an extension binding carries one more. */
|
|
103
|
+
function writerBinding(binding: RealmExtensionBinding): { epochHash: string; activationHash: string; homeHash: string; generation: string } {
|
|
104
|
+
return { epochHash: binding.epochHash, activationHash: binding.activationHash, homeHash: binding.homeHash, generation: binding.generation };
|
|
105
|
+
}
|
|
106
|
+
function activeBinding(home: string): ActivePlacementBinding {
|
|
107
|
+
const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
108
|
+
if (!active) throw Error("sync placement is not active in this home; there is no inventory to admit a realm into");
|
|
109
|
+
return active;
|
|
110
|
+
}
|
|
111
|
+
function machineIdentity(home: string): { id: string; label: string } {
|
|
112
|
+
const machine = readProfileJSON(join(home, "machine.json")) as { id?: unknown; label?: unknown } | undefined;
|
|
113
|
+
const id = machine?.id, label = machine?.label;
|
|
114
|
+
if (typeof id !== "string" || !MACHINE_ID.test(id)) fail("metadata");
|
|
115
|
+
return { id, label: typeof label === "string" ? label : id };
|
|
116
|
+
}
|
|
117
|
+
function inForce(home: string, realm: string): boolean {
|
|
118
|
+
try { return readEffectiveRealmInventory(home, activeBinding(home)).realms.some(item => item.scope === "project" && item.keyHash === realm); }
|
|
119
|
+
catch { return false; }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Every realm identity is a hash here, so only identifiers leave this module. */
|
|
123
|
+
function inspectRealmAdmission(home: string, project: string, owner?: PlacementActivationOwner): RealmAdmissionPreview {
|
|
124
|
+
const realm = digest(project), active = activeBinding(home), binding = realmBinding(active);
|
|
125
|
+
let effective: readonly SyncPlacementRealmBinding[];
|
|
126
|
+
try { effective = readEffectiveRealmInventory(home, active).realms; } catch { return { realm, state: "unavailable" }; }
|
|
127
|
+
if (effective.some(item => item.scope === "project" && item.keyHash === realm)) return { realm, state: "already-admitted" };
|
|
128
|
+
// A scaffold whose fixed paths are not real directories and private files cannot be completed: completing it would create
|
|
129
|
+
// files through a symlink (a restored `legacy` is the easy case). Refuse before an intent or any metadata write, as the
|
|
130
|
+
// same `unavailable` the other unusable states report.
|
|
131
|
+
try { assertCuratedShardLayout(home, { project }); } catch { return { realm, state: "unavailable" }; }
|
|
132
|
+
const descriptor = readShardDescriptor(home, realm.slice(0, 16));
|
|
133
|
+
if (descriptor && digest(descriptor.key) !== realm) return { realm, state: "unavailable" };
|
|
134
|
+
const curated = descriptor !== undefined && existsSync(join(shardDir(home, descriptor.key), "generation.json"));
|
|
135
|
+
// Strict: an unattributed or torn chain is not something a preview or an intent may append over.
|
|
136
|
+
let history: RealmExtensionHistory;
|
|
137
|
+
try { history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding) }); } catch { return { realm, state: "unavailable" }; }
|
|
138
|
+
const source = owner ? previewOwnedSyncPlacementSources(home, owner) : previewSyncPlacementSources(home);
|
|
139
|
+
const captured = source.base.realms.find(item => item.scope === "project" && item.keyHash === realm);
|
|
140
|
+
if (curated !== (captured !== undefined)) return { realm, state: "unavailable" };
|
|
141
|
+
const journal = readPlacementWriterJournalAnchors(home, binding.epochHash);
|
|
142
|
+
if (journal.epoch.homeHash !== binding.homeHash || journal.activation.seal !== binding.activationHash) return { realm, state: "unavailable" };
|
|
143
|
+
const writers = readWriterHistory(home, writerBinding(binding));
|
|
144
|
+
const writerHash = writers.commits.at(-1)?.seal ?? writerInventoryGenesis(binding.epochHash, binding.activationHash);
|
|
145
|
+
const headHash = journal.sequence ? journal.records[journal.sequence - 1]!.seal : binding.epochHash;
|
|
146
|
+
// The facts and the anchors must still hold when the report leaves this function.
|
|
147
|
+
source.assertSourcesUnchanged(); history.assertCurrent(); writers.assertCurrent();
|
|
148
|
+
const next: RealmAdmissionNext = { mode: curated ? "existing" : "new",
|
|
149
|
+
sequence: history.records.length + 1, previousHash: history.headHash,
|
|
150
|
+
previousLogBytes: history.logBytes.length, previousLogHash: history.logBytes.length ? digest(history.logBytes) : empty,
|
|
151
|
+
writerHash, journal: { sequence: journal.sequence, headHash },
|
|
152
|
+
aliasesHash: source.base.aliasesHash, policyHash: source.base.policyHash,
|
|
153
|
+
...(captured ? { bindingHash: captured.bindingHash, descriptorHash: hashJSON(descriptor), sourceHash: source.base.sourceHash } : {}) };
|
|
154
|
+
return { realm, state: curated ? "admissible" : "not-local", next };
|
|
155
|
+
}
|
|
156
|
+
/** A dry-run report only: no fence, no intent, no curated metadata and no appended byte. */
|
|
157
|
+
export function previewRealmAdmission(homeInput: string, project: string): RealmAdmissionPreview {
|
|
158
|
+
const home = realPath(homeInput);
|
|
159
|
+
activeBinding(home); // a home without active placement keeps its own message instead of a metadata class
|
|
160
|
+
try { return inspectRealmAdmission(home, project); } catch (error) { return rethrow(error); }
|
|
161
|
+
}
|
|
162
|
+
/** Person abandon preview: what a confirmed abandon would remove, and whether the append already committed. */
|
|
163
|
+
export function planRealmAbandon(homeInput: string, project: string): RealmAbandonPlan {
|
|
164
|
+
const realm = digest(project);
|
|
165
|
+
try {
|
|
166
|
+
const home = realPath(homeInput), binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
|
|
167
|
+
const stages = inspectRealmIntentStages(home, realm);
|
|
168
|
+
if (stages.length) {
|
|
169
|
+
// A stage is independent of an installed intent or committed record; never discard an unattributed log tail.
|
|
170
|
+
readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: evidence => attributeTornRealmAppend(home, binding, evidence) });
|
|
171
|
+
return { realm, state: "abandonable", staged: stages.length, discards: stages.reduce((sum, stage) => sum + stage.size, 0) };
|
|
172
|
+
}
|
|
173
|
+
if (!intent) return { realm, state: "none", nextStep: "no admission intent is retained for this realm" };
|
|
174
|
+
readRealmProof(home, intent); // A malformed retained proof is not a clean abandon preview.
|
|
175
|
+
if (hasRealmProofStage(home, intent)) {
|
|
176
|
+
try {
|
|
177
|
+
if (!inspectRealmProofStage(home, intent)) return { realm, state: "unavailable", sequence: intent.sequence };
|
|
178
|
+
} catch { return { realm, state: "unavailable", sequence: intent.sequence }; }
|
|
179
|
+
}
|
|
180
|
+
const history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: () => true });
|
|
181
|
+
if (history.records.length + 1 > intent.sequence) return { realm, state: "committed", sequence: intent.sequence, nextStep: "amem migrate --sync-placement --admit <project> --resume" };
|
|
182
|
+
if (history.records.length + 1 < intent.sequence || history.headHash !== intent.previousHash
|
|
183
|
+
|| history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash)
|
|
184
|
+
return { realm, state: "unavailable", sequence: intent.sequence };
|
|
185
|
+
if (history.torn.length && !attributeTornRealmAppend(home, binding, { prefix: history.logBytes, tail: history.torn, sequence: intent.sequence, headHash: history.headHash }))
|
|
186
|
+
return { realm, state: "unavailable", sequence: intent.sequence };
|
|
187
|
+
return { realm, state: "abandonable", sequence: intent.sequence, discards: history.torn.length };
|
|
188
|
+
} catch (error) { return rethrow(error); }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The intent is the frozen review: position, anchors and proofs, plus the target the person named. */
|
|
192
|
+
function intentFor(home: string, project: string, next: RealmAdmissionNext, binding: RealmExtensionBinding): RealmIntent {
|
|
193
|
+
const machine = machineIdentity(home), existing = next.mode === "existing";
|
|
194
|
+
return createRealmIntent({ schema: REALM_INTENT_SCHEMA, home, project, keyHash: digest(project), machine: machine.id,
|
|
195
|
+
epochHash: binding.epochHash, activationHash: binding.activationHash, homeHash: binding.homeHash, generation: binding.generation,
|
|
196
|
+
sequence: next.sequence, previousHash: next.previousHash, previousLogBytes: next.previousLogBytes, previousLogHash: next.previousLogHash,
|
|
197
|
+
mode: next.mode, descriptorHash: existing ? next.descriptorHash! : null, sourceHash: existing ? next.sourceHash! : null,
|
|
198
|
+
aliasesHash: next.aliasesHash, policyHash: next.policyHash, writerHash: next.writerHash, journal: next.journal });
|
|
199
|
+
}
|
|
200
|
+
/** `realm.bindingHash` is the one field the intent omits, so a record can never be rebuilt from an intent alone. */
|
|
201
|
+
function recordFor(intent: RealmIntent, capturedBinding: string, sourceHash: string): RealmExtension {
|
|
202
|
+
return createRealmExtension({ schema: REALM_EXTENSION_SCHEMA, epochHash: intent.epochHash, activationHash: intent.activationHash,
|
|
203
|
+
homeHash: intent.homeHash, generation: intent.generation, sequence: intent.sequence, previousHash: intent.previousHash,
|
|
204
|
+
realm: { scope: "project", keyHash: intent.keyHash, bindingHash: capturedBinding },
|
|
205
|
+
sourceHash: intent.sourceHash ?? sourceHash, aliasesHash: intent.aliasesHash, policyHash: intent.policyHash,
|
|
206
|
+
writerHash: intent.writerHash, journal: intent.journal });
|
|
207
|
+
}
|
|
208
|
+
/** The seal already occupying the intent's position, or undefined while that position is still free. */
|
|
209
|
+
function installedSeal(home: string, binding: RealmExtensionBinding, intent: RealmIntent): string | undefined {
|
|
210
|
+
let history: RealmExtensionHistory;
|
|
211
|
+
try { history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding) }); } catch { return undefined; }
|
|
212
|
+
const existing = history.records[intent.sequence - 1];
|
|
213
|
+
if (!existing) return undefined;
|
|
214
|
+
if (existing.previousHash !== intent.previousHash || existing.realm.keyHash !== intent.keyHash) fail("committed");
|
|
215
|
+
return existing.seal;
|
|
216
|
+
}
|
|
217
|
+
/** Anchors frozen by the intent must still be ancestors of the live history, or the record could never be folded. */
|
|
218
|
+
function assertAnchors(home: string, binding: RealmExtensionBinding, intent: RealmIntent): void {
|
|
219
|
+
const journal = readPlacementWriterJournalAnchors(home, binding.epochHash);
|
|
220
|
+
if (journal.epoch.homeHash !== binding.homeHash || journal.activation.seal !== binding.activationHash
|
|
221
|
+
|| journal.sequence < intent.journal.sequence
|
|
222
|
+
|| (intent.journal.sequence ? journal.records[intent.journal.sequence - 1]?.seal : binding.epochHash) !== intent.journal.headHash) fail("committed");
|
|
223
|
+
const heads = [writerInventoryGenesis(binding.epochHash, binding.activationHash), ...readWriterHistory(home, writerBinding(binding)).commits.map(commit => commit.seal)];
|
|
224
|
+
if (!heads.includes(intent.writerHash)) fail("committed");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export async function applyRealmAdmission(homeInput: string, project: string, options: RealmAdmissionOptions): Promise<RealmAdmissionResult> {
|
|
228
|
+
let home: string;
|
|
229
|
+
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
|
+
const realm = digest(project), projectPrefix = realm.slice(0, 16);
|
|
231
|
+
if (options.mode === "abandon") {
|
|
232
|
+
const plan = planRealmAbandon(home, project);
|
|
233
|
+
if (plan.state === "none") return { mode: "abandon", state: "already-admitted", realm, nextStep: plan.nextStep };
|
|
234
|
+
if (plan.state !== "abandonable") fail(plan.state === "committed" ? "committed" : "metadata");
|
|
235
|
+
if (options.confirm !== true) return { mode: "abandon", state: "retained", realm, sequence: plan.sequence, discarded: plan.discards,
|
|
236
|
+
...(plan.staged ? { staged: plan.staged } : {}), nextStep: "confirm amem migrate --sync-placement --admit <project> --abandon --confirm" };
|
|
237
|
+
const stages = plan.staged ? inspectRealmIntentStages(home, realm) : undefined;
|
|
238
|
+
if (plan.staged && stages?.length !== plan.staged) fail("changed");
|
|
239
|
+
return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
240
|
+
try {
|
|
241
|
+
const binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
|
|
242
|
+
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); }, proof = { mutation, assertCurrent: check };
|
|
243
|
+
if (stages) {
|
|
244
|
+
readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: evidence => attributeTornRealmAppend(home, binding, evidence) });
|
|
245
|
+
clearRealmIntentStages(home, realm, stages, proof);
|
|
246
|
+
return { mode: "abandon" as const, state: "abandoned" as const, realm, staged: stages.length,
|
|
247
|
+
discarded: stages.reduce((sum, stage) => sum + stage.size, 0), nextStep: intent
|
|
248
|
+
? "amem migrate --sync-placement --admit <project> --resume" : "amem migrate --sync-placement --admit <project> --dry-run" };
|
|
249
|
+
}
|
|
250
|
+
if (!intent) return fail("changed");
|
|
251
|
+
const { discarded } = discardRealmExtensionTail(home, binding, intent, proof);
|
|
252
|
+
clearRealmProof(home, intent, proof);
|
|
253
|
+
clearRealmIntent(home, intent, proof);
|
|
254
|
+
return { mode: "abandon" as const, state: "abandoned" as const, realm, sequence: intent.sequence, discarded,
|
|
255
|
+
nextStep: "amem migrate --sync-placement --admit <project> --dry-run" };
|
|
256
|
+
} catch (error) { return rethrow(error); }
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (options.mode === "apply") assertNoPendingAdmission(home);
|
|
260
|
+
const planned = options.mode === "apply" ? inspectRealmAdmission(home, project) : undefined;
|
|
261
|
+
if (planned?.state === "already-admitted") return { mode: options.mode, state: "already-admitted", realm };
|
|
262
|
+
if (planned?.state === "unavailable") fail("metadata");
|
|
263
|
+
if (options.mode === "resume" && !readRealmIntent(home, realm)) {
|
|
264
|
+
if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted", realm };
|
|
265
|
+
throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
|
|
266
|
+
}
|
|
267
|
+
return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
268
|
+
try {
|
|
269
|
+
if (options.mode === "apply") assertNoPendingAdmission(home);
|
|
270
|
+
if (options.mode === "resume") assertNoPendingAdmission(home, realm);
|
|
271
|
+
const binding = realmBinding(activeBinding(home));
|
|
272
|
+
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); }, proof = { mutation, assertCurrent: check };
|
|
273
|
+
let intent = readRealmIntent(home, realm);
|
|
274
|
+
if (intent && options.mode === "apply") fail("pending");
|
|
275
|
+
if (!intent && options.mode === "resume") {
|
|
276
|
+
if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted" as const, realm };
|
|
277
|
+
throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
|
|
278
|
+
}
|
|
279
|
+
if (intent) {
|
|
280
|
+
assertAnchors(home, binding, intent);
|
|
281
|
+
const committed = installedSeal(home, binding, intent);
|
|
282
|
+
if (committed !== undefined) {
|
|
283
|
+
const evidence = readRealmProof(home, intent);
|
|
284
|
+
if (!evidence || evidence.seal !== committed) fail("committed");
|
|
285
|
+
clearRealmIntent(home, intent, proof);
|
|
286
|
+
return { mode: options.mode, state: "admitted" as const, realm, sequence: intent.sequence, headHash: committed, created: false };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
// Stored writer hashes are history, not current install evidence. Re-measure the existing active writer inventory under the fences.
|
|
290
|
+
const writer = activePlacementWriterContext(home, fileURLToPath(new URL("../..", import.meta.url)));
|
|
291
|
+
const current = () => { check(); writer.attest(); check(); };
|
|
292
|
+
current();
|
|
293
|
+
if (!intent) {
|
|
294
|
+
// Apply re-reads every fact it acts on under this fence; the earlier report only named the state.
|
|
295
|
+
const fixed = inspectRealmAdmission(home, project, owner);
|
|
296
|
+
if (fixed.state === "already-admitted") return { mode: options.mode, state: "already-admitted" as const, realm };
|
|
297
|
+
if (!fixed.next) fail("metadata");
|
|
298
|
+
intent = intentFor(home, project, fixed.next, binding);
|
|
299
|
+
writeRealmIntent(home, intent, { mutation, assertCurrent: current });
|
|
300
|
+
await options.checkpoint?.("after-intent");
|
|
301
|
+
}
|
|
302
|
+
const frozen = intent;
|
|
303
|
+
// A new realm's intent has no sourceHash; a partial proof cannot prove the original source snapshot after restart.
|
|
304
|
+
if (options.mode === "resume" && frozen.mode === "new" && hasRealmProofStage(home, frozen)) fail("pending");
|
|
305
|
+
current();
|
|
306
|
+
const created = ensureCuratedRealmMetadata(home, project, binding.generation, machineIdentity(home)).created;
|
|
307
|
+
await options.checkpoint?.("after-metadata");
|
|
308
|
+
const source = previewOwnedSyncPlacementSources(home, owner);
|
|
309
|
+
const captured = source.base.realms.find(item => item.scope === "project" && item.keyHash === realm);
|
|
310
|
+
if (!captured) fail("changed");
|
|
311
|
+
// A frozen curated descriptor or source proof that moved since the review re-reads, never appends.
|
|
312
|
+
const descriptor = readShardDescriptor(home, realm.slice(0, 16));
|
|
313
|
+
if (frozen.descriptorHash !== null && (!descriptor || hashJSON(descriptor) !== frozen.descriptorHash)) fail("changed");
|
|
314
|
+
if (frozen.mode === "existing" && source.base.sourceHash !== frozen.sourceHash) fail("changed");
|
|
315
|
+
if (source.base.aliasesHash !== frozen.aliasesHash || source.base.policyHash !== frozen.policyHash) fail("changed");
|
|
316
|
+
const record = recordFor(frozen, captured.bindingHash, source.base.sourceHash);
|
|
317
|
+
const sourceProof = { mutation, assertCurrent: () => { current(); source.assertSourcesUnchanged(); current(); } };
|
|
318
|
+
writeRealmProof(home, frozen, record, sourceProof);
|
|
319
|
+
await options.checkpoint?.("after-proof");
|
|
320
|
+
const durableProof = { mutation, assertCurrent: () => {
|
|
321
|
+
sourceProof.assertCurrent();
|
|
322
|
+
if (readRealmProof(home, frozen)?.seal !== record.seal) fail("changed");
|
|
323
|
+
sourceProof.assertCurrent();
|
|
324
|
+
} };
|
|
325
|
+
appendRealmExtension(home, binding, frozen, record, durableProof);
|
|
326
|
+
await options.checkpoint?.("after-append");
|
|
327
|
+
clearRealmIntent(home, frozen, proof);
|
|
328
|
+
return { mode: options.mode, state: "admitted" as const, realm, sequence: frozen.sequence, headHash: record.seal, created };
|
|
329
|
+
} catch (error) { return rethrow(error); }
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function directories(home: string, projectPrefix: string): string[] {
|
|
333
|
+
const realmDir = join(home, "projects", projectPrefix);
|
|
334
|
+
return existsSync(realmDir) ? [realmDir] : [];
|
|
335
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Attribute an incomplete extension append to a frozen admission intent; the tail itself is never folded into the chain. */
|
|
2
|
+
import { realPath } from "./platform.ts";
|
|
3
|
+
import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
|
|
4
|
+
import { realmIntentEvidence } from "./sync-placement-realm-intent-storage.ts";
|
|
5
|
+
import { readRealmProof } from "./sync-placement-realm-proof.ts";
|
|
6
|
+
import { verifyTornRealmAppend } from "./sync-placement-realm-torn.ts";
|
|
7
|
+
import type { RealmExtensionBinding, RealmTornEvidence } from "./sync-placement-realm-extension-storage.ts";
|
|
8
|
+
/** True only when a pending admission of this epoch pins this exact prefix, position and head; anything else leaves the chain closed. */
|
|
9
|
+
export function attributeTornRealmAppend(home: string, binding: RealmExtensionBinding, evidence: RealmTornEvidence): boolean {
|
|
10
|
+
try {
|
|
11
|
+
const root = realPath(home), pending = pendingRealmInventory(root);
|
|
12
|
+
if (pending.unknown) return false;
|
|
13
|
+
return pending.hashes.some(keyHash => {
|
|
14
|
+
try {
|
|
15
|
+
const intent = realmIntentEvidence(root, keyHash); if (!intent) return false;
|
|
16
|
+
if (intent.epochHash !== binding.epochHash || intent.activationHash !== binding.activationHash || intent.homeHash !== binding.homeHash
|
|
17
|
+
|| intent.generation !== binding.generation || intent.sequence !== evidence.sequence || intent.previousHash !== evidence.headHash) return false;
|
|
18
|
+
const record = readRealmProof(root, intent); if (!record) return false;
|
|
19
|
+
return verifyTornRealmAppend(Buffer.concat([evidence.prefix, evidence.tail]), intent, record).equals(evidence.prefix);
|
|
20
|
+
} catch { return false; }
|
|
21
|
+
});
|
|
22
|
+
} catch { return false; }
|
|
23
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Effective same-epoch realm inventory; serialized evidence is not fresh writer or policy authority. */
|
|
2
|
+
import { canonicalJSON } from "./generation.ts";
|
|
3
|
+
import { readPlacementWriterJournalAnchors, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
|
|
4
|
+
import { readWriterHistory } from "./sync-placement-writer-history.ts";
|
|
5
|
+
import { writerInventoryGenesis } from "./sync-placement-writer-revision-format.ts";
|
|
6
|
+
import { readRealmExtensionHistory } from "./sync-placement-realm-extension-storage.ts";
|
|
7
|
+
import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
|
|
8
|
+
import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
|
|
9
|
+
import { realmIntentEvidence } from "./sync-placement-realm-intent-storage.ts";
|
|
10
|
+
import { RealmExtensionFormatError, realmExtensionGenesis } from "./sync-placement-realm-extension-format.ts";
|
|
11
|
+
import type { ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
12
|
+
import type { SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
|
|
13
|
+
|
|
14
|
+
export interface EffectiveRealmInventory { realms: readonly SyncPlacementRealmBinding[]; extensionHead: string; assertCurrent(): void }
|
|
15
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
16
|
+
/** The immutable epoch facts the chain is verified against. A caller holding a validated journal supplies them directly,
|
|
17
|
+
* so the chain is verified by the same code with or without the activation marker files on hand. */
|
|
18
|
+
export interface EffectiveRealmBinding { epochHash: string; activationHash: string; homeHash: string; generation: string; realms: readonly SyncPlacementRealmBinding[] }
|
|
19
|
+
/** A zero-byte extension log is this epoch's pre-write state only while an intent for the same epoch and activation is
|
|
20
|
+
* retained; unknown evidence never authorizes the recovery. */
|
|
21
|
+
export function retainedAdmissionCoversEmptyLog(home: string, epochHash: string, activationHash: string): boolean {
|
|
22
|
+
const pending = pendingRealmInventory(home);
|
|
23
|
+
if (pending.unknown) return false;
|
|
24
|
+
return pending.hashes.some(keyHash => {
|
|
25
|
+
const intent = realmIntentEvidence(home, keyHash);
|
|
26
|
+
return !!intent && intent.epochHash === epochHash && intent.activationHash === activationHash;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** Validate the complete extension chain against both immutable activation and committed historical prefixes. */
|
|
30
|
+
export function readEffectiveRealmInventory(home: string, active: ActivePlacementBinding): EffectiveRealmInventory {
|
|
31
|
+
return readEffectiveRealmInventoryFor(home, { epochHash: active.profile.placementHead, activationHash: active.activation.seal,
|
|
32
|
+
homeHash: active.epoch.homeHash, generation: active.epoch.generation, realms: active.activation.realms });
|
|
33
|
+
}
|
|
34
|
+
export function readEffectiveRealmInventoryFor(home: string, binding: EffectiveRealmBinding): EffectiveRealmInventory {
|
|
35
|
+
try {
|
|
36
|
+
const { epochHash, activationHash, homeHash, generation, realms: activated } = binding;
|
|
37
|
+
const initialProjectHashes = activated.flatMap(realm => realm.scope === "project" ? [realm.keyHash] : []);
|
|
38
|
+
// A stop between creating the extension log and its first append leaves a zero-byte file: recover it as the
|
|
39
|
+
// pre-write state while the admission that authorized the append is retained.
|
|
40
|
+
const allowEmptyLog = retainedAdmissionCoversEmptyLog(home, epochHash, activationHash);
|
|
41
|
+
const extensions = readRealmExtensionHistory(home, { epochHash, activationHash, homeHash,
|
|
42
|
+
generation, initialProjectHashes }, { allowEmptyLog, attributeTorn: evidence => attributeTornRealmAppend(home, {
|
|
43
|
+
epochHash, activationHash, homeHash, generation, initialProjectHashes }, evidence) });
|
|
44
|
+
if (!extensions.records.length) return { realms: activated, extensionHead: realmExtensionGenesis(epochHash, activationHash), assertCurrent: extensions.assertCurrent };
|
|
45
|
+
const token = placementWriterJournalToken(home, epochHash), journal = readPlacementWriterJournalAnchors(home, epochHash);
|
|
46
|
+
if (journal.epoch.homeHash !== homeHash || journal.activation.seal !== activationHash) return fail();
|
|
47
|
+
const writers = readWriterHistory(home, { epochHash, activationHash, homeHash, generation });
|
|
48
|
+
const writerHeads = [writerInventoryGenesis(epochHash, activationHash), ...writers.commits.map(commit => commit.seal)];
|
|
49
|
+
let priorWriter = 0;
|
|
50
|
+
for (const record of extensions.records) {
|
|
51
|
+
const writerIndex = writerHeads.indexOf(record.writerHash);
|
|
52
|
+
if (writerIndex < priorWriter || writerIndex < 0 || record.journal.sequence > journal.sequence
|
|
53
|
+
|| (record.journal.sequence ? journal.records[record.journal.sequence - 1]?.seal : epochHash) !== record.journal.headHash) return fail();
|
|
54
|
+
if (writerIndex > 0 && writers.anchors[writerIndex - 1]!.sequence > record.journal.sequence) return fail();
|
|
55
|
+
priorWriter = writerIndex;
|
|
56
|
+
}
|
|
57
|
+
const realms = [...activated, ...extensions.records.map(record => record.realm)];
|
|
58
|
+
if (realms.length > 256) return fail();
|
|
59
|
+
realms.sort((a, b) => a.scope === "user" ? b.scope === "user" ? 0 : -1 : b.scope === "user" ? 1 : a.keyHash.localeCompare(b.keyHash));
|
|
60
|
+
for (const realm of realms) Object.freeze(realm);
|
|
61
|
+
Object.freeze(realms);
|
|
62
|
+
const snapshot = canonicalJSON(realms);
|
|
63
|
+
const assertCurrent = () => {
|
|
64
|
+
try {
|
|
65
|
+
extensions.assertCurrent(); writers.assertCurrent();
|
|
66
|
+
if (placementWriterJournalToken(home, epochHash) !== token || canonicalJSON(realms) !== snapshot) fail();
|
|
67
|
+
} catch { fail(); }
|
|
68
|
+
};
|
|
69
|
+
assertCurrent(); return { realms, extensionHead: extensions.headHash, assertCurrent };
|
|
70
|
+
} catch { return fail(); }
|
|
71
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Closed, data-only same-epoch realm extension records. A seal is not authorization or fresh proof. */
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
4
|
+
|
|
5
|
+
export const REALM_EXTENSION_SCHEMA = "agent-mem.sync-placement-realm-extension/v1";
|
|
6
|
+
export const REALM_EXTENSION_LIMIT = 64;
|
|
7
|
+
export const REALM_EXTENSION_LOG_MAX_BYTES = 64 * 1024;
|
|
8
|
+
export const REALM_RECORD_MAX_BYTES = 4096;
|
|
9
|
+
|
|
10
|
+
export interface RealmExtensionBody {
|
|
11
|
+
schema: typeof REALM_EXTENSION_SCHEMA;
|
|
12
|
+
epochHash: string;
|
|
13
|
+
activationHash: string;
|
|
14
|
+
homeHash: string;
|
|
15
|
+
generation: string;
|
|
16
|
+
sequence: number;
|
|
17
|
+
previousHash: string;
|
|
18
|
+
realm: { scope: "project"; keyHash: string; bindingHash: string };
|
|
19
|
+
sourceHash: string;
|
|
20
|
+
aliasesHash: string;
|
|
21
|
+
policyHash: string;
|
|
22
|
+
writerHash: string;
|
|
23
|
+
journal: { sequence: number; headHash: string };
|
|
24
|
+
}
|
|
25
|
+
export interface RealmExtension extends RealmExtensionBody { seal: string }
|
|
26
|
+
|
|
27
|
+
export class RealmExtensionFormatError extends Error {
|
|
28
|
+
constructor() { super("sync placement realm extension metadata is invalid or exceeds its supported bounds; retain it for inspection"); this.name = "RealmExtensionFormatError"; }
|
|
29
|
+
}
|
|
30
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
31
|
+
function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
|
|
32
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
|
|
33
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return fail();
|
|
34
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
35
|
+
if (Object.keys(fields).length !== keys.length || Object.getOwnPropertyNames(value).length !== keys.length) return fail();
|
|
36
|
+
const copy: Record<string, unknown> = Object.create(null);
|
|
37
|
+
for (const key of keys) { const field = fields[key]; if (!field || !("value" in field) || !field.enumerable) return fail(); copy[key] = field.value; }
|
|
38
|
+
return copy;
|
|
39
|
+
}
|
|
40
|
+
function hex(value: unknown, width = 64): string {
|
|
41
|
+
if (typeof value !== "string" || value.length !== width || !/^[a-f0-9]+$/.test(value)) return fail(); return value;
|
|
42
|
+
}
|
|
43
|
+
function integer(value: unknown, min: number, max: number): number {
|
|
44
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) return fail(); return value;
|
|
45
|
+
}
|
|
46
|
+
/** The original activation seal anchors the first appended extension, without changing it. */
|
|
47
|
+
export function realmExtensionGenesis(epochHash: string, activationHash: string): string {
|
|
48
|
+
return hashJSON(["agent-mem.sync-placement-realm-genesis/v1", hex(epochHash), hex(activationHash)]);
|
|
49
|
+
}
|
|
50
|
+
function checked(input: unknown, sealed: boolean): RealmExtension {
|
|
51
|
+
const row = object(input, ["schema", "epochHash", "activationHash", "homeHash", "generation", "sequence", "previousHash", "realm", "sourceHash", "aliasesHash", "policyHash", "writerHash", "journal", ...(sealed ? ["seal"] : [])]);
|
|
52
|
+
const realm = object(row.realm, ["scope", "keyHash", "bindingHash"]), journal = object(row.journal, ["sequence", "headHash"]);
|
|
53
|
+
if (row.schema !== REALM_EXTENSION_SCHEMA || realm.scope !== "project") return fail();
|
|
54
|
+
const body: RealmExtensionBody = { schema: REALM_EXTENSION_SCHEMA, epochHash: hex(row.epochHash), activationHash: hex(row.activationHash), homeHash: hex(row.homeHash),
|
|
55
|
+
generation: hex(row.generation, 32), sequence: integer(row.sequence, 1, REALM_EXTENSION_LIMIT), previousHash: hex(row.previousHash),
|
|
56
|
+
realm: { scope: "project", keyHash: hex(realm.keyHash), bindingHash: hex(realm.bindingHash) },
|
|
57
|
+
sourceHash: hex(row.sourceHash), aliasesHash: hex(row.aliasesHash), policyHash: hex(row.policyHash), writerHash: hex(row.writerHash),
|
|
58
|
+
journal: { sequence: integer(journal.sequence, 0, 20_000), headHash: hex(journal.headHash) } };
|
|
59
|
+
if (body.sequence === 1 && body.previousHash !== realmExtensionGenesis(body.epochHash, body.activationHash)
|
|
60
|
+
|| body.journal.sequence === 0 && body.journal.headHash !== body.epochHash) return fail();
|
|
61
|
+
const result = { ...body, seal: hashJSON(body) };
|
|
62
|
+
if (sealed && hex(row.seal) !== result.seal || Buffer.byteLength(canonicalJSON(result) + "\n") > REALM_RECORD_MAX_BYTES) return fail();
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
export function createRealmExtension(input: RealmExtensionBody): RealmExtension { return checked(input, false); }
|
|
66
|
+
export function validateRealmExtension(input: unknown): RealmExtension { return checked(input, true); }
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Read the separate same-epoch extension chain without changing activation or acquiring a writer lease. */
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { canonicalJSON } from "./generation.ts";
|
|
5
|
+
import { homeIdentityMatches } from "./home-identity.ts";
|
|
6
|
+
import { realPath } from "./platform.ts";
|
|
7
|
+
import { REALM_EXTENSION_LIMIT, REALM_EXTENSION_LOG_MAX_BYTES, RealmExtensionFormatError, realmExtensionGenesis,
|
|
8
|
+
validateRealmExtension, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
9
|
+
|
|
10
|
+
export const REALM_EXTENSION_LOG = "placement-realm-extensions.jsonl";
|
|
11
|
+
export interface RealmExtensionBinding { epochHash: string; activationHash: string; homeHash: string; generation: string; initialProjectHashes: readonly string[] }
|
|
12
|
+
export interface RealmExtensionHistory { records: readonly RealmExtension[]; headHash: string; torn: Buffer; logBytes: Buffer; assertCurrent(): void }
|
|
13
|
+
/** A tail is attributed to the position it would occupy, so only evidence for that exact append can vouch for it. */
|
|
14
|
+
export interface RealmTornEvidence { prefix: Buffer; tail: Buffer; sequence: number; headHash: string }
|
|
15
|
+
export interface RealmExtensionOptions {
|
|
16
|
+
attributeTorn?: (evidence: RealmTornEvidence) => boolean;
|
|
17
|
+
/** A zero-byte log is the state a stop between creating the file and its first append leaves behind. It reads as the
|
|
18
|
+
* pre-write chain only while the intent that authorized that append is retained; without one it stays a refusal. */
|
|
19
|
+
allowEmptyLog?: boolean;
|
|
20
|
+
}
|
|
21
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
22
|
+
const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
|
|
23
|
+
function owned(stat: BigIntStats, directory: boolean): void {
|
|
24
|
+
if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1)
|
|
25
|
+
|| (directory ? !stat.isDirectory() || (stat.mode & 0o077n) !== 0n : !stat.isFile() || stat.nlink !== 1n || (stat.mode & 0o777n) !== 0o600n)) fail();
|
|
26
|
+
}
|
|
27
|
+
/** A modified or mismatched chain is unavailable. An incomplete final append is reported as `torn` and never folded, but only when `attributeTorn` vouches for it, so an interrupted admission keeps existing realms syncing while any unattributed tail still closes the chain. */
|
|
28
|
+
export function readRealmExtensionHistory(homeInput: string, binding: RealmExtensionBinding, options: RealmExtensionOptions = {}): RealmExtensionHistory {
|
|
29
|
+
try { return readHistory(homeInput, binding, options); } catch { return fail(); }
|
|
30
|
+
}
|
|
31
|
+
function readHistory(homeInput: string, binding: RealmExtensionBinding, options: RealmExtensionOptions): RealmExtensionHistory {
|
|
32
|
+
const home = realPath(homeInput), original = lstatSync(homeInput, { bigint: true }), root = lstatSync(home, { bigint: true });
|
|
33
|
+
owned(original, true); owned(root, true);
|
|
34
|
+
if (original.dev !== root.dev || original.ino !== root.ino || !homeIdentityMatches(binding.homeHash, home, root)) return fail();
|
|
35
|
+
const file = join(home, REALM_EXTENSION_LOG), before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
36
|
+
const checks = () => { try {
|
|
37
|
+
const nowHome = lstatSync(home, { bigint: true }), nowOriginal = lstatSync(homeInput, { bigint: true });
|
|
38
|
+
owned(nowHome, true); owned(nowOriginal, true);
|
|
39
|
+
if (nowHome.dev !== root.dev || nowHome.ino !== root.ino || nowOriginal.dev !== original.dev || nowOriginal.ino !== original.ino) fail();
|
|
40
|
+
const now = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
41
|
+
if (!before) { if (now) fail(); return; }
|
|
42
|
+
if (!now) return fail(); owned(now, false); if (stamp(now) !== stamp(before)) fail();
|
|
43
|
+
} catch { fail(); } };
|
|
44
|
+
const genesis = realmExtensionGenesis(binding.epochHash, binding.activationHash);
|
|
45
|
+
if (!before) return { records: [], headHash: genesis, torn: Buffer.alloc(0), logBytes: Buffer.alloc(0), assertCurrent: checks };
|
|
46
|
+
owned(before, false); if (before.size > BigInt(REALM_EXTENSION_LOG_MAX_BYTES)) return fail();
|
|
47
|
+
// A zero-byte log is the pre-write state of a retained admission, not a damaged chain: recover it instead of asking a
|
|
48
|
+
// person to delete a file. With no retained intent it is unknown evidence and still refuses.
|
|
49
|
+
if (before.size === 0n) {
|
|
50
|
+
if (!options.allowEmptyLog) return fail();
|
|
51
|
+
checks(); return { records: [], headHash: genesis, torn: Buffer.alloc(0), logBytes: Buffer.alloc(0), assertCurrent: checks };
|
|
52
|
+
}
|
|
53
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
54
|
+
let bytes: Buffer;
|
|
55
|
+
try {
|
|
56
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened, false); if (stamp(opened) !== stamp(before)) return fail();
|
|
57
|
+
const data = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
58
|
+
while (at < data.length) { const n = readSync(fd, data, at, data.length - at, at); if (!n) break; at += n; }
|
|
59
|
+
if (at !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened)) return fail();
|
|
60
|
+
bytes = data.subarray(0, at);
|
|
61
|
+
} finally { closeSync(fd); }
|
|
62
|
+
checks();
|
|
63
|
+
const cut = bytes.lastIndexOf(10), torn = Buffer.from(bytes.subarray(cut + 1));
|
|
64
|
+
const complete = cut < 0 ? "" : new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, cut));
|
|
65
|
+
const lines = complete.length ? complete.split("\n") : []; if (lines.length > REALM_EXTENSION_LIMIT) return fail();
|
|
66
|
+
const records: RealmExtension[] = [], seen = new Set(binding.initialProjectHashes), prefixes = new Set(binding.initialProjectHashes.map(hash => hash.slice(0, 16)));
|
|
67
|
+
if (prefixes.size !== binding.initialProjectHashes.length) return fail();
|
|
68
|
+
let head = genesis, journalSequence = 0, journalHead = binding.epochHash;
|
|
69
|
+
for (const [index, line] of lines.entries()) {
|
|
70
|
+
const record = validateRealmExtension(JSON.parse(line));
|
|
71
|
+
if (canonicalJSON(record) !== line || record.sequence !== index + 1 || record.previousHash !== head
|
|
72
|
+
|| record.epochHash !== binding.epochHash || record.activationHash !== binding.activationHash || record.homeHash !== binding.homeHash
|
|
73
|
+
|| record.generation !== binding.generation || seen.has(record.realm.keyHash) || prefixes.has(record.realm.keyHash.slice(0, 16))
|
|
74
|
+
|| record.journal.sequence < journalSequence || record.journal.sequence === journalSequence && record.journal.headHash !== journalHead) return fail();
|
|
75
|
+
seen.add(record.realm.keyHash); prefixes.add(record.realm.keyHash.slice(0, 16)); head = record.seal;
|
|
76
|
+
journalSequence = record.journal.sequence; journalHead = record.journal.headHash;
|
|
77
|
+
Object.freeze(record.realm); Object.freeze(record.journal); records.push(Object.freeze(record));
|
|
78
|
+
}
|
|
79
|
+
const prefix = Buffer.from(bytes.subarray(0, cut + 1));
|
|
80
|
+
if (torn.length && !options.attributeTorn?.({ prefix, tail: torn, sequence: records.length + 1, headHash: head })) return fail();
|
|
81
|
+
checks(); return { records: Object.freeze(records), headHash: head, torn, logBytes: prefix, assertCurrent: checks };
|
|
82
|
+
}
|