@quolu/lattice 0.20.1 → 0.21.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.20.1",
3
+ "version": "0.21.0",
4
4
  "description": "Lattice — phase-aware TODO graph compiler and conflict-aware orchestration runtime",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,8 +14,94 @@ function sortedUniqueRefs(value, { nonempty = false } = {}) {
14
14
  && value.every((entry, index) => index === 0 || value[index - 1] < entry);
15
15
  }
16
16
 
17
+ /**
18
+ * v2の三面surface(ADR 0137 Decision 1)。所有だけがtaskへ紐づく。
19
+ *
20
+ * 残余はsymbolを列挙しない。移らなかったものすべてという補集合であり、列挙を要求すると
21
+ * 原fileの全symbol目録が契約の一部になる。
22
+ */
23
+ function seamSurface(value, taskIds) {
24
+ if (!exactRecord(value, ['role', 'path', 'owner_task_ids', 'symbols'])
25
+ || !['task_owned', 'shared', 'residual'].includes(value.role)
26
+ || !isTodoRef(value.path)
27
+ || !Array.isArray(value.owner_task_ids)
28
+ || !sortedUniqueSymbols(value.symbols)) return false;
29
+ if (value.role === 'task_owned') {
30
+ return value.owner_task_ids.length === 1 && taskIds.has(value.owner_task_ids[0])
31
+ && value.symbols.length > 0;
32
+ }
33
+ if (value.owner_task_ids.length !== 0) return false;
34
+ return value.role === 'shared' ? value.symbols.length > 0 : value.symbols.length === 0;
35
+ }
36
+
37
+ function sortedUniqueSymbols(value) {
38
+ return Array.isArray(value) && value.every(isTodoIdentifier)
39
+ && value.every((entry, index) => index === 0 || value[index - 1] < entry);
40
+ }
41
+
42
+ function validateBoundedSeamCandidateV2(value) {
43
+ if (!exactRecord(value, [
44
+ 'schema', 'candidate_id', 'base_sha', 'manifest_digest', 'finding_digest',
45
+ 'source_path', 'todo_refs', 'surfaces', 'allowed_paths', 'required_paths',
46
+ 'verification_policy', 'candidate_digest',
47
+ ])
48
+ || !isTodoIdentifier(value.candidate_id) || !GIT_OID.test(value.base_sha)
49
+ || !isTodoDigest(value.manifest_digest) || !isTodoDigest(value.finding_digest)
50
+ || !isTodoRef(value.source_path)
51
+ || !Array.isArray(value.todo_refs) || value.todo_refs.length < 2
52
+ || !value.todo_refs.every((entry) => exactRecord(entry, ['plan_key', 'task_id'])
53
+ && isTodoIdentifier(entry.plan_key) && isTodoIdentifier(entry.task_id))
54
+ || !value.todo_refs.every((entry, index) => index === 0
55
+ || `${value.todo_refs[index - 1].plan_key}\0${value.todo_refs[index - 1].task_id}`
56
+ < `${entry.plan_key}\0${entry.task_id}`)) return false;
57
+
58
+ const taskIds = new Set(value.todo_refs.map(({ task_id: taskId }) => taskId));
59
+ if (!Array.isArray(value.surfaces)
60
+ || !value.surfaces.every((surface) => seamSurface(surface, taskIds))
61
+ || !value.surfaces.every((surface, index) => index === 0
62
+ || value.surfaces[index - 1].path < surface.path)) return false;
63
+
64
+ // 所有面は全taskへ1つずつ。残余は原path上に必ず1つ。共有面は0または1(粒度は未裁定)。
65
+ const owned = value.surfaces.filter(({ role }) => role === 'task_owned');
66
+ const shared = value.surfaces.filter(({ role }) => role === 'shared');
67
+ const residual = value.surfaces.filter(({ role }) => role === 'residual');
68
+ const ownerIds = new Set(owned.flatMap(({ owner_task_ids: ids }) => ids));
69
+ if (owned.length !== taskIds.size || ownerIds.size !== taskIds.size
70
+ || shared.length > 1 || residual.length !== 1
71
+ || residual[0].path !== value.source_path) return false;
72
+
73
+ // symbolは1面にしか属せない。二重所有は移動先が決まらない。
74
+ const symbols = value.surfaces.flatMap(({ symbols: list }) => list);
75
+ if (new Set(symbols).size !== symbols.length) return false;
76
+
77
+ if (!sortedUniqueRefs(value.allowed_paths, { nonempty: true })
78
+ || !sortedUniqueRefs(value.required_paths, { nonempty: true })
79
+ || !value.required_paths.every((entry) => value.allowed_paths.includes(entry))
80
+ || !value.surfaces.every(({ path }) => value.allowed_paths.includes(path))
81
+ || !value.required_paths.includes(value.source_path)
82
+ || !owned.every(({ path }) => value.required_paths.includes(path))) return false;
83
+
84
+ // ADR 0138の五条件。1つでもfalseなら、その候補は採用条件を緩めた別物である。
85
+ return exactRecord(value.verification_policy, [
86
+ 'focused_test_refs', 'require_behavior_equivalence', 'require_fresh_sensor',
87
+ 'require_overlap_reduction', 'require_no_new_conflict_pairs',
88
+ 'require_parallelism_improvement',
89
+ ])
90
+ && sortedUniqueRefs(value.verification_policy.focused_test_refs, { nonempty: true })
91
+ && value.verification_policy.require_behavior_equivalence === true
92
+ && value.verification_policy.require_fresh_sensor === true
93
+ && value.verification_policy.require_overlap_reduction === true
94
+ && value.verification_policy.require_no_new_conflict_pairs === true
95
+ && value.verification_policy.require_parallelism_improvement === true
96
+ && isTodoDigest(value.candidate_digest)
97
+ && value.candidate_digest === todoSelfDigest(value, 'candidate_digest');
98
+ }
99
+
17
100
  export function validateBoundedSeamCandidate(value) {
18
101
  try {
102
+ if (value?.schema === 'lattice.bounded_seam_candidate.v2') {
103
+ return validateBoundedSeamCandidateV2(value);
104
+ }
19
105
  return exactRecord(value, [
20
106
  'schema', 'candidate_id', 'base_sha', 'manifest_digest', 'finding_digest',
21
107
  'todo_refs', 'anchor', 'allowed_paths', 'required_paths', 'verification_policy',
package/src/cli-help.mjs CHANGED
@@ -71,6 +71,8 @@ Write commands:
71
71
  independence compile --plan <key> --input <file> # witness setとsensorから並列可否を記録する
72
72
  independence witness migrate --plan <key> # revision後の宣言をtask migrationで写す
73
73
  seam-proposal compile --plan <key> # 並列可否記録と実sensorからseam提案を記録する
74
+ seam-proposal apply --plan <key> # 記録済み提案を隔離worktreeで適用し五条件で採否を決める
75
+ seam-proposal land --plan <key> --names <file> # 採用された変換を本ツリーへ着地させる
74
76
  revise --plan <key> --input <file>
75
77
  revise-phase --plan <key> --input <file>
76
78
  revise-set --input <file>
@@ -3,8 +3,10 @@ import {
3
3
  mkdtemp,
4
4
  readdir,
5
5
  readFile,
6
+ mkdir,
6
7
  readlink,
7
8
  rm,
9
+ symlink,
8
10
  } from 'node:fs/promises';
9
11
  import os from 'node:os';
10
12
  import path from 'node:path';
@@ -51,13 +53,18 @@ function verificationReceipt(verifier, result, outcome) {
51
53
  };
52
54
  }
53
55
 
54
- function verifierEnvironment() {
55
- const env = { ...process.env, NO_COLOR: '1' };
56
+ function verifierEnvironment(extra = {}) {
57
+ const env = { ...process.env, NO_COLOR: '1', ...extra };
56
58
  delete env.NODE_TEST_CONTEXT;
57
59
  delete env.FORCE_COLOR;
58
60
  return env;
59
61
  }
60
62
 
63
+ function isPlainStringRecord(value) {
64
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
65
+ && Object.values(value).every((entry) => typeof entry === 'string');
66
+ }
67
+
61
68
  function safeRelativePath(value) {
62
69
  return typeof value === 'string'
63
70
  && value.length > 0
@@ -123,10 +130,17 @@ async function buildPatch(worktreePath, changedPaths) {
123
130
  return Buffer.concat(parts);
124
131
  }
125
132
 
126
- async function captureSnapshot(worktreePath, baseSha, allowedPaths) {
133
+ async function captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries = []) {
134
+ const mounted = new Set(mountedEntries);
127
135
  const changedPaths = statusPaths((await run('git', [
128
136
  'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching',
129
- ], { cwd: worktreePath })).stdout);
137
+ ], { cwd: worktreePath })).stdout)
138
+ // runnerが張ったmountだけを外す。それ以外は無視しない——gitignore対象であっても、
139
+ // allowed pathの外に現れたものは変更である。
140
+ .filter((changedPath) => {
141
+ const normalized = changedPath.replace(/\/$/u, '');
142
+ return ![...mounted].some((entry) => normalized === entry || normalized.startsWith(`${entry}/`));
143
+ });
130
144
  for (const changedPath of changedPaths) {
131
145
  if (!safeRelativePath(changedPath) || !isAllowed(changedPath, allowedPaths)) {
132
146
  throw new Error(`change outside allowed paths: ${changedPath}`);
@@ -136,8 +150,8 @@ async function captureSnapshot(worktreePath, baseSha, allowedPaths) {
136
150
  return { changedPaths, patch: await buildPatch(worktreePath, changedPaths) };
137
151
  }
138
152
 
139
- async function assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, expected, actor) {
140
- const actual = await captureSnapshot(worktreePath, baseSha, allowedPaths);
153
+ async function assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, expected, actor, mountedEntries = []) {
154
+ const actual = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
141
155
  if (actual.changedPaths.length !== expected.changedPaths.length
142
156
  || actual.changedPaths.some((changedPath, index) => changedPath !== expected.changedPaths[index])
143
157
  || !actual.patch.equals(expected.patch)) {
@@ -257,13 +271,20 @@ async function assertSourceUnchanged(repoRoot, sourceState) {
257
271
  return receipt;
258
272
  }
259
273
 
260
- export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, transform, verifyCommands, observe } = {}) {
274
+ export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, transform, verifyCommands, observe, mounts = [], verifierEnv = {} } = {}) {
261
275
  if (!safeRelativePath('.') || typeof repoRoot !== 'string' || typeof baseRef !== 'string'
262
276
  || !Array.isArray(allowedPaths) || allowedPaths.some((entry) => !safeRelativePath(entry))
263
277
  || typeof transform !== 'function' || !Array.isArray(verifyCommands)
264
- || (observe !== undefined && typeof observe !== 'function')) {
278
+ || (observe !== undefined && typeof observe !== 'function')
279
+ || !isPlainStringRecord(verifierEnv)
280
+ || !Array.isArray(mounts)
281
+ || mounts.some(({ entry, target } = {}) => typeof entry !== 'string'
282
+ || !safeRelativePath(entry) || typeof target !== 'string' || !path.isAbsolute(target))) {
265
283
  throw new TypeError('invalid isolated transform arguments');
266
284
  }
285
+ // mountはrunnerが自分で張り、自分が張ったentryだけをsnapshotから外す。呼び出し側が
286
+ // transformの中で作ると、任意の変更をsnapshotから隠す口になる。
287
+ const mountedEntries = mounts.map(({ entry }) => entry);
267
288
 
268
289
  const sourceState = await captureSourceState(repoRoot);
269
290
  if (sourceState.visibleStatus.length > 0) throw new Error('source repository must be clean');
@@ -278,8 +299,20 @@ export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, tr
278
299
  try {
279
300
  await run('git', ['worktree', 'add', '--detach', worktreePath, baseSha], { cwd: repoRoot });
280
301
  added = true;
302
+ for (const { entry, target } of mounts) {
303
+ // 保護pathへはmountさせない。そこを許すと、変更をsnapshotから隠す口になる。
304
+ if (PROTECTED_PATHS.includes(entry.split('/')[0])) {
305
+ throw new Error(`mount over protected path is not allowed: ${entry}`);
306
+ }
307
+ const mountPath = path.join(worktreePath, entry);
308
+ await mkdir(path.dirname(mountPath), { recursive: true });
309
+ // base checkoutが同名を持つ場合がある(trackedな.gitignore等)。mount配下は
310
+ // まるごとsnapshotの対象外になるので、置き換えても判定の抜けは生まれない。
311
+ await rm(mountPath, { recursive: true, force: true });
312
+ await symlink(target, mountPath);
313
+ }
281
314
  await transform({ worktreePath });
282
- snapshot = await captureSnapshot(worktreePath, baseSha, allowedPaths);
315
+ snapshot = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
283
316
  for (const verifier of verifyCommands) {
284
317
  if (!verifier || typeof verifier.command !== 'string' || !Array.isArray(verifier.args) || verifier.args.some((arg) => typeof arg !== 'string')) {
285
318
  throw new TypeError('verifyCommands must contain command and string args');
@@ -287,18 +320,18 @@ export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, tr
287
320
  try {
288
321
  const verification = await run(verifier.command, verifier.args, {
289
322
  cwd: worktreePath,
290
- env: verifierEnvironment(),
323
+ env: verifierEnvironment(verifierEnv),
291
324
  });
292
325
  verifications.push(verificationReceipt(verifier, verification, 'passed'));
293
326
  } catch (error) {
294
327
  verifications.push(verificationReceipt(verifier, error, 'failed'));
295
328
  throw new Error(`verifier failed (${error.signal ?? error.code}): ${verifier.command}`);
296
329
  }
297
- await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'verifier');
330
+ await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'verifier', mountedEntries);
298
331
  }
299
332
  if (observe) {
300
333
  await observe({ worktreePath, changedPaths: snapshot.changedPaths, patch: snapshot.patch, baseSha });
301
- await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'observe');
334
+ await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'observe', mountedEntries);
302
335
  }
303
336
  result = { baseSha, ...snapshot, verifications };
304
337
  } catch (error) {
Binary file
@@ -0,0 +1,188 @@
1
+ /**
2
+ * seam提案から実行可能な変換候補を導出する(ADR 0137・0138)。
3
+ *
4
+ * 提案が持つのは所有surfaceだけである。宣言symbolを新fileへ移すには、それが依存していて
5
+ * 誰も宣言していないsymbol(共有surface)と、原pathに残るもの(残余surface)まで決まっていなければ
6
+ * 適用後の姿が一意にならない。ここはその三面を、sensorが返した同一file内の依存から導く。
7
+ *
8
+ * 導出は宣言とsensor観測だけを入力にする。ここで新しい所有を発明しない——宣言していないsymbolは
9
+ * 誰のものにもせず、共有面へ送る。
10
+ */
11
+
12
+ import { isTodoIdentifier, isTodoRef, todoSelfDigest } from './todo-contracts.mjs';
13
+
14
+ export const BOUNDED_SEAM_CANDIDATE_SCHEMA = 'lattice.bounded_seam_candidate.v2';
15
+
16
+ /** 三面の役割。所有だけがtaskへ紐づき、共有と残余は誰のものでもない。 */
17
+ export const SEAM_SURFACE_ROLES = Object.freeze(['task_owned', 'shared', 'residual']);
18
+
19
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
20
+ const sortedUnique = (values) => [...new Set(values)].sort(compareText);
21
+
22
+ function reject(reasons) {
23
+ return { candidate: null, reasons: sortedUnique(reasons) };
24
+ }
25
+
26
+ /**
27
+ * 宣言symbolが同一file内で依存する先を、宣言されていない分だけ集める。
28
+ *
29
+ * 推移的に辿るのは、共有面が所有面へ依存しない一方向を作るためである。1段だけ見て止めると、
30
+ * helperのhelperが原pathに残り、共有面から原pathへの辺が生き残る。
31
+ */
32
+ function collectSharedClosure({ sourcePath, ownedSymbols, calleesBySymbol }) {
33
+ const owned = new Set(ownedSymbols);
34
+ const shared = new Set();
35
+ const missing = new Set();
36
+ const pending = [...ownedSymbols];
37
+ while (pending.length > 0) {
38
+ const current = pending.pop();
39
+ const callees = calleesBySymbol[current];
40
+ // 未照会と「calleeが無い」を同一視しない。同一視すると閉包が黙って浅くなり、
41
+ // 移動先で参照だけが宙に浮く——構文は通るので、実行するまで壊れたと分からない。
42
+ if (callees === undefined) { missing.add(current); continue; }
43
+ for (const callee of callees) {
44
+ // 同一file内だけを見る。sensorのsymbol解決は同名の別fileへ寄ることがあるので、
45
+ // pathのexact一致で絞らないと無関係なsymbolを共有面へ引き込む。
46
+ if (callee.path !== sourcePath) continue;
47
+ if (owned.has(callee.name) || shared.has(callee.name)) continue;
48
+ shared.add(callee.name);
49
+ pending.push(callee.name);
50
+ }
51
+ }
52
+ return { shared: [...shared].sort(compareText), missing: [...missing].sort(compareText) };
53
+ }
54
+
55
+ /** 共有面から所有面への辺。1本でもあれば循環を作るので候補にしない(ADR 0137 Decision 2)。 */
56
+ function sharedDependsOnOwned({ sourcePath, ownedSymbols, sharedSymbols, calleesBySymbol }) {
57
+ const owned = new Set(ownedSymbols);
58
+ const violations = [];
59
+ for (const symbol of sharedSymbols) {
60
+ for (const callee of calleesBySymbol[symbol] ?? []) {
61
+ if (callee.path !== sourcePath || !owned.has(callee.name)) continue;
62
+ violations.push(`${symbol}->${callee.name}`);
63
+ }
64
+ }
65
+ return violations.sort(compareText);
66
+ }
67
+
68
+ function surfaceEntry(role, path, ownerTaskIds, symbols) {
69
+ return {
70
+ role,
71
+ path,
72
+ owner_task_ids: [...ownerTaskIds].sort(compareText),
73
+ symbols: [...symbols].sort(compareText),
74
+ };
75
+ }
76
+
77
+ /**
78
+ * 実行可能な変換候補を導出する。
79
+ *
80
+ * 入力はすべて記録済みの事実である——宣言(concern anchors)、提案が決めた所有surfaceのpath、
81
+ * sensorが返した同一file内のcallee、候補のaffected test。ここで再びsensorを引かない。
82
+ */
83
+ export function deriveBoundedSeamCandidate(options = {}) {
84
+ const {
85
+ sourcePath, taskRefs, ownedSymbolsByTask, proposedPathByTask, sharedPath,
86
+ calleesBySymbol = {}, affectedTests = [], baseSha, manifestDigest, findingDigest,
87
+ candidateId,
88
+ } = options;
89
+
90
+ if (!isTodoRef(sourcePath)) return reject(['invalid_source_path']);
91
+ if (!Array.isArray(taskRefs) || taskRefs.length < 2) return reject(['task_refs_below_minimum']);
92
+ const taskIds = taskRefs.map(({ task_id: taskId }) => taskId);
93
+ if (new Set(taskIds).size !== taskIds.length) return reject(['duplicate_task_id']);
94
+
95
+ const ownedByTask = new Map();
96
+ for (const taskId of taskIds) {
97
+ const symbols = sortedUnique(ownedSymbolsByTask?.[taskId] ?? []);
98
+ // 宣言の無いtaskがある構成は、その所有面を作れない。片側の宣言から他方を補完しない。
99
+ if (symbols.length === 0) return reject([`owned_symbols_missing:${taskId}`]);
100
+ ownedByTask.set(taskId, symbols);
101
+ }
102
+ const ownedSymbols = sortedUnique([...ownedByTask.values()].flat());
103
+ const declaredCount = [...ownedByTask.values()].reduce((total, list) => total + list.length, 0);
104
+ if (ownedSymbols.length !== declaredCount) return reject(['owned_symbol_claimed_twice']);
105
+
106
+ const closure = collectSharedClosure({ sourcePath, ownedSymbols, calleesBySymbol });
107
+ // 閉包が閉じていない。呼び出し側は不足分のcalleeを引いてから導出をやり直す。
108
+ if (closure.missing.length > 0) {
109
+ return reject(closure.missing.map((symbol) => `callee_data_missing:${symbol}`));
110
+ }
111
+ const sharedSymbols = closure.shared;
112
+ if (sharedSymbols.length > 0 && !isTodoRef(sharedPath)) return reject(['invalid_shared_path']);
113
+ const violations = sharedDependsOnOwned({
114
+ sourcePath, ownedSymbols, sharedSymbols, calleesBySymbol,
115
+ });
116
+ if (violations.length > 0) {
117
+ return reject(violations.map((edge) => `shared_depends_on_owned:${edge}`));
118
+ }
119
+
120
+ const surfaces = [];
121
+ for (const taskId of [...taskIds].sort(compareText)) {
122
+ const path = proposedPathByTask?.[taskId];
123
+ if (!isTodoRef(path)) return reject([`invalid_owned_path:${taskId}`]);
124
+ surfaces.push(surfaceEntry('task_owned', path, [taskId], ownedByTask.get(taskId)));
125
+ }
126
+ if (sharedSymbols.length > 0) {
127
+ surfaces.push(surfaceEntry('shared', sharedPath, [], sharedSymbols));
128
+ }
129
+ // 残余はsymbolを列挙しない。移らなかったものすべてという補集合であり、
130
+ // 列挙すると原fileの全symbol目録を導出の入力に持ち込むことになる。
131
+ surfaces.push(surfaceEntry('residual', sourcePath, [], []));
132
+
133
+ const paths = surfaces.map(({ path }) => path);
134
+ if (new Set(paths).size !== paths.length) return reject(['surface_path_collision']);
135
+
136
+ const candidate = {
137
+ schema: BOUNDED_SEAM_CANDIDATE_SCHEMA,
138
+ candidate_id: candidateId,
139
+ base_sha: baseSha,
140
+ manifest_digest: manifestDigest,
141
+ finding_digest: findingDigest,
142
+ source_path: sourcePath,
143
+ todo_refs: [...taskRefs]
144
+ .map(({ plan_key: planKey, task_id: taskId }) => ({ plan_key: planKey, task_id: taskId }))
145
+ .sort((left, right) => compareText(
146
+ `${left.plan_key}\0${left.task_id}`, `${right.plan_key}\0${right.task_id}`,
147
+ )),
148
+ surfaces: surfaces.sort((left, right) => compareText(left.path, right.path)),
149
+ allowed_paths: sortedUnique(paths),
150
+ // 原pathと所有面は必ず変わる。変わっていなければ変換が起きていない。
151
+ required_paths: sortedUnique([sourcePath, ...surfaces
152
+ .filter(({ role }) => role === 'task_owned').map(({ path }) => path)]),
153
+ verification_policy: {
154
+ focused_test_refs: sortedUnique(affectedTests),
155
+ require_behavior_equivalence: true,
156
+ require_fresh_sensor: true,
157
+ require_overlap_reduction: true,
158
+ // ADR 0138。局所の競合を消して全体の競合を増やす変換と、
159
+ // 競合は消えるが波数が変わらない変換を採用しない。
160
+ require_no_new_conflict_pairs: true,
161
+ require_parallelism_improvement: true,
162
+ },
163
+ candidate_digest: '',
164
+ };
165
+ if (!isTodoIdentifier(candidate.candidate_id)) return reject(['invalid_candidate_id']);
166
+ candidate.candidate_digest = todoSelfDigest(candidate, 'candidate_digest');
167
+ return { candidate, reasons: [] };
168
+ }
169
+
170
+ /**
171
+ * 導出に要るsensor query set。宣言symbolのcalleeだけを引く。
172
+ *
173
+ * pathのconflictはaffected testしか観測していないので、同一file内の依存は別途引く必要がある
174
+ * (ADR 0133が「pathの競合には分割すべきcall graphが無い」と述べた面)。
175
+ */
176
+ export function buildSeamDerivationQuerySet(concernSymbols = []) {
177
+ const symbols = sortedUnique(concernSymbols);
178
+ return {
179
+ queries: [
180
+ { id: 'seam-derive-status', operation: 'status' },
181
+ ...symbols.map((symbol, index) => ({
182
+ id: `seam-derive-callees-${String(index).padStart(3, '0')}`,
183
+ operation: 'callees',
184
+ target: symbol,
185
+ })),
186
+ ],
187
+ };
188
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * 三面の変換候補を実際のソースへ適用する書き換え(ADR 0137)。
3
+ *
4
+ * 決まった移動を機械的に実行するだけである。どこへ何を移すかはseam導出が決めており、
5
+ * 「どう書くのが綺麗か」の裁量は持ち込まない。整形の判断を入れると、変換の前後で挙動以外の差が
6
+ * 増え、外部挙動同等性の検証が何を見ているのか分からなくなる。
7
+ *
8
+ * 純関数として組む。worktreeへ書くのは呼び出し側の仕事で、ここはtextからtextを作る。
9
+ */
10
+
11
+ const IMPORT_START = /^import[\s{*]/u;
12
+ const COMMENT_LINE = /^\s*(?:\/\/|\/\*|\*|\*\/)/u;
13
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
14
+
15
+ function fail(reasons) {
16
+ return { files: null, reasons: [...new Set(reasons)].sort(compareText) };
17
+ }
18
+
19
+ /**
20
+ * 先頭のimport文を、行範囲と束縛名つきで取り出す。
21
+ *
22
+ * 複数行importがあるので`from '...'`で終わる行までを1文とする。束縛名は、移した先で
23
+ * どのimportが要るかを語単位で判定するために使う。
24
+ */
25
+ export function scanImportStatements(lines) {
26
+ const statements = [];
27
+ let index = 0;
28
+ while (index < lines.length) {
29
+ const line = lines[index];
30
+ if (line.trim() === '' || COMMENT_LINE.test(line)) { index += 1; continue; }
31
+ if (!IMPORT_START.test(line)) break;
32
+ const start = index;
33
+ while (index < lines.length
34
+ && !/from\s+['"][^'"]+['"];?\s*$/u.test(lines[index])
35
+ && !/^import\s+['"][^'"]+['"];?\s*$/u.test(lines[index])) index += 1;
36
+ const end = Math.min(index, lines.length - 1);
37
+ const text = lines.slice(start, end + 1).join('\n');
38
+ statements.push({ text, bindings: importBindings(text), start, end });
39
+ index = end + 1;
40
+ }
41
+ return { statements, endIndex: statements.length === 0 ? -1 : statements.at(-1).end };
42
+ }
43
+
44
+ function importBindings(text) {
45
+ const bindings = [];
46
+ const namespace = /import\s+\*\s+as\s+([A-Za-z_$][\w$]*)/u.exec(text);
47
+ if (namespace) bindings.push(namespace[1]);
48
+ const defaultBinding = /^import\s+([A-Za-z_$][\w$]*)\s*(?:,|\sfrom)/u.exec(text);
49
+ if (defaultBinding) bindings.push(defaultBinding[1]);
50
+ const named = /\{([\s\S]*?)\}/u.exec(text);
51
+ if (named) {
52
+ for (const entry of named[1].split(',')) {
53
+ const parts = entry.split(/\s+as\s+/u).map((part) => part.trim());
54
+ const name = parts.length > 1 ? parts[1] : parts[0];
55
+ if (/^[A-Za-z_$][\w$]*$/u.test(name)) bindings.push(name);
56
+ }
57
+ }
58
+ return [...new Set(bindings)];
59
+ }
60
+
61
+ /** 語として現れるか。string中やcomment中の一致も拾うが、余分なimportは害にならない。 */
62
+ function mentions(text, name) {
63
+ return new RegExp(`(?<![\\w$])${name.replace(/[$]/gu, '\\$$')}(?![\\w$])`, 'u').test(text);
64
+ }
65
+
66
+ /**
67
+ * 宣言の範囲を直前の連続コメント行まで広げる。
68
+ *
69
+ * JSDocを置き去りにすると、残余に持ち主のいない説明が残り、移した先が無説明になる。
70
+ * 空行で切るのは、離れた位置のコメントを巻き込まないため。
71
+ */
72
+ function extendUpward(lines, startLine) {
73
+ let start = startLine;
74
+ while (start - 1 >= 1 && COMMENT_LINE.test(lines[start - 2])) start -= 1;
75
+ return start;
76
+ }
77
+
78
+ function exportedBlock(raw) {
79
+ const parts = raw.split('\n');
80
+ const declarationIndex = parts
81
+ .findIndex((line) => !COMMENT_LINE.test(line) && line.trim() !== '');
82
+ if (declarationIndex >= 0 && !/^\s*export\s/u.test(parts[declarationIndex])) {
83
+ parts[declarationIndex] = `export ${parts[declarationIndex]}`;
84
+ }
85
+ return parts.join('\n');
86
+ }
87
+
88
+ function relativeSpecifier(fromPath, toPath) {
89
+ const fromDir = fromPath.slice(0, fromPath.lastIndexOf('/') + 1);
90
+ return toPath.startsWith(fromDir) ? `./${toPath.slice(fromDir.length)}` : `./${toPath}`;
91
+ }
92
+
93
+ /**
94
+ * 三面の変換後textを作る。
95
+ *
96
+ * @param {object} options
97
+ * @param {string} options.sourceText 原pathの現在の内容
98
+ * @param {object} options.candidate `lattice.bounded_seam_candidate.v2`
99
+ * @param {object} options.symbolExtents symbol名 -> `{startLine, endLine}`(1始まり・両端含む)
100
+ * @returns {{files: object|null, reasons: string[]}} pathごとの変換後text
101
+ */
102
+ export function planSeamRewrite({ sourceText, candidate, symbolExtents } = {}) {
103
+ if (typeof sourceText !== 'string' || sourceText.length === 0) return fail(['empty_source']);
104
+ const lines = sourceText.split('\n');
105
+ const surfaces = candidate?.surfaces ?? [];
106
+ const residual = surfaces.find(({ role }) => role === 'residual');
107
+ const moving = surfaces.filter(({ role }) => role !== 'residual');
108
+ if (residual === undefined || moving.length === 0) return fail(['surfaces_incomplete']);
109
+
110
+ const blocks = [];
111
+ for (const surface of moving) {
112
+ for (const symbol of surface.symbols) {
113
+ const extent = symbolExtents?.[symbol];
114
+ if (extent === undefined
115
+ || !Number.isSafeInteger(extent.startLine) || !Number.isSafeInteger(extent.endLine)
116
+ || extent.startLine < 1 || extent.endLine > lines.length
117
+ || extent.endLine < extent.startLine) {
118
+ return fail([`symbol_extent_missing:${symbol}`]);
119
+ }
120
+ blocks.push({
121
+ symbol, path: surface.path, end: extent.endLine,
122
+ start: extendUpward(lines, extent.startLine),
123
+ });
124
+ }
125
+ }
126
+ blocks.sort((left, right) => left.start - right.start);
127
+ for (let index = 1; index < blocks.length; index += 1) {
128
+ // 範囲が重なる宣言は、片方を切ると他方が壊れる。整形で解こうとせず止める。
129
+ if (blocks[index].start <= blocks[index - 1].end) {
130
+ return fail([`symbol_extent_overlap:${blocks[index - 1].symbol}:${blocks[index].symbol}`]);
131
+ }
132
+ }
133
+
134
+ const { statements, endIndex } = scanImportStatements(lines);
135
+ if (blocks.some((block) => block.start <= endIndex + 1)) {
136
+ return fail(['symbol_inside_import_block']);
137
+ }
138
+
139
+ const bodyByPath = new Map();
140
+ const removal = new Set();
141
+ for (const block of blocks) {
142
+ const raw = lines.slice(block.start - 1, block.end).join('\n');
143
+ if (!bodyByPath.has(block.path)) bodyByPath.set(block.path, []);
144
+ bodyByPath.get(block.path).push(exportedBlock(raw));
145
+ for (let line = block.start; line <= block.end; line += 1) removal.add(line);
146
+ }
147
+
148
+ const symbolPath = new Map(blocks.map((block) => [block.symbol, block.path]));
149
+ const importsFor = (ownerPath, body) => {
150
+ const carried = statements
151
+ .filter((statement) => statement.bindings.some((name) => mentions(body, name)))
152
+ .map((statement) => statement.text);
153
+ const byTarget = new Map();
154
+ for (const [symbol, targetPath] of symbolPath) {
155
+ if (targetPath === ownerPath || !mentions(body, symbol)) continue;
156
+ if (!byTarget.has(targetPath)) byTarget.set(targetPath, []);
157
+ byTarget.get(targetPath).push(symbol);
158
+ }
159
+ const cross = [...byTarget.entries()]
160
+ .sort(([left], [right]) => compareText(left, right))
161
+ .map(([targetPath, names]) => `import { ${[...names].sort(compareText).join(', ')} } from '${relativeSpecifier(ownerPath, targetPath)}';`);
162
+ return [...carried, ...cross];
163
+ };
164
+
165
+ const files = {};
166
+ for (const [path, bodies] of bodyByPath) {
167
+ const body = bodies.join('\n\n');
168
+ const header = importsFor(path, body);
169
+ files[path] = `${header.length === 0 ? '' : `${header.join('\n')}\n\n`}${body}\n`;
170
+ }
171
+
172
+ const keptHeader = lines.slice(0, endIndex + 1);
173
+ const keptBody = lines.slice(endIndex + 1)
174
+ .filter((_, index) => !removal.has(endIndex + 2 + index));
175
+ const residualBody = keptBody.join('\n').replace(/\n{3,}/gu, '\n\n').replace(/\n+$/u, '');
176
+ const residualCross = importsFor(residual.path, residualBody)
177
+ .filter((statement) => !keptHeader.join('\n').includes(statement));
178
+ files[residual.path] = `${[...keptHeader, ...residualCross].join('\n')}\n${residualBody}\n`
179
+ .replace(/^\n+/u, '');
180
+
181
+ return { files, reasons: [] };
182
+ }