@quolu/lattice 0.31.0 → 0.33.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.
Files changed (58) hide show
  1. package/README.ja.md +11 -1
  2. package/README.md +11 -2
  3. package/bin/lattice-scripted-worker.mjs +59 -0
  4. package/bin/lattice.mjs +12 -1
  5. package/package.json +1 -1
  6. package/sensor/dist/bin/lattice-sensor.js +72 -4
  7. package/sensor/dist/db/migrations.d.ts +1 -1
  8. package/sensor/dist/db/migrations.d.ts.map +1 -1
  9. package/sensor/dist/db/migrations.js +32 -2
  10. package/sensor/dist/db/migrations.js.map +1 -1
  11. package/sensor/dist/db/queries.d.ts +10 -0
  12. package/sensor/dist/db/queries.d.ts.map +1 -1
  13. package/sensor/dist/db/queries.js +53 -7
  14. package/sensor/dist/db/queries.js.map +1 -1
  15. package/sensor/dist/db/schema.sql +6 -1
  16. package/sensor/dist/extraction/tree-sitter.d.ts.map +1 -1
  17. package/sensor/dist/extraction/tree-sitter.js +89 -16
  18. package/sensor/dist/extraction/tree-sitter.js.map +1 -1
  19. package/sensor/dist/index.d.ts +8 -1
  20. package/sensor/dist/index.d.ts.map +1 -1
  21. package/sensor/dist/index.js +9 -0
  22. package/sensor/dist/index.js.map +1 -1
  23. package/sensor/dist/resolution/import-resolver.d.ts +11 -0
  24. package/sensor/dist/resolution/import-resolver.d.ts.map +1 -1
  25. package/sensor/dist/resolution/import-resolver.js +13 -5
  26. package/sensor/dist/resolution/import-resolver.js.map +1 -1
  27. package/sensor/dist/resolution/index.d.ts.map +1 -1
  28. package/sensor/dist/resolution/index.js +11 -0
  29. package/sensor/dist/resolution/index.js.map +1 -1
  30. package/sensor/dist/resolution/types.d.ts +4 -0
  31. package/sensor/dist/resolution/types.d.ts.map +1 -1
  32. package/sensor/dist/types.d.ts +16 -0
  33. package/sensor/dist/types.d.ts.map +1 -1
  34. package/src/artifact-contracts.mjs +3 -0
  35. package/src/cli-help.mjs +6 -0
  36. package/src/rc3-scripted-campaign.mjs +3 -1
  37. package/src/runtime-cli.mjs +454 -97
  38. package/src/runtime-contracts.mjs +1 -1
  39. package/src/runtime-control-store.mjs +24 -1
  40. package/src/runtime-controller-protocol.mjs +21 -3
  41. package/src/runtime-decision-verifier.mjs +1 -1
  42. package/src/runtime-diff-observer.mjs +2 -2
  43. package/src/runtime-front-end.mjs +47 -13
  44. package/src/runtime-hold-recompile.mjs +31 -2
  45. package/src/runtime-io-sentinel.mjs +16 -9
  46. package/src/runtime-managed-supervisor.mjs +9 -1
  47. package/src/runtime-multi-epoch-store.mjs +2 -2
  48. package/src/runtime-projection.mjs +27 -0
  49. package/src/runtime-scripted-adapter-controller.mjs +139 -25
  50. package/src/runtime-seam-resolve.mjs +156 -13
  51. package/src/runtime-seam-treatment.mjs +2 -1
  52. package/src/seam-apply.mjs +101 -4
  53. package/src/seam-cost.mjs +322 -0
  54. package/src/seam-gate.mjs +146 -0
  55. package/src/seam-rewrite.mjs +102 -16
  56. package/src/seam-verification.mjs +26 -3
  57. package/src/sensor-adapter.mjs +6 -1
  58. package/src/todo-cli.mjs +55 -0
@@ -1,6 +1,6 @@
1
1
  import net from 'node:net';
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
- import { execFile } from 'node:child_process';
3
+ import { execFile, spawn } from 'node:child_process';
4
4
  import { constants as fsConstants, readFileSync } from 'node:fs';
5
5
  import {
6
6
  chmod,
@@ -13,6 +13,7 @@ import {
13
13
  rm,
14
14
  } from 'node:fs/promises';
15
15
  import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
16
17
  import { promisify } from 'node:util';
17
18
 
18
19
  import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
@@ -29,6 +30,7 @@ import {
29
30
  validateExecutorPacket,
30
31
  validateExecutorReceipt,
31
32
  } from './runtime-contracts.mjs';
33
+ import { captureWorktreeDiff } from './runtime-diff-observer.mjs';
32
34
  import { validateSupervisorWriteGate } from './runtime-gate-store.mjs';
33
35
  import { observeManagedProcessStartIdentity } from './runtime-managed-supervisor.mjs';
34
36
  import { scriptedWorktreeId, scriptedWorktreePath } from './runtime-scripted-worktree.mjs';
@@ -251,7 +253,13 @@ function deterministicWriteBytes(packet, relativePath) {
251
253
  })}\n`);
252
254
  }
253
255
 
254
- async function executePacket({ packet, repoRoot, extraWrites = [] }) {
256
+ /**
257
+ * packetの宣言writeを実行する。**worker processから呼ばれる。**
258
+ *
259
+ * controllerと同じprocessで走らせていた頃、このrunには走行中のTODOが存在せず、
260
+ * 実行時の観測も静止の証明も原理的に成立しなかった(ADR 0143 Decision 7・9)。
261
+ */
262
+ export async function executePacket({ packet, repoRoot, extraWrites = [] }) {
255
263
  const writes = packet.scope?.writes;
256
264
  if (!Array.isArray(writes) || writes.length === 0
257
265
  || writes.some((entry, index) => !safeWritePath(entry)
@@ -382,6 +390,62 @@ async function readScriptedBehavior(repoRoot) {
382
390
  return { hold_ms: holdMs, extra_writes: [...extraWrites] };
383
391
  }
384
392
 
393
+ const WORKER_ENTRYPOINT = fileURLToPath(new URL('../bin/lattice-scripted-worker.mjs', import.meta.url));
394
+
395
+ /**
396
+ * worker processを起こす(ADR 0143 Decision 9)。
397
+ *
398
+ * `detached`で独立process groupへ置く。controllerと同じgroupに居ると、直接OS観測が
399
+ * 「未記録process group memberを検出」として落とす——正しく落ちるので、ここを外さない。
400
+ *
401
+ * 起動直後にprocess start identityを観測して束ねる。pidは再利用されうるので、
402
+ * pidだけでは「同じprocessか」を後から言えない。
403
+ */
404
+ async function spawnScriptedWorker({ packet, worktreePath, extraWrites, holdMs,
405
+ controllerId, runDir }) {
406
+ const job = {
407
+ schema: 'lattice.scripted_worker_job.v1',
408
+ packet: structuredClone(packet),
409
+ worktree_path: worktreePath,
410
+ extra_writes: [...extraWrites],
411
+ hold_ms: holdMs,
412
+ };
413
+ const jobPath = path.join(runDir, 'controllers', controllerId, 'jobs',
414
+ `${packet.packet_digest}.json`);
415
+ await durableReplaceBytes(jobPath, Buffer.from(`${canonicalizeArtifact(job)}\n`));
416
+ const child = spawn(process.execPath, [WORKER_ENTRYPOINT, jobPath], {
417
+ detached: true, stdio: ['ignore', 'pipe', 'pipe'], cwd: worktreePath,
418
+ });
419
+ if (!Number.isSafeInteger(child.pid)) {
420
+ fail('SCRIPTED_EXECUTION_FAILED', 'worker processを起こせない');
421
+ }
422
+ const identity = await observeManagedProcessStartIdentity(child.pid);
423
+ let stdout = '';
424
+ let stderr = '';
425
+ child.stdout.on('data', (chunk) => { stdout += chunk.toString('utf8'); });
426
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8'); });
427
+ const completed = new Promise((resolve, reject) => {
428
+ child.once('error', reject);
429
+ child.once('close', (code, signal) => {
430
+ const line = stdout.split('\n').find((entry) => entry.includes('scripted_worker_result'));
431
+ let parsed = null;
432
+ try { parsed = line === undefined ? null : JSON.parse(line); } catch { parsed = null; }
433
+ if (parsed?.schema !== 'lattice.scripted_worker_result.v1') {
434
+ reject(new TypeError(`worker結果を読めない (${signal ?? code}): ${stderr.trim() || '(出力なし)'}`));
435
+ return;
436
+ }
437
+ resolve({ observedDiff: parsed.observed_diff, checkpointDigest: parsed.checkpoint_digest });
438
+ });
439
+ });
440
+ return {
441
+ pid: child.pid,
442
+ process_group_id: child.pid,
443
+ process_start_identity: identity,
444
+ child,
445
+ completed,
446
+ };
447
+ }
448
+
385
449
  export async function createScriptedAdapterController({
386
450
  bootstrap,
387
451
  runDir,
@@ -446,6 +510,28 @@ export async function createScriptedAdapterController({
446
510
  let currentEpoch = 1;
447
511
  let registrationDigest = null;
448
512
 
513
+ /** dispatch応答が運ぶworker process。誰を止めればよいかをsupervisorへ名指しする。 */
514
+ /**
515
+ * 起こしたworker processを畳む。
516
+ *
517
+ * **SIGKILLでなければ届かない。** barrierで止めたworkerはSIGSTOP状態にあり、
518
+ * SIGTERMは継続されるまで配送されない。放置すると、runもcontrollerもrepoも消えた後まで
519
+ * 停止したままのprocessが残り続ける(自分では終われない)。
520
+ */
521
+ const reapWorkers = () => {
522
+ for (const task of tasks.values()) {
523
+ const pid = task.worker?.pid;
524
+ if (!Number.isSafeInteger(pid)) continue;
525
+ try { process.kill(pid, 'SIGKILL'); } catch { /* 既に終わっている */ }
526
+ }
527
+ };
528
+
529
+ const workerProcessOf = (task) => ({
530
+ pid: task.worker.pid,
531
+ process_group_id: task.worker.process_group_id,
532
+ process_start_identity: structuredClone(task.worker.process_start_identity),
533
+ });
534
+
449
535
  const persistReceipt = async (receipt) => {
450
536
  const payloadDigest = digestArtifact(receipt);
451
537
  const receiptPath = path.join(
@@ -594,12 +680,13 @@ export async function createScriptedAdapterController({
594
680
  fail('SCRIPTED_DUPLICATE_DISPATCH', '同じTODOへ異なるpacketをdispatchできない');
595
681
  }
596
682
  return sign({
597
- schema: 'lattice.adapter_dispatch_response.v1',
683
+ schema: 'lattice.adapter_dispatch_response.v2',
598
684
  request_id: request.request_id,
599
685
  executor_handle: prior.executorHandle,
600
686
  worktree_id: prior.worktreeId,
601
687
  packet_digest: packet.packet_digest,
602
688
  lease_digest: writeLease.lease_digest,
689
+ worker_process: workerProcessOf(prior),
603
690
  response_digest: '',
604
691
  }, 'response_digest');
605
692
  }
@@ -629,29 +716,33 @@ export async function createScriptedAdapterController({
629
716
  worktree_id: worktreeId,
630
717
  state: 'running',
631
718
  };
719
+ const worktreeReal = await realpath(worktreePath);
720
+ // **workerは別processで起こす。** controller自身のprocessで作業すると、holdが
721
+ // 要求する静止を証明できない——止めれば応答できず、止めなければ証明できない。
722
+ // `detached`で独立process groupへ置く。同じgroupにcontrollerが居ると、直接OS観測が
723
+ // 「未記録process group memberを検出」として正しく落とす。
724
+ const spawned = await spawnScriptedWorker({
725
+ packet, worktreePath: worktreeReal, extraWrites: behavior.extra_writes,
726
+ holdMs: behavior.hold_ms, controllerId, runDir: canonicalRunDir,
727
+ });
632
728
  const task = {
633
729
  packet: structuredClone(packet),
634
730
  lease: structuredClone(writeLease),
635
731
  executorHandle,
636
732
  worktreeId,
733
+ worktreePath: worktreeReal,
637
734
  receipt: null,
638
735
  payloadDigest: digestArtifact(progress),
639
736
  state: 'running',
640
737
  failure: null,
641
738
  settled: null,
739
+ worker: spawned,
642
740
  };
643
741
  tasks.set(executorHandle, task);
644
742
  todoToHandle.set(packet.todo_id, executorHandle);
645
- const worktreeReal = await realpath(worktreePath);
646
743
  task.settled = (async () => {
647
744
  try {
648
- const { observedDiff, checkpointDigest } = await executePacket({
649
- packet, repoRoot: worktreeReal, extraWrites: behavior.extra_writes,
650
- });
651
- // 書いた後も走り続ける。これが実行時観測の窓であり、0ならば窓は存在しない。
652
- if (behavior.hold_ms > 0) {
653
- await new Promise((resolve) => { setTimeout(resolve, behavior.hold_ms); });
654
- }
745
+ const { observedDiff, checkpointDigest } = await spawned.completed;
655
746
  const receipt = sign({
656
747
  schema: 'lattice.executor_receipt.v1',
657
748
  receipt_id: `receipt-${packet.packet_digest.slice(0, 24)}`,
@@ -677,12 +768,13 @@ export async function createScriptedAdapterController({
677
768
  }
678
769
  })();
679
770
  return sign({
680
- schema: 'lattice.adapter_dispatch_response.v1',
771
+ schema: 'lattice.adapter_dispatch_response.v2',
681
772
  request_id: request.request_id,
682
773
  executor_handle: executorHandle,
683
774
  worktree_id: worktreeId,
684
775
  packet_digest: packet.packet_digest,
685
776
  lease_digest: writeLease.lease_digest,
777
+ worker_process: workerProcessOf(task),
686
778
  response_digest: '',
687
779
  }, 'response_digest');
688
780
  }
@@ -742,24 +834,40 @@ export async function createScriptedAdapterController({
742
834
  if (task === undefined || task.packet.todo_id !== binding.todo_id) {
743
835
  fail('SCRIPTED_BARRIER_REJECTED', 'barrierが未知のrunning bindingを含む');
744
836
  }
745
- // barrierは静止の宣言である。走行中の作業を残したままackを返すと、
746
- // 「止まった」と言いながらworktreeが動き続ける。settleを待ってから答える。
747
- if (task.settled !== null) await task.settled;
748
- if (task.failure !== null) {
749
- fail('SCRIPTED_BARRIER_REJECTED', 'barrier対象のworker実行が失敗している', {
750
- reason: task.failure,
837
+ // **barrierは静止の宣言である。** worker processを実際に止め、止まった木を読む。
838
+ // 走行中の作業を残したままackを返すと、「止まった」と言いながらworktreeが動き続ける。
839
+ try {
840
+ process.kill(task.worker.pid, 'SIGSTOP');
841
+ } catch (error) {
842
+ fail('SCRIPTED_BARRIER_REJECTED', 'worker processを止められない', {
843
+ pid: task.worker.pid, reason: String(error?.code ?? error?.message ?? error),
751
844
  });
752
845
  }
753
846
  task.state = 'held';
847
+ // supervisorも同じ観測を独立に行い、3つのdigestの一致を要求する。**こちらが別の形で
848
+ // 作ると、両者が別のものを見ていても気づけない。** 形はdirect OS observerの契約に
849
+ // 揃え、入力(自分のprocess・自分の木)だけを独立に観測する。
850
+ const checkpoint = await captureWorktreeDiff({
851
+ worktreePath: task.worktreePath, baseSha: task.packet.base_sha,
852
+ });
754
853
  const processObservationDigest = digestArtifact({
755
- schema: 'lattice.scripted_process_observation.v1',
756
- executor_handle: task.executorHandle,
757
- state: 'stopped',
854
+ schema: 'lattice.direct_process_observation.v2',
855
+ root: {
856
+ pid: task.worker.pid,
857
+ parent_pid: process.pid,
858
+ process_start_identity_digest: task.worker.process_start_identity.identity_digest,
859
+ process_group_id: task.worker.process_group_id,
860
+ state: 'stopped',
861
+ },
862
+ children: [],
863
+ process_group_id: task.worker.process_group_id,
864
+ quiesced: true,
758
865
  });
759
866
  const worktreeFingerprintDigest = digestArtifact({
760
- schema: 'lattice.scripted_worktree_fingerprint.v1',
867
+ schema: 'lattice.direct_worktree_fingerprint.v1',
761
868
  worktree_id: task.worktreeId,
762
- checkpoint_digest: task.receipt.checkpoint_digest,
869
+ worktree_realpath: task.worktreePath,
870
+ checkpoint_digest: checkpoint.checkpoint_digest,
763
871
  });
764
872
  acks.push(sign({
765
873
  schema: 'lattice.executor_quiescence_ack.v1',
@@ -772,7 +880,7 @@ export async function createScriptedAdapterController({
772
880
  packet_digest: binding.packet_digest,
773
881
  write_lease_id: binding.write_lease_id,
774
882
  barrier_control_digest: request.barrier_control_digest,
775
- final_checkpoint_digest: task.receipt.checkpoint_digest,
883
+ final_checkpoint_digest: checkpoint.checkpoint_digest,
776
884
  process_observation_digest: processObservationDigest,
777
885
  worktree_fingerprint_digest: worktreeFingerprintDigest,
778
886
  supervisor_session_nonce_digest: sessionNonceDigest,
@@ -811,7 +919,9 @@ export async function createScriptedAdapterController({
811
919
  worktree_id: rebind.worktree_id,
812
920
  predecessor_epoch: rebind.new_plan_epoch - 1,
813
921
  successor_epoch: rebind.new_plan_epoch,
814
- predecessor_packet_digest: task.receipt.packet_digest,
922
+ // **holdされたworkerにreceiptは無い。** 作業を終えていないから止められているので、
923
+ // 完了の記録を前提にできない。前任packetのdigestはdispatch時のpacketが持っている。
924
+ predecessor_packet_digest: task.packet.packet_digest,
815
925
  rebind_packet_digest: rebind.packet_digest,
816
926
  new_write_lease_id: staged.lease_id,
817
927
  supervisor_session_nonce_digest: sessionNonceDigest,
@@ -854,6 +964,7 @@ export async function createScriptedAdapterController({
854
964
  controllerSessionNonce,
855
965
  descriptor: structuredClone(descriptor),
856
966
  heartbeat,
967
+ reapWorkers,
857
968
  leaseSetDigest() {
858
969
  return digestArtifact([...stagedLeases.keys(), ...armedLeases.keys()].sort());
859
970
  },
@@ -1009,6 +1120,9 @@ export async function runScriptedAdapterController({
1009
1120
  const close = async () => {
1010
1121
  if (closed) return;
1011
1122
  closed = true;
1123
+ // 起こしたworkerを道連れにする。停止中のworkerは自分では終われないので、
1124
+ // ここで畳まないとrunもrepoも消えた後まで残り続ける。
1125
+ controller.reapWorkers();
1012
1126
  clearInterval(heartbeatTimer);
1013
1127
  persistentSocket?.destroy();
1014
1128
  await new Promise((resolve) => server.close(resolve));
@@ -19,11 +19,16 @@ import { digestArtifact } from './artifact-contracts.mjs';
19
19
  import { commitSeamTransform } from './seam-commit.mjs';
20
20
  import { applySeamConflict } from './seam-apply.mjs';
21
21
  import { resolveRuntimeSeamTreatment } from './runtime-seam-treatment.mjs';
22
+ import { affectedTestsFromEvidence } from './runtime-front-end.mjs';
23
+ import { explainSeamGate } from './seam-gate.mjs';
22
24
  import { collectWitnessSensorEvidence, compileTodoIndependence } from './todo-independence.mjs';
23
25
  import { todoSelfDigest } from './todo-contracts.mjs';
24
26
 
25
27
  export const RUNTIME_SEAM_REQUEST_SCHEMA = 'lattice.runtime_seam_request.v1';
26
- export const RUNTIME_SEAM_RESOLUTION_SCHEMA = 'lattice.runtime_seam_resolution.v1';
28
+ // v2は翻訳段(`reconciled`)の追加である。宣言を観測へ合わせてから判定するようになったので、
29
+ // どの宣言の上で五条件を見たかが決着の一部になった。v1の形のまま中身を変えると、記録が何に
30
+ // ついてのものか確定しなくなる。
31
+ export const RUNTIME_SEAM_RESOLUTION_SCHEMA = 'lattice.runtime_seam_resolution.v2';
27
32
 
28
33
  /** 合成するtodo planのkey。実行時planとは別空間なので固定でよい。 */
29
34
  const SYNTHETIC_PLAN_KEY = 'runtime';
@@ -77,21 +82,130 @@ export function validateRuntimeSeamRequest(value) {
77
82
  return value.request_digest === todoSelfDigest(value, 'request_digest');
78
83
  }
79
84
 
85
+ /**
86
+ * 観測された実態へ宣言を合わせる(翻訳段)。
87
+ *
88
+ * 実行時のpath競合は、**片方がその資源を所有していないから起きる**。所有していない資源の内側に
89
+ * 担当は主張できない(`concern_anchor_resource_not_owned`)ので、宣言のままでは変換の入力が
90
+ * 組めない——請求項8は、実行時に見つかった競合の形をそのままでは受け取れなかった。
91
+ *
92
+ * 境界は計画時の**予測**であって、workerを閉じ込める制約ではない。予測を超えたのは予測が狭かった
93
+ * からであり、作業が不正だったからではない。したがって操作は「破った側を直す」ではなく、観測が
94
+ * 示した実態へ宣言を合わせることであり、**対称**である——どちらの足跡が予測を超えたかは観測が
95
+ * 決めるので、ここでは関与TODOを同じ規則で扱う。
96
+ *
97
+ * これは3つ目の処置ではない。翻訳を通ると計画時競合の形(`owns`の交差)になり、そこから先は
98
+ * 既存の請求項7/8がそのまま適用できる。競合辺が立つのは翻訳の副産物ではなく目的である——
99
+ * 立たないままだと`overlap_reduced`が最初から満たされたことになり、変換の検証が無意味になる。
100
+ *
101
+ * 広げるのは観測が示した資源だけとする。findingが持つ係争pathも関与TODOも観測であって推定では
102
+ * ない。広げた事実は呼び出し側へ返す。黙って広げると、予測が外れたことも、判定がどの宣言の上で
103
+ * 行われたかも残らない。
104
+ *
105
+ * **所有の宣言は裏取りと対で広げる。** `owns`だけ足すとその資源は`sensor_unbound`になり、compileは
106
+ * 非dispatchable(`BOUNDARY_UNKNOWN`)へ落ちる。そこでは競合が投影されないので、翻訳したのに
107
+ * 競合辺が立たず、変換の便益が測れない。裏取りに使えるqueryがrun のquery setに無ければ、
108
+ * 広げずに理由を返す——証明できない宣言を作らない。
109
+ */
110
+ export function reconcileWitnessToObservation({
111
+ manualWitness, contestedPath, todoIds, sensorQuerySet = null, observedAffectedTests = null,
112
+ } = {}) {
113
+ const reconciled = {};
114
+ const widened = [];
115
+ const reject = (reason) => ({ manualWitness: null, widened: [], reasons: [reason] });
116
+ // 係争pathを覆えるqueryを、run のquery setから拾う。無ければ翻訳しない。
117
+ //
118
+ // `affected`だけを見る。path所有を裏取りするのはこのoperationであり、構造query(query/callers/
119
+ // callees/impact)はsymbolを的にする。構造queryがたまたま同じ文字列をtargetに持つからといって
120
+ // 所有の裏取りへ流用すると、束縛の意味が変わる。
121
+ const covering = (sensorQuerySet?.queries ?? [])
122
+ .filter((query) => query.operation === 'affected' && query.target === contestedPath)
123
+ .map((query) => query.id)
124
+ .sort(compareText);
125
+
126
+ for (const todoId of todoIds) {
127
+ const witness = manualWitness?.[todoId];
128
+ if (!plainObject(witness)) return reject(`witness_absent:${todoId}`);
129
+ const next = structuredClone(witness);
130
+ const ownsPath = (next.owns ?? [])
131
+ .some((own) => own.kind === 'path' && own.target === contestedPath);
132
+ const writesPath = (next.writes ?? []).includes(contestedPath);
133
+ const boundPath = (next.sensor_provenance?.queries ?? [])
134
+ .some((entry) => (entry.expect?.kind === 'affected' || entry.expect?.kind === 'path')
135
+ && entry.expect?.path === contestedPath);
136
+ // 既に所有と書き込みを宣言しているなら、観測は予測の内側にある。合わせるものが無いので
137
+ // 触らない——裏取りが足りているかどうかは、その宣言を書いた側の問題であり、compileが見る。
138
+ // 翻訳が手を入れてよいのは、観測が予測を超えた分だけである。
139
+ if (ownsPath && writesPath) {
140
+ reconciled[todoId] = next;
141
+ continue;
142
+ }
143
+ if (!boundPath) {
144
+ if (covering.length === 0) return reject(`observation_unbacked:${todoId}:${contestedPath}`);
145
+ // 同じ資源は同じqueryで裏取りする。TODOごとに別のqueryを選ぶと、front-endが被覆の
146
+ // 曖昧さとして弾く。
147
+ if (covering.length > 1) return reject(`observation_binding_ambiguous:${contestedPath}`);
148
+ // 観測できていないaffectedを推測で埋めない。
149
+ if (!Array.isArray(observedAffectedTests)) {
150
+ return reject(`observation_affected_unread:${contestedPath}`);
151
+ }
152
+ }
153
+ // 所有・書き込み・裏取りをまとめて足す。観測されたのは「このpathへの書き込み」であり、
154
+ // 宣言の一部だけを合わせると、宣言が実態からずれたまま次の判定の前提になる。`creates`は
155
+ // 付けない——観測できたのはpathが既に在るからである。
156
+ if (!ownsPath) next.owns = [...next.owns, { kind: 'path', target: contestedPath }]
157
+ .sort((left, right) => compareText(`${left.kind}\0${left.target}`, `${right.kind}\0${right.target}`));
158
+ if (!writesPath) next.writes = [...next.writes, contestedPath].sort(compareText);
159
+ if (!boundPath) {
160
+ next.sensor_provenance = {
161
+ ...next.sensor_provenance,
162
+ queries: [...next.sensor_provenance.queries,
163
+ { query_id: covering[0], expect: { kind: 'affected', path: contestedPath } }],
164
+ };
165
+ // 面を1つ引き受けたら、その面のaffected testも引き受ける。宣言と観測はTODO単位で
166
+ // exact一致を要求されるので、片方だけ広げるとdriftになる。
167
+ next.affected_tests = [...new Set([...next.affected_tests, ...observedAffectedTests])]
168
+ .sort(compareText);
169
+ }
170
+ reconciled[todoId] = next;
171
+ widened.push({
172
+ todo_id: todoId,
173
+ resource: { kind: 'path', target: contestedPath },
174
+ fields: [
175
+ ...(ownsPath ? [] : ['owns']),
176
+ ...(writesPath ? [] : ['writes']),
177
+ ...(boundPath ? [] : ['affected_tests', 'sensor_provenance']),
178
+ ].sort(compareText),
179
+ });
180
+ }
181
+ return { manualWitness: reconciled, widened, reasons: [] };
182
+ }
183
+
80
184
  /**
81
185
  * 実行時witnessへconcern anchorを足してtodo witness setにする。
82
186
  *
83
187
  * 実行時のmanual_witnessはconcern_anchorsを持たない(`lattice.run_request.v3`)。持たせるのでなく、
84
188
  * 宣言から足す——係争資源の中のどのsymbolを触るかは実行時に確定する情報であり、run開始時点の
85
189
  * 契約に書けるものではないからである。
190
+ *
191
+ * anchorを足す前に宣言を観測へ合わせる(`reconcileWitnessToObservation`)。この順序でないと、
192
+ * 係争資源を所有していないTODOのanchorが必ず不正になる。
86
193
  */
87
- export function buildRuntimeSeamWitnessSet({ request, declaration, contestedPath, executors }) {
194
+ export function buildRuntimeSeamWitnessSet({
195
+ request, declaration, contestedPath, executors, observedAffectedTests = null,
196
+ }) {
88
197
  const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
198
+ const translated = reconcileWitnessToObservation({
199
+ manualWitness: request.manual_witness, contestedPath, todoIds,
200
+ sensorQuerySet: request.sensor_query_set, observedAffectedTests,
201
+ });
202
+ if (translated.manualWitness === null) {
203
+ return { witnessSet: null, widened: [], reasons: translated.reasons };
204
+ }
89
205
  const manual = {};
90
206
  for (const todoId of todoIds) {
91
- const witness = request.manual_witness?.[todoId];
92
- if (!plainObject(witness)) return { witnessSet: null, reasons: [`witness_absent:${todoId}`] };
93
207
  manual[todoId] = {
94
- ...structuredClone(witness),
208
+ ...translated.manualWitness[todoId],
95
209
  concern_anchors: [{
96
210
  within: { kind: 'path', target: contestedPath },
97
211
  symbols: [...declaration.concern_symbols[todoId]].sort(compareText),
@@ -108,7 +222,7 @@ export function buildRuntimeSeamWitnessSet({ request, declaration, contestedPath
108
222
  witness_set_digest: '',
109
223
  };
110
224
  witnessSet.witness_set_digest = todoSelfDigest(witnessSet, 'witness_set_digest');
111
- return { witnessSet, reasons: [] };
225
+ return { witnessSet, widened: translated.widened, reasons: [] };
112
226
  }
113
227
 
114
228
  function syntheticTodoPlan(todoIds) {
@@ -137,7 +251,7 @@ export async function resolveRuntimeSeam({
137
251
  const todoIds = Object.keys(declaration.concern_symbols).sort(compareText);
138
252
 
139
253
  if (finding.kind !== 'observed_write_conflict' || typeof finding.path !== 'string') {
140
- return { lane: 'intentional_serial', reasons: ['finding_not_write_conflict'], split: null };
254
+ return { lane: 'intentional_serial', reasons: ['finding_not_write_conflict'], split: null, widened: [] };
141
255
  }
142
256
  const findingTodoIds = [...finding.todo_ids].sort(compareText);
143
257
  if (findingTodoIds.join('\0') !== todoIds.join('\0')) {
@@ -145,30 +259,41 @@ export async function resolveRuntimeSeam({
145
259
  lane: 'intentional_serial',
146
260
  reasons: ['declared_todos_differ_from_finding'],
147
261
  split: null,
262
+ widened: [],
148
263
  };
149
264
  }
150
265
 
266
+ // sensorは1回だけ引く。翻訳(宣言を観測へ合わせる)とcompileは同じ観測の上で行う——
267
+ // 別々に引くと、翻訳が見た実態とcompileが見た実態がずれうる。
268
+ const sensorEvidence = await collectWitnessSensorEvidence({
269
+ cwd: repoRoot, witnessSet: { sensor_query_set: request.sensor_query_set },
270
+ });
151
271
  const built = buildRuntimeSeamWitnessSet({
152
272
  request, declaration, contestedPath: finding.path,
153
273
  executors: request.capacity.executors,
274
+ observedAffectedTests: affectedTestsFromEvidence({
275
+ sensorEvidence, querySet: request.sensor_query_set, path: finding.path,
276
+ }),
154
277
  });
155
278
  if (built.witnessSet === null) {
156
- return { lane: 'intentional_serial', reasons: built.reasons, split: null };
279
+ return { lane: 'intentional_serial', reasons: built.reasons, split: null, widened: [] };
157
280
  }
158
281
  const witnessSet = built.witnessSet;
159
282
  const plan = syntheticTodoPlan(todoIds);
160
283
 
161
- // 観測したaffected testsだけを検証に使う。宣言から発明しない。
284
+ // 観測したaffected testsだけを検証に使う。宣言から発明しない。翻訳後の宣言から採る——
285
+ // 所有が広がったTODOは、その面のtestも自分のaffectedとして引き受けている。
162
286
  const affectedTests = [...new Set(todoIds
163
- .flatMap((todoId) => request.manual_witness[todoId].affected_tests))].sort(compareText);
287
+ .flatMap((todoId) => witnessSet.manual_witness[todoId].affected_tests))].sort(compareText);
164
288
 
165
289
  const baseArtifact = compileTodoIndependence({
166
- witnessSet, plan, baseSha, compiledAt,
167
- sensorEvidence: await collectWitnessSensorEvidence({ cwd: repoRoot, witnessSet }),
290
+ witnessSet, plan, baseSha, compiledAt, sensorEvidence,
168
291
  });
169
292
 
170
293
  const pathNames = { ...declaration.path_names };
171
- return resolveRuntimeSeamTreatment({
294
+ // 翻訳で広げた宣言は決着へ載せる。どの宣言の上で五条件を判定したかが残らないと、
295
+ // 「変換して通った」という記録が何についてのものか確定しない。
296
+ const resolved = await resolveRuntimeSeamTreatment({
172
297
  finding,
173
298
  witnessSet,
174
299
  pathNames,
@@ -176,6 +301,8 @@ export async function resolveRuntimeSeam({
176
301
  manifestDigest: baseArtifact.result_digest,
177
302
  affectedTests,
178
303
  taskMigrationDigest: declaration.task_migration_digest,
304
+ // storeへ記録されたfindingのidで縛る。再計画側はこのidでfinding recordを読む。
305
+ recordedFindingDigest: findingRecord.finding_digest,
179
306
  commitTransform: async ({ files, candidateId }) => commitSeamTransform({
180
307
  repoRoot, baseSha, files, candidateId,
181
308
  }),
@@ -205,6 +332,7 @@ export async function resolveRuntimeSeam({
205
332
  return { ...applied, candidate: applied.candidate ?? null };
206
333
  },
207
334
  });
335
+ return { ...resolved, widened: built.widened };
208
336
  }
209
337
 
210
338
  /** 決着をartifactにする。branchを動かすのは操作するAIなので、行き先を明示して返す。 */
@@ -215,6 +343,21 @@ export function buildRuntimeSeamResolution({ runId, findingDigest, resolved }) {
215
343
  finding_digest: findingDigest,
216
344
  lane: resolved.lane,
217
345
  reasons: [...resolved.reasons].sort(compareText),
346
+ // 確実の門(sc-012)。拒否理由を「宣言を直せば機械で通る」「AIが変換すべき」へ分類し、
347
+ // 次に誰が動くべきかを事実として返す。可否は決めない。
348
+ gate: explainSeamGate(resolved.reasons ?? []),
349
+ // 判定の前に宣言をどれだけ観測へ合わせたか。空配列は「予測が実態を覆っていた」という
350
+ // 意味であり、翻訳しなかったことと区別できる。
351
+ reconciled: [...(resolved.widened ?? [])]
352
+ .map((entry) => ({
353
+ todo_id: entry.todo_id,
354
+ resource: { kind: entry.resource.kind, target: entry.resource.target },
355
+ fields: [...entry.fields].sort(compareText),
356
+ }))
357
+ .sort((left, right) => compareText(
358
+ `${left.todo_id}\0${left.resource.kind}\0${left.resource.target}`,
359
+ `${right.todo_id}\0${right.resource.kind}\0${right.resource.target}`,
360
+ )),
218
361
  split: resolved.split ?? null,
219
362
  successor_base_sha: resolved.successor_base_sha ?? null,
220
363
  successor_base_ref: resolved.successor_base_ref ?? null,
@@ -99,7 +99,7 @@ export async function resolveRuntimeSeamTreatment(options = {}) {
99
99
  const {
100
100
  finding, witnessSet, pathNames = {}, predeclaredTreatments = [],
101
101
  applyConflict, commitTransform, baseSha, manifestDigest, affectedTests = [],
102
- taskMigrationDigest,
102
+ taskMigrationDigest, recordedFindingDigest = null,
103
103
  } = options;
104
104
 
105
105
  if (finding?.kind === 'observed_write_conflict' && typeof finding.path === 'string') {
@@ -112,6 +112,7 @@ export async function resolveRuntimeSeamTreatment(options = {}) {
112
112
 
113
113
  const { conflict, reasons } = seamConflictFromFinding({
114
114
  finding, witnessSet, pathNames, affectedTests, baseSha, manifestDigest,
115
+ recordedFindingDigest,
115
116
  });
116
117
  if (conflict === null) {
117
118
  return { lane: 'intentional_serial', treatment: null, split: null, reasons };