@quolu/lattice 0.104.0 → 0.106.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.
- package/README.ja.md +4 -4
- package/docs/bridge-setup.md +2 -2
- package/package.json +1 -1
- package/src/cli-help.mjs +2 -0
- package/src/project-cli.mjs +1 -1
- package/src/todo-audit-pending.mjs +8 -8
- package/src/todo-cli.mjs +18 -7
- package/src/todo-contracts.mjs +26 -2
- package/src/todo-gantt-html-style.mjs +1 -1
- package/src/todo-gantt-html.mjs +6 -6
- package/src/todo-gantt-scope.mjs +3 -3
- package/src/todo-note-store.mjs +20 -2
- package/src/todo-status.mjs +5 -5
- package/src/todo-store.mjs +311 -183
- package/src/todo-version-compact.mjs +110 -0
package/src/todo-store.mjs
CHANGED
|
@@ -17,10 +17,14 @@ export {
|
|
|
17
17
|
todoTaskCarrySemantics,
|
|
18
18
|
} from './todo-store-view.mjs';
|
|
19
19
|
import { randomBytes } from 'node:crypto';
|
|
20
|
+
import { gunzipSync, gzipSync } from 'node:zlib';
|
|
20
21
|
import { fsyncDirectory } from './fs-dir-sync.mjs';
|
|
21
22
|
import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
|
|
22
23
|
import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
|
|
23
24
|
import { memoByFileIdentity } from './todo-version-memo.mjs';
|
|
25
|
+
import {
|
|
26
|
+
TODO_VERSION_COMPACT_FILE, buildVersionCompact, packVersionCompact, readVersionCompact, reconstructPlan, reconstructRevision,
|
|
27
|
+
} from './todo-version-compact.mjs';
|
|
24
28
|
import {
|
|
25
29
|
lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
|
|
26
30
|
} from 'node:fs/promises';
|
|
@@ -37,6 +41,7 @@ import {
|
|
|
37
41
|
exactRecord,
|
|
38
42
|
isStrictTodoTimestamp,
|
|
39
43
|
isTodoDigest,
|
|
44
|
+
isTodoDoneMessage,
|
|
40
45
|
isTodoIdentifier,
|
|
41
46
|
isTodoRef,
|
|
42
47
|
todoSelfDigest,
|
|
@@ -226,7 +231,7 @@ function decodeUtf8(bytes, code, reason) {
|
|
|
226
231
|
catch { fail(code, reason); }
|
|
227
232
|
}
|
|
228
233
|
|
|
229
|
-
function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null }) {
|
|
234
|
+
function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref = null, canonical = true }) {
|
|
230
235
|
const detail = ref === null ? undefined : { ref };
|
|
231
236
|
if (bytes.length === 0 || bytes.length > maxBytes) {
|
|
232
237
|
fail(code, bytes.length > maxBytes ? 'size_limit_exceeded' : reason, detail);
|
|
@@ -237,9 +242,11 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
|
|
|
237
242
|
let value;
|
|
238
243
|
try { value = JSON.parse(body); } catch { fail(code, reason, detail); }
|
|
239
244
|
if (!text.endsWith('\n')) fail(code, reason, detail);
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
+
}
|
|
243
250
|
if (!validate(value)) {
|
|
244
251
|
const newer = NEWER_SCHEMA_FAMILY.has(validate) ? newerSchema(value, NEWER_SCHEMA_FAMILY.get(validate)) : null;
|
|
245
252
|
if (newer !== null) failNewer(newer, ref);
|
|
@@ -248,12 +255,12 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
|
|
|
248
255
|
return value;
|
|
249
256
|
}
|
|
250
257
|
|
|
251
|
-
async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false }) {
|
|
258
|
+
async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false, canonical = true }) {
|
|
252
259
|
const state = await pathState(repoRoot, ref, code, { missing });
|
|
253
260
|
if (state === null) return null;
|
|
254
261
|
const bytes = normalizeCheckoutEol(await readFile(state.absolute));
|
|
255
262
|
return parseCanonicalJsonLine(bytes, {
|
|
256
|
-
code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref,
|
|
263
|
+
code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref, canonical,
|
|
257
264
|
});
|
|
258
265
|
}
|
|
259
266
|
|
|
@@ -267,7 +274,7 @@ async function readSnapshotArtifact(repoRoot, ref) {
|
|
|
267
274
|
});
|
|
268
275
|
}
|
|
269
276
|
|
|
270
|
-
function parseJournalSegment(bytes, ref = null) {
|
|
277
|
+
function parseJournalSegment(bytes, ref = null, { canonical: checkCanonical = true } = {}) {
|
|
271
278
|
const detail = ref === null ? undefined : { ref };
|
|
272
279
|
if (bytes.length === 0 || bytes.length > TODO_LIMITS.journalSegmentBytes) {
|
|
273
280
|
fail('STORE_CORRUPT', bytes.length > TODO_LIMITS.journalSegmentBytes
|
|
@@ -281,8 +288,8 @@ function parseJournalSegment(bytes, ref = null) {
|
|
|
281
288
|
let event;
|
|
282
289
|
try { event = JSON.parse(line); } catch { fail('STORE_CORRUPT', 'journal_json_invalid'); }
|
|
283
290
|
let canonical;
|
|
284
|
-
try { canonical = canonicalizeTodoArtifact(event); } catch { fail('STORE_CORRUPT', 'journal_schema_invalid'); }
|
|
285
|
-
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');
|
|
286
293
|
if (!validateTodoEvent(event)) {
|
|
287
294
|
const newer = newerEventValue(event);
|
|
288
295
|
if (newer !== null) failNewer(newer, ref);
|
|
@@ -293,7 +300,7 @@ function parseJournalSegment(bytes, ref = null) {
|
|
|
293
300
|
}
|
|
294
301
|
|
|
295
302
|
/** Sealed segments of one chain, in order, each checked for name, digest, range and link. */
|
|
296
|
-
async function readSealedSegments(repoRoot, journalRef, directoryName) {
|
|
303
|
+
async function readSealedSegments(repoRoot, journalRef, directoryName, { canonical = true } = {}) {
|
|
297
304
|
const sealedDirectory = path.resolve(repoRoot, path.dirname(journalRef), directoryName);
|
|
298
305
|
const segments = [];
|
|
299
306
|
try {
|
|
@@ -310,7 +317,7 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
|
|
|
310
317
|
const [, startText, endText, previousDigest, segmentDigest] = name.match(
|
|
311
318
|
/^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u,
|
|
312
319
|
);
|
|
313
|
-
const events = parseJournalSegment(bytes, ref);
|
|
320
|
+
const events = parseJournalSegment(bytes, ref, { canonical });
|
|
314
321
|
if (sha256Bytes(bytes) !== segmentDigest) fail('STORE_CORRUPT', 'sealed_segment_digest_mismatch');
|
|
315
322
|
if (events[0].sequence !== Number(startText) || events.at(-1).sequence !== Number(endText)) {
|
|
316
323
|
fail('STORE_CORRUPT', 'sealed_segment_range_mismatch');
|
|
@@ -327,16 +334,26 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
|
|
|
327
334
|
return segments;
|
|
328
335
|
}
|
|
329
336
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
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 } = {}) {
|
|
342
|
+
// b10: a retained version's active segment may be kept gzip-packed as `active.jsonl.gz` (same bytes once unpacked).
|
|
343
|
+
const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT', { missing: true });
|
|
344
|
+
const packed = state === null ? await pathState(repoRoot, `${journalRef}.gz`, 'STORE_CORRUPT') : null;
|
|
345
|
+
const segments = await readSealedSegments(repoRoot, journalRef, 'sealed', { canonical: verify });
|
|
346
|
+
let activeBytes;
|
|
347
|
+
try {
|
|
348
|
+
activeBytes = state === null ? gunzipSync(await readFile(packed.absolute), { maxOutputLength: TODO_LIMITS.journalSegmentBytes })
|
|
349
|
+
: normalizeCheckoutEol(await readFile(state.absolute));
|
|
350
|
+
} catch { fail('STORE_CORRUPT', 'journal_gzip_invalid', { ref: `${journalRef}.gz` }); }
|
|
334
351
|
const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
|
|
335
352
|
if (!duplicateActive) {
|
|
336
|
-
segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
|
|
353
|
+
segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef, { canonical: verify }) });
|
|
337
354
|
}
|
|
338
355
|
const events = segments.flatMap(({ events: entries }) => entries);
|
|
339
|
-
const failures = verifyLinearHashChain({
|
|
356
|
+
const failures = !verify ? new Set() : verifyLinearHashChain({
|
|
340
357
|
entries: events,
|
|
341
358
|
canonicalize: canonicalizeTodoArtifact,
|
|
342
359
|
digestField: 'event_digest',
|
|
@@ -523,11 +540,11 @@ function projectPhaseStates(plan, events, taskStates) {
|
|
|
523
540
|
} else if (event.kind === 'phase_accept') {
|
|
524
541
|
const state = states.get(event.phase_id);
|
|
525
542
|
state.status = 'accepted'; state.decision_event_digest = event.event_digest;
|
|
526
|
-
state.decision_evidence = event.payload.decision_evidence;
|
|
543
|
+
state.decision_evidence = event.payload.decision_evidence ?? null;
|
|
527
544
|
} else if (event.kind === 'phase_reject') {
|
|
528
545
|
const state = states.get(event.phase_id);
|
|
529
546
|
state.status = 'rejected'; state.decision_event_digest = event.event_digest;
|
|
530
|
-
state.decision_evidence = event.payload.decision_evidence;
|
|
547
|
+
state.decision_evidence = event.payload.decision_evidence ?? null;
|
|
531
548
|
} else if (event.kind === 'phase_close_unaudited') {
|
|
532
549
|
// ADR 0148: 監査していないので証拠(decision_evidence)は残さない。理由はevent payload
|
|
533
550
|
// 自身(decision_event_digestで指せるこの event)に記録済みで、accept/rejectと違い
|
|
@@ -683,12 +700,14 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
|
|
|
683
700
|
pendingVerifications.delete(`phase:${event.phase_id}`);
|
|
684
701
|
} else if (event.kind === 'phase_accept') {
|
|
685
702
|
const phase = phasesOf(plan).find(({ phase_id }) => phase_id === event.phase_id);
|
|
686
|
-
|
|
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);
|
|
687
705
|
if (currentStatus !== 'reviewing' || state.review_event_digest !== event.payload.review_event_digest
|
|
688
|
-
||
|
|
706
|
+
|| (slots !== undefined
|
|
707
|
+
&& canonicalizeTodoArtifact(slots) !== canonicalizeTodoArtifact(phase.required_evidence_slots))) {
|
|
689
708
|
fail('STORE_INCONSISTENT', 'phase_accept_binding_invalid');
|
|
690
709
|
}
|
|
691
|
-
if (verifyEvidence) {
|
|
710
|
+
if (verifyEvidence && event.payload.decision_evidence !== undefined) {
|
|
692
711
|
const decisionEvidence = event.payload.decision_evidence;
|
|
693
712
|
const slotEvidence = event.payload.evidence_slots.map((slot) => slot.evidence);
|
|
694
713
|
pendingVerifications.set(`phase:${event.phase_id}`, () => {
|
|
@@ -699,19 +718,19 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
|
|
|
699
718
|
});
|
|
700
719
|
}
|
|
701
720
|
state.status = 'accepted'; state.decision_event_digest = event.event_digest;
|
|
702
|
-
state.decision_evidence = event.payload.decision_evidence;
|
|
721
|
+
state.decision_evidence = event.payload.decision_evidence ?? null;
|
|
703
722
|
} else if (event.kind === 'phase_reject') {
|
|
704
723
|
if (currentStatus !== 'reviewing' || state.review_event_digest !== event.payload.review_event_digest) {
|
|
705
724
|
fail('STORE_INCONSISTENT', 'phase_reject_binding_invalid');
|
|
706
725
|
}
|
|
707
|
-
if (verifyEvidence) {
|
|
726
|
+
if (verifyEvidence && event.payload.decision_evidence !== undefined) {
|
|
708
727
|
const decisionEvidence = event.payload.decision_evidence;
|
|
709
728
|
pendingVerifications.set(`phase:${event.phase_id}`, () => verifyEvidence(decisionEvidence, {
|
|
710
729
|
plan_key: plan.plan_key, phase_id: event.phase_id, event_digest: event.event_digest,
|
|
711
730
|
}));
|
|
712
731
|
}
|
|
713
732
|
state.status = 'rejected'; state.decision_event_digest = event.event_digest;
|
|
714
|
-
state.decision_evidence = event.payload.decision_evidence;
|
|
733
|
+
state.decision_evidence = event.payload.decision_evidence ?? null;
|
|
715
734
|
} else if (event.kind === 'phase_close_unaudited') {
|
|
716
735
|
// ADR 0148裁定3: reviewと同じ前提(gate_ready)を課す——所属ToDoが全てdoneでない段階では
|
|
717
736
|
// まだ監査の地点に到達していないので、監査なしで閉じることもできない。
|
|
@@ -840,13 +859,13 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
|
|
|
840
859
|
} else if (event.kind === 'done') {
|
|
841
860
|
if (event.payload.done_mode === 'authored') {
|
|
842
861
|
if (state.status !== 'in-progress' || !dependenciesDone) fail('STORE_INCONSISTENT', 'invalid_done_transition');
|
|
843
|
-
if (verifyEvidence) {
|
|
862
|
+
if (verifyEvidence && event.payload.evidence !== undefined) {
|
|
844
863
|
const evidence = event.payload.evidence;
|
|
845
864
|
pendingVerifications.set(`task:${event.task_id}`, () => verifyEvidence(evidence, {
|
|
846
865
|
plan_key: plan.plan_key, task_id: event.task_id, event_digest: event.event_digest,
|
|
847
866
|
}));
|
|
848
867
|
}
|
|
849
|
-
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 };
|
|
850
869
|
state.test_result = event.payload.test_result ?? null;
|
|
851
870
|
state.imported = false;
|
|
852
871
|
completion.set(event.task_id, { mode: 'authored', completed_at: event.recorded_at });
|
|
@@ -1180,12 +1199,15 @@ function reachableObjects(absoluteRepo) {
|
|
|
1180
1199
|
// blob は内容アドレスなので oid が同じなら bytes は不変。gantt serve 等が store を再読する
|
|
1181
1200
|
// たびに同じ evidence blob を git 子起動で読み直すのを避ける(Windows のウィンドウ雪崩と
|
|
1182
1201
|
// 走査コストの主犯)。成功した読みだけを覚え、失敗は覚えない(repo 状態は変わりうる)。
|
|
1183
|
-
|
|
1184
|
-
|
|
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;
|
|
1185
1207
|
|
|
1186
|
-
function
|
|
1208
|
+
function readEvidenceBlobDigest(absoluteRepo, oid) {
|
|
1187
1209
|
const key = `${absoluteRepo}\0${oid}`;
|
|
1188
|
-
const cached =
|
|
1210
|
+
const cached = evidenceBlobDigestCache.get(key);
|
|
1189
1211
|
if (cached !== undefined) return cached;
|
|
1190
1212
|
const [entry] = gitCatFileBatch([oid], {
|
|
1191
1213
|
cwd: absoluteRepo, maxBodyBytes: TODO_LIMITS.narrativeSectionBytes + 1,
|
|
@@ -1194,49 +1216,69 @@ function readEvidenceBlob(absoluteRepo, oid) {
|
|
|
1194
1216
|
// 契約上限はbytesで明示判定し、process bufferの打切りを意味判定に使わない。
|
|
1195
1217
|
if (entry.missing || entry.type !== 'blob'
|
|
1196
1218
|
|| entry.bytes.length > TODO_LIMITS.narrativeSectionBytes) throw new Error('not bounded blob');
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
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;
|
|
1202
1243
|
}
|
|
1203
1244
|
|
|
1204
|
-
|
|
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) {
|
|
1205
1247
|
const repositories = new Map(manifest.repositories.map((repo) => [repo.repo_id, repo.path]));
|
|
1206
|
-
return (descriptor
|
|
1248
|
+
return (descriptor) => {
|
|
1249
|
+
if (isTodoDoneMessage(descriptor)) return true; // plain text: nothing to read back
|
|
1207
1250
|
if (!validateEvidenceDescriptor(descriptor)) fail('STORE_INCONSISTENT', 'evidence_descriptor_invalid');
|
|
1208
1251
|
const repoRef = repositories.get(descriptor.repo_id);
|
|
1209
1252
|
if (repoRef === undefined) fail('STORE_INCONSISTENT', 'evidence_repo_missing');
|
|
1210
1253
|
const absoluteRepo = path.resolve(repoRoot, repoRef);
|
|
1211
1254
|
try {
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
// 誰も確かめられない証拠が残る。実際に16件そうなっており、公開CIで初めて露見した。
|
|
1216
|
-
// 手元とCIで判定が食い違う状態を残さない。
|
|
1217
|
-
//
|
|
1218
|
-
// ただし**書き込み時には要求しない**。証拠文書は同じ変更でcommitするのが普通の流れで、
|
|
1219
|
-
// `todo done`の時点ではindexに在るだけである。そこで拒むと正常な運用が止まる。
|
|
1220
|
-
// 「記録はできるが、commitするまでverifyは通らない」が正しい強さである。
|
|
1221
|
-
if (!hard && !reachableObjects(absoluteRepo).has(descriptor.git_blob_oid)) {
|
|
1222
|
-
throw new Error('blob unreachable from refs');
|
|
1223
|
-
}
|
|
1224
|
-
if (sha256Bytes(bytes) !== descriptor.content_digest) throw new Error('digest mismatch');
|
|
1225
|
-
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);
|
|
1226
1258
|
} catch {
|
|
1227
|
-
// 既存の不達は未検証として残す。新eventの証拠だけは書込み前にhard検証する。
|
|
1228
|
-
if (newEventDigest !== null && context.event_digest !== newEventDigest) return false;
|
|
1229
|
-
if (hard) fail('STORE_INCONSISTENT', 'evidence_unverified', {
|
|
1230
|
-
...context,
|
|
1231
|
-
next_action: context.plan_key === undefined
|
|
1232
|
-
? 'verify_the_evidence_descriptor_and_retry'
|
|
1233
|
-
: `lattice todo verify --plan ${context.plan_key} --json`,
|
|
1234
|
-
});
|
|
1235
1259
|
return false;
|
|
1236
1260
|
}
|
|
1237
1261
|
};
|
|
1238
1262
|
}
|
|
1239
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
|
+
|
|
1240
1282
|
/**
|
|
1241
1283
|
* Read-only (a12): the evidence blob is present with its recorded digest but no ref reaches it yet,
|
|
1242
1284
|
* i.e. it is waiting for a commit (message evidence or an uncommitted file). Missing or changed
|
|
@@ -1248,7 +1290,7 @@ export function isTodoEvidenceUncommitted({ repoRoot, store, evidence }) {
|
|
|
1248
1290
|
if (repoRef === undefined) return false;
|
|
1249
1291
|
const absoluteRepo = path.resolve(repoRoot, repoRef);
|
|
1250
1292
|
try {
|
|
1251
|
-
return
|
|
1293
|
+
return readEvidenceBlobDigest(absoluteRepo, evidence.git_blob_oid) === evidence.content_digest
|
|
1252
1294
|
&& !reachableObjects(absoluteRepo).has(evidence.git_blob_oid);
|
|
1253
1295
|
} catch {
|
|
1254
1296
|
return false;
|
|
@@ -1334,7 +1376,7 @@ function prefetchVerificationObjects(manifest, repoRoot, events, pinnedSourceCac
|
|
|
1334
1376
|
const repoRef = repositories.get(candidate.repo_id);
|
|
1335
1377
|
if (repoRef === undefined) continue;
|
|
1336
1378
|
const absoluteRepo = path.resolve(repoRoot, repoRef);
|
|
1337
|
-
if (
|
|
1379
|
+
if (evidenceBlobDigestCache.has(`${absoluteRepo}\0${candidate.git_blob_oid}`)) continue;
|
|
1338
1380
|
let oids = oidsByRepo.get(absoluteRepo);
|
|
1339
1381
|
if (oids === undefined) oidsByRepo.set(absoluteRepo, oids = new Set());
|
|
1340
1382
|
oids.add(candidate.git_blob_oid);
|
|
@@ -1345,24 +1387,23 @@ function prefetchVerificationObjects(manifest, repoRoot, events, pinnedSourceCac
|
|
|
1345
1387
|
}
|
|
1346
1388
|
}
|
|
1347
1389
|
for (const [absoluteRepo, oids] of oidsByRepo) {
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
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; }
|
|
1358
1400
|
// seedしないだけで正誤は変えない: 上限超過bodyは単体読みのmaxBufferでは読めない
|
|
1359
|
-
// (=従来は未検証)ので、batch同乗の予算合算で検証済みへ昇格させない。
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
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
|
+
});
|
|
1366
1407
|
}
|
|
1367
1408
|
}
|
|
1368
1409
|
const pinnedNames = [...pinnedCommits, ...pinnedSpecs];
|
|
@@ -1409,6 +1450,7 @@ function liveReplacementPreservesListStructure(lineBytes, replacement) {
|
|
|
1409
1450
|
function importSourceVerifier(repoRoot, hard, cache = null, newEventDigest = null) {
|
|
1410
1451
|
return (descriptor, context = {}) => {
|
|
1411
1452
|
if (!validateTodoImportSource(descriptor)) fail('STORE_INCONSISTENT', 'import_source_descriptor_invalid');
|
|
1453
|
+
if (newEventDigest !== null && context.event_digest !== newEventDigest) return true; // b11, as evidenceVerifier
|
|
1412
1454
|
try {
|
|
1413
1455
|
pinnedSourceLine(repoRoot, descriptor, cache);
|
|
1414
1456
|
return true;
|
|
@@ -1576,18 +1618,20 @@ async function readTodoStoreView(options = {}) {
|
|
|
1576
1618
|
}
|
|
1577
1619
|
}
|
|
1578
1620
|
await assertNoCrossPlanImportRecoveryNeeded(repoRoot);
|
|
1579
|
-
const pinnedSourceCache = { commits: new Set(), blobs: new Map() };
|
|
1580
1621
|
const manifest = await readManifest(repoRoot);
|
|
1581
1622
|
const loaded = [];
|
|
1582
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;
|
|
1583
1627
|
const plan = await readArtifact(repoRoot, descriptor.plan_ref, {
|
|
1584
|
-
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan,
|
|
1628
|
+
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, canonical: verifyHistory,
|
|
1585
1629
|
});
|
|
1586
1630
|
if (plan.project_id !== manifest.project_id || plan.plan_key !== descriptor.plan_key
|
|
1587
1631
|
|| plan.plan_version !== descriptor.active_plan_version || plan.topology_digest !== descriptor.topology_digest) {
|
|
1588
1632
|
fail('STORE_INCONSISTENT', 'manifest_plan_binding_mismatch');
|
|
1589
1633
|
}
|
|
1590
|
-
const journal = await readJournal(repoRoot, descriptor.journal_ref);
|
|
1634
|
+
const journal = await readJournal(repoRoot, descriptor.journal_ref, { verify: verifyHistory });
|
|
1591
1635
|
if (journal.events.at(-1).event_digest !== descriptor.journal_head_digest) {
|
|
1592
1636
|
if (!options.recovery || !journal.events.some(({ event_digest: digest }) => (
|
|
1593
1637
|
digest === descriptor.journal_head_digest))) {
|
|
@@ -1602,7 +1646,7 @@ async function readTodoStoreView(options = {}) {
|
|
|
1602
1646
|
const revisionRef = path.posix.join(path.posix.dirname(descriptor.plan_ref), 'revision.json');
|
|
1603
1647
|
const phaseRevision = genesis.schema === 'lattice.todo_event.v4';
|
|
1604
1648
|
revision = await readArtifact(repoRoot, revisionRef, {
|
|
1605
|
-
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes,
|
|
1649
|
+
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, canonical: verifyHistory,
|
|
1606
1650
|
validate: (value) => {
|
|
1607
1651
|
rejectUnsupportedRevisionSchema(value, phaseRevision ? {
|
|
1608
1652
|
family: 'phase_todo_revision', supportedSchemas: PHASE_TODO_REVISION_SCHEMAS,
|
|
@@ -1612,74 +1656,70 @@ async function readTodoStoreView(options = {}) {
|
|
|
1612
1656
|
return phaseRevision ? validatePhaseTodoRevision(value) : validateTodoRevision(value);
|
|
1613
1657
|
},
|
|
1614
1658
|
});
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
}
|
|
1635
|
-
if (genesis.schema === 'lattice.todo_event.v4') {
|
|
1636
|
-
const phaseProjection = revision.phase_migration
|
|
1637
|
-
.filter(({ to_phase_id }) => to_phase_id !== 'removed')
|
|
1638
|
-
.map(({ to_phase_id, state_policy }) => ({ phase_id: to_phase_id, state_policy }))
|
|
1639
|
-
.sort((left, right) => left.phase_id.localeCompare(right.phase_id));
|
|
1640
|
-
const genesisProjection = genesis.phase_state_migration
|
|
1641
|
-
.map(({ phase_id, state_policy }) => ({ phase_id, state_policy }));
|
|
1642
|
-
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) {
|
|
1643
1678
|
fail('STORE_INCONSISTENT', 'revision_genesis_binding_mismatch');
|
|
1644
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
|
+
}
|
|
1645
1691
|
}
|
|
1646
1692
|
}
|
|
1647
1693
|
if (manifest.schema === 'lattice.todo_manifest.v2' && revision === null
|
|
1648
1694
|
&& descriptor.active_revision_digest !== plan.plan_digest) {
|
|
1649
1695
|
fail('STORE_INCONSISTENT', 'manifest_revision_binding_mismatch');
|
|
1650
1696
|
}
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
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`).
|
|
1654
1700
|
const tasks = replay(plan, journal.events, {
|
|
1655
1701
|
now: options.now ? new Date(options.now) : new Date(),
|
|
1656
|
-
verifyEvidence: options.forWrite === true ?
|
|
1657
|
-
verifyImportSource: options.forWrite === true ?
|
|
1702
|
+
verifyEvidence: options.forWrite === true ? structuralEvidenceVerifier(manifest) : undefined,
|
|
1703
|
+
verifyImportSource: options.forWrite === true ? structuralImportSourceVerifier : undefined,
|
|
1658
1704
|
});
|
|
1659
|
-
const expectedSnapshot = snapshotFor(plan, journal.events, structuredClone(tasks));
|
|
1660
|
-
// Read-time evidence failure is annotation, never store rejection.
|
|
1661
|
-
for (const task of tasks) if (task.evidence !== null) {
|
|
1662
|
-
const context = {
|
|
1663
|
-
plan_key: plan.plan_key,
|
|
1664
|
-
task_id: task.task_id,
|
|
1665
|
-
event_digest: null,
|
|
1666
|
-
};
|
|
1667
|
-
const verified = validateTodoImportSource(task.evidence)
|
|
1668
|
-
? verifyImportSource(task.evidence, context) : verifyEvidence(task.evidence, context);
|
|
1669
|
-
if (!verified) task.evidence_unverified = true;
|
|
1670
|
-
}
|
|
1671
1705
|
let snapshot = null;
|
|
1672
1706
|
let snapshotStale = false;
|
|
1707
|
+
let expectedSnapshot = null;
|
|
1673
1708
|
try {
|
|
1674
1709
|
snapshot = await readSnapshotArtifact(repoRoot, descriptor.snapshot_ref);
|
|
1675
|
-
|
|
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
|
+
}
|
|
1676
1716
|
} catch (error) {
|
|
1677
1717
|
if (error instanceof TodoStoreError && error.code === 'SNAPSHOT_INVALID'
|
|
1678
1718
|
&& !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store']
|
|
1679
1719
|
.includes(error.detail.reason)) snapshotStale = true;
|
|
1680
1720
|
else throw error;
|
|
1681
1721
|
}
|
|
1682
|
-
if (
|
|
1722
|
+
if (snapshotStale) expectedSnapshot ??= snapshotFor(plan, journal.events, structuredClone(tasks)); // a stale snapshot is rebuilt, never a refusal
|
|
1683
1723
|
// 導出済みphase状態(ADR 0147)。snapshot artifactの形式(v1/v2)には縛られず、v4/v5・
|
|
1684
1724
|
// phase無しplanのどちらでも同じ形(暗黙のterminal-audit Phase込み)で常に埋める。
|
|
1685
1725
|
// 消費者はここを読み、snapshot.phases(v1には存在しない)を直接読まない。
|
|
@@ -1706,6 +1746,11 @@ async function readTodoStoreView(options = {}) {
|
|
|
1706
1746
|
* unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
|
|
1707
1747
|
*/
|
|
1708
1748
|
async function retainedPlanVersion(repoRoot, base, version) {
|
|
1749
|
+
const compact = await readCompactRecord(repoRoot, base, version).catch(() => null);
|
|
1750
|
+
if (compact !== null) {
|
|
1751
|
+
return { plan: { plan_digest: compact.plan_digest, predecessor_plan_digest: compact.predecessor_plan_digest,
|
|
1752
|
+
topology_digest: compact.topology_digest }, journalRef: `${base}/${version}/journal/active.jsonl` };
|
|
1753
|
+
}
|
|
1709
1754
|
const ref = `${base}/${version}/plan.json`;
|
|
1710
1755
|
const plan = await memoByFileIdentity([path.resolve(repoRoot, ref)], async () => {
|
|
1711
1756
|
const value = await readArtifact(repoRoot, ref, {
|
|
@@ -1717,6 +1762,110 @@ async function retainedPlanVersion(repoRoot, base, version) {
|
|
|
1717
1762
|
return plan === null ? null : { plan, journalRef: `${base}/${version}/journal/active.jsonl` };
|
|
1718
1763
|
}
|
|
1719
1764
|
|
|
1765
|
+
/** b10: a retained version's compact record (see todo-version-compact), or null while it still holds its own files. */
|
|
1766
|
+
async function readCompactRecord(repoRoot, base, version) {
|
|
1767
|
+
const directory = path.resolve(repoRoot, base, version);
|
|
1768
|
+
return memoByFileIdentity([path.join(directory, TODO_VERSION_COMPACT_FILE)], () => readVersionCompact(directory)
|
|
1769
|
+
.catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` })));
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/** b10: one retained version's full `{plan, revision}` (revision null for a genesis version): its own files or its compact record. */
|
|
1773
|
+
export async function readRetainedVersion(repoRoot, base, version, active, cache = new Map()) {
|
|
1774
|
+
if (version === active.plan_version) return { plan: active, revision: null };
|
|
1775
|
+
if (cache.has(version)) return cache.get(version);
|
|
1776
|
+
const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
|
|
1777
|
+
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
|
|
1778
|
+
});
|
|
1779
|
+
let result = null;
|
|
1780
|
+
if (plan !== null) {
|
|
1781
|
+
const revision = await readArtifact(repoRoot, `${base}/${version}/revision.json`, {
|
|
1782
|
+
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, missing: true,
|
|
1783
|
+
validate: (value) => validateTodoRevision(value) || validatePhaseTodoRevision(value),
|
|
1784
|
+
}).catch(() => null);
|
|
1785
|
+
result = { plan, revision };
|
|
1786
|
+
} else {
|
|
1787
|
+
const record = await readCompactRecord(repoRoot, base, version);
|
|
1788
|
+
if (record !== null) {
|
|
1789
|
+
const anchor = await readRetainedVersion(repoRoot, base, record.anchor_plan_version, active, cache);
|
|
1790
|
+
if (anchor === null) fail('STORE_INCONSISTENT', 'compact_anchor_missing', { version });
|
|
1791
|
+
let rebuilt;
|
|
1792
|
+
try { rebuilt = reconstructPlan(record, anchor.plan); } catch { fail('STORE_INCONSISTENT', 'compact_plan_mismatch', { version }); }
|
|
1793
|
+
if (!validateTodoPlan(rebuilt)) fail('STORE_INCONSISTENT', 'compact_plan_invalid', { version });
|
|
1794
|
+
result = { plan: rebuilt, revision: reconstructRevision(record, rebuilt) };
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
cache.set(version, result);
|
|
1798
|
+
return result;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/** b10: keep a retained version's active journal segment as gzip (`active.jsonl.gz`); it is read back byte for byte. */
|
|
1802
|
+
async function packRetainedJournal(plain) {
|
|
1803
|
+
const bytes = await exactFileOrNull(plain);
|
|
1804
|
+
if (bytes === null) return;
|
|
1805
|
+
await atomicWrite(`${plain}.gz`, gzipSync(bytes, { level: 9 }));
|
|
1806
|
+
await rm(plain);
|
|
1807
|
+
await fsyncDirectory(path.dirname(plain));
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
/**
|
|
1811
|
+
* b10: replace the plan.json, revision.json and snapshot.json of the versions a member's active version superseded with one
|
|
1812
|
+
* compact.json each (reverse patch to its successor; the journal segment is gzip-packed). `hook` compacts only the direct predecessor (after every successor write);
|
|
1813
|
+
* `sweep` walks the whole predecessor chain, also finishing a half-done compaction. Lock held by the caller. Returns the versions
|
|
1814
|
+
* compacted and, when the walk could not continue, why. History stays: the three digests, the revision and the exact plan rebuild.
|
|
1815
|
+
*/
|
|
1816
|
+
async function compactSupersededVersions(repoRoot, member, { sweep = false, limit = Infinity } = {}) {
|
|
1817
|
+
const base = `${STORE_ROOT_REF}/plans/${member.plan.plan_key}`;
|
|
1818
|
+
const compacted = [];
|
|
1819
|
+
let anchor = member.plan;
|
|
1820
|
+
let version = member.revision?.predecessor?.plan_version ?? null;
|
|
1821
|
+
while (version !== null) {
|
|
1822
|
+
const directory = path.resolve(repoRoot, base, version);
|
|
1823
|
+
const originals = ['plan.json', 'revision.json', 'snapshot.json'].map((name) => path.join(directory, name));
|
|
1824
|
+
const removeOriginals = async () => {
|
|
1825
|
+
for (const file of originals) await rm(file, { force: true });
|
|
1826
|
+
await packRetainedJournal(path.join(directory, 'journal', 'active.jsonl'));
|
|
1827
|
+
await fsyncDirectory(directory);
|
|
1828
|
+
};
|
|
1829
|
+
const record = await readCompactRecord(repoRoot, base, version);
|
|
1830
|
+
if (record !== null) {
|
|
1831
|
+
if (await exactFileOrNull(originals[0]) !== null) await removeOriginals(); // a compaction cut short after compact.json.gz
|
|
1832
|
+
else if (!sweep) break;
|
|
1833
|
+
try { anchor = reconstructPlan(record, anchor); } catch { return { compacted, stopped: 'compact_anchor_mismatch', version }; }
|
|
1834
|
+
version = record.predecessor_plan_version;
|
|
1835
|
+
} else {
|
|
1836
|
+
const retained = await readRetainedVersion(repoRoot, base, version, member.plan).catch(() => null);
|
|
1837
|
+
if (retained === null) return { compacted, stopped: 'version_unreadable', version };
|
|
1838
|
+
const built = buildVersionCompact({ retained: retained.plan, anchor, revision: retained.revision });
|
|
1839
|
+
if (built === null) return { compacted, stopped: 'round_trip_mismatch', version };
|
|
1840
|
+
await atomicWrite(path.join(directory, TODO_VERSION_COMPACT_FILE), packVersionCompact(built));
|
|
1841
|
+
await removeOriginals();
|
|
1842
|
+
compacted.push(version);
|
|
1843
|
+
anchor = retained.plan;
|
|
1844
|
+
version = built.predecessor_plan_version;
|
|
1845
|
+
}
|
|
1846
|
+
if (!sweep) break;
|
|
1847
|
+
if (compacted.length >= limit && version !== null) return { compacted, stopped: 'limit', version };
|
|
1848
|
+
}
|
|
1849
|
+
return { compacted, stopped: null, version: null };
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
/** b10: `lattice todo compact`: compact the retained versions of every member (or `planKey`), at most `limit` per call. */
|
|
1853
|
+
export async function compactTodoVersions(options = {}) {
|
|
1854
|
+
requireWriter(options.writer, 'g5-authoring');
|
|
1855
|
+
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1856
|
+
return withLock(repoRoot, async () => {
|
|
1857
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
1858
|
+
const plans = [];
|
|
1859
|
+
for (const member of store.members) {
|
|
1860
|
+
if (options.planKey !== undefined && member.plan.plan_key !== options.planKey) continue;
|
|
1861
|
+
const result = await compactSupersededVersions(repoRoot, member, { sweep: true, limit: options.limit });
|
|
1862
|
+
plans.push({ plan_key: member.plan.plan_key, compacted: result.compacted.length, stopped: result.stopped,
|
|
1863
|
+
next_version: result.version });
|
|
1864
|
+
}
|
|
1865
|
+
return { schema: 'lattice.todo_compact_result.v1', project_id: store.project_id, plans };
|
|
1866
|
+
}, { lockCapability: options[STORE_LOCK_HELD] });
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1720
1869
|
async function retainedVersionNames(repoRoot, base, activePlan) {
|
|
1721
1870
|
let names = [];
|
|
1722
1871
|
try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
|
|
@@ -2264,7 +2413,10 @@ async function withLock(repoRoot, callback, {
|
|
|
2264
2413
|
const result = await callback(assertHeld);
|
|
2265
2414
|
// The successor is already published: a failed repair leaves findings for the next locked write.
|
|
2266
2415
|
try {
|
|
2267
|
-
const
|
|
2416
|
+
const view = await readTodoStoreView({ repoRoot });
|
|
2417
|
+
// b10: the version this write superseded keeps only its difference; a failure leaves the full files, retried next write.
|
|
2418
|
+
for (const member of view.members) await compactSupersededVersions(repoRoot, member).catch(() => {});
|
|
2419
|
+
const repairs = await repairCrossPlanBindings(repoRoot, view,
|
|
2268
2420
|
{ assertHeld, actor: repairAfter.actor, recordedAt: repairAfter.recordedAt ?? new Date().toISOString() });
|
|
2269
2421
|
// Results stay digest-bound; the caller learns the repairs through its own callback.
|
|
2270
2422
|
if (repairs.length > 0 && typeof repairAfter.onRepairs === 'function') await repairAfter.onRepairs(repairs);
|
|
@@ -2535,13 +2687,11 @@ export async function appendTodoEvent(options = {}) {
|
|
|
2535
2687
|
fail(validation.code, reason, detail);
|
|
2536
2688
|
}
|
|
2537
2689
|
if (validation?.ok !== true) throw new TypeError('prospective validator must return an ok result');
|
|
2538
|
-
|
|
2539
|
-
prefetchVerificationObjects(store.manifest, repoRoot,
|
|
2540
|
-
[...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).
|
|
2541
2691
|
replay(member.plan, [...member.journal.events, event], {
|
|
2542
2692
|
now: options.now ? new Date(options.now) : new Date(),
|
|
2543
|
-
verifyEvidence:
|
|
2544
|
-
verifyImportSource:
|
|
2693
|
+
verifyEvidence: structuralEvidenceVerifier(store.manifest),
|
|
2694
|
+
verifyImportSource: structuralImportSourceVerifier,
|
|
2545
2695
|
});
|
|
2546
2696
|
if (options.materializedEvidence !== null && options.materializedEvidence !== undefined) {
|
|
2547
2697
|
const asset = options.materializedEvidence;
|
|
@@ -2575,8 +2725,8 @@ export async function appendTodoEvent(options = {}) {
|
|
|
2575
2725
|
await protocolStage(options, 'event_journal_published');
|
|
2576
2726
|
const tasks = replay(member.plan, [...member.journal.events, event], {
|
|
2577
2727
|
now: options.now ? new Date(options.now) : new Date(),
|
|
2578
|
-
verifyEvidence:
|
|
2579
|
-
verifyImportSource:
|
|
2728
|
+
verifyEvidence: structuralEvidenceVerifier(store.manifest),
|
|
2729
|
+
verifyImportSource: structuralImportSourceVerifier,
|
|
2580
2730
|
});
|
|
2581
2731
|
const snapshot = snapshotFor(member.plan, [...member.journal.events, event], tasks);
|
|
2582
2732
|
await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(snapshot));
|
|
@@ -2764,10 +2914,9 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
|
|
|
2764
2914
|
))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
|
|
2765
2915
|
const predecessorBinding = source.revision?.predecessor;
|
|
2766
2916
|
if (!predecessorBinding) fail('DEPENDENCY_INVALID', 'dependency_rebind_predecessor_missing');
|
|
2767
|
-
const predecessor = await
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
});
|
|
2917
|
+
const predecessor = (await readRetainedVersion(repoRoot, `${STORE_ROOT_REF}/plans/${source.plan.plan_key}`,
|
|
2918
|
+
predecessorBinding.plan_version, source.plan))?.plan;
|
|
2919
|
+
if (!predecessor) fail('STORE_INCONSISTENT', 'artifact_missing');
|
|
2771
2920
|
if (predecessor.project_id !== source.plan.project_id || predecessor.plan_key !== source.plan.plan_key
|
|
2772
2921
|
|| predecessor.plan_version !== predecessorBinding.plan_version
|
|
2773
2922
|
|| predecessor.plan_digest !== predecessorBinding.plan_digest) {
|
|
@@ -4949,39 +5098,18 @@ async function cleanupPhaseV3Staging(transaction, staged) {
|
|
|
4949
5098
|
|
|
4950
5099
|
export async function predecessorSourceInventory(repoRoot, previous) {
|
|
4951
5100
|
if (previous.revision?.source_inventory !== undefined) return previous.revision.source_inventory;
|
|
4952
|
-
|
|
4953
|
-
const
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
}
|
|
4965
|
-
const visited = new Set();
|
|
4966
|
-
let digest = previous.plan.predecessor_plan_digest;
|
|
4967
|
-
while (digest !== null && !visited.has(digest) && visited.size < 512) {
|
|
4968
|
-
visited.add(digest);
|
|
4969
|
-
const candidate = plansByDigest.get(digest);
|
|
4970
|
-
if (candidate === undefined) break;
|
|
4971
|
-
const revisionBytes = await exactFileOrNull(path.join(candidate.directory, 'revision.json'));
|
|
4972
|
-
if (revisionBytes !== null) {
|
|
4973
|
-
let revision;
|
|
4974
|
-
try { revision = JSON.parse(decodeUtf8(revisionBytes,
|
|
4975
|
-
'STORE_INCONSISTENT', 'revision_invalid')); } catch { revision = null; }
|
|
4976
|
-
if (revision !== null && revisionBytes.equals(canonicalLine(revision))
|
|
4977
|
-
&& (validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
|
|
4978
|
-
&& revision.project_id === candidate.plan.project_id
|
|
4979
|
-
&& revision.plan_key === candidate.plan.plan_key
|
|
4980
|
-
&& canonicalizeTodoArtifact(revision.desired_plan)
|
|
4981
|
-
=== canonicalizeTodoArtifact(candidate.plan)
|
|
4982
|
-
&& revision.source_inventory !== undefined) return revision.source_inventory;
|
|
4983
|
-
}
|
|
4984
|
-
digest = candidate.plan.predecessor_plan_digest;
|
|
5101
|
+
// b10: walk the revision bindings (no scan of every retained version); a compacted version is rebuilt exactly.
|
|
5102
|
+
const base = `${STORE_ROOT_REF}/plans/${previous.plan.plan_key}`;
|
|
5103
|
+
const cache = new Map(); const visited = new Set();
|
|
5104
|
+
for (let version = previous.revision?.predecessor?.plan_version ?? null; version !== null && !visited.has(version);) {
|
|
5105
|
+
visited.add(version);
|
|
5106
|
+
const candidate = await readRetainedVersion(repoRoot, base, version, previous.plan, cache).catch(() => null);
|
|
5107
|
+
const { plan, revision } = candidate ?? {};
|
|
5108
|
+
if (!plan || plan.plan_key !== previous.plan.plan_key) break;
|
|
5109
|
+
if (revision && revision.project_id === plan.project_id && revision.plan_key === plan.plan_key
|
|
5110
|
+
&& canonicalizeTodoArtifact(revision.desired_plan) === canonicalizeTodoArtifact(plan)
|
|
5111
|
+
&& revision.source_inventory !== undefined) return revision.source_inventory;
|
|
5112
|
+
version = revision?.predecessor?.plan_version ?? null;
|
|
4985
5113
|
}
|
|
4986
5114
|
return { active: [], excluded_tombstones: [] };
|
|
4987
5115
|
}
|
|
@@ -5158,8 +5286,8 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
|
|
|
5158
5286
|
await protocolStage(options, 'phase_v3_marker_durable');
|
|
5159
5287
|
const tasks = replay(revision.desired_plan, [genesis], {
|
|
5160
5288
|
now: options.now ? new Date(options.now) : new Date(),
|
|
5161
|
-
verifyEvidence:
|
|
5162
|
-
verifyImportSource:
|
|
5289
|
+
verifyEvidence: structuralEvidenceVerifier(store.manifest),
|
|
5290
|
+
verifyImportSource: structuralImportSourceVerifier,
|
|
5163
5291
|
});
|
|
5164
5292
|
const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
|
|
5165
5293
|
for (const [stage, ref, bytes] of [
|
|
@@ -5329,8 +5457,8 @@ export async function applyPhaseTodoRevision(options = {}) {
|
|
|
5329
5457
|
await protocolStage(options, 'phase_revision_marker_durable');
|
|
5330
5458
|
const tasks = replay(revision.desired_plan, [genesis], {
|
|
5331
5459
|
now: options.now ? new Date(options.now) : new Date(),
|
|
5332
|
-
verifyEvidence:
|
|
5333
|
-
verifyImportSource:
|
|
5460
|
+
verifyEvidence: structuralEvidenceVerifier(store.manifest),
|
|
5461
|
+
verifyImportSource: structuralImportSourceVerifier,
|
|
5334
5462
|
});
|
|
5335
5463
|
const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
|
|
5336
5464
|
const artifacts = [
|
|
@@ -5487,8 +5615,8 @@ export async function applyTodoRevision(options = {}) {
|
|
|
5487
5615
|
}
|
|
5488
5616
|
await protocolStage(options, 'revision_marker_durable');
|
|
5489
5617
|
|
|
5490
|
-
const verifyEvidence =
|
|
5491
|
-
const verifyImportSource =
|
|
5618
|
+
const verifyEvidence = structuralEvidenceVerifier(store.manifest);
|
|
5619
|
+
const verifyImportSource = structuralImportSourceVerifier;
|
|
5492
5620
|
const tasks = replay(revision.desired_plan, [genesis], {
|
|
5493
5621
|
now: options.now ? new Date(options.now) : new Date(), verifyEvidence, verifyImportSource,
|
|
5494
5622
|
});
|
|
@@ -5769,8 +5897,8 @@ export async function applyTodoRevisionSet(options = {}) {
|
|
|
5769
5897
|
}
|
|
5770
5898
|
await protocolStage(options, 'revision_set_marker_durable');
|
|
5771
5899
|
|
|
5772
|
-
const verifyEvidence =
|
|
5773
|
-
const verifyImportSource =
|
|
5900
|
+
const verifyEvidence = structuralEvidenceVerifier(store.manifest);
|
|
5901
|
+
const verifyImportSource = structuralImportSourceVerifier;
|
|
5774
5902
|
for (const entry of prepared) {
|
|
5775
5903
|
const { revision, genesis } = entry;
|
|
5776
5904
|
const tasks = replay(revision.desired_plan, [genesis], {
|