@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.
- package/LICENSE +147 -147
- package/README.ja.md +355 -355
- package/README.md +258 -258
- package/bin/lattice-mcp.mjs +0 -0
- package/bin/lattice-scripted-adapter.mjs +0 -0
- package/bin/lattice-scripted-worker.mjs +0 -0
- package/bin/lattice-work-order-adapter.mjs +0 -0
- package/bin/lattice.mjs +0 -0
- package/docs/bridge-setup.md +132 -132
- package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
- package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
- package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
- package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
- package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
- package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
- package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
- package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
- package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
- package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
- package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
- package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
- package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
- package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
- package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
- package/package.json +103 -103
- package/sensor/LICENSE +21 -21
- package/sensor/NOTICE +19 -19
- package/sensor/dist/bin/lattice-sensor.js +9 -9
- package/sensor/dist/db/index.js +24 -24
- package/sensor/dist/db/migrations.js +41 -41
- package/sensor/dist/db/queries.js +164 -164
- package/sensor/dist/db/schema.sql +205 -205
- package/sensor/dist/directory.js +5 -5
- package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
- package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
- package/sensor/dist/mcp/liveness-watchdog.js +53 -53
- package/sensor/dist/mcp/server-instructions.js +95 -95
- package/sensor/package.json +56 -56
- package/src/artifact-contracts-v2.mjs +325 -325
- package/src/artifact-contracts.mjs +895 -895
- package/src/boundary-compiler.mjs +712 -712
- package/src/boundary-observation-compiler-v2.mjs +344 -344
- package/src/bounded-seam.mjs +230 -230
- package/src/bridge-address.mjs +107 -107
- package/src/bridge-cli.mjs +297 -297
- package/src/bridge-config.mjs +346 -346
- package/src/bridge-daemon.mjs +378 -378
- package/src/bridge-launch-agent.mjs +323 -323
- package/src/bridge-registrar.mjs +102 -102
- package/src/bridge-server.mjs +376 -376
- package/src/cli-help.mjs +308 -308
- package/src/cli-stdio.mjs +40 -40
- package/src/control-compiler.mjs +532 -532
- package/src/dag-chain.mjs +261 -261
- package/src/factory-diagnostics.mjs +188 -188
- package/src/hash-chain.mjs +76 -76
- package/src/hooks-cli.mjs +1057 -1053
- package/src/isolation-runner.mjs +409 -409
- package/src/node-version-guard.mjs +44 -44
- package/src/project-cli.mjs +697 -697
- package/src/project-identity.mjs +130 -130
- package/src/rc1-black-box-oracle.mjs +906 -906
- package/src/rc1-comparison.mjs +154 -154
- package/src/rc1-evidence-bundle.mjs +456 -456
- package/src/rc1-v4-campaign.mjs +708 -708
- package/src/rc1-v4-transform.mjs +467 -467
- package/src/rc1-v5-artifact-set.mjs +855 -855
- package/src/rc1-v5-behavior-evidence.mjs +594 -594
- package/src/rc1-v5-campaign.mjs +797 -797
- package/src/rc1-v5-transform.mjs +421 -421
- package/src/rc1-v6-artifact-set.mjs +807 -807
- package/src/rc1-v6-behavior-evidence.mjs +273 -273
- package/src/rc1-v6-campaign.mjs +623 -623
- package/src/rc1-v6-causal-binding.mjs +473 -473
- package/src/rc1-v6-measurement.mjs +313 -313
- package/src/rc2-artifact-set.mjs +1584 -1584
- package/src/rc2-campaign.mjs +1506 -1502
- package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
- package/src/rc2-delivery-policy-oracle.mjs +134 -134
- package/src/rc2-delivery-policy-transform.mjs +1127 -1127
- package/src/rc2-rc1-transfer-front-end.mjs +511 -511
- package/src/rc3-actual-dogfood.mjs +652 -652
- package/src/rc3-dogfood-scaffold.mjs +315 -315
- package/src/rc3-scripted-campaign.mjs +1383 -1383
- package/src/rc4-stage1-dogfood.mjs +673 -673
- package/src/runtime-adapter-registry.mjs +524 -520
- package/src/runtime-cli.mjs +4588 -4584
- package/src/runtime-contracts.mjs +824 -824
- package/src/runtime-control-store.mjs +604 -600
- package/src/runtime-controller-protocol.mjs +587 -587
- package/src/runtime-decision-verifier.mjs +701 -701
- package/src/runtime-diff-observer.mjs +361 -361
- package/src/runtime-direct-os-observer.mjs +301 -301
- package/src/runtime-driver-state.mjs +166 -162
- package/src/runtime-engine.mjs +779 -779
- package/src/runtime-errors.mjs +356 -356
- package/src/runtime-event-store.mjs +189 -189
- package/src/runtime-front-end.mjs +925 -925
- package/src/runtime-gate-store.mjs +481 -477
- package/src/runtime-hold-recompile.mjs +916 -916
- package/src/runtime-io-sentinel.mjs +391 -391
- package/src/runtime-lifecycle-lock.mjs +294 -290
- package/src/runtime-managed-supervisor.mjs +1490 -1490
- package/src/runtime-multi-epoch-store.mjs +838 -834
- package/src/runtime-projection.mjs +269 -269
- package/src/runtime-pull-intake.mjs +1192 -1188
- package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
- package/src/runtime-scripted-executor.mjs +163 -163
- package/src/runtime-scripted-worktree.mjs +104 -104
- package/src/runtime-seam-resolve.mjs +428 -428
- package/src/runtime-seam-treatment.mjs +173 -173
- package/src/runtime-socket-owner.mjs +125 -125
- package/src/runtime-work-order-contracts.mjs +91 -91
- package/src/runtime-work-order-controller.mjs +1171 -1167
- package/src/runtime-worktree-executor.mjs +199 -199
- package/src/schedulability-compiler-v2.mjs +303 -303
- package/src/schedulability-verifier-v2.mjs +317 -317
- package/src/seam-apply.mjs +549 -549
- package/src/seam-commit-shared.mjs +22 -22
- package/src/seam-commit-transform.mjs +81 -81
- package/src/seam-commit.mjs +18 -18
- package/src/seam-cost.mjs +322 -322
- package/src/seam-derivation.mjs +188 -188
- package/src/seam-gate.mjs +146 -146
- package/src/seam-proposal-contracts.mjs +446 -446
- package/src/seam-proposal-queries.mjs +521 -521
- package/src/seam-proposal.mjs +2011 -2011
- package/src/seam-ref.mjs +33 -33
- package/src/seam-rewrite.mjs +286 -286
- package/src/seam-transform.mjs +554 -554
- package/src/seam-verification.mjs +260 -260
- package/src/sensor-adapter.mjs +432 -432
- package/src/sensor-cli.mjs +139 -139
- package/src/sensor-diff.mjs +661 -661
- package/src/sensor-node-runtime.mjs +53 -53
- package/src/sensor-runtime.mjs +52 -52
- package/src/timestamp-contract.mjs +8 -8
- package/src/todo-audit-pending.mjs +91 -91
- package/src/todo-chain.mjs +178 -178
- package/src/todo-cli.mjs +3141 -3126
- package/src/todo-contracts.mjs +728 -728
- package/src/todo-dashboard-registry.mjs +573 -573
- package/src/todo-dispatch-shape.mjs +190 -190
- package/src/todo-gantt-html-independence.mjs +239 -239
- package/src/todo-gantt-html-shared.mjs +226 -226
- package/src/todo-gantt-html-style.mjs +131 -131
- package/src/todo-gantt-html.mjs +248 -248
- package/src/todo-gantt-layout.mjs +974 -974
- package/src/todo-gantt-live.mjs +361 -361
- package/src/todo-gantt-nested.mjs +263 -263
- package/src/todo-gantt-presentation.mjs +217 -217
- package/src/todo-gantt-scope.mjs +123 -123
- package/src/todo-gantt-svg.mjs +353 -353
- package/src/todo-independence-contracts.mjs +595 -595
- package/src/todo-independence-guidance.mjs +322 -322
- package/src/todo-independence.mjs +640 -640
- package/src/todo-markdown-renderer.mjs +260 -260
- package/src/todo-migration.mjs +448 -448
- package/src/todo-narrative-anchor.mjs +130 -130
- package/src/todo-note-store.mjs +629 -625
- package/src/todo-parallel-candidates.mjs +114 -114
- package/src/todo-revision.mjs +995 -995
- package/src/todo-split.mjs +472 -472
- package/src/todo-status.mjs +690 -690
- package/src/todo-store-git-transaction.mjs +418 -418
- package/src/todo-store.mjs +4322 -4314
- package/src/treatment-compiler.mjs +728 -728
- package/src/treatment-runner.mjs +656 -656
- package/src/witness-scaffold.mjs +180 -180
|
@@ -1,600 +1,604 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { constants as fsConstants } from 'node:fs';
|
|
3
|
-
import { lstat, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
|
|
6
|
-
import { canonicalizeArtifact, digestArtifact as canonicalDigest } from './artifact-contracts.mjs';
|
|
7
|
-
import { selfDigest } from './runtime-contracts.mjs';
|
|
8
|
-
import {
|
|
9
|
-
validateQuiescenceAck,
|
|
10
|
-
validateRuntimeControlRequest,
|
|
11
|
-
validateRuntimeControlResponse,
|
|
12
|
-
} from './runtime-controller-protocol.mjs';
|
|
13
|
-
|
|
14
|
-
const SHA256 = /^[0-9a-f]{64}$/;
|
|
15
|
-
const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
|
|
16
|
-
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
17
|
-
const EVENT_FIELDS = Object.freeze([
|
|
18
|
-
'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
|
|
19
|
-
'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
|
|
20
|
-
]);
|
|
21
|
-
const TEMPLATE_FIELDS = Object.freeze(['run_id', 'kind', 'session_nonce_digest', 'payload']);
|
|
22
|
-
const TIMED_TEMPLATE_FIELDS = Object.freeze([...TEMPLATE_FIELDS, 'recorded_at']);
|
|
23
|
-
const MAX_EVENTS = 100_000;
|
|
24
|
-
const MAX_REQUESTS = 100_000;
|
|
25
|
-
|
|
26
|
-
// factoryを作り直しても同一process内の同じrunは必ず一列に並ぶ。
|
|
27
|
-
const mutationQueues = new Map();
|
|
28
|
-
|
|
29
|
-
export class RuntimeControlStoreError extends Error {
|
|
30
|
-
constructor(code, detail) {
|
|
31
|
-
super(`${code}: ${detail}`);
|
|
32
|
-
this.name = 'RuntimeControlStoreError';
|
|
33
|
-
this.code = code;
|
|
34
|
-
this.detail = detail;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function fail(code, detail) { throw new RuntimeControlStoreError(code, detail); }
|
|
39
|
-
function digest(value) { return typeof value === 'string' && SHA256.test(value); }
|
|
40
|
-
function identifier(value) { return typeof value === 'string' && ID.test(value); }
|
|
41
|
-
function plain(value) {
|
|
42
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
43
|
-
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
44
|
-
}
|
|
45
|
-
function exact(value, fields) {
|
|
46
|
-
if (!plain(value)) return false;
|
|
47
|
-
const actual = Object.keys(value).sort();
|
|
48
|
-
const expected = [...fields].sort();
|
|
49
|
-
return actual.length === expected.length
|
|
50
|
-
&& actual.every((field, index) => field === expected[index]);
|
|
51
|
-
}
|
|
52
|
-
function timestamp(value) {
|
|
53
|
-
return typeof value === 'string' && TIMESTAMP.test(value)
|
|
54
|
-
&& !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
55
|
-
}
|
|
56
|
-
function selfDigestValid(value, field) {
|
|
57
|
-
if (!digest(value?.[field])) return false;
|
|
58
|
-
try { return selfDigest(value, field) === value[field]; } catch { return false; }
|
|
59
|
-
}
|
|
60
|
-
function canonicalBytes(value) { return Buffer.from(`${canonicalizeArtifact(value)}\n`); }
|
|
61
|
-
|
|
62
|
-
export function validateRuntimeControlEventPayload(kind, value) {
|
|
63
|
-
if (!plain(value)) return false;
|
|
64
|
-
if (kind === 'supervisor_activated') {
|
|
65
|
-
return exact(value, ['supervisor_descriptor_digest', 'controller_descriptor_digest', 'registration_digest'])
|
|
66
|
-
&& [value.supervisor_descriptor_digest, value.controller_descriptor_digest,
|
|
67
|
-
value.registration_digest].every(digest);
|
|
68
|
-
}
|
|
69
|
-
if (kind === 'supervisor_stopped') {
|
|
70
|
-
return (exact(value, ['shutdown_result_digest']) && digest(value.shutdown_result_digest))
|
|
71
|
-
|| (exact(value, ['signal']) && typeof value.signal === 'string' && value.signal.length > 0);
|
|
72
|
-
}
|
|
73
|
-
if (kind === 'controller_registered') {
|
|
74
|
-
return exact(value, ['controller_id', 'registration_digest'])
|
|
75
|
-
&& identifier(value.controller_id) && digest(value.registration_digest);
|
|
76
|
-
}
|
|
77
|
-
if (kind === 'controller_heartbeat') {
|
|
78
|
-
return exact(value, ['controller_id', 'registration_digest', 'sequence', 'lease_set_digest'])
|
|
79
|
-
&& identifier(value.controller_id) && digest(value.registration_digest)
|
|
80
|
-
&& Number.isSafeInteger(value.sequence) && value.sequence > 0
|
|
81
|
-
&& digest(value.lease_set_digest);
|
|
82
|
-
}
|
|
83
|
-
if (kind === 'controller_recovery_rebound') {
|
|
84
|
-
return exact(value, ['old_registration_digests', 'new_registration_digest', 'running_todo_ids'])
|
|
85
|
-
&& Array.isArray(value.old_registration_digests)
|
|
86
|
-
&& value.old_registration_digests.every(digest)
|
|
87
|
-
&& new Set(value.old_registration_digests).size === value.old_registration_digests.length
|
|
88
|
-
&& value.old_registration_digests.every((entry, index) => index === 0 || value.old_registration_digests[index - 1] < entry)
|
|
89
|
-
&& digest(value.new_registration_digest)
|
|
90
|
-
&& Array.isArray(value.running_todo_ids) && value.running_todo_ids.every(identifier)
|
|
91
|
-
&& new Set(value.running_todo_ids).size === value.running_todo_ids.length
|
|
92
|
-
&& value.running_todo_ids.every((entry, index) => index === 0 || value.running_todo_ids[index - 1] < entry);
|
|
93
|
-
}
|
|
94
|
-
if (kind === 'dispatch_routed' || kind === 'observation_routed') {
|
|
95
|
-
return exact(value, ['controller_id', 'request_digest', 'response_digest'])
|
|
96
|
-
&& identifier(value.controller_id) && digest(value.request_digest)
|
|
97
|
-
&& digest(value.response_digest);
|
|
98
|
-
}
|
|
99
|
-
if (kind === 'barrier_requested') {
|
|
100
|
-
return exact(value, ['barrier_id', 'reason', 'running_count', 'running_todo_ids', 'frozen_event_digest'])
|
|
101
|
-
&& identifier(value.barrier_id) && typeof value.reason === 'string' && value.reason.length > 0
|
|
102
|
-
&& Number.isSafeInteger(value.running_count) && value.running_count >= 0
|
|
103
|
-
&& Array.isArray(value.running_todo_ids) && value.running_todo_ids.length === value.running_count
|
|
104
|
-
&& value.running_todo_ids.every(identifier)
|
|
105
|
-
&& new Set(value.running_todo_ids).size === value.running_todo_ids.length
|
|
106
|
-
&& value.running_todo_ids.every((todo, index) => index === 0 || value.running_todo_ids[index - 1] < todo)
|
|
107
|
-
&& digest(value.frozen_event_digest);
|
|
108
|
-
}
|
|
109
|
-
if (kind === 'hold_prepared') {
|
|
110
|
-
return exact(value, ['request_id', 'logical_intent_digest', 'finding_digest',
|
|
111
|
-
'barrier_id', 'recorded_at'])
|
|
112
|
-
&& identifier(value.request_id) && digest(value.logical_intent_digest)
|
|
113
|
-
&& digest(value.finding_digest) && identifier(value.barrier_id)
|
|
114
|
-
&& timestamp(value.recorded_at);
|
|
115
|
-
}
|
|
116
|
-
if (kind === 'executor_quiesced') {
|
|
117
|
-
const observed = value.direct_observation;
|
|
118
|
-
return exact(value, ['barrier_id', 'barrier_control_digest', 'todo_id', 'ack',
|
|
119
|
-
'direct_observation', 'evidence_digest'])
|
|
120
|
-
&& identifier(value.barrier_id) && digest(value.barrier_control_digest)
|
|
121
|
-
&& identifier(value.todo_id) && validateQuiescenceAck(value.ack)
|
|
122
|
-
&& value.ack.todo_id === value.todo_id
|
|
123
|
-
&& value.ack.barrier_control_digest === value.barrier_control_digest
|
|
124
|
-
&& exact(observed, ['quiesced', 'process_observation_digest', 'worktree_fingerprint_digest',
|
|
125
|
-
'final_checkpoint_digest', 'observation', 'worktree_fingerprint', 'checkpoint', 'write_enabled'])
|
|
126
|
-
&& observed.quiesced === true && observed.write_enabled === false
|
|
127
|
-
&& digest(observed.process_observation_digest)
|
|
128
|
-
&& digest(observed.worktree_fingerprint_digest) && digest(observed.final_checkpoint_digest)
|
|
129
|
-
&& observed.process_observation_digest === canonicalDigest(observed.observation)
|
|
130
|
-
&& observed.worktree_fingerprint_digest === canonicalDigest(observed.worktree_fingerprint)
|
|
131
|
-
&& observed.final_checkpoint_digest === observed.checkpoint?.checkpoint_digest
|
|
132
|
-
&& value.ack.process_observation_digest === observed.process_observation_digest
|
|
133
|
-
&& value.ack.worktree_fingerprint_digest === observed.worktree_fingerprint_digest
|
|
134
|
-
&& value.ack.final_checkpoint_digest === observed.final_checkpoint_digest
|
|
135
|
-
&& value.evidence_digest === canonicalDigest({ ack: value.ack, direct_observation: observed });
|
|
136
|
-
}
|
|
137
|
-
if (kind === 'lease_revoked') {
|
|
138
|
-
return (exact(value, ['controller_id', 'reason'])
|
|
139
|
-
|| exact(value, ['controller_id', 'reason', 'response_digest']))
|
|
140
|
-
&& identifier(value.controller_id) && typeof value.reason === 'string' && value.reason.length > 0
|
|
141
|
-
&& (value.response_digest === undefined || digest(value.response_digest));
|
|
142
|
-
}
|
|
143
|
-
if (kind === 'epoch_rebind_acknowledged') {
|
|
144
|
-
return exact(value, ['todo_id', 'ack_digest', 'staged_lease_digest'])
|
|
145
|
-
&& identifier(value.todo_id) && digest(value.ack_digest) && digest(value.staged_lease_digest);
|
|
146
|
-
}
|
|
147
|
-
if (kind === 'write_gate_committed') {
|
|
148
|
-
return exact(value, ['gate_digest', 'gate_generation']) && digest(value.gate_digest)
|
|
149
|
-
&& Number.isSafeInteger(value.gate_generation) && value.gate_generation > 0;
|
|
150
|
-
}
|
|
151
|
-
if (kind === 'epoch_activated' || kind === 'intake_resumed') {
|
|
152
|
-
return exact(value, ['plan_epoch', 'gate_digest'])
|
|
153
|
-
&& Number.isSafeInteger(value.plan_epoch) && value.plan_epoch > 0
|
|
154
|
-
&& digest(value.gate_digest);
|
|
155
|
-
}
|
|
156
|
-
if (kind === 'supervisor_recovery_barrier') {
|
|
157
|
-
return exact(value, ['barrier_id']) && identifier(value.barrier_id);
|
|
158
|
-
}
|
|
159
|
-
// I/O sentinelの早期警報(ADR 0143)。**findingではない**——検知の正本はcheckpointのままで、
|
|
160
|
-
// これは「早くcheckpointを撮って確かめろ」という引き金の記録である。記録しない選択肢は無い:
|
|
161
|
-
// 機械が何かに気づいたのに黙っている状態を残さない。
|
|
162
|
-
if (kind === 'io_warning_observed') {
|
|
163
|
-
return exact(value, ['warning_kind', 'todo_ids', 'path', 'probe_outcome', 'warning_digest'])
|
|
164
|
-
&& ['io_overlap_warning', 'io_undeclared_write_warning'].includes(value.warning_kind)
|
|
165
|
-
&& Array.isArray(value.todo_ids) && value.todo_ids.length >= 1 && value.todo_ids.length <= 256
|
|
166
|
-
&& value.todo_ids.every(identifier)
|
|
167
|
-
&& value.todo_ids.every((id, index) => index === 0 || value.todo_ids[index - 1] < id)
|
|
168
|
-
&& typeof value.path === 'string' && value.path.length > 0 && value.path.length <= 4096
|
|
169
|
-
&& ['observed', 'transient', 'escalated', 'unprobed'].includes(value.probe_outcome)
|
|
170
|
-
&& value.warning_digest === canonicalDigest({
|
|
171
|
-
warning_kind: value.warning_kind, todo_ids: value.todo_ids, path: value.path,
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
// hold裁定のcontinue_setをprocessへ反映した記録(請求項7・8の再開側)。
|
|
175
|
-
// barrierは全workerを止めるので、続けてよいと判定した作業を再開しなければ、
|
|
176
|
-
// 判定と実行が食い違ったままになる。
|
|
177
|
-
if (kind === 'workers_resumed') {
|
|
178
|
-
return exact(value, ['resumed_todo_ids', 'skipped_count'])
|
|
179
|
-
&& Array.isArray(value.resumed_todo_ids) && value.resumed_todo_ids.length <= 4096
|
|
180
|
-
&& value.resumed_todo_ids.every(identifier)
|
|
181
|
-
&& value.resumed_todo_ids.every((id, index) => index === 0
|
|
182
|
-
|| value.resumed_todo_ids[index - 1] < id)
|
|
183
|
-
&& Number.isSafeInteger(value.skipped_count) && value.skipped_count >= 0;
|
|
184
|
-
}
|
|
185
|
-
// 破棄の決定としてworker processを終了した記録。**cleanupではない。**
|
|
186
|
-
// 停止したworkerの行き先は「再開」か「破棄」の二択であり、破棄を選んだなら
|
|
187
|
-
// 誰を止めたかが残っていなければ、後から何が捨てられたか説明できない。
|
|
188
|
-
if (kind === 'worker_processes_terminated') {
|
|
189
|
-
return exact(value, ['reason', 'terminated_pids', 'skipped_count'])
|
|
190
|
-
&& typeof value.reason === 'string' && value.reason.length > 0
|
|
191
|
-
&& Array.isArray(value.terminated_pids) && value.terminated_pids.length <= 4096
|
|
192
|
-
&& value.terminated_pids.every((pid) => Number.isSafeInteger(pid) && pid > 0)
|
|
193
|
-
&& value.terminated_pids.every((pid, index) => index === 0
|
|
194
|
-
|| value.terminated_pids[index - 1] < pid)
|
|
195
|
-
&& Number.isSafeInteger(value.skipped_count) && value.skipped_count >= 0;
|
|
196
|
-
}
|
|
197
|
-
// probeを通った警報を既存hold経路へ入れた顛末(ADR 0143の三段目)。
|
|
198
|
-
// 成否どちらも残す。自動escalationが黙って失敗する状態を作らない——失敗の理由は
|
|
199
|
-
// `detail`が持ち、これが無いと「警報は出たのにholdが掛かっていない」を後から説明できない。
|
|
200
|
-
if (kind === 'io_escalation_decided') {
|
|
201
|
-
return exact(value, ['warning_digest', 'anchor_todo_id', 'checkpoint_digest',
|
|
202
|
-
'finding_digest', 'outcome', 'detail'])
|
|
203
|
-
&& digest(value.warning_digest) && identifier(value.anchor_todo_id)
|
|
204
|
-
&& digest(value.checkpoint_digest)
|
|
205
|
-
&& (value.finding_digest === null || digest(value.finding_digest))
|
|
206
|
-
&& ['held', 'rejected', 'skipped'].includes(value.outcome)
|
|
207
|
-
// holdまで通ったなら、どのfindingで止めたかを必ず指す。途中で落ちた時は
|
|
208
|
-
// 記録済みfindingがあればそれを残す(無ければnull)——後追いの手掛かりを捨てない。
|
|
209
|
-
&& (value.outcome !== 'held' || digest(value.finding_digest))
|
|
210
|
-
&& typeof value.detail === 'string' && value.detail.length > 0 && value.detail.length <= 4096;
|
|
211
|
-
}
|
|
212
|
-
return false;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
export function validateRuntimeControlJournal(value, expectedRunId = null) {
|
|
216
|
-
if (!Array.isArray(value) || value.length > MAX_EVENTS) return false;
|
|
217
|
-
return value.every((event, index) => (
|
|
218
|
-
exact(event, EVENT_FIELDS)
|
|
219
|
-
&& event.schema === 'lattice.runtime_control_event.v1'
|
|
220
|
-
&& identifier(event.run_id)
|
|
221
|
-
&& (expectedRunId === null || event.run_id === expectedRunId)
|
|
222
|
-
&& Number.isSafeInteger(event.sequence) && event.sequence === index + 1
|
|
223
|
-
&& event.previous_digest === (index === 0 ? null : value[index - 1].event_digest)
|
|
224
|
-
&& identifier(event.kind)
|
|
225
|
-
&& digest(event.session_nonce_digest)
|
|
226
|
-
&& validateRuntimeControlEventPayload(event.kind, event.payload)
|
|
227
|
-
&& timestamp(event.recorded_at)
|
|
228
|
-
&& selfDigestValid(event, 'event_digest')
|
|
229
|
-
));
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
function validLedgerEntry(entry, runId) {
|
|
233
|
-
if (!exact(entry, ['request_id', 'request_digest', 'intent_digest', 'state', 'response'])
|
|
234
|
-
|| !identifier(entry.request_id) || !digest(entry.request_digest) || !digest(entry.intent_digest)
|
|
235
|
-
|| !['in_progress', 'completed'].includes(entry.state)) return false;
|
|
236
|
-
if (entry.state === 'in_progress') return entry.response === null;
|
|
237
|
-
return validateRuntimeControlResponse(entry.response)
|
|
238
|
-
&& entry.response.request_id === entry.request_id
|
|
239
|
-
&& entry.response.run_id === runId;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export function validateRuntimeControlRequestLedger(value, expectedRunId = null) {
|
|
243
|
-
if (!exact(value, ['schema', 'run_id', 'entries', 'ledger_digest'])
|
|
244
|
-
|| value.schema !== 'lattice.runtime_control_request_ledger.v1'
|
|
245
|
-
|| !identifier(value.run_id)
|
|
246
|
-
|| (expectedRunId !== null && value.run_id !== expectedRunId)
|
|
247
|
-
|| !Array.isArray(value.entries) || value.entries.length > MAX_REQUESTS
|
|
248
|
-
|| !value.entries.every((entry) => validLedgerEntry(entry, value.run_id))
|
|
249
|
-
|| !value.entries.every((entry, index) => index === 0
|
|
250
|
-
|| value.entries[index - 1].request_id < entry.request_id)
|
|
251
|
-
|| new Set(value.entries.map((entry) => entry.request_id)).size !== value.entries.length) return false;
|
|
252
|
-
return selfDigestValid(value, 'ledger_digest');
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
async function ensureRunDirectory(runDir) {
|
|
256
|
-
let info;
|
|
257
|
-
try { info = await lstat(runDir); } catch { fail('INVALID_CONTROL_STORE', 'run directoryを読めない'); }
|
|
258
|
-
if (!info.isDirectory() || info.isSymbolicLink()) {
|
|
259
|
-
fail('INVALID_CONTROL_STORE', 'run directoryがreal directoryでない');
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
async function readCanonical(pathname, validator, label, { missing = false } = {}) {
|
|
264
|
-
let info;
|
|
265
|
-
let bytes;
|
|
266
|
-
try {
|
|
267
|
-
info = await lstat(pathname);
|
|
268
|
-
if (!info.isFile() || info.isSymbolicLink()) fail('INVALID_CONTROL_STORE', `${label}がregular fileでない`);
|
|
269
|
-
bytes = await readFile(pathname);
|
|
270
|
-
} catch (error) {
|
|
271
|
-
if (error?.code === 'ENOENT' && missing) return null;
|
|
272
|
-
if (error instanceof RuntimeControlStoreError) throw error;
|
|
273
|
-
fail('INVALID_CONTROL_STORE', `${label}を読めない`);
|
|
274
|
-
}
|
|
275
|
-
let value;
|
|
276
|
-
try { value = JSON.parse(bytes.toString('utf8')); } catch { fail('INVALID_CONTROL_STORE', `${label}がJSONでない`); }
|
|
277
|
-
if (!validator(value)) fail('INVALID_CONTROL_STORE', `${label}のexact schema又はdigest chainが不正`);
|
|
278
|
-
if (!bytes.equals(canonicalBytes(value))) fail('INVALID_CONTROL_STORE', `${label}がcanonical bytesでない`);
|
|
279
|
-
return { value, bytes };
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
async function fsyncDirectory(directory) {
|
|
283
|
-
const handle = await open(directory, fsConstants.O_RDONLY);
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
async function
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
handle =
|
|
307
|
-
await
|
|
308
|
-
await
|
|
309
|
-
await
|
|
310
|
-
|
|
311
|
-
await inject(crashInjector,
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
await
|
|
315
|
-
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
ledger
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
if (
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
}
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants as fsConstants } from 'node:fs';
|
|
3
|
+
import { lstat, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { canonicalizeArtifact, digestArtifact as canonicalDigest } from './artifact-contracts.mjs';
|
|
7
|
+
import { selfDigest } from './runtime-contracts.mjs';
|
|
8
|
+
import {
|
|
9
|
+
validateQuiescenceAck,
|
|
10
|
+
validateRuntimeControlRequest,
|
|
11
|
+
validateRuntimeControlResponse,
|
|
12
|
+
} from './runtime-controller-protocol.mjs';
|
|
13
|
+
|
|
14
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
15
|
+
const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
|
|
16
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
17
|
+
const EVENT_FIELDS = Object.freeze([
|
|
18
|
+
'schema', 'run_id', 'sequence', 'previous_digest', 'kind',
|
|
19
|
+
'session_nonce_digest', 'payload', 'recorded_at', 'event_digest',
|
|
20
|
+
]);
|
|
21
|
+
const TEMPLATE_FIELDS = Object.freeze(['run_id', 'kind', 'session_nonce_digest', 'payload']);
|
|
22
|
+
const TIMED_TEMPLATE_FIELDS = Object.freeze([...TEMPLATE_FIELDS, 'recorded_at']);
|
|
23
|
+
const MAX_EVENTS = 100_000;
|
|
24
|
+
const MAX_REQUESTS = 100_000;
|
|
25
|
+
|
|
26
|
+
// factoryを作り直しても同一process内の同じrunは必ず一列に並ぶ。
|
|
27
|
+
const mutationQueues = new Map();
|
|
28
|
+
|
|
29
|
+
export class RuntimeControlStoreError extends Error {
|
|
30
|
+
constructor(code, detail) {
|
|
31
|
+
super(`${code}: ${detail}`);
|
|
32
|
+
this.name = 'RuntimeControlStoreError';
|
|
33
|
+
this.code = code;
|
|
34
|
+
this.detail = detail;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function fail(code, detail) { throw new RuntimeControlStoreError(code, detail); }
|
|
39
|
+
function digest(value) { return typeof value === 'string' && SHA256.test(value); }
|
|
40
|
+
function identifier(value) { return typeof value === 'string' && ID.test(value); }
|
|
41
|
+
function plain(value) {
|
|
42
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
43
|
+
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
44
|
+
}
|
|
45
|
+
function exact(value, fields) {
|
|
46
|
+
if (!plain(value)) return false;
|
|
47
|
+
const actual = Object.keys(value).sort();
|
|
48
|
+
const expected = [...fields].sort();
|
|
49
|
+
return actual.length === expected.length
|
|
50
|
+
&& actual.every((field, index) => field === expected[index]);
|
|
51
|
+
}
|
|
52
|
+
function timestamp(value) {
|
|
53
|
+
return typeof value === 'string' && TIMESTAMP.test(value)
|
|
54
|
+
&& !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
55
|
+
}
|
|
56
|
+
function selfDigestValid(value, field) {
|
|
57
|
+
if (!digest(value?.[field])) return false;
|
|
58
|
+
try { return selfDigest(value, field) === value[field]; } catch { return false; }
|
|
59
|
+
}
|
|
60
|
+
function canonicalBytes(value) { return Buffer.from(`${canonicalizeArtifact(value)}\n`); }
|
|
61
|
+
|
|
62
|
+
export function validateRuntimeControlEventPayload(kind, value) {
|
|
63
|
+
if (!plain(value)) return false;
|
|
64
|
+
if (kind === 'supervisor_activated') {
|
|
65
|
+
return exact(value, ['supervisor_descriptor_digest', 'controller_descriptor_digest', 'registration_digest'])
|
|
66
|
+
&& [value.supervisor_descriptor_digest, value.controller_descriptor_digest,
|
|
67
|
+
value.registration_digest].every(digest);
|
|
68
|
+
}
|
|
69
|
+
if (kind === 'supervisor_stopped') {
|
|
70
|
+
return (exact(value, ['shutdown_result_digest']) && digest(value.shutdown_result_digest))
|
|
71
|
+
|| (exact(value, ['signal']) && typeof value.signal === 'string' && value.signal.length > 0);
|
|
72
|
+
}
|
|
73
|
+
if (kind === 'controller_registered') {
|
|
74
|
+
return exact(value, ['controller_id', 'registration_digest'])
|
|
75
|
+
&& identifier(value.controller_id) && digest(value.registration_digest);
|
|
76
|
+
}
|
|
77
|
+
if (kind === 'controller_heartbeat') {
|
|
78
|
+
return exact(value, ['controller_id', 'registration_digest', 'sequence', 'lease_set_digest'])
|
|
79
|
+
&& identifier(value.controller_id) && digest(value.registration_digest)
|
|
80
|
+
&& Number.isSafeInteger(value.sequence) && value.sequence > 0
|
|
81
|
+
&& digest(value.lease_set_digest);
|
|
82
|
+
}
|
|
83
|
+
if (kind === 'controller_recovery_rebound') {
|
|
84
|
+
return exact(value, ['old_registration_digests', 'new_registration_digest', 'running_todo_ids'])
|
|
85
|
+
&& Array.isArray(value.old_registration_digests)
|
|
86
|
+
&& value.old_registration_digests.every(digest)
|
|
87
|
+
&& new Set(value.old_registration_digests).size === value.old_registration_digests.length
|
|
88
|
+
&& value.old_registration_digests.every((entry, index) => index === 0 || value.old_registration_digests[index - 1] < entry)
|
|
89
|
+
&& digest(value.new_registration_digest)
|
|
90
|
+
&& Array.isArray(value.running_todo_ids) && value.running_todo_ids.every(identifier)
|
|
91
|
+
&& new Set(value.running_todo_ids).size === value.running_todo_ids.length
|
|
92
|
+
&& value.running_todo_ids.every((entry, index) => index === 0 || value.running_todo_ids[index - 1] < entry);
|
|
93
|
+
}
|
|
94
|
+
if (kind === 'dispatch_routed' || kind === 'observation_routed') {
|
|
95
|
+
return exact(value, ['controller_id', 'request_digest', 'response_digest'])
|
|
96
|
+
&& identifier(value.controller_id) && digest(value.request_digest)
|
|
97
|
+
&& digest(value.response_digest);
|
|
98
|
+
}
|
|
99
|
+
if (kind === 'barrier_requested') {
|
|
100
|
+
return exact(value, ['barrier_id', 'reason', 'running_count', 'running_todo_ids', 'frozen_event_digest'])
|
|
101
|
+
&& identifier(value.barrier_id) && typeof value.reason === 'string' && value.reason.length > 0
|
|
102
|
+
&& Number.isSafeInteger(value.running_count) && value.running_count >= 0
|
|
103
|
+
&& Array.isArray(value.running_todo_ids) && value.running_todo_ids.length === value.running_count
|
|
104
|
+
&& value.running_todo_ids.every(identifier)
|
|
105
|
+
&& new Set(value.running_todo_ids).size === value.running_todo_ids.length
|
|
106
|
+
&& value.running_todo_ids.every((todo, index) => index === 0 || value.running_todo_ids[index - 1] < todo)
|
|
107
|
+
&& digest(value.frozen_event_digest);
|
|
108
|
+
}
|
|
109
|
+
if (kind === 'hold_prepared') {
|
|
110
|
+
return exact(value, ['request_id', 'logical_intent_digest', 'finding_digest',
|
|
111
|
+
'barrier_id', 'recorded_at'])
|
|
112
|
+
&& identifier(value.request_id) && digest(value.logical_intent_digest)
|
|
113
|
+
&& digest(value.finding_digest) && identifier(value.barrier_id)
|
|
114
|
+
&& timestamp(value.recorded_at);
|
|
115
|
+
}
|
|
116
|
+
if (kind === 'executor_quiesced') {
|
|
117
|
+
const observed = value.direct_observation;
|
|
118
|
+
return exact(value, ['barrier_id', 'barrier_control_digest', 'todo_id', 'ack',
|
|
119
|
+
'direct_observation', 'evidence_digest'])
|
|
120
|
+
&& identifier(value.barrier_id) && digest(value.barrier_control_digest)
|
|
121
|
+
&& identifier(value.todo_id) && validateQuiescenceAck(value.ack)
|
|
122
|
+
&& value.ack.todo_id === value.todo_id
|
|
123
|
+
&& value.ack.barrier_control_digest === value.barrier_control_digest
|
|
124
|
+
&& exact(observed, ['quiesced', 'process_observation_digest', 'worktree_fingerprint_digest',
|
|
125
|
+
'final_checkpoint_digest', 'observation', 'worktree_fingerprint', 'checkpoint', 'write_enabled'])
|
|
126
|
+
&& observed.quiesced === true && observed.write_enabled === false
|
|
127
|
+
&& digest(observed.process_observation_digest)
|
|
128
|
+
&& digest(observed.worktree_fingerprint_digest) && digest(observed.final_checkpoint_digest)
|
|
129
|
+
&& observed.process_observation_digest === canonicalDigest(observed.observation)
|
|
130
|
+
&& observed.worktree_fingerprint_digest === canonicalDigest(observed.worktree_fingerprint)
|
|
131
|
+
&& observed.final_checkpoint_digest === observed.checkpoint?.checkpoint_digest
|
|
132
|
+
&& value.ack.process_observation_digest === observed.process_observation_digest
|
|
133
|
+
&& value.ack.worktree_fingerprint_digest === observed.worktree_fingerprint_digest
|
|
134
|
+
&& value.ack.final_checkpoint_digest === observed.final_checkpoint_digest
|
|
135
|
+
&& value.evidence_digest === canonicalDigest({ ack: value.ack, direct_observation: observed });
|
|
136
|
+
}
|
|
137
|
+
if (kind === 'lease_revoked') {
|
|
138
|
+
return (exact(value, ['controller_id', 'reason'])
|
|
139
|
+
|| exact(value, ['controller_id', 'reason', 'response_digest']))
|
|
140
|
+
&& identifier(value.controller_id) && typeof value.reason === 'string' && value.reason.length > 0
|
|
141
|
+
&& (value.response_digest === undefined || digest(value.response_digest));
|
|
142
|
+
}
|
|
143
|
+
if (kind === 'epoch_rebind_acknowledged') {
|
|
144
|
+
return exact(value, ['todo_id', 'ack_digest', 'staged_lease_digest'])
|
|
145
|
+
&& identifier(value.todo_id) && digest(value.ack_digest) && digest(value.staged_lease_digest);
|
|
146
|
+
}
|
|
147
|
+
if (kind === 'write_gate_committed') {
|
|
148
|
+
return exact(value, ['gate_digest', 'gate_generation']) && digest(value.gate_digest)
|
|
149
|
+
&& Number.isSafeInteger(value.gate_generation) && value.gate_generation > 0;
|
|
150
|
+
}
|
|
151
|
+
if (kind === 'epoch_activated' || kind === 'intake_resumed') {
|
|
152
|
+
return exact(value, ['plan_epoch', 'gate_digest'])
|
|
153
|
+
&& Number.isSafeInteger(value.plan_epoch) && value.plan_epoch > 0
|
|
154
|
+
&& digest(value.gate_digest);
|
|
155
|
+
}
|
|
156
|
+
if (kind === 'supervisor_recovery_barrier') {
|
|
157
|
+
return exact(value, ['barrier_id']) && identifier(value.barrier_id);
|
|
158
|
+
}
|
|
159
|
+
// I/O sentinelの早期警報(ADR 0143)。**findingではない**——検知の正本はcheckpointのままで、
|
|
160
|
+
// これは「早くcheckpointを撮って確かめろ」という引き金の記録である。記録しない選択肢は無い:
|
|
161
|
+
// 機械が何かに気づいたのに黙っている状態を残さない。
|
|
162
|
+
if (kind === 'io_warning_observed') {
|
|
163
|
+
return exact(value, ['warning_kind', 'todo_ids', 'path', 'probe_outcome', 'warning_digest'])
|
|
164
|
+
&& ['io_overlap_warning', 'io_undeclared_write_warning'].includes(value.warning_kind)
|
|
165
|
+
&& Array.isArray(value.todo_ids) && value.todo_ids.length >= 1 && value.todo_ids.length <= 256
|
|
166
|
+
&& value.todo_ids.every(identifier)
|
|
167
|
+
&& value.todo_ids.every((id, index) => index === 0 || value.todo_ids[index - 1] < id)
|
|
168
|
+
&& typeof value.path === 'string' && value.path.length > 0 && value.path.length <= 4096
|
|
169
|
+
&& ['observed', 'transient', 'escalated', 'unprobed'].includes(value.probe_outcome)
|
|
170
|
+
&& value.warning_digest === canonicalDigest({
|
|
171
|
+
warning_kind: value.warning_kind, todo_ids: value.todo_ids, path: value.path,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
// hold裁定のcontinue_setをprocessへ反映した記録(請求項7・8の再開側)。
|
|
175
|
+
// barrierは全workerを止めるので、続けてよいと判定した作業を再開しなければ、
|
|
176
|
+
// 判定と実行が食い違ったままになる。
|
|
177
|
+
if (kind === 'workers_resumed') {
|
|
178
|
+
return exact(value, ['resumed_todo_ids', 'skipped_count'])
|
|
179
|
+
&& Array.isArray(value.resumed_todo_ids) && value.resumed_todo_ids.length <= 4096
|
|
180
|
+
&& value.resumed_todo_ids.every(identifier)
|
|
181
|
+
&& value.resumed_todo_ids.every((id, index) => index === 0
|
|
182
|
+
|| value.resumed_todo_ids[index - 1] < id)
|
|
183
|
+
&& Number.isSafeInteger(value.skipped_count) && value.skipped_count >= 0;
|
|
184
|
+
}
|
|
185
|
+
// 破棄の決定としてworker processを終了した記録。**cleanupではない。**
|
|
186
|
+
// 停止したworkerの行き先は「再開」か「破棄」の二択であり、破棄を選んだなら
|
|
187
|
+
// 誰を止めたかが残っていなければ、後から何が捨てられたか説明できない。
|
|
188
|
+
if (kind === 'worker_processes_terminated') {
|
|
189
|
+
return exact(value, ['reason', 'terminated_pids', 'skipped_count'])
|
|
190
|
+
&& typeof value.reason === 'string' && value.reason.length > 0
|
|
191
|
+
&& Array.isArray(value.terminated_pids) && value.terminated_pids.length <= 4096
|
|
192
|
+
&& value.terminated_pids.every((pid) => Number.isSafeInteger(pid) && pid > 0)
|
|
193
|
+
&& value.terminated_pids.every((pid, index) => index === 0
|
|
194
|
+
|| value.terminated_pids[index - 1] < pid)
|
|
195
|
+
&& Number.isSafeInteger(value.skipped_count) && value.skipped_count >= 0;
|
|
196
|
+
}
|
|
197
|
+
// probeを通った警報を既存hold経路へ入れた顛末(ADR 0143の三段目)。
|
|
198
|
+
// 成否どちらも残す。自動escalationが黙って失敗する状態を作らない——失敗の理由は
|
|
199
|
+
// `detail`が持ち、これが無いと「警報は出たのにholdが掛かっていない」を後から説明できない。
|
|
200
|
+
if (kind === 'io_escalation_decided') {
|
|
201
|
+
return exact(value, ['warning_digest', 'anchor_todo_id', 'checkpoint_digest',
|
|
202
|
+
'finding_digest', 'outcome', 'detail'])
|
|
203
|
+
&& digest(value.warning_digest) && identifier(value.anchor_todo_id)
|
|
204
|
+
&& digest(value.checkpoint_digest)
|
|
205
|
+
&& (value.finding_digest === null || digest(value.finding_digest))
|
|
206
|
+
&& ['held', 'rejected', 'skipped'].includes(value.outcome)
|
|
207
|
+
// holdまで通ったなら、どのfindingで止めたかを必ず指す。途中で落ちた時は
|
|
208
|
+
// 記録済みfindingがあればそれを残す(無ければnull)——後追いの手掛かりを捨てない。
|
|
209
|
+
&& (value.outcome !== 'held' || digest(value.finding_digest))
|
|
210
|
+
&& typeof value.detail === 'string' && value.detail.length > 0 && value.detail.length <= 4096;
|
|
211
|
+
}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function validateRuntimeControlJournal(value, expectedRunId = null) {
|
|
216
|
+
if (!Array.isArray(value) || value.length > MAX_EVENTS) return false;
|
|
217
|
+
return value.every((event, index) => (
|
|
218
|
+
exact(event, EVENT_FIELDS)
|
|
219
|
+
&& event.schema === 'lattice.runtime_control_event.v1'
|
|
220
|
+
&& identifier(event.run_id)
|
|
221
|
+
&& (expectedRunId === null || event.run_id === expectedRunId)
|
|
222
|
+
&& Number.isSafeInteger(event.sequence) && event.sequence === index + 1
|
|
223
|
+
&& event.previous_digest === (index === 0 ? null : value[index - 1].event_digest)
|
|
224
|
+
&& identifier(event.kind)
|
|
225
|
+
&& digest(event.session_nonce_digest)
|
|
226
|
+
&& validateRuntimeControlEventPayload(event.kind, event.payload)
|
|
227
|
+
&& timestamp(event.recorded_at)
|
|
228
|
+
&& selfDigestValid(event, 'event_digest')
|
|
229
|
+
));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function validLedgerEntry(entry, runId) {
|
|
233
|
+
if (!exact(entry, ['request_id', 'request_digest', 'intent_digest', 'state', 'response'])
|
|
234
|
+
|| !identifier(entry.request_id) || !digest(entry.request_digest) || !digest(entry.intent_digest)
|
|
235
|
+
|| !['in_progress', 'completed'].includes(entry.state)) return false;
|
|
236
|
+
if (entry.state === 'in_progress') return entry.response === null;
|
|
237
|
+
return validateRuntimeControlResponse(entry.response)
|
|
238
|
+
&& entry.response.request_id === entry.request_id
|
|
239
|
+
&& entry.response.run_id === runId;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function validateRuntimeControlRequestLedger(value, expectedRunId = null) {
|
|
243
|
+
if (!exact(value, ['schema', 'run_id', 'entries', 'ledger_digest'])
|
|
244
|
+
|| value.schema !== 'lattice.runtime_control_request_ledger.v1'
|
|
245
|
+
|| !identifier(value.run_id)
|
|
246
|
+
|| (expectedRunId !== null && value.run_id !== expectedRunId)
|
|
247
|
+
|| !Array.isArray(value.entries) || value.entries.length > MAX_REQUESTS
|
|
248
|
+
|| !value.entries.every((entry) => validLedgerEntry(entry, value.run_id))
|
|
249
|
+
|| !value.entries.every((entry, index) => index === 0
|
|
250
|
+
|| value.entries[index - 1].request_id < entry.request_id)
|
|
251
|
+
|| new Set(value.entries.map((entry) => entry.request_id)).size !== value.entries.length) return false;
|
|
252
|
+
return selfDigestValid(value, 'ledger_digest');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function ensureRunDirectory(runDir) {
|
|
256
|
+
let info;
|
|
257
|
+
try { info = await lstat(runDir); } catch { fail('INVALID_CONTROL_STORE', 'run directoryを読めない'); }
|
|
258
|
+
if (!info.isDirectory() || info.isSymbolicLink()) {
|
|
259
|
+
fail('INVALID_CONTROL_STORE', 'run directoryがreal directoryでない');
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function readCanonical(pathname, validator, label, { missing = false } = {}) {
|
|
264
|
+
let info;
|
|
265
|
+
let bytes;
|
|
266
|
+
try {
|
|
267
|
+
info = await lstat(pathname);
|
|
268
|
+
if (!info.isFile() || info.isSymbolicLink()) fail('INVALID_CONTROL_STORE', `${label}がregular fileでない`);
|
|
269
|
+
bytes = await readFile(pathname);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (error?.code === 'ENOENT' && missing) return null;
|
|
272
|
+
if (error instanceof RuntimeControlStoreError) throw error;
|
|
273
|
+
fail('INVALID_CONTROL_STORE', `${label}を読めない`);
|
|
274
|
+
}
|
|
275
|
+
let value;
|
|
276
|
+
try { value = JSON.parse(bytes.toString('utf8')); } catch { fail('INVALID_CONTROL_STORE', `${label}がJSONでない`); }
|
|
277
|
+
if (!validator(value)) fail('INVALID_CONTROL_STORE', `${label}のexact schema又はdigest chainが不正`);
|
|
278
|
+
if (!bytes.equals(canonicalBytes(value))) fail('INVALID_CONTROL_STORE', `${label}がcanonical bytesでない`);
|
|
279
|
+
return { value, bytes };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function fsyncDirectory(directory) {
|
|
283
|
+
const handle = await open(directory, fsConstants.O_RDONLY);
|
|
284
|
+
// Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
|
|
285
|
+
// win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
|
|
286
|
+
try { await handle.sync(); } catch (error) {
|
|
287
|
+
if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
|
|
288
|
+
} finally { await handle.close(); }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function inject(crashInjector, point, context) {
|
|
292
|
+
if (typeof crashInjector === 'function') await crashInjector(point, structuredClone(context));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function replaceCanonical({ pathname, expectedBytes, value, validator, crashInjector,
|
|
296
|
+
label, directoryFsyncPoint }) {
|
|
297
|
+
const current = await readCanonical(pathname, validator, label, { missing: expectedBytes === null });
|
|
298
|
+
if ((current === null) !== (expectedBytes === null)
|
|
299
|
+
|| (current !== null && !current.bytes.equals(expectedBytes))) {
|
|
300
|
+
fail('CONTROL_STORE_CONFLICT', `${label}のdisk prefixが変化した`);
|
|
301
|
+
}
|
|
302
|
+
const bytes = canonicalBytes(value);
|
|
303
|
+
const temporary = path.join(path.dirname(pathname), `.${path.basename(pathname)}.${randomUUID()}.tmp`);
|
|
304
|
+
let handle;
|
|
305
|
+
try {
|
|
306
|
+
handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
307
|
+
await handle.writeFile(bytes);
|
|
308
|
+
await handle.sync();
|
|
309
|
+
await handle.close();
|
|
310
|
+
handle = null;
|
|
311
|
+
await inject(crashInjector, `after_${label}_file_fsync`, { pathname });
|
|
312
|
+
await rename(temporary, pathname);
|
|
313
|
+
await inject(crashInjector, `after_${label}_rename`, { pathname });
|
|
314
|
+
await fsyncDirectory(path.dirname(pathname));
|
|
315
|
+
await inject(crashInjector, directoryFsyncPoint, { pathname });
|
|
316
|
+
} finally {
|
|
317
|
+
if (handle !== null && handle !== undefined) await handle.close().catch(() => {});
|
|
318
|
+
await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function enqueue(runDir, mutation) {
|
|
323
|
+
const previous = mutationQueues.get(runDir) ?? Promise.resolve();
|
|
324
|
+
const result = previous.then(mutation);
|
|
325
|
+
const settled = result.catch(() => {});
|
|
326
|
+
mutationQueues.set(runDir, settled);
|
|
327
|
+
settled.finally(() => {
|
|
328
|
+
if (mutationQueues.get(runDir) === settled) mutationQueues.delete(runDir);
|
|
329
|
+
});
|
|
330
|
+
return result;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function templateRecordedAt(template, clock) {
|
|
334
|
+
if (exact(template, TIMED_TEMPLATE_FIELDS)) return template.recorded_at;
|
|
335
|
+
if (exact(template, TEMPLATE_FIELDS)) return clock();
|
|
336
|
+
fail('INVALID_CONTROL_EVENT', 'append templateのexact fieldが不正');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function sameEventIntent(event, template) {
|
|
340
|
+
return event.run_id === template.run_id
|
|
341
|
+
&& event.kind === template.kind
|
|
342
|
+
&& event.session_nonce_digest === template.session_nonce_digest
|
|
343
|
+
&& canonicalizeArtifact(event.payload) === canonicalizeArtifact(template.payload);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function buildEvent(template, priorEvents, recordedAt, runId) {
|
|
347
|
+
if (template.run_id !== runId || !identifier(template.kind)
|
|
348
|
+
|| !digest(template.session_nonce_digest)
|
|
349
|
+
|| !validateRuntimeControlEventPayload(template.kind, template.payload)
|
|
350
|
+
|| !timestamp(recordedAt)) fail('INVALID_CONTROL_EVENT', 'append template値が不正');
|
|
351
|
+
try { canonicalizeArtifact(template.payload); } catch {
|
|
352
|
+
fail('INVALID_CONTROL_EVENT', 'append payloadがcanonical JSON値でない');
|
|
353
|
+
}
|
|
354
|
+
const previous = priorEvents.at(-1) ?? null;
|
|
355
|
+
const event = {
|
|
356
|
+
schema: 'lattice.runtime_control_event.v1', run_id: runId,
|
|
357
|
+
sequence: (previous?.sequence ?? 0) + 1,
|
|
358
|
+
previous_digest: previous?.event_digest ?? null,
|
|
359
|
+
kind: template.kind, session_nonce_digest: template.session_nonce_digest,
|
|
360
|
+
payload: structuredClone(template.payload), recorded_at: recordedAt, event_digest: '',
|
|
361
|
+
};
|
|
362
|
+
event.event_digest = selfDigest(event, 'event_digest');
|
|
363
|
+
return event;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function emptyLedger(runId) {
|
|
367
|
+
const ledger = {
|
|
368
|
+
schema: 'lattice.runtime_control_request_ledger.v1', run_id: runId,
|
|
369
|
+
entries: [], ledger_digest: '',
|
|
370
|
+
};
|
|
371
|
+
ledger.ledger_digest = selfDigest(ledger, 'ledger_digest');
|
|
372
|
+
return ledger;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function withLedgerEntries(ledger, entries) {
|
|
376
|
+
const next = { ...ledger, entries: [...entries].sort((a, b) => (
|
|
377
|
+
a.request_id < b.request_id ? -1 : a.request_id > b.request_id ? 1 : 0
|
|
378
|
+
)), ledger_digest: '' };
|
|
379
|
+
next.ledger_digest = selfDigest(next, 'ledger_digest');
|
|
380
|
+
return next;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function assertRequest(request, runId) {
|
|
384
|
+
if (!validateRuntimeControlRequest(request) || request.run_id !== runId) {
|
|
385
|
+
fail('INVALID_CONTROL_REQUEST', 'request exact schema又はrun binding不正');
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function logicalIntentDigest(request) {
|
|
390
|
+
return selfDigest({ request_id: request.request_id, run_id: request.run_id,
|
|
391
|
+
operation: request.operation, payload: request.payload, intent_digest: '' }, 'intent_digest');
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function publicLedgerResult(entry, disposition = entry.state) {
|
|
395
|
+
return Object.freeze({
|
|
396
|
+
disposition,
|
|
397
|
+
state: entry.state,
|
|
398
|
+
request_digest: entry.request_digest,
|
|
399
|
+
intent_digest: entry.intent_digest,
|
|
400
|
+
response: entry.response === null ? null : structuredClone(entry.response),
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** run単位のcontrol journalとrequest idempotency ledgerを所有するdurable store。 */
|
|
405
|
+
export function createRuntimeControlStore({ runDir, runId, clock = () => new Date().toISOString(),
|
|
406
|
+
crashInjector = null }) {
|
|
407
|
+
if (typeof runDir !== 'string' || !path.isAbsolute(runDir)
|
|
408
|
+
|| !identifier(runId) || typeof clock !== 'function'
|
|
409
|
+
|| (crashInjector !== null && typeof crashInjector !== 'function')) {
|
|
410
|
+
fail('INVALID_CONTROL_STORE', 'control store設定不正');
|
|
411
|
+
}
|
|
412
|
+
const normalizedRunDir = path.resolve(runDir);
|
|
413
|
+
const eventPath = path.join(normalizedRunDir, 'control-events.json');
|
|
414
|
+
const ledgerPath = path.join(normalizedRunDir, 'control-request-ledger.json');
|
|
415
|
+
const journalValidator = (value) => validateRuntimeControlJournal(value, runId);
|
|
416
|
+
const ledgerValidator = (value) => validateRuntimeControlRequestLedger(value, runId);
|
|
417
|
+
|
|
418
|
+
async function append(template) {
|
|
419
|
+
return enqueue(normalizedRunDir, async () => {
|
|
420
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
421
|
+
const prior = await readCanonical(eventPath, journalValidator, 'control_events', { missing: true });
|
|
422
|
+
const events = prior?.value ?? [];
|
|
423
|
+
const recordedAt = templateRecordedAt(template, clock);
|
|
424
|
+
// tail比較のcanonicalizeより前に入力全体を検査する。
|
|
425
|
+
buildEvent(template, events, recordedAt, runId);
|
|
426
|
+
const tail = events.at(-1);
|
|
427
|
+
// rename後に応答前crashした呼出しは、同じintentから同じevent digestを再発見する。
|
|
428
|
+
if (tail !== undefined && sameEventIntent(tail, template)) {
|
|
429
|
+
await fsyncDirectory(normalizedRunDir);
|
|
430
|
+
return tail.event_digest;
|
|
431
|
+
}
|
|
432
|
+
if (events.length >= MAX_EVENTS) fail('CONTROL_STORE_LIMIT', 'control event上限超過');
|
|
433
|
+
const event = buildEvent(template, events, recordedAt, runId);
|
|
434
|
+
const next = [...events, event];
|
|
435
|
+
await replaceCanonical({
|
|
436
|
+
pathname: eventPath, expectedBytes: prior?.bytes ?? null, value: next,
|
|
437
|
+
validator: journalValidator, crashInjector, label: 'control_events',
|
|
438
|
+
directoryFsyncPoint: 'after_run_directory_fsync',
|
|
439
|
+
});
|
|
440
|
+
return event.event_digest;
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function beginRequest(request) {
|
|
445
|
+
return enqueue(normalizedRunDir, async () => {
|
|
446
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
447
|
+
assertRequest(request, runId);
|
|
448
|
+
const prior = await readCanonical(ledgerPath, ledgerValidator, 'request_ledger', { missing: true });
|
|
449
|
+
const ledger = prior?.value ?? emptyLedger(runId);
|
|
450
|
+
const existing = ledger.entries.find((entry) => entry.request_id === request.request_id);
|
|
451
|
+
if (existing !== undefined) {
|
|
452
|
+
if (existing.intent_digest !== logicalIntentDigest(request)) {
|
|
453
|
+
fail('REQUEST_ID_CONFLICT', '同一request_idへ異なるlogical intent');
|
|
454
|
+
}
|
|
455
|
+
await fsyncDirectory(normalizedRunDir);
|
|
456
|
+
return publicLedgerResult(existing);
|
|
457
|
+
}
|
|
458
|
+
if (ledger.entries.length >= MAX_REQUESTS) fail('CONTROL_STORE_LIMIT', 'request ledger上限超過');
|
|
459
|
+
const entry = { request_id: request.request_id, request_digest: request.request_digest,
|
|
460
|
+
intent_digest: logicalIntentDigest(request),
|
|
461
|
+
state: 'in_progress', response: null };
|
|
462
|
+
const next = withLedgerEntries(ledger, [...ledger.entries, entry]);
|
|
463
|
+
await replaceCanonical({
|
|
464
|
+
pathname: ledgerPath, expectedBytes: prior?.bytes ?? null, value: next,
|
|
465
|
+
validator: ledgerValidator, crashInjector, label: 'request_ledger',
|
|
466
|
+
directoryFsyncPoint: 'after_request_ledger_directory_fsync',
|
|
467
|
+
});
|
|
468
|
+
return publicLedgerResult(entry, 'started');
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async function completeRequest(request, response) {
|
|
473
|
+
return enqueue(normalizedRunDir, async () => {
|
|
474
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
475
|
+
assertRequest(request, runId);
|
|
476
|
+
if (!validateRuntimeControlResponse(response)
|
|
477
|
+
|| response.request_id !== request.request_id || response.run_id !== runId
|
|
478
|
+
|| response.result.operation !== request.operation) {
|
|
479
|
+
fail('INVALID_CONTROL_RESPONSE', 'response exact schema又はrequest binding不正');
|
|
480
|
+
}
|
|
481
|
+
const prior = await readCanonical(ledgerPath, ledgerValidator, 'request_ledger');
|
|
482
|
+
const ledger = prior.value;
|
|
483
|
+
const index = ledger.entries.findIndex((entry) => entry.request_id === request.request_id);
|
|
484
|
+
if (index < 0) fail('REQUEST_NOT_STARTED', 'request ledgerにin_progressがない');
|
|
485
|
+
const existing = ledger.entries[index];
|
|
486
|
+
if (existing.intent_digest !== logicalIntentDigest(request)) {
|
|
487
|
+
fail('REQUEST_ID_CONFLICT', '同一request_idへ異なるlogical intent');
|
|
488
|
+
}
|
|
489
|
+
if (existing.state === 'completed') {
|
|
490
|
+
if (existing.response.response_digest !== response.response_digest) {
|
|
491
|
+
fail('REQUEST_RESPONSE_CONFLICT', 'completed response digest衝突');
|
|
492
|
+
}
|
|
493
|
+
await fsyncDirectory(normalizedRunDir);
|
|
494
|
+
return structuredClone(existing.response);
|
|
495
|
+
}
|
|
496
|
+
const completed = { ...existing, state: 'completed', response: structuredClone(response) };
|
|
497
|
+
const entries = [...ledger.entries];
|
|
498
|
+
entries[index] = completed;
|
|
499
|
+
const next = withLedgerEntries(ledger, entries);
|
|
500
|
+
await replaceCanonical({
|
|
501
|
+
pathname: ledgerPath, expectedBytes: prior.bytes, value: next,
|
|
502
|
+
validator: ledgerValidator, crashInjector, label: 'request_ledger',
|
|
503
|
+
directoryFsyncPoint: 'after_request_ledger_directory_fsync',
|
|
504
|
+
});
|
|
505
|
+
return structuredClone(response);
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async function recoverCompletedRequest(request, response) {
|
|
510
|
+
return enqueue(normalizedRunDir, async () => {
|
|
511
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
512
|
+
assertRequest(request, runId);
|
|
513
|
+
if (!validateRuntimeControlResponse(response)
|
|
514
|
+
|| response.request_id !== request.request_id || response.run_id !== runId
|
|
515
|
+
|| response.result.operation !== request.operation || response.outcome !== 'completed') {
|
|
516
|
+
fail('INVALID_CONTROL_RESPONSE', 'recovery response exact schema又はrequest binding不正');
|
|
517
|
+
}
|
|
518
|
+
const prior = await readCanonical(ledgerPath, ledgerValidator, 'request_ledger');
|
|
519
|
+
const ledger = prior.value;
|
|
520
|
+
const index = ledger.entries.findIndex((entry) => entry.request_id === request.request_id);
|
|
521
|
+
if (index < 0) fail('REQUEST_NOT_STARTED', 'request ledgerにentryがない');
|
|
522
|
+
const existing = ledger.entries[index];
|
|
523
|
+
if (existing.intent_digest !== logicalIntentDigest(request)) {
|
|
524
|
+
fail('REQUEST_ID_CONFLICT', '同一request_idへ異なるlogical intent');
|
|
525
|
+
}
|
|
526
|
+
if (existing.state !== 'completed' || existing.response?.outcome !== 'rejected') {
|
|
527
|
+
fail('REQUEST_RESPONSE_CONFLICT', 'rejected response以外はrecovery昇格できない');
|
|
528
|
+
}
|
|
529
|
+
const recovered = { ...existing, request_digest: request.request_digest,
|
|
530
|
+
response: structuredClone(response) };
|
|
531
|
+
const entries = [...ledger.entries];
|
|
532
|
+
entries[index] = recovered;
|
|
533
|
+
const next = withLedgerEntries(ledger, entries);
|
|
534
|
+
await replaceCanonical({
|
|
535
|
+
pathname: ledgerPath, expectedBytes: prior.bytes, value: next,
|
|
536
|
+
validator: ledgerValidator, crashInjector, label: 'request_ledger',
|
|
537
|
+
directoryFsyncPoint: 'after_request_ledger_directory_fsync',
|
|
538
|
+
});
|
|
539
|
+
return structuredClone(response);
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function replaceCompletedActivationRequest(request, response) {
|
|
544
|
+
return enqueue(normalizedRunDir, async () => {
|
|
545
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
546
|
+
assertRequest(request, runId);
|
|
547
|
+
if (request.operation !== 'activate' || !validateRuntimeControlResponse(response, 'activate')
|
|
548
|
+
|| response.request_id !== request.request_id || response.run_id !== runId
|
|
549
|
+
|| response.outcome !== 'completed') {
|
|
550
|
+
fail('INVALID_CONTROL_RESPONSE', 'activation recovery response binding不正');
|
|
551
|
+
}
|
|
552
|
+
const prior = await readCanonical(ledgerPath, ledgerValidator, 'request_ledger');
|
|
553
|
+
const ledger = prior.value;
|
|
554
|
+
const index = ledger.entries.findIndex((entry) => entry.request_id === request.request_id);
|
|
555
|
+
if (index < 0) fail('REQUEST_NOT_STARTED', 'request ledgerにactivation entryがない');
|
|
556
|
+
const existing = ledger.entries[index];
|
|
557
|
+
if (existing.intent_digest !== logicalIntentDigest(request)) {
|
|
558
|
+
fail('REQUEST_ID_CONFLICT', '同一request_idへ異なるlogical intent');
|
|
559
|
+
}
|
|
560
|
+
if (existing.state === 'completed' && existing.request_digest === request.request_digest
|
|
561
|
+
&& existing.response.response_digest === response.response_digest) {
|
|
562
|
+
await fsyncDirectory(normalizedRunDir);
|
|
563
|
+
return structuredClone(existing.response);
|
|
564
|
+
}
|
|
565
|
+
const recovered = { ...existing, request_digest: request.request_digest,
|
|
566
|
+
state: 'completed', response: structuredClone(response) };
|
|
567
|
+
const entries = [...ledger.entries];
|
|
568
|
+
entries[index] = recovered;
|
|
569
|
+
const next = withLedgerEntries(ledger, entries);
|
|
570
|
+
await replaceCanonical({
|
|
571
|
+
pathname: ledgerPath, expectedBytes: prior.bytes, value: next,
|
|
572
|
+
validator: ledgerValidator, crashInjector, label: 'request_ledger',
|
|
573
|
+
directoryFsyncPoint: 'after_request_ledger_directory_fsync',
|
|
574
|
+
});
|
|
575
|
+
return structuredClone(response);
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async function readRequest(request) {
|
|
580
|
+
return enqueue(normalizedRunDir, async () => {
|
|
581
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
582
|
+
assertRequest(request, runId);
|
|
583
|
+
const stored = await readCanonical(ledgerPath, ledgerValidator, 'request_ledger', { missing: true });
|
|
584
|
+
if (stored === null) return null;
|
|
585
|
+
const entry = stored.value.entries.find((candidate) => candidate.request_id === request.request_id);
|
|
586
|
+
if (entry === undefined) return null;
|
|
587
|
+
if (entry.intent_digest !== logicalIntentDigest(request)) {
|
|
588
|
+
fail('REQUEST_ID_CONFLICT', '同一request_idへ異なるlogical intent');
|
|
589
|
+
}
|
|
590
|
+
return publicLedgerResult(entry);
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async function readEvents() {
|
|
595
|
+
return enqueue(normalizedRunDir, async () => {
|
|
596
|
+
await ensureRunDirectory(normalizedRunDir);
|
|
597
|
+
const stored = await readCanonical(eventPath, journalValidator, 'control_events', { missing: true });
|
|
598
|
+
return structuredClone(stored?.value ?? []);
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
return Object.freeze({ append, beginRequest, completeRequest, recoverCompletedRequest,
|
|
603
|
+
replaceCompletedActivationRequest, readRequest, readEvents });
|
|
604
|
+
}
|