@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
package/src/seam-cost.mjs CHANGED
@@ -1,322 +1,322 @@
1
- /**
2
- * seam 切断コストの内訳(`lattice.seam_cost_profile.v1`、docs/plan_seam-cost.md)。
3
- *
4
- * 係争 file を task ごとに分割する時、**何を共有しているから単純に切れないのか**を
5
- * 数えられる事実として返す。装置は分類して見せるだけで、可否を決めない——「切るのを
6
- * やめろ」とは言わないし、閾値も持たない。「深さ2まで」「件数20超はやめる」を決めるのは
7
- * 方針と操作する AI である(seam-proposal の Pareto 支配と同じ規律)。
8
- *
9
- * これは**投影であって記録ではない**。sensor が進めば変わる値なので、digest 済み artifact へ
10
- * 焼き込まない(ADR 0127 の independence 記録と同じ線)。記録に残らないものは採点にも
11
- * 使えない——「このファイルは N 回競合した」という会計を装置が持たないための構造的裏付け
12
- * でもある(ADR 0145)。
13
- *
14
- * 共有物は複製可能性で重さが分かれる:
15
- *
16
- * | 分類 | 分割後 | 由来 |
17
- * |---|---|---|
18
- * | `shared_imports` | 両面から import すればよい(複製可・安い) | import 文の束縛言及 |
19
- * | `shared_functions` | 共有面へ出せる(装置が機械的に処理できる) | 同一 file 内の calls 辺 |
20
- * | `shared_state` | **複製できない**。所有者を決める設計判断が要る | valueRef 辺 |
21
- * | `cross_edges` | 書き換える参照そのもの | task 間の直接辺 |
22
- * | `same_cycle` | 循環を壊さない限り**切れない** | 同一 file 内 SCC |
23
- */
24
-
25
- import { spawnSync } from 'node:child_process';
26
-
27
- import { invokeSensorCli } from './sensor-runtime.mjs';
28
- import { mentions, scanImportStatements } from './seam-rewrite.mjs';
29
-
30
- const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
31
-
32
- export const SEAM_COST_PROFILE_SCHEMA = 'lattice.seam_cost_profile.v1';
33
-
34
- /** module 状態として数えるノード種別。関数・クラスは複製や共有面行きで解けるので含めない。 */
35
- const STATE_KINDS = new Set(['constant', 'variable']);
36
- const FUNCTION_KINDS = new Set(['function', 'method']);
37
-
38
- function sortedEntries(entries, key) {
39
- return [...entries].sort((left, right) => compareText(key(left), key(right)));
40
- }
41
-
42
- /**
43
- * 同一 file 内の隣接から強連結成分を求める(Tarjan・反復形)。
44
- *
45
- * seam-proposal の実装は正規化 graph の shape に結合しているので、ここでは file 内
46
- * adjacency(symbol 名 → symbol 名)の小さな入力に対して独立に持つ。
47
- */
48
- export function fileCycles(adjacency) {
49
- const names = [...adjacency.keys()].sort(compareText);
50
- const index = new Map();
51
- const low = new Map();
52
- const onStack = new Set();
53
- const stack = [];
54
- const cycles = [];
55
- let next = 0;
56
-
57
- for (const root of names) {
58
- if (index.has(root)) continue;
59
- const work = [{ name: root, childIndex: 0 }];
60
- while (work.length > 0) {
61
- const frame = work.at(-1);
62
- const { name } = frame;
63
- if (frame.childIndex === 0) {
64
- index.set(name, next);
65
- low.set(name, next);
66
- next += 1;
67
- stack.push(name);
68
- onStack.add(name);
69
- }
70
- const targets = (adjacency.get(name) ?? []).filter((target) => adjacency.has(target));
71
- if (frame.childIndex < targets.length) {
72
- const target = targets[frame.childIndex];
73
- frame.childIndex += 1;
74
- if (!index.has(target)) {
75
- work.push({ name: target, childIndex: 0 });
76
- } else if (onStack.has(target)) {
77
- low.set(name, Math.min(low.get(name), index.get(target)));
78
- }
79
- continue;
80
- }
81
- work.pop();
82
- const parent = work.at(-1);
83
- if (parent !== undefined) {
84
- low.set(parent.name, Math.min(low.get(parent.name), low.get(name)));
85
- }
86
- if (low.get(name) === index.get(name)) {
87
- const component = [];
88
- let member;
89
- do {
90
- member = stack.pop();
91
- onStack.delete(member);
92
- component.push(member);
93
- } while (member !== name);
94
- // 自己再帰だけの1要素成分は「循環で切れない」とは別の話なので、2要素以上だけを返す。
95
- if (component.length > 1) cycles.push(component.sort(compareText));
96
- }
97
- }
98
- }
99
- return cycles.sort((left, right) => compareText(left.join(','), right.join(',')));
100
- }
101
-
102
- /**
103
- * 内訳の計算本体(純関数)。観測の取得と分類を分けるので、分類はここで単体検証できる。
104
- *
105
- * @param {object} options
106
- * @param {string} options.sourcePath 係争 file
107
- * @param {string} options.sourceText 係争 file の現在の内容
108
- * @param {Array<{name: string, kind: string, startLine: number, endLine: number, isExported: boolean}>} options.nodes
109
- * 係争 file の symbol 一覧(`file-nodes`)
110
- * @param {Record<string, Array<{name: string, path: string, edgeKind: string, valueRef: boolean, truncated?: boolean}>>} options.calleesBySymbol
111
- * symbol ごとの隣接(callees、辺種別つき)。**係争 file 内の相手だけ**が渡される前提
112
- * @param {Record<string, string[]>} options.ownedSymbolsByTask task ごとの宣言 symbol
113
- * @param {string[]} [options.truncatedSymbols] callees が limit に達した symbol(観測の打ち切り申告)
114
- */
115
- export function classifySeamCost({
116
- sourcePath, sourceText, nodes, calleesBySymbol, ownedSymbolsByTask, truncatedSymbols = [],
117
- } = {}) {
118
- const taskIds = Object.keys(ownedSymbolsByTask).sort(compareText);
119
- const ownerOf = new Map();
120
- for (const taskId of taskIds) {
121
- for (const symbol of ownedSymbolsByTask[taskId]) ownerOf.set(symbol, taskId);
122
- }
123
- const nodeByName = new Map(nodes.map((node) => [node.name, node]));
124
- const lines = sourceText.split('\n');
125
-
126
- // task ごとの本文。extent の行範囲で切る。宣言に extent が無い symbol は本文不明として
127
- // 言及判定から外れる——「無い」へ丸めず observed で申告する。
128
- const bodyOf = new Map();
129
- const bodyMissing = [];
130
- for (const taskId of taskIds) {
131
- const parts = [];
132
- for (const symbol of ownedSymbolsByTask[taskId]) {
133
- const node = nodeByName.get(symbol);
134
- if (node === undefined) { bodyMissing.push(symbol); continue; }
135
- parts.push(lines.slice(node.startLine - 1, node.endLine).join('\n'));
136
- }
137
- bodyOf.set(taskId, parts.join('\n'));
138
- }
139
-
140
- // 1) task 間の直接辺。書き換える参照そのものであり、切断コストのほぼ定義。
141
- const crossEdges = [];
142
- for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
143
- const fromTask = ownerOf.get(symbol);
144
- if (fromTask === undefined) continue;
145
- for (const callee of callees) {
146
- const toTask = ownerOf.get(callee.name);
147
- if (toTask === undefined || toTask === fromTask) continue;
148
- crossEdges.push({
149
- from_task: fromTask, from: symbol, to_task: toTask, to: callee.name,
150
- edge_kind: callee.edgeKind, value_ref: callee.valueRef === true,
151
- value_write: callee.valueWrite === true,
152
- });
153
- }
154
- }
155
-
156
- // 2) 同一 file 内の循環。両 task を跨ぐ成分は、循環を壊さない限り切れない。
157
- const adjacency = new Map();
158
- for (const node of nodes) adjacency.set(node.name, []);
159
- for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
160
- if (!adjacency.has(symbol)) adjacency.set(symbol, []);
161
- for (const callee of callees) {
162
- if (adjacency.has(callee.name)) adjacency.get(symbol).push(callee.name);
163
- }
164
- }
165
- const sameCycle = fileCycles(adjacency)
166
- .map((component) => ({
167
- symbols: component,
168
- task_ids: [...new Set(component.map((name) => ownerOf.get(name)).filter(Boolean))].sort(compareText),
169
- }))
170
- .filter(({ task_ids: ids }) => ids.length >= 2);
171
-
172
- // 3) 共有の分類。誰の宣言でもない同一 file 内の隣接を、複製可能性で分ける。
173
- const reachedBy = new Map();
174
- for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
175
- const fromTask = ownerOf.get(symbol);
176
- if (fromTask === undefined) continue;
177
- for (const callee of callees) {
178
- if (ownerOf.has(callee.name)) continue;
179
- if (!reachedBy.has(callee.name)) {
180
- reachedBy.set(callee.name, { tasks: new Set(), writers: new Set() });
181
- }
182
- const reach = reachedBy.get(callee.name);
183
- reach.tasks.add(fromTask);
184
- if (callee.valueWrite === true) reach.writers.add(fromTask);
185
- }
186
- }
187
- const sharedState = [];
188
- const sharedFunctions = [];
189
- for (const [name, reach] of reachedBy) {
190
- const kind = nodeByName.get(name)?.kind ?? 'unknown';
191
- const referencedBy = [...reach.tasks].sort(compareText);
192
- if (STATE_KINDS.has(kind)) {
193
- // 共有の重さは読むだけ/片方が書く/両方書くでほぼ決まる。誰が書くかまで数える。
194
- sharedState.push({
195
- name, kind, referenced_by: referencedBy,
196
- written_by: [...reach.writers].sort(compareText),
197
- });
198
- } else if (FUNCTION_KINDS.has(kind)) {
199
- sharedFunctions.push({ name, kind, referenced_by: referencedBy });
200
- } else {
201
- // それ以外(class等)は cross/cycle が拾う。分類できない共有を黙って捨てないため、
202
- // state でも function でもない到達は shared_functions 側へ kind つきで載せる。
203
- sharedFunctions.push({ name, kind, referenced_by: referencedBy });
204
- }
205
- }
206
-
207
- // 4) import の共有。複製できるので安い——ESM の import 文束縛への言及で数える。
208
- // 正規表現による ESM 限定の解析であり、他言語では観測不能(confidence で申告)。
209
- const statements = scanImportStatements(lines).statements;
210
- const sharedImports = [];
211
- for (const statement of statements) {
212
- const usedBy = taskIds.filter((taskId) => statement.bindings
213
- .some((binding) => mentions(bodyOf.get(taskId) ?? '', binding)));
214
- if (usedBy.length >= 2) sharedImports.push({ statement: statement.text, used_by: usedBy });
215
- }
216
-
217
- // 5) symbol ごとの数えられる事実。行数と公開面。判断はしない。
218
- const tasks = {};
219
- for (const taskId of taskIds) {
220
- tasks[taskId] = {
221
- symbols: ownedSymbolsByTask[taskId].map((symbol) => {
222
- const node = nodeByName.get(symbol);
223
- return node === undefined
224
- ? { name: symbol, kind: null, lines: null, exported: null }
225
- : {
226
- name: symbol, kind: node.kind,
227
- lines: node.endLine - node.startLine + 1,
228
- exported: node.isExported === true,
229
- };
230
- }),
231
- };
232
- }
233
-
234
- return {
235
- schema: SEAM_COST_PROFILE_SCHEMA,
236
- source_path: sourcePath,
237
- tasks,
238
- cross_edges: sortedEntries(crossEdges, (edge) => `${edge.from}\0${edge.to}`),
239
- same_cycle: sameCycle,
240
- shared_state: sortedEntries(sharedState, ({ name }) => name),
241
- shared_functions: sortedEntries(sharedFunctions, ({ name }) => name),
242
- shared_imports: sharedImports,
243
- confidence: {
244
- // 盲点の申告(計画の不変条件4)。見えていないものを「共有なし」と言わない。
245
- // 3文字未満の名前(i, db等)はloop/parameterのnoiseが支配的なので辺にしない。
246
- value_ref_name_filter: 'names-under-3-chars-invisible-in-edges',
247
- // TS/JS/ArkTS/Go/Python/Javaはwasmとkernelの両経路で同じwrite判定を持つ。
248
- // それ以外のvalue-ref対応言語はmetadata.writeが未配線なので、範囲を明記する。
249
- write_distinction: 'ts-js-arkts-go-python-java-all-routes',
250
- imports_analysis: 'esm-only',
251
- callees_truncated: [...new Set(truncatedSymbols)].sort(compareText),
252
- body_missing: [...new Set(bodyMissing)].sort(compareText),
253
- },
254
- };
255
- }
256
-
257
- const CALLEES_LIMIT = 200;
258
-
259
- /**
260
- * 実 sensor から材料を集めて内訳を返す(投影・read-only)。
261
- *
262
- * `blast_by_depth` は impact を深さ別に引いて差分で数える。深さだけの方針は粗い——
263
- * 深さ2に3件と300件は別の作業なので、件数まで出す。「深さ2まで、件数 N 超はやめる」を
264
- * 書けるようにするのが目的で、書くのは方針と AI である。
265
- */
266
- export async function computeSeamCostProfile({
267
- repoRoot, sourcePath, sourceText, ownedSymbolsByTask, impactDepths = [1, 2, 3],
268
- } = {}) {
269
- const invoke = (args) => invokeSensorCli(
270
- (command, cliArgs, options) => spawnSync(command, cliArgs, options),
271
- args,
272
- { cwd: repoRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
273
- );
274
-
275
- const fileNodes = invoke(['file-nodes', sourcePath, '--path', '.']);
276
- if (fileNodes.status !== 0) {
277
- return { profile: null, reasons: ['file_nodes_unavailable'] };
278
- }
279
- let nodes;
280
- try { nodes = JSON.parse(fileNodes.stdout)?.nodes ?? null; } catch { nodes = null; }
281
- if (nodes === null) return { profile: null, reasons: ['file_nodes_unreadable'] };
282
-
283
- const allOwned = [...new Set(Object.values(ownedSymbolsByTask).flat())].sort(compareText);
284
- const calleesBySymbol = {};
285
- const truncatedSymbols = [];
286
- for (const symbol of allOwned) {
287
- const result = invoke(['callees', symbol, '--path', '.', '--limit', String(CALLEES_LIMIT), '--json']);
288
- if (result.status !== 0) { calleesBySymbol[symbol] = []; continue; }
289
- let callees;
290
- try { callees = JSON.parse(result.stdout)?.callees ?? []; } catch { callees = []; }
291
- if (callees.length >= CALLEES_LIMIT) truncatedSymbols.push(symbol);
292
- calleesBySymbol[symbol] = callees
293
- .filter((callee) => callee.filePath === sourcePath)
294
- .map((callee) => ({
295
- name: callee.name, path: callee.filePath,
296
- edgeKind: callee.edgeKind ?? 'calls', valueRef: callee.valueRef === true,
297
- valueWrite: callee.valueWrite === true,
298
- }));
299
- }
300
-
301
- const profile = classifySeamCost({
302
- sourcePath, sourceText, nodes, calleesBySymbol, ownedSymbolsByTask, truncatedSymbols,
303
- });
304
-
305
- // 深さごとの影響件数。累積値の差分が「その深さで初めて届く数」になる。
306
- const blast = {};
307
- for (const symbol of allOwned) {
308
- const perDepth = {};
309
- let previous = 0;
310
- for (const depth of [...impactDepths].sort((a, b) => a - b)) {
311
- const result = invoke(['impact', symbol, '--path', '.', '--depth', String(depth), '--json']);
312
- if (result.status !== 0) { perDepth[depth] = null; continue; }
313
- let count = null;
314
- try { count = JSON.parse(result.stdout)?.nodeCount ?? null; } catch { count = null; }
315
- perDepth[depth] = count === null ? null : Math.max(0, count - previous);
316
- if (count !== null) previous = count;
317
- }
318
- blast[symbol] = perDepth;
319
- }
320
- profile.blast_by_depth = blast;
321
- return { profile, reasons: [] };
322
- }
1
+ /**
2
+ * seam 切断コストの内訳(`lattice.seam_cost_profile.v1`、docs/plan_seam-cost.md)。
3
+ *
4
+ * 係争 file を task ごとに分割する時、**何を共有しているから単純に切れないのか**を
5
+ * 数えられる事実として返す。装置は分類して見せるだけで、可否を決めない——「切るのを
6
+ * やめろ」とは言わないし、閾値も持たない。「深さ2まで」「件数20超はやめる」を決めるのは
7
+ * 方針と操作する AI である(seam-proposal の Pareto 支配と同じ規律)。
8
+ *
9
+ * これは**投影であって記録ではない**。sensor が進めば変わる値なので、digest 済み artifact へ
10
+ * 焼き込まない(ADR 0127 の independence 記録と同じ線)。記録に残らないものは採点にも
11
+ * 使えない——「このファイルは N 回競合した」という会計を装置が持たないための構造的裏付け
12
+ * でもある(ADR 0145)。
13
+ *
14
+ * 共有物は複製可能性で重さが分かれる:
15
+ *
16
+ * | 分類 | 分割後 | 由来 |
17
+ * |---|---|---|
18
+ * | `shared_imports` | 両面から import すればよい(複製可・安い) | import 文の束縛言及 |
19
+ * | `shared_functions` | 共有面へ出せる(装置が機械的に処理できる) | 同一 file 内の calls 辺 |
20
+ * | `shared_state` | **複製できない**。所有者を決める設計判断が要る | valueRef 辺 |
21
+ * | `cross_edges` | 書き換える参照そのもの | task 間の直接辺 |
22
+ * | `same_cycle` | 循環を壊さない限り**切れない** | 同一 file 内 SCC |
23
+ */
24
+
25
+ import { spawnSync } from 'node:child_process';
26
+
27
+ import { invokeSensorCli } from './sensor-runtime.mjs';
28
+ import { mentions, scanImportStatements } from './seam-rewrite.mjs';
29
+
30
+ const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
31
+
32
+ export const SEAM_COST_PROFILE_SCHEMA = 'lattice.seam_cost_profile.v1';
33
+
34
+ /** module 状態として数えるノード種別。関数・クラスは複製や共有面行きで解けるので含めない。 */
35
+ const STATE_KINDS = new Set(['constant', 'variable']);
36
+ const FUNCTION_KINDS = new Set(['function', 'method']);
37
+
38
+ function sortedEntries(entries, key) {
39
+ return [...entries].sort((left, right) => compareText(key(left), key(right)));
40
+ }
41
+
42
+ /**
43
+ * 同一 file 内の隣接から強連結成分を求める(Tarjan・反復形)。
44
+ *
45
+ * seam-proposal の実装は正規化 graph の shape に結合しているので、ここでは file 内
46
+ * adjacency(symbol 名 → symbol 名)の小さな入力に対して独立に持つ。
47
+ */
48
+ export function fileCycles(adjacency) {
49
+ const names = [...adjacency.keys()].sort(compareText);
50
+ const index = new Map();
51
+ const low = new Map();
52
+ const onStack = new Set();
53
+ const stack = [];
54
+ const cycles = [];
55
+ let next = 0;
56
+
57
+ for (const root of names) {
58
+ if (index.has(root)) continue;
59
+ const work = [{ name: root, childIndex: 0 }];
60
+ while (work.length > 0) {
61
+ const frame = work.at(-1);
62
+ const { name } = frame;
63
+ if (frame.childIndex === 0) {
64
+ index.set(name, next);
65
+ low.set(name, next);
66
+ next += 1;
67
+ stack.push(name);
68
+ onStack.add(name);
69
+ }
70
+ const targets = (adjacency.get(name) ?? []).filter((target) => adjacency.has(target));
71
+ if (frame.childIndex < targets.length) {
72
+ const target = targets[frame.childIndex];
73
+ frame.childIndex += 1;
74
+ if (!index.has(target)) {
75
+ work.push({ name: target, childIndex: 0 });
76
+ } else if (onStack.has(target)) {
77
+ low.set(name, Math.min(low.get(name), index.get(target)));
78
+ }
79
+ continue;
80
+ }
81
+ work.pop();
82
+ const parent = work.at(-1);
83
+ if (parent !== undefined) {
84
+ low.set(parent.name, Math.min(low.get(parent.name), low.get(name)));
85
+ }
86
+ if (low.get(name) === index.get(name)) {
87
+ const component = [];
88
+ let member;
89
+ do {
90
+ member = stack.pop();
91
+ onStack.delete(member);
92
+ component.push(member);
93
+ } while (member !== name);
94
+ // 自己再帰だけの1要素成分は「循環で切れない」とは別の話なので、2要素以上だけを返す。
95
+ if (component.length > 1) cycles.push(component.sort(compareText));
96
+ }
97
+ }
98
+ }
99
+ return cycles.sort((left, right) => compareText(left.join(','), right.join(',')));
100
+ }
101
+
102
+ /**
103
+ * 内訳の計算本体(純関数)。観測の取得と分類を分けるので、分類はここで単体検証できる。
104
+ *
105
+ * @param {object} options
106
+ * @param {string} options.sourcePath 係争 file
107
+ * @param {string} options.sourceText 係争 file の現在の内容
108
+ * @param {Array<{name: string, kind: string, startLine: number, endLine: number, isExported: boolean}>} options.nodes
109
+ * 係争 file の symbol 一覧(`file-nodes`)
110
+ * @param {Record<string, Array<{name: string, path: string, edgeKind: string, valueRef: boolean, truncated?: boolean}>>} options.calleesBySymbol
111
+ * symbol ごとの隣接(callees、辺種別つき)。**係争 file 内の相手だけ**が渡される前提
112
+ * @param {Record<string, string[]>} options.ownedSymbolsByTask task ごとの宣言 symbol
113
+ * @param {string[]} [options.truncatedSymbols] callees が limit に達した symbol(観測の打ち切り申告)
114
+ */
115
+ export function classifySeamCost({
116
+ sourcePath, sourceText, nodes, calleesBySymbol, ownedSymbolsByTask, truncatedSymbols = [],
117
+ } = {}) {
118
+ const taskIds = Object.keys(ownedSymbolsByTask).sort(compareText);
119
+ const ownerOf = new Map();
120
+ for (const taskId of taskIds) {
121
+ for (const symbol of ownedSymbolsByTask[taskId]) ownerOf.set(symbol, taskId);
122
+ }
123
+ const nodeByName = new Map(nodes.map((node) => [node.name, node]));
124
+ const lines = sourceText.split('\n');
125
+
126
+ // task ごとの本文。extent の行範囲で切る。宣言に extent が無い symbol は本文不明として
127
+ // 言及判定から外れる——「無い」へ丸めず observed で申告する。
128
+ const bodyOf = new Map();
129
+ const bodyMissing = [];
130
+ for (const taskId of taskIds) {
131
+ const parts = [];
132
+ for (const symbol of ownedSymbolsByTask[taskId]) {
133
+ const node = nodeByName.get(symbol);
134
+ if (node === undefined) { bodyMissing.push(symbol); continue; }
135
+ parts.push(lines.slice(node.startLine - 1, node.endLine).join('\n'));
136
+ }
137
+ bodyOf.set(taskId, parts.join('\n'));
138
+ }
139
+
140
+ // 1) task 間の直接辺。書き換える参照そのものであり、切断コストのほぼ定義。
141
+ const crossEdges = [];
142
+ for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
143
+ const fromTask = ownerOf.get(symbol);
144
+ if (fromTask === undefined) continue;
145
+ for (const callee of callees) {
146
+ const toTask = ownerOf.get(callee.name);
147
+ if (toTask === undefined || toTask === fromTask) continue;
148
+ crossEdges.push({
149
+ from_task: fromTask, from: symbol, to_task: toTask, to: callee.name,
150
+ edge_kind: callee.edgeKind, value_ref: callee.valueRef === true,
151
+ value_write: callee.valueWrite === true,
152
+ });
153
+ }
154
+ }
155
+
156
+ // 2) 同一 file 内の循環。両 task を跨ぐ成分は、循環を壊さない限り切れない。
157
+ const adjacency = new Map();
158
+ for (const node of nodes) adjacency.set(node.name, []);
159
+ for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
160
+ if (!adjacency.has(symbol)) adjacency.set(symbol, []);
161
+ for (const callee of callees) {
162
+ if (adjacency.has(callee.name)) adjacency.get(symbol).push(callee.name);
163
+ }
164
+ }
165
+ const sameCycle = fileCycles(adjacency)
166
+ .map((component) => ({
167
+ symbols: component,
168
+ task_ids: [...new Set(component.map((name) => ownerOf.get(name)).filter(Boolean))].sort(compareText),
169
+ }))
170
+ .filter(({ task_ids: ids }) => ids.length >= 2);
171
+
172
+ // 3) 共有の分類。誰の宣言でもない同一 file 内の隣接を、複製可能性で分ける。
173
+ const reachedBy = new Map();
174
+ for (const [symbol, callees] of Object.entries(calleesBySymbol)) {
175
+ const fromTask = ownerOf.get(symbol);
176
+ if (fromTask === undefined) continue;
177
+ for (const callee of callees) {
178
+ if (ownerOf.has(callee.name)) continue;
179
+ if (!reachedBy.has(callee.name)) {
180
+ reachedBy.set(callee.name, { tasks: new Set(), writers: new Set() });
181
+ }
182
+ const reach = reachedBy.get(callee.name);
183
+ reach.tasks.add(fromTask);
184
+ if (callee.valueWrite === true) reach.writers.add(fromTask);
185
+ }
186
+ }
187
+ const sharedState = [];
188
+ const sharedFunctions = [];
189
+ for (const [name, reach] of reachedBy) {
190
+ const kind = nodeByName.get(name)?.kind ?? 'unknown';
191
+ const referencedBy = [...reach.tasks].sort(compareText);
192
+ if (STATE_KINDS.has(kind)) {
193
+ // 共有の重さは読むだけ/片方が書く/両方書くでほぼ決まる。誰が書くかまで数える。
194
+ sharedState.push({
195
+ name, kind, referenced_by: referencedBy,
196
+ written_by: [...reach.writers].sort(compareText),
197
+ });
198
+ } else if (FUNCTION_KINDS.has(kind)) {
199
+ sharedFunctions.push({ name, kind, referenced_by: referencedBy });
200
+ } else {
201
+ // それ以外(class等)は cross/cycle が拾う。分類できない共有を黙って捨てないため、
202
+ // state でも function でもない到達は shared_functions 側へ kind つきで載せる。
203
+ sharedFunctions.push({ name, kind, referenced_by: referencedBy });
204
+ }
205
+ }
206
+
207
+ // 4) import の共有。複製できるので安い——ESM の import 文束縛への言及で数える。
208
+ // 正規表現による ESM 限定の解析であり、他言語では観測不能(confidence で申告)。
209
+ const statements = scanImportStatements(lines).statements;
210
+ const sharedImports = [];
211
+ for (const statement of statements) {
212
+ const usedBy = taskIds.filter((taskId) => statement.bindings
213
+ .some((binding) => mentions(bodyOf.get(taskId) ?? '', binding)));
214
+ if (usedBy.length >= 2) sharedImports.push({ statement: statement.text, used_by: usedBy });
215
+ }
216
+
217
+ // 5) symbol ごとの数えられる事実。行数と公開面。判断はしない。
218
+ const tasks = {};
219
+ for (const taskId of taskIds) {
220
+ tasks[taskId] = {
221
+ symbols: ownedSymbolsByTask[taskId].map((symbol) => {
222
+ const node = nodeByName.get(symbol);
223
+ return node === undefined
224
+ ? { name: symbol, kind: null, lines: null, exported: null }
225
+ : {
226
+ name: symbol, kind: node.kind,
227
+ lines: node.endLine - node.startLine + 1,
228
+ exported: node.isExported === true,
229
+ };
230
+ }),
231
+ };
232
+ }
233
+
234
+ return {
235
+ schema: SEAM_COST_PROFILE_SCHEMA,
236
+ source_path: sourcePath,
237
+ tasks,
238
+ cross_edges: sortedEntries(crossEdges, (edge) => `${edge.from}\0${edge.to}`),
239
+ same_cycle: sameCycle,
240
+ shared_state: sortedEntries(sharedState, ({ name }) => name),
241
+ shared_functions: sortedEntries(sharedFunctions, ({ name }) => name),
242
+ shared_imports: sharedImports,
243
+ confidence: {
244
+ // 盲点の申告(計画の不変条件4)。見えていないものを「共有なし」と言わない。
245
+ // 3文字未満の名前(i, db等)はloop/parameterのnoiseが支配的なので辺にしない。
246
+ value_ref_name_filter: 'names-under-3-chars-invisible-in-edges',
247
+ // TS/JS/ArkTS/Go/Python/Javaはwasmとkernelの両経路で同じwrite判定を持つ。
248
+ // それ以外のvalue-ref対応言語はmetadata.writeが未配線なので、範囲を明記する。
249
+ write_distinction: 'ts-js-arkts-go-python-java-all-routes',
250
+ imports_analysis: 'esm-only',
251
+ callees_truncated: [...new Set(truncatedSymbols)].sort(compareText),
252
+ body_missing: [...new Set(bodyMissing)].sort(compareText),
253
+ },
254
+ };
255
+ }
256
+
257
+ const CALLEES_LIMIT = 200;
258
+
259
+ /**
260
+ * 実 sensor から材料を集めて内訳を返す(投影・read-only)。
261
+ *
262
+ * `blast_by_depth` は impact を深さ別に引いて差分で数える。深さだけの方針は粗い——
263
+ * 深さ2に3件と300件は別の作業なので、件数まで出す。「深さ2まで、件数 N 超はやめる」を
264
+ * 書けるようにするのが目的で、書くのは方針と AI である。
265
+ */
266
+ export async function computeSeamCostProfile({
267
+ repoRoot, sourcePath, sourceText, ownedSymbolsByTask, impactDepths = [1, 2, 3],
268
+ } = {}) {
269
+ const invoke = (args) => invokeSensorCli(
270
+ (command, cliArgs, options) => spawnSync(command, cliArgs, options),
271
+ args,
272
+ { cwd: repoRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
273
+ );
274
+
275
+ const fileNodes = invoke(['file-nodes', sourcePath, '--path', '.']);
276
+ if (fileNodes.status !== 0) {
277
+ return { profile: null, reasons: ['file_nodes_unavailable'] };
278
+ }
279
+ let nodes;
280
+ try { nodes = JSON.parse(fileNodes.stdout)?.nodes ?? null; } catch { nodes = null; }
281
+ if (nodes === null) return { profile: null, reasons: ['file_nodes_unreadable'] };
282
+
283
+ const allOwned = [...new Set(Object.values(ownedSymbolsByTask).flat())].sort(compareText);
284
+ const calleesBySymbol = {};
285
+ const truncatedSymbols = [];
286
+ for (const symbol of allOwned) {
287
+ const result = invoke(['callees', symbol, '--path', '.', '--limit', String(CALLEES_LIMIT), '--json']);
288
+ if (result.status !== 0) { calleesBySymbol[symbol] = []; continue; }
289
+ let callees;
290
+ try { callees = JSON.parse(result.stdout)?.callees ?? []; } catch { callees = []; }
291
+ if (callees.length >= CALLEES_LIMIT) truncatedSymbols.push(symbol);
292
+ calleesBySymbol[symbol] = callees
293
+ .filter((callee) => callee.filePath === sourcePath)
294
+ .map((callee) => ({
295
+ name: callee.name, path: callee.filePath,
296
+ edgeKind: callee.edgeKind ?? 'calls', valueRef: callee.valueRef === true,
297
+ valueWrite: callee.valueWrite === true,
298
+ }));
299
+ }
300
+
301
+ const profile = classifySeamCost({
302
+ sourcePath, sourceText, nodes, calleesBySymbol, ownedSymbolsByTask, truncatedSymbols,
303
+ });
304
+
305
+ // 深さごとの影響件数。累積値の差分が「その深さで初めて届く数」になる。
306
+ const blast = {};
307
+ for (const symbol of allOwned) {
308
+ const perDepth = {};
309
+ let previous = 0;
310
+ for (const depth of [...impactDepths].sort((a, b) => a - b)) {
311
+ const result = invoke(['impact', symbol, '--path', '.', '--depth', String(depth), '--json']);
312
+ if (result.status !== 0) { perDepth[depth] = null; continue; }
313
+ let count = null;
314
+ try { count = JSON.parse(result.stdout)?.nodeCount ?? null; } catch { count = null; }
315
+ perDepth[depth] = count === null ? null : Math.max(0, count - previous);
316
+ if (count !== null) previous = count;
317
+ }
318
+ blast[symbol] = perDepth;
319
+ }
320
+ profile.blast_by_depth = blast;
321
+ return { profile, reasons: [] };
322
+ }