@staix/agent-mem 0.28.2 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -7
- package/package.json +1 -1
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +34 -13
- package/src/commands-table.ts +2 -0
- package/src/mcp-memory.ts +1 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +15 -12
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/metrics.ts +1 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-capture.ts +53 -17
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inventory.ts +136 -0
- package/src/memory/sync-placement-journal-storage.ts +21 -4
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +14 -3
- package/src/memory/sync-placement-publication-plan.ts +8 -4
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +335 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-transport.ts +69 -31
- package/src/memory/sync-placement-yield.ts +30 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +23 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Data-only frozen admission intent. The intent is evidence to recheck, not authorization. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { types } from "node:util";
|
|
5
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
6
|
+
import { REALM_EXTENSION_LIMIT, REALM_EXTENSION_LOG_MAX_BYTES, RealmExtensionFormatError, realmExtensionGenesis } from "./sync-placement-realm-extension-format.ts";
|
|
7
|
+
|
|
8
|
+
export const REALM_INTENT_SCHEMA = "agent-mem.sync-placement-realm-intent/v1";
|
|
9
|
+
export const REALM_INTENT_MAX_BYTES = 16 * 1024;
|
|
10
|
+
export interface RealmIntentBody {
|
|
11
|
+
schema: typeof REALM_INTENT_SCHEMA;
|
|
12
|
+
home: string; project: string; keyHash: string; machine: string;
|
|
13
|
+
epochHash: string; activationHash: string; homeHash: string; generation: string;
|
|
14
|
+
sequence: number; previousHash: string; previousLogBytes: number; previousLogHash: string;
|
|
15
|
+
mode: "new" | "existing"; descriptorHash: string | null; sourceHash: string | null;
|
|
16
|
+
aliasesHash: string; policyHash: string; writerHash: string; journal: { sequence: number; headHash: string };
|
|
17
|
+
}
|
|
18
|
+
export interface RealmIntent extends RealmIntentBody { seal: string }
|
|
19
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
20
|
+
function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
|
|
21
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
|
|
22
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return fail();
|
|
23
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
24
|
+
if (Object.keys(fields).length !== keys.length || Object.getOwnPropertyNames(value).length !== keys.length) return fail();
|
|
25
|
+
const copy: Record<string, unknown> = Object.create(null);
|
|
26
|
+
for (const key of keys) { const field = fields[key]; if (!field || !("value" in field) || !field.enumerable) return fail(); copy[key] = field.value; }
|
|
27
|
+
return copy;
|
|
28
|
+
}
|
|
29
|
+
function hex(value: unknown, width = 64): string { if (typeof value !== "string" || value.length !== width || !/^[a-f0-9]+$/.test(value)) return fail(); return value; }
|
|
30
|
+
function integer(value: unknown, min: number, max: number): number { if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) return fail(); return value; }
|
|
31
|
+
function checked(input: unknown, sealed: boolean): RealmIntent {
|
|
32
|
+
const row = object(input, ["schema", "home", "project", "keyHash", "machine", "epochHash", "activationHash", "homeHash", "generation", "sequence", "previousHash",
|
|
33
|
+
"previousLogBytes", "previousLogHash", "mode", "descriptorHash", "sourceHash", "aliasesHash", "policyHash", "writerHash", "journal", ...(sealed ? ["seal"] : [])]);
|
|
34
|
+
const journal = object(row.journal, ["sequence", "headHash"]);
|
|
35
|
+
if (row.schema !== REALM_INTENT_SCHEMA || typeof row.home !== "string" || !isAbsolute(row.home) || resolve(row.home) !== row.home || row.home.includes("\0") || Buffer.byteLength(row.home) > 4096
|
|
36
|
+
|| typeof row.project !== "string" || !row.project.trim() || Buffer.byteLength(row.project) > 400 || /[\r\n\0]/.test(row.project)
|
|
37
|
+
|| (row.mode !== "new" && row.mode !== "existing")) return fail();
|
|
38
|
+
const body: RealmIntentBody = { schema: REALM_INTENT_SCHEMA, home: row.home, project: row.project, keyHash: hex(row.keyHash), machine: hex(row.machine, 16),
|
|
39
|
+
epochHash: hex(row.epochHash), activationHash: hex(row.activationHash), homeHash: hex(row.homeHash), generation: hex(row.generation, 32),
|
|
40
|
+
sequence: integer(row.sequence, 1, REALM_EXTENSION_LIMIT), previousHash: hex(row.previousHash), previousLogBytes: integer(row.previousLogBytes, 0, REALM_EXTENSION_LOG_MAX_BYTES),
|
|
41
|
+
previousLogHash: hex(row.previousLogHash), mode: row.mode, descriptorHash: row.descriptorHash === null ? null : hex(row.descriptorHash), sourceHash: row.sourceHash === null ? null : hex(row.sourceHash),
|
|
42
|
+
aliasesHash: hex(row.aliasesHash), policyHash: hex(row.policyHash), writerHash: hex(row.writerHash), journal: { sequence: integer(journal.sequence, 0, 20_000), headHash: hex(journal.headHash) } };
|
|
43
|
+
const empty = createHash("sha256").update("").digest("hex");
|
|
44
|
+
if (createHash("sha256").update(body.project).digest("hex") !== body.keyHash
|
|
45
|
+
|| (body.sequence === 1) !== (body.previousLogBytes === 0) || body.previousLogBytes === 0 && body.previousLogHash !== empty
|
|
46
|
+
|| body.sequence === 1 && body.previousHash !== realmExtensionGenesis(body.epochHash, body.activationHash)
|
|
47
|
+
|| body.journal.sequence === 0 && body.journal.headHash !== body.epochHash
|
|
48
|
+
|| body.mode === "existing" && (!body.descriptorHash || !body.sourceHash)
|
|
49
|
+
|| body.mode === "new" && body.sourceHash !== null) return fail();
|
|
50
|
+
const result = { ...body, seal: hashJSON(body) };
|
|
51
|
+
if (sealed && hex(row.seal) !== result.seal || Buffer.byteLength(canonicalJSON(result) + "\n") > REALM_INTENT_MAX_BYTES) return fail();
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
export function createRealmIntent(input: RealmIntentBody): RealmIntent { return checked(input, false); }
|
|
55
|
+
export function validateRealmIntent(input: unknown): RealmIntent { return checked(input, true); }
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** Frozen admission intent storage. The caller owns person authority, the profile lock and the home mutation fence. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, opendirSync, readSync, renameSync, unlinkSync, writeFileSync, type BigIntStats } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { canonicalJSON } from "./generation.ts";
|
|
6
|
+
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
7
|
+
import { realPath } from "./platform.ts";
|
|
8
|
+
import { RealmExtensionFormatError } from "./sync-placement-realm-extension-format.ts";
|
|
9
|
+
import { REALM_INTENT_MAX_BYTES, validateRealmIntent, type RealmIntent } from "./sync-placement-realm-intent-format.ts";
|
|
10
|
+
import { REALM_INTENT_PREFIX } from "./sync-placement-realm-pending.ts";
|
|
11
|
+
|
|
12
|
+
export interface RealmIntentProof { mutation: MutationHandle; assertCurrent(): void }
|
|
13
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
14
|
+
const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
15
|
+
const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
|
|
16
|
+
const owned = (stat: BigIntStats): void => {
|
|
17
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o777n) !== 0o600n) fail();
|
|
18
|
+
};
|
|
19
|
+
export const realmIntentPath = (home: string, keyHash: string): string => join(home, `${REALM_INTENT_PREFIX}${keyHash}.json`);
|
|
20
|
+
/** The staging name carries the digest of the exact bytes, so a retained staging file is either ours or unknown. */
|
|
21
|
+
const stagingPath = (file: string, text: string): string => `${file}.pending-${digest(Buffer.from(text))}`;
|
|
22
|
+
|
|
23
|
+
interface IntentStage { name: string; stamp: string; size: number; hash: string }
|
|
24
|
+
/** Bounded, private staging evidence for one realm; never returns its content. */
|
|
25
|
+
export function inspectRealmIntentStages(homeInput: string, keyHash: string): IntentStage[] {
|
|
26
|
+
if (!/^[a-f0-9]{64}$/.test(keyHash)) fail();
|
|
27
|
+
const home = realPath(homeInput), prefix = `${REALM_INTENT_PREFIX}${keyHash}.json.pending-`, stages: IntentStage[] = [];
|
|
28
|
+
const directory = opendirSync(home); let count = 0;
|
|
29
|
+
try {
|
|
30
|
+
for (;;) {
|
|
31
|
+
const entry = directory.readSync(); if (!entry) break;
|
|
32
|
+
if (++count > 20_000) fail();
|
|
33
|
+
if (!entry.name.startsWith(prefix)) continue;
|
|
34
|
+
if (!/^[a-f0-9]{64}$/.test(entry.name.slice(prefix.length)) || stages.length >= 64) fail();
|
|
35
|
+
const file = join(home, entry.name), before = lstatSync(file, { bigint: true }); owned(before);
|
|
36
|
+
if (before.size > BigInt(REALM_INTENT_MAX_BYTES)) fail();
|
|
37
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
38
|
+
try {
|
|
39
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
|
|
40
|
+
const bytes = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
41
|
+
while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
|
|
42
|
+
if (at !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened)
|
|
43
|
+
|| stamp(lstatSync(file, { bigint: true })) !== stamp(opened)) fail();
|
|
44
|
+
stages.push({ name: entry.name, stamp: stamp(opened), size: at, hash: digest(bytes.subarray(0, at)) });
|
|
45
|
+
} finally { closeSync(fd); }
|
|
46
|
+
}
|
|
47
|
+
} finally { directory.closeSync(); }
|
|
48
|
+
return stages.sort((a, b) => a.name.localeCompare(b.name));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Confirmed abandon removes only the exact private stages rechecked under the mutation fence. */
|
|
52
|
+
export function clearRealmIntentStages(homeInput: string, keyHash: string, expected: IntentStage[], options: RealmIntentProof): void {
|
|
53
|
+
const home = realPath(homeInput); proof(home, options);
|
|
54
|
+
if (canonicalJSON(inspectRealmIntentStages(home, keyHash)) !== canonicalJSON(expected)) fail();
|
|
55
|
+
for (const stage of expected) {
|
|
56
|
+
proof(home, options);
|
|
57
|
+
const file = join(home, stage.name), now = lstatSync(file, { bigint: true }); owned(now);
|
|
58
|
+
if (stamp(now) !== stage.stamp) fail();
|
|
59
|
+
unlinkSync(file); syncDirectory(home);
|
|
60
|
+
}
|
|
61
|
+
proof(home, options);
|
|
62
|
+
if (inspectRealmIntentStages(home, keyHash).length) fail();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function read(home: string, keyHash: string): { intent: RealmIntent; text: string; stat: BigIntStats } | undefined {
|
|
66
|
+
const file = realmIntentPath(home, keyHash), before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
67
|
+
if (!before) return undefined;
|
|
68
|
+
owned(before); if (before.size <= 0n || before.size > BigInt(REALM_INTENT_MAX_BYTES)) fail();
|
|
69
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
70
|
+
let bytes: Buffer;
|
|
71
|
+
try {
|
|
72
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
|
|
73
|
+
const data = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
74
|
+
while (at < data.length) { const count = readSync(fd, data, at, data.length - at, at); if (!count) break; at += count; }
|
|
75
|
+
if (at !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(file, { bigint: true })) !== stamp(opened)) fail();
|
|
76
|
+
bytes = data.subarray(0, at);
|
|
77
|
+
} finally { closeSync(fd); }
|
|
78
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes), intent = validateRealmIntent(JSON.parse(text));
|
|
79
|
+
if (canonicalJSON(intent) + "\n" !== text || intent.keyHash !== keyHash) fail();
|
|
80
|
+
return { intent, text, stat: before };
|
|
81
|
+
}
|
|
82
|
+
/** Absent is absent; unsafe, torn or foreign evidence refuses instead of reading as no intent. */
|
|
83
|
+
export function readRealmIntent(home: string, keyHash: string): RealmIntent | undefined { return read(realPath(home), keyHash)?.intent; }
|
|
84
|
+
/** Attribution evidence: anything unreadable attributes nothing, so a tail cannot borrow another file's authority. */
|
|
85
|
+
export function realmIntentEvidence(home: string, keyHash: string): RealmIntent | null {
|
|
86
|
+
try { return read(realPath(home), keyHash)?.intent ?? null; } catch { return null; }
|
|
87
|
+
}
|
|
88
|
+
function syncDirectory(dir: string): void { const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(fd); } finally { closeSync(fd); } }
|
|
89
|
+
function proof(home: string, options: RealmIntentProof): void {
|
|
90
|
+
try { assertMutationHandle(options.mutation, home); options.assertCurrent(); assertMutationHandle(options.mutation, home); } catch { fail(); }
|
|
91
|
+
}
|
|
92
|
+
/** Idempotent: identical retained bytes are kept, a different retained intent refuses rather than being replaced. */
|
|
93
|
+
export function writeRealmIntent(home: string, value: RealmIntent, options: RealmIntentProof): void {
|
|
94
|
+
const intent = validateRealmIntent(value), expected = canonicalJSON(intent) + "\n";
|
|
95
|
+
if (intent.home !== realPath(home)) fail();
|
|
96
|
+
proof(home, options);
|
|
97
|
+
const prior = read(home, intent.keyHash);
|
|
98
|
+
if (prior) { if (prior.text !== expected) fail(); proof(home, options); return; }
|
|
99
|
+
const file = realmIntentPath(home, intent.keyHash), staging = stagingPath(file, expected), retained = lstatSync(staging, { bigint: true, throwIfNoEntry: false });
|
|
100
|
+
if (!retained) {
|
|
101
|
+
const fd = openSync(staging, "wx", 0o600);
|
|
102
|
+
try { writeFileSync(fd, expected); fsyncSync(fd); } finally { closeSync(fd); }
|
|
103
|
+
}
|
|
104
|
+
const stage = inspectRealmIntentStages(home, intent.keyHash).find(item => join(home, item.name) === staging) ?? fail();
|
|
105
|
+
if (stage.size !== Buffer.byteLength(expected) || stage.hash !== digest(Buffer.from(expected))) fail();
|
|
106
|
+
proof(home, options);
|
|
107
|
+
if (lstatSync(file, { throwIfNoEntry: false }) || stamp(lstatSync(staging, { bigint: true })) !== stage.stamp) fail();
|
|
108
|
+
renameSync(staging, file); syncDirectory(home); proof(home, options);
|
|
109
|
+
if (read(home, intent.keyHash)?.text !== expected) fail();
|
|
110
|
+
}
|
|
111
|
+
/** Removes only the exact owned bytes; an already clean home is left alone so a lost acknowledgement resumes. */
|
|
112
|
+
export function clearRealmIntent(home: string, value: RealmIntent, options: RealmIntentProof): void {
|
|
113
|
+
const intent = validateRealmIntent(value);
|
|
114
|
+
proof(home, options);
|
|
115
|
+
const prior = read(home, intent.keyHash);
|
|
116
|
+
if (prior) {
|
|
117
|
+
if (prior.text !== canonicalJSON(intent) + "\n") fail();
|
|
118
|
+
proof(home, options);
|
|
119
|
+
if (stamp(prior.stat) !== stamp(lstatSync(realmIntentPath(home, intent.keyHash), { bigint: true }))) fail();
|
|
120
|
+
unlinkSync(realmIntentPath(home, intent.keyHash));
|
|
121
|
+
}
|
|
122
|
+
syncDirectory(home); proof(home, options);
|
|
123
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Metadata-only detection of pending realm admission; never grants authority or opens a realm. */
|
|
2
|
+
import { lstatSync, opendirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export const REALM_INTENT_PREFIX = "placement-realm-intent-";
|
|
6
|
+
export interface PendingRealmInventory { hashes: readonly string[]; unknown: boolean }
|
|
7
|
+
/** A pending filename identifies the realm even when its content is torn. Unknown evidence cannot authorize an extension. */
|
|
8
|
+
export function pendingRealmInventory(home: string): PendingRealmInventory {
|
|
9
|
+
const hashes = new Set<string>(); let unknown = false, count = 0;
|
|
10
|
+
try {
|
|
11
|
+
const directory = opendirSync(home);
|
|
12
|
+
try {
|
|
13
|
+
for (;;) {
|
|
14
|
+
const entry = directory.readSync(); if (!entry) break;
|
|
15
|
+
if (++count > 20_000) return { hashes: [], unknown: true };
|
|
16
|
+
if (!entry.name.startsWith(REALM_INTENT_PREFIX)) continue;
|
|
17
|
+
const match = /^placement-realm-intent-([a-f0-9]{64})\.json(?:\.pending-[a-f0-9]{64})?$/.exec(entry.name);
|
|
18
|
+
if (!match || match[0] !== entry.name) { unknown = true; continue; }
|
|
19
|
+
hashes.add(match[1]!);
|
|
20
|
+
if (hashes.size > 64) return { hashes: [], unknown: true };
|
|
21
|
+
const stat = lstatSync(join(home, entry.name));
|
|
22
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0 || ![1, 2].includes(stat.nlink)) unknown = true;
|
|
23
|
+
}
|
|
24
|
+
} finally { directory.closeSync(); }
|
|
25
|
+
} catch { return { hashes: [], unknown: true }; }
|
|
26
|
+
return { hashes: [...hashes].sort(), unknown };
|
|
27
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/** Frozen record evidence for recovery of an interrupted realm extension. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, renameSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { canonicalJSON, fsyncDirectory, hashJSON } from "./generation.ts";
|
|
6
|
+
import { assertMutationHandle } from "./mutation.ts";
|
|
7
|
+
import { realPath } from "./platform.ts";
|
|
8
|
+
import { RealmExtensionFormatError, validateRealmExtension, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
9
|
+
import { validateRealmIntent, type RealmIntent } from "./sync-placement-realm-intent-format.ts";
|
|
10
|
+
import type { RealmIntentProof } from "./sync-placement-realm-intent-storage.ts";
|
|
11
|
+
|
|
12
|
+
const SCHEMA = "agent-mem.sync-placement-realm-proof/v1", LIMIT = 8192;
|
|
13
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
14
|
+
const pathOf = (home: string, intent: RealmIntent) => join(home, `placement-realm-proof-${intent.seal}.json`);
|
|
15
|
+
const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
|
|
16
|
+
function owned(stat: BigIntStats): void {
|
|
17
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o777n) !== 0o600n) fail();
|
|
18
|
+
}
|
|
19
|
+
function checkIntentRecord(intent: RealmIntent, record: RealmExtension): void {
|
|
20
|
+
if (record.epochHash !== intent.epochHash || record.activationHash !== intent.activationHash || record.homeHash !== intent.homeHash
|
|
21
|
+
|| record.generation !== intent.generation || record.sequence !== intent.sequence || record.previousHash !== intent.previousHash
|
|
22
|
+
|| record.realm.keyHash !== intent.keyHash || record.aliasesHash !== intent.aliasesHash || record.policyHash !== intent.policyHash
|
|
23
|
+
|| record.writerHash !== intent.writerHash || record.journal.sequence !== intent.journal.sequence || record.journal.headHash !== intent.journal.headHash
|
|
24
|
+
|| intent.sourceHash !== null && record.sourceHash !== intent.sourceHash) fail();
|
|
25
|
+
}
|
|
26
|
+
function bytesOf(intent: RealmIntent, record: RealmExtension): string {
|
|
27
|
+
checkIntentRecord(intent, record);
|
|
28
|
+
const body = { schema: SCHEMA, intent: intent.seal, record }, result = { ...body, seal: hashJSON(body) };
|
|
29
|
+
const text = canonicalJSON(result) + "\n";
|
|
30
|
+
if (Buffer.byteLength(text) > LIMIT) fail();
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
/** Reads only stable private regular bytes and refuses any malformed or differently bound proof. */
|
|
34
|
+
function readProof(homeInput: string, raw: RealmIntent): { record: RealmExtension; stat: BigIntStats } | undefined {
|
|
35
|
+
const home = realPath(homeInput), intent = validateRealmIntent(raw), file = pathOf(home, intent);
|
|
36
|
+
if (intent.home !== home) fail();
|
|
37
|
+
const before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!before) return undefined;
|
|
38
|
+
owned(before); if (before.size <= 0n || before.size > BigInt(LIMIT)) fail();
|
|
39
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
40
|
+
let content: Buffer;
|
|
41
|
+
try {
|
|
42
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
|
|
43
|
+
const data = Buffer.alloc(Number(opened.size) + 1); let offset = 0;
|
|
44
|
+
while (offset < data.length) { const n = readSync(fd, data, offset, data.length - offset, offset); if (!n) break; offset += n; }
|
|
45
|
+
if (offset !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(file, { bigint: true })) !== stamp(opened)) fail();
|
|
46
|
+
content = data.subarray(0, offset);
|
|
47
|
+
} finally { closeSync(fd); }
|
|
48
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(content), value = JSON.parse(text) as Record<string, unknown>;
|
|
49
|
+
if (!value || Object.keys(value).sort().join(",") !== "intent,record,schema,seal" || value.schema !== SCHEMA || value.intent !== intent.seal) return fail();
|
|
50
|
+
const record = validateRealmExtension(value.record);
|
|
51
|
+
if (bytesOf(intent, record) !== text) fail();
|
|
52
|
+
return { record, stat: before };
|
|
53
|
+
}
|
|
54
|
+
export function readRealmProof(homeInput: string, raw: RealmIntent): RealmExtension | undefined { return readProof(homeInput, raw)?.record; }
|
|
55
|
+
/** Under the home fence, finish an attributable staging prefix and atomically install the frozen proof. */
|
|
56
|
+
export function writeRealmProof(homeInput: string, raw: RealmIntent, input: RealmExtension, proof: RealmIntentProof): void {
|
|
57
|
+
const home = realPath(homeInput), intent = validateRealmIntent(raw), record = validateRealmExtension(input);
|
|
58
|
+
if (intent.home !== home) fail();
|
|
59
|
+
const check = () => { assertMutationHandle(proof.mutation, home); proof.assertCurrent(); assertMutationHandle(proof.mutation, home); };
|
|
60
|
+
const text = bytesOf(intent, record), expected = Buffer.from(text), file = pathOf(home, intent), staged = `${file}.pending`;
|
|
61
|
+
check(); const prior = readRealmProof(home, intent);
|
|
62
|
+
if (prior) { if (canonicalJSON(prior) !== canonicalJSON(record)) fail(); return; }
|
|
63
|
+
let fd: number;
|
|
64
|
+
try { fd = openSync(staged, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
65
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; fd = openSync(staged, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
66
|
+
let stagedStamp: string;
|
|
67
|
+
try {
|
|
68
|
+
const stat = fstatSync(fd, { bigint: true }); owned(stat);
|
|
69
|
+
if (stat.size > BigInt(expected.length)) fail();
|
|
70
|
+
const present = Buffer.alloc(Number(stat.size)); let at = 0;
|
|
71
|
+
while (at < present.length) { const n = readSync(fd, present, at, present.length - at, at); if (!n) fail(); at += n; }
|
|
72
|
+
if (!present.equals(expected.subarray(0, present.length)) || stamp(lstatSync(staged, { bigint: true })) !== stamp(stat)) fail();
|
|
73
|
+
check(); for (let at = present.length; at < expected.length;) { const n = writeSync(fd, expected, at, expected.length - at, at); if (n <= 0) fail(); at += n; }
|
|
74
|
+
fsyncSync(fd);
|
|
75
|
+
const finished = fstatSync(fd, { bigint: true }); owned(finished);
|
|
76
|
+
if (finished.size !== BigInt(expected.length) || stamp(lstatSync(staged, { bigint: true })) !== stamp(finished)) fail();
|
|
77
|
+
stagedStamp = stamp(finished);
|
|
78
|
+
} finally { closeSync(fd); }
|
|
79
|
+
check(); if (lstatSync(file, { throwIfNoEntry: false })) fail();
|
|
80
|
+
if (stamp(lstatSync(staged, { bigint: true })) !== stagedStamp!) fail();
|
|
81
|
+
renameSync(staged, file); fsyncDirectory(home); check();
|
|
82
|
+
if (canonicalJSON(readRealmProof(home, intent)) !== canonicalJSON(record)) fail();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function hasRealmProofStage(homeInput: string, raw: RealmIntent): boolean {
|
|
86
|
+
const home = realPath(homeInput), intent = validateRealmIntent(raw);
|
|
87
|
+
if (intent.home !== home) fail();
|
|
88
|
+
return !!lstatSync(`${pathOf(home, intent)}.pending`, { throwIfNoEntry: false });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function readStage(home: string, intent: RealmIntent): { stat: BigIntStats; hash: string } | undefined {
|
|
92
|
+
const staged = `${pathOf(home, intent)}.pending`, before = lstatSync(staged, { bigint: true, throwIfNoEntry: false });
|
|
93
|
+
if (!before) return undefined;
|
|
94
|
+
const header = Buffer.from(`{"intent":"${intent.seal}"`);
|
|
95
|
+
owned(before); if (before.size > BigInt(LIMIT)) fail();
|
|
96
|
+
const fd = openSync(staged, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
97
|
+
try {
|
|
98
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
|
|
99
|
+
const data = Buffer.alloc(Number(opened.size)); let at = 0;
|
|
100
|
+
while (at < data.length) { const n = readSync(fd, data, at, data.length - at, at); if (!n) fail(); at += n; }
|
|
101
|
+
if (!data.subarray(0, Math.min(data.length, header.length)).equals(header.subarray(0, Math.min(data.length, header.length)))
|
|
102
|
+
|| stamp(fstatSync(fd, { bigint: true })) !== stamp(opened)
|
|
103
|
+
|| stamp(lstatSync(staged, { bigint: true })) !== stamp(opened)) fail();
|
|
104
|
+
return { stat: before, hash: createHash("sha256").update(data).digest("hex") };
|
|
105
|
+
} finally { closeSync(fd); }
|
|
106
|
+
}
|
|
107
|
+
/** Preview private stage bytes bound by name and the available intent header, without reading live sources. */
|
|
108
|
+
export function inspectRealmProofStage(homeInput: string, raw: RealmIntent): boolean {
|
|
109
|
+
const home = realPath(homeInput), intent = validateRealmIntent(raw); if (intent.home !== home) fail();
|
|
110
|
+
return !!readStage(home, intent);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Abandon removes only validated proof bytes, after any attributable log tail has been removed. */
|
|
114
|
+
export function clearRealmProof(homeInput: string, raw: RealmIntent, proof: RealmIntentProof): void {
|
|
115
|
+
const home = realPath(homeInput), intent = validateRealmIntent(raw), file = pathOf(home, intent);
|
|
116
|
+
assertMutationHandle(proof.mutation, home); proof.assertCurrent();
|
|
117
|
+
const prior = readProof(home, intent);
|
|
118
|
+
const staged = `${file}.pending`, beforeStage = lstatSync(staged, { bigint: true, throwIfNoEntry: false });
|
|
119
|
+
if (beforeStage) {
|
|
120
|
+
const inspected = readStage(home, intent) ?? fail(); if (stamp(inspected.stat) !== stamp(beforeStage)) fail();
|
|
121
|
+
proof.assertCurrent(); assertMutationHandle(proof.mutation, home);
|
|
122
|
+
const current = readStage(home, intent) ?? fail();
|
|
123
|
+
if (stamp(current.stat) !== stamp(beforeStage) || current.hash !== inspected.hash) fail();
|
|
124
|
+
unlinkSync(staged); fsyncDirectory(home); proof.assertCurrent();
|
|
125
|
+
}
|
|
126
|
+
if (!prior) return;
|
|
127
|
+
const before = prior.stat; owned(before);
|
|
128
|
+
proof.assertCurrent(); assertMutationHandle(proof.mutation, home);
|
|
129
|
+
if (stamp(lstatSync(file, { bigint: true })) !== stamp(before)) fail();
|
|
130
|
+
unlinkSync(file); fsyncDirectory(home); proof.assertCurrent();
|
|
131
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Data-only verification of an incomplete append against frozen admission evidence. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { canonicalJSON } from "./generation.ts";
|
|
4
|
+
import { RealmExtensionFormatError, validateRealmExtension, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
5
|
+
import { validateRealmIntent, type RealmIntent } from "./sync-placement-realm-intent-format.ts";
|
|
6
|
+
|
|
7
|
+
/** The caller must establish the provenance and freshness of both inputs under its mutation fence. */
|
|
8
|
+
export function verifyTornRealmAppend(bytes: Uint8Array, frozenIntent: RealmIntent, frozenRecord: RealmExtension): Buffer {
|
|
9
|
+
const intent = validateRealmIntent(frozenIntent), record = validateRealmExtension(frozenRecord);
|
|
10
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
11
|
+
if (record.epochHash !== intent.epochHash || record.activationHash !== intent.activationHash
|
|
12
|
+
|| record.homeHash !== intent.homeHash || record.generation !== intent.generation
|
|
13
|
+
|| record.sequence !== intent.sequence || record.previousHash !== intent.previousHash
|
|
14
|
+
|| record.realm.keyHash !== intent.keyHash || record.aliasesHash !== intent.aliasesHash
|
|
15
|
+
|| record.policyHash !== intent.policyHash || record.writerHash !== intent.writerHash
|
|
16
|
+
|| record.journal.sequence !== intent.journal.sequence || record.journal.headHash !== intent.journal.headHash
|
|
17
|
+
|| intent.sourceHash !== null && record.sourceHash !== intent.sourceHash) return fail();
|
|
18
|
+
const input = Buffer.from(bytes), offset = intent.previousLogBytes;
|
|
19
|
+
if (input.length <= offset || offset > input.length) return fail();
|
|
20
|
+
const prefix = input.subarray(0, offset), tail = input.subarray(offset);
|
|
21
|
+
const line = Buffer.from(canonicalJSON(record) + "\n");
|
|
22
|
+
if (createHash("sha256").update(prefix).digest("hex") !== intent.previousLogHash
|
|
23
|
+
|| offset > 0 && prefix[offset - 1] !== 10 || tail.length >= line.length
|
|
24
|
+
|| !tail.equals(line.subarray(0, tail.length))) return fail();
|
|
25
|
+
return Buffer.from(prefix);
|
|
26
|
+
}
|