@quolu/lattice 0.110.0 → 0.110.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.110.0",
3
+ "version": "0.110.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",
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { spawnSensorCli } from './sensor-runtime.mjs';
5
5
 
6
6
  const OPERATIONS = new Set(['status', 'query', 'callers', 'callees', 'impact', 'affected']);
7
+ const SENSOR_QUERY_CONCURRENCY = 6;
7
8
  const ANSI_ESCAPE = /\u001B\[[0-?]*[ -/]*[@-~]/g;
8
9
 
9
10
  function stripAnsi(value) {
@@ -430,13 +431,19 @@ export async function collectSensorEvidence({
430
431
  return { cwd, outcomes: [{ outcome: 'unresolved', reason: 'invalid_path_inspector' }] };
431
432
  }
432
433
 
433
- const outcomes = [];
434
- for (const query of queries) {
435
- if (!query || typeof query !== 'object') {
436
- outcomes.push({ outcome: 'unresolved', reason: 'invalid_query' });
437
- continue;
434
+ // Each affected query spawns one sensor process (250-400 ms); run a few at once.
435
+ // Workers claim the next index, so outcomes stay in query order and no outcome changes.
436
+ const outcomes = new Array(queries.length);
437
+ let next = 0;
438
+ const worker = async () => {
439
+ while (next < queries.length) {
440
+ const index = next++;
441
+ const query = queries[index];
442
+ outcomes[index] = !query || typeof query !== 'object'
443
+ ? { outcome: 'unresolved', reason: 'invalid_query' }
444
+ : await collectOne({ cwd, query, execute, inspectAffectedPath });
438
445
  }
439
- outcomes.push(await collectOne({ cwd, query, execute, inspectAffectedPath }));
440
- }
446
+ };
447
+ await Promise.all(Array.from({ length: Math.min(SENSOR_QUERY_CONCURRENCY, queries.length) }, worker));
441
448
  return { cwd, outcomes };
442
449
  }
@@ -519,7 +519,7 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
519
519
  // perf-store: validated once per process while the files are unchanged (todo-version-memo).
520
520
  const version = await memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
521
521
  // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
522
- const compact = await readVersionCompact(versionRoot).catch(() => fail('NOTE_PROJECTION_INVALID',
522
+ const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
523
523
  'note_historical_plan_invalid', { plan_version: entry.name }));
524
524
  if (compact !== null) {
525
525
  if (compact.plan_key !== planKey || compact.plan_version !== entry.name) {
@@ -561,7 +561,8 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
561
561
  });
562
562
  if (version === null) continue;
563
563
  versions.add(entry.name);
564
- if (version.migration !== null) migrations.push(structuredClone(version.migration));
564
+ // The memoized migration is only read (migrationIndex copies it into its own Map), so it is shared, not cloned.
565
+ if (version.migration !== null) migrations.push(version.migration);
565
566
  }
566
567
  if ([...eventVersions].some((version) => !versions.has(version))) {
567
568
  fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
@@ -235,8 +235,15 @@ function decodeUtf8(bytes, code, reason) {
235
235
  catch { fail(code, reason); }
236
236
  }
237
237
 
238
+ /** w4: artifact bytes this process already accepted at one ref and mode (see `acceptedSegments`); a repeat read only parses. */
239
+ const acceptedArtifacts = new Set();
240
+
238
241
  function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null, canonical = true }) {
239
242
  const detail = ref === null ? undefined : { ref };
243
+ // `validate` is fixed by what lives at `ref`; without a ref there is nothing to key it by, so nothing is remembered.
244
+ const identity = ref === null ? null : `${ref}:${sha256Bytes(bytes)}`;
245
+ const key = identity === null ? null : `${canonical ? 'strict' : 'read'}:${identity}`;
246
+ const known = key !== null && (acceptedArtifacts.has(key) || (!canonical && acceptedArtifacts.has(`strict:${identity}`)));
240
247
  if (bytes.length === 0 || bytes.length > maxBytes) {
241
248
  fail(code, bytes.length > maxBytes ? 'size_limit_exceeded' : reason, detail);
242
249
  }
@@ -246,6 +253,7 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
246
253
  let value;
247
254
  try { value = JSON.parse(body); } catch { fail(code, reason, detail); }
248
255
  if (!text.endsWith('\n')) fail(code, reason, detail);
256
+ if (known) return value;
249
257
  if (canonical) {
250
258
  let expected;
251
259
  try { expected = `${canonicalizeTodoArtifact(value)}\n`; } catch { fail(code, reason, detail); }
@@ -256,6 +264,7 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
256
264
  if (newer !== null) failNewer(newer, ref);
257
265
  fail(code, 'schema_invalid', detail);
258
266
  }
267
+ if (key !== null) acceptedArtifacts.add(key);
259
268
  return value;
260
269
  }
261
270
 
@@ -278,6 +287,12 @@ async function readSnapshotArtifact(repoRoot, ref) {
278
287
  });
279
288
  }
280
289
 
290
+ /**
291
+ * w4: segments this process has already accepted, by sha256 of their bytes and the mode. The canonical check and `validateTodoEvent`
292
+ * 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
+ */
294
+ const acceptedSegments = new Set();
295
+
281
296
  function parseJournalSegment(bytes, ref = null, { canonical: checkCanonical = true } = {}) {
282
297
  const detail = ref === null ? undefined : { ref };
283
298
  if (bytes.length === 0 || bytes.length > TODO_LIMITS.journalSegmentBytes) {
@@ -288,9 +303,13 @@ function parseJournalSegment(bytes, ref = null, { canonical: checkCanonical = tr
288
303
  if (!text.endsWith('\n') || text.startsWith('\uFEFF')) fail('STORE_CORRUPT', 'journal_byte_contract', detail);
289
304
  const lines = text.slice(0, -1).split('\n');
290
305
  if (lines.some((line) => line.length === 0)) fail('STORE_CORRUPT', 'journal_truncated_or_empty_line');
291
- return lines.map((line) => {
306
+ const digest = sha256Bytes(bytes);
307
+ const strictKey = `strict:${digest}`;
308
+ const known = acceptedSegments.has(strictKey) || (!checkCanonical && acceptedSegments.has(`read:${digest}`));
309
+ const events = lines.map((line) => {
292
310
  let event;
293
311
  try { event = JSON.parse(line); } catch { fail('STORE_CORRUPT', 'journal_json_invalid'); }
312
+ if (known) return event;
294
313
  let canonical;
295
314
  if (checkCanonical) try { canonical = canonicalizeTodoArtifact(event); } catch { fail('STORE_CORRUPT', 'journal_schema_invalid'); }
296
315
  if (checkCanonical && line !== canonical) fail('STORE_CORRUPT', 'journal_non_canonical_or_duplicate_key');
@@ -301,6 +320,8 @@ function parseJournalSegment(bytes, ref = null, { canonical: checkCanonical = tr
301
320
  }
302
321
  return event;
303
322
  });
323
+ acceptedSegments.add(checkCanonical ? strictKey : `read:${digest}`);
324
+ return events;
304
325
  }
305
326
 
306
327
  /** Sealed segments of one chain, in order, each checked for name, digest, range and link. */
@@ -414,12 +435,14 @@ function planScopedJournalRef(journalRef) {
414
435
  *
415
436
  * lifecycle journalと違いgenesisを持たない——planの存在はjournalが証明しており、この
416
437
  * chainはそこへ後から積まれる宣言だけを持つ。壊れている記録はnullや空へ丸めずtyped failにする。
438
+ * `verify: false`(通常の読み・k4)はlifecycle journalと同じく、eventごとのcanonical再確認とhash chain全検証を省く。
439
+ * `todo verify`(`verifyHistory`)だけが`verify: true`で全部を確かめる。
417
440
  */
418
- async function readPlanScopedJournal(repoRoot, journalRef) {
441
+ async function readPlanScopedJournal(repoRoot, journalRef, { verify = true } = {}) {
419
442
  const ref = planScopedJournalRef(journalRef);
420
443
  const absolute = path.resolve(repoRoot, ref);
421
444
  // s1-seal: sealed segments first, then the active file (same rules as the lifecycle journal).
422
- const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY);
445
+ const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY, { canonical: verify });
423
446
  let bytes = null;
424
447
  try {
425
448
  const state = await lstat(absolute);
@@ -433,11 +456,11 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
433
456
  // A crash between sealing and the active replacement leaves an active equal to the newest sealed segment.
434
457
  const redundant = bytes === null || segments.at(-1)?.bytes.equals(bytes) === true;
435
458
  const events = [...segments.flatMap(({ events: entries }) => entries),
436
- ...(redundant ? [] : parseJournalSegment(bytes, ref))];
459
+ ...(redundant ? [] : parseJournalSegment(bytes, ref, { canonical: verify }))];
437
460
  if (!events.every(({ kind }) => TODO_PLAN_SCOPED_EVENT_KINDS.includes(kind))) {
438
461
  fail('STORE_CORRUPT', 'plan_scoped_journal_kind_invalid');
439
462
  }
440
- const failures = verifyLinearHashChain({
463
+ const failures = !verify ? new Set() : verifyLinearHashChain({
441
464
  entries: events,
442
465
  canonicalize: canonicalizeTodoArtifact,
443
466
  digestField: 'event_digest',
@@ -1732,7 +1755,7 @@ async function readTodoStoreView(options = {}) {
1732
1755
  const phases = projectPhaseStates(plan, journal.events, new Map(tasks.map((task) => [task.task_id, task])));
1733
1756
  // 調整方式の宣言(ob03)。lifecycle journalとは別chainから読む。phasesと同じく
1734
1757
  // snapshot artifactの形式には縛られない導出ビューで、未宣言はnull(「まだ選んでいない」)。
1735
- const planScoped = await readPlanScopedJournal(repoRoot, descriptor.journal_ref);
1758
+ const planScoped = await readPlanScopedJournal(repoRoot, descriptor.journal_ref, { verify: verifyHistory });
1736
1759
  const coordination = projectTodoCoordination(planScoped.events)
1737
1760
  ?? await inheritedTodoCoordination(repoRoot, plan);
1738
1761
  loaded.push({ descriptor, plan, revision, journal, plan_scoped: planScoped,
@@ -1752,7 +1775,7 @@ async function readTodoStoreView(options = {}) {
1752
1775
  * unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
1753
1776
  */
1754
1777
  async function retainedPlanVersion(repoRoot, base, version) {
1755
- const compact = await readCompactRecord(repoRoot, base, version).catch(() => null);
1778
+ const compact = await readCompactRecord(repoRoot, base, version, { verify: false }).catch(() => null);
1756
1779
  if (compact !== null) {
1757
1780
  return { plan: { plan_digest: compact.plan_digest, predecessor_plan_digest: compact.predecessor_plan_digest,
1758
1781
  topology_digest: compact.topology_digest }, journalRef: `${base}/${version}/journal/active.jsonl` };
@@ -1769,10 +1792,10 @@ async function retainedPlanVersion(repoRoot, base, version) {
1769
1792
  }
1770
1793
 
1771
1794
  /** b10: a retained version's compact record (see todo-version-compact), or null while it still holds its own files. */
1772
- async function readCompactRecord(repoRoot, base, version) {
1795
+ async function readCompactRecord(repoRoot, base, version, { verify = true } = {}) {
1773
1796
  const directory = path.resolve(repoRoot, base, version);
1774
- return memoByFileIdentity([path.join(directory, TODO_VERSION_COMPACT_FILE)], () => readVersionCompact(directory)
1775
- .catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` })));
1797
+ return readVersionCompact(directory, undefined, { verify })
1798
+ .catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` }));
1776
1799
  }
1777
1800
 
1778
1801
  /** b10: one retained version's full `{plan, revision}` (revision null for a genesis version): its own files or its compact record. */
@@ -1914,8 +1937,8 @@ async function inheritedTodoCoordination(repoRoot, plan) {
1914
1937
  const predecessor = await find(digest);
1915
1938
  if (predecessor === undefined) return null;
1916
1939
  const declared = await memoByFileIdentity([path.resolve(repoRoot, planScopedJournalRef(predecessor.journalRef))],
1917
- () => readPlanScopedJournal(repoRoot, predecessor.journalRef)
1918
- .then((chain) => projectTodoCoordination(chain.events), () => undefined));
1940
+ () => readPlanScopedJournal(repoRoot, predecessor.journalRef, { verify: false })
1941
+ .then((chain) => projectTodoCoordination(chain.events), () => undefined), 'read');
1919
1942
  if (declared === undefined) return null;
1920
1943
  if (declared !== null) return declared;
1921
1944
  digest = predecessor.plan.predecessor_plan_digest;
@@ -10,6 +10,7 @@
10
10
  import { readFile } from 'node:fs/promises';
11
11
  import { gunzipSync, gzipSync } from 'node:zlib';
12
12
  import { canonicalizeTodoArtifact, isTodoDigest, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
13
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
13
14
 
14
15
  export const TODO_VERSION_COMPACT_SCHEMA = 'lattice.todo_version_compact.v1';
15
16
  export const TODO_VERSION_COMPACT_FILE = 'compact.json.gz';
@@ -69,7 +70,8 @@ export function buildVersionCompact({ retained, anchor, revision }) {
69
70
  return record;
70
71
  }
71
72
 
72
- export function validateVersionCompact(value) {
73
+ /** `verify: false` (a read) checks the record's shape only; the self digest is recomputed for `verify` (writers, `todo verify`). */
74
+ export function validateVersionCompact(value, { verify = true } = {}) {
73
75
  const keys = ['schema', 'project_id', 'plan_key', 'plan_version', 'plan_digest', 'predecessor_plan_digest', 'predecessor_plan_version',
74
76
  'topology_digest', 'anchor_plan_version', 'anchor_plan_digest', 'plan_patch', 'revision', 'compact_digest'];
75
77
  return isObject(value) && Object.keys(value).length === keys.length && keys.every((key) => key in value)
@@ -79,7 +81,7 @@ export function validateVersionCompact(value) {
79
81
  && (value.predecessor_plan_digest === null || isTodoDigest(value.predecessor_plan_digest))
80
82
  && (value.predecessor_plan_version === null || isTodoIdentifier(value.predecessor_plan_version))
81
83
  && isObject(value.plan_patch) && (value.revision === null || isObject(value.revision))
82
- && value.compact_digest === todoSelfDigest(value, 'compact_digest');
84
+ && (!verify || value.compact_digest === todoSelfDigest(value, 'compact_digest'));
83
85
  }
84
86
 
85
87
  /** The exact plan of `record`, from its anchor's full plan. Throws when the result does not match plan_digest's plan. */
@@ -96,15 +98,22 @@ export const reconstructRevision = (record, plan) => (record.revision === null ?
96
98
  /** The record as stored: canonical JSON line, gzip-packed (a revision's per-task migration is long and repetitive). */
97
99
  export const packVersionCompact = (record) => gzipSync(Buffer.from(`${canonicalizeTodoArtifact(record)}\n`, 'utf8'), { level: 9 });
98
100
 
99
- /** The compact record in `directory`, or null when there is none. Throws when the file is not a canonical, digest-true record. */
100
- export async function readVersionCompact(directory, maxBytes = 8 * 1024 * 1024) {
101
- let packed;
102
- try { packed = await readFile(`${directory}/${TODO_VERSION_COMPACT_FILE}`); } catch (error) {
103
- if (error?.code === 'ENOENT') return null;
104
- throw error;
105
- }
106
- const text = gunzipSync(packed, { maxOutputLength: maxBytes }).toString('utf8');
107
- const value = JSON.parse(text);
108
- if (text !== `${canonicalizeTodoArtifact(value)}\n` || !validateVersionCompact(value)) throw new Error('compact_record_invalid');
109
- return value;
101
+ /**
102
+ * The compact record in `directory`, or null when there is none. Throws when the file is not a canonical, digest-true record.
103
+ * `verify: false` (ADR 0204 k4, a retained version is immutable history) skips the canonical re-serialization and the self digest
104
+ * and keeps the shape check: one gunzip and one parse per version, which a read pays for every retained version of a plan.
105
+ */
106
+ export async function readVersionCompact(directory, maxBytes = 8 * 1024 * 1024, { verify = true } = {}) {
107
+ // perf-store: a retained version is immutable, and the store reader and the note reader both ask for it in one process.
108
+ return memoByFileIdentity([`${directory}/${TODO_VERSION_COMPACT_FILE}`], async () => {
109
+ let packed;
110
+ try { packed = await readFile(`${directory}/${TODO_VERSION_COMPACT_FILE}`); } catch (error) {
111
+ if (error?.code === 'ENOENT') return null;
112
+ throw error;
113
+ }
114
+ const text = gunzipSync(packed, { maxOutputLength: maxBytes }).toString('utf8');
115
+ const value = JSON.parse(text);
116
+ if ((verify && text !== `${canonicalizeTodoArtifact(value)}\n`) || !validateVersionCompact(value, { verify })) throw new Error('compact_record_invalid');
117
+ return value;
118
+ }, verify ? 'verify' : 'read');
110
119
  }
@@ -20,8 +20,9 @@ async function fileIdentity(absolute) {
20
20
  }
21
21
  }
22
22
 
23
- export async function memoByFileIdentity(files, compute) {
24
- const key = files.join('\0');
23
+ /** `mode` separates values computed from the same files under different checks (a read's and a writer's). */
24
+ export async function memoByFileIdentity(files, compute, mode = '') {
25
+ const key = `${files.join('\0')}\0#${mode}`;
25
26
  const identity = (await Promise.all(files.map(fileIdentity))).join('|');
26
27
  const hit = memo.get(key);
27
28
  if (hit !== undefined && hit.identity === identity) return hit.value;