@quolu/lattice 0.52.2 → 0.52.4

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 (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. 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
+ }