@quolu/lattice 0.52.2 → 0.52.4

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.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,728 +1,728 @@
1
- import { createHash } from 'node:crypto';
2
- import { isCanonicalUtcTimestamp } from './timestamp-contract.mjs';
3
-
4
- export const TODO_EVENT_KINDS = Object.freeze([
5
- 'plan_genesis', 'start', 'start_retracted', 'block', 'unblock', 'done', 'reopen',
6
- 'phase_review', 'phase_accept', 'phase_reject', 'phase_reopen',
7
- // ADR 0148: 監査していない歴史を「監査なしで閉じた」として明示的に閉じるための専用kind。
8
- // phase_review/accept/reject/reopenと同じv3 tail event shape(phase_id持ち)に収め、
9
- // 新しいevent schema版は作らない。
10
- 'phase_close_unaudited',
11
- // ob03: 調整方式(witness検証で並列するか、会話調整で行くか)の宣言。planに帰属する事実で
12
- // taskにもPhaseにも属さないため、task_idもphase_idも持たない最初のkindになる。actorが
13
- // 「誰が選んだか」の帰属を持つ——witnessが全planの暗黙義務だった時に帰属が無く、正確な
14
- // 案内が素通りされたことへの是正である(オーナー裁定C①)。
15
- 'coordination_mode',
16
- // 開発中に発見したplan跨ぎの依存を、active plan topologyの追記改変ではなく
17
- // version-boundなplan-scoped eventとして接続する。推定はせず、AIが発見した時だけ積む。
18
- 'cross_plan_dependency',
19
- ]);
20
-
21
- /** planへ帰属し、taskにもPhaseにも属さないevent kind。 */
22
- export const TODO_PLAN_SCOPED_EVENT_KINDS = Object.freeze([
23
- 'coordination_mode', 'cross_plan_dependency',
24
- ]);
25
-
26
- /** 調整方式。witness=独立性を宣言し検証して並列する/conversation=会話で調整する。 */
27
- export const TODO_COORDINATION_MODES = Object.freeze(['witness', 'conversation']);
28
- export const TODO_NOTE_EVENT_SCHEMA = 'lattice.todo_note_event.v1';
29
- /**
30
- * plan単位のnote event。工程レベルの義務(順序制約・一度きりの観測が在ること)は特定のtaskに
31
- * 属さないので、v1の`task_id`必須では書けない。v1は書き換えない——既存chainはhash連鎖で
32
- * 固定済みであり、taskノートの挙動も digest も動かさない。
33
- *
34
- * v2は**別のchain file**(`plan-active.jsonl`)へ積む。同じchainへ混ぜると、旧CLIは
35
- * 1 eventずつのbyte検証で chain全体を壊れと読み、noteの読みを前提条件とする`todo start`が
36
- * 落ちる。しかもstoreへ書いたものは戻せない。分離すれば旧CLIはfileの存在に気づかず、
37
- * task noteの読み書きは1バイトも変わらない。
38
- */
39
- export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
40
- /**
41
- * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
42
- * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
43
- */
44
- export const TODO_NOTE_CONTEXT_SCHEMA = 'lattice.todo_note_context.v2';
45
- export const TODO_LIMITS = Object.freeze({
46
- tasksPerPlan: 512,
47
- edgesPerPlan: 2_048,
48
- joinsPerPlan: 128,
49
- journalSegmentBytes: 1_048_576,
50
- snapshotBytes: 8_388_608,
51
- narrativeSectionBytes: 262_144,
52
- noteBodyBytes: 16_384,
53
- noteContextBytes: 65_536,
54
- // statusのplan_notes entryが載せる最新noteの件数。本文を載せない代わりに
55
- // 「誰がいつ置いたか」だけを新しい順で数件出す(中身はnote listが持つ)。
56
- statusPlanNoteLatest: 3,
57
- });
58
-
59
- const DIGEST = /^[0-9a-f]{64}$/;
60
- const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
61
- const CONTROL = /[\u0000-\u001f\u007f]/u;
62
- const NOTE_FORBIDDEN_CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u;
63
-
64
- export const TODO_DESIGN_MEMO_PROMPT = 'あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください';
65
-
66
- export const isTodoDigest = (value) => typeof value === 'string' && DIGEST.test(value);
67
- export const isTodoIdentifier = (value) => typeof value === 'string' && IDENTIFIER.test(value);
68
- export const isNonNegativeSafeInteger = (value) => Number.isSafeInteger(value) && value >= 0;
69
-
70
- export function isStrictTodoTimestamp(value) {
71
- return isCanonicalUtcTimestamp(value);
72
- }
73
-
74
- export function assertStrictTodoTimestamp(value, field = 'timestamp') {
75
- if (!isStrictTodoTimestamp(value)) throw new TypeError(`${field}: strict timestamp required`);
76
- return value;
77
- }
78
-
79
- export function isTodoRef(value) {
80
- if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 1_024
81
- || CONTROL.test(value) || value.includes('\\') || value.startsWith('/')) return false;
82
- return value.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
83
- }
84
-
85
- export function exactRecord(value, keys) {
86
- if (value === null || typeof value !== 'object' || Array.isArray(value)
87
- || Object.getPrototypeOf(value) !== Object.prototype) return false;
88
- const actual = Object.keys(value).sort();
89
- const expected = [...keys].sort();
90
- return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
91
- }
92
-
93
- function canonicalPart(value, seen, depth) {
94
- if (depth > 40) throw new TypeError('todo artifact nesting limit exceeded');
95
- if (value === null || typeof value === 'boolean') return JSON.stringify(value);
96
- if (typeof value === 'string') return JSON.stringify(value);
97
- if (typeof value === 'number') {
98
- if (!Number.isFinite(value) || !Number.isSafeInteger(value) || Object.is(value, -0)) {
99
- throw new TypeError('todo artifact number must be a safe integer');
100
- }
101
- return JSON.stringify(value);
102
- }
103
- if (typeof value !== 'object' || seen.has(value)) throw new TypeError('todo artifact is not a JSON tree');
104
- seen.add(value);
105
- let result;
106
- if (Array.isArray(value)) {
107
- if (Object.getPrototypeOf(value) !== Array.prototype
108
- || Reflect.ownKeys(value).length !== value.length + 1) throw new TypeError('todo artifact array is not dense');
109
- result = `[${value.map((entry) => canonicalPart(entry, seen, depth + 1)).join(',')}]`;
110
- } else {
111
- if (Object.getPrototypeOf(value) !== Object.prototype
112
- || Reflect.ownKeys(value).some((key) => typeof key !== 'string')) throw new TypeError('todo artifact must use plain objects');
113
- result = `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalPart(value[key], seen, depth + 1)}`).join(',')}}`;
114
- }
115
- seen.delete(value);
116
- return result;
117
- }
118
-
119
- export function canonicalizeTodoArtifact(value) {
120
- return canonicalPart(value, new Set(), 0);
121
- }
122
-
123
- export function digestTodoArtifact(value) {
124
- return createHash('sha256').update(canonicalizeTodoArtifact(value), 'utf8').digest('hex');
125
- }
126
-
127
- export function todoSelfDigest(value, field) {
128
- const projection = {};
129
- for (const key of Object.keys(value)) if (key !== field) projection[key] = value[key];
130
- return digestTodoArtifact(projection);
131
- }
132
-
133
- const noteBody = (value) => typeof value === 'string' && value.length > 0
134
- && Buffer.byteLength(value, 'utf8') <= TODO_LIMITS.noteBodyBytes
135
- && !NOTE_FORBIDDEN_CONTROL.test(value);
136
-
137
- /**
138
- * lifecycle journalとは独立したnote eventを検証する。v1(task note)とv2(plan note)は
139
- * 別chainへ積まれるが、検証器は両方を受ける——どちらのchainを読んでいるかはpathが決め、
140
- * chainへ他scopeが混ざっていないことは`readTodoNoteEvents`が読み出し時に落とす。
141
- * v1は`scope`を持たない——定義上taskであり、投影の側で明示`scope`へ正規化する。
142
- */
143
- export function validateTodoNoteEvent(value) {
144
- try {
145
- const keys = [
146
- 'schema', 'project_id', 'plan_key', 'task_id', 'plan_version', 'sequence',
147
- 'previous_digest', 'actor', 'recorded_at', 'body', 'supersedes', 'event_digest',
148
- ];
149
- const planScoped = value?.schema === TODO_NOTE_EVENT_V2_SCHEMA;
150
- return exactRecord(value, planScoped ? [...keys, 'scope'] : keys)
151
- && (planScoped
152
- // v2は今のところplan scopeだけを表す。phase scopeは配達面(audit_pending entry)を
153
- // 持つtaskと同じ波で足す——書けるが届かない面を作らないため。
154
- ? value.scope === 'plan' && value.task_id === null
155
- : value.schema === TODO_NOTE_EVENT_SCHEMA && isTodoIdentifier(value.task_id))
156
- && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
157
- && isTodoIdentifier(value.plan_version)
158
- && Number.isSafeInteger(value.sequence) && value.sequence >= 1
159
- && (value.sequence === 1 ? value.previous_digest === null : isTodoDigest(value.previous_digest))
160
- && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
161
- && (value.supersedes === null || isTodoDigest(value.supersedes))
162
- && isTodoDigest(value.event_digest) && value.supersedes !== value.event_digest
163
- && value.event_digest === todoSelfDigest(value, 'event_digest');
164
- } catch {
165
- return false;
166
- }
167
- }
168
-
169
- /**
170
- * `scope`は投影が必ず埋める。読み手はここでv1/v2の区別を持たないので、`origin_task_id`が
171
- * nullであることから「plan単位だ」を推論させない——型で表現していない区別は、exact検証を
172
- * 通り抜けて受け手の解釈に落ちる。
173
- */
174
- function noteContextEntry(value) {
175
- return exactRecord(value, [
176
- 'event_digest', 'origin_plan_version', 'scope', 'origin_task_id', 'actor', 'recorded_at',
177
- 'body', 'supersedes', 'superseded_by', 'correction_state',
178
- ]) && isTodoDigest(value.event_digest) && isTodoIdentifier(value.origin_plan_version)
179
- && ['plan', 'task'].includes(value.scope)
180
- && (value.scope === 'plan'
181
- ? value.origin_task_id === null : isTodoIdentifier(value.origin_task_id))
182
- && actor(value.actor)
183
- && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
184
- && (value.supersedes === null || isTodoDigest(value.supersedes))
185
- && (value.superseded_by === null || isTodoDigest(value.superseded_by))
186
- && ['current', 'superseded'].includes(value.correction_state)
187
- && ((value.correction_state === 'current' && value.superseded_by === null)
188
- || (value.correction_state === 'superseded' && isTodoDigest(value.superseded_by)));
189
- }
190
-
191
- /** 個別ToDo詳細とstart結果へ必ず同梱するbounded note contextを検証する。 */
192
- export function validateTodoNoteContext(value) {
193
- try {
194
- if (!exactRecord(value, [
195
- 'schema', 'project_id', 'plan_key', 'task_id', 'notes', 'note_head_digest',
196
- 'plan_note_head_digest', 'overflow_count', 'full_history_command', 'context_digest',
197
- ]) || value.schema !== TODO_NOTE_CONTEXT_SCHEMA
198
- || !isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)
199
- || !isTodoIdentifier(value.task_id) || !Array.isArray(value.notes)
200
- || value.notes.length > TODO_LIMITS.tasksPerPlan || !value.notes.every(noteContextEntry)
201
- || !(value.note_head_digest === null || isTodoDigest(value.note_head_digest))
202
- || !(value.plan_note_head_digest === null || isTodoDigest(value.plan_note_head_digest))
203
- || !isNonNegativeSafeInteger(value.overflow_count)
204
- // contextはplan noteも載せるので、案内するのはplan全体を返す形でなければならない。
205
- // `--task <id>`形はplan noteを落とすため、fullと名乗りながら全部を取りに行けなくなる。
206
- || value.full_history_command !== `lattice todo note list --plan ${value.plan_key} --json`
207
- || !isTodoDigest(value.context_digest)
208
- || value.context_digest !== todoSelfDigest(value, 'context_digest')) return false;
209
- // headはchainごとなので、同値もscopeで切る。task noteが空でplan noteが在る時に
210
- // 「notesが非空なのにheadがnull」を壊れと読まないため。overflowで本文が落ちても
211
- // headはchainの実在を述べ続ける——同値はnotesではなくoverflow込みの母集合で見る。
212
- const scoped = (scope) => value.notes.some((note) => note.scope === scope);
213
- if (value.overflow_count === 0) {
214
- if (scoped('task') !== (value.note_head_digest !== null)) return false;
215
- if (scoped('plan') !== (value.plan_note_head_digest !== null)) return false;
216
- } else if (value.note_head_digest === null && value.plan_note_head_digest === null) {
217
- return false;
218
- }
219
- return value.notes.reduce((bytes, note) => bytes + Buffer.byteLength(note.body, 'utf8'), 0)
220
- <= TODO_LIMITS.noteContextBytes;
221
- } catch {
222
- return false;
223
- }
224
- }
225
-
226
- const nullableDigest = (value) => value === null || isTodoDigest(value);
227
- const nullableText = (value) => value === null || (typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 16_384);
228
- /** 設計メモの拒否理由を、本文をerrorへ複製せずAIが訂正できる形で返す。 */
229
- export function explainTodoDesignMemo(value) {
230
- const expected = {
231
- type: 'string', non_whitespace: true,
232
- max_characters: TODO_LIMITS.noteBodyBytes, max_utf8_bytes: TODO_LIMITS.noteBodyBytes,
233
- forbidden_control_characters: false,
234
- };
235
- if (typeof value !== 'string') {
236
- return { valid: false, reason: 'type', expected,
237
- actual: { type: value === null ? 'null' : typeof value } };
238
- }
239
- const byteLength = Buffer.byteLength(value, 'utf8');
240
- if (value.trim().length === 0) {
241
- return { valid: false, reason: 'blank', expected,
242
- actual: { byte_length: byteLength, non_whitespace: false } };
243
- }
244
- if (value.length > TODO_LIMITS.noteBodyBytes || byteLength > TODO_LIMITS.noteBodyBytes) {
245
- return { valid: false, reason: 'too_large', expected,
246
- actual: { character_length: value.length, byte_length: byteLength } };
247
- }
248
- if (NOTE_FORBIDDEN_CONTROL.test(value)) {
249
- return { valid: false, reason: 'forbidden_control', expected,
250
- actual: { byte_length: byteLength, contains_forbidden_control: true } };
251
- }
252
- return { valid: true };
253
- }
254
-
255
- export const isTodoDesignMemo = (value) => explainTodoDesignMemo(value).valid;
256
- const actor = (value) => exactRecord(value, ['host', 'session', 'agent'])
257
- && [value.host, value.session, value.agent].every(isTodoIdentifier);
258
- const provenance = (value) => value === null || (exactRecord(value, ['source_commit', 'source_event_digest'])
259
- && /^[0-9a-f]{40}$/u.test(value.source_commit) && isTodoDigest(value.source_event_digest));
260
- const nodeRef = (value) => (exactRecord(value, ['project_id', 'plan_key', 'task_id'])
261
- || exactRecord(value, ['project_id', 'plan_key', 'task_id', 'expected_topology_digest']))
262
- && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
263
- && isTodoIdentifier(value.task_id)
264
- && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
265
- const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
266
- const refKey = (value) => `${value.project_id}\0${value.plan_key}\0${value.task_id}`;
267
- const phaseRef = (value) => (exactRecord(value, ['project_id', 'plan_key', 'phase_id'])
268
- || exactRecord(value, ['project_id', 'plan_key', 'phase_id', 'expected_topology_digest']))
269
- && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
270
- && isTodoIdentifier(value.phase_id)
271
- && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
272
- const phaseRefKey = (value) => `${value.project_id}\0${value.plan_key}\0${value.phase_id}`;
273
-
274
- function compileBinding(value) {
275
- return value === null || (exactRecord(value, [
276
- 'boundary_manifest_digest', 'compiled_plan_digest', 'topology_digest', 'base_sha',
277
- ]) && isTodoDigest(value.boundary_manifest_digest) && isTodoDigest(value.compiled_plan_digest)
278
- && isTodoDigest(value.topology_digest) && /^[0-9a-f]{40}$/u.test(value.base_sha));
279
- }
280
-
281
- function taskV1(value) {
282
- return exactRecord(value, ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding'])
283
- && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
284
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref)) && compileBinding(value.compile_binding);
285
- }
286
-
287
- export function validateTodoNarrativeAnchor(value) {
288
- return exactRecord(value, ['origin_plan_ref', 'origin_line', 'source_commit', 'source_line_digest'])
289
- && isTodoRef(value.origin_plan_ref) && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
290
- && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(value.source_commit)
291
- && isTodoDigest(value.source_line_digest);
292
- }
293
-
294
- function taskV2(value) {
295
- return exactRecord(value, [
296
- 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
297
- ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
298
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
299
- && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
300
- && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
301
- && compileBinding(value.compile_binding);
302
- }
303
-
304
- function evidence(value) {
305
- return exactRecord(value, [
306
- 'evidence_id', 'repo_id', 'path', 'git_blob_oid', 'content_digest', 'media_type', 'anchor_digest',
307
- ]) && isTodoIdentifier(value.evidence_id) && isTodoIdentifier(value.repo_id) && isTodoRef(value.path)
308
- && /^[0-9a-f]{40,64}$/u.test(value.git_blob_oid) && isTodoDigest(value.content_digest)
309
- && typeof value.media_type === 'string' && /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/u.test(value.media_type)
310
- && nullableDigest(value.anchor_digest);
311
- }
312
-
313
- export function validateTodoImportSource(value) {
314
- return exactRecord(value, ['schema', 'origin_plan_ref', 'origin_line', 'source_commit'])
315
- && value.schema === 'lattice.todo_import_source.v1' && isTodoRef(value.origin_plan_ref)
316
- && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
317
- && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(value.source_commit);
318
- }
319
-
320
- function taskV3(value) {
321
- return exactRecord(value, [
322
- 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
323
- 'parent_task_id',
324
- ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
325
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
326
- && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
327
- && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
328
- && compileBinding(value.compile_binding)
329
- && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id));
330
- }
331
-
332
- function taskV4(value) {
333
- return exactRecord(value, [
334
- 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
335
- 'parent_task_id', 'phase_id',
336
- ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
337
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
338
- && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
339
- && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
340
- && compileBinding(value.compile_binding)
341
- && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
342
- && isTodoIdentifier(value.phase_id);
343
- }
344
-
345
- function taskV5(value) {
346
- return exactRecord(value, [
347
- 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
348
- 'compile_binding', 'parent_task_id',
349
- ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
350
- && isTodoDesignMemo(value.design_memo)
351
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
352
- && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
353
- && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
354
- && compileBinding(value.compile_binding)
355
- && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id));
356
- }
357
-
358
- function taskV6(value) {
359
- return exactRecord(value, [
360
- 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
361
- 'compile_binding', 'parent_task_id', 'phase_id',
362
- ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
363
- && isTodoDesignMemo(value.design_memo)
364
- && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
365
- && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
366
- && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
367
- && compileBinding(value.compile_binding)
368
- && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
369
- && isTodoIdentifier(value.phase_id);
370
- }
371
-
372
- function phaseV1(value) {
373
- return exactRecord(value, [
374
- 'phase_id', 'title', 'gate_policy', 'predecessor_phase_ids', 'required_evidence_slots',
375
- ]) && isTodoIdentifier(value.phase_id) && nullableText(value.title)
376
- && isTodoIdentifier(value.gate_policy)
377
- && Array.isArray(value.predecessor_phase_ids)
378
- && value.predecessor_phase_ids.every(isTodoIdentifier)
379
- && value.predecessor_phase_ids.every((entry, index) => index === 0
380
- || compareText(value.predecessor_phase_ids[index - 1], entry) < 0)
381
- && Array.isArray(value.required_evidence_slots) && value.required_evidence_slots.length > 0
382
- && value.required_evidence_slots.every(isTodoIdentifier)
383
- && value.required_evidence_slots.every((entry, index) => index === 0
384
- || compareText(value.required_evidence_slots[index - 1], entry) < 0);
385
- }
386
-
387
- function validPhaseGraph(phases) {
388
- const ids = new Set(phases.map(({ phase_id }) => phase_id));
389
- const predecessors = new Map(phases.map(({ phase_id, predecessor_phase_ids }) => (
390
- [phase_id, predecessor_phase_ids]
391
- )));
392
- if (phases.some(({ phase_id, predecessor_phase_ids }) => predecessor_phase_ids.includes(phase_id)
393
- || predecessor_phase_ids.some((id) => !ids.has(id)))) return false;
394
- const colors = new Map();
395
- const visit = (id) => {
396
- if (colors.get(id) === 1) return false;
397
- if (colors.get(id) === 2) return true;
398
- colors.set(id, 1);
399
- if (!predecessors.get(id).every(visit)) return false;
400
- colors.set(id, 2);
401
- return true;
402
- };
403
- return [...ids].every(visit);
404
- }
405
-
406
- function validParentGraph(tasks) {
407
- const parents = new Map(tasks.map(({ task_id, parent_task_id }) => [task_id, parent_task_id]));
408
- for (const [taskId, parentTaskId] of parents) {
409
- if (parentTaskId !== null && (parentTaskId === taskId || !parents.has(parentTaskId))) return false;
410
- const seen = new Set([taskId]);
411
- let cursor = parentTaskId;
412
- while (cursor !== null) {
413
- if (seen.has(cursor)) return false;
414
- seen.add(cursor);
415
- cursor = parents.get(cursor);
416
- }
417
- }
418
- return true;
419
- }
420
-
421
- export function validateTodoPlan(value) {
422
- try {
423
- const taskValidator = value?.schema === 'lattice.todo_plan.v1' ? taskV1
424
- : value?.schema === 'lattice.todo_plan.v2' ? taskV2
425
- : value?.schema === 'lattice.todo_plan.v3' ? taskV3
426
- : ['lattice.todo_plan.v4', 'lattice.todo_plan.v5'].includes(value?.schema) ? taskV4
427
- : value?.schema === 'lattice.todo_plan.v6' ? taskV5
428
- : value?.schema === 'lattice.todo_plan.v7' ? taskV6 : null;
429
- const planKeys = [
430
- 'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
431
- 'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
432
- ];
433
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
434
- .includes(value?.schema)) planKeys.push('phases');
435
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema)) {
436
- planKeys.push('phase_accept_dependencies');
437
- }
438
- if (!exactRecord(value, planKeys) || taskValidator === null || !isTodoIdentifier(value.project_id)
439
- || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
440
- || !nullableDigest(value.predecessor_plan_digest) || !Array.isArray(value.tasks)
441
- || value.tasks.length === 0 || value.tasks.length > TODO_LIMITS.tasksPerPlan
442
- || !value.tasks.every(taskValidator) || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
443
- || !Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan
444
- || !value.hard_dependencies.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
445
- || !Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan
446
- || !value.joins.every((join) => exactRecord(join, ['id', 'after', 'before']) && isTodoIdentifier(join.id)
447
- && Array.isArray(join.after) && join.after.length > 0 && join.after.length <= TODO_LIMITS.tasksPerPlan
448
- && join.after.every(nodeRef) && nodeRef(join.before))
449
- || !isTodoDigest(value.topology_digest) || !isTodoDigest(value.plan_digest)
450
- || (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
451
- 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
452
- && !validParentGraph(value.tasks))) return false;
453
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
454
- && (!Array.isArray(value.phases) || value.phases.length === 0
455
- || value.phases.length > TODO_LIMITS.tasksPerPlan || !value.phases.every(phaseV1)
456
- || value.phases.some((entry, index) => index > 0
457
- && compareText(value.phases[index - 1].phase_id, entry.phase_id) >= 0)
458
- || new Set(value.phases.map(({ phase_id }) => phase_id)).size !== value.phases.length
459
- || value.tasks.some(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id))
460
- || !validPhaseGraph(value.phases))) return false;
461
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
462
- && (!Array.isArray(value.phase_accept_dependencies)
463
- || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan
464
- || !value.phase_accept_dependencies.every((edge) => exactRecord(edge, ['from', 'to'])
465
- && phaseRef(edge.from) && nodeRef(edge.to))
466
- || value.phase_accept_dependencies.some((edge, index) => index > 0
467
- && compareText(`${phaseRefKey(value.phase_accept_dependencies[index - 1].from)}\0${refKey(value.phase_accept_dependencies[index - 1].to)}`,
468
- `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`) >= 0))) return false;
469
- if (value.tasks.some((entry, index) => index > 0 && compareText(value.tasks[index - 1].task_id, entry.task_id) >= 0)
470
- || value.hard_dependencies.some((edge, index) => index > 0
471
- && compareText(`${refKey(value.hard_dependencies[index - 1].from)}\0${refKey(value.hard_dependencies[index - 1].to)}`,
472
- `${refKey(edge.from)}\0${refKey(edge.to)}`) >= 0)
473
- || value.joins.some((join, index) => index > 0 && compareText(value.joins[index - 1].id, join.id) >= 0)
474
- || value.joins.some((join) => join.after.some((entry, index) => index > 0
475
- && compareText(refKey(join.after[index - 1]), refKey(entry)) >= 0))) return false;
476
- const topology = {
477
- project_id: value.project_id, plan_key: value.plan_key, plan_version: value.plan_version,
478
- tasks: value.tasks, hard_dependencies: value.hard_dependencies, joins: value.joins,
479
- ...(['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
480
- ? { phases: value.phases } : {}),
481
- ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
482
- ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
483
- };
484
- return value.topology_digest === digestTodoArtifact(topology)
485
- && value.plan_digest === todoSelfDigest(value, 'plan_digest');
486
- } catch { return false; }
487
- }
488
-
489
- export function validateEvidenceDescriptor(value) { return evidence(value); }
490
-
491
- function validPayload(event) {
492
- const payload = event.payload;
493
- if (event.kind === 'plan_genesis') return (exactRecord(payload, [
494
- 'plan_digest', 'topology_digest', 'predecessor_plan_digest', 'task_migration',
495
- ]) || exactRecord(payload, [
496
- 'plan_digest', 'topology_digest', 'predecessor_plan_digest', 'task_migration', 'historical_import',
497
- ])) && (payload.historical_import === undefined || payload.historical_import === true)
498
- && isTodoDigest(payload.plan_digest) && isTodoDigest(payload.topology_digest)
499
- && nullableDigest(payload.predecessor_plan_digest) && Array.isArray(payload.task_migration)
500
- && payload.task_migration.length <= TODO_LIMITS.tasksPerPlan
501
- && payload.task_migration.every((entry) => exactRecord(entry, ['from_task_id', 'to_task_id'])
502
- && isTodoIdentifier(entry.from_task_id) && (entry.to_task_id === 'removed' || isTodoIdentifier(entry.to_task_id)));
503
- if (event.kind === 'start' && payload?.start_mode === 'historical_import') {
504
- return exactRecord(payload, ['start_mode', 'imported', 'status', 'started_at', 'evidence'])
505
- && payload.imported === true && payload.status === 'in-progress'
506
- && (payload.started_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(payload.started_at))
507
- && validateTodoImportSource(payload.evidence);
508
- }
509
- if (event.kind === 'coordination_mode') {
510
- return exactRecord(payload, ['mode', 'reason'])
511
- && TODO_COORDINATION_MODES.includes(payload.mode)
512
- && nullableText(payload.reason) && payload.reason !== null;
513
- }
514
- if (event.kind === 'cross_plan_dependency') {
515
- const dependencyRef = (value) => exactRecord(value, [
516
- 'project_id', 'plan_key', 'task_id', 'expected_topology_digest',
517
- ]) && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
518
- && isTodoIdentifier(value.task_id) && isTodoDigest(value.expected_topology_digest);
519
- return exactRecord(payload, ['from', 'to', 'reason'])
520
- && dependencyRef(payload.from) && dependencyRef(payload.to)
521
- && nullableText(payload.reason) && payload.reason !== null;
522
- }
523
- if (event.kind === 'start') return exactRecord(payload, ['override_reason']) && nullableText(payload.override_reason);
524
- if (event.kind === 'start_retracted') return exactRecord(payload, ['reason', 'target_start_digest'])
525
- && nullableText(payload.reason) && payload.reason !== null
526
- && isTodoDigest(payload.target_start_digest);
527
- if (event.kind === 'block') return exactRecord(payload, ['reason']) && nullableText(payload.reason) && payload.reason !== null;
528
- if (event.kind === 'unblock') return exactRecord(payload, []);
529
- if (event.kind === 'done' && payload?.done_mode === 'authored') {
530
- return exactRecord(payload, ['done_mode', 'imported', 'evidence'])
531
- && payload.imported === false && evidence(payload.evidence);
532
- }
533
- if (event.kind === 'done' && payload?.done_mode === 'historical_import') {
534
- return exactRecord(payload, ['done_mode', 'imported', 'status', 'completed_at', 'evidence'])
535
- && payload.imported === true && payload.status === 'done'
536
- && (payload.completed_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(payload.completed_at))
537
- && validateTodoImportSource(payload.evidence);
538
- }
539
- if (event.kind === 'done' && payload?.done_mode === 'evidence_promotion') {
540
- return exactRecord(payload, ['done_mode', 'imported', 'target_done_digest', 'evidence'])
541
- && payload.imported === true && isTodoDigest(payload.target_done_digest) && evidence(payload.evidence);
542
- }
543
- if (event.kind === 'reopen') return exactRecord(payload, ['reason', 'target_done_digest', 'override_reason'])
544
- && nullableText(payload.reason) && payload.reason !== null && isTodoDigest(payload.target_done_digest)
545
- && nullableText(payload.override_reason);
546
- if (event.kind === 'phase_review') return exactRecord(payload, ['reason'])
547
- && nullableText(payload.reason) && payload.reason !== null;
548
- if (event.kind === 'phase_accept') return exactRecord(payload, [
549
- 'review_event_digest', 'decision_evidence', 'evidence_slots',
550
- ]) && isTodoDigest(payload.review_event_digest) && evidence(payload.decision_evidence)
551
- && Array.isArray(payload.evidence_slots) && payload.evidence_slots.length > 0
552
- && payload.evidence_slots.every((entry) => exactRecord(entry, ['slot_id', 'evidence'])
553
- && isTodoIdentifier(entry.slot_id) && evidence(entry.evidence))
554
- && payload.evidence_slots.every((entry, index) => index === 0
555
- || compareText(payload.evidence_slots[index - 1].slot_id, entry.slot_id) < 0);
556
- if (event.kind === 'phase_reject') return exactRecord(payload, [
557
- 'review_event_digest', 'reason', 'decision_evidence',
558
- ]) && isTodoDigest(payload.review_event_digest) && nullableText(payload.reason)
559
- && payload.reason !== null && evidence(payload.decision_evidence);
560
- if (event.kind === 'phase_reopen') return exactRecord(payload, [
561
- 'reason', 'target_decision_digest', 'override_reason',
562
- ]) && nullableText(payload.reason) && payload.reason !== null
563
- && isTodoDigest(payload.target_decision_digest) && nullableText(payload.override_reason);
564
- // ADR 0148裁定1: 監査なしで閉じたことの理由は必須(payload.reason !== null)。証拠は無い
565
- // ——監査していないというのが事実であり、evidenceを要求すると「監査した体」を装う経路になる。
566
- if (event.kind === 'phase_close_unaudited') return exactRecord(payload, ['reason'])
567
- && nullableText(payload.reason) && payload.reason !== null;
568
- return false;
569
- }
570
-
571
- function validCarriedState(value) {
572
- if (!exactRecord(value, [
573
- 'status', 'started_at', 'done_at', 'blocked_reason', 'evidence', 'imported',
574
- ]) || !['pending', 'in-progress', 'blocked', 'done'].includes(value.status)
575
- || (value.started_at !== null && !isStrictTodoTimestamp(value.started_at))
576
- || (value.done_at !== null && !isStrictTodoTimestamp(value.done_at))
577
- || (value.blocked_reason !== null && !nullableText(value.blocked_reason))
578
- || typeof value.imported !== 'boolean') return false;
579
- if (value.status === 'pending') return value.started_at === null && value.done_at === null
580
- && value.blocked_reason === null && value.evidence === null && value.imported === false;
581
- const activeEvidenceValid = value.imported
582
- ? value.evidence === null || validateTodoImportSource(value.evidence)
583
- : value.evidence === null;
584
- if (value.status === 'in-progress') return value.done_at === null && value.blocked_reason === null
585
- && activeEvidenceValid;
586
- if (value.status === 'blocked') return value.done_at === null && value.blocked_reason !== null
587
- && activeEvidenceValid;
588
- return value.blocked_reason === null && value.evidence !== null
589
- && (value.imported ? validateTodoImportSource(value.evidence) : evidence(value.evidence));
590
- }
591
-
592
- function validStateMigration(value) {
593
- return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
594
- && value.every((entry) => exactRecord(entry, [
595
- 'from_task_id', 'to_task_id', 'state_policy', 'state',
596
- ]) && isTodoIdentifier(entry.from_task_id)
597
- && (entry.to_task_id === 'removed' || isTodoIdentifier(entry.to_task_id))
598
- && ['carry', 'carry_reconciled_metadata', 'reset_pending', 'removed', 'acquire_phase'].includes(entry.state_policy)
599
- && ((['carry', 'carry_reconciled_metadata', 'acquire_phase'].includes(entry.state_policy)
600
- && entry.to_task_id !== 'removed' && validCarriedState(entry.state))
601
- || (entry.state_policy === 'reset_pending' && entry.to_task_id !== 'removed' && entry.state === null)
602
- || (entry.state_policy === 'removed' && entry.to_task_id === 'removed' && entry.state === null)))
603
- && new Set(value.map(({ from_task_id }) => from_task_id)).size === value.length
604
- && value.every((entry, index) => index === 0
605
- || compareText(value[index - 1].from_task_id, entry.from_task_id) < 0);
606
- }
607
-
608
- function validPhaseStateMigration(value) {
609
- return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
610
- && value.every((entry) => exactRecord(entry, ['phase_id', 'state_policy', 'state'])
611
- && isTodoIdentifier(entry.phase_id) && ['carry', 'reset'].includes(entry.state_policy)
612
- && (entry.state_policy === 'reset' ? entry.state === null
613
- : exactRecord(entry.state, [
614
- 'status', 'review_event_digest', 'decision_event_digest', 'decision_evidence',
615
- ]) && ['locked', 'active', 'gate_ready', 'reviewing', 'accepted', 'rejected', 'closed_unaudited']
616
- .includes(entry.state.status)
617
- && nullableDigest(entry.state.review_event_digest)
618
- && nullableDigest(entry.state.decision_event_digest)
619
- && (entry.state.decision_evidence === null || evidence(entry.state.decision_evidence))))
620
- && value.every((entry, index) => index === 0
621
- || compareText(value[index - 1].phase_id, entry.phase_id) < 0);
622
- }
623
-
624
- export function validateTodoEvent(value) {
625
- try {
626
- const commonKeys = [
627
- 'schema', 'project_id', 'plan_key', 'plan_version', 'sequence', 'previous_digest',
628
- 'kind', 'task_id', 'actor', 'recorded_at', 'provenance', 'payload', 'event_digest',
629
- ];
630
- const v1 = value?.schema === 'lattice.todo_event.v1' && exactRecord(value, commonKeys);
631
- const v2 = value?.schema === 'lattice.todo_event.v2' && exactRecord(value, [
632
- ...commonKeys, 'reconciliation_state', 'revision_digest', 'reconciliation_digest',
633
- 'state_migration',
634
- ]) && value.kind === 'plan_genesis' && value.task_id === null
635
- && value.reconciliation_state === 'reconciled' && isTodoDigest(value.revision_digest)
636
- && isTodoDigest(value.reconciliation_digest) && validStateMigration(value.state_migration);
637
- const v3 = value?.schema === 'lattice.todo_event.v3' && exactRecord(value, [
638
- ...commonKeys, 'phase_id',
639
- ]);
640
- const v4 = value?.schema === 'lattice.todo_event.v4' && exactRecord(value, [
641
- ...commonKeys, 'phase_id', 'revision_digest', 'state_migration', 'phase_state_migration',
642
- ]) && value.kind === 'plan_genesis' && value.task_id === null && value.phase_id === null
643
- && isTodoDigest(value.revision_digest) && validStateMigration(value.state_migration)
644
- && validPhaseStateMigration(value.phase_state_migration);
645
- const phaseKind = ['phase_review', 'phase_accept', 'phase_reject', 'phase_reopen', 'phase_close_unaudited']
646
- .includes(value?.kind);
647
- // planへ帰属するkindは、plan_genesisと同じくtask_idを持たない(v3/v4ではphase_idも持たない)。
648
- // plan_genesisと違うのはjournalの途中に何度でも積めることで、最後の1件が現在の宣言になる。
649
- const planScopedKind = TODO_PLAN_SCOPED_EVENT_KINDS.includes(value?.kind);
650
- const planLevel = value?.kind === 'plan_genesis' || planScopedKind;
651
- return (v1 || v2 || v3 || v4) && isTodoIdentifier(value.project_id)
652
- && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.plan_version)
653
- && isNonNegativeSafeInteger(value.sequence) && nullableDigest(value.previous_digest)
654
- && TODO_EVENT_KINDS.includes(value.kind)
655
- && (v3 || v4
656
- ? ((planLevel && value.task_id === null && value.phase_id === null)
657
- || (phaseKind && value.task_id === null && isTodoIdentifier(value.phase_id))
658
- || (!phaseKind && !planLevel && isTodoIdentifier(value.task_id)
659
- && value.phase_id === null))
660
- : !phaseKind && ((planLevel && value.task_id === null)
661
- || (!planLevel && isTodoIdentifier(value.task_id))))
662
- && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && provenance(value.provenance)
663
- && validPayload(value) && isTodoDigest(value.event_digest)
664
- && value.event_digest === todoSelfDigest(value, 'event_digest');
665
- } catch { return false; }
666
- }
667
-
668
- export function validateTodoManifest(value) {
669
- try {
670
- const manifestV1 = value?.schema === 'lattice.todo_manifest.v1';
671
- const manifestV2 = value?.schema === 'lattice.todo_manifest.v2';
672
- return exactRecord(value, ['schema', 'project_id', 'repositories', 'members', 'manifest_digest'])
673
- && (manifestV1 || manifestV2) && isTodoIdentifier(value.project_id)
674
- && Array.isArray(value.repositories) && value.repositories.length > 0 && value.repositories.length <= 256
675
- && value.repositories.every((repo) => exactRecord(repo, ['repo_id', 'path'])
676
- && isTodoIdentifier(repo.repo_id) && (repo.path === '.' || isTodoRef(repo.path)))
677
- && new Set(value.repositories.map(({ repo_id }) => repo_id)).size === value.repositories.length
678
- && value.repositories.every((repo, index) => index === 0 || value.repositories[index - 1].repo_id < repo.repo_id)
679
- && Array.isArray(value.members) && value.members.length > 0 && value.members.length <= 256
680
- && value.members.every((member) => exactRecord(member, [
681
- 'plan_key', 'active_plan_version', 'plan_ref', 'journal_ref', 'snapshot_ref',
682
- 'topology_digest', 'journal_head_digest', ...(manifestV2 ? ['active_revision_digest'] : []),
683
- ]) && isTodoIdentifier(member.plan_key) && isTodoIdentifier(member.active_plan_version)
684
- && isTodoRef(member.plan_ref) && isTodoRef(member.journal_ref) && isTodoRef(member.snapshot_ref)
685
- && isTodoDigest(member.topology_digest) && isTodoDigest(member.journal_head_digest)
686
- && (!manifestV2 || isTodoDigest(member.active_revision_digest)))
687
- && value.members.every((member, index) => index === 0 || value.members[index - 1].plan_key < member.plan_key)
688
- && new Set(value.members.map(({ plan_key }) => plan_key)).size === value.members.length
689
- && isTodoDigest(value.manifest_digest) && value.manifest_digest === todoSelfDigest(value, 'manifest_digest');
690
- } catch { return false; }
691
- }
692
-
693
- export function validateTodoSnapshot(value) {
694
- try {
695
- const v1 = value?.schema === 'lattice.todo_snapshot.v1' && exactRecord(value, [
696
- 'schema', 'project_id', 'plan_key', 'plan_version', 'projection_version', 'through_sequence',
697
- 'journal_head_digest', 'tasks', 'snapshot_digest',
698
- ]);
699
- const v2 = value?.schema === 'lattice.todo_snapshot.v2' && exactRecord(value, [
700
- 'schema', 'project_id', 'plan_key', 'plan_version', 'projection_version', 'through_sequence',
701
- 'journal_head_digest', 'tasks', 'phases', 'snapshot_digest',
702
- ]);
703
- return (v1 || v2) && isTodoIdentifier(value.project_id)
704
- && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.plan_version)
705
- && value.projection_version === (v1 ? 1 : 2) && isNonNegativeSafeInteger(value.through_sequence)
706
- && isTodoDigest(value.journal_head_digest) && Array.isArray(value.tasks)
707
- && value.tasks.length > 0 && value.tasks.length <= TODO_LIMITS.tasksPerPlan
708
- && value.tasks.every((entry) => exactRecord(entry, [
709
- 'task_id', 'status', 'started_at', 'done_at', 'blocked_reason', 'evidence', 'evidence_unverified', 'imported',
710
- ]) && isTodoIdentifier(entry.task_id) && ['pending', 'in-progress', 'blocked', 'done'].includes(entry.status)
711
- && (entry.started_at === null || isStrictTodoTimestamp(entry.started_at))
712
- && (entry.done_at === null || isStrictTodoTimestamp(entry.done_at)) && nullableText(entry.blocked_reason)
713
- && (entry.evidence === null || evidence(entry.evidence) || validateTodoImportSource(entry.evidence))
714
- && typeof entry.evidence_unverified === 'boolean' && typeof entry.imported === 'boolean')
715
- && value.tasks.every((entry, index) => index === 0 || value.tasks[index - 1].task_id < entry.task_id)
716
- && (!v2 || (Array.isArray(value.phases) && value.phases.length > 0
717
- && value.phases.every((entry) => exactRecord(entry, [
718
- 'phase_id', 'status', 'review_event_digest', 'decision_event_digest', 'decision_evidence',
719
- ]) && isTodoIdentifier(entry.phase_id)
720
- && ['locked', 'active', 'gate_ready', 'reviewing', 'accepted', 'rejected', 'closed_unaudited']
721
- .includes(entry.status)
722
- && nullableDigest(entry.review_event_digest) && nullableDigest(entry.decision_event_digest)
723
- && (entry.decision_evidence === null || evidence(entry.decision_evidence)))
724
- && value.phases.every((entry, index) => index === 0
725
- || value.phases[index - 1].phase_id < entry.phase_id)))
726
- && isTodoDigest(value.snapshot_digest) && value.snapshot_digest === todoSelfDigest(value, 'snapshot_digest');
727
- } catch { return false; }
728
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { isCanonicalUtcTimestamp } from './timestamp-contract.mjs';
3
+
4
+ export const TODO_EVENT_KINDS = Object.freeze([
5
+ 'plan_genesis', 'start', 'start_retracted', 'block', 'unblock', 'done', 'reopen',
6
+ 'phase_review', 'phase_accept', 'phase_reject', 'phase_reopen',
7
+ // ADR 0148: 監査していない歴史を「監査なしで閉じた」として明示的に閉じるための専用kind。
8
+ // phase_review/accept/reject/reopenと同じv3 tail event shape(phase_id持ち)に収め、
9
+ // 新しいevent schema版は作らない。
10
+ 'phase_close_unaudited',
11
+ // ob03: 調整方式(witness検証で並列するか、会話調整で行くか)の宣言。planに帰属する事実で
12
+ // taskにもPhaseにも属さないため、task_idもphase_idも持たない最初のkindになる。actorが
13
+ // 「誰が選んだか」の帰属を持つ——witnessが全planの暗黙義務だった時に帰属が無く、正確な
14
+ // 案内が素通りされたことへの是正である(オーナー裁定C①)。
15
+ 'coordination_mode',
16
+ // 開発中に発見したplan跨ぎの依存を、active plan topologyの追記改変ではなく
17
+ // version-boundなplan-scoped eventとして接続する。推定はせず、AIが発見した時だけ積む。
18
+ 'cross_plan_dependency',
19
+ ]);
20
+
21
+ /** planへ帰属し、taskにもPhaseにも属さないevent kind。 */
22
+ export const TODO_PLAN_SCOPED_EVENT_KINDS = Object.freeze([
23
+ 'coordination_mode', 'cross_plan_dependency',
24
+ ]);
25
+
26
+ /** 調整方式。witness=独立性を宣言し検証して並列する/conversation=会話で調整する。 */
27
+ export const TODO_COORDINATION_MODES = Object.freeze(['witness', 'conversation']);
28
+ export const TODO_NOTE_EVENT_SCHEMA = 'lattice.todo_note_event.v1';
29
+ /**
30
+ * plan単位のnote event。工程レベルの義務(順序制約・一度きりの観測が在ること)は特定のtaskに
31
+ * 属さないので、v1の`task_id`必須では書けない。v1は書き換えない——既存chainはhash連鎖で
32
+ * 固定済みであり、taskノートの挙動も digest も動かさない。
33
+ *
34
+ * v2は**別のchain file**(`plan-active.jsonl`)へ積む。同じchainへ混ぜると、旧CLIは
35
+ * 1 eventずつのbyte検証で chain全体を壊れと読み、noteの読みを前提条件とする`todo start`が
36
+ * 落ちる。しかもstoreへ書いたものは戻せない。分離すれば旧CLIはfileの存在に気づかず、
37
+ * task noteの読み書きは1バイトも変わらない。
38
+ */
39
+ export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
40
+ /**
41
+ * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
42
+ * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
43
+ */
44
+ export const TODO_NOTE_CONTEXT_SCHEMA = 'lattice.todo_note_context.v2';
45
+ export const TODO_LIMITS = Object.freeze({
46
+ tasksPerPlan: 512,
47
+ edgesPerPlan: 2_048,
48
+ joinsPerPlan: 128,
49
+ journalSegmentBytes: 1_048_576,
50
+ snapshotBytes: 8_388_608,
51
+ narrativeSectionBytes: 262_144,
52
+ noteBodyBytes: 16_384,
53
+ noteContextBytes: 65_536,
54
+ // statusのplan_notes entryが載せる最新noteの件数。本文を載せない代わりに
55
+ // 「誰がいつ置いたか」だけを新しい順で数件出す(中身はnote listが持つ)。
56
+ statusPlanNoteLatest: 3,
57
+ });
58
+
59
+ const DIGEST = /^[0-9a-f]{64}$/;
60
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
61
+ const CONTROL = /[\u0000-\u001f\u007f]/u;
62
+ const NOTE_FORBIDDEN_CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u;
63
+
64
+ export const TODO_DESIGN_MEMO_PROMPT = 'あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください';
65
+
66
+ export const isTodoDigest = (value) => typeof value === 'string' && DIGEST.test(value);
67
+ export const isTodoIdentifier = (value) => typeof value === 'string' && IDENTIFIER.test(value);
68
+ export const isNonNegativeSafeInteger = (value) => Number.isSafeInteger(value) && value >= 0;
69
+
70
+ export function isStrictTodoTimestamp(value) {
71
+ return isCanonicalUtcTimestamp(value);
72
+ }
73
+
74
+ export function assertStrictTodoTimestamp(value, field = 'timestamp') {
75
+ if (!isStrictTodoTimestamp(value)) throw new TypeError(`${field}: strict timestamp required`);
76
+ return value;
77
+ }
78
+
79
+ export function isTodoRef(value) {
80
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 1_024
81
+ || CONTROL.test(value) || value.includes('\\') || value.startsWith('/')) return false;
82
+ return value.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
83
+ }
84
+
85
+ export function exactRecord(value, keys) {
86
+ if (value === null || typeof value !== 'object' || Array.isArray(value)
87
+ || Object.getPrototypeOf(value) !== Object.prototype) return false;
88
+ const actual = Object.keys(value).sort();
89
+ const expected = [...keys].sort();
90
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
91
+ }
92
+
93
+ function canonicalPart(value, seen, depth) {
94
+ if (depth > 40) throw new TypeError('todo artifact nesting limit exceeded');
95
+ if (value === null || typeof value === 'boolean') return JSON.stringify(value);
96
+ if (typeof value === 'string') return JSON.stringify(value);
97
+ if (typeof value === 'number') {
98
+ if (!Number.isFinite(value) || !Number.isSafeInteger(value) || Object.is(value, -0)) {
99
+ throw new TypeError('todo artifact number must be a safe integer');
100
+ }
101
+ return JSON.stringify(value);
102
+ }
103
+ if (typeof value !== 'object' || seen.has(value)) throw new TypeError('todo artifact is not a JSON tree');
104
+ seen.add(value);
105
+ let result;
106
+ if (Array.isArray(value)) {
107
+ if (Object.getPrototypeOf(value) !== Array.prototype
108
+ || Reflect.ownKeys(value).length !== value.length + 1) throw new TypeError('todo artifact array is not dense');
109
+ result = `[${value.map((entry) => canonicalPart(entry, seen, depth + 1)).join(',')}]`;
110
+ } else {
111
+ if (Object.getPrototypeOf(value) !== Object.prototype
112
+ || Reflect.ownKeys(value).some((key) => typeof key !== 'string')) throw new TypeError('todo artifact must use plain objects');
113
+ result = `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalPart(value[key], seen, depth + 1)}`).join(',')}}`;
114
+ }
115
+ seen.delete(value);
116
+ return result;
117
+ }
118
+
119
+ export function canonicalizeTodoArtifact(value) {
120
+ return canonicalPart(value, new Set(), 0);
121
+ }
122
+
123
+ export function digestTodoArtifact(value) {
124
+ return createHash('sha256').update(canonicalizeTodoArtifact(value), 'utf8').digest('hex');
125
+ }
126
+
127
+ export function todoSelfDigest(value, field) {
128
+ const projection = {};
129
+ for (const key of Object.keys(value)) if (key !== field) projection[key] = value[key];
130
+ return digestTodoArtifact(projection);
131
+ }
132
+
133
+ const noteBody = (value) => typeof value === 'string' && value.length > 0
134
+ && Buffer.byteLength(value, 'utf8') <= TODO_LIMITS.noteBodyBytes
135
+ && !NOTE_FORBIDDEN_CONTROL.test(value);
136
+
137
+ /**
138
+ * lifecycle journalとは独立したnote eventを検証する。v1(task note)とv2(plan note)は
139
+ * 別chainへ積まれるが、検証器は両方を受ける——どちらのchainを読んでいるかはpathが決め、
140
+ * chainへ他scopeが混ざっていないことは`readTodoNoteEvents`が読み出し時に落とす。
141
+ * v1は`scope`を持たない——定義上taskであり、投影の側で明示`scope`へ正規化する。
142
+ */
143
+ export function validateTodoNoteEvent(value) {
144
+ try {
145
+ const keys = [
146
+ 'schema', 'project_id', 'plan_key', 'task_id', 'plan_version', 'sequence',
147
+ 'previous_digest', 'actor', 'recorded_at', 'body', 'supersedes', 'event_digest',
148
+ ];
149
+ const planScoped = value?.schema === TODO_NOTE_EVENT_V2_SCHEMA;
150
+ return exactRecord(value, planScoped ? [...keys, 'scope'] : keys)
151
+ && (planScoped
152
+ // v2は今のところplan scopeだけを表す。phase scopeは配達面(audit_pending entry)を
153
+ // 持つtaskと同じ波で足す——書けるが届かない面を作らないため。
154
+ ? value.scope === 'plan' && value.task_id === null
155
+ : value.schema === TODO_NOTE_EVENT_SCHEMA && isTodoIdentifier(value.task_id))
156
+ && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
157
+ && isTodoIdentifier(value.plan_version)
158
+ && Number.isSafeInteger(value.sequence) && value.sequence >= 1
159
+ && (value.sequence === 1 ? value.previous_digest === null : isTodoDigest(value.previous_digest))
160
+ && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
161
+ && (value.supersedes === null || isTodoDigest(value.supersedes))
162
+ && isTodoDigest(value.event_digest) && value.supersedes !== value.event_digest
163
+ && value.event_digest === todoSelfDigest(value, 'event_digest');
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * `scope`は投影が必ず埋める。読み手はここでv1/v2の区別を持たないので、`origin_task_id`が
171
+ * nullであることから「plan単位だ」を推論させない——型で表現していない区別は、exact検証を
172
+ * 通り抜けて受け手の解釈に落ちる。
173
+ */
174
+ function noteContextEntry(value) {
175
+ return exactRecord(value, [
176
+ 'event_digest', 'origin_plan_version', 'scope', 'origin_task_id', 'actor', 'recorded_at',
177
+ 'body', 'supersedes', 'superseded_by', 'correction_state',
178
+ ]) && isTodoDigest(value.event_digest) && isTodoIdentifier(value.origin_plan_version)
179
+ && ['plan', 'task'].includes(value.scope)
180
+ && (value.scope === 'plan'
181
+ ? value.origin_task_id === null : isTodoIdentifier(value.origin_task_id))
182
+ && actor(value.actor)
183
+ && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
184
+ && (value.supersedes === null || isTodoDigest(value.supersedes))
185
+ && (value.superseded_by === null || isTodoDigest(value.superseded_by))
186
+ && ['current', 'superseded'].includes(value.correction_state)
187
+ && ((value.correction_state === 'current' && value.superseded_by === null)
188
+ || (value.correction_state === 'superseded' && isTodoDigest(value.superseded_by)));
189
+ }
190
+
191
+ /** 個別ToDo詳細とstart結果へ必ず同梱するbounded note contextを検証する。 */
192
+ export function validateTodoNoteContext(value) {
193
+ try {
194
+ if (!exactRecord(value, [
195
+ 'schema', 'project_id', 'plan_key', 'task_id', 'notes', 'note_head_digest',
196
+ 'plan_note_head_digest', 'overflow_count', 'full_history_command', 'context_digest',
197
+ ]) || value.schema !== TODO_NOTE_CONTEXT_SCHEMA
198
+ || !isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)
199
+ || !isTodoIdentifier(value.task_id) || !Array.isArray(value.notes)
200
+ || value.notes.length > TODO_LIMITS.tasksPerPlan || !value.notes.every(noteContextEntry)
201
+ || !(value.note_head_digest === null || isTodoDigest(value.note_head_digest))
202
+ || !(value.plan_note_head_digest === null || isTodoDigest(value.plan_note_head_digest))
203
+ || !isNonNegativeSafeInteger(value.overflow_count)
204
+ // contextはplan noteも載せるので、案内するのはplan全体を返す形でなければならない。
205
+ // `--task <id>`形はplan noteを落とすため、fullと名乗りながら全部を取りに行けなくなる。
206
+ || value.full_history_command !== `lattice todo note list --plan ${value.plan_key} --json`
207
+ || !isTodoDigest(value.context_digest)
208
+ || value.context_digest !== todoSelfDigest(value, 'context_digest')) return false;
209
+ // headはchainごとなので、同値もscopeで切る。task noteが空でplan noteが在る時に
210
+ // 「notesが非空なのにheadがnull」を壊れと読まないため。overflowで本文が落ちても
211
+ // headはchainの実在を述べ続ける——同値はnotesではなくoverflow込みの母集合で見る。
212
+ const scoped = (scope) => value.notes.some((note) => note.scope === scope);
213
+ if (value.overflow_count === 0) {
214
+ if (scoped('task') !== (value.note_head_digest !== null)) return false;
215
+ if (scoped('plan') !== (value.plan_note_head_digest !== null)) return false;
216
+ } else if (value.note_head_digest === null && value.plan_note_head_digest === null) {
217
+ return false;
218
+ }
219
+ return value.notes.reduce((bytes, note) => bytes + Buffer.byteLength(note.body, 'utf8'), 0)
220
+ <= TODO_LIMITS.noteContextBytes;
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+
226
+ const nullableDigest = (value) => value === null || isTodoDigest(value);
227
+ const nullableText = (value) => value === null || (typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 16_384);
228
+ /** 設計メモの拒否理由を、本文をerrorへ複製せずAIが訂正できる形で返す。 */
229
+ export function explainTodoDesignMemo(value) {
230
+ const expected = {
231
+ type: 'string', non_whitespace: true,
232
+ max_characters: TODO_LIMITS.noteBodyBytes, max_utf8_bytes: TODO_LIMITS.noteBodyBytes,
233
+ forbidden_control_characters: false,
234
+ };
235
+ if (typeof value !== 'string') {
236
+ return { valid: false, reason: 'type', expected,
237
+ actual: { type: value === null ? 'null' : typeof value } };
238
+ }
239
+ const byteLength = Buffer.byteLength(value, 'utf8');
240
+ if (value.trim().length === 0) {
241
+ return { valid: false, reason: 'blank', expected,
242
+ actual: { byte_length: byteLength, non_whitespace: false } };
243
+ }
244
+ if (value.length > TODO_LIMITS.noteBodyBytes || byteLength > TODO_LIMITS.noteBodyBytes) {
245
+ return { valid: false, reason: 'too_large', expected,
246
+ actual: { character_length: value.length, byte_length: byteLength } };
247
+ }
248
+ if (NOTE_FORBIDDEN_CONTROL.test(value)) {
249
+ return { valid: false, reason: 'forbidden_control', expected,
250
+ actual: { byte_length: byteLength, contains_forbidden_control: true } };
251
+ }
252
+ return { valid: true };
253
+ }
254
+
255
+ export const isTodoDesignMemo = (value) => explainTodoDesignMemo(value).valid;
256
+ const actor = (value) => exactRecord(value, ['host', 'session', 'agent'])
257
+ && [value.host, value.session, value.agent].every(isTodoIdentifier);
258
+ const provenance = (value) => value === null || (exactRecord(value, ['source_commit', 'source_event_digest'])
259
+ && /^[0-9a-f]{40}$/u.test(value.source_commit) && isTodoDigest(value.source_event_digest));
260
+ const nodeRef = (value) => (exactRecord(value, ['project_id', 'plan_key', 'task_id'])
261
+ || exactRecord(value, ['project_id', 'plan_key', 'task_id', 'expected_topology_digest']))
262
+ && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
263
+ && isTodoIdentifier(value.task_id)
264
+ && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
265
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
266
+ const refKey = (value) => `${value.project_id}\0${value.plan_key}\0${value.task_id}`;
267
+ const phaseRef = (value) => (exactRecord(value, ['project_id', 'plan_key', 'phase_id'])
268
+ || exactRecord(value, ['project_id', 'plan_key', 'phase_id', 'expected_topology_digest']))
269
+ && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
270
+ && isTodoIdentifier(value.phase_id)
271
+ && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
272
+ const phaseRefKey = (value) => `${value.project_id}\0${value.plan_key}\0${value.phase_id}`;
273
+
274
+ function compileBinding(value) {
275
+ return value === null || (exactRecord(value, [
276
+ 'boundary_manifest_digest', 'compiled_plan_digest', 'topology_digest', 'base_sha',
277
+ ]) && isTodoDigest(value.boundary_manifest_digest) && isTodoDigest(value.compiled_plan_digest)
278
+ && isTodoDigest(value.topology_digest) && /^[0-9a-f]{40}$/u.test(value.base_sha));
279
+ }
280
+
281
+ function taskV1(value) {
282
+ return exactRecord(value, ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding'])
283
+ && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
284
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref)) && compileBinding(value.compile_binding);
285
+ }
286
+
287
+ export function validateTodoNarrativeAnchor(value) {
288
+ return exactRecord(value, ['origin_plan_ref', 'origin_line', 'source_commit', 'source_line_digest'])
289
+ && isTodoRef(value.origin_plan_ref) && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
290
+ && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(value.source_commit)
291
+ && isTodoDigest(value.source_line_digest);
292
+ }
293
+
294
+ function taskV2(value) {
295
+ return exactRecord(value, [
296
+ 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
297
+ ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
298
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
299
+ && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
300
+ && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
301
+ && compileBinding(value.compile_binding);
302
+ }
303
+
304
+ function evidence(value) {
305
+ return exactRecord(value, [
306
+ 'evidence_id', 'repo_id', 'path', 'git_blob_oid', 'content_digest', 'media_type', 'anchor_digest',
307
+ ]) && isTodoIdentifier(value.evidence_id) && isTodoIdentifier(value.repo_id) && isTodoRef(value.path)
308
+ && /^[0-9a-f]{40,64}$/u.test(value.git_blob_oid) && isTodoDigest(value.content_digest)
309
+ && typeof value.media_type === 'string' && /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/u.test(value.media_type)
310
+ && nullableDigest(value.anchor_digest);
311
+ }
312
+
313
+ export function validateTodoImportSource(value) {
314
+ return exactRecord(value, ['schema', 'origin_plan_ref', 'origin_line', 'source_commit'])
315
+ && value.schema === 'lattice.todo_import_source.v1' && isTodoRef(value.origin_plan_ref)
316
+ && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
317
+ && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(value.source_commit);
318
+ }
319
+
320
+ function taskV3(value) {
321
+ return exactRecord(value, [
322
+ 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
323
+ 'parent_task_id',
324
+ ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
325
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
326
+ && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
327
+ && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
328
+ && compileBinding(value.compile_binding)
329
+ && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id));
330
+ }
331
+
332
+ function taskV4(value) {
333
+ return exactRecord(value, [
334
+ 'task_id', 'title', 'lane', 'narrative_ref', 'narrative_anchor', 'compile_binding',
335
+ 'parent_task_id', 'phase_id',
336
+ ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
337
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
338
+ && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
339
+ && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
340
+ && compileBinding(value.compile_binding)
341
+ && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
342
+ && isTodoIdentifier(value.phase_id);
343
+ }
344
+
345
+ function taskV5(value) {
346
+ return exactRecord(value, [
347
+ 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
348
+ 'compile_binding', 'parent_task_id',
349
+ ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
350
+ && isTodoDesignMemo(value.design_memo)
351
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
352
+ && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
353
+ && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
354
+ && compileBinding(value.compile_binding)
355
+ && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id));
356
+ }
357
+
358
+ function taskV6(value) {
359
+ return exactRecord(value, [
360
+ 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
361
+ 'compile_binding', 'parent_task_id', 'phase_id',
362
+ ]) && isTodoIdentifier(value.task_id) && nullableText(value.title) && isTodoIdentifier(value.lane)
363
+ && isTodoDesignMemo(value.design_memo)
364
+ && (value.narrative_ref === null || isTodoRef(value.narrative_ref))
365
+ && (value.narrative_anchor === null || (validateTodoNarrativeAnchor(value.narrative_anchor)
366
+ && value.narrative_ref === value.narrative_anchor.origin_plan_ref))
367
+ && compileBinding(value.compile_binding)
368
+ && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
369
+ && isTodoIdentifier(value.phase_id);
370
+ }
371
+
372
+ function phaseV1(value) {
373
+ return exactRecord(value, [
374
+ 'phase_id', 'title', 'gate_policy', 'predecessor_phase_ids', 'required_evidence_slots',
375
+ ]) && isTodoIdentifier(value.phase_id) && nullableText(value.title)
376
+ && isTodoIdentifier(value.gate_policy)
377
+ && Array.isArray(value.predecessor_phase_ids)
378
+ && value.predecessor_phase_ids.every(isTodoIdentifier)
379
+ && value.predecessor_phase_ids.every((entry, index) => index === 0
380
+ || compareText(value.predecessor_phase_ids[index - 1], entry) < 0)
381
+ && Array.isArray(value.required_evidence_slots) && value.required_evidence_slots.length > 0
382
+ && value.required_evidence_slots.every(isTodoIdentifier)
383
+ && value.required_evidence_slots.every((entry, index) => index === 0
384
+ || compareText(value.required_evidence_slots[index - 1], entry) < 0);
385
+ }
386
+
387
+ function validPhaseGraph(phases) {
388
+ const ids = new Set(phases.map(({ phase_id }) => phase_id));
389
+ const predecessors = new Map(phases.map(({ phase_id, predecessor_phase_ids }) => (
390
+ [phase_id, predecessor_phase_ids]
391
+ )));
392
+ if (phases.some(({ phase_id, predecessor_phase_ids }) => predecessor_phase_ids.includes(phase_id)
393
+ || predecessor_phase_ids.some((id) => !ids.has(id)))) return false;
394
+ const colors = new Map();
395
+ const visit = (id) => {
396
+ if (colors.get(id) === 1) return false;
397
+ if (colors.get(id) === 2) return true;
398
+ colors.set(id, 1);
399
+ if (!predecessors.get(id).every(visit)) return false;
400
+ colors.set(id, 2);
401
+ return true;
402
+ };
403
+ return [...ids].every(visit);
404
+ }
405
+
406
+ function validParentGraph(tasks) {
407
+ const parents = new Map(tasks.map(({ task_id, parent_task_id }) => [task_id, parent_task_id]));
408
+ for (const [taskId, parentTaskId] of parents) {
409
+ if (parentTaskId !== null && (parentTaskId === taskId || !parents.has(parentTaskId))) return false;
410
+ const seen = new Set([taskId]);
411
+ let cursor = parentTaskId;
412
+ while (cursor !== null) {
413
+ if (seen.has(cursor)) return false;
414
+ seen.add(cursor);
415
+ cursor = parents.get(cursor);
416
+ }
417
+ }
418
+ return true;
419
+ }
420
+
421
+ export function validateTodoPlan(value) {
422
+ try {
423
+ const taskValidator = value?.schema === 'lattice.todo_plan.v1' ? taskV1
424
+ : value?.schema === 'lattice.todo_plan.v2' ? taskV2
425
+ : value?.schema === 'lattice.todo_plan.v3' ? taskV3
426
+ : ['lattice.todo_plan.v4', 'lattice.todo_plan.v5'].includes(value?.schema) ? taskV4
427
+ : value?.schema === 'lattice.todo_plan.v6' ? taskV5
428
+ : value?.schema === 'lattice.todo_plan.v7' ? taskV6 : null;
429
+ const planKeys = [
430
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
431
+ 'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
432
+ ];
433
+ if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
434
+ .includes(value?.schema)) planKeys.push('phases');
435
+ if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema)) {
436
+ planKeys.push('phase_accept_dependencies');
437
+ }
438
+ if (!exactRecord(value, planKeys) || taskValidator === null || !isTodoIdentifier(value.project_id)
439
+ || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
440
+ || !nullableDigest(value.predecessor_plan_digest) || !Array.isArray(value.tasks)
441
+ || value.tasks.length === 0 || value.tasks.length > TODO_LIMITS.tasksPerPlan
442
+ || !value.tasks.every(taskValidator) || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
443
+ || !Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan
444
+ || !value.hard_dependencies.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
445
+ || !Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan
446
+ || !value.joins.every((join) => exactRecord(join, ['id', 'after', 'before']) && isTodoIdentifier(join.id)
447
+ && Array.isArray(join.after) && join.after.length > 0 && join.after.length <= TODO_LIMITS.tasksPerPlan
448
+ && join.after.every(nodeRef) && nodeRef(join.before))
449
+ || !isTodoDigest(value.topology_digest) || !isTodoDigest(value.plan_digest)
450
+ || (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
451
+ 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
452
+ && !validParentGraph(value.tasks))) return false;
453
+ if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
454
+ && (!Array.isArray(value.phases) || value.phases.length === 0
455
+ || value.phases.length > TODO_LIMITS.tasksPerPlan || !value.phases.every(phaseV1)
456
+ || value.phases.some((entry, index) => index > 0
457
+ && compareText(value.phases[index - 1].phase_id, entry.phase_id) >= 0)
458
+ || new Set(value.phases.map(({ phase_id }) => phase_id)).size !== value.phases.length
459
+ || value.tasks.some(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id))
460
+ || !validPhaseGraph(value.phases))) return false;
461
+ if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
462
+ && (!Array.isArray(value.phase_accept_dependencies)
463
+ || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan
464
+ || !value.phase_accept_dependencies.every((edge) => exactRecord(edge, ['from', 'to'])
465
+ && phaseRef(edge.from) && nodeRef(edge.to))
466
+ || value.phase_accept_dependencies.some((edge, index) => index > 0
467
+ && compareText(`${phaseRefKey(value.phase_accept_dependencies[index - 1].from)}\0${refKey(value.phase_accept_dependencies[index - 1].to)}`,
468
+ `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`) >= 0))) return false;
469
+ if (value.tasks.some((entry, index) => index > 0 && compareText(value.tasks[index - 1].task_id, entry.task_id) >= 0)
470
+ || value.hard_dependencies.some((edge, index) => index > 0
471
+ && compareText(`${refKey(value.hard_dependencies[index - 1].from)}\0${refKey(value.hard_dependencies[index - 1].to)}`,
472
+ `${refKey(edge.from)}\0${refKey(edge.to)}`) >= 0)
473
+ || value.joins.some((join, index) => index > 0 && compareText(value.joins[index - 1].id, join.id) >= 0)
474
+ || value.joins.some((join) => join.after.some((entry, index) => index > 0
475
+ && compareText(refKey(join.after[index - 1]), refKey(entry)) >= 0))) return false;
476
+ const topology = {
477
+ project_id: value.project_id, plan_key: value.plan_key, plan_version: value.plan_version,
478
+ tasks: value.tasks, hard_dependencies: value.hard_dependencies, joins: value.joins,
479
+ ...(['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
480
+ ? { phases: value.phases } : {}),
481
+ ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
482
+ ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
483
+ };
484
+ return value.topology_digest === digestTodoArtifact(topology)
485
+ && value.plan_digest === todoSelfDigest(value, 'plan_digest');
486
+ } catch { return false; }
487
+ }
488
+
489
+ export function validateEvidenceDescriptor(value) { return evidence(value); }
490
+
491
+ function validPayload(event) {
492
+ const payload = event.payload;
493
+ if (event.kind === 'plan_genesis') return (exactRecord(payload, [
494
+ 'plan_digest', 'topology_digest', 'predecessor_plan_digest', 'task_migration',
495
+ ]) || exactRecord(payload, [
496
+ 'plan_digest', 'topology_digest', 'predecessor_plan_digest', 'task_migration', 'historical_import',
497
+ ])) && (payload.historical_import === undefined || payload.historical_import === true)
498
+ && isTodoDigest(payload.plan_digest) && isTodoDigest(payload.topology_digest)
499
+ && nullableDigest(payload.predecessor_plan_digest) && Array.isArray(payload.task_migration)
500
+ && payload.task_migration.length <= TODO_LIMITS.tasksPerPlan
501
+ && payload.task_migration.every((entry) => exactRecord(entry, ['from_task_id', 'to_task_id'])
502
+ && isTodoIdentifier(entry.from_task_id) && (entry.to_task_id === 'removed' || isTodoIdentifier(entry.to_task_id)));
503
+ if (event.kind === 'start' && payload?.start_mode === 'historical_import') {
504
+ return exactRecord(payload, ['start_mode', 'imported', 'status', 'started_at', 'evidence'])
505
+ && payload.imported === true && payload.status === 'in-progress'
506
+ && (payload.started_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(payload.started_at))
507
+ && validateTodoImportSource(payload.evidence);
508
+ }
509
+ if (event.kind === 'coordination_mode') {
510
+ return exactRecord(payload, ['mode', 'reason'])
511
+ && TODO_COORDINATION_MODES.includes(payload.mode)
512
+ && nullableText(payload.reason) && payload.reason !== null;
513
+ }
514
+ if (event.kind === 'cross_plan_dependency') {
515
+ const dependencyRef = (value) => exactRecord(value, [
516
+ 'project_id', 'plan_key', 'task_id', 'expected_topology_digest',
517
+ ]) && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
518
+ && isTodoIdentifier(value.task_id) && isTodoDigest(value.expected_topology_digest);
519
+ return exactRecord(payload, ['from', 'to', 'reason'])
520
+ && dependencyRef(payload.from) && dependencyRef(payload.to)
521
+ && nullableText(payload.reason) && payload.reason !== null;
522
+ }
523
+ if (event.kind === 'start') return exactRecord(payload, ['override_reason']) && nullableText(payload.override_reason);
524
+ if (event.kind === 'start_retracted') return exactRecord(payload, ['reason', 'target_start_digest'])
525
+ && nullableText(payload.reason) && payload.reason !== null
526
+ && isTodoDigest(payload.target_start_digest);
527
+ if (event.kind === 'block') return exactRecord(payload, ['reason']) && nullableText(payload.reason) && payload.reason !== null;
528
+ if (event.kind === 'unblock') return exactRecord(payload, []);
529
+ if (event.kind === 'done' && payload?.done_mode === 'authored') {
530
+ return exactRecord(payload, ['done_mode', 'imported', 'evidence'])
531
+ && payload.imported === false && evidence(payload.evidence);
532
+ }
533
+ if (event.kind === 'done' && payload?.done_mode === 'historical_import') {
534
+ return exactRecord(payload, ['done_mode', 'imported', 'status', 'completed_at', 'evidence'])
535
+ && payload.imported === true && payload.status === 'done'
536
+ && (payload.completed_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(payload.completed_at))
537
+ && validateTodoImportSource(payload.evidence);
538
+ }
539
+ if (event.kind === 'done' && payload?.done_mode === 'evidence_promotion') {
540
+ return exactRecord(payload, ['done_mode', 'imported', 'target_done_digest', 'evidence'])
541
+ && payload.imported === true && isTodoDigest(payload.target_done_digest) && evidence(payload.evidence);
542
+ }
543
+ if (event.kind === 'reopen') return exactRecord(payload, ['reason', 'target_done_digest', 'override_reason'])
544
+ && nullableText(payload.reason) && payload.reason !== null && isTodoDigest(payload.target_done_digest)
545
+ && nullableText(payload.override_reason);
546
+ if (event.kind === 'phase_review') return exactRecord(payload, ['reason'])
547
+ && nullableText(payload.reason) && payload.reason !== null;
548
+ if (event.kind === 'phase_accept') return exactRecord(payload, [
549
+ 'review_event_digest', 'decision_evidence', 'evidence_slots',
550
+ ]) && isTodoDigest(payload.review_event_digest) && evidence(payload.decision_evidence)
551
+ && Array.isArray(payload.evidence_slots) && payload.evidence_slots.length > 0
552
+ && payload.evidence_slots.every((entry) => exactRecord(entry, ['slot_id', 'evidence'])
553
+ && isTodoIdentifier(entry.slot_id) && evidence(entry.evidence))
554
+ && payload.evidence_slots.every((entry, index) => index === 0
555
+ || compareText(payload.evidence_slots[index - 1].slot_id, entry.slot_id) < 0);
556
+ if (event.kind === 'phase_reject') return exactRecord(payload, [
557
+ 'review_event_digest', 'reason', 'decision_evidence',
558
+ ]) && isTodoDigest(payload.review_event_digest) && nullableText(payload.reason)
559
+ && payload.reason !== null && evidence(payload.decision_evidence);
560
+ if (event.kind === 'phase_reopen') return exactRecord(payload, [
561
+ 'reason', 'target_decision_digest', 'override_reason',
562
+ ]) && nullableText(payload.reason) && payload.reason !== null
563
+ && isTodoDigest(payload.target_decision_digest) && nullableText(payload.override_reason);
564
+ // ADR 0148裁定1: 監査なしで閉じたことの理由は必須(payload.reason !== null)。証拠は無い
565
+ // ——監査していないというのが事実であり、evidenceを要求すると「監査した体」を装う経路になる。
566
+ if (event.kind === 'phase_close_unaudited') return exactRecord(payload, ['reason'])
567
+ && nullableText(payload.reason) && payload.reason !== null;
568
+ return false;
569
+ }
570
+
571
+ function validCarriedState(value) {
572
+ if (!exactRecord(value, [
573
+ 'status', 'started_at', 'done_at', 'blocked_reason', 'evidence', 'imported',
574
+ ]) || !['pending', 'in-progress', 'blocked', 'done'].includes(value.status)
575
+ || (value.started_at !== null && !isStrictTodoTimestamp(value.started_at))
576
+ || (value.done_at !== null && !isStrictTodoTimestamp(value.done_at))
577
+ || (value.blocked_reason !== null && !nullableText(value.blocked_reason))
578
+ || typeof value.imported !== 'boolean') return false;
579
+ if (value.status === 'pending') return value.started_at === null && value.done_at === null
580
+ && value.blocked_reason === null && value.evidence === null && value.imported === false;
581
+ const activeEvidenceValid = value.imported
582
+ ? value.evidence === null || validateTodoImportSource(value.evidence)
583
+ : value.evidence === null;
584
+ if (value.status === 'in-progress') return value.done_at === null && value.blocked_reason === null
585
+ && activeEvidenceValid;
586
+ if (value.status === 'blocked') return value.done_at === null && value.blocked_reason !== null
587
+ && activeEvidenceValid;
588
+ return value.blocked_reason === null && value.evidence !== null
589
+ && (value.imported ? validateTodoImportSource(value.evidence) : evidence(value.evidence));
590
+ }
591
+
592
+ function validStateMigration(value) {
593
+ return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
594
+ && value.every((entry) => exactRecord(entry, [
595
+ 'from_task_id', 'to_task_id', 'state_policy', 'state',
596
+ ]) && isTodoIdentifier(entry.from_task_id)
597
+ && (entry.to_task_id === 'removed' || isTodoIdentifier(entry.to_task_id))
598
+ && ['carry', 'carry_reconciled_metadata', 'reset_pending', 'removed', 'acquire_phase'].includes(entry.state_policy)
599
+ && ((['carry', 'carry_reconciled_metadata', 'acquire_phase'].includes(entry.state_policy)
600
+ && entry.to_task_id !== 'removed' && validCarriedState(entry.state))
601
+ || (entry.state_policy === 'reset_pending' && entry.to_task_id !== 'removed' && entry.state === null)
602
+ || (entry.state_policy === 'removed' && entry.to_task_id === 'removed' && entry.state === null)))
603
+ && new Set(value.map(({ from_task_id }) => from_task_id)).size === value.length
604
+ && value.every((entry, index) => index === 0
605
+ || compareText(value[index - 1].from_task_id, entry.from_task_id) < 0);
606
+ }
607
+
608
+ function validPhaseStateMigration(value) {
609
+ return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
610
+ && value.every((entry) => exactRecord(entry, ['phase_id', 'state_policy', 'state'])
611
+ && isTodoIdentifier(entry.phase_id) && ['carry', 'reset'].includes(entry.state_policy)
612
+ && (entry.state_policy === 'reset' ? entry.state === null
613
+ : exactRecord(entry.state, [
614
+ 'status', 'review_event_digest', 'decision_event_digest', 'decision_evidence',
615
+ ]) && ['locked', 'active', 'gate_ready', 'reviewing', 'accepted', 'rejected', 'closed_unaudited']
616
+ .includes(entry.state.status)
617
+ && nullableDigest(entry.state.review_event_digest)
618
+ && nullableDigest(entry.state.decision_event_digest)
619
+ && (entry.state.decision_evidence === null || evidence(entry.state.decision_evidence))))
620
+ && value.every((entry, index) => index === 0
621
+ || compareText(value[index - 1].phase_id, entry.phase_id) < 0);
622
+ }
623
+
624
+ export function validateTodoEvent(value) {
625
+ try {
626
+ const commonKeys = [
627
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'sequence', 'previous_digest',
628
+ 'kind', 'task_id', 'actor', 'recorded_at', 'provenance', 'payload', 'event_digest',
629
+ ];
630
+ const v1 = value?.schema === 'lattice.todo_event.v1' && exactRecord(value, commonKeys);
631
+ const v2 = value?.schema === 'lattice.todo_event.v2' && exactRecord(value, [
632
+ ...commonKeys, 'reconciliation_state', 'revision_digest', 'reconciliation_digest',
633
+ 'state_migration',
634
+ ]) && value.kind === 'plan_genesis' && value.task_id === null
635
+ && value.reconciliation_state === 'reconciled' && isTodoDigest(value.revision_digest)
636
+ && isTodoDigest(value.reconciliation_digest) && validStateMigration(value.state_migration);
637
+ const v3 = value?.schema === 'lattice.todo_event.v3' && exactRecord(value, [
638
+ ...commonKeys, 'phase_id',
639
+ ]);
640
+ const v4 = value?.schema === 'lattice.todo_event.v4' && exactRecord(value, [
641
+ ...commonKeys, 'phase_id', 'revision_digest', 'state_migration', 'phase_state_migration',
642
+ ]) && value.kind === 'plan_genesis' && value.task_id === null && value.phase_id === null
643
+ && isTodoDigest(value.revision_digest) && validStateMigration(value.state_migration)
644
+ && validPhaseStateMigration(value.phase_state_migration);
645
+ const phaseKind = ['phase_review', 'phase_accept', 'phase_reject', 'phase_reopen', 'phase_close_unaudited']
646
+ .includes(value?.kind);
647
+ // planへ帰属するkindは、plan_genesisと同じくtask_idを持たない(v3/v4ではphase_idも持たない)。
648
+ // plan_genesisと違うのはjournalの途中に何度でも積めることで、最後の1件が現在の宣言になる。
649
+ const planScopedKind = TODO_PLAN_SCOPED_EVENT_KINDS.includes(value?.kind);
650
+ const planLevel = value?.kind === 'plan_genesis' || planScopedKind;
651
+ return (v1 || v2 || v3 || v4) && isTodoIdentifier(value.project_id)
652
+ && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.plan_version)
653
+ && isNonNegativeSafeInteger(value.sequence) && nullableDigest(value.previous_digest)
654
+ && TODO_EVENT_KINDS.includes(value.kind)
655
+ && (v3 || v4
656
+ ? ((planLevel && value.task_id === null && value.phase_id === null)
657
+ || (phaseKind && value.task_id === null && isTodoIdentifier(value.phase_id))
658
+ || (!phaseKind && !planLevel && isTodoIdentifier(value.task_id)
659
+ && value.phase_id === null))
660
+ : !phaseKind && ((planLevel && value.task_id === null)
661
+ || (!planLevel && isTodoIdentifier(value.task_id))))
662
+ && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && provenance(value.provenance)
663
+ && validPayload(value) && isTodoDigest(value.event_digest)
664
+ && value.event_digest === todoSelfDigest(value, 'event_digest');
665
+ } catch { return false; }
666
+ }
667
+
668
+ export function validateTodoManifest(value) {
669
+ try {
670
+ const manifestV1 = value?.schema === 'lattice.todo_manifest.v1';
671
+ const manifestV2 = value?.schema === 'lattice.todo_manifest.v2';
672
+ return exactRecord(value, ['schema', 'project_id', 'repositories', 'members', 'manifest_digest'])
673
+ && (manifestV1 || manifestV2) && isTodoIdentifier(value.project_id)
674
+ && Array.isArray(value.repositories) && value.repositories.length > 0 && value.repositories.length <= 256
675
+ && value.repositories.every((repo) => exactRecord(repo, ['repo_id', 'path'])
676
+ && isTodoIdentifier(repo.repo_id) && (repo.path === '.' || isTodoRef(repo.path)))
677
+ && new Set(value.repositories.map(({ repo_id }) => repo_id)).size === value.repositories.length
678
+ && value.repositories.every((repo, index) => index === 0 || value.repositories[index - 1].repo_id < repo.repo_id)
679
+ && Array.isArray(value.members) && value.members.length > 0 && value.members.length <= 256
680
+ && value.members.every((member) => exactRecord(member, [
681
+ 'plan_key', 'active_plan_version', 'plan_ref', 'journal_ref', 'snapshot_ref',
682
+ 'topology_digest', 'journal_head_digest', ...(manifestV2 ? ['active_revision_digest'] : []),
683
+ ]) && isTodoIdentifier(member.plan_key) && isTodoIdentifier(member.active_plan_version)
684
+ && isTodoRef(member.plan_ref) && isTodoRef(member.journal_ref) && isTodoRef(member.snapshot_ref)
685
+ && isTodoDigest(member.topology_digest) && isTodoDigest(member.journal_head_digest)
686
+ && (!manifestV2 || isTodoDigest(member.active_revision_digest)))
687
+ && value.members.every((member, index) => index === 0 || value.members[index - 1].plan_key < member.plan_key)
688
+ && new Set(value.members.map(({ plan_key }) => plan_key)).size === value.members.length
689
+ && isTodoDigest(value.manifest_digest) && value.manifest_digest === todoSelfDigest(value, 'manifest_digest');
690
+ } catch { return false; }
691
+ }
692
+
693
+ export function validateTodoSnapshot(value) {
694
+ try {
695
+ const v1 = value?.schema === 'lattice.todo_snapshot.v1' && exactRecord(value, [
696
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'projection_version', 'through_sequence',
697
+ 'journal_head_digest', 'tasks', 'snapshot_digest',
698
+ ]);
699
+ const v2 = value?.schema === 'lattice.todo_snapshot.v2' && exactRecord(value, [
700
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'projection_version', 'through_sequence',
701
+ 'journal_head_digest', 'tasks', 'phases', 'snapshot_digest',
702
+ ]);
703
+ return (v1 || v2) && isTodoIdentifier(value.project_id)
704
+ && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.plan_version)
705
+ && value.projection_version === (v1 ? 1 : 2) && isNonNegativeSafeInteger(value.through_sequence)
706
+ && isTodoDigest(value.journal_head_digest) && Array.isArray(value.tasks)
707
+ && value.tasks.length > 0 && value.tasks.length <= TODO_LIMITS.tasksPerPlan
708
+ && value.tasks.every((entry) => exactRecord(entry, [
709
+ 'task_id', 'status', 'started_at', 'done_at', 'blocked_reason', 'evidence', 'evidence_unverified', 'imported',
710
+ ]) && isTodoIdentifier(entry.task_id) && ['pending', 'in-progress', 'blocked', 'done'].includes(entry.status)
711
+ && (entry.started_at === null || isStrictTodoTimestamp(entry.started_at))
712
+ && (entry.done_at === null || isStrictTodoTimestamp(entry.done_at)) && nullableText(entry.blocked_reason)
713
+ && (entry.evidence === null || evidence(entry.evidence) || validateTodoImportSource(entry.evidence))
714
+ && typeof entry.evidence_unverified === 'boolean' && typeof entry.imported === 'boolean')
715
+ && value.tasks.every((entry, index) => index === 0 || value.tasks[index - 1].task_id < entry.task_id)
716
+ && (!v2 || (Array.isArray(value.phases) && value.phases.length > 0
717
+ && value.phases.every((entry) => exactRecord(entry, [
718
+ 'phase_id', 'status', 'review_event_digest', 'decision_event_digest', 'decision_evidence',
719
+ ]) && isTodoIdentifier(entry.phase_id)
720
+ && ['locked', 'active', 'gate_ready', 'reviewing', 'accepted', 'rejected', 'closed_unaudited']
721
+ .includes(entry.status)
722
+ && nullableDigest(entry.review_event_digest) && nullableDigest(entry.decision_event_digest)
723
+ && (entry.decision_evidence === null || evidence(entry.decision_evidence)))
724
+ && value.phases.every((entry, index) => index === 0
725
+ || value.phases[index - 1].phase_id < entry.phase_id)))
726
+ && isTodoDigest(value.snapshot_digest) && value.snapshot_digest === todoSelfDigest(value, 'snapshot_digest');
727
+ } catch { return false; }
728
+ }