@quolu/lattice 0.82.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +1 -1
  3. package/bin/lattice-bridge-supervisor.mjs +10 -0
  4. package/bin/lattice-dashboard.mjs +3 -18
  5. package/bin/lattice-mcp.mjs +6 -3
  6. package/bin/lattice.mjs +30 -23
  7. package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
  8. package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
  9. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
  10. package/package.json +2 -1
  11. package/sensor/dist/db/index.d.ts +1 -0
  12. package/sensor/dist/db/index.d.ts.map +1 -1
  13. package/sensor/dist/db/index.js +13 -0
  14. package/sensor/dist/db/index.js.map +1 -1
  15. package/sensor/dist/index.d.ts.map +1 -1
  16. package/sensor/dist/index.js +12 -2
  17. package/sensor/dist/index.js.map +1 -1
  18. package/sensor/dist/mcp/answer-freshness.js +1 -1
  19. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  20. package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
  21. package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
  22. package/sensor/dist/mcp/daemon-paths.js +7 -1
  23. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  24. package/sensor/dist/mcp/engine.d.ts +11 -0
  25. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  26. package/sensor/dist/mcp/engine.js +83 -4
  27. package/sensor/dist/mcp/engine.js.map +1 -1
  28. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  29. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  30. package/sensor/dist/mcp/index-repair.js +93 -0
  31. package/sensor/dist/mcp/index-repair.js.map +1 -0
  32. package/sensor/dist/mcp/index.d.ts.map +1 -1
  33. package/sensor/dist/mcp/index.js +12 -7
  34. package/sensor/dist/mcp/index.js.map +1 -1
  35. package/sensor/dist/mcp/tools.d.ts +4 -0
  36. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  37. package/sensor/dist/mcp/tools.js +29 -9
  38. package/sensor/dist/mcp/tools.js.map +1 -1
  39. package/src/bridge-hub-server.mjs +46 -9
  40. package/src/cli-help.mjs +10 -8
  41. package/src/cli-refusal-guidance.mjs +354 -0
  42. package/src/dashboard-delivery.mjs +2 -1
  43. package/src/dashboard-lifecycle-journal.mjs +42 -20
  44. package/src/hooks-cli.mjs +30 -6
  45. package/src/plan-backchain.mjs +95 -41
  46. package/src/plan-revise.mjs +274 -72
  47. package/src/project-cli.mjs +301 -163
  48. package/src/project-identity.mjs +14 -0
  49. package/src/runtime-cli.mjs +38 -29
  50. package/src/runtime-control-store.mjs +22 -1
  51. package/src/runtime-decision-verifier.mjs +27 -8
  52. package/src/runtime-engine.mjs +34 -5
  53. package/src/runtime-hold-recompile.mjs +19 -15
  54. package/src/runtime-kept-worktree.mjs +136 -0
  55. package/src/runtime-lifecycle-lock.mjs +118 -30
  56. package/src/runtime-managed-supervisor.mjs +10 -10
  57. package/src/runtime-pull-intake.mjs +90 -44
  58. package/src/store-lock.mjs +142 -57
  59. package/src/todo-authoring-input.mjs +211 -2
  60. package/src/todo-cli.mjs +554 -200
  61. package/src/todo-contracts.mjs +22 -6
  62. package/src/todo-dashboard-registry.mjs +35 -6
  63. package/src/todo-gantt-display.mjs +259 -0
  64. package/src/todo-gantt-html-independence.mjs +10 -3
  65. package/src/todo-gantt-html-shared.mjs +16 -1
  66. package/src/todo-gantt-html.mjs +74 -53
  67. package/src/todo-gantt-layout.mjs +137 -59
  68. package/src/todo-gantt-live.mjs +6 -3
  69. package/src/todo-independence-guidance.mjs +4 -26
  70. package/src/todo-note-store.mjs +6 -3
  71. package/src/todo-readiness.mjs +83 -20
  72. package/src/todo-revision.mjs +156 -8
  73. package/src/todo-split.mjs +6 -3
  74. package/src/todo-status.mjs +141 -54
  75. package/src/todo-store-cache.mjs +1 -1
  76. package/src/todo-store-view.mjs +20 -2
  77. package/src/todo-store.mjs +562 -444
@@ -3,12 +3,12 @@ import {
3
3
  isPhaseTodoPlanSchema,
4
4
  isPhaselessTodoPlanSchema,
5
5
  projectTodoCrossPlanDependencies,
6
- localTaskRef,
7
- removedTaskRef,
8
- todoTaskCarrySemantics as taskSemantics,
6
+ normalizeCheckoutEol,
7
+ isFinishedTodoTaskState,
9
8
  } from './todo-store-view.mjs';
10
9
  export {
11
10
  isDecoupledPhaseTodoPlanSchema,
11
+ isFinishedTodoTaskState,
12
12
  isPhaseTodoPlanSchema,
13
13
  isPhaselessTodoPlanSchema,
14
14
  projectTodoCrossPlanDependencies,
@@ -81,7 +81,6 @@ const CROSS_PLAN_IMPORT_TRANSACTION_SCHEMA = 'lattice.todo_cross_plan_import_tra
81
81
  const SOURCE_CUTOVER_BARRIER_REF = `${STORE_ROOT_REF}/source-cutover-recovery.json`;
82
82
  const SOURCE_CUTOVER_RECOVERY_CAPABILITY = Symbol('lattice.todo.source-cutover-recovery');
83
83
  const STORE_LOCK_HELD = Symbol('lattice.todo.lock-held');
84
- const MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
85
84
  const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring']);
86
85
  const TODO_REVISION_SCHEMAS = Object.freeze([
87
86
  'lattice.todo_revision.v1', 'lattice.todo_revision.v2',
@@ -162,11 +161,6 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
162
161
  fail(code, bytes.length > maxBytes ? 'size_limit_exceeded' : reason, detail);
163
162
  }
164
163
  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
164
  if (text.startsWith('\uFEFF')) fail(code, reason, detail);
171
165
  const body = text.endsWith('\n') ? text.slice(0, -1) : text;
172
166
  let value;
@@ -182,7 +176,7 @@ function parseCanonicalJsonLine(bytes, { code, reason, maxBytes, validate, ref =
182
176
  async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing = false }) {
183
177
  const state = await pathState(repoRoot, ref, code, { missing });
184
178
  if (state === null) return null;
185
- const bytes = await readFile(state.absolute);
179
+ const bytes = normalizeCheckoutEol(await readFile(state.absolute));
186
180
  return parseCanonicalJsonLine(bytes, {
187
181
  code, reason: 'artifact_truncated_or_trailing_bytes', maxBytes, validate, ref,
188
182
  });
@@ -191,7 +185,7 @@ async function readArtifact(repoRoot, ref, { code, maxBytes, validate, missing =
191
185
  async function readSnapshotArtifact(repoRoot, ref) {
192
186
  const state = await pathState(repoRoot, ref, 'STORE_INCONSISTENT', { missing: true });
193
187
  if (state === null) return null;
194
- const bytes = await readFile(state.absolute);
188
+ const bytes = normalizeCheckoutEol(await readFile(state.absolute));
195
189
  return parseCanonicalJsonLine(bytes, {
196
190
  code: 'SNAPSHOT_INVALID', reason: 'snapshot_truncated_or_trailing_bytes',
197
191
  maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoSnapshot, ref,
@@ -205,11 +199,6 @@ function parseJournalSegment(bytes, ref = null) {
205
199
  ? 'journal_segment_limit_exceeded' : 'journal_empty', detail);
206
200
  }
207
201
  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
202
  if (!text.endsWith('\n') || text.startsWith('\uFEFF')) fail('STORE_CORRUPT', 'journal_byte_contract', detail);
214
203
  const lines = text.slice(0, -1).split('\n');
215
204
  if (lines.some((line) => line.length === 0)) fail('STORE_CORRUPT', 'journal_truncated_or_empty_line');
@@ -239,7 +228,7 @@ async function readJournal(repoRoot, journalRef) {
239
228
  }
240
229
  const ref = path.posix.join(path.posix.dirname(journalRef), 'sealed', name);
241
230
  const sealed = await pathState(repoRoot, ref, 'STORE_CORRUPT');
242
- const bytes = await readFile(sealed.absolute);
231
+ const bytes = normalizeCheckoutEol(await readFile(sealed.absolute));
243
232
  const [, startText, endText, previousDigest, segmentDigest] = name.match(
244
233
  /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u,
245
234
  );
@@ -257,7 +246,7 @@ async function readJournal(repoRoot, journalRef) {
257
246
  if (error instanceof TodoStoreError) throw error;
258
247
  if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
259
248
  }
260
- const activeBytes = await readFile(state.absolute);
249
+ const activeBytes = normalizeCheckoutEol(await readFile(state.absolute));
261
250
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
262
251
  if (!duplicateActive) {
263
252
  segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
@@ -326,7 +315,7 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
326
315
  try {
327
316
  const state = await lstat(absolute);
328
317
  if (state.isSymbolicLink() || !state.isFile()) fail('STORE_CORRUPT', 'plan_scoped_journal_unsafe');
329
- bytes = await readFile(absolute);
318
+ bytes = normalizeCheckoutEol(await readFile(absolute));
330
319
  } catch (error) {
331
320
  if (error instanceof TodoStoreError) throw error;
332
321
  if (error?.code === 'ENOENT') return { ref, events: [], activeBytes: Buffer.alloc(0) };
@@ -484,7 +473,7 @@ function localSuccessors(plan, taskId) {
484
473
  return plan.tasks.map(({ task_id }) => task_id).filter((candidate) => localPredecessors(plan, candidate).includes(taskId));
485
474
  }
486
475
 
487
- function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSource } = {}) {
476
+ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
488
477
  const states = new Map(plan.tasks.map(({ task_id }) => [task_id, taskState(task_id)]));
489
478
  const phaseStates = new Map(phasesOf(plan).map(({ phase_id }) => [phase_id, emptyPhaseState(phase_id)]));
490
479
  const doneDigest = new Map();
@@ -496,22 +485,12 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
496
485
  // storeを恒久的に書き込み不能へ落とす(2026-08-22実被弾: reopen済み旧doneのdangling blob)。
497
486
  const pendingVerifications = new Map();
498
487
  const importedGenesis = events[0]?.payload.historical_import === true;
499
- let previousTime = null;
500
488
  for (const event of events) {
501
489
  if (event.project_id !== plan.project_id || event.plan_key !== plan.plan_key || event.plan_version !== plan.plan_version) {
502
490
  fail('STORE_CORRUPT', 'journal_identity_mismatch');
503
491
  }
504
492
  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;
493
+ // u03 A4/A5: order is the sequence + hash chain; recorded_at is a shown fact, never an integrity key.
515
494
  if (event.kind === 'plan_genesis') {
516
495
  if (event.payload.plan_digest !== plan.plan_digest || event.payload.topology_digest !== plan.topology_digest
517
496
  || event.payload.predecessor_plan_digest !== plan.predecessor_plan_digest) {
@@ -657,7 +636,8 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
657
636
  }
658
637
  const state = states.get(event.task_id);
659
638
  if (state === undefined) fail('STORE_INCONSISTENT', 'event_task_missing');
660
- const dependenciesDone = localPredecessors(plan, event.task_id).every((id) => states.get(id)?.status === 'done');
639
+ const dependenciesDone = localPredecessors(plan, event.task_id)
640
+ .every((id) => isFinishedTodoTaskState(states.get(id)));
661
641
  if (event.kind === 'start') {
662
642
  if (event.payload.start_mode === 'rebind') {
663
643
  // 改訂でcarryされたin-progressの再束縛。状態・開始時刻は動かさず、start束縛だけを
@@ -726,9 +706,26 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
726
706
  if (state.status !== 'blocked') fail('STORE_INCONSISTENT', 'invalid_unblock_transition');
727
707
  state.status = 'in-progress'; state.blocked_reason = null;
728
708
  } 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');
709
+ const priorStatus = event.payload.prior_status;
710
+ if (priorStatus === undefined) {
711
+ // legacy payload: pending/blocked only.
712
+ if (!['pending', 'blocked'].includes(state.status)) fail('STORE_INCONSISTENT', 'invalid_retire_transition');
713
+ } else {
714
+ if (state.status === 'retired') fail('STORE_INCONSISTENT', 'invalid_retire_transition');
715
+ if (priorStatus !== state.status) fail('STORE_INCONSISTENT', 'retire_prior_status_mismatch');
716
+ }
717
+ const wasDone = state.status === 'done';
731
718
  state.status = 'retired'; state.blocked_reason = event.payload.reason;
719
+ state.done_at = wasDone ? state.done_at : null;
720
+ // done_at and imported survive a retire from done so the finished mark stays (isFinishedTodoTaskState).
721
+ state.evidence = null; state.test_result = null; state.imported = wasDone ? state.imported : false;
722
+ state.evidence_unverified = false;
723
+ authoredStartBindings.delete(event.task_id);
724
+ if (wasDone) {
725
+ completion.delete(event.task_id);
726
+ pendingVerifications.delete(`task:${event.task_id}`);
727
+ }
728
+ // a retired task is unreachable by promotion/reopen (both require status done), so doneDigest is left as is.
732
729
  } else if (event.kind === 'done') {
733
730
  if (event.payload.done_mode === 'authored') {
734
731
  if (state.status !== 'in-progress' || !dependenciesDone) fail('STORE_INCONSISTENT', 'invalid_done_transition');
@@ -788,20 +785,8 @@ function replay(plan, events, { now = new Date(), verifyEvidence, verifyImportSo
788
785
  if (state.status !== 'done' || doneDigest.get(event.task_id) !== event.payload.target_done_digest) {
789
786
  fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
790
787
  }
791
- {
792
- // 暗黙のterminal-audit Phaseがaccepted/closed_unauditedの後にtaskだけを無警告でreopen
793
- // できると、監査済み(または監査なしで閉じた)まま(gantt上も畳まれたまま)裏で作業が
794
- // 再開する抜け道になり、ADR 0147/0148の「監査の記録なしに閉じたことにさせない」を
795
- // 潜脱する。v4/v5の既存Phaseと同じ規律を暗黙Phaseにも及ぼし、phase_reopenを先に
796
- // 通させる。closed_unauditedをここへ足さないと、ADR 0148で新設した状態だけが
797
- // このgateを素通りしてしまう。
798
- const phaseId = isPhaselessTodoPlanSchema(plan.schema)
799
- ? TERMINAL_AUDIT_PHASE_ID
800
- : plan.tasks.find(({ task_id }) => task_id === event.task_id).phase_id;
801
- if (['accepted', 'closed_unaudited'].includes(derivedPhaseStatus(plan, states, phaseStates, phaseId))) {
802
- fail('STORE_INCONSISTENT', 'task_reopen_requires_phase_reopen');
803
- }
804
- }
788
+ // u03 A15: reopening a task in an accepted/closed_unaudited phase is the user's change. The
789
+ // phase decision stays as recorded; Plan shows it as acceptance_stale (derived from the journal).
805
790
  const startedSuccessor = localSuccessors(plan, event.task_id).some((id) => states.get(id).status !== 'pending');
806
791
  if (startedSuccessor && event.payload.override_reason === null) fail('STORE_INCONSISTENT', 'reopen_has_started_successor');
807
792
  state.status = 'in-progress'; state.done_at = null; state.evidence = null; state.test_result = null;
@@ -871,10 +856,14 @@ function snapshotFor(plan, events, tasks) {
871
856
  return snapshot;
872
857
  }
873
858
 
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;
859
+ /**
860
+ * Validates the merged graph and returns cross-plan findings (u03 A24/A25b/N6): a reference into
861
+ * another plan never refuses for a stale digest or a removed endpoint; a removed endpoint's edge
862
+ * is left out of the graph. Same-plan shape and merged cycles still refuse.
863
+ */
864
+ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPlanDependencies(members),
865
+ { newPlanKey = null } = {}) {
866
+ const findings = [];
878
867
  const tasks = new Map();
879
868
  for (const member of members) for (const task of member.plan.tasks) {
880
869
  tasks.set(`${member.plan.project_id}\0${member.plan.plan_key}\0${task.task_id}`, member.plan.topology_digest);
@@ -889,38 +878,43 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
889
878
  adjacency.set(key, []);
890
879
  }
891
880
  }
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');
881
+ // Returns the node key, or null when a foreign endpoint is gone (the edge is then skipped).
882
+ const bindIn = (nodes, key, ref, ownerPlan, eventDigest, side, danglingReason) => {
883
+ const foreign = ref.project_id !== ownerPlan.project_id || ref.plan_key !== ownerPlan.plan_key;
884
+ const topology = nodes.get(key);
885
+ const finding = (reason) => findings.push({ owner_plan_key: ownerPlan.plan_key,
886
+ event_digest: eventDigest, side, ref: structuredClone(ref), reason });
887
+ // A plan being created is new input: it must name existing endpoints at their current topology.
888
+ const strict = !foreign || ownerPlan.plan_key === newPlanKey;
889
+ if (topology === undefined) {
890
+ if (strict) fail('STORE_INCONSISTENT', danglingReason);
891
+ finding('endpoint_missing');
892
+ return null;
900
893
  }
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');
894
+ if (foreign && ref.expected_topology_digest === undefined) fail('STORE_INCONSISTENT', 'cross_plan_binding_missing');
895
+ if (ref.expected_topology_digest !== undefined && topology !== ref.expected_topology_digest) {
896
+ if (foreign && ownerPlan.plan_key === newPlanKey) fail('STORE_INCONSISTENT', 'binding_stale');
897
+ finding('binding_stale');
911
898
  }
912
899
  return key;
913
900
  };
901
+ const bind = (ref, ownerPlan, eventDigest = null, side = null) => bindIn(tasks,
902
+ `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`, ref, ownerPlan, eventDigest, side, 'dangling_dependency');
903
+ const bindPhase = (ref, ownerPlan) => bindIn(phases,
904
+ `phase\0${ref.project_id}\0${ref.plan_key}\0${ref.phase_id}`, ref, ownerPlan, null, 'from',
905
+ 'dangling_phase_dependency');
914
906
  for (const { plan } of members) {
915
907
  for (const edge of plan.hard_dependencies) {
916
- const from = bind(edge.from, plan); const to = bind(edge.to, plan);
908
+ const from = bind(edge.from, plan, null, 'from'); const to = bind(edge.to, plan, null, 'to');
909
+ if (from === null || to === null) continue;
917
910
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
918
911
  adjacency.get(from).push(to);
919
912
  }
920
913
  for (const join of plan.joins) {
921
- const before = bind(join.before, plan);
914
+ const before = bind(join.before, plan, null, 'to');
922
915
  for (const afterRef of join.after) {
923
- const after = bind(afterRef, plan);
916
+ const after = bind(afterRef, plan, null, 'from');
917
+ if (before === null || after === null) continue;
924
918
  if (after === before) fail('STORE_INCONSISTENT', 'join_self_edge');
925
919
  adjacency.get(after).push(before);
926
920
  }
@@ -938,7 +932,8 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
938
932
  }
939
933
  }
940
934
  for (const edge of plan.phase_accept_dependencies) {
941
- adjacency.get(bindPhase(edge.from, plan)).push(bind(edge.to, plan));
935
+ const from = bindPhase(edge.from, plan); const to = bind(edge.to, plan, null, 'to');
936
+ if (from !== null && to !== null) adjacency.get(from).push(to);
942
937
  }
943
938
  }
944
939
  }
@@ -946,8 +941,10 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
946
941
  const owner = members.find(({ plan }) => plan.project_id === dependency.to.project_id
947
942
  && plan.plan_key === dependency.to.plan_key);
948
943
  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);
944
+ const digest = dependency.event_digest ?? null;
945
+ const from = bind(dependency.from, owner.plan, digest, 'from');
946
+ const to = bind(dependency.to, owner.plan, digest, 'to');
947
+ if (from === null || to === null) continue;
951
948
  if (from === to) fail('STORE_INCONSISTENT', 'self_edge');
952
949
  adjacency.get(from).push(to);
953
950
  }
@@ -958,6 +955,11 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
958
955
  colors.set(node, 1); for (const next of adjacency.get(node)) visit(next); colors.set(node, 2);
959
956
  };
960
957
  for (const node of adjacency.keys()) visit(node);
958
+ // A join binds `before` once per member: keep one finding per identity, in code-unit order.
959
+ const order = (finding) => JSON.stringify([finding.owner_plan_key, finding.event_digest ?? '',
960
+ finding.side, finding.ref.plan_key, finding.ref.task_id ?? finding.ref.phase_id, finding.reason]);
961
+ return [...new Map(findings.map((finding) => [canonicalizeTodoArtifact(finding), finding])).values()]
962
+ .sort((left, right) => (order(left) < order(right) ? -1 : order(left) > order(right) ? 1 : 0));
961
963
  }
962
964
 
963
965
  function crossPlanDependencyTask(store, ref) {
@@ -1110,6 +1112,24 @@ function evidenceVerifier(manifest, repoRoot, hard, newEventDigest = null) {
1110
1112
  };
1111
1113
  }
1112
1114
 
1115
+ /**
1116
+ * Read-only (a12): the evidence blob is present with its recorded digest but no ref reaches it yet,
1117
+ * i.e. it is waiting for a commit (message evidence or an uncommitted file). Missing or changed
1118
+ * bytes are not "uncommitted" and stay evidence_unverified refusals.
1119
+ */
1120
+ export function isTodoEvidenceUncommitted({ repoRoot, store, evidence }) {
1121
+ if (!validateEvidenceDescriptor(evidence)) return false;
1122
+ const repoRef = store.manifest.repositories.find(({ repo_id: id }) => id === evidence.repo_id)?.path;
1123
+ if (repoRef === undefined) return false;
1124
+ const absoluteRepo = path.resolve(repoRoot, repoRef);
1125
+ try {
1126
+ return sha256Bytes(readEvidenceBlob(absoluteRepo, evidence.git_blob_oid)) === evidence.content_digest
1127
+ && !reachableObjects(absoluteRepo).has(evidence.git_blob_oid);
1128
+ } catch {
1129
+ return false;
1130
+ }
1131
+ }
1132
+
1113
1133
  function pinnedSourceLine(repoRoot, source, cache = null) {
1114
1134
  // commit の型検査と blob 読みを 1 回の cat-file --batch へまとめる(object ごとの git
1115
1135
  // 子起動はWindowsで可視コンソールを開き、起動コストだけで走査を桁で遅くする)。
@@ -1329,9 +1349,9 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1329
1349
 
1330
1350
  function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache = null) {
1331
1351
  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;
1352
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) return;
1333
1353
  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)
1354
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(trustedPlan?.schema)
1335
1355
  ? trustedPlan.tasks : [])
1336
1356
  .map((task) => [task.task_id, task.narrative_anchor]));
1337
1357
  for (const task of plan.tasks) {
@@ -1394,6 +1414,9 @@ async function readTodoStoreLocked(options = {}) {
1394
1414
  await recoverCrossPlanImports(repoRoot);
1395
1415
  const recovery = { manifestDirty: false };
1396
1416
  const store = await readTodoStoreView({ ...options, recovery });
1417
+ if (options.assertHeld) {
1418
+ store.cross_plan_repairs = await repairCrossPlanBindings(repoRoot, store, options.repairContext);
1419
+ }
1397
1420
  // Every member and merged graph has validated before any derived publication.
1398
1421
  for (const member of store.members) {
1399
1422
  if (!member.snapshot_stale) continue;
@@ -1529,8 +1552,8 @@ async function readTodoStoreView(options = {}) {
1529
1552
  snapshotStale = snapshot === null || canonicalizeTodoArtifact(snapshot) !== canonicalizeTodoArtifact(expectedSnapshot);
1530
1553
  } catch (error) {
1531
1554
  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;
1555
+ && !['unsafe_artifact_path', 'path_alias_or_escape', 'path_outside_store']
1556
+ .includes(error.detail.reason)) snapshotStale = true;
1534
1557
  else throw error;
1535
1558
  }
1536
1559
  if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
@@ -1546,16 +1569,136 @@ async function readTodoStoreView(options = {}) {
1546
1569
  snapshot: snapshotStale ? expectedSnapshot : snapshot,
1547
1570
  tasks, phases, coordination, snapshot_stale: snapshotStale });
1548
1571
  }
1549
- validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded), {
1550
- tolerateStaleBindings: options.tolerateStaleBindings === true,
1551
- });
1572
+ const crossPlanFindings = validateMergedGraph(loaded, projectTodoCrossPlanDependencies(loaded));
1552
1573
  return {
1553
1574
  schema: 'lattice.todo_store_read.v1', project_id: manifest.project_id, manifest,
1554
1575
  members: loaded, snapshot_stale: loaded.some((member) => member.snapshot_stale),
1576
+ cross_plan_findings: crossPlanFindings,
1555
1577
  };
1556
1578
  }
1557
1579
 
1580
+ /**
1581
+ * Composes the source plan's recorded task migrations back to the version whose topology the
1582
+ * connection names (u03): returns the source task id it maps to now, 'removed', or null (unknown).
1583
+ */
1584
+ async function carriedSourceTask(repoRoot, source, ref, versionsCache) {
1585
+ if (!versionsCache.has(source)) {
1586
+ const base = `${STORE_ROOT_REF}/plans/${source.plan.plan_key}`;
1587
+ const byDigest = new Map();
1588
+ let names = [];
1589
+ try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1590
+ for (const version of names) {
1591
+ if (version === source.plan.plan_version || !isTodoIdentifier(version)) continue;
1592
+ const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1593
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1594
+ }).catch(() => null);
1595
+ if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1596
+ }
1597
+ versionsCache.set(source, byDigest);
1598
+ }
1599
+ const byDigest = versionsCache.get(source);
1600
+ // Newest first: the active genesis maps its predecessor's ids onto the active ids.
1601
+ const migrations = [source.journal.events[0].payload.task_migration ?? []];
1602
+ for (let plan = source.plan; migrations.length <= byDigest.size;) {
1603
+ const predecessor = byDigest.get(plan.predecessor_plan_digest);
1604
+ if (predecessor === undefined) return null;
1605
+ if (predecessor.plan.topology_digest === ref.expected_topology_digest) {
1606
+ let taskId = ref.task_id;
1607
+ for (const migration of migrations.reverse()) {
1608
+ const entry = migration.find(({ from_task_id: from }) => from === taskId);
1609
+ if (entry === undefined) return null;
1610
+ if (entry.to_task_id === 'removed') return 'removed';
1611
+ taskId = entry.to_task_id;
1612
+ }
1613
+ return taskId;
1614
+ }
1615
+ let journal;
1616
+ try { journal = await readJournal(repoRoot, predecessor.journalRef); } catch { return null; }
1617
+ migrations.push(journal.events[0].payload.task_migration ?? []);
1618
+ plan = predecessor.plan;
1619
+ }
1620
+ return null;
1621
+ }
1622
+
1623
+ /**
1624
+ * u03 A24/A25b: a live connection whose source plan was revised follows the source's recorded
1625
+ * task migrations (Plan's revision decision, the carry proof): carried -> tombstone + replacement,
1626
+ * removed -> tombstone. A repair that would duplicate an edge or close a cycle is dropped alone and
1627
+ * stays a finding; the rest publish once per owner chain and update the in-memory store.
1628
+ */
1629
+ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, recordedAt }) {
1630
+ const stale = (store.cross_plan_findings ?? []).filter(({ event_digest: digest, side }) => (
1631
+ digest !== null && side === 'from'));
1632
+ if (stale.length === 0) return [];
1633
+ const live = new Map(projectTodoCrossPlanDependencies(store.members)
1634
+ .map((dependency) => [dependency.event_digest, dependency]));
1635
+ const versionsCache = new Map();
1636
+ const staged = new Map();
1637
+ const repairs = [];
1638
+ let findings = store.cross_plan_findings;
1639
+ for (const finding of stale) {
1640
+ const dependency = live.get(finding.event_digest);
1641
+ const source = store.members.find(({ plan }) => plan.project_id === finding.ref.project_id
1642
+ && plan.plan_key === finding.ref.plan_key);
1643
+ const owner = store.members.find(({ plan_scoped: chain }) => (chain?.events ?? [])
1644
+ .some(({ event_digest: digest }) => digest === finding.event_digest));
1645
+ if (!dependency || !source || !owner) continue;
1646
+ const mapped = await carriedSourceTask(repoRoot, source, dependency.from, versionsCache);
1647
+ if (mapped === null) continue;
1648
+ if (!staged.has(owner)) {
1649
+ staged.set(owner, { ...owner, plan_scoped: { ...owner.plan_scoped,
1650
+ events: [...owner.plan_scoped.events], activeBytes: owner.plan_scoped.activeBytes } });
1651
+ }
1652
+ const target = staged.get(owner);
1653
+ const before = { events: target.plan_scoped.events.length, activeBytes: target.plan_scoped.activeBytes };
1654
+ const inputs = [{ kind: 'cross_plan_dependency_removed', payload: {
1655
+ target_event_digest: dependency.event_digest,
1656
+ reason: `source ${source.plan.plan_key} ${source.plan.plan_version} ${mapped === 'removed'
1657
+ ? 'removed the task' : 'carried the task'}`,
1658
+ } }];
1659
+ if (mapped !== 'removed') inputs.push({ kind: 'cross_plan_dependency', payload: {
1660
+ from: { ...dependency.from, task_id: mapped, expected_topology_digest: source.plan.topology_digest },
1661
+ to: dependency.to, reason: dependency.reason,
1662
+ } });
1663
+ for (const input of inputs) {
1664
+ const event = buildPlanScopedEvent(target, { ...input, actor, recorded_at: recordedAt });
1665
+ target.plan_scoped.activeBytes = Buffer.concat([target.plan_scoped.activeBytes,
1666
+ planScopedEventBytes(target, event)]);
1667
+ target.plan_scoped.events.push(event);
1668
+ }
1669
+ const prospective = store.members.map((member) => staged.get(member) ?? member);
1670
+ const keys = projectTodoCrossPlanDependencies(prospective)
1671
+ .map(({ from, to }) => `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`);
1672
+ try {
1673
+ if (new Set(keys).size !== keys.length) fail('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate');
1674
+ findings = validateMergedGraph(prospective);
1675
+ } catch (error) {
1676
+ if (!(error instanceof TodoStoreError)) throw error;
1677
+ target.plan_scoped.events.length = before.events;
1678
+ target.plan_scoped.activeBytes = before.activeBytes;
1679
+ continue;
1680
+ }
1681
+ repairs.push({ owner_plan_key: owner.plan.plan_key, original_event_digest: dependency.event_digest,
1682
+ replacement_event_digest: mapped === 'removed' ? null : target.plan_scoped.events.at(-1).event_digest,
1683
+ action: mapped === 'removed' ? 'tombstoned' : 'rebound' });
1684
+ }
1685
+ if (repairs.length === 0) return [];
1686
+ await assertHeld();
1687
+ for (const [owner, target] of staged) {
1688
+ if (target.plan_scoped.events.length === owner.plan_scoped.events.length) continue;
1689
+ await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), target.plan_scoped.activeBytes);
1690
+ owner.plan_scoped = target.plan_scoped;
1691
+ owner.coordination = projectTodoCoordination(target.plan_scoped.events);
1692
+ }
1693
+ store.cross_plan_findings = findings;
1694
+ return repairs;
1695
+ }
1696
+
1558
1697
  export async function readTodoStoreStable(options = {}) {
1698
+ return readStoreStableWith(options, readTodoStore);
1699
+ }
1700
+
1701
+ async function readStoreStableWith(options, readStore) {
1559
1702
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1560
1703
  const maximumAttempts = options.maximumAttempts ?? 4;
1561
1704
  if (!Number.isSafeInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 16) {
@@ -1572,7 +1715,7 @@ export async function readTodoStoreStable(options = {}) {
1572
1715
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1573
1716
  });
1574
1717
  try {
1575
- const store = await readTodoStore(options);
1718
+ const store = await readStore(options);
1576
1719
  const after = await readArtifact(repoRoot, MANIFEST_REF, {
1577
1720
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
1578
1721
  });
@@ -1602,6 +1745,260 @@ export async function readTodoStoreStable(options = {}) {
1602
1745
  fail('STORE_BUSY', 'stable_read_exhausted', { attempts: maximumAttempts });
1603
1746
  }
1604
1747
 
1748
+ // Store display read (dfd-store-display-read.md). Read-only toward canonical Store files:
1749
+ // no lock, recovery or writer; the only write is the derived checkpoint below.
1750
+ const DISPLAY_CHECKPOINT_REF = '.lattice/generated/store-display/last-verified.json';
1751
+ const DISPLAY_CHECKPOINT_SCHEMA = 'lattice.todo_store_display_checkpoint.v1';
1752
+ const DISPLAY_SOURCE_SCHEMA = 'lattice.todo_store_display_source.v1';
1753
+ const DISPLAY_CHECKPOINT_MAX_BYTES = 64 * 1_048_576;
1754
+
1755
+ const nullableString = (value) => (typeof value === 'string' ? value : null);
1756
+
1757
+ /** Any display-read error as public {code, detail}; an untyped fault is warned server-side only. */
1758
+ function displayFault(error) {
1759
+ if (error instanceof TodoStoreError) return { code: error.code, detail: { ...error.detail } };
1760
+ process.emitWarning(`Store display read fault: ${error?.stack ?? error}`, { code: 'LATTICE_STORE_DISPLAY_READ_FAULT' });
1761
+ return { code: 'STORE_READ_FAULT', detail: { reason: 'unexpected_error' } };
1762
+ }
1763
+
1764
+ function displayFailure(error) {
1765
+ const { code, detail } = displayFault(error);
1766
+ return { code, reason: detail.reason ?? null };
1767
+ }
1768
+
1769
+ async function canonicalRepoRoot(repoRoot) {
1770
+ try { return await realpath(repoRoot); } catch { return path.resolve(repoRoot); }
1771
+ }
1772
+
1773
+ /** Bounded raw bytes of a contained `.lattice/todo` file; no schema or digest checks. */
1774
+ async function readRawStoreFile(repoRoot, ref, maxBytes, { missing = false } = {}) {
1775
+ if (typeof ref !== 'string') fail('STORE_INCONSISTENT', 'ref_invalid');
1776
+ const state = await pathState(repoRoot, ref, 'STORE_INCONSISTENT', { missing });
1777
+ if (state === null) return null;
1778
+ if (state.stats.size > maxBytes) fail('STORE_INCONSISTENT', 'size_limit_exceeded', { ref });
1779
+ try { return await readFile(state.absolute); } catch { fail('STORE_INCONSISTENT', 'artifact_read_failed', { ref }); }
1780
+ }
1781
+
1782
+ async function readRawStoreJson(repoRoot, ref, maxBytes) {
1783
+ const bytes = await readRawStoreFile(repoRoot, ref, maxBytes);
1784
+ const text = decodeUtf8(bytes, 'STORE_INCONSISTENT', 'invalid_utf8');
1785
+ try { return JSON.parse(text); } catch { fail('STORE_INCONSISTENT', 'json_invalid', { ref }); }
1786
+ }
1787
+
1788
+ async function rawLastEventDigest(repoRoot, ref, { missing = false } = {}) {
1789
+ const bytes = await readRawStoreFile(repoRoot, ref, TODO_LIMITS.journalSegmentBytes, { missing });
1790
+ if (bytes === null) return null;
1791
+ const lines = decodeUtf8(bytes, 'STORE_INCONSISTENT', 'invalid_utf8').split('\n').filter(Boolean);
1792
+ let digest;
1793
+ try { digest = JSON.parse(lines.at(-1)).event_digest; } catch { fail('STORE_INCONSISTENT', 'json_invalid', { ref }); }
1794
+ if (typeof digest !== 'string') fail('STORE_INCONSISTENT', 'event_digest_missing', { ref });
1795
+ return digest;
1796
+ }
1797
+
1798
+ async function readRawManifest(repoRoot) {
1799
+ const manifest = await readRawStoreJson(repoRoot, MANIFEST_REF, TODO_LIMITS.snapshotBytes);
1800
+ if (manifest === null || typeof manifest !== 'object' || !Array.isArray(manifest.members)) {
1801
+ fail('STORE_INCONSISTENT', 'manifest_members_unenumerable', { ref: MANIFEST_REF });
1802
+ }
1803
+ return manifest;
1804
+ }
1805
+
1806
+ function sortDisplayMembers(members) {
1807
+ return members.sort((left, right) => String(left.plan_key).localeCompare(String(right.plan_key)));
1808
+ }
1809
+
1810
+ async function observeDisplaySource(repoRoot, manifest) {
1811
+ const diagnostics = [];
1812
+ const members = [];
1813
+ for (const descriptor of manifest.members) {
1814
+ const entry = descriptor !== null && typeof descriptor === 'object' ? descriptor : {};
1815
+ const planKey = nullableString(entry.plan_key);
1816
+ const observe = async (field, read) => {
1817
+ try { return await read(); } catch (error) {
1818
+ diagnostics.push({ plan_key: planKey, field, ...displayFailure(error) });
1819
+ return null;
1820
+ }
1821
+ };
1822
+ const journalRef = nullableString(entry.journal_ref);
1823
+ members.push({
1824
+ plan_key: planKey,
1825
+ active_plan_version: nullableString(entry.active_plan_version),
1826
+ plan_digest: await observe('plan_digest', async () => {
1827
+ const digest = (await readRawStoreJson(repoRoot, entry.plan_ref, TODO_LIMITS.snapshotBytes))?.plan_digest;
1828
+ if (typeof digest !== 'string') fail('STORE_INCONSISTENT', 'plan_digest_missing');
1829
+ return digest;
1830
+ }),
1831
+ topology_digest: nullableString(entry.topology_digest),
1832
+ lifecycle_head: await observe('lifecycle_head', () => rawLastEventDigest(repoRoot, journalRef)),
1833
+ plan_scoped_head: journalRef === null ? null : await observe('plan_scoped_head', () => (
1834
+ rawLastEventDigest(repoRoot, planScopedJournalRef(journalRef), { missing: true }))),
1835
+ });
1836
+ }
1837
+ return {
1838
+ schema: DISPLAY_SOURCE_SCHEMA,
1839
+ repository_identity: sha256Bytes(Buffer.from(await canonicalRepoRoot(repoRoot), 'utf8')),
1840
+ project_id: nullableString(manifest.project_id),
1841
+ manifest_digest: nullableString(manifest.manifest_digest),
1842
+ members: sortDisplayMembers(members),
1843
+ diagnostics,
1844
+ };
1845
+ }
1846
+
1847
+ async function verifiedDisplaySource(repoRoot, store) {
1848
+ return {
1849
+ schema: DISPLAY_SOURCE_SCHEMA,
1850
+ repository_identity: sha256Bytes(Buffer.from(await canonicalRepoRoot(repoRoot), 'utf8')),
1851
+ project_id: store.project_id,
1852
+ manifest_digest: store.manifest.manifest_digest,
1853
+ members: sortDisplayMembers(store.members.map(({ descriptor, plan, journal, plan_scoped: planScoped }) => ({
1854
+ plan_key: descriptor.plan_key,
1855
+ active_plan_version: descriptor.active_plan_version,
1856
+ plan_digest: plan.plan_digest,
1857
+ topology_digest: descriptor.topology_digest,
1858
+ lifecycle_head: journal.events.at(-1).event_digest,
1859
+ plan_scoped_head: planScoped.events.at(-1)?.event_digest ?? null,
1860
+ }))),
1861
+ diagnostics: [],
1862
+ };
1863
+ }
1864
+
1865
+ /** The existing read model without implementation bytes; JSON-serializable. */
1866
+ function displayStoreView(store) {
1867
+ return JSON.parse(JSON.stringify({
1868
+ schema: store.schema, project_id: store.project_id, manifest: store.manifest,
1869
+ members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => ({
1870
+ ...member,
1871
+ journal: { events: journal.events },
1872
+ plan_scoped: { ref: planScoped.ref, events: planScoped.events },
1873
+ })),
1874
+ }));
1875
+ }
1876
+
1877
+ function checkpointDigest(checkpoint) {
1878
+ const { checkpoint_digest: _digest, ...body } = checkpoint;
1879
+ return sha256Bytes(Buffer.from(JSON.stringify(body), 'utf8'));
1880
+ }
1881
+
1882
+ /**
1883
+ * Returns the checkpoint attributable to this repository, or null. Never writes.
1884
+ * A readable current projectId must match; without one (broken manifest) the realpath
1885
+ * repository identity attributes it, since the file lives in this repository's .lattice.
1886
+ */
1887
+ async function readDisplayCheckpoint(repoRoot, projectId) {
1888
+ const root = await canonicalRepoRoot(repoRoot);
1889
+ const absolute = path.resolve(root, DISPLAY_CHECKPOINT_REF);
1890
+ let checkpoint;
1891
+ try {
1892
+ const stats = await lstat(absolute);
1893
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.size > DISPLAY_CHECKPOINT_MAX_BYTES) return null;
1894
+ if (await realpath(absolute) !== absolute) return null;
1895
+ checkpoint = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readFile(absolute)));
1896
+ } catch { return null; }
1897
+ const valid = exactRecord(checkpoint, ['schema', 'verified_at', 'source', 'store', 'checkpoint_digest'])
1898
+ && checkpoint.schema === DISPLAY_CHECKPOINT_SCHEMA
1899
+ && isStrictTodoTimestamp(checkpoint.verified_at)
1900
+ && checkpoint.checkpoint_digest === checkpointDigest(checkpoint)
1901
+ && checkpoint.source?.schema === DISPLAY_SOURCE_SCHEMA
1902
+ && checkpoint.source.repository_identity === sha256Bytes(Buffer.from(root, 'utf8'))
1903
+ && typeof checkpoint.source.project_id === 'string'
1904
+ && (typeof projectId !== 'string' || checkpoint.source.project_id === projectId)
1905
+ && checkpoint.store?.project_id === checkpoint.source.project_id && Array.isArray(checkpoint.store.members);
1906
+ return valid ? checkpoint : null;
1907
+ }
1908
+
1909
+ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
1910
+ const root = await canonicalRepoRoot(repoRoot);
1911
+ let directory = root;
1912
+ for (const segment of path.posix.dirname(DISPLAY_CHECKPOINT_REF).split('/')) {
1913
+ directory = path.join(directory, segment);
1914
+ if (segment !== '.lattice') await mkdir(directory).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
1915
+ const stats = await lstat(directory);
1916
+ if (stats.isSymbolicLink() || !stats.isDirectory() || await realpath(directory) !== directory) {
1917
+ fail('STORE_DISPLAY_CHECKPOINT_UNSAFE', 'unsafe_checkpoint_directory', { ref: path.relative(root, directory) });
1918
+ }
1919
+ }
1920
+ const checkpoint = { schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store, checkpoint_digest: '' };
1921
+ checkpoint.checkpoint_digest = checkpointDigest(checkpoint);
1922
+ await atomicWrite(path.resolve(root, DISPLAY_CHECKPOINT_REF), Buffer.from(JSON.stringify(checkpoint), 'utf8'));
1923
+ }
1924
+
1925
+ async function readRawDisplayMembers(repoRoot, manifest) {
1926
+ const members = [];
1927
+ const dropped = [];
1928
+ for (const descriptor of manifest.members) {
1929
+ const entry = descriptor !== null && typeof descriptor === 'object' ? descriptor : {};
1930
+ const planKey = nullableString(entry.plan_key);
1931
+ let snapshot;
1932
+ try { snapshot = await readRawStoreJson(repoRoot, entry.snapshot_ref, TODO_LIMITS.snapshotBytes); } catch (error) {
1933
+ dropped.push({ plan_key: planKey, snapshot_ref: nullableString(entry.snapshot_ref), ...displayFailure(error) });
1934
+ continue;
1935
+ }
1936
+ // Plans are immutable per version; an unreadable plan drops only the plan, not the member.
1937
+ let plan = null;
1938
+ try { plan = await readRawStoreJson(repoRoot, entry.plan_ref, TODO_LIMITS.snapshotBytes); } catch (error) {
1939
+ dropped.push({ plan_key: planKey, plan_ref: nullableString(entry.plan_ref), ...displayFailure(error) });
1940
+ }
1941
+ members.push({ descriptor, plan, snapshot });
1942
+ }
1943
+ return { members, dropped };
1944
+ }
1945
+
1946
+ /** Cheap unverified change hint for display polling; never validation or recovery. */
1947
+ export async function readTodoStoreDisplaySource({ repoRoot = process.cwd() } = {}) {
1948
+ const root = path.resolve(repoRoot);
1949
+ return observeDisplaySource(root, await readRawManifest(root));
1950
+ }
1951
+
1952
+ /** Display-only envelope: verified > unverified current raw > last_verified > unavailable. */
1953
+ export async function readTodoStoreForDisplay({ repoRoot = process.cwd(), now } = {}) {
1954
+ const root = path.resolve(repoRoot);
1955
+ const verifiedAt = new Date(now ?? Date.now()).toISOString();
1956
+ let inconsistency;
1957
+ try {
1958
+ const strict = await readStoreStableWith({ repoRoot: root, now }, readTodoStoreView);
1959
+ const store = displayStoreView(strict);
1960
+ const source = await verifiedDisplaySource(root, strict);
1961
+ try {
1962
+ const retained = await readDisplayCheckpoint(root, source.project_id);
1963
+ if (JSON.stringify(retained?.source) !== JSON.stringify(source)) {
1964
+ await publishDisplayCheckpoint(root, { verified_at: verifiedAt, source, store });
1965
+ }
1966
+ } catch (error) {
1967
+ process.emitWarning(`Store display checkpoint was not published: ${error?.detail?.reason ?? error?.code ?? error}`, {
1968
+ code: 'LATTICE_STORE_DISPLAY_CHECKPOINT_PUBLICATION_FAILED',
1969
+ });
1970
+ }
1971
+ return { state: 'verified', store, verified_at: verifiedAt, source, inconsistency: null, dropped_members: [] };
1972
+ } catch (error) {
1973
+ inconsistency = displayFault(error);
1974
+ }
1975
+ let manifest = null;
1976
+ try { manifest = await readRawManifest(root); } catch (error) { displayFault(error); }
1977
+ let dropped = [];
1978
+ if (manifest !== null) {
1979
+ const raw = await readRawDisplayMembers(root, manifest);
1980
+ dropped = raw.dropped;
1981
+ if (raw.members.length > 0) {
1982
+ return {
1983
+ state: 'unverified',
1984
+ store: { project_id: nullableString(manifest.project_id), manifest, members: raw.members },
1985
+ verified_at: null,
1986
+ source: await observeDisplaySource(root, manifest),
1987
+ inconsistency,
1988
+ dropped_members: dropped,
1989
+ };
1990
+ }
1991
+ }
1992
+ const checkpoint = await readDisplayCheckpoint(root, nullableString(manifest?.project_id));
1993
+ if (checkpoint !== null) {
1994
+ return {
1995
+ state: 'last_verified', store: checkpoint.store, verified_at: checkpoint.verified_at,
1996
+ source: checkpoint.source, inconsistency, dropped_members: dropped,
1997
+ };
1998
+ }
1999
+ return { state: 'unavailable', store: null, verified_at: null, source: null, inconsistency, dropped_members: dropped };
2000
+ }
2001
+
1605
2002
  async function atomicWrite(absolute, bytes) {
1606
2003
  await mkdir(path.dirname(absolute), { recursive: true });
1607
2004
  const temporary = path.join(path.dirname(absolute), `.${path.basename(absolute)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
@@ -1639,9 +2036,23 @@ async function atomicWriteMode(absolute, bytes, mode) {
1639
2036
 
1640
2037
 
1641
2038
  async function withLock(repoRoot, callback, {
1642
- onProtocolStage = null, lockCapability = null, initialize = false,
2039
+ onProtocolStage = null, lockCapability = null, initialize = false, repairAfter = null,
1643
2040
  } = {}) {
1644
- if (lockCapability === STORE_LOCK_HELD) return callback();
2041
+ if (lockCapability === STORE_LOCK_HELD) return callback(async () => {});
2042
+ // u03 A24/A25b: a successor writer rebinds or tombstones the connections it left stale.
2043
+ const run = repairAfter === null ? callback : async (assertHeld) => {
2044
+ const result = await callback(assertHeld);
2045
+ // The successor is already published: a failed repair leaves findings for the next locked write.
2046
+ try {
2047
+ const repairs = await repairCrossPlanBindings(repoRoot, await readTodoStoreView({ repoRoot }),
2048
+ { assertHeld, actor: repairAfter.actor, recordedAt: repairAfter.recordedAt ?? new Date().toISOString() });
2049
+ // Results stay digest-bound; the caller learns the repairs through its own callback.
2050
+ if (repairs.length > 0 && typeof repairAfter.onRepairs === 'function') await repairAfter.onRepairs(repairs);
2051
+ } catch (error) {
2052
+ if (!(error instanceof TodoStoreError || error instanceof StoreLockError)) throw error;
2053
+ }
2054
+ return result;
2055
+ };
1645
2056
  try {
1646
2057
  if (!initialize) {
1647
2058
  const root = await lstat(path.join(repoRoot, STORE_ROOT_REF)).catch((error) => {
@@ -1663,7 +2074,7 @@ async function withLock(repoRoot, callback, {
1663
2074
  recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
1664
2075
  onRecoveryClaim: typeof onProtocolStage === 'function'
1665
2076
  ? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
1666
- }, callback);
2077
+ }, run);
1667
2078
  } catch (error) {
1668
2079
  if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
1669
2080
  throw error;
@@ -1810,83 +2221,17 @@ function resolveCanonicalTaskId(plan, requestedTaskId) {
1810
2221
  return matches[0].task_id;
1811
2222
  }
1812
2223
 
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
2224
  export async function appendTodoEvent(options = {}) {
1878
2225
  requireWriter(options.writer, 'g5-authoring');
1879
2226
  if (typeof options.validateProspectiveEvent !== 'function') {
1880
2227
  throw new TypeError('appendTodoEvent requires a Plan-supplied validateProspectiveEvent');
1881
2228
  }
1882
2229
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1883
- return withLock(repoRoot, async () => {
2230
+ return withLock(repoRoot, async (assertHeld) => {
1884
2231
  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',
2232
+ repoRoot, forWrite: true, now: options.now, assertHeld,
2233
+ repairContext: { assertHeld, actor: options.event.actor,
2234
+ recordedAt: options.event.recorded_at ?? new Date().toISOString() },
1890
2235
  });
1891
2236
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
1892
2237
  if (!member) fail('STORE_INCONSISTENT', 'plan_not_active');
@@ -1910,17 +2255,16 @@ export async function appendTodoEvent(options = {}) {
1910
2255
  fail('DEPENDENCY_INVALID', 'cross_plan_dependency_already_removed', { target_event_digest: digest });
1911
2256
  }
1912
2257
  }
1913
- return appendPlanScopedEvent({
1914
- repoRoot, member,
2258
+ return { cross_plan_repairs: store.cross_plan_repairs, ...await appendPlanScopedEvent({
2259
+ repoRoot, member, assertHeld,
1915
2260
  input: { ...options.event, recorded_at: options.event.recorded_at ?? new Date().toISOString() },
1916
- });
2261
+ }) };
1917
2262
  }
1918
2263
  const input = resolveTargetedEvent({
1919
2264
  ...options.event,
1920
2265
  task_id: resolveCanonicalTaskId(member.plan, options.event.task_id),
1921
2266
  recorded_at: options.event.recorded_at ?? new Date().toISOString(),
1922
2267
  }, member);
1923
- await enforceTodoStructureLifecycleGate(repoRoot, member, input);
1924
2268
  const event = nextEvent(input, member);
1925
2269
  if ((event.kind === 'start' && event.payload.start_mode === 'historical_import')
1926
2270
  || (event.kind === 'done' && event.payload.done_mode === 'historical_import')) {
@@ -1957,6 +2301,8 @@ export async function appendTodoEvent(options = {}) {
1957
2301
  const eventBytes = canonicalLine(event);
1958
2302
  const activeRef = member.descriptor.journal_ref;
1959
2303
  const activeAbsolute = path.resolve(repoRoot, activeRef);
2304
+ // A holder that lost its lock while suspended must not overwrite the new owner's journal.
2305
+ await assertHeld();
1960
2306
  if (member.journal.activeBytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
1961
2307
  const activeEvents = member.journal.segments.at(-1).events;
1962
2308
  const previousSegmentDigest = member.journal.segments.length > 1
@@ -1986,7 +2332,7 @@ export async function appendTodoEvent(options = {}) {
1986
2332
  // 見るための導出ビューは、snapshotと分けてここで別途返す。
1987
2333
  const phases = projectPhaseStates(member.plan, [...member.journal.events, event],
1988
2334
  new Map(tasks.map((task) => [task.task_id, task])));
1989
- return { event, snapshot, plan: member.plan, phases };
2335
+ return { event, snapshot, plan: member.plan, phases, cross_plan_repairs: store.cross_plan_repairs };
1990
2336
  });
1991
2337
  }
1992
2338
 
@@ -2029,9 +2375,10 @@ function planScopedEventBytes(member, event) {
2029
2375
  return bytes;
2030
2376
  }
2031
2377
 
2032
- async function appendPlanScopedEvent({ repoRoot, member, input }) {
2378
+ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2033
2379
  const event = buildPlanScopedEvent(member, input);
2034
2380
  const bytes = planScopedEventBytes(member, event);
2381
+ await assertHeld();
2035
2382
  await atomicWrite(path.resolve(repoRoot, member.plan_scoped.ref),
2036
2383
  Buffer.concat([member.plan_scoped.activeBytes, bytes]));
2037
2384
  const events = [...member.plan_scoped.events, event];
@@ -2058,8 +2405,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2058
2405
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2059
2406
  return withLock(repoRoot, async () => {
2060
2407
  // 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 });
2408
+ const store = await readTodoStoreView({ repoRoot, now: options.now });
2063
2409
  const owner = store.members.find(({ plan }) => plan.plan_key === options.planKey);
2064
2410
  const source = store.members.find(({ plan }) => plan.plan_key === options.sourcePlanKey);
2065
2411
  if (store.manifest.manifest_digest !== options.expectedManifestDigest
@@ -2303,7 +2649,7 @@ function prepareImportedArtifacts(repoRoot, options, projectId, memberPlans) {
2303
2649
  const tasks = replay(plan, events, {
2304
2650
  now: options.now ? new Date(options.now) : new Date(), verifyImportSource,
2305
2651
  });
2306
- validateMergedGraph([...memberPlans, { plan }]);
2652
+ validateMergedGraph([...memberPlans, { plan }], undefined, { newPlanKey: plan.plan_key });
2307
2653
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2308
2654
  }
2309
2655
 
@@ -2575,7 +2921,7 @@ async function finalizeVisibleCrossPlanImport(repoRoot, transaction, { removeTra
2575
2921
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.staged_ref });
2576
2922
  }
2577
2923
  const target = await pathState(repoRoot, artifact.ref, 'STORE_INCONSISTENT', { missing: true });
2578
- const current = target === null ? Buffer.alloc(0) : await readFile(target.absolute);
2924
+ const current = target === null ? Buffer.alloc(0) : normalizeCheckoutEol(await readFile(target.absolute));
2579
2925
  const before = bytes.subarray(0, bytes.length - eventBytes.length);
2580
2926
  if (!current.equals(before) && !current.equals(bytes)) {
2581
2927
  fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.ref });
@@ -2742,7 +3088,7 @@ function prepareAuthoredArtifacts(repoRoot, options, store) {
2742
3088
  const genesis = buildPlanGenesis(plan, options.genesis);
2743
3089
  const events = [genesis];
2744
3090
  const tasks = replay(plan, events);
2745
- validateMergedGraph([...store.members, { plan }]);
3091
+ validateMergedGraph([...store.members, { plan }], undefined, { newPlanKey: plan.plan_key });
2746
3092
  return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2747
3093
  }
2748
3094
 
@@ -2974,7 +3320,7 @@ const sameDirectoryIdentity = (left, right) => left !== null && right !== null
2974
3320
 
2975
3321
  async function transientStoreDirectory(root, allowNotes = true) {
2976
3322
  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;
3323
+ if (entry.isFile() && (entry.name === '.write.lock' || /^\.write\.lock\..+\.(?:tmp|stale)$/u.test(entry.name))) continue;
2978
3324
  if (!entry.isDirectory()) return false;
2979
3325
  const child = path.join(root, entry.name);
2980
3326
  if (allowNotes && entry.name === 'notes') {
@@ -3122,7 +3468,7 @@ export async function initializeAuthoredTodoStore(options = {}) {
3122
3468
  verifyPlanNarrativeAnchors(repoRoot, plan);
3123
3469
  const genesis = buildPlanGenesis(plan, options.genesis);
3124
3470
  const tasks = replay(plan, [genesis]);
3125
- validateMergedGraph([{ plan }]);
3471
+ validateMergedGraph([{ plan }], undefined, { newPlanKey: plan.plan_key });
3126
3472
  const snapshot = snapshotFor(plan, [genesis], tasks);
3127
3473
  const base = `plans/${plan.plan_key}/${plan.plan_version}`;
3128
3474
  const planRef = `${STORE_ROOT_REF}/${base}/plan.json`;
@@ -3359,264 +3705,39 @@ export async function verifyPhaseTodoRevisionSources(options = {}) {
3359
3705
  return true;
3360
3706
  }
3361
3707
 
3362
- function removedTaskIdsFor(revision) {
3363
- return new Set(revision.task_migration
3364
- .filter(({ to_task_id, state_policy }) => to_task_id === 'removed' && state_policy === 'removed')
3365
- .map(({ from_task_id }) => from_task_id));
3366
- }
3367
-
3368
- function phaseV3CarrySemantics(plan, taskId, taskIdMap, phaseIdMap,
3369
- { reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set() } = {}) {
3370
- const task = plan.tasks.find(({ task_id: id }) => id === taskId);
3371
- if (task === undefined) return null;
3372
- const mapTaskRef = (ref) => ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
3373
- ? { ...ref, task_id: taskIdMap.get(ref.task_id) ?? ref.task_id } : ref;
3374
- const mapPhaseRef = (ref) => ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
3375
- ? { ...ref, phase_id: phaseIdMap.get(ref.phase_id) ?? ref.phase_id } : ref;
3376
- // Phaseを持たない世代(todo_plan.v3)のtaskはphase_idを持たない。undefinedのまま
3377
- // canonicalizeするとJSON treeでないとしてTypeErrorになり、typedな拒否理由が失われる。
3378
- // nullへ正規化してcarry比較へ渡し、Phase割当ての獲得をcarry_semantics_changedとして拒否する。
3379
- const mappedPhaseId = phaseIdMap.get(task.phase_id) ?? task.phase_id ?? null;
3380
- const mappedTask = reconciliationMetadata ? {
3381
- task_id: taskIdMap.get(task.task_id) ?? task.task_id, title: task.title, lane: task.lane,
3382
- compile_binding: task.compile_binding,
3383
- phase_id: mappedPhaseId,
3384
- } : {
3385
- task_id: taskIdMap.get(task.task_id) ?? task.task_id,
3386
- title: task.title, lane: task.lane,
3387
- ...(includeDesignMemo ? { design_memo: task.design_memo } : {}),
3388
- narrative_ref: task.narrative_ref, narrative_anchor: task.narrative_anchor ?? null,
3389
- compile_binding: task.compile_binding,
3390
- phase_id: mappedPhaseId,
3391
- parent_task_id: task.parent_task_id === null ? null
3392
- : taskIdMap.get(task.parent_task_id) ?? task.parent_task_id,
3393
- };
3394
- const incoming = [];
3395
- const outgoing = [];
3396
- for (const edge of plan.hard_dependencies) {
3397
- if (removedTaskRef(edge.from, plan, removedTaskIds)
3398
- || removedTaskRef(edge.to, plan, removedTaskIds)) continue;
3399
- const mapped = { kind: 'hard', from: mapTaskRef(edge.from), to: mapTaskRef(edge.to) };
3400
- if (localTaskRef(edge.to, plan, taskId)) incoming.push(mapped);
3401
- if (localTaskRef(edge.from, plan, taskId)) outgoing.push(mapped);
3402
- }
3403
- for (const join of plan.joins) {
3404
- if (removedTaskRef(join.before, plan, removedTaskIds)) continue;
3405
- const to = mapTaskRef(join.before);
3406
- for (const after of join.after) {
3407
- if (removedTaskRef(after, plan, removedTaskIds)) continue;
3408
- const tuple = { kind: 'join', join_id: join.id, from: mapTaskRef(after), to };
3409
- if (localTaskRef(join.before, plan, taskId)) incoming.push(tuple);
3410
- if (localTaskRef(after, plan, taskId)) outgoing.push(tuple);
3411
- }
3412
- }
3413
- if (isDecoupledPhaseTodoPlanSchema(plan.schema)) for (const edge of plan.phase_accept_dependencies) {
3414
- if (localTaskRef(edge.to, plan, taskId)) incoming.push({ kind: 'phase_accept',
3415
- from: mapPhaseRef(edge.from), to: mapTaskRef(edge.to) });
3416
- }
3417
- const sort = (entries) => entries.map(canonicalizeTodoArtifact).sort();
3418
- return { task: mappedTask, incoming: sort(incoming), outgoing: sort(outgoing) };
3419
- }
3420
-
3421
- function validatePhaseV3Carry(previous, revision, migration, idMap, state) {
3422
- const reconciliationMetadata = migration.state_policy === 'carry_reconciled_metadata';
3423
- const predecessorTask = previous.plan.tasks.find(({ task_id }) => task_id === migration.from_task_id);
3424
- const includeDesignMemo = !reconciliationMetadata && typeof predecessorTask?.design_memo === 'string';
3425
- const removedTaskIds = removedTaskIdsFor(revision);
3426
- const phaseIdMap = new Map(revision.phase_migration
3427
- .filter(({ from_phase_id, to_phase_id }) => from_phase_id !== null && to_phase_id !== 'removed')
3428
- .map(({ from_phase_id, to_phase_id }) => [from_phase_id, to_phase_id]));
3429
- const before = phaseV3CarrySemantics(previous.plan, migration.from_task_id, idMap, phaseIdMap,
3430
- { reconciliationMetadata, includeDesignMemo, removedTaskIds });
3431
- const after = phaseV3CarrySemantics(revision.desired_plan, migration.to_task_id,
3432
- new Map(), new Map(),
3433
- { reconciliationMetadata, includeDesignMemo });
3434
- if (canonicalizeTodoArtifact(before.task) !== canonicalizeTodoArtifact(after.task)
3435
- || canonicalizeTodoArtifact(before.incoming) !== canonicalizeTodoArtifact(after.incoming)) {
3436
- fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3437
- }
3438
- const successorOutgoing = new Set(after.outgoing);
3439
- if (!before.outgoing.every((edge) => successorOutgoing.has(edge))) {
3440
- fail('REVISION_INVALID', 'carry_outgoing_edge_removed', { from_task_id: migration.from_task_id });
3441
- }
3442
- }
3443
-
3444
- function validateBackchainCarry(previous, revision, migration, idMap) {
3445
- const decision = revision.backchain.continuity?.find(({ task_id: id }) =>
3446
- id === migration.from_task_id);
3447
- if (decision?.policy === 'carry') return;
3448
- const reconciliationMetadata = migration.state_policy === 'carry_reconciled_metadata';
3449
- const predecessorTask = previous.plan.tasks.find(({ task_id }) => task_id === migration.from_task_id);
3450
- const phaseIdMap = new Map(revision.phase_migration
3451
- .filter(({ from_phase_id, to_phase_id }) => from_phase_id !== null && to_phase_id !== 'removed')
3452
- .map(({ from_phase_id, to_phase_id }) => [from_phase_id, to_phase_id]));
3453
- const before = phaseV3CarrySemantics(previous.plan, migration.from_task_id, idMap, phaseIdMap, {
3454
- reconciliationMetadata, includeDesignMemo: !reconciliationMetadata
3455
- && typeof predecessorTask?.design_memo === 'string',
3456
- removedTaskIds: removedTaskIdsFor(revision),
3457
- });
3458
- const after = phaseV3CarrySemantics(revision.desired_plan, migration.to_task_id,
3459
- new Map(), new Map(), {
3460
- reconciliationMetadata, includeDesignMemo: !reconciliationMetadata
3461
- && typeof predecessorTask?.design_memo === 'string',
3462
- });
3463
- // 利用先の増減は提供済み機能の意味を変えない。入力・提供機能の同一性は
3464
- // backchain契約で別に照合し、工程の入力辺と本体の意味だけをここで検査する。
3465
- if (canonicalizeTodoArtifact(before.task) !== canonicalizeTodoArtifact(after.task)
3466
- || canonicalizeTodoArtifact(before.incoming) !== canonicalizeTodoArtifact(after.incoming)) {
3467
- fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3468
- }
3469
- }
3470
-
3471
- function backchainTaskSignature(chain, taskId) {
3472
- const task = chain?.tasks?.find(({ task_id: id }) => id === taskId);
3473
- if (task === undefined) return null;
3474
- const featureIds = [...new Set([...task.requires_feature_ids, ...task.provides_feature_ids])].sort();
3475
- const byId = new Map(chain.features.map((feature) => [feature.feature_id, feature]));
3476
- return canonicalizeTodoArtifact({
3477
- requires_feature_ids: task.requires_feature_ids,
3478
- provides_feature_ids: task.provides_feature_ids,
3479
- features: featureIds.map((id) => byId.get(id)),
3480
- });
3481
- }
3482
-
3483
- async function assertBackchainCarryContracts(repoRoot, previous, revision) {
3484
- const decisions = new Map((revision.backchain.continuity ?? [])
3485
- .map((entry) => [entry.task_id, entry]));
3486
- for (const decision of decisions.values()) {
3487
- const migration = revision.task_migration.find(({ from_task_id: id }) => id === decision.task_id);
3488
- if (migration === undefined || (decision.policy === 'carry'
3489
- && !['carry', 'carry_reconciled_metadata'].includes(migration.state_policy))
3490
- || (decision.policy === 'reset' && migration.state_policy !== 'reset_pending')
3491
- || (decision.policy === 'retire' && migration.state_policy !== 'removed')) {
3492
- fail('REVISION_INVALID', 'backchain_continuity_mismatch', { task_id: decision.task_id });
3493
- }
3494
- }
3495
- const carried = revision.task_migration.filter(({ state_policy }) =>
3496
- ['carry', 'carry_reconciled_metadata', 'acquire_phase'].includes(state_policy));
3497
- if (carried.length === 0) return;
3498
- const oldRef = path.resolve(repoRoot, STORE_ROOT_REF, 'plans', previous.plan.plan_key,
3499
- previous.plan.plan_version, 'backchain.json');
3500
- const bytes = await exactFileOrNull(oldRef);
3501
- if (bytes === null) fail('REVISION_INVALID', 'backchain_predecessor_missing');
3502
- let binding;
3503
- try { binding = JSON.parse(decodeUtf8(bytes, 'REVISION_INVALID', 'backchain_predecessor_invalid')); }
3504
- catch { fail('REVISION_INVALID', 'backchain_predecessor_invalid'); }
3505
- if (binding?.schema !== 'lattice.plan_backchain_binding.v1'
3506
- || binding.plan_digest !== previous.plan.plan_digest
3507
- || binding.binding_digest !== todoSelfDigest(binding, 'binding_digest')) {
3508
- fail('REVISION_INVALID', 'backchain_predecessor_invalid');
3509
- }
3510
- for (const migration of carried) {
3511
- if (decisions.get(migration.from_task_id)?.policy === 'carry') continue;
3512
- if (backchainTaskSignature(binding.chain, migration.from_task_id)
3513
- !== backchainTaskSignature(revision.backchain, migration.to_task_id)) {
3514
- fail('REVISION_INVALID', 'backchain_carry_feature_changed', {
3515
- from_task_id: migration.from_task_id, to_task_id: migration.to_task_id,
3516
- });
3517
- }
3518
- }
3519
- }
3520
-
3521
- /**
3522
- * acquire_phase専用のcarry検証(ADR 0147裁定4)。既存carry/carry_reconciled_metadataの
3523
- * 分岐(validatePhaseV3Carry)には一切手を入れず、「Phase割当ての獲得だけ」を許す別分岐として
3524
- * 独立に置く——同じcarry比較へphase_idだけ除外する特例を混ぜると、以後の意味論比較すべてに
3525
- * 例外条件が混入する経路を開いてしまう(裁定4が名指しで禁じる形)。
3526
- *
3527
- * 獲得の定義: predecessor側がphase無し(phase_idがnullに正規化される)→successor側がphase有り、
3528
- * という向きだけを許す。既にphaseを持つtaskの付け替えは意味論の変更であり、acquire_phaseでは
3529
- * 許さない(carryへ回して従来どおりcarry_semantics_changedで拒否させる)。phase_id以外の
3530
- * 属性(title/lane/narrative_ref/narrative_anchor/compile_binding/parent_task_id)と
3531
- * 依存辺(incoming)は、phaseV3CarrySemanticsのtaskからphase_idだけを取り除いた上で
3532
- * carryと同じ完全一致を要求する。outgoingの扱い(successor側が上位集合であること)もcarryと同じ。
3533
- */
3534
- function validateAcquirePhaseCarry(previous, revision, migration, idMap) {
3535
- const phaseIdMap = new Map(revision.phase_migration
3536
- .filter(({ from_phase_id, to_phase_id }) => from_phase_id !== null && to_phase_id !== 'removed')
3537
- .map(({ from_phase_id, to_phase_id }) => [from_phase_id, to_phase_id]));
3538
- const predecessorTask = previous.plan.tasks.find(({ task_id }) => task_id === migration.from_task_id);
3539
- const includeDesignMemo = typeof predecessorTask?.design_memo === 'string';
3540
- const removedTaskIds = removedTaskIdsFor(revision);
3541
- const before = phaseV3CarrySemantics(previous.plan, migration.from_task_id, idMap, phaseIdMap,
3542
- { includeDesignMemo, removedTaskIds });
3543
- const after = phaseV3CarrySemantics(revision.desired_plan, migration.to_task_id, new Map(), new Map(),
3544
- { includeDesignMemo });
3545
- if (before.task.phase_id !== null) {
3546
- fail('REVISION_INVALID', 'acquire_phase_requires_unassigned_predecessor', { from_task_id: migration.from_task_id });
3547
- }
3548
- if (after.task.phase_id === null) {
3549
- fail('REVISION_INVALID', 'acquire_phase_requires_assigned_successor', { from_task_id: migration.from_task_id });
3550
- }
3551
- const stripPhase = ({ phase_id, ...rest }) => rest;
3552
- if (canonicalizeTodoArtifact(stripPhase(before.task)) !== canonicalizeTodoArtifact(stripPhase(after.task))
3553
- || canonicalizeTodoArtifact(before.incoming) !== canonicalizeTodoArtifact(after.incoming)) {
3554
- fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3555
- }
3556
- const successorOutgoing = new Set(after.outgoing);
3557
- if (!before.outgoing.every((edge) => successorOutgoing.has(edge))) {
3558
- fail('REVISION_INVALID', 'carry_outgoing_edge_removed', { from_task_id: migration.from_task_id });
3559
- }
3560
- }
3561
-
3562
3708
  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)) {
3709
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
3710
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
3711
+ .includes(revision.desired_plan.schema)) {
3565
3712
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
3566
3713
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
3567
3714
  });
3568
3715
  }
3716
+ if (previous.plan.schema === 'lattice.todo_plan.v8'
3717
+ && revision.desired_plan.schema !== 'lattice.todo_plan.v8') {
3718
+ fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
3719
+ predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
3720
+ });
3721
+ }
3569
3722
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id);
3570
3723
  const migrationIds = revision.task_migration.map(({ from_task_id }) => from_task_id);
3571
3724
  if (canonicalizeTodoArtifact([...oldIds].sort()) !== canonicalizeTodoArtifact([...migrationIds].sort())) {
3572
3725
  fail('REVISION_INVALID', 'predecessor_task_migration_incomplete');
3573
3726
  }
3574
- const idMap = new Map(revision.task_migration
3575
- .filter(({ to_task_id }) => to_task_id !== 'removed')
3576
- .map(({ from_task_id, to_task_id }) => [from_task_id, to_task_id]));
3577
- const removedTaskIds = removedTaskIdsFor(revision);
3578
3727
  const states = new Map(previous.tasks.map((state) => [state.task_id, state]));
3579
3728
  return revision.task_migration.map((migration) => {
3580
3729
  const carriesState = ['carry', 'carry_reconciled_metadata', 'acquire_phase'].includes(migration.state_policy);
3581
3730
  if (!carriesState) return { ...migration, state: null };
3582
- const reconciliationMetadata = migration.state_policy === 'carry_reconciled_metadata';
3583
3731
  const state = states.get(migration.from_task_id);
3584
3732
  if (!state) fail('STORE_INCONSISTENT', 'predecessor_task_state_missing');
3585
- if (migration.state_policy === 'acquire_phase') {
3586
- // acquire_phaseはv3 phase revision専用の獲得判定を持つ。v3以外(v1/v2 phase revisionや
3587
- // 平文todo_revision)ではtaskSemantics自体がphase_idを比較対象へ含めないため、carryと
3588
- // 同じ比較で意味論は保たれる——ここを別ロジックにする理由が無い(既知のv1/v2の緩さは
3589
- // ADR 0147の対象外であり、緩めも締めもしない)。
3590
- if (revision.schema === 'lattice.phase_todo_revision.v3') {
3591
- validateAcquirePhaseCarry(previous, revision, migration, idMap);
3592
- } else {
3593
- const predecessorTask = previous.plan.tasks
3594
- .find(({ task_id }) => task_id === migration.from_task_id);
3595
- const includeDesignMemo = typeof predecessorTask?.design_memo === 'string';
3596
- const before = taskSemantics(previous.plan, migration.from_task_id, idMap,
3597
- { includeDesignMemo, removedTaskIds });
3598
- const after = taskSemantics(revision.desired_plan, migration.to_task_id, new Map(),
3599
- { includeDesignMemo });
3600
- if (canonicalizeTodoArtifact(before) !== canonicalizeTodoArtifact(after)) {
3601
- fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3602
- }
3603
- }
3604
- } else if (revision.schema === 'lattice.phase_todo_revision.v3') {
3605
- validatePhaseV3Carry(previous, revision, migration, idMap, state);
3606
- } else if (revision.schema === 'lattice.phase_todo_revision.v4') {
3607
- validateBackchainCarry(previous, revision, migration, idMap);
3608
- } else {
3609
- const predecessorTask = previous.plan.tasks
3610
- .find(({ task_id }) => task_id === migration.from_task_id);
3611
- const includeDesignMemo = !reconciliationMetadata
3612
- && typeof predecessorTask?.design_memo === 'string';
3613
- const before = taskSemantics(previous.plan, migration.from_task_id, idMap,
3614
- { reconciliationMetadata, includeDesignMemo, removedTaskIds });
3615
- const after = taskSemantics(revision.desired_plan, migration.to_task_id, new Map(),
3616
- { reconciliationMetadata, includeDesignMemo });
3617
- if (canonicalizeTodoArtifact(before) !== canonicalizeTodoArtifact(after)) {
3618
- fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3619
- }
3733
+ // u03 A38/A39: every schema uses the u12 light-carry rule. Authored fields, edges, joins and
3734
+ // phase assignment may change at any state; only the id mapping and compile_binding bind
3735
+ // carried state (the claim 1-4 impact binding must not carry onto another compiled spec).
3736
+ const predecessorTask = previous.plan.tasks.find(({ task_id }) => task_id === migration.from_task_id);
3737
+ const desiredTask = revision.desired_plan.tasks.find(({ task_id }) => task_id === migration.to_task_id);
3738
+ if (!desiredTask || canonicalizeTodoArtifact(predecessorTask?.compile_binding ?? null)
3739
+ !== canonicalizeTodoArtifact(desiredTask.compile_binding ?? null)) {
3740
+ fail('REVISION_INVALID', 'carry_semantics_changed', { from_task_id: migration.from_task_id });
3620
3741
  }
3621
3742
  return { ...migration, state: {
3622
3743
  status: state.status, started_at: state.started_at, done_at: state.done_at,
@@ -3635,12 +3756,6 @@ function phaseStateMigrationFor(previous, revision) {
3635
3756
  !== canonicalizeTodoArtifact(predecessorPhases.map(({ phase_id }) => phase_id).sort())) {
3636
3757
  fail('REVISION_INVALID', 'predecessor_phase_migration_incomplete');
3637
3758
  }
3638
- const idMap = new Map(revision.phase_migration
3639
- .filter(({ from_phase_id, to_phase_id }) => from_phase_id !== null && to_phase_id !== 'removed')
3640
- .map(({ from_phase_id, to_phase_id }) => [from_phase_id, to_phase_id]));
3641
- const taskIdMap = new Map(revision.task_migration
3642
- .filter(({ to_task_id }) => to_task_id !== 'removed')
3643
- .map(({ from_task_id, to_task_id }) => [from_task_id, to_task_id]));
3644
3759
  const previousStates = new Map((previous.snapshot.phases ?? []).map((state) => [state.phase_id, state]));
3645
3760
  return revision.phase_migration
3646
3761
  .filter(({ to_phase_id }) => to_phase_id !== 'removed')
@@ -3648,19 +3763,9 @@ function phaseStateMigrationFor(previous, revision) {
3648
3763
  if (migration.state_policy === 'reset') {
3649
3764
  return { phase_id: migration.to_phase_id, state_policy: 'reset', state: null };
3650
3765
  }
3651
- const before = predecessorPhases.find(({ phase_id }) => phase_id === migration.from_phase_id);
3652
3766
  const after = revision.desired_plan.phases.find(({ phase_id }) => phase_id === migration.to_phase_id);
3653
- const mappedBefore = { ...before, phase_id: migration.to_phase_id,
3654
- predecessor_phase_ids: before.predecessor_phase_ids.map((id) => idMap.get(id) ?? id).sort() };
3655
- const beforeTaskIds = previous.plan.tasks
3656
- .filter(({ phase_id }) => phase_id === migration.from_phase_id)
3657
- .map(({ task_id }) => taskIdMap.get(task_id) ?? 'removed').filter((id) => id !== 'removed').sort();
3658
- const afterTaskIds = revision.desired_plan.tasks
3659
- .filter(({ phase_id }) => phase_id === migration.to_phase_id).map(({ task_id }) => task_id).sort();
3660
- if (canonicalizeTodoArtifact({ phase: mappedBefore, task_ids: beforeTaskIds })
3661
- !== canonicalizeTodoArtifact({ phase: after, task_ids: afterTaskIds })) {
3662
- fail('REVISION_INVALID', 'phase_carry_semantics_changed', { from_phase_id: migration.from_phase_id });
3663
- }
3767
+ // u12/u03 A38: the revision chose carry vs reset; Store checks only the id mapping.
3768
+ if (!after) fail('REVISION_INVALID', 'phase_carry_semantics_changed', { from_phase_id: migration.from_phase_id });
3664
3769
  const state = previousStates.get(migration.from_phase_id);
3665
3770
  if (state === undefined) fail('STORE_INCONSISTENT', 'predecessor_phase_state_missing');
3666
3771
  return { phase_id: migration.to_phase_id, state_policy: 'carry', state: {
@@ -4378,7 +4483,7 @@ async function cleanupPhaseV3Staging(transaction, staged) {
4378
4483
  await fsyncDirectory(transaction);
4379
4484
  }
4380
4485
 
4381
- async function predecessorSourceInventory(repoRoot, previous) {
4486
+ export async function predecessorSourceInventory(repoRoot, previous) {
4382
4487
  if (previous.revision?.source_inventory !== undefined) return previous.revision.source_inventory;
4383
4488
  const versionsRoot = path.join(repoRoot, STORE_ROOT_REF, 'plans', previous.plan.plan_key);
4384
4489
  const plansByDigest = new Map();
@@ -4688,7 +4793,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4688
4793
  await fsyncDirectory(path.dirname(barrierAbsolute));
4689
4794
  await rm(transaction, { recursive: true, force: true });
4690
4795
  return commitReceipt;
4691
- }, { lockCapability: options[STORE_LOCK_HELD] });
4796
+ }, { lockCapability: options[STORE_LOCK_HELD],
4797
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
4798
+ onRepairs: options.onCrossPlanRepairs } });
4692
4799
  }
4693
4800
 
4694
4801
  /** Native successor transaction for first-class Phase plans; no Markdown source inventory is involved. */
@@ -4720,9 +4827,6 @@ export async function applyPhaseTodoRevision(options = {}) {
4720
4827
  fail('STORE_WRITE_CONFLICT', 'stale_predecessor');
4721
4828
  }
4722
4829
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4723
- if (revision.schema === 'lattice.phase_todo_revision.v4') {
4724
- await assertBackchainCarryContracts(repoRoot, previous, revision);
4725
- }
4726
4830
  const stateMigration = stateMigrationFor(previous, revision);
4727
4831
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
4728
4832
  const prospective = store.members.map((member) => member === previous
@@ -4798,7 +4902,9 @@ export async function applyPhaseTodoRevision(options = {}) {
4798
4902
  await protocolStage(options, 'phase_revision_manifest_activated');
4799
4903
  await rm(transaction, { recursive: true, force: true });
4800
4904
  return phaseRevisionResult(revision, genesis, false);
4801
- }, { lockCapability: options[STORE_LOCK_HELD] });
4905
+ }, { lockCapability: options[STORE_LOCK_HELD],
4906
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
4907
+ onRepairs: options.onCrossPlanRepairs } });
4802
4908
  }
4803
4909
 
4804
4910
  /** G5 revision transaction: exact successor, state migration, and manifest-CAS activation. */
@@ -4986,7 +5092,9 @@ export async function applyTodoRevision(options = {}) {
4986
5092
  }
4987
5093
  await rm(transaction, { recursive: true, force: true });
4988
5094
  return revisionResult(revision, genesis, { recovered: recovering });
4989
- }, { lockCapability: options[STORE_LOCK_HELD] });
5095
+ }, { lockCapability: options[STORE_LOCK_HELD],
5096
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5097
+ onRepairs: options.onCrossPlanRepairs } });
4990
5098
  }
4991
5099
 
4992
5100
  function revisionSetResult(projectId, revisionSetDigest, entries, { recovered }) {
@@ -5293,7 +5401,9 @@ export async function applyTodoRevisionSet(options = {}) {
5293
5401
  }
5294
5402
  await rm(transaction, { recursive: true, force: true });
5295
5403
  return revisionSetResult(projectId, revisionSetDigest, prepared, { recovered: recovering });
5296
- }, { lockCapability: options[STORE_LOCK_HELD] });
5404
+ }, { lockCapability: options[STORE_LOCK_HELD],
5405
+ repairAfter: { actor: options.actor, recordedAt: options.recordedAt,
5406
+ onRepairs: options.onCrossPlanRepairs } });
5297
5407
  }
5298
5408
 
5299
5409
  /** G5 revise primitive: topology changes only by publishing a successor version. */
@@ -5314,7 +5424,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5314
5424
  ['lattice.todo_plan.v1', 1], ['lattice.todo_plan.v2', 2], ['lattice.todo_plan.v3', 3],
5315
5425
  // v6はphase無しv3へdesign_memoを追加した枝であり、phase世代より後という意味ではない。
5316
5426
  ['lattice.todo_plan.v4', 4], ['lattice.todo_plan.v5', 5], ['lattice.todo_plan.v6', 3],
5317
- ['lattice.todo_plan.v7', 5],
5427
+ ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5],
5318
5428
  ]);
5319
5429
  if (schemaRank.get(plan.schema) < schemaRank.get(previous.plan.schema)) {
5320
5430
  throw new TypeError(previous.plan.schema === 'lattice.todo_plan.v2'
@@ -5322,9 +5432,16 @@ export async function createSuccessorTodoPlan(options = {}) {
5322
5432
  ? 'todo plan schema cannot regress from v2 to v1'
5323
5433
  : 'todo plan schema cannot regress');
5324
5434
  }
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');
5435
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
5436
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
5437
+ fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
5438
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
5439
+ });
5440
+ }
5441
+ if (previous.plan.schema === 'lattice.todo_plan.v8' && plan.schema !== 'lattice.todo_plan.v8') {
5442
+ fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
5443
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
5444
+ });
5328
5445
  }
5329
5446
  verifyPlanNarrativeAnchors(repoRoot, plan, previous.plan);
5330
5447
  const migration = options.genesis.task_migration ?? [];
@@ -5360,7 +5477,8 @@ export async function createSuccessorTodoPlan(options = {}) {
5360
5477
  store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
5361
5478
  await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
5362
5479
  return { plan, genesis, snapshot };
5363
- });
5480
+ }, { repairAfter: { actor: options.genesis.actor, recordedAt: options.genesis.recorded_at,
5481
+ onRepairs: options.onCrossPlanRepairs } });
5364
5482
  }
5365
5483
 
5366
5484
  const INDEPENDENCE_ARTIFACT_NAME = 'independence.json';
@@ -5977,7 +6095,7 @@ export async function readTodoStructureRealizationChain(options = {}) {
5977
6095
  missing: true,
5978
6096
  });
5979
6097
  if (state === null) return [];
5980
- return parseTodoStructureRealizationChain(await readFile(state.absolute), {
6098
+ return parseTodoStructureRealizationChain(normalizeCheckoutEol(await readFile(state.absolute)), {
5981
6099
  structureSet: options.structureSet, taskId: options.taskId,
5982
6100
  });
5983
6101
  }