@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
@@ -1,409 +1,409 @@
1
- import {
2
- lstat,
3
- mkdtemp,
4
- readdir,
5
- readFile,
6
- mkdir,
7
- readlink,
8
- rm,
9
- symlink,
10
- } from 'node:fs/promises';
11
- import os from 'node:os';
12
- import path from 'node:path';
13
- import { spawn } from 'node:child_process';
14
- import { createHash } from 'node:crypto';
15
-
16
- function run(command, args, { cwd, allowExitCodes = [0], env } = {}) {
17
- return new Promise((resolve, reject) => {
18
- const child = spawn(command, args, {
19
- cwd,
20
- shell: false,
21
- stdio: ['ignore', 'pipe', 'pipe'],
22
- ...(env === undefined ? {} : { env }),
23
- });
24
- const stdout = [];
25
- const stderr = [];
26
- child.stdout.on('data', (chunk) => stdout.push(chunk));
27
- child.stderr.on('data', (chunk) => stderr.push(chunk));
28
- child.once('error', reject);
29
- child.once('close', (code, signal) => {
30
- const result = { code, signal, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) };
31
- if (allowExitCodes.includes(code) && signal === null) resolve(result);
32
- else reject(Object.assign(new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`), result));
33
- });
34
- });
35
- }
36
-
37
- function bufferDigest(value) {
38
- return createHash('sha256').update(value).digest('hex');
39
- }
40
-
41
- const PROTECTED_PATHS = Object.freeze(['src', 'test']);
42
-
43
- function verificationReceipt(verifier, result, outcome) {
44
- const stdout = Buffer.isBuffer(result?.stdout) ? result.stdout : Buffer.alloc(0);
45
- const stderr = Buffer.isBuffer(result?.stderr) ? result.stderr : Buffer.alloc(0);
46
- return {
47
- command: verifier.command,
48
- args: [...verifier.args],
49
- outcome,
50
- exit_code: Number.isSafeInteger(result?.code) && result.code >= 0 ? result.code : 1,
51
- stdout_digest: bufferDigest(stdout),
52
- stderr_digest: bufferDigest(stderr),
53
- };
54
- }
55
-
56
- function verifierEnvironment(extra = {}) {
57
- const env = { ...process.env, NO_COLOR: '1', ...extra };
58
- delete env.NODE_TEST_CONTEXT;
59
- delete env.FORCE_COLOR;
60
- return env;
61
- }
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
-
68
- function safeRelativePath(value) {
69
- return typeof value === 'string'
70
- && value.length > 0
71
- && !value.includes('\0')
72
- && !path.posix.isAbsolute(value)
73
- && value === path.posix.normalize(value)
74
- && !value.split('/').includes('..');
75
- }
76
-
77
- function isAllowed(changedPath, allowedPaths) {
78
- return allowedPaths.some((allowedPath) => changedPath === allowedPath || changedPath.startsWith(`${allowedPath}/`));
79
- }
80
-
81
- function statusPaths(status) {
82
- const fields = status.toString('utf8').split('\0');
83
- const paths = [];
84
- for (let index = 0; index < fields.length - 1; index += 1) {
85
- const entry = fields[index];
86
- if (!entry) continue;
87
- const code = entry.slice(0, 2);
88
- paths.push(entry.slice(3));
89
- if (code[0] === 'R' || code[0] === 'C') paths.push(fields[++index]);
90
- }
91
- return [...new Set(paths)].sort();
92
- }
93
-
94
- async function rejectUnsafeEntry(worktreePath, baseSha, changedPath) {
95
- const segments = changedPath.split('/');
96
- for (let index = 1; index <= segments.length; index += 1) {
97
- const candidate = path.join(worktreePath, ...segments.slice(0, index));
98
- try {
99
- const stat = await lstat(candidate);
100
- if (stat.isSymbolicLink()) throw new Error(`symlink change is not allowed: ${changedPath}`);
101
- if (index === segments.length && !stat.isFile()) throw new Error(`special file change is not allowed: ${changedPath}`);
102
- } catch (error) {
103
- if (error?.code !== 'ENOENT') throw error;
104
- }
105
- }
106
- const tree = await run('git', ['ls-tree', '-z', baseSha, '--', changedPath], { cwd: worktreePath });
107
- if (tree.stdout.length > 0) {
108
- const mode = tree.stdout.toString('utf8').slice(0, 6);
109
- if (mode === '120000') throw new Error(`symlink change is not allowed: ${changedPath}`);
110
- if (mode === '160000') throw new Error(`submodule change is not allowed: ${changedPath}`);
111
- if (mode !== '100644' && mode !== '100755') throw new Error(`special file change is not allowed: ${changedPath}`);
112
- }
113
- }
114
-
115
- async function buildPatch(worktreePath, changedPaths) {
116
- const tracked = await run('git', ['diff', '--binary', 'HEAD'], { cwd: worktreePath });
117
- const parts = [tracked.stdout];
118
- for (const changedPath of changedPaths) {
119
- const trackedPath = await run('git', ['ls-files', '--error-unmatch', '--', changedPath], {
120
- cwd: worktreePath,
121
- allowExitCodes: [0, 1],
122
- });
123
- if (trackedPath.code === 0) continue;
124
- const added = await run('git', ['diff', '--binary', '--no-index', '--', '/dev/null', changedPath], {
125
- cwd: worktreePath,
126
- allowExitCodes: [0, 1],
127
- });
128
- if (added.stdout.length > 0) parts.push(added.stdout);
129
- }
130
- return Buffer.concat(parts);
131
- }
132
-
133
- /**
134
- * mountのために作った親dirが1エントリで報告されたら、除外せず展開して子を同じ規律で見る。
135
- *
136
- * 親ごと除外すると、その中に現れた別の変更まで隠れる。runnerが張ったmountだけを外す規律を、
137
- * ディレクトリ単位の報告でも保つ。
138
- */
139
- async function expandMountAncestors(worktreePath, paths, mountedEntries) {
140
- const isAncestor = (entry) => mountedEntries
141
- .some((mount) => mount.startsWith(`${entry}/`));
142
- const expanded = [];
143
- const pending = [...paths];
144
- while (pending.length > 0) {
145
- const current = pending.pop();
146
- const normalized = current.replace(/\/$/u, '');
147
- if (!current.endsWith('/') || !isAncestor(normalized)) { expanded.push(current); continue; }
148
- const children = await readdir(path.join(worktreePath, normalized), { withFileTypes: true });
149
- for (const child of children) {
150
- pending.push(`${normalized}/${child.name}${child.isDirectory() ? '/' : ''}`);
151
- }
152
- }
153
- return [...new Set(expanded)].sort();
154
- }
155
-
156
- async function captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries = []) {
157
- const mounted = new Set(mountedEntries);
158
- const reported = statusPaths((await run('git', [
159
- 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching',
160
- ], { cwd: worktreePath })).stdout);
161
- const changedPaths = (await expandMountAncestors(worktreePath, reported, [...mounted]))
162
- // runnerが張ったmountだけを外す。それ以外は無視しない——gitignore対象であっても、
163
- // allowed pathの外に現れたものは変更である。
164
- .filter((changedPath) => {
165
- const normalized = changedPath.replace(/\/$/u, '');
166
- return ![...mounted].some((entry) => normalized === entry || normalized.startsWith(`${entry}/`));
167
- });
168
- for (const changedPath of changedPaths) {
169
- if (!safeRelativePath(changedPath) || !isAllowed(changedPath, allowedPaths)) {
170
- throw new Error(`change outside allowed paths: ${changedPath}`);
171
- }
172
- await rejectUnsafeEntry(worktreePath, baseSha, changedPath);
173
- }
174
- return { changedPaths, patch: await buildPatch(worktreePath, changedPaths) };
175
- }
176
-
177
- async function assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, expected, actor, mountedEntries = []) {
178
- const actual = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
179
- if (actual.changedPaths.length !== expected.changedPaths.length
180
- || actual.changedPaths.some((changedPath, index) => changedPath !== expected.changedPaths[index])
181
- || !actual.patch.equals(expected.patch)) {
182
- throw new Error(`${actor} mutated isolated snapshot`);
183
- }
184
- }
185
-
186
- async function fingerprintEntry(repoRoot, relativePath, records) {
187
- const absolutePath = path.join(repoRoot, relativePath);
188
- let stat;
189
- try {
190
- stat = await lstat(absolutePath);
191
- } catch (error) {
192
- if (error?.code === 'ENOENT') {
193
- records.push({ path: relativePath, type: 'missing', content_digest: null });
194
- return;
195
- }
196
- throw error;
197
- }
198
- if (stat.isDirectory()) {
199
- records.push({ path: relativePath, type: 'directory', content_digest: null });
200
- const entries = await readdir(absolutePath, { withFileTypes: true });
201
- entries.sort((left, right) => left.name.localeCompare(right.name));
202
- for (const entry of entries) {
203
- await fingerprintEntry(repoRoot, path.posix.join(relativePath, entry.name), records);
204
- }
205
- return;
206
- }
207
- if (stat.isFile()) {
208
- records.push({
209
- path: relativePath,
210
- type: 'file',
211
- content_digest: bufferDigest(await readFile(absolutePath)),
212
- });
213
- return;
214
- }
215
- if (stat.isSymbolicLink()) {
216
- records.push({
217
- path: relativePath,
218
- type: 'symlink',
219
- content_digest: bufferDigest(Buffer.from(await readlink(absolutePath), 'utf8')),
220
- });
221
- return;
222
- }
223
- records.push({ path: relativePath, type: 'special', content_digest: null });
224
- }
225
-
226
- async function protectedFingerprint(repoRoot) {
227
- const records = [];
228
- for (const protectedPath of PROTECTED_PATHS) {
229
- await fingerprintEntry(repoRoot, protectedPath, records);
230
- }
231
- return {
232
- digest: bufferDigest(Buffer.from(JSON.stringify(records), 'utf8')),
233
- entry_count: records.length,
234
- };
235
- }
236
-
237
- async function captureSourceState(repoRoot) {
238
- const [head, visibleStatus, ignoredStatus, protectedContent] = await Promise.all([
239
- run('git', ['rev-parse', 'HEAD'], { cwd: repoRoot }),
240
- run('git', ['status', '--porcelain=v1', '-z'], { cwd: repoRoot }),
241
- run('git', [
242
- 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching',
243
- ], { cwd: repoRoot }),
244
- protectedFingerprint(repoRoot),
245
- ]);
246
- return {
247
- head: head.stdout.toString('utf8').trim(),
248
- visibleStatus: visibleStatus.stdout,
249
- ignoredStatus: ignoredStatus.stdout,
250
- protectedContent,
251
- };
252
- }
253
-
254
- function sourceInvariantComparison(before, after) {
255
- const compareBuffers = (left, right) => ({
256
- before_digest: bufferDigest(left),
257
- after_digest: bufferDigest(right),
258
- equal: left.equals(right),
259
- });
260
- const receipt = {
261
- schema: 'lattice.source_invariant_receipt.v1',
262
- protected_paths: [...PROTECTED_PATHS],
263
- outcome: 'passed',
264
- head: {
265
- before: before.head,
266
- after: after.head,
267
- equal: before.head === after.head,
268
- },
269
- visible_status: compareBuffers(before.visibleStatus, after.visibleStatus),
270
- ignored_paths: compareBuffers(before.ignoredStatus, after.ignoredStatus),
271
- protected_content: {
272
- before_digest: before.protectedContent.digest,
273
- after_digest: after.protectedContent.digest,
274
- before_entry_count: before.protectedContent.entry_count,
275
- after_entry_count: after.protectedContent.entry_count,
276
- equal: before.protectedContent.digest === after.protectedContent.digest,
277
- },
278
- };
279
- receipt.outcome = [
280
- receipt.head.equal,
281
- receipt.visible_status.equal,
282
- receipt.ignored_paths.equal,
283
- receipt.protected_content.equal,
284
- ].every(Boolean) ? 'passed' : 'failed';
285
- return receipt;
286
- }
287
-
288
- async function assertSourceUnchanged(repoRoot, sourceState) {
289
- const receipt = sourceInvariantComparison(sourceState, await captureSourceState(repoRoot));
290
- if (receipt.outcome !== 'passed') {
291
- const error = new Error('source repository changed during isolated transform');
292
- error.sourceInvariant = receipt;
293
- throw error;
294
- }
295
- return receipt;
296
- }
297
-
298
- export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, transform, verifyCommands, observe, mounts = [], verifierEnv = {} } = {}) {
299
- if (!safeRelativePath('.') || typeof repoRoot !== 'string' || typeof baseRef !== 'string'
300
- || !Array.isArray(allowedPaths) || allowedPaths.some((entry) => !safeRelativePath(entry))
301
- || typeof transform !== 'function' || !Array.isArray(verifyCommands)
302
- || (observe !== undefined && typeof observe !== 'function')
303
- || !isPlainStringRecord(verifierEnv)
304
- || !Array.isArray(mounts)
305
- || mounts.some(({ entry, target } = {}) => typeof entry !== 'string'
306
- || !safeRelativePath(entry) || typeof target !== 'string' || !path.isAbsolute(target))) {
307
- throw new TypeError('invalid isolated transform arguments');
308
- }
309
- // mountはrunnerが自分で張り、自分が張ったentryだけをsnapshotから外す。呼び出し側が
310
- // transformの中で作ると、任意の変更をsnapshotから隠す口になる。
311
- const mountedEntries = mounts.map(({ entry }) => entry);
312
-
313
- const sourceState = await captureSourceState(repoRoot);
314
- if (sourceState.visibleStatus.length > 0) {
315
- // どのpathが汚しているかを言わないと、呼び出したAIは何を片付ければよいか分からない。
316
- // 実運用で、このコマンドへ渡す入力fileそのものが木を汚して詰まった。
317
- // visibleStatusはNUL区切りのBufferである。行として扱うと空文字が並ぶ。
318
- const entries = statusPaths(sourceState.visibleStatus).slice(0, 20);
319
- throw new Error('source repository must be clean :: '
320
- + `${entries.join(' | ')} :: 変換は既知のbaseに対して測る。commitするか、`
321
- + 'gitが無視するpathへ退避してから再実行する');
322
- }
323
- const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot })).stdout.toString('utf8').trim();
324
- const worktreePath = await mkdtemp(path.join(os.tmpdir(), 'lattice-isolated-transform-'));
325
- let added = false;
326
- let primaryError;
327
- let result;
328
- let snapshot;
329
- let sourceInvariant;
330
- const verifications = [];
331
- try {
332
- await run('git', ['worktree', 'add', '--detach', worktreePath, baseSha], { cwd: repoRoot });
333
- added = true;
334
- for (const { entry, target } of mounts) {
335
- // 保護pathへはmountさせない。そこを許すと、変更をsnapshotから隠す口になる。
336
- if (PROTECTED_PATHS.includes(entry.split('/')[0])) {
337
- throw new Error(`mount over protected path is not allowed: ${entry}`);
338
- }
339
- const mountPath = path.join(worktreePath, entry);
340
- await mkdir(path.dirname(mountPath), { recursive: true });
341
- // base checkoutが同名を持つ場合がある(trackedな.gitignore等)。mount配下は
342
- // まるごとsnapshotの対象外になるので、置き換えても判定の抜けは生まれない。
343
- await rm(mountPath, { recursive: true, force: true });
344
- await symlink(target, mountPath);
345
- }
346
- await transform({ worktreePath });
347
- snapshot = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
348
- for (const verifier of verifyCommands) {
349
- if (!verifier || typeof verifier.command !== 'string' || !Array.isArray(verifier.args) || verifier.args.some((arg) => typeof arg !== 'string')) {
350
- throw new TypeError('verifyCommands must contain command and string args');
351
- }
352
- try {
353
- const verification = await run(verifier.command, verifier.args, {
354
- cwd: worktreePath,
355
- env: verifierEnvironment(verifierEnv),
356
- });
357
- verifications.push(verificationReceipt(verifier, verification, 'passed'));
358
- } catch (error) {
359
- verifications.push(verificationReceipt(verifier, error, 'failed'));
360
- // どのverifierがなぜ落ちたかを載せる。commandだけ返すと、五条件の棄却理由が
361
- // 「focused testが落ちた」で止まり、原因を追う手段が無くなる。
362
- // stdout/stderrはBufferで、空でもtruthyになる。`||`で繋ぐとstdoutへ落ちない。
363
- // node --testは失敗をstdoutへ書くので、それを取り落とすと理由が消える。
364
- const streams = [error?.stderr, error?.stdout]
365
- .map((value) => (value === undefined ? '' : String(value)))
366
- .filter((value) => value.trim().length > 0);
367
- const detail = (streams[0] ?? '')
368
- .split('\n').filter((line) => line.trim().length > 0).slice(-6).join(' | ').slice(0, 600);
369
- throw new Error(`verifier failed (${error.signal ?? error.code}):`
370
- + ` ${[verifier.command, ...verifier.args].join(' ')}`
371
- + (detail.length > 0 ? ` :: ${detail}` : ''));
372
- }
373
- await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'verifier', mountedEntries);
374
- }
375
- if (observe) {
376
- await observe({ worktreePath, changedPaths: snapshot.changedPaths, patch: snapshot.patch, baseSha });
377
- await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'observe', mountedEntries);
378
- }
379
- result = { baseSha, ...snapshot, verifications };
380
- } catch (error) {
381
- primaryError = error;
382
- }
383
- let cleanupError;
384
- try {
385
- if (added) await run('git', ['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot });
386
- await rm(worktreePath, { recursive: true, force: true });
387
- } catch (error) {
388
- cleanupError = new Error(`cleanup failed: ${error.message}`);
389
- }
390
- let sourceInvariantError;
391
- try {
392
- sourceInvariant = await assertSourceUnchanged(repoRoot, sourceState);
393
- } catch (error) {
394
- sourceInvariant = error.sourceInvariant;
395
- sourceInvariantError = error;
396
- }
397
- const errors = [primaryError, cleanupError, sourceInvariantError].filter(Boolean);
398
- const transformEvidence = {
399
- baseSha,
400
- changedPaths: snapshot ? [...snapshot.changedPaths] : [],
401
- patch: snapshot ? Buffer.from(snapshot.patch) : null,
402
- verifications: structuredClone(verifications),
403
- sourceInvariant: sourceInvariant ? structuredClone(sourceInvariant) : null,
404
- };
405
- for (const error of errors) error.transformEvidence = transformEvidence;
406
- if (errors.length === 1) throw errors[0];
407
- if (errors.length > 1) throw new AggregateError(errors, 'isolated transform failed; source repository changed or cleanup failed');
408
- return { ...result, sourceInvariant };
409
- }
1
+ import {
2
+ lstat,
3
+ mkdtemp,
4
+ readdir,
5
+ readFile,
6
+ mkdir,
7
+ readlink,
8
+ rm,
9
+ symlink,
10
+ } from 'node:fs/promises';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { spawn } from 'node:child_process';
14
+ import { createHash } from 'node:crypto';
15
+
16
+ function run(command, args, { cwd, allowExitCodes = [0], env } = {}) {
17
+ return new Promise((resolve, reject) => {
18
+ const child = spawn(command, args, {
19
+ cwd,
20
+ shell: false,
21
+ stdio: ['ignore', 'pipe', 'pipe'],
22
+ ...(env === undefined ? {} : { env }),
23
+ });
24
+ const stdout = [];
25
+ const stderr = [];
26
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
27
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
28
+ child.once('error', reject);
29
+ child.once('close', (code, signal) => {
30
+ const result = { code, signal, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) };
31
+ if (allowExitCodes.includes(code) && signal === null) resolve(result);
32
+ else reject(Object.assign(new Error(`${command} failed (${signal ?? code}): ${result.stderr.toString('utf8').trim()}`), result));
33
+ });
34
+ });
35
+ }
36
+
37
+ function bufferDigest(value) {
38
+ return createHash('sha256').update(value).digest('hex');
39
+ }
40
+
41
+ const PROTECTED_PATHS = Object.freeze(['src', 'test']);
42
+
43
+ function verificationReceipt(verifier, result, outcome) {
44
+ const stdout = Buffer.isBuffer(result?.stdout) ? result.stdout : Buffer.alloc(0);
45
+ const stderr = Buffer.isBuffer(result?.stderr) ? result.stderr : Buffer.alloc(0);
46
+ return {
47
+ command: verifier.command,
48
+ args: [...verifier.args],
49
+ outcome,
50
+ exit_code: Number.isSafeInteger(result?.code) && result.code >= 0 ? result.code : 1,
51
+ stdout_digest: bufferDigest(stdout),
52
+ stderr_digest: bufferDigest(stderr),
53
+ };
54
+ }
55
+
56
+ function verifierEnvironment(extra = {}) {
57
+ const env = { ...process.env, NO_COLOR: '1', ...extra };
58
+ delete env.NODE_TEST_CONTEXT;
59
+ delete env.FORCE_COLOR;
60
+ return env;
61
+ }
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
+
68
+ function safeRelativePath(value) {
69
+ return typeof value === 'string'
70
+ && value.length > 0
71
+ && !value.includes('\0')
72
+ && !path.posix.isAbsolute(value)
73
+ && value === path.posix.normalize(value)
74
+ && !value.split('/').includes('..');
75
+ }
76
+
77
+ function isAllowed(changedPath, allowedPaths) {
78
+ return allowedPaths.some((allowedPath) => changedPath === allowedPath || changedPath.startsWith(`${allowedPath}/`));
79
+ }
80
+
81
+ function statusPaths(status) {
82
+ const fields = status.toString('utf8').split('\0');
83
+ const paths = [];
84
+ for (let index = 0; index < fields.length - 1; index += 1) {
85
+ const entry = fields[index];
86
+ if (!entry) continue;
87
+ const code = entry.slice(0, 2);
88
+ paths.push(entry.slice(3));
89
+ if (code[0] === 'R' || code[0] === 'C') paths.push(fields[++index]);
90
+ }
91
+ return [...new Set(paths)].sort();
92
+ }
93
+
94
+ async function rejectUnsafeEntry(worktreePath, baseSha, changedPath) {
95
+ const segments = changedPath.split('/');
96
+ for (let index = 1; index <= segments.length; index += 1) {
97
+ const candidate = path.join(worktreePath, ...segments.slice(0, index));
98
+ try {
99
+ const stat = await lstat(candidate);
100
+ if (stat.isSymbolicLink()) throw new Error(`symlink change is not allowed: ${changedPath}`);
101
+ if (index === segments.length && !stat.isFile()) throw new Error(`special file change is not allowed: ${changedPath}`);
102
+ } catch (error) {
103
+ if (error?.code !== 'ENOENT') throw error;
104
+ }
105
+ }
106
+ const tree = await run('git', ['ls-tree', '-z', baseSha, '--', changedPath], { cwd: worktreePath });
107
+ if (tree.stdout.length > 0) {
108
+ const mode = tree.stdout.toString('utf8').slice(0, 6);
109
+ if (mode === '120000') throw new Error(`symlink change is not allowed: ${changedPath}`);
110
+ if (mode === '160000') throw new Error(`submodule change is not allowed: ${changedPath}`);
111
+ if (mode !== '100644' && mode !== '100755') throw new Error(`special file change is not allowed: ${changedPath}`);
112
+ }
113
+ }
114
+
115
+ async function buildPatch(worktreePath, changedPaths) {
116
+ const tracked = await run('git', ['diff', '--binary', 'HEAD'], { cwd: worktreePath });
117
+ const parts = [tracked.stdout];
118
+ for (const changedPath of changedPaths) {
119
+ const trackedPath = await run('git', ['ls-files', '--error-unmatch', '--', changedPath], {
120
+ cwd: worktreePath,
121
+ allowExitCodes: [0, 1],
122
+ });
123
+ if (trackedPath.code === 0) continue;
124
+ const added = await run('git', ['diff', '--binary', '--no-index', '--', '/dev/null', changedPath], {
125
+ cwd: worktreePath,
126
+ allowExitCodes: [0, 1],
127
+ });
128
+ if (added.stdout.length > 0) parts.push(added.stdout);
129
+ }
130
+ return Buffer.concat(parts);
131
+ }
132
+
133
+ /**
134
+ * mountのために作った親dirが1エントリで報告されたら、除外せず展開して子を同じ規律で見る。
135
+ *
136
+ * 親ごと除外すると、その中に現れた別の変更まで隠れる。runnerが張ったmountだけを外す規律を、
137
+ * ディレクトリ単位の報告でも保つ。
138
+ */
139
+ async function expandMountAncestors(worktreePath, paths, mountedEntries) {
140
+ const isAncestor = (entry) => mountedEntries
141
+ .some((mount) => mount.startsWith(`${entry}/`));
142
+ const expanded = [];
143
+ const pending = [...paths];
144
+ while (pending.length > 0) {
145
+ const current = pending.pop();
146
+ const normalized = current.replace(/\/$/u, '');
147
+ if (!current.endsWith('/') || !isAncestor(normalized)) { expanded.push(current); continue; }
148
+ const children = await readdir(path.join(worktreePath, normalized), { withFileTypes: true });
149
+ for (const child of children) {
150
+ pending.push(`${normalized}/${child.name}${child.isDirectory() ? '/' : ''}`);
151
+ }
152
+ }
153
+ return [...new Set(expanded)].sort();
154
+ }
155
+
156
+ async function captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries = []) {
157
+ const mounted = new Set(mountedEntries);
158
+ const reported = statusPaths((await run('git', [
159
+ 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching',
160
+ ], { cwd: worktreePath })).stdout);
161
+ const changedPaths = (await expandMountAncestors(worktreePath, reported, [...mounted]))
162
+ // runnerが張ったmountだけを外す。それ以外は無視しない——gitignore対象であっても、
163
+ // allowed pathの外に現れたものは変更である。
164
+ .filter((changedPath) => {
165
+ const normalized = changedPath.replace(/\/$/u, '');
166
+ return ![...mounted].some((entry) => normalized === entry || normalized.startsWith(`${entry}/`));
167
+ });
168
+ for (const changedPath of changedPaths) {
169
+ if (!safeRelativePath(changedPath) || !isAllowed(changedPath, allowedPaths)) {
170
+ throw new Error(`change outside allowed paths: ${changedPath}`);
171
+ }
172
+ await rejectUnsafeEntry(worktreePath, baseSha, changedPath);
173
+ }
174
+ return { changedPaths, patch: await buildPatch(worktreePath, changedPaths) };
175
+ }
176
+
177
+ async function assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, expected, actor, mountedEntries = []) {
178
+ const actual = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
179
+ if (actual.changedPaths.length !== expected.changedPaths.length
180
+ || actual.changedPaths.some((changedPath, index) => changedPath !== expected.changedPaths[index])
181
+ || !actual.patch.equals(expected.patch)) {
182
+ throw new Error(`${actor} mutated isolated snapshot`);
183
+ }
184
+ }
185
+
186
+ async function fingerprintEntry(repoRoot, relativePath, records) {
187
+ const absolutePath = path.join(repoRoot, relativePath);
188
+ let stat;
189
+ try {
190
+ stat = await lstat(absolutePath);
191
+ } catch (error) {
192
+ if (error?.code === 'ENOENT') {
193
+ records.push({ path: relativePath, type: 'missing', content_digest: null });
194
+ return;
195
+ }
196
+ throw error;
197
+ }
198
+ if (stat.isDirectory()) {
199
+ records.push({ path: relativePath, type: 'directory', content_digest: null });
200
+ const entries = await readdir(absolutePath, { withFileTypes: true });
201
+ entries.sort((left, right) => left.name.localeCompare(right.name));
202
+ for (const entry of entries) {
203
+ await fingerprintEntry(repoRoot, path.posix.join(relativePath, entry.name), records);
204
+ }
205
+ return;
206
+ }
207
+ if (stat.isFile()) {
208
+ records.push({
209
+ path: relativePath,
210
+ type: 'file',
211
+ content_digest: bufferDigest(await readFile(absolutePath)),
212
+ });
213
+ return;
214
+ }
215
+ if (stat.isSymbolicLink()) {
216
+ records.push({
217
+ path: relativePath,
218
+ type: 'symlink',
219
+ content_digest: bufferDigest(Buffer.from(await readlink(absolutePath), 'utf8')),
220
+ });
221
+ return;
222
+ }
223
+ records.push({ path: relativePath, type: 'special', content_digest: null });
224
+ }
225
+
226
+ async function protectedFingerprint(repoRoot) {
227
+ const records = [];
228
+ for (const protectedPath of PROTECTED_PATHS) {
229
+ await fingerprintEntry(repoRoot, protectedPath, records);
230
+ }
231
+ return {
232
+ digest: bufferDigest(Buffer.from(JSON.stringify(records), 'utf8')),
233
+ entry_count: records.length,
234
+ };
235
+ }
236
+
237
+ async function captureSourceState(repoRoot) {
238
+ const [head, visibleStatus, ignoredStatus, protectedContent] = await Promise.all([
239
+ run('git', ['rev-parse', 'HEAD'], { cwd: repoRoot }),
240
+ run('git', ['status', '--porcelain=v1', '-z'], { cwd: repoRoot }),
241
+ run('git', [
242
+ 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching',
243
+ ], { cwd: repoRoot }),
244
+ protectedFingerprint(repoRoot),
245
+ ]);
246
+ return {
247
+ head: head.stdout.toString('utf8').trim(),
248
+ visibleStatus: visibleStatus.stdout,
249
+ ignoredStatus: ignoredStatus.stdout,
250
+ protectedContent,
251
+ };
252
+ }
253
+
254
+ function sourceInvariantComparison(before, after) {
255
+ const compareBuffers = (left, right) => ({
256
+ before_digest: bufferDigest(left),
257
+ after_digest: bufferDigest(right),
258
+ equal: left.equals(right),
259
+ });
260
+ const receipt = {
261
+ schema: 'lattice.source_invariant_receipt.v1',
262
+ protected_paths: [...PROTECTED_PATHS],
263
+ outcome: 'passed',
264
+ head: {
265
+ before: before.head,
266
+ after: after.head,
267
+ equal: before.head === after.head,
268
+ },
269
+ visible_status: compareBuffers(before.visibleStatus, after.visibleStatus),
270
+ ignored_paths: compareBuffers(before.ignoredStatus, after.ignoredStatus),
271
+ protected_content: {
272
+ before_digest: before.protectedContent.digest,
273
+ after_digest: after.protectedContent.digest,
274
+ before_entry_count: before.protectedContent.entry_count,
275
+ after_entry_count: after.protectedContent.entry_count,
276
+ equal: before.protectedContent.digest === after.protectedContent.digest,
277
+ },
278
+ };
279
+ receipt.outcome = [
280
+ receipt.head.equal,
281
+ receipt.visible_status.equal,
282
+ receipt.ignored_paths.equal,
283
+ receipt.protected_content.equal,
284
+ ].every(Boolean) ? 'passed' : 'failed';
285
+ return receipt;
286
+ }
287
+
288
+ async function assertSourceUnchanged(repoRoot, sourceState) {
289
+ const receipt = sourceInvariantComparison(sourceState, await captureSourceState(repoRoot));
290
+ if (receipt.outcome !== 'passed') {
291
+ const error = new Error('source repository changed during isolated transform');
292
+ error.sourceInvariant = receipt;
293
+ throw error;
294
+ }
295
+ return receipt;
296
+ }
297
+
298
+ export async function runIsolatedTransform({ repoRoot, baseRef, allowedPaths, transform, verifyCommands, observe, mounts = [], verifierEnv = {} } = {}) {
299
+ if (!safeRelativePath('.') || typeof repoRoot !== 'string' || typeof baseRef !== 'string'
300
+ || !Array.isArray(allowedPaths) || allowedPaths.some((entry) => !safeRelativePath(entry))
301
+ || typeof transform !== 'function' || !Array.isArray(verifyCommands)
302
+ || (observe !== undefined && typeof observe !== 'function')
303
+ || !isPlainStringRecord(verifierEnv)
304
+ || !Array.isArray(mounts)
305
+ || mounts.some(({ entry, target } = {}) => typeof entry !== 'string'
306
+ || !safeRelativePath(entry) || typeof target !== 'string' || !path.isAbsolute(target))) {
307
+ throw new TypeError('invalid isolated transform arguments');
308
+ }
309
+ // mountはrunnerが自分で張り、自分が張ったentryだけをsnapshotから外す。呼び出し側が
310
+ // transformの中で作ると、任意の変更をsnapshotから隠す口になる。
311
+ const mountedEntries = mounts.map(({ entry }) => entry);
312
+
313
+ const sourceState = await captureSourceState(repoRoot);
314
+ if (sourceState.visibleStatus.length > 0) {
315
+ // どのpathが汚しているかを言わないと、呼び出したAIは何を片付ければよいか分からない。
316
+ // 実運用で、このコマンドへ渡す入力fileそのものが木を汚して詰まった。
317
+ // visibleStatusはNUL区切りのBufferである。行として扱うと空文字が並ぶ。
318
+ const entries = statusPaths(sourceState.visibleStatus).slice(0, 20);
319
+ throw new Error('source repository must be clean :: '
320
+ + `${entries.join(' | ')} :: 変換は既知のbaseに対して測る。commitするか、`
321
+ + 'gitが無視するpathへ退避してから再実行する');
322
+ }
323
+ const baseSha = (await run('git', ['rev-parse', '--verify', `${baseRef}^{commit}`], { cwd: repoRoot })).stdout.toString('utf8').trim();
324
+ const worktreePath = await mkdtemp(path.join(os.tmpdir(), 'lattice-isolated-transform-'));
325
+ let added = false;
326
+ let primaryError;
327
+ let result;
328
+ let snapshot;
329
+ let sourceInvariant;
330
+ const verifications = [];
331
+ try {
332
+ await run('git', ['worktree', 'add', '--detach', worktreePath, baseSha], { cwd: repoRoot });
333
+ added = true;
334
+ for (const { entry, target } of mounts) {
335
+ // 保護pathへはmountさせない。そこを許すと、変更をsnapshotから隠す口になる。
336
+ if (PROTECTED_PATHS.includes(entry.split('/')[0])) {
337
+ throw new Error(`mount over protected path is not allowed: ${entry}`);
338
+ }
339
+ const mountPath = path.join(worktreePath, entry);
340
+ await mkdir(path.dirname(mountPath), { recursive: true });
341
+ // base checkoutが同名を持つ場合がある(trackedな.gitignore等)。mount配下は
342
+ // まるごとsnapshotの対象外になるので、置き換えても判定の抜けは生まれない。
343
+ await rm(mountPath, { recursive: true, force: true });
344
+ await symlink(target, mountPath);
345
+ }
346
+ await transform({ worktreePath });
347
+ snapshot = await captureSnapshot(worktreePath, baseSha, allowedPaths, mountedEntries);
348
+ for (const verifier of verifyCommands) {
349
+ if (!verifier || typeof verifier.command !== 'string' || !Array.isArray(verifier.args) || verifier.args.some((arg) => typeof arg !== 'string')) {
350
+ throw new TypeError('verifyCommands must contain command and string args');
351
+ }
352
+ try {
353
+ const verification = await run(verifier.command, verifier.args, {
354
+ cwd: worktreePath,
355
+ env: verifierEnvironment(verifierEnv),
356
+ });
357
+ verifications.push(verificationReceipt(verifier, verification, 'passed'));
358
+ } catch (error) {
359
+ verifications.push(verificationReceipt(verifier, error, 'failed'));
360
+ // どのverifierがなぜ落ちたかを載せる。commandだけ返すと、五条件の棄却理由が
361
+ // 「focused testが落ちた」で止まり、原因を追う手段が無くなる。
362
+ // stdout/stderrはBufferで、空でもtruthyになる。`||`で繋ぐとstdoutへ落ちない。
363
+ // node --testは失敗をstdoutへ書くので、それを取り落とすと理由が消える。
364
+ const streams = [error?.stderr, error?.stdout]
365
+ .map((value) => (value === undefined ? '' : String(value)))
366
+ .filter((value) => value.trim().length > 0);
367
+ const detail = (streams[0] ?? '')
368
+ .split('\n').filter((line) => line.trim().length > 0).slice(-6).join(' | ').slice(0, 600);
369
+ throw new Error(`verifier failed (${error.signal ?? error.code}):`
370
+ + ` ${[verifier.command, ...verifier.args].join(' ')}`
371
+ + (detail.length > 0 ? ` :: ${detail}` : ''));
372
+ }
373
+ await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'verifier', mountedEntries);
374
+ }
375
+ if (observe) {
376
+ await observe({ worktreePath, changedPaths: snapshot.changedPaths, patch: snapshot.patch, baseSha });
377
+ await assertSnapshotUnchanged(worktreePath, baseSha, allowedPaths, snapshot, 'observe', mountedEntries);
378
+ }
379
+ result = { baseSha, ...snapshot, verifications };
380
+ } catch (error) {
381
+ primaryError = error;
382
+ }
383
+ let cleanupError;
384
+ try {
385
+ if (added) await run('git', ['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot });
386
+ await rm(worktreePath, { recursive: true, force: true });
387
+ } catch (error) {
388
+ cleanupError = new Error(`cleanup failed: ${error.message}`);
389
+ }
390
+ let sourceInvariantError;
391
+ try {
392
+ sourceInvariant = await assertSourceUnchanged(repoRoot, sourceState);
393
+ } catch (error) {
394
+ sourceInvariant = error.sourceInvariant;
395
+ sourceInvariantError = error;
396
+ }
397
+ const errors = [primaryError, cleanupError, sourceInvariantError].filter(Boolean);
398
+ const transformEvidence = {
399
+ baseSha,
400
+ changedPaths: snapshot ? [...snapshot.changedPaths] : [],
401
+ patch: snapshot ? Buffer.from(snapshot.patch) : null,
402
+ verifications: structuredClone(verifications),
403
+ sourceInvariant: sourceInvariant ? structuredClone(sourceInvariant) : null,
404
+ };
405
+ for (const error of errors) error.transformEvidence = transformEvidence;
406
+ if (errors.length === 1) throw errors[0];
407
+ if (errors.length > 1) throw new AggregateError(errors, 'isolated transform failed; source repository changed or cleanup failed');
408
+ return { ...result, sourceInvariant };
409
+ }