@quolu/lattice 0.114.0 → 0.114.2

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.114.0",
3
+ "version": "0.114.2",
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-cli.mjs CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  isTodoRef,
37
37
  isTodoTestResult,
38
38
  todoSelfDigest,
39
+ todoTaskPin,
39
40
  } from './todo-contracts.mjs';
40
41
  import {
41
42
  adoptTodoDashboardActivity,
@@ -1960,8 +1961,8 @@ async function dependencyConnectLedger({
1960
1961
  if (liveLedgerEdge(store, endpoints)) return dependencyUnchanged(store, endpoints);
1961
1962
  const from = {
1962
1963
  project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId,
1963
- expected_topology_digest: source.plan.topology_digest,
1964
1964
  };
1965
+ from.expected_topology_digest = todoTaskPin(from); // ADR 0206: the edge depends on its source task, not on the plan's other tasks
1965
1966
  const to = {
1966
1967
  project_id: store.project_id, plan_key: toPlanKey, task_id: toTaskId,
1967
1968
  expected_topology_digest: target.plan.topology_digest,
@@ -152,6 +152,14 @@ export function digestTodoArtifact(value) {
152
152
  return createHash('sha256').update(canonicalizeTodoArtifact(value), 'utf8').digest('hex');
153
153
  }
154
154
 
155
+ /**
156
+ * ADR 0206: the pin of a cross-plan edge's `from` ref into a plan of the same project. It names the task, not the plan's topology,
157
+ * so a revision that neither changes nor remaps the task leaves the pin (and the edge) as it is. Stored in `expected_topology_digest`.
158
+ */
159
+ export function todoTaskPin({ project_id: projectId, plan_key: planKey, task_id: taskId }) {
160
+ return digestTodoArtifact({ schema: 'lattice.todo_task_pin.v1', project_id: projectId, plan_key: planKey, task_id: taskId });
161
+ }
162
+
155
163
  export function todoSelfDigest(value, field) {
156
164
  const projection = {};
157
165
  for (const key of Object.keys(value)) if (key !== field) projection[key] = value[key];
@@ -45,6 +45,7 @@ import {
45
45
  isTodoIdentifier,
46
46
  isTodoRef,
47
47
  todoSelfDigest,
48
+ todoTaskPin,
48
49
  validateEvidenceDescriptor,
49
50
  validateTodoChartMeta,
50
51
  validateTodoImportSource,
@@ -73,6 +74,7 @@ import {
73
74
  collectTodoStructureGitProvenance,
74
75
  } from './todo-structure-git-adapter.mjs';
75
76
  import { sha256Bytes, verifyLinearHashChain } from './hash-chain.mjs';
77
+ import { AcceptedKeys } from './todo-verified-receipts.mjs';
76
78
  import packageJson from '../package.json' with { type: 'json' };
77
79
  import { gitCatFileBatch, gitSync } from './git-process.mjs';
78
80
  import { matchesTodoSourceLineDigest } from './todo-source-line-eol.mjs';
@@ -236,7 +238,8 @@ function decodeUtf8(bytes, code, reason) {
236
238
  }
237
239
 
238
240
  /** w4: artifact bytes this process already accepted at one ref and mode (see `acceptedSegments`); a repeat read only parses. */
239
- const acceptedArtifacts = new Set();
241
+ const acceptedKeys = new AcceptedKeys();
242
+ const acceptedArtifacts = { has: (key) => acceptedKeys.has(`artifact:${key}`), add: (key) => acceptedKeys.add(`artifact:${key}`) };
240
243
 
241
244
  function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null, canonical = true }) {
242
245
  const detail = ref === null ? undefined : { ref };
@@ -291,7 +294,7 @@ async function readSnapshotArtifact(repoRoot, ref) {
291
294
  * w4: segments this process has already accepted, by sha256 of their bytes and the mode. The canonical check and `validateTodoEvent`
292
295
  * 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
296
  */
294
- const acceptedSegments = new Set();
297
+ const acceptedSegments = { has: (key) => acceptedKeys.has(`segment:${key}`), add: (key) => acceptedKeys.add(`segment:${key}`) };
295
298
 
296
299
  /**
297
300
  * 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 +625,24 @@ function localSuccessors(plan, taskId) {
622
625
 
623
626
  const CARRY_STATE_POLICIES = ['carry', 'carry_reconciled_metadata', 'acquire_phase'];
624
627
 
628
+ /** s5: the tasks a genesis carries open, once per event (replay asks for every task of the plan; a scan each was quadratic). */
629
+ const carriedOpenByGenesis = new WeakMap();
630
+ function genesisCarriedOpen(event) {
631
+ let tasks = carriedOpenByGenesis.get(event);
632
+ if (tasks === undefined) {
633
+ tasks = new Set((event.state_migration ?? []).filter((migration) => CARRY_STATE_POLICIES.includes(migration.state_policy)
634
+ && ['in-progress', 'blocked'].includes(migration.state?.status)).map((migration) => migration.to_task_id));
635
+ carriedOpenByGenesis.set(event, tasks);
636
+ }
637
+ return tasks;
638
+ }
639
+
625
640
  /**
626
641
  * retract-anyone (A3, Ludmila 2026-11-12): the digest of the event that last made the task in-progress, or null.
627
642
  * One rule for replay and resolveTodoStartRetractionBinding. A revision genesis carrying the task open binds it.
628
643
  */
629
644
  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
- }
645
+ if (event.kind === 'plan_genesis') return genesisCarriedOpen(event).has(taskId) ? event.event_digest : binding;
635
646
  if (event.task_id !== taskId) return binding;
636
647
  if (event.kind === 'start' || (event.kind === 'reopen' && event.payload.to_status === undefined)) return event.event_digest;
637
648
  if (['done', 'retire', 'start_retracted', 'reopen'].includes(event.kind)) return null;
@@ -1057,7 +1068,11 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
1057
1068
  return null;
1058
1069
  }
1059
1070
  if (foreign && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
1060
- if (ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
1071
+ // A task pin (ADR 0206) names the task: it never goes stale while the task exists (its absence is endpoint_missing above).
1072
+ // Any other pin is a topology digest. shortcut: a remap onto ids that all stay in the plan (a swap) is not seen, upgrade to a migration check if one occurs.
1073
+ const stale = ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest
1074
+ && ref.expected_topology_digest !== todoTaskPin(ref);
1075
+ if (stale) {
1061
1076
  if (foreign && ownerPlan.plan_key === newPlanKey) fail('STORE_INCONSISTENT', 'binding_stale');
1062
1077
  finding('binding_stale');
1063
1078
  }
@@ -1143,7 +1158,7 @@ function crossPlanDependencyTask(store, ref) {
1143
1158
  const member = store.members.find(({ plan }) => plan.project_id === ref.project_id
1144
1159
  && plan.plan_key === ref.plan_key);
1145
1160
  if (member === undefined) fail('DEPENDENCY_INVALID', 'dependency_plan_not_found', { ref });
1146
- if (member.plan.topology_digest !== ref.expected_topology_digest) {
1161
+ if (member.plan.topology_digest !== ref.expected_topology_digest && ref.expected_topology_digest !== todoTaskPin(ref)) {
1147
1162
  fail('DEPENDENCY_STALE', 'dependency_topology_stale', {
1148
1163
  ref, actual_topology_digest: member.plan.topology_digest,
1149
1164
  });
@@ -1641,6 +1656,9 @@ async function readTodoStoreLocked(options = {}) {
1641
1656
 
1642
1657
  async function readTodoStoreView(options = {}) {
1643
1658
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1659
+ // s5: `todo verify` re-validates everything; every other read reuses what an earlier process accepted for these exact bytes.
1660
+ const useReceipts = options.verifyHistory !== true;
1661
+ if (useReceipts) await acceptedKeys.attach(repoRoot);
1644
1662
  const barrier = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
1645
1663
  if (barrier !== null) {
1646
1664
  let value;
@@ -1775,6 +1793,7 @@ async function readTodoStoreView(options = {}) {
1775
1793
  tasks, phases, coordination, snapshot_stale: snapshotStale });
1776
1794
  }
1777
1795
  const crossPlanFindings = validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded));
1796
+ if (useReceipts) await acceptedKeys.persist(repoRoot);
1778
1797
  return {
1779
1798
  schema: 'lattice.todo_store_read.v1', project_id: manifest.project_id, manifest,
1780
1799
  members: loaded, snapshot_stale: loaded.some((member) => member.snapshot_stale),
@@ -1996,6 +2015,10 @@ export async function readTodoCarriedBlocks({ repoRoot = process.cwd(), member,
1996
2015
  * connection names (u03): returns the source task id it maps to now, 'removed', or null (unknown).
1997
2016
  */
1998
2017
  async function carriedSourceTask(repoRoot, source, ref, versionsCache) {
2018
+ // ADR 0206: a task pin is repaired from the one revision that made it stale; no lineage walk, no retained versions read.
2019
+ if (ref.expected_topology_digest === todoTaskPin(ref)) {
2020
+ return (source.journal.events[0].payload.task_migration ?? []).find(({ from_task_id: from }) => from === ref.task_id)?.to_task_id ?? null;
2021
+ }
1999
2022
  if (!versionsCache.has(source)) versionsCache.set(source, await retainedPlanVersions(repoRoot, source.plan));
2000
2023
  const byDigest = versionsCache.get(source);
2001
2024
  // Newest first: the active genesis maps its predecessor's ids onto the active ids.
@@ -2057,7 +2080,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
2057
2080
  ? 'removed the task' : 'carried the task'}`,
2058
2081
  } }];
2059
2082
  if (mapped !== 'removed') inputs.push({ kind: 'cross_plan_dependency', payload: {
2060
- from: { ...dependency.from, task_id: mapped, expected_topology_digest: source.plan.topology_digest },
2083
+ from: { ...dependency.from, task_id: mapped, expected_topology_digest: todoTaskPin({ ...dependency.from, task_id: mapped }) },
2061
2084
  to: dependency.to, reason: dependency.reason,
2062
2085
  } });
2063
2086
  for (const input of inputs) {
@@ -2149,6 +2172,9 @@ async function readStoreStableWith(options, readStore) {
2149
2172
  // Store display read (dfd-store-display-read.md). Read-only toward canonical Store files:
2150
2173
  // no lock, recovery or writer; the only write is the derived checkpoint below.
2151
2174
  const DISPLAY_CHECKPOINT_REF = '.lattice/generated/store-display/last-verified.json';
2175
+ // s5: a few hundred bytes beside the checkpoint: which source it holds and the file identity it was written with.
2176
+ const DISPLAY_CHECKPOINT_HEAD_REF = '.lattice/generated/store-display/last-verified.head.json';
2177
+ const DISPLAY_CHECKPOINT_HEAD_SCHEMA = 'lattice.todo_store_display_checkpoint_head.v1';
2152
2178
  const DISPLAY_CHECKPOINT_SCHEMA = 'lattice.todo_store_display_checkpoint.v1';
2153
2179
  const DISPLAY_SOURCE_SCHEMA = 'lattice.todo_store_display_source.v1';
2154
2180
  const DISPLAY_CHECKPOINT_MAX_BYTES = 64 * 1_048_576;
@@ -2266,16 +2292,20 @@ async function verifiedDisplaySource(repoRoot, store) {
2266
2292
  };
2267
2293
  }
2268
2294
 
2269
- /** The existing read model without implementation bytes; JSON-serializable. */
2295
+ /**
2296
+ * The existing read model without implementation bytes; JSON-serializable. s5: no deep copy (it cost ~0.2 s on the bellteam Store):
2297
+ * the strict read is private to this call, every field left is JSON data (strings, numbers, plain objects), and the members are
2298
+ * rebuilt here, so nothing outside the result holds them.
2299
+ */
2270
2300
  function displayStoreView(store) {
2271
- return JSON.parse(JSON.stringify({
2301
+ return {
2272
2302
  schema: store.schema, project_id: store.project_id, manifest: store.manifest,
2273
2303
  members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => ({
2274
2304
  ...member,
2275
2305
  journal: { events: journal.events },
2276
2306
  plan_scoped: { ref: planScoped.ref, events: planScoped.events },
2277
2307
  })),
2278
- }));
2308
+ };
2279
2309
  }
2280
2310
 
2281
2311
  function checkpointDigest(checkpoint) {
@@ -2310,6 +2340,34 @@ async function readDisplayCheckpoint(repoRoot, projectId) {
2310
2340
  return valid ? checkpoint : null;
2311
2341
  }
2312
2342
 
2343
+ const displaySourceDigest = (source) => sha256Bytes(Buffer.from(JSON.stringify(source), 'utf8'));
2344
+
2345
+ /**
2346
+ * s5: true when the retained checkpoint is known to hold `source` without reading it: the head names the source digest and the
2347
+ * size and mtime of the checkpoint file it was written with. Any doubt (no head, another writer touched the file) is false and the
2348
+ * caller compares the checkpoint itself, as before.
2349
+ */
2350
+ async function displayCheckpointHeadMatches(repoRoot, source) {
2351
+ try {
2352
+ const root = await canonicalRepoRoot(repoRoot);
2353
+ const head = JSON.parse(await readFile(path.resolve(root, DISPLAY_CHECKPOINT_HEAD_REF), 'utf8'));
2354
+ if (!exactRecord(head, ['schema', 'source_digest', 'size', 'mtime_ms'])
2355
+ || head.schema !== DISPLAY_CHECKPOINT_HEAD_SCHEMA || head.source_digest !== displaySourceDigest(source)) return false;
2356
+ const absolute = path.resolve(root, DISPLAY_CHECKPOINT_REF);
2357
+ const stats = await lstat(absolute);
2358
+ return !stats.isSymbolicLink() && stats.isFile() && stats.size === head.size && stats.mtimeMs === head.mtime_ms
2359
+ && await realpath(absolute) === absolute;
2360
+ } catch { return false; }
2361
+ }
2362
+
2363
+ async function publishDisplayCheckpointHead(repoRoot, source) {
2364
+ const root = await canonicalRepoRoot(repoRoot);
2365
+ const stats = await lstat(path.resolve(root, DISPLAY_CHECKPOINT_REF));
2366
+ await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_HEAD_REF), Buffer.from(JSON.stringify({
2367
+ schema: DISPLAY_CHECKPOINT_HEAD_SCHEMA, source_digest: displaySourceDigest(source), size: stats.size, mtime_ms: stats.mtimeMs,
2368
+ }), 'utf8'));
2369
+ }
2370
+
2313
2371
  async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
2314
2372
  const root = await canonicalRepoRoot(repoRoot);
2315
2373
  let directory = root;
@@ -2321,9 +2379,10 @@ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, sou
2321
2379
  fail('STORE_DISPLAY_CHECKPOINT_UNSAFE', 'unsafe_checkpoint_directory', { ref: path.relative(root, directory) });
2322
2380
  }
2323
2381
  }
2324
- const checkpoint = { schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store, checkpoint_digest: '' };
2325
- checkpoint.checkpoint_digest = checkpointDigest(checkpoint);
2326
- await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_REF), Buffer.from(JSON.stringify(checkpoint), 'utf8'));
2382
+ // s5: the store is serialized once (37.8 MB on bellteam): the digest covers the object without checkpoint_digest, the file adds it last.
2383
+ const body = JSON.stringify({ schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store });
2384
+ const digest = sha256Bytes(Buffer.from(body, 'utf8'));
2385
+ await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_REF), Buffer.from(`${body.slice(0, -1)},"checkpoint_digest":"${digest}"}`, 'utf8'));
2327
2386
  }
2328
2387
 
2329
2388
  async function readRawDisplayMembers(repoRoot, manifest) {
@@ -2371,9 +2430,13 @@ export async function readTodoStoreForDisplay({ repoRoot = process.cwd(), now }
2371
2430
  const store = displayStoreView(strict);
2372
2431
  const source = await verifiedDisplaySource(root, strict);
2373
2432
  try {
2374
- const retained = await readDisplayCheckpoint(root, source.project_id);
2375
- if (JSON.stringify(retained?.source) !== JSON.stringify(source)) {
2376
- await publishDisplayCheckpoint(root, { verified_at: verifiedAt, source, store });
2433
+ if (!await displayCheckpointHeadMatches(root, source)) {
2434
+ const retained = await readDisplayCheckpoint(root, source.project_id);
2435
+ if (JSON.stringify(retained?.source) !== JSON.stringify(source)) {
2436
+ await publishDisplayCheckpoint(root, { verified_at: verifiedAt, source, store });
2437
+ }
2438
+ // The retained checkpoint (or the new one) holds this source: remember it so the next read need not open the file.
2439
+ await publishDisplayCheckpointHead(root, source);
2377
2440
  }
2378
2441
  } catch (error) {
2379
2442
  process.emitWarning(`Store display checkpoint was not published: ${error?.detail?.reason ?? error?.code ?? error}`, {
@@ -2958,7 +3021,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2958
3021
  .filter(({ event_digest: digest }) => options.eventDigests.includes(digest));
2959
3022
  if (dependencies.length !== options.eventDigests.length || dependencies.some(({ from, to, event_digest: digest }) => (
2960
3023
  from.project_id !== source.plan.project_id || from.plan_key !== source.plan.plan_key
2961
- || from.expected_topology_digest === source.plan.topology_digest
3024
+ || from.expected_topology_digest === source.plan.topology_digest || from.expected_topology_digest === todoTaskPin(from)
2962
3025
  || to.project_id !== owner.plan.project_id || to.plan_key !== owner.plan.plan_key
2963
3026
  || !owner.plan_scoped.events.some((event) => event.event_digest === digest)
2964
3027
  ))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
@@ -2991,7 +3054,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2991
3054
  target_event_digest: dependency.event_digest, reason: options.reason,
2992
3055
  } },
2993
3056
  { kind: 'cross_plan_dependency', payload: {
2994
- from: { ...dependency.from, expected_topology_digest: source.plan.topology_digest },
3057
+ from: { ...dependency.from, expected_topology_digest: todoTaskPin(dependency.from) },
2995
3058
  to: dependency.to, reason: dependency.reason,
2996
3059
  } },
2997
3060
  ]) {
@@ -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
+ }