@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,477 +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
- try { await handle.sync(); } finally { await handle.close(); }
202
- }
203
-
204
- async function inject(crashInjector, point, context) {
205
- if (typeof crashInjector === 'function') await crashInjector(point, structuredClone(context));
206
- }
207
-
208
- async function atomicPublish(pathname, value, validator, crashInjector, label) {
209
- const existing = await readCanonical(pathname, validator, label, { missing: true });
210
- if (existing !== null) {
211
- if (!canonicalBytes(existing).equals(canonicalBytes(value))) {
212
- fail('GATE_COMMIT_CONFLICT', `${label}に異なるdigestが既にある`);
213
- }
214
- return;
215
- }
216
- const directory = path.dirname(pathname);
217
- await mkdir(directory, { recursive: true, mode: 0o700 });
218
- const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
219
- let handle;
220
- try {
221
- handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
222
- await handle.writeFile(canonicalBytes(value));
223
- await handle.sync();
224
- await handle.close();
225
- handle = null;
226
- await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
227
- await rename(temporary, pathname);
228
- await inject(crashInjector, `after_${label}_rename`, { pathname });
229
- await fsyncDirectory(directory);
230
- await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
231
- } finally {
232
- if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
233
- await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
234
- }
235
- }
236
-
237
- async function atomicReplace(pathname, previousValue, value, validator, crashInjector, label) {
238
- const existing = await readCanonical(pathname, validator, label, { missing: true });
239
- if (existing !== null && canonicalBytes(existing).equals(canonicalBytes(value))) return;
240
- if ((existing === null) !== (previousValue === null)
241
- || (existing !== null && !canonicalBytes(existing).equals(canonicalBytes(previousValue)))) {
242
- fail('GATE_COMMIT_CONFLICT', `${label}のcommitted prefixが変化した`);
243
- }
244
- const directory = path.dirname(pathname);
245
- await mkdir(directory, { recursive: true, mode: 0o700 });
246
- const temporary = path.join(directory, `.${path.basename(pathname)}.${randomUUID()}.tmp`);
247
- let handle;
248
- try {
249
- handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
250
- await handle.writeFile(canonicalBytes(value));
251
- await handle.sync();
252
- await handle.close();
253
- handle = null;
254
- await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
255
- await rename(temporary, pathname);
256
- await inject(crashInjector, `after_${label}_rename`, { pathname });
257
- await fsyncDirectory(directory);
258
- await inject(crashInjector, `after_${label}_directory_fsync`, { pathname });
259
- } finally {
260
- if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
261
- await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
262
- }
263
- }
264
-
265
- function gateName(generation, suffix) {
266
- return `${String(generation).padStart(8, '0')}.${suffix}.json`;
267
- }
268
-
269
- function pathsFor(runDir, generation, controlEventsPath = null) {
270
- const supervisorDir = path.join(runDir, 'supervisor');
271
- return {
272
- supervisorDir,
273
- gate: path.join(supervisorDir, 'write-gate.json'),
274
- events: controlEventsPath ?? path.join(runDir, 'control-events.json'),
275
- bundle: path.join(supervisorDir, 'gate-commits', gateName(generation, 'bundle')),
276
- receipt: path.join(supervisorDir, 'gate-receipts', gateName(generation, 'receipt')),
277
- };
278
- }
279
-
280
- function validateControlJournal(value) {
281
- if (!Array.isArray(value) || value.length > 100_000) return false;
282
- return value.every((event, index) => (
283
- exact(event, ['schema', 'run_id', 'sequence', 'previous_digest', 'kind', 'session_nonce_digest', 'payload', 'recorded_at', 'event_digest'])
284
- && event.schema === 'lattice.runtime_control_event.v1'
285
- && identifier(event.run_id)
286
- && Number.isSafeInteger(event.sequence) && event.sequence >= 1
287
- && (index === 0 || event.sequence === value[index - 1].sequence + 1)
288
- && (index === 0 ? event.previous_digest === null : event.previous_digest === value[index - 1].event_digest)
289
- && digest(event.session_nonce_digest) && plain(event.payload) && timestamp(event.recorded_at)
290
- && selfDigestValid(event, 'event_digest')
291
- ));
292
- }
293
-
294
- function createEvents({ runId, sessionNonceDigest, previousEvents, templates, committedAt }) {
295
- let previousDigest = previousEvents.at(-1)?.event_digest ?? null;
296
- const firstSequence = (previousEvents.at(-1)?.sequence ?? 0) + 1;
297
- const events = templates.map((template, offset) => {
298
- if (!exact(template, ['kind', 'payload']) || !GATE_EVENT_KINDS.includes(template.kind)
299
- || !validGateEventPayload(template.kind, template.payload)) {
300
- fail('INVALID_GATE_COMMIT', 'gate control event template不正');
301
- }
302
- const event = {
303
- schema: 'lattice.runtime_control_event.v1', run_id: runId,
304
- sequence: firstSequence + offset, previous_digest: previousDigest,
305
- kind: template.kind, session_nonce_digest: sessionNonceDigest,
306
- payload: structuredClone(template.payload), recorded_at: committedAt, event_digest: '',
307
- };
308
- event.event_digest = selfDigest(event, 'event_digest');
309
- previousDigest = event.event_digest;
310
- return event;
311
- });
312
- return events;
313
- }
314
-
315
- async function readPriorState(runDir, gate) {
316
- const currentGate = await readCanonical(pathsFor(runDir, gate.gate_generation).gate,
317
- validateSupervisorWriteGate, 'gate', { missing: true });
318
- let previousReceipt = null;
319
- if (gate.gate_generation > 1) {
320
- previousReceipt = await readCanonical(
321
- pathsFor(runDir, gate.gate_generation - 1).receipt,
322
- validateRuntimeGateCommitReceipt, 'previous_receipt', { missing: false },
323
- );
324
- }
325
- if (gate.gate_generation === 1) {
326
- if (gate.previous_gate_digest !== null || currentGate !== null) {
327
- if (currentGate?.gate_digest !== gate.gate_digest) fail('GATE_COMMIT_CONFLICT', 'generation 1 gate chain不正');
328
- }
329
- } else if (gate.previous_gate_digest !== previousReceipt?.gate_digest) {
330
- fail('GATE_COMMIT_CONFLICT', 'previous gate/receipt chain不一致');
331
- }
332
- if (currentGate === null && gate.gate_generation !== 1) {
333
- fail('GATE_COMMIT_CONFLICT', 'previous committed gateがない');
334
- }
335
- if (currentGate !== null
336
- && currentGate.gate_generation !== gate.gate_generation
337
- && currentGate.gate_generation !== gate.gate_generation - 1) {
338
- fail('GATE_COMMIT_CONFLICT', 'stale又はfuture gate generation retry');
339
- }
340
- if (currentGate?.gate_generation === gate.gate_generation
341
- && currentGate.gate_digest !== gate.gate_digest) {
342
- fail('GATE_COMMIT_CONFLICT', '同一generation gate digest衝突');
343
- }
344
- if (currentGate?.gate_generation === gate.gate_generation - 1
345
- && currentGate.gate_digest !== gate.previous_gate_digest) {
346
- fail('GATE_COMMIT_CONFLICT', 'current gate chain不一致');
347
- }
348
- return { currentGate, previousReceipt };
349
- }
350
-
351
- async function buildCommit({ runDir, runId, sessionNonceDigest, activation,
352
- controlEventsPath = null }) {
353
- if (!plain(activation) || !exact(activation, ['gate', 'control_events'])
354
- || !validateSupervisorWriteGate(activation.gate)
355
- || activation.gate.run_id !== runId || !digest(sessionNonceDigest)) {
356
- fail('INVALID_GATE_COMMIT', 'gate activation入力不正');
357
- }
358
- const { previousReceipt } = await readPriorState(runDir, activation.gate);
359
- const eventPath = pathsFor(runDir, activation.gate.gate_generation, controlEventsPath).events;
360
- const priorEvents = await readCanonical(eventPath, validateControlJournal, 'control_events', { missing: true }) ?? [];
361
- const alreadyAppended = priorEvents.slice(-3);
362
- let baseEvents = priorEvents;
363
- let newEvents;
364
- if (alreadyAppended.length === 3
365
- && alreadyAppended.map((event) => event.kind).join(',') === GATE_EVENT_KINDS.join(',')
366
- && alreadyAppended.every((event) => event.payload.gate_digest === activation.gate.gate_digest)) {
367
- newEvents = alreadyAppended;
368
- baseEvents = priorEvents.slice(0, -3);
369
- } else {
370
- newEvents = createEvents({ runId, sessionNonceDigest, previousEvents: priorEvents,
371
- templates: activation.control_events, committedAt: activation.gate.committed_at });
372
- }
373
- const previousControlHeadDigest = baseEvents.at(-1)?.event_digest ?? null;
374
- const bundle = {
375
- schema: 'lattice.runtime_gate_commit_bundle.v1', run_id: runId,
376
- gate: structuredClone(activation.gate), control_events: structuredClone(newEvents),
377
- previous_control_head_digest: previousControlHeadDigest,
378
- previous_receipt_digest: previousReceipt?.receipt_digest ?? null, bundle_digest: '',
379
- };
380
- bundle.bundle_digest = selfDigest(bundle, 'bundle_digest');
381
- const receipt = {
382
- schema: 'lattice.runtime_gate_commit_receipt.v1', run_id: runId,
383
- gate_generation: activation.gate.gate_generation, gate_digest: activation.gate.gate_digest,
384
- bundle_digest: bundle.bundle_digest, control_head_digest: newEvents.at(-1).event_digest,
385
- previous_receipt_digest: bundle.previous_receipt_digest,
386
- committed_at: activation.gate.committed_at, receipt_digest: '',
387
- };
388
- receipt.receipt_digest = selfDigest(receipt, 'receipt_digest');
389
- return { bundle, receipt, baseEvents, newEvents, currentGate: (await readPriorState(runDir, activation.gate)).currentGate };
390
- }
391
-
392
- async function commitBuilt({ runDir, built, crashInjector, controlEventsPath = null }) {
393
- const generation = built.bundle.gate.gate_generation;
394
- const paths = pathsFor(runDir, generation, controlEventsPath);
395
- await atomicPublish(paths.bundle, built.bundle, validateRuntimeGateBundle, crashInjector, 'bundle');
396
- const committedBundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
397
- if (committedBundle.bundle_digest !== built.bundle.bundle_digest) fail('GATE_COMMIT_CONFLICT', 'bundle digest衝突');
398
- await atomicReplace(paths.events, built.baseEvents, [...built.baseEvents, ...built.newEvents], validateControlJournal, crashInjector, 'events');
399
- await atomicReplace(paths.gate, built.currentGate, built.bundle.gate, validateSupervisorWriteGate, crashInjector, 'gate');
400
- // receipt renameが唯一のcommit point。これ以前のartifactはsame digest recovery専用である。
401
- await atomicPublish(paths.receipt, built.receipt, validateRuntimeGateCommitReceipt, crashInjector, 'receipt');
402
- return structuredClone(built.receipt);
403
- }
404
-
405
- export async function commitRuntimeGateActivation(options) {
406
- const built = await buildCommit(options);
407
- return commitBuilt({ runDir: options.runDir, built, crashInjector: options.crashInjector,
408
- controlEventsPath: options.controlEventsPath ?? null });
409
- }
410
-
411
- export async function recoverRuntimeGateCommit(options) {
412
- return commitRuntimeGateActivation(options);
413
- }
414
-
415
- export async function readCommittedRuntimeGate({ runDir, expectedRunId = null,
416
- controlEventsPath = null }) {
417
- const gatePath = path.join(runDir, 'supervisor', 'write-gate.json');
418
- const gate = await readCanonical(gatePath, validateSupervisorWriteGate, 'gate', { missing: true });
419
- if (gate === null) return null;
420
- if (expectedRunId !== null && gate.run_id !== expectedRunId) fail('INVALID_GATE_STORE', 'gate run binding不一致');
421
- const paths = pathsFor(runDir, gate.gate_generation, controlEventsPath);
422
- const bundle = await readCanonical(paths.bundle, validateRuntimeGateBundle, 'bundle');
423
- const receipt = await readCanonical(paths.receipt, validateRuntimeGateCommitReceipt, 'receipt');
424
- const events = await readCanonical(paths.events, validateControlJournal, 'control_events');
425
- if (bundle.gate.gate_digest !== gate.gate_digest
426
- || receipt.run_id !== gate.run_id
427
- || receipt.gate_generation !== gate.gate_generation
428
- || receipt.gate_digest !== gate.gate_digest
429
- || receipt.bundle_digest !== bundle.bundle_digest
430
- || !events.some((event) => event.event_digest === receipt.control_head_digest)
431
- || receipt.control_head_digest !== bundle.control_events.at(-1)?.event_digest
432
- || receipt.previous_receipt_digest !== bundle.previous_receipt_digest
433
- || receipt.committed_at !== gate.committed_at) {
434
- fail('INVALID_GATE_STORE', 'gate/bundle/event/receipt binding不一致');
435
- }
436
- let newerReceipt = receipt;
437
- let newerGate = gate;
438
- for (let generation = gate.gate_generation - 1; generation >= 1; generation -= 1) {
439
- const previousPaths = pathsFor(runDir, generation);
440
- const previousReceipt = await readCanonical(previousPaths.receipt,
441
- validateRuntimeGateCommitReceipt, `receipt generation ${generation}`);
442
- const previousBundle = await readCanonical(previousPaths.bundle,
443
- validateRuntimeGateBundle, `bundle generation ${generation}`);
444
- if (previousReceipt.gate_generation !== generation
445
- || previousReceipt.run_id !== gate.run_id
446
- || previousBundle.run_id !== gate.run_id
447
- || previousBundle.gate.gate_generation !== generation
448
- || previousReceipt.bundle_digest !== previousBundle.bundle_digest
449
- || previousReceipt.gate_digest !== previousBundle.gate.gate_digest
450
- || previousReceipt.control_head_digest !== previousBundle.control_events.at(-1).event_digest
451
- || newerReceipt.previous_receipt_digest !== previousReceipt.receipt_digest
452
- || newerGate.previous_gate_digest !== previousReceipt.gate_digest) {
453
- fail('INVALID_GATE_STORE', `receipt chain generation ${generation}不一致`);
454
- }
455
- newerReceipt = previousReceipt;
456
- newerGate = previousBundle.gate;
457
- }
458
- if (newerReceipt.previous_receipt_digest !== null || newerGate.previous_gate_digest !== null) {
459
- fail('INVALID_GATE_STORE', 'generation 1 chain不正');
460
- }
461
- return { gate: structuredClone(gate), bundle: structuredClone(bundle), receipt: structuredClone(receipt) };
462
- }
463
-
464
- /** RuntimeManagedSupervisorの`gateWriter` dependencyへそのまま渡せるadapter。 */
465
- export function createRuntimeGateStore({ runDir, runId, sessionNonceDigest,
466
- controlEventsPath = null, crashInjector = null }) {
467
- if (typeof runDir !== 'string' || !path.isAbsolute(runDir) || !identifier(runId) || !digest(sessionNonceDigest)) {
468
- fail('INVALID_GATE_COMMIT', 'gate store設定不正');
469
- }
470
- return Object.freeze({
471
- commit: (activation) => commitRuntimeGateActivation({ runDir, runId, sessionNonceDigest,
472
- controlEventsPath, activation, crashInjector }),
473
- recover: (activation) => recoverRuntimeGateCommit({ runDir, runId, sessionNonceDigest,
474
- controlEventsPath, activation, crashInjector }),
475
- read: () => readCommittedRuntimeGate({ runDir, expectedRunId: runId, controlEventsPath }),
476
- });
477
- }
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
+ }