@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,834 +1,838 @@
|
|
|
1
|
-
import {
|
|
2
|
-
lstat,
|
|
3
|
-
mkdir,
|
|
4
|
-
open,
|
|
5
|
-
readFile,
|
|
6
|
-
rename,
|
|
7
|
-
rm,
|
|
8
|
-
writeFile,
|
|
9
|
-
} from 'node:fs/promises';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
|
|
12
|
-
import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
|
|
13
|
-
import { buildExecutorPackets } from './runtime-engine.mjs';
|
|
14
|
-
import {
|
|
15
|
-
RUNTIME_CONFLICT_KINDS,
|
|
16
|
-
validateExecutorPacket,
|
|
17
|
-
validateRunRequest,
|
|
18
|
-
validateRuntimeBoundaryManifest,
|
|
19
|
-
validateRuntimePlan,
|
|
20
|
-
verifyRuntimePlanBinding,
|
|
21
|
-
} from './runtime-contracts.mjs';
|
|
22
|
-
import {
|
|
23
|
-
validateRunRequestV2,
|
|
24
|
-
validateRuntimeRecompileRequest,
|
|
25
|
-
validateRuntimeTaskMigration,
|
|
26
|
-
} from './runtime-hold-recompile.mjs';
|
|
27
|
-
|
|
28
|
-
const HEX_DIGEST = /^[0-9a-f]{64}$/u;
|
|
29
|
-
const EPOCH_DIRECTORY = /^\d{8}$/u;
|
|
30
|
-
const TRANSACTION_ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
|
|
31
|
-
const RUNTIME_UPGRADE_COMMAND = 'npm install -g @quolu/lattice@latest --prefer-online';
|
|
32
|
-
|
|
33
|
-
export class RuntimeEpochStoreError extends Error {
|
|
34
|
-
constructor(code, message, detail) {
|
|
35
|
-
super(message);
|
|
36
|
-
this.name = 'RuntimeEpochStoreError';
|
|
37
|
-
this.code = code;
|
|
38
|
-
this.detail = detail;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function fail(code, message, detail) {
|
|
43
|
-
throw new RuntimeEpochStoreError(code, message, detail);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function schemaGeneration(schema, family) {
|
|
47
|
-
if (typeof schema !== 'string') return null;
|
|
48
|
-
const prefix = `${family}.v`;
|
|
49
|
-
if (!schema.startsWith(prefix)) return null;
|
|
50
|
-
const generationText = schema.slice(prefix.length);
|
|
51
|
-
if (!/^[1-9][0-9]*$/u.test(generationText)) return null;
|
|
52
|
-
const generation = Number.parseInt(generationText, 10);
|
|
53
|
-
return Number.isSafeInteger(generation) ? generation : null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function rejectFutureRuntimeStoreSchema(schema, { artifact, family, expectedVersion }) {
|
|
57
|
-
const observedVersion = schemaGeneration(schema, family);
|
|
58
|
-
if (observedVersion === null || observedVersion <= expectedVersion) return;
|
|
59
|
-
const expectedSchema = `${family}.v${expectedVersion}`;
|
|
60
|
-
fail(
|
|
61
|
-
'UNSUPPORTED_RUNTIME_STORE_VERSION',
|
|
62
|
-
`${artifact}のschema ${schema} はこのLatticeが対応する ${expectedSchema} より新しい`,
|
|
63
|
-
{
|
|
64
|
-
artifact,
|
|
65
|
-
observed_schema: schema,
|
|
66
|
-
expected_schema: expectedSchema,
|
|
67
|
-
observed_version: observedVersion,
|
|
68
|
-
expected_version: expectedVersion,
|
|
69
|
-
upgrade_command: RUNTIME_UPGRADE_COMMAND,
|
|
70
|
-
},
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function rejectFutureArtifact(value, options) {
|
|
75
|
-
rejectFutureRuntimeStoreSchema(value?.schema, options);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function plainRecord(value) {
|
|
79
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
80
|
-
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function exactRecord(value, keys) {
|
|
84
|
-
return plainRecord(value)
|
|
85
|
-
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function selfDigestValid(value, field) {
|
|
89
|
-
if (!plainRecord(value) || !HEX_DIGEST.test(value[field] ?? '')) return false;
|
|
90
|
-
const body = { ...value };
|
|
91
|
-
delete body[field];
|
|
92
|
-
return digestArtifact(body) === value[field];
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
export function validateRuntimeFindingRecord(value) {
|
|
96
|
-
if (!exactRecord(value, ['schema', 'finding_id', 'run_id', 'plan_epoch',
|
|
97
|
-
'source_checkpoint_digest', 'observed_event_digest', 'finding', 'recorded_by', 'finding_digest'])
|
|
98
|
-
|| value.schema !== 'lattice.runtime_finding_record.v1'
|
|
99
|
-
|| !TRANSACTION_ID.test(value.finding_id ?? '') || !TRANSACTION_ID.test(value.run_id ?? '')
|
|
100
|
-
|| !Number.isSafeInteger(value.plan_epoch) || value.plan_epoch < 1
|
|
101
|
-
|| !HEX_DIGEST.test(value.source_checkpoint_digest ?? '')
|
|
102
|
-
|| !HEX_DIGEST.test(value.observed_event_digest ?? '')
|
|
103
|
-
|| !selfDigestValid(value, 'finding_digest')) return false;
|
|
104
|
-
const finding = value.finding;
|
|
105
|
-
if (!exactRecord(finding, ['schema', 'kind', 'todo_ids', 'path', 'resource_id',
|
|
106
|
-
'evidence_digests', 'finding_digest'])
|
|
107
|
-
|| finding.schema !== 'lattice.runtime_conflict_finding.v1'
|
|
108
|
-
|| !RUNTIME_CONFLICT_KINDS.includes(finding.kind)
|
|
109
|
-
|| !Array.isArray(finding.todo_ids) || finding.todo_ids.length < 1 || finding.todo_ids.length > 256
|
|
110
|
-
|| finding.todo_ids.some((todoId) => !TRANSACTION_ID.test(todoId))
|
|
111
|
-
|| new Set(finding.todo_ids).size !== finding.todo_ids.length
|
|
112
|
-
|| finding.todo_ids.some((todoId, index) => index > 0 && finding.todo_ids[index - 1] >= todoId)
|
|
113
|
-
|| !(finding.path === null || (typeof finding.path === 'string' && finding.path.length > 0))
|
|
114
|
-
|| !(finding.resource_id === null || TRANSACTION_ID.test(finding.resource_id))
|
|
115
|
-
|| !Array.isArray(finding.evidence_digests) || finding.evidence_digests.length > 256
|
|
116
|
-
|| finding.evidence_digests.some((entry) => !HEX_DIGEST.test(entry))
|
|
117
|
-
|| new Set(finding.evidence_digests).size !== finding.evidence_digests.length
|
|
118
|
-
|| finding.evidence_digests.some((entry, index) => index > 0 && finding.evidence_digests[index - 1] >= entry)
|
|
119
|
-
|| !selfDigestValid(finding, 'finding_digest')) return false;
|
|
120
|
-
const pathKind = ['observed_write_conflict', 'undeclared_write', 'stale_context'].includes(finding.kind);
|
|
121
|
-
if (pathKind !== (finding.path !== null) || pathKind === (finding.resource_id !== null)) return false;
|
|
122
|
-
const observer = value.recorded_by;
|
|
123
|
-
return exactRecord(observer, ['schema', 'kind', 'controller_registration_digest',
|
|
124
|
-
'executor_handle', 'identity_digest'])
|
|
125
|
-
&& observer.schema === 'lattice.runtime_observer_identity.v1'
|
|
126
|
-
&& ['supervisor', 'controller', 'executor'].includes(observer.kind)
|
|
127
|
-
&& (observer.controller_registration_digest === null
|
|
128
|
-
|| HEX_DIGEST.test(observer.controller_registration_digest))
|
|
129
|
-
&& (observer.executor_handle === null || TRANSACTION_ID.test(observer.executor_handle))
|
|
130
|
-
&& selfDigestValid(observer, 'identity_digest');
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export function validateRuntimeFindingCandidate(value) {
|
|
134
|
-
if (!exactRecord(value, ['schema', 'proposed_kind', 'todo_ids', 'path', 'resource_id',
|
|
135
|
-
'evidence_digests', 'candidate_digest'])
|
|
136
|
-
|| value.schema !== 'lattice.runtime_finding_candidate.v1'
|
|
137
|
-
|| !RUNTIME_CONFLICT_KINDS.includes(value.proposed_kind)
|
|
138
|
-
|| !Array.isArray(value.todo_ids) || value.todo_ids.length < 1 || value.todo_ids.length > 256
|
|
139
|
-
|| value.todo_ids.some((id) => !TRANSACTION_ID.test(id))
|
|
140
|
-
|| value.todo_ids.some((id, index) => index > 0 && value.todo_ids[index - 1] >= id)
|
|
141
|
-
|| !Array.isArray(value.evidence_digests) || value.evidence_digests.length > 256
|
|
142
|
-
|| value.evidence_digests.some((digest) => !HEX_DIGEST.test(digest))
|
|
143
|
-
|| value.evidence_digests.some((digest, index) => index > 0
|
|
144
|
-
&& value.evidence_digests[index - 1] >= digest)
|
|
145
|
-
|| !selfDigestValid(value, 'candidate_digest')) return false;
|
|
146
|
-
const pathKind = ['observed_write_conflict', 'undeclared_write', 'stale_context']
|
|
147
|
-
.includes(value.proposed_kind);
|
|
148
|
-
return pathKind
|
|
149
|
-
? typeof value.path === 'string' && value.path.length > 0 && value.resource_id === null
|
|
150
|
-
: value.path === null && TRANSACTION_ID.test(value.resource_id ?? '');
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** candidate本文を信用せず保存checkpointとactive bundleへ再束縛してfindingを発行する。 */
|
|
154
|
-
export async function recordRuntimeFinding({ runDir, candidate, checkpointDigest,
|
|
155
|
-
observedEventDigest, recordedBy, deriveFinding = null, verifyFinding = null }) {
|
|
156
|
-
if (!validateRuntimeFindingCandidate(candidate) || !HEX_DIGEST.test(checkpointDigest ?? '')
|
|
157
|
-
|| !HEX_DIGEST.test(observedEventDigest ?? '')) fail('FINDING_UNRESOLVED', 'finding candidate入力不正');
|
|
158
|
-
const committed = await readCommittedEpochStore(runDir);
|
|
159
|
-
if (committed === null) fail('RUN_NOT_MANAGED', 'managed epochが存在しない');
|
|
160
|
-
const todoSet = new Set(committed.bundle.plan.nodes.map(({ todo_id: id }) => id));
|
|
161
|
-
if (!candidate.todo_ids.every((id) => todoSet.has(id))) {
|
|
162
|
-
fail('STALE_FINDING', 'candidateがactive epoch外TODOを参照する');
|
|
163
|
-
}
|
|
164
|
-
const events = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
|
|
165
|
-
const observed = events.find((event) => event.event_digest === observedEventDigest
|
|
166
|
-
&& event.plan_epoch === committed.pointer.plan_epoch
|
|
167
|
-
&& event.payload?.checkpoint_digest === checkpointDigest);
|
|
168
|
-
if (observed === undefined) fail('FINDING_UNRESOLVED', 'checkpoint/event bindingを解決できない');
|
|
169
|
-
const proposed = typeof deriveFinding === 'function'
|
|
170
|
-
? await deriveFinding(structuredClone(candidate), {
|
|
171
|
-
checkpoint: structuredClone(observed), bundle: structuredClone(committed.bundle),
|
|
172
|
-
})
|
|
173
|
-
: { schema: 'lattice.runtime_conflict_finding.v1', kind: candidate.proposed_kind,
|
|
174
|
-
todo_ids: [...candidate.todo_ids], path: candidate.path, resource_id: candidate.resource_id,
|
|
175
|
-
evidence_digests: [...candidate.evidence_digests], finding_digest: '' };
|
|
176
|
-
proposed.finding_digest = digestArtifact(Object.fromEntries(Object.entries(proposed)
|
|
177
|
-
.filter(([key]) => key !== 'finding_digest')));
|
|
178
|
-
if (typeof verifyFinding === 'function' && await verifyFinding(structuredClone(proposed), {
|
|
179
|
-
candidate: structuredClone(candidate), checkpoint: structuredClone(observed),
|
|
180
|
-
bundle: structuredClone(committed.bundle),
|
|
181
|
-
}) !== true) fail('FINDING_UNRESOLVED', 'independent finding verifierが不一致');
|
|
182
|
-
const record = { schema: 'lattice.runtime_finding_record.v1',
|
|
183
|
-
finding_id: `finding-${proposed.finding_digest.slice(0, 24)}`, run_id: committed.meta.run_id,
|
|
184
|
-
plan_epoch: committed.pointer.plan_epoch, source_checkpoint_digest: checkpointDigest,
|
|
185
|
-
observed_event_digest: observedEventDigest, finding: proposed,
|
|
186
|
-
recorded_by: structuredClone(recordedBy), finding_digest: '' };
|
|
187
|
-
const recordBody = { ...record }; delete recordBody.finding_digest;
|
|
188
|
-
record.finding_digest = digestArtifact(recordBody);
|
|
189
|
-
if (!validateRuntimeFindingRecord(record)) fail('FINDING_UNRESOLVED', 'derived finding recordが不正');
|
|
190
|
-
const findingsDir = path.join(runDir, 'findings');
|
|
191
|
-
await mkdir(findingsDir, { recursive: true });
|
|
192
|
-
const findingPath = path.join(findingsDir, `${record.finding_digest}.json`);
|
|
193
|
-
try {
|
|
194
|
-
await writeDurableJson(findingPath, record);
|
|
195
|
-
await fsyncDirectory(findingsDir);
|
|
196
|
-
} catch (error) {
|
|
197
|
-
if (error?.code !== 'EEXIST') throw error;
|
|
198
|
-
const existing = await readRegularJson(findingPath, 'runtime finding');
|
|
199
|
-
if (!validateRuntimeFindingRecord(existing)
|
|
200
|
-
|| existing.finding_digest !== record.finding_digest) fail('FINDING_CONFLICT', 'finding digest alias競合');
|
|
201
|
-
}
|
|
202
|
-
return record;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async function readRegularJson(filePath, label) {
|
|
206
|
-
let info;
|
|
207
|
-
try {
|
|
208
|
-
info = await lstat(filePath);
|
|
209
|
-
} catch {
|
|
210
|
-
fail('INVALID_RUN_STORE', `${label}を読めない`);
|
|
211
|
-
}
|
|
212
|
-
if (!info.isFile() || info.isSymbolicLink()) fail('INVALID_RUN_STORE', `${label}がregular fileではない`);
|
|
213
|
-
try {
|
|
214
|
-
return JSON.parse(await readFile(filePath, 'utf8'));
|
|
215
|
-
} catch {
|
|
216
|
-
fail('INVALID_RUN_STORE', `${label}がvalid JSONではない`);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
async function fsyncDirectory(directory) {
|
|
221
|
-
const handle = await open(directory, 'r');
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
await handle.
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
await
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
||
|
|
262
|
-
||
|
|
263
|
-
|| !
|
|
264
|
-
||
|
|
265
|
-
|| compileArtifact.
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
fail('INVALID_RUN_STORE', 'epoch 1
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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
|
-
if (bundle.
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
&& typeof value.
|
|
383
|
-
&&
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
&& typeof meta.
|
|
396
|
-
&&
|
|
397
|
-
&&
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
&& meta.
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
&&
|
|
419
|
-
&&
|
|
420
|
-
&&
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
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
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
await mkdir(
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
await
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
if (
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
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
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
rejectFutureRuntimeStoreSchema(meta.
|
|
526
|
-
{ artifact: '
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
if (
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
if (recompileRequest.
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|| receipt.
|
|
627
|
-
|| receipt.
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
candidate.
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
const
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
await
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
await
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
await
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
if (
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
await
|
|
764
|
-
await fsyncDirectory(epochsDir);
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
||
|
|
793
|
-
|| !barrier.
|
|
794
|
-
|
|
795
|
-
|| !
|
|
796
|
-
|
|
797
|
-
|| !
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
lstat,
|
|
3
|
+
mkdir,
|
|
4
|
+
open,
|
|
5
|
+
readFile,
|
|
6
|
+
rename,
|
|
7
|
+
rm,
|
|
8
|
+
writeFile,
|
|
9
|
+
} from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
|
|
13
|
+
import { buildExecutorPackets } from './runtime-engine.mjs';
|
|
14
|
+
import {
|
|
15
|
+
RUNTIME_CONFLICT_KINDS,
|
|
16
|
+
validateExecutorPacket,
|
|
17
|
+
validateRunRequest,
|
|
18
|
+
validateRuntimeBoundaryManifest,
|
|
19
|
+
validateRuntimePlan,
|
|
20
|
+
verifyRuntimePlanBinding,
|
|
21
|
+
} from './runtime-contracts.mjs';
|
|
22
|
+
import {
|
|
23
|
+
validateRunRequestV2,
|
|
24
|
+
validateRuntimeRecompileRequest,
|
|
25
|
+
validateRuntimeTaskMigration,
|
|
26
|
+
} from './runtime-hold-recompile.mjs';
|
|
27
|
+
|
|
28
|
+
const HEX_DIGEST = /^[0-9a-f]{64}$/u;
|
|
29
|
+
const EPOCH_DIRECTORY = /^\d{8}$/u;
|
|
30
|
+
const TRANSACTION_ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
|
|
31
|
+
const RUNTIME_UPGRADE_COMMAND = 'npm install -g @quolu/lattice@latest --prefer-online';
|
|
32
|
+
|
|
33
|
+
export class RuntimeEpochStoreError extends Error {
|
|
34
|
+
constructor(code, message, detail) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'RuntimeEpochStoreError';
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.detail = detail;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function fail(code, message, detail) {
|
|
43
|
+
throw new RuntimeEpochStoreError(code, message, detail);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function schemaGeneration(schema, family) {
|
|
47
|
+
if (typeof schema !== 'string') return null;
|
|
48
|
+
const prefix = `${family}.v`;
|
|
49
|
+
if (!schema.startsWith(prefix)) return null;
|
|
50
|
+
const generationText = schema.slice(prefix.length);
|
|
51
|
+
if (!/^[1-9][0-9]*$/u.test(generationText)) return null;
|
|
52
|
+
const generation = Number.parseInt(generationText, 10);
|
|
53
|
+
return Number.isSafeInteger(generation) ? generation : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function rejectFutureRuntimeStoreSchema(schema, { artifact, family, expectedVersion }) {
|
|
57
|
+
const observedVersion = schemaGeneration(schema, family);
|
|
58
|
+
if (observedVersion === null || observedVersion <= expectedVersion) return;
|
|
59
|
+
const expectedSchema = `${family}.v${expectedVersion}`;
|
|
60
|
+
fail(
|
|
61
|
+
'UNSUPPORTED_RUNTIME_STORE_VERSION',
|
|
62
|
+
`${artifact}のschema ${schema} はこのLatticeが対応する ${expectedSchema} より新しい`,
|
|
63
|
+
{
|
|
64
|
+
artifact,
|
|
65
|
+
observed_schema: schema,
|
|
66
|
+
expected_schema: expectedSchema,
|
|
67
|
+
observed_version: observedVersion,
|
|
68
|
+
expected_version: expectedVersion,
|
|
69
|
+
upgrade_command: RUNTIME_UPGRADE_COMMAND,
|
|
70
|
+
},
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function rejectFutureArtifact(value, options) {
|
|
75
|
+
rejectFutureRuntimeStoreSchema(value?.schema, options);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function plainRecord(value) {
|
|
79
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
80
|
+
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function exactRecord(value, keys) {
|
|
84
|
+
return plainRecord(value)
|
|
85
|
+
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function selfDigestValid(value, field) {
|
|
89
|
+
if (!plainRecord(value) || !HEX_DIGEST.test(value[field] ?? '')) return false;
|
|
90
|
+
const body = { ...value };
|
|
91
|
+
delete body[field];
|
|
92
|
+
return digestArtifact(body) === value[field];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function validateRuntimeFindingRecord(value) {
|
|
96
|
+
if (!exactRecord(value, ['schema', 'finding_id', 'run_id', 'plan_epoch',
|
|
97
|
+
'source_checkpoint_digest', 'observed_event_digest', 'finding', 'recorded_by', 'finding_digest'])
|
|
98
|
+
|| value.schema !== 'lattice.runtime_finding_record.v1'
|
|
99
|
+
|| !TRANSACTION_ID.test(value.finding_id ?? '') || !TRANSACTION_ID.test(value.run_id ?? '')
|
|
100
|
+
|| !Number.isSafeInteger(value.plan_epoch) || value.plan_epoch < 1
|
|
101
|
+
|| !HEX_DIGEST.test(value.source_checkpoint_digest ?? '')
|
|
102
|
+
|| !HEX_DIGEST.test(value.observed_event_digest ?? '')
|
|
103
|
+
|| !selfDigestValid(value, 'finding_digest')) return false;
|
|
104
|
+
const finding = value.finding;
|
|
105
|
+
if (!exactRecord(finding, ['schema', 'kind', 'todo_ids', 'path', 'resource_id',
|
|
106
|
+
'evidence_digests', 'finding_digest'])
|
|
107
|
+
|| finding.schema !== 'lattice.runtime_conflict_finding.v1'
|
|
108
|
+
|| !RUNTIME_CONFLICT_KINDS.includes(finding.kind)
|
|
109
|
+
|| !Array.isArray(finding.todo_ids) || finding.todo_ids.length < 1 || finding.todo_ids.length > 256
|
|
110
|
+
|| finding.todo_ids.some((todoId) => !TRANSACTION_ID.test(todoId))
|
|
111
|
+
|| new Set(finding.todo_ids).size !== finding.todo_ids.length
|
|
112
|
+
|| finding.todo_ids.some((todoId, index) => index > 0 && finding.todo_ids[index - 1] >= todoId)
|
|
113
|
+
|| !(finding.path === null || (typeof finding.path === 'string' && finding.path.length > 0))
|
|
114
|
+
|| !(finding.resource_id === null || TRANSACTION_ID.test(finding.resource_id))
|
|
115
|
+
|| !Array.isArray(finding.evidence_digests) || finding.evidence_digests.length > 256
|
|
116
|
+
|| finding.evidence_digests.some((entry) => !HEX_DIGEST.test(entry))
|
|
117
|
+
|| new Set(finding.evidence_digests).size !== finding.evidence_digests.length
|
|
118
|
+
|| finding.evidence_digests.some((entry, index) => index > 0 && finding.evidence_digests[index - 1] >= entry)
|
|
119
|
+
|| !selfDigestValid(finding, 'finding_digest')) return false;
|
|
120
|
+
const pathKind = ['observed_write_conflict', 'undeclared_write', 'stale_context'].includes(finding.kind);
|
|
121
|
+
if (pathKind !== (finding.path !== null) || pathKind === (finding.resource_id !== null)) return false;
|
|
122
|
+
const observer = value.recorded_by;
|
|
123
|
+
return exactRecord(observer, ['schema', 'kind', 'controller_registration_digest',
|
|
124
|
+
'executor_handle', 'identity_digest'])
|
|
125
|
+
&& observer.schema === 'lattice.runtime_observer_identity.v1'
|
|
126
|
+
&& ['supervisor', 'controller', 'executor'].includes(observer.kind)
|
|
127
|
+
&& (observer.controller_registration_digest === null
|
|
128
|
+
|| HEX_DIGEST.test(observer.controller_registration_digest))
|
|
129
|
+
&& (observer.executor_handle === null || TRANSACTION_ID.test(observer.executor_handle))
|
|
130
|
+
&& selfDigestValid(observer, 'identity_digest');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function validateRuntimeFindingCandidate(value) {
|
|
134
|
+
if (!exactRecord(value, ['schema', 'proposed_kind', 'todo_ids', 'path', 'resource_id',
|
|
135
|
+
'evidence_digests', 'candidate_digest'])
|
|
136
|
+
|| value.schema !== 'lattice.runtime_finding_candidate.v1'
|
|
137
|
+
|| !RUNTIME_CONFLICT_KINDS.includes(value.proposed_kind)
|
|
138
|
+
|| !Array.isArray(value.todo_ids) || value.todo_ids.length < 1 || value.todo_ids.length > 256
|
|
139
|
+
|| value.todo_ids.some((id) => !TRANSACTION_ID.test(id))
|
|
140
|
+
|| value.todo_ids.some((id, index) => index > 0 && value.todo_ids[index - 1] >= id)
|
|
141
|
+
|| !Array.isArray(value.evidence_digests) || value.evidence_digests.length > 256
|
|
142
|
+
|| value.evidence_digests.some((digest) => !HEX_DIGEST.test(digest))
|
|
143
|
+
|| value.evidence_digests.some((digest, index) => index > 0
|
|
144
|
+
&& value.evidence_digests[index - 1] >= digest)
|
|
145
|
+
|| !selfDigestValid(value, 'candidate_digest')) return false;
|
|
146
|
+
const pathKind = ['observed_write_conflict', 'undeclared_write', 'stale_context']
|
|
147
|
+
.includes(value.proposed_kind);
|
|
148
|
+
return pathKind
|
|
149
|
+
? typeof value.path === 'string' && value.path.length > 0 && value.resource_id === null
|
|
150
|
+
: value.path === null && TRANSACTION_ID.test(value.resource_id ?? '');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** candidate本文を信用せず保存checkpointとactive bundleへ再束縛してfindingを発行する。 */
|
|
154
|
+
export async function recordRuntimeFinding({ runDir, candidate, checkpointDigest,
|
|
155
|
+
observedEventDigest, recordedBy, deriveFinding = null, verifyFinding = null }) {
|
|
156
|
+
if (!validateRuntimeFindingCandidate(candidate) || !HEX_DIGEST.test(checkpointDigest ?? '')
|
|
157
|
+
|| !HEX_DIGEST.test(observedEventDigest ?? '')) fail('FINDING_UNRESOLVED', 'finding candidate入力不正');
|
|
158
|
+
const committed = await readCommittedEpochStore(runDir);
|
|
159
|
+
if (committed === null) fail('RUN_NOT_MANAGED', 'managed epochが存在しない');
|
|
160
|
+
const todoSet = new Set(committed.bundle.plan.nodes.map(({ todo_id: id }) => id));
|
|
161
|
+
if (!candidate.todo_ids.every((id) => todoSet.has(id))) {
|
|
162
|
+
fail('STALE_FINDING', 'candidateがactive epoch外TODOを参照する');
|
|
163
|
+
}
|
|
164
|
+
const events = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
|
|
165
|
+
const observed = events.find((event) => event.event_digest === observedEventDigest
|
|
166
|
+
&& event.plan_epoch === committed.pointer.plan_epoch
|
|
167
|
+
&& event.payload?.checkpoint_digest === checkpointDigest);
|
|
168
|
+
if (observed === undefined) fail('FINDING_UNRESOLVED', 'checkpoint/event bindingを解決できない');
|
|
169
|
+
const proposed = typeof deriveFinding === 'function'
|
|
170
|
+
? await deriveFinding(structuredClone(candidate), {
|
|
171
|
+
checkpoint: structuredClone(observed), bundle: structuredClone(committed.bundle),
|
|
172
|
+
})
|
|
173
|
+
: { schema: 'lattice.runtime_conflict_finding.v1', kind: candidate.proposed_kind,
|
|
174
|
+
todo_ids: [...candidate.todo_ids], path: candidate.path, resource_id: candidate.resource_id,
|
|
175
|
+
evidence_digests: [...candidate.evidence_digests], finding_digest: '' };
|
|
176
|
+
proposed.finding_digest = digestArtifact(Object.fromEntries(Object.entries(proposed)
|
|
177
|
+
.filter(([key]) => key !== 'finding_digest')));
|
|
178
|
+
if (typeof verifyFinding === 'function' && await verifyFinding(structuredClone(proposed), {
|
|
179
|
+
candidate: structuredClone(candidate), checkpoint: structuredClone(observed),
|
|
180
|
+
bundle: structuredClone(committed.bundle),
|
|
181
|
+
}) !== true) fail('FINDING_UNRESOLVED', 'independent finding verifierが不一致');
|
|
182
|
+
const record = { schema: 'lattice.runtime_finding_record.v1',
|
|
183
|
+
finding_id: `finding-${proposed.finding_digest.slice(0, 24)}`, run_id: committed.meta.run_id,
|
|
184
|
+
plan_epoch: committed.pointer.plan_epoch, source_checkpoint_digest: checkpointDigest,
|
|
185
|
+
observed_event_digest: observedEventDigest, finding: proposed,
|
|
186
|
+
recorded_by: structuredClone(recordedBy), finding_digest: '' };
|
|
187
|
+
const recordBody = { ...record }; delete recordBody.finding_digest;
|
|
188
|
+
record.finding_digest = digestArtifact(recordBody);
|
|
189
|
+
if (!validateRuntimeFindingRecord(record)) fail('FINDING_UNRESOLVED', 'derived finding recordが不正');
|
|
190
|
+
const findingsDir = path.join(runDir, 'findings');
|
|
191
|
+
await mkdir(findingsDir, { recursive: true });
|
|
192
|
+
const findingPath = path.join(findingsDir, `${record.finding_digest}.json`);
|
|
193
|
+
try {
|
|
194
|
+
await writeDurableJson(findingPath, record);
|
|
195
|
+
await fsyncDirectory(findingsDir);
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
198
|
+
const existing = await readRegularJson(findingPath, 'runtime finding');
|
|
199
|
+
if (!validateRuntimeFindingRecord(existing)
|
|
200
|
+
|| existing.finding_digest !== record.finding_digest) fail('FINDING_CONFLICT', 'finding digest alias競合');
|
|
201
|
+
}
|
|
202
|
+
return record;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function readRegularJson(filePath, label) {
|
|
206
|
+
let info;
|
|
207
|
+
try {
|
|
208
|
+
info = await lstat(filePath);
|
|
209
|
+
} catch {
|
|
210
|
+
fail('INVALID_RUN_STORE', `${label}を読めない`);
|
|
211
|
+
}
|
|
212
|
+
if (!info.isFile() || info.isSymbolicLink()) fail('INVALID_RUN_STORE', `${label}がregular fileではない`);
|
|
213
|
+
try {
|
|
214
|
+
return JSON.parse(await readFile(filePath, 'utf8'));
|
|
215
|
+
} catch {
|
|
216
|
+
fail('INVALID_RUN_STORE', `${label}がvalid JSONではない`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function fsyncDirectory(directory) {
|
|
221
|
+
const handle = await open(directory, 'r');
|
|
222
|
+
// Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
|
|
223
|
+
// win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
|
|
224
|
+
try {
|
|
225
|
+
await handle.sync();
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
|
|
228
|
+
} finally {
|
|
229
|
+
await handle.close();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function writeDurableJson(filePath, value, { exclusive = true } = {}) {
|
|
234
|
+
const bytes = `${JSON.stringify(value, null, 1)}\n`;
|
|
235
|
+
const handle = await open(filePath, exclusive ? 'wx' : 'w', 0o600);
|
|
236
|
+
try {
|
|
237
|
+
await handle.writeFile(bytes);
|
|
238
|
+
await handle.sync();
|
|
239
|
+
} finally {
|
|
240
|
+
await handle.close();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function replaceDurableJson(directory, name, value) {
|
|
245
|
+
const temporary = path.join(directory, `.${name}-${process.pid}-${Date.now()}.tmp`);
|
|
246
|
+
try {
|
|
247
|
+
await writeDurableJson(temporary, value);
|
|
248
|
+
await rename(temporary, path.join(directory, name));
|
|
249
|
+
await fsyncDirectory(directory);
|
|
250
|
+
} finally {
|
|
251
|
+
await rm(temporary, { force: true }).catch(() => {});
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function validateLegacyInputs({ request, compileArtifact, legacyMeta }) {
|
|
256
|
+
const compileKeys = ['schema', 'request_digest', 'plan', 'manifests', 'schedule', 'graph_digest', 'result_digest'];
|
|
257
|
+
const metaKeys = ['schema', 'run_id', 'executor_adapter', 'plan_digest'];
|
|
258
|
+
const compileBody = { ...compileArtifact };
|
|
259
|
+
delete compileBody.result_digest;
|
|
260
|
+
if (!validateRunRequest(request)
|
|
261
|
+
|| !exactRecord(legacyMeta, metaKeys) || legacyMeta.schema !== 'lattice.run_meta.v1'
|
|
262
|
+
|| legacyMeta.run_id !== request.request_id
|
|
263
|
+
|| !exactRecord(compileArtifact, compileKeys)
|
|
264
|
+
|| compileArtifact.schema !== 'lattice.plan_compile_result.v1'
|
|
265
|
+
|| compileArtifact.result_digest !== digestArtifact(compileBody)
|
|
266
|
+
|| compileArtifact.request_digest !== request.request_digest
|
|
267
|
+
|| !validateRuntimePlan(compileArtifact.plan)
|
|
268
|
+
|| !verifyRuntimePlanBinding({ plan: compileArtifact.plan, request })
|
|
269
|
+
|| compileArtifact.plan.plan_digest !== legacyMeta.plan_digest) {
|
|
270
|
+
fail('INVALID_RUN_STORE', 'legacy epoch 1 artifact bindingが不正');
|
|
271
|
+
}
|
|
272
|
+
const todoIds = compileArtifact.plan.nodes.map(({ todo_id: todoId }) => todoId).sort();
|
|
273
|
+
if (Object.keys(compileArtifact.manifests ?? {}).sort().join('\0') !== todoIds.join('\0')) {
|
|
274
|
+
fail('INVALID_RUN_STORE', 'epoch 1 manifest key集合がplanと一致しない');
|
|
275
|
+
}
|
|
276
|
+
for (const todoId of todoIds) {
|
|
277
|
+
const manifest = compileArtifact.manifests[todoId];
|
|
278
|
+
if (!validateRuntimeBoundaryManifest(manifest)
|
|
279
|
+
|| manifest.manifest_digest !== compileArtifact.plan.manifest_digests[todoId]) {
|
|
280
|
+
fail('INVALID_RUN_STORE', `epoch 1 manifest bindingが不正: ${todoId}`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function normalizeActivationMeta(meta, request, compileArtifact) {
|
|
286
|
+
rejectFutureArtifact(meta, { artifact: 'run_meta', family: 'lattice.run_meta', expectedVersion: 2 });
|
|
287
|
+
if (meta?.schema === 'lattice.run_meta.v1') return meta;
|
|
288
|
+
if (exactRecord(meta, [
|
|
289
|
+
'schema', 'run_id', 'executor_adapter', 'run_event_schema', 'control_event_schema',
|
|
290
|
+
'epoch_bundle_schema', 'created_plan_digest', 'meta_digest',
|
|
291
|
+
]) && meta.schema === 'lattice.run_meta.v2'
|
|
292
|
+
&& meta.run_id === request.request_id
|
|
293
|
+
&& meta.created_plan_digest === compileArtifact.plan.plan_digest
|
|
294
|
+
&& selfDigestValid(meta, 'meta_digest')) {
|
|
295
|
+
return {
|
|
296
|
+
schema: 'lattice.run_meta.v1',
|
|
297
|
+
run_id: meta.run_id,
|
|
298
|
+
executor_adapter: meta.executor_adapter,
|
|
299
|
+
plan_digest: meta.created_plan_digest,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
fail('INVALID_RUN_STORE', 'activation対象run metaがv1/同一runのv2ではない');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function buildEpochOneBundle({ request, compileArtifact, legacyMeta }) {
|
|
306
|
+
validateLegacyInputs({ request, compileArtifact, legacyMeta });
|
|
307
|
+
const bundle = {
|
|
308
|
+
schema: 'lattice.runtime_epoch_bundle.v1',
|
|
309
|
+
run_id: legacyMeta.run_id,
|
|
310
|
+
plan_epoch: 1,
|
|
311
|
+
request,
|
|
312
|
+
plan: compileArtifact.plan,
|
|
313
|
+
manifests: compileArtifact.manifests,
|
|
314
|
+
executor_packets: buildExecutorPackets({
|
|
315
|
+
plan: compileArtifact.plan,
|
|
316
|
+
manifests: compileArtifact.manifests,
|
|
317
|
+
}),
|
|
318
|
+
rebind_packets: null,
|
|
319
|
+
plan_diff: null,
|
|
320
|
+
task_migration: null,
|
|
321
|
+
treatment: null,
|
|
322
|
+
phase_revision_digest: null,
|
|
323
|
+
phase_revision_commit_receipt: null,
|
|
324
|
+
predecessor_bundle_digest: null,
|
|
325
|
+
};
|
|
326
|
+
bundle.bundle_digest = digestArtifact(bundle);
|
|
327
|
+
return bundle;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function validateRuntimeEpochBundle(bundle) {
|
|
331
|
+
if (!exactRecord(bundle, [
|
|
332
|
+
'schema', 'run_id', 'plan_epoch', 'request', 'plan', 'manifests', 'executor_packets',
|
|
333
|
+
'rebind_packets', 'plan_diff', 'task_migration', 'treatment', 'phase_revision_digest',
|
|
334
|
+
'phase_revision_commit_receipt', 'predecessor_bundle_digest', 'bundle_digest',
|
|
335
|
+
]) || bundle.schema !== 'lattice.runtime_epoch_bundle.v1'
|
|
336
|
+
|| !Number.isInteger(bundle.plan_epoch) || bundle.plan_epoch < 1
|
|
337
|
+
|| bundle.plan_epoch !== bundle.plan?.plan_epoch
|
|
338
|
+
|| bundle.run_id !== bundle.request?.request_id
|
|
339
|
+
|| !(bundle.plan_epoch === 1 ? validateRunRequest(bundle.request) : validateRunRequestV2(bundle.request))
|
|
340
|
+
|| !validateRuntimePlan(bundle.plan)
|
|
341
|
+
|| !(bundle.plan_epoch === 1
|
|
342
|
+
? verifyRuntimePlanBinding({ plan: bundle.plan, request: bundle.request })
|
|
343
|
+
: bundle.plan.request_digest === bundle.request.request_digest
|
|
344
|
+
&& bundle.plan.base_sha === bundle.request.repo.base_sha)
|
|
345
|
+
|| !selfDigestValid(bundle, 'bundle_digest')) return false;
|
|
346
|
+
const todoIds = bundle.plan.nodes.map(({ todo_id: todoId }) => todoId).sort();
|
|
347
|
+
if (Object.keys(bundle.manifests ?? {}).sort().join('\0') !== todoIds.join('\0')
|
|
348
|
+
|| Object.keys(bundle.executor_packets ?? {}).sort().join('\0') !== todoIds.join('\0')) return false;
|
|
349
|
+
for (const todoId of todoIds) {
|
|
350
|
+
const manifest = bundle.manifests[todoId];
|
|
351
|
+
const packet = bundle.executor_packets[todoId];
|
|
352
|
+
if (!validateRuntimeBoundaryManifest(manifest)
|
|
353
|
+
|| manifest.manifest_digest !== bundle.plan.manifest_digests[todoId]
|
|
354
|
+
|| !validateExecutorPacket(packet)
|
|
355
|
+
|| packet.todo_id !== todoId
|
|
356
|
+
|| packet.plan_ref !== bundle.plan.plan_ref
|
|
357
|
+
|| packet.plan_epoch !== bundle.plan_epoch) return false;
|
|
358
|
+
}
|
|
359
|
+
if (bundle.plan_epoch === 1) {
|
|
360
|
+
return ['rebind_packets', 'plan_diff', 'task_migration', 'treatment',
|
|
361
|
+
'phase_revision_digest', 'phase_revision_commit_receipt', 'predecessor_bundle_digest']
|
|
362
|
+
.every((key) => bundle[key] === null);
|
|
363
|
+
}
|
|
364
|
+
if (!HEX_DIGEST.test(bundle.predecessor_bundle_digest ?? '')
|
|
365
|
+
|| !validateRuntimeTaskMigration(bundle.task_migration)
|
|
366
|
+
|| !plainRecord(bundle.rebind_packets) || !plainRecord(bundle.plan_diff)
|
|
367
|
+
|| !plainRecord(bundle.treatment)) return false;
|
|
368
|
+
if (bundle.phase_revision_digest === null) {
|
|
369
|
+
return bundle.phase_revision_commit_receipt === null;
|
|
370
|
+
}
|
|
371
|
+
return HEX_DIGEST.test(bundle.phase_revision_digest)
|
|
372
|
+
&& validatePhaseRevisionCommitReceipt(bundle.phase_revision_commit_receipt)
|
|
373
|
+
&& bundle.phase_revision_commit_receipt.revision_digest === bundle.phase_revision_digest;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function validatePhaseRevisionCommitReceipt(value) {
|
|
377
|
+
return exactRecord(value, ['schema', 'project_id', 'plan_key', 'plan_version',
|
|
378
|
+
'revision_digest', 'committed_member_digest', 'active_plan_digest', 'journal_genesis_digest',
|
|
379
|
+
'reconciliation_digest', 'source_cutover_receipt_digest', 'committed_at', 'receipt_digest'])
|
|
380
|
+
&& value.schema === 'lattice.phase_revision_commit_receipt.v1'
|
|
381
|
+
&& TRANSACTION_ID.test(value.project_id ?? '') && TRANSACTION_ID.test(value.plan_key ?? '')
|
|
382
|
+
&& typeof value.plan_version === 'string' && value.plan_version.length > 0
|
|
383
|
+
&& [value.revision_digest, value.committed_member_digest, value.active_plan_digest,
|
|
384
|
+
value.journal_genesis_digest, value.reconciliation_digest,
|
|
385
|
+
value.source_cutover_receipt_digest].every((digest) => HEX_DIGEST.test(digest ?? ''))
|
|
386
|
+
&& typeof value.committed_at === 'string' && !Number.isNaN(Date.parse(value.committed_at))
|
|
387
|
+
&& selfDigestValid(value, 'receipt_digest');
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function validateRunMetaV2Envelope(meta) {
|
|
391
|
+
return exactRecord(meta, [
|
|
392
|
+
'schema', 'run_id', 'executor_adapter', 'run_event_schema', 'control_event_schema',
|
|
393
|
+
'epoch_bundle_schema', 'created_plan_digest', 'meta_digest',
|
|
394
|
+
]) && meta.schema === 'lattice.run_meta.v2'
|
|
395
|
+
&& typeof meta.run_id === 'string'
|
|
396
|
+
&& typeof meta.executor_adapter === 'string'
|
|
397
|
+
&& typeof meta.run_event_schema === 'string'
|
|
398
|
+
&& typeof meta.control_event_schema === 'string'
|
|
399
|
+
&& typeof meta.epoch_bundle_schema === 'string'
|
|
400
|
+
&& HEX_DIGEST.test(meta.created_plan_digest ?? '')
|
|
401
|
+
&& selfDigestValid(meta, 'meta_digest');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function validateRunMetaV2(meta, createdBundle) {
|
|
405
|
+
return validateRunMetaV2Envelope(meta)
|
|
406
|
+
&& meta.run_id === createdBundle.run_id
|
|
407
|
+
&& meta.run_event_schema === 'lattice.run_event.v1'
|
|
408
|
+
&& meta.control_event_schema === 'lattice.runtime_control_event.v1'
|
|
409
|
+
&& meta.epoch_bundle_schema === 'lattice.runtime_epoch_bundle.v1'
|
|
410
|
+
&& meta.created_plan_digest === createdBundle.plan.plan_digest;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function validateCommittedPointerEnvelope(pointer) {
|
|
414
|
+
return exactRecord(pointer, [
|
|
415
|
+
'schema', 'run_id', 'plan_epoch', 'plan_ref', 'bundle_digest',
|
|
416
|
+
'activation_run_event_digest', 'activation_control_event_digest', 'pointer_digest',
|
|
417
|
+
]) && pointer.schema === 'lattice.committed_epoch_pointer.v1'
|
|
418
|
+
&& typeof pointer.run_id === 'string'
|
|
419
|
+
&& Number.isSafeInteger(pointer.plan_epoch) && pointer.plan_epoch >= 1
|
|
420
|
+
&& typeof pointer.plan_ref === 'string'
|
|
421
|
+
&& HEX_DIGEST.test(pointer.bundle_digest ?? '')
|
|
422
|
+
&& HEX_DIGEST.test(pointer.activation_run_event_digest ?? '')
|
|
423
|
+
&& HEX_DIGEST.test(pointer.activation_control_event_digest ?? '')
|
|
424
|
+
&& selfDigestValid(pointer, 'pointer_digest');
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function validateCommittedPointer(pointer, bundle) {
|
|
428
|
+
return validateCommittedPointerEnvelope(pointer)
|
|
429
|
+
&& pointer.run_id === bundle.run_id
|
|
430
|
+
&& pointer.plan_epoch === bundle.plan_epoch
|
|
431
|
+
&& pointer.plan_ref === bundle.plan.plan_ref
|
|
432
|
+
&& pointer.bundle_digest === bundle.bundle_digest;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** v1 aliasをbyte不変のままepoch 1へ昇格し、pointerを最後にcommitする。 */
|
|
436
|
+
export async function activateEpochOneStore({
|
|
437
|
+
runDir, request, compileArtifact, legacyMeta, activationRunEventDigest, activationControlEventDigest,
|
|
438
|
+
}) {
|
|
439
|
+
if (!HEX_DIGEST.test(activationRunEventDigest ?? '')
|
|
440
|
+
|| !HEX_DIGEST.test(activationControlEventDigest ?? '')) {
|
|
441
|
+
fail('INVALID_RUN_STORE', 'activation event digestが不正');
|
|
442
|
+
}
|
|
443
|
+
const runEvents = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
|
|
444
|
+
const controlEvents = await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
|
|
445
|
+
const controlHead = controlEvents.at?.(-1);
|
|
446
|
+
if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
|
|
447
|
+
|| !Array.isArray(controlEvents)
|
|
448
|
+
|| controlHead?.event_digest !== activationControlEventDigest
|
|
449
|
+
|| controlHead?.kind !== 'supervisor_activated'
|
|
450
|
+
|| !selfDigestValid(controlHead, 'event_digest')) {
|
|
451
|
+
fail('INVALID_RUN_STORE', 'activation pointerがdurable event headへbindしない');
|
|
452
|
+
}
|
|
453
|
+
const normalizedMeta = normalizeActivationMeta(legacyMeta, request, compileArtifact);
|
|
454
|
+
const bundle = buildEpochOneBundle({ request, compileArtifact, legacyMeta: normalizedMeta });
|
|
455
|
+
const epochsDir = path.join(runDir, 'epochs');
|
|
456
|
+
const epochDir = path.join(epochsDir, '00000001');
|
|
457
|
+
const stagingDir = path.join(runDir, `.epoch-1-${process.pid}-${Date.now()}.tmp`);
|
|
458
|
+
await mkdir(epochsDir, { recursive: true });
|
|
459
|
+
await mkdir(path.join(runDir, 'staging'), { recursive: true });
|
|
460
|
+
await mkdir(path.join(runDir, 'findings'), { recursive: true });
|
|
461
|
+
await mkdir(path.join(runDir, 'controllers'), { recursive: true });
|
|
462
|
+
await mkdir(path.join(runDir, 'leases'), { recursive: true });
|
|
463
|
+
for (const directory of [epochsDir, path.join(runDir, 'staging'), path.join(runDir, 'findings'),
|
|
464
|
+
path.join(runDir, 'controllers'), path.join(runDir, 'leases')]) await fsyncDirectory(directory);
|
|
465
|
+
await fsyncDirectory(runDir);
|
|
466
|
+
|
|
467
|
+
try {
|
|
468
|
+
const existing = await readRegularJson(path.join(epochDir, 'epoch-bundle.json'), 'epoch 1 bundle');
|
|
469
|
+
if (!validateRuntimeEpochBundle(existing) || existing.bundle_digest !== bundle.bundle_digest) {
|
|
470
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'epoch 1へ異なるbundleが存在する');
|
|
471
|
+
}
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (error instanceof RuntimeEpochStoreError && error.message.endsWith('を読めない')) {
|
|
474
|
+
await mkdir(stagingDir);
|
|
475
|
+
await writeDurableJson(path.join(stagingDir, 'epoch-bundle.json'), bundle);
|
|
476
|
+
await fsyncDirectory(stagingDir);
|
|
477
|
+
try {
|
|
478
|
+
await rename(stagingDir, epochDir);
|
|
479
|
+
await fsyncDirectory(epochsDir);
|
|
480
|
+
} catch (renameError) {
|
|
481
|
+
await rm(stagingDir, { recursive: true, force: true });
|
|
482
|
+
if (renameError?.code !== 'EEXIST' && renameError?.code !== 'ENOTEMPTY') throw renameError;
|
|
483
|
+
const raced = await readRegularJson(path.join(epochDir, 'epoch-bundle.json'), 'epoch 1 bundle');
|
|
484
|
+
if (!validateRuntimeEpochBundle(raced) || raced.bundle_digest !== bundle.bundle_digest) {
|
|
485
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'epoch 1 concurrent commitが異なる');
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
} else {
|
|
489
|
+
throw error;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const meta = {
|
|
494
|
+
schema: 'lattice.run_meta.v2',
|
|
495
|
+
run_id: normalizedMeta.run_id,
|
|
496
|
+
executor_adapter: normalizedMeta.executor_adapter,
|
|
497
|
+
run_event_schema: 'lattice.run_event.v1',
|
|
498
|
+
control_event_schema: 'lattice.runtime_control_event.v1',
|
|
499
|
+
epoch_bundle_schema: 'lattice.runtime_epoch_bundle.v1',
|
|
500
|
+
created_plan_digest: compileArtifact.plan.plan_digest,
|
|
501
|
+
};
|
|
502
|
+
meta.meta_digest = digestArtifact(meta);
|
|
503
|
+
await replaceDurableJson(runDir, 'run-meta.json', meta);
|
|
504
|
+
|
|
505
|
+
const pointer = {
|
|
506
|
+
schema: 'lattice.committed_epoch_pointer.v1',
|
|
507
|
+
run_id: normalizedMeta.run_id,
|
|
508
|
+
plan_epoch: 1,
|
|
509
|
+
plan_ref: compileArtifact.plan.plan_ref,
|
|
510
|
+
bundle_digest: bundle.bundle_digest,
|
|
511
|
+
activation_run_event_digest: activationRunEventDigest,
|
|
512
|
+
activation_control_event_digest: activationControlEventDigest,
|
|
513
|
+
};
|
|
514
|
+
pointer.pointer_digest = digestArtifact(pointer);
|
|
515
|
+
await replaceDurableJson(runDir, 'committed-epoch.json', pointer);
|
|
516
|
+
return { bundle, meta, pointer };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** pointerを正本としてactive bundleだけを読む。directory最大値へfallbackしない。 */
|
|
520
|
+
export async function readCommittedEpochStore(runDir) {
|
|
521
|
+
const meta = await readRegularJson(path.join(runDir, 'run-meta.json'), 'run meta');
|
|
522
|
+
rejectFutureArtifact(meta, { artifact: 'run_meta', family: 'lattice.run_meta', expectedVersion: 2 });
|
|
523
|
+
if (meta?.schema !== 'lattice.run_meta.v2') return null;
|
|
524
|
+
if (!validateRunMetaV2Envelope(meta)) fail('INVALID_RUN_STORE', 'run meta envelopeが不正');
|
|
525
|
+
rejectFutureRuntimeStoreSchema(meta.run_event_schema,
|
|
526
|
+
{ artifact: 'run_event', family: 'lattice.run_event', expectedVersion: 1 });
|
|
527
|
+
rejectFutureRuntimeStoreSchema(meta.control_event_schema,
|
|
528
|
+
{ artifact: 'runtime_control_event', family: 'lattice.runtime_control_event', expectedVersion: 1 });
|
|
529
|
+
rejectFutureRuntimeStoreSchema(meta.epoch_bundle_schema,
|
|
530
|
+
{ artifact: 'runtime_epoch_bundle', family: 'lattice.runtime_epoch_bundle', expectedVersion: 1 });
|
|
531
|
+
if (meta.run_event_schema !== 'lattice.run_event.v1'
|
|
532
|
+
|| meta.control_event_schema !== 'lattice.runtime_control_event.v1'
|
|
533
|
+
|| meta.epoch_bundle_schema !== 'lattice.runtime_epoch_bundle.v1') {
|
|
534
|
+
fail('INVALID_RUN_STORE', 'run meta schema bindingが不正');
|
|
535
|
+
}
|
|
536
|
+
const pointer = await readRegularJson(path.join(runDir, 'committed-epoch.json'), 'committed epoch pointer');
|
|
537
|
+
rejectFutureArtifact(pointer, {
|
|
538
|
+
artifact: 'committed_epoch_pointer', family: 'lattice.committed_epoch_pointer', expectedVersion: 1,
|
|
539
|
+
});
|
|
540
|
+
if (!validateCommittedPointerEnvelope(pointer)) fail('INVALID_RUN_STORE', 'committed epoch pointer envelopeが不正');
|
|
541
|
+
const epochName = String(pointer.plan_epoch).padStart(8, '0');
|
|
542
|
+
if (!EPOCH_DIRECTORY.test(epochName)) fail('INVALID_RUN_STORE', 'epoch directory名が不正');
|
|
543
|
+
const bundle = await readRegularJson(path.join(runDir, 'epochs', epochName, 'epoch-bundle.json'), 'epoch bundle');
|
|
544
|
+
rejectFutureArtifact(bundle,
|
|
545
|
+
{ artifact: 'runtime_epoch_bundle', family: 'lattice.runtime_epoch_bundle', expectedVersion: 1 });
|
|
546
|
+
const createdBundle = pointer.plan_epoch === 1
|
|
547
|
+
? bundle
|
|
548
|
+
: await readRegularJson(path.join(runDir, 'epochs', '00000001', 'epoch-bundle.json'), 'created epoch bundle');
|
|
549
|
+
rejectFutureArtifact(createdBundle,
|
|
550
|
+
{ artifact: 'runtime_epoch_bundle', family: 'lattice.runtime_epoch_bundle', expectedVersion: 1 });
|
|
551
|
+
if (!validateRuntimeEpochBundle(bundle)
|
|
552
|
+
|| !validateRuntimeEpochBundle(createdBundle)
|
|
553
|
+
|| createdBundle.plan_epoch !== 1
|
|
554
|
+
|| !validateRunMetaV2(meta, createdBundle)
|
|
555
|
+
|| !validateCommittedPointer(pointer, bundle)) {
|
|
556
|
+
fail('INVALID_RUN_STORE', 'multi-epoch store bindingが不正');
|
|
557
|
+
}
|
|
558
|
+
let previous = createdBundle;
|
|
559
|
+
for (let epoch = 2; epoch <= pointer.plan_epoch; epoch += 1) {
|
|
560
|
+
const current = epoch === pointer.plan_epoch
|
|
561
|
+
? bundle
|
|
562
|
+
: await readRegularJson(path.join(runDir, 'epochs', String(epoch).padStart(8, '0'), 'epoch-bundle.json'), `epoch ${epoch} bundle`);
|
|
563
|
+
rejectFutureArtifact(current,
|
|
564
|
+
{ artifact: 'runtime_epoch_bundle', family: 'lattice.runtime_epoch_bundle', expectedVersion: 1 });
|
|
565
|
+
if (!validateRuntimeEpochBundle(current) || current.plan_epoch !== epoch
|
|
566
|
+
|| current.run_id !== meta.run_id
|
|
567
|
+
|| current.predecessor_bundle_digest !== previous.bundle_digest) {
|
|
568
|
+
fail('INVALID_RUN_STORE', `epoch ${epoch} predecessor chainが不正`);
|
|
569
|
+
}
|
|
570
|
+
previous = current;
|
|
571
|
+
}
|
|
572
|
+
return { meta, pointer, bundle };
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* successorはLPG028のrun_request.v2/migration/treatment verifierを必須注入する。
|
|
577
|
+
* v1 validatorやopaque objectへfallbackせず、verifier未導入中はstore無変更で拒否する。
|
|
578
|
+
*/
|
|
579
|
+
export async function stageSuccessorEpoch({ runDir, transactionId, bundle, recompileRequest = null,
|
|
580
|
+
validateSuccessor, validatePhaseRevision = null, commitPhaseRevision = null }) {
|
|
581
|
+
if (!TRANSACTION_ID.test(transactionId ?? '')) {
|
|
582
|
+
fail('INVALID_RUN_STORE', 'staging transaction idが不正');
|
|
583
|
+
}
|
|
584
|
+
if (typeof validateSuccessor !== 'function') {
|
|
585
|
+
fail('UNSUPPORTED_SUCCESSOR_SCHEMA', 'run_request.v2 successor verifierが未指定');
|
|
586
|
+
}
|
|
587
|
+
const committed = await readCommittedEpochStore(runDir);
|
|
588
|
+
if (recompileRequest !== null && !validateRuntimeRecompileRequest(recompileRequest, {
|
|
589
|
+
predecessorBundle: committed?.bundle ?? null,
|
|
590
|
+
validatePhaseRevision,
|
|
591
|
+
})) fail('INVALID_RECOMPILE_REQUEST', 'runtime recompile requestがcontractを満たさない');
|
|
592
|
+
let candidate = structuredClone(bundle);
|
|
593
|
+
if (committed === null || candidate?.schema !== 'lattice.runtime_epoch_bundle.v1'
|
|
594
|
+
|| candidate.plan_epoch !== committed.pointer.plan_epoch + 1
|
|
595
|
+
|| candidate.predecessor_bundle_digest !== committed.bundle.bundle_digest) {
|
|
596
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'successor bundleがcommitted predecessorへbindしない');
|
|
597
|
+
}
|
|
598
|
+
if (recompileRequest !== null) {
|
|
599
|
+
if (candidate?.request?.request_digest !== recompileRequest.successor_request.request_digest
|
|
600
|
+
|| candidate?.task_migration?.migration_digest !== recompileRequest.task_migration.migration_digest) {
|
|
601
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'successor bundleがrecompile requestへbindしない');
|
|
602
|
+
}
|
|
603
|
+
if (recompileRequest.phase_revision === null) {
|
|
604
|
+
if (candidate.phase_revision_digest !== null
|
|
605
|
+
|| candidate.phase_revision_commit_receipt !== null) {
|
|
606
|
+
fail('PHASE_REVISION_COMMIT_MISMATCH', 'null phase revisionへreceiptが存在する');
|
|
607
|
+
}
|
|
608
|
+
} else {
|
|
609
|
+
const preview = { ...candidate, phase_revision_digest: null,
|
|
610
|
+
phase_revision_commit_receipt: null };
|
|
611
|
+
const previewBody = { ...preview }; delete previewBody.bundle_digest;
|
|
612
|
+
preview.bundle_digest = digestArtifact(previewBody);
|
|
613
|
+
if (!validateRuntimeEpochBundle(preview)
|
|
614
|
+
|| await validateSuccessor(structuredClone(preview), {
|
|
615
|
+
predecessor: structuredClone(committed.bundle),
|
|
616
|
+
pointer: structuredClone(committed.pointer), phase_revision_pending: true,
|
|
617
|
+
}) !== true) {
|
|
618
|
+
fail('UNSUPPORTED_SUCCESSOR_SCHEMA', 'phase commit前successor verifierがbundleを棄却した');
|
|
619
|
+
}
|
|
620
|
+
if (typeof commitPhaseRevision !== 'function') {
|
|
621
|
+
fail('PHASE_REVISION_UNAVAILABLE', 'phase_todo_revision.v3 committerが未指定');
|
|
622
|
+
}
|
|
623
|
+
// validate後、runtime storeへ一byteも書く前にTODO transactionをcommitする。
|
|
624
|
+
const receipt = await commitPhaseRevision(structuredClone(recompileRequest.phase_revision));
|
|
625
|
+
if (!validatePhaseRevisionCommitReceipt(receipt)
|
|
626
|
+
|| receipt.revision_digest !== recompileRequest.phase_revision.revision_digest
|
|
627
|
+
|| receipt.project_id !== recompileRequest.phase_revision.project_id
|
|
628
|
+
|| receipt.plan_key !== recompileRequest.phase_revision.plan_key
|
|
629
|
+
|| receipt.plan_version !== recompileRequest.phase_revision.desired_plan?.plan_version
|
|
630
|
+
|| receipt.active_plan_digest !== recompileRequest.phase_revision.desired_plan?.plan_digest
|
|
631
|
+
|| receipt.reconciliation_digest !== recompileRequest.phase_revision.reconciliation?.reconciliation_digest) {
|
|
632
|
+
fail('PHASE_REVISION_COMMIT_MISMATCH', 'phase revision commit receipt bindingが不正');
|
|
633
|
+
}
|
|
634
|
+
candidate.phase_revision_digest = recompileRequest.phase_revision.revision_digest;
|
|
635
|
+
candidate.phase_revision_commit_receipt = receipt;
|
|
636
|
+
const body = { ...candidate };
|
|
637
|
+
delete body.bundle_digest;
|
|
638
|
+
candidate.bundle_digest = digestArtifact(body);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const verdict = await validateSuccessor(structuredClone(candidate), {
|
|
642
|
+
predecessor: structuredClone(committed.bundle),
|
|
643
|
+
pointer: structuredClone(committed.pointer),
|
|
644
|
+
});
|
|
645
|
+
if (verdict !== true) {
|
|
646
|
+
fail('UNSUPPORTED_SUCCESSOR_SCHEMA', 'run_request.v2 successor verifierがbundleを棄却した');
|
|
647
|
+
}
|
|
648
|
+
if (!validateRuntimeEpochBundle(candidate)) {
|
|
649
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'successor epoch bundle contractが不正');
|
|
650
|
+
}
|
|
651
|
+
const stagingRoot = path.join(runDir, 'staging');
|
|
652
|
+
const transactionDir = path.join(stagingRoot, transactionId);
|
|
653
|
+
const prepare = { schema: 'lattice.runtime_epoch_prepare.v1',
|
|
654
|
+
transaction_id: transactionId, bundle_digest: candidate.bundle_digest, prepare_digest: '' };
|
|
655
|
+
const prepareBody = { ...prepare }; delete prepareBody.prepare_digest;
|
|
656
|
+
prepare.prepare_digest = digestArtifact(prepareBody);
|
|
657
|
+
await mkdir(stagingRoot, { recursive: true });
|
|
658
|
+
await fsyncDirectory(runDir);
|
|
659
|
+
try {
|
|
660
|
+
await mkdir(transactionDir);
|
|
661
|
+
await writeDurableJson(path.join(transactionDir, 'epoch-bundle.json'), candidate);
|
|
662
|
+
await writeDurableJson(path.join(transactionDir, 'prepare.json'), prepare);
|
|
663
|
+
await fsyncDirectory(transactionDir);
|
|
664
|
+
await fsyncDirectory(stagingRoot);
|
|
665
|
+
} catch (error) {
|
|
666
|
+
if (error?.code !== 'EEXIST') {
|
|
667
|
+
await rm(transactionDir, { recursive: true, force: true });
|
|
668
|
+
throw error;
|
|
669
|
+
}
|
|
670
|
+
const bundlePath = path.join(transactionDir, 'epoch-bundle.json');
|
|
671
|
+
let existing;
|
|
672
|
+
try {
|
|
673
|
+
existing = await readRegularJson(bundlePath, 'staged epoch bundle');
|
|
674
|
+
} catch (readError) {
|
|
675
|
+
try { await lstat(bundlePath); throw readError; }
|
|
676
|
+
catch (statError) {
|
|
677
|
+
if (statError === readError || statError?.code !== 'ENOENT') throw readError;
|
|
678
|
+
}
|
|
679
|
+
await writeDurableJson(bundlePath, candidate);
|
|
680
|
+
existing = candidate;
|
|
681
|
+
}
|
|
682
|
+
if (!validateRuntimeEpochBundle(existing) || existing.bundle_digest !== candidate.bundle_digest) {
|
|
683
|
+
fail('EPOCH_BUNDLE_CONFLICT', '同一transactionへ異なるsuccessor bundleが存在する');
|
|
684
|
+
}
|
|
685
|
+
const preparePath = path.join(transactionDir, 'prepare.json');
|
|
686
|
+
try {
|
|
687
|
+
const existingPrepare = await readRegularJson(preparePath, 'staged epoch prepare');
|
|
688
|
+
if (canonicalizeArtifact(existingPrepare) !== canonicalizeArtifact(prepare)) {
|
|
689
|
+
fail('EPOCH_BUNDLE_CONFLICT', '同一transactionのprepare bindingが異なる');
|
|
690
|
+
}
|
|
691
|
+
} catch (readError) {
|
|
692
|
+
try { await lstat(preparePath); throw readError; }
|
|
693
|
+
catch (statError) {
|
|
694
|
+
if (statError === readError || statError?.code !== 'ENOENT') throw readError;
|
|
695
|
+
}
|
|
696
|
+
await writeDurableJson(preparePath, prepare);
|
|
697
|
+
}
|
|
698
|
+
await fsyncDirectory(transactionDir);
|
|
699
|
+
await fsyncDirectory(stagingRoot);
|
|
700
|
+
}
|
|
701
|
+
return { transaction_id: transactionId, bundle_digest: candidate.bundle_digest,
|
|
702
|
+
bundle: structuredClone(candidate) };
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* staged successorをepoch historyへrenameし、durable event headsを確認してpointerを最後にcommitする。
|
|
707
|
+
* 同digest retryだけを許し、directory最大値や別transactionへfallbackしない。
|
|
708
|
+
*/
|
|
709
|
+
export async function commitStagedSuccessorEpoch({ runDir, transactionId,
|
|
710
|
+
activationRunEventDigest, activationControlEventDigest, readActivationControlEvents = null }) {
|
|
711
|
+
if (!TRANSACTION_ID.test(transactionId ?? '')
|
|
712
|
+
|| !HEX_DIGEST.test(activationRunEventDigest ?? '')
|
|
713
|
+
|| !HEX_DIGEST.test(activationControlEventDigest ?? '')) {
|
|
714
|
+
fail('INVALID_RUN_STORE', 'successor commit入力が不正');
|
|
715
|
+
}
|
|
716
|
+
const committed = await readCommittedEpochStore(runDir);
|
|
717
|
+
if (committed === null) fail('INVALID_RUN_STORE', 'managed predecessorが存在しない');
|
|
718
|
+
const transactionDir = path.join(runDir, 'staging', transactionId);
|
|
719
|
+
let bundle;
|
|
720
|
+
let alreadyRenamed = false;
|
|
721
|
+
try {
|
|
722
|
+
bundle = await readRegularJson(path.join(transactionDir, 'epoch-bundle.json'), 'staged epoch bundle');
|
|
723
|
+
} catch (error) {
|
|
724
|
+
if (!(error instanceof RuntimeEpochStoreError)) throw error;
|
|
725
|
+
const successorDir = path.join(runDir, 'epochs', String(committed.pointer.plan_epoch + 1).padStart(8, '0'));
|
|
726
|
+
let prepare;
|
|
727
|
+
try {
|
|
728
|
+
prepare = await readRegularJson(path.join(successorDir, 'prepare.json'), 'renamed epoch prepare');
|
|
729
|
+
bundle = await readRegularJson(path.join(successorDir, 'epoch-bundle.json'), 'renamed epoch bundle');
|
|
730
|
+
alreadyRenamed = true;
|
|
731
|
+
} catch {
|
|
732
|
+
const currentDir = path.join(runDir, 'epochs', String(committed.pointer.plan_epoch).padStart(8, '0'));
|
|
733
|
+
prepare = await readRegularJson(path.join(currentDir, 'prepare.json'), 'committed epoch prepare');
|
|
734
|
+
bundle = committed.bundle;
|
|
735
|
+
}
|
|
736
|
+
if (!exactRecord(prepare, ['schema', 'transaction_id', 'bundle_digest', 'prepare_digest'])
|
|
737
|
+
|| prepare.schema !== 'lattice.runtime_epoch_prepare.v1'
|
|
738
|
+
|| prepare.transaction_id !== transactionId || !selfDigestValid(prepare, 'prepare_digest')
|
|
739
|
+
|| prepare.bundle_digest !== bundle.bundle_digest) throw error;
|
|
740
|
+
if (bundle.plan_epoch === committed.pointer.plan_epoch) {
|
|
741
|
+
if (committed.pointer.activation_run_event_digest !== activationRunEventDigest
|
|
742
|
+
|| committed.pointer.activation_control_event_digest !== activationControlEventDigest) throw error;
|
|
743
|
+
return { bundle: committed.bundle, pointer: committed.pointer };
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (!validateRuntimeEpochBundle(bundle)
|
|
747
|
+
|| bundle.plan_epoch !== committed.pointer.plan_epoch + 1
|
|
748
|
+
|| bundle.predecessor_bundle_digest !== committed.bundle.bundle_digest) {
|
|
749
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'staged successor bindingが不正');
|
|
750
|
+
}
|
|
751
|
+
const runEvents = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
|
|
752
|
+
const controlEvents = typeof readActivationControlEvents === 'function'
|
|
753
|
+
? await readActivationControlEvents()
|
|
754
|
+
: await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
|
|
755
|
+
if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
|
|
756
|
+
|| !Array.isArray(controlEvents) || controlEvents.at(-1)?.event_digest !== activationControlEventDigest) {
|
|
757
|
+
fail('EPOCH_ACTIVATION_INCOMPLETE', 'successor activation event headが未耐久化');
|
|
758
|
+
}
|
|
759
|
+
const epochsDir = path.join(runDir, 'epochs');
|
|
760
|
+
const epochDir = path.join(epochsDir, String(bundle.plan_epoch).padStart(8, '0'));
|
|
761
|
+
try {
|
|
762
|
+
if (!alreadyRenamed) {
|
|
763
|
+
await rename(transactionDir, epochDir);
|
|
764
|
+
await fsyncDirectory(epochsDir);
|
|
765
|
+
await fsyncDirectory(path.join(runDir, 'staging'));
|
|
766
|
+
} else {
|
|
767
|
+
await fsyncDirectory(epochDir);
|
|
768
|
+
await fsyncDirectory(epochsDir);
|
|
769
|
+
}
|
|
770
|
+
} catch (error) {
|
|
771
|
+
if (error?.code !== 'EEXIST' && error?.code !== 'ENOTEMPTY') throw error;
|
|
772
|
+
const existing = await readRegularJson(path.join(epochDir, 'epoch-bundle.json'), 'committed successor bundle');
|
|
773
|
+
if (!validateRuntimeEpochBundle(existing) || existing.bundle_digest !== bundle.bundle_digest) {
|
|
774
|
+
fail('EPOCH_BUNDLE_CONFLICT', 'successor epoch concurrent commitが異なる');
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const pointer = {
|
|
778
|
+
schema: 'lattice.committed_epoch_pointer.v1', run_id: bundle.run_id,
|
|
779
|
+
plan_epoch: bundle.plan_epoch, plan_ref: bundle.plan.plan_ref,
|
|
780
|
+
bundle_digest: bundle.bundle_digest, activation_run_event_digest: activationRunEventDigest,
|
|
781
|
+
activation_control_event_digest: activationControlEventDigest,
|
|
782
|
+
};
|
|
783
|
+
pointer.pointer_digest = digestArtifact(pointer);
|
|
784
|
+
await replaceDurableJson(runDir, 'committed-epoch.json', pointer);
|
|
785
|
+
return { bundle, pointer };
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
export async function commitReleaseEpochBarrier({ runDir, barrier }) {
|
|
789
|
+
if (!exactRecord(barrier, ['schema', 'run_id', 'committed_epoch_pointer_digest',
|
|
790
|
+
'plan_epoch', 'activation_digest', 'controller_ready_ack_digests',
|
|
791
|
+
'staged_lease_digests', 'gate_generation', 'release_digest'])
|
|
792
|
+
|| barrier.schema !== 'lattice.release_epoch_barrier.v1'
|
|
793
|
+
|| !HEX_DIGEST.test(barrier.committed_epoch_pointer_digest ?? '')
|
|
794
|
+
|| !HEX_DIGEST.test(barrier.activation_digest ?? '')
|
|
795
|
+
|| !Array.isArray(barrier.controller_ready_ack_digests)
|
|
796
|
+
|| !Array.isArray(barrier.staged_lease_digests)
|
|
797
|
+
|| !barrier.controller_ready_ack_digests.every((value, index) => HEX_DIGEST.test(value)
|
|
798
|
+
&& (index === 0 || barrier.controller_ready_ack_digests[index - 1] < value))
|
|
799
|
+
|| !barrier.staged_lease_digests.every((value, index) => HEX_DIGEST.test(value)
|
|
800
|
+
&& (index === 0 || barrier.staged_lease_digests[index - 1] < value))
|
|
801
|
+
|| !selfDigestValid(barrier, 'release_digest')) {
|
|
802
|
+
fail('EPOCH_ACTIVATION_INCOMPLETE', 'release epoch barrier contractが不正');
|
|
803
|
+
}
|
|
804
|
+
const committed = await readCommittedEpochStore(runDir);
|
|
805
|
+
if (committed === null || barrier.run_id !== committed.meta.run_id
|
|
806
|
+
|| barrier.plan_epoch !== committed.pointer.plan_epoch
|
|
807
|
+
|| barrier.committed_epoch_pointer_digest !== committed.pointer.pointer_digest
|
|
808
|
+
|| !Number.isSafeInteger(barrier.gate_generation) || barrier.gate_generation < 1) {
|
|
809
|
+
fail('EPOCH_ACTIVATION_INCOMPLETE', 'release barrierがcommitted pointerへbindしない');
|
|
810
|
+
}
|
|
811
|
+
await replaceDurableJson(runDir, 'release-epoch.json', barrier);
|
|
812
|
+
return { release_digest: barrier.release_digest };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
export async function isManagedRunFrozen(runDir, events) {
|
|
816
|
+
const committed = await readCommittedEpochStore(runDir);
|
|
817
|
+
if (committed === null) return false;
|
|
818
|
+
const lastFreeze = events.findLast((event) => event.kind === 'intake_frozen');
|
|
819
|
+
const lastResume = events.findLast((event) => event.kind === 'intake_resumed'
|
|
820
|
+
&& event.plan_epoch === committed.pointer.plan_epoch);
|
|
821
|
+
const hasFreeze = lastFreeze !== undefined
|
|
822
|
+
&& (lastResume === undefined || lastResume.sequence < lastFreeze.sequence);
|
|
823
|
+
let gateValid = false;
|
|
824
|
+
try {
|
|
825
|
+
const gate = await readRegularJson(path.join(runDir, 'supervisor', 'write-gate.json'), 'supervisor write gate');
|
|
826
|
+
gateValid = exactRecord(gate, [
|
|
827
|
+
'schema', 'run_id', 'plan_epoch', 'gate_generation', 'release_barrier_digest',
|
|
828
|
+
'controller_release_ack_digests', 'armed_lease_digests', 'previous_gate_digest',
|
|
829
|
+
'committed_at', 'gate_digest',
|
|
830
|
+
]) && gate.schema === 'lattice.supervisor_write_gate.v1'
|
|
831
|
+
&& gate.run_id === committed.meta.run_id
|
|
832
|
+
&& gate.plan_epoch === committed.pointer.plan_epoch
|
|
833
|
+
&& selfDigestValid(gate, 'gate_digest');
|
|
834
|
+
} catch (error) {
|
|
835
|
+
if (!(error instanceof RuntimeEpochStoreError)) throw error;
|
|
836
|
+
}
|
|
837
|
+
return hasFreeze || !gateValid;
|
|
838
|
+
}
|