@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,925 +1,925 @@
1
- import { createHash } from 'node:crypto';
2
-
3
- import { digestArtifact } from './artifact-contracts.mjs';
4
- import { compileBoundaryObservationV2 } from './boundary-observation-compiler-v2.mjs';
5
- import { portableSensorOutcome } from './sensor-adapter.mjs';
6
- import { compileSchedulabilityGraphV2 } from './schedulability-compiler-v2.mjs';
7
- import { verifySchedulabilityPlanV2 } from './schedulability-verifier-v2.mjs';
8
- import {
9
- BOUNDARY_MANIFEST_SCHEMA,
10
- RUN_REQUEST_PREDICTION_SCHEMA,
11
- RUN_REQUEST_SCHEMA,
12
- SENSOR_EXPECT_KINDS,
13
- SENSOR_QUERY_OPERATIONS,
14
- selfDigest,
15
- validateRunRequest,
16
- validateRuntimeBoundaryManifest,
17
- validateRuntimePlan,
18
- verifyRuntimePlanBinding,
19
- } from './runtime-contracts.mjs';
20
-
21
- /**
22
- * RC3-D generic front-end(ADR 0044 Decision 2・8、plan RC3-D)。
23
- *
24
- * `lattice.run_request.v1`のmanual witnessとfresh LatticeSensor観測evidenceから、
25
- * fixture名・期待conflict・期待waveの分岐なしに`lattice.runtime_plan.v1`と
26
- * TODOごとの`lattice.boundary_manifest.v2`をcompileする。
27
- *
28
- * adapter契約(witness.sensor_provenance、RC3-Dで固定):
29
- * { queries: [{ query_id, expect }] }
30
- * expect = { kind: 'symbol', name, path } — query outcomeにnode.name/filePathの
31
- * exact一致がちょうど1件あることを要求(fuzzy解決の誤読防止)
32
- * | { kind: 'path', path } — outcomeにfilePath exact一致が1件以上
33
- * | { kind: 'affected', path } — affected outcomeのchangedFilesが[path]と
34
- * exact一致し、affectedTestsがwitness.affected_testsとexact一致
35
- *
36
- * typed non-dispatchable(dispatchable planを発行しない、fail closed):
37
- * NODE_LIMIT_EXCEEDED / BOUNDARY_UNKNOWN / SEARCH_BUDGET_EXHAUSTED /
38
- * QUERY_DRIFT / AFFECTED_TEST_DRIFT
39
- *
40
- * LatticeSensor raw telemetryはevidence captureに留め、plan・manifest identityへは
41
- * portable outcome projectionのcanonical digestだけを入れる(Decision 10.4)。
42
- */
43
-
44
- // 閉集合の正本はruntime-contracts。ここでは輸入して使う。
45
- const QUERY_OPERATIONS = SENSOR_QUERY_OPERATIONS;
46
- const STRUCTURE_OPERATIONS = new Set(['query', 'callers', 'callees', 'impact']);
47
- const EXPECT_KINDS = new Set(SENSOR_EXPECT_KINDS);
48
- const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
49
- const STATE_KIND_MAP = Object.freeze({
50
- state: 'state',
51
- schema: 'state',
52
- invariant: 'state',
53
- effect: 'effect',
54
- external_effect: 'effect',
55
- });
56
-
57
- export const RUNTIME_NON_DISPATCHABLE_CODES = Object.freeze([
58
- 'NODE_LIMIT_EXCEEDED',
59
- 'BOUNDARY_UNKNOWN',
60
- 'SEARCH_BUDGET_EXHAUSTED',
61
- 'QUERY_DRIFT',
62
- 'AFFECTED_TEST_DRIFT',
63
- ]);
64
-
65
- function fail(reason) {
66
- throw new TypeError(`runtime front-end契約違反: ${reason}`);
67
- }
68
-
69
- function plainRecord(value) {
70
- return value !== null
71
- && typeof value === 'object'
72
- && !Array.isArray(value)
73
- && Object.getPrototypeOf(value) === Object.prototype;
74
- }
75
-
76
- function exactRecord(value, keys) {
77
- if (!plainRecord(value)) return false;
78
- const actual = Object.keys(value).sort();
79
- const expected = [...keys].sort();
80
- return actual.length === expected.length
81
- && actual.every((key, index) => key === expected[index]);
82
- }
83
-
84
- function identifier(value) {
85
- return typeof value === 'string' && IDENTIFIER.test(value);
86
- }
87
-
88
- const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
89
-
90
- /**
91
- * repo相対pathだけを受理する(runtime-contracts.mjsと同じ規律、Decision 2・10.4)。
92
- * absolute path・`..`・空segment・制御文字・`\`をmanifest/plan identityへ混入させない。
93
- */
94
- function repoRelativePath(value, { allowPrefix = false } = {}) {
95
- if (typeof value !== 'string'
96
- || value.length === 0
97
- || Buffer.byteLength(value, 'utf8') > 1_024
98
- || CONTROL_CHARACTER.test(value)
99
- || value.includes('\\')
100
- || value.startsWith('/')) {
101
- return false;
102
- }
103
- const isPrefix = value.endsWith('/');
104
- if (isPrefix && !allowPrefix) return false;
105
- const body = isPrefix ? value.slice(0, -1) : value;
106
- return body.split('/').every((segment) => (
107
- segment.length > 0 && segment !== '.' && segment !== '..'
108
- ));
109
- }
110
-
111
- function sha16(value) {
112
- return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
113
- }
114
-
115
- function compareText(left, right) {
116
- if (left < right) return -1;
117
- if (left > right) return 1;
118
- return 0;
119
- }
120
-
121
- function nonDispatchable(code, detail) {
122
- if (!RUNTIME_NON_DISPATCHABLE_CODES.includes(code)) fail(`未知のnon-dispatchable code: ${code}`);
123
- return { outcome: 'non_dispatchable', code, detail };
124
- }
125
-
126
- /** query set(run_request.sensor_query_set)のexact shapeを検査する。 */
127
- function normalizeQuerySet(querySet) {
128
- if (!exactRecord(querySet, ['queries'])) fail('sensor_query_set shapeが不正');
129
- if (!Array.isArray(querySet.queries)) fail('sensor_query_set.queriesがarrayではない');
130
- const byId = new Map();
131
- for (const query of querySet.queries) {
132
- const keys = Object.hasOwn(query ?? {}, 'target')
133
- ? ['id', 'operation', 'target']
134
- : ['id', 'operation'];
135
- if (!exactRecord(query, keys)
136
- || !identifier(query.id)
137
- || !QUERY_OPERATIONS.includes(query.operation)
138
- || (keys.includes('target') && (typeof query.target !== 'string' || query.target.length === 0))) {
139
- fail('query set entry shapeが不正');
140
- }
141
- if (byId.has(query.id)) fail(`query idが重複している: ${query.id}`);
142
- byId.set(query.id, query);
143
- }
144
- return byId;
145
- }
146
-
147
- /**
148
- * captureされたevidenceをquery setとexact整合させ、portable projectionへ分離する。
149
- * evidence = { outcomes: [{ query_id, operation, status, raw }] }(query set順)
150
- */
151
- function normalizeEvidence(evidence, queryById) {
152
- if (!exactRecord(evidence, ['outcomes'])) fail('sensor evidence shapeが不正');
153
- if (!Array.isArray(evidence.outcomes)) fail('evidence.outcomesがarrayではない');
154
- if (evidence.outcomes.length !== queryById.size) {
155
- fail(`evidence件数(${evidence.outcomes.length})がquery set件数(${queryById.size})と一致しない`);
156
- }
157
- const queries = [...queryById.values()];
158
- const byQueryId = new Map();
159
- evidence.outcomes.forEach((outcome, index) => {
160
- if (!exactRecord(outcome, ['query_id', 'operation', 'status', 'raw'])) {
161
- fail('evidence outcome shapeが不正');
162
- }
163
- const query = queries[index];
164
- if (outcome.query_id !== query.id || outcome.operation !== query.operation) {
165
- fail(`evidence outcomeがquery setと順序整合しない: ${outcome.query_id}`);
166
- }
167
- if (typeof outcome.status !== 'string' || outcome.status.length === 0) {
168
- fail('evidence outcome statusが不正');
169
- }
170
- const portable = portableSensorOutcome(outcome.raw);
171
- byQueryId.set(outcome.query_id, {
172
- query_id: outcome.query_id,
173
- operation: outcome.operation,
174
- status: outcome.status,
175
- raw: outcome.raw,
176
- portable,
177
- portable_digest: digestArtifact({
178
- query_id: outcome.query_id,
179
- operation: outcome.operation,
180
- status: outcome.status,
181
- portable,
182
- }),
183
- });
184
- });
185
- return byQueryId;
186
- }
187
-
188
- function normalizeProvenanceQueries(witness, todoId) {
189
- const provenance = witness.sensor_provenance;
190
- if (!exactRecord(provenance, ['queries']) || !Array.isArray(provenance.queries)) {
191
- fail(`witness ${todoId}.sensor_provenance shapeが不正`);
192
- }
193
- return provenance.queries.map((entry) => {
194
- if (!exactRecord(entry, ['query_id', 'expect']) || !identifier(entry.query_id)) {
195
- fail(`witness ${todoId}.sensor_provenance entry shapeが不正`);
196
- }
197
- const expect = entry.expect;
198
- if (!plainRecord(expect) || !EXPECT_KINDS.has(expect.kind)) {
199
- fail(`witness ${todoId}.expect shapeが不正`);
200
- }
201
- if (expect.kind === 'symbol') {
202
- if (!exactRecord(expect, ['kind', 'name', 'path'])
203
- || typeof expect.name !== 'string' || expect.name.length === 0
204
- || !repoRelativePath(expect.path)) {
205
- fail(`witness ${todoId}.symbol expectが不正`);
206
- }
207
- } else if (!exactRecord(expect, ['kind', 'path']) || !repoRelativePath(expect.path)) {
208
- fail(`witness ${todoId}.${expect.kind} expectが不正`);
209
- }
210
- return { query_id: entry.query_id, expect };
211
- });
212
- }
213
-
214
- const STRUCTURE_EXPECT_OPERATIONS = new Set(['query', 'callers', 'callees', 'impact']);
215
-
216
- /**
217
- * witness expectとquery set entryのcross-binding(別targetのreceiptへの再ラベル防止)。
218
- * 不一致はQUERY_DRIFT。
219
- */
220
- function bindingMatchesQuery(binding, query) {
221
- const { expect } = binding;
222
- if (expect.kind === 'affected') {
223
- return query.operation === 'affected' && query.target === expect.path;
224
- }
225
- if (expect.kind === 'symbol') {
226
- return STRUCTURE_EXPECT_OPERATIONS.has(query.operation) && query.target === expect.name;
227
- }
228
- return (STRUCTURE_EXPECT_OPERATIONS.has(query.operation) || query.operation === 'affected')
229
- && query.target === expect.path;
230
- }
231
-
232
- /** raw outcome(`{operation, data}`包み、RC2 evidence互換)のpayloadを取り出す。 */
233
- function rawPayload(raw) {
234
- return plainRecord(raw) && Object.hasOwn(raw, 'data') ? raw.data : raw;
235
- }
236
-
237
- /**
238
- * affected outcomeのpayloadを取り出す。lattice-sensor-adapterのper-target形
239
- * (`{targets: [{target, outcome, data}]}`)と直接data形の両方を受ける。
240
- */
241
- function affectedPayload(raw, expectPath) {
242
- if (plainRecord(raw) && Array.isArray(raw.targets)) {
243
- const entry = raw.targets.find((candidate) => (
244
- plainRecord(candidate) && candidate.target === expectPath
245
- ));
246
- return plainRecord(entry) && plainRecord(entry.data) ? entry.data : null;
247
- }
248
- const payload = rawPayload(raw);
249
- return plainRecord(payload) ? payload : null;
250
- }
251
-
252
- /**
253
- * 収集済みsensor evidenceから、あるpathのaffected testを読む。
254
- *
255
- * 実行時の翻訳段(宣言を観測へ合わせる)が同じ観測を必要とする。payloadの形の解釈をあちらへ
256
- * 書き直すと、driftを判定する規則と、driftを起こさない宣言を作る規則が別々に育つ。
257
- *
258
- * @returns {string[]|null} 観測できなければnull(空配列と区別する)
259
- */
260
- export function affectedTestsFromEvidence({ sensorEvidence, querySet, path: target } = {}) {
261
- const queries = (querySet?.queries ?? [])
262
- .filter((query) => query.operation === 'affected' && query.target === target);
263
- if (queries.length !== 1) return null;
264
- const outcome = (sensorEvidence?.outcomes ?? [])
265
- .find((entry) => entry.query_id === queries[0].id);
266
- if (!plainRecord(outcome) || outcome.status !== 'ready') return null;
267
- const payload = affectedPayload(outcome.raw, target);
268
- return Array.isArray(payload?.affectedTests) ? [...payload.affectedTests].sort(compareText) : null;
269
- }
270
-
271
- function affectedTarget(raw, expectPath) {
272
- if (!plainRecord(raw) || !Array.isArray(raw.targets)) return null;
273
- const entry = raw.targets.find((candidate) => (
274
- plainRecord(candidate) && candidate.target === expectPath
275
- ));
276
- return plainRecord(entry) ? entry : null;
277
- }
278
-
279
- function rawEntries(raw) {
280
- const payload = rawPayload(raw);
281
- return Array.isArray(payload) ? payload : null;
282
- }
283
-
284
- function entryNode(entry) {
285
- if (plainRecord(entry) && plainRecord(entry.node)) return entry.node;
286
- if (plainRecord(entry)) return entry;
287
- return null;
288
- }
289
-
290
- /**
291
- * 創作宣言されたpathの裏付けを決める(ADR 0136)。
292
- *
293
- * 宣言と観測が一致する時だけ`ready`にする。fresh absentは推測ではなくfsのlstat結果なので、
294
- * 「観測できなかった」ではなく「観測して、無かった」である。存在しないfileに依存するものは
295
- * 構造的に存在しえないため、affected testが空であることまで確かめれば裏付けは閉じる。
296
- *
297
- * 既に存在するpathへ創作を宣言していたら`creates_path_present`で止める。実害は無いが、
298
- * 宣言が実態からずれているのを黙って通すと、宣言と観測が一致しているという前提が崩れる。
299
- * 宣言していないabsent pathは従来どおり`path_absent`のままにする——綴り違いを
300
- * 「黙って通る創作境界」にしないための線である。
301
- */
302
- function creationBoundaryStatus(outcome, expectPath) {
303
- // sensorが答えられていない状況は、この関数の管轄でない。通常のstatus判定へ返す。
304
- if (!['ready', 'empty'].includes(outcome.status)) return null;
305
- const target = affectedTarget(outcome.raw, expectPath);
306
- // fs観測が記録に無いなら、不存在は確かめられていない。宣言だけで裏付けにしない。
307
- if (target === null || target === undefined) return 'creates_unverified';
308
- if (target.path_state !== 'absent') return 'creates_path_present';
309
- const payload = affectedPayload(outcome.raw, expectPath);
310
- if (payload === null
311
- || !Array.isArray(payload.changedFiles)
312
- || payload.changedFiles.length !== 1
313
- || payload.changedFiles[0] !== expectPath
314
- || !Array.isArray(payload.affectedTests)
315
- || payload.affectedTests.length !== 0) return 'creates_unverified';
316
- return 'ready';
317
- }
318
-
319
- /**
320
- * 束縛queryのoutcomeへexpectをexact照合し、sensor statusを決める。
321
- * fuzzy解決・空結果は依存なしへ丸めず、unknown系statusへ落とす(AGENTS.md)。
322
- */
323
- function resolveBindingStatus(binding, outcome) {
324
- if (binding.expect.kind === 'affected' && binding.creates === true) {
325
- const declared = creationBoundaryStatus(outcome, binding.expect.path);
326
- if (declared !== null) return declared;
327
- }
328
- if (outcome.status !== 'ready') return outcome.status;
329
- const { expect } = binding;
330
- if (expect.kind === 'affected') {
331
- if (affectedTarget(outcome.raw, expect.path)?.path_state === 'absent') return 'path_absent';
332
- const payload = affectedPayload(outcome.raw, expect.path);
333
- if (payload === null
334
- || !Array.isArray(payload.changedFiles)
335
- || payload.changedFiles.length !== 1
336
- || payload.changedFiles[0] !== expect.path) {
337
- return 'empty';
338
- }
339
- return 'ready';
340
- }
341
- const entries = rawEntries(outcome.raw);
342
- if (entries === null) return 'invalid_json';
343
- if (expect.kind === 'symbol') {
344
- const matches = entries.filter((entry) => {
345
- const node = entryNode(entry);
346
- return node !== null && node.name === expect.name && node.filePath === expect.path;
347
- });
348
- if (matches.length === 1) return 'ready';
349
- return matches.length === 0 ? 'symbol_absent' : 'unresolved';
350
- }
351
- const matches = entries.filter((entry) => {
352
- const node = entryNode(entry);
353
- return node !== null && node.filePath === expect.path;
354
- });
355
- return matches.length >= 1 ? 'ready' : 'empty';
356
- }
357
-
358
- function bindingCoversOwn(binding, own) {
359
- if (own.kind === 'symbol') {
360
- return binding.expect.kind === 'symbol' && binding.expect.name === own.target;
361
- }
362
- return (binding.expect.kind === 'path' || binding.expect.kind === 'affected')
363
- && binding.expect.path === own.target;
364
- }
365
-
366
- function pathPrefixOverlap(left, right) {
367
- const leftIsPrefix = left.endsWith('/');
368
- const rightIsPrefix = right.endsWith('/');
369
- if (left === right) return true;
370
- if (leftIsPrefix && (right === left.slice(0, -1) || right.startsWith(left))) return true;
371
- if (rightIsPrefix && (left === right.slice(0, -1) || left.startsWith(right))) return true;
372
- return false;
373
- }
374
-
375
- function manualProvenance(request) {
376
- return {
377
- source: 'manual_state_effect',
378
- evidence_ref: `run-request:${request.request_id}`,
379
- evidence_digest: request.request_digest,
380
- status: 'asserted',
381
- };
382
- }
383
-
384
- function candidateProvenance(request) {
385
- return {
386
- source: 'manual_candidate_spec',
387
- evidence_ref: `run-request:${request.request_id}`,
388
- evidence_digest: request.request_digest,
389
- status: 'asserted',
390
- };
391
- }
392
-
393
- /**
394
- * `collectSensorEvidence`のraw収集結果を、query set順へexact整合した
395
- * front-end evidence契約(`{outcomes: [{query_id, operation, status, raw}]}`)へ写す。
396
- * 件数・id・operationの不一致はfail closed。
397
- */
398
- export function evidenceFromCollectedOutcomes(options = {}) {
399
- if (!exactRecord(options, ['querySet', 'collected'])) {
400
- fail('evidenceFromCollectedOutcomes optionsがexact shapeでない');
401
- }
402
- const { querySet, collected } = options;
403
- const queryById = normalizeQuerySet(querySet);
404
- if (!plainRecord(collected) || !Array.isArray(collected.outcomes)) {
405
- fail('collected evidence shapeが不正');
406
- }
407
- if (collected.outcomes.length !== queryById.size) {
408
- fail(`collected outcomes件数(${collected.outcomes.length})がquery set件数(${queryById.size})と一致しない`);
409
- }
410
- const queries = [...queryById.values()];
411
- return {
412
- outcomes: collected.outcomes.map((outcome, index) => {
413
- const query = queries[index];
414
- if (!plainRecord(outcome)
415
- || (Object.hasOwn(outcome, 'id') && outcome.id !== query.id)
416
- || (Object.hasOwn(outcome, 'operation') && outcome.operation !== query.operation)
417
- || typeof outcome.outcome !== 'string'
418
- || outcome.outcome.length === 0) {
419
- fail(`collected outcomeがquery setと整合しない: ${query.id}`);
420
- }
421
- return {
422
- query_id: query.id,
423
- operation: query.operation,
424
- status: outcome.outcome,
425
- raw: outcome,
426
- };
427
- }),
428
- };
429
- }
430
-
431
- /**
432
- * run_requestとsensor evidenceからobservation set・graph・planを一括compileする。
433
- * 成功時はdispatchable outcome、契約内の識別可能な不成立はtyped non-dispatchable、
434
- * 入力shape違反はTypeErrorでfail closed。
435
- */
436
- export function compileRuntimePlanV1(options = {}) {
437
- if (!exactRecord(options, ['request', 'sensorEvidence', 'planRef', 'planEpoch', 'predecessorRefs'])) {
438
- fail('compileRuntimePlanV1 optionsがexact shapeでない');
439
- }
440
- const { request, sensorEvidence, planRef, planEpoch, predecessorRefs } = options;
441
- if (!validateRunRequest(request)) fail('run_request.v1がcontractを満たさない');
442
- if (!identifier(planRef)) fail('planRefがidentifierではない');
443
- if (!Number.isSafeInteger(planEpoch) || planEpoch < 0) fail('planEpochが不正');
444
- if (!Array.isArray(predecessorRefs) || !predecessorRefs.every((ref) => typeof ref === 'string')) {
445
- fail('predecessorRefsがstring arrayではない');
446
- }
447
-
448
- const queryById = normalizeQuerySet(request.sensor_query_set);
449
- const outcomeByQueryId = normalizeEvidence(sensorEvidence, queryById);
450
-
451
- const todoIds = request.todos.map((todo) => todo.todo_id);
452
- const predictionsOnly = [RUN_REQUEST_SCHEMA, RUN_REQUEST_PREDICTION_SCHEMA]
453
- .includes(request.schema);
454
-
455
- // witnessの束縛を解決する。query set外の参照と、expect↔query targetの
456
- // 不一致(別targetのreceiptへの再ラベル)はQUERY_DRIFT。
457
- const bindingsByTodo = new Map();
458
- const driftDetails = [];
459
- for (const todoId of todoIds) {
460
- const witness = request.manual_witness[todoId];
461
- // 創作宣言はowns側にある。裏付けを決めるのはbindingなので、覆っているbindingへ写す。
462
- const creating = new Set(witness.owns
463
- .filter((own) => own.creates === true).map((own) => own.target));
464
- const bindings = normalizeProvenanceQueries(witness, todoId)
465
- .map((binding) => (!predictionsOnly && creating.size > 0
466
- && [...creating].some((target) => bindingCoversOwn(binding, { kind: 'path', target }))
467
- ? { ...binding, creates: true } : binding));
468
- for (const binding of bindings) {
469
- const query = queryById.get(binding.query_id);
470
- if (query === undefined) {
471
- driftDetails.push({ todo_id: todoId, query_id: binding.query_id, reason: 'query set外の参照' });
472
- } else if (!bindingMatchesQuery(binding, query)) {
473
- driftDetails.push({
474
- todo_id: todoId,
475
- query_id: binding.query_id,
476
- reason: 'expectとquery operation/targetが一致しない',
477
- });
478
- }
479
- }
480
- bindingsByTodo.set(todoId, bindings);
481
- }
482
- if (driftDetails.length > 0) return nonDispatchable('QUERY_DRIFT', { references: driftDetails });
483
-
484
- // status queryは正確に1つ要求し、fresh index規律をここで検査する。
485
- const statusQueries = [...queryById.values()].filter((query) => query.operation === 'status');
486
- if (statusQueries.length !== 1) {
487
- return nonDispatchable('QUERY_DRIFT', {
488
- references: [{ reason: `status queryが${statusQueries.length}件(正確に1件が必要)` }],
489
- });
490
- }
491
- const statusOutcome = outcomeByQueryId.get(statusQueries[0].id);
492
-
493
- const unknowns = [];
494
- if (statusOutcome.status !== 'ready') {
495
- for (const todoId of todoIds) {
496
- unknowns.push({ todo_id: todoId, kind: `sensor_${statusOutcome.status}`, ref: statusQueries[0].id });
497
- }
498
- }
499
-
500
- // 全束縛queryの解決statusを検査する。非readyな構造/affected evidenceは
501
- // dispatchable planへ丸めず、unknownとしてevidence acquisitionへ送る。
502
- for (const todoId of todoIds) {
503
- for (const binding of bindingsByTodo.get(todoId)) {
504
- const resolved = resolveBindingStatus(binding, outcomeByQueryId.get(binding.query_id));
505
- if (!predictionsOnly && resolved !== 'ready') {
506
- unknowns.push({ todo_id: todoId, kind: `sensor_${resolved}`, ref: binding.query_id });
507
- }
508
- }
509
- }
510
-
511
- // affected test drift検査(witness宣言とfresh affected観測のexact比較)。
512
- //
513
- // 比較はTODO単位で、そのTODOが持つ**全affected束縛の観測の和**に対して行う。1面しか持たない
514
- // TODOでは束縛ごとの比較と同じ結果になり、複数面を所有するTODOでも表現できる——束縛ごとに
515
- // 宣言全体とexact比較すると、affectedの異なる2 pathを所有するTODOは原理的に成立せず、
516
- // 実行時に所有が広がった宣言を受け取れなくなる。和なので緩みは入らない(余分な宣言も
517
- // 足りない宣言もdriftのまま)。
518
- const affectedDrift = [];
519
- for (const todoId of todoIds) {
520
- const witness = request.manual_witness[todoId];
521
- const declared = [...witness.affected_tests].sort(compareText);
522
- const queryIds = [];
523
- const observedUnion = new Set();
524
- let unreadable = false;
525
- for (const binding of bindingsByTodo.get(todoId)) {
526
- if (binding.expect.kind !== 'affected') continue;
527
- const outcome = outcomeByQueryId.get(binding.query_id);
528
- if (resolveBindingStatus(binding, outcome) !== 'ready') continue;
529
- queryIds.push(binding.query_id);
530
- const payload = affectedPayload(outcome.raw, binding.expect.path);
531
- if (!Array.isArray(payload?.affectedTests)) {
532
- // 観測が読めないのは「一致しない」とは別の事象である。丸めずそのまま残す。
533
- affectedDrift.push({ todo_id: todoId, query_id: binding.query_id, declared, observed: null });
534
- unreadable = true;
535
- continue;
536
- }
537
- for (const test of payload.affectedTests) observedUnion.add(test);
538
- }
539
- if (unreadable || queryIds.length === 0) continue;
540
- const observed = [...observedUnion].sort(compareText);
541
- if (observed.length !== declared.length
542
- || observed.some((test, index) => test !== declared[index])) {
543
- affectedDrift.push({
544
- todo_id: todoId,
545
- query_id: queryIds.sort(compareText).join(','),
546
- declared,
547
- observed,
548
- });
549
- }
550
- }
551
- if (!predictionsOnly && affectedDrift.length > 0) {
552
- return nonDispatchable('AFFECTED_TEST_DRIFT', { mismatches: affectedDrift });
553
- }
554
-
555
- // owns targetごとの構造的裏付け。covering queryは全witnessを通じて一意でなければならない。
556
- const ownGroups = new Map();
557
- const coveringByTarget = new Map();
558
- const ambiguous = [];
559
- for (const todoId of todoIds) {
560
- const witness = request.manual_witness[todoId];
561
- for (const own of witness.owns) {
562
- if (own.kind === 'path' && !repoRelativePath(own.target, { allowPrefix: true })) {
563
- fail(`witness ${todoId}のowns pathがrepo相対規律を満たさない: ${own.target}`);
564
- }
565
- const key = `${own.kind} ${own.target}`;
566
- if (!ownGroups.has(key)) ownGroups.set(key, { own, todoIds: [] });
567
- ownGroups.get(key).todoIds.push(todoId);
568
- const covering = bindingsByTodo.get(todoId).filter((binding) => bindingCoversOwn(binding, own));
569
- for (const binding of covering) {
570
- const seen = coveringByTarget.get(key);
571
- if (seen === undefined) {
572
- coveringByTarget.set(key, binding.query_id);
573
- } else if (seen !== binding.query_id) {
574
- ambiguous.push({ target: own.target, query_ids: [seen, binding.query_id].sort(compareText) });
575
- }
576
- }
577
- if (!predictionsOnly && covering.length === 0) {
578
- unknowns.push({ todo_id: todoId, kind: 'sensor_unbound', ref: `${own.kind}:${own.target}` });
579
- }
580
- }
581
- }
582
- if (ambiguous.length > 0) return nonDispatchable('QUERY_DRIFT', { ambiguous_targets: ambiguous });
583
-
584
- // 最新契約ではwrite scopeは予測である。既知の交差はserial conflictへ使うが、
585
- // 予測が足りないこと自体はunknownへ落とさない。
586
- const predictedWriteGroups = [];
587
- for (let left = 0; left < todoIds.length; left += 1) {
588
- for (let right = left + 1; right < todoIds.length; right += 1) {
589
- const leftWitness = request.manual_witness[todoIds[left]];
590
- const rightWitness = request.manual_witness[todoIds[right]];
591
- const leftOwnPaths = new Set(leftWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
592
- const rightOwnPaths = new Set(rightWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
593
- for (const leftPath of leftWitness.writes) {
594
- for (const rightPath of rightWitness.writes) {
595
- if (!pathPrefixOverlap(leftPath, rightPath)) continue;
596
- // 同一targetを両者がownsで所有主張している場合はwrite conflictとして
597
- // resource経由で扱われる。owns解決のない交差だけをunknownにする。
598
- if (leftOwnPaths.has(leftPath) && rightOwnPaths.has(rightPath)
599
- && leftPath === rightPath) continue;
600
- if (predictionsOnly) {
601
- predictedWriteGroups.push({
602
- target: [leftPath, rightPath].sort(compareText).join(' ↔ '),
603
- todoIds: [todoIds[left], todoIds[right]],
604
- });
605
- } else {
606
- unknowns.push({
607
- todo_id: todoIds[left], kind: 'undeclared_write_overlap',
608
- ref: `${leftPath} ${rightPath}`,
609
- });
610
- unknowns.push({
611
- todo_id: todoIds[right], kind: 'undeclared_write_overlap',
612
- ref: `${leftPath} ${rightPath}`,
613
- });
614
- }
615
- }
616
- }
617
- }
618
- }
619
-
620
- // witness明示unknowns。
621
- for (const todoId of todoIds) {
622
- for (const unknown of request.manual_witness[todoId].unknowns) {
623
- unknowns.push({ todo_id: todoId, kind: unknown.kind, ref: unknown.ref });
624
- }
625
- }
626
-
627
- // read/write交差は「片方が書き、他方が読む」state依存としてconflict化する
628
- // (RC2 boundary compilerのstate overlap規則の継承)。並列化してはならない。
629
- const readWriteGroups = new Map();
630
- for (let left = 0; left < todoIds.length; left += 1) {
631
- for (let right = 0; right < todoIds.length; right += 1) {
632
- if (left === right) continue;
633
- const writer = request.manual_witness[todoIds[left]];
634
- const reader = request.manual_witness[todoIds[right]];
635
- for (const writePath of writer.writes) {
636
- for (const readPath of reader.reads) {
637
- if (!pathPrefixOverlap(writePath, readPath)) continue;
638
- if (!readWriteGroups.has(writePath)) readWriteGroups.set(writePath, new Set());
639
- const group = readWriteGroups.get(writePath);
640
- group.add(todoIds[left]);
641
- group.add(todoIds[right]);
642
- }
643
- }
644
- }
645
- }
646
-
647
- // 同じ意味的な線はpathが交差しなくても共有契約である。reads同士だけは並列可とし、
648
- // 少なくとも片方がwritesのpairを独立したresourceへする。1 lineを全taskの単一resourceへ
649
- // 丸めるとreads×readsまでconflictになるため、pair単位で実体化する。
650
- const lineGroups = new Map();
651
- for (const todoId of todoIds) {
652
- for (const line of request.manual_witness[todoId].lines ?? []) {
653
- if (!lineGroups.has(line.line_id)) {
654
- lineGroups.set(line.line_id, { reads: new Set(), writes: new Set() });
655
- }
656
- lineGroups.get(line.line_id)[line.role].add(todoId);
657
- }
658
- }
659
- const lineConflictGroups = [];
660
- for (const [lineId, roles] of [...lineGroups.entries()]
661
- .sort((left, right) => compareText(left[0], right[0]))) {
662
- const participants = [...new Set([...roles.reads, ...roles.writes])].sort(compareText);
663
- for (let left = 0; left < participants.length; left += 1) {
664
- for (let right = left + 1; right < participants.length; right += 1) {
665
- const leftId = participants[left];
666
- const rightId = participants[right];
667
- if (!roles.writes.has(leftId) && !roles.writes.has(rightId)) continue;
668
- lineConflictGroups.push({ lineId, todoIds: [leftId, rightId] });
669
- }
670
- }
671
- }
672
-
673
- // state_effect宣言のないbare shared resourceは、方向不明の共有資源として
674
- // conflict化する(安全と推測しない)。
675
- const bareResourceGroups = new Map();
676
- for (const todoId of todoIds) {
677
- const witness = request.manual_witness[todoId];
678
- const declaredStateIds = new Set(witness.state_effects.map((entry) => entry.resource_id));
679
- for (const resourceId of witness.resources) {
680
- if (declaredStateIds.has(resourceId)) continue;
681
- if (!bareResourceGroups.has(resourceId)) bareResourceGroups.set(resourceId, new Set());
682
- bareResourceGroups.get(resourceId).add(todoId);
683
- }
684
- }
685
-
686
- // observation set resources。
687
- const resources = [];
688
- for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
689
- const coveringQueryId = coveringByTarget.get(key);
690
- if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
691
- const outcome = outcomeByQueryId.get(coveringQueryId);
692
- // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
693
- let representative;
694
- for (const todoId of group.todoIds) {
695
- representative = bindingsByTodo.get(todoId).find((entry) => (
696
- entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
697
- ));
698
- if (representative !== undefined) break;
699
- }
700
- if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
701
- if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
702
- const status = statusOutcome.status !== 'ready'
703
- ? statusOutcome.status
704
- : resolveBindingStatus(representative, outcome);
705
- resources.push({
706
- resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
707
- kind: group.own.kind,
708
- target: group.own.target,
709
- todo_ids: [...group.todoIds].sort(compareText),
710
- provenance: [
711
- {
712
- source: 'sensor',
713
- evidence_ref: coveringQueryId,
714
- evidence_digest: outcome.portable_digest,
715
- status,
716
- },
717
- candidateProvenance(request),
718
- ],
719
- });
720
- }
721
-
722
- const stateGroups = new Map();
723
- for (const todoId of todoIds) {
724
- for (const entry of request.manual_witness[todoId].state_effects) {
725
- if (!stateGroups.has(entry.resource_id)) {
726
- stateGroups.set(entry.resource_id, { kind: STATE_KIND_MAP[entry.kind], todoIds: new Set() });
727
- }
728
- const group = stateGroups.get(entry.resource_id);
729
- if (group.kind !== STATE_KIND_MAP[entry.kind]) {
730
- fail(`resource ${entry.resource_id}のstate/effect kindがwitness間で矛盾している`);
731
- }
732
- group.todoIds.add(todoId);
733
- }
734
- }
735
- // bare shared resourceは、同idのstate_effect宣言があればそこへmergeし、
736
- // なければ方向不明の共有state資源として独立に実体化する。
737
- for (const [resourceId, todos] of bareResourceGroups) {
738
- if (stateGroups.has(resourceId)) {
739
- const group = stateGroups.get(resourceId);
740
- for (const todoId of todos) group.todoIds.add(todoId);
741
- } else {
742
- stateGroups.set(resourceId, { kind: 'state', todoIds: todos });
743
- }
744
- }
745
- for (const [resourceId, group] of [...stateGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
746
- resources.push({
747
- resource_id: resourceId,
748
- kind: group.kind,
749
- target: resourceId,
750
- todo_ids: [...group.todoIds].sort(compareText),
751
- provenance: [manualProvenance(request)],
752
- });
753
- }
754
- for (const [writePath, todos] of [...readWriteGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
755
- resources.push({
756
- resource_id: `rw-${sha16(writePath)}`,
757
- kind: 'state',
758
- target: writePath,
759
- todo_ids: [...todos].sort(compareText),
760
- provenance: [manualProvenance(request)],
761
- });
762
- }
763
- for (const group of lineConflictGroups) {
764
- resources.push({
765
- resource_id: `line-${sha16(group.lineId)}-${sha16(group.todoIds.join('\0'))}`,
766
- kind: 'line',
767
- target: group.lineId,
768
- todo_ids: group.todoIds,
769
- provenance: [manualProvenance(request)],
770
- });
771
- }
772
- for (const [index, group] of predictedWriteGroups.entries()) {
773
- resources.push({
774
- resource_id: `predicted-ww-${sha16(`${group.target}:${index}`)}`,
775
- kind: 'state',
776
- target: group.target,
777
- todo_ids: group.todoIds,
778
- provenance: [manualProvenance(request)],
779
- });
780
- }
781
-
782
- let dynamicIndex = 0;
783
- for (const unknown of unknowns) {
784
- resources.push({
785
- resource_id: `dyn-${String(dynamicIndex += 1).padStart(3, '0')}-${sha16(`${unknown.kind}:${unknown.ref}`)}`,
786
- kind: 'dynamic',
787
- target: `${unknown.kind}:${unknown.ref}`.slice(0, 4_096).trim(),
788
- todo_ids: [unknown.todo_id],
789
- provenance: [manualProvenance(request)],
790
- });
791
- }
792
-
793
- const observationSet = {
794
- schema_version: 'lattice.boundary_observation_set.v2',
795
- source: {
796
- snapshot_digest: digestArtifact({ base_sha: request.repo.base_sha }),
797
- candidate_witness_digest: digestArtifact(request.manual_witness),
798
- query_set_digest: digestArtifact(request.sensor_query_set),
799
- manual_evidence_digest: request.request_digest,
800
- },
801
- capacity: request.capacity.executors,
802
- todos: todoIds,
803
- resources,
804
- precedences: [],
805
- };
806
-
807
- const bundle = compileBoundaryObservationV2(observationSet);
808
- const compiled = compileSchedulabilityGraphV2(bundle.graph);
809
-
810
- if (compiled.outcome === 'unsupported' && compiled.code === 'NODE_LIMIT_EXCEEDED') {
811
- return nonDispatchable('NODE_LIMIT_EXCEEDED', { todo_count: todoIds.length });
812
- }
813
- if (compiled.outcome === 'unknown') {
814
- const hasFreshAbsentPath = todoIds.some((todoId) => (
815
- bindingsByTodo.get(todoId).some((binding) => {
816
- if (!['path', 'affected'].includes(binding.expect.kind)) return false;
817
- const query = queryById.get(binding.query_id);
818
- const outcome = outcomeByQueryId.get(binding.query_id);
819
- return query.operation === 'affected'
820
- && outcome.status === 'empty'
821
- && affectedTarget(outcome.raw, binding.expect.path)?.path_state === 'absent';
822
- })
823
- ));
824
- return nonDispatchable('BOUNDARY_UNKNOWN', {
825
- unknowns: compiled.unknowns,
826
- unresolved_witnesses: unknowns,
827
- guidance: hasFreshAbsentPath
828
- ? {
829
- code: 'BOOTSTRAP_OWNERSHIP_SEAM',
830
- message: '不存在と観測されたpathは、そのTODOが作るならowns entryへcreates: trueを宣言して再compileする。宣言せずに裏付けを得るなら、親が空の専用seamをbase commitへ先行追加し、sensor sync後に同じrequestを再compileする',
831
- }
832
- : {
833
- code: 'ACQUIRE_OWNERSHIP_EVIDENCE',
834
- message: '既存path・symbol・未束縛ownershipはfresh Sensor queryを追加して同じrequestを再compileする',
835
- },
836
- });
837
- }
838
- if (compiled.outcome === 'unsupported' && compiled.code === 'SEARCH_BUDGET_EXHAUSTED') {
839
- return nonDispatchable('SEARCH_BUDGET_EXHAUSTED', {});
840
- }
841
- if (compiled.outcome !== 'compiled') fail(`未知のcompiler outcome: ${compiled.outcome}`);
842
-
843
- // producer非依存の独立verifierと必ず一致すること(成功条件5)。
844
- const verified = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
845
- if (verified.outcome !== 'verified'
846
- || verified.minimum_feasible_waves !== compiled.plan.minimum_feasible_waves) {
847
- fail(`producerとverifierの結果が一致しない: ${JSON.stringify(verified)}`);
848
- }
849
-
850
- // boundary_manifest.v2をTODOごとに構成する。
851
- const manifests = {};
852
- for (const todoId of todoIds) {
853
- const witness = request.manual_witness[todoId];
854
- const witnessProvenance = {};
855
- for (const resource of resources) {
856
- if (!resource.todo_ids.includes(todoId)) continue;
857
- witnessProvenance[resource.resource_id] = resource.kind === 'symbol' || resource.kind === 'path'
858
- ? 'sensor'
859
- : 'manual_state_effect';
860
- }
861
- const manifest = {
862
- schema: BOUNDARY_MANIFEST_SCHEMA,
863
- todo_id: todoId,
864
- owns: witness.owns,
865
- reads: witness.reads,
866
- writes: witness.writes,
867
- resources: witness.resources,
868
- state_effects: witness.state_effects,
869
- unknowns: witness.unknowns,
870
- affected_tests: witness.affected_tests,
871
- ...(witness.lines === undefined ? {} : { lines: witness.lines }),
872
- graph_evidence: bindingsByTodo.get(todoId).map((binding) => {
873
- const outcome = outcomeByQueryId.get(binding.query_id);
874
- return {
875
- query_id: binding.query_id,
876
- operation: outcome.operation,
877
- status: resolveBindingStatus(binding, outcome),
878
- result_digest: outcome.portable_digest,
879
- };
880
- }),
881
- witness_provenance: witnessProvenance,
882
- };
883
- manifest.manifest_digest = selfDigest(manifest, 'manifest_digest');
884
- if (!validateRuntimeBoundaryManifest(manifest)) {
885
- fail(`生成manifestがboundary_manifest contractを満たさない: ${todoId}`);
886
- }
887
- manifests[todoId] = manifest;
888
- }
889
-
890
- const plan = {
891
- schema: 'lattice.runtime_plan.v1',
892
- plan_ref: planRef,
893
- plan_epoch: planEpoch,
894
- request_digest: request.request_digest,
895
- base_sha: request.repo.base_sha,
896
- nodes: bundle.graph.todos.map((todoId) => ({ todo_id: todoId })),
897
- precedence: bundle.graph.precedences.map((entry) => ({
898
- from_todo_id: entry.from_todo_id,
899
- to_todo_id: entry.to_todo_id,
900
- })),
901
- conflicts: bundle.graph.conflicts,
902
- capacity: { executors: request.capacity.executors },
903
- manifest_digests: Object.fromEntries(bundle.graph.todos.map((todoId) => (
904
- [todoId, manifests[todoId].manifest_digest]
905
- ))),
906
- claim: { mode: 'exact_minimum' },
907
- predecessor_refs: [...predecessorRefs],
908
- };
909
- plan.plan_digest = selfDigest(plan, 'plan_digest');
910
- if (!validateRuntimePlan(plan)) fail('生成planがruntime_plan.v1 contractを満たさない');
911
- if (!verifyRuntimePlanBinding({ plan, request })) fail('生成planがrequestへbindできない');
912
-
913
- return {
914
- outcome: 'dispatchable',
915
- plan,
916
- manifests,
917
- schedule: compiled.plan,
918
- pairwise_verdicts: compiled.pairwise_verdicts,
919
- graph: bundle.graph,
920
- // graph.conflictsはresource_idしか持たない。resource kindはここでしか引けないため、
921
- // conflictの切断可能性を判定する消費者へnormalized resourceをそのまま渡す(ADR 0128)。
922
- resources: bundle.resources,
923
- graph_digest: bundle.graph_digest,
924
- };
925
- }
1
+ import { createHash } from 'node:crypto';
2
+
3
+ import { digestArtifact } from './artifact-contracts.mjs';
4
+ import { compileBoundaryObservationV2 } from './boundary-observation-compiler-v2.mjs';
5
+ import { portableSensorOutcome } from './sensor-adapter.mjs';
6
+ import { compileSchedulabilityGraphV2 } from './schedulability-compiler-v2.mjs';
7
+ import { verifySchedulabilityPlanV2 } from './schedulability-verifier-v2.mjs';
8
+ import {
9
+ BOUNDARY_MANIFEST_SCHEMA,
10
+ RUN_REQUEST_PREDICTION_SCHEMA,
11
+ RUN_REQUEST_SCHEMA,
12
+ SENSOR_EXPECT_KINDS,
13
+ SENSOR_QUERY_OPERATIONS,
14
+ selfDigest,
15
+ validateRunRequest,
16
+ validateRuntimeBoundaryManifest,
17
+ validateRuntimePlan,
18
+ verifyRuntimePlanBinding,
19
+ } from './runtime-contracts.mjs';
20
+
21
+ /**
22
+ * RC3-D generic front-end(ADR 0044 Decision 2・8、plan RC3-D)。
23
+ *
24
+ * `lattice.run_request.v1`のmanual witnessとfresh LatticeSensor観測evidenceから、
25
+ * fixture名・期待conflict・期待waveの分岐なしに`lattice.runtime_plan.v1`と
26
+ * TODOごとの`lattice.boundary_manifest.v2`をcompileする。
27
+ *
28
+ * adapter契約(witness.sensor_provenance、RC3-Dで固定):
29
+ * { queries: [{ query_id, expect }] }
30
+ * expect = { kind: 'symbol', name, path } — query outcomeにnode.name/filePathの
31
+ * exact一致がちょうど1件あることを要求(fuzzy解決の誤読防止)
32
+ * | { kind: 'path', path } — outcomeにfilePath exact一致が1件以上
33
+ * | { kind: 'affected', path } — affected outcomeのchangedFilesが[path]と
34
+ * exact一致し、affectedTestsがwitness.affected_testsとexact一致
35
+ *
36
+ * typed non-dispatchable(dispatchable planを発行しない、fail closed):
37
+ * NODE_LIMIT_EXCEEDED / BOUNDARY_UNKNOWN / SEARCH_BUDGET_EXHAUSTED /
38
+ * QUERY_DRIFT / AFFECTED_TEST_DRIFT
39
+ *
40
+ * LatticeSensor raw telemetryはevidence captureに留め、plan・manifest identityへは
41
+ * portable outcome projectionのcanonical digestだけを入れる(Decision 10.4)。
42
+ */
43
+
44
+ // 閉集合の正本はruntime-contracts。ここでは輸入して使う。
45
+ const QUERY_OPERATIONS = SENSOR_QUERY_OPERATIONS;
46
+ const STRUCTURE_OPERATIONS = new Set(['query', 'callers', 'callees', 'impact']);
47
+ const EXPECT_KINDS = new Set(SENSOR_EXPECT_KINDS);
48
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
49
+ const STATE_KIND_MAP = Object.freeze({
50
+ state: 'state',
51
+ schema: 'state',
52
+ invariant: 'state',
53
+ effect: 'effect',
54
+ external_effect: 'effect',
55
+ });
56
+
57
+ export const RUNTIME_NON_DISPATCHABLE_CODES = Object.freeze([
58
+ 'NODE_LIMIT_EXCEEDED',
59
+ 'BOUNDARY_UNKNOWN',
60
+ 'SEARCH_BUDGET_EXHAUSTED',
61
+ 'QUERY_DRIFT',
62
+ 'AFFECTED_TEST_DRIFT',
63
+ ]);
64
+
65
+ function fail(reason) {
66
+ throw new TypeError(`runtime front-end契約違反: ${reason}`);
67
+ }
68
+
69
+ function plainRecord(value) {
70
+ return value !== null
71
+ && typeof value === 'object'
72
+ && !Array.isArray(value)
73
+ && Object.getPrototypeOf(value) === Object.prototype;
74
+ }
75
+
76
+ function exactRecord(value, keys) {
77
+ if (!plainRecord(value)) return false;
78
+ const actual = Object.keys(value).sort();
79
+ const expected = [...keys].sort();
80
+ return actual.length === expected.length
81
+ && actual.every((key, index) => key === expected[index]);
82
+ }
83
+
84
+ function identifier(value) {
85
+ return typeof value === 'string' && IDENTIFIER.test(value);
86
+ }
87
+
88
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
89
+
90
+ /**
91
+ * repo相対pathだけを受理する(runtime-contracts.mjsと同じ規律、Decision 2・10.4)。
92
+ * absolute path・`..`・空segment・制御文字・`\`をmanifest/plan identityへ混入させない。
93
+ */
94
+ function repoRelativePath(value, { allowPrefix = false } = {}) {
95
+ if (typeof value !== 'string'
96
+ || value.length === 0
97
+ || Buffer.byteLength(value, 'utf8') > 1_024
98
+ || CONTROL_CHARACTER.test(value)
99
+ || value.includes('\\')
100
+ || value.startsWith('/')) {
101
+ return false;
102
+ }
103
+ const isPrefix = value.endsWith('/');
104
+ if (isPrefix && !allowPrefix) return false;
105
+ const body = isPrefix ? value.slice(0, -1) : value;
106
+ return body.split('/').every((segment) => (
107
+ segment.length > 0 && segment !== '.' && segment !== '..'
108
+ ));
109
+ }
110
+
111
+ function sha16(value) {
112
+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
113
+ }
114
+
115
+ function compareText(left, right) {
116
+ if (left < right) return -1;
117
+ if (left > right) return 1;
118
+ return 0;
119
+ }
120
+
121
+ function nonDispatchable(code, detail) {
122
+ if (!RUNTIME_NON_DISPATCHABLE_CODES.includes(code)) fail(`未知のnon-dispatchable code: ${code}`);
123
+ return { outcome: 'non_dispatchable', code, detail };
124
+ }
125
+
126
+ /** query set(run_request.sensor_query_set)のexact shapeを検査する。 */
127
+ function normalizeQuerySet(querySet) {
128
+ if (!exactRecord(querySet, ['queries'])) fail('sensor_query_set shapeが不正');
129
+ if (!Array.isArray(querySet.queries)) fail('sensor_query_set.queriesがarrayではない');
130
+ const byId = new Map();
131
+ for (const query of querySet.queries) {
132
+ const keys = Object.hasOwn(query ?? {}, 'target')
133
+ ? ['id', 'operation', 'target']
134
+ : ['id', 'operation'];
135
+ if (!exactRecord(query, keys)
136
+ || !identifier(query.id)
137
+ || !QUERY_OPERATIONS.includes(query.operation)
138
+ || (keys.includes('target') && (typeof query.target !== 'string' || query.target.length === 0))) {
139
+ fail('query set entry shapeが不正');
140
+ }
141
+ if (byId.has(query.id)) fail(`query idが重複している: ${query.id}`);
142
+ byId.set(query.id, query);
143
+ }
144
+ return byId;
145
+ }
146
+
147
+ /**
148
+ * captureされたevidenceをquery setとexact整合させ、portable projectionへ分離する。
149
+ * evidence = { outcomes: [{ query_id, operation, status, raw }] }(query set順)
150
+ */
151
+ function normalizeEvidence(evidence, queryById) {
152
+ if (!exactRecord(evidence, ['outcomes'])) fail('sensor evidence shapeが不正');
153
+ if (!Array.isArray(evidence.outcomes)) fail('evidence.outcomesがarrayではない');
154
+ if (evidence.outcomes.length !== queryById.size) {
155
+ fail(`evidence件数(${evidence.outcomes.length})がquery set件数(${queryById.size})と一致しない`);
156
+ }
157
+ const queries = [...queryById.values()];
158
+ const byQueryId = new Map();
159
+ evidence.outcomes.forEach((outcome, index) => {
160
+ if (!exactRecord(outcome, ['query_id', 'operation', 'status', 'raw'])) {
161
+ fail('evidence outcome shapeが不正');
162
+ }
163
+ const query = queries[index];
164
+ if (outcome.query_id !== query.id || outcome.operation !== query.operation) {
165
+ fail(`evidence outcomeがquery setと順序整合しない: ${outcome.query_id}`);
166
+ }
167
+ if (typeof outcome.status !== 'string' || outcome.status.length === 0) {
168
+ fail('evidence outcome statusが不正');
169
+ }
170
+ const portable = portableSensorOutcome(outcome.raw);
171
+ byQueryId.set(outcome.query_id, {
172
+ query_id: outcome.query_id,
173
+ operation: outcome.operation,
174
+ status: outcome.status,
175
+ raw: outcome.raw,
176
+ portable,
177
+ portable_digest: digestArtifact({
178
+ query_id: outcome.query_id,
179
+ operation: outcome.operation,
180
+ status: outcome.status,
181
+ portable,
182
+ }),
183
+ });
184
+ });
185
+ return byQueryId;
186
+ }
187
+
188
+ function normalizeProvenanceQueries(witness, todoId) {
189
+ const provenance = witness.sensor_provenance;
190
+ if (!exactRecord(provenance, ['queries']) || !Array.isArray(provenance.queries)) {
191
+ fail(`witness ${todoId}.sensor_provenance shapeが不正`);
192
+ }
193
+ return provenance.queries.map((entry) => {
194
+ if (!exactRecord(entry, ['query_id', 'expect']) || !identifier(entry.query_id)) {
195
+ fail(`witness ${todoId}.sensor_provenance entry shapeが不正`);
196
+ }
197
+ const expect = entry.expect;
198
+ if (!plainRecord(expect) || !EXPECT_KINDS.has(expect.kind)) {
199
+ fail(`witness ${todoId}.expect shapeが不正`);
200
+ }
201
+ if (expect.kind === 'symbol') {
202
+ if (!exactRecord(expect, ['kind', 'name', 'path'])
203
+ || typeof expect.name !== 'string' || expect.name.length === 0
204
+ || !repoRelativePath(expect.path)) {
205
+ fail(`witness ${todoId}.symbol expectが不正`);
206
+ }
207
+ } else if (!exactRecord(expect, ['kind', 'path']) || !repoRelativePath(expect.path)) {
208
+ fail(`witness ${todoId}.${expect.kind} expectが不正`);
209
+ }
210
+ return { query_id: entry.query_id, expect };
211
+ });
212
+ }
213
+
214
+ const STRUCTURE_EXPECT_OPERATIONS = new Set(['query', 'callers', 'callees', 'impact']);
215
+
216
+ /**
217
+ * witness expectとquery set entryのcross-binding(別targetのreceiptへの再ラベル防止)。
218
+ * 不一致はQUERY_DRIFT。
219
+ */
220
+ function bindingMatchesQuery(binding, query) {
221
+ const { expect } = binding;
222
+ if (expect.kind === 'affected') {
223
+ return query.operation === 'affected' && query.target === expect.path;
224
+ }
225
+ if (expect.kind === 'symbol') {
226
+ return STRUCTURE_EXPECT_OPERATIONS.has(query.operation) && query.target === expect.name;
227
+ }
228
+ return (STRUCTURE_EXPECT_OPERATIONS.has(query.operation) || query.operation === 'affected')
229
+ && query.target === expect.path;
230
+ }
231
+
232
+ /** raw outcome(`{operation, data}`包み、RC2 evidence互換)のpayloadを取り出す。 */
233
+ function rawPayload(raw) {
234
+ return plainRecord(raw) && Object.hasOwn(raw, 'data') ? raw.data : raw;
235
+ }
236
+
237
+ /**
238
+ * affected outcomeのpayloadを取り出す。lattice-sensor-adapterのper-target形
239
+ * (`{targets: [{target, outcome, data}]}`)と直接data形の両方を受ける。
240
+ */
241
+ function affectedPayload(raw, expectPath) {
242
+ if (plainRecord(raw) && Array.isArray(raw.targets)) {
243
+ const entry = raw.targets.find((candidate) => (
244
+ plainRecord(candidate) && candidate.target === expectPath
245
+ ));
246
+ return plainRecord(entry) && plainRecord(entry.data) ? entry.data : null;
247
+ }
248
+ const payload = rawPayload(raw);
249
+ return plainRecord(payload) ? payload : null;
250
+ }
251
+
252
+ /**
253
+ * 収集済みsensor evidenceから、あるpathのaffected testを読む。
254
+ *
255
+ * 実行時の翻訳段(宣言を観測へ合わせる)が同じ観測を必要とする。payloadの形の解釈をあちらへ
256
+ * 書き直すと、driftを判定する規則と、driftを起こさない宣言を作る規則が別々に育つ。
257
+ *
258
+ * @returns {string[]|null} 観測できなければnull(空配列と区別する)
259
+ */
260
+ export function affectedTestsFromEvidence({ sensorEvidence, querySet, path: target } = {}) {
261
+ const queries = (querySet?.queries ?? [])
262
+ .filter((query) => query.operation === 'affected' && query.target === target);
263
+ if (queries.length !== 1) return null;
264
+ const outcome = (sensorEvidence?.outcomes ?? [])
265
+ .find((entry) => entry.query_id === queries[0].id);
266
+ if (!plainRecord(outcome) || outcome.status !== 'ready') return null;
267
+ const payload = affectedPayload(outcome.raw, target);
268
+ return Array.isArray(payload?.affectedTests) ? [...payload.affectedTests].sort(compareText) : null;
269
+ }
270
+
271
+ function affectedTarget(raw, expectPath) {
272
+ if (!plainRecord(raw) || !Array.isArray(raw.targets)) return null;
273
+ const entry = raw.targets.find((candidate) => (
274
+ plainRecord(candidate) && candidate.target === expectPath
275
+ ));
276
+ return plainRecord(entry) ? entry : null;
277
+ }
278
+
279
+ function rawEntries(raw) {
280
+ const payload = rawPayload(raw);
281
+ return Array.isArray(payload) ? payload : null;
282
+ }
283
+
284
+ function entryNode(entry) {
285
+ if (plainRecord(entry) && plainRecord(entry.node)) return entry.node;
286
+ if (plainRecord(entry)) return entry;
287
+ return null;
288
+ }
289
+
290
+ /**
291
+ * 創作宣言されたpathの裏付けを決める(ADR 0136)。
292
+ *
293
+ * 宣言と観測が一致する時だけ`ready`にする。fresh absentは推測ではなくfsのlstat結果なので、
294
+ * 「観測できなかった」ではなく「観測して、無かった」である。存在しないfileに依存するものは
295
+ * 構造的に存在しえないため、affected testが空であることまで確かめれば裏付けは閉じる。
296
+ *
297
+ * 既に存在するpathへ創作を宣言していたら`creates_path_present`で止める。実害は無いが、
298
+ * 宣言が実態からずれているのを黙って通すと、宣言と観測が一致しているという前提が崩れる。
299
+ * 宣言していないabsent pathは従来どおり`path_absent`のままにする——綴り違いを
300
+ * 「黙って通る創作境界」にしないための線である。
301
+ */
302
+ function creationBoundaryStatus(outcome, expectPath) {
303
+ // sensorが答えられていない状況は、この関数の管轄でない。通常のstatus判定へ返す。
304
+ if (!['ready', 'empty'].includes(outcome.status)) return null;
305
+ const target = affectedTarget(outcome.raw, expectPath);
306
+ // fs観測が記録に無いなら、不存在は確かめられていない。宣言だけで裏付けにしない。
307
+ if (target === null || target === undefined) return 'creates_unverified';
308
+ if (target.path_state !== 'absent') return 'creates_path_present';
309
+ const payload = affectedPayload(outcome.raw, expectPath);
310
+ if (payload === null
311
+ || !Array.isArray(payload.changedFiles)
312
+ || payload.changedFiles.length !== 1
313
+ || payload.changedFiles[0] !== expectPath
314
+ || !Array.isArray(payload.affectedTests)
315
+ || payload.affectedTests.length !== 0) return 'creates_unverified';
316
+ return 'ready';
317
+ }
318
+
319
+ /**
320
+ * 束縛queryのoutcomeへexpectをexact照合し、sensor statusを決める。
321
+ * fuzzy解決・空結果は依存なしへ丸めず、unknown系statusへ落とす(AGENTS.md)。
322
+ */
323
+ function resolveBindingStatus(binding, outcome) {
324
+ if (binding.expect.kind === 'affected' && binding.creates === true) {
325
+ const declared = creationBoundaryStatus(outcome, binding.expect.path);
326
+ if (declared !== null) return declared;
327
+ }
328
+ if (outcome.status !== 'ready') return outcome.status;
329
+ const { expect } = binding;
330
+ if (expect.kind === 'affected') {
331
+ if (affectedTarget(outcome.raw, expect.path)?.path_state === 'absent') return 'path_absent';
332
+ const payload = affectedPayload(outcome.raw, expect.path);
333
+ if (payload === null
334
+ || !Array.isArray(payload.changedFiles)
335
+ || payload.changedFiles.length !== 1
336
+ || payload.changedFiles[0] !== expect.path) {
337
+ return 'empty';
338
+ }
339
+ return 'ready';
340
+ }
341
+ const entries = rawEntries(outcome.raw);
342
+ if (entries === null) return 'invalid_json';
343
+ if (expect.kind === 'symbol') {
344
+ const matches = entries.filter((entry) => {
345
+ const node = entryNode(entry);
346
+ return node !== null && node.name === expect.name && node.filePath === expect.path;
347
+ });
348
+ if (matches.length === 1) return 'ready';
349
+ return matches.length === 0 ? 'symbol_absent' : 'unresolved';
350
+ }
351
+ const matches = entries.filter((entry) => {
352
+ const node = entryNode(entry);
353
+ return node !== null && node.filePath === expect.path;
354
+ });
355
+ return matches.length >= 1 ? 'ready' : 'empty';
356
+ }
357
+
358
+ function bindingCoversOwn(binding, own) {
359
+ if (own.kind === 'symbol') {
360
+ return binding.expect.kind === 'symbol' && binding.expect.name === own.target;
361
+ }
362
+ return (binding.expect.kind === 'path' || binding.expect.kind === 'affected')
363
+ && binding.expect.path === own.target;
364
+ }
365
+
366
+ function pathPrefixOverlap(left, right) {
367
+ const leftIsPrefix = left.endsWith('/');
368
+ const rightIsPrefix = right.endsWith('/');
369
+ if (left === right) return true;
370
+ if (leftIsPrefix && (right === left.slice(0, -1) || right.startsWith(left))) return true;
371
+ if (rightIsPrefix && (left === right.slice(0, -1) || left.startsWith(right))) return true;
372
+ return false;
373
+ }
374
+
375
+ function manualProvenance(request) {
376
+ return {
377
+ source: 'manual_state_effect',
378
+ evidence_ref: `run-request:${request.request_id}`,
379
+ evidence_digest: request.request_digest,
380
+ status: 'asserted',
381
+ };
382
+ }
383
+
384
+ function candidateProvenance(request) {
385
+ return {
386
+ source: 'manual_candidate_spec',
387
+ evidence_ref: `run-request:${request.request_id}`,
388
+ evidence_digest: request.request_digest,
389
+ status: 'asserted',
390
+ };
391
+ }
392
+
393
+ /**
394
+ * `collectSensorEvidence`のraw収集結果を、query set順へexact整合した
395
+ * front-end evidence契約(`{outcomes: [{query_id, operation, status, raw}]}`)へ写す。
396
+ * 件数・id・operationの不一致はfail closed。
397
+ */
398
+ export function evidenceFromCollectedOutcomes(options = {}) {
399
+ if (!exactRecord(options, ['querySet', 'collected'])) {
400
+ fail('evidenceFromCollectedOutcomes optionsがexact shapeでない');
401
+ }
402
+ const { querySet, collected } = options;
403
+ const queryById = normalizeQuerySet(querySet);
404
+ if (!plainRecord(collected) || !Array.isArray(collected.outcomes)) {
405
+ fail('collected evidence shapeが不正');
406
+ }
407
+ if (collected.outcomes.length !== queryById.size) {
408
+ fail(`collected outcomes件数(${collected.outcomes.length})がquery set件数(${queryById.size})と一致しない`);
409
+ }
410
+ const queries = [...queryById.values()];
411
+ return {
412
+ outcomes: collected.outcomes.map((outcome, index) => {
413
+ const query = queries[index];
414
+ if (!plainRecord(outcome)
415
+ || (Object.hasOwn(outcome, 'id') && outcome.id !== query.id)
416
+ || (Object.hasOwn(outcome, 'operation') && outcome.operation !== query.operation)
417
+ || typeof outcome.outcome !== 'string'
418
+ || outcome.outcome.length === 0) {
419
+ fail(`collected outcomeがquery setと整合しない: ${query.id}`);
420
+ }
421
+ return {
422
+ query_id: query.id,
423
+ operation: query.operation,
424
+ status: outcome.outcome,
425
+ raw: outcome,
426
+ };
427
+ }),
428
+ };
429
+ }
430
+
431
+ /**
432
+ * run_requestとsensor evidenceからobservation set・graph・planを一括compileする。
433
+ * 成功時はdispatchable outcome、契約内の識別可能な不成立はtyped non-dispatchable、
434
+ * 入力shape違反はTypeErrorでfail closed。
435
+ */
436
+ export function compileRuntimePlanV1(options = {}) {
437
+ if (!exactRecord(options, ['request', 'sensorEvidence', 'planRef', 'planEpoch', 'predecessorRefs'])) {
438
+ fail('compileRuntimePlanV1 optionsがexact shapeでない');
439
+ }
440
+ const { request, sensorEvidence, planRef, planEpoch, predecessorRefs } = options;
441
+ if (!validateRunRequest(request)) fail('run_request.v1がcontractを満たさない');
442
+ if (!identifier(planRef)) fail('planRefがidentifierではない');
443
+ if (!Number.isSafeInteger(planEpoch) || planEpoch < 0) fail('planEpochが不正');
444
+ if (!Array.isArray(predecessorRefs) || !predecessorRefs.every((ref) => typeof ref === 'string')) {
445
+ fail('predecessorRefsがstring arrayではない');
446
+ }
447
+
448
+ const queryById = normalizeQuerySet(request.sensor_query_set);
449
+ const outcomeByQueryId = normalizeEvidence(sensorEvidence, queryById);
450
+
451
+ const todoIds = request.todos.map((todo) => todo.todo_id);
452
+ const predictionsOnly = [RUN_REQUEST_SCHEMA, RUN_REQUEST_PREDICTION_SCHEMA]
453
+ .includes(request.schema);
454
+
455
+ // witnessの束縛を解決する。query set外の参照と、expect↔query targetの
456
+ // 不一致(別targetのreceiptへの再ラベル)はQUERY_DRIFT。
457
+ const bindingsByTodo = new Map();
458
+ const driftDetails = [];
459
+ for (const todoId of todoIds) {
460
+ const witness = request.manual_witness[todoId];
461
+ // 創作宣言はowns側にある。裏付けを決めるのはbindingなので、覆っているbindingへ写す。
462
+ const creating = new Set(witness.owns
463
+ .filter((own) => own.creates === true).map((own) => own.target));
464
+ const bindings = normalizeProvenanceQueries(witness, todoId)
465
+ .map((binding) => (!predictionsOnly && creating.size > 0
466
+ && [...creating].some((target) => bindingCoversOwn(binding, { kind: 'path', target }))
467
+ ? { ...binding, creates: true } : binding));
468
+ for (const binding of bindings) {
469
+ const query = queryById.get(binding.query_id);
470
+ if (query === undefined) {
471
+ driftDetails.push({ todo_id: todoId, query_id: binding.query_id, reason: 'query set外の参照' });
472
+ } else if (!bindingMatchesQuery(binding, query)) {
473
+ driftDetails.push({
474
+ todo_id: todoId,
475
+ query_id: binding.query_id,
476
+ reason: 'expectとquery operation/targetが一致しない',
477
+ });
478
+ }
479
+ }
480
+ bindingsByTodo.set(todoId, bindings);
481
+ }
482
+ if (driftDetails.length > 0) return nonDispatchable('QUERY_DRIFT', { references: driftDetails });
483
+
484
+ // status queryは正確に1つ要求し、fresh index規律をここで検査する。
485
+ const statusQueries = [...queryById.values()].filter((query) => query.operation === 'status');
486
+ if (statusQueries.length !== 1) {
487
+ return nonDispatchable('QUERY_DRIFT', {
488
+ references: [{ reason: `status queryが${statusQueries.length}件(正確に1件が必要)` }],
489
+ });
490
+ }
491
+ const statusOutcome = outcomeByQueryId.get(statusQueries[0].id);
492
+
493
+ const unknowns = [];
494
+ if (statusOutcome.status !== 'ready') {
495
+ for (const todoId of todoIds) {
496
+ unknowns.push({ todo_id: todoId, kind: `sensor_${statusOutcome.status}`, ref: statusQueries[0].id });
497
+ }
498
+ }
499
+
500
+ // 全束縛queryの解決statusを検査する。非readyな構造/affected evidenceは
501
+ // dispatchable planへ丸めず、unknownとしてevidence acquisitionへ送る。
502
+ for (const todoId of todoIds) {
503
+ for (const binding of bindingsByTodo.get(todoId)) {
504
+ const resolved = resolveBindingStatus(binding, outcomeByQueryId.get(binding.query_id));
505
+ if (!predictionsOnly && resolved !== 'ready') {
506
+ unknowns.push({ todo_id: todoId, kind: `sensor_${resolved}`, ref: binding.query_id });
507
+ }
508
+ }
509
+ }
510
+
511
+ // affected test drift検査(witness宣言とfresh affected観測のexact比較)。
512
+ //
513
+ // 比較はTODO単位で、そのTODOが持つ**全affected束縛の観測の和**に対して行う。1面しか持たない
514
+ // TODOでは束縛ごとの比較と同じ結果になり、複数面を所有するTODOでも表現できる——束縛ごとに
515
+ // 宣言全体とexact比較すると、affectedの異なる2 pathを所有するTODOは原理的に成立せず、
516
+ // 実行時に所有が広がった宣言を受け取れなくなる。和なので緩みは入らない(余分な宣言も
517
+ // 足りない宣言もdriftのまま)。
518
+ const affectedDrift = [];
519
+ for (const todoId of todoIds) {
520
+ const witness = request.manual_witness[todoId];
521
+ const declared = [...witness.affected_tests].sort(compareText);
522
+ const queryIds = [];
523
+ const observedUnion = new Set();
524
+ let unreadable = false;
525
+ for (const binding of bindingsByTodo.get(todoId)) {
526
+ if (binding.expect.kind !== 'affected') continue;
527
+ const outcome = outcomeByQueryId.get(binding.query_id);
528
+ if (resolveBindingStatus(binding, outcome) !== 'ready') continue;
529
+ queryIds.push(binding.query_id);
530
+ const payload = affectedPayload(outcome.raw, binding.expect.path);
531
+ if (!Array.isArray(payload?.affectedTests)) {
532
+ // 観測が読めないのは「一致しない」とは別の事象である。丸めずそのまま残す。
533
+ affectedDrift.push({ todo_id: todoId, query_id: binding.query_id, declared, observed: null });
534
+ unreadable = true;
535
+ continue;
536
+ }
537
+ for (const test of payload.affectedTests) observedUnion.add(test);
538
+ }
539
+ if (unreadable || queryIds.length === 0) continue;
540
+ const observed = [...observedUnion].sort(compareText);
541
+ if (observed.length !== declared.length
542
+ || observed.some((test, index) => test !== declared[index])) {
543
+ affectedDrift.push({
544
+ todo_id: todoId,
545
+ query_id: queryIds.sort(compareText).join(','),
546
+ declared,
547
+ observed,
548
+ });
549
+ }
550
+ }
551
+ if (!predictionsOnly && affectedDrift.length > 0) {
552
+ return nonDispatchable('AFFECTED_TEST_DRIFT', { mismatches: affectedDrift });
553
+ }
554
+
555
+ // owns targetごとの構造的裏付け。covering queryは全witnessを通じて一意でなければならない。
556
+ const ownGroups = new Map();
557
+ const coveringByTarget = new Map();
558
+ const ambiguous = [];
559
+ for (const todoId of todoIds) {
560
+ const witness = request.manual_witness[todoId];
561
+ for (const own of witness.owns) {
562
+ if (own.kind === 'path' && !repoRelativePath(own.target, { allowPrefix: true })) {
563
+ fail(`witness ${todoId}のowns pathがrepo相対規律を満たさない: ${own.target}`);
564
+ }
565
+ const key = `${own.kind} ${own.target}`;
566
+ if (!ownGroups.has(key)) ownGroups.set(key, { own, todoIds: [] });
567
+ ownGroups.get(key).todoIds.push(todoId);
568
+ const covering = bindingsByTodo.get(todoId).filter((binding) => bindingCoversOwn(binding, own));
569
+ for (const binding of covering) {
570
+ const seen = coveringByTarget.get(key);
571
+ if (seen === undefined) {
572
+ coveringByTarget.set(key, binding.query_id);
573
+ } else if (seen !== binding.query_id) {
574
+ ambiguous.push({ target: own.target, query_ids: [seen, binding.query_id].sort(compareText) });
575
+ }
576
+ }
577
+ if (!predictionsOnly && covering.length === 0) {
578
+ unknowns.push({ todo_id: todoId, kind: 'sensor_unbound', ref: `${own.kind}:${own.target}` });
579
+ }
580
+ }
581
+ }
582
+ if (ambiguous.length > 0) return nonDispatchable('QUERY_DRIFT', { ambiguous_targets: ambiguous });
583
+
584
+ // 最新契約ではwrite scopeは予測である。既知の交差はserial conflictへ使うが、
585
+ // 予測が足りないこと自体はunknownへ落とさない。
586
+ const predictedWriteGroups = [];
587
+ for (let left = 0; left < todoIds.length; left += 1) {
588
+ for (let right = left + 1; right < todoIds.length; right += 1) {
589
+ const leftWitness = request.manual_witness[todoIds[left]];
590
+ const rightWitness = request.manual_witness[todoIds[right]];
591
+ const leftOwnPaths = new Set(leftWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
592
+ const rightOwnPaths = new Set(rightWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
593
+ for (const leftPath of leftWitness.writes) {
594
+ for (const rightPath of rightWitness.writes) {
595
+ if (!pathPrefixOverlap(leftPath, rightPath)) continue;
596
+ // 同一targetを両者がownsで所有主張している場合はwrite conflictとして
597
+ // resource経由で扱われる。owns解決のない交差だけをunknownにする。
598
+ if (leftOwnPaths.has(leftPath) && rightOwnPaths.has(rightPath)
599
+ && leftPath === rightPath) continue;
600
+ if (predictionsOnly) {
601
+ predictedWriteGroups.push({
602
+ target: [leftPath, rightPath].sort(compareText).join(' ↔ '),
603
+ todoIds: [todoIds[left], todoIds[right]],
604
+ });
605
+ } else {
606
+ unknowns.push({
607
+ todo_id: todoIds[left], kind: 'undeclared_write_overlap',
608
+ ref: `${leftPath} ${rightPath}`,
609
+ });
610
+ unknowns.push({
611
+ todo_id: todoIds[right], kind: 'undeclared_write_overlap',
612
+ ref: `${leftPath} ${rightPath}`,
613
+ });
614
+ }
615
+ }
616
+ }
617
+ }
618
+ }
619
+
620
+ // witness明示unknowns。
621
+ for (const todoId of todoIds) {
622
+ for (const unknown of request.manual_witness[todoId].unknowns) {
623
+ unknowns.push({ todo_id: todoId, kind: unknown.kind, ref: unknown.ref });
624
+ }
625
+ }
626
+
627
+ // read/write交差は「片方が書き、他方が読む」state依存としてconflict化する
628
+ // (RC2 boundary compilerのstate overlap規則の継承)。並列化してはならない。
629
+ const readWriteGroups = new Map();
630
+ for (let left = 0; left < todoIds.length; left += 1) {
631
+ for (let right = 0; right < todoIds.length; right += 1) {
632
+ if (left === right) continue;
633
+ const writer = request.manual_witness[todoIds[left]];
634
+ const reader = request.manual_witness[todoIds[right]];
635
+ for (const writePath of writer.writes) {
636
+ for (const readPath of reader.reads) {
637
+ if (!pathPrefixOverlap(writePath, readPath)) continue;
638
+ if (!readWriteGroups.has(writePath)) readWriteGroups.set(writePath, new Set());
639
+ const group = readWriteGroups.get(writePath);
640
+ group.add(todoIds[left]);
641
+ group.add(todoIds[right]);
642
+ }
643
+ }
644
+ }
645
+ }
646
+
647
+ // 同じ意味的な線はpathが交差しなくても共有契約である。reads同士だけは並列可とし、
648
+ // 少なくとも片方がwritesのpairを独立したresourceへする。1 lineを全taskの単一resourceへ
649
+ // 丸めるとreads×readsまでconflictになるため、pair単位で実体化する。
650
+ const lineGroups = new Map();
651
+ for (const todoId of todoIds) {
652
+ for (const line of request.manual_witness[todoId].lines ?? []) {
653
+ if (!lineGroups.has(line.line_id)) {
654
+ lineGroups.set(line.line_id, { reads: new Set(), writes: new Set() });
655
+ }
656
+ lineGroups.get(line.line_id)[line.role].add(todoId);
657
+ }
658
+ }
659
+ const lineConflictGroups = [];
660
+ for (const [lineId, roles] of [...lineGroups.entries()]
661
+ .sort((left, right) => compareText(left[0], right[0]))) {
662
+ const participants = [...new Set([...roles.reads, ...roles.writes])].sort(compareText);
663
+ for (let left = 0; left < participants.length; left += 1) {
664
+ for (let right = left + 1; right < participants.length; right += 1) {
665
+ const leftId = participants[left];
666
+ const rightId = participants[right];
667
+ if (!roles.writes.has(leftId) && !roles.writes.has(rightId)) continue;
668
+ lineConflictGroups.push({ lineId, todoIds: [leftId, rightId] });
669
+ }
670
+ }
671
+ }
672
+
673
+ // state_effect宣言のないbare shared resourceは、方向不明の共有資源として
674
+ // conflict化する(安全と推測しない)。
675
+ const bareResourceGroups = new Map();
676
+ for (const todoId of todoIds) {
677
+ const witness = request.manual_witness[todoId];
678
+ const declaredStateIds = new Set(witness.state_effects.map((entry) => entry.resource_id));
679
+ for (const resourceId of witness.resources) {
680
+ if (declaredStateIds.has(resourceId)) continue;
681
+ if (!bareResourceGroups.has(resourceId)) bareResourceGroups.set(resourceId, new Set());
682
+ bareResourceGroups.get(resourceId).add(todoId);
683
+ }
684
+ }
685
+
686
+ // observation set resources。
687
+ const resources = [];
688
+ for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
689
+ const coveringQueryId = coveringByTarget.get(key);
690
+ if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
691
+ const outcome = outcomeByQueryId.get(coveringQueryId);
692
+ // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
693
+ let representative;
694
+ for (const todoId of group.todoIds) {
695
+ representative = bindingsByTodo.get(todoId).find((entry) => (
696
+ entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
697
+ ));
698
+ if (representative !== undefined) break;
699
+ }
700
+ if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
701
+ if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
702
+ const status = statusOutcome.status !== 'ready'
703
+ ? statusOutcome.status
704
+ : resolveBindingStatus(representative, outcome);
705
+ resources.push({
706
+ resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
707
+ kind: group.own.kind,
708
+ target: group.own.target,
709
+ todo_ids: [...group.todoIds].sort(compareText),
710
+ provenance: [
711
+ {
712
+ source: 'sensor',
713
+ evidence_ref: coveringQueryId,
714
+ evidence_digest: outcome.portable_digest,
715
+ status,
716
+ },
717
+ candidateProvenance(request),
718
+ ],
719
+ });
720
+ }
721
+
722
+ const stateGroups = new Map();
723
+ for (const todoId of todoIds) {
724
+ for (const entry of request.manual_witness[todoId].state_effects) {
725
+ if (!stateGroups.has(entry.resource_id)) {
726
+ stateGroups.set(entry.resource_id, { kind: STATE_KIND_MAP[entry.kind], todoIds: new Set() });
727
+ }
728
+ const group = stateGroups.get(entry.resource_id);
729
+ if (group.kind !== STATE_KIND_MAP[entry.kind]) {
730
+ fail(`resource ${entry.resource_id}のstate/effect kindがwitness間で矛盾している`);
731
+ }
732
+ group.todoIds.add(todoId);
733
+ }
734
+ }
735
+ // bare shared resourceは、同idのstate_effect宣言があればそこへmergeし、
736
+ // なければ方向不明の共有state資源として独立に実体化する。
737
+ for (const [resourceId, todos] of bareResourceGroups) {
738
+ if (stateGroups.has(resourceId)) {
739
+ const group = stateGroups.get(resourceId);
740
+ for (const todoId of todos) group.todoIds.add(todoId);
741
+ } else {
742
+ stateGroups.set(resourceId, { kind: 'state', todoIds: todos });
743
+ }
744
+ }
745
+ for (const [resourceId, group] of [...stateGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
746
+ resources.push({
747
+ resource_id: resourceId,
748
+ kind: group.kind,
749
+ target: resourceId,
750
+ todo_ids: [...group.todoIds].sort(compareText),
751
+ provenance: [manualProvenance(request)],
752
+ });
753
+ }
754
+ for (const [writePath, todos] of [...readWriteGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
755
+ resources.push({
756
+ resource_id: `rw-${sha16(writePath)}`,
757
+ kind: 'state',
758
+ target: writePath,
759
+ todo_ids: [...todos].sort(compareText),
760
+ provenance: [manualProvenance(request)],
761
+ });
762
+ }
763
+ for (const group of lineConflictGroups) {
764
+ resources.push({
765
+ resource_id: `line-${sha16(group.lineId)}-${sha16(group.todoIds.join('\0'))}`,
766
+ kind: 'line',
767
+ target: group.lineId,
768
+ todo_ids: group.todoIds,
769
+ provenance: [manualProvenance(request)],
770
+ });
771
+ }
772
+ for (const [index, group] of predictedWriteGroups.entries()) {
773
+ resources.push({
774
+ resource_id: `predicted-ww-${sha16(`${group.target}:${index}`)}`,
775
+ kind: 'state',
776
+ target: group.target,
777
+ todo_ids: group.todoIds,
778
+ provenance: [manualProvenance(request)],
779
+ });
780
+ }
781
+
782
+ let dynamicIndex = 0;
783
+ for (const unknown of unknowns) {
784
+ resources.push({
785
+ resource_id: `dyn-${String(dynamicIndex += 1).padStart(3, '0')}-${sha16(`${unknown.kind}:${unknown.ref}`)}`,
786
+ kind: 'dynamic',
787
+ target: `${unknown.kind}:${unknown.ref}`.slice(0, 4_096).trim(),
788
+ todo_ids: [unknown.todo_id],
789
+ provenance: [manualProvenance(request)],
790
+ });
791
+ }
792
+
793
+ const observationSet = {
794
+ schema_version: 'lattice.boundary_observation_set.v2',
795
+ source: {
796
+ snapshot_digest: digestArtifact({ base_sha: request.repo.base_sha }),
797
+ candidate_witness_digest: digestArtifact(request.manual_witness),
798
+ query_set_digest: digestArtifact(request.sensor_query_set),
799
+ manual_evidence_digest: request.request_digest,
800
+ },
801
+ capacity: request.capacity.executors,
802
+ todos: todoIds,
803
+ resources,
804
+ precedences: [],
805
+ };
806
+
807
+ const bundle = compileBoundaryObservationV2(observationSet);
808
+ const compiled = compileSchedulabilityGraphV2(bundle.graph);
809
+
810
+ if (compiled.outcome === 'unsupported' && compiled.code === 'NODE_LIMIT_EXCEEDED') {
811
+ return nonDispatchable('NODE_LIMIT_EXCEEDED', { todo_count: todoIds.length });
812
+ }
813
+ if (compiled.outcome === 'unknown') {
814
+ const hasFreshAbsentPath = todoIds.some((todoId) => (
815
+ bindingsByTodo.get(todoId).some((binding) => {
816
+ if (!['path', 'affected'].includes(binding.expect.kind)) return false;
817
+ const query = queryById.get(binding.query_id);
818
+ const outcome = outcomeByQueryId.get(binding.query_id);
819
+ return query.operation === 'affected'
820
+ && outcome.status === 'empty'
821
+ && affectedTarget(outcome.raw, binding.expect.path)?.path_state === 'absent';
822
+ })
823
+ ));
824
+ return nonDispatchable('BOUNDARY_UNKNOWN', {
825
+ unknowns: compiled.unknowns,
826
+ unresolved_witnesses: unknowns,
827
+ guidance: hasFreshAbsentPath
828
+ ? {
829
+ code: 'BOOTSTRAP_OWNERSHIP_SEAM',
830
+ message: '不存在と観測されたpathは、そのTODOが作るならowns entryへcreates: trueを宣言して再compileする。宣言せずに裏付けを得るなら、親が空の専用seamをbase commitへ先行追加し、sensor sync後に同じrequestを再compileする',
831
+ }
832
+ : {
833
+ code: 'ACQUIRE_OWNERSHIP_EVIDENCE',
834
+ message: '既存path・symbol・未束縛ownershipはfresh Sensor queryを追加して同じrequestを再compileする',
835
+ },
836
+ });
837
+ }
838
+ if (compiled.outcome === 'unsupported' && compiled.code === 'SEARCH_BUDGET_EXHAUSTED') {
839
+ return nonDispatchable('SEARCH_BUDGET_EXHAUSTED', {});
840
+ }
841
+ if (compiled.outcome !== 'compiled') fail(`未知のcompiler outcome: ${compiled.outcome}`);
842
+
843
+ // producer非依存の独立verifierと必ず一致すること(成功条件5)。
844
+ const verified = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
845
+ if (verified.outcome !== 'verified'
846
+ || verified.minimum_feasible_waves !== compiled.plan.minimum_feasible_waves) {
847
+ fail(`producerとverifierの結果が一致しない: ${JSON.stringify(verified)}`);
848
+ }
849
+
850
+ // boundary_manifest.v2をTODOごとに構成する。
851
+ const manifests = {};
852
+ for (const todoId of todoIds) {
853
+ const witness = request.manual_witness[todoId];
854
+ const witnessProvenance = {};
855
+ for (const resource of resources) {
856
+ if (!resource.todo_ids.includes(todoId)) continue;
857
+ witnessProvenance[resource.resource_id] = resource.kind === 'symbol' || resource.kind === 'path'
858
+ ? 'sensor'
859
+ : 'manual_state_effect';
860
+ }
861
+ const manifest = {
862
+ schema: BOUNDARY_MANIFEST_SCHEMA,
863
+ todo_id: todoId,
864
+ owns: witness.owns,
865
+ reads: witness.reads,
866
+ writes: witness.writes,
867
+ resources: witness.resources,
868
+ state_effects: witness.state_effects,
869
+ unknowns: witness.unknowns,
870
+ affected_tests: witness.affected_tests,
871
+ ...(witness.lines === undefined ? {} : { lines: witness.lines }),
872
+ graph_evidence: bindingsByTodo.get(todoId).map((binding) => {
873
+ const outcome = outcomeByQueryId.get(binding.query_id);
874
+ return {
875
+ query_id: binding.query_id,
876
+ operation: outcome.operation,
877
+ status: resolveBindingStatus(binding, outcome),
878
+ result_digest: outcome.portable_digest,
879
+ };
880
+ }),
881
+ witness_provenance: witnessProvenance,
882
+ };
883
+ manifest.manifest_digest = selfDigest(manifest, 'manifest_digest');
884
+ if (!validateRuntimeBoundaryManifest(manifest)) {
885
+ fail(`生成manifestがboundary_manifest contractを満たさない: ${todoId}`);
886
+ }
887
+ manifests[todoId] = manifest;
888
+ }
889
+
890
+ const plan = {
891
+ schema: 'lattice.runtime_plan.v1',
892
+ plan_ref: planRef,
893
+ plan_epoch: planEpoch,
894
+ request_digest: request.request_digest,
895
+ base_sha: request.repo.base_sha,
896
+ nodes: bundle.graph.todos.map((todoId) => ({ todo_id: todoId })),
897
+ precedence: bundle.graph.precedences.map((entry) => ({
898
+ from_todo_id: entry.from_todo_id,
899
+ to_todo_id: entry.to_todo_id,
900
+ })),
901
+ conflicts: bundle.graph.conflicts,
902
+ capacity: { executors: request.capacity.executors },
903
+ manifest_digests: Object.fromEntries(bundle.graph.todos.map((todoId) => (
904
+ [todoId, manifests[todoId].manifest_digest]
905
+ ))),
906
+ claim: { mode: 'exact_minimum' },
907
+ predecessor_refs: [...predecessorRefs],
908
+ };
909
+ plan.plan_digest = selfDigest(plan, 'plan_digest');
910
+ if (!validateRuntimePlan(plan)) fail('生成planがruntime_plan.v1 contractを満たさない');
911
+ if (!verifyRuntimePlanBinding({ plan, request })) fail('生成planがrequestへbindできない');
912
+
913
+ return {
914
+ outcome: 'dispatchable',
915
+ plan,
916
+ manifests,
917
+ schedule: compiled.plan,
918
+ pairwise_verdicts: compiled.pairwise_verdicts,
919
+ graph: bundle.graph,
920
+ // graph.conflictsはresource_idしか持たない。resource kindはここでしか引けないため、
921
+ // conflictの切断可能性を判定する消費者へnormalized resourceをそのまま渡す(ADR 0128)。
922
+ resources: bundle.resources,
923
+ graph_digest: bundle.graph_digest,
924
+ };
925
+ }