@quolu/lattice 0.52.0 → 0.52.2

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 (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. 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
+ }