@quolu/lattice 0.82.0 → 0.84.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 (77) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +1 -1
  3. package/bin/lattice-bridge-supervisor.mjs +10 -0
  4. package/bin/lattice-dashboard.mjs +3 -18
  5. package/bin/lattice-mcp.mjs +6 -3
  6. package/bin/lattice.mjs +30 -23
  7. package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
  8. package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
  9. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
  10. package/package.json +2 -1
  11. package/sensor/dist/db/index.d.ts +1 -0
  12. package/sensor/dist/db/index.d.ts.map +1 -1
  13. package/sensor/dist/db/index.js +13 -0
  14. package/sensor/dist/db/index.js.map +1 -1
  15. package/sensor/dist/index.d.ts.map +1 -1
  16. package/sensor/dist/index.js +12 -2
  17. package/sensor/dist/index.js.map +1 -1
  18. package/sensor/dist/mcp/answer-freshness.js +1 -1
  19. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  20. package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
  21. package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
  22. package/sensor/dist/mcp/daemon-paths.js +7 -1
  23. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  24. package/sensor/dist/mcp/engine.d.ts +11 -0
  25. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  26. package/sensor/dist/mcp/engine.js +83 -4
  27. package/sensor/dist/mcp/engine.js.map +1 -1
  28. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  29. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  30. package/sensor/dist/mcp/index-repair.js +93 -0
  31. package/sensor/dist/mcp/index-repair.js.map +1 -0
  32. package/sensor/dist/mcp/index.d.ts.map +1 -1
  33. package/sensor/dist/mcp/index.js +12 -7
  34. package/sensor/dist/mcp/index.js.map +1 -1
  35. package/sensor/dist/mcp/tools.d.ts +4 -0
  36. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  37. package/sensor/dist/mcp/tools.js +29 -9
  38. package/sensor/dist/mcp/tools.js.map +1 -1
  39. package/src/bridge-hub-server.mjs +46 -9
  40. package/src/cli-help.mjs +10 -8
  41. package/src/cli-refusal-guidance.mjs +354 -0
  42. package/src/dashboard-delivery.mjs +2 -1
  43. package/src/dashboard-lifecycle-journal.mjs +42 -20
  44. package/src/hooks-cli.mjs +30 -6
  45. package/src/plan-backchain.mjs +95 -41
  46. package/src/plan-revise.mjs +274 -72
  47. package/src/project-cli.mjs +301 -163
  48. package/src/project-identity.mjs +14 -0
  49. package/src/runtime-cli.mjs +38 -29
  50. package/src/runtime-control-store.mjs +22 -1
  51. package/src/runtime-decision-verifier.mjs +27 -8
  52. package/src/runtime-engine.mjs +34 -5
  53. package/src/runtime-hold-recompile.mjs +19 -15
  54. package/src/runtime-kept-worktree.mjs +136 -0
  55. package/src/runtime-lifecycle-lock.mjs +118 -30
  56. package/src/runtime-managed-supervisor.mjs +10 -10
  57. package/src/runtime-pull-intake.mjs +90 -44
  58. package/src/store-lock.mjs +142 -57
  59. package/src/todo-authoring-input.mjs +211 -2
  60. package/src/todo-cli.mjs +554 -200
  61. package/src/todo-contracts.mjs +22 -6
  62. package/src/todo-dashboard-registry.mjs +35 -6
  63. package/src/todo-gantt-display.mjs +259 -0
  64. package/src/todo-gantt-html-independence.mjs +10 -3
  65. package/src/todo-gantt-html-shared.mjs +16 -1
  66. package/src/todo-gantt-html.mjs +74 -53
  67. package/src/todo-gantt-layout.mjs +137 -59
  68. package/src/todo-gantt-live.mjs +6 -3
  69. package/src/todo-independence-guidance.mjs +4 -26
  70. package/src/todo-note-store.mjs +6 -3
  71. package/src/todo-readiness.mjs +83 -20
  72. package/src/todo-revision.mjs +156 -8
  73. package/src/todo-split.mjs +6 -3
  74. package/src/todo-status.mjs +141 -54
  75. package/src/todo-store-cache.mjs +1 -1
  76. package/src/todo-store-view.mjs +20 -2
  77. package/src/todo-store.mjs +562 -444
@@ -128,3 +128,17 @@ export async function readProjectExternalPane({ repoRoot, projectId }) {
128
128
  if (document === null || document.external_pane === undefined) return null;
129
129
  return externalPane(document.external_pane);
130
130
  }
131
+
132
+ /**
133
+ * The project id a repository registered in its identity file, or null. A route hint for a
134
+ * serving process that cannot read the Store; the file's own validity is judged elsewhere.
135
+ */
136
+ export async function readRegisteredProjectId({ repoRoot }) {
137
+ try {
138
+ const ref = path.join(await realpath(repoRoot), PROJECT_IDENTITY_REF);
139
+ const stats = await lstat(ref);
140
+ if (!stats.isFile() || stats.isSymbolicLink() || stats.size > MAX_BYTES) return null;
141
+ const id = JSON.parse(await readFile(ref, 'utf8')).project_id;
142
+ return typeof id === 'string' ? id : null;
143
+ } catch { return null; }
144
+ }
@@ -25,6 +25,7 @@ import {
25
25
  buildIoEscalation, createRunSentinel, probeIoWarning, syncSentinelWatches,
26
26
  } from './runtime-io-sentinel.mjs';
27
27
  import { ensureScriptedWorktree, removeScriptedWorktrees } from './runtime-scripted-worktree.mjs';
28
+ import { recoverKeptWorktrees } from './runtime-kept-worktree.mjs';
28
29
  import {
29
30
  buildRuntimeSeamResolution, readRuntimeFindingRecord, resolveRuntimeSeam,
30
31
  validateRuntimeSeamRequest, verifySeamSplitSuccessor,
@@ -52,6 +53,7 @@ import {
52
53
  adjudicatePendingReceipts,
53
54
  buildNextRunEvent,
54
55
  buildExecutorPackets,
56
+ closeRunAbandoningRemaining,
55
57
  closeRunIfComplete,
56
58
  dispatchReadyFrontier,
57
59
  initializeRunEvents,
@@ -805,20 +807,16 @@ async function durableReplaceBytes(directory, name, bytes) {
805
807
  async function withLifecycleLock(runDir, action) {
806
808
  // managed mutationの正本lockはdurable supervisorが所有する。これはunmanaged/launch CLI競合だけを塞ぐ。
807
809
  const lockPath = path.join(runDir, '.cli-lifecycle.lock');
808
- let handle;
809
- try {
810
- handle = await open(lockPath, 'wx', 0o600);
811
- } catch (error) {
812
- if (error?.code === 'EEXIST') {
813
- throw new CliContractError('RUN_BUSY', 'run lifecycle操作が既に進行中');
814
- }
815
- throw error;
816
- }
810
+ const lock = await acquireRuntimeLifecycleLock({
811
+ lockPath,
812
+ sessionNonceDigest: digestArtifact({ run_dir: runDir, lock: '.cli-lifecycle.lock' }),
813
+ operation: 'cli-lifecycle',
814
+ requestId: randomUUID(),
815
+ });
817
816
  try {
818
817
  return await action();
819
818
  } finally {
820
- await handle.close();
821
- await unlink(lockPath).catch(() => {});
819
+ await lock.release();
822
820
  }
823
821
  }
824
822
 
@@ -877,6 +875,7 @@ async function readScriptedControllerReceipt({
877
875
  async function reapRunWorkerProcesses({ events }) {
878
876
  const reaped = [];
879
877
  const skipped = [];
878
+ const unavailable = [];
880
879
  const seen = new Set();
881
880
  for (const event of events) {
882
881
  if (event.kind !== 'executor_dispatched') continue;
@@ -886,14 +885,18 @@ async function reapRunWorkerProcesses({ events }) {
886
885
  if (!Number.isSafeInteger(pid) || typeof recorded !== 'string' || seen.has(pid)) continue;
887
886
  seen.add(pid);
888
887
  const observed = await observeManagedProcessStartIdentity(pid).catch(() => null);
889
- if (observed === null) continue; // 既に居ない
888
+ if (observed === null) {
889
+ // 居ないか、居るのに再認証できない。後者には送らず記録する(u03 C25)。
890
+ try { process.kill(pid, 0); unavailable.push(pid); } catch { /* 既に居ない */ }
891
+ continue;
892
+ }
890
893
  if (observed.identity_digest !== recorded) {
891
894
  skipped.push({ pid, reason: 'start identity不一致(pid再利用)' });
892
895
  continue;
893
896
  }
894
897
  try { process.kill(pid, 'SIGKILL'); reaped.push(pid); } catch { /* 競合で既に消えた */ }
895
898
  }
896
- return { reaped, skipped };
899
+ return { reaped, skipped, unavailable };
897
900
  }
898
901
 
899
902
  async function driveScriptedManagedEpoch({
@@ -1817,20 +1820,15 @@ async function runClose({ runDir, repoRoot, stdout, requestId = null }) {
1817
1820
  if (alreadyClosed && existingClose?.payload?.outcome === 'abandoned') {
1818
1821
  throw new CliContractError('RUN_ABANDONED', 'abandoned runは正常closeへ変更できない');
1819
1822
  }
1823
+ let abandonedTodoIds = [];
1820
1824
  if (!alreadyClosed) {
1821
- const closed = closeRunIfComplete({
1825
+ const closed = closeRunAbandoningRemaining({
1822
1826
  runId: meta.run_id,
1823
1827
  plan: compileArtifact.plan,
1824
1828
  events,
1825
1829
  recordedAt: canonicalNow(),
1826
1830
  });
1827
- if (!closed.closed) {
1828
- throw new CliContractError(
1829
- 'RUN_NOT_COMPLETE',
1830
- '全TODOのreceipt accepted前はrunを正常closeできない',
1831
- { guidance: 'run statusで未完了TODOを確認するか、run abandonを明示実行する' },
1832
- );
1833
- }
1831
+ abandonedTodoIds = closed.abandoned_todo_ids;
1834
1832
  if (managed !== null) {
1835
1833
  await runManagedControl({ runDir, runRef: path.relative(repoRoot, runDir),
1836
1834
  operation: 'close', artifactDigest: null, stdout, shutdownReason: 'normal-close',
@@ -1846,6 +1844,7 @@ async function runClose({ runDir, repoRoot, stdout, requestId = null }) {
1846
1844
  outcome: 'closed',
1847
1845
  run_id: meta.run_id,
1848
1846
  already_closed: alreadyClosed,
1847
+ ...(abandonedTodoIds.length > 0 ? { abandoned_todo_ids: abandonedTodoIds } : {}),
1849
1848
  event_count: next.length,
1850
1849
  events_digest: digestArtifact(next.map(({ event_digest: digest }) => digest)),
1851
1850
  landing: await buildRunLandingReport({
@@ -3650,9 +3649,8 @@ export async function runManagedSupervisorDaemon({
3650
3649
  }
3651
3650
  let proposed;
3652
3651
  if (controlRequest.operation === 'close') {
3653
- proposed = closeRunIfComplete({ runId: request.request_id, plan: active.bundle.plan,
3652
+ proposed = closeRunAbandoningRemaining({ runId: request.request_id, plan: active.bundle.plan,
3654
3653
  events, recordedAt: canonicalNow() });
3655
- if (!proposed.closed) throw new ManagedRuntimeError('RUN_NOT_COMPLETE', '全TODO完了前はcloseできない');
3656
3654
  }
3657
3655
  const shutdown = await managedSupervisor.shutdownManaged({ mode: controlRequest.operation,
3658
3656
  reason: shutdownReason, barrierId: `shutdown-${randomUUID()}`,
@@ -3667,19 +3665,30 @@ export async function runManagedSupervisorDaemon({
3667
3665
  }
3668
3666
  await replaceEventsAtomically(runDir, events);
3669
3667
  // **abandonは成果を捨てる決定である。** worker processの終了はcleanupではなく
3670
- // その決定の一部なので、誰を止めたかを記録へ残す。closeでは何もしない——
3671
- // 完走したrunのworkerは既にterminalであり、生きていればそれは欠陥である
3672
- // (`closeRunIfComplete`が全TODO accepted を要求するので、そもそもcloseへ来ない)。
3673
- if (controlRequest.operation === 'abandon') {
3674
- const reaped = await reapRunWorkerProcesses({ events }).catch(() => null);
3675
- if (reaped !== null && (reaped.reaped.length > 0 || reaped.skipped.length > 0)) {
3668
+ // その決定の一部なので、誰を止めたかを記録へ残す。完走したcloseでは何もしない。
3669
+ // u03 C18: 未完了TODOを放棄して閉じるcloseはworkerも止める。作業木はrunの成果なので残す。
3670
+ // SIGKILLは停止中(SIGSTOP)のworkerにも届く。
3671
+ const stopsWorkers = controlRequest.operation === 'abandon'
3672
+ || proposed?.abandoned_todo_ids.length > 0;
3673
+ if (stopsWorkers) {
3674
+ const reaped = await reapRunWorkerProcesses({ events }).catch(() => null)
3675
+ ?? { reaped: [], skipped: [], unavailable: [] };
3676
+ // R2k: a killed worker's tree loses a stale index.lock and names unobserved writes.
3677
+ const keptWorktrees = await recoverKeptWorktrees({ events });
3678
+ if (reaped.reaped.length > 0 || reaped.skipped.length > 0
3679
+ || reaped.unavailable.length > 0 || keptWorktrees.length > 0) {
3676
3680
  await appendControl({ run_id: request.request_id, kind: 'worker_processes_terminated',
3677
3681
  session_nonce_digest: digestArtifact(sessionNonce), payload: {
3678
3682
  reason: shutdownReason,
3679
3683
  terminated_pids: [...reaped.reaped].sort((left, right) => left - right),
3680
3684
  skipped_count: reaped.skipped.length,
3685
+ ...(reaped.unavailable.length > 0
3686
+ ? { signal_unavailable_pids: [...reaped.unavailable].sort((left, right) => left - right) } : {}),
3687
+ ...(keptWorktrees.length > 0 ? { kept_worktrees: keptWorktrees } : {}),
3681
3688
  } });
3682
3689
  }
3690
+ }
3691
+ if (controlRequest.operation === 'abandon') {
3683
3692
  // 木も畳む。closeでは畳まない——木そのものがrunの成果であり、着地させる前に
3684
3693
  // 消したら受理した内容が残らない。
3685
3694
  await removeScriptedWorktrees({ repoRoot, runDir }).catch(() => null);
@@ -187,7 +187,28 @@ export function validateRuntimeControlEventPayload(kind, value) {
187
187
  // 停止したworkerの行き先は「再開」か「破棄」の二択であり、破棄を選んだなら
188
188
  // 誰を止めたかが残っていなければ、後から何が捨てられたか説明できない。
189
189
  if (kind === 'worker_processes_terminated') {
190
- return exact(value, ['reason', 'terminated_pids', 'skipped_count'])
190
+ // signal_unavailable_pids (u03 C25): alive but not re-authenticated, so not signalled.
191
+ const pidList = (pids) => Array.isArray(pids) && pids.length > 0 && pids.length <= 4096
192
+ && pids.every((pid, index) => Number.isSafeInteger(pid) && pid > 0
193
+ && (index === 0 || pids[index - 1] < pid));
194
+ // kept_worktrees (R2k): per tree, index.lock recovery and paths written after the last checkpoint.
195
+ const textList = (items) => Array.isArray(items) && items.length <= 4096
196
+ && items.every((item) => typeof item === 'string' && item.length > 0);
197
+ const keptWorktree = (entry) => plain(entry)
198
+ && (exact(entry, ['todo_ids', 'worktree_path', 'index_lock', 'unobserved_paths'])
199
+ ? textList(entry.unobserved_paths)
200
+ : exact(entry, ['todo_ids', 'worktree_path', 'index_lock', 'observation_error'])
201
+ && typeof entry.observation_error === 'string')
202
+ && Array.isArray(entry.todo_ids) && entry.todo_ids.length > 0 && entry.todo_ids.every(identifier)
203
+ && typeof entry.worktree_path === 'string' && path.isAbsolute(entry.worktree_path)
204
+ && ['absent', 'removed', 'replaced', 'conflict_kept', 'owner_live', 'owner_unproven', 'unknown']
205
+ .includes(entry.index_lock);
206
+ const optional = Object.keys(value ?? {}).filter((key) => !['reason', 'terminated_pids',
207
+ 'skipped_count'].includes(key));
208
+ return exact(value, ['reason', 'terminated_pids', 'skipped_count', ...optional])
209
+ && optional.every((key) => (key === 'signal_unavailable_pids' && pidList(value[key]))
210
+ || (key === 'kept_worktrees' && Array.isArray(value[key]) && value[key].length > 0
211
+ && value[key].length <= 4096 && value[key].every(keptWorktree)))
191
212
  && typeof value.reason === 'string' && value.reason.length > 0
192
213
  && Array.isArray(value.terminated_pids) && value.terminated_pids.length <= 4096
193
214
  && value.terminated_pids.every((pid) => Number.isSafeInteger(pid) && pid > 0)
@@ -436,15 +436,31 @@ export function recomputeHoldDecision(options = {}) {
436
436
  const holdSet = new Set();
437
437
  const continueSet = new Set();
438
438
  const reasons = {};
439
+ // u03 C43 (claim 10): hold only the affected group. Outside the closure, only a TODO whose
440
+ // declared writes or frozen observed paths touch the finding paths is affected.
441
+ const findingPaths = new Set(frozenConflicts.flatMap((conflict) => (
442
+ typeof conflict.path === 'string' ? [conflict.path] : (conflict.paths ?? []))));
443
+ const touchesFinding = (todoId) => {
444
+ const declared = manifests?.[todoId]?.writes ?? [];
445
+ const observed = new Set(state.checkpoints
446
+ .filter((entry) => entry.todo_id === todoId && entry.sequence <= freezeSequence)
447
+ .flatMap((entry) => (entry.payload?.diff?.entries ?? []).map((entry2) => entry2.path)));
448
+ for (const findingPath of findingPaths) {
449
+ if (observed.has(findingPath)) return true;
450
+ if (declared.some((write) => write === findingPath
451
+ || (write.endsWith('/') && findingPath.startsWith(write)))) return true;
452
+ }
453
+ return false;
454
+ };
439
455
  for (const todoId of frozenRunning) {
440
456
  if (closure.has(todoId)) {
441
457
  holdSet.add(todoId);
442
458
  reasons[todoId] = 'affected_closure';
443
- } else if (witnessedForContinue(state.witnesses[todoId], todoId)) {
444
- continueSet.add(todoId);
445
- } else {
459
+ } else if (touchesFinding(todoId)) {
446
460
  holdSet.add(todoId);
447
- reasons[todoId] = 'carry_over_unprovable';
461
+ reasons[todoId] = 'finding_scope_overlap';
462
+ } else {
463
+ continueSet.add(todoId);
448
464
  }
449
465
  }
450
466
  for (const todoId of closure) {
@@ -529,9 +545,7 @@ export function recomputeReceiptDecisions(options = {}) {
529
545
  const originBindingRetained = (() => {
530
546
  if (!Number.isSafeInteger(receipt.plan_epoch) || receipt.plan_epoch >= plan.plan_epoch) return false;
531
547
  for (let epoch = receipt.plan_epoch; epoch < plan.plan_epoch; epoch += 1) {
532
- const witnessed = events.some((event) => event.sequence < receipt.sequence
533
- && event.kind === 'carry_over_witnessed' && event.plan_epoch === epoch
534
- && event.subject?.kind === 'todo' && event.subject.ref === receipt.todo_id);
548
+ // u03 C43: continue_set membership carries the origin binding; no witness required.
535
549
  const continued = events.some((event) => event.sequence < receipt.sequence
536
550
  && event.kind === 'hold_decided' && event.plan_epoch === epoch
537
551
  && event.payload?.continue_set?.includes(receipt.todo_id));
@@ -540,7 +554,7 @@ export function recomputeReceiptDecisions(options = {}) {
540
554
  const invalidated = events.some((event) => event.sequence < receipt.sequence
541
555
  && event.kind === 'context_invalidated' && event.plan_epoch === epoch + 1
542
556
  && event.subject?.kind === 'todo' && event.subject.ref === receipt.todo_id);
543
- if (!witnessed || !continued || !recompiled || invalidated) return false;
557
+ if (!continued || !recompiled || invalidated) return false;
544
558
  }
545
559
  return true;
546
560
  })();
@@ -612,6 +626,11 @@ export function recomputeReceiptDecisions(options = {}) {
612
626
  // receipt_bindingsが当該receiptをbindする場合だけ有効になる(Decision 7.5)。
613
627
  const witnessRecord = state.witnesses[receipt.todo_id];
614
628
  if (!witnessedForContinue(witnessRecord, receipt.todo_id)) {
629
+ // u03 C43: without any witness, this epoch's continue_set decides.
630
+ const continued = witnessRecord?.payload?.witness?.predecessor_epoch !== plan.plan_epoch && events.some((event) => (
631
+ event.kind === 'hold_decided' && event.plan_epoch === plan.plan_epoch
632
+ && event.payload?.continue_set?.includes(receipt.todo_id)));
633
+ if (continued) return { ...base, decision: 'accepted', reason: null, detail: null };
615
634
  return reject('witness_unproven');
616
635
  }
617
636
  const bound = witnessRecord.payload.witness.receipt_bindings.some((binding) => (
@@ -594,12 +594,17 @@ function witnessProvenReceiptBinding(state, receipt) {
594
594
  ));
595
595
  }
596
596
 
597
+ // u03 C43: an unwitnessed closure-external TODO continued by this epoch's hold decision.
598
+ function continuedWithoutWitness(events, receipt, currentEpoch) {
599
+ return events.some((event) => event.kind === 'hold_decided' && event.plan_epoch === currentEpoch
600
+ && event.payload?.continue_set?.includes(receipt.todo_id));
601
+ }
602
+
597
603
  function retainsOriginBinding(events, receipt, currentEpoch) {
598
604
  if (!Number.isSafeInteger(receipt.plan_epoch) || receipt.plan_epoch >= currentEpoch) return false;
605
+ // u03 C43: continue_set membership (durable in hold_decided) carries the origin binding;
606
+ // the witness is evidence when provable, not a condition.
599
607
  for (let epoch = receipt.plan_epoch; epoch < currentEpoch; epoch += 1) {
600
- const witnessed = events.some((event) => event.sequence < receipt.sequence
601
- && event.kind === 'carry_over_witnessed' && event.plan_epoch === epoch
602
- && event.subject?.kind === 'todo' && event.subject.ref === receipt.todo_id);
603
608
  const continued = events.some((event) => event.sequence < receipt.sequence
604
609
  && event.kind === 'hold_decided' && event.plan_epoch === epoch
605
610
  && event.payload?.continue_set?.includes(receipt.todo_id));
@@ -608,7 +613,7 @@ function retainsOriginBinding(events, receipt, currentEpoch) {
608
613
  const invalidated = events.some((event) => event.sequence < receipt.sequence
609
614
  && event.kind === 'context_invalidated' && event.plan_epoch === epoch + 1
610
615
  && event.subject?.kind === 'todo' && event.subject.ref === receipt.todo_id);
611
- if (!witnessed || !continued || !recompiled || invalidated) return false;
616
+ if (!continued || !recompiled || invalidated) return false;
612
617
  }
613
618
  return true;
614
619
  }
@@ -710,7 +715,9 @@ export function adjudicatePendingReceipts(options = {}) {
710
715
  // 実証済みcarry-over witnessのbindingがある場合だけ受理(Decision 7.5)。
711
716
  if (receipt.sequence > freezeBoundary) {
712
717
  rejection = 'post_freeze';
713
- } else if (!witnessProvenReceiptBinding(state, receipt)) {
718
+ } else if (!witnessProvenReceiptBinding(state, receipt)
719
+ && !(state.witnesses[receipt.todo_id]?.payload?.witness?.predecessor_epoch !== plan.plan_epoch
720
+ && continuedWithoutWitness(events, receipt, plan.plan_epoch))) {
714
721
  rejection = 'witness_unproven';
715
722
  }
716
723
  }
@@ -769,3 +776,25 @@ export function closeRunIfComplete(options = {}) {
769
776
  }));
770
777
  return { events: next, closed: true };
771
778
  }
779
+
780
+ /**
781
+ * u03 C18: closeはrunを必ず閉じる。完了済みなら従来と同じbytes、未完了TODOは
782
+ * `abandoned_todo_ids`として記録する(明示`run abandon`の作業木削除は行わない)。
783
+ */
784
+ export function closeRunAbandoningRemaining({ runId, plan, events, recordedAt }) {
785
+ const complete = closeRunIfComplete({ runId, plan, events, recordedAt });
786
+ const state = projectRuntimeState({ events });
787
+ if (complete.closed || state.closed) return { ...complete, abandoned_todo_ids: [] };
788
+ const abandoned = sortedText(plan.nodes.map((node) => node.todo_id)
789
+ .filter((todoId) => !state.accepted.includes(todoId)));
790
+ const next = [...events, buildNextRunEvent({
791
+ events,
792
+ runId,
793
+ kind: 'run_closed',
794
+ planEpoch: plan.plan_epoch,
795
+ subject: { kind: 'runtime_plan', ref: plan.plan_ref },
796
+ payload: { accepted: sortedText(state.accepted), abandoned_todo_ids: abandoned },
797
+ recordedAt,
798
+ })];
799
+ return { events: next, closed: true, abandoned_todo_ids: abandoned };
800
+ }
@@ -407,13 +407,8 @@ export function decideHoldAndCarryOver(options = {}) {
407
407
  holdSet.add(todoId);
408
408
  continue;
409
409
  }
410
- // closure外のin-flight TODO: witnessを構築・実証できた場合だけcontinue。
410
+ // u03 C43 (claim 10): closure外は影響群でない限りcontinue。witnessは実証できた時だけ記録する。
411
411
  const packet = packets[todoId];
412
- if (packet === undefined || manifests[todoId] === undefined) {
413
- holdSet.add(todoId);
414
- witnessFailures[todoId] = ['missing_packet_or_manifest'];
415
- continue;
416
- }
417
412
  // freeze後に当該TODOの未取り込みdiff/receipt eventが存在するなら
418
413
  // carry-over不能(Decision 7.2「freeze後に未取り込みdiff eventが存在しない」)。
419
414
  const postFreezeEvents = events.some((event) => (
@@ -423,14 +418,9 @@ export function decideHoldAndCarryOver(options = {}) {
423
418
  && ['checkpoint_observed', 'receipt_recorded'].includes(event.kind)
424
419
  && event.payload?.barrier_final !== true
425
420
  ));
426
- if (postFreezeEvents) {
427
- holdSet.add(todoId);
428
- witnessFailures[todoId] = ['post_freeze_events'];
429
- continue;
430
- }
421
+ const declaredWrites = manifests[todoId]?.writes ?? [];
431
422
  // 競合finding pathと当該TODOのdeclared write/観測pathが交差するなら
432
423
  // 非交差を証明できない(Decision 7.2の changed scope 非交差条件)。
433
- const declaredWrites = manifests[todoId].writes ?? [];
434
424
  const observedPaths = state.checkpoints
435
425
  .filter((entry) => entry.todo_id === todoId && entry.sequence <= freezeSequence)
436
426
  .flatMap((entry) => (entry.payload?.diff?.entries ?? []).map(({ path }) => path));
@@ -445,6 +435,17 @@ export function decideHoldAndCarryOver(options = {}) {
445
435
  witnessFailures[todoId] = ['finding_scope_overlap'];
446
436
  continue;
447
437
  }
438
+ // witnessを作れない理由はcontinueを妨げない。記録だけ返す。
439
+ if (packet === undefined || manifests[todoId] === undefined) {
440
+ continueSet.add(todoId);
441
+ witnessFailures[todoId] = ['missing_packet_or_manifest'];
442
+ continue;
443
+ }
444
+ if (postFreezeEvents) {
445
+ continueSet.add(todoId);
446
+ witnessFailures[todoId] = ['post_freeze_events'];
447
+ continue;
448
+ }
448
449
  const receiptBindings = state.receipts
449
450
  .filter((receipt) => (
450
451
  receipt.todo_id === todoId
@@ -480,7 +481,7 @@ export function decideHoldAndCarryOver(options = {}) {
480
481
  receiptBindings,
481
482
  });
482
483
  if (built.witness === null) {
483
- holdSet.add(todoId);
484
+ continueSet.add(todoId);
484
485
  witnessFailures[todoId] = built.reasons;
485
486
  continue;
486
487
  }
@@ -800,8 +801,11 @@ export function recompileNextEpochPlan(options = {}) {
800
801
  const packet = packets[todoId];
801
802
  const dispatch = state.dispatches[todoId];
802
803
  const witnessRecord = state.witnesses[todoId];
803
- if (packet === undefined || dispatch === undefined || witnessRecord === undefined) {
804
- fail(`carried-over TODOのpacket/dispatch/witnessが欠落: ${todoId}`);
804
+ // shortcut: unwitnessed carry has no rebind packet; it keeps its origin binding, and
805
+ // hold_decided.continue_set (durable) still accepts its receipts after a restart.
806
+ if (witnessRecord?.payload?.witness?.predecessor_epoch !== plan.plan_epoch) continue;
807
+ if (packet === undefined || dispatch === undefined) {
808
+ fail(`carried-over TODOのpacket/dispatchが欠落: ${todoId}`);
805
809
  }
806
810
  // authorized checkpointはfrozen prefix内の最後の観測checkpoint。checkpointが
807
811
  // 一件もないcarry-overはgenesis sentinel(64桁ゼロ、RC3-J ADRで正式裁定予定)。
@@ -0,0 +1,136 @@
1
+ /**
2
+ * R2k: what a SIGKILLed worker leaves in its kept worktree (dfd-runtime-hold-resume.md).
3
+ *
4
+ * Git's index.lock names no owner. The owner is every process Runtime put in that 1:1 tree,
5
+ * recorded by `executor_dispatched`. The lock goes only when all of them are proven gone, and
6
+ * only the judged inode. Half-written files are reported, never repaired: close keeps the tree.
7
+ */
8
+
9
+ import { spawn } from 'node:child_process';
10
+ import { lstat } from 'node:fs/promises';
11
+ import path from 'node:path';
12
+
13
+ import { captureWorktreeDiff } from './runtime-diff-observer.mjs';
14
+ import { removeJudgedEntry } from './runtime-lifecycle-lock.mjs';
15
+ import { observeManagedProcessStartIdentity } from './runtime-managed-supervisor.mjs';
16
+ import { observePsSnapshot } from './runtime-os-observation.mjs';
17
+
18
+ const DEAD_WAIT_MS = 2_000;
19
+
20
+ function gitPath(worktreePath, name) {
21
+ return new Promise((resolve, reject) => {
22
+ const child = spawn('git', ['rev-parse', '--git-path', name], {
23
+ cwd: worktreePath, shell: false, stdio: ['ignore', 'pipe', 'ignore'],
24
+ });
25
+ let stdout = '';
26
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
27
+ child.once('error', reject);
28
+ child.once('close', (code) => (code === 0
29
+ ? resolve(path.resolve(worktreePath, stdout.trim()))
30
+ : reject(new Error(`git rev-parse --git-path failed (${code})`))));
31
+ });
32
+ }
33
+
34
+ /** 'dead' | 'live' | 'unproven' for the set of workers bound to one tree. */
35
+ async function ownersState(bindings) {
36
+ let rows;
37
+ try {
38
+ rows = (await observePsSnapshot()).split('\n').map((line) => line.trim().split(/\s+/u))
39
+ .filter((fields) => fields.length >= 4)
40
+ .map(([pid, , pgid, state]) => ({ pid: Number(pid), pgid: Number(pgid), state }));
41
+ } catch {
42
+ return 'unproven'; // no ps (win32) or failed observation: the group cannot be shown empty
43
+ }
44
+ const live = rows.filter((row) => !row.state.startsWith('Z'));
45
+ for (const binding of bindings) {
46
+ if (!Number.isSafeInteger(binding.process_group_id)) return 'unproven';
47
+ if (live.some((row) => row.pgid === binding.process_group_id)) return 'live';
48
+ if (!live.some((row) => row.pid === binding.process_pid)) continue;
49
+ let observed;
50
+ try { observed = await observeManagedProcessStartIdentity(binding.process_pid); }
51
+ catch { return 'unproven'; } // alive but not re-authenticated (u03 C25)
52
+ if (observed.identity_digest === binding.process_start_identity?.identity_digest) return 'live';
53
+ }
54
+ return 'dead';
55
+ }
56
+
57
+ async function waitOwners(bindings) {
58
+ const deadline = Date.now() + DEAD_WAIT_MS;
59
+ for (;;) {
60
+ const state = await ownersState(bindings);
61
+ if (state !== 'live' || Date.now() >= deadline) return state;
62
+ await new Promise((resolve) => setTimeout(resolve, 50));
63
+ }
64
+ }
65
+
66
+ async function recoverIndexLock(worktreePath, bindings) {
67
+ const lockPath = await gitPath(worktreePath, 'index.lock');
68
+ let info;
69
+ try { info = await lstat(lockPath); }
70
+ catch (error) { if (error?.code === 'ENOENT') return 'absent'; throw error; }
71
+ const owners = await waitOwners(bindings);
72
+ if (owners !== 'dead') return `owner_${owners}`;
73
+ try { return await removeJudgedEntry(lockPath, info); }
74
+ catch (error) {
75
+ if (error?.code === 'RUN_LOCK_INVALID') return 'conflict_kept'; // put-back EEXIST preserves both entries
76
+ throw error;
77
+ }
78
+ }
79
+
80
+ function unobservedPaths(current, checkpoint) {
81
+ const checkpointEntries = checkpoint?.payload?.diff?.entries ?? [];
82
+ const recorded = new Map(checkpointEntries
83
+ .map((entry) => [entry.path, `${entry.change}:${entry.content_digest}`]));
84
+ const currentPaths = new Set(current.diff.entries.map((entry) => entry.path));
85
+ const checkpointOnlyPaths = new Set();
86
+ return [
87
+ ...current.diff.entries
88
+ .filter((entry) => recorded.get(entry.path) !== `${entry.change}:${entry.content_digest}`)
89
+ .map((entry) => entry.path),
90
+ ...checkpointEntries.filter((entry) => {
91
+ if (currentPaths.has(entry.path) || checkpointOnlyPaths.has(entry.path)) return false;
92
+ checkpointOnlyPaths.add(entry.path);
93
+ return true;
94
+ }).map((entry) => entry.path),
95
+ ];
96
+ }
97
+
98
+ /**
99
+ * For every TODO whose last dispatch has no terminal (the work close/abandon ended), recover
100
+ * its tree's stale index.lock and list paths written after the last checkpoint. Never throws.
101
+ */
102
+ export async function recoverKeptWorktrees({ events }) {
103
+ const lastDispatch = new Map();
104
+ for (const event of events) {
105
+ const todoId = event.subject?.ref;
106
+ if (event.kind === 'executor_dispatched') lastDispatch.set(todoId, event);
107
+ if (event.kind === 'executor_terminal') lastDispatch.delete(todoId);
108
+ }
109
+ const trees = new Map();
110
+ for (const [todoId, dispatch] of lastDispatch) {
111
+ const binding = dispatch.payload?.direct_os_observation_binding;
112
+ if (typeof binding?.worktree_path !== 'string') continue;
113
+ const tree = trees.get(binding.worktree_path)
114
+ ?? { todo_ids: [], bindings: [], base_sha: binding.base_sha, checkpoints: [] };
115
+ tree.todo_ids.push(todoId);
116
+ tree.bindings.push(binding);
117
+ tree.checkpoints.push(events.findLast((event) => event.kind === 'checkpoint_observed'
118
+ && event.subject?.ref === todoId && event.sequence > dispatch.sequence));
119
+ trees.set(binding.worktree_path, tree);
120
+ }
121
+ const results = [];
122
+ for (const [worktreePath, tree] of [...trees].sort(([left], [right]) => (left < right ? -1 : 1))) {
123
+ const entry = { todo_ids: tree.todo_ids.sort(), worktree_path: worktreePath };
124
+ try {
125
+ entry.index_lock = await recoverIndexLock(worktreePath, tree.bindings);
126
+ const current = await captureWorktreeDiff({ worktreePath, baseSha: tree.base_sha });
127
+ // shortcut: a tree shared by several TODOs is compared with the first TODO's checkpoint only, upgrade if trees stop being 1:1 per TODO.
128
+ entry.unobserved_paths = unobservedPaths(current, tree.checkpoints[0]);
129
+ } catch (error) {
130
+ entry.index_lock ??= 'unknown';
131
+ entry.observation_error = String(error?.message ?? error).slice(0, 512);
132
+ }
133
+ results.push(entry);
134
+ }
135
+ return results;
136
+ }