@quolu/lattice 0.32.0 → 0.33.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.
- package/README.ja.md +11 -1
- package/README.md +11 -2
- package/bin/lattice.mjs +12 -1
- package/package.json +1 -1
- package/sensor/dist/bin/lattice-sensor.js +72 -4
- package/sensor/dist/db/migrations.d.ts +1 -1
- package/sensor/dist/db/migrations.d.ts.map +1 -1
- package/sensor/dist/db/migrations.js +32 -2
- package/sensor/dist/db/migrations.js.map +1 -1
- package/sensor/dist/db/queries.d.ts +10 -0
- package/sensor/dist/db/queries.d.ts.map +1 -1
- package/sensor/dist/db/queries.js +53 -7
- package/sensor/dist/db/queries.js.map +1 -1
- package/sensor/dist/db/schema.sql +6 -1
- package/sensor/dist/extraction/tree-sitter.d.ts.map +1 -1
- package/sensor/dist/extraction/tree-sitter.js +89 -16
- package/sensor/dist/extraction/tree-sitter.js.map +1 -1
- package/sensor/dist/index.d.ts +8 -1
- package/sensor/dist/index.d.ts.map +1 -1
- package/sensor/dist/index.js +9 -0
- package/sensor/dist/index.js.map +1 -1
- package/sensor/dist/resolution/import-resolver.d.ts +11 -0
- package/sensor/dist/resolution/import-resolver.d.ts.map +1 -1
- package/sensor/dist/resolution/import-resolver.js +13 -5
- package/sensor/dist/resolution/import-resolver.js.map +1 -1
- package/sensor/dist/resolution/index.d.ts.map +1 -1
- package/sensor/dist/resolution/index.js +11 -0
- package/sensor/dist/resolution/index.js.map +1 -1
- package/sensor/dist/resolution/types.d.ts +4 -0
- package/sensor/dist/resolution/types.d.ts.map +1 -1
- package/sensor/dist/types.d.ts +16 -0
- package/sensor/dist/types.d.ts.map +1 -1
- package/src/artifact-contracts.mjs +3 -0
- package/src/cli-help.mjs +6 -0
- package/src/rc3-scripted-campaign.mjs +3 -1
- package/src/runtime-cli.mjs +280 -36
- package/src/runtime-contracts.mjs +1 -1
- package/src/runtime-control-store.mjs +24 -1
- package/src/runtime-decision-verifier.mjs +1 -1
- package/src/runtime-diff-observer.mjs +2 -2
- package/src/runtime-front-end.mjs +47 -13
- package/src/runtime-hold-recompile.mjs +31 -2
- package/src/runtime-io-sentinel.mjs +16 -9
- package/src/runtime-managed-supervisor.mjs +9 -1
- package/src/runtime-multi-epoch-store.mjs +2 -2
- package/src/runtime-projection.mjs +27 -0
- package/src/runtime-scripted-adapter-controller.mjs +22 -1
- package/src/runtime-seam-resolve.mjs +156 -13
- package/src/runtime-seam-treatment.mjs +2 -1
- package/src/seam-apply.mjs +101 -4
- package/src/seam-cost.mjs +322 -0
- package/src/seam-gate.mjs +146 -0
- package/src/seam-rewrite.mjs +102 -16
- package/src/seam-verification.mjs +26 -3
- package/src/sensor-adapter.mjs +6 -1
- package/src/todo-cli.mjs +55 -0
|
@@ -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
|
+
}
|
package/src/seam-rewrite.mjs
CHANGED
|
@@ -21,6 +21,10 @@ function fail(reasons) {
|
|
|
21
21
|
*
|
|
22
22
|
* 複数行importがあるので`from '...'`で終わる行までを1文とする。束縛名は、移した先で
|
|
23
23
|
* どのimportが要るかを語単位で判定するために使う。
|
|
24
|
+
*
|
|
25
|
+
* **書き換え本体はこれを使わない(sc-013)。** planSeamRewriteのimport面はsensorの
|
|
26
|
+
* AST観測(`joinImportSurface`)から受け取る。この正規表現走査が残っているのは
|
|
27
|
+
* seam-costのprofile投影(ESM限定とconfidenceで申告済み)のためだけである。
|
|
24
28
|
*/
|
|
25
29
|
export function scanImportStatements(lines) {
|
|
26
30
|
const statements = [];
|
|
@@ -41,7 +45,7 @@ export function scanImportStatements(lines) {
|
|
|
41
45
|
return { statements, endIndex: statements.length === 0 ? -1 : statements.at(-1).end };
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
function importBindings(text) {
|
|
48
|
+
export function importBindings(text) {
|
|
45
49
|
const bindings = [];
|
|
46
50
|
const namespace = /import\s+\*\s+as\s+([A-Za-z_$][\w$]*)/u.exec(text);
|
|
47
51
|
if (namespace) bindings.push(namespace[1]);
|
|
@@ -59,10 +63,39 @@ function importBindings(text) {
|
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
/** 語として現れるか。string中やcomment中の一致も拾うが、余分なimportは害にならない。 */
|
|
62
|
-
function mentions(text, name) {
|
|
66
|
+
export function mentions(text, name) {
|
|
63
67
|
return new RegExp(`(?<![\\w$])${name.replace(/[$]/gu, '\\$$')}(?![\\w$])`, 'u').test(text);
|
|
64
68
|
}
|
|
65
69
|
|
|
70
|
+
/**
|
|
71
|
+
* sensorの観測(`file-nodes`の`imports`と`import_bindings`)をimport文単位へ束ねる(sc-013)。
|
|
72
|
+
*
|
|
73
|
+
* importsは文の行範囲、import_bindingsは束縛ごとの`{local, form, imported, line}`で、
|
|
74
|
+
* 両者は行番号で結合できる(解決済み束縛はedge metadata、builtin等の未解決束縛は
|
|
75
|
+
* unresolved_refs由来——どちらもAST抽出であり、正規表現の再実装ではない)。
|
|
76
|
+
* どの文にも入らない束縛は`unassigned`として返し、黙って捨てない。
|
|
77
|
+
*
|
|
78
|
+
* @returns {{statements: Array<{startLine:number,endLine:number,bindings:string[]}>, unassigned: string[]}}
|
|
79
|
+
*/
|
|
80
|
+
export function joinImportSurface(importNodes = [], importBindings = []) {
|
|
81
|
+
const statements = importNodes
|
|
82
|
+
.filter((node) => Number.isSafeInteger(node?.startLine) && Number.isSafeInteger(node?.endLine)
|
|
83
|
+
&& node.startLine >= 1 && node.endLine >= node.startLine)
|
|
84
|
+
.map((node) => ({ startLine: node.startLine, endLine: node.endLine, bindings: [] }))
|
|
85
|
+
.sort((left, right) => left.startLine - right.startLine);
|
|
86
|
+
const unassigned = [];
|
|
87
|
+
for (const binding of importBindings) {
|
|
88
|
+
if (typeof binding?.local !== 'string' || binding.local === '') continue;
|
|
89
|
+
const owner = Number.isSafeInteger(binding.line)
|
|
90
|
+
? statements.find(({ startLine, endLine }) => binding.line >= startLine && binding.line <= endLine)
|
|
91
|
+
: undefined;
|
|
92
|
+
if (owner === undefined) { unassigned.push(binding.local); continue; }
|
|
93
|
+
if (!owner.bindings.includes(binding.local)) owner.bindings.push(binding.local);
|
|
94
|
+
}
|
|
95
|
+
for (const statement of statements) statement.bindings.sort(compareText);
|
|
96
|
+
return { statements, unassigned: [...new Set(unassigned)].sort(compareText) };
|
|
97
|
+
}
|
|
98
|
+
|
|
66
99
|
/**
|
|
67
100
|
* 宣言の範囲を直前の連続コメント行まで広げる。
|
|
68
101
|
*
|
|
@@ -85,28 +118,44 @@ function exportedBlock(raw) {
|
|
|
85
118
|
return parts.join('\n');
|
|
86
119
|
}
|
|
87
120
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const declaration = raw.split('\n')
|
|
91
|
-
.find((line) => !COMMENT_LINE.test(line) && line.trim() !== '');
|
|
92
|
-
return declaration !== undefined && /^\s*export\s/u.test(declaration);
|
|
93
|
-
}
|
|
121
|
+
// 原pathでexport宣言だったかは、text走査でなくsensorのisExported(AST事実)で判定する
|
|
122
|
+
// (sc-013)。extentと同じくfile-nodes由来で、symbolExtentsの各entryが持って来る。
|
|
94
123
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
124
|
+
/**
|
|
125
|
+
* repo相対path同士から、ESMが解決できる相対specifierを作る。
|
|
126
|
+
*
|
|
127
|
+
* 以前は行き先がfromの配下でない時に`./<repo相対>`を返しており、親ディレクトリや兄弟
|
|
128
|
+
* ディレクトリへの移動で**解決不能なspecifier**を生成していた(`src/a/x.mjs`→`src/b/y.mjs`で
|
|
129
|
+
* `./src/b/y.mjs`)。segment単位で共通prefixを外し、残りを`../`で遡って組み立てる。
|
|
130
|
+
*/
|
|
131
|
+
export function relativeSpecifier(fromPath, toPath) {
|
|
132
|
+
const fromSegments = fromPath.split('/').slice(0, -1);
|
|
133
|
+
const toSegments = toPath.split('/');
|
|
134
|
+
let shared = 0;
|
|
135
|
+
while (shared < fromSegments.length && shared < toSegments.length - 1
|
|
136
|
+
&& fromSegments[shared] === toSegments[shared]) shared += 1;
|
|
137
|
+
const ascent = '../'.repeat(fromSegments.length - shared);
|
|
138
|
+
const descent = toSegments.slice(shared).join('/');
|
|
139
|
+
return ascent === '' ? `./${descent}` : `${ascent}${descent}`;
|
|
98
140
|
}
|
|
99
141
|
|
|
100
142
|
/**
|
|
101
143
|
* 三面の変換後textを作る。
|
|
102
144
|
*
|
|
145
|
+
* import面と各symbolのexport状態はsensorの観測を入力として受け取る(sc-013)。
|
|
146
|
+
* ここで正規表現によるimport再解析を行わない——言語理解はsensorが所有し、
|
|
147
|
+
* ここは決まった移動のtext組み立てだけを持つ。観測が無ければtyped理由で止める。
|
|
148
|
+
* 唯一残るtext走査は直前コメント行の巻き込み(extendUpward)で、sensorはcomment行の
|
|
149
|
+
* 範囲を記録しないため、これはtext組み立ての一部として保持する。
|
|
150
|
+
*
|
|
103
151
|
* @param {object} options
|
|
104
152
|
* @param {string} options.sourceText 原pathの現在の内容
|
|
105
153
|
* @param {object} options.candidate `lattice.bounded_seam_candidate.v2`
|
|
106
|
-
* @param {object} options.symbolExtents symbol名 -> `{startLine, endLine}`(1始まり・両端含む)
|
|
154
|
+
* @param {object} options.symbolExtents symbol名 -> `{startLine, endLine, isExported}`(1始まり・両端含む)
|
|
155
|
+
* @param {object} options.importSurface `joinImportSurface`の結果(`{statements, unassigned}`)
|
|
107
156
|
* @returns {{files: object|null, reasons: string[]}} pathごとの変換後text
|
|
108
157
|
*/
|
|
109
|
-
export function planSeamRewrite({ sourceText, candidate, symbolExtents } = {}) {
|
|
158
|
+
export function planSeamRewrite({ sourceText, candidate, symbolExtents, importSurface } = {}) {
|
|
110
159
|
if (typeof sourceText !== 'string' || sourceText.length === 0) return fail(['empty_source']);
|
|
111
160
|
const lines = sourceText.split('\n');
|
|
112
161
|
const surfaces = candidate?.surfaces ?? [];
|
|
@@ -124,8 +173,12 @@ export function planSeamRewrite({ sourceText, candidate, symbolExtents } = {}) {
|
|
|
124
173
|
|| extent.endLine < extent.startLine) {
|
|
125
174
|
return fail([`symbol_extent_missing:${symbol}`]);
|
|
126
175
|
}
|
|
176
|
+
// export状態はAST事実として要求する。無ければ推測せず止める(確実の門)。
|
|
177
|
+
if (typeof extent.isExported !== 'boolean') {
|
|
178
|
+
return fail([`symbol_export_status_missing:${symbol}`]);
|
|
179
|
+
}
|
|
127
180
|
blocks.push({
|
|
128
|
-
symbol, path: surface.path, end: extent.endLine,
|
|
181
|
+
symbol, path: surface.path, end: extent.endLine, exported: extent.isExported,
|
|
129
182
|
start: extendUpward(lines, extent.startLine),
|
|
130
183
|
});
|
|
131
184
|
}
|
|
@@ -138,7 +191,40 @@ export function planSeamRewrite({ sourceText, candidate, symbolExtents } = {}) {
|
|
|
138
191
|
}
|
|
139
192
|
}
|
|
140
193
|
|
|
141
|
-
|
|
194
|
+
// import面はsensorの観測から。観測が無い・束縛の帰属が決まらない・importが先頭block
|
|
195
|
+
// の外にある——いずれも「たぶん大丈夫」で進まず、typed理由でAIへ渡す。
|
|
196
|
+
if (importSurface === null || typeof importSurface !== 'object'
|
|
197
|
+
|| !Array.isArray(importSurface.statements)) {
|
|
198
|
+
return fail(['import_surface_missing']);
|
|
199
|
+
}
|
|
200
|
+
if (Array.isArray(importSurface.unassigned) && importSurface.unassigned.length > 0) {
|
|
201
|
+
return fail(importSurface.unassigned.map((name) => `import_binding_unassigned:${name}`));
|
|
202
|
+
}
|
|
203
|
+
const statements = [];
|
|
204
|
+
let cursor = 1;
|
|
205
|
+
for (const entry of [...importSurface.statements]
|
|
206
|
+
.sort((left, right) => left.startLine - right.startLine)) {
|
|
207
|
+
if (!Number.isSafeInteger(entry.startLine) || !Number.isSafeInteger(entry.endLine)
|
|
208
|
+
|| entry.startLine < 1 || entry.endLine > lines.length || entry.endLine < entry.startLine
|
|
209
|
+
|| !Array.isArray(entry.bindings)) {
|
|
210
|
+
return fail(['import_surface_missing']);
|
|
211
|
+
}
|
|
212
|
+
if (entry.startLine < cursor) return fail([`import_statement_ambiguous:${entry.startLine}`]);
|
|
213
|
+
for (let line = cursor; line < entry.startLine; line += 1) {
|
|
214
|
+
const text = lines[line - 1];
|
|
215
|
+
if (text.trim() !== '' && !COMMENT_LINE.test(text)) {
|
|
216
|
+
// 先頭block外のimport(ESMでは合法)は、残余headerの組み立てが機械では確実に
|
|
217
|
+
// できない。整形で解こうとせず止める。
|
|
218
|
+
return fail([`import_below_header:${entry.startLine}`]);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
statements.push({
|
|
222
|
+
text: lines.slice(entry.startLine - 1, entry.endLine).join('\n'),
|
|
223
|
+
bindings: entry.bindings.filter((name) => typeof name === 'string' && name !== ''),
|
|
224
|
+
});
|
|
225
|
+
cursor = entry.endLine + 1;
|
|
226
|
+
}
|
|
227
|
+
const endIndex = cursor - 2;
|
|
142
228
|
if (blocks.some((block) => block.start <= endIndex + 1)) {
|
|
143
229
|
return fail(['symbol_inside_import_block']);
|
|
144
230
|
}
|
|
@@ -152,7 +238,7 @@ export function planSeamRewrite({ sourceText, candidate, symbolExtents } = {}) {
|
|
|
152
238
|
const raw = lines.slice(block.start - 1, block.end).join('\n');
|
|
153
239
|
if (!bodyByPath.has(block.path)) bodyByPath.set(block.path, []);
|
|
154
240
|
bodyByPath.get(block.path).push(exportedBlock(raw));
|
|
155
|
-
if (
|
|
241
|
+
if (block.exported) {
|
|
156
242
|
if (!reExportByPath.has(block.path)) reExportByPath.set(block.path, []);
|
|
157
243
|
reExportByPath.get(block.path).push(block.symbol);
|
|
158
244
|
}
|