@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,916 +1,916 @@
|
|
|
1
|
-
import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
|
|
2
|
-
// 切断可能性の写像はtodo側と同じ正本を使う。計画時と実行時で「切れる種類」の定義が
|
|
3
|
-
// 分かれると、同じ資源が段によって別の答えを持つ。
|
|
4
|
-
import { severabilityOfConflictKind } from './todo-independence-contracts.mjs';
|
|
5
|
-
import { buildNextRunEvent, buildExecutorPackets } from './runtime-engine.mjs';
|
|
6
|
-
import { projectRuntimeState } from './runtime-projection.mjs';
|
|
7
|
-
import {
|
|
8
|
-
recomputeHoldDecision,
|
|
9
|
-
verifyCarryOverWitness,
|
|
10
|
-
} from './runtime-decision-verifier.mjs';
|
|
11
|
-
import {
|
|
12
|
-
computeContextContentDigest,
|
|
13
|
-
RUN_REQUEST_SCHEMA,
|
|
14
|
-
selfDigest,
|
|
15
|
-
validateCarryOverWitness,
|
|
16
|
-
validateEpochRebindPacket,
|
|
17
|
-
validateHoldDecision,
|
|
18
|
-
validateRunRequest,
|
|
19
|
-
validateRuntimePlan,
|
|
20
|
-
validateRuntimePlanDiff,
|
|
21
|
-
verifyRuntimePlanBinding,
|
|
22
|
-
} from './runtime-contracts.mjs';
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* RC3-G 後発競合のselective holdとplan vN+1 recompile(ADR 0044 Decision 6・7、plan RC3-G)。
|
|
26
|
-
*
|
|
27
|
-
* producer側の裁定実装。affected closure・hold/continue集合は
|
|
28
|
-
* `runtime-decision-verifier.mjs`と独立に計算した上で、保存bytesからの
|
|
29
|
-
* verifier再計算とのexact一致をfail-loudに自己検査する(divergenceは即例外)。
|
|
30
|
-
*
|
|
31
|
-
* - 競合発見時はactive planへ追記しない。frozen prefixを固定してclosureを計算し、
|
|
32
|
-
* closure外のin-flight TODOはcarry-over witnessを実証できた場合だけ継続する。
|
|
33
|
-
* 1 fieldでも証明不能ならholdへ戻す(fail closed、silent fallbackなし)。
|
|
34
|
-
* - carry-overは旧contextの継続利用ではない。content digest不変・epochだけ更新の
|
|
35
|
-
* epoch rebind packetによる、失効後の再認可である(Decision 7.3)。
|
|
36
|
-
* - 旧plan・旧context・partial patchはcontext_invalidated eventで失効し、
|
|
37
|
-
* redispatch TODOへは新plan_ref由来の別contentのpacketを発行する。
|
|
38
|
-
* - irreducible conflictはprecedenceへ偽装せず、unordered conflictのまま
|
|
39
|
-
* intentional serialとして保持する(Decision 7.6)。
|
|
40
|
-
*/
|
|
41
|
-
|
|
42
|
-
function fail(reason) {
|
|
43
|
-
throw new TypeError(`hold/recompile契約違反: ${reason}`);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function plainRecord(value) {
|
|
47
|
-
return value !== null
|
|
48
|
-
&& typeof value === 'object'
|
|
49
|
-
&& !Array.isArray(value)
|
|
50
|
-
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function exactRecord(value, keys) {
|
|
54
|
-
if (!plainRecord(value)) return false;
|
|
55
|
-
const actual = Object.keys(value).sort();
|
|
56
|
-
const expected = [...keys].sort();
|
|
57
|
-
return actual.length === expected.length
|
|
58
|
-
&& actual.every((key, index) => key === expected[index]);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function sorted(values) {
|
|
62
|
-
return [...values].sort();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function sha16(value) {
|
|
66
|
-
return digestArtifact({ path: value }).slice(0, 16);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const WITNESS_KINDS = Object.freeze(['state', 'schema', 'invariant', 'effect', 'external_effect']);
|
|
70
|
-
const HEX_DIGEST = /^[0-9a-f]{64}$/u;
|
|
71
|
-
const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
|
|
72
|
-
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
73
|
-
|
|
74
|
-
function selfDigestValid(value, field) {
|
|
75
|
-
return plainRecord(value) && HEX_DIGEST.test(value[field] ?? '')
|
|
76
|
-
&& selfDigest(value, field) === value[field];
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function sortedUnique(values, predicate) {
|
|
80
|
-
return Array.isArray(values) && values.every(predicate)
|
|
81
|
-
&& values.every((value, index) => index === 0
|
|
82
|
-
|| canonicalizeArtifact(values[index - 1]) < canonicalizeArtifact(value));
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function primaryFirstUnique(values, predicate) {
|
|
86
|
-
if (!Array.isArray(values) || !values.every(predicate)
|
|
87
|
-
|| new Set(values).size !== values.length) return false;
|
|
88
|
-
const tail = values.slice(1);
|
|
89
|
-
return tail.every((value, index) => index === 0
|
|
90
|
-
|| canonicalizeArtifact(tail[index - 1]) < canonicalizeArtifact(value));
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** ADR 0064 Decision 5のfull predecessor→successor mapping。 */
|
|
94
|
-
export function validateRuntimeTaskMigration(value, { predecessorTaskIds = null,
|
|
95
|
-
successorTaskIds = null } = {}) {
|
|
96
|
-
if (!exactRecord(value, ['schema', 'entries', 'migration_digest'])
|
|
97
|
-
|| value.schema !== 'lattice.runtime_task_migration.v1'
|
|
98
|
-
|| !Array.isArray(value.entries) || value.entries.length > 10_000
|
|
99
|
-
|| !selfDigestValid(value, 'migration_digest')) return false;
|
|
100
|
-
const predecessor = [];
|
|
101
|
-
const successorOwners = new Map();
|
|
102
|
-
for (const entry of value.entries) {
|
|
103
|
-
if (!exactRecord(entry, ['predecessor_task_id', 'disposition', 'successor_task_ids',
|
|
104
|
-
'reason', 'evidence_digests'])
|
|
105
|
-
|| !IDENTIFIER.test(entry.predecessor_task_id ?? '')
|
|
106
|
-
|| !['carry', 'replace', 'split', 'retire', 'stay'].includes(entry.disposition)
|
|
107
|
-
|| typeof entry.reason !== 'string' || entry.reason.length === 0
|
|
108
|
-
|| !primaryFirstUnique(entry.successor_task_ids, (id) => IDENTIFIER.test(id))
|
|
109
|
-
|| !sortedUnique(entry.evidence_digests, (digest) => HEX_DIGEST.test(digest))) return false;
|
|
110
|
-
if (['carry', 'stay'].includes(entry.disposition)
|
|
111
|
-
&& canonicalizeArtifact(entry.successor_task_ids) !== canonicalizeArtifact([entry.predecessor_task_id])) return false;
|
|
112
|
-
if (entry.disposition === 'retire' && entry.successor_task_ids.length !== 0) return false;
|
|
113
|
-
if (['replace', 'split'].includes(entry.disposition) && entry.successor_task_ids.length === 0) return false;
|
|
114
|
-
predecessor.push(entry.predecessor_task_id);
|
|
115
|
-
for (const id of entry.successor_task_ids) {
|
|
116
|
-
const owners = successorOwners.get(id) ?? [];
|
|
117
|
-
owners.push(entry.predecessor_task_id);
|
|
118
|
-
successorOwners.set(id, owners);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
if (!sortedUnique(predecessor, (id) => IDENTIFIER.test(id))) return false;
|
|
122
|
-
if ([...successorOwners.values()].some((owners) => owners.length !== 1)) return false;
|
|
123
|
-
if (predecessorTaskIds !== null
|
|
124
|
-
&& canonicalizeArtifact(predecessor) !== canonicalizeArtifact(sorted(predecessorTaskIds))) return false;
|
|
125
|
-
if (successorTaskIds !== null) {
|
|
126
|
-
const mapped = sorted(successorOwners.keys());
|
|
127
|
-
if (canonicalizeArtifact(mapped) !== canonicalizeArtifact(sorted(successorTaskIds))) return false;
|
|
128
|
-
}
|
|
129
|
-
return true;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export function validateRunRequestV2(value) {
|
|
133
|
-
if (!exactRecord(value, ['schema', 'request_id', 'repo', 'capacity', 'todos', 'manual_witness',
|
|
134
|
-
'sensor_query_set', 'executor_capability', 'claim_mode', 'predecessor_request_digest',
|
|
135
|
-
'task_migration_digest', 'request_digest'])
|
|
136
|
-
|| value.schema !== 'lattice.run_request.v2'
|
|
137
|
-
|| !HEX_DIGEST.test(value.predecessor_request_digest ?? '')
|
|
138
|
-
|| !HEX_DIGEST.test(value.task_migration_digest ?? '')
|
|
139
|
-
|| !selfDigestValid(value, 'request_digest')) return false;
|
|
140
|
-
const projected = {
|
|
141
|
-
// 後継requestの本体はbase契約と同じ規律で読む。v1へ固定すると、創作境界を持つ
|
|
142
|
-
// 宣言が再計画を跨げない(ADR 0136)。
|
|
143
|
-
schema: RUN_REQUEST_SCHEMA, request_id: value.request_id, repo: value.repo,
|
|
144
|
-
capacity: value.capacity, todos: value.todos, manual_witness: value.manual_witness,
|
|
145
|
-
sensor_query_set: value.sensor_query_set, executor_capability: value.executor_capability,
|
|
146
|
-
claim_mode: value.claim_mode, request_digest: '',
|
|
147
|
-
};
|
|
148
|
-
projected.request_digest = selfDigest(projected, 'request_digest');
|
|
149
|
-
return validateRunRequest(projected);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export function validateRuntimeRecompileRequest(value, { predecessorBundle = null,
|
|
153
|
-
frozenEventDigest = null, holdDecisionDigest = null, validatePhaseRevision = null } = {}) {
|
|
154
|
-
if (!exactRecord(value, ['schema', 'request_id', 'run_id', 'predecessor_epoch',
|
|
155
|
-
'frozen_event_digest', 'hold_decision_digest', 'mode', 'reason', 'successor_request',
|
|
156
|
-
'task_migration', 'phase_revision', 'seam_split', 'intentional_serial', 'request_digest'])
|
|
157
|
-
|| value.schema !== 'lattice.runtime_recompile_request.v1'
|
|
158
|
-
|| !IDENTIFIER.test(value.request_id ?? '') || !IDENTIFIER.test(value.run_id ?? '')
|
|
159
|
-
|| !Number.isSafeInteger(value.predecessor_epoch) || value.predecessor_epoch < 1
|
|
160
|
-
|| !HEX_DIGEST.test(value.frozen_event_digest ?? '')
|
|
161
|
-
|| !HEX_DIGEST.test(value.hold_decision_digest ?? '')
|
|
162
|
-
|| !['seam_split', 'intentional_serial'].includes(value.mode)
|
|
163
|
-
|| typeof value.reason !== 'string' || value.reason.length === 0
|
|
164
|
-
|| !validateRunRequestV2(value.successor_request)
|
|
165
|
-
|| !validateRuntimeTaskMigration(value.task_migration, {
|
|
166
|
-
predecessorTaskIds: predecessorBundle?.plan?.nodes?.map(({ todo_id: id }) => id) ?? null,
|
|
167
|
-
successorTaskIds: value.successor_request.todos?.map(({ todo_id: id }) => id) ?? null,
|
|
168
|
-
})
|
|
169
|
-
|| value.successor_request.request_id !== value.run_id
|
|
170
|
-
|| value.successor_request.task_migration_digest !== value.task_migration.migration_digest
|
|
171
|
-
|| !selfDigestValid(value, 'request_digest')) return false;
|
|
172
|
-
if (predecessorBundle !== null
|
|
173
|
-
&& (value.predecessor_epoch !== predecessorBundle.plan_epoch
|
|
174
|
-
|| value.successor_request.predecessor_request_digest !== predecessorBundle.request.request_digest)) return false;
|
|
175
|
-
if (frozenEventDigest !== null && value.frozen_event_digest !== frozenEventDigest) return false;
|
|
176
|
-
if (holdDecisionDigest !== null && value.hold_decision_digest !== holdDecisionDigest) return false;
|
|
177
|
-
if (value.phase_revision === null) {
|
|
178
|
-
// phase revisionを省略できるのは、TODO/source/edge入力とtask identityが完全に不変な時だけ。
|
|
179
|
-
// intentional_serialのruntime conflict edgeはplan overlayでありTODO工程revisionではない。
|
|
180
|
-
if (predecessorBundle !== null) {
|
|
181
|
-
const predecessorRequest = predecessorBundle.request;
|
|
182
|
-
const stableInputs = ['todos', 'manual_witness', 'sensor_query_set'];
|
|
183
|
-
if (stableInputs.some((key) => canonicalizeArtifact(value.successor_request[key])
|
|
184
|
-
!== canonicalizeArtifact(predecessorRequest[key]))) return false;
|
|
185
|
-
if (value.task_migration.entries.some((entry) => !['stay', 'carry'].includes(entry.disposition)
|
|
186
|
-
|| entry.successor_task_ids.length !== 1
|
|
187
|
-
|| entry.successor_task_ids[0] !== entry.predecessor_task_id)) return false;
|
|
188
|
-
}
|
|
189
|
-
} else if (typeof validatePhaseRevision !== 'function'
|
|
190
|
-
|| validatePhaseRevision(structuredClone(value.phase_revision)) !== true
|
|
191
|
-
|| canonicalizeArtifact(value.phase_revision.runtime_task_migration)
|
|
192
|
-
!== canonicalizeArtifact(value.task_migration)) return false;
|
|
193
|
-
if (value.mode === 'seam_split') {
|
|
194
|
-
if (value.intentional_serial !== null || !validateRuntimeSeamSplit(value.seam_split, value)) return false;
|
|
195
|
-
if (value.phase_revision === null && [
|
|
196
|
-
value.seam_split.ownership_diff.added, value.seam_split.ownership_diff.removed,
|
|
197
|
-
value.seam_split.edge_diff.added, value.seam_split.edge_diff.removed,
|
|
198
|
-
].some((entries) => entries.length > 0)) return false;
|
|
199
|
-
} else if (value.seam_split !== null || !validateRuntimeIntentionalSerial(value.intentional_serial, value)) return false;
|
|
200
|
-
return true;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function validateRuntimeSeamSplit(value, request) {
|
|
204
|
-
return exactRecord(value, ['schema', 'finding_digest', 'predecessor_task_ids',
|
|
205
|
-
'task_migration_digest', 'ownership_diff', 'edge_diff', 'verifier_refs', 'split_digest'])
|
|
206
|
-
&& value.schema === 'lattice.runtime_seam_split.v1'
|
|
207
|
-
&& HEX_DIGEST.test(value.finding_digest ?? '')
|
|
208
|
-
&& sortedUnique(value.predecessor_task_ids, (id) => IDENTIFIER.test(id))
|
|
209
|
-
&& value.task_migration_digest === request.task_migration.migration_digest
|
|
210
|
-
&& validateOwnershipDiff(value.ownership_diff) && validateEdgeDiff(value.edge_diff)
|
|
211
|
-
&& sortedUnique(value.verifier_refs, (ref) => typeof ref === 'string' && ref.length > 0)
|
|
212
|
-
&& selfDigestValid(value, 'split_digest');
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function validateOwnershipDiff(value) {
|
|
216
|
-
const entry = (item) => exactRecord(item, ['resource_id', 'owner_todo_id', 'access_kind'])
|
|
217
|
-
&& IDENTIFIER.test(item.resource_id ?? '') && IDENTIFIER.test(item.owner_todo_id ?? '')
|
|
218
|
-
&& ['read', 'write', 'own'].includes(item.access_kind);
|
|
219
|
-
return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
|
|
220
|
-
&& value.schema === 'lattice.runtime_ownership_diff.v1'
|
|
221
|
-
&& sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
|
|
222
|
-
&& selfDigestValid(value, 'diff_digest');
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function validateEdgeDiff(value) {
|
|
226
|
-
const entry = (item) => exactRecord(item, ['from_todo_id', 'to_todo_id', 'kind'])
|
|
227
|
-
&& IDENTIFIER.test(item.from_todo_id ?? '') && IDENTIFIER.test(item.to_todo_id ?? '')
|
|
228
|
-
&& ['hard_dependency', 'conflict'].includes(item.kind);
|
|
229
|
-
return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
|
|
230
|
-
&& value.schema === 'lattice.runtime_edge_diff.v1'
|
|
231
|
-
&& sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
|
|
232
|
-
&& selfDigestValid(value, 'diff_digest');
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
function validateRuntimeIntentionalSerial(value, request) {
|
|
236
|
-
if (!exactRecord(value, ['schema', 'finding_digest', 'todo_ids', 'resource_id',
|
|
237
|
-
'stay_todo_id', 'reason', 'serial_digest'])
|
|
238
|
-
|| value.schema !== 'lattice.runtime_intentional_serial.v1'
|
|
239
|
-
|| !HEX_DIGEST.test(value.finding_digest ?? '')
|
|
240
|
-
|| !sortedUnique(value.todo_ids, (id) => IDENTIFIER.test(id)) || value.todo_ids.length < 2
|
|
241
|
-
|| !IDENTIFIER.test(value.resource_id ?? '') || !value.todo_ids.includes(value.stay_todo_id)
|
|
242
|
-
|| typeof value.reason !== 'string' || value.reason.length === 0
|
|
243
|
-
|| !selfDigestValid(value, 'serial_digest')) return false;
|
|
244
|
-
const byId = new Map(request.task_migration.entries.map((entry) => [entry.predecessor_task_id, entry]));
|
|
245
|
-
return value.todo_ids.every((id) => byId.has(id))
|
|
246
|
-
&& byId.get(value.stay_todo_id)?.disposition === 'stay';
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
function manifestResourceIds(manifest) {
|
|
250
|
-
const ids = new Set(manifest?.resources ?? []);
|
|
251
|
-
for (const effect of manifest?.state_effects ?? []) {
|
|
252
|
-
if (WITNESS_KINDS.includes(effect.kind) && typeof effect.resource_id === 'string') {
|
|
253
|
-
ids.add(effect.resource_id);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
return ids;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/** producer独自のaffected closure計算(conflict edge伝播+共有resource witness到達)。 */
|
|
260
|
-
function computeAffectedClosure(plan, manifests, seedTodoIds) {
|
|
261
|
-
const closure = new Set(seedTodoIds);
|
|
262
|
-
const byResource = new Map();
|
|
263
|
-
for (const [todoId, manifest] of Object.entries(manifests)) {
|
|
264
|
-
for (const resourceId of manifestResourceIds(manifest)) {
|
|
265
|
-
const members = byResource.get(resourceId) ?? new Set();
|
|
266
|
-
members.add(todoId);
|
|
267
|
-
byResource.set(resourceId, members);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
let changed = true;
|
|
271
|
-
while (changed) {
|
|
272
|
-
changed = false;
|
|
273
|
-
for (const conflict of plan.conflicts) {
|
|
274
|
-
const [left, right] = conflict.todo_ids;
|
|
275
|
-
if (closure.has(left) !== closure.has(right)) {
|
|
276
|
-
closure.add(left);
|
|
277
|
-
closure.add(right);
|
|
278
|
-
changed = true;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
// hard predecessorの下流はaffected(前提が失効するため。Decision 6.3)。
|
|
282
|
-
for (const edge of plan.precedence) {
|
|
283
|
-
if (closure.has(edge.from_todo_id) && !closure.has(edge.to_todo_id)) {
|
|
284
|
-
closure.add(edge.to_todo_id);
|
|
285
|
-
changed = true;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
for (const todoId of [...closure]) {
|
|
289
|
-
const manifest = manifests[todoId];
|
|
290
|
-
if (manifest === undefined) continue;
|
|
291
|
-
for (const resourceId of manifestResourceIds(manifest)) {
|
|
292
|
-
for (const member of byResource.get(resourceId) ?? []) {
|
|
293
|
-
if (!closure.has(member)) {
|
|
294
|
-
closure.add(member);
|
|
295
|
-
changed = true;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
return closure;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/** runtime findingから、停止・再計画する作業群だけを取り出す。 */
|
|
305
|
-
export function affectedTodoIds(plan, manifests, seedTodoIds) {
|
|
306
|
-
return sorted(computeAffectedClosure(plan, manifests, seedTodoIds));
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/**
|
|
310
|
-
* carry-over witness documentを構築し、提供sourcesに対して自己実証する。
|
|
311
|
-
* 実証できない場合はnullでなくreasons付きの失敗を返す(呼び出し側がholdへ戻す)。
|
|
312
|
-
*/
|
|
313
|
-
export function buildCarryOverWitness(options = {}) {
|
|
314
|
-
if (!exactRecord(options, [
|
|
315
|
-
'todoId', 'predecessorEpoch', 'successorEpoch', 'sources', 'nonOverlapEvidence', 'receiptBindings',
|
|
316
|
-
])) {
|
|
317
|
-
fail('buildCarryOverWitness optionsがexact shapeでない');
|
|
318
|
-
}
|
|
319
|
-
const { todoId, predecessorEpoch, successorEpoch, sources, nonOverlapEvidence, receiptBindings } = options;
|
|
320
|
-
const witness = {
|
|
321
|
-
schema: 'lattice.carry_over_witness.v1',
|
|
322
|
-
witness_id: `witness-${todoId}-e${successorEpoch}`,
|
|
323
|
-
todo_id: todoId,
|
|
324
|
-
predecessor_epoch: predecessorEpoch,
|
|
325
|
-
successor_epoch: successorEpoch,
|
|
326
|
-
invariant_digests: {
|
|
327
|
-
todo_input: digestArtifact(sources.todo_input),
|
|
328
|
-
boundary_manifest: digestArtifact(sources.boundary_manifest),
|
|
329
|
-
validator: digestArtifact(sources.validator),
|
|
330
|
-
context_content: digestArtifact(sources.context_content),
|
|
331
|
-
},
|
|
332
|
-
non_overlap_evidence: [...nonOverlapEvidence],
|
|
333
|
-
receipt_bindings: structuredClone(receiptBindings),
|
|
334
|
-
};
|
|
335
|
-
witness.witness_digest = selfDigest(witness, 'witness_digest');
|
|
336
|
-
// 構築不能はthrowでなくtyped失敗で返す(呼び出し側がholdへ戻すため)。
|
|
337
|
-
if (!validateCarryOverWitness(witness)) {
|
|
338
|
-
return { witness: null, reasons: ['witness_schema', 'carry_over_unprovable'] };
|
|
339
|
-
}
|
|
340
|
-
const verified = verifyCarryOverWitness({ witness, sources });
|
|
341
|
-
if (!verified.valid) {
|
|
342
|
-
return { witness: null, reasons: verified.reasons };
|
|
343
|
-
}
|
|
344
|
-
return { witness, reasons: [] };
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/**
|
|
348
|
-
* frozen prefixからhold decisionを裁定し、carry_over_witnessed/hold_decided eventを
|
|
349
|
-
* 追記する。continueできるのはwitnessを実証済みのclosure外running TODOだけで、
|
|
350
|
-
* 証明不能TODOはholdへ戻す。裁定はverifier再計算とのexact一致を自己検査する。
|
|
351
|
-
*/
|
|
352
|
-
export function decideHoldAndCarryOver(options = {}) {
|
|
353
|
-
if (!exactRecord(options, [
|
|
354
|
-
'runId', 'request', 'plan', 'manifests', 'packets', 'events', 'recordedAt',
|
|
355
|
-
])) {
|
|
356
|
-
fail('decideHoldAndCarryOver optionsがexact shapeでない');
|
|
357
|
-
}
|
|
358
|
-
const { runId, request, plan, manifests, packets, events, recordedAt } = options;
|
|
359
|
-
if (!validateRuntimePlan(plan)) fail('planがruntime_plan.v1 contractを満たさない');
|
|
360
|
-
if (!validateRunRequest(request)) fail('requestがrun_request.v1 contractを満たさない');
|
|
361
|
-
|
|
362
|
-
const state = projectRuntimeState({ events });
|
|
363
|
-
if (state.freeze === null) fail('freezeされていないprefixからholdを裁定できない');
|
|
364
|
-
const freezeSequence = state.freeze.sequence;
|
|
365
|
-
// seedは現plan epochのconflictだけにする(過去epochで処理済みのconflictを
|
|
366
|
-
// 再seedしない。二度目以降のfreezeでの再混入防止)。
|
|
367
|
-
const currentEpochConflictSequences = new Set(events
|
|
368
|
-
.filter((event) => event.kind === 'conflict_found' && event.plan_epoch === plan.plan_epoch)
|
|
369
|
-
.map((event) => event.sequence));
|
|
370
|
-
const frozenConflicts = state.conflicts.filter((conflict) => (
|
|
371
|
-
conflict.sequence <= freezeSequence && currentEpochConflictSequences.has(conflict.sequence)
|
|
372
|
-
));
|
|
373
|
-
if (frozenConflicts.length === 0) fail('frozen prefix内にconflict findingがない');
|
|
374
|
-
|
|
375
|
-
const seed = frozenConflicts.flatMap((conflict) => conflict.todo_ids ?? []);
|
|
376
|
-
const closure = computeAffectedClosure(plan, manifests, seed);
|
|
377
|
-
|
|
378
|
-
// frozen prefix時点のrunning集合(producer独自計算)。
|
|
379
|
-
const frozenRunning = new Set();
|
|
380
|
-
for (const event of events) {
|
|
381
|
-
if (event.sequence > freezeSequence) continue;
|
|
382
|
-
if (event.kind === 'executor_dispatched' && event.subject?.kind === 'todo') {
|
|
383
|
-
frozenRunning.add(event.subject.ref);
|
|
384
|
-
}
|
|
385
|
-
if ((event.kind === 'receipt_accepted' || event.kind === 'executor_terminal')
|
|
386
|
-
&& event.subject?.kind === 'todo') {
|
|
387
|
-
frozenRunning.delete(event.subject.ref);
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
const conflictEventDigests = events
|
|
392
|
-
.filter((event) => event.kind === 'conflict_found' && event.sequence <= freezeSequence)
|
|
393
|
-
.map((event) => event.event_digest);
|
|
394
|
-
|
|
395
|
-
let next = [...events];
|
|
396
|
-
const holdSet = new Set();
|
|
397
|
-
const continueSet = new Set();
|
|
398
|
-
const witnessFailures = {};
|
|
399
|
-
|
|
400
|
-
// 競合findingが指すpath集合(carry-over候補の非交差検査に使う)。
|
|
401
|
-
const findingPaths = new Set(frozenConflicts.flatMap((conflict) => (
|
|
402
|
-
typeof conflict.path === 'string' ? [conflict.path] : (conflict.paths ?? [])
|
|
403
|
-
)));
|
|
404
|
-
|
|
405
|
-
for (const todoId of sorted(frozenRunning)) {
|
|
406
|
-
if (closure.has(todoId)) {
|
|
407
|
-
holdSet.add(todoId);
|
|
408
|
-
continue;
|
|
409
|
-
}
|
|
410
|
-
// closure外のin-flight TODO: witnessを構築・実証できた場合だけcontinue。
|
|
411
|
-
const packet = packets[todoId];
|
|
412
|
-
if (packet === undefined || manifests[todoId] === undefined) {
|
|
413
|
-
holdSet.add(todoId);
|
|
414
|
-
witnessFailures[todoId] = ['missing_packet_or_manifest'];
|
|
415
|
-
continue;
|
|
416
|
-
}
|
|
417
|
-
// freeze後に当該TODOの未取り込みdiff/receipt eventが存在するなら
|
|
418
|
-
// carry-over不能(Decision 7.2「freeze後に未取り込みdiff eventが存在しない」)。
|
|
419
|
-
const postFreezeEvents = events.some((event) => (
|
|
420
|
-
event.sequence > freezeSequence
|
|
421
|
-
&& event.subject?.kind === 'todo'
|
|
422
|
-
&& event.subject.ref === todoId
|
|
423
|
-
&& ['checkpoint_observed', 'receipt_recorded'].includes(event.kind)
|
|
424
|
-
&& event.payload?.barrier_final !== true
|
|
425
|
-
));
|
|
426
|
-
if (postFreezeEvents) {
|
|
427
|
-
holdSet.add(todoId);
|
|
428
|
-
witnessFailures[todoId] = ['post_freeze_events'];
|
|
429
|
-
continue;
|
|
430
|
-
}
|
|
431
|
-
// 競合finding pathと当該TODOのdeclared write/観測pathが交差するなら
|
|
432
|
-
// 非交差を証明できない(Decision 7.2の changed scope 非交差条件)。
|
|
433
|
-
const declaredWrites = manifests[todoId].writes ?? [];
|
|
434
|
-
const observedPaths = state.checkpoints
|
|
435
|
-
.filter((entry) => entry.todo_id === todoId && entry.sequence <= freezeSequence)
|
|
436
|
-
.flatMap((entry) => (entry.payload?.diff?.entries ?? []).map(({ path }) => path));
|
|
437
|
-
const intersects = [...findingPaths].some((findingPath) => (
|
|
438
|
-
declaredWrites.some((declared) => (
|
|
439
|
-
declared === findingPath || (declared.endsWith('/') && findingPath.startsWith(declared))
|
|
440
|
-
))
|
|
441
|
-
|| observedPaths.includes(findingPath)
|
|
442
|
-
));
|
|
443
|
-
if (intersects) {
|
|
444
|
-
holdSet.add(todoId);
|
|
445
|
-
witnessFailures[todoId] = ['finding_scope_overlap'];
|
|
446
|
-
continue;
|
|
447
|
-
}
|
|
448
|
-
const receiptBindings = state.receipts
|
|
449
|
-
.filter((receipt) => (
|
|
450
|
-
receipt.todo_id === todoId
|
|
451
|
-
&& receipt.sequence <= freezeSequence
|
|
452
|
-
&& receipt.accepted_sequence === null
|
|
453
|
-
&& receipt.rejected_sequence === null
|
|
454
|
-
))
|
|
455
|
-
.map((receipt) => ({
|
|
456
|
-
receipt_id: receipt.receipt_id,
|
|
457
|
-
checkpoint_digest: receipt.payload?.checkpoint_digest ?? '0'.repeat(64),
|
|
458
|
-
recorded_sequence: receipt.sequence,
|
|
459
|
-
within_frozen_prefix: true,
|
|
460
|
-
}));
|
|
461
|
-
const sources = {
|
|
462
|
-
todo_input: request.manual_witness[todoId],
|
|
463
|
-
boundary_manifest: manifests[todoId],
|
|
464
|
-
validator: packet.verifier_refs,
|
|
465
|
-
context_content: {
|
|
466
|
-
todo_id: packet.todo_id,
|
|
467
|
-
task_ref: packet.task_ref,
|
|
468
|
-
scope: packet.scope,
|
|
469
|
-
base_sha: packet.base_sha,
|
|
470
|
-
verifier_refs: packet.verifier_refs,
|
|
471
|
-
forbidden_operations: packet.forbidden_operations,
|
|
472
|
-
},
|
|
473
|
-
};
|
|
474
|
-
const built = buildCarryOverWitness({
|
|
475
|
-
todoId,
|
|
476
|
-
predecessorEpoch: plan.plan_epoch,
|
|
477
|
-
successorEpoch: plan.plan_epoch + 1,
|
|
478
|
-
sources,
|
|
479
|
-
nonOverlapEvidence: conflictEventDigests.map((digest) => `conflict_found#${digest.slice(0, 16)}`),
|
|
480
|
-
receiptBindings,
|
|
481
|
-
});
|
|
482
|
-
if (built.witness === null) {
|
|
483
|
-
holdSet.add(todoId);
|
|
484
|
-
witnessFailures[todoId] = built.reasons;
|
|
485
|
-
continue;
|
|
486
|
-
}
|
|
487
|
-
next.push(buildNextRunEvent({
|
|
488
|
-
events: next,
|
|
489
|
-
runId,
|
|
490
|
-
kind: 'carry_over_witnessed',
|
|
491
|
-
planEpoch: plan.plan_epoch,
|
|
492
|
-
subject: { kind: 'todo', ref: todoId },
|
|
493
|
-
payload: { witness_digest: built.witness.witness_digest, witness: built.witness },
|
|
494
|
-
recordedAt,
|
|
495
|
-
}));
|
|
496
|
-
continueSet.add(todoId);
|
|
497
|
-
}
|
|
498
|
-
for (const todoId of closure) {
|
|
499
|
-
if (!continueSet.has(todoId)) holdSet.add(todoId);
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
const holdDecision = {
|
|
503
|
-
schema: 'lattice.hold_decision.v1',
|
|
504
|
-
decision_id: `hold-${runId}-seq${freezeSequence}`,
|
|
505
|
-
finding: structuredClone(frozenConflicts.at(-1)),
|
|
506
|
-
frozen_prefix_digest: state.freeze.frozen_prefix_digest ?? digestArtifact(
|
|
507
|
-
events.filter((event) => event.sequence <= freezeSequence).map((event) => event.event_digest),
|
|
508
|
-
),
|
|
509
|
-
affected_closure: sorted(closure),
|
|
510
|
-
hold_set: sorted(holdSet),
|
|
511
|
-
continue_set: sorted(continueSet),
|
|
512
|
-
evidence_digests: conflictEventDigests,
|
|
513
|
-
};
|
|
514
|
-
holdDecision.decision_digest = selfDigest(holdDecision, 'decision_digest');
|
|
515
|
-
if (!validateHoldDecision(holdDecision)) fail('hold decisionがcontractを満たさない');
|
|
516
|
-
|
|
517
|
-
next.push(buildNextRunEvent({
|
|
518
|
-
events: next,
|
|
519
|
-
runId,
|
|
520
|
-
kind: 'hold_decided',
|
|
521
|
-
planEpoch: plan.plan_epoch,
|
|
522
|
-
subject: { kind: 'runtime_plan', ref: plan.plan_ref },
|
|
523
|
-
payload: structuredClone(holdDecision),
|
|
524
|
-
recordedAt,
|
|
525
|
-
}));
|
|
526
|
-
|
|
527
|
-
// 独立verifierとのexact一致を自己検査する(divergenceはfail loud)。
|
|
528
|
-
const recomputed = recomputeHoldDecision({ plan, events: next, manifests });
|
|
529
|
-
if (JSON.stringify(recomputed.hold_set) !== JSON.stringify(holdDecision.hold_set)
|
|
530
|
-
|| JSON.stringify(recomputed.continue_set) !== JSON.stringify(holdDecision.continue_set)) {
|
|
531
|
-
fail(`hold裁定がverifier再計算と一致しない: producer=${JSON.stringify({
|
|
532
|
-
hold: holdDecision.hold_set, continue: holdDecision.continue_set,
|
|
533
|
-
})} verifier=${JSON.stringify({ hold: recomputed.hold_set, continue: recomputed.continue_set })}`);
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
return { events: next, holdDecision, witnessFailures };
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
/**
|
|
540
|
-
* 競合findingをtreatment laneへ送る(Decision 7.6)。
|
|
541
|
-
* predeclared treatmentがfindingのpath集合を覆う場合だけseam laneを返し、
|
|
542
|
-
* それ以外(shared state/effect・未宣言path競合)はintentional serialにする。
|
|
543
|
-
*/
|
|
544
|
-
/**
|
|
545
|
-
* 同じ競合が何epochにわたって観測されたかを数える。
|
|
546
|
-
*
|
|
547
|
-
* 過去epochのconflictを再seedしないguardは既に在るが、**新しく観測された同じ競合**は毎epoch
|
|
548
|
-
* seedされる。原因が続く限り「hold→再計画→再開→また同じ競合」が繰り返せる。
|
|
549
|
-
* 誤帰属でも、scope違反を繰り返すworkerでも、変換で解けない競合でも同じことが起きる。
|
|
550
|
-
*
|
|
551
|
-
* 鍵は種別・資源・関与task対である。plan_epochで数えるのは、同一epoch内の複数回観測を
|
|
552
|
-
* 繰り返しと数えないためで、再計画を1回挟んで再び現れたことだけを繰り返しとする。
|
|
553
|
-
*/
|
|
554
|
-
export function countConflictRecurrence(events = []) {
|
|
555
|
-
const epochsByKey = new Map();
|
|
556
|
-
for (const event of events) {
|
|
557
|
-
if (event?.kind !== 'conflict_found') continue;
|
|
558
|
-
const finding = event.payload ?? {};
|
|
559
|
-
if (typeof finding.kind !== 'string' || !Array.isArray(finding.todo_ids)) continue;
|
|
560
|
-
const key = [
|
|
561
|
-
finding.kind,
|
|
562
|
-
typeof finding.path === 'string' ? finding.path : '',
|
|
563
|
-
[...finding.todo_ids].sort(compareText).join(','),
|
|
564
|
-
].join('\u0000');
|
|
565
|
-
if (!epochsByKey.has(key)) epochsByKey.set(key, new Set());
|
|
566
|
-
epochsByKey.get(key).add(event.plan_epoch);
|
|
567
|
-
}
|
|
568
|
-
return epochsByKey;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
/**
|
|
572
|
-
* 再計画で解けていない競合。1つでもあれば、もう一度同じ処置を試しても収束しない。
|
|
573
|
-
*
|
|
574
|
-
* 既定の閾値を3とするのは、1回目は通常の競合、2回目は再計画が効かなかった可能性(順序の綾を
|
|
575
|
-
* 含む)、3回目で「同じことが繰り返されている」と言えるためである。直列化で誤魔化さない——
|
|
576
|
-
* 誤帰属が原因なら直列化しても解けず、解けないことを解けたように見せることになる。
|
|
577
|
-
*/
|
|
578
|
-
export const NON_CONVERGENT_EPOCH_THRESHOLD = 3;
|
|
579
|
-
|
|
580
|
-
export function detectNonConvergentConflicts(options = {}) {
|
|
581
|
-
if (!exactRecord(options, ['events']) && !exactRecord(options, ['events', 'threshold'])) {
|
|
582
|
-
fail('detectNonConvergentConflicts optionsがexact shapeでない');
|
|
583
|
-
}
|
|
584
|
-
const { events, threshold = NON_CONVERGENT_EPOCH_THRESHOLD } = options;
|
|
585
|
-
if (!Array.isArray(events)) fail('eventsがarrayでない');
|
|
586
|
-
if (!Number.isSafeInteger(threshold) || threshold < 2) fail('thresholdが2以上の整数でない');
|
|
587
|
-
const recurrence = countConflictRecurrence(events);
|
|
588
|
-
const entries = [];
|
|
589
|
-
for (const [key, epochs] of recurrence) {
|
|
590
|
-
if (epochs.size < threshold) continue;
|
|
591
|
-
const [kind, resource, todoIds] = key.split('\u0000');
|
|
592
|
-
entries.push({
|
|
593
|
-
kind,
|
|
594
|
-
resource,
|
|
595
|
-
todo_ids: todoIds === '' ? [] : todoIds.split(','),
|
|
596
|
-
epochs: [...epochs].sort((left, right) => left - right),
|
|
597
|
-
});
|
|
598
|
-
}
|
|
599
|
-
return entries.sort((left, right) => compareText(
|
|
600
|
-
`${left.kind}\u0000${left.resource}\u0000${left.todo_ids.join(',')}`,
|
|
601
|
-
`${right.kind}\u0000${right.resource}\u0000${right.todo_ids.join(',')}`,
|
|
602
|
-
));
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/**
|
|
606
|
-
* 係争資源が構造的に切れる種類かを返す(ADR 0144の続き、請求項8の入口判定)。
|
|
607
|
-
*
|
|
608
|
-
* pathやsymbolは面を分ければ別々に所有できる。共有stateや外部effectは分けられない——
|
|
609
|
-
* 変換をどれだけ工夫しても同じ資源に触り続ける。**これは「切れる」ではなく「切れる種類だ」で
|
|
610
|
-
* あって、実際に切れるかは試して初めて分かる。**
|
|
611
|
-
*/
|
|
612
|
-
export function severabilityOfRuntimeFinding(finding) {
|
|
613
|
-
return severabilityOfConflictKind(typeof finding?.path === 'string' ? 'path' : 'state');
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* 競合をどちらの処置へ運ぶか(請求項7=直列化/請求項8=変換)。
|
|
618
|
-
*
|
|
619
|
-
* `seam_transform`を返すのは事前宣言済みtreatmentが係争pathを覆っている時だけである。
|
|
620
|
-
* それ以外の既定は直列化だが、**それは「変換が不可能」という意味ではない**。実行時に初めて
|
|
621
|
-
* 見つかった競合には事前宣言が無いので、既定だけを見ると請求項8へ行く道が無いように見える。
|
|
622
|
-
*
|
|
623
|
-
* そこで`severability`と`transform_attemptable`を併せて返す。装置が言えるのは「切れる種類の
|
|
624
|
-
* 資源か」までで、**実際の難しさは変換を試して五条件で測る**(`run seam resolve`)。試すかどうかは
|
|
625
|
-
* 費用のかかる判断なので装置が決めない——隔離worktreeでの変換、focused test、再indexを毎回
|
|
626
|
-
* 走らせるかは、操作するAIが持つ文脈で決める(AGENTS.md「装置の境界にAIを含める」)。
|
|
627
|
-
*/
|
|
628
|
-
export function routeConflictTreatment(options = {}) {
|
|
629
|
-
if (!exactRecord(options, ['finding', 'predeclaredTreatments'])) {
|
|
630
|
-
fail('routeConflictTreatment optionsがexact shapeでない');
|
|
631
|
-
}
|
|
632
|
-
const { finding, predeclaredTreatments } = options;
|
|
633
|
-
if (!plainRecord(finding) || typeof finding.kind !== 'string') fail('findingが不正');
|
|
634
|
-
const severability = severabilityOfRuntimeFinding(finding);
|
|
635
|
-
if (finding.kind === 'observed_write_conflict' && typeof finding.path === 'string') {
|
|
636
|
-
for (const treatment of predeclaredTreatments) {
|
|
637
|
-
if (Array.isArray(treatment.covered_paths) && treatment.covered_paths.includes(finding.path)) {
|
|
638
|
-
return { lane: 'seam_transform', treatment: structuredClone(treatment),
|
|
639
|
-
severability, transform_attemptable: true };
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
return { lane: 'intentional_serial', treatment: null,
|
|
644
|
-
severability, transform_attemptable: severability === 'code_seam' };
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* hold決定後のplan vN+1をcompileする。carried-over TODOへはepoch rebind packet
|
|
649
|
-
* (content不変・epoch/plan refのみ更新)、hold TODOへは新plan_ref由来の
|
|
650
|
-
* 新context packetを発行し、旧contextを失効する。rebind/prepare ack、epoch pointer、
|
|
651
|
-
* controller ready/release ack、中央gate commit前にはepoch_rebound/intake_resumedを発行しない。
|
|
652
|
-
*
|
|
653
|
-
* baseはここでは動かさない。変換で構造が変わった時に後継baseを決めるのは後継run requestで
|
|
654
|
-
* あり、それが本当に変換を含むかは`verifySeamSplitSuccessor`が見る(ADR 0141)。
|
|
655
|
-
*/
|
|
656
|
-
export function recompileNextEpochPlan(options = {}) {
|
|
657
|
-
if (!exactRecord(options, [
|
|
658
|
-
'runId', 'request', 'plan', 'manifests', 'packets', 'events', 'holdDecision',
|
|
659
|
-
'additionalConflicts', 'recordedAt',
|
|
660
|
-
])) {
|
|
661
|
-
fail('recompileNextEpochPlan optionsがexact shapeでない');
|
|
662
|
-
}
|
|
663
|
-
const {
|
|
664
|
-
runId, request, plan, manifests, packets, events, holdDecision, additionalConflicts, recordedAt,
|
|
665
|
-
} = options;
|
|
666
|
-
if (!validateRuntimePlan(plan)) fail('planがruntime_plan.v1 contractを満たさない');
|
|
667
|
-
if (!validateHoldDecision(holdDecision)) fail('holdDecisionがcontractを満たさない');
|
|
668
|
-
if (!Array.isArray(additionalConflicts)) fail('additionalConflictsがarrayではない');
|
|
669
|
-
// 同じ競合が閾値のepoch数だけ繰り返しているなら、もう一度同じ処置を試しても収束しない。
|
|
670
|
-
// 直列化やもう1周で誤魔化さず、解けていないことをtypedに述べて止める。
|
|
671
|
-
const nonConvergent = detectNonConvergentConflicts({ events });
|
|
672
|
-
if (nonConvergent.length > 0) {
|
|
673
|
-
fail(`再計画で解けていない競合がある(非収束): ${nonConvergent
|
|
674
|
-
.map((entry) => `${entry.kind}:${entry.resource}:${entry.todo_ids.join(',')}@${entry.epochs.join('/')}`)
|
|
675
|
-
.join(' ')}`);
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
const state = projectRuntimeState({ events });
|
|
679
|
-
if (state.freeze === null) fail('freeze中でないprefixからrecompileできない');
|
|
680
|
-
|
|
681
|
-
// 新planは追記でなく全体を再発行する(plan version barrier)。
|
|
682
|
-
const conflictKeys = new Set(plan.conflicts.map((conflict) => (
|
|
683
|
-
`${[...conflict.todo_ids].sort().join(',')}|${conflict.resource_id}`
|
|
684
|
-
)));
|
|
685
|
-
const mergedConflicts = [...plan.conflicts.map((conflict) => structuredClone(conflict))];
|
|
686
|
-
for (const conflict of additionalConflicts) {
|
|
687
|
-
if (!plainRecord(conflict) || !Array.isArray(conflict.todo_ids) || typeof conflict.resource_id !== 'string') {
|
|
688
|
-
fail('additional conflictが不正');
|
|
689
|
-
}
|
|
690
|
-
const key = `${[...conflict.todo_ids].sort().join(',')}|${conflict.resource_id}`;
|
|
691
|
-
if (conflictKeys.has(key)) continue;
|
|
692
|
-
conflictKeys.add(key);
|
|
693
|
-
mergedConflicts.push({ todo_ids: [...conflict.todo_ids].sort(), resource_id: conflict.resource_id });
|
|
694
|
-
}
|
|
695
|
-
mergedConflicts.sort((left, right) => (
|
|
696
|
-
(left.todo_ids[0] < right.todo_ids[0] ? -1 : left.todo_ids[0] > right.todo_ids[0] ? 1 : 0)
|
|
697
|
-
|| (left.todo_ids[1] < right.todo_ids[1] ? -1 : left.todo_ids[1] > right.todo_ids[1] ? 1 : 0)
|
|
698
|
-
|| (left.resource_id < right.resource_id ? -1 : 1)
|
|
699
|
-
));
|
|
700
|
-
|
|
701
|
-
const newEpoch = plan.plan_epoch + 1;
|
|
702
|
-
const newPlanRef = `plan-${request.request_id}-e${newEpoch}`;
|
|
703
|
-
const acceptedCheckpoints = state.receipts
|
|
704
|
-
.filter((receipt) => receipt.accepted_sequence !== null)
|
|
705
|
-
.map((receipt) => receipt.payload?.checkpoint_digest)
|
|
706
|
-
.filter((digest) => typeof digest === 'string');
|
|
707
|
-
|
|
708
|
-
const newPlan = {
|
|
709
|
-
schema: 'lattice.runtime_plan.v1',
|
|
710
|
-
plan_ref: newPlanRef,
|
|
711
|
-
plan_epoch: newEpoch,
|
|
712
|
-
request_digest: request.request_digest,
|
|
713
|
-
base_sha: plan.base_sha,
|
|
714
|
-
nodes: structuredClone(plan.nodes),
|
|
715
|
-
precedence: structuredClone(plan.precedence),
|
|
716
|
-
conflicts: mergedConflicts,
|
|
717
|
-
capacity: structuredClone(plan.capacity),
|
|
718
|
-
manifest_digests: structuredClone(plan.manifest_digests),
|
|
719
|
-
claim: { mode: 'exact_minimum' },
|
|
720
|
-
predecessor_refs: [plan.plan_ref, ...acceptedCheckpoints.map((digest) => `checkpoint:${digest}`)],
|
|
721
|
-
};
|
|
722
|
-
newPlan.plan_digest = selfDigest(newPlan, 'plan_digest');
|
|
723
|
-
if (!validateRuntimePlan(newPlan)) fail('新planがruntime_plan.v1 contractを満たさない');
|
|
724
|
-
if (!verifyRuntimePlanBinding({ plan: newPlan, request })) fail('新planがrequestへbindできない');
|
|
725
|
-
|
|
726
|
-
let next = [...events];
|
|
727
|
-
|
|
728
|
-
// hold集合のrunning executorを旧epochで終端する(放棄の証拠化。runningから
|
|
729
|
-
// 外れることで、新epochでのredispatchが可能になる)。
|
|
730
|
-
const runningSet = new Set(state.running);
|
|
731
|
-
for (const todoId of holdDecision.hold_set) {
|
|
732
|
-
if (!runningSet.has(todoId)) continue;
|
|
733
|
-
const dispatch = state.dispatches[todoId];
|
|
734
|
-
next.push(buildNextRunEvent({
|
|
735
|
-
events: next,
|
|
736
|
-
runId,
|
|
737
|
-
kind: 'executor_terminal',
|
|
738
|
-
planEpoch: plan.plan_epoch,
|
|
739
|
-
subject: { kind: 'todo', ref: todoId },
|
|
740
|
-
payload: {
|
|
741
|
-
executor_handle: dispatch?.payload?.executor_handle ?? 'unknown',
|
|
742
|
-
terminal_state: 'context_invalidated',
|
|
743
|
-
},
|
|
744
|
-
recordedAt,
|
|
745
|
-
}));
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
next.push(buildNextRunEvent({
|
|
749
|
-
events: next,
|
|
750
|
-
runId,
|
|
751
|
-
kind: 'plan_recompiled',
|
|
752
|
-
planEpoch: newEpoch,
|
|
753
|
-
subject: { kind: 'runtime_plan', ref: newPlanRef },
|
|
754
|
-
payload: {
|
|
755
|
-
old_plan_ref: plan.plan_ref,
|
|
756
|
-
new_plan_digest: newPlan.plan_digest,
|
|
757
|
-
hold_decision_digest: holdDecision.decision_digest,
|
|
758
|
-
},
|
|
759
|
-
recordedAt,
|
|
760
|
-
}));
|
|
761
|
-
|
|
762
|
-
// 失効するのは停止・再計画対象だけ。closure外のrunning TODOはorigin bindingのまま
|
|
763
|
-
// 継続するため、contextもpartial patchも無効化しない。
|
|
764
|
-
for (const todoId of sorted(holdDecision.hold_set)) {
|
|
765
|
-
next.push(buildNextRunEvent({
|
|
766
|
-
events: next,
|
|
767
|
-
runId,
|
|
768
|
-
kind: 'context_invalidated',
|
|
769
|
-
planEpoch: newEpoch,
|
|
770
|
-
subject: { kind: 'todo', ref: todoId },
|
|
771
|
-
payload: {
|
|
772
|
-
old_plan_ref: plan.plan_ref,
|
|
773
|
-
invalidated: ['agent_context', 'partial_patch', 'interface_assumption', 'boundary_evidence'],
|
|
774
|
-
reauthorized_via: 'redispatch',
|
|
775
|
-
},
|
|
776
|
-
recordedAt,
|
|
777
|
-
}));
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
// carried-over TODOがrecompileで追加されるconflictの当事者なら設計矛盾
|
|
781
|
-
// (closureに入っているべき)。fail loudで止める。
|
|
782
|
-
for (const conflict of additionalConflicts) {
|
|
783
|
-
for (const todoId of conflict.todo_ids ?? []) {
|
|
784
|
-
if (holdDecision.continue_set.includes(todoId)) {
|
|
785
|
-
fail(`carried-over TODOが追加conflictの当事者になっている: ${todoId}`);
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// freeze時点のfrozen prefix境界(authorized checkpoint lineageの基準)。
|
|
791
|
-
const freezeSequenceForLineage = events
|
|
792
|
-
.filter((event) => event.kind === 'intake_frozen' && event.plan_epoch === plan.plan_epoch)
|
|
793
|
-
.map((event) => event.sequence)
|
|
794
|
-
.sort((left, right) => left - right)[0] ?? null;
|
|
795
|
-
|
|
796
|
-
// restart時は全process barrierになるため、その場合だけcarry-overを現epochへ復元できる
|
|
797
|
-
// rebind packetをbundleへ残す。通常のrecompileでは使わずorigin bindingを維持する。
|
|
798
|
-
const rebindPackets = {};
|
|
799
|
-
for (const todoId of holdDecision.continue_set) {
|
|
800
|
-
const packet = packets[todoId];
|
|
801
|
-
const dispatch = state.dispatches[todoId];
|
|
802
|
-
const witnessRecord = state.witnesses[todoId];
|
|
803
|
-
if (packet === undefined || dispatch === undefined || witnessRecord === undefined) {
|
|
804
|
-
fail(`carried-over TODOのpacket/dispatch/witnessが欠落: ${todoId}`);
|
|
805
|
-
}
|
|
806
|
-
// authorized checkpointはfrozen prefix内の最後の観測checkpoint。checkpointが
|
|
807
|
-
// 一件もないcarry-overはgenesis sentinel(64桁ゼロ、RC3-J ADRで正式裁定予定)。
|
|
808
|
-
const frozenCheckpoints = state.checkpoints.filter((entry) => (
|
|
809
|
-
entry.todo_id === todoId
|
|
810
|
-
&& (freezeSequenceForLineage === null || entry.sequence <= freezeSequenceForLineage)
|
|
811
|
-
));
|
|
812
|
-
const authorizedCheckpointDigest = frozenCheckpoints.length > 0
|
|
813
|
-
? frozenCheckpoints[frozenCheckpoints.length - 1].payload?.checkpoint_digest ?? '0'.repeat(64)
|
|
814
|
-
: '0'.repeat(64);
|
|
815
|
-
const rebind = {
|
|
816
|
-
schema: 'lattice.epoch_rebind_packet.v1',
|
|
817
|
-
packet_id: `${newPlanRef}-rebind-${todoId}`,
|
|
818
|
-
todo_id: todoId,
|
|
819
|
-
executor_handle: dispatch.payload.executor_handle,
|
|
820
|
-
worktree_id: dispatch.payload.worktree_id,
|
|
821
|
-
witness_digest: witnessRecord.payload.witness_digest,
|
|
822
|
-
context_content_digest: packet.context_content_digest,
|
|
823
|
-
authorized_checkpoint_digest: authorizedCheckpointDigest,
|
|
824
|
-
old_plan_ref: plan.plan_ref,
|
|
825
|
-
new_plan_ref: newPlanRef,
|
|
826
|
-
new_plan_epoch: newEpoch,
|
|
827
|
-
};
|
|
828
|
-
rebind.packet_digest = selfDigest(rebind, 'packet_digest');
|
|
829
|
-
if (!validateEpochRebindPacket(rebind)) fail(`rebind packetがcontractを満たさない: ${todoId}`);
|
|
830
|
-
if (rebind.context_content_digest !== computeContextContentDigest({
|
|
831
|
-
todo_id: packet.todo_id,
|
|
832
|
-
task_ref: packet.task_ref,
|
|
833
|
-
scope: packet.scope,
|
|
834
|
-
base_sha: packet.base_sha,
|
|
835
|
-
verifier_refs: packet.verifier_refs,
|
|
836
|
-
forbidden_operations: packet.forbidden_operations,
|
|
837
|
-
})) {
|
|
838
|
-
fail(`rebindのcontent digestがvN packet contentと一致しない: ${todoId}`);
|
|
839
|
-
}
|
|
840
|
-
rebindPackets[todoId] = rebind;
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
// redispatch TODOへは新plan_ref由来の別content packetを発行する。
|
|
844
|
-
const allNewPackets = buildExecutorPackets({ plan: newPlan, manifests });
|
|
845
|
-
const redispatchPackets = Object.fromEntries(
|
|
846
|
-
holdDecision.hold_set.map((todoId) => [todoId, allNewPackets[todoId]]),
|
|
847
|
-
);
|
|
848
|
-
|
|
849
|
-
const planDiff = {
|
|
850
|
-
schema: 'lattice.runtime_plan_diff.v1',
|
|
851
|
-
old_plan_ref: plan.plan_ref,
|
|
852
|
-
new_plan_ref: newPlanRef,
|
|
853
|
-
accepted_checkpoints: sorted(acceptedCheckpoints),
|
|
854
|
-
invalidated_contexts: [...holdDecision.hold_set],
|
|
855
|
-
carried_over: [...holdDecision.continue_set],
|
|
856
|
-
redispatched: [...holdDecision.hold_set],
|
|
857
|
-
node_edge_diff: {
|
|
858
|
-
added_nodes: [],
|
|
859
|
-
removed_nodes: [],
|
|
860
|
-
added_conflicts: mergedConflicts.length - plan.conflicts.length,
|
|
861
|
-
},
|
|
862
|
-
};
|
|
863
|
-
planDiff.diff_digest = selfDigest(planDiff, 'diff_digest');
|
|
864
|
-
if (!validateRuntimePlanDiff(planDiff)) fail('plan diffがcontractを満たさない');
|
|
865
|
-
|
|
866
|
-
return {
|
|
867
|
-
events: next,
|
|
868
|
-
newPlan,
|
|
869
|
-
planDiff,
|
|
870
|
-
rebindPackets,
|
|
871
|
-
redispatchPackets,
|
|
872
|
-
};
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
/**
|
|
876
|
-
* controller direct ackと中央gate commitが全件揃った後だけrun eventを公開する。
|
|
877
|
-
* producer compileとは分離し、ack前の呼出しは一切のpartial eventを返さない。
|
|
878
|
-
*/
|
|
879
|
-
export function finalizeRecompileActivation(options = {}) {
|
|
880
|
-
if (!exactRecord(options, ['runId', 'events', 'plan', 'planDiff', 'rebindPackets',
|
|
881
|
-
'rebindAcks', 'gateDigest', 'gateControlEventDigest', 'recordedAt'])) {
|
|
882
|
-
fail('finalizeRecompileActivation optionsがexact shapeでない');
|
|
883
|
-
}
|
|
884
|
-
const { runId, events, plan, planDiff, rebindPackets, rebindAcks, gateDigest,
|
|
885
|
-
gateControlEventDigest, recordedAt } = options;
|
|
886
|
-
if (!validateRuntimePlan(plan) || !validateRuntimePlanDiff(planDiff)
|
|
887
|
-
|| !HEX_DIGEST.test(gateDigest ?? '') || !HEX_DIGEST.test(gateControlEventDigest ?? '')
|
|
888
|
-
|| !plainRecord(rebindPackets) || !plainRecord(rebindAcks)) {
|
|
889
|
-
fail('activation bindingが不正');
|
|
890
|
-
}
|
|
891
|
-
const packetIds = Object.keys(rebindPackets).sort();
|
|
892
|
-
if (canonicalizeArtifact(Object.keys(rebindAcks).sort()) !== canonicalizeArtifact(packetIds)) {
|
|
893
|
-
fail('rebind ack集合がpacket集合とexact一致しない');
|
|
894
|
-
}
|
|
895
|
-
for (const todoId of packetIds) {
|
|
896
|
-
const packet = rebindPackets[todoId];
|
|
897
|
-
const ack = rebindAcks[todoId];
|
|
898
|
-
if (!validateEpochRebindPacket(packet)
|
|
899
|
-
|| !plainRecord(ack) || ack.schema !== 'lattice.executor_epoch_rebind_ack.v1'
|
|
900
|
-
|| ack.todo_id !== todoId || ack.rebind_packet_digest !== packet.packet_digest
|
|
901
|
-
|| ack.successor_epoch !== plan.plan_epoch || !HEX_DIGEST.test(ack.ack_digest ?? '')
|
|
902
|
-
|| !selfDigestValid(ack, 'ack_digest')) fail(`rebind ack bindingが不正: ${todoId}`);
|
|
903
|
-
}
|
|
904
|
-
let next = [...events];
|
|
905
|
-
// 全件を先に検証した後にだけbatchを構築する(partial epoch_rebound禁止)。
|
|
906
|
-
for (const todoId of packetIds) {
|
|
907
|
-
next.push(buildNextRunEvent({ events: next, runId, kind: 'epoch_rebound',
|
|
908
|
-
planEpoch: plan.plan_epoch, subject: { kind: 'todo', ref: todoId },
|
|
909
|
-
payload: structuredClone(rebindPackets[todoId]), recordedAt }));
|
|
910
|
-
}
|
|
911
|
-
next.push(buildNextRunEvent({ events: next, runId, kind: 'intake_resumed',
|
|
912
|
-
planEpoch: plan.plan_epoch, subject: { kind: 'runtime_plan', ref: plan.plan_ref },
|
|
913
|
-
payload: { plan_diff_digest: planDiff.diff_digest, write_gate_digest: gateDigest,
|
|
914
|
-
control_event_digest: gateControlEventDigest }, recordedAt }));
|
|
915
|
-
return { events: next, redispatchTodoIds: [...planDiff.redispatched].sort() };
|
|
916
|
-
}
|
|
1
|
+
import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
|
|
2
|
+
// 切断可能性の写像はtodo側と同じ正本を使う。計画時と実行時で「切れる種類」の定義が
|
|
3
|
+
// 分かれると、同じ資源が段によって別の答えを持つ。
|
|
4
|
+
import { severabilityOfConflictKind } from './todo-independence-contracts.mjs';
|
|
5
|
+
import { buildNextRunEvent, buildExecutorPackets } from './runtime-engine.mjs';
|
|
6
|
+
import { projectRuntimeState } from './runtime-projection.mjs';
|
|
7
|
+
import {
|
|
8
|
+
recomputeHoldDecision,
|
|
9
|
+
verifyCarryOverWitness,
|
|
10
|
+
} from './runtime-decision-verifier.mjs';
|
|
11
|
+
import {
|
|
12
|
+
computeContextContentDigest,
|
|
13
|
+
RUN_REQUEST_SCHEMA,
|
|
14
|
+
selfDigest,
|
|
15
|
+
validateCarryOverWitness,
|
|
16
|
+
validateEpochRebindPacket,
|
|
17
|
+
validateHoldDecision,
|
|
18
|
+
validateRunRequest,
|
|
19
|
+
validateRuntimePlan,
|
|
20
|
+
validateRuntimePlanDiff,
|
|
21
|
+
verifyRuntimePlanBinding,
|
|
22
|
+
} from './runtime-contracts.mjs';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* RC3-G 後発競合のselective holdとplan vN+1 recompile(ADR 0044 Decision 6・7、plan RC3-G)。
|
|
26
|
+
*
|
|
27
|
+
* producer側の裁定実装。affected closure・hold/continue集合は
|
|
28
|
+
* `runtime-decision-verifier.mjs`と独立に計算した上で、保存bytesからの
|
|
29
|
+
* verifier再計算とのexact一致をfail-loudに自己検査する(divergenceは即例外)。
|
|
30
|
+
*
|
|
31
|
+
* - 競合発見時はactive planへ追記しない。frozen prefixを固定してclosureを計算し、
|
|
32
|
+
* closure外のin-flight TODOはcarry-over witnessを実証できた場合だけ継続する。
|
|
33
|
+
* 1 fieldでも証明不能ならholdへ戻す(fail closed、silent fallbackなし)。
|
|
34
|
+
* - carry-overは旧contextの継続利用ではない。content digest不変・epochだけ更新の
|
|
35
|
+
* epoch rebind packetによる、失効後の再認可である(Decision 7.3)。
|
|
36
|
+
* - 旧plan・旧context・partial patchはcontext_invalidated eventで失効し、
|
|
37
|
+
* redispatch TODOへは新plan_ref由来の別contentのpacketを発行する。
|
|
38
|
+
* - irreducible conflictはprecedenceへ偽装せず、unordered conflictのまま
|
|
39
|
+
* intentional serialとして保持する(Decision 7.6)。
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
function fail(reason) {
|
|
43
|
+
throw new TypeError(`hold/recompile契約違反: ${reason}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function plainRecord(value) {
|
|
47
|
+
return value !== null
|
|
48
|
+
&& typeof value === 'object'
|
|
49
|
+
&& !Array.isArray(value)
|
|
50
|
+
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function exactRecord(value, keys) {
|
|
54
|
+
if (!plainRecord(value)) return false;
|
|
55
|
+
const actual = Object.keys(value).sort();
|
|
56
|
+
const expected = [...keys].sort();
|
|
57
|
+
return actual.length === expected.length
|
|
58
|
+
&& actual.every((key, index) => key === expected[index]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sorted(values) {
|
|
62
|
+
return [...values].sort();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sha16(value) {
|
|
66
|
+
return digestArtifact({ path: value }).slice(0, 16);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const WITNESS_KINDS = Object.freeze(['state', 'schema', 'invariant', 'effect', 'external_effect']);
|
|
70
|
+
const HEX_DIGEST = /^[0-9a-f]{64}$/u;
|
|
71
|
+
const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
|
|
72
|
+
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
73
|
+
|
|
74
|
+
function selfDigestValid(value, field) {
|
|
75
|
+
return plainRecord(value) && HEX_DIGEST.test(value[field] ?? '')
|
|
76
|
+
&& selfDigest(value, field) === value[field];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function sortedUnique(values, predicate) {
|
|
80
|
+
return Array.isArray(values) && values.every(predicate)
|
|
81
|
+
&& values.every((value, index) => index === 0
|
|
82
|
+
|| canonicalizeArtifact(values[index - 1]) < canonicalizeArtifact(value));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function primaryFirstUnique(values, predicate) {
|
|
86
|
+
if (!Array.isArray(values) || !values.every(predicate)
|
|
87
|
+
|| new Set(values).size !== values.length) return false;
|
|
88
|
+
const tail = values.slice(1);
|
|
89
|
+
return tail.every((value, index) => index === 0
|
|
90
|
+
|| canonicalizeArtifact(tail[index - 1]) < canonicalizeArtifact(value));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** ADR 0064 Decision 5のfull predecessor→successor mapping。 */
|
|
94
|
+
export function validateRuntimeTaskMigration(value, { predecessorTaskIds = null,
|
|
95
|
+
successorTaskIds = null } = {}) {
|
|
96
|
+
if (!exactRecord(value, ['schema', 'entries', 'migration_digest'])
|
|
97
|
+
|| value.schema !== 'lattice.runtime_task_migration.v1'
|
|
98
|
+
|| !Array.isArray(value.entries) || value.entries.length > 10_000
|
|
99
|
+
|| !selfDigestValid(value, 'migration_digest')) return false;
|
|
100
|
+
const predecessor = [];
|
|
101
|
+
const successorOwners = new Map();
|
|
102
|
+
for (const entry of value.entries) {
|
|
103
|
+
if (!exactRecord(entry, ['predecessor_task_id', 'disposition', 'successor_task_ids',
|
|
104
|
+
'reason', 'evidence_digests'])
|
|
105
|
+
|| !IDENTIFIER.test(entry.predecessor_task_id ?? '')
|
|
106
|
+
|| !['carry', 'replace', 'split', 'retire', 'stay'].includes(entry.disposition)
|
|
107
|
+
|| typeof entry.reason !== 'string' || entry.reason.length === 0
|
|
108
|
+
|| !primaryFirstUnique(entry.successor_task_ids, (id) => IDENTIFIER.test(id))
|
|
109
|
+
|| !sortedUnique(entry.evidence_digests, (digest) => HEX_DIGEST.test(digest))) return false;
|
|
110
|
+
if (['carry', 'stay'].includes(entry.disposition)
|
|
111
|
+
&& canonicalizeArtifact(entry.successor_task_ids) !== canonicalizeArtifact([entry.predecessor_task_id])) return false;
|
|
112
|
+
if (entry.disposition === 'retire' && entry.successor_task_ids.length !== 0) return false;
|
|
113
|
+
if (['replace', 'split'].includes(entry.disposition) && entry.successor_task_ids.length === 0) return false;
|
|
114
|
+
predecessor.push(entry.predecessor_task_id);
|
|
115
|
+
for (const id of entry.successor_task_ids) {
|
|
116
|
+
const owners = successorOwners.get(id) ?? [];
|
|
117
|
+
owners.push(entry.predecessor_task_id);
|
|
118
|
+
successorOwners.set(id, owners);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!sortedUnique(predecessor, (id) => IDENTIFIER.test(id))) return false;
|
|
122
|
+
if ([...successorOwners.values()].some((owners) => owners.length !== 1)) return false;
|
|
123
|
+
if (predecessorTaskIds !== null
|
|
124
|
+
&& canonicalizeArtifact(predecessor) !== canonicalizeArtifact(sorted(predecessorTaskIds))) return false;
|
|
125
|
+
if (successorTaskIds !== null) {
|
|
126
|
+
const mapped = sorted(successorOwners.keys());
|
|
127
|
+
if (canonicalizeArtifact(mapped) !== canonicalizeArtifact(sorted(successorTaskIds))) return false;
|
|
128
|
+
}
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function validateRunRequestV2(value) {
|
|
133
|
+
if (!exactRecord(value, ['schema', 'request_id', 'repo', 'capacity', 'todos', 'manual_witness',
|
|
134
|
+
'sensor_query_set', 'executor_capability', 'claim_mode', 'predecessor_request_digest',
|
|
135
|
+
'task_migration_digest', 'request_digest'])
|
|
136
|
+
|| value.schema !== 'lattice.run_request.v2'
|
|
137
|
+
|| !HEX_DIGEST.test(value.predecessor_request_digest ?? '')
|
|
138
|
+
|| !HEX_DIGEST.test(value.task_migration_digest ?? '')
|
|
139
|
+
|| !selfDigestValid(value, 'request_digest')) return false;
|
|
140
|
+
const projected = {
|
|
141
|
+
// 後継requestの本体はbase契約と同じ規律で読む。v1へ固定すると、創作境界を持つ
|
|
142
|
+
// 宣言が再計画を跨げない(ADR 0136)。
|
|
143
|
+
schema: RUN_REQUEST_SCHEMA, request_id: value.request_id, repo: value.repo,
|
|
144
|
+
capacity: value.capacity, todos: value.todos, manual_witness: value.manual_witness,
|
|
145
|
+
sensor_query_set: value.sensor_query_set, executor_capability: value.executor_capability,
|
|
146
|
+
claim_mode: value.claim_mode, request_digest: '',
|
|
147
|
+
};
|
|
148
|
+
projected.request_digest = selfDigest(projected, 'request_digest');
|
|
149
|
+
return validateRunRequest(projected);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function validateRuntimeRecompileRequest(value, { predecessorBundle = null,
|
|
153
|
+
frozenEventDigest = null, holdDecisionDigest = null, validatePhaseRevision = null } = {}) {
|
|
154
|
+
if (!exactRecord(value, ['schema', 'request_id', 'run_id', 'predecessor_epoch',
|
|
155
|
+
'frozen_event_digest', 'hold_decision_digest', 'mode', 'reason', 'successor_request',
|
|
156
|
+
'task_migration', 'phase_revision', 'seam_split', 'intentional_serial', 'request_digest'])
|
|
157
|
+
|| value.schema !== 'lattice.runtime_recompile_request.v1'
|
|
158
|
+
|| !IDENTIFIER.test(value.request_id ?? '') || !IDENTIFIER.test(value.run_id ?? '')
|
|
159
|
+
|| !Number.isSafeInteger(value.predecessor_epoch) || value.predecessor_epoch < 1
|
|
160
|
+
|| !HEX_DIGEST.test(value.frozen_event_digest ?? '')
|
|
161
|
+
|| !HEX_DIGEST.test(value.hold_decision_digest ?? '')
|
|
162
|
+
|| !['seam_split', 'intentional_serial'].includes(value.mode)
|
|
163
|
+
|| typeof value.reason !== 'string' || value.reason.length === 0
|
|
164
|
+
|| !validateRunRequestV2(value.successor_request)
|
|
165
|
+
|| !validateRuntimeTaskMigration(value.task_migration, {
|
|
166
|
+
predecessorTaskIds: predecessorBundle?.plan?.nodes?.map(({ todo_id: id }) => id) ?? null,
|
|
167
|
+
successorTaskIds: value.successor_request.todos?.map(({ todo_id: id }) => id) ?? null,
|
|
168
|
+
})
|
|
169
|
+
|| value.successor_request.request_id !== value.run_id
|
|
170
|
+
|| value.successor_request.task_migration_digest !== value.task_migration.migration_digest
|
|
171
|
+
|| !selfDigestValid(value, 'request_digest')) return false;
|
|
172
|
+
if (predecessorBundle !== null
|
|
173
|
+
&& (value.predecessor_epoch !== predecessorBundle.plan_epoch
|
|
174
|
+
|| value.successor_request.predecessor_request_digest !== predecessorBundle.request.request_digest)) return false;
|
|
175
|
+
if (frozenEventDigest !== null && value.frozen_event_digest !== frozenEventDigest) return false;
|
|
176
|
+
if (holdDecisionDigest !== null && value.hold_decision_digest !== holdDecisionDigest) return false;
|
|
177
|
+
if (value.phase_revision === null) {
|
|
178
|
+
// phase revisionを省略できるのは、TODO/source/edge入力とtask identityが完全に不変な時だけ。
|
|
179
|
+
// intentional_serialのruntime conflict edgeはplan overlayでありTODO工程revisionではない。
|
|
180
|
+
if (predecessorBundle !== null) {
|
|
181
|
+
const predecessorRequest = predecessorBundle.request;
|
|
182
|
+
const stableInputs = ['todos', 'manual_witness', 'sensor_query_set'];
|
|
183
|
+
if (stableInputs.some((key) => canonicalizeArtifact(value.successor_request[key])
|
|
184
|
+
!== canonicalizeArtifact(predecessorRequest[key]))) return false;
|
|
185
|
+
if (value.task_migration.entries.some((entry) => !['stay', 'carry'].includes(entry.disposition)
|
|
186
|
+
|| entry.successor_task_ids.length !== 1
|
|
187
|
+
|| entry.successor_task_ids[0] !== entry.predecessor_task_id)) return false;
|
|
188
|
+
}
|
|
189
|
+
} else if (typeof validatePhaseRevision !== 'function'
|
|
190
|
+
|| validatePhaseRevision(structuredClone(value.phase_revision)) !== true
|
|
191
|
+
|| canonicalizeArtifact(value.phase_revision.runtime_task_migration)
|
|
192
|
+
!== canonicalizeArtifact(value.task_migration)) return false;
|
|
193
|
+
if (value.mode === 'seam_split') {
|
|
194
|
+
if (value.intentional_serial !== null || !validateRuntimeSeamSplit(value.seam_split, value)) return false;
|
|
195
|
+
if (value.phase_revision === null && [
|
|
196
|
+
value.seam_split.ownership_diff.added, value.seam_split.ownership_diff.removed,
|
|
197
|
+
value.seam_split.edge_diff.added, value.seam_split.edge_diff.removed,
|
|
198
|
+
].some((entries) => entries.length > 0)) return false;
|
|
199
|
+
} else if (value.seam_split !== null || !validateRuntimeIntentionalSerial(value.intentional_serial, value)) return false;
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function validateRuntimeSeamSplit(value, request) {
|
|
204
|
+
return exactRecord(value, ['schema', 'finding_digest', 'predecessor_task_ids',
|
|
205
|
+
'task_migration_digest', 'ownership_diff', 'edge_diff', 'verifier_refs', 'split_digest'])
|
|
206
|
+
&& value.schema === 'lattice.runtime_seam_split.v1'
|
|
207
|
+
&& HEX_DIGEST.test(value.finding_digest ?? '')
|
|
208
|
+
&& sortedUnique(value.predecessor_task_ids, (id) => IDENTIFIER.test(id))
|
|
209
|
+
&& value.task_migration_digest === request.task_migration.migration_digest
|
|
210
|
+
&& validateOwnershipDiff(value.ownership_diff) && validateEdgeDiff(value.edge_diff)
|
|
211
|
+
&& sortedUnique(value.verifier_refs, (ref) => typeof ref === 'string' && ref.length > 0)
|
|
212
|
+
&& selfDigestValid(value, 'split_digest');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function validateOwnershipDiff(value) {
|
|
216
|
+
const entry = (item) => exactRecord(item, ['resource_id', 'owner_todo_id', 'access_kind'])
|
|
217
|
+
&& IDENTIFIER.test(item.resource_id ?? '') && IDENTIFIER.test(item.owner_todo_id ?? '')
|
|
218
|
+
&& ['read', 'write', 'own'].includes(item.access_kind);
|
|
219
|
+
return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
|
|
220
|
+
&& value.schema === 'lattice.runtime_ownership_diff.v1'
|
|
221
|
+
&& sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
|
|
222
|
+
&& selfDigestValid(value, 'diff_digest');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function validateEdgeDiff(value) {
|
|
226
|
+
const entry = (item) => exactRecord(item, ['from_todo_id', 'to_todo_id', 'kind'])
|
|
227
|
+
&& IDENTIFIER.test(item.from_todo_id ?? '') && IDENTIFIER.test(item.to_todo_id ?? '')
|
|
228
|
+
&& ['hard_dependency', 'conflict'].includes(item.kind);
|
|
229
|
+
return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
|
|
230
|
+
&& value.schema === 'lattice.runtime_edge_diff.v1'
|
|
231
|
+
&& sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
|
|
232
|
+
&& selfDigestValid(value, 'diff_digest');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function validateRuntimeIntentionalSerial(value, request) {
|
|
236
|
+
if (!exactRecord(value, ['schema', 'finding_digest', 'todo_ids', 'resource_id',
|
|
237
|
+
'stay_todo_id', 'reason', 'serial_digest'])
|
|
238
|
+
|| value.schema !== 'lattice.runtime_intentional_serial.v1'
|
|
239
|
+
|| !HEX_DIGEST.test(value.finding_digest ?? '')
|
|
240
|
+
|| !sortedUnique(value.todo_ids, (id) => IDENTIFIER.test(id)) || value.todo_ids.length < 2
|
|
241
|
+
|| !IDENTIFIER.test(value.resource_id ?? '') || !value.todo_ids.includes(value.stay_todo_id)
|
|
242
|
+
|| typeof value.reason !== 'string' || value.reason.length === 0
|
|
243
|
+
|| !selfDigestValid(value, 'serial_digest')) return false;
|
|
244
|
+
const byId = new Map(request.task_migration.entries.map((entry) => [entry.predecessor_task_id, entry]));
|
|
245
|
+
return value.todo_ids.every((id) => byId.has(id))
|
|
246
|
+
&& byId.get(value.stay_todo_id)?.disposition === 'stay';
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function manifestResourceIds(manifest) {
|
|
250
|
+
const ids = new Set(manifest?.resources ?? []);
|
|
251
|
+
for (const effect of manifest?.state_effects ?? []) {
|
|
252
|
+
if (WITNESS_KINDS.includes(effect.kind) && typeof effect.resource_id === 'string') {
|
|
253
|
+
ids.add(effect.resource_id);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return ids;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** producer独自のaffected closure計算(conflict edge伝播+共有resource witness到達)。 */
|
|
260
|
+
function computeAffectedClosure(plan, manifests, seedTodoIds) {
|
|
261
|
+
const closure = new Set(seedTodoIds);
|
|
262
|
+
const byResource = new Map();
|
|
263
|
+
for (const [todoId, manifest] of Object.entries(manifests)) {
|
|
264
|
+
for (const resourceId of manifestResourceIds(manifest)) {
|
|
265
|
+
const members = byResource.get(resourceId) ?? new Set();
|
|
266
|
+
members.add(todoId);
|
|
267
|
+
byResource.set(resourceId, members);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
let changed = true;
|
|
271
|
+
while (changed) {
|
|
272
|
+
changed = false;
|
|
273
|
+
for (const conflict of plan.conflicts) {
|
|
274
|
+
const [left, right] = conflict.todo_ids;
|
|
275
|
+
if (closure.has(left) !== closure.has(right)) {
|
|
276
|
+
closure.add(left);
|
|
277
|
+
closure.add(right);
|
|
278
|
+
changed = true;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// hard predecessorの下流はaffected(前提が失効するため。Decision 6.3)。
|
|
282
|
+
for (const edge of plan.precedence) {
|
|
283
|
+
if (closure.has(edge.from_todo_id) && !closure.has(edge.to_todo_id)) {
|
|
284
|
+
closure.add(edge.to_todo_id);
|
|
285
|
+
changed = true;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
for (const todoId of [...closure]) {
|
|
289
|
+
const manifest = manifests[todoId];
|
|
290
|
+
if (manifest === undefined) continue;
|
|
291
|
+
for (const resourceId of manifestResourceIds(manifest)) {
|
|
292
|
+
for (const member of byResource.get(resourceId) ?? []) {
|
|
293
|
+
if (!closure.has(member)) {
|
|
294
|
+
closure.add(member);
|
|
295
|
+
changed = true;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return closure;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** runtime findingから、停止・再計画する作業群だけを取り出す。 */
|
|
305
|
+
export function affectedTodoIds(plan, manifests, seedTodoIds) {
|
|
306
|
+
return sorted(computeAffectedClosure(plan, manifests, seedTodoIds));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* carry-over witness documentを構築し、提供sourcesに対して自己実証する。
|
|
311
|
+
* 実証できない場合はnullでなくreasons付きの失敗を返す(呼び出し側がholdへ戻す)。
|
|
312
|
+
*/
|
|
313
|
+
export function buildCarryOverWitness(options = {}) {
|
|
314
|
+
if (!exactRecord(options, [
|
|
315
|
+
'todoId', 'predecessorEpoch', 'successorEpoch', 'sources', 'nonOverlapEvidence', 'receiptBindings',
|
|
316
|
+
])) {
|
|
317
|
+
fail('buildCarryOverWitness optionsがexact shapeでない');
|
|
318
|
+
}
|
|
319
|
+
const { todoId, predecessorEpoch, successorEpoch, sources, nonOverlapEvidence, receiptBindings } = options;
|
|
320
|
+
const witness = {
|
|
321
|
+
schema: 'lattice.carry_over_witness.v1',
|
|
322
|
+
witness_id: `witness-${todoId}-e${successorEpoch}`,
|
|
323
|
+
todo_id: todoId,
|
|
324
|
+
predecessor_epoch: predecessorEpoch,
|
|
325
|
+
successor_epoch: successorEpoch,
|
|
326
|
+
invariant_digests: {
|
|
327
|
+
todo_input: digestArtifact(sources.todo_input),
|
|
328
|
+
boundary_manifest: digestArtifact(sources.boundary_manifest),
|
|
329
|
+
validator: digestArtifact(sources.validator),
|
|
330
|
+
context_content: digestArtifact(sources.context_content),
|
|
331
|
+
},
|
|
332
|
+
non_overlap_evidence: [...nonOverlapEvidence],
|
|
333
|
+
receipt_bindings: structuredClone(receiptBindings),
|
|
334
|
+
};
|
|
335
|
+
witness.witness_digest = selfDigest(witness, 'witness_digest');
|
|
336
|
+
// 構築不能はthrowでなくtyped失敗で返す(呼び出し側がholdへ戻すため)。
|
|
337
|
+
if (!validateCarryOverWitness(witness)) {
|
|
338
|
+
return { witness: null, reasons: ['witness_schema', 'carry_over_unprovable'] };
|
|
339
|
+
}
|
|
340
|
+
const verified = verifyCarryOverWitness({ witness, sources });
|
|
341
|
+
if (!verified.valid) {
|
|
342
|
+
return { witness: null, reasons: verified.reasons };
|
|
343
|
+
}
|
|
344
|
+
return { witness, reasons: [] };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* frozen prefixからhold decisionを裁定し、carry_over_witnessed/hold_decided eventを
|
|
349
|
+
* 追記する。continueできるのはwitnessを実証済みのclosure外running TODOだけで、
|
|
350
|
+
* 証明不能TODOはholdへ戻す。裁定はverifier再計算とのexact一致を自己検査する。
|
|
351
|
+
*/
|
|
352
|
+
export function decideHoldAndCarryOver(options = {}) {
|
|
353
|
+
if (!exactRecord(options, [
|
|
354
|
+
'runId', 'request', 'plan', 'manifests', 'packets', 'events', 'recordedAt',
|
|
355
|
+
])) {
|
|
356
|
+
fail('decideHoldAndCarryOver optionsがexact shapeでない');
|
|
357
|
+
}
|
|
358
|
+
const { runId, request, plan, manifests, packets, events, recordedAt } = options;
|
|
359
|
+
if (!validateRuntimePlan(plan)) fail('planがruntime_plan.v1 contractを満たさない');
|
|
360
|
+
if (!validateRunRequest(request)) fail('requestがrun_request.v1 contractを満たさない');
|
|
361
|
+
|
|
362
|
+
const state = projectRuntimeState({ events });
|
|
363
|
+
if (state.freeze === null) fail('freezeされていないprefixからholdを裁定できない');
|
|
364
|
+
const freezeSequence = state.freeze.sequence;
|
|
365
|
+
// seedは現plan epochのconflictだけにする(過去epochで処理済みのconflictを
|
|
366
|
+
// 再seedしない。二度目以降のfreezeでの再混入防止)。
|
|
367
|
+
const currentEpochConflictSequences = new Set(events
|
|
368
|
+
.filter((event) => event.kind === 'conflict_found' && event.plan_epoch === plan.plan_epoch)
|
|
369
|
+
.map((event) => event.sequence));
|
|
370
|
+
const frozenConflicts = state.conflicts.filter((conflict) => (
|
|
371
|
+
conflict.sequence <= freezeSequence && currentEpochConflictSequences.has(conflict.sequence)
|
|
372
|
+
));
|
|
373
|
+
if (frozenConflicts.length === 0) fail('frozen prefix内にconflict findingがない');
|
|
374
|
+
|
|
375
|
+
const seed = frozenConflicts.flatMap((conflict) => conflict.todo_ids ?? []);
|
|
376
|
+
const closure = computeAffectedClosure(plan, manifests, seed);
|
|
377
|
+
|
|
378
|
+
// frozen prefix時点のrunning集合(producer独自計算)。
|
|
379
|
+
const frozenRunning = new Set();
|
|
380
|
+
for (const event of events) {
|
|
381
|
+
if (event.sequence > freezeSequence) continue;
|
|
382
|
+
if (event.kind === 'executor_dispatched' && event.subject?.kind === 'todo') {
|
|
383
|
+
frozenRunning.add(event.subject.ref);
|
|
384
|
+
}
|
|
385
|
+
if ((event.kind === 'receipt_accepted' || event.kind === 'executor_terminal')
|
|
386
|
+
&& event.subject?.kind === 'todo') {
|
|
387
|
+
frozenRunning.delete(event.subject.ref);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const conflictEventDigests = events
|
|
392
|
+
.filter((event) => event.kind === 'conflict_found' && event.sequence <= freezeSequence)
|
|
393
|
+
.map((event) => event.event_digest);
|
|
394
|
+
|
|
395
|
+
let next = [...events];
|
|
396
|
+
const holdSet = new Set();
|
|
397
|
+
const continueSet = new Set();
|
|
398
|
+
const witnessFailures = {};
|
|
399
|
+
|
|
400
|
+
// 競合findingが指すpath集合(carry-over候補の非交差検査に使う)。
|
|
401
|
+
const findingPaths = new Set(frozenConflicts.flatMap((conflict) => (
|
|
402
|
+
typeof conflict.path === 'string' ? [conflict.path] : (conflict.paths ?? [])
|
|
403
|
+
)));
|
|
404
|
+
|
|
405
|
+
for (const todoId of sorted(frozenRunning)) {
|
|
406
|
+
if (closure.has(todoId)) {
|
|
407
|
+
holdSet.add(todoId);
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
// closure外のin-flight TODO: witnessを構築・実証できた場合だけcontinue。
|
|
411
|
+
const packet = packets[todoId];
|
|
412
|
+
if (packet === undefined || manifests[todoId] === undefined) {
|
|
413
|
+
holdSet.add(todoId);
|
|
414
|
+
witnessFailures[todoId] = ['missing_packet_or_manifest'];
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
// freeze後に当該TODOの未取り込みdiff/receipt eventが存在するなら
|
|
418
|
+
// carry-over不能(Decision 7.2「freeze後に未取り込みdiff eventが存在しない」)。
|
|
419
|
+
const postFreezeEvents = events.some((event) => (
|
|
420
|
+
event.sequence > freezeSequence
|
|
421
|
+
&& event.subject?.kind === 'todo'
|
|
422
|
+
&& event.subject.ref === todoId
|
|
423
|
+
&& ['checkpoint_observed', 'receipt_recorded'].includes(event.kind)
|
|
424
|
+
&& event.payload?.barrier_final !== true
|
|
425
|
+
));
|
|
426
|
+
if (postFreezeEvents) {
|
|
427
|
+
holdSet.add(todoId);
|
|
428
|
+
witnessFailures[todoId] = ['post_freeze_events'];
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
// 競合finding pathと当該TODOのdeclared write/観測pathが交差するなら
|
|
432
|
+
// 非交差を証明できない(Decision 7.2の changed scope 非交差条件)。
|
|
433
|
+
const declaredWrites = manifests[todoId].writes ?? [];
|
|
434
|
+
const observedPaths = state.checkpoints
|
|
435
|
+
.filter((entry) => entry.todo_id === todoId && entry.sequence <= freezeSequence)
|
|
436
|
+
.flatMap((entry) => (entry.payload?.diff?.entries ?? []).map(({ path }) => path));
|
|
437
|
+
const intersects = [...findingPaths].some((findingPath) => (
|
|
438
|
+
declaredWrites.some((declared) => (
|
|
439
|
+
declared === findingPath || (declared.endsWith('/') && findingPath.startsWith(declared))
|
|
440
|
+
))
|
|
441
|
+
|| observedPaths.includes(findingPath)
|
|
442
|
+
));
|
|
443
|
+
if (intersects) {
|
|
444
|
+
holdSet.add(todoId);
|
|
445
|
+
witnessFailures[todoId] = ['finding_scope_overlap'];
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
const receiptBindings = state.receipts
|
|
449
|
+
.filter((receipt) => (
|
|
450
|
+
receipt.todo_id === todoId
|
|
451
|
+
&& receipt.sequence <= freezeSequence
|
|
452
|
+
&& receipt.accepted_sequence === null
|
|
453
|
+
&& receipt.rejected_sequence === null
|
|
454
|
+
))
|
|
455
|
+
.map((receipt) => ({
|
|
456
|
+
receipt_id: receipt.receipt_id,
|
|
457
|
+
checkpoint_digest: receipt.payload?.checkpoint_digest ?? '0'.repeat(64),
|
|
458
|
+
recorded_sequence: receipt.sequence,
|
|
459
|
+
within_frozen_prefix: true,
|
|
460
|
+
}));
|
|
461
|
+
const sources = {
|
|
462
|
+
todo_input: request.manual_witness[todoId],
|
|
463
|
+
boundary_manifest: manifests[todoId],
|
|
464
|
+
validator: packet.verifier_refs,
|
|
465
|
+
context_content: {
|
|
466
|
+
todo_id: packet.todo_id,
|
|
467
|
+
task_ref: packet.task_ref,
|
|
468
|
+
scope: packet.scope,
|
|
469
|
+
base_sha: packet.base_sha,
|
|
470
|
+
verifier_refs: packet.verifier_refs,
|
|
471
|
+
forbidden_operations: packet.forbidden_operations,
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
const built = buildCarryOverWitness({
|
|
475
|
+
todoId,
|
|
476
|
+
predecessorEpoch: plan.plan_epoch,
|
|
477
|
+
successorEpoch: plan.plan_epoch + 1,
|
|
478
|
+
sources,
|
|
479
|
+
nonOverlapEvidence: conflictEventDigests.map((digest) => `conflict_found#${digest.slice(0, 16)}`),
|
|
480
|
+
receiptBindings,
|
|
481
|
+
});
|
|
482
|
+
if (built.witness === null) {
|
|
483
|
+
holdSet.add(todoId);
|
|
484
|
+
witnessFailures[todoId] = built.reasons;
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
next.push(buildNextRunEvent({
|
|
488
|
+
events: next,
|
|
489
|
+
runId,
|
|
490
|
+
kind: 'carry_over_witnessed',
|
|
491
|
+
planEpoch: plan.plan_epoch,
|
|
492
|
+
subject: { kind: 'todo', ref: todoId },
|
|
493
|
+
payload: { witness_digest: built.witness.witness_digest, witness: built.witness },
|
|
494
|
+
recordedAt,
|
|
495
|
+
}));
|
|
496
|
+
continueSet.add(todoId);
|
|
497
|
+
}
|
|
498
|
+
for (const todoId of closure) {
|
|
499
|
+
if (!continueSet.has(todoId)) holdSet.add(todoId);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const holdDecision = {
|
|
503
|
+
schema: 'lattice.hold_decision.v1',
|
|
504
|
+
decision_id: `hold-${runId}-seq${freezeSequence}`,
|
|
505
|
+
finding: structuredClone(frozenConflicts.at(-1)),
|
|
506
|
+
frozen_prefix_digest: state.freeze.frozen_prefix_digest ?? digestArtifact(
|
|
507
|
+
events.filter((event) => event.sequence <= freezeSequence).map((event) => event.event_digest),
|
|
508
|
+
),
|
|
509
|
+
affected_closure: sorted(closure),
|
|
510
|
+
hold_set: sorted(holdSet),
|
|
511
|
+
continue_set: sorted(continueSet),
|
|
512
|
+
evidence_digests: conflictEventDigests,
|
|
513
|
+
};
|
|
514
|
+
holdDecision.decision_digest = selfDigest(holdDecision, 'decision_digest');
|
|
515
|
+
if (!validateHoldDecision(holdDecision)) fail('hold decisionがcontractを満たさない');
|
|
516
|
+
|
|
517
|
+
next.push(buildNextRunEvent({
|
|
518
|
+
events: next,
|
|
519
|
+
runId,
|
|
520
|
+
kind: 'hold_decided',
|
|
521
|
+
planEpoch: plan.plan_epoch,
|
|
522
|
+
subject: { kind: 'runtime_plan', ref: plan.plan_ref },
|
|
523
|
+
payload: structuredClone(holdDecision),
|
|
524
|
+
recordedAt,
|
|
525
|
+
}));
|
|
526
|
+
|
|
527
|
+
// 独立verifierとのexact一致を自己検査する(divergenceはfail loud)。
|
|
528
|
+
const recomputed = recomputeHoldDecision({ plan, events: next, manifests });
|
|
529
|
+
if (JSON.stringify(recomputed.hold_set) !== JSON.stringify(holdDecision.hold_set)
|
|
530
|
+
|| JSON.stringify(recomputed.continue_set) !== JSON.stringify(holdDecision.continue_set)) {
|
|
531
|
+
fail(`hold裁定がverifier再計算と一致しない: producer=${JSON.stringify({
|
|
532
|
+
hold: holdDecision.hold_set, continue: holdDecision.continue_set,
|
|
533
|
+
})} verifier=${JSON.stringify({ hold: recomputed.hold_set, continue: recomputed.continue_set })}`);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
return { events: next, holdDecision, witnessFailures };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 競合findingをtreatment laneへ送る(Decision 7.6)。
|
|
541
|
+
* predeclared treatmentがfindingのpath集合を覆う場合だけseam laneを返し、
|
|
542
|
+
* それ以外(shared state/effect・未宣言path競合)はintentional serialにする。
|
|
543
|
+
*/
|
|
544
|
+
/**
|
|
545
|
+
* 同じ競合が何epochにわたって観測されたかを数える。
|
|
546
|
+
*
|
|
547
|
+
* 過去epochのconflictを再seedしないguardは既に在るが、**新しく観測された同じ競合**は毎epoch
|
|
548
|
+
* seedされる。原因が続く限り「hold→再計画→再開→また同じ競合」が繰り返せる。
|
|
549
|
+
* 誤帰属でも、scope違反を繰り返すworkerでも、変換で解けない競合でも同じことが起きる。
|
|
550
|
+
*
|
|
551
|
+
* 鍵は種別・資源・関与task対である。plan_epochで数えるのは、同一epoch内の複数回観測を
|
|
552
|
+
* 繰り返しと数えないためで、再計画を1回挟んで再び現れたことだけを繰り返しとする。
|
|
553
|
+
*/
|
|
554
|
+
export function countConflictRecurrence(events = []) {
|
|
555
|
+
const epochsByKey = new Map();
|
|
556
|
+
for (const event of events) {
|
|
557
|
+
if (event?.kind !== 'conflict_found') continue;
|
|
558
|
+
const finding = event.payload ?? {};
|
|
559
|
+
if (typeof finding.kind !== 'string' || !Array.isArray(finding.todo_ids)) continue;
|
|
560
|
+
const key = [
|
|
561
|
+
finding.kind,
|
|
562
|
+
typeof finding.path === 'string' ? finding.path : '',
|
|
563
|
+
[...finding.todo_ids].sort(compareText).join(','),
|
|
564
|
+
].join('\u0000');
|
|
565
|
+
if (!epochsByKey.has(key)) epochsByKey.set(key, new Set());
|
|
566
|
+
epochsByKey.get(key).add(event.plan_epoch);
|
|
567
|
+
}
|
|
568
|
+
return epochsByKey;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* 再計画で解けていない競合。1つでもあれば、もう一度同じ処置を試しても収束しない。
|
|
573
|
+
*
|
|
574
|
+
* 既定の閾値を3とするのは、1回目は通常の競合、2回目は再計画が効かなかった可能性(順序の綾を
|
|
575
|
+
* 含む)、3回目で「同じことが繰り返されている」と言えるためである。直列化で誤魔化さない——
|
|
576
|
+
* 誤帰属が原因なら直列化しても解けず、解けないことを解けたように見せることになる。
|
|
577
|
+
*/
|
|
578
|
+
export const NON_CONVERGENT_EPOCH_THRESHOLD = 3;
|
|
579
|
+
|
|
580
|
+
export function detectNonConvergentConflicts(options = {}) {
|
|
581
|
+
if (!exactRecord(options, ['events']) && !exactRecord(options, ['events', 'threshold'])) {
|
|
582
|
+
fail('detectNonConvergentConflicts optionsがexact shapeでない');
|
|
583
|
+
}
|
|
584
|
+
const { events, threshold = NON_CONVERGENT_EPOCH_THRESHOLD } = options;
|
|
585
|
+
if (!Array.isArray(events)) fail('eventsがarrayでない');
|
|
586
|
+
if (!Number.isSafeInteger(threshold) || threshold < 2) fail('thresholdが2以上の整数でない');
|
|
587
|
+
const recurrence = countConflictRecurrence(events);
|
|
588
|
+
const entries = [];
|
|
589
|
+
for (const [key, epochs] of recurrence) {
|
|
590
|
+
if (epochs.size < threshold) continue;
|
|
591
|
+
const [kind, resource, todoIds] = key.split('\u0000');
|
|
592
|
+
entries.push({
|
|
593
|
+
kind,
|
|
594
|
+
resource,
|
|
595
|
+
todo_ids: todoIds === '' ? [] : todoIds.split(','),
|
|
596
|
+
epochs: [...epochs].sort((left, right) => left - right),
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
return entries.sort((left, right) => compareText(
|
|
600
|
+
`${left.kind}\u0000${left.resource}\u0000${left.todo_ids.join(',')}`,
|
|
601
|
+
`${right.kind}\u0000${right.resource}\u0000${right.todo_ids.join(',')}`,
|
|
602
|
+
));
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* 係争資源が構造的に切れる種類かを返す(ADR 0144の続き、請求項8の入口判定)。
|
|
607
|
+
*
|
|
608
|
+
* pathやsymbolは面を分ければ別々に所有できる。共有stateや外部effectは分けられない——
|
|
609
|
+
* 変換をどれだけ工夫しても同じ資源に触り続ける。**これは「切れる」ではなく「切れる種類だ」で
|
|
610
|
+
* あって、実際に切れるかは試して初めて分かる。**
|
|
611
|
+
*/
|
|
612
|
+
export function severabilityOfRuntimeFinding(finding) {
|
|
613
|
+
return severabilityOfConflictKind(typeof finding?.path === 'string' ? 'path' : 'state');
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* 競合をどちらの処置へ運ぶか(請求項7=直列化/請求項8=変換)。
|
|
618
|
+
*
|
|
619
|
+
* `seam_transform`を返すのは事前宣言済みtreatmentが係争pathを覆っている時だけである。
|
|
620
|
+
* それ以外の既定は直列化だが、**それは「変換が不可能」という意味ではない**。実行時に初めて
|
|
621
|
+
* 見つかった競合には事前宣言が無いので、既定だけを見ると請求項8へ行く道が無いように見える。
|
|
622
|
+
*
|
|
623
|
+
* そこで`severability`と`transform_attemptable`を併せて返す。装置が言えるのは「切れる種類の
|
|
624
|
+
* 資源か」までで、**実際の難しさは変換を試して五条件で測る**(`run seam resolve`)。試すかどうかは
|
|
625
|
+
* 費用のかかる判断なので装置が決めない——隔離worktreeでの変換、focused test、再indexを毎回
|
|
626
|
+
* 走らせるかは、操作するAIが持つ文脈で決める(AGENTS.md「装置の境界にAIを含める」)。
|
|
627
|
+
*/
|
|
628
|
+
export function routeConflictTreatment(options = {}) {
|
|
629
|
+
if (!exactRecord(options, ['finding', 'predeclaredTreatments'])) {
|
|
630
|
+
fail('routeConflictTreatment optionsがexact shapeでない');
|
|
631
|
+
}
|
|
632
|
+
const { finding, predeclaredTreatments } = options;
|
|
633
|
+
if (!plainRecord(finding) || typeof finding.kind !== 'string') fail('findingが不正');
|
|
634
|
+
const severability = severabilityOfRuntimeFinding(finding);
|
|
635
|
+
if (finding.kind === 'observed_write_conflict' && typeof finding.path === 'string') {
|
|
636
|
+
for (const treatment of predeclaredTreatments) {
|
|
637
|
+
if (Array.isArray(treatment.covered_paths) && treatment.covered_paths.includes(finding.path)) {
|
|
638
|
+
return { lane: 'seam_transform', treatment: structuredClone(treatment),
|
|
639
|
+
severability, transform_attemptable: true };
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return { lane: 'intentional_serial', treatment: null,
|
|
644
|
+
severability, transform_attemptable: severability === 'code_seam' };
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* hold決定後のplan vN+1をcompileする。carried-over TODOへはepoch rebind packet
|
|
649
|
+
* (content不変・epoch/plan refのみ更新)、hold TODOへは新plan_ref由来の
|
|
650
|
+
* 新context packetを発行し、旧contextを失効する。rebind/prepare ack、epoch pointer、
|
|
651
|
+
* controller ready/release ack、中央gate commit前にはepoch_rebound/intake_resumedを発行しない。
|
|
652
|
+
*
|
|
653
|
+
* baseはここでは動かさない。変換で構造が変わった時に後継baseを決めるのは後継run requestで
|
|
654
|
+
* あり、それが本当に変換を含むかは`verifySeamSplitSuccessor`が見る(ADR 0141)。
|
|
655
|
+
*/
|
|
656
|
+
export function recompileNextEpochPlan(options = {}) {
|
|
657
|
+
if (!exactRecord(options, [
|
|
658
|
+
'runId', 'request', 'plan', 'manifests', 'packets', 'events', 'holdDecision',
|
|
659
|
+
'additionalConflicts', 'recordedAt',
|
|
660
|
+
])) {
|
|
661
|
+
fail('recompileNextEpochPlan optionsがexact shapeでない');
|
|
662
|
+
}
|
|
663
|
+
const {
|
|
664
|
+
runId, request, plan, manifests, packets, events, holdDecision, additionalConflicts, recordedAt,
|
|
665
|
+
} = options;
|
|
666
|
+
if (!validateRuntimePlan(plan)) fail('planがruntime_plan.v1 contractを満たさない');
|
|
667
|
+
if (!validateHoldDecision(holdDecision)) fail('holdDecisionがcontractを満たさない');
|
|
668
|
+
if (!Array.isArray(additionalConflicts)) fail('additionalConflictsがarrayではない');
|
|
669
|
+
// 同じ競合が閾値のepoch数だけ繰り返しているなら、もう一度同じ処置を試しても収束しない。
|
|
670
|
+
// 直列化やもう1周で誤魔化さず、解けていないことをtypedに述べて止める。
|
|
671
|
+
const nonConvergent = detectNonConvergentConflicts({ events });
|
|
672
|
+
if (nonConvergent.length > 0) {
|
|
673
|
+
fail(`再計画で解けていない競合がある(非収束): ${nonConvergent
|
|
674
|
+
.map((entry) => `${entry.kind}:${entry.resource}:${entry.todo_ids.join(',')}@${entry.epochs.join('/')}`)
|
|
675
|
+
.join(' ')}`);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const state = projectRuntimeState({ events });
|
|
679
|
+
if (state.freeze === null) fail('freeze中でないprefixからrecompileできない');
|
|
680
|
+
|
|
681
|
+
// 新planは追記でなく全体を再発行する(plan version barrier)。
|
|
682
|
+
const conflictKeys = new Set(plan.conflicts.map((conflict) => (
|
|
683
|
+
`${[...conflict.todo_ids].sort().join(',')}|${conflict.resource_id}`
|
|
684
|
+
)));
|
|
685
|
+
const mergedConflicts = [...plan.conflicts.map((conflict) => structuredClone(conflict))];
|
|
686
|
+
for (const conflict of additionalConflicts) {
|
|
687
|
+
if (!plainRecord(conflict) || !Array.isArray(conflict.todo_ids) || typeof conflict.resource_id !== 'string') {
|
|
688
|
+
fail('additional conflictが不正');
|
|
689
|
+
}
|
|
690
|
+
const key = `${[...conflict.todo_ids].sort().join(',')}|${conflict.resource_id}`;
|
|
691
|
+
if (conflictKeys.has(key)) continue;
|
|
692
|
+
conflictKeys.add(key);
|
|
693
|
+
mergedConflicts.push({ todo_ids: [...conflict.todo_ids].sort(), resource_id: conflict.resource_id });
|
|
694
|
+
}
|
|
695
|
+
mergedConflicts.sort((left, right) => (
|
|
696
|
+
(left.todo_ids[0] < right.todo_ids[0] ? -1 : left.todo_ids[0] > right.todo_ids[0] ? 1 : 0)
|
|
697
|
+
|| (left.todo_ids[1] < right.todo_ids[1] ? -1 : left.todo_ids[1] > right.todo_ids[1] ? 1 : 0)
|
|
698
|
+
|| (left.resource_id < right.resource_id ? -1 : 1)
|
|
699
|
+
));
|
|
700
|
+
|
|
701
|
+
const newEpoch = plan.plan_epoch + 1;
|
|
702
|
+
const newPlanRef = `plan-${request.request_id}-e${newEpoch}`;
|
|
703
|
+
const acceptedCheckpoints = state.receipts
|
|
704
|
+
.filter((receipt) => receipt.accepted_sequence !== null)
|
|
705
|
+
.map((receipt) => receipt.payload?.checkpoint_digest)
|
|
706
|
+
.filter((digest) => typeof digest === 'string');
|
|
707
|
+
|
|
708
|
+
const newPlan = {
|
|
709
|
+
schema: 'lattice.runtime_plan.v1',
|
|
710
|
+
plan_ref: newPlanRef,
|
|
711
|
+
plan_epoch: newEpoch,
|
|
712
|
+
request_digest: request.request_digest,
|
|
713
|
+
base_sha: plan.base_sha,
|
|
714
|
+
nodes: structuredClone(plan.nodes),
|
|
715
|
+
precedence: structuredClone(plan.precedence),
|
|
716
|
+
conflicts: mergedConflicts,
|
|
717
|
+
capacity: structuredClone(plan.capacity),
|
|
718
|
+
manifest_digests: structuredClone(plan.manifest_digests),
|
|
719
|
+
claim: { mode: 'exact_minimum' },
|
|
720
|
+
predecessor_refs: [plan.plan_ref, ...acceptedCheckpoints.map((digest) => `checkpoint:${digest}`)],
|
|
721
|
+
};
|
|
722
|
+
newPlan.plan_digest = selfDigest(newPlan, 'plan_digest');
|
|
723
|
+
if (!validateRuntimePlan(newPlan)) fail('新planがruntime_plan.v1 contractを満たさない');
|
|
724
|
+
if (!verifyRuntimePlanBinding({ plan: newPlan, request })) fail('新planがrequestへbindできない');
|
|
725
|
+
|
|
726
|
+
let next = [...events];
|
|
727
|
+
|
|
728
|
+
// hold集合のrunning executorを旧epochで終端する(放棄の証拠化。runningから
|
|
729
|
+
// 外れることで、新epochでのredispatchが可能になる)。
|
|
730
|
+
const runningSet = new Set(state.running);
|
|
731
|
+
for (const todoId of holdDecision.hold_set) {
|
|
732
|
+
if (!runningSet.has(todoId)) continue;
|
|
733
|
+
const dispatch = state.dispatches[todoId];
|
|
734
|
+
next.push(buildNextRunEvent({
|
|
735
|
+
events: next,
|
|
736
|
+
runId,
|
|
737
|
+
kind: 'executor_terminal',
|
|
738
|
+
planEpoch: plan.plan_epoch,
|
|
739
|
+
subject: { kind: 'todo', ref: todoId },
|
|
740
|
+
payload: {
|
|
741
|
+
executor_handle: dispatch?.payload?.executor_handle ?? 'unknown',
|
|
742
|
+
terminal_state: 'context_invalidated',
|
|
743
|
+
},
|
|
744
|
+
recordedAt,
|
|
745
|
+
}));
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
next.push(buildNextRunEvent({
|
|
749
|
+
events: next,
|
|
750
|
+
runId,
|
|
751
|
+
kind: 'plan_recompiled',
|
|
752
|
+
planEpoch: newEpoch,
|
|
753
|
+
subject: { kind: 'runtime_plan', ref: newPlanRef },
|
|
754
|
+
payload: {
|
|
755
|
+
old_plan_ref: plan.plan_ref,
|
|
756
|
+
new_plan_digest: newPlan.plan_digest,
|
|
757
|
+
hold_decision_digest: holdDecision.decision_digest,
|
|
758
|
+
},
|
|
759
|
+
recordedAt,
|
|
760
|
+
}));
|
|
761
|
+
|
|
762
|
+
// 失効するのは停止・再計画対象だけ。closure外のrunning TODOはorigin bindingのまま
|
|
763
|
+
// 継続するため、contextもpartial patchも無効化しない。
|
|
764
|
+
for (const todoId of sorted(holdDecision.hold_set)) {
|
|
765
|
+
next.push(buildNextRunEvent({
|
|
766
|
+
events: next,
|
|
767
|
+
runId,
|
|
768
|
+
kind: 'context_invalidated',
|
|
769
|
+
planEpoch: newEpoch,
|
|
770
|
+
subject: { kind: 'todo', ref: todoId },
|
|
771
|
+
payload: {
|
|
772
|
+
old_plan_ref: plan.plan_ref,
|
|
773
|
+
invalidated: ['agent_context', 'partial_patch', 'interface_assumption', 'boundary_evidence'],
|
|
774
|
+
reauthorized_via: 'redispatch',
|
|
775
|
+
},
|
|
776
|
+
recordedAt,
|
|
777
|
+
}));
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// carried-over TODOがrecompileで追加されるconflictの当事者なら設計矛盾
|
|
781
|
+
// (closureに入っているべき)。fail loudで止める。
|
|
782
|
+
for (const conflict of additionalConflicts) {
|
|
783
|
+
for (const todoId of conflict.todo_ids ?? []) {
|
|
784
|
+
if (holdDecision.continue_set.includes(todoId)) {
|
|
785
|
+
fail(`carried-over TODOが追加conflictの当事者になっている: ${todoId}`);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// freeze時点のfrozen prefix境界(authorized checkpoint lineageの基準)。
|
|
791
|
+
const freezeSequenceForLineage = events
|
|
792
|
+
.filter((event) => event.kind === 'intake_frozen' && event.plan_epoch === plan.plan_epoch)
|
|
793
|
+
.map((event) => event.sequence)
|
|
794
|
+
.sort((left, right) => left - right)[0] ?? null;
|
|
795
|
+
|
|
796
|
+
// restart時は全process barrierになるため、その場合だけcarry-overを現epochへ復元できる
|
|
797
|
+
// rebind packetをbundleへ残す。通常のrecompileでは使わずorigin bindingを維持する。
|
|
798
|
+
const rebindPackets = {};
|
|
799
|
+
for (const todoId of holdDecision.continue_set) {
|
|
800
|
+
const packet = packets[todoId];
|
|
801
|
+
const dispatch = state.dispatches[todoId];
|
|
802
|
+
const witnessRecord = state.witnesses[todoId];
|
|
803
|
+
if (packet === undefined || dispatch === undefined || witnessRecord === undefined) {
|
|
804
|
+
fail(`carried-over TODOのpacket/dispatch/witnessが欠落: ${todoId}`);
|
|
805
|
+
}
|
|
806
|
+
// authorized checkpointはfrozen prefix内の最後の観測checkpoint。checkpointが
|
|
807
|
+
// 一件もないcarry-overはgenesis sentinel(64桁ゼロ、RC3-J ADRで正式裁定予定)。
|
|
808
|
+
const frozenCheckpoints = state.checkpoints.filter((entry) => (
|
|
809
|
+
entry.todo_id === todoId
|
|
810
|
+
&& (freezeSequenceForLineage === null || entry.sequence <= freezeSequenceForLineage)
|
|
811
|
+
));
|
|
812
|
+
const authorizedCheckpointDigest = frozenCheckpoints.length > 0
|
|
813
|
+
? frozenCheckpoints[frozenCheckpoints.length - 1].payload?.checkpoint_digest ?? '0'.repeat(64)
|
|
814
|
+
: '0'.repeat(64);
|
|
815
|
+
const rebind = {
|
|
816
|
+
schema: 'lattice.epoch_rebind_packet.v1',
|
|
817
|
+
packet_id: `${newPlanRef}-rebind-${todoId}`,
|
|
818
|
+
todo_id: todoId,
|
|
819
|
+
executor_handle: dispatch.payload.executor_handle,
|
|
820
|
+
worktree_id: dispatch.payload.worktree_id,
|
|
821
|
+
witness_digest: witnessRecord.payload.witness_digest,
|
|
822
|
+
context_content_digest: packet.context_content_digest,
|
|
823
|
+
authorized_checkpoint_digest: authorizedCheckpointDigest,
|
|
824
|
+
old_plan_ref: plan.plan_ref,
|
|
825
|
+
new_plan_ref: newPlanRef,
|
|
826
|
+
new_plan_epoch: newEpoch,
|
|
827
|
+
};
|
|
828
|
+
rebind.packet_digest = selfDigest(rebind, 'packet_digest');
|
|
829
|
+
if (!validateEpochRebindPacket(rebind)) fail(`rebind packetがcontractを満たさない: ${todoId}`);
|
|
830
|
+
if (rebind.context_content_digest !== computeContextContentDigest({
|
|
831
|
+
todo_id: packet.todo_id,
|
|
832
|
+
task_ref: packet.task_ref,
|
|
833
|
+
scope: packet.scope,
|
|
834
|
+
base_sha: packet.base_sha,
|
|
835
|
+
verifier_refs: packet.verifier_refs,
|
|
836
|
+
forbidden_operations: packet.forbidden_operations,
|
|
837
|
+
})) {
|
|
838
|
+
fail(`rebindのcontent digestがvN packet contentと一致しない: ${todoId}`);
|
|
839
|
+
}
|
|
840
|
+
rebindPackets[todoId] = rebind;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// redispatch TODOへは新plan_ref由来の別content packetを発行する。
|
|
844
|
+
const allNewPackets = buildExecutorPackets({ plan: newPlan, manifests });
|
|
845
|
+
const redispatchPackets = Object.fromEntries(
|
|
846
|
+
holdDecision.hold_set.map((todoId) => [todoId, allNewPackets[todoId]]),
|
|
847
|
+
);
|
|
848
|
+
|
|
849
|
+
const planDiff = {
|
|
850
|
+
schema: 'lattice.runtime_plan_diff.v1',
|
|
851
|
+
old_plan_ref: plan.plan_ref,
|
|
852
|
+
new_plan_ref: newPlanRef,
|
|
853
|
+
accepted_checkpoints: sorted(acceptedCheckpoints),
|
|
854
|
+
invalidated_contexts: [...holdDecision.hold_set],
|
|
855
|
+
carried_over: [...holdDecision.continue_set],
|
|
856
|
+
redispatched: [...holdDecision.hold_set],
|
|
857
|
+
node_edge_diff: {
|
|
858
|
+
added_nodes: [],
|
|
859
|
+
removed_nodes: [],
|
|
860
|
+
added_conflicts: mergedConflicts.length - plan.conflicts.length,
|
|
861
|
+
},
|
|
862
|
+
};
|
|
863
|
+
planDiff.diff_digest = selfDigest(planDiff, 'diff_digest');
|
|
864
|
+
if (!validateRuntimePlanDiff(planDiff)) fail('plan diffがcontractを満たさない');
|
|
865
|
+
|
|
866
|
+
return {
|
|
867
|
+
events: next,
|
|
868
|
+
newPlan,
|
|
869
|
+
planDiff,
|
|
870
|
+
rebindPackets,
|
|
871
|
+
redispatchPackets,
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* controller direct ackと中央gate commitが全件揃った後だけrun eventを公開する。
|
|
877
|
+
* producer compileとは分離し、ack前の呼出しは一切のpartial eventを返さない。
|
|
878
|
+
*/
|
|
879
|
+
export function finalizeRecompileActivation(options = {}) {
|
|
880
|
+
if (!exactRecord(options, ['runId', 'events', 'plan', 'planDiff', 'rebindPackets',
|
|
881
|
+
'rebindAcks', 'gateDigest', 'gateControlEventDigest', 'recordedAt'])) {
|
|
882
|
+
fail('finalizeRecompileActivation optionsがexact shapeでない');
|
|
883
|
+
}
|
|
884
|
+
const { runId, events, plan, planDiff, rebindPackets, rebindAcks, gateDigest,
|
|
885
|
+
gateControlEventDigest, recordedAt } = options;
|
|
886
|
+
if (!validateRuntimePlan(plan) || !validateRuntimePlanDiff(planDiff)
|
|
887
|
+
|| !HEX_DIGEST.test(gateDigest ?? '') || !HEX_DIGEST.test(gateControlEventDigest ?? '')
|
|
888
|
+
|| !plainRecord(rebindPackets) || !plainRecord(rebindAcks)) {
|
|
889
|
+
fail('activation bindingが不正');
|
|
890
|
+
}
|
|
891
|
+
const packetIds = Object.keys(rebindPackets).sort();
|
|
892
|
+
if (canonicalizeArtifact(Object.keys(rebindAcks).sort()) !== canonicalizeArtifact(packetIds)) {
|
|
893
|
+
fail('rebind ack集合がpacket集合とexact一致しない');
|
|
894
|
+
}
|
|
895
|
+
for (const todoId of packetIds) {
|
|
896
|
+
const packet = rebindPackets[todoId];
|
|
897
|
+
const ack = rebindAcks[todoId];
|
|
898
|
+
if (!validateEpochRebindPacket(packet)
|
|
899
|
+
|| !plainRecord(ack) || ack.schema !== 'lattice.executor_epoch_rebind_ack.v1'
|
|
900
|
+
|| ack.todo_id !== todoId || ack.rebind_packet_digest !== packet.packet_digest
|
|
901
|
+
|| ack.successor_epoch !== plan.plan_epoch || !HEX_DIGEST.test(ack.ack_digest ?? '')
|
|
902
|
+
|| !selfDigestValid(ack, 'ack_digest')) fail(`rebind ack bindingが不正: ${todoId}`);
|
|
903
|
+
}
|
|
904
|
+
let next = [...events];
|
|
905
|
+
// 全件を先に検証した後にだけbatchを構築する(partial epoch_rebound禁止)。
|
|
906
|
+
for (const todoId of packetIds) {
|
|
907
|
+
next.push(buildNextRunEvent({ events: next, runId, kind: 'epoch_rebound',
|
|
908
|
+
planEpoch: plan.plan_epoch, subject: { kind: 'todo', ref: todoId },
|
|
909
|
+
payload: structuredClone(rebindPackets[todoId]), recordedAt }));
|
|
910
|
+
}
|
|
911
|
+
next.push(buildNextRunEvent({ events: next, runId, kind: 'intake_resumed',
|
|
912
|
+
planEpoch: plan.plan_epoch, subject: { kind: 'runtime_plan', ref: plan.plan_ref },
|
|
913
|
+
payload: { plan_diff_digest: planDiff.diff_digest, write_gate_digest: gateDigest,
|
|
914
|
+
control_event_digest: gateControlEventDigest }, recordedAt }));
|
|
915
|
+
return { events: next, redispatchTodoIds: [...planDiff.redispatched].sort() };
|
|
916
|
+
}
|