@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,315 +1,315 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import { invokeSensorCli } from './sensor-runtime.mjs';
7
-
8
- import { digestArtifact } from './artifact-contracts.mjs';
9
-
10
- /**
11
- * RC3-D dogfood scaffold(ADR 0044 Decision 11.1〜11.3)。
12
- *
13
- * RC2 delivery-policy fixtureの3点(fixture entry・oracle・shared test)を
14
- * Lattice sourceからbyte-identicalに同一相対pathへ複製したdisposable git repoを、
15
- * tmpdir配下のworkRootへ新規作成する(Latticeのworktreeにしない)。
16
- *
17
- * - oracle bytesはaccepted candidate witness(epoch `delivery-policy-semantic-v2`)の
18
- * `fixed_oracle.source_digest`とbindし、不成立はtyped rejection(TypeError)とする。
19
- * bind不能を黙って別bytesへfallbackしない(Decision 11.3)。
20
- * - provenanceはlattice_source(adapter・runnerが属する)とtarget(fixture・changed
21
- * pathsが属する)の2 namespaceへ分離して保存する(Decision 11.2)。
22
- * - 既存repoRootへの上書きscaffoldは拒否する(atomic no-overwrite規律の継承)。
23
- */
24
-
25
- export const RC3_DOGFOOD_SCAFFOLD_PATHS = Object.freeze([
26
- 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs',
27
- 'src/rc2-delivery-policy-oracle.mjs',
28
- 'test/rc2-delivery-policy-fixture.test.mjs',
29
- ]);
30
-
31
- const CANDIDATE_SPEC_PATH = 'research/campaigns/rc2/inputs/candidate-spec-v1.json';
32
- const EXPECTED_CANDIDATE_ID = 'shard-delivery-policy-registry-by-channel';
33
- const EXPECTED_CANDIDATE_DIGEST = '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907';
34
- const EXPECTED_TREATMENT_EPOCH = 'delivery-policy-semantic-v2';
35
- const ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
36
- const ADAPTER_PATH = 'src/rc2-delivery-policy-transform.mjs';
37
- const TRANSFORM_ONLY_PATHS = Object.freeze([
38
- 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
39
- 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
40
- 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
41
- 'test/rc2-delivery-policy-email.test.mjs',
42
- 'test/rc2-delivery-policy-push.test.mjs',
43
- 'test/rc2-delivery-policy-sms.test.mjs',
44
- ]);
45
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
46
- const GIT_IDENTITY = ['-c', 'user.email=rc3-dogfood@lattice.invalid', '-c', 'user.name=rc3-dogfood'];
47
-
48
- function fail(reason) {
49
- throw new TypeError(`rc3 dogfood scaffold契約違反: ${reason}`);
50
- }
51
-
52
- function plainRecord(value) {
53
- return value !== null
54
- && typeof value === 'object'
55
- && !Array.isArray(value)
56
- && Object.getPrototypeOf(value) === Object.prototype;
57
- }
58
-
59
- function exactRecord(value, keys) {
60
- if (!plainRecord(value)) return false;
61
- const actual = Object.keys(value).sort();
62
- const expected = [...keys].sort();
63
- return actual.length === expected.length
64
- && actual.every((key, index) => key === expected[index]);
65
- }
66
-
67
- function sha256(bytes) {
68
- return createHash('sha256').update(bytes).digest('hex');
69
- }
70
-
71
- function run(command, args, cwd) {
72
- return new Promise((resolve, reject) => {
73
- const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
74
- const stdout = [];
75
- const stderr = [];
76
- child.stdout.on('data', (chunk) => stdout.push(chunk));
77
- child.stderr.on('data', (chunk) => stderr.push(chunk));
78
- child.once('error', reject);
79
- child.once('close', (code, signal) => {
80
- const result = {
81
- code,
82
- stdout: Buffer.concat(stdout).toString('utf8'),
83
- stderr: Buffer.concat(stderr).toString('utf8'),
84
- };
85
- if (code === 0 && signal === null) resolve(result);
86
- else reject(new TypeError(`${command} ${args[0]} failed (${signal ?? code}): ${result.stderr.trim()}`));
87
- });
88
- });
89
- }
90
-
91
- async function pathExists(target) {
92
- try {
93
- await lstat(target);
94
- return true;
95
- } catch (error) {
96
- if (error?.code === 'ENOENT') return false;
97
- throw error;
98
- }
99
- }
100
-
101
- function runRaw(command, args, cwd) {
102
- return new Promise((resolve, reject) => {
103
- const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
104
- const stdout = [];
105
- const stderr = [];
106
- child.stdout.on('data', (chunk) => stdout.push(chunk));
107
- child.stderr.on('data', (chunk) => stderr.push(chunk));
108
- child.once('error', reject);
109
- child.once('close', (code, signal) => {
110
- if (code === 0 && signal === null) resolve(Buffer.concat(stdout));
111
- else {
112
- reject(new TypeError(
113
- `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
114
- ));
115
- }
116
- });
117
- });
118
- }
119
-
120
- // disposable repo自身のroot ignoreへ生成sensor stateを明示し、init後もtreeをcleanに保つ。
121
- // Lattice sourceのtracked bytesとは別物なのでsource provenanceへ混ぜない。
122
- const SENSOR_IGNORE_PATH = '.gitignore';
123
- const SENSOR_IGNORE_BYTES = Buffer.from('.lattice/sensor/\n', 'utf8');
124
-
125
- async function readLatticeSources(latticeRoot) {
126
- // bytesの正はHEAD blob(base commitへ束縛するため)。working treeが
127
- // HEADと食い違う場合は、dirty bytesをbase shaへ誤帰属させずrejectする。
128
- const bytesByPath = new Map();
129
- for (const relativePath of RC3_DOGFOOD_SCAFFOLD_PATHS) {
130
- let headBytes;
131
- try {
132
- headBytes = await runRaw('git', ['show', `HEAD:${relativePath}`], latticeRoot);
133
- } catch {
134
- fail(`Lattice HEAD blobを読めない: ${relativePath}`);
135
- }
136
- let workingBytes;
137
- try {
138
- workingBytes = await readFile(path.join(latticeRoot, relativePath));
139
- } catch {
140
- fail(`Lattice sourceを読めない: ${relativePath}`);
141
- }
142
- if (!workingBytes.equals(headBytes)) {
143
- fail(`Lattice working treeがHEADと一致しない(dirty sourceはscaffoldできない): ${relativePath}`);
144
- }
145
- bytesByPath.set(relativePath, headBytes);
146
- }
147
- let candidateSpec;
148
- try {
149
- candidateSpec = JSON.parse(await readFile(path.join(latticeRoot, CANDIDATE_SPEC_PATH), 'utf8'));
150
- } catch {
151
- fail(`candidate specを読めない: ${CANDIDATE_SPEC_PATH}`);
152
- }
153
- const candidateDigest = digestArtifact(candidateSpec);
154
- if (candidateDigest !== EXPECTED_CANDIDATE_DIGEST
155
- || candidateSpec?.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
156
- || candidateSpec?.candidate_id !== EXPECTED_CANDIDATE_ID
157
- || candidateSpec?.fixed_oracle?.path !== ORACLE_PATH) {
158
- fail('candidate specがaccepted RC2 witnessと一致しない');
159
- }
160
- const oracleDigest = sha256(bytesByPath.get(ORACLE_PATH));
161
- if (oracleDigest !== candidateSpec.fixed_oracle.source_digest) {
162
- fail(`oracle bytesがaccepted witnessのfixed_oracle.source_digestとbindできない: ${oracleDigest}`);
163
- }
164
- return { bytesByPath, candidateSpec, candidateDigest, oracleDigest };
165
- }
166
-
167
- function pathDigests(bytesByPath) {
168
- return Object.fromEntries([...bytesByPath.entries()]
169
- .sort(([left], [right]) => (left < right ? -1 : 1))
170
- .map(([relativePath, bytes]) => [relativePath, sha256(bytes)]));
171
- }
172
-
173
- /**
174
- * disposable dogfood repoをworkRoot/repoへ新規作成し、scaffold recordを返す。
175
- */
176
- export async function scaffoldRc3DogfoodRepo(options = {}) {
177
- if (!exactRecord(options, ['latticeRoot', 'workRoot'])) {
178
- fail('scaffoldRc3DogfoodRepo optionsがexact shapeでない');
179
- }
180
- const { latticeRoot, workRoot } = options;
181
- if (typeof latticeRoot !== 'string' || latticeRoot.length === 0
182
- || typeof workRoot !== 'string' || workRoot.length === 0) {
183
- fail('latticeRoot/workRootが不正');
184
- }
185
- const repoRoot = path.join(workRoot, 'repo');
186
- const { bytesByPath, candidateDigest, oracleDigest } = await readLatticeSources(latticeRoot);
187
- const targetBytesByPath = new Map(bytesByPath);
188
- targetBytesByPath.set(SENSOR_IGNORE_PATH, SENSOR_IGNORE_BYTES);
189
- const latticeHead = (await run('git', ['rev-parse', 'HEAD'], latticeRoot)).stdout.trim();
190
- if (!GIT_SHA1.test(latticeHead)) fail('Lattice HEADを解決できない');
191
-
192
- // no-overwriteをatomicにする: exclusive mkdirで作成と存在検査を一手にする。
193
- await mkdir(workRoot, { recursive: true });
194
- try {
195
- await mkdir(repoRoot);
196
- } catch (error) {
197
- if (error?.code === 'EEXIST') fail(`repoRootが既に存在する(上書き禁止): ${repoRoot}`);
198
- throw error;
199
- }
200
- for (const [relativePath, bytes] of targetBytesByPath) {
201
- const absolutePath = path.join(repoRoot, relativePath);
202
- await mkdir(path.dirname(absolutePath), { recursive: true });
203
- await writeFile(absolutePath, bytes);
204
- }
205
- await run('git', ['init', '--quiet', '--initial-branch=main'], repoRoot);
206
- await run('git', [...GIT_IDENTITY, 'add', '.'], repoRoot);
207
- await run('git', [...GIT_IDENTITY, 'commit', '--quiet', '-m', 'rc3 dogfood scaffold'], repoRoot);
208
- const baseSha = (await run('git', ['rev-parse', 'HEAD'], repoRoot)).stdout.trim();
209
- if (!GIT_SHA1.test(baseSha)) fail('scaffold base shaを解決できない');
210
- await invokeSensorCli(run, ['init', '.'], repoRoot);
211
-
212
- const status = await run('git', ['status', '--porcelain=v1', '--untracked-files=all'], repoRoot);
213
- if (status.stdout !== '') fail(`scaffold直後のtreeがcleanではない: ${status.stdout.trim()}`);
214
- for (const absent of TRANSFORM_ONLY_PATHS) {
215
- if (await pathExists(path.join(repoRoot, absent))) {
216
- fail(`transform対象pathがscaffoldに存在してはならない: ${absent}`);
217
- }
218
- }
219
-
220
- return Object.freeze({
221
- schema: 'lattice.rc3.dogfood_scaffold.v1',
222
- repoRoot,
223
- lattice_source: Object.freeze({
224
- root_kind: 'lattice-source',
225
- base_sha: latticeHead,
226
- adapter_path: ADAPTER_PATH,
227
- path_digests: Object.freeze(pathDigests(bytesByPath)),
228
- }),
229
- target: Object.freeze({
230
- root_kind: 'disposable-dogfood',
231
- base_sha: baseSha,
232
- path_digests: Object.freeze(pathDigests(targetBytesByPath)),
233
- }),
234
- predeclared_treatment: Object.freeze({
235
- epoch: EXPECTED_TREATMENT_EPOCH,
236
- candidate_digest: candidateDigest,
237
- oracle_source_digest: oracleDigest,
238
- adapter_path: ADAPTER_PATH,
239
- }),
240
- });
241
- }
242
-
243
- /**
244
- * scaffold recordに対するdisposable repoの現状をre-verifyする。
245
- * 違反は例外にせずtyped violationsとして列挙する(親が裁定するため)。
246
- */
247
- export async function verifyRc3DogfoodScaffold(options = {}) {
248
- if (!exactRecord(options, ['latticeRoot', 'repoRoot', 'expected'])) {
249
- fail('verifyRc3DogfoodScaffold optionsがexact shapeでない');
250
- }
251
- const { latticeRoot, repoRoot, expected } = options;
252
- const violations = [];
253
-
254
- // expected record自体を偽造できないよう、predeclared treatment bindingを
255
- // Lattice sourceから再導出して照合する(保存値を鵜呑みにしない)。
256
- if (expected?.schema !== 'lattice.rc3.dogfood_scaffold.v1') {
257
- violations.push({ code: 'EXPECTED_RECORD_INVALID', detail: String(expected?.schema) });
258
- } else {
259
- try {
260
- const rederived = await readLatticeSources(latticeRoot);
261
- if (expected.predeclared_treatment?.candidate_digest !== rederived.candidateDigest
262
- || expected.predeclared_treatment?.oracle_source_digest !== rederived.oracleDigest
263
- || expected.predeclared_treatment?.epoch !== EXPECTED_TREATMENT_EPOCH
264
- || expected.predeclared_treatment?.adapter_path !== ADAPTER_PATH
265
- || expected.target?.path_digests?.[ORACLE_PATH] !== rederived.oracleDigest) {
266
- violations.push({ code: 'TREATMENT_BINDING_DRIFT' });
267
- }
268
- } catch (error) {
269
- violations.push({ code: 'TREATMENT_BINDING_DRIFT', detail: String(error?.message) });
270
- }
271
- }
272
-
273
- const head = (await run('git', ['rev-parse', 'HEAD'], repoRoot)).stdout.trim();
274
- if (head !== expected?.target?.base_sha) {
275
- violations.push({ code: 'BASE_DRIFT', detail: head });
276
- }
277
-
278
- // untracked混入を含むdirty treeをrejectする(対象3 path以外の追加も検出する)。
279
- const status = await run('git', ['status', '--porcelain=v1', '--untracked-files=all'], repoRoot);
280
- if (status.stdout !== '') {
281
- violations.push({ code: 'TREE_DIRTY', detail: status.stdout.trim().slice(0, 512) });
282
- }
283
-
284
- for (const relativePath of RC3_DOGFOOD_SCAFFOLD_PATHS) {
285
- let targetBytes = null;
286
- try {
287
- targetBytes = await readFile(path.join(repoRoot, relativePath));
288
- } catch {
289
- violations.push({ code: 'PATH_MISSING', path: relativePath });
290
- continue;
291
- }
292
- const digest = sha256(targetBytes);
293
- if (digest !== expected?.target?.path_digests?.[relativePath]) {
294
- violations.push({ code: 'PATH_BYTES_DRIFT', path: relativePath, detail: digest });
295
- }
296
- try {
297
- const latticeBytes = await readFile(path.join(latticeRoot, relativePath));
298
- if (!latticeBytes.equals(targetBytes)) {
299
- violations.push({ code: 'LATTICE_SOURCE_DRIFT', path: relativePath });
300
- }
301
- } catch {
302
- violations.push({ code: 'LATTICE_SOURCE_DRIFT', path: relativePath });
303
- }
304
- }
305
-
306
- for (const absent of TRANSFORM_ONLY_PATHS) {
307
- if (await pathExists(path.join(repoRoot, absent))) {
308
- violations.push({ code: 'TRANSFORM_PATH_PRESENT', path: absent });
309
- }
310
- }
311
-
312
- return violations.length === 0
313
- ? { outcome: 'verified' }
314
- : { outcome: 'rejected', violations };
315
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ import { invokeSensorCli } from './sensor-runtime.mjs';
7
+
8
+ import { digestArtifact } from './artifact-contracts.mjs';
9
+
10
+ /**
11
+ * RC3-D dogfood scaffold(ADR 0044 Decision 11.1〜11.3)。
12
+ *
13
+ * RC2 delivery-policy fixtureの3点(fixture entry・oracle・shared test)を
14
+ * Lattice sourceからbyte-identicalに同一相対pathへ複製したdisposable git repoを、
15
+ * tmpdir配下のworkRootへ新規作成する(Latticeのworktreeにしない)。
16
+ *
17
+ * - oracle bytesはaccepted candidate witness(epoch `delivery-policy-semantic-v2`)の
18
+ * `fixed_oracle.source_digest`とbindし、不成立はtyped rejection(TypeError)とする。
19
+ * bind不能を黙って別bytesへfallbackしない(Decision 11.3)。
20
+ * - provenanceはlattice_source(adapter・runnerが属する)とtarget(fixture・changed
21
+ * pathsが属する)の2 namespaceへ分離して保存する(Decision 11.2)。
22
+ * - 既存repoRootへの上書きscaffoldは拒否する(atomic no-overwrite規律の継承)。
23
+ */
24
+
25
+ export const RC3_DOGFOOD_SCAFFOLD_PATHS = Object.freeze([
26
+ 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs',
27
+ 'src/rc2-delivery-policy-oracle.mjs',
28
+ 'test/rc2-delivery-policy-fixture.test.mjs',
29
+ ]);
30
+
31
+ const CANDIDATE_SPEC_PATH = 'research/campaigns/rc2/inputs/candidate-spec-v1.json';
32
+ const EXPECTED_CANDIDATE_ID = 'shard-delivery-policy-registry-by-channel';
33
+ const EXPECTED_CANDIDATE_DIGEST = '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907';
34
+ const EXPECTED_TREATMENT_EPOCH = 'delivery-policy-semantic-v2';
35
+ const ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
36
+ const ADAPTER_PATH = 'src/rc2-delivery-policy-transform.mjs';
37
+ const TRANSFORM_ONLY_PATHS = Object.freeze([
38
+ 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
39
+ 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
40
+ 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
41
+ 'test/rc2-delivery-policy-email.test.mjs',
42
+ 'test/rc2-delivery-policy-push.test.mjs',
43
+ 'test/rc2-delivery-policy-sms.test.mjs',
44
+ ]);
45
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
46
+ const GIT_IDENTITY = ['-c', 'user.email=rc3-dogfood@lattice.invalid', '-c', 'user.name=rc3-dogfood'];
47
+
48
+ function fail(reason) {
49
+ throw new TypeError(`rc3 dogfood scaffold契約違反: ${reason}`);
50
+ }
51
+
52
+ function plainRecord(value) {
53
+ return value !== null
54
+ && typeof value === 'object'
55
+ && !Array.isArray(value)
56
+ && Object.getPrototypeOf(value) === Object.prototype;
57
+ }
58
+
59
+ function exactRecord(value, keys) {
60
+ if (!plainRecord(value)) return false;
61
+ const actual = Object.keys(value).sort();
62
+ const expected = [...keys].sort();
63
+ return actual.length === expected.length
64
+ && actual.every((key, index) => key === expected[index]);
65
+ }
66
+
67
+ function sha256(bytes) {
68
+ return createHash('sha256').update(bytes).digest('hex');
69
+ }
70
+
71
+ function run(command, args, cwd) {
72
+ return new Promise((resolve, reject) => {
73
+ const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
74
+ const stdout = [];
75
+ const stderr = [];
76
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
77
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
78
+ child.once('error', reject);
79
+ child.once('close', (code, signal) => {
80
+ const result = {
81
+ code,
82
+ stdout: Buffer.concat(stdout).toString('utf8'),
83
+ stderr: Buffer.concat(stderr).toString('utf8'),
84
+ };
85
+ if (code === 0 && signal === null) resolve(result);
86
+ else reject(new TypeError(`${command} ${args[0]} failed (${signal ?? code}): ${result.stderr.trim()}`));
87
+ });
88
+ });
89
+ }
90
+
91
+ async function pathExists(target) {
92
+ try {
93
+ await lstat(target);
94
+ return true;
95
+ } catch (error) {
96
+ if (error?.code === 'ENOENT') return false;
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ function runRaw(command, args, cwd) {
102
+ return new Promise((resolve, reject) => {
103
+ const child = spawn(command, args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
104
+ const stdout = [];
105
+ const stderr = [];
106
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
107
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
108
+ child.once('error', reject);
109
+ child.once('close', (code, signal) => {
110
+ if (code === 0 && signal === null) resolve(Buffer.concat(stdout));
111
+ else {
112
+ reject(new TypeError(
113
+ `${command} ${args[0]} failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8').trim()}`,
114
+ ));
115
+ }
116
+ });
117
+ });
118
+ }
119
+
120
+ // disposable repo自身のroot ignoreへ生成sensor stateを明示し、init後もtreeをcleanに保つ。
121
+ // Lattice sourceのtracked bytesとは別物なのでsource provenanceへ混ぜない。
122
+ const SENSOR_IGNORE_PATH = '.gitignore';
123
+ const SENSOR_IGNORE_BYTES = Buffer.from('.lattice/sensor/\n', 'utf8');
124
+
125
+ async function readLatticeSources(latticeRoot) {
126
+ // bytesの正はHEAD blob(base commitへ束縛するため)。working treeが
127
+ // HEADと食い違う場合は、dirty bytesをbase shaへ誤帰属させずrejectする。
128
+ const bytesByPath = new Map();
129
+ for (const relativePath of RC3_DOGFOOD_SCAFFOLD_PATHS) {
130
+ let headBytes;
131
+ try {
132
+ headBytes = await runRaw('git', ['show', `HEAD:${relativePath}`], latticeRoot);
133
+ } catch {
134
+ fail(`Lattice HEAD blobを読めない: ${relativePath}`);
135
+ }
136
+ let workingBytes;
137
+ try {
138
+ workingBytes = await readFile(path.join(latticeRoot, relativePath));
139
+ } catch {
140
+ fail(`Lattice sourceを読めない: ${relativePath}`);
141
+ }
142
+ if (!workingBytes.equals(headBytes)) {
143
+ fail(`Lattice working treeがHEADと一致しない(dirty sourceはscaffoldできない): ${relativePath}`);
144
+ }
145
+ bytesByPath.set(relativePath, headBytes);
146
+ }
147
+ let candidateSpec;
148
+ try {
149
+ candidateSpec = JSON.parse(await readFile(path.join(latticeRoot, CANDIDATE_SPEC_PATH), 'utf8'));
150
+ } catch {
151
+ fail(`candidate specを読めない: ${CANDIDATE_SPEC_PATH}`);
152
+ }
153
+ const candidateDigest = digestArtifact(candidateSpec);
154
+ if (candidateDigest !== EXPECTED_CANDIDATE_DIGEST
155
+ || candidateSpec?.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
156
+ || candidateSpec?.candidate_id !== EXPECTED_CANDIDATE_ID
157
+ || candidateSpec?.fixed_oracle?.path !== ORACLE_PATH) {
158
+ fail('candidate specがaccepted RC2 witnessと一致しない');
159
+ }
160
+ const oracleDigest = sha256(bytesByPath.get(ORACLE_PATH));
161
+ if (oracleDigest !== candidateSpec.fixed_oracle.source_digest) {
162
+ fail(`oracle bytesがaccepted witnessのfixed_oracle.source_digestとbindできない: ${oracleDigest}`);
163
+ }
164
+ return { bytesByPath, candidateSpec, candidateDigest, oracleDigest };
165
+ }
166
+
167
+ function pathDigests(bytesByPath) {
168
+ return Object.fromEntries([...bytesByPath.entries()]
169
+ .sort(([left], [right]) => (left < right ? -1 : 1))
170
+ .map(([relativePath, bytes]) => [relativePath, sha256(bytes)]));
171
+ }
172
+
173
+ /**
174
+ * disposable dogfood repoをworkRoot/repoへ新規作成し、scaffold recordを返す。
175
+ */
176
+ export async function scaffoldRc3DogfoodRepo(options = {}) {
177
+ if (!exactRecord(options, ['latticeRoot', 'workRoot'])) {
178
+ fail('scaffoldRc3DogfoodRepo optionsがexact shapeでない');
179
+ }
180
+ const { latticeRoot, workRoot } = options;
181
+ if (typeof latticeRoot !== 'string' || latticeRoot.length === 0
182
+ || typeof workRoot !== 'string' || workRoot.length === 0) {
183
+ fail('latticeRoot/workRootが不正');
184
+ }
185
+ const repoRoot = path.join(workRoot, 'repo');
186
+ const { bytesByPath, candidateDigest, oracleDigest } = await readLatticeSources(latticeRoot);
187
+ const targetBytesByPath = new Map(bytesByPath);
188
+ targetBytesByPath.set(SENSOR_IGNORE_PATH, SENSOR_IGNORE_BYTES);
189
+ const latticeHead = (await run('git', ['rev-parse', 'HEAD'], latticeRoot)).stdout.trim();
190
+ if (!GIT_SHA1.test(latticeHead)) fail('Lattice HEADを解決できない');
191
+
192
+ // no-overwriteをatomicにする: exclusive mkdirで作成と存在検査を一手にする。
193
+ await mkdir(workRoot, { recursive: true });
194
+ try {
195
+ await mkdir(repoRoot);
196
+ } catch (error) {
197
+ if (error?.code === 'EEXIST') fail(`repoRootが既に存在する(上書き禁止): ${repoRoot}`);
198
+ throw error;
199
+ }
200
+ for (const [relativePath, bytes] of targetBytesByPath) {
201
+ const absolutePath = path.join(repoRoot, relativePath);
202
+ await mkdir(path.dirname(absolutePath), { recursive: true });
203
+ await writeFile(absolutePath, bytes);
204
+ }
205
+ await run('git', ['init', '--quiet', '--initial-branch=main'], repoRoot);
206
+ await run('git', [...GIT_IDENTITY, 'add', '.'], repoRoot);
207
+ await run('git', [...GIT_IDENTITY, 'commit', '--quiet', '-m', 'rc3 dogfood scaffold'], repoRoot);
208
+ const baseSha = (await run('git', ['rev-parse', 'HEAD'], repoRoot)).stdout.trim();
209
+ if (!GIT_SHA1.test(baseSha)) fail('scaffold base shaを解決できない');
210
+ await invokeSensorCli(run, ['init', '.'], repoRoot);
211
+
212
+ const status = await run('git', ['status', '--porcelain=v1', '--untracked-files=all'], repoRoot);
213
+ if (status.stdout !== '') fail(`scaffold直後のtreeがcleanではない: ${status.stdout.trim()}`);
214
+ for (const absent of TRANSFORM_ONLY_PATHS) {
215
+ if (await pathExists(path.join(repoRoot, absent))) {
216
+ fail(`transform対象pathがscaffoldに存在してはならない: ${absent}`);
217
+ }
218
+ }
219
+
220
+ return Object.freeze({
221
+ schema: 'lattice.rc3.dogfood_scaffold.v1',
222
+ repoRoot,
223
+ lattice_source: Object.freeze({
224
+ root_kind: 'lattice-source',
225
+ base_sha: latticeHead,
226
+ adapter_path: ADAPTER_PATH,
227
+ path_digests: Object.freeze(pathDigests(bytesByPath)),
228
+ }),
229
+ target: Object.freeze({
230
+ root_kind: 'disposable-dogfood',
231
+ base_sha: baseSha,
232
+ path_digests: Object.freeze(pathDigests(targetBytesByPath)),
233
+ }),
234
+ predeclared_treatment: Object.freeze({
235
+ epoch: EXPECTED_TREATMENT_EPOCH,
236
+ candidate_digest: candidateDigest,
237
+ oracle_source_digest: oracleDigest,
238
+ adapter_path: ADAPTER_PATH,
239
+ }),
240
+ });
241
+ }
242
+
243
+ /**
244
+ * scaffold recordに対するdisposable repoの現状をre-verifyする。
245
+ * 違反は例外にせずtyped violationsとして列挙する(親が裁定するため)。
246
+ */
247
+ export async function verifyRc3DogfoodScaffold(options = {}) {
248
+ if (!exactRecord(options, ['latticeRoot', 'repoRoot', 'expected'])) {
249
+ fail('verifyRc3DogfoodScaffold optionsがexact shapeでない');
250
+ }
251
+ const { latticeRoot, repoRoot, expected } = options;
252
+ const violations = [];
253
+
254
+ // expected record自体を偽造できないよう、predeclared treatment bindingを
255
+ // Lattice sourceから再導出して照合する(保存値を鵜呑みにしない)。
256
+ if (expected?.schema !== 'lattice.rc3.dogfood_scaffold.v1') {
257
+ violations.push({ code: 'EXPECTED_RECORD_INVALID', detail: String(expected?.schema) });
258
+ } else {
259
+ try {
260
+ const rederived = await readLatticeSources(latticeRoot);
261
+ if (expected.predeclared_treatment?.candidate_digest !== rederived.candidateDigest
262
+ || expected.predeclared_treatment?.oracle_source_digest !== rederived.oracleDigest
263
+ || expected.predeclared_treatment?.epoch !== EXPECTED_TREATMENT_EPOCH
264
+ || expected.predeclared_treatment?.adapter_path !== ADAPTER_PATH
265
+ || expected.target?.path_digests?.[ORACLE_PATH] !== rederived.oracleDigest) {
266
+ violations.push({ code: 'TREATMENT_BINDING_DRIFT' });
267
+ }
268
+ } catch (error) {
269
+ violations.push({ code: 'TREATMENT_BINDING_DRIFT', detail: String(error?.message) });
270
+ }
271
+ }
272
+
273
+ const head = (await run('git', ['rev-parse', 'HEAD'], repoRoot)).stdout.trim();
274
+ if (head !== expected?.target?.base_sha) {
275
+ violations.push({ code: 'BASE_DRIFT', detail: head });
276
+ }
277
+
278
+ // untracked混入を含むdirty treeをrejectする(対象3 path以外の追加も検出する)。
279
+ const status = await run('git', ['status', '--porcelain=v1', '--untracked-files=all'], repoRoot);
280
+ if (status.stdout !== '') {
281
+ violations.push({ code: 'TREE_DIRTY', detail: status.stdout.trim().slice(0, 512) });
282
+ }
283
+
284
+ for (const relativePath of RC3_DOGFOOD_SCAFFOLD_PATHS) {
285
+ let targetBytes = null;
286
+ try {
287
+ targetBytes = await readFile(path.join(repoRoot, relativePath));
288
+ } catch {
289
+ violations.push({ code: 'PATH_MISSING', path: relativePath });
290
+ continue;
291
+ }
292
+ const digest = sha256(targetBytes);
293
+ if (digest !== expected?.target?.path_digests?.[relativePath]) {
294
+ violations.push({ code: 'PATH_BYTES_DRIFT', path: relativePath, detail: digest });
295
+ }
296
+ try {
297
+ const latticeBytes = await readFile(path.join(latticeRoot, relativePath));
298
+ if (!latticeBytes.equals(targetBytes)) {
299
+ violations.push({ code: 'LATTICE_SOURCE_DRIFT', path: relativePath });
300
+ }
301
+ } catch {
302
+ violations.push({ code: 'LATTICE_SOURCE_DRIFT', path: relativePath });
303
+ }
304
+ }
305
+
306
+ for (const absent of TRANSFORM_ONLY_PATHS) {
307
+ if (await pathExists(path.join(repoRoot, absent))) {
308
+ violations.push({ code: 'TRANSFORM_PATH_PRESENT', path: absent });
309
+ }
310
+ }
311
+
312
+ return violations.length === 0
313
+ ? { outcome: 'verified' }
314
+ : { outcome: 'rejected', violations };
315
+ }