@quolu/lattice 0.52.0 → 0.52.2

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