@quolu/lattice 0.81.0 → 0.83.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 (71) hide show
  1. package/bin/lattice-bridge-supervisor.mjs +18 -3
  2. package/bin/lattice-dashboard.mjs +3 -18
  3. package/bin/lattice-mcp.mjs +6 -3
  4. package/bin/lattice.mjs +29 -1
  5. package/docs/schemas/lattice.plan_create_input.v5.schema.json +375 -0
  6. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +35 -0
  7. package/package.json +4 -2
  8. package/sensor/dist/db/index.d.ts +1 -0
  9. package/sensor/dist/db/index.d.ts.map +1 -1
  10. package/sensor/dist/db/index.js +13 -0
  11. package/sensor/dist/db/index.js.map +1 -1
  12. package/sensor/dist/index.d.ts.map +1 -1
  13. package/sensor/dist/index.js +12 -2
  14. package/sensor/dist/index.js.map +1 -1
  15. package/sensor/dist/mcp/answer-freshness.js +1 -1
  16. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  17. package/sensor/dist/mcp/engine.d.ts +11 -0
  18. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  19. package/sensor/dist/mcp/engine.js +83 -4
  20. package/sensor/dist/mcp/engine.js.map +1 -1
  21. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  22. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  23. package/sensor/dist/mcp/index-repair.js +93 -0
  24. package/sensor/dist/mcp/index-repair.js.map +1 -0
  25. package/sensor/dist/mcp/index.d.ts.map +1 -1
  26. package/sensor/dist/mcp/index.js +12 -7
  27. package/sensor/dist/mcp/index.js.map +1 -1
  28. package/sensor/dist/mcp/tools.d.ts +4 -0
  29. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  30. package/sensor/dist/mcp/tools.js +29 -9
  31. package/sensor/dist/mcp/tools.js.map +1 -1
  32. package/src/bridge-cli.mjs +16 -4
  33. package/src/bridge-detached-supervisor.mjs +204 -0
  34. package/src/bridge-hub-server.mjs +46 -9
  35. package/src/bridge-startup-folder.mjs +7 -4
  36. package/src/cli-help.mjs +5 -2
  37. package/src/dashboard-lifecycle-journal.mjs +42 -20
  38. package/src/plan-backchain.mjs +31 -12
  39. package/src/plan-binding-carry.mjs +60 -0
  40. package/src/plan-revise.mjs +276 -0
  41. package/src/project-cli.mjs +50 -22
  42. package/src/project-identity.mjs +14 -0
  43. package/src/runtime-cli.mjs +31 -18
  44. package/src/runtime-control-store.mjs +22 -1
  45. package/src/runtime-decision-verifier.mjs +27 -8
  46. package/src/runtime-engine.mjs +34 -5
  47. package/src/runtime-hold-recompile.mjs +19 -15
  48. package/src/runtime-kept-worktree.mjs +136 -0
  49. package/src/runtime-lifecycle-lock.mjs +118 -30
  50. package/src/runtime-managed-supervisor.mjs +10 -10
  51. package/src/runtime-os-observation.mjs +39 -1
  52. package/src/runtime-pull-intake.mjs +87 -43
  53. package/src/store-lock.mjs +146 -59
  54. package/src/todo-authoring-input.mjs +57 -2
  55. package/src/todo-cli.mjs +173 -45
  56. package/src/todo-contracts.mjs +22 -6
  57. package/src/todo-dashboard-registry.mjs +31 -4
  58. package/src/todo-gantt-display.mjs +260 -0
  59. package/src/todo-gantt-html-independence.mjs +8 -1
  60. package/src/todo-gantt-html-shared.mjs +2 -1
  61. package/src/todo-gantt-html.mjs +4 -2
  62. package/src/todo-gantt-layout.mjs +7 -36
  63. package/src/todo-gantt-live.mjs +6 -3
  64. package/src/todo-note-store.mjs +13 -5
  65. package/src/todo-readiness.mjs +29 -8
  66. package/src/todo-revision.mjs +9 -8
  67. package/src/todo-split.mjs +6 -3
  68. package/src/todo-status.mjs +53 -9
  69. package/src/todo-store-cache.mjs +1 -1
  70. package/src/todo-store-view.mjs +21 -2
  71. package/src/todo-store.mjs +642 -172
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { fsyncDirectory as syncDirectory } from './fs-dir-sync.mjs';
3
3
  import { constants as fsConstants } from 'node:fs';
4
- import { lstat, open, readFile, rename, rm, unlink } from 'node:fs/promises';
4
+ import { link, lstat, open, readdir, readFile, rename, rm, unlink } from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
 
7
7
  import { canonicalizeArtifact } from './artifact-contracts.mjs';
@@ -11,6 +11,9 @@ const SHA256 = /^[0-9a-f]{64}$/;
11
11
  const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
12
12
  const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
13
13
  const LOCK_NAME = '.lifecycle.lock';
14
+ // Pre-u03 binaries wrote after O_EXCL create; their write finishes well inside this window.
15
+ const UNIDENTIFIED_GRACE_MS = 10_000;
16
+ const NO_HARD_LINK = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS']);
14
17
 
15
18
  export class RuntimeLifecycleLockError extends Error {
16
19
  constructor(code, detail) {
@@ -84,22 +87,59 @@ async function defaultObserver(pid) {
84
87
  return observeManagedProcessStartIdentity(pid);
85
88
  }
86
89
 
90
+ class UnidentifiedLock extends Error {
91
+ constructor(info) { super('unidentified lifecycle lock'); this.info = info; }
92
+ }
93
+
94
+ // nlink 2 is the publisher's window between link() and unlinking its temporary.
87
95
  async function readLockArtifact(lockPath) {
88
96
  const info = await lstat(lockPath);
89
- if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) {
90
- fail('RUN_LOCK_INVALID', 'lifecycle lockが単一linkのregular fileでない');
97
+ if (!info.isFile() || info.isSymbolicLink()) {
98
+ fail('RUN_LOCK_INVALID', 'lifecycle lockがregular fileでない');
91
99
  }
92
100
  const bytes = await readFile(lockPath);
93
101
  let value;
94
- try { value = JSON.parse(bytes.toString('utf8')); }
95
- catch { fail('RUN_BUSY', 'lifecycle lock取得処理が進行中'); }
96
- if (!validateRuntimeLifecycleLockArtifact(value)) {
97
- fail('RUN_LOCK_INVALID', 'lifecycle lock artifact不正');
102
+ try { value = JSON.parse(bytes.toString('utf8')); } catch { throw new UnidentifiedLock(info); }
103
+ if (validateRuntimeLifecycleLockArtifact(value)
104
+ && bytes.toString('utf8') === `${canonicalizeArtifact(value)}\n`) return { value, info };
105
+ // Another schema may be a newer binary's live owner: identified but unsupported, never aged out.
106
+ if (plain(value) && value.schema !== 'lattice.runtime_lifecycle_lock.v1') {
107
+ fail('RUN_LOCK_INVALID', `未対応のlifecycle lock schema: ${String(value.schema)}`);
98
108
  }
99
- if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
100
- fail('RUN_LOCK_INVALID', 'lifecycle lockがcanonical bytesでない');
109
+ throw new UnidentifiedLock(info);
110
+ }
111
+
112
+ /** Empty/torn/invalid bytes name no owner; only their age can show the writer is gone. */
113
+ export async function recoverUnidentifiedLock(lockPath, info) {
114
+ if (Date.now() - info.mtimeMs < UNIDENTIFIED_GRACE_MS) return false;
115
+ await removeJudgedEntry(lockPath, info);
116
+ return true;
117
+ }
118
+
119
+ /**
120
+ * Unlink exactly the entry judged by `info` ({dev,ino,size,mtimeMs}); never a newer one.
121
+ * Returns 'removed', 'absent' or 'replaced' (another entry took the path: put back untouched).
122
+ */
123
+ export async function removeJudgedEntry(lockPath, info) {
124
+ const quarantine = path.join(path.dirname(lockPath),
125
+ `.${path.basename(lockPath)}.${process.pid}.${randomUUID()}.stale`);
126
+ try { await rename(lockPath, quarantine); }
127
+ catch (error) { if (error?.code === 'ENOENT') return 'absent'; throw error; }
128
+ const moved = await lstat(quarantine);
129
+ if (moved.dev !== info.dev || moved.ino !== info.ino || moved.size !== info.size
130
+ || moved.mtimeMs !== info.mtimeMs) {
131
+ // Not the entry we judged (release + fresh acquire raced stat→rename): put it back untouched.
132
+ try { await link(quarantine, lockPath); }
133
+ catch (error) {
134
+ if (error?.code === 'EEXIST') fail('RUN_LOCK_INVALID', `回収競合artifactを保全した: ${quarantine}`);
135
+ throw error;
136
+ }
137
+ await unlink(quarantine);
138
+ return 'replaced';
101
139
  }
102
- return { value, info };
140
+ await unlink(quarantine);
141
+ await syncDirectory(path.dirname(lockPath));
142
+ return 'removed';
103
143
  }
104
144
 
105
145
  async function pidExists(pid) {
@@ -137,7 +177,13 @@ async function recoverStaleLock(lockPath, expectedDigest) {
137
177
  throw error;
138
178
  }
139
179
  try {
140
- const moved = await readLockArtifact(quarantine);
180
+ const moved = await readLockArtifact(quarantine).catch((error) => {
181
+ // Anything but the judged owner (torn, other schema) goes back untouched.
182
+ if (error instanceof UnidentifiedLock || error instanceof RuntimeLifecycleLockError) {
183
+ return { value: { lock_digest: null } };
184
+ }
185
+ throw error;
186
+ });
141
187
  if (moved.value.lock_digest !== expectedDigest) {
142
188
  // stale判定後に別ownerが取得したfileをrenameしてしまった場合は破棄しない。
143
189
  try { await rename(quarantine, lockPath); }
@@ -157,29 +203,66 @@ async function recoverStaleLock(lockPath, expectedDigest) {
157
203
  }
158
204
  }
159
205
 
160
- async function createLock(lockPath, artifact) {
206
+ const TEMPORARY = /^(\d+)\.[0-9a-f-]{36}\.tmp$/u;
207
+
208
+ async function removeDeadTemporaries(lockPath) {
209
+ const prefix = `${path.basename(lockPath)}.`;
210
+ let names;
211
+ try { names = await readdir(path.dirname(lockPath)); }
212
+ catch (error) { if (error?.code === 'ENOENT') return; throw error; }
213
+ for (const name of names) {
214
+ const pid = name.startsWith(prefix) ? Number(name.slice(prefix.length).match(TEMPORARY)?.[1]) : NaN;
215
+ if (Number.isSafeInteger(pid) && pid !== process.pid && !await pidExists(pid)) {
216
+ await rm(path.join(path.dirname(lockPath), name), { force: true });
217
+ }
218
+ }
219
+ }
220
+
221
+ /** Pre-u03 publication, kept for filesystems without hard links; L2 recovers its crash window. */
222
+ async function createLockInPlace(lockPath, artifact) {
161
223
  let handle;
162
- let created = false;
163
224
  try {
164
- handle = await open(lockPath,
165
- fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
166
- created = true;
225
+ handle = await open(lockPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
226
+ } catch (error) {
227
+ if (error?.code === 'EEXIST') return false;
228
+ throw error;
229
+ }
230
+ try {
167
231
  await handle.writeFile(Buffer.from(`${canonicalizeArtifact(artifact)}\n`, 'utf8'));
168
232
  await handle.sync();
169
- await handle.close();
233
+ } catch (error) {
234
+ await handle.close().catch(() => {});
170
235
  handle = null;
236
+ await unlink(lockPath).catch(() => {});
237
+ throw error;
238
+ } finally {
239
+ if (handle) await handle.close();
240
+ }
241
+ await syncDirectory(path.dirname(lockPath));
242
+ return true;
243
+ }
244
+
245
+ /** The shared path only ever receives complete bytes: write a private temporary, then link it. */
246
+ async function createLock(lockPath, artifact, publishLink = link) {
247
+ const temporary = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
248
+ try {
249
+ const handle = await open(temporary,
250
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
251
+ try {
252
+ await handle.writeFile(Buffer.from(`${canonicalizeArtifact(artifact)}\n`, 'utf8'));
253
+ await handle.sync();
254
+ } finally { await handle.close(); }
255
+ try { await publishLink(temporary, lockPath); }
256
+ catch (error) {
257
+ if (error?.code === 'EEXIST') return false;
258
+ if (NO_HARD_LINK.has(error?.code)) return createLockInPlace(lockPath, artifact);
259
+ throw error;
260
+ }
261
+ await unlink(temporary);
171
262
  await syncDirectory(path.dirname(lockPath));
172
263
  return true;
173
- } catch (error) {
174
- if (error?.code === 'EEXIST') return false;
175
- if (handle) {
176
- await handle.close().catch(() => {});
177
- handle = null;
178
- }
179
- if (created) await unlink(lockPath).catch(() => {});
180
- throw error;
181
264
  } finally {
182
- if (handle) await handle.close().catch(() => {});
265
+ await rm(temporary, { force: true }).catch(() => {});
183
266
  }
184
267
  }
185
268
 
@@ -202,6 +285,7 @@ export async function acquireRuntimeLifecycleLock({
202
285
  processStartIdentity = null,
203
286
  observeProcessStartIdentity = null,
204
287
  now = () => new Date(),
288
+ publishLink = link, // test seam: filesystems without hard links
205
289
  } = {}) {
206
290
  const resolvedLockPath = validateOptions({ lockPath, runDir, sessionNonceDigest, operation,
207
291
  requestId, timeoutMs, retryIntervalMs, processStartIdentity, observeProcessStartIdentity, now });
@@ -226,9 +310,10 @@ export async function acquireRuntimeLifecycleLock({
226
310
  };
227
311
  artifact.lock_digest = selfDigest(artifact, 'lock_digest');
228
312
  const deadline = Date.now() + timeoutMs;
313
+ await removeDeadTemporaries(resolvedLockPath);
229
314
 
230
315
  while (true) {
231
- if (await createLock(resolvedLockPath, artifact)) {
316
+ if (await createLock(resolvedLockPath, artifact, publishLink)) {
232
317
  let released = false;
233
318
  return {
234
319
  artifact: structuredClone(artifact),
@@ -247,9 +332,11 @@ export async function acquireRuntimeLifecycleLock({
247
332
  try { existing = await readLockArtifact(resolvedLockPath); }
248
333
  catch (error) {
249
334
  if (error?.code === 'ENOENT') continue;
250
- if (error instanceof RuntimeLifecycleLockError && error.code === 'RUN_BUSY'
251
- && Date.now() < deadline) { await sleep(retryIntervalMs); continue; }
252
- throw error;
335
+ if (!(error instanceof UnidentifiedLock)) throw error;
336
+ if (await recoverUnidentifiedLock(resolvedLockPath, error.info)) continue;
337
+ if (Date.now() >= deadline) fail('RUN_BUSY', 'lifecycle lock取得処理が進行中');
338
+ await sleep(Math.min(retryIntervalMs, Math.max(1, deadline - Date.now())));
339
+ continue;
253
340
  }
254
341
  if (!await ownerIsLive(existing.value, observer)) {
255
342
  await recoverStaleLock(resolvedLockPath, existing.value.lock_digest);
@@ -273,6 +360,7 @@ export async function releaseRuntimeLifecycleLock({ lockPath, ownerDigest } = {}
273
360
  try { existing = await readLockArtifact(lockPath); }
274
361
  catch (error) {
275
362
  if (error?.code === 'ENOENT') fail('RUN_LOCK_OWNER_MISMATCH', 'release対象lockなし');
363
+ if (error instanceof UnidentifiedLock) fail('RUN_LOCK_OWNER_MISMATCH', 'lifecycle lock owner digest不一致');
276
364
  throw error;
277
365
  }
278
366
  if (existing.value.lock_digest !== ownerDigest) {
@@ -976,16 +976,16 @@ async function activateManagedSupervisorController({ repoRoot, runDir, runId, ad
976
976
  if (!socketInfo.isSocket()) fail('ADAPTER_CONTROLLER_UNAVAILABLE', 'controller endpointがsocketでない');
977
977
  // exec後にも同じ実行image bytesを再検証する。PID生存も同時に要求する。
978
978
  try { process.kill(child.pid, 0); } catch { fail('ADAPTER_CONTROLLER_UNAVAILABLE', 'controller process不達'); }
979
- let executedImage;
980
- try {
981
- executedImage = await observeProcessExecutablePath(child.pid);
982
- } catch { fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path観測失敗'); }
983
- if (executedImage !== binaryReal || sha256Bytes(await readFile(executedImage)) !== launch.binary_digest) {
984
- fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path/bytes不一致');
985
- }
986
- if (launch.binary_identity !== null
987
- && canonicalizeArtifact(await binaryIdentityObserver(executedImage)) !== canonicalizeArtifact(launch.binary_identity)) {
988
- fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後macOS identity不一致');
979
+ // u03 C25: 観測できない時はpre-exec検証だけで進む。観測できて食い違う時だけ止める。
980
+ const executedImage = await observeProcessExecutablePath(child.pid).catch(() => null);
981
+ if (executedImage !== null) {
982
+ if (executedImage !== binaryReal || sha256Bytes(await readFile(executedImage)) !== launch.binary_digest) {
983
+ fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path/bytes不一致');
984
+ }
985
+ if (launch.binary_identity !== null
986
+ && canonicalizeArtifact(await binaryIdentityObserver(executedImage)) !== canonicalizeArtifact(launch.binary_identity)) {
987
+ fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後macOS identity不一致');
988
+ }
989
989
  }
990
990
  } else {
991
991
  if (!path.isAbsolute(handshakeSocket) || await realpath(path.dirname(handshakeSocket)) !== path.dirname(handshakeSocket)) {
@@ -40,7 +40,45 @@ export async function observeStartIdentityRaw(pid) {
40
40
  ? ['-NoProfile', '-NonInteractive', '-Command',
41
41
  `[System.Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime().Ticks`]
42
42
  : ['-o', 'lstart=', '-p', String(pid)];
43
- const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
43
+ try {
44
+ const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
45
+ return stdout.trim();
46
+ } catch (error) {
47
+ // Another account's process denies its handle; its PID may be a reused dead owner's.
48
+ if (process.platform === 'win32') return observeStartIdentitySnapshotRaw(pid);
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ // SYSTEM_PROCESS_INFORMATION: CreateTime at 32, UniqueProcessId at 80 (64-bit) / 68 (32-bit).
54
+ const WINDOWS_PROCESS_SNAPSHOT = `
55
+ using System; using System.Runtime.InteropServices;
56
+ public static class LatticeProcessSnapshot {
57
+ [DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int c, IntPtr b, int l, out int r);
58
+ public static long CreateTime(long pid) {
59
+ for (int length = 1 << 20; ; length *= 2) {
60
+ IntPtr buffer = Marshal.AllocHGlobal(length);
61
+ try {
62
+ int needed; int status = NtQuerySystemInformation(5, buffer, length, out needed);
63
+ if (status == unchecked((int)0xC0000004)) continue;
64
+ if (status != 0) throw new InvalidOperationException("NtQuerySystemInformation " + status);
65
+ for (IntPtr entry = buffer; ; ) {
66
+ if (Marshal.ReadIntPtr(entry, IntPtr.Size == 8 ? 80 : 68).ToInt64() == pid) return Marshal.ReadInt64(entry, 32);
67
+ int next = Marshal.ReadInt32(entry); if (next == 0) break; entry = IntPtr.Add(entry, next);
68
+ }
69
+ throw new ArgumentException("process not running: " + pid);
70
+ } finally { Marshal.FreeHGlobal(buffer); }
71
+ }
72
+ }
73
+ }`;
74
+
75
+ /** win32: handle-free start identity, identical to StartTime UTC ticks (both are the kernel CreateTime). */
76
+ export async function observeStartIdentitySnapshotRaw(pid) {
77
+ const script = `$ErrorActionPreference='Stop'; Add-Type -TypeDefinition '${WINDOWS_PROCESS_SNAPSHOT}'; `
78
+ + `[DateTime]::FromFileTimeUtc([LatticeProcessSnapshot]::CreateTime(${Number(pid)})).Ticks`;
79
+ // EncodedCommand keeps the C# quotes out of Windows command-line quoting.
80
+ const { stdout } = await execFileAsync('pwsh.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
81
+ Buffer.from(script, 'utf16le').toString('base64')], { encoding: 'utf8', env: osObservationEnvironment() });
44
82
  return stdout.trim();
45
83
  }
46
84