@quolu/lattice 0.52.3 → 0.53.0

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