@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,448 +1,448 @@
1
- import {
2
- TODO_LIMITS,
3
- exactRecord,
4
- isStrictTodoTimestamp,
5
- isTodoDigest,
6
- isTodoDesignMemo,
7
- isTodoIdentifier,
8
- isTodoRef,
9
- todoSelfDigest,
10
- } from './todo-contracts.mjs';
11
- import {
12
- TodoStoreError,
13
- appendImportedPlan,
14
- createTodoStoreWriter,
15
- } from './todo-store.mjs';
16
-
17
- export const TODO_EXTRACTION_SCHEMA = 'lattice.todo_extraction.v1';
18
- export const TODO_EXTRACTION_SCHEMA_V2 = 'lattice.todo_extraction.v2';
19
- export const TODO_EXTRACTION_SCHEMA_V3 = 'lattice.todo_extraction.v3';
20
-
21
- const V1_DISPOSITIONS = new Set([
22
- 'register_pending',
23
- 'register_done',
24
- 'exclude_superseded',
25
- 'exclude_compatibility_record',
26
- 'unknown_requires_evidence',
27
- ]);
28
- const V2_DISPOSITIONS = new Set([...V1_DISPOSITIONS, 'register_in_progress']);
29
- const CHECKBOX_STATES = new Set(['checked', 'unchecked', 'absent', 'ambiguous']);
30
- const COMMIT_OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
31
-
32
- function boundedText(value, maximumBytes = 16_384) {
33
- return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= maximumBytes;
34
- }
35
-
36
- function nullableText(value) {
37
- return value === null || boundedText(value);
38
- }
39
-
40
- function actor(value) {
41
- return exactRecord(value, ['host', 'session', 'agent'])
42
- && [value.host, value.session, value.agent].every(isTodoIdentifier);
43
- }
44
-
45
- function nodeRef(value) {
46
- return (exactRecord(value, ['project_id', 'plan_key', 'task_id'])
47
- || exactRecord(value, ['project_id', 'plan_key', 'task_id', 'expected_topology_digest']))
48
- && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
49
- && isTodoIdentifier(value.task_id)
50
- && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
51
- }
52
-
53
- function refKey(value) {
54
- return `${value.project_id}\0${value.plan_key}\0${value.task_id}`;
55
- }
56
-
57
- function sortedStrictly(values, key = (value) => value) {
58
- return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
59
- }
60
-
61
- function sourceLocation(value) {
62
- return exactRecord(value, [
63
- 'origin_plan_ref', 'origin_line', 'source_commit', 'heading_path', 'markdown_depth',
64
- 'parent_task_id', 'checkbox_state',
65
- ]) && isTodoRef(value.origin_plan_ref) && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
66
- && COMMIT_OID.test(value.source_commit)
67
- && Array.isArray(value.heading_path) && value.heading_path.length <= 32
68
- && value.heading_path.every((part) => boundedText(part, 1_024))
69
- && Number.isSafeInteger(value.markdown_depth) && value.markdown_depth >= 0 && value.markdown_depth <= 64
70
- && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
71
- && CHECKBOX_STATES.has(value.checkbox_state);
72
- }
73
-
74
- function migrationContext(value) {
75
- return exactRecord(value, [
76
- 'external_canonical_ref', 'carry_over_ref', 'h_required', 'condition', 'evidence_refs', 'notes',
77
- ]) && nullableText(value.external_canonical_ref) && nullableText(value.carry_over_ref)
78
- && typeof value.h_required === 'boolean' && nullableText(value.condition)
79
- && Array.isArray(value.evidence_refs) && value.evidence_refs.length <= 64
80
- && value.evidence_refs.every((entry) => boundedText(entry, 4_096))
81
- && Array.isArray(value.notes) && value.notes.length <= 64
82
- && value.notes.every((entry) => boundedText(entry, 4_096));
83
- }
84
-
85
- function completion(value) {
86
- return exactRecord(value, ['done_mode', 'completed_at'])
87
- && value.done_mode === 'historical_import'
88
- && (value.completed_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(value.completed_at));
89
- }
90
-
91
- function historicalStart(value) {
92
- return exactRecord(value, ['start_mode', 'status', 'started_at'])
93
- && value.start_mode === 'historical_import' && value.status === 'in-progress'
94
- && (value.started_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(value.started_at));
95
- }
96
-
97
- function extractionTask(value, schema) {
98
- const v2 = [TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema);
99
- const v3 = schema === TODO_EXTRACTION_SCHEMA_V3;
100
- const keys = [
101
- 'task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
102
- 'completion', 'source', 'migration_context',
103
- ];
104
- if (v2) keys.push('start');
105
- if (v3) keys.push('design_memo');
106
- if (!exactRecord(value, keys) || !isTodoIdentifier(value.task_id) || !boundedText(value.title)
107
- || !isTodoIdentifier(value.lane) || (value.narrative_ref !== null && !isTodoRef(value.narrative_ref))
108
- || (v3 && !isTodoDesignMemo(value.design_memo))
109
- || value.compile_binding !== null || !(v2 ? V2_DISPOSITIONS : V1_DISPOSITIONS).has(value.disposition)
110
- || !sourceLocation(value.source) || !migrationContext(value.migration_context)) return false;
111
- if (!v2) return value.disposition === 'register_done' ? completion(value.completion) : value.completion === null;
112
- if (value.disposition === 'register_done') return value.start === null && completion(value.completion);
113
- if (value.disposition === 'register_in_progress') {
114
- return historicalStart(value.start) && value.completion === null;
115
- }
116
- return value.start === null && value.completion === null;
117
- }
118
-
119
- function validateEdges(value) {
120
- return Array.isArray(value) && value.length <= TODO_LIMITS.edgesPerPlan
121
- && value.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
122
- && sortedStrictly(value, (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`);
123
- }
124
-
125
- function validateJoins(value) {
126
- return Array.isArray(value) && value.length <= TODO_LIMITS.joinsPerPlan
127
- && value.every((join) => exactRecord(join, ['id', 'after', 'before'])
128
- && isTodoIdentifier(join.id) && Array.isArray(join.after) && join.after.length > 0
129
- && join.after.length <= TODO_LIMITS.tasksPerPlan && join.after.every(nodeRef)
130
- && sortedStrictly(join.after, refKey) && nodeRef(join.before))
131
- && sortedStrictly(value, (join) => join.id);
132
- }
133
-
134
- const reject = (reason, path = '', detail = {}) => ({ valid: false, reason, path, ...detail });
135
-
136
- /** value自体がexactRecordの対象になれる素朴なobjectかどうか(配列・nullを除く)。 */
137
- function plainObject(value) {
138
- return value !== null && typeof value === 'object' && !Array.isArray(value);
139
- }
140
-
141
- /**
142
- * 期待keyとの過不足を1件ずつ言い当てる。missing/unexpectedのどちらが先に見つかっても
143
- * そこで止め、複数の欠落を一度に説明しない——`exactRecord`のbooleanと違い、
144
- * 最初に見つかった違反fieldをpathへ刻む。
145
- */
146
- function explainKeys(value, requiredKeys, at) {
147
- if (!plainObject(value) || Object.getPrototypeOf(value) !== Object.prototype) {
148
- return reject('not_an_object', at);
149
- }
150
- const actualKeys = new Set(Object.keys(value));
151
- for (const key of requiredKeys) {
152
- if (!actualKeys.has(key)) return reject('missing_required_key', `${at}/${key}`);
153
- }
154
- const requiredSet = new Set(requiredKeys);
155
- for (const key of actualKeys) {
156
- if (!requiredSet.has(key)) return reject('unexpected_key', `${at}/${key}`);
157
- }
158
- return { valid: true };
159
- }
160
-
161
- function explainSortedStrictly(values, key, at) {
162
- for (let index = 1; index < values.length; index += 1) {
163
- if (!(key(values[index - 1]) < key(values[index]))) {
164
- return reject('unsorted_or_duplicate_collection', `${at}/${index}`);
165
- }
166
- }
167
- return { valid: true };
168
- }
169
-
170
- /**
171
- * `lattice.todo_extraction.v1/v2`を、既存の`validateTodoExtraction`の可否は変えずに
172
- * 診断する(ADR 0130の案内規律をmigration入口へ拡張)。
173
- *
174
- * 深いgraph整合(親task解決・edge/join local参照解決)はここでは個別に言い当てず、
175
- * 単一のreasonへ丸める——既知の実運用の詰まりどころ(必須key欠落・task/edge/joinの
176
- * ソート違反・digest不一致)を優先して解消する。それでも掴めない違反は
177
- * `diagnosis_incomplete`として正直に返す。
178
- */
179
- export function explainTodoExtraction(value) {
180
- try {
181
- if (!plainObject(value)) return reject('not_an_object', '');
182
- const schema = value.schema;
183
- if (![TODO_EXTRACTION_SCHEMA, TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema)) {
184
- return reject('schema_mismatch', '/schema', {
185
- expected: TODO_EXTRACTION_SCHEMA_V3, actual: typeof schema === 'string' ? schema : null,
186
- });
187
- }
188
- const v2 = [TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema);
189
- const v3 = schema === TODO_EXTRACTION_SCHEMA_V3;
190
- const topKeys = [
191
- 'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
192
- 'tasks', 'hard_dependencies', 'joins', 'extraction_digest',
193
- ];
194
- const topKeyCheck = explainKeys(value, topKeys, '');
195
- if (!topKeyCheck.valid) return topKeyCheck;
196
- if (!isTodoIdentifier(value.project_id)) return reject('invalid_identifier', '/project_id');
197
- if (!isTodoIdentifier(value.plan_key)) return reject('invalid_identifier', '/plan_key');
198
- if (!isTodoIdentifier(value.plan_version)) return reject('invalid_identifier', '/plan_version');
199
- if (!actor(value.actor)) return reject('invalid_actor', '/actor');
200
- if (!isStrictTodoTimestamp(value.recorded_at)) return reject('invalid_timestamp', '/recorded_at');
201
- if (!Array.isArray(value.tasks) || value.tasks.length === 0
202
- || value.tasks.length > TODO_LIMITS.tasksPerPlan) {
203
- return reject('bounded_collection_violation', '/tasks');
204
- }
205
- const taskKeys = v2
206
- ? ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
207
- 'start', 'completion', 'source', 'migration_context']
208
- : ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
209
- 'completion', 'source', 'migration_context'];
210
- if (v3) taskKeys.push('design_memo');
211
- for (const [index, task] of value.tasks.entries()) {
212
- const taskKeyCheck = explainKeys(task, taskKeys, `/tasks/${index}`);
213
- if (!taskKeyCheck.valid) return taskKeyCheck;
214
- if (v3 && !isTodoDesignMemo(task.design_memo)) {
215
- return reject('design_memo_required', `/tasks/${index}/design_memo`, {
216
- task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
217
- expected: 'non-empty Markdown or NO_PLAN',
218
- });
219
- }
220
- if (task.disposition === 'register_done'
221
- && task.completion?.done_mode !== 'historical_import') {
222
- return reject('enum_mismatch', `/tasks/${index}/completion/done_mode`, {
223
- task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
224
- expected: 'historical_import', actual: task.completion?.done_mode ?? null,
225
- });
226
- }
227
- if (!Array.isArray(task.migration_context?.notes)) {
228
- return reject('expected_array', `/tasks/${index}/migration_context/notes`, {
229
- task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
230
- expected: 'array', actual: typeof task.migration_context?.notes,
231
- });
232
- }
233
- if (!extractionTask(task, schema)) {
234
- return reject('task_shape_invalid', `/tasks/${index}`, {
235
- task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
236
- });
237
- }
238
- }
239
- const sortCheck = explainSortedStrictly(value.tasks, (task) => task.task_id, '/tasks');
240
- if (!sortCheck.valid) return sortCheck;
241
- if (new Set(value.tasks.map(({ task_id: taskId }) => taskId)).size !== value.tasks.length) {
242
- return reject('duplicate_task_id', '/tasks');
243
- }
244
- if (!validateEdges(value.hard_dependencies)) return reject('hard_dependencies_invalid', '/hard_dependencies');
245
- if (!validateJoins(value.joins)) return reject('joins_invalid', '/joins');
246
- if (!isTodoDigest(value.extraction_digest)) return reject('invalid_digest', '/extraction_digest');
247
- const expectedDigest = todoSelfDigest(value, 'extraction_digest');
248
- if (value.extraction_digest !== expectedDigest) {
249
- return reject('extraction_digest_mismatch', '/extraction_digest', {
250
- expected: expectedDigest, actual: value.extraction_digest,
251
- });
252
- }
253
- const taskIds = new Set(value.tasks.map(({ task_id: taskId }) => taskId));
254
- const badParent = value.tasks.find((task) => task.source.parent_task_id === task.task_id
255
- || (task.source.parent_task_id !== null && !taskIds.has(task.source.parent_task_id)));
256
- if (badParent !== undefined) {
257
- return reject('parent_task_id_unresolved',
258
- `/tasks/${value.tasks.indexOf(badParent)}/source/parent_task_id`);
259
- }
260
- const excluded = new Set(value.tasks
261
- .filter((task) => task.disposition.startsWith('exclude_'))
262
- .map(({ task_id }) => task_id));
263
- const excludedParent = value.tasks.find((task) => task.disposition.startsWith('register_')
264
- && task.source.parent_task_id !== null && excluded.has(task.source.parent_task_id));
265
- if (excludedParent !== undefined) {
266
- return reject('registered_parent_task_id_unresolved',
267
- `/tasks/${value.tasks.indexOf(excludedParent)}/source/parent_task_id`, {
268
- task_id: excludedParent.task_id,
269
- expected: 'task_id not excluded from the compiled plan',
270
- actual: excludedParent.source.parent_task_id,
271
- });
272
- }
273
- const localRefViolation = firstUnregisteredLocalRef(value);
274
- if (localRefViolation !== null) {
275
- return reject('local_ref_unresolved', localRefViolation.path, {
276
- task_id: localRefViolation.task_id,
277
- expected: 'registered task_id', actual: localRefViolation.task_id,
278
- });
279
- }
280
- // ここまでの個別検査を全て通過したのに`validateTodoExtraction`がfalseを返す状況は、
281
- // このexplainがまだ言い当てられない違反があるということ。捏造せず未特定と申告する。
282
- return { valid: true };
283
- } catch {
284
- return reject('diagnosis_failed', '');
285
- }
286
- }
287
-
288
- function registeredTaskIds(value) {
289
- return new Set(value.tasks
290
- .filter(({ disposition }) => disposition.startsWith('register_'))
291
- .map(({ task_id }) => task_id));
292
- }
293
-
294
- function localRefsResolve(value) {
295
- return firstUnregisteredLocalRef(value) === null;
296
- }
297
-
298
- function firstUnregisteredLocalRef(value) {
299
- const registered = registeredTaskIds(value);
300
- const unresolved = (ref) => ref.project_id === value.project_id && ref.plan_key === value.plan_key
301
- && !registered.has(ref.task_id);
302
- for (const [index, edge] of value.hard_dependencies.entries()) {
303
- if (unresolved(edge.from)) return { path: `/hard_dependencies/${index}/from`, task_id: edge.from.task_id };
304
- if (unresolved(edge.to)) return { path: `/hard_dependencies/${index}/to`, task_id: edge.to.task_id };
305
- }
306
- for (const [index, join] of value.joins.entries()) {
307
- if (unresolved(join.before)) return { path: `/joins/${index}/before`, task_id: join.before.task_id };
308
- const afterIndex = join.after.findIndex(unresolved);
309
- if (afterIndex >= 0) {
310
- return { path: `/joins/${index}/after/${afterIndex}`, task_id: join.after[afterIndex].task_id };
311
- }
312
- }
313
- return null;
314
- }
315
-
316
- /** Exact, bounded validation for the AI-authored G4 intermediate artifact. */
317
- export function validateTodoExtraction(value) {
318
- try {
319
- const schema = value?.schema;
320
- if (!exactRecord(value, [
321
- 'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
322
- 'tasks', 'hard_dependencies', 'joins', 'extraction_digest',
323
- ]) || ![TODO_EXTRACTION_SCHEMA, TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema)
324
- || !isTodoIdentifier(value.project_id)
325
- || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
326
- || !actor(value.actor) || !isStrictTodoTimestamp(value.recorded_at)
327
- || !Array.isArray(value.tasks) || value.tasks.length === 0
328
- || value.tasks.length > TODO_LIMITS.tasksPerPlan
329
- || !value.tasks.every((task) => extractionTask(task, schema))
330
- || !sortedStrictly(value.tasks, (task) => task.task_id)
331
- || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
332
- || !validateEdges(value.hard_dependencies) || !validateJoins(value.joins)
333
- || !isTodoDigest(value.extraction_digest)
334
- || value.extraction_digest !== todoSelfDigest(value, 'extraction_digest')) return false;
335
-
336
- const taskIds = new Set(value.tasks.map(({ task_id }) => task_id));
337
- if (value.tasks.some((task) => task.source.parent_task_id === task.task_id
338
- || (task.source.parent_task_id !== null && !taskIds.has(task.source.parent_task_id)))) return false;
339
- const excluded = new Set(value.tasks
340
- .filter((task) => task.disposition.startsWith('exclude_'))
341
- .map(({ task_id }) => task_id));
342
- if (value.tasks.some((task) => task.disposition.startsWith('register_')
343
- && task.source.parent_task_id !== null && excluded.has(task.source.parent_task_id))) return false;
344
- return localRefsResolve(value);
345
- } catch {
346
- return false;
347
- }
348
- }
349
-
350
- export function todoExtractionImportSource(task) {
351
- return {
352
- schema: 'lattice.todo_import_source.v1',
353
- origin_plan_ref: task.source.origin_plan_ref,
354
- origin_line: task.source.origin_line,
355
- source_commit: task.source.source_commit,
356
- };
357
- }
358
-
359
- /**
360
- * Translate an already-extracted artifact into appendImportedPlan input.
361
- * Source locations are passed to the importer but no Markdown is read here.
362
- * Unresolved records stop the whole transaction so the owner can adjudicate
363
- * the JSON and rerun the same command.
364
- */
365
- export function compileTodoExtraction(value, repoRoot) {
366
- if (!validateTodoExtraction(value)) {
367
- const explained = explainTodoExtraction(value);
368
- throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined,
369
- explained.valid ? undefined : {
370
- violation_reason: explained.reason, violation_path: explained.path,
371
- ...(explained.task_id === undefined ? {} : { task_id: explained.task_id }),
372
- });
373
- }
374
- const unresolved = value.tasks
375
- .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
376
- .map(({ task_id }) => task_id);
377
- if (unresolved.length > 0) {
378
- throw new TodoStoreError('MIGRATION_UNRESOLVED', 'unknown_requires_evidence', undefined, {
379
- task_ids: unresolved,
380
- });
381
- }
382
-
383
- const registered = value.tasks.filter(({ disposition }) => disposition.startsWith('register_'));
384
- if (registered.length === 0) {
385
- throw new TodoStoreError('MIGRATION_EMPTY', 'no_registered_tasks');
386
- }
387
- return {
388
- repoRoot,
389
- writer: createTodoStoreWriter({ caller: 'g4-migration' }),
390
- initializeIfMissing: {
391
- projectId: value.project_id,
392
- repositories: [{ repo_id: 'self', path: '.' }],
393
- },
394
- plan: {
395
- schema: value.schema === TODO_EXTRACTION_SCHEMA_V3
396
- ? 'lattice.todo_plan.v6' : 'lattice.todo_plan.v2',
397
- project_id: value.project_id,
398
- plan_key: value.plan_key,
399
- plan_version: value.plan_version,
400
- predecessor_plan_digest: null,
401
- tasks: registered.map((task) => ({
402
- task_id: task.task_id,
403
- title: task.title,
404
- lane: task.lane,
405
- ...(value.schema === TODO_EXTRACTION_SCHEMA_V3
406
- ? { design_memo: task.design_memo } : {}),
407
- narrative_ref: task.narrative_ref,
408
- narrative_anchor: null,
409
- compile_binding: null,
410
- ...(value.schema === TODO_EXTRACTION_SCHEMA_V3
411
- ? { parent_task_id: task.source.parent_task_id } : {}),
412
- })),
413
- hard_dependencies: value.hard_dependencies,
414
- joins: value.joins,
415
- },
416
- narrativeAnchorSources: registered.map((task) => ({
417
- task_id: task.task_id,
418
- origin_plan_ref: task.source.origin_plan_ref,
419
- origin_line: task.source.origin_line,
420
- source_commit: task.source.source_commit,
421
- checkbox_state: task.source.checkbox_state,
422
- })),
423
- genesis: {
424
- actor: value.actor,
425
- recorded_at: value.recorded_at,
426
- provenance: null,
427
- },
428
- completedTasks: registered
429
- .filter(({ disposition }) => disposition === 'register_done')
430
- .map((task) => ({
431
- task_id: task.task_id,
432
- completed_at: task.completion.completed_at,
433
- evidence: todoExtractionImportSource(task),
434
- })),
435
- inProgressTasks: registered
436
- .filter(({ disposition }) => disposition === 'register_in_progress')
437
- .map((task) => ({
438
- task_id: task.task_id,
439
- started_at: task.start.started_at,
440
- evidence: todoExtractionImportSource(task),
441
- })),
442
- };
443
- }
444
-
445
- export async function appendTodoExtraction({ repoRoot, extraction }) {
446
- const request = compileTodoExtraction(extraction, repoRoot);
447
- return appendImportedPlan(request);
448
- }
1
+ import {
2
+ TODO_LIMITS,
3
+ exactRecord,
4
+ isStrictTodoTimestamp,
5
+ isTodoDigest,
6
+ isTodoDesignMemo,
7
+ isTodoIdentifier,
8
+ isTodoRef,
9
+ todoSelfDigest,
10
+ } from './todo-contracts.mjs';
11
+ import {
12
+ TodoStoreError,
13
+ appendImportedPlan,
14
+ createTodoStoreWriter,
15
+ } from './todo-store.mjs';
16
+
17
+ export const TODO_EXTRACTION_SCHEMA = 'lattice.todo_extraction.v1';
18
+ export const TODO_EXTRACTION_SCHEMA_V2 = 'lattice.todo_extraction.v2';
19
+ export const TODO_EXTRACTION_SCHEMA_V3 = 'lattice.todo_extraction.v3';
20
+
21
+ const V1_DISPOSITIONS = new Set([
22
+ 'register_pending',
23
+ 'register_done',
24
+ 'exclude_superseded',
25
+ 'exclude_compatibility_record',
26
+ 'unknown_requires_evidence',
27
+ ]);
28
+ const V2_DISPOSITIONS = new Set([...V1_DISPOSITIONS, 'register_in_progress']);
29
+ const CHECKBOX_STATES = new Set(['checked', 'unchecked', 'absent', 'ambiguous']);
30
+ const COMMIT_OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
31
+
32
+ function boundedText(value, maximumBytes = 16_384) {
33
+ return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= maximumBytes;
34
+ }
35
+
36
+ function nullableText(value) {
37
+ return value === null || boundedText(value);
38
+ }
39
+
40
+ function actor(value) {
41
+ return exactRecord(value, ['host', 'session', 'agent'])
42
+ && [value.host, value.session, value.agent].every(isTodoIdentifier);
43
+ }
44
+
45
+ function nodeRef(value) {
46
+ return (exactRecord(value, ['project_id', 'plan_key', 'task_id'])
47
+ || exactRecord(value, ['project_id', 'plan_key', 'task_id', 'expected_topology_digest']))
48
+ && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
49
+ && isTodoIdentifier(value.task_id)
50
+ && (value.expected_topology_digest === undefined || isTodoDigest(value.expected_topology_digest));
51
+ }
52
+
53
+ function refKey(value) {
54
+ return `${value.project_id}\0${value.plan_key}\0${value.task_id}`;
55
+ }
56
+
57
+ function sortedStrictly(values, key = (value) => value) {
58
+ return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
59
+ }
60
+
61
+ function sourceLocation(value) {
62
+ return exactRecord(value, [
63
+ 'origin_plan_ref', 'origin_line', 'source_commit', 'heading_path', 'markdown_depth',
64
+ 'parent_task_id', 'checkbox_state',
65
+ ]) && isTodoRef(value.origin_plan_ref) && Number.isSafeInteger(value.origin_line) && value.origin_line >= 1
66
+ && COMMIT_OID.test(value.source_commit)
67
+ && Array.isArray(value.heading_path) && value.heading_path.length <= 32
68
+ && value.heading_path.every((part) => boundedText(part, 1_024))
69
+ && Number.isSafeInteger(value.markdown_depth) && value.markdown_depth >= 0 && value.markdown_depth <= 64
70
+ && (value.parent_task_id === null || isTodoIdentifier(value.parent_task_id))
71
+ && CHECKBOX_STATES.has(value.checkbox_state);
72
+ }
73
+
74
+ function migrationContext(value) {
75
+ return exactRecord(value, [
76
+ 'external_canonical_ref', 'carry_over_ref', 'h_required', 'condition', 'evidence_refs', 'notes',
77
+ ]) && nullableText(value.external_canonical_ref) && nullableText(value.carry_over_ref)
78
+ && typeof value.h_required === 'boolean' && nullableText(value.condition)
79
+ && Array.isArray(value.evidence_refs) && value.evidence_refs.length <= 64
80
+ && value.evidence_refs.every((entry) => boundedText(entry, 4_096))
81
+ && Array.isArray(value.notes) && value.notes.length <= 64
82
+ && value.notes.every((entry) => boundedText(entry, 4_096));
83
+ }
84
+
85
+ function completion(value) {
86
+ return exactRecord(value, ['done_mode', 'completed_at'])
87
+ && value.done_mode === 'historical_import'
88
+ && (value.completed_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(value.completed_at));
89
+ }
90
+
91
+ function historicalStart(value) {
92
+ return exactRecord(value, ['start_mode', 'status', 'started_at'])
93
+ && value.start_mode === 'historical_import' && value.status === 'in-progress'
94
+ && (value.started_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(value.started_at));
95
+ }
96
+
97
+ function extractionTask(value, schema) {
98
+ const v2 = [TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema);
99
+ const v3 = schema === TODO_EXTRACTION_SCHEMA_V3;
100
+ const keys = [
101
+ 'task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
102
+ 'completion', 'source', 'migration_context',
103
+ ];
104
+ if (v2) keys.push('start');
105
+ if (v3) keys.push('design_memo');
106
+ if (!exactRecord(value, keys) || !isTodoIdentifier(value.task_id) || !boundedText(value.title)
107
+ || !isTodoIdentifier(value.lane) || (value.narrative_ref !== null && !isTodoRef(value.narrative_ref))
108
+ || (v3 && !isTodoDesignMemo(value.design_memo))
109
+ || value.compile_binding !== null || !(v2 ? V2_DISPOSITIONS : V1_DISPOSITIONS).has(value.disposition)
110
+ || !sourceLocation(value.source) || !migrationContext(value.migration_context)) return false;
111
+ if (!v2) return value.disposition === 'register_done' ? completion(value.completion) : value.completion === null;
112
+ if (value.disposition === 'register_done') return value.start === null && completion(value.completion);
113
+ if (value.disposition === 'register_in_progress') {
114
+ return historicalStart(value.start) && value.completion === null;
115
+ }
116
+ return value.start === null && value.completion === null;
117
+ }
118
+
119
+ function validateEdges(value) {
120
+ return Array.isArray(value) && value.length <= TODO_LIMITS.edgesPerPlan
121
+ && value.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
122
+ && sortedStrictly(value, (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`);
123
+ }
124
+
125
+ function validateJoins(value) {
126
+ return Array.isArray(value) && value.length <= TODO_LIMITS.joinsPerPlan
127
+ && value.every((join) => exactRecord(join, ['id', 'after', 'before'])
128
+ && isTodoIdentifier(join.id) && Array.isArray(join.after) && join.after.length > 0
129
+ && join.after.length <= TODO_LIMITS.tasksPerPlan && join.after.every(nodeRef)
130
+ && sortedStrictly(join.after, refKey) && nodeRef(join.before))
131
+ && sortedStrictly(value, (join) => join.id);
132
+ }
133
+
134
+ const reject = (reason, path = '', detail = {}) => ({ valid: false, reason, path, ...detail });
135
+
136
+ /** value自体がexactRecordの対象になれる素朴なobjectかどうか(配列・nullを除く)。 */
137
+ function plainObject(value) {
138
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
139
+ }
140
+
141
+ /**
142
+ * 期待keyとの過不足を1件ずつ言い当てる。missing/unexpectedのどちらが先に見つかっても
143
+ * そこで止め、複数の欠落を一度に説明しない——`exactRecord`のbooleanと違い、
144
+ * 最初に見つかった違反fieldをpathへ刻む。
145
+ */
146
+ function explainKeys(value, requiredKeys, at) {
147
+ if (!plainObject(value) || Object.getPrototypeOf(value) !== Object.prototype) {
148
+ return reject('not_an_object', at);
149
+ }
150
+ const actualKeys = new Set(Object.keys(value));
151
+ for (const key of requiredKeys) {
152
+ if (!actualKeys.has(key)) return reject('missing_required_key', `${at}/${key}`);
153
+ }
154
+ const requiredSet = new Set(requiredKeys);
155
+ for (const key of actualKeys) {
156
+ if (!requiredSet.has(key)) return reject('unexpected_key', `${at}/${key}`);
157
+ }
158
+ return { valid: true };
159
+ }
160
+
161
+ function explainSortedStrictly(values, key, at) {
162
+ for (let index = 1; index < values.length; index += 1) {
163
+ if (!(key(values[index - 1]) < key(values[index]))) {
164
+ return reject('unsorted_or_duplicate_collection', `${at}/${index}`);
165
+ }
166
+ }
167
+ return { valid: true };
168
+ }
169
+
170
+ /**
171
+ * `lattice.todo_extraction.v1/v2`を、既存の`validateTodoExtraction`の可否は変えずに
172
+ * 診断する(ADR 0130の案内規律をmigration入口へ拡張)。
173
+ *
174
+ * 深いgraph整合(親task解決・edge/join local参照解決)はここでは個別に言い当てず、
175
+ * 単一のreasonへ丸める——既知の実運用の詰まりどころ(必須key欠落・task/edge/joinの
176
+ * ソート違反・digest不一致)を優先して解消する。それでも掴めない違反は
177
+ * `diagnosis_incomplete`として正直に返す。
178
+ */
179
+ export function explainTodoExtraction(value) {
180
+ try {
181
+ if (!plainObject(value)) return reject('not_an_object', '');
182
+ const schema = value.schema;
183
+ if (![TODO_EXTRACTION_SCHEMA, TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema)) {
184
+ return reject('schema_mismatch', '/schema', {
185
+ expected: TODO_EXTRACTION_SCHEMA_V3, actual: typeof schema === 'string' ? schema : null,
186
+ });
187
+ }
188
+ const v2 = [TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema);
189
+ const v3 = schema === TODO_EXTRACTION_SCHEMA_V3;
190
+ const topKeys = [
191
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
192
+ 'tasks', 'hard_dependencies', 'joins', 'extraction_digest',
193
+ ];
194
+ const topKeyCheck = explainKeys(value, topKeys, '');
195
+ if (!topKeyCheck.valid) return topKeyCheck;
196
+ if (!isTodoIdentifier(value.project_id)) return reject('invalid_identifier', '/project_id');
197
+ if (!isTodoIdentifier(value.plan_key)) return reject('invalid_identifier', '/plan_key');
198
+ if (!isTodoIdentifier(value.plan_version)) return reject('invalid_identifier', '/plan_version');
199
+ if (!actor(value.actor)) return reject('invalid_actor', '/actor');
200
+ if (!isStrictTodoTimestamp(value.recorded_at)) return reject('invalid_timestamp', '/recorded_at');
201
+ if (!Array.isArray(value.tasks) || value.tasks.length === 0
202
+ || value.tasks.length > TODO_LIMITS.tasksPerPlan) {
203
+ return reject('bounded_collection_violation', '/tasks');
204
+ }
205
+ const taskKeys = v2
206
+ ? ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
207
+ 'start', 'completion', 'source', 'migration_context']
208
+ : ['task_id', 'title', 'lane', 'narrative_ref', 'compile_binding', 'disposition',
209
+ 'completion', 'source', 'migration_context'];
210
+ if (v3) taskKeys.push('design_memo');
211
+ for (const [index, task] of value.tasks.entries()) {
212
+ const taskKeyCheck = explainKeys(task, taskKeys, `/tasks/${index}`);
213
+ if (!taskKeyCheck.valid) return taskKeyCheck;
214
+ if (v3 && !isTodoDesignMemo(task.design_memo)) {
215
+ return reject('design_memo_required', `/tasks/${index}/design_memo`, {
216
+ task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
217
+ expected: 'non-empty Markdown or NO_PLAN',
218
+ });
219
+ }
220
+ if (task.disposition === 'register_done'
221
+ && task.completion?.done_mode !== 'historical_import') {
222
+ return reject('enum_mismatch', `/tasks/${index}/completion/done_mode`, {
223
+ task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
224
+ expected: 'historical_import', actual: task.completion?.done_mode ?? null,
225
+ });
226
+ }
227
+ if (!Array.isArray(task.migration_context?.notes)) {
228
+ return reject('expected_array', `/tasks/${index}/migration_context/notes`, {
229
+ task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
230
+ expected: 'array', actual: typeof task.migration_context?.notes,
231
+ });
232
+ }
233
+ if (!extractionTask(task, schema)) {
234
+ return reject('task_shape_invalid', `/tasks/${index}`, {
235
+ task_id: isTodoIdentifier(task.task_id) ? task.task_id : null,
236
+ });
237
+ }
238
+ }
239
+ const sortCheck = explainSortedStrictly(value.tasks, (task) => task.task_id, '/tasks');
240
+ if (!sortCheck.valid) return sortCheck;
241
+ if (new Set(value.tasks.map(({ task_id: taskId }) => taskId)).size !== value.tasks.length) {
242
+ return reject('duplicate_task_id', '/tasks');
243
+ }
244
+ if (!validateEdges(value.hard_dependencies)) return reject('hard_dependencies_invalid', '/hard_dependencies');
245
+ if (!validateJoins(value.joins)) return reject('joins_invalid', '/joins');
246
+ if (!isTodoDigest(value.extraction_digest)) return reject('invalid_digest', '/extraction_digest');
247
+ const expectedDigest = todoSelfDigest(value, 'extraction_digest');
248
+ if (value.extraction_digest !== expectedDigest) {
249
+ return reject('extraction_digest_mismatch', '/extraction_digest', {
250
+ expected: expectedDigest, actual: value.extraction_digest,
251
+ });
252
+ }
253
+ const taskIds = new Set(value.tasks.map(({ task_id: taskId }) => taskId));
254
+ const badParent = value.tasks.find((task) => task.source.parent_task_id === task.task_id
255
+ || (task.source.parent_task_id !== null && !taskIds.has(task.source.parent_task_id)));
256
+ if (badParent !== undefined) {
257
+ return reject('parent_task_id_unresolved',
258
+ `/tasks/${value.tasks.indexOf(badParent)}/source/parent_task_id`);
259
+ }
260
+ const excluded = new Set(value.tasks
261
+ .filter((task) => task.disposition.startsWith('exclude_'))
262
+ .map(({ task_id }) => task_id));
263
+ const excludedParent = value.tasks.find((task) => task.disposition.startsWith('register_')
264
+ && task.source.parent_task_id !== null && excluded.has(task.source.parent_task_id));
265
+ if (excludedParent !== undefined) {
266
+ return reject('registered_parent_task_id_unresolved',
267
+ `/tasks/${value.tasks.indexOf(excludedParent)}/source/parent_task_id`, {
268
+ task_id: excludedParent.task_id,
269
+ expected: 'task_id not excluded from the compiled plan',
270
+ actual: excludedParent.source.parent_task_id,
271
+ });
272
+ }
273
+ const localRefViolation = firstUnregisteredLocalRef(value);
274
+ if (localRefViolation !== null) {
275
+ return reject('local_ref_unresolved', localRefViolation.path, {
276
+ task_id: localRefViolation.task_id,
277
+ expected: 'registered task_id', actual: localRefViolation.task_id,
278
+ });
279
+ }
280
+ // ここまでの個別検査を全て通過したのに`validateTodoExtraction`がfalseを返す状況は、
281
+ // このexplainがまだ言い当てられない違反があるということ。捏造せず未特定と申告する。
282
+ return { valid: true };
283
+ } catch {
284
+ return reject('diagnosis_failed', '');
285
+ }
286
+ }
287
+
288
+ function registeredTaskIds(value) {
289
+ return new Set(value.tasks
290
+ .filter(({ disposition }) => disposition.startsWith('register_'))
291
+ .map(({ task_id }) => task_id));
292
+ }
293
+
294
+ function localRefsResolve(value) {
295
+ return firstUnregisteredLocalRef(value) === null;
296
+ }
297
+
298
+ function firstUnregisteredLocalRef(value) {
299
+ const registered = registeredTaskIds(value);
300
+ const unresolved = (ref) => ref.project_id === value.project_id && ref.plan_key === value.plan_key
301
+ && !registered.has(ref.task_id);
302
+ for (const [index, edge] of value.hard_dependencies.entries()) {
303
+ if (unresolved(edge.from)) return { path: `/hard_dependencies/${index}/from`, task_id: edge.from.task_id };
304
+ if (unresolved(edge.to)) return { path: `/hard_dependencies/${index}/to`, task_id: edge.to.task_id };
305
+ }
306
+ for (const [index, join] of value.joins.entries()) {
307
+ if (unresolved(join.before)) return { path: `/joins/${index}/before`, task_id: join.before.task_id };
308
+ const afterIndex = join.after.findIndex(unresolved);
309
+ if (afterIndex >= 0) {
310
+ return { path: `/joins/${index}/after/${afterIndex}`, task_id: join.after[afterIndex].task_id };
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /** Exact, bounded validation for the AI-authored G4 intermediate artifact. */
317
+ export function validateTodoExtraction(value) {
318
+ try {
319
+ const schema = value?.schema;
320
+ if (!exactRecord(value, [
321
+ 'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
322
+ 'tasks', 'hard_dependencies', 'joins', 'extraction_digest',
323
+ ]) || ![TODO_EXTRACTION_SCHEMA, TODO_EXTRACTION_SCHEMA_V2, TODO_EXTRACTION_SCHEMA_V3].includes(schema)
324
+ || !isTodoIdentifier(value.project_id)
325
+ || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
326
+ || !actor(value.actor) || !isStrictTodoTimestamp(value.recorded_at)
327
+ || !Array.isArray(value.tasks) || value.tasks.length === 0
328
+ || value.tasks.length > TODO_LIMITS.tasksPerPlan
329
+ || !value.tasks.every((task) => extractionTask(task, schema))
330
+ || !sortedStrictly(value.tasks, (task) => task.task_id)
331
+ || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
332
+ || !validateEdges(value.hard_dependencies) || !validateJoins(value.joins)
333
+ || !isTodoDigest(value.extraction_digest)
334
+ || value.extraction_digest !== todoSelfDigest(value, 'extraction_digest')) return false;
335
+
336
+ const taskIds = new Set(value.tasks.map(({ task_id }) => task_id));
337
+ if (value.tasks.some((task) => task.source.parent_task_id === task.task_id
338
+ || (task.source.parent_task_id !== null && !taskIds.has(task.source.parent_task_id)))) return false;
339
+ const excluded = new Set(value.tasks
340
+ .filter((task) => task.disposition.startsWith('exclude_'))
341
+ .map(({ task_id }) => task_id));
342
+ if (value.tasks.some((task) => task.disposition.startsWith('register_')
343
+ && task.source.parent_task_id !== null && excluded.has(task.source.parent_task_id))) return false;
344
+ return localRefsResolve(value);
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+
350
+ export function todoExtractionImportSource(task) {
351
+ return {
352
+ schema: 'lattice.todo_import_source.v1',
353
+ origin_plan_ref: task.source.origin_plan_ref,
354
+ origin_line: task.source.origin_line,
355
+ source_commit: task.source.source_commit,
356
+ };
357
+ }
358
+
359
+ /**
360
+ * Translate an already-extracted artifact into appendImportedPlan input.
361
+ * Source locations are passed to the importer but no Markdown is read here.
362
+ * Unresolved records stop the whole transaction so the owner can adjudicate
363
+ * the JSON and rerun the same command.
364
+ */
365
+ export function compileTodoExtraction(value, repoRoot) {
366
+ if (!validateTodoExtraction(value)) {
367
+ const explained = explainTodoExtraction(value);
368
+ throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined,
369
+ explained.valid ? undefined : {
370
+ violation_reason: explained.reason, violation_path: explained.path,
371
+ ...(explained.task_id === undefined ? {} : { task_id: explained.task_id }),
372
+ });
373
+ }
374
+ const unresolved = value.tasks
375
+ .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
376
+ .map(({ task_id }) => task_id);
377
+ if (unresolved.length > 0) {
378
+ throw new TodoStoreError('MIGRATION_UNRESOLVED', 'unknown_requires_evidence', undefined, {
379
+ task_ids: unresolved,
380
+ });
381
+ }
382
+
383
+ const registered = value.tasks.filter(({ disposition }) => disposition.startsWith('register_'));
384
+ if (registered.length === 0) {
385
+ throw new TodoStoreError('MIGRATION_EMPTY', 'no_registered_tasks');
386
+ }
387
+ return {
388
+ repoRoot,
389
+ writer: createTodoStoreWriter({ caller: 'g4-migration' }),
390
+ initializeIfMissing: {
391
+ projectId: value.project_id,
392
+ repositories: [{ repo_id: 'self', path: '.' }],
393
+ },
394
+ plan: {
395
+ schema: value.schema === TODO_EXTRACTION_SCHEMA_V3
396
+ ? 'lattice.todo_plan.v6' : 'lattice.todo_plan.v2',
397
+ project_id: value.project_id,
398
+ plan_key: value.plan_key,
399
+ plan_version: value.plan_version,
400
+ predecessor_plan_digest: null,
401
+ tasks: registered.map((task) => ({
402
+ task_id: task.task_id,
403
+ title: task.title,
404
+ lane: task.lane,
405
+ ...(value.schema === TODO_EXTRACTION_SCHEMA_V3
406
+ ? { design_memo: task.design_memo } : {}),
407
+ narrative_ref: task.narrative_ref,
408
+ narrative_anchor: null,
409
+ compile_binding: null,
410
+ ...(value.schema === TODO_EXTRACTION_SCHEMA_V3
411
+ ? { parent_task_id: task.source.parent_task_id } : {}),
412
+ })),
413
+ hard_dependencies: value.hard_dependencies,
414
+ joins: value.joins,
415
+ },
416
+ narrativeAnchorSources: registered.map((task) => ({
417
+ task_id: task.task_id,
418
+ origin_plan_ref: task.source.origin_plan_ref,
419
+ origin_line: task.source.origin_line,
420
+ source_commit: task.source.source_commit,
421
+ checkbox_state: task.source.checkbox_state,
422
+ })),
423
+ genesis: {
424
+ actor: value.actor,
425
+ recorded_at: value.recorded_at,
426
+ provenance: null,
427
+ },
428
+ completedTasks: registered
429
+ .filter(({ disposition }) => disposition === 'register_done')
430
+ .map((task) => ({
431
+ task_id: task.task_id,
432
+ completed_at: task.completion.completed_at,
433
+ evidence: todoExtractionImportSource(task),
434
+ })),
435
+ inProgressTasks: registered
436
+ .filter(({ disposition }) => disposition === 'register_in_progress')
437
+ .map((task) => ({
438
+ task_id: task.task_id,
439
+ started_at: task.start.started_at,
440
+ evidence: todoExtractionImportSource(task),
441
+ })),
442
+ };
443
+ }
444
+
445
+ export async function appendTodoExtraction({ repoRoot, extraction }) {
446
+ const request = compileTodoExtraction(extraction, repoRoot);
447
+ return appendImportedPlan(request);
448
+ }