@quolu/lattice 0.114.0 → 0.114.1
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/package.json +1 -1
- package/src/todo-store.mjs +70 -16
- package/src/todo-verified-receipts.mjs +99 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.114.
|
|
3
|
+
"version": "0.114.1",
|
|
4
4
|
"description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Quo / クオ at kitepon.dev",
|
package/src/todo-store.mjs
CHANGED
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
collectTodoStructureGitProvenance,
|
|
74
74
|
} from './todo-structure-git-adapter.mjs';
|
|
75
75
|
import { sha256Bytes, verifyLinearHashChain } from './hash-chain.mjs';
|
|
76
|
+
import { AcceptedKeys } from './todo-verified-receipts.mjs';
|
|
76
77
|
import packageJson from '../package.json' with { type: 'json' };
|
|
77
78
|
import { gitCatFileBatch, gitSync } from './git-process.mjs';
|
|
78
79
|
import { matchesTodoSourceLineDigest } from './todo-source-line-eol.mjs';
|
|
@@ -236,7 +237,8 @@ function decodeUtf8(bytes, code, reason) {
|
|
|
236
237
|
}
|
|
237
238
|
|
|
238
239
|
/** w4: artifact bytes this process already accepted at one ref and mode (see `acceptedSegments`); a repeat read only parses. */
|
|
239
|
-
const
|
|
240
|
+
const acceptedKeys = new AcceptedKeys();
|
|
241
|
+
const acceptedArtifacts = { has: (key) => acceptedKeys.has(`artifact:${key}`), add: (key) => acceptedKeys.add(`artifact:${key}`) };
|
|
240
242
|
|
|
241
243
|
function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null, canonical = true }) {
|
|
242
244
|
const detail = ref === null ? undefined : { ref };
|
|
@@ -291,7 +293,7 @@ async function readSnapshotArtifact(repoRoot, ref) {
|
|
|
291
293
|
* w4: segments this process has already accepted, by sha256 of their bytes and the mode. The canonical check and `validateTodoEvent`
|
|
292
294
|
* are pure functions of the bytes, so a repeat read of the same bytes (one command reads the Store about a dozen times) only parses.
|
|
293
295
|
*/
|
|
294
|
-
const acceptedSegments =
|
|
296
|
+
const acceptedSegments = { has: (key) => acceptedKeys.has(`segment:${key}`), add: (key) => acceptedKeys.add(`segment:${key}`) };
|
|
295
297
|
|
|
296
298
|
/**
|
|
297
299
|
* A revision genesis carries every task's migrated state in one line, so it grows with the plan (ADR 0201 bounds a plan by
|
|
@@ -622,16 +624,24 @@ function localSuccessors(plan, taskId) {
|
|
|
622
624
|
|
|
623
625
|
const CARRY_STATE_POLICIES = ['carry', 'carry_reconciled_metadata', 'acquire_phase'];
|
|
624
626
|
|
|
627
|
+
/** s5: the tasks a genesis carries open, once per event (replay asks for every task of the plan; a scan each was quadratic). */
|
|
628
|
+
const carriedOpenByGenesis = new WeakMap();
|
|
629
|
+
function genesisCarriedOpen(event) {
|
|
630
|
+
let tasks = carriedOpenByGenesis.get(event);
|
|
631
|
+
if (tasks === undefined) {
|
|
632
|
+
tasks = new Set((event.state_migration ?? []).filter((migration) => CARRY_STATE_POLICIES.includes(migration.state_policy)
|
|
633
|
+
&& ['in-progress', 'blocked'].includes(migration.state?.status)).map((migration) => migration.to_task_id));
|
|
634
|
+
carriedOpenByGenesis.set(event, tasks);
|
|
635
|
+
}
|
|
636
|
+
return tasks;
|
|
637
|
+
}
|
|
638
|
+
|
|
625
639
|
/**
|
|
626
640
|
* retract-anyone (A3, Ludmila 2026-11-12): the digest of the event that last made the task in-progress, or null.
|
|
627
641
|
* One rule for replay and resolveTodoStartRetractionBinding. A revision genesis carrying the task open binds it.
|
|
628
642
|
*/
|
|
629
643
|
function stepStartBinding(binding, event, taskId) {
|
|
630
|
-
if (event.kind === 'plan_genesis')
|
|
631
|
-
return (event.state_migration ?? []).some((migration) => CARRY_STATE_POLICIES.includes(migration.state_policy)
|
|
632
|
-
&& migration.to_task_id === taskId && ['in-progress', 'blocked'].includes(migration.state?.status))
|
|
633
|
-
? event.event_digest : binding;
|
|
634
|
-
}
|
|
644
|
+
if (event.kind === 'plan_genesis') return genesisCarriedOpen(event).has(taskId) ? event.event_digest : binding;
|
|
635
645
|
if (event.task_id !== taskId) return binding;
|
|
636
646
|
if (event.kind === 'start' || (event.kind === 'reopen' && event.payload.to_status === undefined)) return event.event_digest;
|
|
637
647
|
if (['done', 'retire', 'start_retracted', 'reopen'].includes(event.kind)) return null;
|
|
@@ -1641,6 +1651,9 @@ async function readTodoStoreLocked(options = {}) {
|
|
|
1641
1651
|
|
|
1642
1652
|
async function readTodoStoreView(options = {}) {
|
|
1643
1653
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1654
|
+
// s5: `todo verify` re-validates everything; every other read reuses what an earlier process accepted for these exact bytes.
|
|
1655
|
+
const useReceipts = options.verifyHistory !== true;
|
|
1656
|
+
if (useReceipts) await acceptedKeys.attach(repoRoot);
|
|
1644
1657
|
const barrier = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
|
|
1645
1658
|
if (barrier !== null) {
|
|
1646
1659
|
let value;
|
|
@@ -1775,6 +1788,7 @@ async function readTodoStoreView(options = {}) {
|
|
|
1775
1788
|
tasks, phases, coordination, snapshot_stale: snapshotStale });
|
|
1776
1789
|
}
|
|
1777
1790
|
const crossPlanFindings = validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded));
|
|
1791
|
+
if (useReceipts) await acceptedKeys.persist(repoRoot);
|
|
1778
1792
|
return {
|
|
1779
1793
|
schema: 'lattice.todo_store_read.v1', project_id: manifest.project_id, manifest,
|
|
1780
1794
|
members: loaded, snapshot_stale: loaded.some((member) => member.snapshot_stale),
|
|
@@ -2149,6 +2163,9 @@ async function readStoreStableWith(options, readStore) {
|
|
|
2149
2163
|
// Store display read (dfd-store-display-read.md). Read-only toward canonical Store files:
|
|
2150
2164
|
// no lock, recovery or writer; the only write is the derived checkpoint below.
|
|
2151
2165
|
const DISPLAY_CHECKPOINT_REF = '.lattice/generated/store-display/last-verified.json';
|
|
2166
|
+
// s5: a few hundred bytes beside the checkpoint: which source it holds and the file identity it was written with.
|
|
2167
|
+
const DISPLAY_CHECKPOINT_HEAD_REF = '.lattice/generated/store-display/last-verified.head.json';
|
|
2168
|
+
const DISPLAY_CHECKPOINT_HEAD_SCHEMA = 'lattice.todo_store_display_checkpoint_head.v1';
|
|
2152
2169
|
const DISPLAY_CHECKPOINT_SCHEMA = 'lattice.todo_store_display_checkpoint.v1';
|
|
2153
2170
|
const DISPLAY_SOURCE_SCHEMA = 'lattice.todo_store_display_source.v1';
|
|
2154
2171
|
const DISPLAY_CHECKPOINT_MAX_BYTES = 64 * 1_048_576;
|
|
@@ -2266,16 +2283,20 @@ async function verifiedDisplaySource(repoRoot, store) {
|
|
|
2266
2283
|
};
|
|
2267
2284
|
}
|
|
2268
2285
|
|
|
2269
|
-
/**
|
|
2286
|
+
/**
|
|
2287
|
+
* The existing read model without implementation bytes; JSON-serializable. s5: no deep copy (it cost ~0.2 s on the bellteam Store):
|
|
2288
|
+
* the strict read is private to this call, every field left is JSON data (strings, numbers, plain objects), and the members are
|
|
2289
|
+
* rebuilt here, so nothing outside the result holds them.
|
|
2290
|
+
*/
|
|
2270
2291
|
function displayStoreView(store) {
|
|
2271
|
-
return
|
|
2292
|
+
return {
|
|
2272
2293
|
schema: store.schema, project_id: store.project_id, manifest: store.manifest,
|
|
2273
2294
|
members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => ({
|
|
2274
2295
|
...member,
|
|
2275
2296
|
journal: { events: journal.events },
|
|
2276
2297
|
plan_scoped: { ref: planScoped.ref, events: planScoped.events },
|
|
2277
2298
|
})),
|
|
2278
|
-
}
|
|
2299
|
+
};
|
|
2279
2300
|
}
|
|
2280
2301
|
|
|
2281
2302
|
function checkpointDigest(checkpoint) {
|
|
@@ -2310,6 +2331,34 @@ async function readDisplayCheckpoint(repoRoot, projectId) {
|
|
|
2310
2331
|
return valid ? checkpoint : null;
|
|
2311
2332
|
}
|
|
2312
2333
|
|
|
2334
|
+
const displaySourceDigest = (source) => sha256Bytes(Buffer.from(JSON.stringify(source), 'utf8'));
|
|
2335
|
+
|
|
2336
|
+
/**
|
|
2337
|
+
* s5: true when the retained checkpoint is known to hold `source` without reading it: the head names the source digest and the
|
|
2338
|
+
* size and mtime of the checkpoint file it was written with. Any doubt (no head, another writer touched the file) is false and the
|
|
2339
|
+
* caller compares the checkpoint itself, as before.
|
|
2340
|
+
*/
|
|
2341
|
+
async function displayCheckpointHeadMatches(repoRoot, source) {
|
|
2342
|
+
try {
|
|
2343
|
+
const root = await canonicalRepoRoot(repoRoot);
|
|
2344
|
+
const head = JSON.parse(await readFile(path.resolve(root, DISPLAY_CHECKPOINT_HEAD_REF), 'utf8'));
|
|
2345
|
+
if (!exactRecord(head, ['schema', 'source_digest', 'size', 'mtime_ms'])
|
|
2346
|
+
|| head.schema !== DISPLAY_CHECKPOINT_HEAD_SCHEMA || head.source_digest !== displaySourceDigest(source)) return false;
|
|
2347
|
+
const absolute = path.resolve(root, DISPLAY_CHECKPOINT_REF);
|
|
2348
|
+
const stats = await lstat(absolute);
|
|
2349
|
+
return !stats.isSymbolicLink() && stats.isFile() && stats.size === head.size && stats.mtimeMs === head.mtime_ms
|
|
2350
|
+
&& await realpath(absolute) === absolute;
|
|
2351
|
+
} catch { return false; }
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
async function publishDisplayCheckpointHead(repoRoot, source) {
|
|
2355
|
+
const root = await canonicalRepoRoot(repoRoot);
|
|
2356
|
+
const stats = await lstat(path.resolve(root, DISPLAY_CHECKPOINT_REF));
|
|
2357
|
+
await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_HEAD_REF), Buffer.from(JSON.stringify({
|
|
2358
|
+
schema: DISPLAY_CHECKPOINT_HEAD_SCHEMA, source_digest: displaySourceDigest(source), size: stats.size, mtime_ms: stats.mtimeMs,
|
|
2359
|
+
}), 'utf8'));
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2313
2362
|
async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
|
|
2314
2363
|
const root = await canonicalRepoRoot(repoRoot);
|
|
2315
2364
|
let directory = root;
|
|
@@ -2321,9 +2370,10 @@ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, sou
|
|
|
2321
2370
|
fail('STORE_DISPLAY_CHECKPOINT_UNSAFE', 'unsafe_checkpoint_directory', { ref: path.relative(root, directory) });
|
|
2322
2371
|
}
|
|
2323
2372
|
}
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2373
|
+
// s5: the store is serialized once (37.8 MB on bellteam): the digest covers the object without checkpoint_digest, the file adds it last.
|
|
2374
|
+
const body = JSON.stringify({ schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store });
|
|
2375
|
+
const digest = sha256Bytes(Buffer.from(body, 'utf8'));
|
|
2376
|
+
await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_REF), Buffer.from(`${body.slice(0, -1)},"checkpoint_digest":"${digest}"}`, 'utf8'));
|
|
2327
2377
|
}
|
|
2328
2378
|
|
|
2329
2379
|
async function readRawDisplayMembers(repoRoot, manifest) {
|
|
@@ -2371,9 +2421,13 @@ export async function readTodoStoreForDisplay({ repoRoot = process.cwd(), now }
|
|
|
2371
2421
|
const store = displayStoreView(strict);
|
|
2372
2422
|
const source = await verifiedDisplaySource(root, strict);
|
|
2373
2423
|
try {
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2424
|
+
if (!await displayCheckpointHeadMatches(root, source)) {
|
|
2425
|
+
const retained = await readDisplayCheckpoint(root, source.project_id);
|
|
2426
|
+
if (JSON.stringify(retained?.source) !== JSON.stringify(source)) {
|
|
2427
|
+
await publishDisplayCheckpoint(root, { verified_at: verifiedAt, source, store });
|
|
2428
|
+
}
|
|
2429
|
+
// The retained checkpoint (or the new one) holds this source: remember it so the next read need not open the file.
|
|
2430
|
+
await publishDisplayCheckpointHead(root, source);
|
|
2377
2431
|
}
|
|
2378
2432
|
} catch (error) {
|
|
2379
2433
|
process.emitWarning(`Store display checkpoint was not published: ${error?.detail?.reason ?? error?.code ?? error}`, {
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Derived, cross-process memory of "these exact bytes passed this exact validator" (dfd-store-display-read.md, s5).
|
|
2
|
+
// Never canonical: a missing, unreadable, oversized or mismatching file is a cache miss and the caller validates in full,
|
|
3
|
+
// as it did before. A key is sha256 of the bytes (plus mode/ref), the file is bound to a fingerprint of the validator code,
|
|
4
|
+
// so changed bytes or changed code never hit. Reads still hash every byte; only the per-event validation is skipped.
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { lstat, mkdir, open, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { renamePublishedFile } from './fs-publish.mjs';
|
|
10
|
+
import packageJson from '../package.json' with { type: 'json' };
|
|
11
|
+
|
|
12
|
+
export const TODO_RECEIPTS_SCHEMA = 'lattice.todo_verified_receipts.v1';
|
|
13
|
+
export const TODO_RECEIPTS_REF = '.lattice/generated/store-verified/receipts.json';
|
|
14
|
+
const MAX_KEYS = 1024;
|
|
15
|
+
const MAX_FILE_BYTES = 1_048_576;
|
|
16
|
+
// The modules whose code decides acceptance; changing any of them changes the fingerprint and drops every receipt.
|
|
17
|
+
const VALIDATOR_MODULES = ['todo-contracts.mjs', 'todo-revision.mjs', 'todo-store.mjs'];
|
|
18
|
+
|
|
19
|
+
let fingerprint;
|
|
20
|
+
function validatorFingerprint() {
|
|
21
|
+
if (fingerprint !== undefined) return fingerprint;
|
|
22
|
+
try {
|
|
23
|
+
const hash = createHash('sha256').update(packageJson.version);
|
|
24
|
+
for (const name of VALIDATOR_MODULES) hash.update('\0').update(readFileSync(new URL(`./${name}`, import.meta.url)));
|
|
25
|
+
fingerprint = hash.digest('hex');
|
|
26
|
+
} catch { fingerprint = null; }
|
|
27
|
+
return fingerprint;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const keysDigest = (keys) => createHash('sha256').update(keys.join('\n')).digest('hex');
|
|
31
|
+
|
|
32
|
+
/** Insertion-ordered set of accepted keys, bounded to the most recently used MAX_KEYS. */
|
|
33
|
+
export class AcceptedKeys {
|
|
34
|
+
#keys = new Map();
|
|
35
|
+
#loaded = new Set();
|
|
36
|
+
#dirty = false;
|
|
37
|
+
|
|
38
|
+
has(key) {
|
|
39
|
+
if (!this.#keys.has(key)) return false;
|
|
40
|
+
this.#keys.delete(key); this.#keys.set(key, true); // recency only; a hit alone never rewrites the file
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
add(key) {
|
|
45
|
+
if (this.#keys.has(key)) return;
|
|
46
|
+
this.#keys.set(key, true);
|
|
47
|
+
this.#dirty = true;
|
|
48
|
+
if (this.#keys.size > MAX_KEYS) this.#keys.delete(this.#keys.keys().next().value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Merge the receipts stored for this repository once per process; any problem leaves the set as it is. */
|
|
52
|
+
async attach(repoRoot) {
|
|
53
|
+
const code = validatorFingerprint();
|
|
54
|
+
if (code === null || this.#loaded.has(repoRoot)) return;
|
|
55
|
+
this.#loaded.add(repoRoot);
|
|
56
|
+
try {
|
|
57
|
+
const absolute = path.join(await realpath(repoRoot), TODO_RECEIPTS_REF);
|
|
58
|
+
const stats = await lstat(absolute);
|
|
59
|
+
if (stats.isSymbolicLink() || !stats.isFile() || stats.size > MAX_FILE_BYTES) return;
|
|
60
|
+
const file = JSON.parse(await readFile(absolute, 'utf8'));
|
|
61
|
+
if (file?.schema !== TODO_RECEIPTS_SCHEMA || file.fingerprint !== code || !Array.isArray(file.keys)
|
|
62
|
+
|| file.keys.length > MAX_KEYS || !file.keys.every((key) => typeof key === 'string' && key.length <= 512)
|
|
63
|
+
|| file.keys_digest !== keysDigest(file.keys)) return;
|
|
64
|
+
const own = new Map(this.#keys);
|
|
65
|
+
this.#keys = new Map(file.keys.map((key) => [key, true]));
|
|
66
|
+
for (const key of own.keys()) { this.#keys.delete(key); this.#keys.set(key, true); }
|
|
67
|
+
} catch { /* a cache miss */ }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Publish the keys accepted since the last publication; a failure leaves the cache as it was. */
|
|
71
|
+
async persist(repoRoot) {
|
|
72
|
+
const code = validatorFingerprint();
|
|
73
|
+
if (code === null || !this.#dirty) return;
|
|
74
|
+
this.#dirty = false;
|
|
75
|
+
let temporary = null;
|
|
76
|
+
try {
|
|
77
|
+
const root = await realpath(repoRoot);
|
|
78
|
+
let directory = root;
|
|
79
|
+
for (const segment of path.posix.dirname(TODO_RECEIPTS_REF).split('/')) {
|
|
80
|
+
directory = path.join(directory, segment);
|
|
81
|
+
if (segment !== '.lattice') await mkdir(directory).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
|
|
82
|
+
const stats = await lstat(directory);
|
|
83
|
+
if (stats.isSymbolicLink() || !stats.isDirectory() || await realpath(directory) !== directory) return;
|
|
84
|
+
}
|
|
85
|
+
// The user's repository must stay clean: `*` ignores the receipts and this file itself, whatever the repository's own ignore rules.
|
|
86
|
+
await writeFile(path.join(directory, '.gitignore'), '*\n', { flag: 'wx' }).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
|
|
87
|
+
const keys = [...this.#keys.keys()];
|
|
88
|
+
const body = Buffer.from(JSON.stringify({ schema: TODO_RECEIPTS_SCHEMA, fingerprint: code, keys,
|
|
89
|
+
keys_digest: keysDigest(keys) }), 'utf8');
|
|
90
|
+
temporary = path.join(directory, `.receipts.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
|
|
91
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
92
|
+
try { await handle.writeFile(body); } finally { await handle.close(); }
|
|
93
|
+
await renamePublishedFile(temporary, path.join(root, TODO_RECEIPTS_REF)); // no fsync: losing it is a cache miss
|
|
94
|
+
temporary = null;
|
|
95
|
+
} catch { /* derived data: the next read validates and tries again */ } finally {
|
|
96
|
+
if (temporary !== null) await rm(temporary, { force: true }).catch(() => {});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|