@quolu/lattice 0.52.2 → 0.52.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,428 +1,428 @@
1
- /**
2
- * 実行時に観測した競合を、実際の変換で解消するproduct入口(請求項8)。
3
- *
4
- * これが無い間、変換の中身は動くのに実運転からそこへ行く道が無かった。実運転側が使う
5
- * `routeConflictTreatment`は「事前宣言済みtreatmentがpathを覆う時だけseam_transform」なので、
6
- * **予期しなかった競合は変換にかからず直列へ退化していた**。
7
- *
8
- * 装置の境界にAIを含める(AGENTS.md)。したがってここでLatticeが供給するのは、AIが自分では
9
- * 作れないもの——構造観測、隔離実行、五条件の検証、変換の確定と記録——だけである。
10
- * 「どのTODOが係争fileの中のどのsymbolを触るか」「新しい面をどう名付けるか」はAIが既に
11
- * 知っているので、宣言として受け取る。推定しない。
12
- */
13
-
14
- import path from 'node:path';
15
- import { createHash } from 'node:crypto';
16
- import { readFile } from 'node:fs/promises';
17
-
18
- import { digestArtifact } from './artifact-contracts.mjs';
19
- import { commitSeamTransform } from './seam-commit.mjs';
20
- import { applySeamConflict } from './seam-apply.mjs';
21
- import { resolveRuntimeSeamTreatment } from './runtime-seam-treatment.mjs';
22
- import { affectedTestsFromEvidence } from './runtime-front-end.mjs';
23
- import { explainSeamGate } from './seam-gate.mjs';
24
- import { collectWitnessSensorEvidence, compileTodoIndependence } from './todo-independence.mjs';
25
- import { todoSelfDigest } from './todo-contracts.mjs';
26
- import { TODO_WITNESS_SET_SCHEMA } from './todo-independence-contracts.mjs';
27
-
28
- export const RUNTIME_SEAM_REQUEST_SCHEMA = 'lattice.runtime_seam_request.v1';
29
- // v2は翻訳段(`reconciled`)の追加である。宣言を観測へ合わせてから判定するようになったので、
30
- // どの宣言の上で五条件を見たかが決着の一部になった。v1の形のまま中身を変えると、記録が何に
31
- // ついてのものか確定しなくなる。
32
- export const RUNTIME_SEAM_RESOLUTION_SCHEMA = 'lattice.runtime_seam_resolution.v2';
33
-
34
- /** 合成するtodo planのkey。実行時planとは別空間なので固定でよい。 */
35
- const SYNTHETIC_PLAN_KEY = 'runtime';
36
- const HEX_DIGEST = /^[0-9a-f]{64}$/u;
37
- const REPO_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[\w./-]+$/u;
38
- const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
39
-
40
- const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
41
-
42
- /** 資源idはruntime front-endと同じ合成形にする(`own-<kind>-<sha16>`)。 */
43
- const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
44
-
45
- function plainObject(value) {
46
- return typeof value === 'object' && value !== null && !Array.isArray(value);
47
- }
48
-
49
- function exactRecord(value, keys) {
50
- if (!plainObject(value)) return false;
51
- const own = Object.keys(value);
52
- return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key));
53
- }
54
-
55
- /**
56
- * AIが出す宣言。ここに書くのは「係争fileの中で各TODOが触るsymbol」「新しい面の名前」
57
- * 「後継planへ渡すtask migrationのdigest」だけで、どれもAIが既に持っている情報である。
58
- */
59
- export function validateRuntimeSeamRequest(value) {
60
- if (!exactRecord(value, [
61
- 'schema', 'run_id', 'finding_digest', 'concern_symbols', 'path_names',
62
- 'task_migration_digest', 'request_digest',
63
- ])) return false;
64
- if (value.schema !== RUNTIME_SEAM_REQUEST_SCHEMA) return false;
65
- if (!IDENTIFIER.test(value.run_id ?? '')) return false;
66
- if (!HEX_DIGEST.test(value.finding_digest ?? '')) return false;
67
- if (!HEX_DIGEST.test(value.task_migration_digest ?? '')) return false;
68
- if (!plainObject(value.concern_symbols) || !plainObject(value.path_names)) return false;
69
-
70
- const todoIds = Object.keys(value.concern_symbols);
71
- if (todoIds.length < 2 || todoIds.length > 64) return false;
72
- for (const todoId of todoIds) {
73
- if (!IDENTIFIER.test(todoId)) return false;
74
- const symbols = value.concern_symbols[todoId];
75
- if (!Array.isArray(symbols) || symbols.length === 0 || symbols.length > 256) return false;
76
- if (!symbols.every((symbol) => IDENTIFIER.test(symbol))) return false;
77
- if (!REPO_PATH.test(value.path_names[todoId] ?? '')) return false;
78
- }
79
- // sharedはresidualから切り出す共有面。TODOに属さないので別枠で必ず要る。
80
- if (!REPO_PATH.test(value.path_names.shared ?? '')) return false;
81
- if (!exactRecord(value.path_names, [...todoIds, 'shared'])) return false;
82
- if (!HEX_DIGEST.test(value.request_digest ?? '')) return false;
83
- return value.request_digest === todoSelfDigest(value, 'request_digest');
84
- }
85
-
86
- /**
87
- * 観測された実態へ宣言を合わせる(翻訳段)。
88
- *
89
- * 実行時のpath競合は、**片方がその資源を所有していないから起きる**。所有していない資源の内側に
90
- * 担当は主張できない(`concern_anchor_resource_not_owned`)ので、宣言のままでは変換の入力が
91
- * 組めない——請求項8は、実行時に見つかった競合の形をそのままでは受け取れなかった。
92
- *
93
- * 境界は計画時の**予測**であって、workerを閉じ込める制約ではない。予測を超えたのは予測が狭かった
94
- * からであり、作業が不正だったからではない。したがって操作は「破った側を直す」ではなく、観測が
95
- * 示した実態へ宣言を合わせることであり、**対称**である——どちらの足跡が予測を超えたかは観測が
96
- * 決めるので、ここでは関与TODOを同じ規則で扱う。
97
- *
98
- * これは3つ目の処置ではない。翻訳を通ると計画時競合の形(`owns`の交差)になり、そこから先は
99
- * 既存の請求項7/8がそのまま適用できる。競合辺が立つのは翻訳の副産物ではなく目的である——
100
- * 立たないままだと`overlap_reduced`が最初から満たされたことになり、変換の検証が無意味になる。
101
- *
102
- * 広げるのは観測が示した資源だけとする。findingが持つ係争pathも関与TODOも観測であって推定では
103
- * ない。広げた事実は呼び出し側へ返す。黙って広げると、予測が外れたことも、判定がどの宣言の上で
104
- * 行われたかも残らない。
105
- *
106
- * **所有の宣言は裏取りと対で広げる。** `owns`だけ足すとその資源は`sensor_unbound`になり、compileは
107
- * 非dispatchable(`BOUNDARY_UNKNOWN`)へ落ちる。そこでは競合が投影されないので、翻訳したのに
108
- * 競合辺が立たず、変換の便益が測れない。裏取りに使えるqueryがrun のquery setに無ければ、
109
- * 広げずに理由を返す——証明できない宣言を作らない。
110
- */
111
- export function reconcileWitnessToObservation({
112
- manualWitness, contestedPath, todoIds, sensorQuerySet = null, observedAffectedTests = null,
113
- } = {}) {
114
- const reconciled = {};
115
- const widened = [];
116
- const reject = (reason) => ({ manualWitness: null, widened: [], reasons: [reason] });
117
- // 係争pathを覆えるqueryを、run のquery setから拾う。無ければ翻訳しない。
118
- //
119
- // `affected`だけを見る。path所有を裏取りするのはこのoperationであり、構造query(query/callers/
120
- // callees/impact)はsymbolを的にする。構造queryがたまたま同じ文字列をtargetに持つからといって
121
- // 所有の裏取りへ流用すると、束縛の意味が変わる。
122
- const covering = (sensorQuerySet?.queries ?? [])
123
- .filter((query) => query.operation === 'affected' && query.target === contestedPath)
124
- .map((query) => query.id)
125
- .sort(compareText);
126
-
127
- for (const todoId of todoIds) {
128
- const witness = manualWitness?.[todoId];
129
- if (!plainObject(witness)) return reject(`witness_absent:${todoId}`);
130
- const next = structuredClone(witness);
131
- const ownsPath = (next.owns ?? [])
132
- .some((own) => own.kind === 'path' && own.target === contestedPath);
133
- const writesPath = (next.writes ?? []).includes(contestedPath);
134
- const boundPath = (next.sensor_provenance?.queries ?? [])
135
- .some((entry) => (entry.expect?.kind === 'affected' || entry.expect?.kind === 'path')
136
- && entry.expect?.path === contestedPath);
137
- // 既に所有と書き込みを宣言しているなら、観測は予測の内側にある。合わせるものが無いので
138
- // 触らない——裏取りが足りているかどうかは、その宣言を書いた側の問題であり、compileが見る。
139
- // 翻訳が手を入れてよいのは、観測が予測を超えた分だけである。
140
- if (ownsPath && writesPath) {
141
- reconciled[todoId] = next;
142
- continue;
143
- }
144
- if (!boundPath) {
145
- if (covering.length === 0) return reject(`observation_unbacked:${todoId}:${contestedPath}`);
146
- // 同じ資源は同じqueryで裏取りする。TODOごとに別のqueryを選ぶと、front-endが被覆の
147
- // 曖昧さとして弾く。
148
- if (covering.length > 1) return reject(`observation_binding_ambiguous:${contestedPath}`);
149
- // 観測できていないaffectedを推測で埋めない。
150
- if (!Array.isArray(observedAffectedTests)) {
151
- return reject(`observation_affected_unread:${contestedPath}`);
152
- }
153
- }
154
- // 所有・書き込み・裏取りをまとめて足す。観測されたのは「このpathへの書き込み」であり、
155
- // 宣言の一部だけを合わせると、宣言が実態からずれたまま次の判定の前提になる。`creates`は
156
- // 付けない——観測できたのはpathが既に在るからである。
157
- if (!ownsPath) next.owns = [...next.owns, { kind: 'path', target: contestedPath }]
158
- .sort((left, right) => compareText(`${left.kind}\0${left.target}`, `${right.kind}\0${right.target}`));
159
- if (!writesPath) next.writes = [...next.writes, contestedPath].sort(compareText);
160
- if (!boundPath) {
161
- next.sensor_provenance = {
162
- ...next.sensor_provenance,
163
- queries: [...next.sensor_provenance.queries,
164
- { query_id: covering[0], expect: { kind: 'affected', path: contestedPath } }],
165
- };
166
- // 面を1つ引き受けたら、その面のaffected testも引き受ける。宣言と観測はTODO単位で
167
- // exact一致を要求されるので、片方だけ広げるとdriftになる。
168
- next.affected_tests = [...new Set([...next.affected_tests, ...observedAffectedTests])]
169
- .sort(compareText);
170
- }
171
- reconciled[todoId] = next;
172
- widened.push({
173
- todo_id: todoId,
174
- resource: { kind: 'path', target: contestedPath },
175
- fields: [
176
- ...(ownsPath ? [] : ['owns']),
177
- ...(writesPath ? [] : ['writes']),
178
- ...(boundPath ? [] : ['affected_tests', 'sensor_provenance']),
179
- ].sort(compareText),
180
- });
181
- }
182
- return { manualWitness: reconciled, widened, reasons: [] };
183
- }
184
-
185
- /**
186
- * 実行時witnessへconcern anchorを足してtodo witness setにする。
187
- *
188
- * 実行時のmanual_witnessはconcern_anchorsを持たない(`lattice.run_request.v4`)。持たせるのでなく、
189
- * 宣言から足す——係争資源の中のどのsymbolを触るかは実行時に確定する情報であり、run開始時点の
190
- * 契約に書けるものではないからである。
191
- *
192
- * anchorを足す前に宣言を観測へ合わせる(`reconcileWitnessToObservation`)。この順序でないと、
193
- * 係争資源を所有していないTODOのanchorが必ず不正になる。
194
- */
195
- export function buildRuntimeSeamWitnessSet({
196
- request, declaration, contestedPath, executors, observedAffectedTests = null,
197
- }) {
198
- const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
199
- const translated = reconcileWitnessToObservation({
200
- manualWitness: request.manual_witness, contestedPath, todoIds,
201
- sensorQuerySet: request.sensor_query_set, observedAffectedTests,
202
- });
203
- if (translated.manualWitness === null) {
204
- return { witnessSet: null, widened: [], reasons: translated.reasons };
205
- }
206
- const manual = {};
207
- for (const todoId of todoIds) {
208
- manual[todoId] = {
209
- ...translated.manualWitness[todoId],
210
- concern_anchors: [{
211
- within: { kind: 'path', target: contestedPath },
212
- symbols: [...declaration.concern_symbols[todoId]].sort(compareText),
213
- }],
214
- };
215
- }
216
- const witnessSet = {
217
- schema: TODO_WITNESS_SET_SCHEMA,
218
- project_id: SYNTHETIC_PLAN_KEY,
219
- plan_key: SYNTHETIC_PLAN_KEY,
220
- capacity: { executors },
221
- sensor_query_set: structuredClone(request.sensor_query_set),
222
- manual_witness: manual,
223
- witness_set_digest: '',
224
- };
225
- witnessSet.witness_set_digest = todoSelfDigest(witnessSet, 'witness_set_digest');
226
- return { witnessSet, widened: translated.widened, reasons: [] };
227
- }
228
-
229
- function syntheticTodoPlan(todoIds) {
230
- return {
231
- schema: 'lattice.todo_plan.v2',
232
- project_id: SYNTHETIC_PLAN_KEY,
233
- plan_key: SYNTHETIC_PLAN_KEY,
234
- plan_version: 'v1',
235
- topology_digest: digestArtifact({ tasks: [...todoIds].sort(compareText) }),
236
- tasks: [...todoIds].sort(compareText).map((taskId) => ({ task_id: taskId })),
237
- };
238
- }
239
-
240
- /**
241
- * 記録済みfindingと宣言から、変換を導出・適用・検証・確定して処置を返す。
242
- *
243
- * 五条件(ADR 0138)を1つでも欠いたら意図的直列を返す。確定できなければ採用しない(ADR 0141)。
244
- * 「変換した」と言いながら再開できない状態を作らない。
245
- */
246
- export async function resolveRuntimeSeam({
247
- repoRoot, runDir, findingRecord, bundle, declaration, latticeBin, compiledAt,
248
- } = {}) {
249
- const finding = findingRecord.finding;
250
- const request = bundle.request;
251
- const baseSha = request.repo.base_sha;
252
- const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
253
-
254
- if (finding.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
255
- return { lane: 'intentional_serial', reasons: ['finding_not_write_conflict'], split: null, widened: [] };
256
- }
257
- const findingTodoIds = [...finding.todo_ids].sort(compareText);
258
- if (findingTodoIds.join('\0') !== todoIds.join('\0')) {
259
- return {
260
- lane: 'intentional_serial',
261
- reasons: ['declared_todos_differ_from_finding'],
262
- split: null,
263
- widened: [],
264
- };
265
- }
266
-
267
- // sensorは1回だけ引く。翻訳(宣言を観測へ合わせる)とcompileは同じ観測の上で行う——
268
- // 別々に引くと、翻訳が見た実態とcompileが見た実態がずれうる。
269
- const sensorEvidence = await collectWitnessSensorEvidence({
270
- cwd: repoRoot, witnessSet: { sensor_query_set: request.sensor_query_set },
271
- });
272
- const built = buildRuntimeSeamWitnessSet({
273
- request, declaration, contestedPath: finding.path,
274
- executors: request.capacity.executors,
275
- observedAffectedTests: affectedTestsFromEvidence({
276
- sensorEvidence, querySet: request.sensor_query_set, path: finding.path,
277
- }),
278
- });
279
- if (built.witnessSet === null) {
280
- return { lane: 'intentional_serial', reasons: built.reasons, split: null, widened: [] };
281
- }
282
- const witnessSet = built.witnessSet;
283
- const plan = syntheticTodoPlan(todoIds);
284
-
285
- // 観測したaffected testsだけを検証に使う。宣言から発明しない。翻訳後の宣言から採る——
286
- // 所有が広がったTODOは、その面のtestも自分のaffectedとして引き受けている。
287
- const affectedTests = [...new Set(todoIds
288
- .flatMap((todoId) => witnessSet.manual_witness[todoId].affected_tests))].sort(compareText);
289
-
290
- const baseArtifact = compileTodoIndependence({
291
- witnessSet, plan, baseSha, compiledAt, sensorEvidence,
292
- });
293
-
294
- const pathNames = { ...declaration.path_names };
295
- // 翻訳で広げた宣言は決着へ載せる。どの宣言の上で五条件を判定したかが残らないと、
296
- // 「変換して通った」という記録が何についてのものか確定しない。
297
- const resolved = await resolveRuntimeSeamTreatment({
298
- finding,
299
- witnessSet,
300
- pathNames,
301
- baseSha,
302
- manifestDigest: baseArtifact.result_digest,
303
- affectedTests,
304
- taskMigrationDigest: declaration.task_migration_digest,
305
- // storeへ記録されたfindingのidで縛る。再計画側はこのidでfinding recordを読む。
306
- recordedFindingDigest: findingRecord.finding_digest,
307
- commitTransform: async ({ files, candidateId }) => commitSeamTransform({
308
- repoRoot, baseSha, files, candidateId,
309
- }),
310
- applyConflict: async ({ conflict }) => {
311
- const applied = await applySeamConflict({
312
- repoRoot,
313
- planKey: SYNTHETIC_PLAN_KEY,
314
- conflict,
315
- witnessSet,
316
- latticeBin,
317
- sharedPathFor: () => declaration.path_names.shared,
318
- executors: request.capacity.executors,
319
- precedences: bundle.plan.precedence,
320
- pathNames,
321
- compileIndependence: {
322
- baseArtifact,
323
- inWorktree: async ({ worktreePath, witnessSet: postWitness }) => compileTodoIndependence({
324
- witnessSet: postWitness,
325
- plan,
326
- baseSha,
327
- compiledAt,
328
- sensorEvidence: await collectWitnessSensorEvidence({
329
- cwd: worktreePath, witnessSet: postWitness,
330
- }),
331
- }),
332
- },
333
- });
334
- return { ...applied, candidate: applied.candidate ?? null };
335
- },
336
- });
337
- return { ...resolved, widened: built.widened };
338
- }
339
-
340
- /** 決着をartifactにする。branchを動かすのは操作するAIなので、行き先を明示して返す。 */
341
- export function buildRuntimeSeamResolution({ runId, findingDigest, resolved }) {
342
- const resolution = {
343
- schema: RUNTIME_SEAM_RESOLUTION_SCHEMA,
344
- run_id: runId,
345
- finding_digest: findingDigest,
346
- lane: resolved.lane,
347
- reasons: [...resolved.reasons].sort(compareText),
348
- // 確実の門(sc-012)。拒否理由を「宣言を直せば機械で通る」「AIが変換すべき」へ分類し、
349
- // 次に誰が動くべきかを事実として返す。可否は決めない。
350
- gate: explainSeamGate(resolved.reasons ?? []),
351
- // 判定の前に宣言をどれだけ観測へ合わせたか。空配列は「予測が実態を覆っていた」という
352
- // 意味であり、翻訳しなかったことと区別できる。
353
- reconciled: [...(resolved.widened ?? [])]
354
- .map((entry) => ({
355
- todo_id: entry.todo_id,
356
- resource: { kind: entry.resource.kind, target: entry.resource.target },
357
- fields: [...entry.fields].sort(compareText),
358
- }))
359
- .sort((left, right) => compareText(
360
- `${left.todo_id}\0${left.resource.kind}\0${left.resource.target}`,
361
- `${right.todo_id}\0${right.resource.kind}\0${right.resource.target}`,
362
- )),
363
- split: resolved.split ?? null,
364
- successor_base_sha: resolved.successor_base_sha ?? null,
365
- successor_base_ref: resolved.successor_base_ref ?? null,
366
- resolution_digest: '',
367
- };
368
- resolution.resolution_digest = todoSelfDigest(resolution, 'resolution_digest');
369
- return resolution;
370
- }
371
-
372
- /**
373
- * seam_split再計画で、後継baseが本当に変換を含むかを検査する(ADR 0141)。
374
- *
375
- * これが無い間、`mode: 'seam_split'`の再計画requestは**変換を含まないbaseを指していても通った**。
376
- * splitは新しい面の所有を宣言するのに、compileされる後継treeにそのfileが無い——rb工程で
377
- * 直したのと同じ欠陥が、管理runtimeの層に残っていた。
378
- *
379
- * 検査するのは3つ。どれもLatticeが既に持っているartifactだけで判定でき、推定を含まない。
380
- *
381
- * 1. baseが前進し、かつ旧baseの子孫であること。変換が着地していなければ前進しない。
382
- * 2. splitが「消える」と述べた競合辺が、後継planに実際に無いこと。後継treeに変換が
383
- * 載っていなければ両TODOは同じfileを書き続けるので、この辺は消えない。
384
- * 3. splitが新たに所有すると述べた資源が、後継requestで**creationとして宣言されていない**こと。
385
- * seam splitは既存codeを新しい面へ移す操作であり、変換が既に作っている。これから作る、
386
- * と宣言されているなら、指しているbaseは変換前である。
387
- */
388
- export function verifySeamSplitSuccessor({
389
- split, predecessorBaseSha, successorBaseSha, successorIsDescendant,
390
- successorConflicts = [], successorWitness = {},
391
- } = {}) {
392
- const reasons = [];
393
- if (successorBaseSha === predecessorBaseSha) reasons.push('successor_base_not_advanced');
394
- else if (successorIsDescendant !== true) reasons.push('successor_base_not_descendant');
395
-
396
- const removedEdges = split?.edge_diff?.removed ?? [];
397
- const remaining = new Set(successorConflicts
398
- .map(({ todo_ids: ids }) => [...ids].sort(compareText).join('\0')));
399
- for (const edge of removedEdges) {
400
- const key = [edge.from_todo_id, edge.to_todo_id].sort(compareText).join('\0');
401
- if (remaining.has(key)) reasons.push(`declared_removed_conflict_persists:${key.replace('\0', ',')}`);
402
- }
403
-
404
- for (const added of split?.ownership_diff?.added ?? []) {
405
- const owns = successorWitness[added.owner_todo_id]?.owns ?? [];
406
- for (const own of owns) {
407
- const resourceId = `own-${own.kind}-${sha16(own.target)}`;
408
- if (resourceId === added.resource_id && own.creates === true) {
409
- reasons.push(`declared_owned_surface_is_creation:${added.owner_todo_id}`);
410
- }
411
- }
412
- }
413
- return { ok: reasons.length === 0, reasons: [...new Set(reasons)].sort(compareText) };
414
- }
415
-
416
- /** `<runDir>/findings/<digest>.json`を読む。存在しない/別epochのfindingは受けない。 */
417
- export async function readRuntimeFindingRecord({ runDir, findingDigest, planEpoch }) {
418
- const filePath = path.join(runDir, 'findings', `${findingDigest}.json`);
419
- let record;
420
- try {
421
- record = JSON.parse(await readFile(filePath, 'utf8'));
422
- } catch {
423
- return { record: null, reason: 'finding_not_recorded' };
424
- }
425
- if (record?.finding_digest !== findingDigest) return { record: null, reason: 'finding_digest_mismatch' };
426
- if (record.plan_epoch !== planEpoch) return { record: null, reason: 'finding_from_other_epoch' };
427
- return { record, reason: null };
428
- }
1
+ /**
2
+ * 実行時に観測した競合を、実際の変換で解消するproduct入口(請求項8)。
3
+ *
4
+ * これが無い間、変換の中身は動くのに実運転からそこへ行く道が無かった。実運転側が使う
5
+ * `routeConflictTreatment`は「事前宣言済みtreatmentがpathを覆う時だけseam_transform」なので、
6
+ * **予期しなかった競合は変換にかからず直列へ退化していた**。
7
+ *
8
+ * 装置の境界にAIを含める(AGENTS.md)。したがってここでLatticeが供給するのは、AIが自分では
9
+ * 作れないもの——構造観測、隔離実行、五条件の検証、変換の確定と記録——だけである。
10
+ * 「どのTODOが係争fileの中のどのsymbolを触るか」「新しい面をどう名付けるか」はAIが既に
11
+ * 知っているので、宣言として受け取る。推定しない。
12
+ */
13
+
14
+ import path from 'node:path';
15
+ import { createHash } from 'node:crypto';
16
+ import { readFile } from 'node:fs/promises';
17
+
18
+ import { digestArtifact } from './artifact-contracts.mjs';
19
+ import { commitSeamTransform } from './seam-commit.mjs';
20
+ import { applySeamConflict } from './seam-apply.mjs';
21
+ import { resolveRuntimeSeamTreatment } from './runtime-seam-treatment.mjs';
22
+ import { affectedTestsFromEvidence } from './runtime-front-end.mjs';
23
+ import { explainSeamGate } from './seam-gate.mjs';
24
+ import { collectWitnessSensorEvidence, compileTodoIndependence } from './todo-independence.mjs';
25
+ import { todoSelfDigest } from './todo-contracts.mjs';
26
+ import { TODO_WITNESS_SET_SCHEMA } from './todo-independence-contracts.mjs';
27
+
28
+ export const RUNTIME_SEAM_REQUEST_SCHEMA = 'lattice.runtime_seam_request.v1';
29
+ // v2は翻訳段(`reconciled`)の追加である。宣言を観測へ合わせてから判定するようになったので、
30
+ // どの宣言の上で五条件を見たかが決着の一部になった。v1の形のまま中身を変えると、記録が何に
31
+ // ついてのものか確定しなくなる。
32
+ export const RUNTIME_SEAM_RESOLUTION_SCHEMA = 'lattice.runtime_seam_resolution.v2';
33
+
34
+ /** 合成するtodo planのkey。実行時planとは別空間なので固定でよい。 */
35
+ const SYNTHETIC_PLAN_KEY = 'runtime';
36
+ const HEX_DIGEST = /^[0-9a-f]{64}$/u;
37
+ const REPO_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[\w./-]+$/u;
38
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
39
+
40
+ const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
41
+
42
+ /** 資源idはruntime front-endと同じ合成形にする(`own-<kind>-<sha16>`)。 */
43
+ const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
44
+
45
+ function plainObject(value) {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ }
48
+
49
+ function exactRecord(value, keys) {
50
+ if (!plainObject(value)) return false;
51
+ const own = Object.keys(value);
52
+ return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key));
53
+ }
54
+
55
+ /**
56
+ * AIが出す宣言。ここに書くのは「係争fileの中で各TODOが触るsymbol」「新しい面の名前」
57
+ * 「後継planへ渡すtask migrationのdigest」だけで、どれもAIが既に持っている情報である。
58
+ */
59
+ export function validateRuntimeSeamRequest(value) {
60
+ if (!exactRecord(value, [
61
+ 'schema', 'run_id', 'finding_digest', 'concern_symbols', 'path_names',
62
+ 'task_migration_digest', 'request_digest',
63
+ ])) return false;
64
+ if (value.schema !== RUNTIME_SEAM_REQUEST_SCHEMA) return false;
65
+ if (!IDENTIFIER.test(value.run_id ?? '')) return false;
66
+ if (!HEX_DIGEST.test(value.finding_digest ?? '')) return false;
67
+ if (!HEX_DIGEST.test(value.task_migration_digest ?? '')) return false;
68
+ if (!plainObject(value.concern_symbols) || !plainObject(value.path_names)) return false;
69
+
70
+ const todoIds = Object.keys(value.concern_symbols);
71
+ if (todoIds.length < 2 || todoIds.length > 64) return false;
72
+ for (const todoId of todoIds) {
73
+ if (!IDENTIFIER.test(todoId)) return false;
74
+ const symbols = value.concern_symbols[todoId];
75
+ if (!Array.isArray(symbols) || symbols.length === 0 || symbols.length > 256) return false;
76
+ if (!symbols.every((symbol) => IDENTIFIER.test(symbol))) return false;
77
+ if (!REPO_PATH.test(value.path_names[todoId] ?? '')) return false;
78
+ }
79
+ // sharedはresidualから切り出す共有面。TODOに属さないので別枠で必ず要る。
80
+ if (!REPO_PATH.test(value.path_names.shared ?? '')) return false;
81
+ if (!exactRecord(value.path_names, [...todoIds, 'shared'])) return false;
82
+ if (!HEX_DIGEST.test(value.request_digest ?? '')) return false;
83
+ return value.request_digest === todoSelfDigest(value, 'request_digest');
84
+ }
85
+
86
+ /**
87
+ * 観測された実態へ宣言を合わせる(翻訳段)。
88
+ *
89
+ * 実行時のpath競合は、**片方がその資源を所有していないから起きる**。所有していない資源の内側に
90
+ * 担当は主張できない(`concern_anchor_resource_not_owned`)ので、宣言のままでは変換の入力が
91
+ * 組めない——請求項8は、実行時に見つかった競合の形をそのままでは受け取れなかった。
92
+ *
93
+ * 境界は計画時の**予測**であって、workerを閉じ込める制約ではない。予測を超えたのは予測が狭かった
94
+ * からであり、作業が不正だったからではない。したがって操作は「破った側を直す」ではなく、観測が
95
+ * 示した実態へ宣言を合わせることであり、**対称**である——どちらの足跡が予測を超えたかは観測が
96
+ * 決めるので、ここでは関与TODOを同じ規則で扱う。
97
+ *
98
+ * これは3つ目の処置ではない。翻訳を通ると計画時競合の形(`owns`の交差)になり、そこから先は
99
+ * 既存の請求項7/8がそのまま適用できる。競合辺が立つのは翻訳の副産物ではなく目的である——
100
+ * 立たないままだと`overlap_reduced`が最初から満たされたことになり、変換の検証が無意味になる。
101
+ *
102
+ * 広げるのは観測が示した資源だけとする。findingが持つ係争pathも関与TODOも観測であって推定では
103
+ * ない。広げた事実は呼び出し側へ返す。黙って広げると、予測が外れたことも、判定がどの宣言の上で
104
+ * 行われたかも残らない。
105
+ *
106
+ * **所有の宣言は裏取りと対で広げる。** `owns`だけ足すとその資源は`sensor_unbound`になり、compileは
107
+ * 非dispatchable(`BOUNDARY_UNKNOWN`)へ落ちる。そこでは競合が投影されないので、翻訳したのに
108
+ * 競合辺が立たず、変換の便益が測れない。裏取りに使えるqueryがrun のquery setに無ければ、
109
+ * 広げずに理由を返す——証明できない宣言を作らない。
110
+ */
111
+ export function reconcileWitnessToObservation({
112
+ manualWitness, contestedPath, todoIds, sensorQuerySet = null, observedAffectedTests = null,
113
+ } = {}) {
114
+ const reconciled = {};
115
+ const widened = [];
116
+ const reject = (reason) => ({ manualWitness: null, widened: [], reasons: [reason] });
117
+ // 係争pathを覆えるqueryを、run のquery setから拾う。無ければ翻訳しない。
118
+ //
119
+ // `affected`だけを見る。path所有を裏取りするのはこのoperationであり、構造query(query/callers/
120
+ // callees/impact)はsymbolを的にする。構造queryがたまたま同じ文字列をtargetに持つからといって
121
+ // 所有の裏取りへ流用すると、束縛の意味が変わる。
122
+ const covering = (sensorQuerySet?.queries ?? [])
123
+ .filter((query) => query.operation === 'affected' && query.target === contestedPath)
124
+ .map((query) => query.id)
125
+ .sort(compareText);
126
+
127
+ for (const todoId of todoIds) {
128
+ const witness = manualWitness?.[todoId];
129
+ if (!plainObject(witness)) return reject(`witness_absent:${todoId}`);
130
+ const next = structuredClone(witness);
131
+ const ownsPath = (next.owns ?? [])
132
+ .some((own) => own.kind === 'path' && own.target === contestedPath);
133
+ const writesPath = (next.writes ?? []).includes(contestedPath);
134
+ const boundPath = (next.sensor_provenance?.queries ?? [])
135
+ .some((entry) => (entry.expect?.kind === 'affected' || entry.expect?.kind === 'path')
136
+ && entry.expect?.path === contestedPath);
137
+ // 既に所有と書き込みを宣言しているなら、観測は予測の内側にある。合わせるものが無いので
138
+ // 触らない——裏取りが足りているかどうかは、その宣言を書いた側の問題であり、compileが見る。
139
+ // 翻訳が手を入れてよいのは、観測が予測を超えた分だけである。
140
+ if (ownsPath && writesPath) {
141
+ reconciled[todoId] = next;
142
+ continue;
143
+ }
144
+ if (!boundPath) {
145
+ if (covering.length === 0) return reject(`observation_unbacked:${todoId}:${contestedPath}`);
146
+ // 同じ資源は同じqueryで裏取りする。TODOごとに別のqueryを選ぶと、front-endが被覆の
147
+ // 曖昧さとして弾く。
148
+ if (covering.length > 1) return reject(`observation_binding_ambiguous:${contestedPath}`);
149
+ // 観測できていないaffectedを推測で埋めない。
150
+ if (!Array.isArray(observedAffectedTests)) {
151
+ return reject(`observation_affected_unread:${contestedPath}`);
152
+ }
153
+ }
154
+ // 所有・書き込み・裏取りをまとめて足す。観測されたのは「このpathへの書き込み」であり、
155
+ // 宣言の一部だけを合わせると、宣言が実態からずれたまま次の判定の前提になる。`creates`は
156
+ // 付けない——観測できたのはpathが既に在るからである。
157
+ if (!ownsPath) next.owns = [...next.owns, { kind: 'path', target: contestedPath }]
158
+ .sort((left, right) => compareText(`${left.kind}\0${left.target}`, `${right.kind}\0${right.target}`));
159
+ if (!writesPath) next.writes = [...next.writes, contestedPath].sort(compareText);
160
+ if (!boundPath) {
161
+ next.sensor_provenance = {
162
+ ...next.sensor_provenance,
163
+ queries: [...next.sensor_provenance.queries,
164
+ { query_id: covering[0], expect: { kind: 'affected', path: contestedPath } }],
165
+ };
166
+ // 面を1つ引き受けたら、その面のaffected testも引き受ける。宣言と観測はTODO単位で
167
+ // exact一致を要求されるので、片方だけ広げるとdriftになる。
168
+ next.affected_tests = [...new Set([...next.affected_tests, ...observedAffectedTests])]
169
+ .sort(compareText);
170
+ }
171
+ reconciled[todoId] = next;
172
+ widened.push({
173
+ todo_id: todoId,
174
+ resource: { kind: 'path', target: contestedPath },
175
+ fields: [
176
+ ...(ownsPath ? [] : ['owns']),
177
+ ...(writesPath ? [] : ['writes']),
178
+ ...(boundPath ? [] : ['affected_tests', 'sensor_provenance']),
179
+ ].sort(compareText),
180
+ });
181
+ }
182
+ return { manualWitness: reconciled, widened, reasons: [] };
183
+ }
184
+
185
+ /**
186
+ * 実行時witnessへconcern anchorを足してtodo witness setにする。
187
+ *
188
+ * 実行時のmanual_witnessはconcern_anchorsを持たない(`lattice.run_request.v4`)。持たせるのでなく、
189
+ * 宣言から足す——係争資源の中のどのsymbolを触るかは実行時に確定する情報であり、run開始時点の
190
+ * 契約に書けるものではないからである。
191
+ *
192
+ * anchorを足す前に宣言を観測へ合わせる(`reconcileWitnessToObservation`)。この順序でないと、
193
+ * 係争資源を所有していないTODOのanchorが必ず不正になる。
194
+ */
195
+ export function buildRuntimeSeamWitnessSet({
196
+ request, declaration, contestedPath, executors, observedAffectedTests = null,
197
+ }) {
198
+ const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
199
+ const translated = reconcileWitnessToObservation({
200
+ manualWitness: request.manual_witness, contestedPath, todoIds,
201
+ sensorQuerySet: request.sensor_query_set, observedAffectedTests,
202
+ });
203
+ if (translated.manualWitness === null) {
204
+ return { witnessSet: null, widened: [], reasons: translated.reasons };
205
+ }
206
+ const manual = {};
207
+ for (const todoId of todoIds) {
208
+ manual[todoId] = {
209
+ ...translated.manualWitness[todoId],
210
+ concern_anchors: [{
211
+ within: { kind: 'path', target: contestedPath },
212
+ symbols: [...declaration.concern_symbols[todoId]].sort(compareText),
213
+ }],
214
+ };
215
+ }
216
+ const witnessSet = {
217
+ schema: TODO_WITNESS_SET_SCHEMA,
218
+ project_id: SYNTHETIC_PLAN_KEY,
219
+ plan_key: SYNTHETIC_PLAN_KEY,
220
+ capacity: { executors },
221
+ sensor_query_set: structuredClone(request.sensor_query_set),
222
+ manual_witness: manual,
223
+ witness_set_digest: '',
224
+ };
225
+ witnessSet.witness_set_digest = todoSelfDigest(witnessSet, 'witness_set_digest');
226
+ return { witnessSet, widened: translated.widened, reasons: [] };
227
+ }
228
+
229
+ function syntheticTodoPlan(todoIds) {
230
+ return {
231
+ schema: 'lattice.todo_plan.v2',
232
+ project_id: SYNTHETIC_PLAN_KEY,
233
+ plan_key: SYNTHETIC_PLAN_KEY,
234
+ plan_version: 'v1',
235
+ topology_digest: digestArtifact({ tasks: [...todoIds].sort(compareText) }),
236
+ tasks: [...todoIds].sort(compareText).map((taskId) => ({ task_id: taskId })),
237
+ };
238
+ }
239
+
240
+ /**
241
+ * 記録済みfindingと宣言から、変換を導出・適用・検証・確定して処置を返す。
242
+ *
243
+ * 五条件(ADR 0138)を1つでも欠いたら意図的直列を返す。確定できなければ採用しない(ADR 0141)。
244
+ * 「変換した」と言いながら再開できない状態を作らない。
245
+ */
246
+ export async function resolveRuntimeSeam({
247
+ repoRoot, runDir, findingRecord, bundle, declaration, latticeBin, compiledAt,
248
+ } = {}) {
249
+ const finding = findingRecord.finding;
250
+ const request = bundle.request;
251
+ const baseSha = request.repo.base_sha;
252
+ const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
253
+
254
+ if (finding.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
255
+ return { lane: 'intentional_serial', reasons: ['finding_not_write_conflict'], split: null, widened: [] };
256
+ }
257
+ const findingTodoIds = [...finding.todo_ids].sort(compareText);
258
+ if (findingTodoIds.join('\0') !== todoIds.join('\0')) {
259
+ return {
260
+ lane: 'intentional_serial',
261
+ reasons: ['declared_todos_differ_from_finding'],
262
+ split: null,
263
+ widened: [],
264
+ };
265
+ }
266
+
267
+ // sensorは1回だけ引く。翻訳(宣言を観測へ合わせる)とcompileは同じ観測の上で行う——
268
+ // 別々に引くと、翻訳が見た実態とcompileが見た実態がずれうる。
269
+ const sensorEvidence = await collectWitnessSensorEvidence({
270
+ cwd: repoRoot, witnessSet: { sensor_query_set: request.sensor_query_set },
271
+ });
272
+ const built = buildRuntimeSeamWitnessSet({
273
+ request, declaration, contestedPath: finding.path,
274
+ executors: request.capacity.executors,
275
+ observedAffectedTests: affectedTestsFromEvidence({
276
+ sensorEvidence, querySet: request.sensor_query_set, path: finding.path,
277
+ }),
278
+ });
279
+ if (built.witnessSet === null) {
280
+ return { lane: 'intentional_serial', reasons: built.reasons, split: null, widened: [] };
281
+ }
282
+ const witnessSet = built.witnessSet;
283
+ const plan = syntheticTodoPlan(todoIds);
284
+
285
+ // 観測したaffected testsだけを検証に使う。宣言から発明しない。翻訳後の宣言から採る——
286
+ // 所有が広がったTODOは、その面のtestも自分のaffectedとして引き受けている。
287
+ const affectedTests = [...new Set(todoIds
288
+ .flatMap((todoId) => witnessSet.manual_witness[todoId].affected_tests))].sort(compareText);
289
+
290
+ const baseArtifact = compileTodoIndependence({
291
+ witnessSet, plan, baseSha, compiledAt, sensorEvidence,
292
+ });
293
+
294
+ const pathNames = { ...declaration.path_names };
295
+ // 翻訳で広げた宣言は決着へ載せる。どの宣言の上で五条件を判定したかが残らないと、
296
+ // 「変換して通った」という記録が何についてのものか確定しない。
297
+ const resolved = await resolveRuntimeSeamTreatment({
298
+ finding,
299
+ witnessSet,
300
+ pathNames,
301
+ baseSha,
302
+ manifestDigest: baseArtifact.result_digest,
303
+ affectedTests,
304
+ taskMigrationDigest: declaration.task_migration_digest,
305
+ // storeへ記録されたfindingのidで縛る。再計画側はこのidでfinding recordを読む。
306
+ recordedFindingDigest: findingRecord.finding_digest,
307
+ commitTransform: async ({ files, candidateId }) => commitSeamTransform({
308
+ repoRoot, baseSha, files, candidateId,
309
+ }),
310
+ applyConflict: async ({ conflict }) => {
311
+ const applied = await applySeamConflict({
312
+ repoRoot,
313
+ planKey: SYNTHETIC_PLAN_KEY,
314
+ conflict,
315
+ witnessSet,
316
+ latticeBin,
317
+ sharedPathFor: () => declaration.path_names.shared,
318
+ executors: request.capacity.executors,
319
+ precedences: bundle.plan.precedence,
320
+ pathNames,
321
+ compileIndependence: {
322
+ baseArtifact,
323
+ inWorktree: async ({ worktreePath, witnessSet: postWitness }) => compileTodoIndependence({
324
+ witnessSet: postWitness,
325
+ plan,
326
+ baseSha,
327
+ compiledAt,
328
+ sensorEvidence: await collectWitnessSensorEvidence({
329
+ cwd: worktreePath, witnessSet: postWitness,
330
+ }),
331
+ }),
332
+ },
333
+ });
334
+ return { ...applied, candidate: applied.candidate ?? null };
335
+ },
336
+ });
337
+ return { ...resolved, widened: built.widened };
338
+ }
339
+
340
+ /** 決着をartifactにする。branchを動かすのは操作するAIなので、行き先を明示して返す。 */
341
+ export function buildRuntimeSeamResolution({ runId, findingDigest, resolved }) {
342
+ const resolution = {
343
+ schema: RUNTIME_SEAM_RESOLUTION_SCHEMA,
344
+ run_id: runId,
345
+ finding_digest: findingDigest,
346
+ lane: resolved.lane,
347
+ reasons: [...resolved.reasons].sort(compareText),
348
+ // 確実の門(sc-012)。拒否理由を「宣言を直せば機械で通る」「AIが変換すべき」へ分類し、
349
+ // 次に誰が動くべきかを事実として返す。可否は決めない。
350
+ gate: explainSeamGate(resolved.reasons ?? []),
351
+ // 判定の前に宣言をどれだけ観測へ合わせたか。空配列は「予測が実態を覆っていた」という
352
+ // 意味であり、翻訳しなかったことと区別できる。
353
+ reconciled: [...(resolved.widened ?? [])]
354
+ .map((entry) => ({
355
+ todo_id: entry.todo_id,
356
+ resource: { kind: entry.resource.kind, target: entry.resource.target },
357
+ fields: [...entry.fields].sort(compareText),
358
+ }))
359
+ .sort((left, right) => compareText(
360
+ `${left.todo_id}\0${left.resource.kind}\0${left.resource.target}`,
361
+ `${right.todo_id}\0${right.resource.kind}\0${right.resource.target}`,
362
+ )),
363
+ split: resolved.split ?? null,
364
+ successor_base_sha: resolved.successor_base_sha ?? null,
365
+ successor_base_ref: resolved.successor_base_ref ?? null,
366
+ resolution_digest: '',
367
+ };
368
+ resolution.resolution_digest = todoSelfDigest(resolution, 'resolution_digest');
369
+ return resolution;
370
+ }
371
+
372
+ /**
373
+ * seam_split再計画で、後継baseが本当に変換を含むかを検査する(ADR 0141)。
374
+ *
375
+ * これが無い間、`mode: 'seam_split'`の再計画requestは**変換を含まないbaseを指していても通った**。
376
+ * splitは新しい面の所有を宣言するのに、compileされる後継treeにそのfileが無い——rb工程で
377
+ * 直したのと同じ欠陥が、管理runtimeの層に残っていた。
378
+ *
379
+ * 検査するのは3つ。どれもLatticeが既に持っているartifactだけで判定でき、推定を含まない。
380
+ *
381
+ * 1. baseが前進し、かつ旧baseの子孫であること。変換が着地していなければ前進しない。
382
+ * 2. splitが「消える」と述べた競合辺が、後継planに実際に無いこと。後継treeに変換が
383
+ * 載っていなければ両TODOは同じfileを書き続けるので、この辺は消えない。
384
+ * 3. splitが新たに所有すると述べた資源が、後継requestで**creationとして宣言されていない**こと。
385
+ * seam splitは既存codeを新しい面へ移す操作であり、変換が既に作っている。これから作る、
386
+ * と宣言されているなら、指しているbaseは変換前である。
387
+ */
388
+ export function verifySeamSplitSuccessor({
389
+ split, predecessorBaseSha, successorBaseSha, successorIsDescendant,
390
+ successorConflicts = [], successorWitness = {},
391
+ } = {}) {
392
+ const reasons = [];
393
+ if (successorBaseSha === predecessorBaseSha) reasons.push('successor_base_not_advanced');
394
+ else if (successorIsDescendant !== true) reasons.push('successor_base_not_descendant');
395
+
396
+ const removedEdges = split?.edge_diff?.removed ?? [];
397
+ const remaining = new Set(successorConflicts
398
+ .map(({ todo_ids: ids }) => [...ids].sort(compareText).join('\0')));
399
+ for (const edge of removedEdges) {
400
+ const key = [edge.from_todo_id, edge.to_todo_id].sort(compareText).join('\0');
401
+ if (remaining.has(key)) reasons.push(`declared_removed_conflict_persists:${key.replace('\0', ',')}`);
402
+ }
403
+
404
+ for (const added of split?.ownership_diff?.added ?? []) {
405
+ const owns = successorWitness[added.owner_todo_id]?.owns ?? [];
406
+ for (const own of owns) {
407
+ const resourceId = `own-${own.kind}-${sha16(own.target)}`;
408
+ if (resourceId === added.resource_id && own.creates === true) {
409
+ reasons.push(`declared_owned_surface_is_creation:${added.owner_todo_id}`);
410
+ }
411
+ }
412
+ }
413
+ return { ok: reasons.length === 0, reasons: [...new Set(reasons)].sort(compareText) };
414
+ }
415
+
416
+ /** `<runDir>/findings/<digest>.json`を読む。存在しない/別epochのfindingは受けない。 */
417
+ export async function readRuntimeFindingRecord({ runDir, findingDigest, planEpoch }) {
418
+ const filePath = path.join(runDir, 'findings', `${findingDigest}.json`);
419
+ let record;
420
+ try {
421
+ record = JSON.parse(await readFile(filePath, 'utf8'));
422
+ } catch {
423
+ return { record: null, reason: 'finding_not_recorded' };
424
+ }
425
+ if (record?.finding_digest !== findingDigest) return { record: null, reason: 'finding_digest_mismatch' };
426
+ if (record.plan_epoch !== planEpoch) return { record: null, reason: 'finding_from_other_epoch' };
427
+ return { record, reason: null };
428
+ }