@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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +17 -11
- package/package.json +3 -2
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +97 -17
- package/src/commands-table.ts +6 -0
- package/src/mcp-memory.ts +37 -9
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +32 -26
- package/src/memory/formats.ts +4 -3
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +174 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- 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 +67 -19
- 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-guard.ts +52 -1
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +141 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +148 -28
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +47 -22
- 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 +26 -5
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +352 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-discovery.ts +42 -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-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 +268 -79
- 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 +44 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +26 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Effective same-epoch realm inventory; serialized evidence is not fresh writer or policy authority. */
|
|
2
|
+
import { canonicalJSON } from "./generation.ts";
|
|
3
|
+
import { readPlacementWriterJournalAnchors, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
|
|
4
|
+
import { readWriterHistory } from "./sync-placement-writer-history.ts";
|
|
5
|
+
import { writerInventoryGenesis } from "./sync-placement-writer-revision-format.ts";
|
|
6
|
+
import { readRealmExtensionHistory } from "./sync-placement-realm-extension-storage.ts";
|
|
7
|
+
import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
|
|
8
|
+
import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
|
|
9
|
+
import { realmIntentEvidence } from "./sync-placement-realm-intent-storage.ts";
|
|
10
|
+
import { RealmExtensionFormatError, realmExtensionGenesis } from "./sync-placement-realm-extension-format.ts";
|
|
11
|
+
import type { ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
12
|
+
import type { SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
|
|
13
|
+
|
|
14
|
+
export interface EffectiveRealmInventory { realms: readonly SyncPlacementRealmBinding[]; extensionHead: string; assertCurrent(): void }
|
|
15
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
16
|
+
/** The immutable epoch facts the chain is verified against. A caller holding a validated journal supplies them directly,
|
|
17
|
+
* so the chain is verified by the same code with or without the activation marker files on hand. */
|
|
18
|
+
export interface EffectiveRealmBinding { epochHash: string; activationHash: string; homeHash: string; generation: string; realms: readonly SyncPlacementRealmBinding[] }
|
|
19
|
+
/** A zero-byte extension log is this epoch's pre-write state only while an intent for the same epoch and activation is
|
|
20
|
+
* retained; unknown evidence never authorizes the recovery. */
|
|
21
|
+
export function retainedAdmissionCoversEmptyLog(home: string, epochHash: string, activationHash: string): boolean {
|
|
22
|
+
const pending = pendingRealmInventory(home);
|
|
23
|
+
if (pending.unknown) return false;
|
|
24
|
+
return pending.hashes.some(keyHash => {
|
|
25
|
+
const intent = realmIntentEvidence(home, keyHash);
|
|
26
|
+
return !!intent && intent.epochHash === epochHash && intent.activationHash === activationHash;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** Validate the complete extension chain against both immutable activation and committed historical prefixes. */
|
|
30
|
+
export function readEffectiveRealmInventory(home: string, active: ActivePlacementBinding): EffectiveRealmInventory {
|
|
31
|
+
return readEffectiveRealmInventoryFor(home, { epochHash: active.profile.placementHead, activationHash: active.activation.seal,
|
|
32
|
+
homeHash: active.epoch.homeHash, generation: active.epoch.generation, realms: active.activation.realms });
|
|
33
|
+
}
|
|
34
|
+
export function readEffectiveRealmInventoryFor(home: string, binding: EffectiveRealmBinding): EffectiveRealmInventory {
|
|
35
|
+
try {
|
|
36
|
+
const { epochHash, activationHash, homeHash, generation, realms: activated } = binding;
|
|
37
|
+
const initialProjectHashes = activated.flatMap(realm => realm.scope === "project" ? [realm.keyHash] : []);
|
|
38
|
+
// A stop between creating the extension log and its first append leaves a zero-byte file: recover it as the
|
|
39
|
+
// pre-write state while the admission that authorized the append is retained.
|
|
40
|
+
const allowEmptyLog = retainedAdmissionCoversEmptyLog(home, epochHash, activationHash);
|
|
41
|
+
const extensions = readRealmExtensionHistory(home, { epochHash, activationHash, homeHash,
|
|
42
|
+
generation, initialProjectHashes }, { allowEmptyLog, attributeTorn: evidence => attributeTornRealmAppend(home, {
|
|
43
|
+
epochHash, activationHash, homeHash, generation, initialProjectHashes }, evidence) });
|
|
44
|
+
if (!extensions.records.length) return { realms: activated, extensionHead: realmExtensionGenesis(epochHash, activationHash), assertCurrent: extensions.assertCurrent };
|
|
45
|
+
const token = placementWriterJournalToken(home, epochHash), journal = readPlacementWriterJournalAnchors(home, epochHash);
|
|
46
|
+
if (journal.epoch.homeHash !== homeHash || journal.activation.seal !== activationHash) return fail();
|
|
47
|
+
const writers = readWriterHistory(home, { epochHash, activationHash, homeHash, generation });
|
|
48
|
+
const writerHeads = [writerInventoryGenesis(epochHash, activationHash), ...writers.commits.map(commit => commit.seal)];
|
|
49
|
+
let priorWriter = 0;
|
|
50
|
+
for (const record of extensions.records) {
|
|
51
|
+
const writerIndex = writerHeads.indexOf(record.writerHash);
|
|
52
|
+
if (writerIndex < priorWriter || writerIndex < 0 || record.journal.sequence > journal.sequence
|
|
53
|
+
|| (record.journal.sequence ? journal.records[record.journal.sequence - 1]?.seal : epochHash) !== record.journal.headHash) return fail();
|
|
54
|
+
if (writerIndex > 0 && writers.anchors[writerIndex - 1]!.sequence > record.journal.sequence) return fail();
|
|
55
|
+
priorWriter = writerIndex;
|
|
56
|
+
}
|
|
57
|
+
const realms = [...activated, ...extensions.records.map(record => record.realm)];
|
|
58
|
+
if (realms.length > 256) return fail();
|
|
59
|
+
realms.sort((a, b) => a.scope === "user" ? b.scope === "user" ? 0 : -1 : b.scope === "user" ? 1 : a.keyHash.localeCompare(b.keyHash));
|
|
60
|
+
for (const realm of realms) Object.freeze(realm);
|
|
61
|
+
Object.freeze(realms);
|
|
62
|
+
const snapshot = canonicalJSON(realms);
|
|
63
|
+
const assertCurrent = () => {
|
|
64
|
+
try {
|
|
65
|
+
extensions.assertCurrent(); writers.assertCurrent();
|
|
66
|
+
if (placementWriterJournalToken(home, epochHash) !== token || canonicalJSON(realms) !== snapshot) fail();
|
|
67
|
+
} catch { fail(); }
|
|
68
|
+
};
|
|
69
|
+
assertCurrent(); return { realms, extensionHead: extensions.headHash, assertCurrent };
|
|
70
|
+
} catch { return fail(); }
|
|
71
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Closed, data-only same-epoch realm extension records. A seal is not authorization or fresh proof. */
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
4
|
+
|
|
5
|
+
export const REALM_EXTENSION_SCHEMA = "agent-mem.sync-placement-realm-extension/v1";
|
|
6
|
+
export const REALM_EXTENSION_LIMIT = 64;
|
|
7
|
+
export const REALM_EXTENSION_LOG_MAX_BYTES = 64 * 1024;
|
|
8
|
+
export const REALM_RECORD_MAX_BYTES = 4096;
|
|
9
|
+
|
|
10
|
+
export interface RealmExtensionBody {
|
|
11
|
+
schema: typeof REALM_EXTENSION_SCHEMA;
|
|
12
|
+
epochHash: string;
|
|
13
|
+
activationHash: string;
|
|
14
|
+
homeHash: string;
|
|
15
|
+
generation: string;
|
|
16
|
+
sequence: number;
|
|
17
|
+
previousHash: string;
|
|
18
|
+
realm: { scope: "project"; keyHash: string; bindingHash: string };
|
|
19
|
+
sourceHash: string;
|
|
20
|
+
aliasesHash: string;
|
|
21
|
+
policyHash: string;
|
|
22
|
+
writerHash: string;
|
|
23
|
+
journal: { sequence: number; headHash: string };
|
|
24
|
+
}
|
|
25
|
+
export interface RealmExtension extends RealmExtensionBody { seal: string }
|
|
26
|
+
|
|
27
|
+
export class RealmExtensionFormatError extends Error {
|
|
28
|
+
constructor() { super("sync placement realm extension metadata is invalid or exceeds its supported bounds; retain it for inspection"); this.name = "RealmExtensionFormatError"; }
|
|
29
|
+
}
|
|
30
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
31
|
+
function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
|
|
32
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
|
|
33
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return fail();
|
|
34
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
35
|
+
if (Object.keys(fields).length !== keys.length || Object.getOwnPropertyNames(value).length !== keys.length) return fail();
|
|
36
|
+
const copy: Record<string, unknown> = Object.create(null);
|
|
37
|
+
for (const key of keys) { const field = fields[key]; if (!field || !("value" in field) || !field.enumerable) return fail(); copy[key] = field.value; }
|
|
38
|
+
return copy;
|
|
39
|
+
}
|
|
40
|
+
function hex(value: unknown, width = 64): string {
|
|
41
|
+
if (typeof value !== "string" || value.length !== width || !/^[a-f0-9]+$/.test(value)) return fail(); return value;
|
|
42
|
+
}
|
|
43
|
+
function integer(value: unknown, min: number, max: number): number {
|
|
44
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) return fail(); return value;
|
|
45
|
+
}
|
|
46
|
+
/** The original activation seal anchors the first appended extension, without changing it. */
|
|
47
|
+
export function realmExtensionGenesis(epochHash: string, activationHash: string): string {
|
|
48
|
+
return hashJSON(["agent-mem.sync-placement-realm-genesis/v1", hex(epochHash), hex(activationHash)]);
|
|
49
|
+
}
|
|
50
|
+
function checked(input: unknown, sealed: boolean): RealmExtension {
|
|
51
|
+
const row = object(input, ["schema", "epochHash", "activationHash", "homeHash", "generation", "sequence", "previousHash", "realm", "sourceHash", "aliasesHash", "policyHash", "writerHash", "journal", ...(sealed ? ["seal"] : [])]);
|
|
52
|
+
const realm = object(row.realm, ["scope", "keyHash", "bindingHash"]), journal = object(row.journal, ["sequence", "headHash"]);
|
|
53
|
+
if (row.schema !== REALM_EXTENSION_SCHEMA || realm.scope !== "project") return fail();
|
|
54
|
+
const body: RealmExtensionBody = { schema: REALM_EXTENSION_SCHEMA, epochHash: hex(row.epochHash), activationHash: hex(row.activationHash), homeHash: hex(row.homeHash),
|
|
55
|
+
generation: hex(row.generation, 32), sequence: integer(row.sequence, 1, REALM_EXTENSION_LIMIT), previousHash: hex(row.previousHash),
|
|
56
|
+
realm: { scope: "project", keyHash: hex(realm.keyHash), bindingHash: hex(realm.bindingHash) },
|
|
57
|
+
sourceHash: hex(row.sourceHash), aliasesHash: hex(row.aliasesHash), policyHash: hex(row.policyHash), writerHash: hex(row.writerHash),
|
|
58
|
+
journal: { sequence: integer(journal.sequence, 0, 20_000), headHash: hex(journal.headHash) } };
|
|
59
|
+
if (body.sequence === 1 && body.previousHash !== realmExtensionGenesis(body.epochHash, body.activationHash)
|
|
60
|
+
|| body.journal.sequence === 0 && body.journal.headHash !== body.epochHash) return fail();
|
|
61
|
+
const result = { ...body, seal: hashJSON(body) };
|
|
62
|
+
if (sealed && hex(row.seal) !== result.seal || Buffer.byteLength(canonicalJSON(result) + "\n") > REALM_RECORD_MAX_BYTES) return fail();
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
export function createRealmExtension(input: RealmExtensionBody): RealmExtension { return checked(input, false); }
|
|
66
|
+
export function validateRealmExtension(input: unknown): RealmExtension { return checked(input, true); }
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Read the separate same-epoch extension chain without changing activation or acquiring a writer lease. */
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { canonicalJSON } from "./generation.ts";
|
|
5
|
+
import { homeIdentityMatches } from "./home-identity.ts";
|
|
6
|
+
import { realPath } from "./platform.ts";
|
|
7
|
+
import { REALM_EXTENSION_LIMIT, REALM_EXTENSION_LOG_MAX_BYTES, RealmExtensionFormatError, realmExtensionGenesis,
|
|
8
|
+
validateRealmExtension, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
|
|
9
|
+
|
|
10
|
+
export const REALM_EXTENSION_LOG = "placement-realm-extensions.jsonl";
|
|
11
|
+
export interface RealmExtensionBinding { epochHash: string; activationHash: string; homeHash: string; generation: string; initialProjectHashes: readonly string[] }
|
|
12
|
+
export interface RealmExtensionHistory { records: readonly RealmExtension[]; headHash: string; torn: Buffer; logBytes: Buffer; assertCurrent(): void }
|
|
13
|
+
/** A tail is attributed to the position it would occupy, so only evidence for that exact append can vouch for it. */
|
|
14
|
+
export interface RealmTornEvidence { prefix: Buffer; tail: Buffer; sequence: number; headHash: string }
|
|
15
|
+
export interface RealmExtensionOptions {
|
|
16
|
+
attributeTorn?: (evidence: RealmTornEvidence) => boolean;
|
|
17
|
+
/** A zero-byte log is the state a stop between creating the file and its first append leaves behind. It reads as the
|
|
18
|
+
* pre-write chain only while the intent that authorized that append is retained; without one it stays a refusal. */
|
|
19
|
+
allowEmptyLog?: boolean;
|
|
20
|
+
}
|
|
21
|
+
const fail = (): never => { throw new RealmExtensionFormatError(); };
|
|
22
|
+
const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
|
|
23
|
+
function owned(stat: BigIntStats, directory: boolean): void {
|
|
24
|
+
if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1)
|
|
25
|
+
|| (directory ? !stat.isDirectory() || (stat.mode & 0o077n) !== 0n : !stat.isFile() || stat.nlink !== 1n || (stat.mode & 0o777n) !== 0o600n)) fail();
|
|
26
|
+
}
|
|
27
|
+
/** A modified or mismatched chain is unavailable. An incomplete final append is reported as `torn` and never folded, but only when `attributeTorn` vouches for it, so an interrupted admission keeps existing realms syncing while any unattributed tail still closes the chain. */
|
|
28
|
+
export function readRealmExtensionHistory(homeInput: string, binding: RealmExtensionBinding, options: RealmExtensionOptions = {}): RealmExtensionHistory {
|
|
29
|
+
try { return readHistory(homeInput, binding, options); } catch { return fail(); }
|
|
30
|
+
}
|
|
31
|
+
function readHistory(homeInput: string, binding: RealmExtensionBinding, options: RealmExtensionOptions): RealmExtensionHistory {
|
|
32
|
+
const home = realPath(homeInput), original = lstatSync(homeInput, { bigint: true }), root = lstatSync(home, { bigint: true });
|
|
33
|
+
owned(original, true); owned(root, true);
|
|
34
|
+
if (original.dev !== root.dev || original.ino !== root.ino || !homeIdentityMatches(binding.homeHash, home, root)) return fail();
|
|
35
|
+
const file = join(home, REALM_EXTENSION_LOG), before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
36
|
+
const checks = () => { try {
|
|
37
|
+
const nowHome = lstatSync(home, { bigint: true }), nowOriginal = lstatSync(homeInput, { bigint: true });
|
|
38
|
+
owned(nowHome, true); owned(nowOriginal, true);
|
|
39
|
+
if (nowHome.dev !== root.dev || nowHome.ino !== root.ino || nowOriginal.dev !== original.dev || nowOriginal.ino !== original.ino) fail();
|
|
40
|
+
const now = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
41
|
+
if (!before) { if (now) fail(); return; }
|
|
42
|
+
if (!now) return fail(); owned(now, false); if (stamp(now) !== stamp(before)) fail();
|
|
43
|
+
} catch { fail(); } };
|
|
44
|
+
const genesis = realmExtensionGenesis(binding.epochHash, binding.activationHash);
|
|
45
|
+
if (!before) return { records: [], headHash: genesis, torn: Buffer.alloc(0), logBytes: Buffer.alloc(0), assertCurrent: checks };
|
|
46
|
+
owned(before, false); if (before.size > BigInt(REALM_EXTENSION_LOG_MAX_BYTES)) return fail();
|
|
47
|
+
// A zero-byte log is the pre-write state of a retained admission, not a damaged chain: recover it instead of asking a
|
|
48
|
+
// person to delete a file. With no retained intent it is unknown evidence and still refuses.
|
|
49
|
+
if (before.size === 0n) {
|
|
50
|
+
if (!options.allowEmptyLog) return fail();
|
|
51
|
+
checks(); return { records: [], headHash: genesis, torn: Buffer.alloc(0), logBytes: Buffer.alloc(0), assertCurrent: checks };
|
|
52
|
+
}
|
|
53
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
54
|
+
let bytes: Buffer;
|
|
55
|
+
try {
|
|
56
|
+
const opened = fstatSync(fd, { bigint: true }); owned(opened, false); if (stamp(opened) !== stamp(before)) return fail();
|
|
57
|
+
const data = Buffer.alloc(Number(opened.size) + 1); let at = 0;
|
|
58
|
+
while (at < data.length) { const n = readSync(fd, data, at, data.length - at, at); if (!n) break; at += n; }
|
|
59
|
+
if (at !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened)) return fail();
|
|
60
|
+
bytes = data.subarray(0, at);
|
|
61
|
+
} finally { closeSync(fd); }
|
|
62
|
+
checks();
|
|
63
|
+
const cut = bytes.lastIndexOf(10), torn = Buffer.from(bytes.subarray(cut + 1));
|
|
64
|
+
const complete = cut < 0 ? "" : new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, cut));
|
|
65
|
+
const lines = complete.length ? complete.split("\n") : []; if (lines.length > REALM_EXTENSION_LIMIT) return fail();
|
|
66
|
+
const records: RealmExtension[] = [], seen = new Set(binding.initialProjectHashes), prefixes = new Set(binding.initialProjectHashes.map(hash => hash.slice(0, 16)));
|
|
67
|
+
if (prefixes.size !== binding.initialProjectHashes.length) return fail();
|
|
68
|
+
let head = genesis, journalSequence = 0, journalHead = binding.epochHash;
|
|
69
|
+
for (const [index, line] of lines.entries()) {
|
|
70
|
+
const record = validateRealmExtension(JSON.parse(line));
|
|
71
|
+
if (canonicalJSON(record) !== line || record.sequence !== index + 1 || record.previousHash !== head
|
|
72
|
+
|| record.epochHash !== binding.epochHash || record.activationHash !== binding.activationHash || record.homeHash !== binding.homeHash
|
|
73
|
+
|| record.generation !== binding.generation || seen.has(record.realm.keyHash) || prefixes.has(record.realm.keyHash.slice(0, 16))
|
|
74
|
+
|| record.journal.sequence < journalSequence || record.journal.sequence === journalSequence && record.journal.headHash !== journalHead) return fail();
|
|
75
|
+
seen.add(record.realm.keyHash); prefixes.add(record.realm.keyHash.slice(0, 16)); head = record.seal;
|
|
76
|
+
journalSequence = record.journal.sequence; journalHead = record.journal.headHash;
|
|
77
|
+
Object.freeze(record.realm); Object.freeze(record.journal); records.push(Object.freeze(record));
|
|
78
|
+
}
|
|
79
|
+
const prefix = Buffer.from(bytes.subarray(0, cut + 1));
|
|
80
|
+
if (torn.length && !options.attributeTorn?.({ prefix, tail: torn, sequence: records.length + 1, headHash: head })) return fail();
|
|
81
|
+
checks(); return { records: Object.freeze(records), headHash: head, torn, logBytes: prefix, assertCurrent: checks };
|
|
82
|
+
}
|
|
@@ -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
|
+
}
|