@staix/agent-mem 0.28.2 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +17 -11
  3. package/package.json +3 -2
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +97 -17
  6. package/src/commands-table.ts +6 -0
  7. package/src/mcp-memory.ts +37 -9
  8. package/src/memory/bridge.ts +26 -1
  9. package/src/memory/capacity.ts +5 -2
  10. package/src/memory/catalog.ts +10 -1
  11. package/src/memory/commands.ts +5 -3
  12. package/src/memory/curated-cache-state.ts +10 -7
  13. package/src/memory/doctor.ts +32 -26
  14. package/src/memory/formats.ts +4 -3
  15. package/src/memory/generation-index.ts +79 -17
  16. package/src/memory/index-file.ts +2 -2
  17. package/src/memory/intent-brief.ts +34 -6
  18. package/src/memory/metrics.ts +174 -14
  19. package/src/memory/shard-bridge.ts +18 -6
  20. package/src/memory/shard-sync-format.ts +18 -0
  21. package/src/memory/shard-sync-history.ts +6 -0
  22. package/src/memory/shard-sync.ts +52 -4
  23. package/src/memory/shard.ts +33 -13
  24. package/src/memory/store.ts +147 -41
  25. package/src/memory/sync-placement-bound.ts +21 -4
  26. package/src/memory/sync-placement-cache.ts +16 -1
  27. package/src/memory/sync-placement-capture.ts +67 -19
  28. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  29. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  30. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  31. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  32. package/src/memory/sync-placement-checkpoint.ts +234 -0
  33. package/src/memory/sync-placement-dependencies.ts +42 -9
  34. package/src/memory/sync-placement-effective-writers.ts +12 -6
  35. package/src/memory/sync-placement-git.ts +17 -7
  36. package/src/memory/sync-placement-guard.ts +52 -1
  37. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  38. package/src/memory/sync-placement-inventory.ts +141 -0
  39. package/src/memory/sync-placement-journal-format.ts +4 -1
  40. package/src/memory/sync-placement-journal-storage.ts +148 -28
  41. package/src/memory/sync-placement-journal.ts +13 -4
  42. package/src/memory/sync-placement-materialize.ts +47 -22
  43. package/src/memory/sync-placement-projection.ts +7 -1
  44. package/src/memory/sync-placement-publication-events.ts +42 -0
  45. package/src/memory/sync-placement-publication-plan.ts +26 -5
  46. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  47. package/src/memory/sync-placement-realm-admission.ts +352 -0
  48. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  49. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  50. package/src/memory/sync-placement-realm-effective.ts +71 -0
  51. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  52. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  53. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  54. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  55. package/src/memory/sync-placement-realm-pending.ts +27 -0
  56. package/src/memory/sync-placement-realm-proof.ts +131 -0
  57. package/src/memory/sync-placement-realm-torn.ts +26 -0
  58. package/src/memory/sync-placement-remote-admission.ts +190 -0
  59. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  60. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  61. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  62. package/src/memory/sync-placement-remote-stage.ts +275 -0
  63. package/src/memory/sync-placement-transport.ts +268 -79
  64. package/src/memory/sync-placement-writer-history.ts +75 -17
  65. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  66. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  67. package/src/memory/sync-placement-yield.ts +44 -0
  68. package/src/memory/sync-progress.ts +47 -6
  69. package/src/memory/sync.ts +26 -1
  70. package/src/memory/work-lists.ts +129 -9
  71. package/src/session-brief.ts +34 -1
  72. package/src/sync-placement-writer-context.ts +5 -5
  73. package/src/ui/plugin.ts +1 -1
@@ -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,18 +151,38 @@ 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
- let selected: PlacementPublicationChunk["items"] = [];
156
- const flush = () => { if (selected.length) { chunks.push(validatePlacementPublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: selected })); selected = []; } };
170
+ let selected: PlacementPublicationChunk["items"] = [], selectedBytes = 0;
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)) {
158
- const row = item(kind, value), candidate = { schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: [...selected, row] };
159
- if (publicationBytes(candidate).length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) flush(); selected.push(row);
173
+ if (++stepped >= STEP_ITEMS) { stepped = 0; yield; }
174
+ // #462: the candidate chunk's exact canonical size, summed per item instead of re-serializing the whole chunk per row
175
+ // (quadratic). canonicalJSON of an array is its items' canonical forms joined by commas, so the sum is identical.
176
+ const row = item(kind, value), rowBytes = Buffer.byteLength(canonicalJSON(row));
177
+ const empty = publicationBytes({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: [] }).length;
178
+ if (empty + selectedBytes + (selected.length ? 1 : 0) + rowBytes > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) flush();
179
+ selectedBytes += (selected.length ? 1 : 0) + rowBytes; selected.push(row);
160
180
  }
161
181
  flush();
162
182
  }
163
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,
164
- chunks: chunks.map(c => ({ kind: c.kind, index: c.index, hash: publicationHash(publicationBytes(c)), count: c.items.length, bytes: publicationBytes(c).length })) };
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 }; }) };
165
186
  const { seal: _seal, ...safeBody } = normalizedRoot({ ...body, seal: "0".repeat(64) }, false);
166
187
  return validatePlacementPublicationBundle({ root: { ...safeBody, seal: hashJSON(safeBody) }, chunks });
167
188
  }
@@ -0,0 +1,128 @@
1
+ /** The two fenced writes of a person-reviewed realm admission: empty curated metadata, then the extension record. */
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { canonicalJSON, fsyncDirectory, generationDescriptor, hashJSON, readProfileJSON, writeProfileJSON } from "./generation.ts";
6
+ import { ensureShardDescriptor, assertCuratedShardLayout, shardDir } from "./shard.ts";
7
+ import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
8
+ import { REALM_EXTENSION_LIMIT, REALM_EXTENSION_LOG_MAX_BYTES, RealmExtensionFormatError, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
9
+ import { readRealmExtensionHistory, REALM_EXTENSION_LOG, type RealmExtensionBinding } from "./sync-placement-realm-extension-storage.ts";
10
+ import { retainedAdmissionCoversEmptyLog } from "./sync-placement-realm-effective.ts";
11
+ import type { RealmIntent } from "./sync-placement-realm-intent-format.ts";
12
+ import type { RealmIntentProof } from "./sync-placement-realm-intent-storage.ts";
13
+ import { verifyTornRealmAppend } from "./sync-placement-realm-torn.ts";
14
+
15
+ const fail = (): never => { throw new RealmExtensionFormatError(); };
16
+ const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
17
+ const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
18
+ const owned = (stat: BigIntStats): void => {
19
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o777n) !== 0o600n) fail();
20
+ };
21
+
22
+ /**
23
+ * Empty curated metadata at the fixed shard path, written so that every interruption leaves the realm `not-local`.
24
+ * `generation.json` is last: capture, 0.28.2 and the #450 inventory all read a project without it as a scaffold, so a
25
+ * crash after any earlier file creates nothing anyone acts on. The immutable source-proof companion (empty
26
+ * `migration-sources.json` plus `generation-seal.json`) precedes it for the same reason: a realm is never visible
27
+ * with `generation.json` but without the provenance capture revalidates.
28
+ */
29
+ export function ensureCuratedRealmMetadata(home: string, project: string, generation: string, machine: { id: string; label?: string }): { created: boolean } {
30
+ // Validate the fixed scaffold before the first write: a restored or received directory holding a symlinked `legacy` (or any
31
+ // other fixed path) must refuse here instead of receiving machine.json and generation.json in the symlink's destination
32
+ // ahead of a source-capture refusal. These are the same no-follow checks curated writes already apply; the inventory gate
33
+ // they usually sit behind belongs to the caller, because a realm being admitted is not in the inventory until it commits.
34
+ assertCuratedShardLayout(home, { project });
35
+ const dir = shardDir(home, project);
36
+ if (readProfileJSON(join(dir, "generation.json")) !== undefined) return { created: false };
37
+ ensureShardDescriptor(home, project);
38
+ for (const folder of ["log", "local", "legacy/log", "legacy/local", "legacy-main/log", "legacy-main/local"]) mkdirSync(join(dir, folder), { recursive: true, mode: 0o700 });
39
+ const identity = { id: machine.id, label: typeof machine.label === "string" ? machine.label : machine.id };
40
+ for (const path of ["machine.json", "legacy/machine.json", "legacy-main/machine.json"]) {
41
+ const file = join(dir, path), prior = readProfileJSON(file) as { id?: unknown } | undefined;
42
+ if (prior === undefined) writeProfileJSON(file, identity);
43
+ else if (prior?.id !== identity.id) fail();
44
+ }
45
+ const sources: unknown[] = [], sourceFile = join(dir, "migration-sources.json"), sourceValue = { schema: "agent-mem.migration-sources/v1", sources };
46
+ const sourcePrior = readProfileJSON(sourceFile);
47
+ if (sourcePrior === undefined) writeProfileJSON(sourceFile, sourceValue);
48
+ else if (canonicalJSON(sourcePrior) !== canonicalJSON(sourceValue)) fail();
49
+ const descriptor = generationDescriptor(generation), sealFile = join(dir, "generation-seal.json");
50
+ const sealValue = { schema: "agent-mem.generation-seal/v1", generation, descriptorHash: hashJSON(descriptor), sourceDigest: hashJSON({ sources, legacyCommit: undefined }) };
51
+ const sealPrior = readProfileJSON(sealFile);
52
+ if (sealPrior === undefined) writeProfileJSON(sealFile, sealValue);
53
+ else if (canonicalJSON(sealPrior) !== canonicalJSON(sealValue)) fail();
54
+ writeProfileJSON(join(dir, "generation.json"), descriptor);
55
+ fsyncDirectory(dir); fsyncDirectory(join(dir, ".."));
56
+ return { created: true };
57
+ }
58
+
59
+ /**
60
+ * Append the frozen record, completing an interrupted byte prefix of itself when one is attributed to `intent`.
61
+ * Nothing else may occupy the next position: the prefix hash and length are the intent's own independent evidence.
62
+ */
63
+ export function appendRealmExtension(home: string, binding: RealmExtensionBinding, intent: RealmIntent, record: RealmExtension, options: RealmIntentProof): void {
64
+ const file = join(home, REALM_EXTENSION_LOG), history = readRealmExtensionHistory(home, binding, { allowEmptyLog: retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash), attributeTorn: () => true });
65
+ const bytes = Buffer.concat([history.logBytes, history.torn]);
66
+ if (history.records.length + 1 !== intent.sequence || history.headHash !== intent.previousHash) fail();
67
+ let remainder: Buffer;
68
+ const line = Buffer.from(canonicalJSON(record) + "\n");
69
+ if (history.torn.length) {
70
+ // verifyTornRealmAppend re-derives the prefix from the intent itself, so it never trusts the tail it completes.
71
+ if (!verifyTornRealmAppend(bytes, intent, record).equals(history.logBytes)) fail();
72
+ remainder = line.subarray(history.torn.length);
73
+ } else {
74
+ if (history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash) fail();
75
+ remainder = line;
76
+ }
77
+ if (bytes.length + remainder.length > REALM_EXTENSION_LOG_MAX_BYTES || history.records.length + 1 > REALM_EXTENSION_LIMIT) fail();
78
+ history.assertCurrent(); options.assertCurrent();
79
+ const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
80
+ if (before) { owned(before); if (Number(before.size) !== bytes.length) fail(); }
81
+ const fd = before ? openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW)
82
+ : openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
83
+ try {
84
+ const opened = fstatSync(fd, { bigint: true }); owned(opened);
85
+ if (before ? stamp(opened) !== stamp(before) : Number(opened.size) !== 0) fail();
86
+ for (let at = 0; at < remainder.length;) at += writeSync(fd, remainder, at, remainder.length - at);
87
+ fsyncSync(fd);
88
+ if (Number(fstatSync(fd, { bigint: true }).size) !== bytes.length + remainder.length) fail();
89
+ } finally { closeSync(fd); }
90
+ fsyncDirectory(home); options.assertCurrent();
91
+ const installed = readRealmExtensionHistory(home, binding);
92
+ if (installed.torn.length || installed.records.length !== intent.sequence || installed.records.at(-1)?.seal !== record.seal) fail();
93
+ }
94
+
95
+ /**
96
+ * Cut back only an incomplete append this intent authorized, when a person abandons before it committed.
97
+ * The retained evidence names the exact prefix and the incomplete bytes are no line any reader folds; a tail that
98
+ * cannot be attributed to this intent refuses instead of being removed.
99
+ */
100
+ export function discardRealmExtensionTail(home: string, binding: RealmExtensionBinding, intent: RealmIntent, options: RealmIntentProof): { discarded: number } {
101
+ const file = join(home, REALM_EXTENSION_LOG), history = readRealmExtensionHistory(home, binding, { allowEmptyLog: retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash), attributeTorn: () => true });
102
+ if (history.records.length + 1 !== intent.sequence || history.headHash !== intent.previousHash
103
+ || history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash) fail();
104
+ // Clearing the intent withdraws the only evidence that reads a zero-byte log as this epoch's pre-write chain, so an
105
+ // abandoned admission that never wrote a byte removes the file it created instead of leaving every realm unreadable.
106
+ const tail = history.torn.length;
107
+ if (!tail && intent.previousLogBytes !== 0) return { discarded: 0 };
108
+ if (tail && !attributeTornRealmAppend(home, binding, { prefix: history.logBytes, tail: history.torn, sequence: intent.sequence, headHash: history.headHash })) fail();
109
+ options.assertCurrent();
110
+ const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
111
+ // A stop before the file existed has nothing to remove; a damaged chain must still be there to be cut back.
112
+ if (!before) { if (tail) fail(); return { discarded: 0 }; }
113
+ owned(before);
114
+ if (Number(before.size) !== history.logBytes.length + tail) fail();
115
+ const fd = openSync(file, constants.O_WRONLY | constants.O_NOFOLLOW);
116
+ try {
117
+ const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
118
+ // A zero-length log file is itself a refusal, so an emptied chain keeps no file instead of an empty one.
119
+ if (intent.previousLogBytes === 0) unlinkSync(file); else ftruncateSync(fd, intent.previousLogBytes);
120
+ fsyncSync(fd);
121
+ } finally { closeSync(fd); }
122
+ fsyncDirectory(home); options.assertCurrent();
123
+ const after = lstatSync(file, { bigint: true, throwIfNoEntry: false });
124
+ if (intent.previousLogBytes === 0 ? after !== undefined : !after || Number(after.size) !== intent.previousLogBytes) fail();
125
+ const installed = readRealmExtensionHistory(home, binding);
126
+ if (installed.torn.length || installed.records.length + 1 !== intent.sequence) fail();
127
+ return { discarded: tail };
128
+ }
@@ -0,0 +1,352 @@
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 { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
29
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
30
+ import { createRealmExtension, REALM_EXTENSION_SCHEMA, RealmExtensionFormatError, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
31
+ import { readRealmExtensionHistory, type RealmExtensionBinding, type RealmExtensionHistory } from "./sync-placement-realm-extension-storage.ts";
32
+ /** A zero-byte extension log is the pre-write state of a retained admission for this epoch, never an unknown chain. */
33
+ const emptyLogAllowed = (home: string, binding: RealmExtensionBinding): boolean => retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash);
34
+ import { readEffectiveRealmInventory, retainedAdmissionCoversEmptyLog } from "./sync-placement-realm-effective.ts";
35
+ import { createRealmIntent, REALM_INTENT_SCHEMA, type RealmIntent } from "./sync-placement-realm-intent-format.ts";
36
+ import { clearRealmIntent, clearRealmIntentStages, inspectRealmIntentStages, readRealmIntent, writeRealmIntent } from "./sync-placement-realm-intent-storage.ts";
37
+ import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
38
+ import { clearRealmProof, hasRealmProofStage, inspectRealmProofStage, readRealmProof, writeRealmProof } from "./sync-placement-realm-proof.ts";
39
+ import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
40
+ import { appendRealmExtension, discardRealmExtensionTail, ensureCuratedRealmMetadata } from "./sync-placement-realm-admission-storage.ts";
41
+ import { readWriterHistory } from "./sync-placement-writer-history.ts";
42
+ import { activePlacementWriterContext } from "../sync-placement-writer-context.ts";
43
+ import { writerInventoryGenesis } from "./sync-placement-writer-revision-format.ts";
44
+ import type { SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
45
+
46
+ const digest = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
47
+ const empty = digest("");
48
+ const MACHINE_ID = /^[0-9a-f]{16}$/;
49
+
50
+ /** `not-local` is a state both 0.28.2 and the #450 driver already report: no curated shard yet, so nothing to admit yet. */
51
+ export type RealmAdmissionState = "admissible" | "already-admitted" | "not-local" | "unavailable";
52
+ /** Everything the intent and record would pin; identifiers and hashes only, never a project key or a row. */
53
+ export interface RealmAdmissionNext {
54
+ mode: "new" | "existing";
55
+ sequence: number; previousHash: string; previousLogBytes: number; previousLogHash: string;
56
+ writerHash: string; journal: { sequence: number; headHash: string };
57
+ bindingHash?: string; descriptorHash?: string; sourceHash?: string;
58
+ aliasesHash: string; policyHash: string;
59
+ }
60
+ export interface RealmAdmissionPreview { realm: string; state: RealmAdmissionState; next?: RealmAdmissionNext }
61
+ export interface RealmAbandonPlan { realm: string; state: "abandonable" | "committed" | "none" | "unavailable"; sequence?: number; discards?: number; staged?: number; nextStep?: string }
62
+ export type RealmAdmissionMode = "apply" | "resume" | "abandon";
63
+ export type RealmAdmissionStage = "after-intent" | "after-metadata" | "after-proof" | "after-append";
64
+ export interface RealmAdmissionOptions {
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 };
68
+ /** Internal fault seam between durable steps; the CLI never supplies it. */
69
+ checkpoint?(stage: RealmAdmissionStage): void | Promise<void>;
70
+ }
71
+ export interface RealmAdmissionResult {
72
+ mode: RealmAdmissionMode; state: "admitted" | "already-admitted" | "abandoned" | "retained";
73
+ realm: string; sequence?: number; headHash?: string; created?: boolean; discarded?: number; staged?: number; nextStep?: string;
74
+ }
75
+ export class RealmAdmissionError extends Error {
76
+ constructor(readonly causeClass: "readers" | "busy" | "changed" | "pending" | "committed" | "metadata", readonly retainedRealm?: string) {
77
+ super(`Sync placement realm admission is ${causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
78
+ this.name = "RealmAdmissionError";
79
+ }
80
+ }
81
+ function action(causeClass: RealmAdmissionError["causeClass"]): string {
82
+ 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.";
83
+ 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.";
84
+ if (causeClass === "changed") return "Re-read the home with amem migrate --sync-placement --admit <project> --dry-run and apply the reviewed append.";
85
+ if (causeClass === "metadata") return "Inspect the local placement and curated metadata it names, then run amem migrate --sync-placement --admit <project> --dry-run.";
86
+ return "Close cooperating readers and writers, then run amem migrate --sync-placement --admit <project> --dry-run.";
87
+ }
88
+ function fail(causeClass: RealmAdmissionError["causeClass"]): never { throw new RealmAdmissionError(causeClass); }
89
+ function assertNoPendingAdmission(home: string, ownRealm?: string): void {
90
+ const pending = pendingRealmInventory(home);
91
+ if (pending.unknown) fail("pending");
92
+ const other = pending.hashes.find(key => key !== ownRealm);
93
+ if (other) throw new RealmAdmissionError("pending", other);
94
+ }
95
+ function rethrow(error: unknown): never {
96
+ if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError || error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error;
97
+ if (error instanceof PlacementInventoryFenceError) fail(error.causeClass);
98
+ return fail("metadata");
99
+ }
100
+
101
+ function realmBinding(active: ActivePlacementBinding): RealmExtensionBinding {
102
+ return { epochHash: active.profile.placementHead, activationHash: active.activation.seal, homeHash: active.epoch.homeHash,
103
+ generation: active.epoch.generation,
104
+ initialProjectHashes: active.activation.realms.flatMap(realm => realm.scope === "project" ? [realm.keyHash] : []) };
105
+ }
106
+ /** The writer history reads exactly four identity fields; an extension binding carries one more. */
107
+ function writerBinding(binding: RealmExtensionBinding): { epochHash: string; activationHash: string; homeHash: string; generation: string } {
108
+ return { epochHash: binding.epochHash, activationHash: binding.activationHash, homeHash: binding.homeHash, generation: binding.generation };
109
+ }
110
+ function activeBinding(home: string): ActivePlacementBinding {
111
+ const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
112
+ if (!active) throw Error("sync placement is not active in this home; there is no inventory to admit a realm into");
113
+ return active;
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
+ }
120
+ function machineIdentity(home: string): { id: string; label: string } {
121
+ const machine = readProfileJSON(join(home, "machine.json")) as { id?: unknown; label?: unknown } | undefined;
122
+ const id = machine?.id, label = machine?.label;
123
+ if (typeof id !== "string" || !MACHINE_ID.test(id)) fail("metadata");
124
+ return { id, label: typeof label === "string" ? label : id };
125
+ }
126
+ function inForce(home: string, realm: string): boolean {
127
+ try { return readEffectiveRealmInventory(home, activeBinding(home)).realms.some(item => item.scope === "project" && item.keyHash === realm); }
128
+ catch { return false; }
129
+ }
130
+
131
+ /** Every realm identity is a hash here, so only identifiers leave this module. */
132
+ function inspectRealmAdmission(home: string, project: string, owner?: PlacementActivationOwner): RealmAdmissionPreview {
133
+ const realm = digest(project), active = activeBinding(home), binding = realmBinding(active);
134
+ let effective: readonly SyncPlacementRealmBinding[];
135
+ try { effective = readEffectiveRealmInventory(home, active).realms; } catch { return { realm, state: "unavailable" }; }
136
+ if (effective.some(item => item.scope === "project" && item.keyHash === realm)) return { realm, state: "already-admitted" };
137
+ // A scaffold whose fixed paths are not real directories and private files cannot be completed: completing it would create
138
+ // files through a symlink (a restored `legacy` is the easy case). Refuse before an intent or any metadata write, as the
139
+ // same `unavailable` the other unusable states report.
140
+ try { assertCuratedShardLayout(home, { project }); } catch { return { realm, state: "unavailable" }; }
141
+ const descriptor = readShardDescriptor(home, realm.slice(0, 16));
142
+ if (descriptor && digest(descriptor.key) !== realm) return { realm, state: "unavailable" };
143
+ const curated = descriptor !== undefined && existsSync(join(shardDir(home, descriptor.key), "generation.json"));
144
+ // Strict: an unattributed or torn chain is not something a preview or an intent may append over.
145
+ let history: RealmExtensionHistory;
146
+ try { history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding) }); } catch { return { realm, state: "unavailable" }; }
147
+ const source = owner ? previewOwnedSyncPlacementSources(home, owner) : previewSyncPlacementSources(home);
148
+ const captured = source.base.realms.find(item => item.scope === "project" && item.keyHash === realm);
149
+ if (curated !== (captured !== undefined)) return { realm, state: "unavailable" };
150
+ const journal = readPlacementWriterJournalAnchors(home, binding.epochHash);
151
+ if (journal.epoch.homeHash !== binding.homeHash || journal.activation.seal !== binding.activationHash) return { realm, state: "unavailable" };
152
+ const writers = readWriterHistory(home, writerBinding(binding));
153
+ const writerHash = writers.commits.at(-1)?.seal ?? writerInventoryGenesis(binding.epochHash, binding.activationHash);
154
+ const headHash = journal.sequence ? journal.records[journal.sequence - 1]!.seal : binding.epochHash;
155
+ // The facts and the anchors must still hold when the report leaves this function.
156
+ source.assertSourcesUnchanged(); history.assertCurrent(); writers.assertCurrent();
157
+ const next: RealmAdmissionNext = { mode: curated ? "existing" : "new",
158
+ sequence: history.records.length + 1, previousHash: history.headHash,
159
+ previousLogBytes: history.logBytes.length, previousLogHash: history.logBytes.length ? digest(history.logBytes) : empty,
160
+ writerHash, journal: { sequence: journal.sequence, headHash },
161
+ aliasesHash: source.base.aliasesHash, policyHash: source.base.policyHash,
162
+ ...(captured ? { bindingHash: captured.bindingHash, descriptorHash: hashJSON(descriptor), sourceHash: source.base.sourceHash } : {}) };
163
+ return { realm, state: curated ? "admissible" : "not-local", next };
164
+ }
165
+ /** A dry-run report only: no fence, no intent, no curated metadata and no appended byte. */
166
+ export function previewRealmAdmission(homeInput: string, project: string): RealmAdmissionPreview {
167
+ const home = realPath(homeInput);
168
+ activeBinding(home); // a home without active placement keeps its own message instead of a metadata class
169
+ try { return inspectRealmAdmission(home, project); } catch (error) { return rethrow(error); }
170
+ }
171
+ /** Person abandon preview: what a confirmed abandon would remove, and whether the append already committed. */
172
+ export function planRealmAbandon(homeInput: string, project: string): RealmAbandonPlan {
173
+ const realm = digest(project);
174
+ try {
175
+ const home = realPath(homeInput), binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
176
+ const stages = inspectRealmIntentStages(home, realm);
177
+ if (stages.length) {
178
+ // A stage is independent of an installed intent or committed record; never discard an unattributed log tail.
179
+ readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: evidence => attributeTornRealmAppend(home, binding, evidence) });
180
+ return { realm, state: "abandonable", staged: stages.length, discards: stages.reduce((sum, stage) => sum + stage.size, 0) };
181
+ }
182
+ if (!intent) return { realm, state: "none", nextStep: "no admission intent is retained for this realm" };
183
+ readRealmProof(home, intent); // A malformed retained proof is not a clean abandon preview.
184
+ if (hasRealmProofStage(home, intent)) {
185
+ try {
186
+ if (!inspectRealmProofStage(home, intent)) return { realm, state: "unavailable", sequence: intent.sequence };
187
+ } catch { return { realm, state: "unavailable", sequence: intent.sequence }; }
188
+ }
189
+ const history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: () => true });
190
+ if (history.records.length + 1 > intent.sequence) return { realm, state: "committed", sequence: intent.sequence, nextStep: "amem migrate --sync-placement --admit <project> --resume" };
191
+ if (history.records.length + 1 < intent.sequence || history.headHash !== intent.previousHash
192
+ || history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash)
193
+ return { realm, state: "unavailable", sequence: intent.sequence };
194
+ if (history.torn.length && !attributeTornRealmAppend(home, binding, { prefix: history.logBytes, tail: history.torn, sequence: intent.sequence, headHash: history.headHash }))
195
+ return { realm, state: "unavailable", sequence: intent.sequence };
196
+ return { realm, state: "abandonable", sequence: intent.sequence, discards: history.torn.length };
197
+ } catch (error) { return rethrow(error); }
198
+ }
199
+
200
+ /** The intent is the frozen review: position, anchors and proofs, plus the target the person named. */
201
+ function intentFor(home: string, project: string, next: RealmAdmissionNext, binding: RealmExtensionBinding): RealmIntent {
202
+ const machine = machineIdentity(home), existing = next.mode === "existing";
203
+ return createRealmIntent({ schema: REALM_INTENT_SCHEMA, home, project, keyHash: digest(project), machine: machine.id,
204
+ epochHash: binding.epochHash, activationHash: binding.activationHash, homeHash: binding.homeHash, generation: binding.generation,
205
+ sequence: next.sequence, previousHash: next.previousHash, previousLogBytes: next.previousLogBytes, previousLogHash: next.previousLogHash,
206
+ mode: next.mode, descriptorHash: existing ? next.descriptorHash! : null, sourceHash: existing ? next.sourceHash! : null,
207
+ aliasesHash: next.aliasesHash, policyHash: next.policyHash, writerHash: next.writerHash, journal: next.journal });
208
+ }
209
+ /** `realm.bindingHash` is the one field the intent omits, so a record can never be rebuilt from an intent alone. */
210
+ function recordFor(intent: RealmIntent, capturedBinding: string, sourceHash: string): RealmExtension {
211
+ return createRealmExtension({ schema: REALM_EXTENSION_SCHEMA, epochHash: intent.epochHash, activationHash: intent.activationHash,
212
+ homeHash: intent.homeHash, generation: intent.generation, sequence: intent.sequence, previousHash: intent.previousHash,
213
+ realm: { scope: "project", keyHash: intent.keyHash, bindingHash: capturedBinding },
214
+ sourceHash: intent.sourceHash ?? sourceHash, aliasesHash: intent.aliasesHash, policyHash: intent.policyHash,
215
+ writerHash: intent.writerHash, journal: intent.journal });
216
+ }
217
+ /** The seal already occupying the intent's position, or undefined while that position is still free. */
218
+ function installedSeal(home: string, binding: RealmExtensionBinding, intent: RealmIntent): string | undefined {
219
+ let history: RealmExtensionHistory;
220
+ try { history = readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding) }); } catch { return undefined; }
221
+ const existing = history.records[intent.sequence - 1];
222
+ if (!existing) return undefined;
223
+ if (existing.previousHash !== intent.previousHash || existing.realm.keyHash !== intent.keyHash) fail("committed");
224
+ return existing.seal;
225
+ }
226
+ /** Anchors frozen by the intent must still be ancestors of the live history, or the record could never be folded. */
227
+ function assertAnchors(home: string, binding: RealmExtensionBinding, intent: RealmIntent): void {
228
+ const journal = readPlacementWriterJournalAnchors(home, binding.epochHash);
229
+ if (journal.epoch.homeHash !== binding.homeHash || journal.activation.seal !== binding.activationHash
230
+ || journal.sequence < intent.journal.sequence
231
+ || (intent.journal.sequence ? journal.records[intent.journal.sequence - 1]?.seal : binding.epochHash) !== intent.journal.headHash) fail("committed");
232
+ const heads = [writerInventoryGenesis(binding.epochHash, binding.activationHash), ...readWriterHistory(home, writerBinding(binding)).commits.map(commit => commit.seal)];
233
+ if (!heads.includes(intent.writerHash)) fail("committed");
234
+ }
235
+
236
+ export async function applyRealmAdmission(homeInput: string, project: string, options: RealmAdmissionOptions): Promise<RealmAdmissionResult> {
237
+ let home: string;
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."); }
239
+ const realm = digest(project), projectPrefix = realm.slice(0, 16);
240
+ assertCheckpointClear(home);
241
+ if (options.mode === "abandon") {
242
+ const plan = planRealmAbandon(home, project);
243
+ if (plan.state === "none") return { mode: "abandon", state: "already-admitted", realm, nextStep: plan.nextStep };
244
+ if (plan.state !== "abandonable") fail(plan.state === "committed" ? "committed" : "metadata");
245
+ if (options.confirm !== true) return { mode: "abandon", state: "retained", realm, sequence: plan.sequence, discarded: plan.discards,
246
+ ...(plan.staged ? { staged: plan.staged } : {}), nextStep: "confirm amem migrate --sync-placement --admit <project> --abandon --confirm" };
247
+ const stages = plan.staged ? inspectRealmIntentStages(home, realm) : undefined;
248
+ if (plan.staged && stages?.length !== plan.staged) fail("changed");
249
+ return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
250
+ try {
251
+ assertCheckpointClear(home);
252
+ const binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
253
+ const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
254
+ if (stages) {
255
+ readRealmExtensionHistory(home, binding, { allowEmptyLog: emptyLogAllowed(home, binding), attributeTorn: evidence => attributeTornRealmAppend(home, binding, evidence) });
256
+ clearRealmIntentStages(home, realm, stages, proof);
257
+ return { mode: "abandon" as const, state: "abandoned" as const, realm, staged: stages.length,
258
+ discarded: stages.reduce((sum, stage) => sum + stage.size, 0), nextStep: intent
259
+ ? "amem migrate --sync-placement --admit <project> --resume" : "amem migrate --sync-placement --admit <project> --dry-run" };
260
+ }
261
+ if (!intent) return fail("changed");
262
+ const { discarded } = discardRealmExtensionTail(home, binding, intent, proof);
263
+ clearRealmProof(home, intent, proof);
264
+ clearRealmIntent(home, intent, proof);
265
+ return { mode: "abandon" as const, state: "abandoned" as const, realm, sequence: intent.sequence, discarded,
266
+ nextStep: "amem migrate --sync-placement --admit <project> --dry-run" };
267
+ } catch (error) { return rethrow(error); }
268
+ });
269
+ }
270
+ if (options.mode === "apply") assertNoPendingAdmission(home);
271
+ const planned = options.mode === "apply" ? inspectRealmAdmission(home, project) : undefined;
272
+ if (planned?.state === "already-admitted") return { mode: options.mode, state: "already-admitted", realm };
273
+ if (planned?.state === "unavailable") fail("metadata");
274
+ if (options.mode === "resume" && !readRealmIntent(home, realm)) {
275
+ if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted", realm };
276
+ throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
277
+ }
278
+ return withPlacementActivationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
279
+ try {
280
+ assertCheckpointClear(home);
281
+ if (options.mode === "apply") assertNoPendingAdmission(home);
282
+ if (options.mode === "resume") assertNoPendingAdmission(home, realm);
283
+ const binding = realmBinding(activeBinding(home));
284
+ const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
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");
289
+ if (intent && options.mode === "apply") fail("pending");
290
+ if (!intent && options.mode === "resume") {
291
+ if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted" as const, realm };
292
+ throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
293
+ }
294
+ if (intent) {
295
+ assertAnchors(home, binding, intent);
296
+ const committed = installedSeal(home, binding, intent);
297
+ if (committed !== undefined) {
298
+ const evidence = readRealmProof(home, intent);
299
+ if (!evidence || evidence.seal !== committed) fail("committed");
300
+ clearRealmIntent(home, intent, proof);
301
+ return { mode: options.mode, state: "admitted" as const, realm, sequence: intent.sequence, headHash: committed, created: false };
302
+ }
303
+ }
304
+ // Stored writer hashes are history, not current install evidence. Re-measure the existing active writer inventory under the fences.
305
+ const writer = activePlacementWriterContext(home, fileURLToPath(new URL("../..", import.meta.url)));
306
+ const current = () => { check(); writer.attest(); check(); };
307
+ current();
308
+ if (!intent) {
309
+ // Apply re-reads every fact it acts on under this fence; the earlier report only named the state.
310
+ const fixed = inspectRealmAdmission(home, project, owner);
311
+ if (fixed.state === "already-admitted") return { mode: options.mode, state: "already-admitted" as const, realm };
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");
315
+ intent = intentFor(home, project, fixed.next, binding);
316
+ writeRealmIntent(home, intent, { mutation, assertCurrent: current });
317
+ await options.checkpoint?.("after-intent");
318
+ }
319
+ const frozen = intent;
320
+ // A new realm's intent has no sourceHash; a partial proof cannot prove the original source snapshot after restart.
321
+ if (options.mode === "resume" && frozen.mode === "new" && hasRealmProofStage(home, frozen)) fail("pending");
322
+ current();
323
+ const created = ensureCuratedRealmMetadata(home, project, binding.generation, machineIdentity(home)).created;
324
+ await options.checkpoint?.("after-metadata");
325
+ const source = previewOwnedSyncPlacementSources(home, owner);
326
+ const captured = source.base.realms.find(item => item.scope === "project" && item.keyHash === realm);
327
+ if (!captured) fail("changed");
328
+ // A frozen curated descriptor or source proof that moved since the review re-reads, never appends.
329
+ const descriptor = readShardDescriptor(home, realm.slice(0, 16));
330
+ if (frozen.descriptorHash !== null && (!descriptor || hashJSON(descriptor) !== frozen.descriptorHash)) fail("changed");
331
+ if (frozen.mode === "existing" && source.base.sourceHash !== frozen.sourceHash) fail("changed");
332
+ if (source.base.aliasesHash !== frozen.aliasesHash || source.base.policyHash !== frozen.policyHash) fail("changed");
333
+ const record = recordFor(frozen, captured.bindingHash, source.base.sourceHash);
334
+ const sourceProof = { mutation, assertCurrent: () => { current(); source.assertSourcesUnchanged(); current(); } };
335
+ writeRealmProof(home, frozen, record, sourceProof);
336
+ await options.checkpoint?.("after-proof");
337
+ const durableProof = { mutation, assertCurrent: () => {
338
+ sourceProof.assertCurrent();
339
+ if (readRealmProof(home, frozen)?.seal !== record.seal) fail("changed");
340
+ sourceProof.assertCurrent();
341
+ } };
342
+ appendRealmExtension(home, binding, frozen, record, durableProof);
343
+ await options.checkpoint?.("after-append");
344
+ clearRealmIntent(home, frozen, proof);
345
+ return { mode: options.mode, state: "admitted" as const, realm, sequence: frozen.sequence, headHash: record.seal, created };
346
+ } catch (error) { return rethrow(error); }
347
+ });
348
+ }
349
+ function directories(home: string, projectPrefix: string): string[] {
350
+ const realmDir = join(home, "projects", projectPrefix);
351
+ return existsSync(realmDir) ? [realmDir] : [];
352
+ }
@@ -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,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
+ }