@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
@@ -562,13 +562,13 @@ function packetFor({ meta, taskId, baseSha, manifest }) {
562
562
  return packet;
563
563
  }
564
564
 
565
- async function acquirePullLock(runDir, operation, requestId) {
565
+ async function acquirePullLock(runDir, operation, requestId, timeoutMs = 0) {
566
566
  return acquireRuntimeLifecycleLock({
567
567
  lockPath: path.join(runDir, '.pull-intake.lock'),
568
568
  sessionNonceDigest: digestArtifact({ run_dir: runDir, schema: PULL_RUN_META_SCHEMA }),
569
569
  operation,
570
570
  requestId,
571
- timeoutMs: 0,
571
+ timeoutMs,
572
572
  });
573
573
  }
574
574
 
@@ -582,54 +582,94 @@ async function acquireStartBindingLock(repoRoot, operation) {
582
582
  });
583
583
  }
584
584
 
585
- async function activePullIntakesForStart(repoRoot, { planKey, taskId, activationEventDigest }) {
585
+ function boundIntake(state, { planKey, taskId, activationEventDigest }) {
586
+ if (state.closed || state.plan_key !== planKey) return undefined;
587
+ return state.intakes.find((candidate) => candidate.task_id === taskId
588
+ && candidate.activation_event_digest === activationEventDigest
589
+ && candidate.accepted === null);
590
+ }
591
+
592
+ /** Only readable open pull runs can hold an intake; anything else under runs/ is skipped (u03 X1). */
593
+ async function pullRunsBoundToStart(repoRoot, binding) {
586
594
  const root = path.join(repoRoot, '.lattice', 'runs');
587
- let entries;
588
- try { entries = await readdir(root, { withFileTypes: true }); }
589
- catch (error) {
590
- if (error?.code === 'ENOENT') return [];
591
- fail('INVALID_RUN_STORE', 'run store一覧を読めない');
592
- }
593
- const active = [];
595
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
596
+ const bound = [];
597
+ const unreadable = [];
594
598
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
595
- if (!entry.isDirectory() || !identifier(entry.name)) {
596
- fail('INVALID_RUN_STORE', `不正なrun store entry: ${entry.name}`);
597
- }
599
+ if (!entry.isDirectory() || !identifier(entry.name)) continue;
598
600
  const runDir = path.join(root, entry.name);
599
- const mode = await inspectRunMode(runDir);
600
- if (mode.mode !== 'pull') continue;
601
- const stored = await readPullStore(runDir);
602
- const state = project(stored.events, stored.meta);
603
- if (state.closed || state.plan_key !== planKey) continue;
604
- const intake = state.intakes.find((candidate) => candidate.task_id === taskId
605
- && candidate.activation_event_digest === activationEventDigest
606
- && candidate.accepted === null);
607
- if (intake !== undefined) active.push({
608
- run_id: state.run_id,
609
- run_ref: `.lattice/runs/${entry.name}`,
610
- activation_event_digest: intake.activation_event_digest,
611
- });
601
+ try {
602
+ if ((await inspectRunMode(runDir)).mode !== 'pull') continue;
603
+ const stored = await readPullStore(runDir);
604
+ if (boundIntake(project(stored.events, stored.meta), binding) !== undefined) bound.push(runDir);
605
+ } catch { unreadable.push(`.lattice/runs/${entry.name}`); }
606
+ }
607
+ // An unreadable run may still hold an intake for this start: make the leftover visible.
608
+ if (unreadable.length > 0) {
609
+ process.emitWarning(`start撤回で読めないrunを飛ばした: ${unreadable.join(', ')}`,
610
+ { code: 'LATTICE_RETRACT_RUNS_SKIPPED' });
611
+ }
612
+ return bound;
613
+ }
614
+
615
+ /**
616
+ * Detach (resuming a stopped worker first) and release one unaccepted intake under the
617
+ * caller's pull lock, recording each step. A worker that cannot be re-authenticated is
618
+ * not signalled (u03 C25) and the record says so.
619
+ */
620
+ async function releaseIntakeRecorded(runDir, current, intake, actor, reason, detail = {}) {
621
+ if (intake.worker !== null) {
622
+ let resumed = false;
623
+ let signal = intake.worker.stopped ? 'sent' : 'not_needed';
624
+ if (intake.worker.stopped) {
625
+ try { resumed = await signalAttachedWorker(intake, 'SIGCONT'); }
626
+ catch { signal = 'unavailable'; }
627
+ if (signal === 'sent' && !resumed) signal = 'worker_gone';
628
+ }
629
+ if (resumed) {
630
+ current = await appendEvent(runDir, current, buildEvent({
631
+ events: current.events, meta: current.meta, kind: 'worker_resumed', taskId: intake.task_id,
632
+ payload: { released_by: reason },
633
+ }));
634
+ }
635
+ current = await appendEvent(runDir, current, buildEvent({
636
+ events: current.events, meta: current.meta, kind: 'worker_detached', taskId: intake.task_id,
637
+ payload: { detached_by: actor, pid: intake.worker.pid, resumed, reason, signal },
638
+ }));
612
639
  }
613
- return active;
640
+ return appendEvent(runDir, current, buildEvent({
641
+ events: current.events, meta: current.meta, kind: 'intake_released', taskId: intake.task_id,
642
+ payload: { released_by: actor, reason, ...detail },
643
+ }));
614
644
  }
615
645
 
646
+ /**
647
+ * Retracting a start releases every unaccepted intake bound to it and records that (u03 C11).
648
+ * Release happens before Plan's event, so a failed append leaves a start that can be intaken again.
649
+ */
616
650
  export async function withStartRetractionGuard({
617
- repoRoot, planKey, taskId, activationEventDigest, action,
651
+ repoRoot, planKey, taskId, activationEventDigest, action, environment = process.env,
618
652
  }) {
619
653
  if (!identifier(planKey) || !identifier(taskId) || !sha256(activationEventDigest)
620
654
  || typeof action !== 'function') {
621
655
  fail('INVALID_START_RETRACTION', 'start retraction guard入力が不正');
622
656
  }
657
+ const binding = { planKey, taskId, activationEventDigest };
658
+ const actor = optionalActorFromEnvironment(environment);
623
659
  const lock = await acquireStartBindingLock(repoRoot, 'start-retract');
624
660
  try {
625
- const active = await activePullIntakesForStart(repoRoot, {
626
- planKey, taskId, activationEventDigest,
627
- });
628
- if (active.length > 0) {
629
- fail('ACTIVE_PULL_INTAKE', 'active intakeをreleaseしてからstartを撤回すること', {
630
- plan_key: planKey, task_id: taskId, active_intakes: active,
631
- next_action: 'lattice run intake release --run <run_ref> --task <task_id>',
632
- });
661
+ for (const runDir of await pullRunsBoundToStart(repoRoot, binding)) {
662
+ // intake takes pull then binding lock with zero wait, so waiting here cannot deadlock.
663
+ const runLock = await acquirePullLock(runDir, 'retract-release', `retract-${randomUUID()}`, 5000);
664
+ try {
665
+ const current = await readPullStore(runDir);
666
+ const intake = boundIntake(project(current.events, current.meta), binding);
667
+ if (intake !== undefined) {
668
+ await releaseIntakeRecorded(runDir, current, intake, actor, 'start_retracted', {
669
+ target_start_digest: activationEventDigest,
670
+ });
671
+ }
672
+ } finally { await runLock.release(); }
633
673
  }
634
674
  return await action();
635
675
  } finally { await lock.release(); }
@@ -1426,7 +1466,7 @@ export async function landingPullRun({ repoRoot, runDir }) {
1426
1466
  output.result_digest = digestArtifact(output); return output;
1427
1467
  }
1428
1468
 
1429
- export async function closePullRun({ repoRoot, runDir }) {
1469
+ export async function closePullRun({ repoRoot, runDir, environment = process.env }) {
1430
1470
  const lock = await acquirePullLock(runDir, 'close', `close-${randomUUID()}`);
1431
1471
  try {
1432
1472
  let current = await readPullStore(runDir);
@@ -1437,18 +1477,22 @@ export async function closePullRun({ repoRoot, runDir }) {
1437
1477
  landing: await landingPullRun({ repoRoot, runDir }) };
1438
1478
  output.result_digest = digestArtifact(output); return output;
1439
1479
  }
1480
+ // u03 C18: close releases what is still open and records it instead of refusing.
1440
1481
  const incomplete = state.intakes.filter((entry) => entry.accepted === null);
1441
- if (incomplete.length > 0) {
1442
- fail('RUN_NOT_COMPLETE', 'pending/hold中intakeが残っている', {
1443
- task_ids: incomplete.map((entry) => entry.task_id),
1444
- });
1482
+ const actor = optionalActorFromEnvironment(environment);
1483
+ for (const intake of incomplete) {
1484
+ current = await releaseIntakeRecorded(runDir, current, intake, actor, 'run_closed');
1445
1485
  }
1486
+ const releasedTaskIds = incomplete.map((entry) => entry.task_id).sort();
1487
+ const payload = { accepted_task_ids: state.intakes.filter((entry) => entry.accepted !== null)
1488
+ .map((entry) => entry.task_id).sort() };
1489
+ if (releasedTaskIds.length > 0) payload.released_task_ids = releasedTaskIds;
1446
1490
  current = await appendEvent(runDir, current, buildEvent({
1447
- events: current.events, meta: current.meta, kind: 'run_closed',
1448
- payload: { accepted_task_ids: state.intakes.map((entry) => entry.task_id).sort() },
1491
+ events: current.events, meta: current.meta, kind: 'run_closed', payload,
1449
1492
  }));
1450
1493
  const output = { schema: 'lattice.pull_run_close_result.v1', outcome: 'closed',
1451
1494
  run_id: state.run_id, already_closed: false, intake_count: state.intakes.length,
1495
+ released_task_ids: releasedTaskIds,
1452
1496
  landing: await landingPullRun({ repoRoot, runDir }) };
1453
1497
  output.result_digest = digestArtifact(output); return output;
1454
1498
  } finally { await lock.release(); }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { link, lstat, mkdir, open, readFile, readdir, rm, rmdir } from 'node:fs/promises';
2
+ import { link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, utimes } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { fsyncDirectory } from './fs-dir-sync.mjs';
5
5
  import { syncPublishedFile } from './fs-publish.mjs';
@@ -7,6 +7,13 @@ import { observeStartIdentityRaw, observeProcessHostIdentityRaw } from './runtim
7
7
 
8
8
  const hash = (value) => createHash('sha256').update(value).digest('hex');
9
9
  const CLAIM = /^([0-9a-f]{64})-([1-9][0-9]*)-([0-9a-f]{64})-([0-9a-f]{16})$/u;
10
+ // u03 N1/N2: an owner that cannot be proven dead (foreign host, legacy, weak) is abandoned once
11
+ // its heartbeat mtime is older than LOCK_STALE_MS; every holder touches its lock and claim.
12
+ export const LOCK_STALE_MS = 10 * 60_000;
13
+ export const LOCK_HEARTBEAT_MS = 30_000;
14
+ // Weak identity when own observation is unavailable: never PID-recovered, only heartbeat-stale.
15
+ const WEAK = 'unobserved';
16
+ const NO_HARD_LINK = ['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'];
10
17
  let ownStart;
11
18
  let ownHost;
12
19
 
@@ -17,9 +24,7 @@ export class StoreLockError extends Error {
17
24
  this.reason = reason;
18
25
  this.detail = {
19
26
  lock_path: lockPath,
20
- next_action: reason === 'lock_owner_unidentified'
21
- ? `Confirm no writer is running, then manually remove the unidentified lock: ${lockPath}`
22
- : `Retry after the owner releases ${lockPath}; if it cannot, confirm no writer on the recorded host before manually clearing the abandoned lock.`,
27
+ next_action: `Retry after the owner releases ${lockPath}; an owner that stops refreshing it is recovered automatically after ${LOCK_STALE_MS / 60_000} minutes.`,
23
28
  ...detail,
24
29
  };
25
30
  }
@@ -38,51 +43,103 @@ function identified(owner) {
38
43
  }
39
44
 
40
45
  async function processIsDead(pid, startDigest) {
46
+ // Existence first: a PID freed after a failed observation may be reused before a later check.
47
+ try { process.kill(pid, 0); }
48
+ catch (error) { if (error?.code === 'ESRCH') return true; }
41
49
  try {
42
50
  const observed = await observeStartIdentityRaw(pid);
43
51
  if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
44
52
  } catch {
45
- // A failed observation cannot turn an existing PID into a dead owner.
53
+ // A failed observation cannot turn an existing PID into a dead owner, but a PID that
54
+ // vanished meanwhile was a short-lived reuser (Windows reuses PIDs at once): the owner is gone.
55
+ try { process.kill(pid, 0); }
56
+ catch (error) { if (error?.code === 'ESRCH') return true; }
46
57
  }
47
- try { process.kill(pid, 0); return false; }
48
- catch (error) { return error?.code === 'ESRCH'; }
58
+ return false;
49
59
  }
50
60
 
61
+ /** Returns null (absent) or {owner (null when unidentified), stale, info: the judged lstat}. */
51
62
  async function readOwner(lockPath) {
52
63
  try {
53
64
  const info = await lstat(lockPath);
54
- if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) {
55
- throw new StoreLockError('lock_owner_unidentified', lockPath);
56
- }
65
+ const stale = info.mtimeMs < Date.now() - LOCK_STALE_MS;
66
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) return { owner: null, stale, info };
57
67
  let owner;
58
68
  try { owner = JSON.parse(await readFile(lockPath, 'utf8')); }
59
69
  catch (error) {
60
70
  if (error?.code === 'ENOENT') return null;
61
71
  if (!(error instanceof SyntaxError)) throw error;
62
- throw new StoreLockError('lock_owner_unidentified', lockPath);
72
+ return { owner: null, stale, info };
63
73
  }
64
- if (!identified(owner)) throw new StoreLockError('lock_owner_unidentified', lockPath);
65
- return owner;
74
+ return { owner: identified(owner) ? owner : null, stale, info };
66
75
  } catch (error) {
67
76
  if (error?.code === 'ENOENT') return null;
68
77
  throw error;
69
78
  }
70
79
  }
71
80
 
72
- async function ownerIsDead(owner, host) {
73
- return owner.host === host && owner.process_start.platform === process.platform
74
- && processIsDead(owner.pid,
81
+ /** A local identified owner is judged by PID + start only; any other owner by heartbeat staleness. */
82
+ async function abandoned({ owner, stale }, host) {
83
+ if (owner !== null && host !== WEAK && owner.host === host
84
+ && owner.process_start.platform === process.platform) {
85
+ return processIsDead(owner.pid,
75
86
  hash(`${owner.process_start.platform}:${owner.process_start.identity}`));
87
+ }
88
+ return stale;
89
+ }
90
+
91
+ /**
92
+ * Remove only the entry that was judged abandoned. A stale owner may still be alive and
93
+ * release, letting a new owner link in between judgement and removal; that one goes back.
94
+ */
95
+ async function removeJudged(lockPath, judged) {
96
+ const quarantine = `${lockPath}.${randomBytes(8).toString('hex')}.stale`;
97
+ try { await rename(lockPath, quarantine); }
98
+ catch (error) { if (error?.code === 'ENOENT') return; throw error; }
99
+ const moved = await lstat(quarantine).catch((error) => {
100
+ if (error?.code !== 'ENOENT') throw error;
101
+ return null;
102
+ });
103
+ // Swept concurrently: only an entry older than LOCK_STALE_MS is swept, so it was abandoned too.
104
+ if (moved === null) return;
105
+ if (moved.dev === judged.dev && moved.ino === judged.ino && moved.size === judged.size
106
+ && moved.mtimeMs === judged.mtimeMs) {
107
+ await rm(quarantine);
108
+ return;
109
+ }
110
+ try { await link(quarantine, lockPath); }
111
+ catch (error) {
112
+ if (error?.code !== 'EEXIST' && !NO_HARD_LINK.includes(error?.code)) throw error;
113
+ // Both owners stay on disk; the displaced one fails its held-check (lock_lost).
114
+ throw new StoreLockError('store_locked', lockPath, {
115
+ cause: 'lock_recovery_raced', quarantine_path: quarantine,
116
+ next_action: `Retry; ${quarantine} keeps the owner displaced by a racing recovery and is removed by hand only after that owner exits.`,
117
+ });
118
+ }
119
+ await rm(quarantine);
120
+ }
121
+
122
+ function busy(state, lockPath) {
123
+ return new StoreLockError(state.owner === null ? 'lock_owner_unidentified' : 'store_locked', lockPath);
124
+ }
125
+
126
+ async function isStale(entryPath) {
127
+ const info = await lstat(entryPath).catch((error) => {
128
+ if (error?.code !== 'ENOENT') throw error;
129
+ return null;
130
+ });
131
+ return info !== null && info.mtimeMs < Date.now() - LOCK_STALE_MS;
76
132
  }
77
133
 
78
134
  async function removeDeadTemporaries(lockPath, hostDigest) {
79
135
  const prefix = `${path.basename(lockPath)}.`;
80
136
  for (const name of await readdir(path.dirname(lockPath))) {
81
- if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
82
- const parsed = name.slice(prefix.length, -4).match(CLAIM);
83
- if (parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]))
84
- && await processIsDead(Number(parsed[2]), parsed[3])) {
85
- const temporary = path.join(path.dirname(lockPath), name);
137
+ if (!name.startsWith(prefix) || !(name.endsWith('.tmp') || name.endsWith('.stale'))) continue;
138
+ const parsed = name.endsWith('.tmp') ? name.slice(prefix.length, -4).match(CLAIM) : null;
139
+ const temporary = path.join(path.dirname(lockPath), name);
140
+ // A `.stale` quarantine's owner already fails assertHeld; it goes once older than LOCK_STALE_MS.
141
+ const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
142
+ if (local ? await processIsDead(Number(parsed[2]), parsed[3]) : await isStale(temporary)) {
86
143
  const info = await lstat(temporary).catch((error) => {
87
144
  if (error?.code !== 'ENOENT') throw error;
88
145
  return null;
@@ -105,7 +162,7 @@ async function recoveryClaim(claimsPath, owner, lockPath) {
105
162
  catch (error) { if (error?.code !== 'ENOENT') throw error; }
106
163
  }
107
164
  try {
108
- await removeDeadClaims(claimsPath, hostDigest, lockPath);
165
+ await removeDeadClaims(claimsPath, owner.host === WEAK ? null : hostDigest, lockPath);
109
166
  // All claimants publish before inspection; only a sole claimant may recover.
110
167
  // Timestamp ordering could let a delayed earlier publisher enter twice.
111
168
  const candidates = await readdir(claimsPath);
@@ -131,9 +188,9 @@ async function removeDeadClaims(claimsPath, hostDigest, lockPath) {
131
188
  }
132
189
  for (const entry of await readdir(claimsPath, { withFileTypes: true })) {
133
190
  const parsed = entry.name.match(CLAIM);
134
- if (entry.isDirectory() && parsed && parsed[1] === hostDigest
135
- && Number.isSafeInteger(Number(parsed[2]))
136
- && await processIsDead(Number(parsed[2]), parsed[3])) {
191
+ const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
192
+ if (entry.isDirectory() && (local ? await processIsDead(Number(parsed[2]), parsed[3])
193
+ : await isStale(path.join(claimsPath, entry.name)))) {
137
194
  try { await rmdir(path.join(claimsPath, entry.name)); }
138
195
  catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
139
196
  }
@@ -159,28 +216,40 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
159
216
  let identity;
160
217
  let host;
161
218
  try { [identity, host] = await Promise.all([ownStart, ownHost]); }
162
- catch {
163
- throw new StoreLockError('store_locked', lockPath, {
164
- cause: 'lock_identity_unavailable',
165
- next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
166
- });
167
- }
168
- const owner = { pid: process.pid,
219
+ catch { identity = WEAK; host = WEAK; }
220
+ let owner = { pid: process.pid,
169
221
  process_start: { platform: process.platform, identity }, host };
170
- if (!identified(owner)) throw new StoreLockError('store_locked', lockPath, {
171
- cause: 'lock_identity_unavailable',
172
- next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
173
- });
222
+ if (!identified(owner)) {
223
+ host = WEAK;
224
+ owner = { pid: process.pid, process_start: { platform: process.platform, identity: WEAK }, host };
225
+ }
174
226
  const ownerBytes = `${JSON.stringify(owner)}\n`;
175
227
  const temporary = `${lockPath}.${hash(host)}-${owner.pid}-${hash(`${owner.process_start.platform}:${owner.process_start.identity}`)}-${randomBytes(8).toString('hex')}.tmp`;
176
228
  let claimPath = null;
177
229
  let acquired = false;
178
230
  let fileIdentity = null;
179
231
  let callbackEntered = false;
232
+ let heartbeat = null;
233
+ let lost = false;
234
+ const stillOwned = async (current) => {
235
+ if (current === null || !acquired) return false;
236
+ const info = await lstat(current).catch((error) => {
237
+ if (error?.code === 'ENOENT') return null;
238
+ throw error;
239
+ });
240
+ return info !== null && info.isFile() && !info.isSymbolicLink()
241
+ && info.dev === fileIdentity.dev && info.ino === fileIdentity.ino
242
+ && await readFile(current, 'utf8').catch((error) => {
243
+ if (error?.code === 'ENOENT') return null;
244
+ throw error;
245
+ }) === ownerBytes;
246
+ };
180
247
  try {
181
- await removeDeadTemporaries(lockPath, hash(host));
248
+ // A weak writer cannot prove anyone dead by PID; it only clears stale entries.
249
+ const hostDigest = host === WEAK ? null : hash(host);
250
+ await removeDeadTemporaries(lockPath, hostDigest);
182
251
  for (const claimsPath of new Set([recoveryClaimsPath, `${lockPath}.recovery`])) {
183
- await removeDeadClaims(claimsPath, hash(host), lockPath);
252
+ await removeDeadClaims(claimsPath, hostDigest, lockPath);
184
253
  try { await rmdir(claimsPath); }
185
254
  catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
186
255
  }
@@ -193,31 +262,57 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
193
262
  for (;;) {
194
263
  try { await link(temporary, lockPath); acquired = true; break; }
195
264
  catch (error) {
196
- if (['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'].includes(error?.code)) {
197
- throw new StoreLockError('store_locked', lockPath, {
198
- cause: 'lock_publication_unavailable',
199
- next_action: `Use a filesystem permitting atomic hard-link publication for ${lockPath}, then retry`,
200
- });
201
- }
202
- if (error?.code !== 'EEXIST') throw error;
265
+ if (NO_HARD_LINK.includes(error?.code)) {
266
+ // u03: without hard links publish in place; a torn record reads as unidentified and goes stale.
267
+ let direct = null;
268
+ try { direct = await open(lockPath, 'wx', 0o600); }
269
+ catch (openError) { if (openError?.code !== 'EEXIST') throw openError; }
270
+ if (direct !== null) {
271
+ try {
272
+ await direct.writeFile(ownerBytes); await syncPublishedFile(direct, lockPath);
273
+ fileIdentity = await direct.stat();
274
+ } finally { await direct.close(); }
275
+ acquired = true;
276
+ break;
277
+ }
278
+ } else if (error?.code !== 'EEXIST') throw error;
203
279
  }
204
280
  const existing = await readOwner(lockPath);
205
281
  if (existing === null) continue;
206
- if (!await ownerIsDead(existing, host)) throw new StoreLockError('store_locked', lockPath);
282
+ if (!await abandoned(existing, host)) throw busy(existing, lockPath);
207
283
  if (claimPath === null) {
208
284
  claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath);
209
285
  if (onRecoveryClaim) await onRecoveryClaim();
210
286
  }
211
287
  const fresh = await readOwner(lockPath);
212
288
  if (fresh !== null) {
213
- if (!await ownerIsDead(fresh, host)) throw new StoreLockError('store_locked', lockPath);
214
- await rm(lockPath);
289
+ if (!await abandoned(fresh, host)) throw busy(fresh, lockPath);
290
+ await removeJudged(lockPath, fresh.info);
215
291
  }
216
292
  }
217
293
  await rm(temporary);
218
294
  await fsyncDirectory(path.dirname(lockPath));
295
+ // Touch only our own entry: a resumed old holder must not keep a replacement lock fresh.
296
+ heartbeat = setInterval(() => {
297
+ Promise.resolve(releasePath()).then(async (current) => {
298
+ if (current === null) return;
299
+ if (!await stillOwned(current)) { lost = true; clearInterval(heartbeat); return; }
300
+ const now = new Date();
301
+ await Promise.all([utimes(current, now, now),
302
+ claimPath === null ? null : utimes(claimPath, now, now)]);
303
+ }).catch(() => {});
304
+ }, LOCK_HEARTBEAT_MS);
305
+ heartbeat.unref();
219
306
  callbackEntered = true;
220
- return await callback();
307
+ // Callers check right before publishing; the check-to-rename gap is a named residual.
308
+ return await callback(async () => {
309
+ if (!lost && await stillOwned(await releasePath())) return;
310
+ lost = true;
311
+ throw new StoreLockError('store_locked', lockPath, {
312
+ cause: 'lock_lost',
313
+ next_action: `Retry; ${lockPath} was recovered by another writer while this one held it, and nothing was published after the check.`,
314
+ });
315
+ });
221
316
  } catch (error) {
222
317
  if (!callbackEntered && error?.code === 'ENOENT') {
223
318
  throw new StoreLockError('store_locked', lockPath, {
@@ -227,18 +322,10 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
227
322
  }
228
323
  throw error;
229
324
  } finally {
325
+ clearInterval(heartbeat);
230
326
  try {
231
327
  const currentLockPath = await releasePath();
232
- const currentIdentity = currentLockPath === null ? null : await lstat(currentLockPath).catch((error) => {
233
- if (error?.code === 'ENOENT') return null;
234
- throw error;
235
- });
236
- if (acquired && currentIdentity?.isFile() && !currentIdentity.isSymbolicLink()
237
- && currentIdentity.dev === fileIdentity.dev && currentIdentity.ino === fileIdentity.ino
238
- && await readFile(currentLockPath, 'utf8').catch((error) => {
239
- if (error?.code === 'ENOENT') return null;
240
- throw error;
241
- }) === ownerBytes) {
328
+ if (await stillOwned(currentLockPath)) {
242
329
  await rm(currentLockPath);
243
330
  await fsyncDirectory(path.dirname(currentLockPath));
244
331
  }
@@ -10,7 +10,7 @@ import { lstat, readFile, realpath } from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
  import { parseTree } from 'jsonc-parser';
12
12
 
13
- import { todoSelfDigest } from './todo-contracts.mjs';
13
+ import { canonicalizeTodoArtifact, todoSelfDigest } from './todo-contracts.mjs';
14
14
  import { TodoStoreError } from './todo-store.mjs';
15
15
 
16
16
  const MAX_AUTHORING_INPUT_BYTES = 8_388_608;
@@ -29,12 +29,14 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
29
29
  'lattice.plan_create_input.v2': 'input_digest',
30
30
  'lattice.plan_create_input.v3': 'input_digest',
31
31
  'lattice.plan_create_input.v4': 'input_digest',
32
+ 'lattice.plan_create_input.v5': 'input_digest',
32
33
  'lattice.todo_revision.v1': 'revision_digest',
33
34
  'lattice.todo_revision.v2': 'revision_digest',
34
35
  'lattice.phase_todo_revision.v1': 'revision_digest',
35
36
  'lattice.phase_todo_revision.v2': 'revision_digest',
36
37
  'lattice.phase_todo_revision.v3': 'revision_digest',
37
38
  'lattice.phase_todo_revision.v4': 'revision_digest',
39
+ 'lattice.phase_todo_revision.v5': 'revision_digest',
38
40
  'lattice.todo_revision_set.v1': 'revision_set_digest',
39
41
  'lattice.todo_revision_set.v2': 'revision_set_digest',
40
42
  'lattice.todo_revision_set.v3': 'revision_set_digest',
@@ -84,11 +86,64 @@ export function parseAuthoringJson(text, { invalidCode = 'INVALID_JSON' } = {})
84
86
  return null;
85
87
  }
86
88
 
89
+ // todo-contractsのcompareText/refKey/phaseRefKeyと同じ比較。validatorが要求する正準順そのもの。
90
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
91
+ const refKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.task_id}`;
92
+ const phaseRefKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.phase_id}`;
93
+
94
+ /** 正準順へ整列し、完全一致の重複だけを落とす。同じkeyで内容が違うものは残し、validatorに拒否させる。 */
95
+ function sortUnique(list, key) {
96
+ if (!Array.isArray(list)) return list;
97
+ const seen = new Set();
98
+ const kept = [];
99
+ for (const entry of list) {
100
+ const identity = canonicalizeTodoArtifact(entry);
101
+ if (seen.has(identity)) continue;
102
+ seen.add(identity);
103
+ kept.push({ entry, sortKey: key(entry), index: kept.length });
104
+ }
105
+ return kept.sort((left, right) => compareText(left.sortKey, right.sortKey) || left.index - right.index)
106
+ .map(({ entry }) => entry);
107
+ }
108
+
109
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
110
+
111
+ /**
112
+ * plan_create_input.v5だけ: 並びに作成者の意味が無い集合を、入力順に依らず正準形へ寄せる。
113
+ * tasksと他の配列は並べ替えない。形が壊れていれば触らず、validatorの指摘に任せる。
114
+ */
115
+ function normalizeCreateInputV5(value) {
116
+ const normalizers = {
117
+ hard_dependencies: (list) => sortUnique(list, (edge) => `${refKey(edge?.from)}\0${refKey(edge?.to)}`),
118
+ phase_accept_dependencies: (list) => sortUnique(list,
119
+ (edge) => `${phaseRefKey(edge?.from)}\0${refKey(edge?.to)}`),
120
+ joins: (list) => (Array.isArray(list)
121
+ ? sortUnique(list.map((join) => (isRecord(join)
122
+ ? { ...join, after: sortUnique(join.after, refKey) } : join)), (join) => join?.id) : list),
123
+ phases: (list) => (Array.isArray(list)
124
+ ? sortUnique(list.map((phase) => (isRecord(phase) ? {
125
+ ...phase,
126
+ predecessor_phase_ids: sortUnique(phase.predecessor_phase_ids, (id) => id),
127
+ required_evidence_slots: sortUnique(phase.required_evidence_slots, (id) => id),
128
+ } : phase)), (phase) => phase?.phase_id) : list),
129
+ };
130
+ try {
131
+ const next = { ...value };
132
+ for (const [field, normalize] of Object.entries(normalizers)) {
133
+ if (field in next) next[field] = normalize(next[field]);
134
+ }
135
+ return next;
136
+ } catch {
137
+ return value;
138
+ }
139
+ }
140
+
87
141
  export function repairAuthoringArtifact(value) {
88
142
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
89
143
  const field = AUTHORING_DIGEST_FIELDS[value.schema];
90
144
  if (field === undefined) return value;
91
- const next = { ...value, [field]: typeof value[field] === 'string' ? value[field] : '' };
145
+ const base = value.schema === 'lattice.plan_create_input.v5' ? normalizeCreateInputV5(value) : value;
146
+ const next = { ...base, [field]: typeof base[field] === 'string' ? base[field] : '' };
92
147
  next[field] = todoSelfDigest(next, field);
93
148
  return next;
94
149
  }