@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
@@ -4,11 +4,14 @@ import {
4
4
  isPhaselessTodoPlanSchema,
5
5
  projectTodoCrossPlanDependencies,
6
6
  localTaskRef,
7
+ normalizeCheckoutEol,
7
8
  removedTaskRef,
9
+ isFinishedTodoTaskState,
8
10
  todoTaskCarrySemantics as taskSemantics,
9
11
  } from './todo-store-view.mjs';
10
12
  export {
11
13
  isDecoupledPhaseTodoPlanSchema,
14
+ isFinishedTodoTaskState,
12
15
  isPhaseTodoPlanSchema,
13
16
  isPhaselessTodoPlanSchema,
14
17
  projectTodoCrossPlanDependencies,
@@ -81,7 +84,6 @@ const CROSS_PLAN_IMPORT_TRANSACTION_SCHEMA = 'lattice.todo_cross_plan_import_tra
81
84
  const SOURCE_CUTOVER_BARRIER_REF = `${STORE_ROOT_REF}/source-cutover-recovery.json`;
82
85
  const SOURCE_CUTOVER_RECOVERY_CAPABILITY = Symbol('lattice.todo.source-cutover-recovery');
83
86
  const STORE_LOCK_HELD = Symbol('lattice.todo.lock-held');
84
- const MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
85
87
  const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring']);
86
88
  const TODO_REVISION_SCHEMAS = Object.freeze([
87
89
  'lattice.todo_revision.v1', 'lattice.todo_revision.v2',
@@ -162,11 +164,6 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
162
164
  fail(code, bytes.length > maxBytes ? 'size_limit_exceeded' : reason, detail);
163
165
  }
164
166
  const text = decodeUtf8(bytes, code, 'invalid_utf8');
165
- if (text.includes('\r')) {
166
- fail(code, 'artifact_eol_converted', {
167
- ...detail, next_action: 'lattice todo repair-eol --json',
168
- });
169
- }
170
167
  if (text.startsWith('\uFEFF')) fail(code, reason, detail);
171
168
  const body = text.endsWith('\n') ? text.slice(0, -1) : text;
172
169
  let value;
@@ -182,7 +179,7 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
182
179
  async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false }) {
183
180
  const state = await pathState(repoRoot, ref, code, { missing });
184
181
  if (state === null) return null;
185
- const bytes = await readFile(state.absolute);
182
+ const bytes = normalizeCheckoutEol(await readFile(state.absolute));
186
183
  return parseCanonicalJsonLine(bytes, {
187
184
  code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref,
188
185
  });
@@ -191,7 +188,7 @@ async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing =
191
188
  async function readSnapshotArtifact(repoRoot, ref) {
192
189
  const state = await pathState(repoRoot, ref, 'STORE_INCONSISTENT', { missing: true });
193
190
  if (state === null) return null;
194
- const bytes = await readFile(state.absolute);
191
+ const bytes = normalizeCheckoutEol(await readFile(state.absolute));
195
192
  return parseCanonicalJsonLine(bytes, {
196
193
  code: 'SNAPSHOT_INVALID', reason: 'snapshot_truncated_or_trailing_bytes',
197
194
  maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoSnapshot, ref,
@@ -205,11 +202,6 @@ function parseJournalSegment(bytes, ref = null) {
205
202
  ? 'journal_segment_limit_exceeded' : 'journal_empty', detail);
206
203
  }
207
204
  const text = decodeUtf8(bytes, 'STORE_CORRUPT', 'journal_invalid_utf8');
208
- if (text.includes('\r')) {
209
- fail('STORE_CORRUPT', 'artifact_eol_converted', {
210
- ...detail, next_action: 'lattice todo repair-eol --json',
211
- });
212
- }
213
205
  if (!text.endsWith('\n') || text.startsWith('\uFEFF')) fail('STORE_CORRUPT', 'journal_byte_contract', detail);
214
206
  const lines = text.slice(0, -1).split('\n');
215
207
  if (lines.some((line) => line.length === 0)) fail('STORE_CORRUPT', 'journal_truncated_or_empty_line');
@@ -239,7 +231,7 @@ async function readJournal(repoRoot, journalRef) {
239
231
  }
240
232
  const ref = path.posix.join(path.posix.dirname(journalRef), 'sealed', name);
241
233
  const sealed = await pathState(repoRoot, ref, 'STORE_CORRUPT');
242
- const bytes = await readFile(sealed.absolute);
234
+ const bytes = normalizeCheckoutEol(await readFile(sealed.absolute));
243
235
  const [, startText, endText, previousDigest, segmentDigest] = name.match(
244
236
  /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u,
245
237
  );
@@ -257,7 +249,7 @@ async function readJournal(repoRoot, journalRef) {
257
249
  if (error instanceof TodoStoreError) throw error;
258
250
  if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
259
251
  }
260
- const activeBytes = await readFile(state.absolute);
252
+ const activeBytes = normalizeCheckoutEol(await readFile(state.absolute));
261
253
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
262
254
  if (!duplicateActive) {
263
255
  segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
@@ -326,7 +318,7 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
326
318
  try {
327
319
  const state = await lstat(absolute);
328
320
  if (state.isSymbolicLink() || !state.isFile()) fail('STORE_CORRUPT', 'plan_scoped_journal_unsafe');
329
- bytes = await readFile(absolute);
321
+ bytes = normalizeCheckoutEol(await readFile(absolute));
330
322
  } catch (error) {
331
323
  if (error instanceof TodoStoreError) throw error;
332
324
  if (error?.code === 'ENOENT') return { ref, events: [], activeBytes: Buffer.alloc(0) };
@@ -484,7 +476,7 @@ function localSuccessors(plan, taskId) {
484
476
  return plan.tasks.map(({ task_id }) => task_id).filter((candidate) => localPredecessors(plan, candidate).includes(taskId));
485
477
  }
486
478
 
487
- function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSource } = {}) {
479
+ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
488
480
  const states = new Map(plan.tasks.map(({ task_id }) => [task_id, taskState(task_id)]));
489
481
  const phaseStates = new Map(phasesOf(plan).map(({ phase_id }) => [phase_id, emptyPhaseState(phase_id)]));
490
482
  const doneDigest = new Map();
@@ -496,22 +488,12 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
496
488
  // storeを恒久的に書き込み不能へ落とす(2026-08-22実被弾: reopen済み旧doneのdangling blob)。
497
489
  const pendingVerifications = new Map();
498
490
  const importedGenesis = events[0]?.payload.historical_import === true;
499
- let previousTime = null;
500
491
  for (const event of events) {
501
492
  if (event.project_id !== plan.project_id || event.plan_key !== plan.plan_key || event.plan_version !== plan.plan_version) {
502
493
  fail('STORE_CORRUPT', 'journal_identity_mismatch');
503
494
  }
504
495
  if (!isStrictTodoTimestamp(event.recorded_at)) fail('STORE_CORRUPT', 'timestamp_invalid');
505
- const time = Date.parse(event.recorded_at);
506
- if (previousTime !== null && time < previousTime) fail('STORE_INCONSISTENT', 'clock_reversal');
507
- if (time > now.valueOf() + MAX_FUTURE_SKEW_MS) {
508
- fail('STORE_INCONSISTENT', 'future_clock_skew', {
509
- recorded_at: event.recorded_at,
510
- current_time: now.toISOString(),
511
- max_future_skew_ms: MAX_FUTURE_SKEW_MS,
512
- });
513
- }
514
- previousTime = time;
496
+ // u03 A4/A5: order is the sequence + hash chain; recorded_at is a shown fact, never an integrity key.
515
497
  if (event.kind === 'plan_genesis') {
516
498
  if (event.payload.plan_digest !== plan.plan_digest || event.payload.topology_digest !== plan.topology_digest
517
499
  || event.payload.predecessor_plan_digest !== plan.predecessor_plan_digest) {
@@ -657,7 +639,8 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
657
639
  }
658
640
  const state = states.get(event.task_id);
659
641
  if (state === undefined) fail('STORE_INCONSISTENT', 'event_task_missing');
660
- const dependenciesDone = localPredecessors(plan, event.task_id).every((id) => states.get(id)?.status === 'done');
642
+ const dependenciesDone = localPredecessors(plan, event.task_id)
643
+ .every((id) => isFinishedTodoTaskState(states.get(id)));
661
644
  if (event.kind === 'start') {
662
645
  if (event.payload.start_mode === 'rebind') {
663
646
  // 改訂でcarryされたin-progressの再束縛。状態・開始時刻は動かさず、start束縛だけを
@@ -726,9 +709,26 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
726
709
  if (state.status !== 'blocked') fail('STORE_INCONSISTENT', 'invalid_unblock_transition');
727
710
  state.status = 'in-progress'; state.blocked_reason = null;
728
711
  } else if (event.kind === 'retire') {
729
- // 恒久除去はpending/blockedからだけ。in-progressは保持者がretractしてから、doneは撤去対象でない。
730
- if (!['pending', 'blocked'].includes(state.status)) fail('STORE_INCONSISTENT', 'invalid_retire_transition');
712
+ const priorStatus = event.payload.prior_status;
713
+ if (priorStatus === undefined) {
714
+ // legacy payload: pending/blocked only.
715
+ if (!['pending', 'blocked'].includes(state.status)) fail('STORE_INCONSISTENT', 'invalid_retire_transition');
716
+ } else {
717
+ if (state.status === 'retired') fail('STORE_INCONSISTENT', 'invalid_retire_transition');
718
+ if (priorStatus !== state.status) fail('STORE_INCONSISTENT', 'retire_prior_status_mismatch');
719
+ }
720
+ const wasDone = state.status === 'done';
731
721
  state.status = 'retired'; state.blocked_reason = event.payload.reason;
722
+ state.done_at = wasDone ? state.done_at : null;
723
+ // done_at and imported survive a retire from done so the finished mark stays (isFinishedTodoTaskState).
724
+ state.evidence = null; state.test_result = null; state.imported = wasDone ? state.imported : false;
725
+ state.evidence_unverified = false;
726
+ authoredStartBindings.delete(event.task_id);
727
+ if (wasDone) {
728
+ completion.delete(event.task_id);
729
+ pendingVerifications.delete(`task:${event.task_id}`);
730
+ }
731
+ // a retired task is unreachable by promotion/reopen (both require status done), so doneDigest is left as is.
732
732
  } else if (event.kind === 'done') {
733
733
  if (event.payload.done_mode === 'authored') {
734
734
  if (state.status !== 'in-progress' || !dependenciesDone) fail('STORE_INCONSISTENT', 'invalid_done_transition');
@@ -871,13 +871,14 @@ function snapshotFor(plan, events, tasks) {
871
871
  return snapshot;
872
872
  }
873
873
 
874
- function validateMergedGraph(members, crossPlanDependencies = [], options = {}) {
875
- // tolerateStaleBindings は dependency disconnect 専用の修理扉。plan revise が越境依存の
876
- // 固定digestを陳腐化させると、通常loadは binding_stale で fail closed するが、その修理
877
- // コマンド自身も load を要するため、扉が無いと修理経路が存在しない(実被弾 2026-08-29:
878
- // evidence-2 改訂で store 全体が読めなくなり、disconnect も同エラーで詰んだ)。
879
- // 許容するのは digest 不一致だけで、dangling / missing は修理扉でも fail する。
880
- const tolerateStale = options.tolerateStaleBindings === true;
874
+ /**
875
+ * Validates the merged graph and returns cross-plan findings (u03 A24/A25b/N6): a reference into
876
+ * another plan never refuses for a stale digest or a removed endpoint; a removed endpoint's edge
877
+ * is left out of the graph. Same-plan shape and merged cycles still refuse.
878
+ */
879
+ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPlanDependencies(members),
880
+ { newPlanKey = null } = {}) {
881
+ const findings = [];
881
882
  const tasks = new Map();
882
883
  for (const member of members) for (const task of member.plan.tasks) {
883
884
  tasks.set(`${member.plan.project_id}\0${member.plan.plan_key}\0${task.task_id}`, member.plan.topology_digest);
@@ -892,38 +893,43 @@ function validateMergedGraph(members, crossPlanDependencies = [], options = {})
892
893
  adjacency.set(key, []);
893
894
  }
894
895
  }
895
- const bind = (ref, ownerPlan) => {
896
- const key = `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`;
897
- const topology = tasks.get(key);
898
- if (topology === undefined) fail('STORE_INCONSISTENT', 'dangling_dependency');
899
- if ((ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key)
900
- && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
901
- if (!tolerateStale && ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
902
- fail('STORE_INCONSISTENT', 'binding_stale');
896
+ // Returns the node key, or null when a foreign endpoint is gone (the edge is then skipped).
897
+ const bindIn = (nodes, key, ref, ownerPlan, eventDigest, side, danglingReason) => {
898
+ const foreign = ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key;
899
+ const topology = nodes.get(key);
900
+ const finding = (reason) => findings.push({ owner_plan_key: ownerPlan.plan_key,
901
+ event_digest: eventDigest, side, ref: structuredClone(ref), reason });
902
+ // A plan being created is new input: it must name existing endpoints at their current topology.
903
+ const strict = !foreign || ownerPlan.plan_key === newPlanKey;
904
+ if (topology === undefined) {
905
+ if (strict) fail('STORE_INCONSISTENT', danglingReason);
906
+ finding('endpoint_missing');
907
+ return null;
903
908
  }
904
- return key;
905
- };
906
- const bindPhase = (ref, ownerPlan) => {
907
- const key = `phase\0${ref.project_id}\0${ref.plan_key}\0${ref.phase_id}`;
908
- const topology = phases.get(key);
909
- if (topology === undefined) fail('STORE_INCONSISTENT', 'dangling_phase_dependency');
910
- if ((ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key)
911
- && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
912
- if (!tolerateStale && ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
913
- fail('STORE_INCONSISTENT', 'binding_stale');
909
+ if (foreign && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
910
+ if (ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
911
+ if (foreign && ownerPlan.plan_key === newPlanKey) fail('STORE_INCONSISTENT', 'binding_stale');
912
+ finding('binding_stale');
914
913
  }
915
914
  return key;
916
915
  };
916
+ const bind = (ref, ownerPlan, eventDigest = null, side = null) => bindIn(tasks,
917
+ `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`, ref, ownerPlan, eventDigest, side, 'dangling_dependency');
918
+ const bindPhase = (ref, ownerPlan) => bindIn(phases,
919
+ `phase\0${ref.project_id}\0${ref.plan_key}\0${ref.phase_id}`, ref, ownerPlan, null, 'from',
920
+ 'dangling_phase_dependency');
917
921
  for (const { plan } of members) {
918
922
  for (const edge of plan.hard_dependencies) {
919
- const from = bind(edge.from, plan); const to = bind(edge.to, plan);
923
+ const from = bind(edge.from, plan, null, 'from'); const to = bind(edge.to, plan, null, 'to');
924
+ if (from === null || to === null) continue;
920
925
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
921
926
  adjacency.get(from).push(to);
922
927
  }
923
928
  for (const join of plan.joins) {
924
- const before = bind(join.before, plan);
929
+ const before = bind(join.before, plan, null, 'to');
925
930
  for (const afterRef of join.after) {
926
- const after = bind(afterRef, plan);
931
+ const after = bind(afterRef, plan, null, 'from');
932
+ if (before === null || after === null) continue;
927
933
  if (after === before) fail('STORE_INCONSISTENT', 'join_self_edge');
928
934
  adjacency.get(after).push(before);
929
935
  }
@@ -941,7 +947,8 @@ function validateMergedGraph(members, crossPlanDependencies = [], options = {})
941
947
  }
942
948
  }
943
949
  for (const edge of plan.phase_accept_dependencies) {
944
- adjacency.get(bindPhase(edge.from, plan)).push(bind(edge.to, plan));
950
+ const from = bindPhase(edge.from, plan); const to = bind(edge.to, plan, null, 'to');
951
+ if (from !== null && to !== null) adjacency.get(from).push(to);
945
952
  }
946
953
  }
947
954
  }
@@ -949,8 +956,10 @@ function validateMergedGraph(members, crossPlanDependencies = [], options = {})
949
956
  const owner = members.find(({ plan }) => plan.project_id === dependency.to.project_id
950
957
  && plan.plan_key === dependency.to.plan_key);
951
958
  if (owner === undefined) fail('STORE_INCONSISTENT', 'cross_plan_dependency_owner_missing');
952
- const from = bind(dependency.from, owner.plan);
953
- const to = bind(dependency.to, owner.plan);
959
+ const digest = dependency.event_digest ?? null;
960
+ const from = bind(dependency.from, owner.plan, digest, 'from');
961
+ const to = bind(dependency.to, owner.plan, digest, 'to');
962
+ if (from === null || to === null) continue;
954
963
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
955
964
  adjacency.get(from).push(to);
956
965
  }
@@ -961,6 +970,11 @@ function validateMergedGraph(members, crossPlanDependencies = [], options = {})
961
970
  colors.set(node, 1); for (const next of adjacency.get(node)) visit(next); colors.set(node, 2);
962
971
  };
963
972
  for (const node of adjacency.keys()) visit(node);
973
+ // A join binds `before` once per member: keep one finding per identity, in code-unit order.
974
+ const order = (finding) => JSON.stringify([finding.owner_plan_key, finding.event_digest ?? '',
975
+ finding.side, finding.ref.plan_key, finding.ref.task_id ?? finding.ref.phase_id, finding.reason]);
976
+ return [...new Map(findings.map((finding) => [canonicalizeTodoArtifact(finding), finding])).values()]
977
+ .sort((left, right) => (order(left) < order(right) ? -1 : order(left) > order(right) ? 1 : 0));
964
978
  }
965
979
 
966
980
  function crossPlanDependencyTask(store, ref) {
@@ -1332,9 +1346,9 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1332
1346
 
1333
1347
  function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache = null) {
1334
1348
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1335
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(plan.schema)) return;
1349
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) return;
1336
1350
  const trusted = new Map((['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1337
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(trustedPlan?.schema)
1351
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(trustedPlan?.schema)
1338
1352
  ? trustedPlan.tasks : [])
1339
1353
  .map((task) => [task.task_id, task.narrative_anchor]));
1340
1354
  for (const task of plan.tasks) {
@@ -1397,6 +1411,9 @@ async function readTodoStoreLocked(options = {}) {
1397
1411
  await recoverCrossPlanImports(repoRoot);
1398
1412
  const recovery = { manifestDirty: false };
1399
1413
  const store = await readTodoStoreView({ ...options, recovery });
1414
+ if (options.assertHeld) {
1415
+ store.cross_plan_repairs = await repairCrossPlanBindings(repoRoot, store, options.repairContext);
1416
+ }
1400
1417
  // Every member and merged graph has validated before any derived publication.
1401
1418
  for (const member of store.members) {
1402
1419
  if (!member.snapshot_stale) continue;
@@ -1532,8 +1549,8 @@ async function readTodoStoreView(options = {}) {
1532
1549
  snapshotStale = snapshot === null || canonicalizeTodoArtifact(snapshot) !== canonicalizeTodoArtifact(expectedSnapshot);
1533
1550
  } catch (error) {
1534
1551
  if (error instanceof TodoStoreError && error.code === 'SNAPSHOT_INVALID'
1535
- && !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store',
1536
- 'artifact_eol_converted'].includes(error.detail.reason)) snapshotStale = true;
1552
+ && !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store']
1553
+ .includes(error.detail.reason)) snapshotStale = true;
1537
1554
  else throw error;
1538
1555
  }
1539
1556
  if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
@@ -1549,16 +1566,136 @@ async function readTodoStoreView(options = {}) {
1549
1566
  snapshot: snapshotStale ? expectedSnapshot : snapshot,
1550
1567
  tasks, phases, coordination, snapshot_stale: snapshotStale });
1551
1568
  }
1552
- validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded), {
1553
- tolerateStaleBindings: options.tolerateStaleBindings === true,
1554
- });
1569
+ const crossPlanFindings = validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded));
1555
1570
  return {
1556
1571
  schema: 'lattice.todo_store_read.v1', project_id: manifest.project_id, manifest,
1557
1572
  members: loaded, snapshot_stale: loaded.some((member) => member.snapshot_stale),
1573
+ cross_plan_findings: crossPlanFindings,
1558
1574
  };
1559
1575
  }
1560
1576
 
1577
+ /**
1578
+ * Composes the source plan's recorded task migrations back to the version whose topology the
1579
+ * connection names (u03): returns the source task id it maps to now, 'removed', or null (unknown).
1580
+ */
1581
+ async function carriedSourceTask(repoRoot, source, ref, versionsCache) {
1582
+ if (!versionsCache.has(source)) {
1583
+ const base = `${STORE_ROOT_REF}/plans/${source.plan.plan_key}`;
1584
+ const byDigest = new Map();
1585
+ let names = [];
1586
+ try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1587
+ for (const version of names) {
1588
+ if (version === source.plan.plan_version || !isTodoIdentifier(version)) continue;
1589
+ const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1590
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1591
+ }).catch(() => null);
1592
+ if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1593
+ }
1594
+ versionsCache.set(source, byDigest);
1595
+ }
1596
+ const byDigest = versionsCache.get(source);
1597
+ // Newest first: the active genesis maps its predecessor's ids onto the active ids.
1598
+ const migrations = [source.journal.events[0].payload.task_migration ?? []];
1599
+ for (let plan = source.plan; migrations.length <= byDigest.size;) {
1600
+ const predecessor = byDigest.get(plan.predecessor_plan_digest);
1601
+ if (predecessor === undefined) return null;
1602
+ if (predecessor.plan.topology_digest === ref.expected_topology_digest) {
1603
+ let taskId = ref.task_id;
1604
+ for (const migration of migrations.reverse()) {
1605
+ const entry = migration.find(({ from_task_id: from }) => from === taskId);
1606
+ if (entry === undefined) return null;
1607
+ if (entry.to_task_id === 'removed') return 'removed';
1608
+ taskId = entry.to_task_id;
1609
+ }
1610
+ return taskId;
1611
+ }
1612
+ let journal;
1613
+ try { journal = await readJournal(repoRoot, predecessor.journalRef); } catch { return null; }
1614
+ migrations.push(journal.events[0].payload.task_migration ?? []);
1615
+ plan = predecessor.plan;
1616
+ }
1617
+ return null;
1618
+ }
1619
+
1620
+ /**
1621
+ * u03 A24/A25b: a live connection whose source plan was revised follows the source's recorded
1622
+ * task migrations (Plan's revision decision, the carry proof): carried -> tombstone + replacement,
1623
+ * removed -> tombstone. A repair that would duplicate an edge or close a cycle is dropped alone and
1624
+ * stays a finding; the rest publish once per owner chain and update the in-memory store.
1625
+ */
1626
+ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, recordedAt }) {
1627
+ const stale = (store.cross_plan_findings ?? []).filter(({ event_digest: digest, side }) => (
1628
+ digest !== null && side === 'from'));
1629
+ if (stale.length === 0) return [];
1630
+ const live = new Map(projectTodoCrossPlanDependencies(store.members)
1631
+ .map((dependency) => [dependency.event_digest, dependency]));
1632
+ const versionsCache = new Map();
1633
+ const staged = new Map();
1634
+ const repairs = [];
1635
+ let findings = store.cross_plan_findings;
1636
+ for (const finding of stale) {
1637
+ const dependency = live.get(finding.event_digest);
1638
+ const source = store.members.find(({ plan }) => plan.project_id === finding.ref.project_id
1639
+ && plan.plan_key === finding.ref.plan_key);
1640
+ const owner = store.members.find(({ plan_scoped: chain }) => (chain?.events ?? [])
1641
+ .some(({ event_digest: digest }) => digest === finding.event_digest));
1642
+ if (!dependency || !source || !owner) continue;
1643
+ const mapped = await carriedSourceTask(repoRoot, source, dependency.from, versionsCache);
1644
+ if (mapped === null) continue;
1645
+ if (!staged.has(owner)) {
1646
+ staged.set(owner, { ...owner, plan_scoped: { ...owner.plan_scoped,
1647
+ events: [...owner.plan_scoped.events], activeBytes: owner.plan_scoped.activeBytes } });
1648
+ }
1649
+ const target = staged.get(owner);
1650
+ const before = { events: target.plan_scoped.events.length, activeBytes: target.plan_scoped.activeBytes };
1651
+ const inputs = [{ kind: 'cross_plan_dependency_removed', payload: {
1652
+ target_event_digest: dependency.event_digest,
1653
+ reason: `source ${source.plan.plan_key} ${source.plan.plan_version} ${mapped === 'removed'
1654
+ ? 'removed the task' : 'carried the task'}`,
1655
+ } }];
1656
+ if (mapped !== 'removed') inputs.push({ kind: 'cross_plan_dependency', payload: {
1657
+ from: { ...dependency.from, task_id: mapped, expected_topology_digest: source.plan.topology_digest },
1658
+ to: dependency.to, reason: dependency.reason,
1659
+ } });
1660
+ for (const input of inputs) {
1661
+ const event = buildPlanScopedEvent(target, { ...input, actor, recorded_at: recordedAt });
1662
+ target.plan_scoped.activeBytes = Buffer.concat([target.plan_scoped.activeBytes,
1663
+ planScopedEventBytes(target, event)]);
1664
+ target.plan_scoped.events.push(event);
1665
+ }
1666
+ const prospective = store.members.map((member) => staged.get(member) ?? member);
1667
+ const keys = projectTodoCrossPlanDependencies(prospective)
1668
+ .map(({ from, to }) => `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`);
1669
+ try {
1670
+ if (new Set(keys).size !== keys.length) fail('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate');
1671
+ findings = validateMergedGraph(prospective);
1672
+ } catch (error) {
1673
+ if (!(error instanceof TodoStoreError)) throw error;
1674
+ target.plan_scoped.events.length = before.events;
1675
+ target.plan_scoped.activeBytes = before.activeBytes;
1676
+ continue;
1677
+ }
1678
+ repairs.push({ owner_plan_key: owner.plan.plan_key, original_event_digest: dependency.event_digest,
1679
+ replacement_event_digest: mapped === 'removed' ? null : target.plan_scoped.events.at(-1).event_digest,
1680
+ action: mapped === 'removed' ? 'tombstoned' : 'rebound' });
1681
+ }
1682
+ if (repairs.length === 0) return [];
1683
+ await assertHeld();
1684
+ for (const [owner, target] of staged) {
1685
+ if (target.plan_scoped.events.length === owner.plan_scoped.events.length) continue;
1686
+ await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), target.plan_scoped.activeBytes);
1687
+ owner.plan_scoped = target.plan_scoped;
1688
+ owner.coordination = projectTodoCoordination(target.plan_scoped.events);
1689
+ }
1690
+ store.cross_plan_findings = findings;
1691
+ return repairs;
1692
+ }
1693
+
1561
1694
  export async function readTodoStoreStable(options = {}) {
1695
+ return readStoreStableWith(options, readTodoStore);
1696
+ }
1697
+
1698
+ async function readStoreStableWith(options, readStore) {
1562
1699
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1563
1700
  const maximumAttempts = options.maximumAttempts ?? 4;
1564
1701
  if (!Number.isSafeInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 16) {
@@ -1575,7 +1712,7 @@ export async function readTodoStoreStable(options = {}) {
1575
1712
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1576
1713
  });
1577
1714
  try {
1578
- const store = await readTodoStore(options);
1715
+ const store = await readStore(options);
1579
1716
  const after = await readArtifact(repoRoot, MANIFEST_REF, {
1580
1717
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1581
1718
  });
@@ -1605,6 +1742,260 @@ export async function readTodoStoreStable(options = {}) {
1605
1742
  fail('STORE_BUSY', 'stable_read_exhausted', { attempts: maximumAttempts });
1606
1743
  }
1607
1744
 
1745
+ // Store display read (dfd-store-display-read.md). Read-only toward canonical Store files:
1746
+ // no lock, recovery or writer; the only write is the derived checkpoint below.
1747
+ const DISPLAY_CHECKPOINT_REF = '.lattice/generated/store-display/last-verified.json';
1748
+ const DISPLAY_CHECKPOINT_SCHEMA = 'lattice.todo_store_display_checkpoint.v1';
1749
+ const DISPLAY_SOURCE_SCHEMA = 'lattice.todo_store_display_source.v1';
1750
+ const DISPLAY_CHECKPOINT_MAX_BYTES = 64 * 1_048_576;
1751
+
1752
+ const nullableString = (value) => (typeof value === 'string' ? value : null);
1753
+
1754
+ /** Any display-read error as public {code, detail}; an untyped fault is warned server-side only. */
1755
+ function displayFault(error) {
1756
+ if (error instanceof TodoStoreError) return { code: error.code, detail: { ...error.detail } };
1757
+ process.emitWarning(`Store display read fault: ${error?.stack ?? error}`, { code: 'LATTICE_STORE_DISPLAY_READ_FAULT' });
1758
+ return { code: 'STORE_READ_FAULT', detail: { reason: 'unexpected_error' } };
1759
+ }
1760
+
1761
+ function displayFailure(error) {
1762
+ const { code, detail } = displayFault(error);
1763
+ return { code, reason: detail.reason ?? null };
1764
+ }
1765
+
1766
+ async function canonicalRepoRoot(repoRoot) {
1767
+ try { return await realpath(repoRoot); } catch { return path.resolve(repoRoot); }
1768
+ }
1769
+
1770
+ /** Bounded raw bytes of a contained `.lattice/todo` file; no schema or digest checks. */
1771
+ async function readRawStoreFile(repoRoot, ref, maxBytes, { missing = false } = {}) {
1772
+ if (typeof ref !== 'string') fail('STORE_INCONSISTENT', 'ref_invalid');
1773
+ const state = await pathState(repoRoot, ref, 'STORE_INCONSISTENT', { missing });
1774
+ if (state === null) return null;
1775
+ if (state.stats.size > maxBytes) fail('STORE_INCONSISTENT', 'size_limit_exceeded', { ref });
1776
+ try { return await readFile(state.absolute); } catch { fail('STORE_INCONSISTENT', 'artifact_read_failed', { ref }); }
1777
+ }
1778
+
1779
+ async function readRawStoreJson(repoRoot, ref, maxBytes) {
1780
+ const bytes = await readRawStoreFile(repoRoot, ref, maxBytes);
1781
+ const text = decodeUtf8(bytes, 'STORE_INCONSISTENT', 'invalid_utf8');
1782
+ try { return JSON.parse(text); } catch { fail('STORE_INCONSISTENT', 'json_invalid', { ref }); }
1783
+ }
1784
+
1785
+ async function rawLastEventDigest(repoRoot, ref, { missing = false } = {}) {
1786
+ const bytes = await readRawStoreFile(repoRoot, ref, TODO_LIMITS.journalSegmentBytes, { missing });
1787
+ if (bytes === null) return null;
1788
+ const lines = decodeUtf8(bytes, 'STORE_INCONSISTENT', 'invalid_utf8').split('\n').filter(Boolean);
1789
+ let digest;
1790
+ try { digest = JSON.parse(lines.at(-1)).event_digest; } catch { fail('STORE_INCONSISTENT', 'json_invalid', { ref }); }
1791
+ if (typeof digest !== 'string') fail('STORE_INCONSISTENT', 'event_digest_missing', { ref });
1792
+ return digest;
1793
+ }
1794
+
1795
+ async function readRawManifest(repoRoot) {
1796
+ const manifest = await readRawStoreJson(repoRoot, MANIFEST_REF, TODO_LIMITS.snapshotBytes);
1797
+ if (manifest === null || typeof manifest !== 'object' || !Array.isArray(manifest.members)) {
1798
+ fail('STORE_INCONSISTENT', 'manifest_members_unenumerable', { ref: MANIFEST_REF });
1799
+ }
1800
+ return manifest;
1801
+ }
1802
+
1803
+ function sortDisplayMembers(members) {
1804
+ return members.sort((left, right) => String(left.plan_key).localeCompare(String(right.plan_key)));
1805
+ }
1806
+
1807
+ async function observeDisplaySource(repoRoot, manifest) {
1808
+ const diagnostics = [];
1809
+ const members = [];
1810
+ for (const descriptor of manifest.members) {
1811
+ const entry = descriptor !== null && typeof descriptor === 'object' ? descriptor : {};
1812
+ const planKey = nullableString(entry.plan_key);
1813
+ const observe = async (field, read) => {
1814
+ try { return await read(); } catch (error) {
1815
+ diagnostics.push({ plan_key: planKey, field, ...displayFailure(error) });
1816
+ return null;
1817
+ }
1818
+ };
1819
+ const journalRef = nullableString(entry.journal_ref);
1820
+ members.push({
1821
+ plan_key: planKey,
1822
+ active_plan_version: nullableString(entry.active_plan_version),
1823
+ plan_digest: await observe('plan_digest', async () => {
1824
+ const digest = (await readRawStoreJson(repoRoot, entry.plan_ref, TODO_LIMITS.snapshotBytes))?.plan_digest;
1825
+ if (typeof digest !== 'string') fail('STORE_INCONSISTENT', 'plan_digest_missing');
1826
+ return digest;
1827
+ }),
1828
+ topology_digest: nullableString(entry.topology_digest),
1829
+ lifecycle_head: await observe('lifecycle_head', () => rawLastEventDigest(repoRoot, journalRef)),
1830
+ plan_scoped_head: journalRef === null ? null : await observe('plan_scoped_head', () => (
1831
+ rawLastEventDigest(repoRoot, planScopedJournalRef(journalRef), { missing: true }))),
1832
+ });
1833
+ }
1834
+ return {
1835
+ schema: DISPLAY_SOURCE_SCHEMA,
1836
+ repository_identity: sha256Bytes(Buffer.from(await canonicalRepoRoot(repoRoot), 'utf8')),
1837
+ project_id: nullableString(manifest.project_id),
1838
+ manifest_digest: nullableString(manifest.manifest_digest),
1839
+ members: sortDisplayMembers(members),
1840
+ diagnostics,
1841
+ };
1842
+ }
1843
+
1844
+ async function verifiedDisplaySource(repoRoot, store) {
1845
+ return {
1846
+ schema: DISPLAY_SOURCE_SCHEMA,
1847
+ repository_identity: sha256Bytes(Buffer.from(await canonicalRepoRoot(repoRoot), 'utf8')),
1848
+ project_id: store.project_id,
1849
+ manifest_digest: store.manifest.manifest_digest,
1850
+ members: sortDisplayMembers(store.members.map(({ descriptor, plan, journal, plan_scoped: planScoped }) => ({
1851
+ plan_key: descriptor.plan_key,
1852
+ active_plan_version: descriptor.active_plan_version,
1853
+ plan_digest: plan.plan_digest,
1854
+ topology_digest: descriptor.topology_digest,
1855
+ lifecycle_head: journal.events.at(-1).event_digest,
1856
+ plan_scoped_head: planScoped.events.at(-1)?.event_digest ?? null,
1857
+ }))),
1858
+ diagnostics: [],
1859
+ };
1860
+ }
1861
+
1862
+ /** The existing read model without implementation bytes; JSON-serializable. */
1863
+ function displayStoreView(store) {
1864
+ return JSON.parse(JSON.stringify({
1865
+ schema: store.schema, project_id: store.project_id, manifest: store.manifest,
1866
+ members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => ({
1867
+ ...member,
1868
+ journal: { events: journal.events },
1869
+ plan_scoped: { ref: planScoped.ref, events: planScoped.events },
1870
+ })),
1871
+ }));
1872
+ }
1873
+
1874
+ function checkpointDigest(checkpoint) {
1875
+ const { checkpoint_digest: _digest, ...body } = checkpoint;
1876
+ return sha256Bytes(Buffer.from(JSON.stringify(body), 'utf8'));
1877
+ }
1878
+
1879
+ /**
1880
+ * Returns the checkpoint attributable to this repository, or null. Never writes.
1881
+ * A readable current projectId must match; without one (broken manifest) the realpath
1882
+ * repository identity attributes it, since the file lives in this repository's .lattice.
1883
+ */
1884
+ async function readDisplayCheckpoint(repoRoot, projectId) {
1885
+ const root = await canonicalRepoRoot(repoRoot);
1886
+ const absolute = path.resolve(root, DISPLAY_CHECKPOINT_REF);
1887
+ let checkpoint;
1888
+ try {
1889
+ const stats = await lstat(absolute);
1890
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.size > DISPLAY_CHECKPOINT_MAX_BYTES) return null;
1891
+ if (await realpath(absolute) !== absolute) return null;
1892
+ checkpoint = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readFile(absolute)));
1893
+ } catch { return null; }
1894
+ const valid = exactRecord(checkpoint, ['schema', 'verified_at', 'source', 'store', 'checkpoint_digest'])
1895
+ && checkpoint.schema === DISPLAY_CHECKPOINT_SCHEMA
1896
+ && isStrictTodoTimestamp(checkpoint.verified_at)
1897
+ && checkpoint.checkpoint_digest === checkpointDigest(checkpoint)
1898
+ && checkpoint.source?.schema === DISPLAY_SOURCE_SCHEMA
1899
+ && checkpoint.source.repository_identity === sha256Bytes(Buffer.from(root, 'utf8'))
1900
+ && typeof checkpoint.source.project_id === 'string'
1901
+ && (typeof projectId !== 'string' || checkpoint.source.project_id === projectId)
1902
+ && checkpoint.store?.project_id === checkpoint.source.project_id && Array.isArray(checkpoint.store.members);
1903
+ return valid ? checkpoint : null;
1904
+ }
1905
+
1906
+ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
1907
+ const root = await canonicalRepoRoot(repoRoot);
1908
+ let directory = root;
1909
+ for (const segment of path.posix.dirname(DISPLAY_CHECKPOINT_REF).split('/')) {
1910
+ directory = path.join(directory, segment);
1911
+ if (segment !== '.lattice') await mkdir(directory).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
1912
+ const stats = await lstat(directory);
1913
+ if (stats.isSymbolicLink() || !stats.isDirectory() || await realpath(directory) !== directory) {
1914
+ fail('STORE_DISPLAY_CHECKPOINT_UNSAFE', 'unsafe_checkpoint_directory', { ref: path.relative(root, directory) });
1915
+ }
1916
+ }
1917
+ const checkpoint = { schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store, checkpoint_digest: '' };
1918
+ checkpoint.checkpoint_digest = checkpointDigest(checkpoint);
1919
+ await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_REF), Buffer.from(JSON.stringify(checkpoint), 'utf8'));
1920
+ }
1921
+
1922
+ async function readRawDisplayMembers(repoRoot, manifest) {
1923
+ const members = [];
1924
+ const dropped = [];
1925
+ for (const descriptor of manifest.members) {
1926
+ const entry = descriptor !== null && typeof descriptor === 'object' ? descriptor : {};
1927
+ const planKey = nullableString(entry.plan_key);
1928
+ let snapshot;
1929
+ try { snapshot = await readRawStoreJson(repoRoot, entry.snapshot_ref, TODO_LIMITS.snapshotBytes); } catch (error) {
1930
+ dropped.push({ plan_key: planKey, snapshot_ref: nullableString(entry.snapshot_ref), ...displayFailure(error) });
1931
+ continue;
1932
+ }
1933
+ // Plans are immutable per version; an unreadable plan drops only the plan, not the member.
1934
+ let plan = null;
1935
+ try { plan = await readRawStoreJson(repoRoot, entry.plan_ref, TODO_LIMITS.snapshotBytes); } catch (error) {
1936
+ dropped.push({ plan_key: planKey, plan_ref: nullableString(entry.plan_ref), ...displayFailure(error) });
1937
+ }
1938
+ members.push({ descriptor, plan, snapshot });
1939
+ }
1940
+ return { members, dropped };
1941
+ }
1942
+
1943
+ /** Cheap unverified change hint for display polling; never validation or recovery. */
1944
+ export async function readTodoStoreDisplaySource({ repoRoot = process.cwd() } = {}) {
1945
+ const root = path.resolve(repoRoot);
1946
+ return observeDisplaySource(root, await readRawManifest(root));
1947
+ }
1948
+
1949
+ /** Display-only envelope: verified > unverified current raw > last_verified > unavailable. */
1950
+ export async function readTodoStoreForDisplay({ repoRoot = process.cwd(), now } = {}) {
1951
+ const root = path.resolve(repoRoot);
1952
+ const verifiedAt = new Date(now ?? Date.now()).toISOString();
1953
+ let inconsistency;
1954
+ try {
1955
+ const strict = await readStoreStableWith({ repoRoot: root, now }, readTodoStoreView);
1956
+ const store = displayStoreView(strict);
1957
+ const source = await verifiedDisplaySource(root, strict);
1958
+ try {
1959
+ const retained = await readDisplayCheckpoint(root, source.project_id);
1960
+ if (JSON.stringify(retained?.source) !== JSON.stringify(source)) {
1961
+ await publishDisplayCheckpoint(root, { verified_at: verifiedAt, source, store });
1962
+ }
1963
+ } catch (error) {
1964
+ process.emitWarning(`Store display checkpoint was not published: ${error?.detail?.reason ?? error?.code ?? error}`, {
1965
+ code: 'LATTICE_STORE_DISPLAY_CHECKPOINT_PUBLICATION_FAILED',
1966
+ });
1967
+ }
1968
+ return { state: 'verified', store, verified_at: verifiedAt, source, inconsistency: null, dropped_members: [] };
1969
+ } catch (error) {
1970
+ inconsistency = displayFault(error);
1971
+ }
1972
+ let manifest = null;
1973
+ try { manifest = await readRawManifest(root); } catch (error) { displayFault(error); }
1974
+ let dropped = [];
1975
+ if (manifest !== null) {
1976
+ const raw = await readRawDisplayMembers(root, manifest);
1977
+ dropped = raw.dropped;
1978
+ if (raw.members.length > 0) {
1979
+ return {
1980
+ state: 'unverified',
1981
+ store: { project_id: nullableString(manifest.project_id), manifest, members: raw.members },
1982
+ verified_at: null,
1983
+ source: await observeDisplaySource(root, manifest),
1984
+ inconsistency,
1985
+ dropped_members: dropped,
1986
+ };
1987
+ }
1988
+ }
1989
+ const checkpoint = await readDisplayCheckpoint(root, nullableString(manifest?.project_id));
1990
+ if (checkpoint !== null) {
1991
+ return {
1992
+ state: 'last_verified', store: checkpoint.store, verified_at: checkpoint.verified_at,
1993
+ source: checkpoint.source, inconsistency, dropped_members: dropped,
1994
+ };
1995
+ }
1996
+ return { state: 'unavailable', store: null, verified_at: null, source: null, inconsistency, dropped_members: dropped };
1997
+ }
1998
+
1608
1999
  async function atomicWrite(absolute, bytes) {
1609
2000
  await mkdir(path.dirname(absolute), { recursive: true });
1610
2001
  const temporary = path.join(path.dirname(absolute), `.${path.basename(absolute)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
@@ -1642,9 +2033,23 @@ async function atomicWriteMode(absolute, bytes, mode) {
1642
2033
 
1643
2034
 
1644
2035
  async function withLock(repoRoot, callback, {
1645
- onProtocolStage = null, lockCapability = null, initialize = false,
2036
+ onProtocolStage = null, lockCapability = null, initialize = false, repairAfter = null,
1646
2037
  } = {}) {
1647
- if (lockCapability === STORE_LOCK_HELD) return callback();
2038
+ if (lockCapability === STORE_LOCK_HELD) return callback(async () => {});
2039
+ // u03 A24/A25b: a successor writer rebinds or tombstones the connections it left stale.
2040
+ const run = repairAfter === null ? callback : async (assertHeld) => {
2041
+ const result = await callback(assertHeld);
2042
+ // The successor is already published: a failed repair leaves findings for the next locked write.
2043
+ try {
2044
+ const repairs = await repairCrossPlanBindings(repoRoot, await readTodoStoreView({ repoRoot }),
2045
+ { assertHeld, actor: repairAfter.actor, recordedAt: repairAfter.recordedAt ?? new Date().toISOString() });
2046
+ // Results stay digest-bound; the caller learns the repairs through its own callback.
2047
+ if (repairs.length > 0 && typeof repairAfter.onRepairs === 'function') await repairAfter.onRepairs(repairs);
2048
+ } catch (error) {
2049
+ if (!(error instanceof TodoStoreError || error instanceof StoreLockError)) throw error;
2050
+ }
2051
+ return result;
2052
+ };
1648
2053
  try {
1649
2054
  if (!initialize) {
1650
2055
  const root = await lstat(path.join(repoRoot, STORE_ROOT_REF)).catch((error) => {
@@ -1666,7 +2071,7 @@ async function withLock(repoRoot, callback, {
1666
2071
  recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
1667
2072
  onRecoveryClaim: typeof onProtocolStage === 'function'
1668
2073
  ? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
1669
- }, callback);
2074
+ }, run);
1670
2075
  } catch (error) {
1671
2076
  if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
1672
2077
  throw error;
@@ -1813,83 +2218,17 @@ function resolveCanonicalTaskId(plan, requestedTaskId) {
1813
2218
  return matches[0].task_id;
1814
2219
  }
1815
2220
 
1816
- async function enforceTodoStructureLifecycleGate(repoRoot, member, eventInput) {
1817
- if (eventInput.kind === 'done') return;
1818
- const binding = await readTodoStructureBinding({
1819
- repoRoot, planKey: member.plan.plan_key, planVersion: member.plan.plan_version,
1820
- });
1821
- if (binding === null) return;
1822
- const source = await readTodoStructureSource({ repoRoot, planKey: member.plan.plan_key });
1823
- if (source === null || source.structure_set_digest !== binding.structure_set_digest) {
1824
- fail('STRUCTURE_LIFECYCLE_GATE_FAILED', 'enabled_structure_source_unreadable');
1825
- }
1826
- if (!['phase_accept', 'phase_close_unaudited'].includes(eventInput.kind)
1827
- || member.tasks.some(({ status }) => status !== 'done')) return;
1828
- const finalization = await readTodoStructureFinalization({
1829
- repoRoot, planKey: member.plan.plan_key, planVersion: member.plan.plan_version,
1830
- });
1831
- if (finalization === null) {
1832
- fail('STRUCTURE_FINALIZATION_REQUIRED', 'fresh_consistent_finalization_missing', {
1833
- plan_key: member.plan.plan_key,
1834
- next_action: `lattice todo structure finalize --plan ${member.plan.plan_key} --json`,
1835
- });
1836
- }
1837
- let currentHead;
1838
- try {
1839
- currentHead = gitSync(['rev-parse', '--verify', 'HEAD^{commit}'], {
1840
- cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
1841
- }).trim();
1842
- } catch {
1843
- fail('STRUCTURE_GIT_HEAD_UNAVAILABLE', 'current_head_unavailable');
1844
- }
1845
- const realizationHeads = [];
1846
- for (const task of source.tasks.filter(({ applicability }) => applicability === 'graph')) {
1847
- const chain = await readTodoStructureRealizationChain({
1848
- repoRoot, structureSet: source, taskId: task.task_id,
1849
- });
1850
- const head = chain.at(-1);
1851
- if (head !== undefined) realizationHeads.push({
1852
- task_id: task.task_id, sequence: head.sequence,
1853
- realization_digest: head.realization_digest,
1854
- });
1855
- }
1856
- const staleReasons = [];
1857
- if (finalization.project_id !== member.plan.project_id) staleReasons.push('project_id');
1858
- if (finalization.plan_key !== member.plan.plan_key) staleReasons.push('plan_key');
1859
- if (finalization.plan_version !== member.plan.plan_version) staleReasons.push('plan_version');
1860
- if (finalization.topology_digest !== member.plan.topology_digest) {
1861
- staleReasons.push('topology_digest');
1862
- }
1863
- if (finalization.structure_set_digest !== source.structure_set_digest) {
1864
- staleReasons.push('structure_set_digest');
1865
- }
1866
- if (finalization.current_head_sha !== currentHead) staleReasons.push('current_head_sha');
1867
- if (finalization.realization_head_digest
1868
- !== digestTodoStructureRealizationHeads(realizationHeads)) {
1869
- staleReasons.push('realization_head_digest');
1870
- }
1871
- if (finalization.overlay.verdict !== 'consistent') staleReasons.push('verdict');
1872
- if (staleReasons.length > 0) {
1873
- fail('STRUCTURE_FINALIZATION_REQUIRED', 'finalization_stale', {
1874
- plan_key: member.plan.plan_key, stale_reasons: staleReasons.sort(),
1875
- next_action: `lattice todo structure finalize --plan ${member.plan.plan_key} --json`,
1876
- });
1877
- }
1878
- }
1879
-
1880
2221
  export async function appendTodoEvent(options = {}) {
1881
2222
  requireWriter(options.writer, 'g5-authoring');
1882
2223
  if (typeof options.validateProspectiveEvent !== 'function') {
1883
2224
  throw new TypeError('appendTodoEvent requires a Plan-supplied validateProspectiveEvent');
1884
2225
  }
1885
2226
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1886
- return withLock(repoRoot, async () => {
2227
+ return withLock(repoRoot, async (assertHeld) => {
1887
2228
  const store = await readTodoStoreLocked({
1888
- repoRoot, forWrite: true, now: options.now,
1889
- // 修理扉は除去event(tombstone)の書込みだけに開く。それ以外の書込みは従来どおり
1890
- // binding_stale で fail closed する(validateMergedGraph の注記を参照)
1891
- tolerateStaleBindings: options.tolerateStaleBindings === true
1892
- && options.event.kind === 'cross_plan_dependency_removed',
2229
+ repoRoot, forWrite: true, now: options.now, assertHeld,
2230
+ repairContext: { assertHeld, actor: options.event.actor,
2231
+ recordedAt: options.event.recorded_at ?? new Date().toISOString() },
1893
2232
  });
1894
2233
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
1895
2234
  if (!member) fail('STORE_INCONSISTENT', 'plan_not_active');
@@ -1913,17 +2252,16 @@ export async function appendTodoEvent(options = {}) {
1913
2252
  fail('DEPENDENCY_INVALID', 'cross_plan_dependency_already_removed', { target_event_digest: digest });
1914
2253
  }
1915
2254
  }
1916
- return appendPlanScopedEvent({
1917
- repoRoot, member,
2255
+ return { cross_plan_repairs: store.cross_plan_repairs, ...await appendPlanScopedEvent({
2256
+ repoRoot, member, assertHeld,
1918
2257
  input: { ...options.event, recorded_at: options.event.recorded_at ?? new Date().toISOString() },
1919
- });
2258
+ }) };
1920
2259
  }
1921
2260
  const input = resolveTargetedEvent({
1922
2261
  ...options.event,
1923
2262
  task_id: resolveCanonicalTaskId(member.plan, options.event.task_id),
1924
2263
  recorded_at: options.event.recorded_at ?? new Date().toISOString(),
1925
2264
  }, member);
1926
- await enforceTodoStructureLifecycleGate(repoRoot, member, input);
1927
2265
  const event = nextEvent(input, member);
1928
2266
  if ((event.kind === 'start' && event.payload.start_mode === 'historical_import')
1929
2267
  || (event.kind === 'done' && event.payload.done_mode === 'historical_import')) {
@@ -1960,6 +2298,8 @@ export async function appendTodoEvent(options = {}) {
1960
2298
  const eventBytes = canonicalLine(event);
1961
2299
  const activeRef = member.descriptor.journal_ref;
1962
2300
  const activeAbsolute = path.resolve(repoRoot, activeRef);
2301
+ // A holder that lost its lock while suspended must not overwrite the new owner's journal.
2302
+ await assertHeld();
1963
2303
  if (member.journal.activeBytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
1964
2304
  const activeEvents = member.journal.segments.at(-1).events;
1965
2305
  const previousSegmentDigest = member.journal.segments.length > 1
@@ -1989,7 +2329,7 @@ export async function appendTodoEvent(options = {}) {
1989
2329
  // 見るための導出ビューは、snapshotと分けてここで別途返す。
1990
2330
  const phases = projectPhaseStates(member.plan, [...member.journal.events, event],
1991
2331
  new Map(tasks.map((task) => [task.task_id, task])));
1992
- return { event, snapshot, plan: member.plan, phases };
2332
+ return { event, snapshot, plan: member.plan, phases, cross_plan_repairs: store.cross_plan_repairs };
1993
2333
  });
1994
2334
  }
1995
2335
 
@@ -2032,9 +2372,10 @@ function planScopedEventBytes(member, event) {
2032
2372
  return bytes;
2033
2373
  }
2034
2374
 
2035
- async function appendPlanScopedEvent({ repoRoot, member, input }) {
2375
+ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2036
2376
  const event = buildPlanScopedEvent(member, input);
2037
2377
  const bytes = planScopedEventBytes(member, event);
2378
+ await assertHeld();
2038
2379
  await atomicWrite(path.resolve(repoRoot, member.plan_scoped.ref),
2039
2380
  Buffer.concat([member.plan_scoped.activeBytes, bytes]));
2040
2381
  const events = [...member.plan_scoped.events, event];
@@ -2045,6 +2386,99 @@ async function appendPlanScopedEvent({ repoRoot, member, input }) {
2045
2386
  };
2046
2387
  }
2047
2388
 
2389
+ /** Rebind existing connections to a carried source without changing their endpoints. */
2390
+ export async function rebindTodoCrossPlanDependencies(options = {}) {
2391
+ requireWriter(options.writer, 'g5-authoring');
2392
+ if (typeof options.validateBindingCarry !== 'function'
2393
+ || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.sourcePlanKey)
2394
+ || !isTodoDigest(options.expectedManifestDigest)
2395
+ || !isTodoDigest(options.expectedPlanScopedHeadDigest)
2396
+ || !Array.isArray(options.eventDigests) || options.eventDigests.length === 0
2397
+ || !options.eventDigests.every(isTodoDigest)
2398
+ || new Set(options.eventDigests).size !== options.eventDigests.length
2399
+ || typeof options.reason !== 'string' || options.reason.length === 0) {
2400
+ throw new TypeError('dependency rebind requires exact bindings and a Plan carry validator');
2401
+ }
2402
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2403
+ return withLock(repoRoot, async () => {
2404
+ // The repair read must not publish derived state before the complete strict graph check.
2405
+ const store = await readTodoStoreView({ repoRoot, now: options.now });
2406
+ const owner = store.members.find(({ plan }) => plan.plan_key === options.planKey);
2407
+ const source = store.members.find(({ plan }) => plan.plan_key === options.sourcePlanKey);
2408
+ if (store.manifest.manifest_digest !== options.expectedManifestDigest
2409
+ || owner?.plan_scoped.events.at(-1)?.event_digest !== options.expectedPlanScopedHeadDigest) {
2410
+ fail('STORE_WRITE_CONFLICT', 'dependency_rebind_binding_changed');
2411
+ }
2412
+ if (!source || source === owner) fail('DEPENDENCY_INVALID', 'dependency_rebind_source_invalid');
2413
+ const dependencies = projectTodoCrossPlanDependencies(store.members)
2414
+ .filter(({ event_digest: digest }) => options.eventDigests.includes(digest));
2415
+ if (dependencies.length !== options.eventDigests.length || dependencies.some(({ from, to, event_digest: digest }) => (
2416
+ from.project_id !== source.plan.project_id || from.plan_key !== source.plan.plan_key
2417
+ || from.expected_topology_digest === source.plan.topology_digest
2418
+ || to.project_id !== owner.plan.project_id || to.plan_key !== owner.plan.plan_key
2419
+ || !owner.plan_scoped.events.some((event) => event.event_digest === digest)
2420
+ ))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
2421
+ const predecessorBinding = source.revision?.predecessor;
2422
+ if (!predecessorBinding) fail('DEPENDENCY_INVALID', 'dependency_rebind_predecessor_missing');
2423
+ const predecessor = await readArtifact(repoRoot,
2424
+ `${STORE_ROOT_REF}/plans/${source.plan.plan_key}/${predecessorBinding.plan_version}/plan.json`, {
2425
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan,
2426
+ });
2427
+ if (predecessor.project_id !== source.plan.project_id || predecessor.plan_key !== source.plan.plan_key
2428
+ || predecessor.plan_version !== predecessorBinding.plan_version
2429
+ || predecessor.plan_digest !== predecessorBinding.plan_digest) {
2430
+ fail('STORE_INCONSISTENT', 'dependency_rebind_predecessor_mismatch');
2431
+ }
2432
+ const validation = await options.validateBindingCarry({ store, source, dependencies,
2433
+ predecessor: { plan_version: predecessor.plan_version, plan_digest: predecessor.plan_digest,
2434
+ topology_digest: predecessor.topology_digest } });
2435
+ if (validation?.ok === false) {
2436
+ if (typeof validation.code !== 'string' || typeof validation.detail?.reason !== 'string') {
2437
+ throw new TypeError('binding carry validator must return a typed refusal');
2438
+ }
2439
+ const { reason, ...detail } = validation.detail;
2440
+ fail(validation.code, reason, detail);
2441
+ }
2442
+ if (validation?.ok !== true) throw new TypeError('binding carry validator must return an ok result');
2443
+ const staged = { ...owner, plan_scoped: { ...owner.plan_scoped,
2444
+ events: [...owner.plan_scoped.events] } };
2445
+ const replacements = [];
2446
+ for (const dependency of dependencies) {
2447
+ for (const input of [
2448
+ { kind: 'cross_plan_dependency_removed', payload: {
2449
+ target_event_digest: dependency.event_digest, reason: options.reason,
2450
+ } },
2451
+ { kind: 'cross_plan_dependency', payload: {
2452
+ from: { ...dependency.from, expected_topology_digest: source.plan.topology_digest },
2453
+ to: dependency.to, reason: dependency.reason,
2454
+ } },
2455
+ ]) {
2456
+ const event = buildPlanScopedEvent(staged, { ...input, actor: options.actor,
2457
+ recorded_at: options.recordedAt ?? new Date().toISOString() });
2458
+ const bytes = planScopedEventBytes(staged, event);
2459
+ staged.plan_scoped.events.push(event);
2460
+ staged.plan_scoped.activeBytes = Buffer.concat([staged.plan_scoped.activeBytes, bytes]);
2461
+ }
2462
+ replacements.push({ original_event_digest: dependency.event_digest,
2463
+ replacement_event_digest: staged.plan_scoped.events.at(-1).event_digest });
2464
+ }
2465
+ const prospective = store.members.map((member) => member === owner ? staged : member);
2466
+ const projected = projectTodoCrossPlanDependencies(prospective);
2467
+ const edgeKeys = projected.map(({ from, to }) => `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`);
2468
+ if (new Set(edgeKeys).size !== edgeKeys.length) {
2469
+ fail('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate');
2470
+ }
2471
+ validateMergedGraph(prospective, projected);
2472
+ await protocolStage(options, 'dependency_rebind_validated');
2473
+ await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), staged.plan_scoped.activeBytes);
2474
+ await protocolStage(options, 'dependency_rebind_published');
2475
+ return { schema: 'lattice.todo_dependency_rebind_result.v1', project_id: store.project_id,
2476
+ plan_key: owner.plan.plan_key, source_plan_key: source.plan.plan_key,
2477
+ source_topology_digest: source.plan.topology_digest, replacements,
2478
+ plan_scoped_head_digest: staged.plan_scoped.events.at(-1).event_digest };
2479
+ });
2480
+ }
2481
+
2048
2482
  export function buildTodoPlan(input) {
2049
2483
  const plan = { ...input, topology_digest: '', plan_digest: '' };
2050
2484
  plan.topology_digest = digestTodoArtifact({
@@ -2212,7 +2646,7 @@ function prepareImportedArtifacts(repoRoot, options, projectId, memberPlans) {
2212
2646
  const tasks = replay(plan, events, {
2213
2647
  now: options.now ? new Date(options.now) : new Date(), verifyImportSource,
2214
2648
  });
2215
- validateMergedGraph([...memberPlans, { plan }]);
2649
+ validateMergedGraph([...memberPlans, { plan }], undefined, { newPlanKey: plan.plan_key });
2216
2650
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2217
2651
  }
2218
2652
 
@@ -2484,7 +2918,7 @@ async function finalizeVisibleCrossPlanImport(repoRoot, transaction, { removeTra
2484
2918
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.staged_ref });
2485
2919
  }
2486
2920
  const target = await pathState(repoRoot, artifact.ref, 'STORE_INCONSISTENT', { missing: true });
2487
- const current = target === null ? Buffer.alloc(0) : await readFile(target.absolute);
2921
+ const current = target === null ? Buffer.alloc(0) : normalizeCheckoutEol(await readFile(target.absolute));
2488
2922
  const before = bytes.subarray(0, bytes.length - eventBytes.length);
2489
2923
  if (!current.equals(before) && !current.equals(bytes)) {
2490
2924
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.ref });
@@ -2651,7 +3085,7 @@ function prepareAuthoredArtifacts(repoRoot, options, store) {
2651
3085
  const genesis = buildPlanGenesis(plan, options.genesis);
2652
3086
  const events = [genesis];
2653
3087
  const tasks = replay(plan, events);
2654
- validateMergedGraph([...store.members, { plan }]);
3088
+ validateMergedGraph([...store.members, { plan }], undefined, { newPlanKey: plan.plan_key });
2655
3089
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2656
3090
  }
2657
3091
 
@@ -2883,7 +3317,7 @@ const sameDirectoryIdentity = (left, right) => left !== null && right !== null
2883
3317
 
2884
3318
  async function transientStoreDirectory(root, allowNotes = true) {
2885
3319
  for (const entry of await readdir(root, { withFileTypes: true })) {
2886
- if (entry.isFile() && (entry.name === '.write.lock' || /^\.write\.lock\..+\.tmp$/u.test(entry.name))) continue;
3320
+ if (entry.isFile() && (entry.name === '.write.lock' || /^\.write\.lock\..+\.(?:tmp|stale)$/u.test(entry.name))) continue;
2887
3321
  if (!entry.isDirectory()) return false;
2888
3322
  const child = path.join(root, entry.name);
2889
3323
  if (allowNotes && entry.name === 'notes') {
@@ -3031,7 +3465,7 @@ export async function initializeAuthoredTodoStore(options = {}) {
3031
3465
  verifyPlanNarrativeAnchors(repoRoot, plan);
3032
3466
  const genesis = buildPlanGenesis(plan, options.genesis);
3033
3467
  const tasks = replay(plan, [genesis]);
3034
- validateMergedGraph([{ plan }]);
3468
+ validateMergedGraph([{ plan }], undefined, { newPlanKey: plan.plan_key });
3035
3469
  const snapshot = snapshotFor(plan, [genesis], tasks);
3036
3470
  const base = `plans/${plan.plan_key}/${plan.plan_version}`;
3037
3471
  const planRef = `${STORE_ROOT_REF}/${base}/plan.json`;
@@ -3469,12 +3903,19 @@ function validateAcquirePhaseCarry(previous, revision, migration, idMap) {
3469
3903
  }
3470
3904
 
3471
3905
  function stateMigrationFor(previous, revision) {
3472
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(previous.plan.schema)
3473
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(revision.desired_plan.schema)) {
3906
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
3907
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
3908
+ .includes(revision.desired_plan.schema)) {
3474
3909
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
3475
3910
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
3476
3911
  });
3477
3912
  }
3913
+ if (previous.plan.schema === 'lattice.todo_plan.v8'
3914
+ && revision.desired_plan.schema !== 'lattice.todo_plan.v8') {
3915
+ fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
3916
+ predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
3917
+ });
3918
+ }
3478
3919
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id);
3479
3920
  const migrationIds = revision.task_migration.map(({ from_task_id }) => from_task_id);
3480
3921
  if (canonicalizeTodoArtifact([...oldIds].sort()) !== canonicalizeTodoArtifact([...migrationIds].sort())) {
@@ -3510,6 +3951,16 @@ function stateMigrationFor(previous, revision) {
3510
3951
  fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3511
3952
  }
3512
3953
  }
3954
+ } else if (revision.schema === 'lattice.phase_todo_revision.v5' && reconciliationMetadata) {
3955
+ // u12 light carry: only the task_id mapping and compile_binding bind carried state.
3956
+ const predecessorTask = previous.plan.tasks
3957
+ .find(({ task_id }) => task_id === migration.from_task_id);
3958
+ const desiredTask = revision.desired_plan.tasks
3959
+ .find(({ task_id }) => task_id === migration.to_task_id);
3960
+ if (!desiredTask || canonicalizeTodoArtifact(predecessorTask?.compile_binding)
3961
+ !== canonicalizeTodoArtifact(desiredTask.compile_binding)) {
3962
+ fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3963
+ }
3513
3964
  } else if (revision.schema === 'lattice.phase_todo_revision.v3') {
3514
3965
  validatePhaseV3Carry(previous, revision, migration, idMap, state);
3515
3966
  } else if (revision.schema === 'lattice.phase_todo_revision.v4') {
@@ -3566,7 +4017,10 @@ function phaseStateMigrationFor(previous, revision) {
3566
4017
  .map(({ task_id }) => taskIdMap.get(task_id) ?? 'removed').filter((id) => id !== 'removed').sort();
3567
4018
  const afterTaskIds = revision.desired_plan.tasks
3568
4019
  .filter(({ phase_id }) => phase_id === migration.to_phase_id).map(({ task_id }) => task_id).sort();
3569
- if (canonicalizeTodoArtifact({ phase: mappedBefore, task_ids: beforeTaskIds })
4020
+ // u12 light carry (revision v5): Plan chose carry vs reset; Store checks only the id mapping.
4021
+ if (revision.schema === 'lattice.phase_todo_revision.v5') {
4022
+ if (!after) fail('REVISION_INVALID', 'phase_carry_semantics_changed', { from_phase_id: migration.from_phase_id });
4023
+ } else if (canonicalizeTodoArtifact({ phase: mappedBefore, task_ids: beforeTaskIds })
3570
4024
  !== canonicalizeTodoArtifact({ phase: after, task_ids: afterTaskIds })) {
3571
4025
  fail('REVISION_INVALID', 'phase_carry_semantics_changed', { from_phase_id: migration.from_phase_id });
3572
4026
  }
@@ -4464,7 +4918,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4464
4918
  const stateMigration = stateMigrationFor(previous, revision);
4465
4919
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
4466
4920
  validateMergedGraph(store.members.map((member) => member === previous
4467
- ? { ...member, plan: revision.desired_plan } : member));
4921
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member));
4468
4922
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4469
4923
  previous_digest: revision.predecessor.journal_head_digest, actor: options.actor,
4470
4924
  recorded_at: options.recordedAt, provenance: options.provenance ?? null,
@@ -4597,7 +5051,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4597
5051
  await fsyncDirectory(path.dirname(barrierAbsolute));
4598
5052
  await rm(transaction, { recursive: true, force: true });
4599
5053
  return commitReceipt;
4600
- }, { lockCapability: options[STORE_LOCK_HELD] });
5054
+ }, { lockCapability: options[STORE_LOCK_HELD],
5055
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5056
+ onRepairs: options.onCrossPlanRepairs } });
4601
5057
  }
4602
5058
 
4603
5059
  /** Native successor transaction for first-class Phase plans; no Markdown source inventory is involved. */
@@ -4635,7 +5091,7 @@ export async function applyPhaseTodoRevision(options = {}) {
4635
5091
  const stateMigration = stateMigrationFor(previous, revision);
4636
5092
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
4637
5093
  const prospective = store.members.map((member) => member === previous
4638
- ? { ...member, plan: revision.desired_plan } : member);
5094
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
4639
5095
  validateMergedGraph(prospective);
4640
5096
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4641
5097
  previous_digest: revision.predecessor.journal_head_digest,
@@ -4707,7 +5163,9 @@ export async function applyPhaseTodoRevision(options = {}) {
4707
5163
  await protocolStage(options, 'phase_revision_manifest_activated');
4708
5164
  await rm(transaction, { recursive: true, force: true });
4709
5165
  return phaseRevisionResult(revision, genesis, false);
4710
- }, { lockCapability: options[STORE_LOCK_HELD] });
5166
+ }, { lockCapability: options[STORE_LOCK_HELD],
5167
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5168
+ onRepairs: options.onCrossPlanRepairs } });
4711
5169
  }
4712
5170
 
4713
5171
  /** G5 revision transaction: exact successor, state migration, and manifest-CAS activation. */
@@ -4782,7 +5240,7 @@ export async function applyTodoRevision(options = {}) {
4782
5240
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4783
5241
  const stateMigration = stateMigrationFor(previous, revision);
4784
5242
  const prospective = store.members.map((member) => member === previous
4785
- ? { ...member, plan: revision.desired_plan } : member);
5243
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
4786
5244
  validateMergedGraph(prospective);
4787
5245
 
4788
5246
  const candidateGenesis = buildRevisionGenesis(revision.desired_plan, {
@@ -4895,7 +5353,9 @@ export async function applyTodoRevision(options = {}) {
4895
5353
  }
4896
5354
  await rm(transaction, { recursive: true, force: true });
4897
5355
  return revisionResult(revision, genesis, { recovered: recovering });
4898
- }, { lockCapability: options[STORE_LOCK_HELD] });
5356
+ }, { lockCapability: options[STORE_LOCK_HELD],
5357
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5358
+ onRepairs: options.onCrossPlanRepairs } });
4899
5359
  }
4900
5360
 
4901
5361
  function revisionSetResult(projectId, revisionSetDigest, entries, { recovered }) {
@@ -5055,7 +5515,7 @@ export async function applyTodoRevisionSet(options = {}) {
5055
5515
  const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key,
5056
5516
  entry.revision.desired_plan]));
5057
5517
  validateMergedGraph(store.members.map((member) => desiredByPlan.has(member.descriptor.plan_key)
5058
- ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key) } : member));
5518
+ ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key), plan_scoped: null } : member));
5059
5519
 
5060
5520
  await ensureSafeStoreDirectory(repoRoot, transaction);
5061
5521
  const mixedPhaseSet = prepared.some(({ revision }) => ([
@@ -5202,7 +5662,9 @@ export async function applyTodoRevisionSet(options = {}) {
5202
5662
  }
5203
5663
  await rm(transaction, { recursive: true, force: true });
5204
5664
  return revisionSetResult(projectId, revisionSetDigest, prepared, { recovered: recovering });
5205
- }, { lockCapability: options[STORE_LOCK_HELD] });
5665
+ }, { lockCapability: options[STORE_LOCK_HELD],
5666
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5667
+ onRepairs: options.onCrossPlanRepairs } });
5206
5668
  }
5207
5669
 
5208
5670
  /** G5 revise primitive: topology changes only by publishing a successor version. */
@@ -5223,7 +5685,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5223
5685
  ['lattice.todo_plan.v1', 1], ['lattice.todo_plan.v2', 2], ['lattice.todo_plan.v3', 3],
5224
5686
  // v6はphase無しv3へdesign_memoを追加した枝であり、phase世代より後という意味ではない。
5225
5687
  ['lattice.todo_plan.v4', 4], ['lattice.todo_plan.v5', 5], ['lattice.todo_plan.v6', 3],
5226
- ['lattice.todo_plan.v7', 5],
5688
+ ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5],
5227
5689
  ]);
5228
5690
  if (schemaRank.get(plan.schema) < schemaRank.get(previous.plan.schema)) {
5229
5691
  throw new TypeError(previous.plan.schema === 'lattice.todo_plan.v2'
@@ -5231,9 +5693,16 @@ export async function createSuccessorTodoPlan(options = {}) {
5231
5693
  ? 'todo plan schema cannot regress from v2 to v1'
5232
5694
  : 'todo plan schema cannot regress');
5233
5695
  }
5234
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(previous.plan.schema)
5235
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(plan.schema)) {
5236
- throw new TypeError('todo plan design_memo cannot be removed by successor schema');
5696
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
5697
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
5698
+ fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
5699
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
5700
+ });
5701
+ }
5702
+ if (previous.plan.schema === 'lattice.todo_plan.v8' && plan.schema !== 'lattice.todo_plan.v8') {
5703
+ fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
5704
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
5705
+ });
5237
5706
  }
5238
5707
  verifyPlanNarrativeAnchors(repoRoot, plan, previous.plan);
5239
5708
  const migration = options.genesis.task_migration ?? [];
@@ -5248,7 +5717,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5248
5717
  const genesis = buildPlanGenesis(plan, {
5249
5718
  ...options.genesis, previous_digest: previous.journal.events.at(-1).event_digest,
5250
5719
  });
5251
- const prospective = store.members.map((member) => member === previous ? { ...member, plan } : member);
5720
+ const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: null } : member);
5252
5721
  validateMergedGraph(prospective);
5253
5722
  const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}/${plan.plan_version}`;
5254
5723
  const planRef = `${base}/plan.json`; const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
@@ -5269,7 +5738,8 @@ export async function createSuccessorTodoPlan(options = {}) {
5269
5738
  store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
5270
5739
  await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
5271
5740
  return { plan, genesis, snapshot };
5272
- });
5741
+ }, { repairAfter: { actor: options.genesis.actor, recordedAt: options.genesis.recorded_at,
5742
+ onRepairs: options.onCrossPlanRepairs } });
5273
5743
  }
5274
5744
 
5275
5745
  const INDEPENDENCE_ARTIFACT_NAME = 'independence.json';
@@ -5886,7 +6356,7 @@ export async function readTodoStructureRealizationChain(options = {}) {
5886
6356
  missing: true,
5887
6357
  });
5888
6358
  if (state === null) return [];
5889
- return parseTodoStructureRealizationChain(await readFile(state.absolute), {
6359
+ return parseTodoStructureRealizationChain(normalizeCheckoutEol(await readFile(state.absolute)), {
5890
6360
  structureSet: options.structureSet, taskId: options.taskId,
5891
6361
  });
5892
6362
  }