@quolu/lattice 0.82.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 (66) hide show
  1. package/bin/lattice-bridge-supervisor.mjs +10 -0
  2. package/bin/lattice-dashboard.mjs +3 -18
  3. package/bin/lattice-mcp.mjs +6 -3
  4. package/bin/lattice.mjs +1 -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 +6 -3
  7. package/package.json +2 -1
  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-hub-server.mjs +46 -9
  33. package/src/cli-help.mjs +2 -2
  34. package/src/dashboard-lifecycle-journal.mjs +42 -20
  35. package/src/plan-backchain.mjs +25 -8
  36. package/src/plan-revise.mjs +129 -28
  37. package/src/project-cli.mjs +42 -18
  38. package/src/project-identity.mjs +14 -0
  39. package/src/runtime-cli.mjs +31 -18
  40. package/src/runtime-control-store.mjs +22 -1
  41. package/src/runtime-decision-verifier.mjs +27 -8
  42. package/src/runtime-engine.mjs +34 -5
  43. package/src/runtime-hold-recompile.mjs +19 -15
  44. package/src/runtime-kept-worktree.mjs +136 -0
  45. package/src/runtime-lifecycle-lock.mjs +118 -30
  46. package/src/runtime-managed-supervisor.mjs +10 -10
  47. package/src/runtime-pull-intake.mjs +87 -43
  48. package/src/store-lock.mjs +142 -57
  49. package/src/todo-authoring-input.mjs +56 -2
  50. package/src/todo-cli.mjs +168 -42
  51. package/src/todo-contracts.mjs +22 -6
  52. package/src/todo-dashboard-registry.mjs +31 -4
  53. package/src/todo-gantt-display.mjs +260 -0
  54. package/src/todo-gantt-html-independence.mjs +8 -1
  55. package/src/todo-gantt-html-shared.mjs +2 -1
  56. package/src/todo-gantt-html.mjs +4 -2
  57. package/src/todo-gantt-layout.mjs +7 -36
  58. package/src/todo-gantt-live.mjs +6 -3
  59. package/src/todo-note-store.mjs +6 -3
  60. package/src/todo-readiness.mjs +29 -8
  61. package/src/todo-revision.mjs +9 -8
  62. package/src/todo-split.mjs +6 -3
  63. package/src/todo-status.mjs +53 -9
  64. package/src/todo-store-cache.mjs +1 -1
  65. package/src/todo-store-view.mjs +21 -2
  66. package/src/todo-store.mjs +545 -166
@@ -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,10 +871,14 @@ function snapshotFor(plan, events, tasks) {
871
871
  return snapshot;
872
872
  }
873
873
 
874
- function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPlanDependencies(members), options = {}) {
875
- // Only disconnect and the locked identity-preserving repair tolerate stale digests.
876
- // Missing endpoints and bindings remain invalid on both repair paths.
877
- 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 = [];
878
882
  const tasks = new Map();
879
883
  for (const member of members) for (const task of member.plan.tasks) {
880
884
  tasks.set(`${member.plan.project_id}\0${member.plan.plan_key}\0${task.task_id}`, member.plan.topology_digest);
@@ -889,38 +893,43 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
889
893
  adjacency.set(key, []);
890
894
  }
891
895
  }
892
- const bind = (ref, ownerPlan) => {
893
- const key = `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`;
894
- const topology = tasks.get(key);
895
- if (topology === undefined) fail('STORE_INCONSISTENT', 'dangling_dependency');
896
- if ((ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key)
897
- && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
898
- if (!tolerateStale && ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
899
- 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;
900
908
  }
901
- return key;
902
- };
903
- const bindPhase = (ref, ownerPlan) => {
904
- const key = `phase\0${ref.project_id}\0${ref.plan_key}\0${ref.phase_id}`;
905
- const topology = phases.get(key);
906
- if (topology === undefined) fail('STORE_INCONSISTENT', 'dangling_phase_dependency');
907
- if ((ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key)
908
- && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
909
- if (!tolerateStale && ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
910
- 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');
911
913
  }
912
914
  return key;
913
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');
914
921
  for (const { plan } of members) {
915
922
  for (const edge of plan.hard_dependencies) {
916
- 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;
917
925
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
918
926
  adjacency.get(from).push(to);
919
927
  }
920
928
  for (const join of plan.joins) {
921
- const before = bind(join.before, plan);
929
+ const before = bind(join.before, plan, null, 'to');
922
930
  for (const afterRef of join.after) {
923
- const after = bind(afterRef, plan);
931
+ const after = bind(afterRef, plan, null, 'from');
932
+ if (before === null || after === null) continue;
924
933
  if (after === before) fail('STORE_INCONSISTENT', 'join_self_edge');
925
934
  adjacency.get(after).push(before);
926
935
  }
@@ -938,7 +947,8 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
938
947
  }
939
948
  }
940
949
  for (const edge of plan.phase_accept_dependencies) {
941
- 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);
942
952
  }
943
953
  }
944
954
  }
@@ -946,8 +956,10 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
946
956
  const owner = members.find(({ plan }) => plan.project_id === dependency.to.project_id
947
957
  && plan.plan_key === dependency.to.plan_key);
948
958
  if (owner === undefined) fail('STORE_INCONSISTENT', 'cross_plan_dependency_owner_missing');
949
- const from = bind(dependency.from, owner.plan);
950
- 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;
951
963
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
952
964
  adjacency.get(from).push(to);
953
965
  }
@@ -958,6 +970,11 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
958
970
  colors.set(node, 1); for (const next of adjacency.get(node)) visit(next); colors.set(node, 2);
959
971
  };
960
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));
961
978
  }
962
979
 
963
980
  function crossPlanDependencyTask(store, ref) {
@@ -1329,9 +1346,9 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1329
1346
 
1330
1347
  function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache = null) {
1331
1348
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1332
- '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;
1333
1350
  const trusted = new Map((['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1334
- '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)
1335
1352
  ? trustedPlan.tasks : [])
1336
1353
  .map((task) => [task.task_id, task.narrative_anchor]));
1337
1354
  for (const task of plan.tasks) {
@@ -1394,6 +1411,9 @@ async function readTodoStoreLocked(options = {}) {
1394
1411
  await recoverCrossPlanImports(repoRoot);
1395
1412
  const recovery = { manifestDirty: false };
1396
1413
  const store = await readTodoStoreView({ ...options, recovery });
1414
+ if (options.assertHeld) {
1415
+ store.cross_plan_repairs = await repairCrossPlanBindings(repoRoot, store, options.repairContext);
1416
+ }
1397
1417
  // Every member and merged graph has validated before any derived publication.
1398
1418
  for (const member of store.members) {
1399
1419
  if (!member.snapshot_stale) continue;
@@ -1529,8 +1549,8 @@ async function readTodoStoreView(options = {}) {
1529
1549
  snapshotStale = snapshot === null || canonicalizeTodoArtifact(snapshot) !== canonicalizeTodoArtifact(expectedSnapshot);
1530
1550
  } catch (error) {
1531
1551
  if (error instanceof TodoStoreError && error.code === 'SNAPSHOT_INVALID'
1532
- && !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store',
1533
- '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;
1534
1554
  else throw error;
1535
1555
  }
1536
1556
  if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
@@ -1546,16 +1566,136 @@ async function readTodoStoreView(options = {}) {
1546
1566
  snapshot: snapshotStale ? expectedSnapshot : snapshot,
1547
1567
  tasks, phases, coordination, snapshot_stale: snapshotStale });
1548
1568
  }
1549
- validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded), {
1550
- tolerateStaleBindings: options.tolerateStaleBindings === true,
1551
- });
1569
+ const crossPlanFindings = validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded));
1552
1570
  return {
1553
1571
  schema: 'lattice.todo_store_read.v1', project_id: manifest.project_id, manifest,
1554
1572
  members: loaded, snapshot_stale: loaded.some((member) => member.snapshot_stale),
1573
+ cross_plan_findings: crossPlanFindings,
1555
1574
  };
1556
1575
  }
1557
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
+
1558
1694
  export async function readTodoStoreStable(options = {}) {
1695
+ return readStoreStableWith(options, readTodoStore);
1696
+ }
1697
+
1698
+ async function readStoreStableWith(options, readStore) {
1559
1699
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1560
1700
  const maximumAttempts = options.maximumAttempts ?? 4;
1561
1701
  if (!Number.isSafeInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 16) {
@@ -1572,7 +1712,7 @@ export async function readTodoStoreStable(options = {}) {
1572
1712
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1573
1713
  });
1574
1714
  try {
1575
- const store = await readTodoStore(options);
1715
+ const store = await readStore(options);
1576
1716
  const after = await readArtifact(repoRoot, MANIFEST_REF, {
1577
1717
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1578
1718
  });
@@ -1602,6 +1742,260 @@ export async function readTodoStoreStable(options = {}) {
1602
1742
  fail('STORE_BUSY', 'stable_read_exhausted', { attempts: maximumAttempts });
1603
1743
  }
1604
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
+
1605
1999
  async function atomicWrite(absolute, bytes) {
1606
2000
  await mkdir(path.dirname(absolute), { recursive: true });
1607
2001
  const temporary = path.join(path.dirname(absolute), `.${path.basename(absolute)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
@@ -1639,9 +2033,23 @@ async function atomicWriteMode(absolute, bytes, mode) {
1639
2033
 
1640
2034
 
1641
2035
  async function withLock(repoRoot, callback, {
1642
- onProtocolStage = null, lockCapability = null, initialize = false,
2036
+ onProtocolStage = null, lockCapability = null, initialize = false, repairAfter = null,
1643
2037
  } = {}) {
1644
- 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
+ };
1645
2053
  try {
1646
2054
  if (!initialize) {
1647
2055
  const root = await lstat(path.join(repoRoot, STORE_ROOT_REF)).catch((error) => {
@@ -1663,7 +2071,7 @@ async function withLock(repoRoot, callback, {
1663
2071
  recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
1664
2072
  onRecoveryClaim: typeof onProtocolStage === 'function'
1665
2073
  ? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
1666
- }, callback);
2074
+ }, run);
1667
2075
  } catch (error) {
1668
2076
  if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
1669
2077
  throw error;
@@ -1810,83 +2218,17 @@ function resolveCanonicalTaskId(plan, requestedTaskId) {
1810
2218
  return matches[0].task_id;
1811
2219
  }
1812
2220
 
1813
- async function enforceTodoStructureLifecycleGate(repoRoot, member, eventInput) {
1814
- if (eventInput.kind === 'done') return;
1815
- const binding = await readTodoStructureBinding({
1816
- repoRoot, planKey: member.plan.plan_key, planVersion: member.plan.plan_version,
1817
- });
1818
- if (binding === null) return;
1819
- const source = await readTodoStructureSource({ repoRoot, planKey: member.plan.plan_key });
1820
- if (source === null || source.structure_set_digest !== binding.structure_set_digest) {
1821
- fail('STRUCTURE_LIFECYCLE_GATE_FAILED', 'enabled_structure_source_unreadable');
1822
- }
1823
- if (!['phase_accept', 'phase_close_unaudited'].includes(eventInput.kind)
1824
- || member.tasks.some(({ status }) => status !== 'done')) return;
1825
- const finalization = await readTodoStructureFinalization({
1826
- repoRoot, planKey: member.plan.plan_key, planVersion: member.plan.plan_version,
1827
- });
1828
- if (finalization === null) {
1829
- fail('STRUCTURE_FINALIZATION_REQUIRED', 'fresh_consistent_finalization_missing', {
1830
- plan_key: member.plan.plan_key,
1831
- next_action: `lattice todo structure finalize --plan ${member.plan.plan_key} --json`,
1832
- });
1833
- }
1834
- let currentHead;
1835
- try {
1836
- currentHead = gitSync(['rev-parse', '--verify', 'HEAD^{commit}'], {
1837
- cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
1838
- }).trim();
1839
- } catch {
1840
- fail('STRUCTURE_GIT_HEAD_UNAVAILABLE', 'current_head_unavailable');
1841
- }
1842
- const realizationHeads = [];
1843
- for (const task of source.tasks.filter(({ applicability }) => applicability === 'graph')) {
1844
- const chain = await readTodoStructureRealizationChain({
1845
- repoRoot, structureSet: source, taskId: task.task_id,
1846
- });
1847
- const head = chain.at(-1);
1848
- if (head !== undefined) realizationHeads.push({
1849
- task_id: task.task_id, sequence: head.sequence,
1850
- realization_digest: head.realization_digest,
1851
- });
1852
- }
1853
- const staleReasons = [];
1854
- if (finalization.project_id !== member.plan.project_id) staleReasons.push('project_id');
1855
- if (finalization.plan_key !== member.plan.plan_key) staleReasons.push('plan_key');
1856
- if (finalization.plan_version !== member.plan.plan_version) staleReasons.push('plan_version');
1857
- if (finalization.topology_digest !== member.plan.topology_digest) {
1858
- staleReasons.push('topology_digest');
1859
- }
1860
- if (finalization.structure_set_digest !== source.structure_set_digest) {
1861
- staleReasons.push('structure_set_digest');
1862
- }
1863
- if (finalization.current_head_sha !== currentHead) staleReasons.push('current_head_sha');
1864
- if (finalization.realization_head_digest
1865
- !== digestTodoStructureRealizationHeads(realizationHeads)) {
1866
- staleReasons.push('realization_head_digest');
1867
- }
1868
- if (finalization.overlay.verdict !== 'consistent') staleReasons.push('verdict');
1869
- if (staleReasons.length > 0) {
1870
- fail('STRUCTURE_FINALIZATION_REQUIRED', 'finalization_stale', {
1871
- plan_key: member.plan.plan_key, stale_reasons: staleReasons.sort(),
1872
- next_action: `lattice todo structure finalize --plan ${member.plan.plan_key} --json`,
1873
- });
1874
- }
1875
- }
1876
-
1877
2221
  export async function appendTodoEvent(options = {}) {
1878
2222
  requireWriter(options.writer, 'g5-authoring');
1879
2223
  if (typeof options.validateProspectiveEvent !== 'function') {
1880
2224
  throw new TypeError('appendTodoEvent requires a Plan-supplied validateProspectiveEvent');
1881
2225
  }
1882
2226
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1883
- return withLock(repoRoot, async () => {
2227
+ return withLock(repoRoot, async (assertHeld) => {
1884
2228
  const store = await readTodoStoreLocked({
1885
- repoRoot, forWrite: true, now: options.now,
1886
- // 修理扉は除去event(tombstone)の書込みだけに開く。それ以外の書込みは従来どおり
1887
- // binding_stale で fail closed する(validateMergedGraph の注記を参照)
1888
- tolerateStaleBindings: options.tolerateStaleBindings === true
1889
- && 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() },
1890
2232
  });
1891
2233
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
1892
2234
  if (!member) fail('STORE_INCONSISTENT', 'plan_not_active');
@@ -1910,17 +2252,16 @@ export async function appendTodoEvent(options = {}) {
1910
2252
  fail('DEPENDENCY_INVALID', 'cross_plan_dependency_already_removed', { target_event_digest: digest });
1911
2253
  }
1912
2254
  }
1913
- return appendPlanScopedEvent({
1914
- repoRoot, member,
2255
+ return { cross_plan_repairs: store.cross_plan_repairs, ...await appendPlanScopedEvent({
2256
+ repoRoot, member, assertHeld,
1915
2257
  input: { ...options.event, recorded_at: options.event.recorded_at ?? new Date().toISOString() },
1916
- });
2258
+ }) };
1917
2259
  }
1918
2260
  const input = resolveTargetedEvent({
1919
2261
  ...options.event,
1920
2262
  task_id: resolveCanonicalTaskId(member.plan, options.event.task_id),
1921
2263
  recorded_at: options.event.recorded_at ?? new Date().toISOString(),
1922
2264
  }, member);
1923
- await enforceTodoStructureLifecycleGate(repoRoot, member, input);
1924
2265
  const event = nextEvent(input, member);
1925
2266
  if ((event.kind === 'start' && event.payload.start_mode === 'historical_import')
1926
2267
  || (event.kind === 'done' && event.payload.done_mode === 'historical_import')) {
@@ -1957,6 +2298,8 @@ export async function appendTodoEvent(options = {}) {
1957
2298
  const eventBytes = canonicalLine(event);
1958
2299
  const activeRef = member.descriptor.journal_ref;
1959
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();
1960
2303
  if (member.journal.activeBytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
1961
2304
  const activeEvents = member.journal.segments.at(-1).events;
1962
2305
  const previousSegmentDigest = member.journal.segments.length > 1
@@ -1986,7 +2329,7 @@ export async function appendTodoEvent(options = {}) {
1986
2329
  // 見るための導出ビューは、snapshotと分けてここで別途返す。
1987
2330
  const phases = projectPhaseStates(member.plan, [...member.journal.events, event],
1988
2331
  new Map(tasks.map((task) => [task.task_id, task])));
1989
- return { event, snapshot, plan: member.plan, phases };
2332
+ return { event, snapshot, plan: member.plan, phases, cross_plan_repairs: store.cross_plan_repairs };
1990
2333
  });
1991
2334
  }
1992
2335
 
@@ -2029,9 +2372,10 @@ function planScopedEventBytes(member, event) {
2029
2372
  return bytes;
2030
2373
  }
2031
2374
 
2032
- async function appendPlanScopedEvent({ repoRoot, member, input }) {
2375
+ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2033
2376
  const event = buildPlanScopedEvent(member, input);
2034
2377
  const bytes = planScopedEventBytes(member, event);
2378
+ await assertHeld();
2035
2379
  await atomicWrite(path.resolve(repoRoot, member.plan_scoped.ref),
2036
2380
  Buffer.concat([member.plan_scoped.activeBytes, bytes]));
2037
2381
  const events = [...member.plan_scoped.events, event];
@@ -2058,8 +2402,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2058
2402
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2059
2403
  return withLock(repoRoot, async () => {
2060
2404
  // The repair read must not publish derived state before the complete strict graph check.
2061
- const store = await readTodoStoreView({ repoRoot, now: options.now,
2062
- tolerateStaleBindings: true });
2405
+ const store = await readTodoStoreView({ repoRoot, now: options.now });
2063
2406
  const owner = store.members.find(({ plan }) => plan.plan_key === options.planKey);
2064
2407
  const source = store.members.find(({ plan }) => plan.plan_key === options.sourcePlanKey);
2065
2408
  if (store.manifest.manifest_digest !== options.expectedManifestDigest
@@ -2303,7 +2646,7 @@ function prepareImportedArtifacts(repoRoot, options, projectId, memberPlans) {
2303
2646
  const tasks = replay(plan, events, {
2304
2647
  now: options.now ? new Date(options.now) : new Date(), verifyImportSource,
2305
2648
  });
2306
- validateMergedGraph([...memberPlans, { plan }]);
2649
+ validateMergedGraph([...memberPlans, { plan }], undefined, { newPlanKey: plan.plan_key });
2307
2650
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2308
2651
  }
2309
2652
 
@@ -2575,7 +2918,7 @@ async function finalizeVisibleCrossPlanImport(repoRoot, transaction, { removeTra
2575
2918
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.staged_ref });
2576
2919
  }
2577
2920
  const target = await pathState(repoRoot, artifact.ref, 'STORE_INCONSISTENT', { missing: true });
2578
- const current = target === null ? Buffer.alloc(0) : await readFile(target.absolute);
2921
+ const current = target === null ? Buffer.alloc(0) : normalizeCheckoutEol(await readFile(target.absolute));
2579
2922
  const before = bytes.subarray(0, bytes.length - eventBytes.length);
2580
2923
  if (!current.equals(before) && !current.equals(bytes)) {
2581
2924
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.ref });
@@ -2742,7 +3085,7 @@ function prepareAuthoredArtifacts(repoRoot, options, store) {
2742
3085
  const genesis = buildPlanGenesis(plan, options.genesis);
2743
3086
  const events = [genesis];
2744
3087
  const tasks = replay(plan, events);
2745
- validateMergedGraph([...store.members, { plan }]);
3088
+ validateMergedGraph([...store.members, { plan }], undefined, { newPlanKey: plan.plan_key });
2746
3089
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2747
3090
  }
2748
3091
 
@@ -2974,7 +3317,7 @@ const sameDirectoryIdentity = (left, right) => left !== null && right !== null
2974
3317
 
2975
3318
  async function transientStoreDirectory(root, allowNotes = true) {
2976
3319
  for (const entry of await readdir(root, { withFileTypes: true })) {
2977
- 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;
2978
3321
  if (!entry.isDirectory()) return false;
2979
3322
  const child = path.join(root, entry.name);
2980
3323
  if (allowNotes && entry.name === 'notes') {
@@ -3122,7 +3465,7 @@ export async function initializeAuthoredTodoStore(options = {}) {
3122
3465
  verifyPlanNarrativeAnchors(repoRoot, plan);
3123
3466
  const genesis = buildPlanGenesis(plan, options.genesis);
3124
3467
  const tasks = replay(plan, [genesis]);
3125
- validateMergedGraph([{ plan }]);
3468
+ validateMergedGraph([{ plan }], undefined, { newPlanKey: plan.plan_key });
3126
3469
  const snapshot = snapshotFor(plan, [genesis], tasks);
3127
3470
  const base = `plans/${plan.plan_key}/${plan.plan_version}`;
3128
3471
  const planRef = `${STORE_ROOT_REF}/${base}/plan.json`;
@@ -3560,12 +3903,19 @@ function validateAcquirePhaseCarry(previous, revision, migration, idMap) {
3560
3903
  }
3561
3904
 
3562
3905
  function stateMigrationFor(previous, revision) {
3563
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(previous.plan.schema)
3564
- && !['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)) {
3565
3909
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
3566
3910
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
3567
3911
  });
3568
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
+ }
3569
3919
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id);
3570
3920
  const migrationIds = revision.task_migration.map(({ from_task_id }) => from_task_id);
3571
3921
  if (canonicalizeTodoArtifact([...oldIds].sort()) !== canonicalizeTodoArtifact([...migrationIds].sort())) {
@@ -3601,6 +3951,16 @@ function stateMigrationFor(previous, revision) {
3601
3951
  fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3602
3952
  }
3603
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
+ }
3604
3964
  } else if (revision.schema === 'lattice.phase_todo_revision.v3') {
3605
3965
  validatePhaseV3Carry(previous, revision, migration, idMap, state);
3606
3966
  } else if (revision.schema === 'lattice.phase_todo_revision.v4') {
@@ -3657,7 +4017,10 @@ function phaseStateMigrationFor(previous, revision) {
3657
4017
  .map(({ task_id }) => taskIdMap.get(task_id) ?? 'removed').filter((id) => id !== 'removed').sort();
3658
4018
  const afterTaskIds = revision.desired_plan.tasks
3659
4019
  .filter(({ phase_id }) => phase_id === migration.to_phase_id).map(({ task_id }) => task_id).sort();
3660
- 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 })
3661
4024
  !== canonicalizeTodoArtifact({ phase: after, task_ids: afterTaskIds })) {
3662
4025
  fail('REVISION_INVALID', 'phase_carry_semantics_changed', { from_phase_id: migration.from_phase_id });
3663
4026
  }
@@ -4688,7 +5051,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4688
5051
  await fsyncDirectory(path.dirname(barrierAbsolute));
4689
5052
  await rm(transaction, { recursive: true, force: true });
4690
5053
  return commitReceipt;
4691
- }, { lockCapability: options[STORE_LOCK_HELD] });
5054
+ }, { lockCapability: options[STORE_LOCK_HELD],
5055
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5056
+ onRepairs: options.onCrossPlanRepairs } });
4692
5057
  }
4693
5058
 
4694
5059
  /** Native successor transaction for first-class Phase plans; no Markdown source inventory is involved. */
@@ -4798,7 +5163,9 @@ export async function applyPhaseTodoRevision(options = {}) {
4798
5163
  await protocolStage(options, 'phase_revision_manifest_activated');
4799
5164
  await rm(transaction, { recursive: true, force: true });
4800
5165
  return phaseRevisionResult(revision, genesis, false);
4801
- }, { lockCapability: options[STORE_LOCK_HELD] });
5166
+ }, { lockCapability: options[STORE_LOCK_HELD],
5167
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5168
+ onRepairs: options.onCrossPlanRepairs } });
4802
5169
  }
4803
5170
 
4804
5171
  /** G5 revision transaction: exact successor, state migration, and manifest-CAS activation. */
@@ -4986,7 +5353,9 @@ export async function applyTodoRevision(options = {}) {
4986
5353
  }
4987
5354
  await rm(transaction, { recursive: true, force: true });
4988
5355
  return revisionResult(revision, genesis, { recovered: recovering });
4989
- }, { lockCapability: options[STORE_LOCK_HELD] });
5356
+ }, { lockCapability: options[STORE_LOCK_HELD],
5357
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5358
+ onRepairs: options.onCrossPlanRepairs } });
4990
5359
  }
4991
5360
 
4992
5361
  function revisionSetResult(projectId, revisionSetDigest, entries, { recovered }) {
@@ -5293,7 +5662,9 @@ export async function applyTodoRevisionSet(options = {}) {
5293
5662
  }
5294
5663
  await rm(transaction, { recursive: true, force: true });
5295
5664
  return revisionSetResult(projectId, revisionSetDigest, prepared, { recovered: recovering });
5296
- }, { lockCapability: options[STORE_LOCK_HELD] });
5665
+ }, { lockCapability: options[STORE_LOCK_HELD],
5666
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5667
+ onRepairs: options.onCrossPlanRepairs } });
5297
5668
  }
5298
5669
 
5299
5670
  /** G5 revise primitive: topology changes only by publishing a successor version. */
@@ -5314,7 +5685,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5314
5685
  ['lattice.todo_plan.v1', 1], ['lattice.todo_plan.v2', 2], ['lattice.todo_plan.v3', 3],
5315
5686
  // v6はphase無しv3へdesign_memoを追加した枝であり、phase世代より後という意味ではない。
5316
5687
  ['lattice.todo_plan.v4', 4], ['lattice.todo_plan.v5', 5], ['lattice.todo_plan.v6', 3],
5317
- ['lattice.todo_plan.v7', 5],
5688
+ ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5],
5318
5689
  ]);
5319
5690
  if (schemaRank.get(plan.schema) < schemaRank.get(previous.plan.schema)) {
5320
5691
  throw new TypeError(previous.plan.schema === 'lattice.todo_plan.v2'
@@ -5322,9 +5693,16 @@ export async function createSuccessorTodoPlan(options = {}) {
5322
5693
  ? 'todo plan schema cannot regress from v2 to v1'
5323
5694
  : 'todo plan schema cannot regress');
5324
5695
  }
5325
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(previous.plan.schema)
5326
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(plan.schema)) {
5327
- 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
+ });
5328
5706
  }
5329
5707
  verifyPlanNarrativeAnchors(repoRoot, plan, previous.plan);
5330
5708
  const migration = options.genesis.task_migration ?? [];
@@ -5360,7 +5738,8 @@ export async function createSuccessorTodoPlan(options = {}) {
5360
5738
  store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
5361
5739
  await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
5362
5740
  return { plan, genesis, snapshot };
5363
- });
5741
+ }, { repairAfter: { actor: options.genesis.actor, recordedAt: options.genesis.recorded_at,
5742
+ onRepairs: options.onCrossPlanRepairs } });
5364
5743
  }
5365
5744
 
5366
5745
  const INDEPENDENCE_ARTIFACT_NAME = 'independence.json';
@@ -5977,7 +6356,7 @@ export async function readTodoStructureRealizationChain(options = {}) {
5977
6356
  missing: true,
5978
6357
  });
5979
6358
  if (state === null) return [];
5980
- return parseTodoStructureRealizationChain(await readFile(state.absolute), {
6359
+ return parseTodoStructureRealizationChain(normalizeCheckoutEol(await readFile(state.absolute)), {
5981
6360
  structureSet: options.structureSet, taskId: options.taskId,
5982
6361
  });
5983
6362
  }