@quolu/lattice 0.113.2 → 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/bin/lattice-mcp.mjs +3 -2
- package/package.json +1 -1
- package/sensor/dist/db/index.d.ts +3 -2
- package/sensor/dist/db/index.d.ts.map +1 -1
- package/sensor/dist/db/index.js +2 -5
- package/sensor/dist/db/index.js.map +1 -1
- package/sensor/dist/directory.d.ts +2 -0
- package/sensor/dist/directory.d.ts.map +1 -1
- package/sensor/dist/directory.js +3 -1
- package/sensor/dist/directory.js.map +1 -1
- package/sensor/dist/mcp/daemon-paths.d.ts +2 -0
- package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
- package/sensor/dist/mcp/daemon-paths.js +3 -1
- package/sensor/dist/mcp/daemon-paths.js.map +1 -1
- package/sensor/dist/mcp/daemon.d.ts +1 -3
- package/sensor/dist/mcp/daemon.d.ts.map +1 -1
- package/sensor/dist/mcp/daemon.js +2 -4
- package/sensor/dist/mcp/daemon.js.map +1 -1
- package/sensor/dist/mcp/handshake-info.d.ts +24 -0
- package/sensor/dist/mcp/handshake-info.d.ts.map +1 -0
- package/sensor/dist/mcp/handshake-info.js +42 -0
- package/sensor/dist/mcp/handshake-info.js.map +1 -0
- package/sensor/dist/mcp/index.d.ts +8 -5
- package/sensor/dist/mcp/index.d.ts.map +1 -1
- package/sensor/dist/mcp/index.js +38 -37
- package/sensor/dist/mcp/index.js.map +1 -1
- package/sensor/dist/mcp/proxy.d.ts +6 -4
- package/sensor/dist/mcp/proxy.d.ts.map +1 -1
- package/sensor/dist/mcp/proxy.js +46 -25
- package/sensor/dist/mcp/proxy.js.map +1 -1
- package/sensor/dist/mcp/session.d.ts +2 -23
- package/sensor/dist/mcp/session.d.ts.map +1 -1
- package/sensor/dist/mcp/session.js +8 -36
- package/sensor/dist/mcp/session.js.map +1 -1
- package/sensor/dist/mcp/tool-definitions.d.ts +82 -0
- package/sensor/dist/mcp/tool-definitions.d.ts.map +1 -0
- package/sensor/dist/mcp/tool-definitions.js +281 -0
- package/sensor/dist/mcp/tool-definitions.js.map +1 -0
- package/sensor/dist/mcp/tools.d.ts +2 -68
- package/sensor/dist/mcp/tools.d.ts.map +1 -1
- package/sensor/dist/mcp/tools.js +8 -274
- package/sensor/dist/mcp/tools.js.map +1 -1
- package/src/cli-help.mjs +2 -2
- package/src/mcp-startup-receipt.mjs +43 -14
- package/src/todo-cli.mjs +6 -1
- package/src/todo-store-view.mjs +10 -6
- package/src/todo-store.mjs +70 -16
- package/src/todo-verified-receipts.mjs +99 -0
package/src/cli-help.mjs
CHANGED
|
@@ -96,7 +96,7 @@ Read commands:
|
|
|
96
96
|
notice list [--lane <lane>] [--include-acked] [--json] # 着手できるようになった工程の知らせ(既定は未ackだけ。lane省略で全lane)
|
|
97
97
|
blockers [--json] # ブロック中の工程を全部返す(題・担当・理由の全文・ブロックした時刻と者・外すコマンド。読むだけ。外すのは誰でも todo unblock)
|
|
98
98
|
bindings [--plan <key>] [--json] # compile_binding付きTaskをTODO identityつきで投影する
|
|
99
|
-
display read [--json] [--compact] [--open] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す。--compact は journal を activity、plan_scoped を cross_plan_dependencies に絞った lattice.todo_display_compact_result.v1(大きさは task と生きた線に比例)。--open は --compact を含み、task ごとの一覧を開いた木の task だけに絞って closed {trees, tasks} を足す lattice.todo_display_open_result.
|
|
99
|
+
display read [--json] [--compact] [--open] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す。--compact は journal を activity、plan_scoped を cross_plan_dependencies に絞った lattice.todo_display_compact_result.v1(大きさは task と生きた線に比例)。--open は --compact を含み、task ごとの一覧を開いた木の task だけに絞って closed {trees, tasks} を足す lattice.todo_display_open_result.v2(member の revision と、検証済み member の snapshot を持たない。next_ready は state が verified の時だけ todo status と同じ一覧、他は null)
|
|
100
100
|
display history [--json] [--limit <n>] [--before <cursor>] # 閉じた木の task を終了の新しい順に1ページ返す(lattice.todo_display_history_result.v1。limit 既定50・最大500、next_cursor を --before へ渡して次頁)
|
|
101
101
|
display source [--json] # 安い変更検知(lattice.todo_store_display_source.v1)。変わった時だけreadする
|
|
102
102
|
independence [--plan <key>] [--json] # readyを検証済み並列・要直列・未検査へ分けて投影する
|
|
@@ -357,7 +357,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
357
357
|
'chart repo': 'chart repo bind --url <url> --branch <branch> [--json] | sync [--json] # lattice.chart_repo_result.v1',
|
|
358
358
|
'chart repo bind': 'chart repo bind --url <url> --branch <branch> [--json] # コード工程表のrepoを記録する',
|
|
359
359
|
'chart repo sync': 'chart repo sync [--json] # depth-1 fetch、accepted_tipからだけ前進(reset/forceしない)、その後sensor。status current|synced|dirty|diverged|failed',
|
|
360
|
-
'todo display read': 'todo display read [--json] [--compact] [--open] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)。--compact: lattice.todo_display_compact_result.v1(journal→activity、plan_scoped→cross_plan_dependencies)。--open: lattice.todo_display_open_result.
|
|
360
|
+
'todo display read': 'todo display read [--json] [--compact] [--open] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)。--compact: lattice.todo_display_compact_result.v1(journal→activity、plan_scoped→cross_plan_dependencies)。--open: lattice.todo_display_open_result.v2(--compact を含み、開いた木の task だけ + closed {trees, tasks} + next_ready。revision と検証済み member の snapshot は出さない)',
|
|
361
361
|
'todo display history': 'todo display history [--json] [--limit <n>] [--before <cursor>] # lattice.todo_display_history_result.v1 {state, verified_at, source, inconsistency, dropped_members, closed:{trees,tasks}, tasks:[{tree_id, plan_key, task_id, title, lane, phase_id, parent_task_id, design_memo, done_condition, status, done_at, finished_at, activity:{changed_at, started}}], next_cursor}(閉じた木だけ。finished_at の新しい順。limit 既定50・最大500。不正な cursor は INVALID_ARGUMENTS)',
|
|
362
362
|
'todo display source': 'todo display source [--json] # lattice.todo_store_display_source.v1(安い変更検知。変わった時だけreadする)',
|
|
363
363
|
'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation|enforced> --reason <text>'
|
|
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { lstatSync, mkdirSync, openSync, writeFileSync, closeSync, readdirSync } from 'node:fs';
|
|
6
|
+
import { readdir } from 'node:fs/promises';
|
|
6
7
|
import { ensureSafeDir, ensureSafeFile, replaceStoreFile } from './runtime-errors.mjs';
|
|
7
8
|
import { observeDashboardProcess } from './dashboard-process-control.mjs';
|
|
8
9
|
import { isAclScratchName } from './windows-owner-only.mjs';
|
|
@@ -12,29 +13,57 @@ const PHASES = new Set(['initialize_received', 'initialize_response_written']);
|
|
|
12
13
|
export const MCP_RECEIPT_SLOTS = 64;
|
|
13
14
|
export const MCP_RECEIPT_BYTES = 4096;
|
|
14
15
|
|
|
16
|
+
const receiptRoot = home => path.join(home, '.lattice', 'mcp-startup');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Whether a slot may still be claimable: fewer than 64 slot names in the root. Slots are never
|
|
20
|
+
* reclaimed, so a full root stays full and a worker would record nothing for ~12 MB of RSS per
|
|
21
|
+
* session. Only a hint: the worker's exclusive mkdir stays the claim (a race still ends as
|
|
22
|
+
* 'capacity'), and any unreadable root counts as free so the worker keeps deciding as before.
|
|
23
|
+
* Async: the MCP response event loop is never blocked on the directory.
|
|
24
|
+
*/
|
|
25
|
+
async function receiptSlotsFree(home) {
|
|
26
|
+
try { return (await readdir(receiptRoot(home))).filter(name => /^slot-\d+$/u.test(name)).length < MCP_RECEIPT_SLOTS; }
|
|
27
|
+
catch { return true; }
|
|
28
|
+
}
|
|
29
|
+
|
|
15
30
|
/** No filesystem or process-identity work on the MCP response event loop. */
|
|
16
31
|
export function createMcpStartupReceipt(wrapperVersion) {
|
|
17
32
|
let worker;
|
|
33
|
+
// idle -> checking (slot hint pending; observations wait in `queued`) -> running | skipped
|
|
34
|
+
let state = 'idle';
|
|
35
|
+
const queued = [];
|
|
18
36
|
const posted = new Set();
|
|
19
|
-
const post = message => {
|
|
37
|
+
const post = message => {
|
|
38
|
+
if (state === 'checking') queued.push(message);
|
|
39
|
+
else if (state === 'running') { try { worker.postMessage(message); } catch { /* observation only */ } }
|
|
40
|
+
};
|
|
20
41
|
const phase = name => {
|
|
21
|
-
if (
|
|
42
|
+
if (state === 'idle' || state === 'skipped' || posted.has(name)) return;
|
|
22
43
|
posted.add(name); post({ phase: name, at: new Date().toISOString() });
|
|
23
44
|
};
|
|
45
|
+
const start = () => {
|
|
46
|
+
state = 'checking';
|
|
47
|
+
const home = homedir();
|
|
48
|
+
receiptSlotsFree(home).then(free => {
|
|
49
|
+
if (!free) { state = 'skipped'; queued.length = 0; return; }
|
|
50
|
+
try {
|
|
51
|
+
worker = new Worker(new URL(import.meta.url), { workerData: {
|
|
52
|
+
receipt: true, home, wrapperVersion, pid: process.pid,
|
|
53
|
+
runId: randomUUID(), startedAt: new Date().toISOString(),
|
|
54
|
+
}, stdout: true, stderr: true });
|
|
55
|
+
worker.stdout.resume(); worker.stderr.resume();
|
|
56
|
+
worker.on('error', () => {});
|
|
57
|
+
worker.unref();
|
|
58
|
+
} catch { state = 'skipped'; queued.length = 0; return; }
|
|
59
|
+
state = 'running';
|
|
60
|
+
for (const message of queued.splice(0)) post(message);
|
|
61
|
+
});
|
|
62
|
+
};
|
|
24
63
|
return {
|
|
25
64
|
setMode(mode, sensorVersion) {
|
|
26
65
|
if (!['direct', 'proxy'].includes(mode) || !VERSION.test(wrapperVersion) || !VERSION.test(sensorVersion)) return;
|
|
27
|
-
if (
|
|
28
|
-
try {
|
|
29
|
-
worker = new Worker(new URL(import.meta.url), { workerData: {
|
|
30
|
-
receipt: true, home: homedir(), wrapperVersion, pid: process.pid,
|
|
31
|
-
runId: randomUUID(), startedAt: new Date().toISOString(),
|
|
32
|
-
}, stdout: true, stderr: true });
|
|
33
|
-
worker.stdout.resume(); worker.stderr.resume();
|
|
34
|
-
worker.on('error', () => {});
|
|
35
|
-
worker.unref();
|
|
36
|
-
} catch { return; }
|
|
37
|
-
}
|
|
66
|
+
if (state === 'idle') start();
|
|
38
67
|
if (!posted.has(mode)) { posted.add(mode); post({ mode, sensorVersion }); }
|
|
39
68
|
},
|
|
40
69
|
initializeReceived() { phase('initialize_received'); },
|
|
@@ -48,7 +77,7 @@ if (!isMainThread && workerData?.receipt === true) {
|
|
|
48
77
|
let slot = null;
|
|
49
78
|
let disabled = false;
|
|
50
79
|
let record = null;
|
|
51
|
-
const root =
|
|
80
|
+
const root = receiptRoot(workerData.home);
|
|
52
81
|
async function prepare() {
|
|
53
82
|
const parent = path.dirname(root);
|
|
54
83
|
try { mkdirSync(parent, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
package/src/todo-cli.mjs
CHANGED
|
@@ -1291,7 +1291,12 @@ async function displayRead(repoRoot, env, { compact = false, open = false } = {}
|
|
|
1291
1291
|
connections: display.store ? await displayConnections(repoRoot, { ...display.store, external_tasks: externalTasks }) : [] };
|
|
1292
1292
|
// trees, labels and connections are read from the full view above; only the shipped store is compacted
|
|
1293
1293
|
const light = compact || open ? { ...result, schema: 'lattice.todo_display_compact_result.v1', store: result.store && compactDisplayStore(result.store) } : result;
|
|
1294
|
-
|
|
1294
|
+
if (!open) return light;
|
|
1295
|
+
// next_ready (open v2): `todo status`'s list from this same verified read, so a host needs no second process or Store verification.
|
|
1296
|
+
const nextReady = display.state === 'verified'
|
|
1297
|
+
? projectTodoStatus(externalTasks.length > 0 ? { ...display.store, external_tasks: externalTasks } : display.store,
|
|
1298
|
+
{ planNotes: [], parallelCandidates: [], structureFinalizations: [] }).next_ready : null;
|
|
1299
|
+
return openDisplayResult({ ...light, next_ready: nextReady });
|
|
1295
1300
|
}
|
|
1296
1301
|
|
|
1297
1302
|
const HISTORY_DEFAULT_LIMIT = 50;
|
package/src/todo-store-view.mjs
CHANGED
|
@@ -122,9 +122,11 @@ const taskKeyOf = (planKey, taskId) => `${planKey}\0${taskId}`;
|
|
|
122
122
|
const isOpenTree = ({ finished, total }) => finished < total;
|
|
123
123
|
|
|
124
124
|
/**
|
|
125
|
-
* Open display read (`todo display read --open
|
|
125
|
+
* Open display read (`todo display read --open`, v2): the compact result with every per-task list limited to the tasks of open
|
|
126
126
|
* trees (`finished < total` in the result's own `trees`, the one source) and `closed: {trees, tasks}` over the chart.
|
|
127
|
-
*
|
|
127
|
+
* v2 drops what no host reads: each member's `revision` (the whole desired plan, closed trees included) and, for a
|
|
128
|
+
* verified member (it has `tasks`), its `snapshot` (the same task states); an unverified raw member keeps its filtered
|
|
129
|
+
* `snapshot`. `next_ready` is the caller's (`result.next_ready`, null unless the read is verified). Pure. `plan.phases`, descriptors and `activity.first/last_at` stay whole. A ref of another chart is never a task of
|
|
128
130
|
* this chart here, so a join or dependency naming one keeps it.
|
|
129
131
|
*/
|
|
130
132
|
export function openDisplayResult(result) {
|
|
@@ -134,7 +136,7 @@ export function openDisplayResult(result) {
|
|
|
134
136
|
const closed = { trees: closedTrees.length, tasks: closedTrees.reduce((sum, { total }) => sum + total, 0) };
|
|
135
137
|
const connections = (result.connections ?? []).filter(({ plan_key: planKey, task_id: taskId }) => kept.has(taskKeyOf(planKey, taskId)));
|
|
136
138
|
const referred = new Set(connections.flatMap((entry) => entry.connections.map(({ ref }) => ref)));
|
|
137
|
-
const base = { ...result, schema: 'lattice.todo_display_open_result.
|
|
139
|
+
const base = { ...result, schema: 'lattice.todo_display_open_result.v2', next_ready: result.next_ready ?? null,
|
|
138
140
|
trees: trees.filter(isOpenTree), connections, closed,
|
|
139
141
|
external_tasks: (result.external_tasks ?? []).filter(({ project_id: projectId, plan_key: planKey, task_id: taskId }) => referred.has(`${projectId}/${planKey}/${taskId}`)) };
|
|
140
142
|
if (!isObject(result.store)) return base;
|
|
@@ -145,9 +147,11 @@ export function openDisplayResult(result) {
|
|
|
145
147
|
const keptTask = ({ task_id: taskId }) => kept.has(taskKeyOf(planKey, taskId));
|
|
146
148
|
const local = (ref) => (ref.project_id ?? projectId) === projectId;
|
|
147
149
|
const keepRef = (ref) => isObject(ref) && (!local(ref) || kept.has(taskKeyOf(ref.plan_key, ref.task_id)));
|
|
148
|
-
const
|
|
149
|
-
if (Array.isArray(member.tasks))
|
|
150
|
-
|
|
150
|
+
const { revision: _revision, ...next } = member;
|
|
151
|
+
if (Array.isArray(member.tasks)) {
|
|
152
|
+
next.tasks = member.tasks.filter(keptTask);
|
|
153
|
+
delete next.snapshot;
|
|
154
|
+
} else if (Array.isArray(member.snapshot?.tasks)) next.snapshot = { ...member.snapshot, tasks: member.snapshot.tasks.filter(keptTask) };
|
|
151
155
|
if (isObject(member.plan)) {
|
|
152
156
|
next.plan = { ...member.plan };
|
|
153
157
|
if (Array.isArray(member.plan.tasks)) next.plan.tasks = member.plan.tasks.filter(keptTask);
|
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
|
+
}
|