@quolu/lattice 0.52.2 → 0.52.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,712 +1,712 @@
1
- import {
2
- canonicalizeArtifact,
3
- digestArtifact,
4
- validateBoundaryManifest,
5
- validateBoundaryVerdict,
6
- validatePlanGraph,
7
- validatePlanInput,
8
- } from './artifact-contracts.mjs';
9
- import { portableSensorOutcome } from './sensor-adapter.mjs';
10
-
11
- const SHA256 = /^[0-9a-f]{64}$/;
12
- const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
13
- const OPERATIONS = new Set(['status', 'query', 'callers', 'callees', 'impact', 'affected']);
14
- const OPTION_KEYS = [
15
- 'candidateSpec',
16
- 'codeSnapshotDigest',
17
- 'sensorEvidence',
18
- 'manualEvidence',
19
- 'planInput',
20
- 'planVersion',
21
- 'querySet',
22
- ];
23
-
24
- export const RC1_BOUNDARY_COMPILER_CONTRACT = Object.freeze({
25
- export_name: 'compileBoundaryCondition',
26
- condition_selector: 'forbidden',
27
- surface_resolution: 'exact_graph_name_or_qualified_name_at_expected_path',
28
- conflict_rule: 'pairwise_write_resource_intersection',
29
- });
30
-
31
- function fail(reason) {
32
- throw new TypeError(`RC1 v4 boundary compiler契約違反: ${reason}`);
33
- }
34
-
35
- function isPlainObject(value) {
36
- return value !== null
37
- && typeof value === 'object'
38
- && !Array.isArray(value)
39
- && Object.getPrototypeOf(value) === Object.prototype;
40
- }
41
-
42
- function exactRecord(value, keys) {
43
- if (!isPlainObject(value)) return false;
44
- const actual = Object.keys(value).sort();
45
- const expected = [...keys].sort();
46
- return actual.length === expected.length
47
- && actual.every((key, index) => key === expected[index]);
48
- }
49
-
50
- function nonEmptyText(value) {
51
- return typeof value === 'string' && value.length > 0 && value.length <= 4_096;
52
- }
53
-
54
- function identifier(value) {
55
- return typeof value === 'string' && IDENTIFIER.test(value);
56
- }
57
-
58
- function repoPath(value) {
59
- return typeof value === 'string'
60
- && value.length > 0
61
- && value.length <= 1_024
62
- && !value.includes('\0')
63
- && !value.startsWith('/')
64
- && !value.split('/').includes('..');
65
- }
66
-
67
- function unique(values) {
68
- return [...new Set(values)];
69
- }
70
-
71
- function resourceKey(value) {
72
- return `${value.kind}\0${value.target}`;
73
- }
74
-
75
- function uniqueResources(values) {
76
- return [...new Map(values.map((value) => [resourceKey(value), value])).values()]
77
- .sort((left, right) => resourceKey(left).localeCompare(resourceKey(right)));
78
- }
79
-
80
- function assertManualEvidence(planInput, manualEvidence) {
81
- if (!exactRecord(manualEvidence, ['schema', 'evidence'])
82
- || manualEvidence.schema !== 'lattice.manual_boundary_evidence.v1'
83
- || !Array.isArray(manualEvidence.evidence)
84
- || manualEvidence.evidence.length !== planInput.todos.length) {
85
- fail('manual evidence rootがplan inputと一致しない');
86
- }
87
- const todoIds = planInput.todos.map(({ id }) => id);
88
- if (new Set(manualEvidence.evidence.map(({ todo_id: todoId }) => todoId)).size !== todoIds.length) {
89
- fail('manual evidence todo IDが一意でない');
90
- }
91
- for (const entry of manualEvidence.evidence) {
92
- if (!exactRecord(entry, ['todo_id', 'state_reads', 'state_writes', 'effects', 'unknowns'])
93
- || !todoIds.includes(entry.todo_id)
94
- || ![entry.state_reads, entry.state_writes, entry.effects, entry.unknowns]
95
- .every((values) => Array.isArray(values)
96
- && values.every(nonEmptyText)
97
- && new Set(values).size === values.length)) {
98
- fail('manual evidence recordが不正');
99
- }
100
- }
101
- }
102
-
103
- function assertTestSurface(value, { proposed }) {
104
- if (!exactRecord(value, [
105
- 'symbol',
106
- 'path',
107
- 'query_id',
108
- 'impact_id',
109
- 'assertion_id',
110
- 'provenance',
111
- ])
112
- || (proposed ? !nonEmptyText(value.symbol) : value.symbol !== null)
113
- || !repoPath(value.path)
114
- || !identifier(value.query_id)
115
- || (proposed ? !identifier(value.impact_id) : value.impact_id !== null)
116
- || !identifier(value.assertion_id)
117
- || !exactRecord(value.provenance, ['kind', 'ref'])
118
- || value.provenance.kind !== 'todo_outcome'
119
- || !nonEmptyText(value.provenance.ref)) {
120
- fail(`${proposed ? 'proposed' : 'current'} test surfaceが不正`);
121
- }
122
- }
123
-
124
- function assertProductionSurface(value) {
125
- if (!exactRecord(value, ['symbol', 'path', 'query_id', 'impact_id', 'link_query_id'])
126
- || !nonEmptyText(value.symbol)
127
- || !repoPath(value.path)
128
- || !identifier(value.query_id)
129
- || !identifier(value.impact_id)
130
- || !identifier(value.link_query_id)) {
131
- fail('production surfaceが不正');
132
- }
133
- }
134
-
135
- function assertCandidateSpec(planInput, candidateSpec) {
136
- if (!exactRecord(candidateSpec, [
137
- 'schema',
138
- 'candidate_id',
139
- 'plan_input_ref',
140
- 'query_set_ref',
141
- 'behavior_oracle_ref',
142
- 'compiler_contract',
143
- 'stable_surfaces',
144
- 'todos',
145
- ])
146
- || candidateSpec.schema !== 'lattice.rc1.boundary_candidate_spec.v2'
147
- || !identifier(candidateSpec.candidate_id)
148
- || !repoPath(candidateSpec.plan_input_ref)
149
- || !repoPath(candidateSpec.query_set_ref)
150
- || !repoPath(candidateSpec.behavior_oracle_ref)
151
- || !exactRecord(candidateSpec.compiler_contract, [
152
- 'condition_selector',
153
- 'surface_resolution',
154
- 'proposed_activation',
155
- 'unresolved_policy',
156
- 'conflict_rule',
157
- ])
158
- || candidateSpec.compiler_contract.condition_selector !== 'forbidden'
159
- || candidateSpec.compiler_contract.surface_resolution
160
- !== 'exact_graph_name_or_qualified_name_at_expected_path'
161
- || candidateSpec.compiler_contract.proposed_activation
162
- !== 'all_proposed_production_and_test_surfaces_exact'
163
- || candidateSpec.compiler_contract.unresolved_policy !== 'typed_unknown'
164
- || candidateSpec.compiler_contract.conflict_rule !== 'pairwise_write_resource_intersection'
165
- || !Array.isArray(candidateSpec.stable_surfaces)
166
- || candidateSpec.stable_surfaces.length === 0
167
- || !Array.isArray(candidateSpec.todos)
168
- || candidateSpec.todos.length !== planInput.todos.length) {
169
- fail('candidate spec rootが不正');
170
- }
171
-
172
- for (const surface of candidateSpec.stable_surfaces) {
173
- if (!exactRecord(surface, ['kind', 'target', 'path', 'role', 'active_when'])
174
- || !new Set(['symbol', 'path']).has(surface.kind)
175
- || !nonEmptyText(surface.target)
176
- || !repoPath(surface.path)
177
- || !identifier(surface.role)
178
- || !new Set(['always', 'proposed']).has(surface.active_when)) {
179
- fail('stable surfaceが不正');
180
- }
181
- }
182
-
183
- const planTodos = new Map(planInput.todos.map((todo) => [todo.id, todo]));
184
- for (const todo of candidateSpec.todos) {
185
- if (!exactRecord(todo, ['todo_id', 'outcome', 'current', 'proposed'])
186
- || !planTodos.has(todo.todo_id)
187
- || todo.outcome !== planTodos.get(todo.todo_id).outcome) {
188
- fail('candidate TODOがplan inputと一致しない');
189
- }
190
- for (const [mode, proposed] of [['current', false], ['proposed', true]]) {
191
- const value = todo[mode];
192
- if (!exactRecord(value, ['production', 'tests'])
193
- || !Array.isArray(value.tests)
194
- || value.tests.length === 0) {
195
- fail(`${mode} surface setが不正`);
196
- }
197
- assertProductionSurface(value.production);
198
- for (const test of value.tests) assertTestSurface(test, { proposed });
199
- }
200
- }
201
- if (new Set(candidateSpec.todos.map(({ todo_id: todoId }) => todoId)).size
202
- !== planInput.todos.length) {
203
- fail('candidate TODO IDが一意でない');
204
- }
205
- }
206
-
207
- function assertQuerySet(querySet, candidateSpec) {
208
- if (!exactRecord(querySet, ['schema', 'queries'])
209
- || querySet.schema !== 'lattice.sensor_query_set.v2'
210
- || !Array.isArray(querySet.queries)
211
- || querySet.queries.length === 0
212
- || querySet.queries.length > 256) {
213
- fail('query set rootが不正');
214
- }
215
- const ids = new Set();
216
- for (const query of querySet.queries) {
217
- if (!isPlainObject(query) || !identifier(query.id) || ids.has(query.id)
218
- || !OPERATIONS.has(query.operation)) {
219
- fail('query set recordが不正');
220
- }
221
- ids.add(query.id);
222
- if (query.operation === 'status') {
223
- if (!exactRecord(query, ['id', 'operation'])) fail('status query shapeが不正');
224
- } else if (query.operation === 'affected') {
225
- if (!exactRecord(query, ['id', 'operation', 'targets'])
226
- || !Array.isArray(query.targets)
227
- || query.targets.length === 0
228
- || !query.targets.every(repoPath)
229
- || new Set(query.targets).size !== query.targets.length) {
230
- fail('affected query shapeが不正');
231
- }
232
- } else if (!exactRecord(query, ['id', 'operation', 'target'])
233
- || !nonEmptyText(query.target)) {
234
- fail('graph query shapeが不正');
235
- }
236
- }
237
- if (querySet.queries.filter(({ operation }) => operation === 'status').length !== 1
238
- || querySet.queries.filter(({ operation }) => operation === 'affected').length !== 1) {
239
- fail('query setにstatusとaffectedがexactly one必要');
240
- }
241
-
242
- const referenced = candidateSpec.todos.flatMap((todo) => [todo.current, todo.proposed]
243
- .flatMap((surface) => [
244
- surface.production.query_id,
245
- surface.production.impact_id,
246
- surface.production.link_query_id,
247
- ...surface.tests.flatMap((entry) => [entry.query_id, entry.impact_id].filter(Boolean)),
248
- ]));
249
- if (referenced.some((id) => !ids.has(id))) {
250
- fail('candidate specがquery set外のIDを参照する');
251
- }
252
- }
253
-
254
- function assertLatticeSensorEvidence(querySet, sensorEvidence) {
255
- if (!isPlainObject(sensorEvidence)
256
- || !Array.isArray(sensorEvidence.outcomes)
257
- || sensorEvidence.outcomes.length !== querySet.queries.length) {
258
- fail('LatticeSensor evidence rootがquery setと一致しない');
259
- }
260
- for (let index = 0; index < querySet.queries.length; index += 1) {
261
- const query = querySet.queries[index];
262
- const outcome = sensorEvidence.outcomes[index];
263
- if (!isPlainObject(outcome)
264
- || outcome.id !== query.id
265
- || outcome.operation !== query.operation
266
- || !nonEmptyText(outcome.outcome)) {
267
- fail(`LatticeSensor evidence ${query.id}がID/operation/順序と一致しない`);
268
- }
269
- if (query.operation !== 'status' && query.operation !== 'affected'
270
- && outcome.target !== query.target) {
271
- fail(`LatticeSensor evidence ${query.id}のtargetがquery setと一致しない`);
272
- }
273
- if (query.operation === 'affected'
274
- && (!Array.isArray(outcome.targets)
275
- || outcome.targets.length !== query.targets.length
276
- || outcome.targets.some((entry, targetIndex) => (
277
- !isPlainObject(entry) || entry.target !== query.targets[targetIndex]
278
- )))) {
279
- fail(`LatticeSensor evidence ${query.id}のaffected targetがquery setと一致しない`);
280
- }
281
- }
282
- }
283
-
284
- function exactNodeAt(records, target, expectedPath) {
285
- if (!Array.isArray(records)) return false;
286
- const exact = records.filter((entry) => isPlainObject(entry?.node)
287
- && (entry.node.name === target || entry.node.qualifiedName === target)
288
- && entry.node.filePath === expectedPath);
289
- return exact.length === 1;
290
- }
291
-
292
- function exactQueryStatus(outcome, target, expectedPath) {
293
- if (outcome?.outcome === 'symbol_absent') return 'absent';
294
- if (outcome?.outcome !== 'ready') return 'unknown';
295
- return exactNodeAt(outcome.data, target, expectedPath) ? 'ready' : 'unknown';
296
- }
297
-
298
- function exactResolutionStatus(outcome, target, expectedPath) {
299
- if (outcome?.outcome === 'symbol_absent') return 'absent';
300
- if (outcome?.outcome !== 'ready') return 'unknown';
301
- return exactNodeAt(outcome.resolution, target, expectedPath) ? 'ready' : 'unknown';
302
- }
303
-
304
- function callerLinkStatus(outcome, production, anchor) {
305
- const resolution = exactResolutionStatus(outcome, production.symbol, production.path);
306
- if (resolution !== 'ready') return resolution;
307
- const callers = outcome.data?.callers;
308
- if (!Array.isArray(callers)) return 'unknown';
309
- return callers.some((entry) => entry?.name === anchor.symbol && entry?.filePath === anchor.path)
310
- ? 'ready'
311
- : 'unknown';
312
- }
313
-
314
- function outcomeMap(querySet, sensorEvidence) {
315
- return new Map(querySet.queries.map((query, index) => [
316
- query.id,
317
- sensorEvidence.outcomes[index],
318
- ]));
319
- }
320
-
321
- function statusesForSurface(surface, outcomes, anchor, { proposed }) {
322
- const statuses = [
323
- exactQueryStatus(
324
- outcomes.get(surface.production.query_id),
325
- surface.production.symbol,
326
- surface.production.path,
327
- ),
328
- exactResolutionStatus(
329
- outcomes.get(surface.production.impact_id),
330
- surface.production.symbol,
331
- surface.production.path,
332
- ),
333
- ];
334
- if (proposed) {
335
- statuses.push(callerLinkStatus(
336
- outcomes.get(surface.production.link_query_id),
337
- surface.production,
338
- anchor,
339
- ));
340
- }
341
- for (const test of surface.tests) {
342
- const target = test.symbol ?? test.path;
343
- statuses.push(exactQueryStatus(outcomes.get(test.query_id), target, test.path));
344
- if (test.impact_id !== null) {
345
- statuses.push(exactResolutionStatus(outcomes.get(test.impact_id), target, test.path));
346
- }
347
- }
348
- return statuses;
349
- }
350
-
351
- function deriveSurfaceMode(planInput, candidateSpec, outcomes) {
352
- const current = [];
353
- const proposed = [];
354
- for (const candidate of candidateSpec.todos) {
355
- const anchor = planInput.todos.find(({ id }) => id === candidate.todo_id).anchor;
356
- current.push(...statusesForSurface(candidate.current, outcomes, anchor, { proposed: false }));
357
- proposed.push(...statusesForSurface(candidate.proposed, outcomes, anchor, { proposed: true }));
358
- }
359
- if (current.every((status) => status === 'ready')
360
- && proposed.every((status) => status === 'absent')) {
361
- return { mode: 'current', unknowns: [] };
362
- }
363
- if (current.every((status) => status === 'ready')
364
- && proposed.every((status) => status === 'ready')) {
365
- return { mode: 'proposed', unknowns: [] };
366
- }
367
- return {
368
- mode: 'current',
369
- unknowns: [
370
- `surface_resolution_unknown:current=${current.join(',')}:proposed=${proposed.join(',')}`,
371
- ],
372
- };
373
- }
374
-
375
- function surfaceResources(surface) {
376
- return uniqueResources([
377
- { kind: 'symbol', target: surface.production.symbol },
378
- { kind: 'path', target: surface.production.path },
379
- ...surface.tests.flatMap((test) => [
380
- ...(test.symbol === null ? [] : [{ kind: 'symbol', target: test.symbol }]),
381
- { kind: 'path', target: test.path },
382
- ]),
383
- ]);
384
- }
385
-
386
- function surfaceEvidenceRefs(surface) {
387
- return unique([
388
- surface.production.query_id,
389
- surface.production.impact_id,
390
- surface.production.link_query_id,
391
- ...surface.tests.flatMap((test) => [test.query_id, test.impact_id].filter(Boolean)),
392
- ]).sort();
393
- }
394
-
395
- function manualByTodo(manualEvidence) {
396
- return new Map(manualEvidence.evidence.map((entry) => [entry.todo_id, entry]));
397
- }
398
-
399
- function manualRecordId(todoId) {
400
- return `manual-${todoId}`;
401
- }
402
-
403
- function conflictId(kind, index) {
404
- return `${kind}-${String(index + 1).padStart(3, '0')}`;
405
- }
406
-
407
- function compileConflicts(todoDrafts, graphUnknowns) {
408
- const conflicts = [];
409
- let writeIndex = 0;
410
- let stateIndex = 0;
411
- let effectIndex = 0;
412
- for (let leftIndex = 0; leftIndex < todoDrafts.length; leftIndex += 1) {
413
- for (let rightIndex = leftIndex + 1; rightIndex < todoDrafts.length; rightIndex += 1) {
414
- const left = todoDrafts[leftIndex];
415
- const right = todoDrafts[rightIndex];
416
- const rightOwns = new Set(right.owns.map(resourceKey));
417
- for (const resource of left.owns.filter((entry) => rightOwns.has(resourceKey(entry)))) {
418
- conflicts.push({
419
- id: conflictId('write-overlap', writeIndex++),
420
- kind: 'write_boundary',
421
- todo_ids: [left.id, right.id],
422
- resource,
423
- evidence_refs: unique([...left.graphRefs, ...right.graphRefs]).sort(),
424
- });
425
- }
426
-
427
- const stateTargets = unique([
428
- ...left.manual.state_reads,
429
- ...left.manual.state_writes,
430
- ].filter((target) => (
431
- right.manual.state_reads.includes(target) || right.manual.state_writes.includes(target)
432
- ) && (
433
- left.manual.state_writes.includes(target) || right.manual.state_writes.includes(target)
434
- ))).sort();
435
- for (const target of stateTargets) {
436
- conflicts.push({
437
- id: conflictId('state-overlap', stateIndex++),
438
- kind: 'state',
439
- todo_ids: [left.id, right.id],
440
- resource: { kind: 'state', target },
441
- evidence_refs: [manualRecordId(left.id), manualRecordId(right.id)],
442
- });
443
- }
444
-
445
- for (const target of left.manual.effects
446
- .filter((entry) => right.manual.effects.includes(entry)).sort()) {
447
- conflicts.push({
448
- id: conflictId('effect-overlap', effectIndex++),
449
- kind: 'effect',
450
- todo_ids: [left.id, right.id],
451
- resource: { kind: 'effect', target },
452
- evidence_refs: [manualRecordId(left.id), manualRecordId(right.id)],
453
- });
454
- }
455
- }
456
- }
457
-
458
- const allUnknowns = unique([
459
- ...graphUnknowns,
460
- ...todoDrafts.flatMap(({ unknowns }) => unknowns),
461
- ]);
462
- if (allUnknowns.length > 0 && todoDrafts.length >= 2) {
463
- const resource = { kind: 'dynamic', target: 'unresolved-boundary' };
464
- for (const draft of todoDrafts) draft.dynamicWrites.push(resource);
465
- conflicts.push({
466
- id: 'dynamic-unknown-001',
467
- kind: 'dynamic_unknown',
468
- todo_ids: [todoDrafts[0].id, todoDrafts[1].id],
469
- resource,
470
- evidence_refs: unique([
471
- ...todoDrafts.flatMap(({ graphRefs }) => graphRefs),
472
- ...todoDrafts.map(({ id }) => manualRecordId(id)),
473
- ]).sort(),
474
- });
475
- }
476
- return { conflicts, allUnknowns };
477
- }
478
-
479
- function graphRecords(querySet, sensorEvidence) {
480
- return querySet.queries.map((query, index) => ({
481
- id: query.id,
482
- operation: query.operation,
483
- status: sensorEvidence.outcomes[index].outcome,
484
- result_digest: digestArtifact(portableSensorOutcome(sensorEvidence.outcomes[index])),
485
- }));
486
- }
487
-
488
- function compileManifest({
489
- planInput,
490
- candidateSpec,
491
- manualEvidence,
492
- querySet,
493
- sensorEvidence,
494
- codeSnapshotDigest,
495
- surfaceMode,
496
- graphUnknowns,
497
- sensorVersion,
498
- }) {
499
- const manuals = manualByTodo(manualEvidence);
500
- const candidates = new Map(candidateSpec.todos.map((todo) => [todo.todo_id, todo]));
501
- const stableTests = candidateSpec.stable_surfaces
502
- .filter((surface) => surface.kind === 'path'
503
- && (surface.active_when === 'always' || surfaceMode === 'proposed'))
504
- .map(({ path: testPath }) => testPath);
505
- const drafts = planInput.todos.map((todo) => {
506
- const active = candidates.get(todo.id)[surfaceMode];
507
- const manual = manuals.get(todo.id);
508
- return {
509
- id: todo.id,
510
- owns: surfaceResources(active),
511
- graphRefs: surfaceEvidenceRefs(active),
512
- manual,
513
- dynamicWrites: [],
514
- unknowns: manual.unknowns.map((unknown) => `manual_unknown:${todo.id}:${unknown}`),
515
- tests: unique([...active.tests.map(({ path: testPath }) => testPath), ...stableTests]).sort(),
516
- };
517
- });
518
- const { conflicts, allUnknowns } = compileConflicts(drafts, graphUnknowns);
519
- const todos = drafts.map((draft) => ({
520
- id: draft.id,
521
- owns: draft.owns,
522
- reads: draft.manual.state_reads.map((target) => ({ kind: 'state', target })),
523
- writes: uniqueResources([
524
- ...draft.owns,
525
- ...draft.manual.state_writes.map((target) => ({ kind: 'state', target })),
526
- ...draft.manual.effects.map((target) => ({ kind: 'effect', target })),
527
- ...draft.dynamicWrites,
528
- ]),
529
- hard_needs: [],
530
- conflict_ids: conflicts.filter(({ todo_ids: todoIds }) => todoIds.includes(draft.id))
531
- .map(({ id }) => id),
532
- unknowns: unique([...graphUnknowns, ...draft.unknowns]),
533
- tests: draft.tests,
534
- evidence_refs: unique([...draft.graphRefs, manualRecordId(draft.id)]).sort(),
535
- }));
536
- const manifest = {
537
- schema: 'lattice.boundary_manifest.v1',
538
- plan_input_digest: digestArtifact(planInput),
539
- source: {
540
- code_snapshot_digest: codeSnapshotDigest,
541
- query_set_digest: digestArtifact(querySet),
542
- manual_evidence_digest: digestArtifact(manualEvidence),
543
- sensor_version: sensorVersion,
544
- },
545
- graph_evidence: graphRecords(querySet, sensorEvidence),
546
- manual_evidence: planInput.todos.map((todo) => ({
547
- id: manualRecordId(todo.id),
548
- todo_id: todo.id,
549
- result_digest: digestArtifact(manuals.get(todo.id)),
550
- })),
551
- todos,
552
- conflicts,
553
- unknowns: allUnknowns,
554
- };
555
- if (!validateBoundaryManifest(manifest)) fail('生成manifestがpublic contractを満たさない');
556
- return manifest;
557
- }
558
-
559
- function compileVerdict(manifest, candidateSpec, surfaceMode) {
560
- const hasUnknown = manifest.unknowns.length > 0;
561
- const hasManualConflict = manifest.conflicts.some(({ kind }) => kind === 'state' || kind === 'effect');
562
- const hasWriteConflict = manifest.conflicts.some(({ kind }) => kind === 'write_boundary');
563
- let verdict;
564
- let reasons;
565
- let seamCandidate = null;
566
- if (hasUnknown) {
567
- verdict = 'unknown_requires_evidence';
568
- reasons = ['graphまたはmanual unknownが残るためindependenceを確定できない'];
569
- } else if (hasManualConflict) {
570
- verdict = 'intentional_serial';
571
- reasons = ['shared manual state/effect conflictはcode seamでは切断できない'];
572
- } else if (hasWriteConflict && surfaceMode === 'current') {
573
- verdict = 'seam_candidate';
574
- reasons = ['current production/test write overlapはcandidate specのproposed surfaceへ切断可能'];
575
- seamCandidate = {
576
- id: candidateSpec.candidate_id,
577
- proposed_owns: candidateSpec.todos.map((todo) => ({
578
- todo_id: todo.todo_id,
579
- resources: surfaceResources(todo.proposed),
580
- })),
581
- preconditions: [
582
- 'all proposed production and test surfaces resolve exactly',
583
- 'transform-external black-box oracle passes before and after',
584
- ],
585
- };
586
- } else if (hasWriteConflict) {
587
- verdict = 'intentional_serial';
588
- reasons = ['proposed surfaceにもwrite overlapが残るため追加seamまたはjoinが必要'];
589
- } else {
590
- verdict = 'parallel_ready';
591
- reasons = ['same compilerが全production/test write resourceの非重複を導出した'];
592
- }
593
- const artifact = {
594
- schema: 'lattice.boundary_verdict.v1',
595
- boundary_manifest_digest: digestArtifact(manifest),
596
- verdicts: [{
597
- id: 'channel-label-verdict-v4',
598
- todo_ids: manifest.todos.map(({ id }) => id),
599
- verdict,
600
- conflict_ids: manifest.conflicts.map(({ id }) => id),
601
- seam_candidate: seamCandidate,
602
- reasons,
603
- unknowns: manifest.unknowns,
604
- }],
605
- };
606
- if (!validateBoundaryVerdict(artifact)) fail('生成verdictがpublic contractを満たさない');
607
- return artifact;
608
- }
609
-
610
- function compilePlan(planInput, manifest, planVersion) {
611
- const edgeKinds = new Map([
612
- ['write_boundary', 'write_conflict'],
613
- ['state', 'state_conflict'],
614
- ['effect', 'effect_conflict'],
615
- ['semantic', 'semantic_conflict'],
616
- ['dynamic_unknown', 'dynamic_unknown'],
617
- ]);
618
- const edges = manifest.conflicts.map((conflict) => ({
619
- id: conflict.id,
620
- from: conflict.todo_ids[0],
621
- to: conflict.todo_ids[1],
622
- kind: edgeKinds.get(conflict.kind),
623
- evidence_refs: conflict.evidence_refs,
624
- }));
625
- const waves = edges.length === 0
626
- ? [{ index: 0, todo_ids: planInput.todos.map(({ id }) => id) }]
627
- : planInput.todos.map((todo, index) => ({ index, todo_ids: [todo.id] }));
628
- const graph = {
629
- schema: 'lattice.plan_graph.v1',
630
- plan_version: planVersion,
631
- source_manifest_digest: digestArtifact(manifest),
632
- capacity: { writers: planInput.capacity.writers },
633
- nodes: planInput.todos.map((todo) => ({
634
- id: todo.id,
635
- outcome: todo.outcome,
636
- owned_boundaries: manifest.todos.find(({ id }) => id === todo.id).owns,
637
- })),
638
- edges,
639
- joins: [],
640
- waves,
641
- minimum_feasible_waves: waves.length,
642
- };
643
- if (!validatePlanGraph(graph)) fail('生成plan graphがpublic contractを満たさない');
644
- return graph;
645
- }
646
-
647
- /**
648
- * 同じcandidate specと規則から任意code snapshotのRC1 boundaryをcompileする。
649
- * @param {object} options
650
- * @returns {object}
651
- */
652
- export function compileBoundaryCondition(options = {}) {
653
- if (isPlainObject(options) && Object.hasOwn(options, 'condition')) {
654
- fail('condition selector is forbidden');
655
- }
656
- if (!exactRecord(options, OPTION_KEYS)) fail('compiler optionsがexact shapeでない');
657
- const {
658
- planInput,
659
- candidateSpec,
660
- manualEvidence,
661
- querySet,
662
- sensorEvidence,
663
- codeSnapshotDigest,
664
- planVersion,
665
- } = options;
666
- for (const value of [planInput, candidateSpec, manualEvidence, querySet, sensorEvidence]) {
667
- canonicalizeArtifact(value);
668
- }
669
- if (!validatePlanInput(planInput)
670
- || planInput.todos.length !== 2
671
- || planInput.capacity.writers !== 2) {
672
- fail('RC1 plan inputがpublic contractまたは固定topologyを満たさない');
673
- }
674
- if (!SHA256.test(codeSnapshotDigest) || !identifier(planVersion)) {
675
- fail('snapshot digestまたはplan versionが不正');
676
- }
677
- assertManualEvidence(planInput, manualEvidence);
678
- assertCandidateSpec(planInput, candidateSpec);
679
- assertQuerySet(querySet, candidateSpec);
680
- assertLatticeSensorEvidence(querySet, sensorEvidence);
681
- const outcomes = outcomeMap(querySet, sensorEvidence);
682
- const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
683
- const status = outcomes.get(statusQuery.id);
684
- if (status.outcome !== 'ready' || !nonEmptyText(status.data?.version)) {
685
- fail(`LatticeSensor statusがreadyでない: ${status.outcome}`);
686
- }
687
- const selection = deriveSurfaceMode(planInput, candidateSpec, outcomes);
688
- const boundaryManifest = compileManifest({
689
- planInput,
690
- candidateSpec,
691
- manualEvidence,
692
- querySet,
693
- sensorEvidence,
694
- codeSnapshotDigest,
695
- surfaceMode: selection.mode,
696
- graphUnknowns: selection.unknowns,
697
- sensorVersion: status.data.version,
698
- });
699
- const boundaryVerdict = compileVerdict(boundaryManifest, candidateSpec, selection.mode);
700
- const planGraph = compilePlan(planInput, boundaryManifest, planVersion);
701
- return {
702
- compiler: { ...RC1_BOUNDARY_COMPILER_CONTRACT },
703
- candidate_spec_digest: digestArtifact(candidateSpec),
704
- surface_mode: selection.mode,
705
- boundary_manifest: boundaryManifest,
706
- boundary_manifest_digest: digestArtifact(boundaryManifest),
707
- boundary_verdict: boundaryVerdict,
708
- boundary_verdict_digest: digestArtifact(boundaryVerdict),
709
- plan_graph: planGraph,
710
- plan_graph_digest: digestArtifact(planGraph),
711
- };
712
- }
1
+ import {
2
+ canonicalizeArtifact,
3
+ digestArtifact,
4
+ validateBoundaryManifest,
5
+ validateBoundaryVerdict,
6
+ validatePlanGraph,
7
+ validatePlanInput,
8
+ } from './artifact-contracts.mjs';
9
+ import { portableSensorOutcome } from './sensor-adapter.mjs';
10
+
11
+ const SHA256 = /^[0-9a-f]{64}$/;
12
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
13
+ const OPERATIONS = new Set(['status', 'query', 'callers', 'callees', 'impact', 'affected']);
14
+ const OPTION_KEYS = [
15
+ 'candidateSpec',
16
+ 'codeSnapshotDigest',
17
+ 'sensorEvidence',
18
+ 'manualEvidence',
19
+ 'planInput',
20
+ 'planVersion',
21
+ 'querySet',
22
+ ];
23
+
24
+ export const RC1_BOUNDARY_COMPILER_CONTRACT = Object.freeze({
25
+ export_name: 'compileBoundaryCondition',
26
+ condition_selector: 'forbidden',
27
+ surface_resolution: 'exact_graph_name_or_qualified_name_at_expected_path',
28
+ conflict_rule: 'pairwise_write_resource_intersection',
29
+ });
30
+
31
+ function fail(reason) {
32
+ throw new TypeError(`RC1 v4 boundary compiler契約違反: ${reason}`);
33
+ }
34
+
35
+ function isPlainObject(value) {
36
+ return value !== null
37
+ && typeof value === 'object'
38
+ && !Array.isArray(value)
39
+ && Object.getPrototypeOf(value) === Object.prototype;
40
+ }
41
+
42
+ function exactRecord(value, keys) {
43
+ if (!isPlainObject(value)) return false;
44
+ const actual = Object.keys(value).sort();
45
+ const expected = [...keys].sort();
46
+ return actual.length === expected.length
47
+ && actual.every((key, index) => key === expected[index]);
48
+ }
49
+
50
+ function nonEmptyText(value) {
51
+ return typeof value === 'string' && value.length > 0 && value.length <= 4_096;
52
+ }
53
+
54
+ function identifier(value) {
55
+ return typeof value === 'string' && IDENTIFIER.test(value);
56
+ }
57
+
58
+ function repoPath(value) {
59
+ return typeof value === 'string'
60
+ && value.length > 0
61
+ && value.length <= 1_024
62
+ && !value.includes('\0')
63
+ && !value.startsWith('/')
64
+ && !value.split('/').includes('..');
65
+ }
66
+
67
+ function unique(values) {
68
+ return [...new Set(values)];
69
+ }
70
+
71
+ function resourceKey(value) {
72
+ return `${value.kind}\0${value.target}`;
73
+ }
74
+
75
+ function uniqueResources(values) {
76
+ return [...new Map(values.map((value) => [resourceKey(value), value])).values()]
77
+ .sort((left, right) => resourceKey(left).localeCompare(resourceKey(right)));
78
+ }
79
+
80
+ function assertManualEvidence(planInput, manualEvidence) {
81
+ if (!exactRecord(manualEvidence, ['schema', 'evidence'])
82
+ || manualEvidence.schema !== 'lattice.manual_boundary_evidence.v1'
83
+ || !Array.isArray(manualEvidence.evidence)
84
+ || manualEvidence.evidence.length !== planInput.todos.length) {
85
+ fail('manual evidence rootがplan inputと一致しない');
86
+ }
87
+ const todoIds = planInput.todos.map(({ id }) => id);
88
+ if (new Set(manualEvidence.evidence.map(({ todo_id: todoId }) => todoId)).size !== todoIds.length) {
89
+ fail('manual evidence todo IDが一意でない');
90
+ }
91
+ for (const entry of manualEvidence.evidence) {
92
+ if (!exactRecord(entry, ['todo_id', 'state_reads', 'state_writes', 'effects', 'unknowns'])
93
+ || !todoIds.includes(entry.todo_id)
94
+ || ![entry.state_reads, entry.state_writes, entry.effects, entry.unknowns]
95
+ .every((values) => Array.isArray(values)
96
+ && values.every(nonEmptyText)
97
+ && new Set(values).size === values.length)) {
98
+ fail('manual evidence recordが不正');
99
+ }
100
+ }
101
+ }
102
+
103
+ function assertTestSurface(value, { proposed }) {
104
+ if (!exactRecord(value, [
105
+ 'symbol',
106
+ 'path',
107
+ 'query_id',
108
+ 'impact_id',
109
+ 'assertion_id',
110
+ 'provenance',
111
+ ])
112
+ || (proposed ? !nonEmptyText(value.symbol) : value.symbol !== null)
113
+ || !repoPath(value.path)
114
+ || !identifier(value.query_id)
115
+ || (proposed ? !identifier(value.impact_id) : value.impact_id !== null)
116
+ || !identifier(value.assertion_id)
117
+ || !exactRecord(value.provenance, ['kind', 'ref'])
118
+ || value.provenance.kind !== 'todo_outcome'
119
+ || !nonEmptyText(value.provenance.ref)) {
120
+ fail(`${proposed ? 'proposed' : 'current'} test surfaceが不正`);
121
+ }
122
+ }
123
+
124
+ function assertProductionSurface(value) {
125
+ if (!exactRecord(value, ['symbol', 'path', 'query_id', 'impact_id', 'link_query_id'])
126
+ || !nonEmptyText(value.symbol)
127
+ || !repoPath(value.path)
128
+ || !identifier(value.query_id)
129
+ || !identifier(value.impact_id)
130
+ || !identifier(value.link_query_id)) {
131
+ fail('production surfaceが不正');
132
+ }
133
+ }
134
+
135
+ function assertCandidateSpec(planInput, candidateSpec) {
136
+ if (!exactRecord(candidateSpec, [
137
+ 'schema',
138
+ 'candidate_id',
139
+ 'plan_input_ref',
140
+ 'query_set_ref',
141
+ 'behavior_oracle_ref',
142
+ 'compiler_contract',
143
+ 'stable_surfaces',
144
+ 'todos',
145
+ ])
146
+ || candidateSpec.schema !== 'lattice.rc1.boundary_candidate_spec.v2'
147
+ || !identifier(candidateSpec.candidate_id)
148
+ || !repoPath(candidateSpec.plan_input_ref)
149
+ || !repoPath(candidateSpec.query_set_ref)
150
+ || !repoPath(candidateSpec.behavior_oracle_ref)
151
+ || !exactRecord(candidateSpec.compiler_contract, [
152
+ 'condition_selector',
153
+ 'surface_resolution',
154
+ 'proposed_activation',
155
+ 'unresolved_policy',
156
+ 'conflict_rule',
157
+ ])
158
+ || candidateSpec.compiler_contract.condition_selector !== 'forbidden'
159
+ || candidateSpec.compiler_contract.surface_resolution
160
+ !== 'exact_graph_name_or_qualified_name_at_expected_path'
161
+ || candidateSpec.compiler_contract.proposed_activation
162
+ !== 'all_proposed_production_and_test_surfaces_exact'
163
+ || candidateSpec.compiler_contract.unresolved_policy !== 'typed_unknown'
164
+ || candidateSpec.compiler_contract.conflict_rule !== 'pairwise_write_resource_intersection'
165
+ || !Array.isArray(candidateSpec.stable_surfaces)
166
+ || candidateSpec.stable_surfaces.length === 0
167
+ || !Array.isArray(candidateSpec.todos)
168
+ || candidateSpec.todos.length !== planInput.todos.length) {
169
+ fail('candidate spec rootが不正');
170
+ }
171
+
172
+ for (const surface of candidateSpec.stable_surfaces) {
173
+ if (!exactRecord(surface, ['kind', 'target', 'path', 'role', 'active_when'])
174
+ || !new Set(['symbol', 'path']).has(surface.kind)
175
+ || !nonEmptyText(surface.target)
176
+ || !repoPath(surface.path)
177
+ || !identifier(surface.role)
178
+ || !new Set(['always', 'proposed']).has(surface.active_when)) {
179
+ fail('stable surfaceが不正');
180
+ }
181
+ }
182
+
183
+ const planTodos = new Map(planInput.todos.map((todo) => [todo.id, todo]));
184
+ for (const todo of candidateSpec.todos) {
185
+ if (!exactRecord(todo, ['todo_id', 'outcome', 'current', 'proposed'])
186
+ || !planTodos.has(todo.todo_id)
187
+ || todo.outcome !== planTodos.get(todo.todo_id).outcome) {
188
+ fail('candidate TODOがplan inputと一致しない');
189
+ }
190
+ for (const [mode, proposed] of [['current', false], ['proposed', true]]) {
191
+ const value = todo[mode];
192
+ if (!exactRecord(value, ['production', 'tests'])
193
+ || !Array.isArray(value.tests)
194
+ || value.tests.length === 0) {
195
+ fail(`${mode} surface setが不正`);
196
+ }
197
+ assertProductionSurface(value.production);
198
+ for (const test of value.tests) assertTestSurface(test, { proposed });
199
+ }
200
+ }
201
+ if (new Set(candidateSpec.todos.map(({ todo_id: todoId }) => todoId)).size
202
+ !== planInput.todos.length) {
203
+ fail('candidate TODO IDが一意でない');
204
+ }
205
+ }
206
+
207
+ function assertQuerySet(querySet, candidateSpec) {
208
+ if (!exactRecord(querySet, ['schema', 'queries'])
209
+ || querySet.schema !== 'lattice.sensor_query_set.v2'
210
+ || !Array.isArray(querySet.queries)
211
+ || querySet.queries.length === 0
212
+ || querySet.queries.length > 256) {
213
+ fail('query set rootが不正');
214
+ }
215
+ const ids = new Set();
216
+ for (const query of querySet.queries) {
217
+ if (!isPlainObject(query) || !identifier(query.id) || ids.has(query.id)
218
+ || !OPERATIONS.has(query.operation)) {
219
+ fail('query set recordが不正');
220
+ }
221
+ ids.add(query.id);
222
+ if (query.operation === 'status') {
223
+ if (!exactRecord(query, ['id', 'operation'])) fail('status query shapeが不正');
224
+ } else if (query.operation === 'affected') {
225
+ if (!exactRecord(query, ['id', 'operation', 'targets'])
226
+ || !Array.isArray(query.targets)
227
+ || query.targets.length === 0
228
+ || !query.targets.every(repoPath)
229
+ || new Set(query.targets).size !== query.targets.length) {
230
+ fail('affected query shapeが不正');
231
+ }
232
+ } else if (!exactRecord(query, ['id', 'operation', 'target'])
233
+ || !nonEmptyText(query.target)) {
234
+ fail('graph query shapeが不正');
235
+ }
236
+ }
237
+ if (querySet.queries.filter(({ operation }) => operation === 'status').length !== 1
238
+ || querySet.queries.filter(({ operation }) => operation === 'affected').length !== 1) {
239
+ fail('query setにstatusとaffectedがexactly one必要');
240
+ }
241
+
242
+ const referenced = candidateSpec.todos.flatMap((todo) => [todo.current, todo.proposed]
243
+ .flatMap((surface) => [
244
+ surface.production.query_id,
245
+ surface.production.impact_id,
246
+ surface.production.link_query_id,
247
+ ...surface.tests.flatMap((entry) => [entry.query_id, entry.impact_id].filter(Boolean)),
248
+ ]));
249
+ if (referenced.some((id) => !ids.has(id))) {
250
+ fail('candidate specがquery set外のIDを参照する');
251
+ }
252
+ }
253
+
254
+ function assertLatticeSensorEvidence(querySet, sensorEvidence) {
255
+ if (!isPlainObject(sensorEvidence)
256
+ || !Array.isArray(sensorEvidence.outcomes)
257
+ || sensorEvidence.outcomes.length !== querySet.queries.length) {
258
+ fail('LatticeSensor evidence rootがquery setと一致しない');
259
+ }
260
+ for (let index = 0; index < querySet.queries.length; index += 1) {
261
+ const query = querySet.queries[index];
262
+ const outcome = sensorEvidence.outcomes[index];
263
+ if (!isPlainObject(outcome)
264
+ || outcome.id !== query.id
265
+ || outcome.operation !== query.operation
266
+ || !nonEmptyText(outcome.outcome)) {
267
+ fail(`LatticeSensor evidence ${query.id}がID/operation/順序と一致しない`);
268
+ }
269
+ if (query.operation !== 'status' && query.operation !== 'affected'
270
+ && outcome.target !== query.target) {
271
+ fail(`LatticeSensor evidence ${query.id}のtargetがquery setと一致しない`);
272
+ }
273
+ if (query.operation === 'affected'
274
+ && (!Array.isArray(outcome.targets)
275
+ || outcome.targets.length !== query.targets.length
276
+ || outcome.targets.some((entry, targetIndex) => (
277
+ !isPlainObject(entry) || entry.target !== query.targets[targetIndex]
278
+ )))) {
279
+ fail(`LatticeSensor evidence ${query.id}のaffected targetがquery setと一致しない`);
280
+ }
281
+ }
282
+ }
283
+
284
+ function exactNodeAt(records, target, expectedPath) {
285
+ if (!Array.isArray(records)) return false;
286
+ const exact = records.filter((entry) => isPlainObject(entry?.node)
287
+ && (entry.node.name === target || entry.node.qualifiedName === target)
288
+ && entry.node.filePath === expectedPath);
289
+ return exact.length === 1;
290
+ }
291
+
292
+ function exactQueryStatus(outcome, target, expectedPath) {
293
+ if (outcome?.outcome === 'symbol_absent') return 'absent';
294
+ if (outcome?.outcome !== 'ready') return 'unknown';
295
+ return exactNodeAt(outcome.data, target, expectedPath) ? 'ready' : 'unknown';
296
+ }
297
+
298
+ function exactResolutionStatus(outcome, target, expectedPath) {
299
+ if (outcome?.outcome === 'symbol_absent') return 'absent';
300
+ if (outcome?.outcome !== 'ready') return 'unknown';
301
+ return exactNodeAt(outcome.resolution, target, expectedPath) ? 'ready' : 'unknown';
302
+ }
303
+
304
+ function callerLinkStatus(outcome, production, anchor) {
305
+ const resolution = exactResolutionStatus(outcome, production.symbol, production.path);
306
+ if (resolution !== 'ready') return resolution;
307
+ const callers = outcome.data?.callers;
308
+ if (!Array.isArray(callers)) return 'unknown';
309
+ return callers.some((entry) => entry?.name === anchor.symbol && entry?.filePath === anchor.path)
310
+ ? 'ready'
311
+ : 'unknown';
312
+ }
313
+
314
+ function outcomeMap(querySet, sensorEvidence) {
315
+ return new Map(querySet.queries.map((query, index) => [
316
+ query.id,
317
+ sensorEvidence.outcomes[index],
318
+ ]));
319
+ }
320
+
321
+ function statusesForSurface(surface, outcomes, anchor, { proposed }) {
322
+ const statuses = [
323
+ exactQueryStatus(
324
+ outcomes.get(surface.production.query_id),
325
+ surface.production.symbol,
326
+ surface.production.path,
327
+ ),
328
+ exactResolutionStatus(
329
+ outcomes.get(surface.production.impact_id),
330
+ surface.production.symbol,
331
+ surface.production.path,
332
+ ),
333
+ ];
334
+ if (proposed) {
335
+ statuses.push(callerLinkStatus(
336
+ outcomes.get(surface.production.link_query_id),
337
+ surface.production,
338
+ anchor,
339
+ ));
340
+ }
341
+ for (const test of surface.tests) {
342
+ const target = test.symbol ?? test.path;
343
+ statuses.push(exactQueryStatus(outcomes.get(test.query_id), target, test.path));
344
+ if (test.impact_id !== null) {
345
+ statuses.push(exactResolutionStatus(outcomes.get(test.impact_id), target, test.path));
346
+ }
347
+ }
348
+ return statuses;
349
+ }
350
+
351
+ function deriveSurfaceMode(planInput, candidateSpec, outcomes) {
352
+ const current = [];
353
+ const proposed = [];
354
+ for (const candidate of candidateSpec.todos) {
355
+ const anchor = planInput.todos.find(({ id }) => id === candidate.todo_id).anchor;
356
+ current.push(...statusesForSurface(candidate.current, outcomes, anchor, { proposed: false }));
357
+ proposed.push(...statusesForSurface(candidate.proposed, outcomes, anchor, { proposed: true }));
358
+ }
359
+ if (current.every((status) => status === 'ready')
360
+ && proposed.every((status) => status === 'absent')) {
361
+ return { mode: 'current', unknowns: [] };
362
+ }
363
+ if (current.every((status) => status === 'ready')
364
+ && proposed.every((status) => status === 'ready')) {
365
+ return { mode: 'proposed', unknowns: [] };
366
+ }
367
+ return {
368
+ mode: 'current',
369
+ unknowns: [
370
+ `surface_resolution_unknown:current=${current.join(',')}:proposed=${proposed.join(',')}`,
371
+ ],
372
+ };
373
+ }
374
+
375
+ function surfaceResources(surface) {
376
+ return uniqueResources([
377
+ { kind: 'symbol', target: surface.production.symbol },
378
+ { kind: 'path', target: surface.production.path },
379
+ ...surface.tests.flatMap((test) => [
380
+ ...(test.symbol === null ? [] : [{ kind: 'symbol', target: test.symbol }]),
381
+ { kind: 'path', target: test.path },
382
+ ]),
383
+ ]);
384
+ }
385
+
386
+ function surfaceEvidenceRefs(surface) {
387
+ return unique([
388
+ surface.production.query_id,
389
+ surface.production.impact_id,
390
+ surface.production.link_query_id,
391
+ ...surface.tests.flatMap((test) => [test.query_id, test.impact_id].filter(Boolean)),
392
+ ]).sort();
393
+ }
394
+
395
+ function manualByTodo(manualEvidence) {
396
+ return new Map(manualEvidence.evidence.map((entry) => [entry.todo_id, entry]));
397
+ }
398
+
399
+ function manualRecordId(todoId) {
400
+ return `manual-${todoId}`;
401
+ }
402
+
403
+ function conflictId(kind, index) {
404
+ return `${kind}-${String(index + 1).padStart(3, '0')}`;
405
+ }
406
+
407
+ function compileConflicts(todoDrafts, graphUnknowns) {
408
+ const conflicts = [];
409
+ let writeIndex = 0;
410
+ let stateIndex = 0;
411
+ let effectIndex = 0;
412
+ for (let leftIndex = 0; leftIndex < todoDrafts.length; leftIndex += 1) {
413
+ for (let rightIndex = leftIndex + 1; rightIndex < todoDrafts.length; rightIndex += 1) {
414
+ const left = todoDrafts[leftIndex];
415
+ const right = todoDrafts[rightIndex];
416
+ const rightOwns = new Set(right.owns.map(resourceKey));
417
+ for (const resource of left.owns.filter((entry) => rightOwns.has(resourceKey(entry)))) {
418
+ conflicts.push({
419
+ id: conflictId('write-overlap', writeIndex++),
420
+ kind: 'write_boundary',
421
+ todo_ids: [left.id, right.id],
422
+ resource,
423
+ evidence_refs: unique([...left.graphRefs, ...right.graphRefs]).sort(),
424
+ });
425
+ }
426
+
427
+ const stateTargets = unique([
428
+ ...left.manual.state_reads,
429
+ ...left.manual.state_writes,
430
+ ].filter((target) => (
431
+ right.manual.state_reads.includes(target) || right.manual.state_writes.includes(target)
432
+ ) && (
433
+ left.manual.state_writes.includes(target) || right.manual.state_writes.includes(target)
434
+ ))).sort();
435
+ for (const target of stateTargets) {
436
+ conflicts.push({
437
+ id: conflictId('state-overlap', stateIndex++),
438
+ kind: 'state',
439
+ todo_ids: [left.id, right.id],
440
+ resource: { kind: 'state', target },
441
+ evidence_refs: [manualRecordId(left.id), manualRecordId(right.id)],
442
+ });
443
+ }
444
+
445
+ for (const target of left.manual.effects
446
+ .filter((entry) => right.manual.effects.includes(entry)).sort()) {
447
+ conflicts.push({
448
+ id: conflictId('effect-overlap', effectIndex++),
449
+ kind: 'effect',
450
+ todo_ids: [left.id, right.id],
451
+ resource: { kind: 'effect', target },
452
+ evidence_refs: [manualRecordId(left.id), manualRecordId(right.id)],
453
+ });
454
+ }
455
+ }
456
+ }
457
+
458
+ const allUnknowns = unique([
459
+ ...graphUnknowns,
460
+ ...todoDrafts.flatMap(({ unknowns }) => unknowns),
461
+ ]);
462
+ if (allUnknowns.length > 0 && todoDrafts.length >= 2) {
463
+ const resource = { kind: 'dynamic', target: 'unresolved-boundary' };
464
+ for (const draft of todoDrafts) draft.dynamicWrites.push(resource);
465
+ conflicts.push({
466
+ id: 'dynamic-unknown-001',
467
+ kind: 'dynamic_unknown',
468
+ todo_ids: [todoDrafts[0].id, todoDrafts[1].id],
469
+ resource,
470
+ evidence_refs: unique([
471
+ ...todoDrafts.flatMap(({ graphRefs }) => graphRefs),
472
+ ...todoDrafts.map(({ id }) => manualRecordId(id)),
473
+ ]).sort(),
474
+ });
475
+ }
476
+ return { conflicts, allUnknowns };
477
+ }
478
+
479
+ function graphRecords(querySet, sensorEvidence) {
480
+ return querySet.queries.map((query, index) => ({
481
+ id: query.id,
482
+ operation: query.operation,
483
+ status: sensorEvidence.outcomes[index].outcome,
484
+ result_digest: digestArtifact(portableSensorOutcome(sensorEvidence.outcomes[index])),
485
+ }));
486
+ }
487
+
488
+ function compileManifest({
489
+ planInput,
490
+ candidateSpec,
491
+ manualEvidence,
492
+ querySet,
493
+ sensorEvidence,
494
+ codeSnapshotDigest,
495
+ surfaceMode,
496
+ graphUnknowns,
497
+ sensorVersion,
498
+ }) {
499
+ const manuals = manualByTodo(manualEvidence);
500
+ const candidates = new Map(candidateSpec.todos.map((todo) => [todo.todo_id, todo]));
501
+ const stableTests = candidateSpec.stable_surfaces
502
+ .filter((surface) => surface.kind === 'path'
503
+ && (surface.active_when === 'always' || surfaceMode === 'proposed'))
504
+ .map(({ path: testPath }) => testPath);
505
+ const drafts = planInput.todos.map((todo) => {
506
+ const active = candidates.get(todo.id)[surfaceMode];
507
+ const manual = manuals.get(todo.id);
508
+ return {
509
+ id: todo.id,
510
+ owns: surfaceResources(active),
511
+ graphRefs: surfaceEvidenceRefs(active),
512
+ manual,
513
+ dynamicWrites: [],
514
+ unknowns: manual.unknowns.map((unknown) => `manual_unknown:${todo.id}:${unknown}`),
515
+ tests: unique([...active.tests.map(({ path: testPath }) => testPath), ...stableTests]).sort(),
516
+ };
517
+ });
518
+ const { conflicts, allUnknowns } = compileConflicts(drafts, graphUnknowns);
519
+ const todos = drafts.map((draft) => ({
520
+ id: draft.id,
521
+ owns: draft.owns,
522
+ reads: draft.manual.state_reads.map((target) => ({ kind: 'state', target })),
523
+ writes: uniqueResources([
524
+ ...draft.owns,
525
+ ...draft.manual.state_writes.map((target) => ({ kind: 'state', target })),
526
+ ...draft.manual.effects.map((target) => ({ kind: 'effect', target })),
527
+ ...draft.dynamicWrites,
528
+ ]),
529
+ hard_needs: [],
530
+ conflict_ids: conflicts.filter(({ todo_ids: todoIds }) => todoIds.includes(draft.id))
531
+ .map(({ id }) => id),
532
+ unknowns: unique([...graphUnknowns, ...draft.unknowns]),
533
+ tests: draft.tests,
534
+ evidence_refs: unique([...draft.graphRefs, manualRecordId(draft.id)]).sort(),
535
+ }));
536
+ const manifest = {
537
+ schema: 'lattice.boundary_manifest.v1',
538
+ plan_input_digest: digestArtifact(planInput),
539
+ source: {
540
+ code_snapshot_digest: codeSnapshotDigest,
541
+ query_set_digest: digestArtifact(querySet),
542
+ manual_evidence_digest: digestArtifact(manualEvidence),
543
+ sensor_version: sensorVersion,
544
+ },
545
+ graph_evidence: graphRecords(querySet, sensorEvidence),
546
+ manual_evidence: planInput.todos.map((todo) => ({
547
+ id: manualRecordId(todo.id),
548
+ todo_id: todo.id,
549
+ result_digest: digestArtifact(manuals.get(todo.id)),
550
+ })),
551
+ todos,
552
+ conflicts,
553
+ unknowns: allUnknowns,
554
+ };
555
+ if (!validateBoundaryManifest(manifest)) fail('生成manifestがpublic contractを満たさない');
556
+ return manifest;
557
+ }
558
+
559
+ function compileVerdict(manifest, candidateSpec, surfaceMode) {
560
+ const hasUnknown = manifest.unknowns.length > 0;
561
+ const hasManualConflict = manifest.conflicts.some(({ kind }) => kind === 'state' || kind === 'effect');
562
+ const hasWriteConflict = manifest.conflicts.some(({ kind }) => kind === 'write_boundary');
563
+ let verdict;
564
+ let reasons;
565
+ let seamCandidate = null;
566
+ if (hasUnknown) {
567
+ verdict = 'unknown_requires_evidence';
568
+ reasons = ['graphまたはmanual unknownが残るためindependenceを確定できない'];
569
+ } else if (hasManualConflict) {
570
+ verdict = 'intentional_serial';
571
+ reasons = ['shared manual state/effect conflictはcode seamでは切断できない'];
572
+ } else if (hasWriteConflict && surfaceMode === 'current') {
573
+ verdict = 'seam_candidate';
574
+ reasons = ['current production/test write overlapはcandidate specのproposed surfaceへ切断可能'];
575
+ seamCandidate = {
576
+ id: candidateSpec.candidate_id,
577
+ proposed_owns: candidateSpec.todos.map((todo) => ({
578
+ todo_id: todo.todo_id,
579
+ resources: surfaceResources(todo.proposed),
580
+ })),
581
+ preconditions: [
582
+ 'all proposed production and test surfaces resolve exactly',
583
+ 'transform-external black-box oracle passes before and after',
584
+ ],
585
+ };
586
+ } else if (hasWriteConflict) {
587
+ verdict = 'intentional_serial';
588
+ reasons = ['proposed surfaceにもwrite overlapが残るため追加seamまたはjoinが必要'];
589
+ } else {
590
+ verdict = 'parallel_ready';
591
+ reasons = ['same compilerが全production/test write resourceの非重複を導出した'];
592
+ }
593
+ const artifact = {
594
+ schema: 'lattice.boundary_verdict.v1',
595
+ boundary_manifest_digest: digestArtifact(manifest),
596
+ verdicts: [{
597
+ id: 'channel-label-verdict-v4',
598
+ todo_ids: manifest.todos.map(({ id }) => id),
599
+ verdict,
600
+ conflict_ids: manifest.conflicts.map(({ id }) => id),
601
+ seam_candidate: seamCandidate,
602
+ reasons,
603
+ unknowns: manifest.unknowns,
604
+ }],
605
+ };
606
+ if (!validateBoundaryVerdict(artifact)) fail('生成verdictがpublic contractを満たさない');
607
+ return artifact;
608
+ }
609
+
610
+ function compilePlan(planInput, manifest, planVersion) {
611
+ const edgeKinds = new Map([
612
+ ['write_boundary', 'write_conflict'],
613
+ ['state', 'state_conflict'],
614
+ ['effect', 'effect_conflict'],
615
+ ['semantic', 'semantic_conflict'],
616
+ ['dynamic_unknown', 'dynamic_unknown'],
617
+ ]);
618
+ const edges = manifest.conflicts.map((conflict) => ({
619
+ id: conflict.id,
620
+ from: conflict.todo_ids[0],
621
+ to: conflict.todo_ids[1],
622
+ kind: edgeKinds.get(conflict.kind),
623
+ evidence_refs: conflict.evidence_refs,
624
+ }));
625
+ const waves = edges.length === 0
626
+ ? [{ index: 0, todo_ids: planInput.todos.map(({ id }) => id) }]
627
+ : planInput.todos.map((todo, index) => ({ index, todo_ids: [todo.id] }));
628
+ const graph = {
629
+ schema: 'lattice.plan_graph.v1',
630
+ plan_version: planVersion,
631
+ source_manifest_digest: digestArtifact(manifest),
632
+ capacity: { writers: planInput.capacity.writers },
633
+ nodes: planInput.todos.map((todo) => ({
634
+ id: todo.id,
635
+ outcome: todo.outcome,
636
+ owned_boundaries: manifest.todos.find(({ id }) => id === todo.id).owns,
637
+ })),
638
+ edges,
639
+ joins: [],
640
+ waves,
641
+ minimum_feasible_waves: waves.length,
642
+ };
643
+ if (!validatePlanGraph(graph)) fail('生成plan graphがpublic contractを満たさない');
644
+ return graph;
645
+ }
646
+
647
+ /**
648
+ * 同じcandidate specと規則から任意code snapshotのRC1 boundaryをcompileする。
649
+ * @param {object} options
650
+ * @returns {object}
651
+ */
652
+ export function compileBoundaryCondition(options = {}) {
653
+ if (isPlainObject(options) && Object.hasOwn(options, 'condition')) {
654
+ fail('condition selector is forbidden');
655
+ }
656
+ if (!exactRecord(options, OPTION_KEYS)) fail('compiler optionsがexact shapeでない');
657
+ const {
658
+ planInput,
659
+ candidateSpec,
660
+ manualEvidence,
661
+ querySet,
662
+ sensorEvidence,
663
+ codeSnapshotDigest,
664
+ planVersion,
665
+ } = options;
666
+ for (const value of [planInput, candidateSpec, manualEvidence, querySet, sensorEvidence]) {
667
+ canonicalizeArtifact(value);
668
+ }
669
+ if (!validatePlanInput(planInput)
670
+ || planInput.todos.length !== 2
671
+ || planInput.capacity.writers !== 2) {
672
+ fail('RC1 plan inputがpublic contractまたは固定topologyを満たさない');
673
+ }
674
+ if (!SHA256.test(codeSnapshotDigest) || !identifier(planVersion)) {
675
+ fail('snapshot digestまたはplan versionが不正');
676
+ }
677
+ assertManualEvidence(planInput, manualEvidence);
678
+ assertCandidateSpec(planInput, candidateSpec);
679
+ assertQuerySet(querySet, candidateSpec);
680
+ assertLatticeSensorEvidence(querySet, sensorEvidence);
681
+ const outcomes = outcomeMap(querySet, sensorEvidence);
682
+ const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
683
+ const status = outcomes.get(statusQuery.id);
684
+ if (status.outcome !== 'ready' || !nonEmptyText(status.data?.version)) {
685
+ fail(`LatticeSensor statusがreadyでない: ${status.outcome}`);
686
+ }
687
+ const selection = deriveSurfaceMode(planInput, candidateSpec, outcomes);
688
+ const boundaryManifest = compileManifest({
689
+ planInput,
690
+ candidateSpec,
691
+ manualEvidence,
692
+ querySet,
693
+ sensorEvidence,
694
+ codeSnapshotDigest,
695
+ surfaceMode: selection.mode,
696
+ graphUnknowns: selection.unknowns,
697
+ sensorVersion: status.data.version,
698
+ });
699
+ const boundaryVerdict = compileVerdict(boundaryManifest, candidateSpec, selection.mode);
700
+ const planGraph = compilePlan(planInput, boundaryManifest, planVersion);
701
+ return {
702
+ compiler: { ...RC1_BOUNDARY_COMPILER_CONTRACT },
703
+ candidate_spec_digest: digestArtifact(candidateSpec),
704
+ surface_mode: selection.mode,
705
+ boundary_manifest: boundaryManifest,
706
+ boundary_manifest_digest: digestArtifact(boundaryManifest),
707
+ boundary_verdict: boundaryVerdict,
708
+ boundary_verdict_digest: digestArtifact(boundaryVerdict),
709
+ plan_graph: planGraph,
710
+ plan_graph_digest: digestArtifact(planGraph),
711
+ };
712
+ }