@quolu/lattice 0.52.2 → 0.52.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,481 +1,481 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { constants as fsConstants } from 'node:fs';
3
- import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import { canonicalizeArtifact } from './artifact-contracts.mjs';
7
- import { selfDigest } from './runtime-contracts.mjs';
8
-
9
- const SHA256 = /^[0-9a-f]{64}$/;
10
- const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
11
- const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
12
- const GATE_EVENT_KINDS = Object.freeze([
13
- 'write_gate_committed',
14
- 'epoch_activated',
15
- 'intake_resumed',
16
- ]);
17
-
18
- export class RuntimeGateStoreError extends Error {
19
- constructor(code, detail) {
20
- super(`${code}: ${detail}`);
21
- this.name = 'RuntimeGateStoreError';
22
- this.code = code;
23
- this.detail = detail;
24
- }
25
- }
26
-
27
- function fail(code, detail) { throw new RuntimeGateStoreError(code, detail); }
28
- function digest(value) { return typeof value === 'string' && SHA256.test(value); }
29
- function identifier(value) { return typeof value === 'string' && ID.test(value); }
30
- function timestamp(value) {
31
- return typeof value === 'string' && TIMESTAMP.test(value)
32
- && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
33
- }
34
- function plain(value) {
35
- return value !== null && typeof value === 'object' && !Array.isArray(value)
36
- && Object.getPrototypeOf(value) === Object.prototype;
37
- }
38
- function exact(value, keys) {
39
- if (!plain(value)) return false;
40
- const actual = Object.keys(value).sort();
41
- const expected = [...keys].sort();
42
- return actual.length === expected.length
43
- && actual.every((key, index) => key === expected[index]);
44
- }
45
- function sortedUniqueDigests(value) {
46
- return Array.isArray(value) && value.length <= 256 && value.every(digest)
47
- && new Set(value).size === value.length
48
- && value.every((entry, index) => index === 0 || value[index - 1] < entry);
49
- }
50
- function selfDigestValid(value, field) {
51
- if (!digest(value?.[field])) return false;
52
- try { return selfDigest(value, field) === value[field]; } catch { return false; }
53
- }
54
-
55
- export function validateSupervisorWriteGate(value) {
56
- return exact(value, [
57
- 'schema', 'run_id', 'plan_epoch', 'gate_generation', 'release_barrier_digest',
58
- 'controller_release_ack_digests', 'armed_lease_digests', 'previous_gate_digest',
59
- 'committed_at', 'gate_digest',
60
- ])
61
- && value.schema === 'lattice.supervisor_write_gate.v1'
62
- && identifier(value.run_id)
63
- && Number.isSafeInteger(value.plan_epoch) && value.plan_epoch >= 1
64
- && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1
65
- && digest(value.release_barrier_digest)
66
- && sortedUniqueDigests(value.controller_release_ack_digests)
67
- && sortedUniqueDigests(value.armed_lease_digests)
68
- && (value.previous_gate_digest === null || digest(value.previous_gate_digest))
69
- && timestamp(value.committed_at)
70
- && selfDigestValid(value, 'gate_digest');
71
- }
72
-
73
- function validGateEventPayload(kind, value) {
74
- if (kind === 'write_gate_committed') {
75
- return exact(value, ['gate_digest', 'gate_generation'])
76
- && digest(value.gate_digest)
77
- && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1;
78
- }
79
- return exact(value, ['plan_epoch', 'gate_digest'])
80
- && Number.isSafeInteger(value.plan_epoch) && value.plan_epoch >= 1
81
- && digest(value.gate_digest);
82
- }
83
-
84
- /** Gate batchが所有する3 eventのcanonical exact validator。 */
85
- export function validateRuntimeGateControlEvent(value) {
86
- return exact(value, [
87
- 'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
88
- 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
89
- ])
90
- && value.schema === 'lattice.runtime_control_event.v1'
91
- && identifier(value.run_id)
92
- && Number.isSafeInteger(value.sequence) && value.sequence >= 0
93
- && (value.previous_digest === null || digest(value.previous_digest))
94
- && GATE_EVENT_KINDS.includes(value.kind)
95
- && digest(value.session_nonce_digest)
96
- && validGateEventPayload(value.kind, value.payload)
97
- && timestamp(value.recorded_at)
98
- && selfDigestValid(value, 'event_digest');
99
- }
100
-
101
- /**
102
- * revoke失敗を成功証拠へ丸めないためのexact validator。
103
- * `lease_revoked`はcontroller responseと完全な失効集合、residual zeroを必須にする。
104
- */
105
- export function validateLeaseRevokedControlEvent(value) {
106
- return exact(value, [
107
- 'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
108
- 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
109
- ])
110
- && value.schema === 'lattice.runtime_control_event.v1'
111
- && identifier(value.run_id)
112
- && Number.isSafeInteger(value.sequence) && value.sequence >= 0
113
- && (value.previous_digest === null || digest(value.previous_digest))
114
- && value.kind === 'lease_revoked'
115
- && digest(value.session_nonce_digest)
116
- && exact(value.payload, [
117
- 'controller_id', 'reason', 'requested_lease_digests', 'revoked_lease_digests',
118
- 'residual_processes', 'revoke_response_digest',
119
- ])
120
- && identifier(value.payload.controller_id)
121
- && typeof value.payload.reason === 'string' && value.payload.reason.length > 0
122
- && sortedUniqueDigests(value.payload.requested_lease_digests)
123
- && sortedUniqueDigests(value.payload.revoked_lease_digests)
124
- && JSON.stringify(value.payload.requested_lease_digests)
125
- === JSON.stringify(value.payload.revoked_lease_digests)
126
- && Array.isArray(value.payload.residual_processes)
127
- && value.payload.residual_processes.length === 0
128
- && digest(value.payload.revoke_response_digest)
129
- && timestamp(value.recorded_at)
130
- && selfDigestValid(value, 'event_digest');
131
- }
132
-
133
- export function validateRuntimeGateBundle(value) {
134
- if (!(exact(value, [
135
- 'schema', 'run_id', 'gate', 'control_events', 'previous_control_head_digest',
136
- 'previous_receipt_digest', 'bundle_digest',
137
- ])
138
- && value.schema === 'lattice.runtime_gate_commit_bundle.v1'
139
- && identifier(value.run_id)
140
- && validateSupervisorWriteGate(value.gate)
141
- && value.gate.run_id === value.run_id
142
- && Array.isArray(value.control_events) && value.control_events.length === 3
143
- && value.control_events.every(validateRuntimeGateControlEvent)
144
- && value.control_events.map((event) => event.kind).join(',') === GATE_EVENT_KINDS.join(',')
145
- && (value.previous_control_head_digest === null || digest(value.previous_control_head_digest))
146
- && (value.previous_receipt_digest === null || digest(value.previous_receipt_digest))
147
- && selfDigestValid(value, 'bundle_digest'))) return false;
148
- const [committed, activated, resumed] = value.control_events;
149
- return committed.previous_digest === value.previous_control_head_digest
150
- && activated.previous_digest === committed.event_digest
151
- && resumed.previous_digest === activated.event_digest
152
- && committed.sequence + 1 === activated.sequence
153
- && activated.sequence + 1 === resumed.sequence
154
- && committed.run_id === value.run_id && activated.run_id === value.run_id && resumed.run_id === value.run_id
155
- && committed.payload.gate_digest === value.gate.gate_digest
156
- && committed.payload.gate_generation === value.gate.gate_generation
157
- && activated.payload.gate_digest === value.gate.gate_digest
158
- && activated.payload.plan_epoch === value.gate.plan_epoch
159
- && resumed.payload.gate_digest === value.gate.gate_digest
160
- && resumed.payload.plan_epoch === value.gate.plan_epoch;
161
- }
162
-
163
- export function validateRuntimeGateCommitReceipt(value) {
164
- return exact(value, [
165
- 'schema', 'run_id', 'gate_generation', 'gate_digest', 'bundle_digest',
166
- 'control_head_digest', 'previous_receipt_digest', 'committed_at', 'receipt_digest',
167
- ])
168
- && value.schema === 'lattice.runtime_gate_commit_receipt.v1'
169
- && identifier(value.run_id)
170
- && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1
171
- && digest(value.gate_digest) && digest(value.bundle_digest)
172
- && digest(value.control_head_digest)
173
- && (value.previous_receipt_digest === null || digest(value.previous_receipt_digest))
174
- && timestamp(value.committed_at)
175
- && selfDigestValid(value, 'receipt_digest');
176
- }
177
-
178
- function canonicalBytes(value) { return Buffer.from(`${canonicalizeArtifact(value)}\n`); }
179
-
180
- async function readCanonical(pathname, validator, label, { missing = false } = {}) {
181
- let stat;
182
- let bytes;
183
- try {
184
- stat = await lstat(pathname);
185
- if (!stat.isFile() || stat.isSymbolicLink()) fail('INVALID_GATE_STORE', `${label}がregular fileでない`);
186
- bytes = await readFile(pathname);
187
- } catch (error) {
188
- if (error?.code === 'ENOENT' && missing) return null;
189
- if (error instanceof RuntimeGateStoreError) throw error;
190
- fail('INVALID_GATE_STORE', `${label}を読めない`);
191
- }
192
- let value;
193
- try { value = JSON.parse(bytes.toString('utf8')); } catch { fail('INVALID_GATE_STORE', `${label}がJSONでない`); }
194
- if (!validator(value)) fail('INVALID_GATE_STORE', `${label}のexact schema又はdigestが不正`);
195
- if (!bytes.equals(canonicalBytes(value))) fail('INVALID_GATE_STORE', `${label}がcanonical bytesでない`);
196
- return value;
197
- }
198
-
199
- async function fsyncDirectory(directory) {
200
- const handle = await open(directory, fsConstants.O_RDONLY);
201
- // Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
202
- // win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
203
- try { await handle.sync(); } catch (error) {
204
- if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
205
- } finally { await handle.close(); }
206
- }
207
-
208
- async function inject(crashInjector, point, context) {
209
- if (typeof crashInjector === 'function') await crashInjector(point, structuredClone(context));
210
- }
211
-
212
- async function atomicPublish(pathname, value, validator, crashInjector, label) {
213
- const existing = await readCanonical(pathname, validator, label, { missing: true });
214
- if (existing !== null) {
215
- if (!canonicalBytes(existing).equals(canonicalBytes(value))) {
216
- fail('GATE_COMMIT_CONFLICT', `${label}に異なるdigestが既にある`);
217
- }
218
- return;
219
- }
220
- const directory = path.dirname(pathname);
221
- await mkdir(directory, { recursive: true, mode: 0o700 });
222
- const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
223
- let handle;
224
- try {
225
- handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
226
- await handle.writeFile(canonicalBytes(value));
227
- await handle.sync();
228
- await handle.close();
229
- handle = null;
230
- await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
231
- await rename(temporary, pathname);
232
- await inject(crashInjector, `after_${label}_rename`, { pathname });
233
- await fsyncDirectory(directory);
234
- await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
235
- } finally {
236
- if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
237
- await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
238
- }
239
- }
240
-
241
- async function atomicReplace(pathname, previousValue, value, validator, crashInjector, label) {
242
- const existing = await readCanonical(pathname, validator, label, { missing: true });
243
- if (existing !== null && canonicalBytes(existing).equals(canonicalBytes(value))) return;
244
- if ((existing === null) !== (previousValue === null)
245
- || (existing !== null && !canonicalBytes(existing).equals(canonicalBytes(previousValue)))) {
246
- fail('GATE_COMMIT_CONFLICT', `${label}のcommitted prefixが変化した`);
247
- }
248
- const directory = path.dirname(pathname);
249
- await mkdir(directory, { recursive: true, mode: 0o700 });
250
- const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
251
- let handle;
252
- try {
253
- handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
254
- await handle.writeFile(canonicalBytes(value));
255
- await handle.sync();
256
- await handle.close();
257
- handle = null;
258
- await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
259
- await rename(temporary, pathname);
260
- await inject(crashInjector, `after_${label}_rename`, { pathname });
261
- await fsyncDirectory(directory);
262
- await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
263
- } finally {
264
- if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
265
- await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
266
- }
267
- }
268
-
269
- function gateName(generation, suffix) {
270
- return `${String(generation).padStart(8, '0')}.${suffix}.json`;
271
- }
272
-
273
- function pathsFor(runDir, generation, controlEventsPath = null) {
274
- const supervisorDir = path.join(runDir, 'supervisor');
275
- return {
276
- supervisorDir,
277
- gate: path.join(supervisorDir, 'write-gate.json'),
278
- events: controlEventsPath ?? path.join(runDir, 'control-events.json'),
279
- bundle: path.join(supervisorDir, 'gate-commits', gateName(generation, 'bundle')),
280
- receipt: path.join(supervisorDir, 'gate-receipts', gateName(generation, 'receipt')),
281
- };
282
- }
283
-
284
- function validateControlJournal(value) {
285
- if (!Array.isArray(value) || value.length > 100_000) return false;
286
- return value.every((event, index) => (
287
- exact(event, ['schema', 'run_id', 'sequence', 'previous_digest', 'kind', 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest'])
288
- && event.schema === 'lattice.runtime_control_event.v1'
289
- && identifier(event.run_id)
290
- && Number.isSafeInteger(event.sequence) && event.sequence >= 1
291
- && (index === 0 || event.sequence === value[index - 1].sequence + 1)
292
- && (index === 0 ? event.previous_digest === null : event.previous_digest === value[index - 1].event_digest)
293
- && digest(event.session_nonce_digest) && plain(event.payload) && timestamp(event.recorded_at)
294
- && selfDigestValid(event, 'event_digest')
295
- ));
296
- }
297
-
298
- function createEvents({ runId, sessionNonceDigest, previousEvents, templates, committedAt }) {
299
- let previousDigest = previousEvents.at(-1)?.event_digest ?? null;
300
- const firstSequence = (previousEvents.at(-1)?.sequence ?? 0) + 1;
301
- const events = templates.map((template, offset) => {
302
- if (!exact(template, ['kind', 'payload']) || !GATE_EVENT_KINDS.includes(template.kind)
303
- || !validGateEventPayload(template.kind, template.payload)) {
304
- fail('INVALID_GATE_COMMIT', 'gate control event template不正');
305
- }
306
- const event = {
307
- schema: 'lattice.runtime_control_event.v1', run_id: runId,
308
- sequence: firstSequence + offset, previous_digest: previousDigest,
309
- kind: template.kind, session_nonce_digest: sessionNonceDigest,
310
- payload: structuredClone(template.payload), recorded_at: committedAt, event_digest: '',
311
- };
312
- event.event_digest = selfDigest(event, 'event_digest');
313
- previousDigest = event.event_digest;
314
- return event;
315
- });
316
- return events;
317
- }
318
-
319
- async function readPriorState(runDir, gate) {
320
- const currentGate = await readCanonical(pathsFor(runDir, gate.gate_generation).gate,
321
- validateSupervisorWriteGate, 'gate', { missing: true });
322
- let previousReceipt = null;
323
- if (gate.gate_generation > 1) {
324
- previousReceipt = await readCanonical(
325
- pathsFor(runDir, gate.gate_generation - 1).receipt,
326
- validateRuntimeGateCommitReceipt, 'previous_receipt', { missing: false },
327
- );
328
- }
329
- if (gate.gate_generation === 1) {
330
- if (gate.previous_gate_digest !== null || currentGate !== null) {
331
- if (currentGate?.gate_digest !== gate.gate_digest) fail('GATE_COMMIT_CONFLICT', 'generation 1 gate chain不正');
332
- }
333
- } else if (gate.previous_gate_digest !== previousReceipt?.gate_digest) {
334
- fail('GATE_COMMIT_CONFLICT', 'previous gate/receipt chain不一致');
335
- }
336
- if (currentGate === null && gate.gate_generation !== 1) {
337
- fail('GATE_COMMIT_CONFLICT', 'previous committed gateがない');
338
- }
339
- if (currentGate !== null
340
- && currentGate.gate_generation !== gate.gate_generation
341
- && currentGate.gate_generation !== gate.gate_generation - 1) {
342
- fail('GATE_COMMIT_CONFLICT', 'stale又はfuture gate generation retry');
343
- }
344
- if (currentGate?.gate_generation === gate.gate_generation
345
- && currentGate.gate_digest !== gate.gate_digest) {
346
- fail('GATE_COMMIT_CONFLICT', '同一generation gate digest衝突');
347
- }
348
- if (currentGate?.gate_generation === gate.gate_generation - 1
349
- && currentGate.gate_digest !== gate.previous_gate_digest) {
350
- fail('GATE_COMMIT_CONFLICT', 'current gate chain不一致');
351
- }
352
- return { currentGate, previousReceipt };
353
- }
354
-
355
- async function buildCommit({ runDir, runId, sessionNonceDigest, activation,
356
- controlEventsPath = null }) {
357
- if (!plain(activation) || !exact(activation, ['gate', 'control_events'])
358
- || !validateSupervisorWriteGate(activation.gate)
359
- || activation.gate.run_id !== runId || !digest(sessionNonceDigest)) {
360
- fail('INVALID_GATE_COMMIT', 'gate activation入力不正');
361
- }
362
- const { previousReceipt } = await readPriorState(runDir, activation.gate);
363
- const eventPath = pathsFor(runDir, activation.gate.gate_generation, controlEventsPath).events;
364
- const priorEvents = await readCanonical(eventPath, validateControlJournal, 'control_events', { missing: true }) ?? [];
365
- const alreadyAppended = priorEvents.slice(-3);
366
- let baseEvents = priorEvents;
367
- let newEvents;
368
- if (alreadyAppended.length === 3
369
- && alreadyAppended.map((event) => event.kind).join(',') === GATE_EVENT_KINDS.join(',')
370
- && alreadyAppended.every((event) => event.payload.gate_digest === activation.gate.gate_digest)) {
371
- newEvents = alreadyAppended;
372
- baseEvents = priorEvents.slice(0, -3);
373
- } else {
374
- newEvents = createEvents({ runId, sessionNonceDigest, previousEvents: priorEvents,
375
- templates: activation.control_events, committedAt: activation.gate.committed_at });
376
- }
377
- const previousControlHeadDigest = baseEvents.at(-1)?.event_digest ?? null;
378
- const bundle = {
379
- schema: 'lattice.runtime_gate_commit_bundle.v1', run_id: runId,
380
- gate: structuredClone(activation.gate), control_events: structuredClone(newEvents),
381
- previous_control_head_digest: previousControlHeadDigest,
382
- previous_receipt_digest: previousReceipt?.receipt_digest ?? null, bundle_digest: '',
383
- };
384
- bundle.bundle_digest = selfDigest(bundle, 'bundle_digest');
385
- const receipt = {
386
- schema: 'lattice.runtime_gate_commit_receipt.v1', run_id: runId,
387
- gate_generation: activation.gate.gate_generation, gate_digest: activation.gate.gate_digest,
388
- bundle_digest: bundle.bundle_digest, control_head_digest: newEvents.at(-1).event_digest,
389
- previous_receipt_digest: bundle.previous_receipt_digest,
390
- committed_at: activation.gate.committed_at, receipt_digest: '',
391
- };
392
- receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
393
- return { bundle, receipt, baseEvents, newEvents, currentGate: (await readPriorState(runDir, activation.gate)).currentGate };
394
- }
395
-
396
- async function commitBuilt({ runDir, built, crashInjector, controlEventsPath = null }) {
397
- const generation = built.bundle.gate.gate_generation;
398
- const paths = pathsFor(runDir, generation, controlEventsPath);
399
- await atomicPublish(paths.bundle, built.bundle, validateRuntimeGateBundle, crashInjector, 'bundle');
400
- const committedBundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
401
- if (committedBundle.bundle_digest !== built.bundle.bundle_digest) fail('GATE_COMMIT_CONFLICT', 'bundle digest衝突');
402
- await atomicReplace(paths.events, built.baseEvents, [...built.baseEvents, ...built.newEvents], validateControlJournal, crashInjector, 'events');
403
- await atomicReplace(paths.gate, built.currentGate, built.bundle.gate, validateSupervisorWriteGate, crashInjector, 'gate');
404
- // receipt renameが唯一のcommit point。これ以前のartifactはsame digest recovery専用である。
405
- await atomicPublish(paths.receipt, built.receipt, validateRuntimeGateCommitReceipt, crashInjector, 'receipt');
406
- return structuredClone(built.receipt);
407
- }
408
-
409
- export async function commitRuntimeGateActivation(options) {
410
- const built = await buildCommit(options);
411
- return commitBuilt({ runDir: options.runDir, built, crashInjector: options.crashInjector,
412
- controlEventsPath: options.controlEventsPath ?? null });
413
- }
414
-
415
- export async function recoverRuntimeGateCommit(options) {
416
- return commitRuntimeGateActivation(options);
417
- }
418
-
419
- export async function readCommittedRuntimeGate({ runDir, expectedRunId = null,
420
- controlEventsPath = null }) {
421
- const gatePath = path.join(runDir, 'supervisor', 'write-gate.json');
422
- const gate = await readCanonical(gatePath, validateSupervisorWriteGate, 'gate', { missing: true });
423
- if (gate === null) return null;
424
- if (expectedRunId !== null && gate.run_id !== expectedRunId) fail('INVALID_GATE_STORE', 'gate run binding不一致');
425
- const paths = pathsFor(runDir, gate.gate_generation, controlEventsPath);
426
- const bundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
427
- const receipt = await readCanonical(paths.receipt, validateRuntimeGateCommitReceipt, 'receipt');
428
- const events = await readCanonical(paths.events, validateControlJournal, 'control_events');
429
- if (bundle.gate.gate_digest !== gate.gate_digest
430
- || receipt.run_id !== gate.run_id
431
- || receipt.gate_generation !== gate.gate_generation
432
- || receipt.gate_digest !== gate.gate_digest
433
- || receipt.bundle_digest !== bundle.bundle_digest
434
- || !events.some((event) => event.event_digest === receipt.control_head_digest)
435
- || receipt.control_head_digest !== bundle.control_events.at(-1)?.event_digest
436
- || receipt.previous_receipt_digest !== bundle.previous_receipt_digest
437
- || receipt.committed_at !== gate.committed_at) {
438
- fail('INVALID_GATE_STORE', 'gate/bundle/event/receipt binding不一致');
439
- }
440
- let newerReceipt = receipt;
441
- let newerGate = gate;
442
- for (let generation = gate.gate_generation - 1; generation >= 1; generation -= 1) {
443
- const previousPaths = pathsFor(runDir, generation);
444
- const previousReceipt = await readCanonical(previousPaths.receipt,
445
- validateRuntimeGateCommitReceipt, `receipt generation ${generation}`);
446
- const previousBundle = await readCanonical(previousPaths.bundle,
447
- validateRuntimeGateBundle, `bundle generation ${generation}`);
448
- if (previousReceipt.gate_generation !== generation
449
- || previousReceipt.run_id !== gate.run_id
450
- || previousBundle.run_id !== gate.run_id
451
- || previousBundle.gate.gate_generation !== generation
452
- || previousReceipt.bundle_digest !== previousBundle.bundle_digest
453
- || previousReceipt.gate_digest !== previousBundle.gate.gate_digest
454
- || previousReceipt.control_head_digest !== previousBundle.control_events.at(-1).event_digest
455
- || newerReceipt.previous_receipt_digest !== previousReceipt.receipt_digest
456
- || newerGate.previous_gate_digest !== previousReceipt.gate_digest) {
457
- fail('INVALID_GATE_STORE', `receipt chain generation ${generation}不一致`);
458
- }
459
- newerReceipt = previousReceipt;
460
- newerGate = previousBundle.gate;
461
- }
462
- if (newerReceipt.previous_receipt_digest !== null || newerGate.previous_gate_digest !== null) {
463
- fail('INVALID_GATE_STORE', 'generation 1 chain不正');
464
- }
465
- return { gate: structuredClone(gate), bundle: structuredClone(bundle), receipt: structuredClone(receipt) };
466
- }
467
-
468
- /** RuntimeManagedSupervisorの`gateWriter` dependencyへそのまま渡せるadapter。 */
469
- export function createRuntimeGateStore({ runDir, runId, sessionNonceDigest,
470
- controlEventsPath = null, crashInjector = null }) {
471
- if (typeof runDir !== 'string' || !path.isAbsolute(runDir) || !identifier(runId) || !digest(sessionNonceDigest)) {
472
- fail('INVALID_GATE_COMMIT', 'gate store設定不正');
473
- }
474
- return Object.freeze({
475
- commit: (activation) => commitRuntimeGateActivation({ runDir, runId, sessionNonceDigest,
476
- controlEventsPath, activation, crashInjector }),
477
- recover: (activation) => recoverRuntimeGateCommit({ runDir, runId, sessionNonceDigest,
478
- controlEventsPath, activation, crashInjector }),
479
- read: () => readCommittedRuntimeGate({ runDir, expectedRunId: runId, controlEventsPath }),
480
- });
481
- }
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ import { canonicalizeArtifact } from './artifact-contracts.mjs';
7
+ import { selfDigest } from './runtime-contracts.mjs';
8
+
9
+ const SHA256 = /^[0-9a-f]{64}$/;
10
+ const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
11
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
12
+ const GATE_EVENT_KINDS = Object.freeze([
13
+ 'write_gate_committed',
14
+ 'epoch_activated',
15
+ 'intake_resumed',
16
+ ]);
17
+
18
+ export class RuntimeGateStoreError extends Error {
19
+ constructor(code, detail) {
20
+ super(`${code}: ${detail}`);
21
+ this.name = 'RuntimeGateStoreError';
22
+ this.code = code;
23
+ this.detail = detail;
24
+ }
25
+ }
26
+
27
+ function fail(code, detail) { throw new RuntimeGateStoreError(code, detail); }
28
+ function digest(value) { return typeof value === 'string' && SHA256.test(value); }
29
+ function identifier(value) { return typeof value === 'string' && ID.test(value); }
30
+ function timestamp(value) {
31
+ return typeof value === 'string' && TIMESTAMP.test(value)
32
+ && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
33
+ }
34
+ function plain(value) {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
36
+ && Object.getPrototypeOf(value) === Object.prototype;
37
+ }
38
+ function exact(value, keys) {
39
+ if (!plain(value)) return false;
40
+ const actual = Object.keys(value).sort();
41
+ const expected = [...keys].sort();
42
+ return actual.length === expected.length
43
+ && actual.every((key, index) => key === expected[index]);
44
+ }
45
+ function sortedUniqueDigests(value) {
46
+ return Array.isArray(value) && value.length <= 256 && value.every(digest)
47
+ && new Set(value).size === value.length
48
+ && value.every((entry, index) => index === 0 || value[index - 1] < entry);
49
+ }
50
+ function selfDigestValid(value, field) {
51
+ if (!digest(value?.[field])) return false;
52
+ try { return selfDigest(value, field) === value[field]; } catch { return false; }
53
+ }
54
+
55
+ export function validateSupervisorWriteGate(value) {
56
+ return exact(value, [
57
+ 'schema', 'run_id', 'plan_epoch', 'gate_generation', 'release_barrier_digest',
58
+ 'controller_release_ack_digests', 'armed_lease_digests', 'previous_gate_digest',
59
+ 'committed_at', 'gate_digest',
60
+ ])
61
+ && value.schema === 'lattice.supervisor_write_gate.v1'
62
+ && identifier(value.run_id)
63
+ && Number.isSafeInteger(value.plan_epoch) && value.plan_epoch >= 1
64
+ && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1
65
+ && digest(value.release_barrier_digest)
66
+ && sortedUniqueDigests(value.controller_release_ack_digests)
67
+ && sortedUniqueDigests(value.armed_lease_digests)
68
+ && (value.previous_gate_digest === null || digest(value.previous_gate_digest))
69
+ && timestamp(value.committed_at)
70
+ && selfDigestValid(value, 'gate_digest');
71
+ }
72
+
73
+ function validGateEventPayload(kind, value) {
74
+ if (kind === 'write_gate_committed') {
75
+ return exact(value, ['gate_digest', 'gate_generation'])
76
+ && digest(value.gate_digest)
77
+ && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1;
78
+ }
79
+ return exact(value, ['plan_epoch', 'gate_digest'])
80
+ && Number.isSafeInteger(value.plan_epoch) && value.plan_epoch >= 1
81
+ && digest(value.gate_digest);
82
+ }
83
+
84
+ /** Gate batchが所有する3 eventのcanonical exact validator。 */
85
+ export function validateRuntimeGateControlEvent(value) {
86
+ return exact(value, [
87
+ 'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
88
+ 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
89
+ ])
90
+ && value.schema === 'lattice.runtime_control_event.v1'
91
+ && identifier(value.run_id)
92
+ && Number.isSafeInteger(value.sequence) && value.sequence >= 0
93
+ && (value.previous_digest === null || digest(value.previous_digest))
94
+ && GATE_EVENT_KINDS.includes(value.kind)
95
+ && digest(value.session_nonce_digest)
96
+ && validGateEventPayload(value.kind, value.payload)
97
+ && timestamp(value.recorded_at)
98
+ && selfDigestValid(value, 'event_digest');
99
+ }
100
+
101
+ /**
102
+ * revoke失敗を成功証拠へ丸めないためのexact validator。
103
+ * `lease_revoked`はcontroller responseと完全な失効集合、residual zeroを必須にする。
104
+ */
105
+ export function validateLeaseRevokedControlEvent(value) {
106
+ return exact(value, [
107
+ 'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
108
+ 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
109
+ ])
110
+ && value.schema === 'lattice.runtime_control_event.v1'
111
+ && identifier(value.run_id)
112
+ && Number.isSafeInteger(value.sequence) && value.sequence >= 0
113
+ && (value.previous_digest === null || digest(value.previous_digest))
114
+ && value.kind === 'lease_revoked'
115
+ && digest(value.session_nonce_digest)
116
+ && exact(value.payload, [
117
+ 'controller_id', 'reason', 'requested_lease_digests', 'revoked_lease_digests',
118
+ 'residual_processes', 'revoke_response_digest',
119
+ ])
120
+ && identifier(value.payload.controller_id)
121
+ && typeof value.payload.reason === 'string' && value.payload.reason.length > 0
122
+ && sortedUniqueDigests(value.payload.requested_lease_digests)
123
+ && sortedUniqueDigests(value.payload.revoked_lease_digests)
124
+ && JSON.stringify(value.payload.requested_lease_digests)
125
+ === JSON.stringify(value.payload.revoked_lease_digests)
126
+ && Array.isArray(value.payload.residual_processes)
127
+ && value.payload.residual_processes.length === 0
128
+ && digest(value.payload.revoke_response_digest)
129
+ && timestamp(value.recorded_at)
130
+ && selfDigestValid(value, 'event_digest');
131
+ }
132
+
133
+ export function validateRuntimeGateBundle(value) {
134
+ if (!(exact(value, [
135
+ 'schema', 'run_id', 'gate', 'control_events', 'previous_control_head_digest',
136
+ 'previous_receipt_digest', 'bundle_digest',
137
+ ])
138
+ && value.schema === 'lattice.runtime_gate_commit_bundle.v1'
139
+ && identifier(value.run_id)
140
+ && validateSupervisorWriteGate(value.gate)
141
+ && value.gate.run_id === value.run_id
142
+ && Array.isArray(value.control_events) && value.control_events.length === 3
143
+ && value.control_events.every(validateRuntimeGateControlEvent)
144
+ && value.control_events.map((event) => event.kind).join(',') === GATE_EVENT_KINDS.join(',')
145
+ && (value.previous_control_head_digest === null || digest(value.previous_control_head_digest))
146
+ && (value.previous_receipt_digest === null || digest(value.previous_receipt_digest))
147
+ && selfDigestValid(value, 'bundle_digest'))) return false;
148
+ const [committed, activated, resumed] = value.control_events;
149
+ return committed.previous_digest === value.previous_control_head_digest
150
+ && activated.previous_digest === committed.event_digest
151
+ && resumed.previous_digest === activated.event_digest
152
+ && committed.sequence + 1 === activated.sequence
153
+ && activated.sequence + 1 === resumed.sequence
154
+ && committed.run_id === value.run_id && activated.run_id === value.run_id && resumed.run_id === value.run_id
155
+ && committed.payload.gate_digest === value.gate.gate_digest
156
+ && committed.payload.gate_generation === value.gate.gate_generation
157
+ && activated.payload.gate_digest === value.gate.gate_digest
158
+ && activated.payload.plan_epoch === value.gate.plan_epoch
159
+ && resumed.payload.gate_digest === value.gate.gate_digest
160
+ && resumed.payload.plan_epoch === value.gate.plan_epoch;
161
+ }
162
+
163
+ export function validateRuntimeGateCommitReceipt(value) {
164
+ return exact(value, [
165
+ 'schema', 'run_id', 'gate_generation', 'gate_digest', 'bundle_digest',
166
+ 'control_head_digest', 'previous_receipt_digest', 'committed_at', 'receipt_digest',
167
+ ])
168
+ && value.schema === 'lattice.runtime_gate_commit_receipt.v1'
169
+ && identifier(value.run_id)
170
+ && Number.isSafeInteger(value.gate_generation) && value.gate_generation >= 1
171
+ && digest(value.gate_digest) && digest(value.bundle_digest)
172
+ && digest(value.control_head_digest)
173
+ && (value.previous_receipt_digest === null || digest(value.previous_receipt_digest))
174
+ && timestamp(value.committed_at)
175
+ && selfDigestValid(value, 'receipt_digest');
176
+ }
177
+
178
+ function canonicalBytes(value) { return Buffer.from(`${canonicalizeArtifact(value)}\n`); }
179
+
180
+ async function readCanonical(pathname, validator, label, { missing = false } = {}) {
181
+ let stat;
182
+ let bytes;
183
+ try {
184
+ stat = await lstat(pathname);
185
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('INVALID_GATE_STORE', `${label}がregular fileでない`);
186
+ bytes = await readFile(pathname);
187
+ } catch (error) {
188
+ if (error?.code === 'ENOENT' && missing) return null;
189
+ if (error instanceof RuntimeGateStoreError) throw error;
190
+ fail('INVALID_GATE_STORE', `${label}を読めない`);
191
+ }
192
+ let value;
193
+ try { value = JSON.parse(bytes.toString('utf8')); } catch { fail('INVALID_GATE_STORE', `${label}がJSONでない`); }
194
+ if (!validator(value)) fail('INVALID_GATE_STORE', `${label}のexact schema又はdigestが不正`);
195
+ if (!bytes.equals(canonicalBytes(value))) fail('INVALID_GATE_STORE', `${label}がcanonical bytesでない`);
196
+ return value;
197
+ }
198
+
199
+ async function fsyncDirectory(directory) {
200
+ const handle = await open(directory, fsConstants.O_RDONLY);
201
+ // Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
202
+ // win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
203
+ try { await handle.sync(); } catch (error) {
204
+ if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
205
+ } finally { await handle.close(); }
206
+ }
207
+
208
+ async function inject(crashInjector, point, context) {
209
+ if (typeof crashInjector === 'function') await crashInjector(point, structuredClone(context));
210
+ }
211
+
212
+ async function atomicPublish(pathname, value, validator, crashInjector, label) {
213
+ const existing = await readCanonical(pathname, validator, label, { missing: true });
214
+ if (existing !== null) {
215
+ if (!canonicalBytes(existing).equals(canonicalBytes(value))) {
216
+ fail('GATE_COMMIT_CONFLICT', `${label}に異なるdigestが既にある`);
217
+ }
218
+ return;
219
+ }
220
+ const directory = path.dirname(pathname);
221
+ await mkdir(directory, { recursive: true, mode: 0o700 });
222
+ const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
223
+ let handle;
224
+ try {
225
+ handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
226
+ await handle.writeFile(canonicalBytes(value));
227
+ await handle.sync();
228
+ await handle.close();
229
+ handle = null;
230
+ await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
231
+ await rename(temporary, pathname);
232
+ await inject(crashInjector, `after_${label}_rename`, { pathname });
233
+ await fsyncDirectory(directory);
234
+ await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
235
+ } finally {
236
+ if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
237
+ await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
238
+ }
239
+ }
240
+
241
+ async function atomicReplace(pathname, previousValue, value, validator, crashInjector, label) {
242
+ const existing = await readCanonical(pathname, validator, label, { missing: true });
243
+ if (existing !== null && canonicalBytes(existing).equals(canonicalBytes(value))) return;
244
+ if ((existing === null) !== (previousValue === null)
245
+ || (existing !== null && !canonicalBytes(existing).equals(canonicalBytes(previousValue)))) {
246
+ fail('GATE_COMMIT_CONFLICT', `${label}のcommitted prefixが変化した`);
247
+ }
248
+ const directory = path.dirname(pathname);
249
+ await mkdir(directory, { recursive: true, mode: 0o700 });
250
+ const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
251
+ let handle;
252
+ try {
253
+ handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
254
+ await handle.writeFile(canonicalBytes(value));
255
+ await handle.sync();
256
+ await handle.close();
257
+ handle = null;
258
+ await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
259
+ await rename(temporary, pathname);
260
+ await inject(crashInjector, `after_${label}_rename`, { pathname });
261
+ await fsyncDirectory(directory);
262
+ await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
263
+ } finally {
264
+ if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
265
+ await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
266
+ }
267
+ }
268
+
269
+ function gateName(generation, suffix) {
270
+ return `${String(generation).padStart(8, '0')}.${suffix}.json`;
271
+ }
272
+
273
+ function pathsFor(runDir, generation, controlEventsPath = null) {
274
+ const supervisorDir = path.join(runDir, 'supervisor');
275
+ return {
276
+ supervisorDir,
277
+ gate: path.join(supervisorDir, 'write-gate.json'),
278
+ events: controlEventsPath ?? path.join(runDir, 'control-events.json'),
279
+ bundle: path.join(supervisorDir, 'gate-commits', gateName(generation, 'bundle')),
280
+ receipt: path.join(supervisorDir, 'gate-receipts', gateName(generation, 'receipt')),
281
+ };
282
+ }
283
+
284
+ function validateControlJournal(value) {
285
+ if (!Array.isArray(value) || value.length > 100_000) return false;
286
+ return value.every((event, index) => (
287
+ exact(event, ['schema', 'run_id', 'sequence', 'previous_digest', 'kind', 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest'])
288
+ && event.schema === 'lattice.runtime_control_event.v1'
289
+ && identifier(event.run_id)
290
+ && Number.isSafeInteger(event.sequence) && event.sequence >= 1
291
+ && (index === 0 || event.sequence === value[index - 1].sequence + 1)
292
+ && (index === 0 ? event.previous_digest === null : event.previous_digest === value[index - 1].event_digest)
293
+ && digest(event.session_nonce_digest) && plain(event.payload) && timestamp(event.recorded_at)
294
+ && selfDigestValid(event, 'event_digest')
295
+ ));
296
+ }
297
+
298
+ function createEvents({ runId, sessionNonceDigest, previousEvents, templates, committedAt }) {
299
+ let previousDigest = previousEvents.at(-1)?.event_digest ?? null;
300
+ const firstSequence = (previousEvents.at(-1)?.sequence ?? 0) + 1;
301
+ const events = templates.map((template, offset) => {
302
+ if (!exact(template, ['kind', 'payload']) || !GATE_EVENT_KINDS.includes(template.kind)
303
+ || !validGateEventPayload(template.kind, template.payload)) {
304
+ fail('INVALID_GATE_COMMIT', 'gate control event template不正');
305
+ }
306
+ const event = {
307
+ schema: 'lattice.runtime_control_event.v1', run_id: runId,
308
+ sequence: firstSequence + offset, previous_digest: previousDigest,
309
+ kind: template.kind, session_nonce_digest: sessionNonceDigest,
310
+ payload: structuredClone(template.payload), recorded_at: committedAt, event_digest: '',
311
+ };
312
+ event.event_digest = selfDigest(event, 'event_digest');
313
+ previousDigest = event.event_digest;
314
+ return event;
315
+ });
316
+ return events;
317
+ }
318
+
319
+ async function readPriorState(runDir, gate) {
320
+ const currentGate = await readCanonical(pathsFor(runDir, gate.gate_generation).gate,
321
+ validateSupervisorWriteGate, 'gate', { missing: true });
322
+ let previousReceipt = null;
323
+ if (gate.gate_generation > 1) {
324
+ previousReceipt = await readCanonical(
325
+ pathsFor(runDir, gate.gate_generation - 1).receipt,
326
+ validateRuntimeGateCommitReceipt, 'previous_receipt', { missing: false },
327
+ );
328
+ }
329
+ if (gate.gate_generation === 1) {
330
+ if (gate.previous_gate_digest !== null || currentGate !== null) {
331
+ if (currentGate?.gate_digest !== gate.gate_digest) fail('GATE_COMMIT_CONFLICT', 'generation 1 gate chain不正');
332
+ }
333
+ } else if (gate.previous_gate_digest !== previousReceipt?.gate_digest) {
334
+ fail('GATE_COMMIT_CONFLICT', 'previous gate/receipt chain不一致');
335
+ }
336
+ if (currentGate === null && gate.gate_generation !== 1) {
337
+ fail('GATE_COMMIT_CONFLICT', 'previous committed gateがない');
338
+ }
339
+ if (currentGate !== null
340
+ && currentGate.gate_generation !== gate.gate_generation
341
+ && currentGate.gate_generation !== gate.gate_generation - 1) {
342
+ fail('GATE_COMMIT_CONFLICT', 'stale又はfuture gate generation retry');
343
+ }
344
+ if (currentGate?.gate_generation === gate.gate_generation
345
+ && currentGate.gate_digest !== gate.gate_digest) {
346
+ fail('GATE_COMMIT_CONFLICT', '同一generation gate digest衝突');
347
+ }
348
+ if (currentGate?.gate_generation === gate.gate_generation - 1
349
+ && currentGate.gate_digest !== gate.previous_gate_digest) {
350
+ fail('GATE_COMMIT_CONFLICT', 'current gate chain不一致');
351
+ }
352
+ return { currentGate, previousReceipt };
353
+ }
354
+
355
+ async function buildCommit({ runDir, runId, sessionNonceDigest, activation,
356
+ controlEventsPath = null }) {
357
+ if (!plain(activation) || !exact(activation, ['gate', 'control_events'])
358
+ || !validateSupervisorWriteGate(activation.gate)
359
+ || activation.gate.run_id !== runId || !digest(sessionNonceDigest)) {
360
+ fail('INVALID_GATE_COMMIT', 'gate activation入力不正');
361
+ }
362
+ const { previousReceipt } = await readPriorState(runDir, activation.gate);
363
+ const eventPath = pathsFor(runDir, activation.gate.gate_generation, controlEventsPath).events;
364
+ const priorEvents = await readCanonical(eventPath, validateControlJournal, 'control_events', { missing: true }) ?? [];
365
+ const alreadyAppended = priorEvents.slice(-3);
366
+ let baseEvents = priorEvents;
367
+ let newEvents;
368
+ if (alreadyAppended.length === 3
369
+ && alreadyAppended.map((event) => event.kind).join(',') === GATE_EVENT_KINDS.join(',')
370
+ && alreadyAppended.every((event) => event.payload.gate_digest === activation.gate.gate_digest)) {
371
+ newEvents = alreadyAppended;
372
+ baseEvents = priorEvents.slice(0, -3);
373
+ } else {
374
+ newEvents = createEvents({ runId, sessionNonceDigest, previousEvents: priorEvents,
375
+ templates: activation.control_events, committedAt: activation.gate.committed_at });
376
+ }
377
+ const previousControlHeadDigest = baseEvents.at(-1)?.event_digest ?? null;
378
+ const bundle = {
379
+ schema: 'lattice.runtime_gate_commit_bundle.v1', run_id: runId,
380
+ gate: structuredClone(activation.gate), control_events: structuredClone(newEvents),
381
+ previous_control_head_digest: previousControlHeadDigest,
382
+ previous_receipt_digest: previousReceipt?.receipt_digest ?? null, bundle_digest: '',
383
+ };
384
+ bundle.bundle_digest = selfDigest(bundle, 'bundle_digest');
385
+ const receipt = {
386
+ schema: 'lattice.runtime_gate_commit_receipt.v1', run_id: runId,
387
+ gate_generation: activation.gate.gate_generation, gate_digest: activation.gate.gate_digest,
388
+ bundle_digest: bundle.bundle_digest, control_head_digest: newEvents.at(-1).event_digest,
389
+ previous_receipt_digest: bundle.previous_receipt_digest,
390
+ committed_at: activation.gate.committed_at, receipt_digest: '',
391
+ };
392
+ receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
393
+ return { bundle, receipt, baseEvents, newEvents, currentGate: (await readPriorState(runDir, activation.gate)).currentGate };
394
+ }
395
+
396
+ async function commitBuilt({ runDir, built, crashInjector, controlEventsPath = null }) {
397
+ const generation = built.bundle.gate.gate_generation;
398
+ const paths = pathsFor(runDir, generation, controlEventsPath);
399
+ await atomicPublish(paths.bundle, built.bundle, validateRuntimeGateBundle, crashInjector, 'bundle');
400
+ const committedBundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
401
+ if (committedBundle.bundle_digest !== built.bundle.bundle_digest) fail('GATE_COMMIT_CONFLICT', 'bundle digest衝突');
402
+ await atomicReplace(paths.events, built.baseEvents, [...built.baseEvents, ...built.newEvents], validateControlJournal, crashInjector, 'events');
403
+ await atomicReplace(paths.gate, built.currentGate, built.bundle.gate, validateSupervisorWriteGate, crashInjector, 'gate');
404
+ // receipt renameが唯一のcommit point。これ以前のartifactはsame digest recovery専用である。
405
+ await atomicPublish(paths.receipt, built.receipt, validateRuntimeGateCommitReceipt, crashInjector, 'receipt');
406
+ return structuredClone(built.receipt);
407
+ }
408
+
409
+ export async function commitRuntimeGateActivation(options) {
410
+ const built = await buildCommit(options);
411
+ return commitBuilt({ runDir: options.runDir, built, crashInjector: options.crashInjector,
412
+ controlEventsPath: options.controlEventsPath ?? null });
413
+ }
414
+
415
+ export async function recoverRuntimeGateCommit(options) {
416
+ return commitRuntimeGateActivation(options);
417
+ }
418
+
419
+ export async function readCommittedRuntimeGate({ runDir, expectedRunId = null,
420
+ controlEventsPath = null }) {
421
+ const gatePath = path.join(runDir, 'supervisor', 'write-gate.json');
422
+ const gate = await readCanonical(gatePath, validateSupervisorWriteGate, 'gate', { missing: true });
423
+ if (gate === null) return null;
424
+ if (expectedRunId !== null && gate.run_id !== expectedRunId) fail('INVALID_GATE_STORE', 'gate run binding不一致');
425
+ const paths = pathsFor(runDir, gate.gate_generation, controlEventsPath);
426
+ const bundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
427
+ const receipt = await readCanonical(paths.receipt, validateRuntimeGateCommitReceipt, 'receipt');
428
+ const events = await readCanonical(paths.events, validateControlJournal, 'control_events');
429
+ if (bundle.gate.gate_digest !== gate.gate_digest
430
+ || receipt.run_id !== gate.run_id
431
+ || receipt.gate_generation !== gate.gate_generation
432
+ || receipt.gate_digest !== gate.gate_digest
433
+ || receipt.bundle_digest !== bundle.bundle_digest
434
+ || !events.some((event) => event.event_digest === receipt.control_head_digest)
435
+ || receipt.control_head_digest !== bundle.control_events.at(-1)?.event_digest
436
+ || receipt.previous_receipt_digest !== bundle.previous_receipt_digest
437
+ || receipt.committed_at !== gate.committed_at) {
438
+ fail('INVALID_GATE_STORE', 'gate/bundle/event/receipt binding不一致');
439
+ }
440
+ let newerReceipt = receipt;
441
+ let newerGate = gate;
442
+ for (let generation = gate.gate_generation - 1; generation >= 1; generation -= 1) {
443
+ const previousPaths = pathsFor(runDir, generation);
444
+ const previousReceipt = await readCanonical(previousPaths.receipt,
445
+ validateRuntimeGateCommitReceipt, `receipt generation ${generation}`);
446
+ const previousBundle = await readCanonical(previousPaths.bundle,
447
+ validateRuntimeGateBundle, `bundle generation ${generation}`);
448
+ if (previousReceipt.gate_generation !== generation
449
+ || previousReceipt.run_id !== gate.run_id
450
+ || previousBundle.run_id !== gate.run_id
451
+ || previousBundle.gate.gate_generation !== generation
452
+ || previousReceipt.bundle_digest !== previousBundle.bundle_digest
453
+ || previousReceipt.gate_digest !== previousBundle.gate.gate_digest
454
+ || previousReceipt.control_head_digest !== previousBundle.control_events.at(-1).event_digest
455
+ || newerReceipt.previous_receipt_digest !== previousReceipt.receipt_digest
456
+ || newerGate.previous_gate_digest !== previousReceipt.gate_digest) {
457
+ fail('INVALID_GATE_STORE', `receipt chain generation ${generation}不一致`);
458
+ }
459
+ newerReceipt = previousReceipt;
460
+ newerGate = previousBundle.gate;
461
+ }
462
+ if (newerReceipt.previous_receipt_digest !== null || newerGate.previous_gate_digest !== null) {
463
+ fail('INVALID_GATE_STORE', 'generation 1 chain不正');
464
+ }
465
+ return { gate: structuredClone(gate), bundle: structuredClone(bundle), receipt: structuredClone(receipt) };
466
+ }
467
+
468
+ /** RuntimeManagedSupervisorの`gateWriter` dependencyへそのまま渡せるadapter。 */
469
+ export function createRuntimeGateStore({ runDir, runId, sessionNonceDigest,
470
+ controlEventsPath = null, crashInjector = null }) {
471
+ if (typeof runDir !== 'string' || !path.isAbsolute(runDir) || !identifier(runId) || !digest(sessionNonceDigest)) {
472
+ fail('INVALID_GATE_COMMIT', 'gate store設定不正');
473
+ }
474
+ return Object.freeze({
475
+ commit: (activation) => commitRuntimeGateActivation({ runDir, runId, sessionNonceDigest,
476
+ controlEventsPath, activation, crashInjector }),
477
+ recover: (activation) => recoverRuntimeGateCommit({ runDir, runId, sessionNonceDigest,
478
+ controlEventsPath, activation, crashInjector }),
479
+ read: () => readCommittedRuntimeGate({ runDir, expectedRunId: runId, controlEventsPath }),
480
+ });
481
+ }