@quolu/lattice 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1763 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ import { digestArtifact } from './artifact-contracts.mjs';
4
+ import { portableSensorOutcome } from './sensor-adapter.mjs';
5
+ import {
6
+ SEAM_PROPOSAL_SCHEMA,
7
+ deriveSeamProposalId,
8
+ validateSeamProposal,
9
+ } from './seam-proposal-contracts.mjs';
10
+ import {
11
+ synthesizeWitnessRunRequest,
12
+ validateTodoIndependence,
13
+ validateTodoWitnessSet,
14
+ } from './todo-independence-contracts.mjs';
15
+ import {
16
+ digestTodoArtifact,
17
+ todoSelfDigest,
18
+ validateTodoPlan,
19
+ } from './todo-contracts.mjs';
20
+ import {
21
+ selfDigest,
22
+ validateRunRequest,
23
+ } from './runtime-contracts.mjs';
24
+
25
+ const WITNESS_FIELDS = Object.freeze([
26
+ 'owns',
27
+ 'reads',
28
+ 'writes',
29
+ 'resources',
30
+ 'state_effects',
31
+ 'sensor_provenance',
32
+ 'affected_tests',
33
+ 'unknowns',
34
+ ]);
35
+ const STATE_KIND_MAP = Object.freeze({
36
+ state: 'state',
37
+ schema: 'state',
38
+ invariant: 'state',
39
+ effect: 'effect',
40
+ external_effect: 'effect',
41
+ });
42
+ const STRUCTURE_OPERATIONS = new Set(['query', 'callers', 'callees', 'impact']);
43
+ const HYPOTHESIS_PROVENANCE = 'extraction_hypothesis';
44
+
45
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
46
+
47
+ function fail(reason) {
48
+ throw new TypeError(`seam proposal producer契約違反: ${reason}`);
49
+ }
50
+
51
+ function plainRecord(value) {
52
+ return value !== null
53
+ && typeof value === 'object'
54
+ && !Array.isArray(value)
55
+ && Object.getPrototypeOf(value) === Object.prototype;
56
+ }
57
+
58
+ function exactRecord(value, keys) {
59
+ if (!plainRecord(value)) return false;
60
+ const actual = Object.keys(value).sort(compareText);
61
+ const expected = [...keys].sort(compareText);
62
+ return actual.length === expected.length
63
+ && actual.every((key, index) => key === expected[index]);
64
+ }
65
+
66
+ function sha16(value) {
67
+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
68
+ }
69
+
70
+ function resourceKey(value) {
71
+ return `${value.kind}\0${value.target}`;
72
+ }
73
+
74
+ function surfaceKey(value) {
75
+ return `${value.kind}\0${value.target}\0${value.path}\0${value.role}`;
76
+ }
77
+
78
+ function sortedUnique(values) {
79
+ return [...new Set(values)].sort(compareText);
80
+ }
81
+
82
+ function isSubset(left, right) {
83
+ return [...left].every((value) => right.has(value));
84
+ }
85
+
86
+ function pathPrefixOverlap(left, right) {
87
+ const leftIsPrefix = left.endsWith('/');
88
+ const rightIsPrefix = right.endsWith('/');
89
+ if (left === right) return true;
90
+ if (leftIsPrefix && (right === left.slice(0, -1) || right.startsWith(left))) return true;
91
+ if (rightIsPrefix && (left === right.slice(0, -1) || left.startsWith(right))) return true;
92
+ return false;
93
+ }
94
+
95
+ function withWitness(request, manualWitness) {
96
+ const virtualRequest = structuredClone(request);
97
+ virtualRequest.manual_witness = structuredClone(manualWitness);
98
+ virtualRequest.request_digest = '';
99
+ virtualRequest.request_digest = selfDigest(virtualRequest, 'request_digest');
100
+ if (!validateRunRequest(virtualRequest)) fail('virtual witnessがrun_request.v1を満たさない');
101
+ return virtualRequest;
102
+ }
103
+
104
+ /**
105
+ * Clone the original witness and apply a closed, full-field ownership diff.
106
+ * A task patch containing only `owns` is deliberately rejected.
107
+ */
108
+ export function buildVirtualWitness({ request, ownershipDiff } = {}) {
109
+ if (!validateRunRequest(request)) fail('requestがrun_request.v1を満たさない');
110
+ if (!Array.isArray(ownershipDiff)) fail('ownershipDiffがarrayではない');
111
+ const taskIds = new Set(request.todos.map(({ todo_id: todoId }) => todoId));
112
+ const seen = new Set();
113
+ const virtualWitness = structuredClone(request.manual_witness);
114
+ for (const patch of ownershipDiff) {
115
+ if (!exactRecord(patch, ['todo_id', ...WITNESS_FIELDS])
116
+ || !taskIds.has(patch.todo_id)
117
+ || seen.has(patch.todo_id)) {
118
+ fail('ownershipDiff entryがclosed full-field shapeではない');
119
+ }
120
+ seen.add(patch.todo_id);
121
+ virtualWitness[patch.todo_id] = Object.fromEntries(
122
+ WITNESS_FIELDS.map((field) => [field, structuredClone(patch[field])]),
123
+ );
124
+ }
125
+ withWitness(request, virtualWitness);
126
+ return virtualWitness;
127
+ }
128
+
129
+ function normalizeQueries(request) {
130
+ const byId = new Map();
131
+ for (const query of request.sensor_query_set.queries) {
132
+ if (byId.has(query.id)) fail(`query idが重複している: ${query.id}`);
133
+ byId.set(query.id, query);
134
+ }
135
+ return byId;
136
+ }
137
+
138
+ function normalizeEvidence(request, sensorEvidence) {
139
+ if (!exactRecord(sensorEvidence, ['outcomes'])
140
+ || !Array.isArray(sensorEvidence.outcomes)
141
+ || sensorEvidence.outcomes.length !== request.sensor_query_set.queries.length) {
142
+ fail('sensorEvidenceがquery setとexact整合しない');
143
+ }
144
+ const byId = new Map();
145
+ request.sensor_query_set.queries.forEach((query, index) => {
146
+ const outcome = sensorEvidence.outcomes[index];
147
+ if (!exactRecord(outcome, ['query_id', 'operation', 'status', 'raw'])
148
+ || outcome.query_id !== query.id
149
+ || outcome.operation !== query.operation
150
+ || typeof outcome.status !== 'string'
151
+ || outcome.status.length === 0) {
152
+ fail(`sensorEvidence outcomeがquery ${query.id}とexact整合しない`);
153
+ }
154
+ const portable = portableSensorOutcome(outcome.raw);
155
+ byId.set(query.id, {
156
+ ...outcome,
157
+ portable_digest: digestArtifact({
158
+ query_id: outcome.query_id,
159
+ operation: outcome.operation,
160
+ status: outcome.status,
161
+ portable,
162
+ }),
163
+ });
164
+ });
165
+ return byId;
166
+ }
167
+
168
+ function bindingMatchesQuery(binding, query) {
169
+ if (query === undefined) return false;
170
+ const { expect } = binding;
171
+ if (expect.kind === 'affected') {
172
+ return query.operation === 'affected' && query.target === expect.path;
173
+ }
174
+ if (expect.kind === 'symbol') {
175
+ return STRUCTURE_OPERATIONS.has(query.operation) && query.target === expect.name;
176
+ }
177
+ return (STRUCTURE_OPERATIONS.has(query.operation) || query.operation === 'affected')
178
+ && query.target === expect.path;
179
+ }
180
+
181
+ function rawPayload(raw) {
182
+ return plainRecord(raw) && Object.hasOwn(raw, 'data') ? raw.data : raw;
183
+ }
184
+
185
+ function affectedPayload(raw, expectPath) {
186
+ if (plainRecord(raw) && Array.isArray(raw.targets)) {
187
+ const entry = raw.targets.find((candidate) => (
188
+ plainRecord(candidate) && candidate.target === expectPath
189
+ ));
190
+ return plainRecord(entry) && plainRecord(entry.data) ? entry.data : null;
191
+ }
192
+ const payload = rawPayload(raw);
193
+ return plainRecord(payload) ? payload : null;
194
+ }
195
+
196
+ function affectedTarget(raw, expectPath) {
197
+ if (!plainRecord(raw) || !Array.isArray(raw.targets)) return null;
198
+ const entry = raw.targets.find((candidate) => (
199
+ plainRecord(candidate) && candidate.target === expectPath
200
+ ));
201
+ return plainRecord(entry) ? entry : null;
202
+ }
203
+
204
+ function entryNode(entry) {
205
+ if (plainRecord(entry) && plainRecord(entry.node)) return entry.node;
206
+ return plainRecord(entry) ? entry : null;
207
+ }
208
+
209
+ function resolveBindingStatus(binding, outcome) {
210
+ if (outcome.status !== 'ready') return outcome.status;
211
+ const { expect } = binding;
212
+ if (expect.kind === 'affected') {
213
+ if (affectedTarget(outcome.raw, expect.path)?.path_state === 'absent') return 'path_absent';
214
+ const payload = affectedPayload(outcome.raw, expect.path);
215
+ if (payload === null
216
+ || !Array.isArray(payload.changedFiles)
217
+ || payload.changedFiles.length !== 1
218
+ || payload.changedFiles[0] !== expect.path) {
219
+ return 'empty';
220
+ }
221
+ return 'ready';
222
+ }
223
+ const payload = rawPayload(outcome.raw);
224
+ if (!Array.isArray(payload)) return 'invalid_json';
225
+ if (expect.kind === 'symbol') {
226
+ const matches = payload.filter((entry) => {
227
+ const node = entryNode(entry);
228
+ return node !== null && node.name === expect.name && node.filePath === expect.path;
229
+ });
230
+ if (matches.length === 1) return 'ready';
231
+ return matches.length === 0 ? 'symbol_absent' : 'unresolved';
232
+ }
233
+ const matches = payload.filter((entry) => entryNode(entry)?.filePath === expect.path);
234
+ return matches.length >= 1 ? 'ready' : 'empty';
235
+ }
236
+
237
+ function bindingCoversOwn(binding, own) {
238
+ if (own.kind === 'symbol') {
239
+ return binding.expect.kind === 'symbol' && binding.expect.name === own.target;
240
+ }
241
+ return (binding.expect.kind === 'path' || binding.expect.kind === 'affected')
242
+ && binding.expect.path === own.target;
243
+ }
244
+
245
+ function normalizeHypotheses(surfaceHypotheses, manualWitness) {
246
+ if (!Array.isArray(surfaceHypotheses)) fail('surfaceHypothesesがarrayではない');
247
+ const taskIds = new Set(Object.keys(manualWitness));
248
+ const hypotheses = surfaceHypotheses.map((entry) => {
249
+ if (!exactRecord(entry, [
250
+ 'kind', 'target', 'path', 'owner_task_id', 'affected_tests', 'provenance',
251
+ ])
252
+ || !['symbol', 'path'].includes(entry.kind)
253
+ || typeof entry.target !== 'string'
254
+ || typeof entry.path !== 'string'
255
+ || !taskIds.has(entry.owner_task_id)
256
+ || !Array.isArray(entry.affected_tests)
257
+ || entry.provenance !== HYPOTHESIS_PROVENANCE) {
258
+ fail('surface hypothesis shapeが不正');
259
+ }
260
+ if (entry.kind === 'path' && entry.target !== entry.path) {
261
+ fail('path hypothesisのtargetとpathが一致しない');
262
+ }
263
+ const witness = manualWitness[entry.owner_task_id];
264
+ if (!witness.owns.some((own) => resourceKey(own) === `${entry.kind}\0${entry.target}`)
265
+ || !witness.writes.includes(entry.path)
266
+ || entry.affected_tests.some((path) => !witness.affected_tests.includes(path))) {
267
+ fail('surface hypothesisが完全なvirtual witnessへ反映されていない');
268
+ }
269
+ return {
270
+ ...structuredClone(entry),
271
+ affected_tests: [...entry.affected_tests].sort(compareText),
272
+ };
273
+ }).sort((left, right) => compareText(
274
+ `${left.owner_task_id}\0${left.kind}\0${left.target}`,
275
+ `${right.owner_task_id}\0${right.kind}\0${right.target}`,
276
+ ));
277
+ const keys = hypotheses.map((entry) => (
278
+ `${entry.owner_task_id}\0${entry.kind}\0${entry.target}`
279
+ ));
280
+ if (new Set(keys).size !== keys.length) fail('surface hypothesisが重複している');
281
+ return hypotheses;
282
+ }
283
+
284
+ function hypothesisForOwn(hypotheses, todoId, own) {
285
+ return hypotheses.find((entry) => (
286
+ entry.owner_task_id === todoId
287
+ && entry.kind === own.kind
288
+ && entry.target === own.target
289
+ ));
290
+ }
291
+
292
+ function hypothesisForBinding(hypotheses, todoId, binding) {
293
+ return hypotheses.find((entry) => (
294
+ entry.owner_task_id === todoId
295
+ && ((binding.expect.kind === 'symbol'
296
+ && entry.kind === 'symbol'
297
+ && entry.target === binding.expect.name
298
+ && entry.path === binding.expect.path)
299
+ || (['path', 'affected'].includes(binding.expect.kind)
300
+ && entry.kind === 'path'
301
+ && entry.path === binding.expect.path))
302
+ ));
303
+ }
304
+
305
+ function manualProvenance(request) {
306
+ return {
307
+ source: 'manual_state_effect',
308
+ evidence_ref: `run-request:${request.request_id}`,
309
+ evidence_digest: request.request_digest,
310
+ status: 'asserted',
311
+ };
312
+ }
313
+
314
+ function candidateProvenance(request) {
315
+ return {
316
+ source: 'manual_candidate_spec',
317
+ evidence_ref: `run-request:${request.request_id}`,
318
+ evidence_digest: request.request_digest,
319
+ status: 'asserted',
320
+ };
321
+ }
322
+
323
+ function derivationResult({
324
+ outcome,
325
+ virtualWitness,
326
+ hypotheses,
327
+ resources = [],
328
+ conflicts = [],
329
+ unknowns = [],
330
+ unresolvedWitnesses = [],
331
+ drift = [],
332
+ }) {
333
+ const result = {
334
+ outcome,
335
+ resources,
336
+ conflicts,
337
+ unknowns,
338
+ unresolved_witnesses: unresolvedWitnesses,
339
+ drift,
340
+ };
341
+ return {
342
+ virtual_witness: virtualWitness,
343
+ surface_hypotheses: hypotheses,
344
+ ...result,
345
+ input_digest: digestArtifact({
346
+ virtual_witness: virtualWitness,
347
+ surface_hypotheses: hypotheses,
348
+ }),
349
+ result_digest: digestArtifact(result),
350
+ };
351
+ }
352
+
353
+ /**
354
+ * Pure duplicate of runtime-front-end's resource lowering. Existing surfaces retain real
355
+ * sensor provenance; absent/new surfaces can only be represented by an explicit extraction
356
+ * hypothesis and are never relabelled as observed sensor nodes.
357
+ */
358
+ export function deriveVirtualBoundary({
359
+ request,
360
+ sensorEvidence,
361
+ virtualWitness = request?.manual_witness,
362
+ surfaceHypotheses = [],
363
+ } = {}) {
364
+ const virtualRequest = withWitness(request, virtualWitness);
365
+ const hypotheses = normalizeHypotheses(surfaceHypotheses, virtualRequest.manual_witness);
366
+ const queryById = normalizeQueries(virtualRequest);
367
+ const outcomeById = normalizeEvidence(virtualRequest, sensorEvidence);
368
+ const todoIds = virtualRequest.todos.map(({ todo_id: todoId }) => todoId);
369
+ const bindingsByTodo = new Map();
370
+ const drift = [];
371
+
372
+ for (const todoId of todoIds) {
373
+ const bindings = virtualRequest.manual_witness[todoId].sensor_provenance.queries;
374
+ bindingsByTodo.set(todoId, bindings);
375
+ for (const binding of bindings) {
376
+ if (!bindingMatchesQuery(binding, queryById.get(binding.query_id))) {
377
+ drift.push({
378
+ kind: 'query_drift',
379
+ todo_id: todoId,
380
+ ref: binding.query_id,
381
+ });
382
+ }
383
+ }
384
+ }
385
+ const statusQueries = [...queryById.values()]
386
+ .filter((query) => query.operation === 'status');
387
+ if (statusQueries.length !== 1) {
388
+ drift.push({ kind: 'query_drift', todo_id: todoIds[0], ref: 'status_query_count' });
389
+ }
390
+ if (drift.length > 0) {
391
+ return derivationResult({
392
+ outcome: 'query_drift',
393
+ virtualWitness: virtualRequest.manual_witness,
394
+ hypotheses,
395
+ drift: drift.sort((left, right) => compareText(
396
+ `${left.todo_id}\0${left.kind}\0${left.ref}`,
397
+ `${right.todo_id}\0${right.kind}\0${right.ref}`,
398
+ )),
399
+ });
400
+ }
401
+
402
+ const statusOutcome = outcomeById.get(statusQueries[0].id);
403
+ const unresolved = [];
404
+ if (statusOutcome.status !== 'ready') {
405
+ for (const todoId of todoIds) {
406
+ unresolved.push({ todo_id: todoId, kind: `sensor_${statusOutcome.status}`, ref: statusQueries[0].id });
407
+ }
408
+ }
409
+
410
+ for (const todoId of todoIds) {
411
+ for (const binding of bindingsByTodo.get(todoId)) {
412
+ const status = resolveBindingStatus(binding, outcomeById.get(binding.query_id));
413
+ const hypothesis = hypothesisForBinding(hypotheses, todoId, binding);
414
+ const hypothesisMayReplaceAbsence = hypothesis !== undefined
415
+ && ['symbol_absent', 'path_absent', 'empty'].includes(status);
416
+ if (status !== 'ready' && !hypothesisMayReplaceAbsence) {
417
+ unresolved.push({ todo_id: todoId, kind: `sensor_${status}`, ref: binding.query_id });
418
+ }
419
+ }
420
+ }
421
+
422
+ const affectedDrift = [];
423
+ for (const todoId of todoIds) {
424
+ const witness = virtualRequest.manual_witness[todoId];
425
+ for (const binding of bindingsByTodo.get(todoId)) {
426
+ if (binding.expect.kind !== 'affected') continue;
427
+ const outcome = outcomeById.get(binding.query_id);
428
+ if (resolveBindingStatus(binding, outcome) !== 'ready') continue;
429
+ const payload = affectedPayload(outcome.raw, binding.expect.path);
430
+ const observed = Array.isArray(payload?.affectedTests)
431
+ ? [...payload.affectedTests].sort(compareText)
432
+ : null;
433
+ const declared = [...witness.affected_tests].sort(compareText);
434
+ if (observed === null
435
+ || observed.length !== declared.length
436
+ || observed.some((test, index) => test !== declared[index])) {
437
+ affectedDrift.push({
438
+ kind: 'affected_test_drift',
439
+ todo_id: todoId,
440
+ ref: binding.query_id,
441
+ });
442
+ }
443
+ }
444
+ }
445
+ if (affectedDrift.length > 0) {
446
+ return derivationResult({
447
+ outcome: 'affected_test_drift',
448
+ virtualWitness: virtualRequest.manual_witness,
449
+ hypotheses,
450
+ drift: affectedDrift.sort((left, right) => compareText(
451
+ `${left.todo_id}\0${left.ref}`, `${right.todo_id}\0${right.ref}`,
452
+ )),
453
+ });
454
+ }
455
+
456
+ const ownGroups = new Map();
457
+ const coveringByTarget = new Map();
458
+ for (const todoId of todoIds) {
459
+ const witness = virtualRequest.manual_witness[todoId];
460
+ for (const own of witness.owns) {
461
+ const key = `${own.kind} ${own.target}`;
462
+ if (!ownGroups.has(key)) {
463
+ ownGroups.set(key, {
464
+ own,
465
+ todoIds: [],
466
+ hypotheticalTodoIds: new Set(),
467
+ });
468
+ }
469
+ const group = ownGroups.get(key);
470
+ group.todoIds.push(todoId);
471
+ const covering = bindingsByTodo.get(todoId).filter((binding) => bindingCoversOwn(binding, own));
472
+ for (const binding of covering) {
473
+ const seen = coveringByTarget.get(key);
474
+ if (seen === undefined) coveringByTarget.set(key, binding.query_id);
475
+ else if (seen !== binding.query_id) {
476
+ drift.push({ kind: 'query_drift', todo_id: todoId, ref: `${seen} ${binding.query_id}` });
477
+ }
478
+ }
479
+ const hypothesis = hypothesisForOwn(hypotheses, todoId, own);
480
+ if (hypothesis !== undefined) group.hypotheticalTodoIds.add(todoId);
481
+ if (covering.length === 0 && hypothesis === undefined) {
482
+ unresolved.push({ todo_id: todoId, kind: 'sensor_unbound', ref: `${own.kind}:${own.target}` });
483
+ }
484
+ }
485
+ }
486
+ if (drift.length > 0) {
487
+ return derivationResult({
488
+ outcome: 'query_drift',
489
+ virtualWitness: virtualRequest.manual_witness,
490
+ hypotheses,
491
+ drift,
492
+ });
493
+ }
494
+
495
+ for (let left = 0; left < todoIds.length; left += 1) {
496
+ for (let right = left + 1; right < todoIds.length; right += 1) {
497
+ const leftWitness = virtualRequest.manual_witness[todoIds[left]];
498
+ const rightWitness = virtualRequest.manual_witness[todoIds[right]];
499
+ const leftOwnPaths = new Set(leftWitness.owns
500
+ .filter((own) => own.kind === 'path').map((own) => own.target));
501
+ const rightOwnPaths = new Set(rightWitness.owns
502
+ .filter((own) => own.kind === 'path').map((own) => own.target));
503
+ for (const leftPath of leftWitness.writes) {
504
+ for (const rightPath of rightWitness.writes) {
505
+ if (!pathPrefixOverlap(leftPath, rightPath)) continue;
506
+ if (leftOwnPaths.has(leftPath) && rightOwnPaths.has(rightPath)
507
+ && leftPath === rightPath) continue;
508
+ unresolved.push({
509
+ todo_id: todoIds[left],
510
+ kind: 'undeclared_write_overlap',
511
+ ref: `${leftPath} ${rightPath}`,
512
+ });
513
+ unresolved.push({
514
+ todo_id: todoIds[right],
515
+ kind: 'undeclared_write_overlap',
516
+ ref: `${leftPath} ${rightPath}`,
517
+ });
518
+ }
519
+ }
520
+ }
521
+ }
522
+ for (const todoId of todoIds) {
523
+ for (const unknown of virtualRequest.manual_witness[todoId].unknowns) {
524
+ unresolved.push({ todo_id: todoId, kind: unknown.kind, ref: unknown.ref });
525
+ }
526
+ }
527
+
528
+ const readWriteGroups = new Map();
529
+ for (let left = 0; left < todoIds.length; left += 1) {
530
+ for (let right = 0; right < todoIds.length; right += 1) {
531
+ if (left === right) continue;
532
+ const writer = virtualRequest.manual_witness[todoIds[left]];
533
+ const reader = virtualRequest.manual_witness[todoIds[right]];
534
+ for (const writePath of writer.writes) {
535
+ for (const readPath of reader.reads) {
536
+ if (!pathPrefixOverlap(writePath, readPath)) continue;
537
+ if (!readWriteGroups.has(writePath)) readWriteGroups.set(writePath, new Set());
538
+ readWriteGroups.get(writePath).add(todoIds[left]);
539
+ readWriteGroups.get(writePath).add(todoIds[right]);
540
+ }
541
+ }
542
+ }
543
+ }
544
+
545
+ const bareResourceGroups = new Map();
546
+ for (const todoId of todoIds) {
547
+ const witness = virtualRequest.manual_witness[todoId];
548
+ const stateIds = new Set(witness.state_effects.map(({ resource_id: id }) => id));
549
+ for (const resourceId of witness.resources) {
550
+ if (stateIds.has(resourceId)) continue;
551
+ if (!bareResourceGroups.has(resourceId)) bareResourceGroups.set(resourceId, new Set());
552
+ bareResourceGroups.get(resourceId).add(todoId);
553
+ }
554
+ }
555
+
556
+ const resources = [];
557
+ for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
558
+ const coveringQueryId = coveringByTarget.get(key);
559
+ const observedTodoIds = new Set();
560
+ let outcome;
561
+ let representative;
562
+ if (coveringQueryId !== undefined) {
563
+ outcome = outcomeById.get(coveringQueryId);
564
+ for (const todoId of group.todoIds) {
565
+ const binding = bindingsByTodo.get(todoId).find((entry) => (
566
+ entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
567
+ ));
568
+ if (representative === undefined) representative = binding;
569
+ if (binding !== undefined
570
+ && statusOutcome.status === 'ready'
571
+ && resolveBindingStatus(binding, outcome) === 'ready') {
572
+ observedTodoIds.add(todoId);
573
+ }
574
+ }
575
+ }
576
+ const allObserved = group.todoIds.every((todoId) => observedTodoIds.has(todoId));
577
+ const allCovered = group.todoIds.every((todoId) => (
578
+ observedTodoIds.has(todoId) || group.hypotheticalTodoIds.has(todoId)
579
+ ));
580
+ const hasHypothetical = group.todoIds.some(
581
+ (todoId) => group.hypotheticalTodoIds.has(todoId),
582
+ );
583
+ if (coveringQueryId === undefined && !allCovered) continue;
584
+ const status = allObserved ? 'observed'
585
+ : allCovered && hasHypothetical ? 'hypothetical' : 'unknown';
586
+ const provenance = status === 'hypothetical'
587
+ ? [{
588
+ source: HYPOTHESIS_PROVENANCE,
589
+ evidence_ref: `virtual-witness:${virtualRequest.request_id}`,
590
+ evidence_digest: digestArtifact(hypotheses),
591
+ status: 'hypothetical',
592
+ }]
593
+ : [
594
+ candidateProvenance(virtualRequest),
595
+ {
596
+ source: 'sensor',
597
+ evidence_ref: coveringQueryId,
598
+ evidence_digest: outcome.portable_digest,
599
+ status: statusOutcome.status !== 'ready'
600
+ ? statusOutcome.status
601
+ : resolveBindingStatus(representative, outcome),
602
+ },
603
+ ];
604
+ resources.push({
605
+ resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
606
+ kind: group.own.kind,
607
+ target: group.own.target,
608
+ todo_ids: [...group.todoIds].sort(compareText),
609
+ provenance,
610
+ status,
611
+ });
612
+ }
613
+
614
+ const stateGroups = new Map();
615
+ for (const todoId of todoIds) {
616
+ for (const entry of virtualRequest.manual_witness[todoId].state_effects) {
617
+ const kind = STATE_KIND_MAP[entry.kind];
618
+ if (!stateGroups.has(entry.resource_id)) {
619
+ stateGroups.set(entry.resource_id, { kind, todoIds: new Set() });
620
+ }
621
+ const group = stateGroups.get(entry.resource_id);
622
+ if (group.kind !== kind) fail(`resource ${entry.resource_id}のstate/effect kindが矛盾している`);
623
+ group.todoIds.add(todoId);
624
+ }
625
+ }
626
+ for (const [resourceId, todos] of bareResourceGroups) {
627
+ if (stateGroups.has(resourceId)) {
628
+ for (const todoId of todos) stateGroups.get(resourceId).todoIds.add(todoId);
629
+ } else {
630
+ stateGroups.set(resourceId, { kind: 'state', todoIds: todos });
631
+ }
632
+ }
633
+ for (const [resourceId, group] of [...stateGroups.entries()]
634
+ .sort((left, right) => compareText(left[0], right[0]))) {
635
+ resources.push({
636
+ resource_id: resourceId,
637
+ kind: group.kind,
638
+ target: resourceId,
639
+ todo_ids: [...group.todoIds].sort(compareText),
640
+ provenance: [manualProvenance(virtualRequest)],
641
+ status: 'observed',
642
+ });
643
+ }
644
+ for (const [writePath, todos] of [...readWriteGroups.entries()]
645
+ .sort((left, right) => compareText(left[0], right[0]))) {
646
+ resources.push({
647
+ resource_id: `rw-${sha16(writePath)}`,
648
+ kind: 'state',
649
+ target: writePath,
650
+ todo_ids: [...todos].sort(compareText),
651
+ provenance: [manualProvenance(virtualRequest)],
652
+ status: 'observed',
653
+ });
654
+ }
655
+
656
+ let dynamicIndex = 0;
657
+ for (const unknown of unresolved) {
658
+ resources.push({
659
+ resource_id: `dyn-${String(dynamicIndex += 1).padStart(3, '0')}-${sha16(`${unknown.kind}:${unknown.ref}`)}`,
660
+ kind: 'dynamic',
661
+ target: `${unknown.kind}:${unknown.ref}`.slice(0, 4_096).trim(),
662
+ todo_ids: [unknown.todo_id],
663
+ provenance: [manualProvenance(virtualRequest)],
664
+ status: 'unknown',
665
+ });
666
+ }
667
+ resources.sort((left, right) => compareText(left.resource_id, right.resource_id));
668
+ if (new Set(resources.map(({ resource_id: id }) => id)).size !== resources.length) {
669
+ fail('導出resource_idが重複している');
670
+ }
671
+
672
+ const conflicts = [];
673
+ const unknowns = [];
674
+ for (const resource of resources) {
675
+ if (resource.status === 'unknown') {
676
+ for (const todoId of resource.todo_ids) {
677
+ unknowns.push({
678
+ todo_id: todoId,
679
+ kind: resource.kind === 'dynamic'
680
+ ? 'dynamic' : `sensor_${resource.provenance.find(({ source }) => source === 'sensor').status}`,
681
+ reason: `resource ${resource.resource_id} is ${
682
+ resource.kind === 'dynamic'
683
+ ? 'dynamic'
684
+ : resource.provenance.find(({ source }) => source === 'sensor').status
685
+ }`,
686
+ });
687
+ }
688
+ continue;
689
+ }
690
+ for (let left = 0; left < resource.todo_ids.length; left += 1) {
691
+ for (let right = left + 1; right < resource.todo_ids.length; right += 1) {
692
+ conflicts.push({
693
+ todo_ids: [resource.todo_ids[left], resource.todo_ids[right]],
694
+ resource_id: resource.resource_id,
695
+ });
696
+ }
697
+ }
698
+ }
699
+ conflicts.sort((left, right) => compareText(
700
+ `${left.todo_ids[0]}\0${left.todo_ids[1]}\0${left.resource_id}`,
701
+ `${right.todo_ids[0]}\0${right.todo_ids[1]}\0${right.resource_id}`,
702
+ ));
703
+ unknowns.sort((left, right) => compareText(
704
+ `${left.todo_id}\0${left.kind}\0${left.reason}`,
705
+ `${right.todo_id}\0${right.kind}\0${right.reason}`,
706
+ ));
707
+
708
+ return derivationResult({
709
+ outcome: unknowns.length > 0 ? 'unknown' : 'derived',
710
+ virtualWitness: virtualRequest.manual_witness,
711
+ hypotheses,
712
+ resources,
713
+ conflicts,
714
+ unknowns,
715
+ unresolvedWitnesses: unresolved,
716
+ });
717
+ }
718
+
719
+ export function createVirtualCompileReceipt(options = {}) {
720
+ const derivation = deriveVirtualBoundary(options);
721
+ return {
722
+ derivation,
723
+ verification: {
724
+ virtual_compile_input_digest: derivation.input_digest,
725
+ virtual_compile_result_digest: derivation.result_digest,
726
+ residual_conflicts: derivation.conflicts,
727
+ },
728
+ };
729
+ }
730
+
731
+ /**
732
+ * Re-derive from source inputs. This distinguishes a caller-written SHA-shaped receipt from a
733
+ * reproducible virtual compile.
734
+ */
735
+ export function verifyVirtualCompileReceipt({ verification, ...options } = {}) {
736
+ const expected = createVirtualCompileReceipt(options);
737
+ const mismatches = [];
738
+ if (verification?.virtual_compile_input_digest
739
+ !== expected.verification.virtual_compile_input_digest) {
740
+ mismatches.push('virtual_compile_input_digest');
741
+ }
742
+ if (verification?.virtual_compile_result_digest
743
+ !== expected.verification.virtual_compile_result_digest) {
744
+ mismatches.push('virtual_compile_result_digest');
745
+ }
746
+ if (digestArtifact(verification?.residual_conflicts)
747
+ !== digestArtifact(expected.verification.residual_conflicts)) {
748
+ mismatches.push('residual_conflicts');
749
+ }
750
+ return {
751
+ valid: mismatches.length === 0,
752
+ mismatches,
753
+ expected: expected.verification,
754
+ derivation: expected.derivation,
755
+ };
756
+ }
757
+
758
+ function uniqueIntentAnchors(manualWitness, taskIds) {
759
+ const anchorsByTask = new Map();
760
+ const counts = new Map();
761
+ for (const taskId of taskIds) {
762
+ const witness = manualWitness[taskId];
763
+ const anchors = [
764
+ ...witness.owns.map((own) => `owns:${resourceKey(own)}`),
765
+ ...witness.writes.map((path) => `writes:${path}`),
766
+ ...witness.affected_tests.map((path) => `affected_tests:${path}`),
767
+ ];
768
+ anchorsByTask.set(taskId, sortedUnique(anchors));
769
+ for (const anchor of new Set(anchors)) counts.set(anchor, (counts.get(anchor) ?? 0) + 1);
770
+ }
771
+ return new Map([...anchorsByTask].map(([taskId, anchors]) => [
772
+ taskId,
773
+ anchors.filter((anchor) => counts.get(anchor) === 1),
774
+ ]));
775
+ }
776
+
777
+ function graphNode(entry) {
778
+ const node = plainRecord(entry?.node) ? entry.node : entry;
779
+ if (!plainRecord(node)
780
+ || typeof node.name !== 'string'
781
+ || node.name.length === 0
782
+ || typeof node.filePath !== 'string'
783
+ || node.filePath.length === 0
784
+ || node.filePath.startsWith('/')) return null;
785
+ if (node.kind === 'file') {
786
+ return { kind: 'path', target: node.filePath, path: node.filePath };
787
+ }
788
+ return { kind: 'symbol', target: node.name, path: node.filePath };
789
+ }
790
+
791
+ function graphNodeKey(node) {
792
+ return `${node.kind}\0${node.target}\0${node.path}`;
793
+ }
794
+
795
+ function graphEdgeKey(edge) {
796
+ return `${edge.from}\0${edge.to}\0${edge.kind}`;
797
+ }
798
+
799
+ function graphPayload(outcome, operation) {
800
+ if (!plainRecord(outcome) || outcome.outcome !== 'ready') return null;
801
+ if (operation === 'query') return outcome.data;
802
+ if (!plainRecord(outcome.data)) return null;
803
+ if (operation === 'callers') return outcome.data.callers;
804
+ if (operation === 'callees') return outcome.data.callees;
805
+ if (operation === 'impact') return outcome.data.affected;
806
+ return null;
807
+ }
808
+
809
+ function normalizeRawGraph({ conflict, evidence, rawCollected }) {
810
+ if (!plainRecord(rawCollected) || !Array.isArray(rawCollected.outcomes)) {
811
+ return { graph: null, unknown: 'raw_graph_unavailable' };
812
+ }
813
+ const receipts = evidence.queries.filter((query) => (
814
+ query.target === conflict.target && STRUCTURE_OPERATIONS.has(query.operation)
815
+ ));
816
+ if (receipts.length !== STRUCTURE_OPERATIONS.size
817
+ || receipts.some((query) => query.outcome !== 'resolved'
818
+ || query.resolved_name !== conflict.target
819
+ || query.resolved_path === null)) {
820
+ return { graph: null, unknown: 'raw_graph_incomplete' };
821
+ }
822
+ const outcomeById = new Map(rawCollected.outcomes.map((outcome) => [outcome?.id, outcome]));
823
+ const receiptByOperation = new Map(receipts.map((receipt) => [receipt.operation, receipt]));
824
+ const payloadByOperation = new Map();
825
+ for (const operation of STRUCTURE_OPERATIONS) {
826
+ const receipt = receiptByOperation.get(operation);
827
+ const payload = graphPayload(outcomeById.get(receipt.query_id), operation);
828
+ if (!Array.isArray(payload)) {
829
+ return { graph: null, unknown: 'raw_graph_incomplete' };
830
+ }
831
+ payloadByOperation.set(operation, payload);
832
+ }
833
+
834
+ const queryReceipt = receiptByOperation.get('query');
835
+ const rootMatches = payloadByOperation.get('query')
836
+ .map(graphNode)
837
+ .filter((node) => node !== null
838
+ && node.kind === 'symbol'
839
+ && node.target === conflict.target
840
+ && node.path === queryReceipt.resolved_path);
841
+ if (rootMatches.length !== 1) {
842
+ return { graph: null, unknown: 'raw_graph_incomplete' };
843
+ }
844
+ const root = rootMatches[0];
845
+ const nodes = new Map([[graphNodeKey(root), root]]);
846
+ const edges = new Map();
847
+ let invalidObservedNode = false;
848
+ const addObserved = (entry) => {
849
+ const node = graphNode(entry);
850
+ if (node === null) invalidObservedNode = true;
851
+ if (node !== null) nodes.set(graphNodeKey(node), node);
852
+ return node;
853
+ };
854
+ for (const entry of payloadByOperation.get('callers')) {
855
+ const node = addObserved(entry);
856
+ if (node === null) continue;
857
+ const edge = { from: graphNodeKey(node), to: graphNodeKey(root), kind: 'caller' };
858
+ edges.set(graphEdgeKey(edge), edge);
859
+ }
860
+ for (const entry of payloadByOperation.get('callees')) {
861
+ const node = addObserved(entry);
862
+ if (node === null) continue;
863
+ const edge = { from: graphNodeKey(root), to: graphNodeKey(node), kind: 'callee' };
864
+ edges.set(graphEdgeKey(edge), edge);
865
+ }
866
+ for (const entry of payloadByOperation.get('impact')) addObserved(entry);
867
+ let closureComplete = plainRecord(rawCollected.graph_closure)
868
+ && rawCollected.graph_closure.complete === true
869
+ && Array.isArray(rawCollected.graph_closure.expansions);
870
+ if (plainRecord(rawCollected.graph_closure)
871
+ && Array.isArray(rawCollected.graph_closure.expansions)) {
872
+ for (const expansion of rawCollected.graph_closure.expansions) {
873
+ const parent = graphNode(expansion?.parent);
874
+ const rawCallees = expansion?.callees_outcome;
875
+ if (expansion?.exact !== true
876
+ || parent === null
877
+ || !plainRecord(rawCallees)
878
+ || rawCallees.outcome !== 'ready'
879
+ || !plainRecord(rawCallees.data)
880
+ || !Array.isArray(rawCallees.data.callees)) {
881
+ closureComplete = false;
882
+ continue;
883
+ }
884
+ nodes.set(graphNodeKey(parent), parent);
885
+ for (const entry of rawCallees.data.callees) {
886
+ const child = addObserved(entry);
887
+ if (child === null) {
888
+ closureComplete = false;
889
+ continue;
890
+ }
891
+ const edge = {
892
+ from: graphNodeKey(parent),
893
+ to: graphNodeKey(child),
894
+ kind: 'callee',
895
+ };
896
+ edges.set(graphEdgeKey(edge), edge);
897
+ }
898
+ }
899
+ }
900
+ if (invalidObservedNode) {
901
+ return { graph: null, unknown: 'raw_graph_incomplete' };
902
+ }
903
+ return {
904
+ graph: {
905
+ root,
906
+ closure_complete: closureComplete,
907
+ nodes: [...nodes.values()].sort((left, right) => compareText(
908
+ graphNodeKey(left), graphNodeKey(right),
909
+ )),
910
+ edges: [...edges.values()].sort((left, right) => compareText(
911
+ graphEdgeKey(left), graphEdgeKey(right),
912
+ )),
913
+ },
914
+ unknown: null,
915
+ };
916
+ }
917
+
918
+ function stronglyConnectedPartitions(graph) {
919
+ const symbolKeys = new Set(graph.nodes
920
+ .filter(({ kind }) => kind === 'symbol').map(graphNodeKey));
921
+ const adjacency = new Map([...symbolKeys].map((key) => [key, []]));
922
+ for (const edge of graph.edges) {
923
+ if (symbolKeys.has(edge.from) && symbolKeys.has(edge.to)) {
924
+ adjacency.get(edge.from).push(edge.to);
925
+ }
926
+ }
927
+ for (const targets of adjacency.values()) targets.sort(compareText);
928
+ let nextIndex = 0;
929
+ const indexes = new Map();
930
+ const lowLinks = new Map();
931
+ const stack = [];
932
+ const onStack = new Set();
933
+ const components = [];
934
+ const visit = (key) => {
935
+ indexes.set(key, nextIndex);
936
+ lowLinks.set(key, nextIndex);
937
+ nextIndex += 1;
938
+ stack.push(key);
939
+ onStack.add(key);
940
+ for (const target of adjacency.get(key)) {
941
+ if (!indexes.has(target)) {
942
+ visit(target);
943
+ lowLinks.set(key, Math.min(lowLinks.get(key), lowLinks.get(target)));
944
+ } else if (onStack.has(target)) {
945
+ lowLinks.set(key, Math.min(lowLinks.get(key), indexes.get(target)));
946
+ }
947
+ }
948
+ if (lowLinks.get(key) !== indexes.get(key)) return;
949
+ const component = [];
950
+ while (stack.length > 0) {
951
+ const member = stack.pop();
952
+ onStack.delete(member);
953
+ component.push(member);
954
+ if (member === key) break;
955
+ }
956
+ components.push(component.sort(compareText));
957
+ };
958
+ for (const key of [...symbolKeys].sort(compareText)) {
959
+ if (!indexes.has(key)) visit(key);
960
+ }
961
+ return components.sort((left, right) => compareText(left.join('\0'), right.join('\0')));
962
+ }
963
+
964
+ function calleeClosurePartitions(graph) {
965
+ const adjacency = new Map(graph.nodes.map((node) => [graphNodeKey(node), []]));
966
+ for (const edge of graph.edges.filter(({ kind }) => kind === 'callee')) {
967
+ adjacency.get(edge.from)?.push(edge.to);
968
+ }
969
+ for (const targets of adjacency.values()) targets.sort(compareText);
970
+ const direct = adjacency.get(graphNodeKey(graph.root)) ?? [];
971
+ return direct.map((start) => {
972
+ const seen = new Set();
973
+ const queue = [start];
974
+ while (queue.length > 0) {
975
+ const key = queue.shift();
976
+ if (seen.has(key)) continue;
977
+ seen.add(key);
978
+ queue.push(...(adjacency.get(key) ?? []));
979
+ }
980
+ return [...seen].sort(compareText);
981
+ });
982
+ }
983
+
984
+ function moduleFrontierPartitions(graph) {
985
+ const byPath = new Map();
986
+ for (const node of graph.nodes) {
987
+ if (!byPath.has(node.path)) byPath.set(node.path, []);
988
+ byPath.get(node.path).push(graphNodeKey(node));
989
+ }
990
+ return [...byPath.entries()].sort((left, right) => compareText(left[0], right[0]))
991
+ .map(([, keys]) => keys.sort(compareText));
992
+ }
993
+
994
+ function testFrontierPartitions(graph) {
995
+ return graph.nodes
996
+ .filter(({ kind, path }) => kind === 'path'
997
+ && (path.startsWith('test/') || /\.test\.[cm]?[jt]sx?$/u.test(path)))
998
+ .map((node) => [graphNodeKey(node)]);
999
+ }
1000
+
1001
+ function canonicalPartitions(partitions) {
1002
+ const unique = new Set();
1003
+ for (const partition of partitions) {
1004
+ const key = sortedUnique(partition).join('\u0001');
1005
+ if (key.length > 0) unique.add(key);
1006
+ }
1007
+ return [...unique].sort(compareText).map((key) => key.split('\u0001'));
1008
+ }
1009
+
1010
+ function anchorMatchesNode(anchor, node) {
1011
+ if (anchor.startsWith('owns:symbol\0')) {
1012
+ return node.kind === 'symbol' && node.target === anchor.slice('owns:symbol\0'.length);
1013
+ }
1014
+ if (anchor.startsWith('owns:path\0')) {
1015
+ return node.path === anchor.slice('owns:path\0'.length);
1016
+ }
1017
+ if (anchor.startsWith('writes:')) return node.path === anchor.slice('writes:'.length);
1018
+ if (anchor.startsWith('affected_tests:')) {
1019
+ return node.path === anchor.slice('affected_tests:'.length);
1020
+ }
1021
+ return false;
1022
+ }
1023
+
1024
+ function bindSkeleton({ skeleton, graph, intentAnchors, taskIds }) {
1025
+ const nodeByKey = new Map(graph.nodes.map((node) => [graphNodeKey(node), node]));
1026
+ const taskBindings = [];
1027
+ const unknowns = [];
1028
+ for (const taskId of taskIds) {
1029
+ const matches = [];
1030
+ skeleton.partitions.forEach((partition, index) => {
1031
+ const anchors = intentAnchors.get(taskId).filter((anchor) => (
1032
+ partition.some((key) => anchorMatchesNode(anchor, nodeByKey.get(key)))
1033
+ ));
1034
+ if (anchors.length > 0) matches.push({ index, anchors: sortedUnique(anchors) });
1035
+ });
1036
+ if (matches.length === 0) {
1037
+ unknowns.push({
1038
+ kind: 'semantic_owner_binding_missing',
1039
+ ref: `${skeleton.skeleton_id}:${taskId}`,
1040
+ });
1041
+ continue;
1042
+ }
1043
+ if (matches.length > 1) {
1044
+ unknowns.push({
1045
+ kind: 'semantic_owner_binding_ambiguous',
1046
+ ref: `${skeleton.skeleton_id}:${taskId}`,
1047
+ });
1048
+ continue;
1049
+ }
1050
+ taskBindings.push({
1051
+ task_id: taskId,
1052
+ partition_index: matches[0].index,
1053
+ anchors: matches[0].anchors,
1054
+ });
1055
+ }
1056
+ if (taskBindings.length === taskIds.length
1057
+ && new Set(taskBindings.map(({ partition_index: index }) => index)).size
1058
+ !== taskBindings.length) {
1059
+ unknowns.push({
1060
+ kind: 'semantic_owner_binding_ambiguous',
1061
+ ref: `${skeleton.skeleton_id}:shared_partition`,
1062
+ });
1063
+ }
1064
+ return {
1065
+ ...skeleton,
1066
+ task_bindings: taskBindings,
1067
+ binding_unknowns: unknowns,
1068
+ };
1069
+ }
1070
+
1071
+ /**
1072
+ * Enumerate structural cut skeletons from the in-memory sensor outcomes. Graph edges only shape
1073
+ * SCC/closure/frontier partitions; task ownership is bound exclusively by unique witness anchors.
1074
+ */
1075
+ export function enumerateCutSkeletons({
1076
+ component,
1077
+ request,
1078
+ evidence,
1079
+ rawCollected,
1080
+ } = {}) {
1081
+ if (!plainRecord(component)
1082
+ || !Array.isArray(component.task_ids)
1083
+ || !Array.isArray(component.conflicts)
1084
+ || !plainRecord(request)
1085
+ || !plainRecord(evidence)) {
1086
+ fail('cut skeleton enumeration input shapeが不正');
1087
+ }
1088
+ const taskIds = [...component.task_ids].sort(compareText);
1089
+ const intentAnchors = uniqueIntentAnchors(request.manual_witness, taskIds);
1090
+ const missingIntent = taskIds.filter((taskId) => intentAnchors.get(taskId).length === 0);
1091
+ if (missingIntent.length > 0) {
1092
+ return {
1093
+ skeletons: [],
1094
+ unknowns: missingIntent.map((taskId) => ({
1095
+ kind: 'semantic_owner_binding_missing',
1096
+ ref: taskId,
1097
+ })),
1098
+ exploration_complete: false,
1099
+ };
1100
+ }
1101
+
1102
+ const skeletonByLayout = new Map();
1103
+ const unknowns = [];
1104
+ for (const conflict of component.conflicts) {
1105
+ if (conflict.kind !== 'symbol') {
1106
+ unknowns.push({ kind: 'raw_graph_unavailable', ref: conflict.resource_id });
1107
+ continue;
1108
+ }
1109
+ const normalized = normalizeRawGraph({ conflict, evidence, rawCollected });
1110
+ if (normalized.graph === null) {
1111
+ unknowns.push({ kind: normalized.unknown, ref: conflict.resource_id });
1112
+ continue;
1113
+ }
1114
+ const graph = normalized.graph;
1115
+ if (!graph.closure_complete) {
1116
+ unknowns.push({ kind: 'raw_graph_incomplete', ref: conflict.resource_id });
1117
+ }
1118
+ const variants = [
1119
+ ...(graph.closure_complete ? [
1120
+ ['scc', stronglyConnectedPartitions(graph)],
1121
+ ['callee_closure', calleeClosurePartitions(graph)],
1122
+ ] : []),
1123
+ ['module_frontier', moduleFrontierPartitions(graph)],
1124
+ ['task_test_frontier', testFrontierPartitions(graph)],
1125
+ ];
1126
+ for (const [cutKind, rawPartitions] of variants) {
1127
+ const partitions = canonicalPartitions(rawPartitions);
1128
+ if (partitions.length < 2) continue;
1129
+ const layoutKey = digestArtifact({
1130
+ conflict_resource_id: conflict.resource_id,
1131
+ partitions,
1132
+ });
1133
+ const existing = skeletonByLayout.get(layoutKey);
1134
+ if (existing !== undefined) {
1135
+ existing.cut_kinds = sortedUnique([...existing.cut_kinds, cutKind]);
1136
+ continue;
1137
+ }
1138
+ skeletonByLayout.set(layoutKey, {
1139
+ skeleton_id: `cut-${sha16(layoutKey)}`,
1140
+ conflict_resource_id: conflict.resource_id,
1141
+ cut_kinds: [cutKind],
1142
+ root_surface: structuredClone(graph.root),
1143
+ partitions,
1144
+ raw_graph: {
1145
+ nodes: structuredClone(graph.nodes),
1146
+ edges: structuredClone(graph.edges),
1147
+ },
1148
+ });
1149
+ }
1150
+ }
1151
+ const skeletons = [...skeletonByLayout.values()]
1152
+ .sort((left, right) => compareText(left.skeleton_id, right.skeleton_id))
1153
+ .map((skeleton) => bindSkeleton({
1154
+ skeleton,
1155
+ graph: skeleton.raw_graph,
1156
+ intentAnchors,
1157
+ taskIds,
1158
+ }));
1159
+ for (const skeleton of skeletons) unknowns.push(...skeleton.binding_unknowns);
1160
+ if (skeletons.length === 0 && unknowns.length === 0) {
1161
+ unknowns.push({ kind: 'raw_graph_incomplete', ref: component.component_id });
1162
+ }
1163
+ return {
1164
+ skeletons,
1165
+ unknowns: unknowns.sort((left, right) => compareText(
1166
+ `${left.kind}\0${left.ref}`, `${right.kind}\0${right.ref}`,
1167
+ )),
1168
+ exploration_complete: unknowns.length === 0,
1169
+ };
1170
+ }
1171
+
1172
+ function rawGraphSurfaceSet(rawGraph) {
1173
+ if (!exactRecord(rawGraph, ['nodes', 'edges'])
1174
+ || !Array.isArray(rawGraph.nodes)
1175
+ || !Array.isArray(rawGraph.edges)) return null;
1176
+ const surfaces = new Set();
1177
+ for (const node of rawGraph.nodes) {
1178
+ if (!exactRecord(node, ['kind', 'target', 'path'])
1179
+ || !['symbol', 'path'].includes(node.kind)
1180
+ || typeof node.target !== 'string'
1181
+ || typeof node.path !== 'string') return null;
1182
+ surfaces.add(`${node.kind}\0${node.target}\0${node.path}`);
1183
+ }
1184
+ return surfaces;
1185
+ }
1186
+
1187
+ function currentSurfaces(component, evidence) {
1188
+ const ownerByConflict = new Map(component.conflicts.map((conflict) => [
1189
+ conflict.resource_id,
1190
+ sortedUnique(conflict.task_pairs.flat()),
1191
+ ]));
1192
+ const surfaces = [];
1193
+ for (const conflict of component.conflicts) {
1194
+ if (!['symbol', 'path'].includes(conflict.kind)) continue;
1195
+ let path = conflict.target;
1196
+ if (conflict.kind === 'symbol') {
1197
+ const receipt = evidence.queries.find((query) => (
1198
+ query.target === conflict.target
1199
+ && query.outcome === 'resolved'
1200
+ && query.resolved_name === conflict.target
1201
+ && query.resolved_path !== null
1202
+ ));
1203
+ if (receipt === undefined) return null;
1204
+ path = receipt.resolved_path;
1205
+ }
1206
+ surfaces.push({
1207
+ kind: conflict.kind,
1208
+ target: conflict.target,
1209
+ path,
1210
+ role: conflict.kind === 'symbol' ? 'shared_symbol' : 'shared_path',
1211
+ owner_task_ids: ownerByConflict.get(conflict.resource_id),
1212
+ });
1213
+ }
1214
+ return surfaces.sort((left, right) => compareText(surfaceKey(left), surfaceKey(right)));
1215
+ }
1216
+
1217
+ function candidateDominates(left, right) {
1218
+ const noWorse = left.minimumWaves <= right.minimumWaves
1219
+ && isSubset(left.changedSurfaces, right.changedSurfaces)
1220
+ && isSubset(left.blastRadius, right.blastRadius);
1221
+ const strict = left.minimumWaves < right.minimumWaves
1222
+ || left.changedSurfaces.size < right.changedSurfaces.size
1223
+ || left.blastRadius.size < right.blastRadius.size;
1224
+ return noWorse && strict;
1225
+ }
1226
+
1227
+ function decisionUnknown(component, unknowns, reasons = []) {
1228
+ return {
1229
+ component_id: component.component_id,
1230
+ task_ids: [...component.task_ids],
1231
+ conflicts: structuredClone(component.conflicts),
1232
+ verdict: 'unknown_requires_evidence',
1233
+ seam_candidate: null,
1234
+ reasons: reasons.sort((left, right) => compareText(
1235
+ `${left.code}\0${left.detail}`, `${right.code}\0${right.detail}`,
1236
+ )),
1237
+ unknowns: unknowns.sort((left, right) => compareText(
1238
+ `${left.kind}\0${left.ref}`, `${right.kind}\0${right.ref}`,
1239
+ )),
1240
+ };
1241
+ }
1242
+
1243
+ /**
1244
+ * Low-level evaluator for already-materialized skeletons. Task assignment must have been bound
1245
+ * before this point; graph edges are never accepted as ownership evidence.
1246
+ */
1247
+ export function evaluateSeamProposalCandidates({
1248
+ component,
1249
+ request,
1250
+ sensorEvidence,
1251
+ evidence,
1252
+ candidateSpecs,
1253
+ explorationComplete = false,
1254
+ } = {}) {
1255
+ if (!plainRecord(component)
1256
+ || !Array.isArray(component.task_ids)
1257
+ || !Array.isArray(component.conflicts)
1258
+ || !Array.isArray(candidateSpecs)
1259
+ || !plainRecord(evidence)) {
1260
+ fail('decision input shapeが不正');
1261
+ }
1262
+ const taskIds = [...component.task_ids].sort(compareText);
1263
+ if (taskIds.some((taskId, index) => taskId !== component.task_ids[index])) {
1264
+ fail('component.task_idsがstrict sortされていない');
1265
+ }
1266
+ const taskSet = new Set(taskIds);
1267
+ const intentAnchors = uniqueIntentAnchors(request.manual_witness, taskIds);
1268
+ const missingIntent = taskIds.filter((taskId) => intentAnchors.get(taskId).length === 0);
1269
+ if (missingIntent.length > 0) {
1270
+ return decisionUnknown(component, missingIntent.map((taskId) => ({
1271
+ kind: 'semantic_owner_binding_missing',
1272
+ ref: taskId,
1273
+ })));
1274
+ }
1275
+ if (candidateSpecs.length === 0) {
1276
+ return decisionUnknown(component, [{
1277
+ kind: 'candidate_exploration_incomplete',
1278
+ ref: component.component_id,
1279
+ }]);
1280
+ }
1281
+ const current = currentSurfaces(component, evidence);
1282
+ if (current === null) {
1283
+ return decisionUnknown(component, [{
1284
+ kind: 'exact_surface_evidence_missing',
1285
+ ref: component.component_id,
1286
+ }]);
1287
+ }
1288
+
1289
+ const evaluated = [];
1290
+ const rejectedUnknowns = [];
1291
+ const candidateIds = candidateSpecs.map(({ candidate_id: candidateId }) => candidateId);
1292
+ if (new Set(candidateIds).size !== candidateIds.length) {
1293
+ fail('candidate_idが重複している');
1294
+ }
1295
+ for (const spec of candidateSpecs) {
1296
+ if (!exactRecord(spec, [
1297
+ 'candidate_id', 'ownership_diff', 'proposed_surfaces',
1298
+ 'surface_hypotheses', 'raw_graph',
1299
+ ])) {
1300
+ fail('candidate specがclosed shapeではない');
1301
+ }
1302
+ const graphSurfaces = rawGraphSurfaceSet(spec.raw_graph);
1303
+ if (graphSurfaces === null) {
1304
+ rejectedUnknowns.push({ kind: 'raw_graph_unavailable', ref: spec.candidate_id });
1305
+ continue;
1306
+ }
1307
+ if (current.some((surface) => !graphSurfaces.has(
1308
+ `${surface.kind}\0${surface.target}\0${surface.path}`,
1309
+ ))) {
1310
+ rejectedUnknowns.push({ kind: 'raw_graph_incomplete', ref: spec.candidate_id });
1311
+ continue;
1312
+ }
1313
+ if (!Array.isArray(spec.proposed_surfaces)
1314
+ || spec.proposed_surfaces.some((surface) => !plainRecord(surface))) {
1315
+ fail('candidate proposed_surfacesが不正');
1316
+ }
1317
+ const hypothesisKeys = new Set(spec.surface_hypotheses.map((entry) => (
1318
+ `${entry.kind}\0${entry.target}\0${entry.path}`
1319
+ )));
1320
+ const graphIncomplete = spec.proposed_surfaces.some((surface) => {
1321
+ const key = `${surface.kind}\0${surface.target}\0${surface.path}`;
1322
+ return !graphSurfaces.has(key) && !hypothesisKeys.has(key);
1323
+ });
1324
+ if (graphIncomplete) {
1325
+ rejectedUnknowns.push({ kind: 'new_surface_assumption_missing', ref: spec.candidate_id });
1326
+ continue;
1327
+ }
1328
+ const diffIds = spec.ownership_diff.map(({ todo_id: todoId }) => todoId);
1329
+ if (diffIds.length !== taskIds.length
1330
+ || new Set(diffIds).size !== taskIds.length
1331
+ || diffIds.some((taskId) => !taskSet.has(taskId))) {
1332
+ fail('candidate ownership_diffがcomponent全taskのfull diffではない');
1333
+ }
1334
+ const virtualWitness = buildVirtualWitness({
1335
+ request,
1336
+ ownershipDiff: spec.ownership_diff,
1337
+ });
1338
+ const proposedOwnershipMismatch = spec.proposed_surfaces.some((surface) => {
1339
+ if (!Array.isArray(surface.owner_task_ids)) return true;
1340
+ const owners = taskIds.filter((taskId) => virtualWitness[taskId].owns
1341
+ .some((own) => resourceKey(own) === `${surface.kind}\0${surface.target}`));
1342
+ return owners.length !== surface.owner_task_ids.length
1343
+ || owners.some((taskId, index) => taskId !== surface.owner_task_ids[index]);
1344
+ });
1345
+ if (proposedOwnershipMismatch) {
1346
+ rejectedUnknowns.push({
1347
+ kind: 'virtual_witness_surface_mismatch',
1348
+ ref: spec.candidate_id,
1349
+ });
1350
+ continue;
1351
+ }
1352
+ const receipt = createVirtualCompileReceipt({
1353
+ request,
1354
+ sensorEvidence,
1355
+ virtualWitness,
1356
+ surfaceHypotheses: spec.surface_hypotheses,
1357
+ });
1358
+ const derivation = receipt.derivation;
1359
+ if (derivation.outcome !== 'derived'
1360
+ || derivation.unknowns.length > 0
1361
+ || derivation.conflicts.length > 0) {
1362
+ const kind = derivation.drift.length > 0
1363
+ ? derivation.drift[0].kind
1364
+ : derivation.unknowns.length > 0 ? 'virtual_boundary_unknown' : 'residual_conflict';
1365
+ rejectedUnknowns.push({ kind, ref: spec.candidate_id });
1366
+ evaluated.push({ spec, derivation, feasible: false });
1367
+ continue;
1368
+ }
1369
+
1370
+ const proposed = structuredClone(spec.proposed_surfaces)
1371
+ .sort((left, right) => compareText(surfaceKey(left), surfaceKey(right)));
1372
+ const affectedTests = sortedUnique(taskIds.flatMap(
1373
+ (taskId) => virtualWitness[taskId].affected_tests,
1374
+ ));
1375
+ const limits = spec.surface_hypotheses.length > 0
1376
+ ? ['hypothetical_new_surfaces', 'structural_only']
1377
+ : ['structural_only'];
1378
+ const candidate = {
1379
+ proposal_id: deriveSeamProposalId({
1380
+ conflicts: component.conflicts,
1381
+ proposed_surfaces: proposed,
1382
+ }),
1383
+ current_surfaces: current,
1384
+ proposed_surfaces: proposed,
1385
+ affected_tests: affectedTests,
1386
+ verification: {
1387
+ virtual_compile_input_digest: receipt.verification.virtual_compile_input_digest,
1388
+ virtual_compile_result_digest: receipt.verification.virtual_compile_result_digest,
1389
+ residual_conflicts: [],
1390
+ },
1391
+ evidence: structuredClone(evidence),
1392
+ limits,
1393
+ proposal_digest: '',
1394
+ };
1395
+ candidate.proposal_digest = todoSelfDigest(candidate, 'proposal_digest');
1396
+ const changedSurfaces = new Set(proposed.map(surfaceKey));
1397
+ const blastRadius = new Set([
1398
+ ...proposed.map(({ path }) => `path:${path}`),
1399
+ ...affectedTests.map((path) => `test:${path}`),
1400
+ ]);
1401
+ evaluated.push({
1402
+ spec,
1403
+ derivation,
1404
+ feasible: true,
1405
+ candidate,
1406
+ minimumWaves: Math.ceil(taskIds.length / request.capacity.executors),
1407
+ changedSurfaces,
1408
+ blastRadius,
1409
+ });
1410
+ }
1411
+
1412
+ const feasible = evaluated.filter(({ feasible }) => feasible);
1413
+ const nonDominated = feasible.filter((candidate, index) => (
1414
+ !feasible.some((other, otherIndex) => (
1415
+ index !== otherIndex && candidateDominates(other, candidate)
1416
+ ))
1417
+ ));
1418
+ if (nonDominated.length === 1) {
1419
+ return {
1420
+ component_id: component.component_id,
1421
+ task_ids: taskIds,
1422
+ conflicts: structuredClone(component.conflicts),
1423
+ verdict: 'seam_candidate',
1424
+ seam_candidate: nonDominated[0].candidate,
1425
+ reasons: [{
1426
+ code: 'unique_structural_dominant_candidate',
1427
+ detail: 'One feasible candidate structurally dominates all alternatives.',
1428
+ }],
1429
+ unknowns: [],
1430
+ };
1431
+ }
1432
+ if (nonDominated.length > 1) {
1433
+ return decisionUnknown(component, [{
1434
+ kind: 'multiple_incomparable_candidates',
1435
+ ref: nonDominated.map(({ spec }) => spec.candidate_id).sort(compareText).join(','),
1436
+ }]);
1437
+ }
1438
+
1439
+ const serialKinds = new Set(['state', 'effect']);
1440
+ const unseverable = component.conflicts.filter(({ kind }) => serialKinds.has(kind));
1441
+ const unseverableRemains = unseverable.length > 0
1442
+ && evaluated.length === candidateSpecs.length
1443
+ && evaluated.every(({ derivation }) => unseverable.some((conflict) => (
1444
+ derivation.conflicts.some(({ resource_id: resourceId }) => (
1445
+ resourceId === conflict.resource_id || resourceId === conflict.target
1446
+ ))
1447
+ )));
1448
+ if (explorationComplete && unseverableRemains) {
1449
+ return {
1450
+ component_id: component.component_id,
1451
+ task_ids: taskIds,
1452
+ conflicts: structuredClone(component.conflicts),
1453
+ verdict: 'intentional_serial',
1454
+ seam_candidate: null,
1455
+ reasons: [{
1456
+ code: 'unseverable_state_effect_conflict',
1457
+ detail: 'Complete exploration retained a current-contract state/effect conflict.',
1458
+ }],
1459
+ unknowns: [],
1460
+ };
1461
+ }
1462
+ const unknowns = rejectedUnknowns.length > 0
1463
+ ? rejectedUnknowns
1464
+ : [{ kind: 'candidate_exploration_incomplete', ref: component.component_id }];
1465
+ if (!explorationComplete) {
1466
+ unknowns.push({ kind: 'candidate_exploration_incomplete', ref: component.component_id });
1467
+ }
1468
+ return decisionUnknown(component, unknowns);
1469
+ }
1470
+
1471
+ function extractionPath(rootPath, skeletonId, taskId) {
1472
+ const slash = rootPath.lastIndexOf('/');
1473
+ const directory = slash === -1 ? '' : rootPath.slice(0, slash + 1);
1474
+ const filename = slash === -1 ? rootPath : rootPath.slice(slash + 1);
1475
+ const dot = filename.lastIndexOf('.');
1476
+ const stem = dot <= 0 ? filename : filename.slice(0, dot);
1477
+ const extension = dot <= 0 ? '.mjs' : filename.slice(dot);
1478
+ return `${directory}${stem}.seam-${sha16(`${skeletonId}\0${taskId}`)}${extension}`;
1479
+ }
1480
+
1481
+ function skeletonCandidateSpec({ skeleton, component, request, evidence }) {
1482
+ const taskIds = [...component.task_ids].sort(compareText);
1483
+ if (skeleton.binding_unknowns.length > 0
1484
+ || skeleton.task_bindings.length !== taskIds.length) return null;
1485
+ const current = currentSurfaces(component, evidence);
1486
+ if (current === null) return null;
1487
+ const conflictKeys = new Set(component.conflicts.map(({ kind, target }) => (
1488
+ `${kind}\0${target}`
1489
+ )));
1490
+ const currentPaths = sortedUnique(current.map(({ path }) => path));
1491
+ const ownershipDiff = [];
1492
+ const proposedSurfaces = [];
1493
+ const surfaceHypotheses = [];
1494
+ for (const taskId of taskIds) {
1495
+ const original = request.manual_witness[taskId];
1496
+ const path = extractionPath(skeleton.root_surface.path, skeleton.skeleton_id, taskId);
1497
+ const replacePath = (value) => (
1498
+ currentPaths.some((currentPath) => pathPrefixOverlap(value, currentPath)) ? path : value
1499
+ );
1500
+ const owns = original.owns.filter((own) => (
1501
+ !conflictKeys.has(resourceKey(own))
1502
+ && !(own.kind === 'path' && currentPaths.includes(own.target))
1503
+ ));
1504
+ owns.push({ kind: 'path', target: path });
1505
+ const sensorQueries = original.sensor_provenance.queries.filter(({ expect }) => {
1506
+ if (expect.kind === 'symbol') {
1507
+ return !component.conflicts.some((conflict) => (
1508
+ conflict.kind === 'symbol' && conflict.target === expect.name
1509
+ ));
1510
+ }
1511
+ return !currentPaths.includes(expect.path);
1512
+ });
1513
+ ownershipDiff.push({
1514
+ todo_id: taskId,
1515
+ owns: owns.sort((left, right) => compareText(resourceKey(left), resourceKey(right))),
1516
+ reads: sortedUnique(original.reads.map(replacePath)),
1517
+ writes: sortedUnique([...original.writes.map(replacePath), path]),
1518
+ resources: structuredClone(original.resources),
1519
+ state_effects: structuredClone(original.state_effects),
1520
+ sensor_provenance: { queries: structuredClone(sensorQueries) },
1521
+ affected_tests: structuredClone(original.affected_tests),
1522
+ unknowns: structuredClone(original.unknowns),
1523
+ });
1524
+ proposedSurfaces.push({
1525
+ kind: 'path',
1526
+ target: path,
1527
+ path,
1528
+ role: 'task_owned',
1529
+ owner_task_ids: [taskId],
1530
+ });
1531
+ surfaceHypotheses.push({
1532
+ kind: 'path',
1533
+ target: path,
1534
+ path,
1535
+ owner_task_id: taskId,
1536
+ affected_tests: structuredClone(original.affected_tests),
1537
+ provenance: HYPOTHESIS_PROVENANCE,
1538
+ });
1539
+ }
1540
+ return {
1541
+ candidate_id: skeleton.skeleton_id,
1542
+ ownership_diff: ownershipDiff,
1543
+ proposed_surfaces: proposedSurfaces,
1544
+ surface_hypotheses: surfaceHypotheses,
1545
+ raw_graph: structuredClone(skeleton.raw_graph),
1546
+ };
1547
+ }
1548
+
1549
+ /**
1550
+ * Enumerate, bind, materialize, and validate structural cut skeletons. Callers provide collected
1551
+ * sensor outcomes, never handwritten candidate specs.
1552
+ */
1553
+ export function compileSeamProposalDecision({
1554
+ component,
1555
+ request,
1556
+ sensorEvidence,
1557
+ evidence,
1558
+ rawCollected,
1559
+ } = {}) {
1560
+ const enumeration = enumerateCutSkeletons({
1561
+ component,
1562
+ request,
1563
+ evidence,
1564
+ rawCollected,
1565
+ });
1566
+ if (enumeration.unknowns.length > 0) {
1567
+ return decisionUnknown(component, enumeration.unknowns);
1568
+ }
1569
+ const candidateSpecs = enumeration.skeletons.map((skeleton) => (
1570
+ skeletonCandidateSpec({ skeleton, component, request, evidence })
1571
+ ));
1572
+ if (candidateSpecs.some((spec) => spec === null)) {
1573
+ return decisionUnknown(component, [{
1574
+ kind: 'new_surface_assumption_missing',
1575
+ ref: component.component_id,
1576
+ }]);
1577
+ }
1578
+ return evaluateSeamProposalCandidates({
1579
+ component,
1580
+ request,
1581
+ sensorEvidence,
1582
+ evidence,
1583
+ candidateSpecs,
1584
+ explorationComplete: enumeration.exploration_complete,
1585
+ });
1586
+ }
1587
+
1588
+ export class SeamProposalCompileError extends Error {
1589
+ constructor(code, reason, detail = {}) {
1590
+ super(reason);
1591
+ this.name = 'SeamProposalCompileError';
1592
+ this.code = code;
1593
+ this.detail = { reason, ...detail };
1594
+ }
1595
+ }
1596
+
1597
+ function compileFail(code, reason, detail) {
1598
+ throw new SeamProposalCompileError(code, reason, detail);
1599
+ }
1600
+
1601
+ function conflictComponents(independenceArtifact) {
1602
+ const resourceById = new Map(independenceArtifact.conflict_resources.map((resource) => (
1603
+ [resource.resource_id, resource]
1604
+ )));
1605
+ const parent = new Map();
1606
+ const find = (taskId) => {
1607
+ const current = parent.get(taskId) ?? taskId;
1608
+ if (!parent.has(taskId)) parent.set(taskId, taskId);
1609
+ if (current === taskId) return taskId;
1610
+ const root = find(current);
1611
+ parent.set(taskId, root);
1612
+ return root;
1613
+ };
1614
+ const union = (left, right) => {
1615
+ const leftRoot = find(left);
1616
+ const rightRoot = find(right);
1617
+ if (leftRoot === rightRoot) return;
1618
+ if (compareText(leftRoot, rightRoot) < 0) parent.set(rightRoot, leftRoot);
1619
+ else parent.set(leftRoot, rightRoot);
1620
+ };
1621
+
1622
+ for (const { task_ids: [left, right] } of independenceArtifact.conflicts) {
1623
+ union(left, right);
1624
+ }
1625
+
1626
+ const conflictsByRoot = new Map();
1627
+ for (const conflict of independenceArtifact.conflicts) {
1628
+ const root = find(conflict.task_ids[0]);
1629
+ const entries = conflictsByRoot.get(root) ?? [];
1630
+ entries.push(conflict);
1631
+ conflictsByRoot.set(root, entries);
1632
+ }
1633
+
1634
+ const components = [];
1635
+ const classifiedPairKeys = new Set();
1636
+ const classifiedResourceIds = new Set();
1637
+ for (const entries of conflictsByRoot.values()) {
1638
+ const taskIds = sortedUnique(entries.flatMap(({ task_ids: taskPair }) => taskPair));
1639
+ const pairsByResource = new Map();
1640
+ for (const entry of entries) {
1641
+ const pairs = pairsByResource.get(entry.resource_id) ?? [];
1642
+ pairs.push([...entry.task_ids]);
1643
+ pairsByResource.set(entry.resource_id, pairs);
1644
+ classifiedPairKeys.add(`${entry.task_ids[0]}\0${entry.task_ids[1]}\0${entry.resource_id}`);
1645
+ }
1646
+ const conflicts = [...pairsByResource].map(([resourceId, pairs]) => {
1647
+ const resource = resourceById.get(resourceId);
1648
+ if (resource === undefined) {
1649
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_resource_missing', {
1650
+ resource_id: resourceId,
1651
+ });
1652
+ }
1653
+ if (classifiedResourceIds.has(resourceId)) {
1654
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_resource_classified_twice', {
1655
+ resource_id: resourceId,
1656
+ });
1657
+ }
1658
+ classifiedResourceIds.add(resourceId);
1659
+ return {
1660
+ ...structuredClone(resource),
1661
+ task_pairs: pairs.sort((left, right) => compareText(
1662
+ `${left[0]}\0${left[1]}`, `${right[0]}\0${right[1]}`,
1663
+ )),
1664
+ };
1665
+ }).sort((left, right) => compareText(left.resource_id, right.resource_id));
1666
+ const identity = { task_ids: taskIds, conflicts };
1667
+ components.push({
1668
+ component_id: `component-${digestTodoArtifact(identity).slice(0, 24)}`,
1669
+ ...identity,
1670
+ });
1671
+ }
1672
+
1673
+ const expectedPairKeys = new Set(independenceArtifact.conflicts.map((entry) => (
1674
+ `${entry.task_ids[0]}\0${entry.task_ids[1]}\0${entry.resource_id}`
1675
+ )));
1676
+ if (classifiedPairKeys.size !== expectedPairKeys.size
1677
+ || [...expectedPairKeys].some((key) => !classifiedPairKeys.has(key))
1678
+ || classifiedResourceIds.size !== independenceArtifact.conflict_resources.length) {
1679
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_component_partition_incomplete', {
1680
+ expected_pair_count: expectedPairKeys.size,
1681
+ classified_pair_count: classifiedPairKeys.size,
1682
+ expected_resource_count: independenceArtifact.conflict_resources.length,
1683
+ classified_resource_count: classifiedResourceIds.size,
1684
+ });
1685
+ }
1686
+ return components.sort((left, right) => compareText(left.component_id, right.component_id));
1687
+ }
1688
+
1689
+ /**
1690
+ * Build the immutable lattice.seam_proposal.v1 artifact from one complete independence record.
1691
+ * Sensor collection stays outside this producer; callers pass the original witness evidence and
1692
+ * the seam-specific normalized/raw evidence collected for the same clean HEAD.
1693
+ */
1694
+ export function compileSeamProposalArtifact({
1695
+ independenceArtifact,
1696
+ witnessSet,
1697
+ plan,
1698
+ compiledAt,
1699
+ sensorEvidence,
1700
+ evidence,
1701
+ rawCollected,
1702
+ } = {}) {
1703
+ if (!validateTodoIndependence(independenceArtifact)) {
1704
+ compileFail('SEAM_PROPOSAL_INDEPENDENCE_INVALID', 'independence_artifact_invalid');
1705
+ }
1706
+ if (independenceArtifact.outcome !== 'compiled') {
1707
+ compileFail('SEAM_PROPOSAL_INDEPENDENCE_UNAVAILABLE', 'independence_outcome_not_compiled', {
1708
+ outcome: independenceArtifact.outcome,
1709
+ });
1710
+ }
1711
+ if (!validateTodoWitnessSet(witnessSet)) {
1712
+ compileFail('SEAM_PROPOSAL_WITNESS_INVALID', 'witness_set_invalid');
1713
+ }
1714
+ if (!validateTodoPlan(plan)) {
1715
+ compileFail('SEAM_PROPOSAL_PLAN_INVALID', 'plan_invalid');
1716
+ }
1717
+ if (independenceArtifact.project_id !== plan.project_id
1718
+ || independenceArtifact.plan_key !== plan.plan_key
1719
+ || independenceArtifact.plan_version !== plan.plan_version
1720
+ || independenceArtifact.topology_digest !== plan.topology_digest) {
1721
+ compileFail('SEAM_PROPOSAL_BINDING_MISMATCH', 'independence_plan_mismatch');
1722
+ }
1723
+ if (witnessSet.project_id !== plan.project_id
1724
+ || witnessSet.plan_key !== plan.plan_key
1725
+ || witnessSet.witness_set_digest !== independenceArtifact.witness_set_digest) {
1726
+ compileFail('SEAM_PROPOSAL_BINDING_MISMATCH', 'witness_independence_mismatch');
1727
+ }
1728
+
1729
+ const request = synthesizeWitnessRunRequest(witnessSet, {
1730
+ baseSha: independenceArtifact.base_sha,
1731
+ requestId: `seam-proposal-${independenceArtifact.result_digest.slice(0, 24)}`,
1732
+ });
1733
+ const decisions = conflictComponents(independenceArtifact).map((component) => (
1734
+ compileSeamProposalDecision({
1735
+ component,
1736
+ request,
1737
+ sensorEvidence,
1738
+ evidence,
1739
+ rawCollected,
1740
+ })
1741
+ )).sort((left, right) => compareText(left.component_id, right.component_id));
1742
+ const artifact = {
1743
+ schema: SEAM_PROPOSAL_SCHEMA,
1744
+ project_id: plan.project_id,
1745
+ plan_key: plan.plan_key,
1746
+ source_binding: {
1747
+ independence_schema: independenceArtifact.schema,
1748
+ independence_result_digest: independenceArtifact.result_digest,
1749
+ witness_set_digest: independenceArtifact.witness_set_digest,
1750
+ plan_version: independenceArtifact.plan_version,
1751
+ topology_digest: independenceArtifact.topology_digest,
1752
+ base_sha: independenceArtifact.base_sha,
1753
+ },
1754
+ compiled_at: compiledAt,
1755
+ decisions,
1756
+ result_digest: '',
1757
+ };
1758
+ artifact.result_digest = todoSelfDigest(artifact, 'result_digest');
1759
+ if (!validateSeamProposal(artifact)) {
1760
+ compileFail('SEAM_PROPOSAL_ARTIFACT_INVALID', 'seam_proposal_artifact_invalid');
1761
+ }
1762
+ return artifact;
1763
+ }