@quolu/lattice 0.52.3 → 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 +3 -3
  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 +8 -8
  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 +42 -21
  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,549 +1,549 @@
1
- /**
2
- * 記録済みseam提案を隔離worktreeで実際に適用し、五条件で採否を決める(ADR 0137・0138)。
3
- *
4
- * 本repositoryは一切変更しない。変換も検証も使い捨てworktreeの中だけで起き、残るのは判定と
5
- * その理由である。採用された変換を本ツリーへ着地させるのは別工程が持つ。
6
- */
7
-
8
- import { execFile, spawnSync } from 'node:child_process';
9
- import { mkdir, writeFile } from 'node:fs/promises';
10
- import path from 'node:path';
11
- import { promisify } from 'node:util';
12
-
13
- import { runIsolatedTransform } from './isolation-runner.mjs';
14
- import { collectSensorEvidence } from './sensor-adapter.mjs';
15
- import { invokeSensorCli } from './sensor-runtime.mjs';
16
- import { buildSeamDerivationQuerySet, deriveBoundedSeamCandidate } from './seam-derivation.mjs';
17
- import { joinImportSurface, mentions, planSeamRewrite } from './seam-rewrite.mjs';
18
- import {
19
- buildPostTransformWitnessSet, compareExportSurface, evaluateSeamVerification, measureWaveCount,
20
- } from './seam-verification.mjs';
21
- import { isTodoRef, todoSelfDigest } from './todo-contracts.mjs';
22
- import { digestArtifact } from './artifact-contracts.mjs';
23
- import { createHash } from 'node:crypto';
24
-
25
- const execFileAsync = promisify(execFile);
26
- const MISSING_PREFIX = 'callee_data_missing:';
27
- const MAX_CLOSURE_ROUNDS = 32;
28
- const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
29
- const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
30
-
31
- function nodeOf(entry) {
32
- const node = entry?.node ?? entry;
33
- return typeof node?.name === 'string' && typeof node?.filePath === 'string' ? node : null;
34
- }
35
-
36
- /**
37
- * 同一file内のcalleeを、閉包が閉じるまで反復して集める。
38
- *
39
- * 未照会と「calleeが無い」を同一視しないので、導出は不足を`callee_data_missing`で返す。
40
- * その名前を追加照会して繰り返す。1回で済ませようとすると閉包が浅くなり、移動先で参照だけが
41
- * 宙に浮く——構文は通るので実行するまで気づけない。
42
- */
43
- async function deriveWithClosure({ cwd, deriveOnce }) {
44
- const calleesBySymbol = {};
45
- const ask = async (symbols) => {
46
- if (symbols.length === 0) return;
47
- const querySet = buildSeamDerivationQuerySet(symbols);
48
- const collected = await collectSensorEvidence({ cwd, querySet });
49
- querySet.queries.forEach((query, index) => {
50
- if (query.operation !== 'callees') return;
51
- const raw = collected.outcomes[index];
52
- const list = raw?.data?.callees ?? raw?.data ?? [];
53
- calleesBySymbol[query.target] = (Array.isArray(list) ? list : [])
54
- .map(nodeOf).filter(Boolean)
55
- .map((node) => ({ name: node.name, path: node.filePath }));
56
- });
57
- };
58
- await ask(deriveOnce.seeds);
59
- for (let round = 0; round < MAX_CLOSURE_ROUNDS; round += 1) {
60
- const outcome = deriveOnce.derive(calleesBySymbol);
61
- if (outcome.candidate !== null) return { ...outcome, rounds: round + 1, calleesBySymbol };
62
- const missing = outcome.reasons
63
- .filter((reason) => reason.startsWith(MISSING_PREFIX))
64
- .map((reason) => reason.slice(MISSING_PREFIX.length));
65
- if (missing.length === 0) return { ...outcome, rounds: round + 1, calleesBySymbol };
66
- await ask(missing);
67
- }
68
- return { candidate: null, reasons: ['closure_rounds_exhausted'], calleesBySymbol };
69
- }
70
-
71
- /** 宣言symbolの行範囲。移す範囲を決めるので、原path上のexact一致だけを採る。 */
72
- const SYMBOL_LOOKUP_LIMIT = 500;
73
-
74
- /** gitに載らないbuild成果物のうち、focused testが要るものを実在する時だけ張る。 */
75
- async function buildOutputMounts(repoRoot) {
76
- const { access } = await import('node:fs/promises');
77
- const mounts = [];
78
- for (const entry of ['sensor/dist']) {
79
- try {
80
- await access(path.join(repoRoot, entry));
81
- mounts.push({ entry, target: path.join(repoRoot, entry) });
82
- } catch { /* 無ければ張らない。無い環境ではそのtestも同梱sensorを要求しない。 */ }
83
- }
84
- return mounts;
85
- }
86
-
87
- /**
88
- * 変換対象symbolの行範囲を、対象file限定で読む。
89
- *
90
- * witness evidenceの共通経路(`collectSensorEvidence`)で名前を引くと、sensor CLIの既定
91
- * `--limit 10`で打ち切られる。同名symbolが多いprojectでは対象fileの定義が窓の外へ落ち、
92
- * **実在するsymbolを「範囲なし」と誤報して正当な変換を棄却する**。実測では`GIT_SHA1`が
93
- * 17 fileにあり、名前順で先頭10件に入らなかった`src/seam-commit.mjs`の定義が返らなかった。
94
- *
95
- * よってここは共通経路を使わず、明示limitで引く。limitに達した結果は打ち切りの疑いがある
96
- * ので、`missing`ではなく`truncated`として区別して返す——観測の欠落を「無い」へ丸めない。
97
- */
98
- export async function readSymbolExtents({ cwd, sourcePath, symbols }) {
99
- const extents = {};
100
- const truncated = [];
101
- for (const symbol of [...new Set(symbols)]) {
102
- const result = invokeSensorCli(
103
- (command, args, options) => spawnSync(command, args, options),
104
- ['query', symbol, '--path', '.', '--limit', String(SYMBOL_LOOKUP_LIMIT), '--json'],
105
- { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
106
- );
107
- if (result.status !== 0) continue;
108
- let parsed;
109
- try { parsed = JSON.parse(result.stdout); } catch { continue; }
110
- const entries = Array.isArray(parsed) ? parsed : parsed?.data ?? parsed?.results ?? [];
111
- for (const entry of entries) {
112
- const node = nodeOf(entry);
113
- if (node === null || node.name !== symbol || node.filePath !== sourcePath) continue;
114
- if (!Number.isSafeInteger(node.startLine) || !Number.isSafeInteger(node.endLine)) continue;
115
- // 装飾込みの開始行(sensor v11)を優先する。Pythonの@decoratorやRustの#[derive]は
116
- // 宣言の外の行にあり、宣言行だけで切ると装飾が残余面へ取り残される。
117
- const start = Number.isSafeInteger(node.extentStartLine) && node.extentStartLine < node.startLine
118
- ? node.extentStartLine : node.startLine;
119
- // export状態もAST事実として持ち帰る(sc-013)。書き換え側のtext走査を置き換える。
120
- extents[symbol] = { startLine: start, endLine: node.endLine, isExported: node.isExported === true };
121
- }
122
- if (extents[symbol] === undefined && entries.length >= SYMBOL_LOOKUP_LIMIT) truncated.push(symbol);
123
- }
124
- return { extents, truncated: [...new Set(truncated)].sort(compareText) };
125
- }
126
-
127
- /**
128
- * 対象fileのimport面をsensorの観測から読む(sc-013)。
129
- *
130
- * `file-nodes`の`imports`(文の行範囲)と`import_bindings`(AST由来の束縛)を
131
- * `joinImportSurface`で文単位へ束ねる。観測が取れなければnullを返し、書き換え側が
132
- * `import_surface_missing`のtyped理由で止める——正規表現の再解析へfallbackしない。
133
- */
134
- export function readImportSurface({ cwd, sourcePath }) {
135
- const result = invokeSensorCli(
136
- (command, args, options) => spawnSync(command, args, options),
137
- ['file-nodes', sourcePath, '--path', '.'],
138
- { cwd, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
139
- );
140
- if (result.status !== 0) return null;
141
- let parsed;
142
- try { parsed = JSON.parse(result.stdout); } catch { return null; }
143
- if (!Array.isArray(parsed?.imports) || !Array.isArray(parsed?.import_bindings)) return null;
144
- return joinImportSurface(parsed.imports, parsed.import_bindings);
145
- }
146
-
147
- async function runIn(worktreePath, command, args) {
148
- try {
149
- const { stdout } = await execFileAsync(command, args, {
150
- cwd: worktreePath, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
151
- });
152
- return { ok: true, stdout };
153
- } catch (error) {
154
- return { ok: false, stdout: error?.stdout ?? '', stderr: error?.stderr ?? String(error) };
155
- }
156
- }
157
-
158
- /**
159
- * 変換で切断された参照を数える(検証網、ADR 0145)。
160
- *
161
- * 移した先のcodeが、残余面に留まったsymbol(module変数・非公開関数)へ束縛なしで言及して
162
- * いれば、その参照は切断されている——moduleの読み込みは通り、実行して初めてReferenceErrorに
163
- * なるので、focused testが当該経路を通らなければ黙って壊れたまま採用される。これを受入の
164
- * 一点で数える。
165
- *
166
- * 残余面のsymbol一覧は、変換後worktreeのfresh indexから抽出精度で取る(`file-nodes`)。
167
- * value-ref辺の名前フィルタはノード生成に効かないので、全小文字のmodule変数もここには載る。
168
- * `unresolved_refs`は使わない——bare参照の切断はそこに記録されないことを実測で確認した
169
- * (builtin呼び出しは載るが、未束縛のidentifier読みは載らない)。
170
- *
171
- * 検査は保守的である。`mentions`はtext一致なので、文字列やcomment内の同名語も
172
- * 「切断の疑い」として数える——見逃す方向ではなく誤検出の方向へ倒す(fail closed)。
173
- * 網は受入の一点だけで、過程には触れない。不認定は拒否ではなく、理由を見て直せば
174
- * 何度でも再提出できる。
175
- */
176
- async function detectSeveredReferences({ worktreePath, files, residualPath }) {
177
- const readFileNodes = (target) => {
178
- const result = invokeSensorCli(
179
- (command, args, options) => spawnSync(command, args, options),
180
- ['file-nodes', target, '--path', '.'],
181
- { cwd: worktreePath, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
182
- );
183
- if (result.status !== 0) return null;
184
- let parsed;
185
- try { parsed = JSON.parse(result.stdout); } catch { return null; }
186
- if (!Array.isArray(parsed?.nodes)) return null;
187
- return parsed;
188
- };
189
-
190
- const residual = readFileNodes(residualPath);
191
- if (residual === null) return { observed: false, entries: [] };
192
- const residualNames = residual.nodes.map(({ name }) => name);
193
-
194
- const entries = [];
195
- for (const [target, body] of Object.entries(files)) {
196
- if (target === residualPath) continue;
197
- const own = readFileNodes(target);
198
- if (own === null) return { observed: false, entries: [] };
199
- const defined = new Set(own.nodes.map(({ name }) => name));
200
- // import束縛はworktreeのfresh indexのAST観測から取る(sc-013)。text再解析をしない。
201
- // 束縛が観測できないindexでは網の判定材料が欠けるので、unobservedへ倒す(fail closed)。
202
- if (!Array.isArray(own.import_bindings)) return { observed: false, entries: [] };
203
- const imported = new Set(own.import_bindings
204
- .map(({ local }) => local).filter((name) => typeof name === 'string'));
205
- for (const name of residualNames) {
206
- if (defined.has(name) || imported.has(name)) continue;
207
- if (mentions(body, name)) entries.push({ file: target, name });
208
- }
209
- }
210
- return {
211
- observed: true,
212
- entries: entries.sort((left, right) => compareText(
213
- `${left.file}\0${left.name}`, `${right.file}\0${right.name}`,
214
- )),
215
- };
216
- }
217
-
218
- /**
219
- * 変換後worktreeを再indexし、新pathが索引に載ったかを見る。
220
- *
221
- * 載っていなければ、その後のcompileは古い構造を見ている。observationの欠落を
222
- * 「変わらなかった」へ丸めない。
223
- */
224
- async function observeFreshSensor({ worktreePath, latticeBin, paths }) {
225
- const init = await runIn(worktreePath, process.execPath, [latticeBin, 'sensor', 'init', '.', '--json']);
226
- if (!init.ok) {
227
- return {
228
- fresh: false,
229
- detail: `sensor_init_failed:${String(init.stderr ?? '').replace(/\s+/gu, ' ').slice(0, 200)}`,
230
- };
231
- }
232
- const querySet = {
233
- queries: [
234
- { id: 'fresh-status', operation: 'status' },
235
- ...paths.map((target, index) => ({
236
- id: `fresh-affected-${String(index).padStart(3, '0')}`, operation: 'affected', target,
237
- })),
238
- ],
239
- };
240
- const collected = await collectSensorEvidence({ cwd: worktreePath, querySet });
241
- const affectedByPath = {};
242
- let fresh = true;
243
- querySet.queries.forEach((query, index) => {
244
- if (query.operation !== 'affected') return;
245
- const outcome = collected.outcomes[index];
246
- const entry = outcome?.targets?.[0];
247
- // `path_state`はfs観測で不存在だった時にだけ付く。正常時は欄そのものが無いので、
248
- // `=== 'file'`を要求すると常に落ちる。見るべきは「不存在と観測されていないこと」と
249
- // 「affected観測が在ること」の2つである。
250
- if (entry?.path_state === 'absent' || !Array.isArray(entry?.data?.affectedTests)) {
251
- fresh = false;
252
- return;
253
- }
254
- affectedByPath[query.target] = [...entry.data.affectedTests].sort(compareText);
255
- });
256
- return { fresh, affectedByPath, detail: fresh ? null : 'new_path_not_indexed' };
257
- }
258
-
259
- /** 競合対を`{task, task}`の集合として数える。componentでなくplan全体を見る(ADR 0138)。 */
260
- function conflictPairsOf(artifact) {
261
- return new Set((artifact?.conflicts ?? [])
262
- .map(({ task_ids: ids }) => [...ids].sort(compareText).join('\0')));
263
- }
264
-
265
- /** 係争資源の中で、そのtaskが自分の担当と宣言したsymbol。 */
266
- function ownedSymbolsWithin(witnessSet, taskIds, sourcePath) {
267
- const owned = {};
268
- for (const taskId of taskIds) {
269
- owned[taskId] = (witnessSet?.manual_witness?.[taskId]?.concern_anchors ?? [])
270
- .filter((entry) => entry.within.target === sourcePath)
271
- .flatMap((entry) => entry.symbols);
272
- }
273
- return owned;
274
- }
275
-
276
- /**
277
- * 記録済みseam提案を、変換の入力へ正規化する。
278
- *
279
- * 提案が出すpathはhash由来の仮名である。名前を付けるのは判断なので製品が発明しない
280
- * (AGENTS.md「装置の境界」)。与えられた名前は導出の入力として最初から使う——後から改名すると、
281
- * 生成済みのimport指定子が旧名を指したまま残る。
282
- */
283
- export function seamConflictFromProposal({ proposal, witnessSet, pathNames = {} } = {}) {
284
- const decision = (proposal?.decisions ?? []).find(({ verdict }) => verdict === 'seam_candidate');
285
- if (decision === undefined) return { conflict: null, reasons: ['no_seam_candidate'] };
286
- const sourcePath = decision.conflicts[0].target;
287
- return {
288
- conflict: {
289
- sourcePath,
290
- taskIds: [...decision.task_ids],
291
- ownedSymbolsByTask: ownedSymbolsWithin(witnessSet, decision.task_ids, sourcePath),
292
- proposedPathByTask: Object.fromEntries(decision.seam_candidate.proposed_surfaces
293
- .map((surface) => [
294
- surface.owner_task_ids[0],
295
- pathNames[surface.owner_task_ids[0]] ?? surface.target,
296
- ])),
297
- affectedTests: decision.seam_candidate.affected_tests,
298
- baseSha: proposal.source_binding.base_sha,
299
- manifestDigest: proposal.source_binding.independence_result_digest,
300
- findingDigest: decision.seam_candidate.proposal_digest,
301
- candidateId: `seam-apply-${decision.component_id}`,
302
- },
303
- reasons: [],
304
- };
305
- }
306
-
307
- /**
308
- * 実行時競合のfindingを、同じ変換の入力へ正規化する(請求項8)。
309
- *
310
- * 静的側との違いは入力だけである。記録済み提案の代わりに、観測された競合path・関与する2 task・
311
- * 実行中requestの宣言を持つ。導出の芯は同じなので、口だけを分けて共有する。
312
- *
313
- * 提案と違い所有面のpathは決まっていないので、名前は呼び出し側が全部与える。与えられなければ
314
- * 候補を作らない——製品が名前を発明しないという線は実行時でも同じである。
315
- */
316
- export function seamConflictFromFinding({
317
- finding, witnessSet, pathNames = {}, affectedTests = [], baseSha, manifestDigest,
318
- recordedFindingDigest = null,
319
- } = {}) {
320
- if (finding?.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
321
- return { conflict: null, reasons: ['finding_not_write_conflict'] };
322
- }
323
- const taskIds = [...(finding.todo_ids ?? [])].sort(compareText);
324
- if (taskIds.length < 2) return { conflict: null, reasons: ['finding_below_two_tasks'] };
325
- const missing = taskIds.filter((taskId) => !isTodoRef(pathNames[taskId] ?? ''));
326
- if (missing.length > 0) {
327
- return { conflict: null, reasons: missing.map((taskId) => `owned_path_name_missing:${taskId}`) };
328
- }
329
- return {
330
- conflict: {
331
- sourcePath: finding.path,
332
- taskIds,
333
- ownedSymbolsByTask: ownedSymbolsWithin(witnessSet, taskIds, finding.path),
334
- proposedPathByTask: Object.fromEntries(taskIds.map((taskId) => [taskId, pathNames[taskId]])),
335
- affectedTests: [...affectedTests].sort(compareText),
336
- baseSha,
337
- manifestDigest,
338
- // 実行時は提案artifactが無い。観測したfindingそのものを出所として縛る。
339
- //
340
- // **記録済みfindingのdigestがあるなら、それを使う。** 内容から再導出したdigestで縛ると、
341
- // 「この変換はあのfindingへの答えだ」という記録が、storeに実在しないidを指す。実際、
342
- // 再計画側は`findings/<digest>.json`を読むので、再導出値では必ず読めない。
343
- findingDigest: recordedFindingDigest ?? digestArtifact({
344
- kind: finding.kind, path: finding.path, todo_ids: taskIds,
345
- }),
346
- candidateId: `seam-runtime-${sha16(`${finding.path}\0${taskIds.join(',')}`)}`,
347
- },
348
- reasons: [],
349
- };
350
- }
351
-
352
- /**
353
- * 正規化した競合入力から変換を適用し、五条件で採否を返す。
354
- *
355
- * @returns {Promise<{outcome: object, files: object|null}>} `lattice.seam_apply_outcome.v1`
356
- */
357
- export async function applySeamConflict({
358
- repoRoot, planKey, conflict, witnessSet, latticeBin, sharedPathFor,
359
- executors, compileIndependence, pathNames = {}, precedences = [],
360
- } = {}) {
361
- const {
362
- sourcePath, taskIds, ownedSymbolsByTask, proposedPathByTask, affectedTests,
363
- baseSha, manifestDigest, findingDigest, candidateId,
364
- } = conflict;
365
- const decision = { task_ids: taskIds };
366
-
367
- const derived = await deriveWithClosure({
368
- cwd: repoRoot,
369
- deriveOnce: {
370
- seeds: [...new Set(Object.values(ownedSymbolsByTask).flat())],
371
- derive: (calleesBySymbol) => deriveBoundedSeamCandidate({
372
- sourcePath,
373
- taskRefs: taskIds.map((taskId) => ({ plan_key: planKey, task_id: taskId })),
374
- ownedSymbolsByTask,
375
- proposedPathByTask,
376
- sharedPath: pathNames.shared ?? sharedPathFor(sourcePath),
377
- calleesBySymbol,
378
- affectedTests,
379
- baseSha,
380
- manifestDigest,
381
- findingDigest,
382
- candidateId,
383
- }),
384
- },
385
- });
386
- if (derived.candidate === null) {
387
- return { outcome: outcome({ planKey, decision: 'rejected', reasons: derived.reasons }), files: null };
388
- }
389
- const candidate = derived.candidate;
390
-
391
- const { readFile } = await import('node:fs/promises');
392
- const beforeText = await readFile(path.join(repoRoot, sourcePath), 'utf8');
393
- const lookup = await readSymbolExtents({
394
- cwd: repoRoot, sourcePath,
395
- symbols: candidate.surfaces.flatMap(({ symbols }) => symbols),
396
- });
397
- if (lookup.truncated.length > 0) {
398
- // 打ち切りは「範囲が無い」ではない。誤った理由で棄却して原因を隠さない。
399
- return {
400
- outcome: outcome({ planKey, decision: 'rejected', candidate,
401
- reasons: lookup.truncated.map((symbol) => `symbol_lookup_truncated:${symbol}`) }),
402
- files: null,
403
- };
404
- }
405
- const rewritten = planSeamRewrite({
406
- sourceText: beforeText, candidate, symbolExtents: lookup.extents,
407
- importSurface: readImportSurface({ cwd: repoRoot, sourcePath }),
408
- });
409
- if (rewritten.files === null) {
410
- return { outcome: outcome({ planKey, decision: 'rejected', reasons: rewritten.reasons, candidate }), files: null };
411
- }
412
-
413
- const { mkdtemp, rm } = await import('node:fs/promises');
414
- const { tmpdir } = await import('node:os');
415
- const scratchLattice = await mkdtemp(path.join(tmpdir(), 'lattice-seam-scratch-'));
416
- const beforePairs = conflictPairsOf(compileIndependence.baseArtifact);
417
- const targetPair = [...decision.task_ids].sort(compareText).join('\0');
418
- let observation = null;
419
- let verifierFailure = null;
420
- try {
421
- await runIsolatedTransform({
422
- repoRoot,
423
- baseRef: candidate.base_sha,
424
- allowedPaths: candidate.allowed_paths,
425
- transform: async ({ worktreePath }) => {
426
- for (const [target, text] of Object.entries(rewritten.files)) {
427
- await mkdir(path.dirname(path.join(worktreePath, target)), { recursive: true });
428
- await writeFile(path.join(worktreePath, target), text);
429
- }
430
- },
431
- // 依存が無いとfocused testはERR_MODULE_NOT_FOUNDで落ち、変換の欠陥と環境の欠陥が
432
- // 同じfailに見える。runnerが張るので、呼び出し側が任意の変更を隠す口にはならない。
433
- //
434
-
435
- mounts: [
436
- { entry: 'node_modules', target: path.join(repoRoot, 'node_modules') },
437
- // 索引の書き先を使い捨てへ向ける。verifierも再indexもここへ書くので、本repoの
438
- // 索引を触らせない。src/testへはrunnerがmountを拒否する。
439
- { entry: '.lattice/sensor', target: scratchLattice },
440
- // build成果物はgitignoreされているので、どのcommitのworktreeにも存在しない。
441
- // 張らないと、同梱sensorを起動するfocused testがすべてENOENTで落ち、
442
- // focused_tests_passedが原理的に満たせなくなる(実測でこれに当たった)。
443
- // 存在する時だけ張る——Latticeを依存として使うprojectはnode_modules側に持つ。
444
- ...await buildOutputMounts(repoRoot),
445
- ],
446
- // 書き先を隠すのでなく、書かせない。verifierが常駐面を起こすとworktreeへ索引が
447
- // 生まれ、変更を残さない規律に当たる。
448
- verifierEnv: { LATTICE_DASHBOARD_AUTOSTART: '0' },
449
- verifyCommands: candidate.verification_policy.focused_test_refs
450
- .map((ref) => ({ command: process.execPath, args: ['--test', ref] })),
451
- observe: async ({ worktreePath }) => {
452
- const owned = candidate.surfaces
453
- .filter(({ role }) => role === 'task_owned').map(({ path: target }) => target);
454
- const sensor = await observeFreshSensor({ worktreePath, latticeBin, paths: owned });
455
- observation = { sensor, afterText: null, afterArtifact: null, severed: null };
456
- observation.afterText = await readFile(path.join(worktreePath, sourcePath), 'utf8');
457
- if (!sensor.fresh) return;
458
- // 網は受入の一点だけ(ADR 0145)。fresh indexの上でしか意味を持たないので、
459
- // sensorが新pathを見ていない時は数えず、observation欠落として別理由で落とす。
460
- observation.severed = await detectSeveredReferences({
461
- worktreePath, files: rewritten.files, residualPath: sourcePath,
462
- });
463
- const post = buildPostTransformWitnessSet({
464
- witnessSet, candidate, affectedTestsByPath: sensor.affectedByPath,
465
- });
466
- if (post.witnessSet === null) {
467
- observation.reasons = post.reasons;
468
- return;
469
- }
470
- observation.afterArtifact = await compileIndependence.inWorktree({
471
- worktreePath, witnessSet: post.witnessSet,
472
- });
473
- },
474
- });
475
- } catch (error) {
476
- verifierFailure = String(error?.message ?? error);
477
- } finally {
478
- await rm(scratchLattice, { recursive: true, force: true });
479
- }
480
-
481
- const afterPairs = observation?.afterArtifact === null || observation?.afterArtifact === undefined
482
- ? null : conflictPairsOf(observation.afterArtifact);
483
- const orderedTaskIds = [...taskIds].sort(compareText);
484
- const verification = evaluateSeamVerification({
485
- exportSurface: observation?.afterText === null || observation?.afterText === undefined
486
- ? { preserved: false, missing: [] }
487
- : compareExportSurface({ before: beforeText, after: observation.afterText }),
488
- severed: observation?.severed ?? null,
489
- focusedTestsPassed: verifierFailure === null,
490
- sensorFresh: observation?.sensor?.fresh === true,
491
- conflictPairs: afterPairs === null ? { targetResolved: false }
492
- : { targetResolved: !afterPairs.has(targetPair), before: beforePairs.size, after: afterPairs.size },
493
- waves: {
494
- before: measureWaveCount({
495
- taskIds, conflictPairs: [...beforePairs].map((key) => key.split('\0')), precedences, executors,
496
- }).waves,
497
- after: afterPairs === null ? null : measureWaveCount({
498
- taskIds, conflictPairs: [...afterPairs].map((key) => key.split('\0')), precedences, executors,
499
- }).waves,
500
- },
501
- });
502
-
503
- return { files: rewritten.files, outcome: outcome({
504
- planKey,
505
- decision: verification.decision,
506
- reasons: [
507
- ...verification.failures,
508
- ...(verifierFailure === null ? [] : [`verifier:${verifierFailure}`]),
509
- // 判定が落ちた理由を、条件名だけで終わらせない(ADR 0130)。
510
- ...(observation?.sensor?.detail ? [`sensor_detail:${observation.sensor.detail}`] : []),
511
- ...(observation?.reasons ?? []).map((reason) => `witness:${reason}`),
512
- ],
513
- candidate,
514
- conditions: verification.conditions,
515
- closureRounds: derived.rounds ?? null,
516
- }) };
517
- }
518
-
519
- function outcome({ planKey, decision, reasons, candidate = null, conditions = null, closureRounds = null }) {
520
- const result = {
521
- schema: 'lattice.seam_apply_outcome.v1',
522
- plan_key: planKey,
523
- decision,
524
- candidate_id: candidate?.candidate_id ?? null,
525
- candidate_digest: candidate?.candidate_digest ?? null,
526
- surfaces: (candidate?.surfaces ?? []).map(({ role, path: target, owner_task_ids: owners }) => ({
527
- role, path: target, owner_task_ids: [...owners],
528
- })),
529
- conditions,
530
- closure_rounds: closureRounds,
531
- reasons: [...new Set(reasons)].sort(compareText),
532
- result_digest: '',
533
- };
534
- result.result_digest = todoSelfDigest(result, 'result_digest');
535
- return result;
536
- }
537
-
538
- /**
539
- * 記録済みseam提案を適用して採否を返す。入力の正規化だけを行い、芯は`applySeamConflict`が持つ。
540
- */
541
- export async function applySeamProposal({ sourceProposal, witnessSet, pathNames = {}, ...rest } = {}) {
542
- const { conflict, reasons } = seamConflictFromProposal({
543
- proposal: sourceProposal, witnessSet, pathNames,
544
- });
545
- if (conflict === null) {
546
- return { outcome: outcome({ planKey: rest.planKey, decision: 'rejected', reasons }), files: null };
547
- }
548
- return applySeamConflict({ ...rest, conflict, witnessSet, pathNames });
549
- }
1
+ /**
2
+ * 記録済みseam提案を隔離worktreeで実際に適用し、五条件で採否を決める(ADR 0137・0138)。
3
+ *
4
+ * 本repositoryは一切変更しない。変換も検証も使い捨てworktreeの中だけで起き、残るのは判定と
5
+ * その理由である。採用された変換を本ツリーへ着地させるのは別工程が持つ。
6
+ */
7
+
8
+ import { execFile, spawnSync } from 'node:child_process';
9
+ import { mkdir, writeFile } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { promisify } from 'node:util';
12
+
13
+ import { runIsolatedTransform } from './isolation-runner.mjs';
14
+ import { collectSensorEvidence } from './sensor-adapter.mjs';
15
+ import { invokeSensorCli } from './sensor-runtime.mjs';
16
+ import { buildSeamDerivationQuerySet, deriveBoundedSeamCandidate } from './seam-derivation.mjs';
17
+ import { joinImportSurface, mentions, planSeamRewrite } from './seam-rewrite.mjs';
18
+ import {
19
+ buildPostTransformWitnessSet, compareExportSurface, evaluateSeamVerification, measureWaveCount,
20
+ } from './seam-verification.mjs';
21
+ import { isTodoRef, todoSelfDigest } from './todo-contracts.mjs';
22
+ import { digestArtifact } from './artifact-contracts.mjs';
23
+ import { createHash } from 'node:crypto';
24
+
25
+ const execFileAsync = promisify(execFile);
26
+ const MISSING_PREFIX = 'callee_data_missing:';
27
+ const MAX_CLOSURE_ROUNDS = 32;
28
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
29
+ const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
30
+
31
+ function nodeOf(entry) {
32
+ const node = entry?.node ?? entry;
33
+ return typeof node?.name === 'string' && typeof node?.filePath === 'string' ? node : null;
34
+ }
35
+
36
+ /**
37
+ * 同一file内のcalleeを、閉包が閉じるまで反復して集める。
38
+ *
39
+ * 未照会と「calleeが無い」を同一視しないので、導出は不足を`callee_data_missing`で返す。
40
+ * その名前を追加照会して繰り返す。1回で済ませようとすると閉包が浅くなり、移動先で参照だけが
41
+ * 宙に浮く——構文は通るので実行するまで気づけない。
42
+ */
43
+ async function deriveWithClosure({ cwd, deriveOnce }) {
44
+ const calleesBySymbol = {};
45
+ const ask = async (symbols) => {
46
+ if (symbols.length === 0) return;
47
+ const querySet = buildSeamDerivationQuerySet(symbols);
48
+ const collected = await collectSensorEvidence({ cwd, querySet });
49
+ querySet.queries.forEach((query, index) => {
50
+ if (query.operation !== 'callees') return;
51
+ const raw = collected.outcomes[index];
52
+ const list = raw?.data?.callees ?? raw?.data ?? [];
53
+ calleesBySymbol[query.target] = (Array.isArray(list) ? list : [])
54
+ .map(nodeOf).filter(Boolean)
55
+ .map((node) => ({ name: node.name, path: node.filePath }));
56
+ });
57
+ };
58
+ await ask(deriveOnce.seeds);
59
+ for (let round = 0; round < MAX_CLOSURE_ROUNDS; round += 1) {
60
+ const outcome = deriveOnce.derive(calleesBySymbol);
61
+ if (outcome.candidate !== null) return { ...outcome, rounds: round + 1, calleesBySymbol };
62
+ const missing = outcome.reasons
63
+ .filter((reason) => reason.startsWith(MISSING_PREFIX))
64
+ .map((reason) => reason.slice(MISSING_PREFIX.length));
65
+ if (missing.length === 0) return { ...outcome, rounds: round + 1, calleesBySymbol };
66
+ await ask(missing);
67
+ }
68
+ return { candidate: null, reasons: ['closure_rounds_exhausted'], calleesBySymbol };
69
+ }
70
+
71
+ /** 宣言symbolの行範囲。移す範囲を決めるので、原path上のexact一致だけを採る。 */
72
+ const SYMBOL_LOOKUP_LIMIT = 500;
73
+
74
+ /** gitに載らないbuild成果物のうち、focused testが要るものを実在する時だけ張る。 */
75
+ async function buildOutputMounts(repoRoot) {
76
+ const { access } = await import('node:fs/promises');
77
+ const mounts = [];
78
+ for (const entry of ['sensor/dist']) {
79
+ try {
80
+ await access(path.join(repoRoot, entry));
81
+ mounts.push({ entry, target: path.join(repoRoot, entry) });
82
+ } catch { /* 無ければ張らない。無い環境ではそのtestも同梱sensorを要求しない。 */ }
83
+ }
84
+ return mounts;
85
+ }
86
+
87
+ /**
88
+ * 変換対象symbolの行範囲を、対象file限定で読む。
89
+ *
90
+ * witness evidenceの共通経路(`collectSensorEvidence`)で名前を引くと、sensor CLIの既定
91
+ * `--limit 10`で打ち切られる。同名symbolが多いprojectでは対象fileの定義が窓の外へ落ち、
92
+ * **実在するsymbolを「範囲なし」と誤報して正当な変換を棄却する**。実測では`GIT_SHA1`が
93
+ * 17 fileにあり、名前順で先頭10件に入らなかった`src/seam-commit.mjs`の定義が返らなかった。
94
+ *
95
+ * よってここは共通経路を使わず、明示limitで引く。limitに達した結果は打ち切りの疑いがある
96
+ * ので、`missing`ではなく`truncated`として区別して返す——観測の欠落を「無い」へ丸めない。
97
+ */
98
+ export async function readSymbolExtents({ cwd, sourcePath, symbols }) {
99
+ const extents = {};
100
+ const truncated = [];
101
+ for (const symbol of [...new Set(symbols)]) {
102
+ const result = invokeSensorCli(
103
+ (command, args, options) => spawnSync(command, args, options),
104
+ ['query', symbol, '--path', '.', '--limit', String(SYMBOL_LOOKUP_LIMIT), '--json'],
105
+ { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
106
+ );
107
+ if (result.status !== 0) continue;
108
+ let parsed;
109
+ try { parsed = JSON.parse(result.stdout); } catch { continue; }
110
+ const entries = Array.isArray(parsed) ? parsed : parsed?.data ?? parsed?.results ?? [];
111
+ for (const entry of entries) {
112
+ const node = nodeOf(entry);
113
+ if (node === null || node.name !== symbol || node.filePath !== sourcePath) continue;
114
+ if (!Number.isSafeInteger(node.startLine) || !Number.isSafeInteger(node.endLine)) continue;
115
+ // 装飾込みの開始行(sensor v11)を優先する。Pythonの@decoratorやRustの#[derive]は
116
+ // 宣言の外の行にあり、宣言行だけで切ると装飾が残余面へ取り残される。
117
+ const start = Number.isSafeInteger(node.extentStartLine) && node.extentStartLine < node.startLine
118
+ ? node.extentStartLine : node.startLine;
119
+ // export状態もAST事実として持ち帰る(sc-013)。書き換え側のtext走査を置き換える。
120
+ extents[symbol] = { startLine: start, endLine: node.endLine, isExported: node.isExported === true };
121
+ }
122
+ if (extents[symbol] === undefined && entries.length >= SYMBOL_LOOKUP_LIMIT) truncated.push(symbol);
123
+ }
124
+ return { extents, truncated: [...new Set(truncated)].sort(compareText) };
125
+ }
126
+
127
+ /**
128
+ * 対象fileのimport面をsensorの観測から読む(sc-013)。
129
+ *
130
+ * `file-nodes`の`imports`(文の行範囲)と`import_bindings`(AST由来の束縛)を
131
+ * `joinImportSurface`で文単位へ束ねる。観測が取れなければnullを返し、書き換え側が
132
+ * `import_surface_missing`のtyped理由で止める——正規表現の再解析へfallbackしない。
133
+ */
134
+ export function readImportSurface({ cwd, sourcePath }) {
135
+ const result = invokeSensorCli(
136
+ (command, args, options) => spawnSync(command, args, options),
137
+ ['file-nodes', sourcePath, '--path', '.'],
138
+ { cwd, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
139
+ );
140
+ if (result.status !== 0) return null;
141
+ let parsed;
142
+ try { parsed = JSON.parse(result.stdout); } catch { return null; }
143
+ if (!Array.isArray(parsed?.imports) || !Array.isArray(parsed?.import_bindings)) return null;
144
+ return joinImportSurface(parsed.imports, parsed.import_bindings);
145
+ }
146
+
147
+ async function runIn(worktreePath, command, args) {
148
+ try {
149
+ const { stdout } = await execFileAsync(command, args, {
150
+ cwd: worktreePath, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
151
+ });
152
+ return { ok: true, stdout };
153
+ } catch (error) {
154
+ return { ok: false, stdout: error?.stdout ?? '', stderr: error?.stderr ?? String(error) };
155
+ }
156
+ }
157
+
158
+ /**
159
+ * 変換で切断された参照を数える(検証網、ADR 0145)。
160
+ *
161
+ * 移した先のcodeが、残余面に留まったsymbol(module変数・非公開関数)へ束縛なしで言及して
162
+ * いれば、その参照は切断されている——moduleの読み込みは通り、実行して初めてReferenceErrorに
163
+ * なるので、focused testが当該経路を通らなければ黙って壊れたまま採用される。これを受入の
164
+ * 一点で数える。
165
+ *
166
+ * 残余面のsymbol一覧は、変換後worktreeのfresh indexから抽出精度で取る(`file-nodes`)。
167
+ * value-ref辺の名前フィルタはノード生成に効かないので、全小文字のmodule変数もここには載る。
168
+ * `unresolved_refs`は使わない——bare参照の切断はそこに記録されないことを実測で確認した
169
+ * (builtin呼び出しは載るが、未束縛のidentifier読みは載らない)。
170
+ *
171
+ * 検査は保守的である。`mentions`はtext一致なので、文字列やcomment内の同名語も
172
+ * 「切断の疑い」として数える——見逃す方向ではなく誤検出の方向へ倒す(fail closed)。
173
+ * 網は受入の一点だけで、過程には触れない。不認定は拒否ではなく、理由を見て直せば
174
+ * 何度でも再提出できる。
175
+ */
176
+ async function detectSeveredReferences({ worktreePath, files, residualPath }) {
177
+ const readFileNodes = (target) => {
178
+ const result = invokeSensorCli(
179
+ (command, args, options) => spawnSync(command, args, options),
180
+ ['file-nodes', target, '--path', '.'],
181
+ { cwd: worktreePath, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
182
+ );
183
+ if (result.status !== 0) return null;
184
+ let parsed;
185
+ try { parsed = JSON.parse(result.stdout); } catch { return null; }
186
+ if (!Array.isArray(parsed?.nodes)) return null;
187
+ return parsed;
188
+ };
189
+
190
+ const residual = readFileNodes(residualPath);
191
+ if (residual === null) return { observed: false, entries: [] };
192
+ const residualNames = residual.nodes.map(({ name }) => name);
193
+
194
+ const entries = [];
195
+ for (const [target, body] of Object.entries(files)) {
196
+ if (target === residualPath) continue;
197
+ const own = readFileNodes(target);
198
+ if (own === null) return { observed: false, entries: [] };
199
+ const defined = new Set(own.nodes.map(({ name }) => name));
200
+ // import束縛はworktreeのfresh indexのAST観測から取る(sc-013)。text再解析をしない。
201
+ // 束縛が観測できないindexでは網の判定材料が欠けるので、unobservedへ倒す(fail closed)。
202
+ if (!Array.isArray(own.import_bindings)) return { observed: false, entries: [] };
203
+ const imported = new Set(own.import_bindings
204
+ .map(({ local }) => local).filter((name) => typeof name === 'string'));
205
+ for (const name of residualNames) {
206
+ if (defined.has(name) || imported.has(name)) continue;
207
+ if (mentions(body, name)) entries.push({ file: target, name });
208
+ }
209
+ }
210
+ return {
211
+ observed: true,
212
+ entries: entries.sort((left, right) => compareText(
213
+ `${left.file}\0${left.name}`, `${right.file}\0${right.name}`,
214
+ )),
215
+ };
216
+ }
217
+
218
+ /**
219
+ * 変換後worktreeを再indexし、新pathが索引に載ったかを見る。
220
+ *
221
+ * 載っていなければ、その後のcompileは古い構造を見ている。observationの欠落を
222
+ * 「変わらなかった」へ丸めない。
223
+ */
224
+ async function observeFreshSensor({ worktreePath, latticeBin, paths }) {
225
+ const init = await runIn(worktreePath, process.execPath, [latticeBin, 'sensor', 'init', '.', '--json']);
226
+ if (!init.ok) {
227
+ return {
228
+ fresh: false,
229
+ detail: `sensor_init_failed:${String(init.stderr ?? '').replace(/\s+/gu, ' ').slice(0, 200)}`,
230
+ };
231
+ }
232
+ const querySet = {
233
+ queries: [
234
+ { id: 'fresh-status', operation: 'status' },
235
+ ...paths.map((target, index) => ({
236
+ id: `fresh-affected-${String(index).padStart(3, '0')}`, operation: 'affected', target,
237
+ })),
238
+ ],
239
+ };
240
+ const collected = await collectSensorEvidence({ cwd: worktreePath, querySet });
241
+ const affectedByPath = {};
242
+ let fresh = true;
243
+ querySet.queries.forEach((query, index) => {
244
+ if (query.operation !== 'affected') return;
245
+ const outcome = collected.outcomes[index];
246
+ const entry = outcome?.targets?.[0];
247
+ // `path_state`はfs観測で不存在だった時にだけ付く。正常時は欄そのものが無いので、
248
+ // `=== 'file'`を要求すると常に落ちる。見るべきは「不存在と観測されていないこと」と
249
+ // 「affected観測が在ること」の2つである。
250
+ if (entry?.path_state === 'absent' || !Array.isArray(entry?.data?.affectedTests)) {
251
+ fresh = false;
252
+ return;
253
+ }
254
+ affectedByPath[query.target] = [...entry.data.affectedTests].sort(compareText);
255
+ });
256
+ return { fresh, affectedByPath, detail: fresh ? null : 'new_path_not_indexed' };
257
+ }
258
+
259
+ /** 競合対を`{task, task}`の集合として数える。componentでなくplan全体を見る(ADR 0138)。 */
260
+ function conflictPairsOf(artifact) {
261
+ return new Set((artifact?.conflicts ?? [])
262
+ .map(({ task_ids: ids }) => [...ids].sort(compareText).join('\0')));
263
+ }
264
+
265
+ /** 係争資源の中で、そのtaskが自分の担当と宣言したsymbol。 */
266
+ function ownedSymbolsWithin(witnessSet, taskIds, sourcePath) {
267
+ const owned = {};
268
+ for (const taskId of taskIds) {
269
+ owned[taskId] = (witnessSet?.manual_witness?.[taskId]?.concern_anchors ?? [])
270
+ .filter((entry) => entry.within.target === sourcePath)
271
+ .flatMap((entry) => entry.symbols);
272
+ }
273
+ return owned;
274
+ }
275
+
276
+ /**
277
+ * 記録済みseam提案を、変換の入力へ正規化する。
278
+ *
279
+ * 提案が出すpathはhash由来の仮名である。名前を付けるのは判断なので製品が発明しない
280
+ * (AGENTS.md「装置の境界」)。与えられた名前は導出の入力として最初から使う——後から改名すると、
281
+ * 生成済みのimport指定子が旧名を指したまま残る。
282
+ */
283
+ export function seamConflictFromProposal({ proposal, witnessSet, pathNames = {} } = {}) {
284
+ const decision = (proposal?.decisions ?? []).find(({ verdict }) => verdict === 'seam_candidate');
285
+ if (decision === undefined) return { conflict: null, reasons: ['no_seam_candidate'] };
286
+ const sourcePath = decision.conflicts[0].target;
287
+ return {
288
+ conflict: {
289
+ sourcePath,
290
+ taskIds: [...decision.task_ids],
291
+ ownedSymbolsByTask: ownedSymbolsWithin(witnessSet, decision.task_ids, sourcePath),
292
+ proposedPathByTask: Object.fromEntries(decision.seam_candidate.proposed_surfaces
293
+ .map((surface) => [
294
+ surface.owner_task_ids[0],
295
+ pathNames[surface.owner_task_ids[0]] ?? surface.target,
296
+ ])),
297
+ affectedTests: decision.seam_candidate.affected_tests,
298
+ baseSha: proposal.source_binding.base_sha,
299
+ manifestDigest: proposal.source_binding.independence_result_digest,
300
+ findingDigest: decision.seam_candidate.proposal_digest,
301
+ candidateId: `seam-apply-${decision.component_id}`,
302
+ },
303
+ reasons: [],
304
+ };
305
+ }
306
+
307
+ /**
308
+ * 実行時競合のfindingを、同じ変換の入力へ正規化する(請求項8)。
309
+ *
310
+ * 静的側との違いは入力だけである。記録済み提案の代わりに、観測された競合path・関与する2 task・
311
+ * 実行中requestの宣言を持つ。導出の芯は同じなので、口だけを分けて共有する。
312
+ *
313
+ * 提案と違い所有面のpathは決まっていないので、名前は呼び出し側が全部与える。与えられなければ
314
+ * 候補を作らない——製品が名前を発明しないという線は実行時でも同じである。
315
+ */
316
+ export function seamConflictFromFinding({
317
+ finding, witnessSet, pathNames = {}, affectedTests = [], baseSha, manifestDigest,
318
+ recordedFindingDigest = null,
319
+ } = {}) {
320
+ if (finding?.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
321
+ return { conflict: null, reasons: ['finding_not_write_conflict'] };
322
+ }
323
+ const taskIds = [...(finding.todo_ids ?? [])].sort(compareText);
324
+ if (taskIds.length < 2) return { conflict: null, reasons: ['finding_below_two_tasks'] };
325
+ const missing = taskIds.filter((taskId) => !isTodoRef(pathNames[taskId] ?? ''));
326
+ if (missing.length > 0) {
327
+ return { conflict: null, reasons: missing.map((taskId) => `owned_path_name_missing:${taskId}`) };
328
+ }
329
+ return {
330
+ conflict: {
331
+ sourcePath: finding.path,
332
+ taskIds,
333
+ ownedSymbolsByTask: ownedSymbolsWithin(witnessSet, taskIds, finding.path),
334
+ proposedPathByTask: Object.fromEntries(taskIds.map((taskId) => [taskId, pathNames[taskId]])),
335
+ affectedTests: [...affectedTests].sort(compareText),
336
+ baseSha,
337
+ manifestDigest,
338
+ // 実行時は提案artifactが無い。観測したfindingそのものを出所として縛る。
339
+ //
340
+ // **記録済みfindingのdigestがあるなら、それを使う。** 内容から再導出したdigestで縛ると、
341
+ // 「この変換はあのfindingへの答えだ」という記録が、storeに実在しないidを指す。実際、
342
+ // 再計画側は`findings/<digest>.json`を読むので、再導出値では必ず読めない。
343
+ findingDigest: recordedFindingDigest ?? digestArtifact({
344
+ kind: finding.kind, path: finding.path, todo_ids: taskIds,
345
+ }),
346
+ candidateId: `seam-runtime-${sha16(`${finding.path}\0${taskIds.join(',')}`)}`,
347
+ },
348
+ reasons: [],
349
+ };
350
+ }
351
+
352
+ /**
353
+ * 正規化した競合入力から変換を適用し、五条件で採否を返す。
354
+ *
355
+ * @returns {Promise<{outcome: object, files: object|null}>} `lattice.seam_apply_outcome.v1`
356
+ */
357
+ export async function applySeamConflict({
358
+ repoRoot, planKey, conflict, witnessSet, latticeBin, sharedPathFor,
359
+ executors, compileIndependence, pathNames = {}, precedences = [],
360
+ } = {}) {
361
+ const {
362
+ sourcePath, taskIds, ownedSymbolsByTask, proposedPathByTask, affectedTests,
363
+ baseSha, manifestDigest, findingDigest, candidateId,
364
+ } = conflict;
365
+ const decision = { task_ids: taskIds };
366
+
367
+ const derived = await deriveWithClosure({
368
+ cwd: repoRoot,
369
+ deriveOnce: {
370
+ seeds: [...new Set(Object.values(ownedSymbolsByTask).flat())],
371
+ derive: (calleesBySymbol) => deriveBoundedSeamCandidate({
372
+ sourcePath,
373
+ taskRefs: taskIds.map((taskId) => ({ plan_key: planKey, task_id: taskId })),
374
+ ownedSymbolsByTask,
375
+ proposedPathByTask,
376
+ sharedPath: pathNames.shared ?? sharedPathFor(sourcePath),
377
+ calleesBySymbol,
378
+ affectedTests,
379
+ baseSha,
380
+ manifestDigest,
381
+ findingDigest,
382
+ candidateId,
383
+ }),
384
+ },
385
+ });
386
+ if (derived.candidate === null) {
387
+ return { outcome: outcome({ planKey, decision: 'rejected', reasons: derived.reasons }), files: null };
388
+ }
389
+ const candidate = derived.candidate;
390
+
391
+ const { readFile } = await import('node:fs/promises');
392
+ const beforeText = await readFile(path.join(repoRoot, sourcePath), 'utf8');
393
+ const lookup = await readSymbolExtents({
394
+ cwd: repoRoot, sourcePath,
395
+ symbols: candidate.surfaces.flatMap(({ symbols }) => symbols),
396
+ });
397
+ if (lookup.truncated.length > 0) {
398
+ // 打ち切りは「範囲が無い」ではない。誤った理由で棄却して原因を隠さない。
399
+ return {
400
+ outcome: outcome({ planKey, decision: 'rejected', candidate,
401
+ reasons: lookup.truncated.map((symbol) => `symbol_lookup_truncated:${symbol}`) }),
402
+ files: null,
403
+ };
404
+ }
405
+ const rewritten = planSeamRewrite({
406
+ sourceText: beforeText, candidate, symbolExtents: lookup.extents,
407
+ importSurface: readImportSurface({ cwd: repoRoot, sourcePath }),
408
+ });
409
+ if (rewritten.files === null) {
410
+ return { outcome: outcome({ planKey, decision: 'rejected', reasons: rewritten.reasons, candidate }), files: null };
411
+ }
412
+
413
+ const { mkdtemp, rm } = await import('node:fs/promises');
414
+ const { tmpdir } = await import('node:os');
415
+ const scratchLattice = await mkdtemp(path.join(tmpdir(), 'lattice-seam-scratch-'));
416
+ const beforePairs = conflictPairsOf(compileIndependence.baseArtifact);
417
+ const targetPair = [...decision.task_ids].sort(compareText).join('\0');
418
+ let observation = null;
419
+ let verifierFailure = null;
420
+ try {
421
+ await runIsolatedTransform({
422
+ repoRoot,
423
+ baseRef: candidate.base_sha,
424
+ allowedPaths: candidate.allowed_paths,
425
+ transform: async ({ worktreePath }) => {
426
+ for (const [target, text] of Object.entries(rewritten.files)) {
427
+ await mkdir(path.dirname(path.join(worktreePath, target)), { recursive: true });
428
+ await writeFile(path.join(worktreePath, target), text);
429
+ }
430
+ },
431
+ // 依存が無いとfocused testはERR_MODULE_NOT_FOUNDで落ち、変換の欠陥と環境の欠陥が
432
+ // 同じfailに見える。runnerが張るので、呼び出し側が任意の変更を隠す口にはならない。
433
+ //
434
+
435
+ mounts: [
436
+ { entry: 'node_modules', target: path.join(repoRoot, 'node_modules') },
437
+ // 索引の書き先を使い捨てへ向ける。verifierも再indexもここへ書くので、本repoの
438
+ // 索引を触らせない。src/testへはrunnerがmountを拒否する。
439
+ { entry: '.lattice/sensor', target: scratchLattice },
440
+ // build成果物はgitignoreされているので、どのcommitのworktreeにも存在しない。
441
+ // 張らないと、同梱sensorを起動するfocused testがすべてENOENTで落ち、
442
+ // focused_tests_passedが原理的に満たせなくなる(実測でこれに当たった)。
443
+ // 存在する時だけ張る——Latticeを依存として使うprojectはnode_modules側に持つ。
444
+ ...await buildOutputMounts(repoRoot),
445
+ ],
446
+ // 書き先を隠すのでなく、書かせない。verifierが常駐面を起こすとworktreeへ索引が
447
+ // 生まれ、変更を残さない規律に当たる。
448
+ verifierEnv: { LATTICE_DASHBOARD_AUTOSTART: '0' },
449
+ verifyCommands: candidate.verification_policy.focused_test_refs
450
+ .map((ref) => ({ command: process.execPath, args: ['--test', ref] })),
451
+ observe: async ({ worktreePath }) => {
452
+ const owned = candidate.surfaces
453
+ .filter(({ role }) => role === 'task_owned').map(({ path: target }) => target);
454
+ const sensor = await observeFreshSensor({ worktreePath, latticeBin, paths: owned });
455
+ observation = { sensor, afterText: null, afterArtifact: null, severed: null };
456
+ observation.afterText = await readFile(path.join(worktreePath, sourcePath), 'utf8');
457
+ if (!sensor.fresh) return;
458
+ // 網は受入の一点だけ(ADR 0145)。fresh indexの上でしか意味を持たないので、
459
+ // sensorが新pathを見ていない時は数えず、observation欠落として別理由で落とす。
460
+ observation.severed = await detectSeveredReferences({
461
+ worktreePath, files: rewritten.files, residualPath: sourcePath,
462
+ });
463
+ const post = buildPostTransformWitnessSet({
464
+ witnessSet, candidate, affectedTestsByPath: sensor.affectedByPath,
465
+ });
466
+ if (post.witnessSet === null) {
467
+ observation.reasons = post.reasons;
468
+ return;
469
+ }
470
+ observation.afterArtifact = await compileIndependence.inWorktree({
471
+ worktreePath, witnessSet: post.witnessSet,
472
+ });
473
+ },
474
+ });
475
+ } catch (error) {
476
+ verifierFailure = String(error?.message ?? error);
477
+ } finally {
478
+ await rm(scratchLattice, { recursive: true, force: true });
479
+ }
480
+
481
+ const afterPairs = observation?.afterArtifact === null || observation?.afterArtifact === undefined
482
+ ? null : conflictPairsOf(observation.afterArtifact);
483
+ const orderedTaskIds = [...taskIds].sort(compareText);
484
+ const verification = evaluateSeamVerification({
485
+ exportSurface: observation?.afterText === null || observation?.afterText === undefined
486
+ ? { preserved: false, missing: [] }
487
+ : compareExportSurface({ before: beforeText, after: observation.afterText }),
488
+ severed: observation?.severed ?? null,
489
+ focusedTestsPassed: verifierFailure === null,
490
+ sensorFresh: observation?.sensor?.fresh === true,
491
+ conflictPairs: afterPairs === null ? { targetResolved: false }
492
+ : { targetResolved: !afterPairs.has(targetPair), before: beforePairs.size, after: afterPairs.size },
493
+ waves: {
494
+ before: measureWaveCount({
495
+ taskIds, conflictPairs: [...beforePairs].map((key) => key.split('\0')), precedences, executors,
496
+ }).waves,
497
+ after: afterPairs === null ? null : measureWaveCount({
498
+ taskIds, conflictPairs: [...afterPairs].map((key) => key.split('\0')), precedences, executors,
499
+ }).waves,
500
+ },
501
+ });
502
+
503
+ return { files: rewritten.files, outcome: outcome({
504
+ planKey,
505
+ decision: verification.decision,
506
+ reasons: [
507
+ ...verification.failures,
508
+ ...(verifierFailure === null ? [] : [`verifier:${verifierFailure}`]),
509
+ // 判定が落ちた理由を、条件名だけで終わらせない(ADR 0130)。
510
+ ...(observation?.sensor?.detail ? [`sensor_detail:${observation.sensor.detail}`] : []),
511
+ ...(observation?.reasons ?? []).map((reason) => `witness:${reason}`),
512
+ ],
513
+ candidate,
514
+ conditions: verification.conditions,
515
+ closureRounds: derived.rounds ?? null,
516
+ }) };
517
+ }
518
+
519
+ function outcome({ planKey, decision, reasons, candidate = null, conditions = null, closureRounds = null }) {
520
+ const result = {
521
+ schema: 'lattice.seam_apply_outcome.v1',
522
+ plan_key: planKey,
523
+ decision,
524
+ candidate_id: candidate?.candidate_id ?? null,
525
+ candidate_digest: candidate?.candidate_digest ?? null,
526
+ surfaces: (candidate?.surfaces ?? []).map(({ role, path: target, owner_task_ids: owners }) => ({
527
+ role, path: target, owner_task_ids: [...owners],
528
+ })),
529
+ conditions,
530
+ closure_rounds: closureRounds,
531
+ reasons: [...new Set(reasons)].sort(compareText),
532
+ result_digest: '',
533
+ };
534
+ result.result_digest = todoSelfDigest(result, 'result_digest');
535
+ return result;
536
+ }
537
+
538
+ /**
539
+ * 記録済みseam提案を適用して採否を返す。入力の正規化だけを行い、芯は`applySeamConflict`が持つ。
540
+ */
541
+ export async function applySeamProposal({ sourceProposal, witnessSet, pathNames = {}, ...rest } = {}) {
542
+ const { conflict, reasons } = seamConflictFromProposal({
543
+ proposal: sourceProposal, witnessSet, pathNames,
544
+ });
545
+ if (conflict === null) {
546
+ return { outcome: outcome({ planKey: rest.planKey, decision: 'rejected', reasons }), files: null };
547
+ }
548
+ return applySeamConflict({ ...rest, conflict, witnessSet, pathNames });
549
+ }