@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,1127 +1,1127 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import {
4
- lstat,
5
- mkdir,
6
- readFile,
7
- realpath,
8
- writeFile,
9
- } from 'node:fs/promises';
10
- import path from 'node:path';
11
-
12
- import { digestArtifact } from './artifact-contracts.mjs';
13
- import { runIsolatedTransform } from './isolation-runner.mjs';
14
- import { runRc2DeliveryPolicyOracle } from './rc2-delivery-policy-oracle.mjs';
15
-
16
- const ADAPTER_PATH = 'src/rc2-delivery-policy-transform.mjs';
17
- const ENTRY_PATH = 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
18
- const ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
19
- const SHARED_TEST_PATH = 'test/rc2-delivery-policy-fixture.test.mjs';
20
- const EXPECTED_CANDIDATE_ID = 'shard-delivery-policy-registry-by-channel';
21
- const EXPECTED_CANDIDATE_DIGEST = '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907';
22
- const GIT_SHA1 = /^[0-9a-f]{40}$/;
23
-
24
- export const RC2_DELIVERY_POLICY_TRANSFORM_PATHS = Object.freeze([
25
- ENTRY_PATH,
26
- 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
27
- 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
28
- 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
29
- 'test/rc2-delivery-policy-email.test.mjs',
30
- SHARED_TEST_PATH,
31
- 'test/rc2-delivery-policy-push.test.mjs',
32
- 'test/rc2-delivery-policy-sms.test.mjs',
33
- ]);
34
-
35
- const SURFACE_PATHS = Object.freeze([
36
- ...RC2_DELIVERY_POLICY_TRANSFORM_PATHS,
37
- ORACLE_PATH,
38
- ].sort());
39
-
40
- const CURRENT_PATHS = new Set([ENTRY_PATH, SHARED_TEST_PATH, ORACLE_PATH]);
41
-
42
- const CHANNELS = Object.freeze({
43
- email: Object.freeze({
44
- todoId: 'email-policy',
45
- resolver: 'resolveEmailPolicy',
46
- productionPath: 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
47
- contract: 'emailPolicyContract',
48
- testPath: 'test/rc2-delivery-policy-email.test.mjs',
49
- caseIds: Object.freeze(['email-routine', 'email-urgent']),
50
- }),
51
- sms: Object.freeze({
52
- todoId: 'sms-policy',
53
- resolver: 'resolveSmsPolicy',
54
- productionPath: 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
55
- contract: 'smsPolicyContract',
56
- testPath: 'test/rc2-delivery-policy-sms.test.mjs',
57
- caseIds: Object.freeze(['sms-routine', 'sms-urgent']),
58
- }),
59
- push: Object.freeze({
60
- todoId: 'push-policy',
61
- resolver: 'resolvePushPolicy',
62
- productionPath: 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
63
- contract: 'pushPolicyContract',
64
- testPath: 'test/rc2-delivery-policy-push.test.mjs',
65
- caseIds: Object.freeze(['push-routine', 'push-urgent']),
66
- }),
67
- });
68
-
69
- const TEST_CONTRACTS = Object.freeze([
70
- Object.freeze({ testId: CHANNELS.email.contract, path: CHANNELS.email.testPath }),
71
- Object.freeze({ testId: CHANNELS.sms.contract, path: CHANNELS.sms.testPath }),
72
- Object.freeze({ testId: CHANNELS.push.contract, path: CHANNELS.push.testPath }),
73
- Object.freeze({ testId: 'deliveryPolicyCompositionContract', path: SHARED_TEST_PATH }),
74
- ]);
75
-
76
- const MUTATIONS = Object.freeze([
77
- Object.freeze({
78
- caseId: 'email-routine',
79
- owner: CHANNELS.email,
80
- needle: "routine: Object.freeze({ transport: 'smtp', retry_limit: 3, delay_seconds: 60 }),",
81
- replacement: "routine: Object.freeze({ transport: 'smtp', retry_limit: 103, delay_seconds: 60 }),",
82
- }),
83
- Object.freeze({
84
- caseId: 'email-urgent',
85
- owner: CHANNELS.email,
86
- needle: "urgent: Object.freeze({ transport: 'smtp', retry_limit: 5, delay_seconds: 0 }),",
87
- replacement: "urgent: Object.freeze({ transport: 'smtp', retry_limit: 105, delay_seconds: 0 }),",
88
- }),
89
- Object.freeze({
90
- caseId: 'sms-routine',
91
- owner: CHANNELS.sms,
92
- needle: "routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 30 }),",
93
- replacement: "routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 130 }),",
94
- }),
95
- Object.freeze({
96
- caseId: 'sms-urgent',
97
- owner: CHANNELS.sms,
98
- needle: "urgent: Object.freeze({ transport: 'sms', retry_limit: 4, delay_seconds: 0 }),",
99
- replacement: "urgent: Object.freeze({ transport: 'sms', retry_limit: 104, delay_seconds: 0 }),",
100
- }),
101
- Object.freeze({
102
- caseId: 'push-routine',
103
- owner: CHANNELS.push,
104
- needle: "routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 10 }),",
105
- replacement: "routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 110 }),",
106
- }),
107
- Object.freeze({
108
- caseId: 'push-urgent',
109
- owner: CHANNELS.push,
110
- needle: "urgent: Object.freeze({ transport: 'push', retry_limit: 3, delay_seconds: 0 }),",
111
- replacement: "urgent: Object.freeze({ transport: 'push', retry_limit: 103, delay_seconds: 0 }),",
112
- }),
113
- ]);
114
-
115
- const ENTRY_SOURCE = `import { resolveEmailPolicy } from './email-policy.mjs';
116
- import { resolvePushPolicy } from './push-policy.mjs';
117
- import { resolveSmsPolicy } from './sms-policy.mjs';
118
-
119
- const INPUT_KEYS = Object.freeze(['channel', 'urgency']);
120
-
121
- function isPlainObject(value) {
122
- return value !== null
123
- && typeof value === 'object'
124
- && !Array.isArray(value)
125
- && Object.getPrototypeOf(value) === Object.prototype;
126
- }
127
-
128
- function hasExactInputKeys(value) {
129
- if (!isPlainObject(value)) return false;
130
- const keys = Object.keys(value).sort();
131
- return keys.length === INPUT_KEYS.length
132
- && keys.every((key, index) => key === INPUT_KEYS[index]);
133
- }
134
-
135
- /** 公開inputを検証し、channel別resolverへroutingするcomposition entry。 */
136
- export function resolveDeliveryPolicy(input) {
137
- if (!hasExactInputKeys(input)) {
138
- throw new TypeError('delivery policy input must be a plain object with exact keys: channel, urgency');
139
- }
140
- let policy;
141
- if (input.channel === 'email') {
142
- policy = resolveEmailPolicy(input.urgency);
143
- } else if (input.channel === 'push') {
144
- policy = resolvePushPolicy(input.urgency);
145
- } else if (input.channel === 'sms') {
146
- policy = resolveSmsPolicy(input.urgency);
147
- } else {
148
- throw new RangeError('channel must be email, sms, or push');
149
- }
150
- return { channel: input.channel, ...policy };
151
- }
152
- `;
153
-
154
- const EMAIL_SOURCE = `const POLICIES = Object.freeze({
155
- routine: Object.freeze({ transport: 'smtp', retry_limit: 3, delay_seconds: 60 }),
156
- urgent: Object.freeze({ transport: 'smtp', retry_limit: 5, delay_seconds: 0 }),
157
- });
158
-
159
- export function resolveEmailPolicy(urgency) {
160
- if (!Object.hasOwn(POLICIES, urgency)) {
161
- throw new RangeError('urgency must be routine or urgent');
162
- }
163
- return { ...POLICIES[urgency] };
164
- }
165
- `;
166
-
167
- const SMS_SOURCE = `const POLICIES = Object.freeze({
168
- routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 30 }),
169
- urgent: Object.freeze({ transport: 'sms', retry_limit: 4, delay_seconds: 0 }),
170
- });
171
-
172
- export function resolveSmsPolicy(urgency) {
173
- if (!Object.hasOwn(POLICIES, urgency)) {
174
- throw new RangeError('urgency must be routine or urgent');
175
- }
176
- return { ...POLICIES[urgency] };
177
- }
178
- `;
179
-
180
- const PUSH_SOURCE = `const POLICIES = Object.freeze({
181
- routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 10 }),
182
- urgent: Object.freeze({ transport: 'push', retry_limit: 3, delay_seconds: 0 }),
183
- });
184
-
185
- export function resolvePushPolicy(urgency) {
186
- if (!Object.hasOwn(POLICIES, urgency)) {
187
- throw new RangeError('urgency must be routine or urgent');
188
- }
189
- return { ...POLICIES[urgency] };
190
- }
191
- `;
192
-
193
- const EMAIL_TEST_SOURCE = `import assert from 'node:assert/strict';
194
- import test from 'node:test';
195
-
196
- import { resolveEmailPolicy } from '../research/fixtures/delivery-policy-registry/src/email-policy.mjs';
197
-
198
- export function emailPolicyContract() {
199
- assert.deepEqual(resolveEmailPolicy('routine'), {
200
- transport: 'smtp', retry_limit: 3, delay_seconds: 60,
201
- });
202
- assert.deepEqual(resolveEmailPolicy('urgent'), {
203
- transport: 'smtp', retry_limit: 5, delay_seconds: 0,
204
- });
205
- }
206
-
207
- test('email-routine and email-urgent policy contract', emailPolicyContract);
208
- `;
209
-
210
- const SMS_TEST_SOURCE = `import assert from 'node:assert/strict';
211
- import test from 'node:test';
212
-
213
- import { resolveSmsPolicy } from '../research/fixtures/delivery-policy-registry/src/sms-policy.mjs';
214
-
215
- export function smsPolicyContract() {
216
- assert.deepEqual(resolveSmsPolicy('routine'), {
217
- transport: 'sms', retry_limit: 2, delay_seconds: 30,
218
- });
219
- assert.deepEqual(resolveSmsPolicy('urgent'), {
220
- transport: 'sms', retry_limit: 4, delay_seconds: 0,
221
- });
222
- }
223
-
224
- test('sms-routine and sms-urgent policy contract', smsPolicyContract);
225
- `;
226
-
227
- const PUSH_TEST_SOURCE = `import assert from 'node:assert/strict';
228
- import test from 'node:test';
229
-
230
- import { resolvePushPolicy } from '../research/fixtures/delivery-policy-registry/src/push-policy.mjs';
231
-
232
- export function pushPolicyContract() {
233
- assert.deepEqual(resolvePushPolicy('routine'), {
234
- transport: 'push', retry_limit: 1, delay_seconds: 10,
235
- });
236
- assert.deepEqual(resolvePushPolicy('urgent'), {
237
- transport: 'push', retry_limit: 3, delay_seconds: 0,
238
- });
239
- }
240
-
241
- test('push-routine and push-urgent policy contract', pushPolicyContract);
242
- `;
243
-
244
- const SHARED_TEST_SOURCE = `import assert from 'node:assert/strict';
245
- import test from 'node:test';
246
-
247
- import { resolveDeliveryPolicy } from '../research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
248
-
249
- export function deliveryPolicyCompositionContract() {
250
- for (const channel of ['email', 'sms', 'push']) {
251
- const output = resolveDeliveryPolicy({ channel, urgency: 'routine' });
252
- assert.equal(output.channel, channel);
253
- assert.deepEqual(Object.keys(output).sort(), [
254
- 'channel', 'delay_seconds', 'retry_limit', 'transport',
255
- ]);
256
- assert.equal(typeof output.transport, 'string');
257
- assert.equal(typeof output.retry_limit, 'number');
258
- assert.equal(typeof output.delay_seconds, 'number');
259
- }
260
- assert.throws(() => resolveDeliveryPolicy(null), { name: 'TypeError' });
261
- assert.throws(() => resolveDeliveryPolicy({ channel: 'email' }), { name: 'TypeError' });
262
- assert.throws(
263
- () => resolveDeliveryPolicy({ channel: 'email', urgency: 'routine', extra: true }),
264
- { name: 'TypeError' },
265
- );
266
- assert.throws(
267
- () => resolveDeliveryPolicy({ channel: 'webhook', urgency: 'routine' }),
268
- { name: 'RangeError' },
269
- );
270
- assert.throws(
271
- () => resolveDeliveryPolicy({ channel: 'email', urgency: 'later' }),
272
- { name: 'RangeError' },
273
- );
274
- }
275
-
276
- test('delivery policy composition routing, shape, and fail-loud contract',
277
- deliveryPolicyCompositionContract);
278
- `;
279
-
280
- const WRITER_FILES = new Map([
281
- [ENTRY_PATH, ENTRY_SOURCE],
282
- [CHANNELS.email.productionPath, EMAIL_SOURCE],
283
- [CHANNELS.push.productionPath, PUSH_SOURCE],
284
- [CHANNELS.sms.productionPath, SMS_SOURCE],
285
- [CHANNELS.email.testPath, EMAIL_TEST_SOURCE],
286
- [SHARED_TEST_PATH, SHARED_TEST_SOURCE],
287
- [CHANNELS.push.testPath, PUSH_TEST_SOURCE],
288
- [CHANNELS.sms.testPath, SMS_TEST_SOURCE],
289
- ]);
290
-
291
- class TransformContractError extends Error {
292
- constructor(code, message) {
293
- super(message);
294
- this.name = 'TransformContractError';
295
- this.code = code;
296
- }
297
- }
298
-
299
- function isPlainObject(value) {
300
- return value !== null
301
- && typeof value === 'object'
302
- && !Array.isArray(value)
303
- && Object.getPrototypeOf(value) === Object.prototype;
304
- }
305
-
306
- function exactRecord(value, keys) {
307
- if (!isPlainObject(value)) return false;
308
- const actual = Object.keys(value).sort();
309
- const expected = [...keys].sort();
310
- return actual.length === expected.length
311
- && actual.every((key, index) => key === expected[index]);
312
- }
313
-
314
- function sha256(value) {
315
- return createHash('sha256').update(value).digest('hex');
316
- }
317
-
318
- function sameArray(left, right) {
319
- return Array.isArray(left)
320
- && Array.isArray(right)
321
- && left.length === right.length
322
- && left.every((entry, index) => entry === right[index]);
323
- }
324
-
325
- function statusPaths(status) {
326
- const fields = status.split('\0');
327
- const paths = [];
328
- for (let index = 0; index < fields.length - 1; index += 1) {
329
- const entry = fields[index];
330
- if (!entry) continue;
331
- const code = entry.slice(0, 2);
332
- paths.push(entry.slice(3));
333
- if (code[0] === 'R' || code[0] === 'C') paths.push(fields[++index]);
334
- }
335
- return [...new Set(paths)].sort();
336
- }
337
-
338
- function spawnCapture(command, args, { cwd, env } = {}) {
339
- return new Promise((resolve, reject) => {
340
- const child = spawn(command, args, {
341
- cwd,
342
- env,
343
- shell: false,
344
- stdio: ['ignore', 'pipe', 'pipe'],
345
- });
346
- const stdout = [];
347
- const stderr = [];
348
- child.stdout.on('data', (chunk) => stdout.push(chunk));
349
- child.stderr.on('data', (chunk) => stderr.push(chunk));
350
- child.once('error', reject);
351
- child.once('close', (code, signal) => resolve({
352
- code,
353
- signal,
354
- stdout: Buffer.concat(stdout),
355
- stderr: Buffer.concat(stderr),
356
- }));
357
- });
358
- }
359
-
360
- async function git(repoRoot, args) {
361
- const result = await spawnCapture('git', ['-C', repoRoot, ...args]);
362
- if (result.code !== 0 || result.signal !== null) {
363
- throw new Error(`git ${args[0]} failed: ${result.stderr.toString('utf8').trim()}`);
364
- }
365
- return result.stdout.toString('utf8');
366
- }
367
-
368
- async function resolveRepository(repoRoot, baseRef) {
369
- if (typeof repoRoot !== 'string' || repoRoot.length === 0
370
- || typeof baseRef !== 'string' || baseRef.length === 0) {
371
- throw new TypeError('repoRoot and baseRef must be non-empty strings');
372
- }
373
- const root = await realpath(repoRoot);
374
- const status = await git(root, ['status', '--porcelain=v1', '-z']);
375
- if (status.length !== 0) throw new Error('canonical source repository must be clean');
376
- const head = (await git(root, ['rev-parse', '--verify', 'HEAD^{commit}'])).trim();
377
- const baseSha = (await git(root, ['rev-parse', '--verify', `${baseRef}^{commit}`])).trim();
378
- if (!GIT_SHA1.test(head) || !GIT_SHA1.test(baseSha)) {
379
- throw new TypeError('HEAD or baseRef did not resolve to a Git SHA-1');
380
- }
381
- if (head !== baseSha) throw new Error('canonical HEAD must equal the exact baseRef commit');
382
- return { root, baseSha };
383
- }
384
-
385
- async function worktreeCount(repoRoot) {
386
- const output = await git(repoRoot, ['worktree', 'list', '--porcelain']);
387
- return output.split('\n').filter((line) => line.startsWith('worktree ')).length;
388
- }
389
-
390
- async function inspectPath(repoRoot, relativePath) {
391
- const segments = relativePath.split('/');
392
- let current = repoRoot;
393
- for (let index = 0; index < segments.length; index += 1) {
394
- current = path.join(current, segments[index]);
395
- let stat;
396
- try {
397
- stat = await lstat(current);
398
- } catch (error) {
399
- if (error?.code === 'ENOENT') return { state: 'absent', path: current };
400
- throw error;
401
- }
402
- if (stat.isSymbolicLink()) {
403
- throw new TransformContractError(
404
- 'LATTICE_RC2_SCOPE_VIOLATION',
405
- `symlink surface is not allowed: ${relativePath}`,
406
- );
407
- }
408
- if (index < segments.length - 1 && !stat.isDirectory()) {
409
- throw new TransformContractError(
410
- 'LATTICE_RC2_SCOPE_VIOLATION',
411
- `non-directory surface ancestor is not allowed: ${relativePath}`,
412
- );
413
- }
414
- if (index === segments.length - 1 && !stat.isFile()) {
415
- throw new TransformContractError(
416
- 'LATTICE_RC2_SCOPE_VIOLATION',
417
- `special surface is not allowed: ${relativePath}`,
418
- );
419
- }
420
- }
421
- return { state: 'present', path: current };
422
- }
423
-
424
- async function readRegularFile(repoRoot, relativePath) {
425
- const inspected = await inspectPath(repoRoot, relativePath);
426
- if (inspected.state !== 'present') {
427
- throw new TransformContractError(
428
- 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
429
- `required transform surface is absent: ${relativePath}`,
430
- );
431
- }
432
- return readFile(inspected.path);
433
- }
434
-
435
- async function safeWrite(repoRoot, relativePath, bytes) {
436
- const segments = relativePath.split('/');
437
- let current = repoRoot;
438
- for (const segment of segments.slice(0, -1)) {
439
- current = path.join(current, segment);
440
- try {
441
- const stat = await lstat(current);
442
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
443
- throw new TransformContractError(
444
- 'LATTICE_RC2_SCOPE_VIOLATION',
445
- `unsafe writer ancestor: ${relativePath}`,
446
- );
447
- }
448
- } catch (error) {
449
- if (error?.code !== 'ENOENT') throw error;
450
- await mkdir(current);
451
- }
452
- }
453
- const target = path.join(repoRoot, relativePath);
454
- try {
455
- const stat = await lstat(target);
456
- if (stat.isSymbolicLink() || !stat.isFile()) {
457
- throw new TransformContractError(
458
- 'LATTICE_RC2_SCOPE_VIOLATION',
459
- `unsafe writer target: ${relativePath}`,
460
- );
461
- }
462
- } catch (error) {
463
- if (error?.code !== 'ENOENT') throw error;
464
- }
465
- await writeFile(target, bytes);
466
- }
467
-
468
- async function captureSurfaceSnapshot(repoRoot) {
469
- const files = [];
470
- for (const relativePath of SURFACE_PATHS) {
471
- const inspected = await inspectPath(repoRoot, relativePath);
472
- files.push(inspected.state === 'present'
473
- ? {
474
- path: relativePath,
475
- state: 'present',
476
- content_digest: sha256(await readFile(inspected.path)),
477
- }
478
- : { path: relativePath, state: 'absent', content_digest: null });
479
- }
480
- const value = {
481
- schema: 'lattice.rc2.delivery_policy_surface_snapshot.v1',
482
- files,
483
- };
484
- return { ...value, digest: digestArtifact(value) };
485
- }
486
-
487
- function assertControlSnapshot(snapshot) {
488
- for (const file of snapshot.files) {
489
- const expected = CURRENT_PATHS.has(file.path) ? 'present' : 'absent';
490
- if (file.state !== expected) {
491
- throw new TypeError('candidate control surface is not the exact current topology');
492
- }
493
- }
494
- }
495
-
496
- function assertOutputSnapshot(snapshot, oracleDigest) {
497
- if (snapshot.files.some(({ state }) => state !== 'present')) {
498
- throw new TransformContractError(
499
- 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
500
- 'post-transform surface is incomplete',
501
- );
502
- }
503
- const oracle = snapshot.files.find(({ path: relativePath }) => relativePath === ORACLE_PATH);
504
- if (oracle?.content_digest !== oracleDigest) {
505
- throw new TransformContractError(
506
- 'LATTICE_RC2_SCOPE_VIOLATION',
507
- 'fixed oracle bytes changed during transform',
508
- );
509
- }
510
- }
511
-
512
- function assertAcceptedCandidate(candidateSpec) {
513
- const candidateDigest = digestArtifact(candidateSpec);
514
- if (candidateDigest !== EXPECTED_CANDIDATE_DIGEST
515
- || candidateSpec?.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
516
- || candidateSpec?.candidate_id !== EXPECTED_CANDIDATE_ID
517
- || candidateSpec?.fixed_oracle?.path !== ORACLE_PATH
518
- || !sameArray(candidateSpec.fixed_oracle.case_ids, MUTATIONS.map(({ caseId }) => caseId))) {
519
- throw new TypeError('candidateSpec is not the accepted RC2 delivery policy witness');
520
- }
521
- const todoProjection = candidateSpec.todos.map((todo) => ({
522
- todoId: todo.todo_id,
523
- caseIds: todo.case_ids,
524
- resolver: todo.proposed.production.symbol,
525
- productionPath: todo.proposed.production.path,
526
- contract: todo.proposed.tests[0].symbol,
527
- testPath: todo.proposed.tests[0].path,
528
- }));
529
- const expectedProjection = Object.values(CHANNELS).map((channel) => ({
530
- todoId: channel.todoId,
531
- caseIds: channel.caseIds,
532
- resolver: channel.resolver,
533
- productionPath: channel.productionPath,
534
- contract: channel.contract,
535
- testPath: channel.testPath,
536
- }));
537
- if (digestArtifact(todoProjection) !== digestArtifact(expectedProjection)) {
538
- throw new TypeError('candidateSpec case partition or proposed ownership is invalid');
539
- }
540
- return { candidateDigest, fixedCandidate: structuredClone(candidateSpec) };
541
- }
542
-
543
- function assertOracleReceipt(receipt, candidateSpec) {
544
- if (!exactRecord(receipt, ['schema', 'outcome', 'case_results'])
545
- || receipt.schema !== 'lattice.rc2.delivery_policy_oracle_receipt.v1'
546
- || receipt.outcome !== 'passed'
547
- || !sameArray(
548
- receipt.case_results.map(({ id }) => id),
549
- candidateSpec.fixed_oracle.case_ids,
550
- )
551
- || receipt.case_results.some((result) => (
552
- !exactRecord(result, ['id', 'outcome', 'output_digest'])
553
- || result.outcome !== 'passed'
554
- || typeof result.output_digest !== 'string'
555
- || !/^[0-9a-f]{64}$/.test(result.output_digest)
556
- ))) {
557
- throw new TransformContractError(
558
- 'LATTICE_RC2_ORACLE_DIVERGENCE',
559
- 'fixed oracle receipt is invalid',
560
- );
561
- }
562
- }
563
-
564
- function oracleCaseSetDigest(receipt) {
565
- return digestArtifact({
566
- case_results: receipt.case_results.map(({ id, output_digest }) => ({ id, output_digest })),
567
- });
568
- }
569
-
570
- async function assertCompleteTransform(worktreePath, oracleDigest) {
571
- const changedPaths = statusPaths(await git(worktreePath, [
572
- 'status',
573
- '--porcelain=v1',
574
- '-z',
575
- '--untracked-files=all',
576
- '--ignored=matching',
577
- ]));
578
- const outside = changedPaths.find((relativePath) => (
579
- !RC2_DELIVERY_POLICY_TRANSFORM_PATHS.includes(relativePath)
580
- ));
581
- if (outside !== undefined) {
582
- throw new TransformContractError(
583
- 'LATTICE_RC2_SCOPE_VIOLATION',
584
- `writer changed a path outside the exact allowlist: ${outside}`,
585
- );
586
- }
587
- const oracle = await inspectPath(worktreePath, ORACLE_PATH);
588
- if (oracle.state !== 'present') {
589
- throw new TransformContractError(
590
- 'LATTICE_RC2_SCOPE_VIOLATION',
591
- 'fixed oracle was removed during writer execution',
592
- );
593
- }
594
- const actualOracleDigest = sha256(await readFile(oracle.path));
595
- if (actualOracleDigest !== oracleDigest) {
596
- throw new TransformContractError(
597
- 'LATTICE_RC2_SCOPE_VIOLATION',
598
- 'fixed oracle bytes changed during writer execution',
599
- );
600
- }
601
- for (const relativePath of RC2_DELIVERY_POLICY_TRANSFORM_PATHS) {
602
- await readRegularFile(worktreePath, relativePath);
603
- }
604
- }
605
-
606
- function testEnvironment() {
607
- const env = { ...process.env, NO_COLOR: '1' };
608
- delete env.NODE_TEST_CONTEXT;
609
- delete env.FORCE_COLOR;
610
- return env;
611
- }
612
-
613
- async function runMutationCell(worktreePath, contract) {
614
- const result = await spawnCapture(process.execPath, [
615
- '--test',
616
- '--test-reporter=dot',
617
- contract.path,
618
- ], { cwd: worktreePath, env: testEnvironment() });
619
- const exitCode = Number.isSafeInteger(result.code) && result.code >= 0 ? result.code : 1;
620
- return {
621
- test_id: contract.testId,
622
- path: contract.path,
623
- outcome: exitCode === 0 && result.signal === null ? 'passed' : 'failed',
624
- exit_code: exitCode,
625
- stdout_digest: sha256(result.stdout),
626
- stderr_digest: sha256(result.stderr),
627
- };
628
- }
629
-
630
- async function observeOracleMismatch(worktreePath, expectedCaseId) {
631
- try {
632
- await runRc2DeliveryPolicyOracle({ repoRoot: worktreePath });
633
- } catch (error) {
634
- const match = String(error?.message ?? error)
635
- .match(/delivery policy behavior mismatch: ([a-z]+-(?:routine|urgent))/);
636
- if (match?.[1] === expectedCaseId) return match[1];
637
- throw new TransformContractError(
638
- 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
639
- `mutation oracle mismatch was not ${expectedCaseId}`,
640
- );
641
- }
642
- throw new TransformContractError(
643
- 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
644
- `mutation oracle unexpectedly passed: ${expectedCaseId}`,
645
- );
646
- }
647
-
648
- async function runMutationMatrix({
649
- worktreePath,
650
- outputSnapshot,
651
- candidateDigest,
652
- caseSetDigest,
653
- }) {
654
- const rows = [];
655
- for (const mutation of MUTATIONS) {
656
- const original = await readRegularFile(worktreePath, mutation.owner.productionPath);
657
- const source = original.toString('utf8');
658
- if (source.split(mutation.needle).length !== 2) {
659
- throw new TransformContractError(
660
- 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
661
- `mutation target is not unique: ${mutation.caseId}`,
662
- );
663
- }
664
- await safeWrite(
665
- worktreePath,
666
- mutation.owner.productionPath,
667
- Buffer.from(source.replace(mutation.needle, mutation.replacement), 'utf8'),
668
- );
669
-
670
- let primaryError;
671
- let oracleMismatchId;
672
- let cells;
673
- try {
674
- oracleMismatchId = await observeOracleMismatch(worktreePath, mutation.caseId);
675
- cells = [];
676
- for (const contract of TEST_CONTRACTS) {
677
- cells.push(await runMutationCell(worktreePath, contract));
678
- }
679
- for (const cell of cells) {
680
- const owner = cell.test_id === mutation.owner.contract;
681
- if ((owner && (cell.outcome !== 'failed' || cell.exit_code === 0))
682
- || (!owner && (cell.outcome !== 'passed' || cell.exit_code !== 0))) {
683
- throw new TransformContractError(
684
- 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
685
- `owner-only test partition failed: ${mutation.caseId}/${cell.test_id}`,
686
- );
687
- }
688
- }
689
- } catch (error) {
690
- primaryError = error;
691
- }
692
-
693
- try {
694
- await safeWrite(worktreePath, mutation.owner.productionPath, original);
695
- } catch (error) {
696
- throw new TransformContractError(
697
- 'LATTICE_RC2_RESTORE_FAILURE',
698
- `mutation source restore failed: ${mutation.caseId}: ${error.message}`,
699
- );
700
- }
701
- const restored = await captureSurfaceSnapshot(worktreePath);
702
- if (restored.digest !== outputSnapshot.digest) {
703
- throw new TransformContractError(
704
- 'LATTICE_RC2_RESTORE_FAILURE',
705
- `mutation snapshot restore failed: ${mutation.caseId}`,
706
- );
707
- }
708
- if (primaryError) throw primaryError;
709
-
710
- rows.push({
711
- case_id: mutation.caseId,
712
- owner_todo_id: mutation.owner.todoId,
713
- resolver_symbol: mutation.owner.resolver,
714
- mutated_path: mutation.owner.productionPath,
715
- oracle_mismatch_id: oracleMismatchId,
716
- cells,
717
- restore_digest: restored.digest,
718
- });
719
- }
720
- const matrixDigest = digestArtifact({ rows });
721
- const value = {
722
- schema: 'lattice.rc2.delivery_policy_mutation_evidence.v1',
723
- candidate_digest: candidateDigest,
724
- case_set_digest: caseSetDigest,
725
- rows,
726
- matrix_digest: matrixDigest,
727
- };
728
- return { ...value, evidence_digest: digestArtifact(value) };
729
- }
730
-
731
- function makeBehaviorEvidence({
732
- candidateDigest,
733
- adapterSourceDigest,
734
- controlSnapshot,
735
- outputSnapshot,
736
- oracleBytes,
737
- oracleDigest,
738
- preOracle,
739
- postOracle,
740
- }) {
741
- const value = {
742
- schema: 'lattice.rc2.delivery_policy_behavior_evidence.v1',
743
- candidate_digest: candidateDigest,
744
- adapter_source_digest: adapterSourceDigest,
745
- control_snapshot: structuredClone(controlSnapshot),
746
- output_snapshot: structuredClone(outputSnapshot),
747
- fixed_oracle: {
748
- path: ORACLE_PATH,
749
- source_base64: oracleBytes.toString('base64'),
750
- source_digest: oracleDigest,
751
- },
752
- pre_oracle: structuredClone(preOracle),
753
- post_oracle: structuredClone(postOracle),
754
- case_set_digest: oracleCaseSetDigest(preOracle),
755
- equivalent: true,
756
- };
757
- return { ...value, evidence_digest: digestArtifact(value) };
758
- }
759
-
760
- function makeCleanupReceipt(beforeCount, afterCount, forcedFailure = false) {
761
- return {
762
- schema: 'lattice.rc2.delivery_policy_cleanup_receipt.v1',
763
- outcome: !forcedFailure && beforeCount === afterCount ? 'passed' : 'failed',
764
- worktree_count_before: beforeCount,
765
- worktree_count_after: afterCount,
766
- };
767
- }
768
-
769
- function makeReceipt({
770
- status,
771
- artifactDigest,
772
- behaviorEvidenceDigest,
773
- mutationEvidenceDigest,
774
- sourceInvariant,
775
- cleanup,
776
- }) {
777
- const value = {
778
- schema: 'lattice.rc2.delivery_policy_transform_receipt.v1',
779
- status,
780
- transform_artifact_digest: artifactDigest,
781
- behavior_evidence_digest: behaviorEvidenceDigest,
782
- mutation_evidence_digest: mutationEvidenceDigest,
783
- source_invariant: sourceInvariant ?? null,
784
- cleanup: structuredClone(cleanup),
785
- };
786
- return { ...value, receipt_digest: digestArtifact(value) };
787
- }
788
-
789
- function makeResult({ artifact, patch, behaviorEvidence, mutationEvidence, cleanup, sourceInvariant }) {
790
- const artifactDigest = digestArtifact(artifact);
791
- const receipt = makeReceipt({
792
- status: artifact.status,
793
- artifactDigest,
794
- behaviorEvidenceDigest: behaviorEvidence?.evidence_digest ?? null,
795
- mutationEvidenceDigest: mutationEvidence?.evidence_digest ?? null,
796
- sourceInvariant,
797
- cleanup,
798
- });
799
- return {
800
- schema: 'lattice.rc2.delivery_policy_seam_transform_result.v1',
801
- status: artifact.status,
802
- artifact,
803
- artifact_digest: artifactDigest,
804
- receipt,
805
- receipt_digest: receipt.receipt_digest,
806
- patch: Buffer.isBuffer(patch) ? Buffer.from(patch) : null,
807
- behavior_evidence: behaviorEvidence ? structuredClone(behaviorEvidence) : null,
808
- mutation_evidence: mutationEvidence ? structuredClone(mutationEvidence) : null,
809
- };
810
- }
811
-
812
- function flattenErrors(error) {
813
- if (error instanceof AggregateError) return error.errors.flatMap(flattenErrors);
814
- return [error];
815
- }
816
-
817
- function transformEvidence(error) {
818
- return flattenErrors(error)
819
- .map((entry) => entry?.transformEvidence)
820
- .find((entry) => entry && typeof entry.baseSha === 'string');
821
- }
822
-
823
- function rejectionFacts(error) {
824
- const errors = flattenErrors(error);
825
- const codes = new Set(errors.map((entry) => entry?.code).filter(Boolean));
826
- const messages = errors.map((entry) => String(entry?.message ?? entry)).join('\n');
827
- if (codes.has('LATTICE_RC2_INCOMPLETE_TRANSFORM')) {
828
- return { kind: 'incomplete_transform', reason: 'required production or test seam is incomplete' };
829
- }
830
- if (codes.has('LATTICE_RC2_SCOPE_VIOLATION')
831
- || /outside allowed paths|symlink change|submodule change|special file change/i.test(messages)) {
832
- return { kind: 'scope_violation', reason: 'transform changed or traversed a forbidden surface' };
833
- }
834
- if (codes.has('LATTICE_RC2_MUTATION_MATRIX_FAILURE')) {
835
- return { kind: 'mutation_matrix_failure', reason: 'owner-only mutation sensitivity was not proven' };
836
- }
837
- if (codes.has('LATTICE_RC2_RESTORE_FAILURE')) {
838
- return { kind: 'restore_failure', reason: 'mutation bytes did not restore to the accepted snapshot' };
839
- }
840
- if (codes.has('LATTICE_RC2_ORACLE_DIVERGENCE')
841
- || /delivery policy behavior mismatch|oracle child failed/i.test(messages)) {
842
- return { kind: 'oracle_divergence', reason: 'fixed oracle did not preserve the ordered behavior set' };
843
- }
844
- if (/verifier failed/i.test(messages)) {
845
- return { kind: 'behavior_verification_failed', reason: 'focused production or test seam verifier failed' };
846
- }
847
- if (/mutated isolated snapshot/i.test(messages)) {
848
- return { kind: 'snapshot_mutation', reason: 'observer or verifier changed the accepted isolated patch' };
849
- }
850
- if (/source repository changed/i.test(messages)) {
851
- return { kind: 'source_invariant_violation', reason: 'canonical source changed during isolation' };
852
- }
853
- if (/cleanup failed/i.test(messages)) {
854
- return { kind: 'cleanup_failure', reason: 'disposable worktree cleanup failed' };
855
- }
856
- if (codes.has('LATTICE_RC2_CLEANUP_FAILURE')) {
857
- return { kind: 'cleanup_failure', reason: 'disposable worktree cleanup evidence failed' };
858
- }
859
- return { kind: 'execution_failure', reason: 'isolated delivery policy transaction failed' };
860
- }
861
-
862
- function verificationArtifact(status, receipts) {
863
- return { status, receipts: structuredClone(receipts) };
864
- }
865
-
866
- function rejectedResult({
867
- error,
868
- evidence,
869
- candidate,
870
- candidateDigest,
871
- baseSha,
872
- adapterSourceDigest,
873
- controlSnapshot,
874
- oracleDigest,
875
- beforeCount,
876
- afterCount,
877
- }) {
878
- const facts = rejectionFacts(error);
879
- const errors = flattenErrors(error);
880
- const messages = errors.map((entry) => String(entry?.message ?? entry));
881
- const cleanup = makeCleanupReceipt(
882
- beforeCount,
883
- afterCount,
884
- messages.some((message) => /cleanup failed/i.test(message)),
885
- );
886
- const sourceInvariant = evidence?.sourceInvariant ?? null;
887
- const patch = Buffer.isBuffer(evidence?.patch) ? evidence.patch : null;
888
- const receipts = Array.isArray(evidence?.verifications) ? evidence.verifications : [];
889
- const verificationStatus = receipts.length === 0
890
- ? 'not_run'
891
- : (receipts.some(({ outcome }) => outcome !== 'passed') ? 'failed' : 'passed');
892
- const rejection = {
893
- kind: facts.kind,
894
- reasons: [facts.reason],
895
- };
896
- const artifact = {
897
- schema: 'lattice.rc2.delivery_policy_transform_artifact.v1',
898
- status: 'rejected',
899
- candidate: {
900
- candidate_id: candidate.candidate_id,
901
- digest: candidateDigest,
902
- },
903
- source: {
904
- base_sha: baseSha,
905
- adapter: { path: ADAPTER_PATH, digest: adapterSourceDigest },
906
- control_snapshot_digest: controlSnapshot.digest,
907
- fixed_oracle: { path: ORACLE_PATH, source_digest: oracleDigest },
908
- },
909
- scope: {
910
- allowed_paths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
911
- changed_paths: Array.isArray(evidence?.changedPaths) ? [...evidence.changedPaths] : [],
912
- },
913
- patch: { digest: patch ? sha256(patch) : null, bytes: patch?.byteLength ?? 0 },
914
- output: null,
915
- behavior: null,
916
- mutation: null,
917
- verification: verificationArtifact(verificationStatus, receipts),
918
- cleanup: {
919
- status: cleanup.outcome,
920
- source_status: sourceInvariant?.outcome === 'passed'
921
- ? 'unchanged'
922
- : (sourceInvariant?.outcome === 'failed' ? 'changed' : 'unresolved'),
923
- receipt_digest: digestArtifact(cleanup),
924
- },
925
- rejection: { ...rejection, evidence_digest: digestArtifact(rejection) },
926
- };
927
- return makeResult({
928
- artifact,
929
- patch,
930
- behaviorEvidence: null,
931
- mutationEvidence: null,
932
- cleanup,
933
- sourceInvariant,
934
- });
935
- }
936
-
937
- /** 3 channel resolverと対応test seamをdisposable worktreeへ決定的に書く。 */
938
- export async function applyRc2DeliveryPolicyTransform(options = {}) {
939
- if (!exactRecord(options, ['worktreePath'])
940
- || typeof options.worktreePath !== 'string'
941
- || options.worktreePath.length === 0) {
942
- throw new TypeError('applyRc2DeliveryPolicyTransform requires exact worktreePath');
943
- }
944
- const worktreePath = await realpath(options.worktreePath);
945
- for (const relativePath of RC2_DELIVERY_POLICY_TRANSFORM_PATHS) {
946
- await safeWrite(worktreePath, relativePath, Buffer.from(WRITER_FILES.get(relativePath), 'utf8'));
947
- }
948
- }
949
-
950
- /** actual preimageから隔離transform、oracle、mutation matrix、cleanupを一transactionで実行する。 */
951
- export async function runRc2DeliveryPolicySeamTransform(options = {}) {
952
- if (!exactRecord(options, ['repoRoot', 'baseRef', 'candidateSpec'])
953
- && !exactRecord(options, ['repoRoot', 'baseRef', 'candidateSpec', 'transform'])) {
954
- throw new TypeError('runRc2DeliveryPolicySeamTransform options have an invalid shape');
955
- }
956
- const {
957
- repoRoot,
958
- baseRef,
959
- candidateSpec,
960
- transform = applyRc2DeliveryPolicyTransform,
961
- } = options;
962
- if (typeof transform !== 'function') throw new TypeError('transform must be a function');
963
-
964
- const { candidateDigest, fixedCandidate } = assertAcceptedCandidate(candidateSpec);
965
- const { root, baseSha } = await resolveRepository(repoRoot, baseRef);
966
- const controlSnapshot = await captureSurfaceSnapshot(root);
967
- assertControlSnapshot(controlSnapshot);
968
- const oracleBytes = await readRegularFile(root, ORACLE_PATH);
969
- const oracleDigest = sha256(oracleBytes);
970
- if (oracleDigest !== fixedCandidate.fixed_oracle.source_digest) {
971
- throw new TypeError('fixed oracle source digest differs from the accepted candidate');
972
- }
973
- const adapterSourceDigest = sha256(await readFile(new URL(import.meta.url)));
974
- const preOracle = await runRc2DeliveryPolicyOracle({ repoRoot: root });
975
- assertOracleReceipt(preOracle, fixedCandidate);
976
- const beforeCount = await worktreeCount(root);
977
-
978
- let isolated;
979
- let postOracle;
980
- let outputSnapshot;
981
- let mutationEvidence;
982
- try {
983
- isolated = await runIsolatedTransform({
984
- repoRoot: root,
985
- baseRef: baseSha,
986
- allowedPaths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
987
- transform: async ({ worktreePath }) => {
988
- await transform({ worktreePath });
989
- await assertCompleteTransform(worktreePath, oracleDigest);
990
- },
991
- verifyCommands: TEST_CONTRACTS.map((contract) => ({
992
- command: process.execPath,
993
- args: ['--test', '--test-reporter=dot', contract.path],
994
- })),
995
- observe: async ({ worktreePath, changedPaths }) => {
996
- if (!sameArray(changedPaths, RC2_DELIVERY_POLICY_TRANSFORM_PATHS)) {
997
- throw new TransformContractError(
998
- 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
999
- 'accepted writer must change the exact eight allowed paths',
1000
- );
1001
- }
1002
- postOracle = await runRc2DeliveryPolicyOracle({ repoRoot: worktreePath });
1003
- assertOracleReceipt(postOracle, fixedCandidate);
1004
- if (digestArtifact(postOracle) !== digestArtifact(preOracle)) {
1005
- throw new TransformContractError(
1006
- 'LATTICE_RC2_ORACLE_DIVERGENCE',
1007
- 'pre and post fixed oracle receipts differ',
1008
- );
1009
- }
1010
- outputSnapshot = await captureSurfaceSnapshot(worktreePath);
1011
- assertOutputSnapshot(outputSnapshot, oracleDigest);
1012
- mutationEvidence = await runMutationMatrix({
1013
- worktreePath,
1014
- outputSnapshot,
1015
- candidateDigest,
1016
- caseSetDigest: oracleCaseSetDigest(preOracle),
1017
- });
1018
- const afterMatrix = await captureSurfaceSnapshot(worktreePath);
1019
- if (afterMatrix.digest !== outputSnapshot.digest) {
1020
- throw new TransformContractError(
1021
- 'LATTICE_RC2_RESTORE_FAILURE',
1022
- 'mutation matrix leaked bytes into the accepted snapshot',
1023
- );
1024
- }
1025
- },
1026
- });
1027
- const afterCount = await worktreeCount(root);
1028
- const cleanup = makeCleanupReceipt(beforeCount, afterCount);
1029
- if (cleanup.outcome !== 'passed') {
1030
- throw new TransformContractError(
1031
- 'LATTICE_RC2_CLEANUP_FAILURE',
1032
- 'disposable worktree count changed after cleanup',
1033
- );
1034
- }
1035
- if (!sameArray(isolated.changedPaths, RC2_DELIVERY_POLICY_TRANSFORM_PATHS)
1036
- || !Buffer.isBuffer(isolated.patch)
1037
- || isolated.verifications.length !== TEST_CONTRACTS.length
1038
- || isolated.verifications.some(({ outcome }) => outcome !== 'passed')
1039
- || isolated.sourceInvariant?.outcome !== 'passed'
1040
- || !postOracle
1041
- || !outputSnapshot
1042
- || !mutationEvidence) {
1043
- throw new TransformContractError(
1044
- 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
1045
- 'isolated transaction did not produce the complete accepted evidence set',
1046
- );
1047
- }
1048
-
1049
- const behaviorEvidence = makeBehaviorEvidence({
1050
- candidateDigest,
1051
- adapterSourceDigest,
1052
- controlSnapshot,
1053
- outputSnapshot,
1054
- oracleBytes,
1055
- oracleDigest,
1056
- preOracle,
1057
- postOracle,
1058
- });
1059
- const artifact = {
1060
- schema: 'lattice.rc2.delivery_policy_transform_artifact.v1',
1061
- status: 'accepted',
1062
- candidate: {
1063
- candidate_id: fixedCandidate.candidate_id,
1064
- digest: candidateDigest,
1065
- },
1066
- source: {
1067
- base_sha: baseSha,
1068
- adapter: { path: ADAPTER_PATH, digest: adapterSourceDigest },
1069
- control_snapshot_digest: controlSnapshot.digest,
1070
- fixed_oracle: { path: ORACLE_PATH, source_digest: oracleDigest },
1071
- },
1072
- scope: {
1073
- allowed_paths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
1074
- changed_paths: [...isolated.changedPaths],
1075
- },
1076
- patch: { digest: sha256(isolated.patch), bytes: isolated.patch.byteLength },
1077
- output: {
1078
- snapshot_digest: outputSnapshot.digest,
1079
- files: structuredClone(outputSnapshot.files),
1080
- },
1081
- behavior: {
1082
- evidence_digest: behaviorEvidence.evidence_digest,
1083
- pre_oracle_digest: digestArtifact(preOracle),
1084
- post_oracle_digest: digestArtifact(postOracle),
1085
- case_set_digest: behaviorEvidence.case_set_digest,
1086
- equivalent: true,
1087
- },
1088
- mutation: {
1089
- evidence_digest: mutationEvidence.evidence_digest,
1090
- matrix_digest: mutationEvidence.matrix_digest,
1091
- row_count: mutationEvidence.rows.length,
1092
- cell_count: mutationEvidence.rows.reduce((sum, row) => sum + row.cells.length, 0),
1093
- },
1094
- verification: verificationArtifact('passed', isolated.verifications),
1095
- cleanup: {
1096
- status: 'passed',
1097
- source_status: 'unchanged',
1098
- receipt_digest: digestArtifact(cleanup),
1099
- },
1100
- rejection: null,
1101
- };
1102
- return makeResult({
1103
- artifact,
1104
- patch: isolated.patch,
1105
- behaviorEvidence,
1106
- mutationEvidence,
1107
- cleanup,
1108
- sourceInvariant: isolated.sourceInvariant,
1109
- });
1110
- } catch (error) {
1111
- const afterCount = await worktreeCount(root);
1112
- const evidence = transformEvidence(error) ?? isolated;
1113
- if (!evidence || typeof evidence.baseSha !== 'string') throw error;
1114
- return rejectedResult({
1115
- error,
1116
- evidence,
1117
- candidate: fixedCandidate,
1118
- candidateDigest,
1119
- baseSha,
1120
- adapterSourceDigest,
1121
- controlSnapshot,
1122
- oracleDigest,
1123
- beforeCount,
1124
- afterCount,
1125
- });
1126
- }
1127
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ readFile,
7
+ realpath,
8
+ writeFile,
9
+ } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+
12
+ import { digestArtifact } from './artifact-contracts.mjs';
13
+ import { runIsolatedTransform } from './isolation-runner.mjs';
14
+ import { runRc2DeliveryPolicyOracle } from './rc2-delivery-policy-oracle.mjs';
15
+
16
+ const ADAPTER_PATH = 'src/rc2-delivery-policy-transform.mjs';
17
+ const ENTRY_PATH = 'research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
18
+ const ORACLE_PATH = 'src/rc2-delivery-policy-oracle.mjs';
19
+ const SHARED_TEST_PATH = 'test/rc2-delivery-policy-fixture.test.mjs';
20
+ const EXPECTED_CANDIDATE_ID = 'shard-delivery-policy-registry-by-channel';
21
+ const EXPECTED_CANDIDATE_DIGEST = '4cc5d7bb428a8899353d18524c25105742fa90f89ee55d36064c4be3c52e2907';
22
+ const GIT_SHA1 = /^[0-9a-f]{40}$/;
23
+
24
+ export const RC2_DELIVERY_POLICY_TRANSFORM_PATHS = Object.freeze([
25
+ ENTRY_PATH,
26
+ 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
27
+ 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
28
+ 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
29
+ 'test/rc2-delivery-policy-email.test.mjs',
30
+ SHARED_TEST_PATH,
31
+ 'test/rc2-delivery-policy-push.test.mjs',
32
+ 'test/rc2-delivery-policy-sms.test.mjs',
33
+ ]);
34
+
35
+ const SURFACE_PATHS = Object.freeze([
36
+ ...RC2_DELIVERY_POLICY_TRANSFORM_PATHS,
37
+ ORACLE_PATH,
38
+ ].sort());
39
+
40
+ const CURRENT_PATHS = new Set([ENTRY_PATH, SHARED_TEST_PATH, ORACLE_PATH]);
41
+
42
+ const CHANNELS = Object.freeze({
43
+ email: Object.freeze({
44
+ todoId: 'email-policy',
45
+ resolver: 'resolveEmailPolicy',
46
+ productionPath: 'research/fixtures/delivery-policy-registry/src/email-policy.mjs',
47
+ contract: 'emailPolicyContract',
48
+ testPath: 'test/rc2-delivery-policy-email.test.mjs',
49
+ caseIds: Object.freeze(['email-routine', 'email-urgent']),
50
+ }),
51
+ sms: Object.freeze({
52
+ todoId: 'sms-policy',
53
+ resolver: 'resolveSmsPolicy',
54
+ productionPath: 'research/fixtures/delivery-policy-registry/src/sms-policy.mjs',
55
+ contract: 'smsPolicyContract',
56
+ testPath: 'test/rc2-delivery-policy-sms.test.mjs',
57
+ caseIds: Object.freeze(['sms-routine', 'sms-urgent']),
58
+ }),
59
+ push: Object.freeze({
60
+ todoId: 'push-policy',
61
+ resolver: 'resolvePushPolicy',
62
+ productionPath: 'research/fixtures/delivery-policy-registry/src/push-policy.mjs',
63
+ contract: 'pushPolicyContract',
64
+ testPath: 'test/rc2-delivery-policy-push.test.mjs',
65
+ caseIds: Object.freeze(['push-routine', 'push-urgent']),
66
+ }),
67
+ });
68
+
69
+ const TEST_CONTRACTS = Object.freeze([
70
+ Object.freeze({ testId: CHANNELS.email.contract, path: CHANNELS.email.testPath }),
71
+ Object.freeze({ testId: CHANNELS.sms.contract, path: CHANNELS.sms.testPath }),
72
+ Object.freeze({ testId: CHANNELS.push.contract, path: CHANNELS.push.testPath }),
73
+ Object.freeze({ testId: 'deliveryPolicyCompositionContract', path: SHARED_TEST_PATH }),
74
+ ]);
75
+
76
+ const MUTATIONS = Object.freeze([
77
+ Object.freeze({
78
+ caseId: 'email-routine',
79
+ owner: CHANNELS.email,
80
+ needle: "routine: Object.freeze({ transport: 'smtp', retry_limit: 3, delay_seconds: 60 }),",
81
+ replacement: "routine: Object.freeze({ transport: 'smtp', retry_limit: 103, delay_seconds: 60 }),",
82
+ }),
83
+ Object.freeze({
84
+ caseId: 'email-urgent',
85
+ owner: CHANNELS.email,
86
+ needle: "urgent: Object.freeze({ transport: 'smtp', retry_limit: 5, delay_seconds: 0 }),",
87
+ replacement: "urgent: Object.freeze({ transport: 'smtp', retry_limit: 105, delay_seconds: 0 }),",
88
+ }),
89
+ Object.freeze({
90
+ caseId: 'sms-routine',
91
+ owner: CHANNELS.sms,
92
+ needle: "routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 30 }),",
93
+ replacement: "routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 130 }),",
94
+ }),
95
+ Object.freeze({
96
+ caseId: 'sms-urgent',
97
+ owner: CHANNELS.sms,
98
+ needle: "urgent: Object.freeze({ transport: 'sms', retry_limit: 4, delay_seconds: 0 }),",
99
+ replacement: "urgent: Object.freeze({ transport: 'sms', retry_limit: 104, delay_seconds: 0 }),",
100
+ }),
101
+ Object.freeze({
102
+ caseId: 'push-routine',
103
+ owner: CHANNELS.push,
104
+ needle: "routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 10 }),",
105
+ replacement: "routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 110 }),",
106
+ }),
107
+ Object.freeze({
108
+ caseId: 'push-urgent',
109
+ owner: CHANNELS.push,
110
+ needle: "urgent: Object.freeze({ transport: 'push', retry_limit: 3, delay_seconds: 0 }),",
111
+ replacement: "urgent: Object.freeze({ transport: 'push', retry_limit: 103, delay_seconds: 0 }),",
112
+ }),
113
+ ]);
114
+
115
+ const ENTRY_SOURCE = `import { resolveEmailPolicy } from './email-policy.mjs';
116
+ import { resolvePushPolicy } from './push-policy.mjs';
117
+ import { resolveSmsPolicy } from './sms-policy.mjs';
118
+
119
+ const INPUT_KEYS = Object.freeze(['channel', 'urgency']);
120
+
121
+ function isPlainObject(value) {
122
+ return value !== null
123
+ && typeof value === 'object'
124
+ && !Array.isArray(value)
125
+ && Object.getPrototypeOf(value) === Object.prototype;
126
+ }
127
+
128
+ function hasExactInputKeys(value) {
129
+ if (!isPlainObject(value)) return false;
130
+ const keys = Object.keys(value).sort();
131
+ return keys.length === INPUT_KEYS.length
132
+ && keys.every((key, index) => key === INPUT_KEYS[index]);
133
+ }
134
+
135
+ /** 公開inputを検証し、channel別resolverへroutingするcomposition entry。 */
136
+ export function resolveDeliveryPolicy(input) {
137
+ if (!hasExactInputKeys(input)) {
138
+ throw new TypeError('delivery policy input must be a plain object with exact keys: channel, urgency');
139
+ }
140
+ let policy;
141
+ if (input.channel === 'email') {
142
+ policy = resolveEmailPolicy(input.urgency);
143
+ } else if (input.channel === 'push') {
144
+ policy = resolvePushPolicy(input.urgency);
145
+ } else if (input.channel === 'sms') {
146
+ policy = resolveSmsPolicy(input.urgency);
147
+ } else {
148
+ throw new RangeError('channel must be email, sms, or push');
149
+ }
150
+ return { channel: input.channel, ...policy };
151
+ }
152
+ `;
153
+
154
+ const EMAIL_SOURCE = `const POLICIES = Object.freeze({
155
+ routine: Object.freeze({ transport: 'smtp', retry_limit: 3, delay_seconds: 60 }),
156
+ urgent: Object.freeze({ transport: 'smtp', retry_limit: 5, delay_seconds: 0 }),
157
+ });
158
+
159
+ export function resolveEmailPolicy(urgency) {
160
+ if (!Object.hasOwn(POLICIES, urgency)) {
161
+ throw new RangeError('urgency must be routine or urgent');
162
+ }
163
+ return { ...POLICIES[urgency] };
164
+ }
165
+ `;
166
+
167
+ const SMS_SOURCE = `const POLICIES = Object.freeze({
168
+ routine: Object.freeze({ transport: 'sms', retry_limit: 2, delay_seconds: 30 }),
169
+ urgent: Object.freeze({ transport: 'sms', retry_limit: 4, delay_seconds: 0 }),
170
+ });
171
+
172
+ export function resolveSmsPolicy(urgency) {
173
+ if (!Object.hasOwn(POLICIES, urgency)) {
174
+ throw new RangeError('urgency must be routine or urgent');
175
+ }
176
+ return { ...POLICIES[urgency] };
177
+ }
178
+ `;
179
+
180
+ const PUSH_SOURCE = `const POLICIES = Object.freeze({
181
+ routine: Object.freeze({ transport: 'push', retry_limit: 1, delay_seconds: 10 }),
182
+ urgent: Object.freeze({ transport: 'push', retry_limit: 3, delay_seconds: 0 }),
183
+ });
184
+
185
+ export function resolvePushPolicy(urgency) {
186
+ if (!Object.hasOwn(POLICIES, urgency)) {
187
+ throw new RangeError('urgency must be routine or urgent');
188
+ }
189
+ return { ...POLICIES[urgency] };
190
+ }
191
+ `;
192
+
193
+ const EMAIL_TEST_SOURCE = `import assert from 'node:assert/strict';
194
+ import test from 'node:test';
195
+
196
+ import { resolveEmailPolicy } from '../research/fixtures/delivery-policy-registry/src/email-policy.mjs';
197
+
198
+ export function emailPolicyContract() {
199
+ assert.deepEqual(resolveEmailPolicy('routine'), {
200
+ transport: 'smtp', retry_limit: 3, delay_seconds: 60,
201
+ });
202
+ assert.deepEqual(resolveEmailPolicy('urgent'), {
203
+ transport: 'smtp', retry_limit: 5, delay_seconds: 0,
204
+ });
205
+ }
206
+
207
+ test('email-routine and email-urgent policy contract', emailPolicyContract);
208
+ `;
209
+
210
+ const SMS_TEST_SOURCE = `import assert from 'node:assert/strict';
211
+ import test from 'node:test';
212
+
213
+ import { resolveSmsPolicy } from '../research/fixtures/delivery-policy-registry/src/sms-policy.mjs';
214
+
215
+ export function smsPolicyContract() {
216
+ assert.deepEqual(resolveSmsPolicy('routine'), {
217
+ transport: 'sms', retry_limit: 2, delay_seconds: 30,
218
+ });
219
+ assert.deepEqual(resolveSmsPolicy('urgent'), {
220
+ transport: 'sms', retry_limit: 4, delay_seconds: 0,
221
+ });
222
+ }
223
+
224
+ test('sms-routine and sms-urgent policy contract', smsPolicyContract);
225
+ `;
226
+
227
+ const PUSH_TEST_SOURCE = `import assert from 'node:assert/strict';
228
+ import test from 'node:test';
229
+
230
+ import { resolvePushPolicy } from '../research/fixtures/delivery-policy-registry/src/push-policy.mjs';
231
+
232
+ export function pushPolicyContract() {
233
+ assert.deepEqual(resolvePushPolicy('routine'), {
234
+ transport: 'push', retry_limit: 1, delay_seconds: 10,
235
+ });
236
+ assert.deepEqual(resolvePushPolicy('urgent'), {
237
+ transport: 'push', retry_limit: 3, delay_seconds: 0,
238
+ });
239
+ }
240
+
241
+ test('push-routine and push-urgent policy contract', pushPolicyContract);
242
+ `;
243
+
244
+ const SHARED_TEST_SOURCE = `import assert from 'node:assert/strict';
245
+ import test from 'node:test';
246
+
247
+ import { resolveDeliveryPolicy } from '../research/fixtures/delivery-policy-registry/src/delivery-policy-registry.mjs';
248
+
249
+ export function deliveryPolicyCompositionContract() {
250
+ for (const channel of ['email', 'sms', 'push']) {
251
+ const output = resolveDeliveryPolicy({ channel, urgency: 'routine' });
252
+ assert.equal(output.channel, channel);
253
+ assert.deepEqual(Object.keys(output).sort(), [
254
+ 'channel', 'delay_seconds', 'retry_limit', 'transport',
255
+ ]);
256
+ assert.equal(typeof output.transport, 'string');
257
+ assert.equal(typeof output.retry_limit, 'number');
258
+ assert.equal(typeof output.delay_seconds, 'number');
259
+ }
260
+ assert.throws(() => resolveDeliveryPolicy(null), { name: 'TypeError' });
261
+ assert.throws(() => resolveDeliveryPolicy({ channel: 'email' }), { name: 'TypeError' });
262
+ assert.throws(
263
+ () => resolveDeliveryPolicy({ channel: 'email', urgency: 'routine', extra: true }),
264
+ { name: 'TypeError' },
265
+ );
266
+ assert.throws(
267
+ () => resolveDeliveryPolicy({ channel: 'webhook', urgency: 'routine' }),
268
+ { name: 'RangeError' },
269
+ );
270
+ assert.throws(
271
+ () => resolveDeliveryPolicy({ channel: 'email', urgency: 'later' }),
272
+ { name: 'RangeError' },
273
+ );
274
+ }
275
+
276
+ test('delivery policy composition routing, shape, and fail-loud contract',
277
+ deliveryPolicyCompositionContract);
278
+ `;
279
+
280
+ const WRITER_FILES = new Map([
281
+ [ENTRY_PATH, ENTRY_SOURCE],
282
+ [CHANNELS.email.productionPath, EMAIL_SOURCE],
283
+ [CHANNELS.push.productionPath, PUSH_SOURCE],
284
+ [CHANNELS.sms.productionPath, SMS_SOURCE],
285
+ [CHANNELS.email.testPath, EMAIL_TEST_SOURCE],
286
+ [SHARED_TEST_PATH, SHARED_TEST_SOURCE],
287
+ [CHANNELS.push.testPath, PUSH_TEST_SOURCE],
288
+ [CHANNELS.sms.testPath, SMS_TEST_SOURCE],
289
+ ]);
290
+
291
+ class TransformContractError extends Error {
292
+ constructor(code, message) {
293
+ super(message);
294
+ this.name = 'TransformContractError';
295
+ this.code = code;
296
+ }
297
+ }
298
+
299
+ function isPlainObject(value) {
300
+ return value !== null
301
+ && typeof value === 'object'
302
+ && !Array.isArray(value)
303
+ && Object.getPrototypeOf(value) === Object.prototype;
304
+ }
305
+
306
+ function exactRecord(value, keys) {
307
+ if (!isPlainObject(value)) return false;
308
+ const actual = Object.keys(value).sort();
309
+ const expected = [...keys].sort();
310
+ return actual.length === expected.length
311
+ && actual.every((key, index) => key === expected[index]);
312
+ }
313
+
314
+ function sha256(value) {
315
+ return createHash('sha256').update(value).digest('hex');
316
+ }
317
+
318
+ function sameArray(left, right) {
319
+ return Array.isArray(left)
320
+ && Array.isArray(right)
321
+ && left.length === right.length
322
+ && left.every((entry, index) => entry === right[index]);
323
+ }
324
+
325
+ function statusPaths(status) {
326
+ const fields = status.split('\0');
327
+ const paths = [];
328
+ for (let index = 0; index < fields.length - 1; index += 1) {
329
+ const entry = fields[index];
330
+ if (!entry) continue;
331
+ const code = entry.slice(0, 2);
332
+ paths.push(entry.slice(3));
333
+ if (code[0] === 'R' || code[0] === 'C') paths.push(fields[++index]);
334
+ }
335
+ return [...new Set(paths)].sort();
336
+ }
337
+
338
+ function spawnCapture(command, args, { cwd, env } = {}) {
339
+ return new Promise((resolve, reject) => {
340
+ const child = spawn(command, args, {
341
+ cwd,
342
+ env,
343
+ shell: false,
344
+ stdio: ['ignore', 'pipe', 'pipe'],
345
+ });
346
+ const stdout = [];
347
+ const stderr = [];
348
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
349
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
350
+ child.once('error', reject);
351
+ child.once('close', (code, signal) => resolve({
352
+ code,
353
+ signal,
354
+ stdout: Buffer.concat(stdout),
355
+ stderr: Buffer.concat(stderr),
356
+ }));
357
+ });
358
+ }
359
+
360
+ async function git(repoRoot, args) {
361
+ const result = await spawnCapture('git', ['-C', repoRoot, ...args]);
362
+ if (result.code !== 0 || result.signal !== null) {
363
+ throw new Error(`git ${args[0]} failed: ${result.stderr.toString('utf8').trim()}`);
364
+ }
365
+ return result.stdout.toString('utf8');
366
+ }
367
+
368
+ async function resolveRepository(repoRoot, baseRef) {
369
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0
370
+ || typeof baseRef !== 'string' || baseRef.length === 0) {
371
+ throw new TypeError('repoRoot and baseRef must be non-empty strings');
372
+ }
373
+ const root = await realpath(repoRoot);
374
+ const status = await git(root, ['status', '--porcelain=v1', '-z']);
375
+ if (status.length !== 0) throw new Error('canonical source repository must be clean');
376
+ const head = (await git(root, ['rev-parse', '--verify', 'HEAD^{commit}'])).trim();
377
+ const baseSha = (await git(root, ['rev-parse', '--verify', `${baseRef}^{commit}`])).trim();
378
+ if (!GIT_SHA1.test(head) || !GIT_SHA1.test(baseSha)) {
379
+ throw new TypeError('HEAD or baseRef did not resolve to a Git SHA-1');
380
+ }
381
+ if (head !== baseSha) throw new Error('canonical HEAD must equal the exact baseRef commit');
382
+ return { root, baseSha };
383
+ }
384
+
385
+ async function worktreeCount(repoRoot) {
386
+ const output = await git(repoRoot, ['worktree', 'list', '--porcelain']);
387
+ return output.split('\n').filter((line) => line.startsWith('worktree ')).length;
388
+ }
389
+
390
+ async function inspectPath(repoRoot, relativePath) {
391
+ const segments = relativePath.split('/');
392
+ let current = repoRoot;
393
+ for (let index = 0; index < segments.length; index += 1) {
394
+ current = path.join(current, segments[index]);
395
+ let stat;
396
+ try {
397
+ stat = await lstat(current);
398
+ } catch (error) {
399
+ if (error?.code === 'ENOENT') return { state: 'absent', path: current };
400
+ throw error;
401
+ }
402
+ if (stat.isSymbolicLink()) {
403
+ throw new TransformContractError(
404
+ 'LATTICE_RC2_SCOPE_VIOLATION',
405
+ `symlink surface is not allowed: ${relativePath}`,
406
+ );
407
+ }
408
+ if (index < segments.length - 1 && !stat.isDirectory()) {
409
+ throw new TransformContractError(
410
+ 'LATTICE_RC2_SCOPE_VIOLATION',
411
+ `non-directory surface ancestor is not allowed: ${relativePath}`,
412
+ );
413
+ }
414
+ if (index === segments.length - 1 && !stat.isFile()) {
415
+ throw new TransformContractError(
416
+ 'LATTICE_RC2_SCOPE_VIOLATION',
417
+ `special surface is not allowed: ${relativePath}`,
418
+ );
419
+ }
420
+ }
421
+ return { state: 'present', path: current };
422
+ }
423
+
424
+ async function readRegularFile(repoRoot, relativePath) {
425
+ const inspected = await inspectPath(repoRoot, relativePath);
426
+ if (inspected.state !== 'present') {
427
+ throw new TransformContractError(
428
+ 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
429
+ `required transform surface is absent: ${relativePath}`,
430
+ );
431
+ }
432
+ return readFile(inspected.path);
433
+ }
434
+
435
+ async function safeWrite(repoRoot, relativePath, bytes) {
436
+ const segments = relativePath.split('/');
437
+ let current = repoRoot;
438
+ for (const segment of segments.slice(0, -1)) {
439
+ current = path.join(current, segment);
440
+ try {
441
+ const stat = await lstat(current);
442
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
443
+ throw new TransformContractError(
444
+ 'LATTICE_RC2_SCOPE_VIOLATION',
445
+ `unsafe writer ancestor: ${relativePath}`,
446
+ );
447
+ }
448
+ } catch (error) {
449
+ if (error?.code !== 'ENOENT') throw error;
450
+ await mkdir(current);
451
+ }
452
+ }
453
+ const target = path.join(repoRoot, relativePath);
454
+ try {
455
+ const stat = await lstat(target);
456
+ if (stat.isSymbolicLink() || !stat.isFile()) {
457
+ throw new TransformContractError(
458
+ 'LATTICE_RC2_SCOPE_VIOLATION',
459
+ `unsafe writer target: ${relativePath}`,
460
+ );
461
+ }
462
+ } catch (error) {
463
+ if (error?.code !== 'ENOENT') throw error;
464
+ }
465
+ await writeFile(target, bytes);
466
+ }
467
+
468
+ async function captureSurfaceSnapshot(repoRoot) {
469
+ const files = [];
470
+ for (const relativePath of SURFACE_PATHS) {
471
+ const inspected = await inspectPath(repoRoot, relativePath);
472
+ files.push(inspected.state === 'present'
473
+ ? {
474
+ path: relativePath,
475
+ state: 'present',
476
+ content_digest: sha256(await readFile(inspected.path)),
477
+ }
478
+ : { path: relativePath, state: 'absent', content_digest: null });
479
+ }
480
+ const value = {
481
+ schema: 'lattice.rc2.delivery_policy_surface_snapshot.v1',
482
+ files,
483
+ };
484
+ return { ...value, digest: digestArtifact(value) };
485
+ }
486
+
487
+ function assertControlSnapshot(snapshot) {
488
+ for (const file of snapshot.files) {
489
+ const expected = CURRENT_PATHS.has(file.path) ? 'present' : 'absent';
490
+ if (file.state !== expected) {
491
+ throw new TypeError('candidate control surface is not the exact current topology');
492
+ }
493
+ }
494
+ }
495
+
496
+ function assertOutputSnapshot(snapshot, oracleDigest) {
497
+ if (snapshot.files.some(({ state }) => state !== 'present')) {
498
+ throw new TransformContractError(
499
+ 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
500
+ 'post-transform surface is incomplete',
501
+ );
502
+ }
503
+ const oracle = snapshot.files.find(({ path: relativePath }) => relativePath === ORACLE_PATH);
504
+ if (oracle?.content_digest !== oracleDigest) {
505
+ throw new TransformContractError(
506
+ 'LATTICE_RC2_SCOPE_VIOLATION',
507
+ 'fixed oracle bytes changed during transform',
508
+ );
509
+ }
510
+ }
511
+
512
+ function assertAcceptedCandidate(candidateSpec) {
513
+ const candidateDigest = digestArtifact(candidateSpec);
514
+ if (candidateDigest !== EXPECTED_CANDIDATE_DIGEST
515
+ || candidateSpec?.schema !== 'lattice.rc2.boundary_candidate_spec.v1'
516
+ || candidateSpec?.candidate_id !== EXPECTED_CANDIDATE_ID
517
+ || candidateSpec?.fixed_oracle?.path !== ORACLE_PATH
518
+ || !sameArray(candidateSpec.fixed_oracle.case_ids, MUTATIONS.map(({ caseId }) => caseId))) {
519
+ throw new TypeError('candidateSpec is not the accepted RC2 delivery policy witness');
520
+ }
521
+ const todoProjection = candidateSpec.todos.map((todo) => ({
522
+ todoId: todo.todo_id,
523
+ caseIds: todo.case_ids,
524
+ resolver: todo.proposed.production.symbol,
525
+ productionPath: todo.proposed.production.path,
526
+ contract: todo.proposed.tests[0].symbol,
527
+ testPath: todo.proposed.tests[0].path,
528
+ }));
529
+ const expectedProjection = Object.values(CHANNELS).map((channel) => ({
530
+ todoId: channel.todoId,
531
+ caseIds: channel.caseIds,
532
+ resolver: channel.resolver,
533
+ productionPath: channel.productionPath,
534
+ contract: channel.contract,
535
+ testPath: channel.testPath,
536
+ }));
537
+ if (digestArtifact(todoProjection) !== digestArtifact(expectedProjection)) {
538
+ throw new TypeError('candidateSpec case partition or proposed ownership is invalid');
539
+ }
540
+ return { candidateDigest, fixedCandidate: structuredClone(candidateSpec) };
541
+ }
542
+
543
+ function assertOracleReceipt(receipt, candidateSpec) {
544
+ if (!exactRecord(receipt, ['schema', 'outcome', 'case_results'])
545
+ || receipt.schema !== 'lattice.rc2.delivery_policy_oracle_receipt.v1'
546
+ || receipt.outcome !== 'passed'
547
+ || !sameArray(
548
+ receipt.case_results.map(({ id }) => id),
549
+ candidateSpec.fixed_oracle.case_ids,
550
+ )
551
+ || receipt.case_results.some((result) => (
552
+ !exactRecord(result, ['id', 'outcome', 'output_digest'])
553
+ || result.outcome !== 'passed'
554
+ || typeof result.output_digest !== 'string'
555
+ || !/^[0-9a-f]{64}$/.test(result.output_digest)
556
+ ))) {
557
+ throw new TransformContractError(
558
+ 'LATTICE_RC2_ORACLE_DIVERGENCE',
559
+ 'fixed oracle receipt is invalid',
560
+ );
561
+ }
562
+ }
563
+
564
+ function oracleCaseSetDigest(receipt) {
565
+ return digestArtifact({
566
+ case_results: receipt.case_results.map(({ id, output_digest }) => ({ id, output_digest })),
567
+ });
568
+ }
569
+
570
+ async function assertCompleteTransform(worktreePath, oracleDigest) {
571
+ const changedPaths = statusPaths(await git(worktreePath, [
572
+ 'status',
573
+ '--porcelain=v1',
574
+ '-z',
575
+ '--untracked-files=all',
576
+ '--ignored=matching',
577
+ ]));
578
+ const outside = changedPaths.find((relativePath) => (
579
+ !RC2_DELIVERY_POLICY_TRANSFORM_PATHS.includes(relativePath)
580
+ ));
581
+ if (outside !== undefined) {
582
+ throw new TransformContractError(
583
+ 'LATTICE_RC2_SCOPE_VIOLATION',
584
+ `writer changed a path outside the exact allowlist: ${outside}`,
585
+ );
586
+ }
587
+ const oracle = await inspectPath(worktreePath, ORACLE_PATH);
588
+ if (oracle.state !== 'present') {
589
+ throw new TransformContractError(
590
+ 'LATTICE_RC2_SCOPE_VIOLATION',
591
+ 'fixed oracle was removed during writer execution',
592
+ );
593
+ }
594
+ const actualOracleDigest = sha256(await readFile(oracle.path));
595
+ if (actualOracleDigest !== oracleDigest) {
596
+ throw new TransformContractError(
597
+ 'LATTICE_RC2_SCOPE_VIOLATION',
598
+ 'fixed oracle bytes changed during writer execution',
599
+ );
600
+ }
601
+ for (const relativePath of RC2_DELIVERY_POLICY_TRANSFORM_PATHS) {
602
+ await readRegularFile(worktreePath, relativePath);
603
+ }
604
+ }
605
+
606
+ function testEnvironment() {
607
+ const env = { ...process.env, NO_COLOR: '1' };
608
+ delete env.NODE_TEST_CONTEXT;
609
+ delete env.FORCE_COLOR;
610
+ return env;
611
+ }
612
+
613
+ async function runMutationCell(worktreePath, contract) {
614
+ const result = await spawnCapture(process.execPath, [
615
+ '--test',
616
+ '--test-reporter=dot',
617
+ contract.path,
618
+ ], { cwd: worktreePath, env: testEnvironment() });
619
+ const exitCode = Number.isSafeInteger(result.code) && result.code >= 0 ? result.code : 1;
620
+ return {
621
+ test_id: contract.testId,
622
+ path: contract.path,
623
+ outcome: exitCode === 0 && result.signal === null ? 'passed' : 'failed',
624
+ exit_code: exitCode,
625
+ stdout_digest: sha256(result.stdout),
626
+ stderr_digest: sha256(result.stderr),
627
+ };
628
+ }
629
+
630
+ async function observeOracleMismatch(worktreePath, expectedCaseId) {
631
+ try {
632
+ await runRc2DeliveryPolicyOracle({ repoRoot: worktreePath });
633
+ } catch (error) {
634
+ const match = String(error?.message ?? error)
635
+ .match(/delivery policy behavior mismatch: ([a-z]+-(?:routine|urgent))/);
636
+ if (match?.[1] === expectedCaseId) return match[1];
637
+ throw new TransformContractError(
638
+ 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
639
+ `mutation oracle mismatch was not ${expectedCaseId}`,
640
+ );
641
+ }
642
+ throw new TransformContractError(
643
+ 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
644
+ `mutation oracle unexpectedly passed: ${expectedCaseId}`,
645
+ );
646
+ }
647
+
648
+ async function runMutationMatrix({
649
+ worktreePath,
650
+ outputSnapshot,
651
+ candidateDigest,
652
+ caseSetDigest,
653
+ }) {
654
+ const rows = [];
655
+ for (const mutation of MUTATIONS) {
656
+ const original = await readRegularFile(worktreePath, mutation.owner.productionPath);
657
+ const source = original.toString('utf8');
658
+ if (source.split(mutation.needle).length !== 2) {
659
+ throw new TransformContractError(
660
+ 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
661
+ `mutation target is not unique: ${mutation.caseId}`,
662
+ );
663
+ }
664
+ await safeWrite(
665
+ worktreePath,
666
+ mutation.owner.productionPath,
667
+ Buffer.from(source.replace(mutation.needle, mutation.replacement), 'utf8'),
668
+ );
669
+
670
+ let primaryError;
671
+ let oracleMismatchId;
672
+ let cells;
673
+ try {
674
+ oracleMismatchId = await observeOracleMismatch(worktreePath, mutation.caseId);
675
+ cells = [];
676
+ for (const contract of TEST_CONTRACTS) {
677
+ cells.push(await runMutationCell(worktreePath, contract));
678
+ }
679
+ for (const cell of cells) {
680
+ const owner = cell.test_id === mutation.owner.contract;
681
+ if ((owner && (cell.outcome !== 'failed' || cell.exit_code === 0))
682
+ || (!owner && (cell.outcome !== 'passed' || cell.exit_code !== 0))) {
683
+ throw new TransformContractError(
684
+ 'LATTICE_RC2_MUTATION_MATRIX_FAILURE',
685
+ `owner-only test partition failed: ${mutation.caseId}/${cell.test_id}`,
686
+ );
687
+ }
688
+ }
689
+ } catch (error) {
690
+ primaryError = error;
691
+ }
692
+
693
+ try {
694
+ await safeWrite(worktreePath, mutation.owner.productionPath, original);
695
+ } catch (error) {
696
+ throw new TransformContractError(
697
+ 'LATTICE_RC2_RESTORE_FAILURE',
698
+ `mutation source restore failed: ${mutation.caseId}: ${error.message}`,
699
+ );
700
+ }
701
+ const restored = await captureSurfaceSnapshot(worktreePath);
702
+ if (restored.digest !== outputSnapshot.digest) {
703
+ throw new TransformContractError(
704
+ 'LATTICE_RC2_RESTORE_FAILURE',
705
+ `mutation snapshot restore failed: ${mutation.caseId}`,
706
+ );
707
+ }
708
+ if (primaryError) throw primaryError;
709
+
710
+ rows.push({
711
+ case_id: mutation.caseId,
712
+ owner_todo_id: mutation.owner.todoId,
713
+ resolver_symbol: mutation.owner.resolver,
714
+ mutated_path: mutation.owner.productionPath,
715
+ oracle_mismatch_id: oracleMismatchId,
716
+ cells,
717
+ restore_digest: restored.digest,
718
+ });
719
+ }
720
+ const matrixDigest = digestArtifact({ rows });
721
+ const value = {
722
+ schema: 'lattice.rc2.delivery_policy_mutation_evidence.v1',
723
+ candidate_digest: candidateDigest,
724
+ case_set_digest: caseSetDigest,
725
+ rows,
726
+ matrix_digest: matrixDigest,
727
+ };
728
+ return { ...value, evidence_digest: digestArtifact(value) };
729
+ }
730
+
731
+ function makeBehaviorEvidence({
732
+ candidateDigest,
733
+ adapterSourceDigest,
734
+ controlSnapshot,
735
+ outputSnapshot,
736
+ oracleBytes,
737
+ oracleDigest,
738
+ preOracle,
739
+ postOracle,
740
+ }) {
741
+ const value = {
742
+ schema: 'lattice.rc2.delivery_policy_behavior_evidence.v1',
743
+ candidate_digest: candidateDigest,
744
+ adapter_source_digest: adapterSourceDigest,
745
+ control_snapshot: structuredClone(controlSnapshot),
746
+ output_snapshot: structuredClone(outputSnapshot),
747
+ fixed_oracle: {
748
+ path: ORACLE_PATH,
749
+ source_base64: oracleBytes.toString('base64'),
750
+ source_digest: oracleDigest,
751
+ },
752
+ pre_oracle: structuredClone(preOracle),
753
+ post_oracle: structuredClone(postOracle),
754
+ case_set_digest: oracleCaseSetDigest(preOracle),
755
+ equivalent: true,
756
+ };
757
+ return { ...value, evidence_digest: digestArtifact(value) };
758
+ }
759
+
760
+ function makeCleanupReceipt(beforeCount, afterCount, forcedFailure = false) {
761
+ return {
762
+ schema: 'lattice.rc2.delivery_policy_cleanup_receipt.v1',
763
+ outcome: !forcedFailure && beforeCount === afterCount ? 'passed' : 'failed',
764
+ worktree_count_before: beforeCount,
765
+ worktree_count_after: afterCount,
766
+ };
767
+ }
768
+
769
+ function makeReceipt({
770
+ status,
771
+ artifactDigest,
772
+ behaviorEvidenceDigest,
773
+ mutationEvidenceDigest,
774
+ sourceInvariant,
775
+ cleanup,
776
+ }) {
777
+ const value = {
778
+ schema: 'lattice.rc2.delivery_policy_transform_receipt.v1',
779
+ status,
780
+ transform_artifact_digest: artifactDigest,
781
+ behavior_evidence_digest: behaviorEvidenceDigest,
782
+ mutation_evidence_digest: mutationEvidenceDigest,
783
+ source_invariant: sourceInvariant ?? null,
784
+ cleanup: structuredClone(cleanup),
785
+ };
786
+ return { ...value, receipt_digest: digestArtifact(value) };
787
+ }
788
+
789
+ function makeResult({ artifact, patch, behaviorEvidence, mutationEvidence, cleanup, sourceInvariant }) {
790
+ const artifactDigest = digestArtifact(artifact);
791
+ const receipt = makeReceipt({
792
+ status: artifact.status,
793
+ artifactDigest,
794
+ behaviorEvidenceDigest: behaviorEvidence?.evidence_digest ?? null,
795
+ mutationEvidenceDigest: mutationEvidence?.evidence_digest ?? null,
796
+ sourceInvariant,
797
+ cleanup,
798
+ });
799
+ return {
800
+ schema: 'lattice.rc2.delivery_policy_seam_transform_result.v1',
801
+ status: artifact.status,
802
+ artifact,
803
+ artifact_digest: artifactDigest,
804
+ receipt,
805
+ receipt_digest: receipt.receipt_digest,
806
+ patch: Buffer.isBuffer(patch) ? Buffer.from(patch) : null,
807
+ behavior_evidence: behaviorEvidence ? structuredClone(behaviorEvidence) : null,
808
+ mutation_evidence: mutationEvidence ? structuredClone(mutationEvidence) : null,
809
+ };
810
+ }
811
+
812
+ function flattenErrors(error) {
813
+ if (error instanceof AggregateError) return error.errors.flatMap(flattenErrors);
814
+ return [error];
815
+ }
816
+
817
+ function transformEvidence(error) {
818
+ return flattenErrors(error)
819
+ .map((entry) => entry?.transformEvidence)
820
+ .find((entry) => entry && typeof entry.baseSha === 'string');
821
+ }
822
+
823
+ function rejectionFacts(error) {
824
+ const errors = flattenErrors(error);
825
+ const codes = new Set(errors.map((entry) => entry?.code).filter(Boolean));
826
+ const messages = errors.map((entry) => String(entry?.message ?? entry)).join('\n');
827
+ if (codes.has('LATTICE_RC2_INCOMPLETE_TRANSFORM')) {
828
+ return { kind: 'incomplete_transform', reason: 'required production or test seam is incomplete' };
829
+ }
830
+ if (codes.has('LATTICE_RC2_SCOPE_VIOLATION')
831
+ || /outside allowed paths|symlink change|submodule change|special file change/i.test(messages)) {
832
+ return { kind: 'scope_violation', reason: 'transform changed or traversed a forbidden surface' };
833
+ }
834
+ if (codes.has('LATTICE_RC2_MUTATION_MATRIX_FAILURE')) {
835
+ return { kind: 'mutation_matrix_failure', reason: 'owner-only mutation sensitivity was not proven' };
836
+ }
837
+ if (codes.has('LATTICE_RC2_RESTORE_FAILURE')) {
838
+ return { kind: 'restore_failure', reason: 'mutation bytes did not restore to the accepted snapshot' };
839
+ }
840
+ if (codes.has('LATTICE_RC2_ORACLE_DIVERGENCE')
841
+ || /delivery policy behavior mismatch|oracle child failed/i.test(messages)) {
842
+ return { kind: 'oracle_divergence', reason: 'fixed oracle did not preserve the ordered behavior set' };
843
+ }
844
+ if (/verifier failed/i.test(messages)) {
845
+ return { kind: 'behavior_verification_failed', reason: 'focused production or test seam verifier failed' };
846
+ }
847
+ if (/mutated isolated snapshot/i.test(messages)) {
848
+ return { kind: 'snapshot_mutation', reason: 'observer or verifier changed the accepted isolated patch' };
849
+ }
850
+ if (/source repository changed/i.test(messages)) {
851
+ return { kind: 'source_invariant_violation', reason: 'canonical source changed during isolation' };
852
+ }
853
+ if (/cleanup failed/i.test(messages)) {
854
+ return { kind: 'cleanup_failure', reason: 'disposable worktree cleanup failed' };
855
+ }
856
+ if (codes.has('LATTICE_RC2_CLEANUP_FAILURE')) {
857
+ return { kind: 'cleanup_failure', reason: 'disposable worktree cleanup evidence failed' };
858
+ }
859
+ return { kind: 'execution_failure', reason: 'isolated delivery policy transaction failed' };
860
+ }
861
+
862
+ function verificationArtifact(status, receipts) {
863
+ return { status, receipts: structuredClone(receipts) };
864
+ }
865
+
866
+ function rejectedResult({
867
+ error,
868
+ evidence,
869
+ candidate,
870
+ candidateDigest,
871
+ baseSha,
872
+ adapterSourceDigest,
873
+ controlSnapshot,
874
+ oracleDigest,
875
+ beforeCount,
876
+ afterCount,
877
+ }) {
878
+ const facts = rejectionFacts(error);
879
+ const errors = flattenErrors(error);
880
+ const messages = errors.map((entry) => String(entry?.message ?? entry));
881
+ const cleanup = makeCleanupReceipt(
882
+ beforeCount,
883
+ afterCount,
884
+ messages.some((message) => /cleanup failed/i.test(message)),
885
+ );
886
+ const sourceInvariant = evidence?.sourceInvariant ?? null;
887
+ const patch = Buffer.isBuffer(evidence?.patch) ? evidence.patch : null;
888
+ const receipts = Array.isArray(evidence?.verifications) ? evidence.verifications : [];
889
+ const verificationStatus = receipts.length === 0
890
+ ? 'not_run'
891
+ : (receipts.some(({ outcome }) => outcome !== 'passed') ? 'failed' : 'passed');
892
+ const rejection = {
893
+ kind: facts.kind,
894
+ reasons: [facts.reason],
895
+ };
896
+ const artifact = {
897
+ schema: 'lattice.rc2.delivery_policy_transform_artifact.v1',
898
+ status: 'rejected',
899
+ candidate: {
900
+ candidate_id: candidate.candidate_id,
901
+ digest: candidateDigest,
902
+ },
903
+ source: {
904
+ base_sha: baseSha,
905
+ adapter: { path: ADAPTER_PATH, digest: adapterSourceDigest },
906
+ control_snapshot_digest: controlSnapshot.digest,
907
+ fixed_oracle: { path: ORACLE_PATH, source_digest: oracleDigest },
908
+ },
909
+ scope: {
910
+ allowed_paths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
911
+ changed_paths: Array.isArray(evidence?.changedPaths) ? [...evidence.changedPaths] : [],
912
+ },
913
+ patch: { digest: patch ? sha256(patch) : null, bytes: patch?.byteLength ?? 0 },
914
+ output: null,
915
+ behavior: null,
916
+ mutation: null,
917
+ verification: verificationArtifact(verificationStatus, receipts),
918
+ cleanup: {
919
+ status: cleanup.outcome,
920
+ source_status: sourceInvariant?.outcome === 'passed'
921
+ ? 'unchanged'
922
+ : (sourceInvariant?.outcome === 'failed' ? 'changed' : 'unresolved'),
923
+ receipt_digest: digestArtifact(cleanup),
924
+ },
925
+ rejection: { ...rejection, evidence_digest: digestArtifact(rejection) },
926
+ };
927
+ return makeResult({
928
+ artifact,
929
+ patch,
930
+ behaviorEvidence: null,
931
+ mutationEvidence: null,
932
+ cleanup,
933
+ sourceInvariant,
934
+ });
935
+ }
936
+
937
+ /** 3 channel resolverと対応test seamをdisposable worktreeへ決定的に書く。 */
938
+ export async function applyRc2DeliveryPolicyTransform(options = {}) {
939
+ if (!exactRecord(options, ['worktreePath'])
940
+ || typeof options.worktreePath !== 'string'
941
+ || options.worktreePath.length === 0) {
942
+ throw new TypeError('applyRc2DeliveryPolicyTransform requires exact worktreePath');
943
+ }
944
+ const worktreePath = await realpath(options.worktreePath);
945
+ for (const relativePath of RC2_DELIVERY_POLICY_TRANSFORM_PATHS) {
946
+ await safeWrite(worktreePath, relativePath, Buffer.from(WRITER_FILES.get(relativePath), 'utf8'));
947
+ }
948
+ }
949
+
950
+ /** actual preimageから隔離transform、oracle、mutation matrix、cleanupを一transactionで実行する。 */
951
+ export async function runRc2DeliveryPolicySeamTransform(options = {}) {
952
+ if (!exactRecord(options, ['repoRoot', 'baseRef', 'candidateSpec'])
953
+ && !exactRecord(options, ['repoRoot', 'baseRef', 'candidateSpec', 'transform'])) {
954
+ throw new TypeError('runRc2DeliveryPolicySeamTransform options have an invalid shape');
955
+ }
956
+ const {
957
+ repoRoot,
958
+ baseRef,
959
+ candidateSpec,
960
+ transform = applyRc2DeliveryPolicyTransform,
961
+ } = options;
962
+ if (typeof transform !== 'function') throw new TypeError('transform must be a function');
963
+
964
+ const { candidateDigest, fixedCandidate } = assertAcceptedCandidate(candidateSpec);
965
+ const { root, baseSha } = await resolveRepository(repoRoot, baseRef);
966
+ const controlSnapshot = await captureSurfaceSnapshot(root);
967
+ assertControlSnapshot(controlSnapshot);
968
+ const oracleBytes = await readRegularFile(root, ORACLE_PATH);
969
+ const oracleDigest = sha256(oracleBytes);
970
+ if (oracleDigest !== fixedCandidate.fixed_oracle.source_digest) {
971
+ throw new TypeError('fixed oracle source digest differs from the accepted candidate');
972
+ }
973
+ const adapterSourceDigest = sha256(await readFile(new URL(import.meta.url)));
974
+ const preOracle = await runRc2DeliveryPolicyOracle({ repoRoot: root });
975
+ assertOracleReceipt(preOracle, fixedCandidate);
976
+ const beforeCount = await worktreeCount(root);
977
+
978
+ let isolated;
979
+ let postOracle;
980
+ let outputSnapshot;
981
+ let mutationEvidence;
982
+ try {
983
+ isolated = await runIsolatedTransform({
984
+ repoRoot: root,
985
+ baseRef: baseSha,
986
+ allowedPaths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
987
+ transform: async ({ worktreePath }) => {
988
+ await transform({ worktreePath });
989
+ await assertCompleteTransform(worktreePath, oracleDigest);
990
+ },
991
+ verifyCommands: TEST_CONTRACTS.map((contract) => ({
992
+ command: process.execPath,
993
+ args: ['--test', '--test-reporter=dot', contract.path],
994
+ })),
995
+ observe: async ({ worktreePath, changedPaths }) => {
996
+ if (!sameArray(changedPaths, RC2_DELIVERY_POLICY_TRANSFORM_PATHS)) {
997
+ throw new TransformContractError(
998
+ 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
999
+ 'accepted writer must change the exact eight allowed paths',
1000
+ );
1001
+ }
1002
+ postOracle = await runRc2DeliveryPolicyOracle({ repoRoot: worktreePath });
1003
+ assertOracleReceipt(postOracle, fixedCandidate);
1004
+ if (digestArtifact(postOracle) !== digestArtifact(preOracle)) {
1005
+ throw new TransformContractError(
1006
+ 'LATTICE_RC2_ORACLE_DIVERGENCE',
1007
+ 'pre and post fixed oracle receipts differ',
1008
+ );
1009
+ }
1010
+ outputSnapshot = await captureSurfaceSnapshot(worktreePath);
1011
+ assertOutputSnapshot(outputSnapshot, oracleDigest);
1012
+ mutationEvidence = await runMutationMatrix({
1013
+ worktreePath,
1014
+ outputSnapshot,
1015
+ candidateDigest,
1016
+ caseSetDigest: oracleCaseSetDigest(preOracle),
1017
+ });
1018
+ const afterMatrix = await captureSurfaceSnapshot(worktreePath);
1019
+ if (afterMatrix.digest !== outputSnapshot.digest) {
1020
+ throw new TransformContractError(
1021
+ 'LATTICE_RC2_RESTORE_FAILURE',
1022
+ 'mutation matrix leaked bytes into the accepted snapshot',
1023
+ );
1024
+ }
1025
+ },
1026
+ });
1027
+ const afterCount = await worktreeCount(root);
1028
+ const cleanup = makeCleanupReceipt(beforeCount, afterCount);
1029
+ if (cleanup.outcome !== 'passed') {
1030
+ throw new TransformContractError(
1031
+ 'LATTICE_RC2_CLEANUP_FAILURE',
1032
+ 'disposable worktree count changed after cleanup',
1033
+ );
1034
+ }
1035
+ if (!sameArray(isolated.changedPaths, RC2_DELIVERY_POLICY_TRANSFORM_PATHS)
1036
+ || !Buffer.isBuffer(isolated.patch)
1037
+ || isolated.verifications.length !== TEST_CONTRACTS.length
1038
+ || isolated.verifications.some(({ outcome }) => outcome !== 'passed')
1039
+ || isolated.sourceInvariant?.outcome !== 'passed'
1040
+ || !postOracle
1041
+ || !outputSnapshot
1042
+ || !mutationEvidence) {
1043
+ throw new TransformContractError(
1044
+ 'LATTICE_RC2_INCOMPLETE_TRANSFORM',
1045
+ 'isolated transaction did not produce the complete accepted evidence set',
1046
+ );
1047
+ }
1048
+
1049
+ const behaviorEvidence = makeBehaviorEvidence({
1050
+ candidateDigest,
1051
+ adapterSourceDigest,
1052
+ controlSnapshot,
1053
+ outputSnapshot,
1054
+ oracleBytes,
1055
+ oracleDigest,
1056
+ preOracle,
1057
+ postOracle,
1058
+ });
1059
+ const artifact = {
1060
+ schema: 'lattice.rc2.delivery_policy_transform_artifact.v1',
1061
+ status: 'accepted',
1062
+ candidate: {
1063
+ candidate_id: fixedCandidate.candidate_id,
1064
+ digest: candidateDigest,
1065
+ },
1066
+ source: {
1067
+ base_sha: baseSha,
1068
+ adapter: { path: ADAPTER_PATH, digest: adapterSourceDigest },
1069
+ control_snapshot_digest: controlSnapshot.digest,
1070
+ fixed_oracle: { path: ORACLE_PATH, source_digest: oracleDigest },
1071
+ },
1072
+ scope: {
1073
+ allowed_paths: [...RC2_DELIVERY_POLICY_TRANSFORM_PATHS],
1074
+ changed_paths: [...isolated.changedPaths],
1075
+ },
1076
+ patch: { digest: sha256(isolated.patch), bytes: isolated.patch.byteLength },
1077
+ output: {
1078
+ snapshot_digest: outputSnapshot.digest,
1079
+ files: structuredClone(outputSnapshot.files),
1080
+ },
1081
+ behavior: {
1082
+ evidence_digest: behaviorEvidence.evidence_digest,
1083
+ pre_oracle_digest: digestArtifact(preOracle),
1084
+ post_oracle_digest: digestArtifact(postOracle),
1085
+ case_set_digest: behaviorEvidence.case_set_digest,
1086
+ equivalent: true,
1087
+ },
1088
+ mutation: {
1089
+ evidence_digest: mutationEvidence.evidence_digest,
1090
+ matrix_digest: mutationEvidence.matrix_digest,
1091
+ row_count: mutationEvidence.rows.length,
1092
+ cell_count: mutationEvidence.rows.reduce((sum, row) => sum + row.cells.length, 0),
1093
+ },
1094
+ verification: verificationArtifact('passed', isolated.verifications),
1095
+ cleanup: {
1096
+ status: 'passed',
1097
+ source_status: 'unchanged',
1098
+ receipt_digest: digestArtifact(cleanup),
1099
+ },
1100
+ rejection: null,
1101
+ };
1102
+ return makeResult({
1103
+ artifact,
1104
+ patch: isolated.patch,
1105
+ behaviorEvidence,
1106
+ mutationEvidence,
1107
+ cleanup,
1108
+ sourceInvariant: isolated.sourceInvariant,
1109
+ });
1110
+ } catch (error) {
1111
+ const afterCount = await worktreeCount(root);
1112
+ const evidence = transformEvidence(error) ?? isolated;
1113
+ if (!evidence || typeof evidence.baseSha !== 'string') throw error;
1114
+ return rejectedResult({
1115
+ error,
1116
+ evidence,
1117
+ candidate: fixedCandidate,
1118
+ candidateDigest,
1119
+ baseSha,
1120
+ adapterSourceDigest,
1121
+ controlSnapshot,
1122
+ oracleDigest,
1123
+ beforeCount,
1124
+ afterCount,
1125
+ });
1126
+ }
1127
+ }