@quolu/lattice 0.52.3 → 0.53.0

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