@quolu/lattice 0.32.0 → 0.34.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 (64) hide show
  1. package/README.ja.md +11 -1
  2. package/README.md +11 -2
  3. package/bin/lattice.mjs +12 -1
  4. package/package.json +1 -1
  5. package/sensor/dist/bin/lattice-sensor.js +72 -4
  6. package/sensor/dist/db/migrations.d.ts +1 -1
  7. package/sensor/dist/db/migrations.d.ts.map +1 -1
  8. package/sensor/dist/db/migrations.js +42 -2
  9. package/sensor/dist/db/migrations.js.map +1 -1
  10. package/sensor/dist/db/queries.d.ts +18 -0
  11. package/sensor/dist/db/queries.d.ts.map +1 -1
  12. package/sensor/dist/db/queries.js +76 -9
  13. package/sensor/dist/db/queries.js.map +1 -1
  14. package/sensor/dist/db/schema.sql +10 -1
  15. package/sensor/dist/extraction/extraction-version.d.ts +1 -1
  16. package/sensor/dist/extraction/extraction-version.d.ts.map +1 -1
  17. package/sensor/dist/extraction/extraction-version.js +5 -1
  18. package/sensor/dist/extraction/extraction-version.js.map +1 -1
  19. package/sensor/dist/extraction/index.d.ts +2 -0
  20. package/sensor/dist/extraction/index.d.ts.map +1 -1
  21. package/sensor/dist/extraction/index.js +38 -3
  22. package/sensor/dist/extraction/index.js.map +1 -1
  23. package/sensor/dist/extraction/tree-sitter.d.ts.map +1 -1
  24. package/sensor/dist/extraction/tree-sitter.js +89 -16
  25. package/sensor/dist/extraction/tree-sitter.js.map +1 -1
  26. package/sensor/dist/index.d.ts +8 -1
  27. package/sensor/dist/index.d.ts.map +1 -1
  28. package/sensor/dist/index.js +9 -0
  29. package/sensor/dist/index.js.map +1 -1
  30. package/sensor/dist/resolution/import-resolver.d.ts +11 -0
  31. package/sensor/dist/resolution/import-resolver.d.ts.map +1 -1
  32. package/sensor/dist/resolution/import-resolver.js +13 -5
  33. package/sensor/dist/resolution/import-resolver.js.map +1 -1
  34. package/sensor/dist/resolution/index.d.ts.map +1 -1
  35. package/sensor/dist/resolution/index.js +11 -0
  36. package/sensor/dist/resolution/index.js.map +1 -1
  37. package/sensor/dist/resolution/types.d.ts +4 -0
  38. package/sensor/dist/resolution/types.d.ts.map +1 -1
  39. package/sensor/dist/types.d.ts +22 -0
  40. package/sensor/dist/types.d.ts.map +1 -1
  41. package/src/artifact-contracts.mjs +3 -0
  42. package/src/cli-help.mjs +6 -0
  43. package/src/rc3-scripted-campaign.mjs +3 -1
  44. package/src/runtime-cli.mjs +280 -36
  45. package/src/runtime-contracts.mjs +1 -1
  46. package/src/runtime-control-store.mjs +24 -1
  47. package/src/runtime-decision-verifier.mjs +1 -1
  48. package/src/runtime-diff-observer.mjs +2 -2
  49. package/src/runtime-front-end.mjs +47 -13
  50. package/src/runtime-hold-recompile.mjs +31 -2
  51. package/src/runtime-io-sentinel.mjs +16 -9
  52. package/src/runtime-managed-supervisor.mjs +32 -3
  53. package/src/runtime-multi-epoch-store.mjs +2 -2
  54. package/src/runtime-projection.mjs +27 -0
  55. package/src/runtime-scripted-adapter-controller.mjs +22 -1
  56. package/src/runtime-seam-resolve.mjs +156 -13
  57. package/src/runtime-seam-treatment.mjs +2 -1
  58. package/src/seam-apply.mjs +101 -4
  59. package/src/seam-cost.mjs +322 -0
  60. package/src/seam-gate.mjs +146 -0
  61. package/src/seam-rewrite.mjs +102 -16
  62. package/src/seam-verification.mjs +26 -3
  63. package/src/sensor-adapter.mjs +6 -1
  64. package/src/todo-cli.mjs +55 -0
@@ -14,7 +14,7 @@ import { runIsolatedTransform } from './isolation-runner.mjs';
14
14
  import { collectSensorEvidence } from './sensor-adapter.mjs';
15
15
  import { invokeSensorCli } from './sensor-runtime.mjs';
16
16
  import { buildSeamDerivationQuerySet, deriveBoundedSeamCandidate } from './seam-derivation.mjs';
17
- import { planSeamRewrite } from './seam-rewrite.mjs';
17
+ import { joinImportSurface, mentions, planSeamRewrite } from './seam-rewrite.mjs';
18
18
  import {
19
19
  buildPostTransformWitnessSet, compareExportSurface, evaluateSeamVerification, measureWaveCount,
20
20
  } from './seam-verification.mjs';
@@ -112,13 +112,38 @@ export async function readSymbolExtents({ cwd, sourcePath, symbols }) {
112
112
  const node = nodeOf(entry);
113
113
  if (node === null || node.name !== symbol || node.filePath !== sourcePath) continue;
114
114
  if (!Number.isSafeInteger(node.startLine) || !Number.isSafeInteger(node.endLine)) continue;
115
- extents[symbol] = { startLine: node.startLine, endLine: node.endLine };
115
+ // 装飾込みの開始行(sensor v11)を優先する。Pythonの@decoratorやRustの#[derive]
116
+ // 宣言の外の行にあり、宣言行だけで切ると装飾が残余面へ取り残される。
117
+ const start = Number.isSafeInteger(node.extentStartLine) && node.extentStartLine < node.startLine
118
+ ? node.extentStartLine : node.startLine;
119
+ // export状態もAST事実として持ち帰る(sc-013)。書き換え側のtext走査を置き換える。
120
+ extents[symbol] = { startLine: start, endLine: node.endLine, isExported: node.isExported === true };
116
121
  }
117
122
  if (extents[symbol] === undefined && entries.length >= SYMBOL_LOOKUP_LIMIT) truncated.push(symbol);
118
123
  }
119
124
  return { extents, truncated: [...new Set(truncated)].sort(compareText) };
120
125
  }
121
126
 
127
+ /**
128
+ * 対象fileのimport面をsensorの観測から読む(sc-013)。
129
+ *
130
+ * `file-nodes`の`imports`(文の行範囲)と`import_bindings`(AST由来の束縛)を
131
+ * `joinImportSurface`で文単位へ束ねる。観測が取れなければnullを返し、書き換え側が
132
+ * `import_surface_missing`のtyped理由で止める——正規表現の再解析へfallbackしない。
133
+ */
134
+ export function readImportSurface({ cwd, sourcePath }) {
135
+ const result = invokeSensorCli(
136
+ (command, args, options) => spawnSync(command, args, options),
137
+ ['file-nodes', sourcePath, '--path', '.'],
138
+ { cwd, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
139
+ );
140
+ if (result.status !== 0) return null;
141
+ let parsed;
142
+ try { parsed = JSON.parse(result.stdout); } catch { return null; }
143
+ if (!Array.isArray(parsed?.imports) || !Array.isArray(parsed?.import_bindings)) return null;
144
+ return joinImportSurface(parsed.imports, parsed.import_bindings);
145
+ }
146
+
122
147
  async function runIn(worktreePath, command, args) {
123
148
  try {
124
149
  const { stdout } = await execFileAsync(command, args, {
@@ -130,6 +155,66 @@ async function runIn(worktreePath, command, args) {
130
155
  }
131
156
  }
132
157
 
158
+ /**
159
+ * 変換で切断された参照を数える(検証網、ADR 0145)。
160
+ *
161
+ * 移した先のcodeが、残余面に留まったsymbol(module変数・非公開関数)へ束縛なしで言及して
162
+ * いれば、その参照は切断されている——moduleの読み込みは通り、実行して初めてReferenceErrorに
163
+ * なるので、focused testが当該経路を通らなければ黙って壊れたまま採用される。これを受入の
164
+ * 一点で数える。
165
+ *
166
+ * 残余面のsymbol一覧は、変換後worktreeのfresh indexから抽出精度で取る(`file-nodes`)。
167
+ * value-ref辺の名前フィルタはノード生成に効かないので、全小文字のmodule変数もここには載る。
168
+ * `unresolved_refs`は使わない——bare参照の切断はそこに記録されないことを実測で確認した
169
+ * (builtin呼び出しは載るが、未束縛のidentifier読みは載らない)。
170
+ *
171
+ * 検査は保守的である。`mentions`はtext一致なので、文字列やcomment内の同名語も
172
+ * 「切断の疑い」として数える——見逃す方向ではなく誤検出の方向へ倒す(fail closed)。
173
+ * 網は受入の一点だけで、過程には触れない。不認定は拒否ではなく、理由を見て直せば
174
+ * 何度でも再提出できる。
175
+ */
176
+ async function detectSeveredReferences({ worktreePath, files, residualPath }) {
177
+ const readFileNodes = (target) => {
178
+ const result = invokeSensorCli(
179
+ (command, args, options) => spawnSync(command, args, options),
180
+ ['file-nodes', target, '--path', '.'],
181
+ { cwd: worktreePath, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
182
+ );
183
+ if (result.status !== 0) return null;
184
+ let parsed;
185
+ try { parsed = JSON.parse(result.stdout); } catch { return null; }
186
+ if (!Array.isArray(parsed?.nodes)) return null;
187
+ return parsed;
188
+ };
189
+
190
+ const residual = readFileNodes(residualPath);
191
+ if (residual === null) return { observed: false, entries: [] };
192
+ const residualNames = residual.nodes.map(({ name }) => name);
193
+
194
+ const entries = [];
195
+ for (const [target, body] of Object.entries(files)) {
196
+ if (target === residualPath) continue;
197
+ const own = readFileNodes(target);
198
+ if (own === null) return { observed: false, entries: [] };
199
+ const defined = new Set(own.nodes.map(({ name }) => name));
200
+ // import束縛はworktreeのfresh indexのAST観測から取る(sc-013)。text再解析をしない。
201
+ // 束縛が観測できないindexでは網の判定材料が欠けるので、unobservedへ倒す(fail closed)。
202
+ if (!Array.isArray(own.import_bindings)) return { observed: false, entries: [] };
203
+ const imported = new Set(own.import_bindings
204
+ .map(({ local }) => local).filter((name) => typeof name === 'string'));
205
+ for (const name of residualNames) {
206
+ if (defined.has(name) || imported.has(name)) continue;
207
+ if (mentions(body, name)) entries.push({ file: target, name });
208
+ }
209
+ }
210
+ return {
211
+ observed: true,
212
+ entries: entries.sort((left, right) => compareText(
213
+ `${left.file}\0${left.name}`, `${right.file}\0${right.name}`,
214
+ )),
215
+ };
216
+ }
217
+
133
218
  /**
134
219
  * 変換後worktreeを再indexし、新pathが索引に載ったかを見る。
135
220
  *
@@ -230,6 +315,7 @@ export function seamConflictFromProposal({ proposal, witnessSet, pathNames = {}
230
315
  */
231
316
  export function seamConflictFromFinding({
232
317
  finding, witnessSet, pathNames = {}, affectedTests = [], baseSha, manifestDigest,
318
+ recordedFindingDigest = null,
233
319
  } = {}) {
234
320
  if (finding?.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
235
321
  return { conflict: null, reasons: ['finding_not_write_conflict'] };
@@ -250,7 +336,11 @@ export function seamConflictFromFinding({
250
336
  baseSha,
251
337
  manifestDigest,
252
338
  // 実行時は提案artifactが無い。観測したfindingそのものを出所として縛る。
253
- findingDigest: digestArtifact({
339
+ //
340
+ // **記録済みfindingのdigestがあるなら、それを使う。** 内容から再導出したdigestで縛ると、
341
+ // 「この変換はあのfindingへの答えだ」という記録が、storeに実在しないidを指す。実際、
342
+ // 再計画側は`findings/<digest>.json`を読むので、再導出値では必ず読めない。
343
+ findingDigest: recordedFindingDigest ?? digestArtifact({
254
344
  kind: finding.kind, path: finding.path, todo_ids: taskIds,
255
345
  }),
256
346
  candidateId: `seam-runtime-${sha16(`${finding.path}\0${taskIds.join(',')}`)}`,
@@ -314,6 +404,7 @@ export async function applySeamConflict({
314
404
  }
315
405
  const rewritten = planSeamRewrite({
316
406
  sourceText: beforeText, candidate, symbolExtents: lookup.extents,
407
+ importSurface: readImportSurface({ cwd: repoRoot, sourcePath }),
317
408
  });
318
409
  if (rewritten.files === null) {
319
410
  return { outcome: outcome({ planKey, decision: 'rejected', reasons: rewritten.reasons, candidate }), files: null };
@@ -361,9 +452,14 @@ export async function applySeamConflict({
361
452
  const owned = candidate.surfaces
362
453
  .filter(({ role }) => role === 'task_owned').map(({ path: target }) => target);
363
454
  const sensor = await observeFreshSensor({ worktreePath, latticeBin, paths: owned });
364
- observation = { sensor, afterText: null, afterArtifact: null };
455
+ observation = { sensor, afterText: null, afterArtifact: null, severed: null };
365
456
  observation.afterText = await readFile(path.join(worktreePath, sourcePath), 'utf8');
366
457
  if (!sensor.fresh) return;
458
+ // 網は受入の一点だけ(ADR 0145)。fresh indexの上でしか意味を持たないので、
459
+ // sensorが新pathを見ていない時は数えず、observation欠落として別理由で落とす。
460
+ observation.severed = await detectSeveredReferences({
461
+ worktreePath, files: rewritten.files, residualPath: sourcePath,
462
+ });
367
463
  const post = buildPostTransformWitnessSet({
368
464
  witnessSet, candidate, affectedTestsByPath: sensor.affectedByPath,
369
465
  });
@@ -389,6 +485,7 @@ export async function applySeamConflict({
389
485
  exportSurface: observation?.afterText === null || observation?.afterText === undefined
390
486
  ? { preserved: false, missing: [] }
391
487
  : compareExportSurface({ before: beforeText, after: observation.afterText }),
488
+ severed: observation?.severed ?? null,
392
489
  focusedTestsPassed: verifierFailure === null,
393
490
  sensorFresh: observation?.sensor?.fresh === true,
394
491
  conflictPairs: afterPairs === null ? { targetResolved: false }
@@ -0,0 +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族のwasm経路だけが持つ。kernel経路(Rust)は未配線で、
248
+ // その索引では書き込みが読みに見える——盲点として申告する(sc-007で解消)。
249
+ write_distinction: 'ts-js-wasm-pipeline-only',
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
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 確実の門(docs/plan_seam-cost.md sc-012、オーナー裁定)。
3
+ *
4
+ * スクリプト変換は**確実にできる内容だけ**行う。チャレンジは駄目、怪しければ AI へ。
5
+ * ESM 変換器は元から fail closed で、導出・照会・書き換え・五条件の各段が typed 理由で
6
+ * 拒否する——だが条件はコードに散在し、「機械が何を前提にしているか」「拒否されたら誰の
7
+ * 仕事か」を読める一覧が無かった。ここが正典。
8
+ *
9
+ * 門は2つのことだけを言う:
10
+ *
11
+ * - **前提の一覧**: 機械変換が立つ条件。1つでも欠ければ変換は実行されない(既存挙動)。
12
+ * - **手渡しの分類**: 拒否理由を「宣言を直せば機械で通る」(fix_declaration) と
13
+ * 「機械の変換能力の外=AI が変換すべき」(hand_to_ai) へ分ける。装置は可否を決めず、
14
+ * 次に誰が動くべきかの事実だけ返す。
15
+ *
16
+ * **未知の理由は certain 側へ丸めない。** 分類できない拒否は unrecognized として返し、
17
+ * 門は閉じたままにする——理由の語彙が増えた時、黙って「確実」へ倒れる方向の壊れ方を防ぐ。
18
+ */
19
+
20
+ const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
21
+
22
+ /**
23
+ * 機械変換の事前条件の正典。id は安定識別子、reason_prefixes は各段が返す typed 理由
24
+ * との対応(`:` 以降に対象名が付く動的形を含む)。
25
+ */
26
+ export const SEAM_GATE_PRECONDITIONS = Object.freeze([
27
+ {
28
+ id: 'inputs_well_formed',
29
+ holds: '入力(path・task・candidate id)が契約の形である',
30
+ handoff: 'fix_declaration',
31
+ reason_prefixes: [
32
+ 'invalid_source_path', 'invalid_shared_path', 'invalid_owned_path',
33
+ 'invalid_candidate_id', 'task_refs_below_minimum', 'duplicate_task_id',
34
+ 'surface_path_collision', 'empty_source', 'surfaces_incomplete',
35
+ ],
36
+ },
37
+ {
38
+ id: 'ownership_declared_and_exclusive',
39
+ holds: '移す symbol が宣言され、2 task が同じ symbol を主張していない',
40
+ handoff: 'fix_declaration',
41
+ reason_prefixes: ['owned_symbols_missing', 'owned_symbol_claimed_twice'],
42
+ },
43
+ {
44
+ id: 'closure_observed_and_closed',
45
+ holds: '所有 symbol の同一 file 内閉包が観測で閉じている',
46
+ handoff: 'hand_to_ai',
47
+ reason_prefixes: ['callee_data_missing', 'closure_rounds_exhausted'],
48
+ },
49
+ {
50
+ id: 'shared_surface_acyclic',
51
+ holds: '共有面が所有面へ逆依存しない(切った先が元を向かない)',
52
+ handoff: 'hand_to_ai',
53
+ reason_prefixes: ['shared_depends_on_owned'],
54
+ },
55
+ {
56
+ id: 'extents_resolved_and_disjoint',
57
+ holds: '全対象 symbol の行範囲と export 状態が確定し、互いに重ならず、import block の外にある',
58
+ handoff: 'hand_to_ai',
59
+ reason_prefixes: [
60
+ 'symbol_extent_missing', 'symbol_extent_overlap', 'symbol_inside_import_block',
61
+ 'symbol_lookup_truncated', 'symbol_export_status_missing',
62
+ ],
63
+ },
64
+ {
65
+ id: 'import_surface_observed',
66
+ holds: 'import 文の範囲と束縛が sensor 観測で確定している(先頭 block に収まり、帰属が一意)',
67
+ handoff: 'hand_to_ai',
68
+ reason_prefixes: [
69
+ 'import_surface_missing', 'import_statement_ambiguous',
70
+ 'import_binding_unassigned', 'import_below_header',
71
+ ],
72
+ },
73
+ {
74
+ id: 'behavior_preserved',
75
+ holds: '公開面が保たれ、切断参照が無い(ADR 0145 の網)',
76
+ handoff: 'hand_to_ai',
77
+ reason_prefixes: ['behavior_equivalent'],
78
+ },
79
+ {
80
+ id: 'tests_and_index_pass',
81
+ holds: 'focused test が通り、変換後 index が新面を収載している',
82
+ handoff: 'hand_to_ai',
83
+ reason_prefixes: ['focused_tests_passed', 'sensor_fresh', 'verifier', 'witness'],
84
+ },
85
+ {
86
+ id: 'parallelism_gained',
87
+ holds: '対象競合が消え、競合対が増えず、波数が減る(ADR 0138)',
88
+ handoff: 'hand_to_ai',
89
+ reason_prefixes: ['overlap_reduced', 'parallelism_improved'],
90
+ },
91
+ ]);
92
+
93
+ const PREFIX_TO_CONDITION = new Map();
94
+ for (const condition of SEAM_GATE_PRECONDITIONS) {
95
+ for (const prefix of condition.reason_prefixes) {
96
+ PREFIX_TO_CONDITION.set(prefix, condition);
97
+ }
98
+ }
99
+
100
+ function conditionOf(reason) {
101
+ const head = reason.split(':')[0];
102
+ return PREFIX_TO_CONDITION.get(head) ?? null;
103
+ }
104
+
105
+ /**
106
+ * 拒否理由の集合を門で分類する。
107
+ *
108
+ * @param {string[]} reasons 変換が返した typed 理由(空なら門は開いている=機械で確実に通った)
109
+ * @returns {{
110
+ * certain: boolean,
111
+ * handoff: 'none'|'fix_declaration'|'hand_to_ai',
112
+ * failed: Array<{id: string, holds: string, handoff: string, reasons: string[]}>,
113
+ * unrecognized: string[],
114
+ * }}
115
+ */
116
+ export function explainSeamGate(reasons = []) {
117
+ const byCondition = new Map();
118
+ const unrecognized = [];
119
+ for (const reason of reasons) {
120
+ const condition = conditionOf(reason);
121
+ if (condition === null) {
122
+ unrecognized.push(reason);
123
+ continue;
124
+ }
125
+ if (!byCondition.has(condition.id)) {
126
+ byCondition.set(condition.id, { id: condition.id, holds: condition.holds,
127
+ handoff: condition.handoff, reasons: [] });
128
+ }
129
+ byCondition.get(condition.id).reasons.push(reason);
130
+ }
131
+ const failed = [...byCondition.values()]
132
+ .map((entry) => ({ ...entry, reasons: [...entry.reasons].sort(compareText) }))
133
+ .sort((left, right) => compareText(left.id, right.id));
134
+ const certain = reasons.length === 0;
135
+ // hand_to_ai が1つでもあれば機械の再試行では越えられない。fix_declaration だけなら
136
+ // 宣言を直して再提出すれば機械で通りうる。未知の理由は安全側=hand_to_ai として扱う。
137
+ const handoff = certain ? 'none'
138
+ : (failed.some(({ handoff: kind }) => kind === 'hand_to_ai') || unrecognized.length > 0)
139
+ ? 'hand_to_ai' : 'fix_declaration';
140
+ return {
141
+ certain,
142
+ handoff,
143
+ failed,
144
+ unrecognized: [...unrecognized].sort(compareText),
145
+ };
146
+ }