@quolu/lattice 0.14.0 → 0.16.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,1982 @@
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
+ /** 宣言されたconcern symbolを、`query` operationの解決receiptから探す。 */
759
+ function resolvedSymbolPath(queries, name) {
760
+ const receipt = queries.find((query) => (
761
+ query.operation === 'query'
762
+ && query.target === name
763
+ && query.outcome === 'resolved'
764
+ && query.resolved_name === name
765
+ && typeof query.resolved_path === 'string'
766
+ && query.resolved_path.length > 0
767
+ ));
768
+ return receipt === undefined ? null : receipt.resolved_path;
769
+ }
770
+
771
+ function pathContains(resourcePath, symbolPath) {
772
+ return resourcePath.endsWith('/')
773
+ ? symbolPath.startsWith(resourcePath)
774
+ : symbolPath === resourcePath;
775
+ }
776
+
777
+ /**
778
+ * Resolve declared concern anchors against fresh sensor evidence.
779
+ *
780
+ * A declaration only becomes a binding anchor when the sensor resolves the exact name to exactly
781
+ * one path and that path lies inside the declared resource. Fuzzy resolution to a neighbouring
782
+ * symbol, an absent name, or a symbol living outside the contested resource yields a typed
783
+ * unknown instead — a wrong declaration must never widen what the binder believes it knows.
784
+ *
785
+ * Two ToDos claiming the same symbol is a contradiction in the declarations themselves, not a cut
786
+ * to be discovered: the anchor is dropped from both and reported, so neither side can be bound by
787
+ * a claim the other also makes.
788
+ */
789
+ export function resolveConcernAnchors({ manualWitness, taskIds, evidence } = {}) {
790
+ if (!plainRecord(manualWitness) || !Array.isArray(taskIds) || !plainRecord(evidence)) {
791
+ fail('concern anchor resolution input shapeが不正');
792
+ }
793
+ // receiptが1件も無い証拠は「解決しなかった」であって、宣言を素通しさせる理由にはしない。
794
+ const queries = Array.isArray(evidence.queries) ? evidence.queries : [];
795
+ const anchorsByTask = new Map();
796
+ const unknowns = [];
797
+ for (const taskId of taskIds) {
798
+ const anchors = [];
799
+ for (const entry of manualWitness[taskId]?.concern_anchors ?? []) {
800
+ const resourcePath = entry.within.kind === 'path'
801
+ ? entry.within.target
802
+ : resolvedSymbolPath(queries, entry.within.target);
803
+ if (resourcePath === null) {
804
+ unknowns.push({
805
+ kind: 'concern_anchor_resource_unresolved',
806
+ ref: `${taskId}:${entry.within.kind}:${entry.within.target}`,
807
+ });
808
+ continue;
809
+ }
810
+ for (const symbol of entry.symbols) {
811
+ const symbolPath = resolvedSymbolPath(queries, symbol);
812
+ if (symbolPath === null) {
813
+ unknowns.push({ kind: 'concern_anchor_unresolved', ref: `${taskId}:${symbol}` });
814
+ continue;
815
+ }
816
+ if (!pathContains(resourcePath, symbolPath)) {
817
+ unknowns.push({
818
+ kind: 'concern_anchor_outside_resource',
819
+ ref: `${taskId}:${symbol}:${symbolPath}`,
820
+ });
821
+ continue;
822
+ }
823
+ anchors.push(`concern:${symbolPath}\0${symbol}`);
824
+ }
825
+ }
826
+ anchorsByTask.set(taskId, sortedUnique(anchors));
827
+ }
828
+
829
+ // 同じsymbolを2 task以上が担当と主張したら、どちらの束縛根拠にもしない。
830
+ const claimantsByAnchor = new Map();
831
+ for (const [taskId, anchors] of anchorsByTask) {
832
+ for (const anchor of anchors) {
833
+ if (!claimantsByAnchor.has(anchor)) claimantsByAnchor.set(anchor, []);
834
+ claimantsByAnchor.get(anchor).push(taskId);
835
+ }
836
+ }
837
+ const overlapping = new Set();
838
+ for (const [anchor, claimants] of claimantsByAnchor) {
839
+ if (claimants.length < 2) continue;
840
+ overlapping.add(anchor);
841
+ const [path, symbol] = anchor.slice('concern:'.length).split('\0');
842
+ unknowns.push({
843
+ kind: 'concern_anchor_overlap',
844
+ ref: `${[...claimants].sort(compareText).join(',')}:${path}:${symbol}`,
845
+ });
846
+ }
847
+ if (overlapping.size > 0) {
848
+ for (const [taskId, anchors] of anchorsByTask) {
849
+ anchorsByTask.set(taskId, anchors.filter((anchor) => !overlapping.has(anchor)));
850
+ }
851
+ }
852
+
853
+ return {
854
+ anchorsByTask,
855
+ unknowns: unknowns.sort((left, right) => compareText(
856
+ `${left.kind}\0${left.ref}`, `${right.kind}\0${right.ref}`,
857
+ )),
858
+ };
859
+ }
860
+
861
+ /** witness set全体から、sensorへ問い合わせるconcern symbol名を集める。 */
862
+ export function declaredConcernSymbols(manualWitness) {
863
+ if (!plainRecord(manualWitness)) fail('manual witness shapeが不正');
864
+ const names = [];
865
+ for (const witness of Object.values(manualWitness)) {
866
+ for (const entry of witness?.concern_anchors ?? []) {
867
+ names.push(...entry.symbols);
868
+ if (entry.within.kind === 'symbol') names.push(entry.within.target);
869
+ }
870
+ }
871
+ return sortedUnique(names);
872
+ }
873
+
874
+ function uniqueIntentAnchors(manualWitness, taskIds) {
875
+ const anchorsByTask = new Map();
876
+ const counts = new Map();
877
+ for (const taskId of taskIds) {
878
+ const witness = manualWitness[taskId];
879
+ const anchors = [
880
+ ...witness.owns.map((own) => `owns:${resourceKey(own)}`),
881
+ ...witness.writes.map((path) => `writes:${path}`),
882
+ ...witness.affected_tests.map((path) => `affected_tests:${path}`),
883
+ ];
884
+ anchorsByTask.set(taskId, sortedUnique(anchors));
885
+ for (const anchor of new Set(anchors)) counts.set(anchor, (counts.get(anchor) ?? 0) + 1);
886
+ }
887
+ return new Map([...anchorsByTask].map(([taskId, anchors]) => [
888
+ taskId,
889
+ anchors.filter((anchor) => counts.get(anchor) === 1),
890
+ ]));
891
+ }
892
+
893
+ function graphNode(entry) {
894
+ const node = plainRecord(entry?.node) ? entry.node : entry;
895
+ if (!plainRecord(node)
896
+ || typeof node.name !== 'string'
897
+ || node.name.length === 0
898
+ || typeof node.filePath !== 'string'
899
+ || node.filePath.length === 0
900
+ || node.filePath.startsWith('/')) return null;
901
+ if (node.kind === 'file') {
902
+ return { kind: 'path', target: node.filePath, path: node.filePath };
903
+ }
904
+ return { kind: 'symbol', target: node.name, path: node.filePath };
905
+ }
906
+
907
+ function graphNodeKey(node) {
908
+ return `${node.kind}\0${node.target}\0${node.path}`;
909
+ }
910
+
911
+ function graphEdgeKey(edge) {
912
+ return `${edge.from}\0${edge.to}\0${edge.kind}`;
913
+ }
914
+
915
+ function graphPayload(outcome, operation) {
916
+ if (!plainRecord(outcome) || outcome.outcome !== 'ready') return null;
917
+ if (operation === 'query') return outcome.data;
918
+ if (!plainRecord(outcome.data)) return null;
919
+ if (operation === 'callers') return outcome.data.callers;
920
+ if (operation === 'callees') return outcome.data.callees;
921
+ if (operation === 'impact') return outcome.data.affected;
922
+ return null;
923
+ }
924
+
925
+ function normalizeRawGraph({ conflict, evidence, rawCollected }) {
926
+ if (!plainRecord(rawCollected) || !Array.isArray(rawCollected.outcomes)) {
927
+ return { graph: null, unknown: 'raw_graph_unavailable' };
928
+ }
929
+ const receipts = evidence.queries.filter((query) => (
930
+ query.target === conflict.target && STRUCTURE_OPERATIONS.has(query.operation)
931
+ ));
932
+ if (receipts.length !== STRUCTURE_OPERATIONS.size
933
+ || receipts.some((query) => query.outcome !== 'resolved'
934
+ || query.resolved_name !== conflict.target
935
+ || query.resolved_path === null)) {
936
+ return { graph: null, unknown: 'raw_graph_incomplete' };
937
+ }
938
+ const outcomeById = new Map(rawCollected.outcomes.map((outcome) => [outcome?.id, outcome]));
939
+ const receiptByOperation = new Map(receipts.map((receipt) => [receipt.operation, receipt]));
940
+ const payloadByOperation = new Map();
941
+ for (const operation of STRUCTURE_OPERATIONS) {
942
+ const receipt = receiptByOperation.get(operation);
943
+ const payload = graphPayload(outcomeById.get(receipt.query_id), operation);
944
+ if (!Array.isArray(payload)) {
945
+ return { graph: null, unknown: 'raw_graph_incomplete' };
946
+ }
947
+ payloadByOperation.set(operation, payload);
948
+ }
949
+
950
+ const queryReceipt = receiptByOperation.get('query');
951
+ const rootMatches = payloadByOperation.get('query')
952
+ .map(graphNode)
953
+ .filter((node) => node !== null
954
+ && node.kind === 'symbol'
955
+ && node.target === conflict.target
956
+ && node.path === queryReceipt.resolved_path);
957
+ if (rootMatches.length !== 1) {
958
+ return { graph: null, unknown: 'raw_graph_incomplete' };
959
+ }
960
+ const root = rootMatches[0];
961
+ const nodes = new Map([[graphNodeKey(root), root]]);
962
+ const edges = new Map();
963
+ let invalidObservedNode = false;
964
+ const addObserved = (entry) => {
965
+ const node = graphNode(entry);
966
+ if (node === null) invalidObservedNode = true;
967
+ if (node !== null) nodes.set(graphNodeKey(node), node);
968
+ return node;
969
+ };
970
+ for (const entry of payloadByOperation.get('callers')) {
971
+ const node = addObserved(entry);
972
+ if (node === null) continue;
973
+ const edge = { from: graphNodeKey(node), to: graphNodeKey(root), kind: 'caller' };
974
+ edges.set(graphEdgeKey(edge), edge);
975
+ }
976
+ for (const entry of payloadByOperation.get('callees')) {
977
+ const node = addObserved(entry);
978
+ if (node === null) continue;
979
+ const edge = { from: graphNodeKey(root), to: graphNodeKey(node), kind: 'callee' };
980
+ edges.set(graphEdgeKey(edge), edge);
981
+ }
982
+ for (const entry of payloadByOperation.get('impact')) addObserved(entry);
983
+ let closureComplete = plainRecord(rawCollected.graph_closure)
984
+ && rawCollected.graph_closure.complete === true
985
+ && Array.isArray(rawCollected.graph_closure.expansions);
986
+ if (plainRecord(rawCollected.graph_closure)
987
+ && Array.isArray(rawCollected.graph_closure.expansions)) {
988
+ for (const expansion of rawCollected.graph_closure.expansions) {
989
+ const parent = graphNode(expansion?.parent);
990
+ const rawCallees = expansion?.callees_outcome;
991
+ if (expansion?.exact !== true
992
+ || parent === null
993
+ || !plainRecord(rawCallees)
994
+ || rawCallees.outcome !== 'ready'
995
+ || !plainRecord(rawCallees.data)
996
+ || !Array.isArray(rawCallees.data.callees)) {
997
+ closureComplete = false;
998
+ continue;
999
+ }
1000
+ nodes.set(graphNodeKey(parent), parent);
1001
+ for (const entry of rawCallees.data.callees) {
1002
+ const child = addObserved(entry);
1003
+ if (child === null) {
1004
+ closureComplete = false;
1005
+ continue;
1006
+ }
1007
+ const edge = {
1008
+ from: graphNodeKey(parent),
1009
+ to: graphNodeKey(child),
1010
+ kind: 'callee',
1011
+ };
1012
+ edges.set(graphEdgeKey(edge), edge);
1013
+ }
1014
+ }
1015
+ }
1016
+ if (invalidObservedNode) {
1017
+ return { graph: null, unknown: 'raw_graph_incomplete' };
1018
+ }
1019
+ return {
1020
+ graph: {
1021
+ root,
1022
+ closure_complete: closureComplete,
1023
+ nodes: [...nodes.values()].sort((left, right) => compareText(
1024
+ graphNodeKey(left), graphNodeKey(right),
1025
+ )),
1026
+ edges: [...edges.values()].sort((left, right) => compareText(
1027
+ graphEdgeKey(left), graphEdgeKey(right),
1028
+ )),
1029
+ },
1030
+ unknown: null,
1031
+ };
1032
+ }
1033
+
1034
+ function stronglyConnectedPartitions(graph) {
1035
+ const symbolKeys = new Set(graph.nodes
1036
+ .filter(({ kind }) => kind === 'symbol').map(graphNodeKey));
1037
+ const adjacency = new Map([...symbolKeys].map((key) => [key, []]));
1038
+ for (const edge of graph.edges) {
1039
+ if (symbolKeys.has(edge.from) && symbolKeys.has(edge.to)) {
1040
+ adjacency.get(edge.from).push(edge.to);
1041
+ }
1042
+ }
1043
+ for (const targets of adjacency.values()) targets.sort(compareText);
1044
+ let nextIndex = 0;
1045
+ const indexes = new Map();
1046
+ const lowLinks = new Map();
1047
+ const stack = [];
1048
+ const onStack = new Set();
1049
+ const components = [];
1050
+ const visit = (key) => {
1051
+ indexes.set(key, nextIndex);
1052
+ lowLinks.set(key, nextIndex);
1053
+ nextIndex += 1;
1054
+ stack.push(key);
1055
+ onStack.add(key);
1056
+ for (const target of adjacency.get(key)) {
1057
+ if (!indexes.has(target)) {
1058
+ visit(target);
1059
+ lowLinks.set(key, Math.min(lowLinks.get(key), lowLinks.get(target)));
1060
+ } else if (onStack.has(target)) {
1061
+ lowLinks.set(key, Math.min(lowLinks.get(key), indexes.get(target)));
1062
+ }
1063
+ }
1064
+ if (lowLinks.get(key) !== indexes.get(key)) return;
1065
+ const component = [];
1066
+ while (stack.length > 0) {
1067
+ const member = stack.pop();
1068
+ onStack.delete(member);
1069
+ component.push(member);
1070
+ if (member === key) break;
1071
+ }
1072
+ components.push(component.sort(compareText));
1073
+ };
1074
+ for (const key of [...symbolKeys].sort(compareText)) {
1075
+ if (!indexes.has(key)) visit(key);
1076
+ }
1077
+ return components.sort((left, right) => compareText(left.join('\0'), right.join('\0')));
1078
+ }
1079
+
1080
+ function calleeClosurePartitions(graph) {
1081
+ const adjacency = new Map(graph.nodes.map((node) => [graphNodeKey(node), []]));
1082
+ for (const edge of graph.edges.filter(({ kind }) => kind === 'callee')) {
1083
+ adjacency.get(edge.from)?.push(edge.to);
1084
+ }
1085
+ for (const targets of adjacency.values()) targets.sort(compareText);
1086
+ const direct = adjacency.get(graphNodeKey(graph.root)) ?? [];
1087
+ return direct.map((start) => {
1088
+ const seen = new Set();
1089
+ const queue = [start];
1090
+ while (queue.length > 0) {
1091
+ const key = queue.shift();
1092
+ if (seen.has(key)) continue;
1093
+ seen.add(key);
1094
+ queue.push(...(adjacency.get(key) ?? []));
1095
+ }
1096
+ return [...seen].sort(compareText);
1097
+ });
1098
+ }
1099
+
1100
+ function moduleFrontierPartitions(graph) {
1101
+ const byPath = new Map();
1102
+ for (const node of graph.nodes) {
1103
+ if (!byPath.has(node.path)) byPath.set(node.path, []);
1104
+ byPath.get(node.path).push(graphNodeKey(node));
1105
+ }
1106
+ return [...byPath.entries()].sort((left, right) => compareText(left[0], right[0]))
1107
+ .map(([, keys]) => keys.sort(compareText));
1108
+ }
1109
+
1110
+ function testFrontierPartitions(graph) {
1111
+ return graph.nodes
1112
+ .filter(({ kind, path }) => kind === 'path'
1113
+ && (path.startsWith('test/') || /\.test\.[cm]?[jt]sx?$/u.test(path)))
1114
+ .map((node) => [graphNodeKey(node)]);
1115
+ }
1116
+
1117
+ function canonicalPartitions(partitions) {
1118
+ const unique = new Set();
1119
+ for (const partition of partitions) {
1120
+ const key = sortedUnique(partition).join('\u0001');
1121
+ if (key.length > 0) unique.add(key);
1122
+ }
1123
+ return [...unique].sort(compareText).map((key) => key.split('\u0001'));
1124
+ }
1125
+
1126
+ function anchorMatchesNode(anchor, node) {
1127
+ if (anchor.startsWith('concern:')) {
1128
+ const separator = anchor.indexOf('\0');
1129
+ return node.kind === 'symbol'
1130
+ && node.path === anchor.slice('concern:'.length, separator)
1131
+ && node.target === anchor.slice(separator + 1);
1132
+ }
1133
+ if (anchor.startsWith('owns:symbol\0')) {
1134
+ return node.kind === 'symbol' && node.target === anchor.slice('owns:symbol\0'.length);
1135
+ }
1136
+ if (anchor.startsWith('owns:path\0')) {
1137
+ return node.path === anchor.slice('owns:path\0'.length);
1138
+ }
1139
+ if (anchor.startsWith('writes:')) return node.path === anchor.slice('writes:'.length);
1140
+ if (anchor.startsWith('affected_tests:')) {
1141
+ return node.path === anchor.slice('affected_tests:'.length);
1142
+ }
1143
+ return false;
1144
+ }
1145
+
1146
+ /**
1147
+ * Bind tasks to partitions.
1148
+ *
1149
+ * Declared concern anchors take precedence over the coarse owns/writes/test anchors within one
1150
+ * skeleton: a ToDo that named the symbols it touches inside the contested resource has given
1151
+ * strictly more specific evidence than "it owns some file". The coarse anchors stay as the
1152
+ * fallback for skeletons the declaration says nothing about, so declaring a concern for one
1153
+ * conflict never blinds the binder to another.
1154
+ */
1155
+ function bindSkeleton({ skeleton, graph, intentAnchors, concernAnchors, taskIds }) {
1156
+ const nodeByKey = new Map(graph.nodes.map((node) => [graphNodeKey(node), node]));
1157
+ const taskBindings = [];
1158
+ const unknowns = [];
1159
+ const matchesFor = (anchors) => {
1160
+ const matched = [];
1161
+ skeleton.partitions.forEach((partition, index) => {
1162
+ const hits = anchors.filter((anchor) => (
1163
+ partition.some((key) => anchorMatchesNode(anchor, nodeByKey.get(key)))
1164
+ ));
1165
+ if (hits.length > 0) matched.push({ index, anchors: sortedUnique(hits) });
1166
+ });
1167
+ return matched;
1168
+ };
1169
+ for (const taskId of taskIds) {
1170
+ const declared = matchesFor(concernAnchors.get(taskId) ?? []);
1171
+ const matches = declared.length > 0 ? declared : matchesFor(intentAnchors.get(taskId));
1172
+ if (matches.length === 0) {
1173
+ unknowns.push({
1174
+ kind: 'semantic_owner_binding_missing',
1175
+ ref: `${skeleton.skeleton_id}:${taskId}`,
1176
+ });
1177
+ continue;
1178
+ }
1179
+ if (matches.length > 1) {
1180
+ unknowns.push({
1181
+ kind: 'semantic_owner_binding_ambiguous',
1182
+ ref: `${skeleton.skeleton_id}:${taskId}`,
1183
+ });
1184
+ continue;
1185
+ }
1186
+ taskBindings.push({
1187
+ task_id: taskId,
1188
+ partition_index: matches[0].index,
1189
+ anchors: matches[0].anchors,
1190
+ });
1191
+ }
1192
+ if (taskBindings.length === taskIds.length
1193
+ && new Set(taskBindings.map(({ partition_index: index }) => index)).size
1194
+ !== taskBindings.length) {
1195
+ unknowns.push({
1196
+ kind: 'semantic_owner_binding_ambiguous',
1197
+ ref: `${skeleton.skeleton_id}:shared_partition`,
1198
+ });
1199
+ }
1200
+ return {
1201
+ ...skeleton,
1202
+ task_bindings: taskBindings,
1203
+ binding_unknowns: unknowns,
1204
+ };
1205
+ }
1206
+
1207
+ /**
1208
+ * Build a cut skeleton for a contested repo path out of the declared concern anchors alone.
1209
+ *
1210
+ * A path conflict has no call graph to partition — the sensor was only asked which tests the file
1211
+ * affects. What the declarations do give is a partition of the file's symbols by owner, which is
1212
+ * exactly the shape a cut needs. Every task in the component must have named at least one symbol
1213
+ * inside the path; otherwise there is nothing to say about who owns which half and the caller
1214
+ * keeps reporting the resource as unavailable rather than guessing.
1215
+ */
1216
+ function declaredPartitionSkeleton({ conflict, concernAnchors, taskIds }) {
1217
+ const rootPath = conflict.target;
1218
+ const root = { kind: 'path', target: rootPath, path: rootPath };
1219
+ const nodes = [root];
1220
+ const partitions = [];
1221
+ for (const taskId of taskIds) {
1222
+ const owned = (concernAnchors.get(taskId) ?? [])
1223
+ .map((anchor) => {
1224
+ const separator = anchor.indexOf('\0');
1225
+ return {
1226
+ path: anchor.slice('concern:'.length, separator),
1227
+ name: anchor.slice(separator + 1),
1228
+ };
1229
+ })
1230
+ .filter(({ path }) => pathContains(rootPath, path));
1231
+ if (owned.length === 0) return null;
1232
+ for (const { path, name } of owned) nodes.push({ kind: 'symbol', target: name, path });
1233
+ partitions.push(owned.map(({ path, name }) => graphNodeKey({
1234
+ kind: 'symbol', target: name, path,
1235
+ })));
1236
+ }
1237
+ return {
1238
+ root,
1239
+ nodes,
1240
+ partitions: canonicalPartitions(partitions),
1241
+ };
1242
+ }
1243
+
1244
+ /**
1245
+ * Enumerate structural cut skeletons from the in-memory sensor outcomes. Graph edges only shape
1246
+ * SCC/closure/frontier partitions; task ownership is bound exclusively by unique witness anchors
1247
+ * and by declared concern anchors, never by the edges themselves.
1248
+ */
1249
+ export function enumerateCutSkeletons({
1250
+ component,
1251
+ request,
1252
+ evidence,
1253
+ rawCollected,
1254
+ concernAnchors = new Map(),
1255
+ } = {}) {
1256
+ if (!plainRecord(component)
1257
+ || !Array.isArray(component.task_ids)
1258
+ || !Array.isArray(component.conflicts)
1259
+ || !plainRecord(request)
1260
+ || !plainRecord(evidence)) {
1261
+ fail('cut skeleton enumeration input shapeが不正');
1262
+ }
1263
+ const taskIds = [...component.task_ids].sort(compareText);
1264
+ const intentAnchors = uniqueIntentAnchors(request.manual_witness, taskIds);
1265
+ const missingIntent = taskIds.filter((taskId) => (
1266
+ intentAnchors.get(taskId).length === 0 && (concernAnchors.get(taskId) ?? []).length === 0
1267
+ ));
1268
+ if (missingIntent.length > 0) {
1269
+ return {
1270
+ skeletons: [],
1271
+ unknowns: missingIntent.map((taskId) => ({
1272
+ kind: 'semantic_owner_binding_missing',
1273
+ ref: taskId,
1274
+ })),
1275
+ exploration_complete: false,
1276
+ };
1277
+ }
1278
+
1279
+ const skeletonByLayout = new Map();
1280
+ const unknowns = [];
1281
+ for (const conflict of component.conflicts) {
1282
+ if (conflict.kind === 'path') {
1283
+ const declared = declaredPartitionSkeleton({ conflict, concernAnchors, taskIds });
1284
+ if (declared === null || declared.partitions.length < 2) {
1285
+ unknowns.push({ kind: 'raw_graph_unavailable', ref: conflict.resource_id });
1286
+ continue;
1287
+ }
1288
+ const layoutKey = digestArtifact({
1289
+ conflict_resource_id: conflict.resource_id,
1290
+ partitions: declared.partitions,
1291
+ });
1292
+ skeletonByLayout.set(layoutKey, {
1293
+ skeleton_id: `cut-${sha16(layoutKey)}`,
1294
+ conflict_resource_id: conflict.resource_id,
1295
+ cut_kinds: ['declared_partition'],
1296
+ root_surface: structuredClone(declared.root),
1297
+ partitions: declared.partitions,
1298
+ raw_graph: { nodes: structuredClone(declared.nodes), edges: [] },
1299
+ });
1300
+ continue;
1301
+ }
1302
+ if (conflict.kind !== 'symbol') {
1303
+ unknowns.push({ kind: 'raw_graph_unavailable', ref: conflict.resource_id });
1304
+ continue;
1305
+ }
1306
+ const normalized = normalizeRawGraph({ conflict, evidence, rawCollected });
1307
+ if (normalized.graph === null) {
1308
+ unknowns.push({ kind: normalized.unknown, ref: conflict.resource_id });
1309
+ continue;
1310
+ }
1311
+ const graph = normalized.graph;
1312
+ if (!graph.closure_complete) {
1313
+ unknowns.push({ kind: 'raw_graph_incomplete', ref: conflict.resource_id });
1314
+ }
1315
+ const variants = [
1316
+ ...(graph.closure_complete ? [
1317
+ ['scc', stronglyConnectedPartitions(graph)],
1318
+ ['callee_closure', calleeClosurePartitions(graph)],
1319
+ ] : []),
1320
+ ['module_frontier', moduleFrontierPartitions(graph)],
1321
+ ['task_test_frontier', testFrontierPartitions(graph)],
1322
+ ];
1323
+ for (const [cutKind, rawPartitions] of variants) {
1324
+ const partitions = canonicalPartitions(rawPartitions);
1325
+ if (partitions.length < 2) continue;
1326
+ const layoutKey = digestArtifact({
1327
+ conflict_resource_id: conflict.resource_id,
1328
+ partitions,
1329
+ });
1330
+ const existing = skeletonByLayout.get(layoutKey);
1331
+ if (existing !== undefined) {
1332
+ existing.cut_kinds = sortedUnique([...existing.cut_kinds, cutKind]);
1333
+ continue;
1334
+ }
1335
+ skeletonByLayout.set(layoutKey, {
1336
+ skeleton_id: `cut-${sha16(layoutKey)}`,
1337
+ conflict_resource_id: conflict.resource_id,
1338
+ cut_kinds: [cutKind],
1339
+ root_surface: structuredClone(graph.root),
1340
+ partitions,
1341
+ raw_graph: {
1342
+ nodes: structuredClone(graph.nodes),
1343
+ edges: structuredClone(graph.edges),
1344
+ },
1345
+ });
1346
+ }
1347
+ }
1348
+ const skeletons = [...skeletonByLayout.values()]
1349
+ .sort((left, right) => compareText(left.skeleton_id, right.skeleton_id))
1350
+ .map((skeleton) => bindSkeleton({
1351
+ skeleton,
1352
+ graph: skeleton.raw_graph,
1353
+ intentAnchors,
1354
+ concernAnchors,
1355
+ taskIds,
1356
+ }));
1357
+ for (const skeleton of skeletons) unknowns.push(...skeleton.binding_unknowns);
1358
+ if (skeletons.length === 0 && unknowns.length === 0) {
1359
+ unknowns.push({ kind: 'raw_graph_incomplete', ref: component.component_id });
1360
+ }
1361
+ return {
1362
+ skeletons,
1363
+ unknowns: unknowns.sort((left, right) => compareText(
1364
+ `${left.kind}\0${left.ref}`, `${right.kind}\0${right.ref}`,
1365
+ )),
1366
+ exploration_complete: unknowns.length === 0,
1367
+ };
1368
+ }
1369
+
1370
+ function rawGraphSurfaceSet(rawGraph) {
1371
+ if (!exactRecord(rawGraph, ['nodes', 'edges'])
1372
+ || !Array.isArray(rawGraph.nodes)
1373
+ || !Array.isArray(rawGraph.edges)) return null;
1374
+ const surfaces = new Set();
1375
+ for (const node of rawGraph.nodes) {
1376
+ if (!exactRecord(node, ['kind', 'target', 'path'])
1377
+ || !['symbol', 'path'].includes(node.kind)
1378
+ || typeof node.target !== 'string'
1379
+ || typeof node.path !== 'string') return null;
1380
+ surfaces.add(`${node.kind}\0${node.target}\0${node.path}`);
1381
+ }
1382
+ return surfaces;
1383
+ }
1384
+
1385
+ function currentSurfaces(component, evidence) {
1386
+ const ownerByConflict = new Map(component.conflicts.map((conflict) => [
1387
+ conflict.resource_id,
1388
+ sortedUnique(conflict.task_pairs.flat()),
1389
+ ]));
1390
+ const surfaces = [];
1391
+ for (const conflict of component.conflicts) {
1392
+ if (!['symbol', 'path'].includes(conflict.kind)) continue;
1393
+ let path = conflict.target;
1394
+ if (conflict.kind === 'symbol') {
1395
+ const receipt = evidence.queries.find((query) => (
1396
+ query.target === conflict.target
1397
+ && query.outcome === 'resolved'
1398
+ && query.resolved_name === conflict.target
1399
+ && query.resolved_path !== null
1400
+ ));
1401
+ if (receipt === undefined) return null;
1402
+ path = receipt.resolved_path;
1403
+ }
1404
+ surfaces.push({
1405
+ kind: conflict.kind,
1406
+ target: conflict.target,
1407
+ path,
1408
+ role: conflict.kind === 'symbol' ? 'shared_symbol' : 'shared_path',
1409
+ owner_task_ids: ownerByConflict.get(conflict.resource_id),
1410
+ });
1411
+ }
1412
+ return surfaces.sort((left, right) => compareText(surfaceKey(left), surfaceKey(right)));
1413
+ }
1414
+
1415
+ function candidateDominates(left, right) {
1416
+ const noWorse = left.minimumWaves <= right.minimumWaves
1417
+ && isSubset(left.changedSurfaces, right.changedSurfaces)
1418
+ && isSubset(left.blastRadius, right.blastRadius);
1419
+ const strict = left.minimumWaves < right.minimumWaves
1420
+ || left.changedSurfaces.size < right.changedSurfaces.size
1421
+ || left.blastRadius.size < right.blastRadius.size;
1422
+ return noWorse && strict;
1423
+ }
1424
+
1425
+ function decisionUnknown(component, unknowns, reasons = []) {
1426
+ return {
1427
+ component_id: component.component_id,
1428
+ task_ids: [...component.task_ids],
1429
+ conflicts: structuredClone(component.conflicts),
1430
+ verdict: 'unknown_requires_evidence',
1431
+ seam_candidate: null,
1432
+ reasons: reasons.sort((left, right) => compareText(
1433
+ `${left.code}\0${left.detail}`, `${right.code}\0${right.detail}`,
1434
+ )),
1435
+ unknowns: unknowns.sort((left, right) => compareText(
1436
+ `${left.kind}\0${left.ref}`, `${right.kind}\0${right.ref}`,
1437
+ )),
1438
+ };
1439
+ }
1440
+
1441
+ /**
1442
+ * Low-level evaluator for already-materialized skeletons. Task assignment must have been bound
1443
+ * before this point; graph edges are never accepted as ownership evidence.
1444
+ */
1445
+ export function evaluateSeamProposalCandidates({
1446
+ component,
1447
+ request,
1448
+ sensorEvidence,
1449
+ evidence,
1450
+ candidateSpecs,
1451
+ explorationComplete = false,
1452
+ concernAnchors = new Map(),
1453
+ } = {}) {
1454
+ if (!plainRecord(component)
1455
+ || !Array.isArray(component.task_ids)
1456
+ || !Array.isArray(component.conflicts)
1457
+ || !Array.isArray(candidateSpecs)
1458
+ || !plainRecord(evidence)) {
1459
+ fail('decision input shapeが不正');
1460
+ }
1461
+ const taskIds = [...component.task_ids].sort(compareText);
1462
+ if (taskIds.some((taskId, index) => taskId !== component.task_ids[index])) {
1463
+ fail('component.task_idsがstrict sortされていない');
1464
+ }
1465
+ const taskSet = new Set(taskIds);
1466
+ const intentAnchors = uniqueIntentAnchors(request.manual_witness, taskIds);
1467
+ const missingIntent = taskIds.filter((taskId) => (
1468
+ intentAnchors.get(taskId).length === 0 && (concernAnchors.get(taskId) ?? []).length === 0
1469
+ ));
1470
+ if (missingIntent.length > 0) {
1471
+ return decisionUnknown(component, missingIntent.map((taskId) => ({
1472
+ kind: 'semantic_owner_binding_missing',
1473
+ ref: taskId,
1474
+ })));
1475
+ }
1476
+ if (candidateSpecs.length === 0) {
1477
+ return decisionUnknown(component, [{
1478
+ kind: 'candidate_exploration_incomplete',
1479
+ ref: component.component_id,
1480
+ }]);
1481
+ }
1482
+ const current = currentSurfaces(component, evidence);
1483
+ if (current === null) {
1484
+ return decisionUnknown(component, [{
1485
+ kind: 'exact_surface_evidence_missing',
1486
+ ref: component.component_id,
1487
+ }]);
1488
+ }
1489
+
1490
+ const evaluated = [];
1491
+ const rejectedUnknowns = [];
1492
+ const candidateIds = candidateSpecs.map(({ candidate_id: candidateId }) => candidateId);
1493
+ if (new Set(candidateIds).size !== candidateIds.length) {
1494
+ fail('candidate_idが重複している');
1495
+ }
1496
+ for (const spec of candidateSpecs) {
1497
+ if (!exactRecord(spec, [
1498
+ 'candidate_id', 'ownership_diff', 'proposed_surfaces',
1499
+ 'surface_hypotheses', 'raw_graph',
1500
+ ])) {
1501
+ fail('candidate specがclosed shapeではない');
1502
+ }
1503
+ const graphSurfaces = rawGraphSurfaceSet(spec.raw_graph);
1504
+ if (graphSurfaces === null) {
1505
+ rejectedUnknowns.push({ kind: 'raw_graph_unavailable', ref: spec.candidate_id });
1506
+ continue;
1507
+ }
1508
+ if (current.some((surface) => !graphSurfaces.has(
1509
+ `${surface.kind}\0${surface.target}\0${surface.path}`,
1510
+ ))) {
1511
+ rejectedUnknowns.push({ kind: 'raw_graph_incomplete', ref: spec.candidate_id });
1512
+ continue;
1513
+ }
1514
+ if (!Array.isArray(spec.proposed_surfaces)
1515
+ || spec.proposed_surfaces.some((surface) => !plainRecord(surface))) {
1516
+ fail('candidate proposed_surfacesが不正');
1517
+ }
1518
+ const hypothesisKeys = new Set(spec.surface_hypotheses.map((entry) => (
1519
+ `${entry.kind}\0${entry.target}\0${entry.path}`
1520
+ )));
1521
+ const graphIncomplete = spec.proposed_surfaces.some((surface) => {
1522
+ const key = `${surface.kind}\0${surface.target}\0${surface.path}`;
1523
+ return !graphSurfaces.has(key) && !hypothesisKeys.has(key);
1524
+ });
1525
+ if (graphIncomplete) {
1526
+ rejectedUnknowns.push({ kind: 'new_surface_assumption_missing', ref: spec.candidate_id });
1527
+ continue;
1528
+ }
1529
+ const diffIds = spec.ownership_diff.map(({ todo_id: todoId }) => todoId);
1530
+ if (diffIds.length !== taskIds.length
1531
+ || new Set(diffIds).size !== taskIds.length
1532
+ || diffIds.some((taskId) => !taskSet.has(taskId))) {
1533
+ fail('candidate ownership_diffがcomponent全taskのfull diffではない');
1534
+ }
1535
+ const virtualWitness = buildVirtualWitness({
1536
+ request,
1537
+ ownershipDiff: spec.ownership_diff,
1538
+ });
1539
+ const proposedOwnershipMismatch = spec.proposed_surfaces.some((surface) => {
1540
+ if (!Array.isArray(surface.owner_task_ids)) return true;
1541
+ const owners = taskIds.filter((taskId) => virtualWitness[taskId].owns
1542
+ .some((own) => resourceKey(own) === `${surface.kind}\0${surface.target}`));
1543
+ return owners.length !== surface.owner_task_ids.length
1544
+ || owners.some((taskId, index) => taskId !== surface.owner_task_ids[index]);
1545
+ });
1546
+ if (proposedOwnershipMismatch) {
1547
+ rejectedUnknowns.push({
1548
+ kind: 'virtual_witness_surface_mismatch',
1549
+ ref: spec.candidate_id,
1550
+ });
1551
+ continue;
1552
+ }
1553
+ const receipt = createVirtualCompileReceipt({
1554
+ request,
1555
+ sensorEvidence,
1556
+ virtualWitness,
1557
+ surfaceHypotheses: spec.surface_hypotheses,
1558
+ });
1559
+ const derivation = receipt.derivation;
1560
+ if (derivation.outcome !== 'derived'
1561
+ || derivation.unknowns.length > 0
1562
+ || derivation.conflicts.length > 0) {
1563
+ const kind = derivation.drift.length > 0
1564
+ ? derivation.drift[0].kind
1565
+ : derivation.unknowns.length > 0 ? 'virtual_boundary_unknown' : 'residual_conflict';
1566
+ rejectedUnknowns.push({ kind, ref: spec.candidate_id });
1567
+ evaluated.push({ spec, derivation, feasible: false });
1568
+ continue;
1569
+ }
1570
+
1571
+ const proposed = structuredClone(spec.proposed_surfaces)
1572
+ .sort((left, right) => compareText(surfaceKey(left), surfaceKey(right)));
1573
+ const affectedTests = sortedUnique(taskIds.flatMap(
1574
+ (taskId) => virtualWitness[taskId].affected_tests,
1575
+ ));
1576
+ const limits = spec.surface_hypotheses.length > 0
1577
+ ? ['hypothetical_new_surfaces', 'structural_only']
1578
+ : ['structural_only'];
1579
+ const candidate = {
1580
+ proposal_id: deriveSeamProposalId({
1581
+ conflicts: component.conflicts,
1582
+ proposed_surfaces: proposed,
1583
+ }),
1584
+ current_surfaces: current,
1585
+ proposed_surfaces: proposed,
1586
+ affected_tests: affectedTests,
1587
+ verification: {
1588
+ virtual_compile_input_digest: receipt.verification.virtual_compile_input_digest,
1589
+ virtual_compile_result_digest: receipt.verification.virtual_compile_result_digest,
1590
+ residual_conflicts: [],
1591
+ },
1592
+ evidence: structuredClone(evidence),
1593
+ limits,
1594
+ proposal_digest: '',
1595
+ };
1596
+ candidate.proposal_digest = todoSelfDigest(candidate, 'proposal_digest');
1597
+ const changedSurfaces = new Set(proposed.map(surfaceKey));
1598
+ const blastRadius = new Set([
1599
+ ...proposed.map(({ path }) => `path:${path}`),
1600
+ ...affectedTests.map((path) => `test:${path}`),
1601
+ ]);
1602
+ evaluated.push({
1603
+ spec,
1604
+ derivation,
1605
+ feasible: true,
1606
+ candidate,
1607
+ minimumWaves: Math.ceil(taskIds.length / request.capacity.executors),
1608
+ changedSurfaces,
1609
+ blastRadius,
1610
+ });
1611
+ }
1612
+
1613
+ const feasible = evaluated.filter(({ feasible }) => feasible);
1614
+ const nonDominated = feasible.filter((candidate, index) => (
1615
+ !feasible.some((other, otherIndex) => (
1616
+ index !== otherIndex && candidateDominates(other, candidate)
1617
+ ))
1618
+ ));
1619
+ if (nonDominated.length === 1) {
1620
+ return {
1621
+ component_id: component.component_id,
1622
+ task_ids: taskIds,
1623
+ conflicts: structuredClone(component.conflicts),
1624
+ verdict: 'seam_candidate',
1625
+ seam_candidate: nonDominated[0].candidate,
1626
+ reasons: [{
1627
+ code: 'unique_structural_dominant_candidate',
1628
+ detail: 'One feasible candidate structurally dominates all alternatives.',
1629
+ }],
1630
+ unknowns: [],
1631
+ };
1632
+ }
1633
+ if (nonDominated.length > 1) {
1634
+ return decisionUnknown(component, [{
1635
+ kind: 'multiple_incomparable_candidates',
1636
+ ref: nonDominated.map(({ spec }) => spec.candidate_id).sort(compareText).join(','),
1637
+ }]);
1638
+ }
1639
+
1640
+ const serialKinds = new Set(['state', 'effect']);
1641
+ const unseverable = component.conflicts.filter(({ kind }) => serialKinds.has(kind));
1642
+ const unseverableRemains = unseverable.length > 0
1643
+ && evaluated.length === candidateSpecs.length
1644
+ && evaluated.every(({ derivation }) => unseverable.some((conflict) => (
1645
+ derivation.conflicts.some(({ resource_id: resourceId }) => (
1646
+ resourceId === conflict.resource_id || resourceId === conflict.target
1647
+ ))
1648
+ )));
1649
+ if (explorationComplete && unseverableRemains) {
1650
+ return {
1651
+ component_id: component.component_id,
1652
+ task_ids: taskIds,
1653
+ conflicts: structuredClone(component.conflicts),
1654
+ verdict: 'intentional_serial',
1655
+ seam_candidate: null,
1656
+ reasons: [{
1657
+ code: 'unseverable_state_effect_conflict',
1658
+ detail: 'Complete exploration retained a current-contract state/effect conflict.',
1659
+ }],
1660
+ unknowns: [],
1661
+ };
1662
+ }
1663
+ const unknowns = rejectedUnknowns.length > 0
1664
+ ? rejectedUnknowns
1665
+ : [{ kind: 'candidate_exploration_incomplete', ref: component.component_id }];
1666
+ if (!explorationComplete) {
1667
+ unknowns.push({ kind: 'candidate_exploration_incomplete', ref: component.component_id });
1668
+ }
1669
+ return decisionUnknown(component, unknowns);
1670
+ }
1671
+
1672
+ function extractionPath(rootPath, skeletonId, taskId) {
1673
+ const slash = rootPath.lastIndexOf('/');
1674
+ const directory = slash === -1 ? '' : rootPath.slice(0, slash + 1);
1675
+ const filename = slash === -1 ? rootPath : rootPath.slice(slash + 1);
1676
+ const dot = filename.lastIndexOf('.');
1677
+ const stem = dot <= 0 ? filename : filename.slice(0, dot);
1678
+ const extension = dot <= 0 ? '.mjs' : filename.slice(dot);
1679
+ return `${directory}${stem}.seam-${sha16(`${skeletonId}\0${taskId}`)}${extension}`;
1680
+ }
1681
+
1682
+ function skeletonCandidateSpec({ skeleton, component, request, evidence }) {
1683
+ const taskIds = [...component.task_ids].sort(compareText);
1684
+ if (skeleton.binding_unknowns.length > 0
1685
+ || skeleton.task_bindings.length !== taskIds.length) return null;
1686
+ const current = currentSurfaces(component, evidence);
1687
+ if (current === null) return null;
1688
+ const conflictKeys = new Set(component.conflicts.map(({ kind, target }) => (
1689
+ `${kind}\0${target}`
1690
+ )));
1691
+ const currentPaths = sortedUnique(current.map(({ path }) => path));
1692
+ const ownershipDiff = [];
1693
+ const proposedSurfaces = [];
1694
+ const surfaceHypotheses = [];
1695
+ for (const taskId of taskIds) {
1696
+ const original = request.manual_witness[taskId];
1697
+ const path = extractionPath(skeleton.root_surface.path, skeleton.skeleton_id, taskId);
1698
+ const replacePath = (value) => (
1699
+ currentPaths.some((currentPath) => pathPrefixOverlap(value, currentPath)) ? path : value
1700
+ );
1701
+ const owns = original.owns.filter((own) => (
1702
+ !conflictKeys.has(resourceKey(own))
1703
+ && !(own.kind === 'path' && currentPaths.includes(own.target))
1704
+ ));
1705
+ owns.push({ kind: 'path', target: path });
1706
+ const sensorQueries = original.sensor_provenance.queries.filter(({ expect }) => {
1707
+ if (expect.kind === 'symbol') {
1708
+ return !component.conflicts.some((conflict) => (
1709
+ conflict.kind === 'symbol' && conflict.target === expect.name
1710
+ ));
1711
+ }
1712
+ return !currentPaths.includes(expect.path);
1713
+ });
1714
+ ownershipDiff.push({
1715
+ todo_id: taskId,
1716
+ owns: owns.sort((left, right) => compareText(resourceKey(left), resourceKey(right))),
1717
+ reads: sortedUnique(original.reads.map(replacePath)),
1718
+ writes: sortedUnique([...original.writes.map(replacePath), path]),
1719
+ resources: structuredClone(original.resources),
1720
+ state_effects: structuredClone(original.state_effects),
1721
+ sensor_provenance: { queries: structuredClone(sensorQueries) },
1722
+ affected_tests: structuredClone(original.affected_tests),
1723
+ unknowns: structuredClone(original.unknowns),
1724
+ });
1725
+ proposedSurfaces.push({
1726
+ kind: 'path',
1727
+ target: path,
1728
+ path,
1729
+ role: 'task_owned',
1730
+ owner_task_ids: [taskId],
1731
+ });
1732
+ surfaceHypotheses.push({
1733
+ kind: 'path',
1734
+ target: path,
1735
+ path,
1736
+ owner_task_id: taskId,
1737
+ affected_tests: structuredClone(original.affected_tests),
1738
+ provenance: HYPOTHESIS_PROVENANCE,
1739
+ });
1740
+ }
1741
+ return {
1742
+ candidate_id: skeleton.skeleton_id,
1743
+ ownership_diff: ownershipDiff,
1744
+ proposed_surfaces: proposedSurfaces,
1745
+ surface_hypotheses: surfaceHypotheses,
1746
+ raw_graph: structuredClone(skeleton.raw_graph),
1747
+ };
1748
+ }
1749
+
1750
+ /**
1751
+ * Enumerate, bind, materialize, and validate structural cut skeletons. Callers provide collected
1752
+ * sensor outcomes, never handwritten candidate specs.
1753
+ */
1754
+ export function compileSeamProposalDecision({
1755
+ component,
1756
+ request,
1757
+ sensorEvidence,
1758
+ evidence,
1759
+ rawCollected,
1760
+ concernAnchors = new Map(),
1761
+ concernUnknowns = [],
1762
+ } = {}) {
1763
+ const enumeration = enumerateCutSkeletons({
1764
+ component,
1765
+ request,
1766
+ evidence,
1767
+ rawCollected,
1768
+ concernAnchors,
1769
+ });
1770
+ // 宣言が解決しなかった事実は、束縛が成功したかに関わらず記録から消さない。
1771
+ const unknowns = [...concernUnknowns, ...enumeration.unknowns];
1772
+ if (unknowns.length > 0) {
1773
+ return decisionUnknown(component, unknowns);
1774
+ }
1775
+ const candidateSpecs = enumeration.skeletons.map((skeleton) => (
1776
+ skeletonCandidateSpec({ skeleton, component, request, evidence })
1777
+ ));
1778
+ if (candidateSpecs.some((spec) => spec === null)) {
1779
+ return decisionUnknown(component, [{
1780
+ kind: 'new_surface_assumption_missing',
1781
+ ref: component.component_id,
1782
+ }]);
1783
+ }
1784
+ return evaluateSeamProposalCandidates({
1785
+ component,
1786
+ request,
1787
+ sensorEvidence,
1788
+ evidence,
1789
+ candidateSpecs,
1790
+ explorationComplete: enumeration.exploration_complete,
1791
+ concernAnchors,
1792
+ });
1793
+ }
1794
+
1795
+ export class SeamProposalCompileError extends Error {
1796
+ constructor(code, reason, detail = {}) {
1797
+ super(reason);
1798
+ this.name = 'SeamProposalCompileError';
1799
+ this.code = code;
1800
+ this.detail = { reason, ...detail };
1801
+ }
1802
+ }
1803
+
1804
+ function compileFail(code, reason, detail) {
1805
+ throw new SeamProposalCompileError(code, reason, detail);
1806
+ }
1807
+
1808
+ function conflictComponents(independenceArtifact) {
1809
+ const resourceById = new Map(independenceArtifact.conflict_resources.map((resource) => (
1810
+ [resource.resource_id, resource]
1811
+ )));
1812
+ const parent = new Map();
1813
+ const find = (taskId) => {
1814
+ const current = parent.get(taskId) ?? taskId;
1815
+ if (!parent.has(taskId)) parent.set(taskId, taskId);
1816
+ if (current === taskId) return taskId;
1817
+ const root = find(current);
1818
+ parent.set(taskId, root);
1819
+ return root;
1820
+ };
1821
+ const union = (left, right) => {
1822
+ const leftRoot = find(left);
1823
+ const rightRoot = find(right);
1824
+ if (leftRoot === rightRoot) return;
1825
+ if (compareText(leftRoot, rightRoot) < 0) parent.set(rightRoot, leftRoot);
1826
+ else parent.set(leftRoot, rightRoot);
1827
+ };
1828
+
1829
+ for (const { task_ids: [left, right] } of independenceArtifact.conflicts) {
1830
+ union(left, right);
1831
+ }
1832
+
1833
+ const conflictsByRoot = new Map();
1834
+ for (const conflict of independenceArtifact.conflicts) {
1835
+ const root = find(conflict.task_ids[0]);
1836
+ const entries = conflictsByRoot.get(root) ?? [];
1837
+ entries.push(conflict);
1838
+ conflictsByRoot.set(root, entries);
1839
+ }
1840
+
1841
+ const components = [];
1842
+ const classifiedPairKeys = new Set();
1843
+ const classifiedResourceIds = new Set();
1844
+ for (const entries of conflictsByRoot.values()) {
1845
+ const taskIds = sortedUnique(entries.flatMap(({ task_ids: taskPair }) => taskPair));
1846
+ const pairsByResource = new Map();
1847
+ for (const entry of entries) {
1848
+ const pairs = pairsByResource.get(entry.resource_id) ?? [];
1849
+ pairs.push([...entry.task_ids]);
1850
+ pairsByResource.set(entry.resource_id, pairs);
1851
+ classifiedPairKeys.add(`${entry.task_ids[0]}\0${entry.task_ids[1]}\0${entry.resource_id}`);
1852
+ }
1853
+ const conflicts = [...pairsByResource].map(([resourceId, pairs]) => {
1854
+ const resource = resourceById.get(resourceId);
1855
+ if (resource === undefined) {
1856
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_resource_missing', {
1857
+ resource_id: resourceId,
1858
+ });
1859
+ }
1860
+ if (classifiedResourceIds.has(resourceId)) {
1861
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_resource_classified_twice', {
1862
+ resource_id: resourceId,
1863
+ });
1864
+ }
1865
+ classifiedResourceIds.add(resourceId);
1866
+ return {
1867
+ ...structuredClone(resource),
1868
+ task_pairs: pairs.sort((left, right) => compareText(
1869
+ `${left[0]}\0${left[1]}`, `${right[0]}\0${right[1]}`,
1870
+ )),
1871
+ };
1872
+ }).sort((left, right) => compareText(left.resource_id, right.resource_id));
1873
+ const identity = { task_ids: taskIds, conflicts };
1874
+ components.push({
1875
+ component_id: `component-${digestTodoArtifact(identity).slice(0, 24)}`,
1876
+ ...identity,
1877
+ });
1878
+ }
1879
+
1880
+ const expectedPairKeys = new Set(independenceArtifact.conflicts.map((entry) => (
1881
+ `${entry.task_ids[0]}\0${entry.task_ids[1]}\0${entry.resource_id}`
1882
+ )));
1883
+ if (classifiedPairKeys.size !== expectedPairKeys.size
1884
+ || [...expectedPairKeys].some((key) => !classifiedPairKeys.has(key))
1885
+ || classifiedResourceIds.size !== independenceArtifact.conflict_resources.length) {
1886
+ compileFail('SEAM_PROPOSAL_COMPONENT_INVALID', 'conflict_component_partition_incomplete', {
1887
+ expected_pair_count: expectedPairKeys.size,
1888
+ classified_pair_count: classifiedPairKeys.size,
1889
+ expected_resource_count: independenceArtifact.conflict_resources.length,
1890
+ classified_resource_count: classifiedResourceIds.size,
1891
+ });
1892
+ }
1893
+ return components.sort((left, right) => compareText(left.component_id, right.component_id));
1894
+ }
1895
+
1896
+ /**
1897
+ * Build the immutable lattice.seam_proposal.v1 artifact from one complete independence record.
1898
+ * Sensor collection stays outside this producer; callers pass the original witness evidence and
1899
+ * the seam-specific normalized/raw evidence collected for the same clean HEAD.
1900
+ */
1901
+ export function compileSeamProposalArtifact({
1902
+ independenceArtifact,
1903
+ witnessSet,
1904
+ plan,
1905
+ compiledAt,
1906
+ sensorEvidence,
1907
+ evidence,
1908
+ rawCollected,
1909
+ } = {}) {
1910
+ if (!validateTodoIndependence(independenceArtifact)) {
1911
+ compileFail('SEAM_PROPOSAL_INDEPENDENCE_INVALID', 'independence_artifact_invalid');
1912
+ }
1913
+ if (independenceArtifact.outcome !== 'compiled') {
1914
+ compileFail('SEAM_PROPOSAL_INDEPENDENCE_UNAVAILABLE', 'independence_outcome_not_compiled', {
1915
+ outcome: independenceArtifact.outcome,
1916
+ });
1917
+ }
1918
+ if (!validateTodoWitnessSet(witnessSet)) {
1919
+ compileFail('SEAM_PROPOSAL_WITNESS_INVALID', 'witness_set_invalid');
1920
+ }
1921
+ if (!validateTodoPlan(plan)) {
1922
+ compileFail('SEAM_PROPOSAL_PLAN_INVALID', 'plan_invalid');
1923
+ }
1924
+ if (independenceArtifact.project_id !== plan.project_id
1925
+ || independenceArtifact.plan_key !== plan.plan_key
1926
+ || independenceArtifact.plan_version !== plan.plan_version
1927
+ || independenceArtifact.topology_digest !== plan.topology_digest) {
1928
+ compileFail('SEAM_PROPOSAL_BINDING_MISMATCH', 'independence_plan_mismatch');
1929
+ }
1930
+ if (witnessSet.project_id !== plan.project_id
1931
+ || witnessSet.plan_key !== plan.plan_key
1932
+ || witnessSet.witness_set_digest !== independenceArtifact.witness_set_digest) {
1933
+ compileFail('SEAM_PROPOSAL_BINDING_MISMATCH', 'witness_independence_mismatch');
1934
+ }
1935
+
1936
+ const request = synthesizeWitnessRunRequest(witnessSet, {
1937
+ baseSha: independenceArtifact.base_sha,
1938
+ requestId: `seam-proposal-${independenceArtifact.result_digest.slice(0, 24)}`,
1939
+ });
1940
+ const components = conflictComponents(independenceArtifact);
1941
+ const concern = resolveConcernAnchors({
1942
+ manualWitness: witnessSet.manual_witness,
1943
+ taskIds: [...new Set(components.flatMap(({ task_ids: ids }) => ids))].sort(compareText),
1944
+ evidence,
1945
+ });
1946
+ const decisions = components.map((component) => (
1947
+ compileSeamProposalDecision({
1948
+ component,
1949
+ request,
1950
+ sensorEvidence,
1951
+ evidence,
1952
+ rawCollected,
1953
+ concernAnchors: concern.anchorsByTask,
1954
+ // このcomponentのtaskに関する解決失敗だけを持ち込む。
1955
+ concernUnknowns: concern.unknowns.filter((unknown) => (
1956
+ component.task_ids.some((taskId) => unknown.ref.startsWith(`${taskId}:`)
1957
+ || unknown.ref.split(':')[0].split(',').includes(taskId))
1958
+ )),
1959
+ })
1960
+ )).sort((left, right) => compareText(left.component_id, right.component_id));
1961
+ const artifact = {
1962
+ schema: SEAM_PROPOSAL_SCHEMA,
1963
+ project_id: plan.project_id,
1964
+ plan_key: plan.plan_key,
1965
+ source_binding: {
1966
+ independence_schema: independenceArtifact.schema,
1967
+ independence_result_digest: independenceArtifact.result_digest,
1968
+ witness_set_digest: independenceArtifact.witness_set_digest,
1969
+ plan_version: independenceArtifact.plan_version,
1970
+ topology_digest: independenceArtifact.topology_digest,
1971
+ base_sha: independenceArtifact.base_sha,
1972
+ },
1973
+ compiled_at: compiledAt,
1974
+ decisions,
1975
+ result_digest: '',
1976
+ };
1977
+ artifact.result_digest = todoSelfDigest(artifact, 'result_digest');
1978
+ if (!validateSeamProposal(artifact)) {
1979
+ compileFail('SEAM_PROPOSAL_ARTIFACT_INVALID', 'seam_proposal_artifact_invalid');
1980
+ }
1981
+ return artifact;
1982
+ }