@quolu/lattice 0.105.0 → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,6 +41,7 @@ import {
41
41
  exactRecord,
42
42
  isStrictTodoTimestamp,
43
43
  isTodoDigest,
44
+ isTodoDoneMessage,
44
45
  isTodoIdentifier,
45
46
  isTodoRef,
46
47
  todoSelfDigest,
@@ -230,7 +231,7 @@ function decodeUtf8(bytes, code, reason) {
230
231
  catch { fail(code, reason); }
231
232
  }
232
233
 
233
- function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null }) {
234
+ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null, canonical = true }) {
234
235
  const detail = ref === null ? undefined : { ref };
235
236
  if (bytes.length === 0 || bytes.length > maxBytes) {
236
237
  fail(code, bytes.length > maxBytes ? 'size_limit_exceeded' : reason, detail);
@@ -241,9 +242,11 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
241
242
  let value;
242
243
  try { value = JSON.parse(body); } catch { fail(code, reason, detail); }
243
244
  if (!text.endsWith('\n')) fail(code, reason, detail);
244
- let expected;
245
- try { expected = `${canonicalizeTodoArtifact(value)}\n`; } catch { fail(code, reason, detail); }
246
- if (text !== expected) fail(code, 'non_canonical_or_duplicate_key', detail);
245
+ if (canonical) {
246
+ let expected;
247
+ try { expected = `${canonicalizeTodoArtifact(value)}\n`; } catch { fail(code, reason, detail); }
248
+ if (text !== expected) fail(code, 'non_canonical_or_duplicate_key', detail);
249
+ }
247
250
  if (!validate(value)) {
248
251
  const newer = NEWER_SCHEMA_FAMILY.has(validate) ? newerSchema(value, NEWER_SCHEMA_FAMILY.get(validate)) : null;
249
252
  if (newer !== null) failNewer(newer, ref);
@@ -252,12 +255,12 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
252
255
  return value;
253
256
  }
254
257
 
255
- async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false }) {
258
+ async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false, canonical = true }) {
256
259
  const state = await pathState(repoRoot, ref, code, { missing });
257
260
  if (state === null) return null;
258
261
  const bytes = normalizeCheckoutEol(await readFile(state.absolute));
259
262
  return parseCanonicalJsonLine(bytes, {
260
- code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref,
263
+ code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref, canonical,
261
264
  });
262
265
  }
263
266
 
@@ -271,7 +274,7 @@ async function readSnapshotArtifact(repoRoot, ref) {
271
274
  });
272
275
  }
273
276
 
274
- function parseJournalSegment(bytes, ref = null) {
277
+ function parseJournalSegment(bytes, ref = null, { canonical: checkCanonical = true } = {}) {
275
278
  const detail = ref === null ? undefined : { ref };
276
279
  if (bytes.length === 0 || bytes.length > TODO_LIMITS.journalSegmentBytes) {
277
280
  fail('STORE_CORRUPT', bytes.length > TODO_LIMITS.journalSegmentBytes
@@ -285,8 +288,8 @@ function parseJournalSegment(bytes, ref = null) {
285
288
  let event;
286
289
  try { event = JSON.parse(line); } catch { fail('STORE_CORRUPT', 'journal_json_invalid'); }
287
290
  let canonical;
288
- try { canonical = canonicalizeTodoArtifact(event); } catch { fail('STORE_CORRUPT', 'journal_schema_invalid'); }
289
- if (line !== canonical) fail('STORE_CORRUPT', 'journal_non_canonical_or_duplicate_key');
291
+ if (checkCanonical) try { canonical = canonicalizeTodoArtifact(event); } catch { fail('STORE_CORRUPT', 'journal_schema_invalid'); }
292
+ if (checkCanonical && line !== canonical) fail('STORE_CORRUPT', 'journal_non_canonical_or_duplicate_key');
290
293
  if (!validateTodoEvent(event)) {
291
294
  const newer = newerEventValue(event);
292
295
  if (newer !== null) failNewer(newer, ref);
@@ -297,7 +300,7 @@ function parseJournalSegment(bytes, ref = null) {
297
300
  }
298
301
 
299
302
  /** Sealed segments of one chain, in order, each checked for name, digest, range and link. */
300
- async function readSealedSegments(repoRoot, journalRef, directoryName) {
303
+ async function readSealedSegments(repoRoot, journalRef, directoryName, { canonical = true } = {}) {
301
304
  const sealedDirectory = path.resolve(repoRoot, path.dirname(journalRef), directoryName);
302
305
  const segments = [];
303
306
  try {
@@ -314,7 +317,7 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
314
317
  const [, startText, endText, previousDigest, segmentDigest] = name.match(
315
318
  /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u,
316
319
  );
317
- const events = parseJournalSegment(bytes, ref);
320
+ const events = parseJournalSegment(bytes, ref, { canonical });
318
321
  if (sha256Bytes(bytes) !== segmentDigest) fail('STORE_CORRUPT', 'sealed_segment_digest_mismatch');
319
322
  if (events[0].sequence !== Number(startText) || events.at(-1).sequence !== Number(endText)) {
320
323
  fail('STORE_CORRUPT', 'sealed_segment_range_mismatch');
@@ -331,11 +334,15 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
331
334
  return segments;
332
335
  }
333
336
 
334
- async function readJournal(repoRoot, journalRef) {
337
+ /**
338
+ * k4 (ADR 0204): `verify: false` skips the per-event canonical re-check and the whole hash-chain re-verification (a read
339
+ * recomputed every event's digest on every operation and protected nothing named). `verify` stays true for `todo verify`.
340
+ */
341
+ async function readJournal(repoRoot, journalRef, { verify = true } = {}) {
335
342
  // b10: a retained version's active segment may be kept gzip-packed as `active.jsonl.gz` (same bytes once unpacked).
336
343
  const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT', { missing: true });
337
344
  const packed = state === null ? await pathState(repoRoot, `${journalRef}.gz`, 'STORE_CORRUPT') : null;
338
- const segments = await readSealedSegments(repoRoot, journalRef, 'sealed');
345
+ const segments = await readSealedSegments(repoRoot, journalRef, 'sealed', { canonical: verify });
339
346
  let activeBytes;
340
347
  try {
341
348
  activeBytes = state === null ? gunzipSync(await readFile(packed.absolute), { maxOutputLength: TODO_LIMITS.journalSegmentBytes })
@@ -343,10 +350,10 @@ async function readJournal(repoRoot, journalRef) {
343
350
  } catch { fail('STORE_CORRUPT', 'journal_gzip_invalid', { ref: `${journalRef}.gz` }); }
344
351
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
345
352
  if (!duplicateActive) {
346
- segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
353
+ segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef, { canonical: verify }) });
347
354
  }
348
355
  const events = segments.flatMap(({ events: entries }) => entries);
349
- const failures = verifyLinearHashChain({
356
+ const failures = !verify ? new Set() : verifyLinearHashChain({
350
357
  entries: events,
351
358
  canonicalize: canonicalizeTodoArtifact,
352
359
  digestField: 'event_digest',
@@ -533,11 +540,11 @@ function projectPhaseStates(plan, events, taskStates) {
533
540
  } else if (event.kind === 'phase_accept') {
534
541
  const state = states.get(event.phase_id);
535
542
  state.status = 'accepted'; state.decision_event_digest = event.event_digest;
536
- state.decision_evidence = event.payload.decision_evidence;
543
+ state.decision_evidence = event.payload.decision_evidence ?? null;
537
544
  } else if (event.kind === 'phase_reject') {
538
545
  const state = states.get(event.phase_id);
539
546
  state.status = 'rejected'; state.decision_event_digest = event.event_digest;
540
- state.decision_evidence = event.payload.decision_evidence;
547
+ state.decision_evidence = event.payload.decision_evidence ?? null;
541
548
  } else if (event.kind === 'phase_close_unaudited') {
542
549
  // ADR 0148: 監査していないので証拠(decision_evidence)は残さない。理由はevent payload
543
550
  // 自身(decision_event_digestで指せるこの event)に記録済みで、accept/rejectと違い
@@ -693,12 +700,14 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
693
700
  pendingVerifications.delete(`phase:${event.phase_id}`);
694
701
  } else if (event.kind === 'phase_accept') {
695
702
  const phase = phasesOf(plan).find(({ phase_id }) => phase_id === event.phase_id);
696
- const slots = event.payload.evidence_slots.map(({ slot_id }) => slot_id);
703
+ // k4: a new accept names no slots; only a legacy accept (evidence_slots) is matched against the phase definition.
704
+ const slots = event.payload.evidence_slots?.map(({ slot_id }) => slot_id);
697
705
  if (currentStatus !== 'reviewing' || state.review_event_digest !== event.payload.review_event_digest
698
- || canonicalizeTodoArtifact(slots) !== canonicalizeTodoArtifact(phase.required_evidence_slots)) {
706
+ || (slots !== undefined
707
+ && canonicalizeTodoArtifact(slots) !== canonicalizeTodoArtifact(phase.required_evidence_slots))) {
699
708
  fail('STORE_INCONSISTENT', 'phase_accept_binding_invalid');
700
709
  }
701
- if (verifyEvidence) {
710
+ if (verifyEvidence && event.payload.decision_evidence !== undefined) {
702
711
  const decisionEvidence = event.payload.decision_evidence;
703
712
  const slotEvidence = event.payload.evidence_slots.map((slot) => slot.evidence);
704
713
  pendingVerifications.set(`phase:${event.phase_id}`, () => {
@@ -709,19 +718,19 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
709
718
  });
710
719
  }
711
720
  state.status = 'accepted'; state.decision_event_digest = event.event_digest;
712
- state.decision_evidence = event.payload.decision_evidence;
721
+ state.decision_evidence = event.payload.decision_evidence ?? null;
713
722
  } else if (event.kind === 'phase_reject') {
714
723
  if (currentStatus !== 'reviewing' || state.review_event_digest !== event.payload.review_event_digest) {
715
724
  fail('STORE_INCONSISTENT', 'phase_reject_binding_invalid');
716
725
  }
717
- if (verifyEvidence) {
726
+ if (verifyEvidence && event.payload.decision_evidence !== undefined) {
718
727
  const decisionEvidence = event.payload.decision_evidence;
719
728
  pendingVerifications.set(`phase:${event.phase_id}`, () => verifyEvidence(decisionEvidence, {
720
729
  plan_key: plan.plan_key, phase_id: event.phase_id, event_digest: event.event_digest,
721
730
  }));
722
731
  }
723
732
  state.status = 'rejected'; state.decision_event_digest = event.event_digest;
724
- state.decision_evidence = event.payload.decision_evidence;
733
+ state.decision_evidence = event.payload.decision_evidence ?? null;
725
734
  } else if (event.kind === 'phase_close_unaudited') {
726
735
  // ADR 0148裁定3: reviewと同じ前提(gate_ready)を課す——所属ToDoが全てdoneでない段階では
727
736
  // まだ監査の地点に到達していないので、監査なしで閉じることもできない。
@@ -850,13 +859,13 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
850
859
  } else if (event.kind === 'done') {
851
860
  if (event.payload.done_mode === 'authored') {
852
861
  if (state.status !== 'in-progress' || !dependenciesDone) fail('STORE_INCONSISTENT', 'invalid_done_transition');
853
- if (verifyEvidence) {
862
+ if (verifyEvidence && event.payload.evidence !== undefined) {
854
863
  const evidence = event.payload.evidence;
855
864
  pendingVerifications.set(`task:${event.task_id}`, () => verifyEvidence(evidence, {
856
865
  plan_key: plan.plan_key, task_id: event.task_id, event_digest: event.event_digest,
857
866
  }));
858
867
  }
859
- state.status = 'done'; state.done_at = event.recorded_at; state.evidence = event.payload.evidence;
868
+ state.status = 'done'; state.done_at = event.recorded_at; state.evidence = event.payload.evidence ?? { message: event.payload.message };
860
869
  state.test_result = event.payload.test_result ?? null;
861
870
  state.imported = false;
862
871
  completion.set(event.task_id, { mode: 'authored', completed_at: event.recorded_at });
@@ -1190,12 +1199,15 @@ function reachableObjects(absoluteRepo) {
1190
1199
  // blob は内容アドレスなので oid が同じなら bytes は不変。gantt serve 等が store を再読する
1191
1200
  // たびに同じ evidence blob を git 子起動で読み直すのを避ける(Windows のウィンドウ雪崩と
1192
1201
  // 走査コストの主犯)。成功した読みだけを覚え、失敗は覚えない(repo 状態は変わりうる)。
1193
- const EVIDENCE_BLOB_CACHE_LIMIT = 512;
1194
- const evidenceBlobCache = new Map();
1202
+ // b11: 覚えるのは bytes ではなく sha256 だけ(検証が使うのはそれだけ)。件数上限は置かない:
1203
+ // 以前の512件上限を超えた store(本番 bellteam-dev-added)は、超えた分と追い出しのたびに
1204
+ // 1件ずつ git を起動し、1回の書込みの 16 s のうち 13 s を使っていた。
1205
+ const evidenceBlobDigestCache = new Map();
1206
+ const EVIDENCE_PREFETCH_BATCH = 128;
1195
1207
 
1196
- function readEvidenceBlob(absoluteRepo, oid) {
1208
+ function readEvidenceBlobDigest(absoluteRepo, oid) {
1197
1209
  const key = `${absoluteRepo}\0${oid}`;
1198
- const cached = evidenceBlobCache.get(key);
1210
+ const cached = evidenceBlobDigestCache.get(key);
1199
1211
  if (cached !== undefined) return cached;
1200
1212
  const [entry] = gitCatFileBatch([oid], {
1201
1213
  cwd: absoluteRepo, maxBodyBytes: TODO_LIMITS.narrativeSectionBytes + 1,
@@ -1204,49 +1216,69 @@ function readEvidenceBlob(absoluteRepo, oid) {
1204
1216
  // 契約上限はbytesで明示判定し、process bufferの打切りを意味判定に使わない。
1205
1217
  if (entry.missing || entry.type !== 'blob'
1206
1218
  || entry.bytes.length > TODO_LIMITS.narrativeSectionBytes) throw new Error('not bounded blob');
1207
- if (evidenceBlobCache.size >= EVIDENCE_BLOB_CACHE_LIMIT) {
1208
- evidenceBlobCache.delete(evidenceBlobCache.keys().next().value);
1209
- }
1210
- evidenceBlobCache.set(key, entry.bytes);
1211
- return entry.bytes;
1219
+ const digest = sha256Bytes(entry.bytes);
1220
+ evidenceBlobDigestCache.set(key, digest);
1221
+ return digest;
1222
+ }
1223
+
1224
+ /**
1225
+ * b11: what a writer's replay needs from evidence. `replay` discards the verifier's answer (only a thrown refusal changes the
1226
+ * outcome), and the only refusals are a malformed descriptor and an unknown repository. A writer therefore checks those two
1227
+ * without reading the blob; reading every done task's blob through git on every write cost 13 s of a 16 s `todo add` on
1228
+ * bellteam-dev-added. The blob itself is read by readers (the `evidence_unverified` annotation) and, hard, for the new event.
1229
+ */
1230
+ function structuralEvidenceVerifier(manifest) {
1231
+ const repositories = new Set(manifest.repositories.map((repo) => repo.repo_id));
1232
+ return (descriptor) => {
1233
+ if (isTodoDoneMessage(descriptor)) return true;
1234
+ if (!validateEvidenceDescriptor(descriptor)) fail('STORE_INCONSISTENT', 'evidence_descriptor_invalid');
1235
+ if (!repositories.has(descriptor.repo_id)) fail('STORE_INCONSISTENT', 'evidence_repo_missing');
1236
+ return true;
1237
+ };
1238
+ }
1239
+
1240
+ function structuralImportSourceVerifier(descriptor) {
1241
+ if (!validateTodoImportSource(descriptor)) fail('STORE_INCONSISTENT', 'import_source_descriptor_invalid');
1242
+ return true;
1212
1243
  }
1213
1244
 
1214
- function evidenceVerifier(manifest, repoRoot, hard, newEventDigest = null) {
1245
+ /** `todo verify` only (k4): can a recorded evidence blob be read back with its digest and reached from a ref? Reads and writes never ask. */
1246
+ function evidenceVerifier(manifest, repoRoot) {
1215
1247
  const repositories = new Map(manifest.repositories.map((repo) => [repo.repo_id, repo.path]));
1216
- return (descriptor, context = {}) => {
1248
+ return (descriptor) => {
1249
+ if (isTodoDoneMessage(descriptor)) return true; // plain text: nothing to read back
1217
1250
  if (!validateEvidenceDescriptor(descriptor)) fail('STORE_INCONSISTENT', 'evidence_descriptor_invalid');
1218
1251
  const repoRef = repositories.get(descriptor.repo_id);
1219
1252
  if (repoRef === undefined) fail('STORE_INCONSISTENT', 'evidence_repo_missing');
1220
1253
  const absoluteRepo = path.resolve(repoRoot, repoRef);
1221
1254
  try {
1222
- const bytes = readEvidenceBlob(absoluteRepo, descriptor.git_blob_oid);
1223
- // **objectが在ることと、cloneした人が読めることは別である。** commitやtagから辿れない
1224
- // dangling blobでも`cat-file`は通るので、手元では検証済みに見えるのに、fresh cloneでは
1225
- // 誰も確かめられない証拠が残る。実際に16件そうなっており、公開CIで初めて露見した。
1226
- // 手元とCIで判定が食い違う状態を残さない。
1227
- //
1228
- // ただし**書き込み時には要求しない**。証拠文書は同じ変更でcommitするのが普通の流れで、
1229
- // `todo done`の時点ではindexに在るだけである。そこで拒むと正常な運用が止まる。
1230
- // 「記録はできるが、commitするまでverifyは通らない」が正しい強さである。
1231
- if (!hard && !reachableObjects(absoluteRepo).has(descriptor.git_blob_oid)) {
1232
- throw new Error('blob unreachable from refs');
1233
- }
1234
- if (sha256Bytes(bytes) !== descriptor.content_digest) throw new Error('digest mismatch');
1235
- return true;
1255
+ // An object being present is not the same as a fresh clone being able to read it: a dangling blob passes `cat-file`.
1256
+ return readEvidenceBlobDigest(absoluteRepo, descriptor.git_blob_oid) === descriptor.content_digest
1257
+ && reachableObjects(absoluteRepo).has(descriptor.git_blob_oid);
1236
1258
  } catch {
1237
- // 既存の不達は未検証として残す。新eventの証拠だけは書込み前にhard検証する。
1238
- if (newEventDigest !== null && context.event_digest !== newEventDigest) return false;
1239
- if (hard) fail('STORE_INCONSISTENT', 'evidence_unverified', {
1240
- ...context,
1241
- next_action: context.plan_key === undefined
1242
- ? 'verify_the_evidence_descriptor_and_retry'
1243
- : `lattice todo verify --plan ${context.plan_key} --json`,
1244
- });
1245
1259
  return false;
1246
1260
  }
1247
1261
  };
1248
1262
  }
1249
1263
 
1264
+ /**
1265
+ * b11: `todo verify`'s explicit, opt-in evidence check (read-only): the tasks of `member` whose recorded evidence blob
1266
+ * cannot be read back with its digest (or is not reachable from a ref). Reads in `cat-file --batch` chunks. Reads and writes
1267
+ * no longer do this; it was the `evidence_unverified` annotation.
1268
+ */
1269
+ export function findUnverifiedTodoEvidence({ repoRoot, store, member }) {
1270
+ const cache = { commits: new Set(), blobs: new Map() };
1271
+ prefetchVerificationObjects(store.manifest, repoRoot, member.journal.events, cache);
1272
+ const verifyEvidence = evidenceVerifier(store.manifest, repoRoot);
1273
+ const verifyImportSource = importSourceVerifier(repoRoot, false, cache);
1274
+ return member.tasks.filter((task) => {
1275
+ if (task.evidence === null) return false;
1276
+ const context = { plan_key: member.plan.plan_key, task_id: task.task_id, event_digest: null };
1277
+ return !(validateTodoImportSource(task.evidence)
1278
+ ? verifyImportSource(task.evidence, context) : verifyEvidence(task.evidence, context));
1279
+ });
1280
+ }
1281
+
1250
1282
  /**
1251
1283
  * Read-only (a12): the evidence blob is present with its recorded digest but no ref reaches it yet,
1252
1284
  * i.e. it is waiting for a commit (message evidence or an uncommitted file). Missing or changed
@@ -1258,7 +1290,7 @@ export function isTodoEvidenceUncommitted({ repoRoot, store, evidence }) {
1258
1290
  if (repoRef === undefined) return false;
1259
1291
  const absoluteRepo = path.resolve(repoRoot, repoRef);
1260
1292
  try {
1261
- return sha256Bytes(readEvidenceBlob(absoluteRepo, evidence.git_blob_oid)) === evidence.content_digest
1293
+ return readEvidenceBlobDigest(absoluteRepo, evidence.git_blob_oid) === evidence.content_digest
1262
1294
  && !reachableObjects(absoluteRepo).has(evidence.git_blob_oid);
1263
1295
  } catch {
1264
1296
  return false;
@@ -1344,7 +1376,7 @@ function prefetchVerificationObjects(manifest, repoRoot, events, pinnedSourceCac
1344
1376
  const repoRef = repositories.get(candidate.repo_id);
1345
1377
  if (repoRef === undefined) continue;
1346
1378
  const absoluteRepo = path.resolve(repoRoot, repoRef);
1347
- if (evidenceBlobCache.has(`${absoluteRepo}\0${candidate.git_blob_oid}`)) continue;
1379
+ if (evidenceBlobDigestCache.has(`${absoluteRepo}\0${candidate.git_blob_oid}`)) continue;
1348
1380
  let oids = oidsByRepo.get(absoluteRepo);
1349
1381
  if (oids === undefined) oidsByRepo.set(absoluteRepo, oids = new Set());
1350
1382
  oids.add(candidate.git_blob_oid);
@@ -1355,24 +1387,23 @@ function prefetchVerificationObjects(manifest, repoRoot, events, pinnedSourceCac
1355
1387
  }
1356
1388
  }
1357
1389
  for (const [absoluteRepo, oids] of oidsByRepo) {
1358
- let entries;
1359
- try {
1360
- entries = gitCatFileBatch([...oids], {
1361
- cwd: absoluteRepo, maxBodyBytes: TODO_LIMITS.narrativeSectionBytes + 1,
1362
- });
1363
- } catch { continue; }
1364
- let index = 0;
1365
- for (const oid of oids) {
1366
- const entry = entries[index];
1367
- index += 1;
1390
+ // One `cat-file --batch` per EVIDENCE_PREFETCH_BATCH oids keeps the output buffer bounded.
1391
+ const all = [...oids];
1392
+ for (let start = 0; start < all.length; start += EVIDENCE_PREFETCH_BATCH) {
1393
+ const chunk = all.slice(start, start + EVIDENCE_PREFETCH_BATCH);
1394
+ let entries;
1395
+ try {
1396
+ entries = gitCatFileBatch(chunk, {
1397
+ cwd: absoluteRepo, maxBodyBytes: TODO_LIMITS.narrativeSectionBytes + 1,
1398
+ });
1399
+ } catch { continue; }
1368
1400
  // seedしないだけで正誤は変えない: 上限超過bodyは単体読みのmaxBufferでは読めない
1369
- // (=従来は未検証)ので、batch同乗の予算合算で検証済みへ昇格させない。cacheが
1370
- // 満杯なら追い出さずseedを止める——seeding自身の追い出しは自分のseedを連鎖破壊し、
1371
- // 513件以上で全件個別spawnへ戻る。溢れた分はper-item経路が従来どおり扱う。
1372
- if (entry.missing || entry.type !== 'blob'
1373
- || entry.bytes.length > TODO_LIMITS.narrativeSectionBytes
1374
- || evidenceBlobCache.size >= EVIDENCE_BLOB_CACHE_LIMIT) continue;
1375
- evidenceBlobCache.set(`${absoluteRepo}\0${oid}`, entry.bytes);
1401
+ // (=従来は未検証)ので、batch同乗の予算合算で検証済みへ昇格させない。
1402
+ chunk.forEach((oid, index) => {
1403
+ const entry = entries[index];
1404
+ if (entry.missing || entry.type !== 'blob' || entry.bytes.length > TODO_LIMITS.narrativeSectionBytes) return;
1405
+ evidenceBlobDigestCache.set(`${absoluteRepo}\0${oid}`, sha256Bytes(entry.bytes));
1406
+ });
1376
1407
  }
1377
1408
  }
1378
1409
  const pinnedNames = [...pinnedCommits, ...pinnedSpecs];
@@ -1419,6 +1450,7 @@ function liveReplacementPreservesListStructure(lineBytes, replacement) {
1419
1450
  function importSourceVerifier(repoRoot, hard, cache = null, newEventDigest = null) {
1420
1451
  return (descriptor, context = {}) => {
1421
1452
  if (!validateTodoImportSource(descriptor)) fail('STORE_INCONSISTENT', 'import_source_descriptor_invalid');
1453
+ if (newEventDigest !== null && context.event_digest !== newEventDigest) return true; // b11, as evidenceVerifier
1422
1454
  try {
1423
1455
  pinnedSourceLine(repoRoot, descriptor, cache);
1424
1456
  return true;
@@ -1586,18 +1618,20 @@ async function readTodoStoreView(options = {}) {
1586
1618
  }
1587
1619
  }
1588
1620
  await assertNoCrossPlanImportRecoveryNeeded(repoRoot);
1589
- const pinnedSourceCache = { commits: new Set(), blobs: new Map() };
1590
1621
  const manifest = await readManifest(repoRoot);
1591
1622
  const loaded = [];
1592
1623
  for (const descriptor of manifest.members) {
1624
+ // k4 (ADR 0204): a read no longer re-verifies history. `verifyHistory` (only `todo verify`) restores the canonical-byte
1625
+ // checks, the hash chain, the revision/genesis binding and the whole-snapshot comparison.
1626
+ const verifyHistory = options.verifyHistory === true;
1593
1627
  const plan = await readArtifact(repoRoot, descriptor.plan_ref, {
1594
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan,
1628
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, canonical: verifyHistory,
1595
1629
  });
1596
1630
  if (plan.project_id !== manifest.project_id || plan.plan_key !== descriptor.plan_key
1597
1631
  || plan.plan_version !== descriptor.active_plan_version || plan.topology_digest !== descriptor.topology_digest) {
1598
1632
  fail('STORE_INCONSISTENT', 'manifest_plan_binding_mismatch');
1599
1633
  }
1600
- const journal = await readJournal(repoRoot, descriptor.journal_ref);
1634
+ const journal = await readJournal(repoRoot, descriptor.journal_ref, { verify: verifyHistory });
1601
1635
  if (journal.events.at(-1).event_digest !== descriptor.journal_head_digest) {
1602
1636
  if (!options.recovery || !journal.events.some(({ event_digest: digest }) => (
1603
1637
  digest === descriptor.journal_head_digest))) {
@@ -1612,7 +1646,7 @@ async function readTodoStoreView(options = {}) {
1612
1646
  const revisionRef = path.posix.join(path.posix.dirname(descriptor.plan_ref), 'revision.json');
1613
1647
  const phaseRevision = genesis.schema === 'lattice.todo_event.v4';
1614
1648
  revision = await readArtifact(repoRoot, revisionRef, {
1615
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes,
1649
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, canonical: verifyHistory,
1616
1650
  validate: (value) => {
1617
1651
  rejectUnsupportedRevisionSchema(value, phaseRevision ? {
1618
1652
  family: 'phase_todo_revision', supportedSchemas: PHASE_TODO_REVISION_SCHEMAS,
@@ -1622,74 +1656,70 @@ async function readTodoStoreView(options = {}) {
1622
1656
  return phaseRevision ? validatePhaseTodoRevision(value) : validateTodoRevision(value);
1623
1657
  },
1624
1658
  });
1625
- const migrationProjection = genesis.state_migration.map((entry) => ({
1626
- from_task_id: entry.from_task_id, to_task_id: entry.to_task_id,
1627
- state_policy: entry.state_policy,
1628
- }));
1629
- if (canonicalizeTodoArtifact(revision.desired_plan) !== canonicalizeTodoArtifact(plan)
1630
- || revision.revision_digest !== genesis.revision_digest
1631
- || revision.predecessor.plan_digest !== genesis.payload.predecessor_plan_digest
1632
- || revision.predecessor.journal_head_digest !== genesis.previous_digest
1633
- || canonicalizeTodoArtifact(revision.task_migration)
1634
- !== canonicalizeTodoArtifact(migrationProjection)) {
1635
- fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
1636
- }
1637
- if (manifest.schema === 'lattice.todo_manifest.v2'
1638
- && descriptor.active_revision_digest !== genesis.revision_digest) {
1639
- fail('STORE_INCONSISTENT', 'manifest_revision_binding_mismatch');
1640
- }
1641
- if (genesis.schema === 'lattice.todo_event.v2'
1642
- && revision.reconciliation.reconciliation_digest !== genesis.reconciliation_digest) {
1643
- fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
1644
- }
1645
- if (genesis.schema === 'lattice.todo_event.v4') {
1646
- const phaseProjection = revision.phase_migration
1647
- .filter(({ to_phase_id }) => to_phase_id !== 'removed')
1648
- .map(({ to_phase_id, state_policy }) => ({ phase_id: to_phase_id, state_policy }))
1649
- .sort((left, right) => left.phase_id.localeCompare(right.phase_id));
1650
- const genesisProjection = genesis.phase_state_migration
1651
- .map(({ phase_id, state_policy }) => ({ phase_id, state_policy }));
1652
- if (canonicalizeTodoArtifact(phaseProjection) !== canonicalizeTodoArtifact(genesisProjection)) {
1659
+ if (verifyHistory) {
1660
+ const migrationProjection = genesis.state_migration.map((entry) => ({
1661
+ from_task_id: entry.from_task_id, to_task_id: entry.to_task_id,
1662
+ state_policy: entry.state_policy,
1663
+ }));
1664
+ if (canonicalizeTodoArtifact(revision.desired_plan) !== canonicalizeTodoArtifact(plan)
1665
+ || revision.revision_digest !== genesis.revision_digest
1666
+ || revision.predecessor.plan_digest !== genesis.payload.predecessor_plan_digest
1667
+ || revision.predecessor.journal_head_digest !== genesis.previous_digest
1668
+ || canonicalizeTodoArtifact(revision.task_migration)
1669
+ !== canonicalizeTodoArtifact(migrationProjection)) {
1670
+ fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
1671
+ }
1672
+ if (manifest.schema === 'lattice.todo_manifest.v2'
1673
+ && descriptor.active_revision_digest !== genesis.revision_digest) {
1674
+ fail('STORE_INCONSISTENT', 'manifest_revision_binding_mismatch');
1675
+ }
1676
+ if (genesis.schema === 'lattice.todo_event.v2'
1677
+ && revision.reconciliation.reconciliation_digest !== genesis.reconciliation_digest) {
1653
1678
  fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
1654
1679
  }
1680
+ if (genesis.schema === 'lattice.todo_event.v4') {
1681
+ const phaseProjection = revision.phase_migration
1682
+ .filter(({ to_phase_id }) => to_phase_id !== 'removed')
1683
+ .map(({ to_phase_id, state_policy }) => ({ phase_id: to_phase_id, state_policy }))
1684
+ .sort((left, right) => left.phase_id.localeCompare(right.phase_id));
1685
+ const genesisProjection = genesis.phase_state_migration
1686
+ .map(({ phase_id, state_policy }) => ({ phase_id, state_policy }));
1687
+ if (canonicalizeTodoArtifact(phaseProjection) !== canonicalizeTodoArtifact(genesisProjection)) {
1688
+ fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
1689
+ }
1690
+ }
1655
1691
  }
1656
1692
  }
1657
1693
  if (manifest.schema === 'lattice.todo_manifest.v2' && revision === null
1658
1694
  && descriptor.active_revision_digest !== plan.plan_digest) {
1659
1695
  fail('STORE_INCONSISTENT', 'manifest_revision_binding_mismatch');
1660
1696
  }
1661
- prefetchVerificationObjects(manifest, repoRoot, journal.events, pinnedSourceCache);
1662
- const verifyEvidence = evidenceVerifier(manifest, repoRoot, false);
1663
- const verifyImportSource = importSourceVerifier(repoRoot, false, pinnedSourceCache);
1697
+ // b11 (ADR 0203): a read or write no longer re-verifies stored evidence. It read every done task's blob through
1698
+ // `git cat-file` and only set `evidence_unverified`, which blocked nothing (guards.remove-unnamed). Writers keep the
1699
+ // descriptor-shape check (no git); `todo verify` checks the blobs on request (`findUnverifiedTodoEvidence`).
1664
1700
  const tasks = replay(plan, journal.events, {
1665
1701
  now: options.now ? new Date(options.now) : new Date(),
1666
- verifyEvidence: options.forWrite === true ? verifyEvidence : undefined,
1667
- verifyImportSource: options.forWrite === true ? verifyImportSource : undefined,
1702
+ verifyEvidence: options.forWrite === true ? structuralEvidenceVerifier(manifest) : undefined,
1703
+ verifyImportSource: options.forWrite === true ? structuralImportSourceVerifier : undefined,
1668
1704
  });
1669
- const expectedSnapshot = snapshotFor(plan, journal.events, structuredClone(tasks));
1670
- // Read-time evidence failure is annotation, never store rejection.
1671
- for (const task of tasks) if (task.evidence !== null) {
1672
- const context = {
1673
- plan_key: plan.plan_key,
1674
- task_id: task.task_id,
1675
- event_digest: null,
1676
- };
1677
- const verified = validateTodoImportSource(task.evidence)
1678
- ? verifyImportSource(task.evidence, context) : verifyEvidence(task.evidence, context);
1679
- if (!verified) task.evidence_unverified = true;
1680
- }
1681
1705
  let snapshot = null;
1682
1706
  let snapshotStale = false;
1707
+ let expectedSnapshot = null;
1683
1708
  try {
1684
1709
  snapshot = await readSnapshotArtifact(repoRoot, descriptor.snapshot_ref);
1685
- snapshotStale = snapshot === null || canonicalizeTodoArtifact(snapshot) !== canonicalizeTodoArtifact(expectedSnapshot);
1710
+ // The snapshot is current when it names the journal head (O(1)); only `todo verify` compares its whole content.
1711
+ snapshotStale = snapshot === null || snapshot.journal_head_digest !== journal.events.at(-1).event_digest;
1712
+ if (!snapshotStale && verifyHistory) {
1713
+ expectedSnapshot = snapshotFor(plan, journal.events, structuredClone(tasks));
1714
+ snapshotStale = canonicalizeTodoArtifact(snapshot) !== canonicalizeTodoArtifact(expectedSnapshot);
1715
+ }
1686
1716
  } catch (error) {
1687
1717
  if (error instanceof TodoStoreError && error.code === 'SNAPSHOT_INVALID'
1688
1718
  && !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store']
1689
1719
  .includes(error.detail.reason)) snapshotStale = true;
1690
1720
  else throw error;
1691
1721
  }
1692
- if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
1722
+ if (snapshotStale) expectedSnapshot ??= snapshotFor(plan, journal.events, structuredClone(tasks)); // a stale snapshot is rebuilt, never a refusal
1693
1723
  // 導出済みphase状態(ADR 0147)。snapshot artifactの形式(v1/v2)には縛られず、v4/v5・
1694
1724
  // phase無しplanのどちらでも同じ形(暗黙のterminal-audit Phase込み)で常に埋める。
1695
1725
  // 消費者はここを読み、snapshot.phases(v1には存在しない)を直接読まない。
@@ -2657,13 +2687,11 @@ export async function appendTodoEvent(options = {}) {
2657
2687
  fail(validation.code, reason, detail);
2658
2688
  }
2659
2689
  if (validation?.ok !== true) throw new TypeError('prospective validator must return an ok result');
2660
- const appendSourceCache = { commits: new Set(), blobs: new Map() };
2661
- prefetchVerificationObjects(store.manifest, repoRoot,
2662
- [...member.journal.events, event], appendSourceCache);
2690
+ // k4 (ADR 0204): the prospective replay validates the transition; no evidence or import source is read back (descriptor shape only).
2663
2691
  replay(member.plan, [...member.journal.events, event], {
2664
2692
  now: options.now ? new Date(options.now) : new Date(),
2665
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, true, event.event_digest),
2666
- verifyImportSource: importSourceVerifier(repoRoot, true, appendSourceCache, event.event_digest),
2693
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
2694
+ verifyImportSource: structuralImportSourceVerifier,
2667
2695
  });
2668
2696
  if (options.materializedEvidence !== null && options.materializedEvidence !== undefined) {
2669
2697
  const asset = options.materializedEvidence;
@@ -2697,8 +2725,8 @@ export async function appendTodoEvent(options = {}) {
2697
2725
  await protocolStage(options, 'event_journal_published');
2698
2726
  const tasks = replay(member.plan, [...member.journal.events, event], {
2699
2727
  now: options.now ? new Date(options.now) : new Date(),
2700
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
2701
- verifyImportSource: importSourceVerifier(repoRoot, false, appendSourceCache),
2728
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
2729
+ verifyImportSource: structuralImportSourceVerifier,
2702
2730
  });
2703
2731
  const snapshot = snapshotFor(member.plan, [...member.journal.events, event], tasks);
2704
2732
  await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(snapshot));
@@ -3945,7 +3973,7 @@ async function withInitialStoreLocks(stage, currentRoot, callback) {
3945
3973
  /** G5-only initial authoring transaction. Store membership appears by one final directory rename. */
3946
3974
  const CHART_META_REF = '.lattice/chart.json';
3947
3975
  const CHART_META_MAX_BYTES = 65_536;
3948
- const CHART_META_PATCH_KEYS = ['name', 'created_by', 'repo'];
3976
+ const CHART_META_PATCH_KEYS = ['name', 'created_by', 'repo', 'no_code_lanes'];
3949
3977
 
3950
3978
  /** The recorded chart identity, or null when `.lattice/chart.json` does not exist. */
3951
3979
  async function readChartMetaRecord(repoRoot) {
@@ -3971,7 +3999,7 @@ async function readChartMetaRecord(repoRoot) {
3971
3999
  }
3972
4000
 
3973
4001
  const chartMetaView = (record) => ({ name: record?.name ?? null, created_by: record?.created_by ?? null,
3974
- created_at: record?.created_at ?? null, repo: record?.repo ?? null });
4002
+ created_at: record?.created_at ?? null, repo: record?.repo ?? null, no_code_lanes: record?.no_code_lanes ?? [] });
3975
4003
 
3976
4004
  /**
3977
4005
  * a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). Read only, no lock, no Store needed: a missing file
@@ -3982,7 +4010,7 @@ export async function readTodoChartMeta({ repoRoot = process.cwd() } = {}) {
3982
4010
  }
3983
4011
 
3984
4012
  /**
3985
- * a101 K4: patch {name?, created_by?, repo?} (absent key = keep). `created_by` applies only while unrecorded and
4013
+ * a101 K4: patch {name?, created_by?, repo?, no_code_lanes?} (absent key = keep; `no_code_lanes` replaces the list). `created_by` applies only while unrecorded and
3986
4014
  * `created_at` is stamped when the file is first created: the creator is never overwritten. Works before the first plan
3987
4015
  * (creates `.lattice/`). The read-modify-write holds `.lattice/.chart.write.lock` so two writers cannot both see an
3988
4016
  * unrecorded creator (identified lock, proven-dead recovery). Name rules are the CLI's.
@@ -4014,6 +4042,10 @@ export async function writeTodoChartMeta({ repoRoot = process.cwd(), patch = {}
4014
4042
  created_at: current === null ? new Date().toISOString() : current.created_at,
4015
4043
  repo: 'repo' in patch ? patch.repo : current?.repo ?? null,
4016
4044
  };
4045
+ // The list is stored only when non-empty; the patch value replaces it (sorted, unique).
4046
+ const lanes = 'no_code_lanes' in patch ? patch.no_code_lanes : current?.no_code_lanes ?? [];
4047
+ if (!Array.isArray(lanes)) throw new TypeError('chart meta patch invalid');
4048
+ if (lanes.length > 0) next.no_code_lanes = 'no_code_lanes' in patch ? [...new Set(lanes)].sort() : lanes;
4017
4049
  if (!validateTodoChartMeta(next)) throw new TypeError('chart meta patch invalid');
4018
4050
  if (current !== null && canonicalizeTodoArtifact(next) === canonicalizeTodoArtifact(current)) {
4019
4051
  return { meta: chartMetaView(current), unchanged: true };
@@ -5258,8 +5290,8 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
5258
5290
  await protocolStage(options, 'phase_v3_marker_durable');
5259
5291
  const tasks = replay(revision.desired_plan, [genesis], {
5260
5292
  now: options.now ? new Date(options.now) : new Date(),
5261
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
5262
- verifyImportSource: importSourceVerifier(repoRoot, false),
5293
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
5294
+ verifyImportSource: structuralImportSourceVerifier,
5263
5295
  });
5264
5296
  const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
5265
5297
  for (const [stage, ref, bytes] of [
@@ -5429,8 +5461,8 @@ export async function applyPhaseTodoRevision(options = {}) {
5429
5461
  await protocolStage(options, 'phase_revision_marker_durable');
5430
5462
  const tasks = replay(revision.desired_plan, [genesis], {
5431
5463
  now: options.now ? new Date(options.now) : new Date(),
5432
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
5433
- verifyImportSource: importSourceVerifier(repoRoot, false),
5464
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
5465
+ verifyImportSource: structuralImportSourceVerifier,
5434
5466
  });
5435
5467
  const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
5436
5468
  const artifacts = [
@@ -5587,8 +5619,8 @@ export async function applyTodoRevision(options = {}) {
5587
5619
  }
5588
5620
  await protocolStage(options, 'revision_marker_durable');
5589
5621
 
5590
- const verifyEvidence = evidenceVerifier(store.manifest, repoRoot, false);
5591
- const verifyImportSource = importSourceVerifier(repoRoot, false);
5622
+ const verifyEvidence = structuralEvidenceVerifier(store.manifest);
5623
+ const verifyImportSource = structuralImportSourceVerifier;
5592
5624
  const tasks = replay(revision.desired_plan, [genesis], {
5593
5625
  now: options.now ? new Date(options.now) : new Date(), verifyEvidence, verifyImportSource,
5594
5626
  });
@@ -5869,8 +5901,8 @@ export async function applyTodoRevisionSet(options = {}) {
5869
5901
  }
5870
5902
  await protocolStage(options, 'revision_set_marker_durable');
5871
5903
 
5872
- const verifyEvidence = evidenceVerifier(store.manifest, repoRoot, false);
5873
- const verifyImportSource = importSourceVerifier(repoRoot, false);
5904
+ const verifyEvidence = structuralEvidenceVerifier(store.manifest);
5905
+ const verifyImportSource = structuralImportSourceVerifier;
5874
5906
  for (const entry of prepared) {
5875
5907
  const { revision, genesis } = entry;
5876
5908
  const tasks = replay(revision.desired_plan, [genesis], {