@staix/agent-mem 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +20 -574
- package/package.json +3 -2
- package/src/cli-agent-reads.ts +17 -2
- package/src/cli.ts +178 -21
- package/src/commands-table.ts +14 -2
- package/src/index.ts +1 -0
- package/src/ingest.ts +7 -5
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/candidates.ts +17 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +2 -1
- package/src/memory/config.ts +13 -1
- package/src/memory/decay-review.ts +20 -0
- package/src/memory/doctor.ts +133 -47
- package/src/memory/eval-audit.ts +442 -0
- package/src/memory/eval.ts +66 -0
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- package/src/memory/native-roots.ts +28 -0
- package/src/memory/platform.ts +9 -1
- package/src/memory/review-targets.ts +69 -0
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-migration.ts +14 -1
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +4 -0
- package/src/memory/store.ts +4 -2
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +14 -2
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +38 -11
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +207 -53
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +14 -0
- package/src/memory/sync-progress.ts +1 -1
- package/src/memory/sync.ts +5 -2
- package/src/memory/use-telemetry.ts +15 -7
- package/src/setup-drift.ts +12 -2
- package/src/setup-owned.ts +42 -0
- package/src/setup.ts +32 -11
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +26 -11
- package/src/ui/snapshot-cache.ts +24 -11
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/** Offline, effect-free prospective publication sizing for checkpoint headroom. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { canonicalJSON, hashJSON, readProfileJSON } from "./generation.ts";
|
|
6
|
+
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
7
|
+
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
8
|
+
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
9
|
+
import { previewSelectedSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
10
|
+
import { placementInventory, placementInventoryBatches, type InventoryRealm } from "./sync-placement-inventory.ts";
|
|
11
|
+
import { captureInspectionJournal, inspectRetainedPublicationHistories, PlacementInspectionObjects } from "./sync-placement-inspection-evidence.ts";
|
|
12
|
+
import { createPlacementRecord, SyncPlacementJournalError, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
13
|
+
import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
|
|
14
|
+
import { planPlacementPublicationAsync, publicationBytes, publicationFileNames } from "./sync-placement-publication-plan.ts";
|
|
15
|
+
import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
|
|
16
|
+
import { drainSteps } from "./sync-placement-yield.ts";
|
|
17
|
+
import { outboundPolicyEvaluator } from "./sync-screen.ts";
|
|
18
|
+
import { resolveShardProfile } from "./shard.ts";
|
|
19
|
+
import { readPublicPruneViewForActivation } from "./public-prune-view.ts";
|
|
20
|
+
import { reducePublicPruneInputs } from "./public-prune-inputs.ts";
|
|
21
|
+
import { reducePruneRows, type PruneRow } from "./prune.ts";
|
|
22
|
+
import { explicitExpirySnapshot } from "./generation-index.ts";
|
|
23
|
+
import { inspectPublisherPruneLineages } from "./prune-publisher-lineage.ts";
|
|
24
|
+
import type { ShardSyncRealm, ShardSyncRow } from "./shard-sync-format.ts";
|
|
25
|
+
|
|
26
|
+
export type CheckpointProspective = { state: "none" } | { state: "cache-only"; slots: number; reservedJournalChunks: number }
|
|
27
|
+
| { state: "unavailable"; reason: "cache-or-remote-evidence-unavailable" };
|
|
28
|
+
const realm = (item: InventoryRealm): PlacementRealm => item.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: item.keyHash };
|
|
29
|
+
const shard = (item: InventoryRealm): ShardSyncRealm => item.scope === "user" ? { scope: "user" } : { scope: "project", key: item.key };
|
|
30
|
+
const same = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
|
|
31
|
+
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
|
|
32
|
+
const slots = (value: { slots: number; reservedJournalChunks: number }) => value.slots + value.reservedJournalChunks;
|
|
33
|
+
function reserve(lengths: readonly number[]): number {
|
|
34
|
+
let chunks = 0, size = 0;
|
|
35
|
+
for (const bytes of lengths) { if (!chunks || size + bytes > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) { chunks++; size = 0; } size += bytes; }
|
|
36
|
+
return chunks + (lengths.length ? 1 : 0);
|
|
37
|
+
}
|
|
38
|
+
/** Only fixed local Git reads; missing cached refs/objects cannot establish a current remote plan without network. */
|
|
39
|
+
export async function checkpointProspective(home: string): Promise<{ value: CheckpointProspective; assertCurrent(): void }> {
|
|
40
|
+
const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
41
|
+
if (!active) throw new Error("sync placement unavailable");
|
|
42
|
+
const inventory = placementInventory(home), inventoryHash = hashJSON(inventory), effective = readEffectiveRealmInventory(home, active);
|
|
43
|
+
const batches = placementInventoryBatches(inventory.local), sourceChecks: (() => void)[] = [];
|
|
44
|
+
const checkInventory = () => { effective.assertCurrent(); if (hashJSON(placementInventory(home)) !== inventoryHash) throw new Error("placement inventory changed"); };
|
|
45
|
+
if (!batches.length) return { value: { state: "none" }, assertCurrent: checkInventory };
|
|
46
|
+
const cache = join(home, "shard-sync-placement", "objects.git");
|
|
47
|
+
if (!existsSync(cache)) return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
|
|
48
|
+
assertCurrent: () => { checkInventory(); if (existsSync(cache)) throw new Error("placement cache changed"); } };
|
|
49
|
+
const journal = captureInspectionJournal(home, active.profile.placementHead);
|
|
50
|
+
let objects: PlacementInspectionObjects;
|
|
51
|
+
try { objects = new PlacementInspectionObjects(home, () => { checkInventory(); journal.assertCurrent(); }); }
|
|
52
|
+
catch {
|
|
53
|
+
// A changed journal or inventory is not a missing remote: never turn a concurrent drift into the fallback.
|
|
54
|
+
checkInventory(); journal.assertCurrent();
|
|
55
|
+
return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" }, assertCurrent: () => { checkInventory(); journal.assertCurrent(); } };
|
|
56
|
+
}
|
|
57
|
+
const view = readPublicPruneViewForActivation(home, active.profile.pruneInputSetHash, active.profile.generation);
|
|
58
|
+
let largest: { slots: number; reservedJournalChunks: number } | undefined;
|
|
59
|
+
for (const batch of batches) {
|
|
60
|
+
const selected = batch.map(realm), source = previewSelectedSyncPlacementSources(home, selected);
|
|
61
|
+
const targets = batch.map(item => ({ realm: shard(item), profile: resolveShardProfile(home, item.scope === "user" ? { user: true } : { project: item.key }) }));
|
|
62
|
+
let heads: (string | undefined)[];
|
|
63
|
+
try { heads = targets.map(target => objects.ref(target.realm)); }
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof SyncPlacementJournalError && (error.code === "corrupt" || error.code === "bound"))
|
|
66
|
+
return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
|
|
67
|
+
assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
// A missing cache ref is usable only when the latest retained completed publication for this remote and realm
|
|
71
|
+
// observed an absent ref. With no such receipt it could be an unfetched remote, so never invent an empty history.
|
|
72
|
+
const publications = [...journal.publications.values()].filter(item => item.phase === "completed" && item.bundle.root.remoteHash === objects.remoteHash
|
|
73
|
+
&& item.facts.some(fact => fact.phase === "completed" && fact.outcome === "committed"))
|
|
74
|
+
.sort((a, b) => a.bundle.root.journal.sequence - b.bundle.root.journal.sequence);
|
|
75
|
+
const knownEmpty = (identity: PlacementRealm) => {
|
|
76
|
+
const matching = publications.flatMap(item => item.bundle.root.targets.filter(target => same(target.realm, identity)));
|
|
77
|
+
const last = matching.at(-1); return !!last && !last.publish && last.expectedRemoteHead === null && last.commit === null;
|
|
78
|
+
};
|
|
79
|
+
if (heads.some((head, index) => head === undefined && !knownEmpty(selected[index]!)))
|
|
80
|
+
return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
|
|
81
|
+
assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
|
|
82
|
+
// A mutable cache ref is not a remote receipt: retain only the head verified through the publication journal.
|
|
83
|
+
let histories: Awaited<ReturnType<typeof inspectRetainedPublicationHistories>>;
|
|
84
|
+
try { histories = await inspectRetainedPublicationHistories(journal, targets.map(target => ({ realm: target.realm, generation: active.profile.generation })), objects); }
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (error instanceof SyncPlacementJournalError && (error.code === "corrupt" || error.code === "bound"))
|
|
87
|
+
return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
|
|
88
|
+
assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
if (heads.some((head, index) => head !== histories.tips[index]))
|
|
92
|
+
return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
|
|
93
|
+
assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
|
|
94
|
+
const old = histories.old;
|
|
95
|
+
const planned = targets.map((target, index) => {
|
|
96
|
+
const identity = selected[index]!, id = canonicalJSON(identity), sources = source.sourceRowsByRealm.get(id);
|
|
97
|
+
if (!sources) throw new Error("selected placement source unavailable");
|
|
98
|
+
const prunes = [...source.specialRows.values()].filter(row => same(row.key.realm, identity) && row.row.op === "prune");
|
|
99
|
+
const reduced = reducePruneRows(prunes.map(row => ({ row: row.row as PruneRow, placement: row.sourcePlacement })), { rows: sources, expiries: explicitExpirySnapshot(sources) }, active.profile.generation);
|
|
100
|
+
if (reduced.invalid || reduced.pending.length) throw new Error("placement prune proof unavailable");
|
|
101
|
+
const inputHash = view.realms[target.realm.scope === "user" ? "user" : `project:${target.realm.key}`];
|
|
102
|
+
const pruned = inputHash ? reducePublicPruneInputs({ dir: target.profile.dir, realm: target.realm, receivingGeneration: active.profile.generation, inputSetHash: inputHash,
|
|
103
|
+
publicationFormat: active.profile.publicationFormat, nativeTargets: [...reduced.targets], ordinary: sources.map(row => row.row) }).targets : reduced.targets;
|
|
104
|
+
return { realm: target.realm, generation: active.profile.generation, remote: heads[index], local: heads[index], fetched: new Set(old[index]?.rows.keys() ?? []),
|
|
105
|
+
localPrunes: new Map(prunes.filter(row => row.sourcePlacement === "synced").map(row => [row.key.id, row.row as PruneRow])), pruned };
|
|
106
|
+
});
|
|
107
|
+
const lineages = targets.map((target, index) => {
|
|
108
|
+
const rows = new Map<string, ShardSyncRow>(old[index]?.rows);
|
|
109
|
+
for (const value of [...source.rows.values(), ...source.specialRows.values()]) if (same(value.key.realm, selected[index]!) && value.row.op !== "vault_link") {
|
|
110
|
+
const prior = rows.get(value.key.id); if (prior && hashJSON(prior) !== value.key.rowHash) throw new Error("placement row mismatch"); rows.set(value.key.id, value.row);
|
|
111
|
+
}
|
|
112
|
+
const candidates = [...rows.values()].filter((row): row is PruneRow => row.op === "prune" && row.generation === active.profile.generation);
|
|
113
|
+
const machine = readProfileJSON(join(target.profile.dir, "machine.json")) as { id: string };
|
|
114
|
+
const boundary = join(target.profile.dir, "local", `publisher-boundary-${machine.id}.json`);
|
|
115
|
+
return { rows, proof: candidates.length && existsSync(boundary) ? inspectPublisherPruneLineages(target.profile, candidates) : new Map() };
|
|
116
|
+
});
|
|
117
|
+
const verified = verifiedPlacementPrunes(targets.map((target, index) => ({ realm: target.realm, generation: active.profile.generation, rows: lineages[index]!.rows,
|
|
118
|
+
fetched: planned[index]!.fetched, lineageIds: new Set<string>(lineages[index]!.proof.keys()) })));
|
|
119
|
+
const evaluate = outboundPolicyEvaluator(home), now = Date.now(), materialized = await materializePlacementRows({ capture: source, projection: journal.projection,
|
|
120
|
+
generation: active.profile.generation, targets: planned, old, verifiedPrunes: verified, evaluate, createdUnixSeconds: Math.floor(now / 1000),
|
|
121
|
+
readTree: async (_index, head) => objects.tree(head), publisherLineages: (index, rows) => inspectPublisherPruneLineages(targets[index]!.profile, rows) });
|
|
122
|
+
const body = { epochHash: active.profile.placementHead, generation: active.profile.generation, homeHash: source.base.homeHash,
|
|
123
|
+
contextHash: sha("checkpoint-preview"), markerHash: source.markerHash, sourceHash: source.base.sourceHash, aliasesHash: source.base.aliasesHash,
|
|
124
|
+
policyHash: source.base.policyHash, remoteHash: objects.remoteHash, journal: { sequence: journal.journal.sequence, headHash: journal.journal.headHash },
|
|
125
|
+
createdUnixSeconds: Math.floor(now / 1000), policySnapshotUnixMs: now, targets: materialized.plannedTargets, reservedRecords: 0, reservedRecordBytes: [] as number[] };
|
|
126
|
+
const items = { sources: source.prefixes, decisions: materialized.decisions, objects: materialized.objects };
|
|
127
|
+
let bundle = await planPlacementPublicationAsync(body, items);
|
|
128
|
+
const scheduled = drainSteps(placementPublicationEventSteps(bundle, journal.projection, old));
|
|
129
|
+
let head = body.journal.headHash;
|
|
130
|
+
const lengths = scheduled.events.map((event, index) => { const record = createPlacementRecord(body.epochHash, body.journal.sequence + index + 1, head, event); head = record.seal; return publicationBytes(record).length; });
|
|
131
|
+
bundle = await planPlacementPublicationAsync({ ...body, reservedRecords: lengths.length, reservedRecordBytes: lengths }, items);
|
|
132
|
+
const changed = bundle.root.targets.some((target, index) => target.publish && target.commit !== heads[index]);
|
|
133
|
+
if (scheduled.events.length || changed) {
|
|
134
|
+
const candidate = { slots: publicationFileNames(bundle.root).length, reservedJournalChunks: reserve(lengths) };
|
|
135
|
+
if (!largest || slots(candidate) > slots(largest)) largest = candidate;
|
|
136
|
+
}
|
|
137
|
+
source.assertSourcesUnchanged(); journal.assertCurrent(); objects.assertRetained(); sourceChecks.push(source.assertSourcesUnchanged);
|
|
138
|
+
}
|
|
139
|
+
return { value: largest ? { state: "cache-only", ...largest } : { state: "none" },
|
|
140
|
+
assertCurrent: () => { checkInventory(); for (const check of sourceChecks) check(); journal.assertCurrent(); objects.assertRetained(); } };
|
|
141
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one resolver for placement history windows (#288 step 2). Window 0 is the frozen v1 epoch directory; each committed
|
|
3
|
+
* checkpoint W adds `<home>/sync-placement-checkpoints/<E>/windows/<W>/`. Journal storage, writer history, effective
|
|
4
|
+
* writers and inspection evidence all read archived and live members through this function, never by joining paths.
|
|
5
|
+
* Read-only: it never repairs, removes or completes anything.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { closeSync, constants, fstatSync, lstatSync, opendirSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { canonicalJSON } from "./generation.ts";
|
|
11
|
+
import { realPath } from "./platform.ts";
|
|
12
|
+
import { SyncPlacementJournalError, type SyncPlacementJournalErrorCode } from "./sync-placement-journal-format.ts";
|
|
13
|
+
import {
|
|
14
|
+
PLACEMENT_CHECKPOINT_DIR, PLACEMENT_CHECKPOINT_COMMITS, PLACEMENT_CHECKPOINT_INTENT, PLACEMENT_CHECKPOINT_WINDOWS, PLACEMENT_CHECKPOINT_MANIFEST,
|
|
15
|
+
PLACEMENT_CHECKPOINT_PROJECTION, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES, PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES,
|
|
16
|
+
PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES, PLACEMENT_CHECKPOINT_ARCHIVE_MAX_MEMBERS, PLACEMENT_CHECKPOINT_ARCHIVE_MAX_BYTES, PLACEMENT_CHECKPOINT_LIMIT,
|
|
17
|
+
checkpointCommitGenesis, checkpointWindowName, checkpointWriterGenesis, validateCheckpointCatalogPage, validateCheckpointCommit, validateCheckpointIntent,
|
|
18
|
+
validateCheckpointManifest, validateCheckpointProjection,
|
|
19
|
+
type CheckpointCommit, type CheckpointIntent, type CheckpointManifest, type CheckpointMember, type CheckpointProjectionDigest,
|
|
20
|
+
} from "./sync-placement-checkpoint-format.ts";
|
|
21
|
+
import {
|
|
22
|
+
WRITER_COMMIT_LOG, WRITER_COMMIT_MAX_BYTES, WRITER_REVISION_MAX_BYTES, validateWriterCommit, validateWriterRevision, writerRevisionFile,
|
|
23
|
+
} from "./sync-placement-writer-revision-format.ts";
|
|
24
|
+
|
|
25
|
+
/** Largest single archived member: the writer revision ceiling (512 KiB) with headroom; every v1 family is smaller. */
|
|
26
|
+
const MEMBER_MAX_BYTES = 1024 * 1024;
|
|
27
|
+
export interface ArchivedPlacementWindow { window: number; dir: string; members: readonly CheckpointMember[] }
|
|
28
|
+
export interface CatalogedPublication { attemptHash: string; window: number; dir: string; members: readonly CheckpointMember[] }
|
|
29
|
+
export interface ResolvedPlacementWindow {
|
|
30
|
+
home: string; epochHash: string;
|
|
31
|
+
/** Window 0: the v1 epoch directory. epoch.json and activation.json are always read from here. */
|
|
32
|
+
epochDir: string;
|
|
33
|
+
/** The checkpoint directory of this epoch; present only once a checkpoint was started. */
|
|
34
|
+
checkpointDir: string;
|
|
35
|
+
/** The selected live window and its directory: the only members charged against the 256-object allowance. */
|
|
36
|
+
window: number; dir: string;
|
|
37
|
+
/** Ancestors of `dir` from the home down, for identity checks and parent fsyncs. */
|
|
38
|
+
parents: readonly string[];
|
|
39
|
+
archived: readonly ArchivedPlacementWindow[];
|
|
40
|
+
manifests: readonly CheckpointManifest[];
|
|
41
|
+
commits: readonly CheckpointCommit[];
|
|
42
|
+
catalog: ReadonlyMap<string, CatalogedPublication>;
|
|
43
|
+
projection?: CheckpointProjectionDigest;
|
|
44
|
+
/** A checkpoint intent or torn commit line exists: every placement effect refuses until resume or abandon. */
|
|
45
|
+
pending: boolean;
|
|
46
|
+
intent?: CheckpointIntent;
|
|
47
|
+
logBytes: number; logHash: string;
|
|
48
|
+
/** Changes whenever any checkpoint byte or window identity changes; folded into journal inventory tokens. */
|
|
49
|
+
token: string;
|
|
50
|
+
}
|
|
51
|
+
function fail(code: SyncPlacementJournalErrorCode = "corrupt"): never { throw new SyncPlacementJournalError(code); }
|
|
52
|
+
const sha = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
53
|
+
const stamp = (s: BigIntStats) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":");
|
|
54
|
+
const hex = (value: string) => value.length === 64 && /^[a-f0-9]+$/.test(value);
|
|
55
|
+
function owned(s: BigIntStats, directory = false): void {
|
|
56
|
+
const uid = process.getuid?.();
|
|
57
|
+
if (uid === undefined || s.uid !== BigInt(uid) || (s.mode & 0o077n) !== 0n || s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1n)) fail();
|
|
58
|
+
}
|
|
59
|
+
function state(file: string, directory = false): BigIntStats | undefined {
|
|
60
|
+
const s = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (s) owned(s, directory); return s;
|
|
61
|
+
}
|
|
62
|
+
function list(dir: string, maximum: number): string[] {
|
|
63
|
+
const reader = opendirSync(dir), out: string[] = [];
|
|
64
|
+
try { for (;;) { const entry = reader.readSync(); if (!entry) break; if (out.length >= maximum) fail("bound"); out.push(entry.name); } } finally { reader.closeSync(); }
|
|
65
|
+
return out.sort();
|
|
66
|
+
}
|
|
67
|
+
function read(file: string, maximum: number): { bytes: Buffer; stat: BigIntStats } | undefined {
|
|
68
|
+
const before = state(file); if (!before) return undefined; if (before.size > BigInt(maximum)) fail("bound");
|
|
69
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
70
|
+
try {
|
|
71
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail("changed");
|
|
72
|
+
const bytes = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
73
|
+
while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
|
|
74
|
+
if (at !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(state(file) ?? before) !== stamp(opened)) fail("changed");
|
|
75
|
+
return { bytes: bytes.subarray(0, at), stat: opened };
|
|
76
|
+
} finally { closeSync(fd); }
|
|
77
|
+
}
|
|
78
|
+
function decode<T>(bytes: Buffer, validate: (value: unknown) => T): T {
|
|
79
|
+
if (!bytes.length || bytes.at(-1) !== 10) fail("pending");
|
|
80
|
+
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); let value: T;
|
|
81
|
+
try { value = validate(JSON.parse(text)); } catch { return fail(); }
|
|
82
|
+
if (canonicalJSON(value) + "\n" !== text) fail(); return value;
|
|
83
|
+
}
|
|
84
|
+
function sealedMember(dir: string, expected: CheckpointMember, maximum: number): Buffer {
|
|
85
|
+
const found = read(join(dir, expected.name), maximum);
|
|
86
|
+
if (!found || found.bytes.length !== expected.size || sha(found.bytes) !== expected.sha256) fail(); return found.bytes;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Content proof of the frozen windows, keyed by every member's stat stamp (the same trust the journal prefix cache uses).
|
|
90
|
+
* ponytail: one entry per process; a same-size in-place rewrite inside one timestamp tick is caught only on the next miss.
|
|
91
|
+
*/
|
|
92
|
+
let archiveProof: string | undefined;
|
|
93
|
+
function verifyArchive(archived: readonly ArchivedPlacementWindow[]): string {
|
|
94
|
+
const stamps: unknown[] = []; let members = 0, bytes = 0;
|
|
95
|
+
for (const window of archived) {
|
|
96
|
+
const names = list(window.dir, 4097);
|
|
97
|
+
if (canonicalJSON(names) !== canonicalJSON(window.members.map(member => member.name))) fail();
|
|
98
|
+
for (const member of window.members) {
|
|
99
|
+
const s = state(join(window.dir, member.name)); if (!s || s.size !== BigInt(member.size)) fail();
|
|
100
|
+
stamps.push([window.window, member.name, member.sha256, stamp(s)]); members++; bytes += member.size;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (members > PLACEMENT_CHECKPOINT_ARCHIVE_MAX_MEMBERS || bytes > PLACEMENT_CHECKPOINT_ARCHIVE_MAX_BYTES) fail("bound");
|
|
104
|
+
const key = canonicalJSON(stamps);
|
|
105
|
+
if (archiveProof !== key) {
|
|
106
|
+
for (const window of archived) for (const member of window.members) sealedMember(window.dir, member, MEMBER_MAX_BYTES);
|
|
107
|
+
archiveProof = key;
|
|
108
|
+
}
|
|
109
|
+
return sha(Buffer.from(key));
|
|
110
|
+
}
|
|
111
|
+
export function releasePlacementCheckpointCaches(): void { archiveProof = undefined; }
|
|
112
|
+
|
|
113
|
+
/** Resolve the live window of one epoch and verify every frozen window, manifest, catalog page and projection snapshot. */
|
|
114
|
+
export function resolvePlacementWindow(homeInput: string, epochHash: string): ResolvedPlacementWindow {
|
|
115
|
+
if (typeof epochHash !== "string" || !hex(epochHash)) fail("invalid");
|
|
116
|
+
const home = realPath(homeInput); const homeStat = state(home, true); if (!homeStat) fail("changed");
|
|
117
|
+
const epochDir = join(home, "sync-placement", "epochs", epochHash), root = join(home, PLACEMENT_CHECKPOINT_DIR), checkpointDir = join(root, epochHash);
|
|
118
|
+
const windowsDir = join(checkpointDir, PLACEMENT_CHECKPOINT_WINDOWS), empty = sha(Buffer.alloc(0));
|
|
119
|
+
const base = { home, epochHash, epochDir, checkpointDir, window: 0, dir: epochDir, parents: [home, join(home, "sync-placement"), join(home, "sync-placement", "epochs")],
|
|
120
|
+
archived: [], manifests: [], commits: [], catalog: new Map(), pending: false, logBytes: 0, logHash: empty };
|
|
121
|
+
const rootStat = state(root, true);
|
|
122
|
+
if (!rootStat) return { ...base, token: placementWindowToken(home, epochHash) };
|
|
123
|
+
for (const name of list(root, 4096)) if (!hex(name)) fail();
|
|
124
|
+
const dirStat = state(checkpointDir, true);
|
|
125
|
+
if (!dirStat) return { ...base, token: placementWindowToken(home, epochHash) };
|
|
126
|
+
for (const name of list(checkpointDir, 4)) if (![PLACEMENT_CHECKPOINT_COMMITS, PLACEMENT_CHECKPOINT_INTENT, PLACEMENT_CHECKPOINT_WINDOWS].includes(name)) fail();
|
|
127
|
+
// The intent: complete canonical bytes are a validated plan; a torn file is a pending checkpoint with no owned staging yet.
|
|
128
|
+
const intentFile = read(join(checkpointDir, PLACEMENT_CHECKPOINT_INTENT), PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES);
|
|
129
|
+
let intent: CheckpointIntent | undefined;
|
|
130
|
+
if (intentFile && intentFile.bytes.length && intentFile.bytes.at(-1) === 10) intent = decode(intentFile.bytes, validateCheckpointIntent);
|
|
131
|
+
if (intent && intent.epochHash !== epochHash) fail();
|
|
132
|
+
// The commit log: only complete lines are authority. A torn tail without an intent is corruption, never a commit.
|
|
133
|
+
const logFile = read(join(checkpointDir, PLACEMENT_CHECKPOINT_COMMITS), PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES), log = logFile?.bytes ?? Buffer.alloc(0);
|
|
134
|
+
const complete = log.lastIndexOf(10) + 1, torn = complete !== log.length;
|
|
135
|
+
if (torn && !intentFile) fail("pending");
|
|
136
|
+
if (logFile && !log.length && !intentFile) fail("pending");
|
|
137
|
+
const commits: CheckpointCommit[] = []; let head = checkpointCommitGenesis(epochHash), at = 0;
|
|
138
|
+
while (at < complete) {
|
|
139
|
+
const end = log.indexOf(10, at), commit = decode(log.subarray(at, end + 1), validateCheckpointCommit); at = end + 1;
|
|
140
|
+
if (commits.length >= PLACEMENT_CHECKPOINT_LIMIT) fail("bound");
|
|
141
|
+
if (commit.epochHash !== epochHash || commit.window !== commits.length + 1 || commit.previousHash !== head) fail();
|
|
142
|
+
commits.push(commit); head = commit.seal;
|
|
143
|
+
}
|
|
144
|
+
if (intent && (intent.window < commits.length || intent.window > commits.length + 1)) fail();
|
|
145
|
+
const windows = state(windowsDir, true) ? list(windowsDir, PLACEMENT_CHECKPOINT_LIMIT + 1) : [];
|
|
146
|
+
const expected = commits.map(commit => checkpointWindowName(commit.window));
|
|
147
|
+
if (intent && intent.window === commits.length + 1 && windows.length === expected.length + 1) expected.push(checkpointWindowName(intent.window));
|
|
148
|
+
if (canonicalJSON(windows) !== canonicalJSON(expected) || (commits.length && !state(windowsDir, true))) fail();
|
|
149
|
+
// Committed manifests chain from window 1 and each freezes exactly the window before it.
|
|
150
|
+
const manifests: CheckpointManifest[] = [], archived: ArchivedPlacementWindow[] = [], catalog = new Map<string, CatalogedPublication>();
|
|
151
|
+
let projection: CheckpointProjectionDigest | undefined;
|
|
152
|
+
for (const commit of commits) {
|
|
153
|
+
const dir = join(windowsDir, checkpointWindowName(commit.window)); state(dir, true) ?? fail();
|
|
154
|
+
const bytes = read(join(dir, PLACEMENT_CHECKPOINT_MANIFEST), PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES)?.bytes ?? fail();
|
|
155
|
+
const manifest = decode(bytes, validateCheckpointManifest), previous = manifests.at(-1);
|
|
156
|
+
if (manifest.seal !== commit.manifestHash || manifest.epochHash !== epochHash || manifest.window !== commit.window
|
|
157
|
+
|| manifest.previousManifestHash !== (previous?.seal ?? null)) fail();
|
|
158
|
+
if (previous && (manifest.journal.sequence < previous.journal.sequence || manifest.writer.sequence < previous.writer.sequence)) fail();
|
|
159
|
+
const frozen = { window: manifest.archived.window, dir: manifest.archived.window ? join(windowsDir, checkpointWindowName(manifest.archived.window)) : epochDir, members: manifest.archived.members };
|
|
160
|
+
if (frozen.members.some(member => member === undefined || member.name === "append-intent.json")) fail();
|
|
161
|
+
archived.push(frozen);
|
|
162
|
+
// Catalog pages: every completed publication the frozen window holds, by attempt, with exact members; nothing else.
|
|
163
|
+
const publications = new Map<string, CheckpointMember[]>();
|
|
164
|
+
for (const member of frozen.members) {
|
|
165
|
+
const match = /^publication-([a-f0-9]{64})-/.exec(member.name); if (!match) continue;
|
|
166
|
+
publications.set(match[1]!, [...publications.get(match[1]!) ?? [], member]);
|
|
167
|
+
}
|
|
168
|
+
let cataloged = 0;
|
|
169
|
+
for (const [index, page] of manifest.catalog.entries()) {
|
|
170
|
+
const value = decode(sealedMember(dir, page, PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES), validateCheckpointCatalogPage);
|
|
171
|
+
if (value.epochHash !== epochHash || value.window !== commit.window || value.page !== index) fail();
|
|
172
|
+
for (const entry of value.entries) {
|
|
173
|
+
const held = publications.get(entry.attemptHash);
|
|
174
|
+
if (entry.window !== frozen.window || !held || catalog.has(entry.attemptHash) || canonicalJSON(held) !== canonicalJSON(entry.members)) fail();
|
|
175
|
+
catalog.set(entry.attemptHash, { attemptHash: entry.attemptHash, window: frozen.window, dir: frozen.dir, members: entry.members }); cataloged++;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (cataloged !== publications.size) fail();
|
|
179
|
+
projection = decode(sealedMember(dir, manifest.projection, PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES), validateCheckpointProjection);
|
|
180
|
+
if (projection.epochHash !== epochHash || projection.window !== commit.window || canonicalJSON(projection.journal) !== canonicalJSON({ sequence: manifest.journal.sequence, headHash: manifest.journal.headHash })) fail();
|
|
181
|
+
// The commit line binds the window's (W, 1) writer revision and the first line of its writer commit log; a substituted
|
|
182
|
+
// internally valid pair would otherwise pass the local chain check from the window genesis.
|
|
183
|
+
const genesis = checkpointWriterGenesis(epochHash, manifest.activationHash, manifest.seal, manifest.writer.headHash);
|
|
184
|
+
const revision = decode(read(join(dir, writerRevisionFile(1)), WRITER_REVISION_MAX_BYTES)?.bytes ?? fail(), value => validateWriterRevision(value, genesis));
|
|
185
|
+
const writerLog = read(join(dir, WRITER_COMMIT_LOG), WRITER_COMMIT_MAX_BYTES)?.bytes ?? fail(), first = writerLog.indexOf(10);
|
|
186
|
+
if (first < 0) fail();
|
|
187
|
+
const writerCommit = decode(writerLog.subarray(0, first + 1), validateWriterCommit);
|
|
188
|
+
if (revision.seal !== commit.writerRevisionHash || writerCommit.seal !== commit.writerCommitHash) fail();
|
|
189
|
+
manifests.push(manifest);
|
|
190
|
+
}
|
|
191
|
+
if (archived.length) verifyArchive(archived);
|
|
192
|
+
const window = commits.length, dir = window ? join(windowsDir, checkpointWindowName(window)) : epochDir;
|
|
193
|
+
const token = placementWindowToken(home, epochHash);
|
|
194
|
+
if (logFile && !token.includes(stamp(logFile.stat)) || intentFile && !token.includes(stamp(intentFile.stat))) fail("changed");
|
|
195
|
+
return { home, epochHash, epochDir, checkpointDir, window, dir, archived, manifests, commits, catalog, ...(projection ? { projection } : {}),
|
|
196
|
+
parents: window ? [home, root, checkpointDir, windowsDir] : base.parents,
|
|
197
|
+
pending: !!intentFile || torn, ...(intent ? { intent } : {}), logBytes: log.length, logHash: sha(log), token };
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Cheap identity of the checkpoint state: directory identities, commit log and intent stamps. Archived window contents are
|
|
201
|
+
* immutable and content-verified by every `resolvePlacementWindow`; this token detects a checkpoint that starts, commits or
|
|
202
|
+
* is abandoned between two reads of the same operation.
|
|
203
|
+
*/
|
|
204
|
+
export function placementWindowToken(home: string, epochHash: string): string {
|
|
205
|
+
const root = join(home, PLACEMENT_CHECKPOINT_DIR), dir = join(root, epochHash), windows = join(dir, PLACEMENT_CHECKPOINT_WINDOWS);
|
|
206
|
+
const rootStat = state(root, true); if (!rootStat) return canonicalJSON(["none"]);
|
|
207
|
+
const dirStat = state(dir, true); if (!dirStat) return canonicalJSON(["root", String(rootStat.dev), String(rootStat.ino)]);
|
|
208
|
+
const log = state(join(dir, PLACEMENT_CHECKPOINT_COMMITS)), intent = state(join(dir, PLACEMENT_CHECKPOINT_INTENT)), windowsStat = state(windows, true);
|
|
209
|
+
const rows: unknown[] = [String(rootStat.dev), String(rootStat.ino), stamp(dirStat), log ? stamp(log) : null, intent ? stamp(intent) : null];
|
|
210
|
+
if (windowsStat) { rows.push(stamp(windowsStat)); for (const name of list(windows, PLACEMENT_CHECKPOINT_LIMIT + 1)) { const s = state(join(windows, name), true); if (!s) fail("changed"); rows.push([name, String(s.dev), String(s.ino)]); } }
|
|
211
|
+
return canonicalJSON(["checkpoint", rows]);
|
|
212
|
+
}
|
|
213
|
+
export { PLACEMENT_CHECKPOINT_COMMAND, PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./sync-placement-journal-format.ts";
|
|
214
|
+
/** True while a checkpoint is started and not finished; any other resolver failure is left to the caller's own read. */
|
|
215
|
+
export function placementCheckpointPending(home: string, epochHash: string): boolean {
|
|
216
|
+
try { return resolvePlacementWindow(home, epochHash).pending; }
|
|
217
|
+
catch (error) { return error instanceof SyncPlacementJournalError && Object.getOwnPropertyDescriptor(error, "code")?.value === "pending"; }
|
|
218
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Placement checkpoint writer (#288 step 2): plan, confirm, resume and abandon as library calls. The person CLI that
|
|
3
|
+
* previews and authorizes them is a later step; nothing here runs on the capture or hook path or is automatic.
|
|
4
|
+
*
|
|
5
|
+
* Write order: outside intent -> staged window (catalog pages, projection snapshot, (W, 1) writer revision and commit
|
|
6
|
+
* log, manifest last) -> one complete line in commits.jsonl (the commit point) -> intent cleared. The frozen window is
|
|
7
|
+
* never touched, no log line is rewritten and nothing is deleted except the intent's own staging before the commit byte.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, rmdirSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { canonicalJSON } from "./generation.ts";
|
|
13
|
+
import { realPath } from "./platform.ts";
|
|
14
|
+
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
15
|
+
import { SyncPlacementJournalError, type SyncPlacementJournalErrorCode } from "./sync-placement-journal-format.ts";
|
|
16
|
+
import { rebuildPlacementProjection } from "./sync-placement-projection.ts";
|
|
17
|
+
import { readPlacementJournal, readPlacementPublicationMetadata, releasePlacementStorageCaches } from "./sync-placement-journal-storage.ts";
|
|
18
|
+
import { readWriterHistory, type WriterHistoryBinding } from "./sync-placement-writer-history.ts";
|
|
19
|
+
import { createWriterCommit, createWriterRevision, WRITER_COMMIT_LOG, WRITER_REVISION_SCHEMA, writerRevisionFile } from "./sync-placement-writer-revision-format.ts";
|
|
20
|
+
import type { MeasuredSyncPlacementWriterRoot } from "./sync-placement-writers.ts";
|
|
21
|
+
import { resolvePlacementWindow, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
22
|
+
import {
|
|
23
|
+
PLACEMENT_CHECKPOINT_DIR, PLACEMENT_CHECKPOINT_COMMITS, PLACEMENT_CHECKPOINT_INTENT, PLACEMENT_CHECKPOINT_WINDOWS, PLACEMENT_CHECKPOINT_MANIFEST,
|
|
24
|
+
PLACEMENT_CHECKPOINT_PROJECTION, PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA, PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA, PLACEMENT_CHECKPOINT_COMMIT_SCHEMA,
|
|
25
|
+
PLACEMENT_CHECKPOINT_INTENT_SCHEMA, PLACEMENT_CHECKPOINT_LIMIT, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES,
|
|
26
|
+
checkpointCatalogName, checkpointCommitGenesis, checkpointWindowName, checkpointWriterGenesis, createCheckpointCommit, createCheckpointIntent,
|
|
27
|
+
createCheckpointManifest, paginateCheckpointCatalog, validateCheckpointIntent,
|
|
28
|
+
type CheckpointCatalogEntry, type CheckpointIntent, type CheckpointMember,
|
|
29
|
+
} from "./sync-placement-checkpoint-format.ts";
|
|
30
|
+
|
|
31
|
+
export type PlacementCheckpointPhase = "intent-written" | "intent-file-fsync" | "intent-fsync" | "staged-file" | "staged-file-fsync" | "staged-fsync" | "commit-started" | "commit-written" | "commit-file-fsync" | "commit-fsync" | "directory-fsync" | "intent-cleared";
|
|
32
|
+
// ponytail: commitPrefix is an isolated-test seam for every commit-byte crash; remove it when the shared fault injector supports byte boundaries.
|
|
33
|
+
export interface PlacementCheckpointOptions { mutation: MutationHandle; assertCurrent(): void; phase?(phase: PlacementCheckpointPhase): void; commitPrefix?(bytes: number): void }
|
|
34
|
+
export interface PlacementCheckpointInput {
|
|
35
|
+
binding: WriterHistoryBinding & { initialLocatorHash: string };
|
|
36
|
+
/** The measured writer roots for the combined (W, 1) renewal; a caller measures them fresh. */
|
|
37
|
+
roots: MeasuredSyncPlacementWriterRoot[];
|
|
38
|
+
requestId: string;
|
|
39
|
+
}
|
|
40
|
+
const sha = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
41
|
+
const line = (value: unknown) => Buffer.from(canonicalJSON(value) + "\n");
|
|
42
|
+
const stamp = (s: BigIntStats) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":");
|
|
43
|
+
function fail(code: SyncPlacementJournalErrorCode = "corrupt"): never { throw new SyncPlacementJournalError(code); }
|
|
44
|
+
function owned(s: BigIntStats, directory = false): void {
|
|
45
|
+
const uid = process.getuid?.();
|
|
46
|
+
if (uid === undefined || s.uid !== BigInt(uid) || (s.mode & 0o077n) !== 0n || s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1n)) fail();
|
|
47
|
+
}
|
|
48
|
+
function readFile(file: string, maximum: number): Buffer | undefined {
|
|
49
|
+
const before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!before) return undefined; owned(before); if (before.size > BigInt(maximum)) fail("bound");
|
|
50
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
51
|
+
try {
|
|
52
|
+
const opened = fstatSync(fd, { bigint: true }); if (stamp(opened) !== stamp(before)) fail("changed");
|
|
53
|
+
const bytes = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
54
|
+
while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
|
|
55
|
+
if (at !== Number(opened.size)) fail("changed"); return bytes.subarray(0, at);
|
|
56
|
+
} finally { closeSync(fd); }
|
|
57
|
+
}
|
|
58
|
+
function list(dir: string): string[] {
|
|
59
|
+
const reader = opendirSync(dir), out: string[] = [];
|
|
60
|
+
try { for (;;) { const entry = reader.readSync(); if (!entry) break; if (out.length > 4096) fail("bound"); out.push(entry.name); } } finally { reader.closeSync(); }
|
|
61
|
+
return out.sort();
|
|
62
|
+
}
|
|
63
|
+
function proof(home: string, opts: PlacementCheckpointOptions): void {
|
|
64
|
+
try { assertMutationHandle(opts.mutation, home); } catch { fail("busy"); }
|
|
65
|
+
try { opts.assertCurrent(); } catch (error) { if (error instanceof SyncPlacementJournalError) throw error; fail("changed"); }
|
|
66
|
+
try { assertMutationHandle(opts.mutation, home); } catch { fail("busy"); }
|
|
67
|
+
}
|
|
68
|
+
function syncDir(home: string, dir: string, opts: PlacementCheckpointOptions): void {
|
|
69
|
+
proof(home, opts); const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
70
|
+
try { owned(fstatSync(fd, { bigint: true }), true); fsyncSync(fd); opts.phase?.("directory-fsync"); } finally { closeSync(fd); }
|
|
71
|
+
}
|
|
72
|
+
function ensureDir(home: string, dir: string, parent: string, opts: PlacementCheckpointOptions): void {
|
|
73
|
+
const s = lstatSync(dir, { bigint: true, throwIfNoEntry: false });
|
|
74
|
+
if (s) { owned(s, true); return; }
|
|
75
|
+
proof(home, opts); mkdirSync(dir, { mode: 0o700 }); owned(lstatSync(dir, { bigint: true }), true); syncDir(home, parent, opts);
|
|
76
|
+
}
|
|
77
|
+
/** Exact prefix completion, the only recovery write: an existing file must be a prefix of `expected`; nothing is truncated. */
|
|
78
|
+
function complete(home: string, file: string, dir: string, expected: Buffer, opts: PlacementCheckpointOptions, written: PlacementCheckpointPhase, synced: PlacementCheckpointPhase, startPhase?: { at: number; phase: PlacementCheckpointPhase }): void {
|
|
79
|
+
proof(home, opts); const prior = readFile(file, expected.length + 1);
|
|
80
|
+
if (prior && (prior.length > expected.length || !expected.subarray(0, prior.length).equals(prior))) fail("conflict");
|
|
81
|
+
if (prior?.equals(expected)) { const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); try { fsyncSync(fd); } finally { closeSync(fd); } syncDir(home, dir, opts); return; }
|
|
82
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | (prior ? 0 : constants.O_CREAT | constants.O_EXCL), 0o600);
|
|
83
|
+
try {
|
|
84
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (Number(opened.size) !== (prior?.length ?? 0)) fail("changed");
|
|
85
|
+
let at = prior?.length ?? 0;
|
|
86
|
+
while (at < expected.length) {
|
|
87
|
+
proof(home, opts); const first = startPhase !== undefined && at === startPhase.at;
|
|
88
|
+
const n = writeSync(fd, expected, at, first || (startPhase && opts.commitPrefix) ? 1 : expected.length - at, at); if (n < 1) fail(); at += n; if (first) opts.phase?.(startPhase!.phase);
|
|
89
|
+
if (startPhase) opts.commitPrefix?.(at - startPhase.at);
|
|
90
|
+
}
|
|
91
|
+
opts.phase?.(written); proof(home, opts); fsyncSync(fd);
|
|
92
|
+
opts.phase?.(synced === "intent-fsync" ? "intent-file-fsync" : synced === "staged-fsync" ? "staged-file-fsync" : "commit-file-fsync");
|
|
93
|
+
} finally { closeSync(fd); }
|
|
94
|
+
syncDir(home, dir, opts); opts.phase?.(synced);
|
|
95
|
+
if (!readFile(file, expected.length)?.equals(expected)) fail("changed");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Every member of the live window, by exact content. A member that is not settled history refuses the checkpoint. */
|
|
99
|
+
function liveMembers(window: ResolvedPlacementWindow): CheckpointMember[] {
|
|
100
|
+
return list(window.dir).map(name => {
|
|
101
|
+
if (name === "append-intent.json") fail("pending");
|
|
102
|
+
const bytes = readFile(join(window.dir, name), 1024 * 1024) ?? fail("changed");
|
|
103
|
+
return { name, size: bytes.length, sha256: sha(bytes) };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Readonly plan of the next checkpoint: freezes the live window, catalogs its completed publications, seals the replayed
|
|
108
|
+
* projection and prepares the combined (W, 1) renewal. Refuses any open obligation (pending append, publication,
|
|
109
|
+
* reservation or renewal) instead of carrying it across windows.
|
|
110
|
+
*/
|
|
111
|
+
export function planPlacementCheckpoint(homeInput: string, epochHash: string, input: PlacementCheckpointInput): CheckpointIntent {
|
|
112
|
+
const home = realPath(homeInput), window = resolvePlacementWindow(home, epochHash);
|
|
113
|
+
if (window.pending) fail("pending");
|
|
114
|
+
if (window.window + 1 > PLACEMENT_CHECKPOINT_LIMIT) fail("bound");
|
|
115
|
+
const journal = readPlacementJournal(home, epochHash);
|
|
116
|
+
if (journal.pending || journal.publicationReservation) fail("pending");
|
|
117
|
+
if (journal.activation.seal !== input.binding.activationHash || journal.epoch.homeHash !== input.binding.homeHash || journal.epoch.generation !== input.binding.generation) fail("changed");
|
|
118
|
+
const history = readWriterHistory(home, input.binding);
|
|
119
|
+
if (history.pending) fail("pending");
|
|
120
|
+
const members = liveMembers(window), entries: CheckpointCatalogEntry[] = [];
|
|
121
|
+
readPlacementPublicationMetadata(home, epochHash, io => {
|
|
122
|
+
const attempts = new Set(members.flatMap(member => /^publication-([a-f0-9]{64})-/.exec(member.name)?.[1] ?? []));
|
|
123
|
+
for (const attempt of [...attempts].sort()) {
|
|
124
|
+
const publication = io.publication(attempt);
|
|
125
|
+
if (publication.phase !== "completed" || publication.pending) fail("pending");
|
|
126
|
+
entries.push({ attemptHash: attempt, window: window.window, members: members.filter(member => member.name.startsWith(`publication-${attempt}-`)) });
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
const next = window.window + 1, pages = paginateCheckpointCatalog(epochHash, next, entries);
|
|
130
|
+
const projection = { schema: PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA, epochHash, window: next, journal: { sequence: journal.sequence, headHash: journal.headHash },
|
|
131
|
+
projectionHash: rebuildPlacementProjection(journal.epoch, journal.records).digest() } as const;
|
|
132
|
+
const digest = (name: string, value: unknown): CheckpointMember => { const bytes = line(value); return { name, size: bytes.length, sha256: sha(bytes) }; };
|
|
133
|
+
const archivedChunks = (window.manifests.at(-1)?.journal.chunks ?? 0) + members.filter(member => /^records-\d{5}\.jsonl$/.test(member.name)).length;
|
|
134
|
+
const manifest = createCheckpointManifest({ schema: PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA, epochHash, activationHash: input.binding.activationHash, window: next,
|
|
135
|
+
previousManifestHash: window.manifests.at(-1)?.seal ?? null, archived: { window: window.window, members },
|
|
136
|
+
journal: { sequence: journal.sequence, headHash: journal.headHash, chunks: archivedChunks },
|
|
137
|
+
writer: { sequence: history.commits.length, headHash: history.headHash },
|
|
138
|
+
catalog: pages.map((page, index) => digest(checkpointCatalogName(index), page)), projection: digest(PLACEMENT_CHECKPOINT_PROJECTION, projection) });
|
|
139
|
+
const genesis = checkpointWriterGenesis(epochHash, input.binding.activationHash, manifest.seal, history.headHash);
|
|
140
|
+
const writerRevision = createWriterRevision({ schema: WRITER_REVISION_SCHEMA, epochHash, generation: input.binding.generation, homeHash: input.binding.homeHash,
|
|
141
|
+
activationHash: input.binding.activationHash, initialLocatorHash: input.binding.initialLocatorHash, sequence: 1, previousHash: genesis,
|
|
142
|
+
journal: { sequence: journal.sequence, headHash: journal.headHash }, roots: input.roots, requestId: input.requestId }, genesis);
|
|
143
|
+
const writerCommit = createWriterCommit(writerRevision, genesis);
|
|
144
|
+
const previous = window.commits.at(-1)?.seal ?? checkpointCommitGenesis(epochHash);
|
|
145
|
+
const commit = createCheckpointCommit({ schema: PLACEMENT_CHECKPOINT_COMMIT_SCHEMA, epochHash, window: next, previousHash: previous, manifestHash: manifest.seal,
|
|
146
|
+
writerRevisionHash: writerRevision.seal, writerCommitHash: writerCommit.seal });
|
|
147
|
+
const log = readFile(join(window.checkpointDir, PLACEMENT_CHECKPOINT_COMMITS), PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES) ?? Buffer.alloc(0);
|
|
148
|
+
return createCheckpointIntent({ schema: PLACEMENT_CHECKPOINT_INTENT_SCHEMA, epochHash, window: next, previousLogBytes: log.length, previousLogHash: sha(log),
|
|
149
|
+
manifest, commit, pages, projection, writerRevision, writerCommit });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function staged(intent: CheckpointIntent): [string, Buffer][] {
|
|
153
|
+
return [...intent.pages.map((page, index): [string, Buffer] => [checkpointCatalogName(index), line(page)]),
|
|
154
|
+
[PLACEMENT_CHECKPOINT_PROJECTION, line(intent.projection)], [writerRevisionFile(1), line(intent.writerRevision)],
|
|
155
|
+
[WRITER_COMMIT_LOG, line(intent.writerCommit)], [PLACEMENT_CHECKPOINT_MANIFEST, line(intent.manifest)]];
|
|
156
|
+
}
|
|
157
|
+
function layout(home: string, epochHash: string, window: number) {
|
|
158
|
+
const root = join(home, PLACEMENT_CHECKPOINT_DIR), dir = join(root, epochHash), windows = join(dir, PLACEMENT_CHECKPOINT_WINDOWS);
|
|
159
|
+
return { root, dir, windows, window: join(windows, checkpointWindowName(window)), intent: join(dir, PLACEMENT_CHECKPOINT_INTENT), log: join(dir, PLACEMENT_CHECKPOINT_COMMITS) };
|
|
160
|
+
}
|
|
161
|
+
/** Completes the frozen bytes of one intent: staging, then the commit line, then the intent. Idempotent after a lost acknowledgement. */
|
|
162
|
+
function finish(home: string, intent: CheckpointIntent, opts: PlacementCheckpointOptions): void {
|
|
163
|
+
const l = layout(home, intent.epochHash, intent.window);
|
|
164
|
+
ensureDir(home, l.windows, l.dir, opts); ensureDir(home, l.window, l.windows, opts);
|
|
165
|
+
for (const [name, bytes] of staged(intent)) complete(home, join(l.window, name), l.window, bytes, opts, "staged-file", "staged-fsync");
|
|
166
|
+
// Reread the closure before the commit point: every staged name, nothing else.
|
|
167
|
+
if (canonicalJSON(list(l.window)) !== canonicalJSON(staged(intent).map(([name]) => name).sort())) fail("changed");
|
|
168
|
+
const prefix = readFile(l.log, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES) ?? Buffer.alloc(0);
|
|
169
|
+
if (prefix.length < intent.previousLogBytes || sha(prefix.subarray(0, intent.previousLogBytes)) !== intent.previousLogHash) fail("changed");
|
|
170
|
+
complete(home, l.log, l.dir, Buffer.concat([prefix.subarray(0, intent.previousLogBytes), line(intent.commit)]), opts, "commit-written", "commit-fsync", { at: intent.previousLogBytes, phase: "commit-started" });
|
|
171
|
+
proof(home, opts); unlinkSync(l.intent); syncDir(home, l.dir, opts); opts.phase?.("intent-cleared");
|
|
172
|
+
releasePlacementStorageCaches();
|
|
173
|
+
const resolved = resolvePlacementWindow(home, intent.epochHash);
|
|
174
|
+
if (resolved.pending || resolved.window !== intent.window || resolved.manifests.at(-1)?.seal !== intent.manifest.seal) fail("changed");
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Confirm one exact planned checkpoint.
|
|
178
|
+
* The person CLI checks the 0.30.0 home floor and writers before calling this internal storage primitive.
|
|
179
|
+
* Only `amem formats raise` records a floor.
|
|
180
|
+
*/
|
|
181
|
+
export function applyPlacementCheckpoint(homeInput: string, plan: CheckpointIntent, input: PlacementCheckpointInput, opts: PlacementCheckpointOptions): { window: number } {
|
|
182
|
+
const home = realPath(homeInput), intent = validateCheckpointIntent(plan);
|
|
183
|
+
proof(home, opts);
|
|
184
|
+
if (canonicalJSON(planPlacementCheckpoint(home, intent.epochHash, { ...input, requestId: intent.writerRevision.requestId })) !== canonicalJSON(intent)) fail("changed");
|
|
185
|
+
const l = layout(home, intent.epochHash, intent.window);
|
|
186
|
+
ensureDir(home, l.root, home, opts); ensureDir(home, l.dir, l.root, opts);
|
|
187
|
+
complete(home, l.intent, l.dir, line(intent), opts, "intent-written", "intent-fsync");
|
|
188
|
+
// From here on every placement effect refuses with the pending cause until finish or abandon.
|
|
189
|
+
finish(home, intent, opts);
|
|
190
|
+
return { window: intent.window };
|
|
191
|
+
}
|
|
192
|
+
/** Resume a written intent from its own frozen bytes; metadata only, no fresh source, policy or install measurement. */
|
|
193
|
+
export function resumePlacementCheckpoint(homeInput: string, epochHash: string, opts: PlacementCheckpointOptions): { window: number } | undefined {
|
|
194
|
+
const home = realPath(homeInput), l = layout(home, epochHash, 1), bytes = readFile(l.intent, 1024 * 1024);
|
|
195
|
+
if (!bytes) return undefined;
|
|
196
|
+
if (!bytes.length || bytes.at(-1) !== 10) fail("pending"); // A torn intent has no staging: abandon it.
|
|
197
|
+
const intent = validateCheckpointIntent(JSON.parse(bytes.toString("utf8")));
|
|
198
|
+
if (intent.epochHash !== epochHash || !line(intent).equals(bytes)) fail();
|
|
199
|
+
proof(home, opts); finish(home, intent, opts); return { window: intent.window };
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Before the first commit byte, remove only the intent's own staging and then the intent. After it, refuse: only resume
|
|
203
|
+
* may finish a checkpoint whose commit line has started.
|
|
204
|
+
*/
|
|
205
|
+
export function abandonPlacementCheckpoint(homeInput: string, epochHash: string, opts: PlacementCheckpointOptions): { removed: number } {
|
|
206
|
+
const home = realPath(homeInput), l0 = layout(home, epochHash, 1), bytes = readFile(l0.intent, 1024 * 1024);
|
|
207
|
+
if (!bytes) return { removed: 0 };
|
|
208
|
+
let removed = 0;
|
|
209
|
+
if (bytes.length && bytes.at(-1) === 10) {
|
|
210
|
+
const intent = validateCheckpointIntent(JSON.parse(bytes.toString("utf8"))), l = layout(home, epochHash, intent.window);
|
|
211
|
+
const log = readFile(l.log, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES) ?? Buffer.alloc(0);
|
|
212
|
+
if (log.length > intent.previousLogBytes) fail("pending");
|
|
213
|
+
// finish() creates the first commit log before its first byte; a crash there leaves an empty log the resolver refuses.
|
|
214
|
+
const emptyLog = intent.previousLogBytes === 0 ? lstatSync(l.log, { bigint: true, throwIfNoEntry: false }) : undefined;
|
|
215
|
+
if (emptyLog) { owned(emptyLog); if (emptyLog.size !== 0n) fail("pending"); }
|
|
216
|
+
if (lstatSync(l.window, { throwIfNoEntry: false })) {
|
|
217
|
+
// Check every name first: a foreign file refuses before anything is removed.
|
|
218
|
+
const owned = new Map(staged(intent)), names = list(l.window);
|
|
219
|
+
for (const name of names) {
|
|
220
|
+
const expected = owned.get(name); if (!expected) fail("conflict");
|
|
221
|
+
const found = readFile(join(l.window, name), expected.length); if (!found || !expected.subarray(0, found.length).equals(found)) fail("conflict");
|
|
222
|
+
}
|
|
223
|
+
for (const name of names) { proof(home, opts); unlinkSync(join(l.window, name)); removed++; }
|
|
224
|
+
syncDir(home, l.window, opts); proof(home, opts); rmdirSync(l.window); syncDir(home, l.windows, opts);
|
|
225
|
+
}
|
|
226
|
+
if (emptyLog) { proof(home, opts); unlinkSync(l.log); syncDir(home, l.dir, opts); }
|
|
227
|
+
} else if (lstatSync(l0.windows, { throwIfNoEntry: false })) {
|
|
228
|
+
// A torn intent was never followed by staging (the intent is fsynced first); a window beyond the commits is foreign.
|
|
229
|
+
const commits = (readFile(l0.log, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES) ?? Buffer.alloc(0)).toString("utf8").split("\n").filter(Boolean).length;
|
|
230
|
+
if (list(l0.windows).length !== commits) fail("conflict");
|
|
231
|
+
}
|
|
232
|
+
proof(home, opts); unlinkSync(l0.intent); syncDir(home, l0.dir, opts); releasePlacementStorageCaches();
|
|
233
|
+
return { removed };
|
|
234
|
+
}
|