@quolu/lattice 0.105.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 CHANGED
@@ -323,7 +323,7 @@ required evidenceを束縛した`todo phase accept`で重監査の判断を記
323
323
 
324
324
  **監査の既定は「有り」です。** phaseを持たないplanも終端に重監査が要ります(予約Phase
325
325
  `terminal-audit`を暗黙に1つ持ちます)。全taskがdoneになった状態は「完走」ではなく`gate_ready`=
326
- **監査待ち**であり、工程図のlive scopeはそのplanのToDoを畳みません——完走扱いで図から消えることが
326
+ **監査前**であり、工程図のlive scopeはそのplanのToDoを畳みません——完走扱いで図から消えることが
327
327
  「閉じた」の可視表現なので、監査の記録なしにそこへ行かせません。作成時に拒否はせず、
328
328
  `todo migrate`/`plan create`の結果と最後のdoneのadvisoryで`terminal_audit_required`を通知します。
329
329
  **終端監査はToDoのdispatch可否へ影響しません**(Phaseは重監査の順序だけを制御し、開始順はToDo DAGが決めます)。
@@ -341,14 +341,14 @@ lattice todo phase accept --plan <key> --phase terminal-audit --evidence <監査
341
341
 
342
342
  **過去の工程は監査できません。** 監査対象のコードが既に変化しているためです。そこで
343
343
  「監査なしで閉じた」という状態を別に持ちます——`accepted`(監査を通った)へは絶対に化けず、
344
- 記録は永久に区別できます。工程図では畳まれるので監査待ちの札は外れます。
344
+ 記録は永久に区別できます。工程図では畳まれるので監査前の札は外れます。
345
345
 
346
346
  ```bash
347
347
  lattice todo phase close-unaudited --plan <key> --phase terminal-audit --reason <text>
348
348
  lattice todo phase baseline --reason <text> --except <監査したいplan_key> # 一括
349
349
  ```
350
350
 
351
- 一括の入口は、現在監査待ちで一度も監査に触れていないPhaseだけを対象にします。**自動では
351
+ 一括の入口は、現在監査前で一度も監査に触れていないPhaseだけを対象にします。**自動では
352
352
  実行しません**——どれを監査し、どれを歴史として畳むかは人が決め、Latticeは宣言を受け取って
353
353
  記録するだけです。`--except`は「最近の作業でコードも生きているので本当に監査したい」planを
354
354
  残すための口です。規約は
@@ -376,7 +376,7 @@ dashboardはmanifestのfile identityが変わらない間のstable store readを
376
376
  巨大工程図のrender中にhealth応答が遅れても、生存中dashboardを新daemonで置き換えず
377
377
  `DASHBOARD_DAEMON_UNRESPONSIVE`としてtyped拒否します。
378
378
  最近のsession activityが1週間を過ぎても、Lattice storeの`active_set`が非空なproject、
379
- または監査待ちPhaseがあるprojectは一覧へ残ります。
379
+ または監査前Phaseがあるprojectは一覧へ残ります。
380
380
  長時間の外部処理中にCLI呼出しが途切れても進行中projectを休眠扱いしません。
381
381
  LANや外部reverse proxyから閲覧するoptional bridgeは既定で無効です。明示したIPにだけbindする初回設定、
382
382
  再設定、停止方法は[bridge setup](docs/bridge-setup.md)を参照してください。reverse proxy hostへsshで
@@ -205,8 +205,8 @@ hubへ繋いでいる端末では、`runtime.last_heartbeat`が最後にhubへ
205
205
  | `null` | hub未設定、またはまだ1回も送っていない | — |
206
206
 
207
207
  名乗る集合はdaemonが実際に配信している集合そのもの(ADR 0165)。配信集合は
208
- `last_seen_at`が1週間以内、またはactive run、または監査待ちPhaseがあるprojectである。
209
- 人がCLIを叩かなくても、その条件を満たす限り公開面に残る。1週間を超え、runも監査待ちも
208
+ `last_seen_at`が1週間以内、またはactive run、または監査前Phaseがあるprojectである。
209
+ 人がCLIを叩かなくても、その条件を満たす限り公開面に残る。1週間を超え、runも監査前も
210
210
  無いprojectは配信から外れる。heartbeatの90秒TTLは、配信そのものが止まった時
211
211
  (daemon停止)にofflineへ落とすためのもので、鮮度窓ではない。
212
212
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.105.0",
3
+ "version": "0.106.0",
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",
@@ -319,7 +319,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
319
319
  // 監査/構造finalization待ちが在る限り「残作業なし」と答えない。優先順位は
320
320
  // active_run > next_ready > structure finalization > audit_pending > なし。
321
321
  // ready frontierが在る間はADR 0063の並列開始コマンドが勝つ
322
- // ——ここを監査で上書きするとdispatchが再直列化する。監査待ちはtodo statusの
322
+ // ——ここを監査で上書きするとdispatchが再直列化する。監査前はtodo statusの
323
323
  // audit_pending欄に常在するので、順位を下げても消えない。
324
324
  // gate_ready(全taskが終わり監査も未着手)は軽い出口close-unauditedを1行で示す(a22)。
325
325
  // 監査を始めた後(reviewing/rejected)は読み取り専用の`todo phase status`が両分岐を示す。
@@ -1,19 +1,19 @@
1
1
  /**
2
- * 監査待ちPhaseの定義(ADR 0147/0148)。
2
+ * 監査前Phaseの定義(ADR 0147/0148)。
3
3
  *
4
- * 「監査待ち」は同じ3状態の集合として、gantt scopeのfold判定・dashboardの表示判定へ
4
+ * 「監査前」は同じ3状態の集合として、gantt scopeのfold判定・dashboardの表示判定へ
5
5
  * 別々に書かれていた。status面にも同じ判定が要るので、定義をここへ一本化する——
6
6
  * 集合が三重になれば、片方だけ更新された時に「図には出るがstatusには出ない」形の
7
7
  * ずれが生まれる。ADR 0147が塞ごうとした事故と外形が同じになる。
8
8
  *
9
- * このmoduleが持つのは監査待ちの**定義**だけである。各消費者の方針
9
+ * このmoduleが持つのは監査前の**定義**だけである。各消費者の方針
10
10
  * (ganttのfold対象をどのplan世代へ限るか等)はここへ持ち込まない。
11
11
  */
12
12
 
13
13
  /**
14
14
  * 監査の判断がまだ着いていないPhase状態。
15
15
  *
16
- * - `gate_ready`: 所属ToDoが全てdoneで、監査待ち。
16
+ * - `gate_ready`: 所属ToDoが全てdoneで、監査前。
17
17
  * - `reviewing`: 監査中(reviewは出たが、acceptもrejectも出ていない)。
18
18
  * - `rejected`: 監査が通らず、要フォロー。
19
19
  *
@@ -23,19 +23,19 @@
23
23
  */
24
24
  export const AUDIT_PENDING_PHASE_STATUSES = new Set(['gate_ready', 'reviewing', 'rejected']);
25
25
 
26
- /** そのPhase状態が監査待ちか。null/undefined/未知の値はfalse。 */
26
+ /** そのPhase状態が監査前か。null/undefined/未知の値はfalse。 */
27
27
  export function isAuditPendingPhaseStatus(status) {
28
28
  return AUDIT_PENDING_PHASE_STATUSES.has(status ?? null);
29
29
  }
30
30
 
31
31
  /**
32
- * その監査待ち状態から実際に打てるコマンド。
32
+ * その監査前状態から実際に打てるコマンド。
33
33
  *
34
34
  * `src/todo-store.mjs`の遷移guardと一致させる——gate_readyからいきなりacceptはできず
35
35
  * (`phase_gate_not_ready`)、reviewing以外からのrejectもできない(`phase_reject_binding_invalid`)。
36
36
  * 実行すれば必ず弾かれる遷移を「次の一歩」として案内しない。
37
37
  *
38
- * 監査待ちでない状態を渡すのは呼び出し側の誤りなので、空配列へ丸めずに投げる。
38
+ * 監査前でない状態を渡すのは呼び出し側の誤りなので、空配列へ丸めずに投げる。
39
39
  * 呼ぶ前に`isAuditPendingPhaseStatus`で絞ること。
40
40
  *
41
41
  * `slotCount`は必須evidence slotの数。1つなら`--evidence`で足り、複数なら`--input`が要る。
@@ -73,7 +73,7 @@ export function phaseAuditRequired(member, gatePolicy) {
73
73
  }
74
74
 
75
75
  /**
76
- * store read model(`lattice.todo_store_read.v1`)の中の監査待ちPhaseを列挙する。
76
+ * store read model(`lattice.todo_store_read.v1`)の中の監査前Phaseを列挙する。
77
77
  *
78
78
  * `member.phases`はstoreが常に埋める導出ビューで、phase無しplanの暗黙terminal-audit Phaseも
79
79
  * 同じ形で入っている(ADR 0147)。planの世代で分岐しないのはそのためである。
package/src/todo-cli.mjs CHANGED
@@ -71,6 +71,7 @@ import {
71
71
  createTodoStoreWriter,
72
72
  TodoStoreError,
73
73
  isPhaselessTodoPlanSchema,
74
+ findUnverifiedTodoEvidence,
74
75
  isTodoEvidenceUncommitted,
75
76
  isUninitializedTodoStore,
76
77
  projectTodoCrossPlanDependencies,
@@ -2342,7 +2343,7 @@ async function phaseStatus({ repoRoot, planKey }) {
2342
2343
  // 無いのでsnapshot.phasesは直接読まない)。ここでPHASE_UNAVAILABLEへ拒否せず、その暗黙Phase
2343
2344
  // をそのまま返す——`implicit`で機械可読に「宣言されたPhaseではない」ことを示す。
2344
2345
  const implicit = isPhaselessTodoPlanSchema(member.plan.schema);
2345
- // ADR 0148裁定8: gate_readyのPhaseには、なぜ監査待ちになったかと次の一歩をここでも言う
2346
+ // ADR 0148裁定8: gate_readyのPhaseには、なぜ監査前になったかと次の一歩をここでも言う
2346
2347
  // (todo doneのadvisoryと同じ文言)。implicit(暗黙のterminal-audit Phase)に限らず、
2347
2348
  // v4/v5の実Phaseがgate_readyになった場合も同じ理由で同じ案内が要る。
2348
2349
  const phases = member.phases.map((phase) => ({
@@ -2539,7 +2540,7 @@ async function migrate({ repoRoot, inputRef }) {
2539
2540
  next_action: `lattice todo revise-phase --plan ${imported.plan.plan_key} --input <phase-revision.json>`,
2540
2541
  } : null,
2541
2542
  // ob03: 起票直後のplanは必ず調整方式が未宣言である。ここで案内しないと、選ぶ機会が
2542
- // 「誰も呼ぶ動機の無いdrilldown」にしか無くなる——前campaignの監査待ちと同じ形になる。
2543
+ // 「誰も呼ぶ動機の無いdrilldown」にしか無くなる——前campaignの監査前と同じ形になる。
2543
2544
  coordination_guidance: imported.connectionOnly === true ? null : {
2544
2545
  mode: null,
2545
2546
  modes: [...TODO_COORDINATION_MODES],
@@ -5284,7 +5285,8 @@ async function evidenceAnchor({ repoRoot }) {
5284
5285
  }
5285
5286
 
5286
5287
  async function verify({ repoRoot, requestedPlanKey }) {
5287
- const store = await readTodoStore({ repoRoot });
5288
+ // k4: the full history checks (hash chain, canonical bytes, whole-snapshot comparison) run only here, on request.
5289
+ const store = await readTodoStore({ repoRoot, verifyHistory: true });
5288
5290
  const members = selectMembers(store, requestedPlanKey);
5289
5291
  // note chainはlifecycle storeと独立だが、verifyは両方を検査する。破損を空扱いしない。
5290
5292
  for (const member of members) {
@@ -5295,8 +5297,8 @@ async function verify({ repoRoot, requestedPlanKey }) {
5295
5297
  for (const member of members) {
5296
5298
  const planKey = member.descriptor.plan_key;
5297
5299
  // a12: evidence waiting for a commit is an item; missing or changed evidence still refuses.
5298
- const pending = member.tasks.filter((task) => task.evidence_unverified
5299
- && isTodoEvidenceUncommitted({ repoRoot, store, evidence: task.evidence }));
5300
+ const unverifiedTasks = findUnverifiedTodoEvidence({ repoRoot, store, member });
5301
+ const pending = unverifiedTasks.filter((task) => isTodoEvidenceUncommitted({ repoRoot, store, evidence: task.evidence }));
5300
5302
  for (const { task_id: taskId, evidence } of pending) {
5301
5303
  uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
5302
5304
  }
@@ -5304,7 +5306,7 @@ async function verify({ repoRoot, requestedPlanKey }) {
5304
5306
  if (decisionEvidenceState(repoRoot, store, evidence) !== 'uncommitted') continue;
5305
5307
  uncommittedEvidence.push({ plan_key: planKey, phase_id: phaseId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
5306
5308
  }
5307
- const unverified = member.tasks.find((task) => task.evidence_unverified && !pending.includes(task));
5309
+ const unverified = unverifiedTasks.find((task) => !pending.includes(task));
5308
5310
  if (unverified !== undefined) {
5309
5311
  throw new TodoStoreError('STORE_INCONSISTENT', 'evidence_unverified', 'evidence_unverified', {
5310
5312
  plan_key: member.descriptor.plan_key,
@@ -246,6 +246,9 @@ export function validateTodoNoteContext(value) {
246
246
  }
247
247
 
248
248
  const nullableDigest = (value) => value === null || isTodoDigest(value);
249
+ /** k4: a done recorded as plain text. The task's `evidence` is `{message}` (carried across revisions like any evidence). */
250
+ export const isTodoDoneMessage = (value) => exactRecord(value, ['message']) && typeof value.message === 'string'
251
+ && value.message.trim().length > 0 && Buffer.byteLength(value.message) <= TODO_LIMITS.noteBodyBytes;
249
252
  const nullableText = (value) => value === null || (typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 16_384);
250
253
  /** 設計メモの拒否理由を、本文をerrorへ複製せずAIが訂正できる形で返す。 */
251
254
  export function explainTodoDesignMemo(value) {
@@ -632,6 +635,14 @@ function validPayload(event) {
632
635
  && ['pending', 'blocked', 'in-progress', 'done'].includes(payload.prior_status)))
633
636
  && nullableText(payload.reason) && payload.reason !== null;
634
637
  }
638
+ if (event.kind === 'done' && payload?.done_mode === 'authored' && typeof payload.message === 'string') {
639
+ // k4: a new done record is plain text in the event (no blob, descriptor or digest). Legacy `evidence` records stay valid below.
640
+ return (exactRecord(payload, ['done_mode', 'imported', 'message'])
641
+ || exactRecord(payload, ['done_mode', 'imported', 'message', 'test_result']))
642
+ && payload.imported === false && payload.message.trim().length > 0
643
+ && Buffer.byteLength(payload.message) <= TODO_LIMITS.noteBodyBytes
644
+ && (payload.test_result === undefined || isTodoTestResult(payload.test_result));
645
+ }
635
646
  if (event.kind === 'done' && payload?.done_mode === 'authored') {
636
647
  return (exactRecord(payload, ['done_mode', 'imported', 'evidence'])
637
648
  || exactRecord(payload, ['done_mode', 'imported', 'evidence', 'test_result']))
@@ -656,6 +667,18 @@ function validPayload(event) {
656
667
  && nullableText(payload.override_reason);
657
668
  if (event.kind === 'phase_review') return exactRecord(payload, ['reason'])
658
669
  && nullableText(payload.reason) && payload.reason !== null;
670
+ // k4: a new accept/reject carries no evidence descriptor or slots; an optional plain-text `message` (same limits as done's).
671
+ const planMessage = (value) => typeof value === 'string' && value.trim().length > 0
672
+ && Buffer.byteLength(value) <= TODO_LIMITS.noteBodyBytes;
673
+ if (event.kind === 'phase_accept' && (exactRecord(payload, ['review_event_digest'])
674
+ || exactRecord(payload, ['review_event_digest', 'message']))) {
675
+ return isTodoDigest(payload.review_event_digest) && (payload.message === undefined || planMessage(payload.message));
676
+ }
677
+ if (event.kind === 'phase_reject' && (exactRecord(payload, ['review_event_digest', 'reason'])
678
+ || exactRecord(payload, ['review_event_digest', 'reason', 'message']))) {
679
+ return isTodoDigest(payload.review_event_digest) && nullableText(payload.reason) && payload.reason !== null
680
+ && (payload.message === undefined || planMessage(payload.message));
681
+ }
659
682
  if (event.kind === 'phase_accept') return exactRecord(payload, [
660
683
  'review_event_digest', 'decision_evidence', 'evidence_slots',
661
684
  ]) && isTodoDigest(payload.review_event_digest) && evidence(payload.decision_evidence)
@@ -712,7 +735,7 @@ function validCarriedState(value) {
712
735
  // imported doneの現在証拠はimport sourceまたは通常evidence descriptorのどちらも有効。
713
736
  && (value.imported
714
737
  ? validateTodoImportSource(value.evidence) || evidence(value.evidence)
715
- : evidence(value.evidence));
738
+ : evidence(value.evidence) || isTodoDoneMessage(value.evidence));
716
739
  }
717
740
 
718
741
  function validStateMigration(value) {
@@ -848,7 +871,8 @@ export function validateTodoSnapshot(value) {
848
871
  ]) && isTodoIdentifier(entry.task_id) && ['pending', 'in-progress', 'blocked', 'retired', 'done'].includes(entry.status)
849
872
  && (entry.started_at === null || isStrictTodoTimestamp(entry.started_at))
850
873
  && (entry.done_at === null || isStrictTodoTimestamp(entry.done_at)) && nullableText(entry.blocked_reason)
851
- && (entry.evidence === null || evidence(entry.evidence) || validateTodoImportSource(entry.evidence))
874
+ && (entry.evidence === null || evidence(entry.evidence) || validateTodoImportSource(entry.evidence)
875
+ || isTodoDoneMessage(entry.evidence))
852
876
  && typeof entry.evidence_unverified === 'boolean' && typeof entry.imported === 'boolean'
853
877
  && (!resultAware || (entry.status === 'done'
854
878
  ? entry.test_result === null || isTodoTestResult(entry.test_result)
@@ -20,7 +20,7 @@ body{display:grid;grid-template-rows:minmax(0,1fr);height:100vh;margin:0;backgro
20
20
  .gantt-pane{display:grid;grid-template-rows:auto auto minmax(0,1fr);min-width:0;min-height:0;overflow:hidden;background:var(--surface-1)}
21
21
  .pane-divider{width:8px;cursor:col-resize;background:rgba(217,216,212,.5);touch-action:none}
22
22
  .diagram-toolbar{z-index:3;display:flex;align-items:center;gap:8px;padding:8px 16px;border-bottom:1px solid var(--border);background:var(--surface-2);color:var(--text-secondary)}
23
- /* 監査待ちの札が入って以降、ツールバーは幅の奪い合いになる。操作系は縮ませない——
23
+ /* 監査前の札が入って以降、ツールバーは幅の奪い合いになる。操作系は縮ませない——
24
24
  縮むと「等倍」「全体表示」が2行に折れて、押せるが読みにくい形になる。削るのは札の側で、
25
25
  そちらはellipsisと件数の下限を持っている。 */
26
26
  .diagram-toolbar button{flex:0 0 auto;white-space:nowrap;min-height:32px;padding:0 8px;border:1px solid var(--border);border-radius:4px;background:var(--surface-2);color:var(--text-primary);font:500 12px/1.6 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif}
@@ -21,10 +21,10 @@ function projectDisplayName(readModel, metadata) {
21
21
  }
22
22
 
23
23
  /**
24
- * 監査待ちPhaseをヘッダへ出す(ADR 0147/0148)。
24
+ * 監査前Phaseをヘッダへ出す(ADR 0147/0148)。
25
25
  *
26
26
  * CLIのstdoutは1行のversioned JSONというADR 0049の公理があり、人が読むテキスト面が無い。
27
- * 人が実際に見るのはこの図とdashboard(同じHTMLを配信する)なので、監査待ちはここへ出す。
27
+ * 人が実際に見るのはこの図とdashboard(同じHTMLを配信する)なので、監査前はここへ出す。
28
28
  * 全taskがdoneでも監査が済んでいなければ工程は閉じていない——図が「全部緑」に見えるのに
29
29
  * ヘッダが無言なら、読み手は完了したと読む。
30
30
  *
@@ -33,8 +33,8 @@ function projectDisplayName(readModel, metadata) {
33
33
  * **出す文字列を有界にする。** ツールバーはpane幅で制約されていないので、長い札は縮まずに
34
34
  * 行を押し広げ、ズーム操作を画面外へ追い出す(2026-08-08に実測)。CSSの`text-overflow`は
35
35
  * ここでは発動しないため、頼れない。全plan名を並べる代わりに先頭1件+残件数だけを出し、
36
- * 全文は`title`に残す。件数(`監査待ち N件`)は常に見える——省略するのは内訳であって、
37
- * 監査待ちの存在そのものではない。
36
+ * 全文は`title`に残す。件数(`監査前 N件`)は常に見える——省略するのは内訳であって、
37
+ * 監査前の存在そのものではない。
38
38
  */
39
39
  function renderAuditPendingChip(readModel) {
40
40
  const pending = auditPendingPhasesOf(readModel);
@@ -42,8 +42,8 @@ function renderAuditPendingChip(readModel) {
42
42
  const label = ({ plan_key: planKey, phase_id: phaseId, status }) => `${planKey}/${phaseId} (${status})`;
43
43
  // 残件数は書かない——先頭の`N件`が既に全体を数えており、「ほかM件」はその引き算でしかない。
44
44
  // 幅は有限なので、同じことを二度言う分だけplan名が削れる。
45
- const text = `監査待ち ${pending.length}件: ${label(pending[0])}`;
46
- const full = `監査待ち ${pending.length}件: ${pending.map(label).join(' · ')}`;
45
+ const text = `監査前 ${pending.length}件: ${label(pending[0])}`;
46
+ const full = `監査前 ${pending.length}件: ${pending.map(label).join(' · ')}`;
47
47
  return `<span class="audit-pending-chip" title="${escapeHtmlAttribute(full)}">${escapeHtmlText(text)}</span>`;
48
48
  }
49
49
 
@@ -43,7 +43,7 @@ function compareText(left, right) {
43
43
  /**
44
44
  * ADR 0147: phase無しplan(v1/v2/v3)は終端の暗黙Phase(terminal-audit)がacceptedになるまで
45
45
  * 「閉じた」ことにならない。全taskがdoneでも監査未了なら、そのplanのToDoは生きた作業と同じ
46
- * 扱い(distance 0)にして畳ませない——畳んでしまうと監査待ちであることが図から消え、
46
+ * 扱い(distance 0)にして畳ませない——畳んでしまうと監査前であることが図から消え、
47
47
  * ADR 0147が塞ごうとした「一度も重監査を通らず完走した」事故と外形が同じになる。
48
48
  *
49
49
  * v4/v5(phaseを宣言したplan)はこの判定の対象外にする——既存のPhase gateが重監査を担って
@@ -52,11 +52,11 @@ function compareText(left, right) {
52
52
  * phase無しplanのtaskにはphase_idフィールド自体が無いため、そこでは暗黙Phaseの状態を
53
53
  * 埋める。フィールドが無い/nullの入力(既存test・素のnode)は従来どおり対象外(false)になる。
54
54
  *
55
- * 監査待ちの状態集合そのものは`todo-audit-pending.mjs`が持つ(gate_ready・reviewing・rejected)。
55
+ * 監査前の状態集合そのものは`todo-audit-pending.mjs`が持つ(gate_ready・reviewing・rejected)。
56
56
  * `active`(一部taskがまだpending)が入っていないことにここも依存している——ここまで
57
57
  * 広げると、完走していない枝の通常foldまで止めてしまい既存挙動を変える。
58
58
  *
59
- * 下のv4/v5除外は共有moduleへ移さない。あれは「監査待ちとは何か」の定義ではなく、
59
+ * 下のv4/v5除外は共有moduleへ移さない。あれは「監査前とは何か」の定義ではなく、
60
60
  * ganttがどこまでfoldを止めるかという本moduleの方針である。移すと、宣言Phase planの
61
61
  * fold挙動を他の消費者の都合で変えてしまう。
62
62
  */
@@ -165,11 +165,11 @@ function blockedEntry(value) {
165
165
  }
166
166
 
167
167
  /**
168
- * 監査待ちPhase 1件。
168
+ * 監査前Phase 1件。
169
169
  *
170
170
  * task entryと紛れないよう`status`ではなく`phase_status`にする。状態集合は
171
171
  * `todo-audit-pending.mjs`の定義をそのまま使う(ここで書き直さない)。
172
- * `next_commands`を非空必須にしたのは、監査待ちなのに次の一手が空なら次アクション面として
172
+ * `next_commands`を非空必須にしたのは、監査前なのに次の一手が空なら次アクション面として
173
173
  * 無意味だからである(状態集合が閉じている以上、空になる枝は無い)。
174
174
  */
175
175
  function auditPendingEntry(value) {
@@ -401,9 +401,9 @@ export function validateTodoStatusResult(value) {
401
401
  }
402
402
 
403
403
  /**
404
- * memberの監査待ちPhaseを`audit_pending` entryへ起こす。
404
+ * memberの監査前Phaseを`audit_pending` entryへ起こす。
405
405
  *
406
- * 「監査待ちか」の判定は`todo-audit-pending.mjs`、Phase定義(slots)は`todo-store.mjs`の
406
+ * 「監査前か」の判定は`todo-audit-pending.mjs`、Phase定義(slots)は`todo-store.mjs`の
407
407
  * `todoPhaseDefinitions`が正本である。`plan.phases`を直接読むとphase無しplan(v1/v2/v3)と
408
408
  * synthetic read modelで落ちるので読まない。
409
409
  *
@@ -717,7 +717,7 @@ export function projectTodoStatus(readModel, options = undefined) {
717
717
  dispatch_frontier: dispatchFrontier(readModel.project_id, lists.next_ready),
718
718
  blocked: lists.blocked,
719
719
  connection_pending: lists.connection_pending,
720
- // 監査待ちは`member.phases`だけから作った別の列で、dispatch(next_ready/dispatch_frontier)へは
720
+ // 監査前は`member.phases`だけから作った別の列で、dispatch(next_ready/dispatch_frontier)へは
721
721
  // 影響しない。監査が進んでもfrontier_digestは動かない。
722
722
  audit_pending: lists.audit_pending,
723
723
  // 全task done後、構造finalizationが無い/古いplanだけを別列へ出す。監査状態と
@@ -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));
@@ -5258,8 +5286,8 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
5258
5286
  await protocolStage(options, 'phase_v3_marker_durable');
5259
5287
  const tasks = replay(revision.desired_plan, [genesis], {
5260
5288
  now: options.now ? new Date(options.now) : new Date(),
5261
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
5262
- verifyImportSource: importSourceVerifier(repoRoot, false),
5289
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
5290
+ verifyImportSource: structuralImportSourceVerifier,
5263
5291
  });
5264
5292
  const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
5265
5293
  for (const [stage, ref, bytes] of [
@@ -5429,8 +5457,8 @@ export async function applyPhaseTodoRevision(options = {}) {
5429
5457
  await protocolStage(options, 'phase_revision_marker_durable');
5430
5458
  const tasks = replay(revision.desired_plan, [genesis], {
5431
5459
  now: options.now ? new Date(options.now) : new Date(),
5432
- verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
5433
- verifyImportSource: importSourceVerifier(repoRoot, false),
5460
+ verifyEvidence: structuralEvidenceVerifier(store.manifest),
5461
+ verifyImportSource: structuralImportSourceVerifier,
5434
5462
  });
5435
5463
  const snapshot = snapshotFor(revision.desired_plan, [genesis], tasks);
5436
5464
  const artifacts = [
@@ -5587,8 +5615,8 @@ export async function applyTodoRevision(options = {}) {
5587
5615
  }
5588
5616
  await protocolStage(options, 'revision_marker_durable');
5589
5617
 
5590
- const verifyEvidence = evidenceVerifier(store.manifest, repoRoot, false);
5591
- const verifyImportSource = importSourceVerifier(repoRoot, false);
5618
+ const verifyEvidence = structuralEvidenceVerifier(store.manifest);
5619
+ const verifyImportSource = structuralImportSourceVerifier;
5592
5620
  const tasks = replay(revision.desired_plan, [genesis], {
5593
5621
  now: options.now ? new Date(options.now) : new Date(), verifyEvidence, verifyImportSource,
5594
5622
  });
@@ -5869,8 +5897,8 @@ export async function applyTodoRevisionSet(options = {}) {
5869
5897
  }
5870
5898
  await protocolStage(options, 'revision_set_marker_durable');
5871
5899
 
5872
- const verifyEvidence = evidenceVerifier(store.manifest, repoRoot, false);
5873
- const verifyImportSource = importSourceVerifier(repoRoot, false);
5900
+ const verifyEvidence = structuralEvidenceVerifier(store.manifest);
5901
+ const verifyImportSource = structuralImportSourceVerifier;
5874
5902
  for (const entry of prepared) {
5875
5903
  const { revision, genesis } = entry;
5876
5904
  const tasks = replay(revision.desired_plan, [genesis], {