@quolu/lattice 0.52.3 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. 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
+ }