@quolu/lattice 0.79.5 → 0.80.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 (51) hide show
  1. package/docs/schemas/lattice.plan_create_input.v4.schema.json +8 -4
  2. package/docs/schemas/lattice.todo_extraction.v3.schema.json +5 -3
  3. package/docs/schemas/lattice.todo_extraction.v4.schema.json +5 -3
  4. package/package.json +1 -1
  5. package/src/fs-publish.mjs +9 -0
  6. package/src/mcp-startup-receipt.mjs +3 -3
  7. package/src/project-cli.mjs +2 -2
  8. package/src/runtime-os-observation.mjs +18 -1
  9. package/src/store-lock.mjs +250 -0
  10. package/src/todo-cli.mjs +6 -0
  11. package/src/todo-contracts.mjs +95 -50
  12. package/src/todo-migration.mjs +35 -10
  13. package/src/todo-note-store.mjs +45 -12
  14. package/src/todo-readiness.mjs +154 -0
  15. package/src/todo-status.mjs +4 -33
  16. package/src/todo-store-git-transaction.mjs +11 -6
  17. package/src/todo-store-view.mjs +47 -0
  18. package/src/todo-store.mjs +597 -398
  19. package/src/artifact-contracts-v2.mjs +0 -325
  20. package/src/boundary-compiler.mjs +0 -712
  21. package/src/bounded-seam.mjs +0 -230
  22. package/src/control-compiler.mjs +0 -532
  23. package/src/rc1-black-box-oracle.mjs +0 -906
  24. package/src/rc1-comparison.mjs +0 -154
  25. package/src/rc1-evidence-bundle.mjs +0 -456
  26. package/src/rc1-v4-campaign.mjs +0 -708
  27. package/src/rc1-v4-transform.mjs +0 -467
  28. package/src/rc1-v5-artifact-set.mjs +0 -855
  29. package/src/rc1-v5-behavior-evidence.mjs +0 -594
  30. package/src/rc1-v5-campaign.mjs +0 -797
  31. package/src/rc1-v5-transform.mjs +0 -421
  32. package/src/rc1-v6-artifact-set.mjs +0 -807
  33. package/src/rc1-v6-behavior-evidence.mjs +0 -273
  34. package/src/rc1-v6-campaign.mjs +0 -623
  35. package/src/rc1-v6-causal-binding.mjs +0 -473
  36. package/src/rc1-v6-measurement.mjs +0 -313
  37. package/src/rc2-artifact-set.mjs +0 -1584
  38. package/src/rc2-campaign.mjs +0 -1495
  39. package/src/rc2-delivery-policy-front-end.mjs +0 -1079
  40. package/src/rc2-delivery-policy-oracle.mjs +0 -134
  41. package/src/rc2-delivery-policy-transform.mjs +0 -1127
  42. package/src/rc2-rc1-transfer-front-end.mjs +0 -511
  43. package/src/rc3-actual-dogfood.mjs +0 -652
  44. package/src/rc3-dogfood-scaffold.mjs +0 -315
  45. package/src/rc3-scripted-campaign.mjs +0 -1383
  46. package/src/rc4-stage1-dogfood.mjs +0 -673
  47. package/src/runtime-scripted-executor.mjs +0 -163
  48. package/src/runtime-worktree-executor.mjs +0 -199
  49. package/src/seam-transform.mjs +0 -554
  50. package/src/treatment-compiler.mjs +0 -728
  51. package/src/treatment-runner.mjs +0 -656
@@ -1,6 +1,19 @@
1
+ import {
2
+ isDecoupledPhaseTodoPlanSchema,
3
+ isPhaseTodoPlanSchema,
4
+ isPhaselessTodoPlanSchema,
5
+ projectTodoCrossPlanDependencies,
6
+ } from './todo-store-view.mjs';
7
+ export {
8
+ isDecoupledPhaseTodoPlanSchema,
9
+ isPhaseTodoPlanSchema,
10
+ isPhaselessTodoPlanSchema,
11
+ projectTodoCrossPlanDependencies,
12
+ } from './todo-store-view.mjs';
1
13
  import { randomBytes } from 'node:crypto';
2
14
  import { fsyncDirectory } from './fs-dir-sync.mjs';
3
- import { renamePublishedFile } from './fs-publish.mjs';
15
+ import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
16
+ import { StoreLockError, withStoreLock } from './store-lock.mjs';
4
17
  import {
5
18
  lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
6
19
  } from 'node:fs/promises';
@@ -11,6 +24,7 @@ import {
11
24
  TODO_PLAN_SCOPED_EVENT_KINDS,
12
25
  canonicalizeTodoArtifact,
13
26
  digestTodoArtifact,
27
+ explainTodoPlan,
14
28
  exactRecord,
15
29
  isStrictTodoTimestamp,
16
30
  isTodoDigest,
@@ -62,6 +76,7 @@ const CROSS_PLAN_RECOVERY_CLAIMS_REF = `${STORE_ROOT_REF}/.cross-plan-recovery`;
62
76
  const CROSS_PLAN_IMPORT_TRANSACTION_SCHEMA = 'lattice.todo_cross_plan_import_transaction.v1';
63
77
  const SOURCE_CUTOVER_BARRIER_REF = `${STORE_ROOT_REF}/source-cutover-recovery.json`;
64
78
  const SOURCE_CUTOVER_RECOVERY_CAPABILITY = Symbol('lattice.todo.source-cutover-recovery');
79
+ const STORE_LOCK_HELD = Symbol('lattice.todo.lock-held');
65
80
  const MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
66
81
  const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring']);
67
82
  const TODO_REVISION_SCHEMAS = Object.freeze([
@@ -238,7 +253,10 @@ async function readJournal(repoRoot, journalRef) {
238
253
  if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
239
254
  }
240
255
  const activeBytes = await readFile(state.absolute);
241
- segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
256
+ const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
257
+ if (!duplicateActive) {
258
+ segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
259
+ }
242
260
  const events = segments.flatMap(({ events: entries }) => entries);
243
261
  const failures = verifyLinearHashChain({
244
262
  entries: events,
@@ -271,7 +289,7 @@ async function readJournal(repoRoot, journalRef) {
271
289
  ? event.schema !== 'lattice.todo_event.v1' : !legacyOrImplicitPhaseTail(event)))) {
272
290
  fail('STORE_CORRUPT', 'journal_schema_sequence_invalid');
273
291
  }
274
- return { segments, events, activeBytes };
292
+ return { segments, events, activeBytes: duplicateActive ? Buffer.alloc(0) : activeBytes };
275
293
  }
276
294
 
277
295
  /**
@@ -342,20 +360,6 @@ function emptyPhaseState(phaseId) {
342
360
  // と衝突しない予約名として固定する。
343
361
  export const TERMINAL_AUDIT_PHASE_ID = 'terminal-audit';
344
362
 
345
- export function isPhaseTodoPlanSchema(schema) {
346
- return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
347
- }
348
-
349
- export function isDecoupledPhaseTodoPlanSchema(schema) {
350
- return ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
351
- }
352
-
353
- // CLI側(migrate/plan create/最後のdone)が「終端重監査が要る」ことを通知するために
354
- // 同じ判定を再利用する。判定基準を二重管理しないよう、ここから公開する。
355
- export function isPhaselessTodoPlanSchema(schema) {
356
- return !isPhaseTodoPlanSchema(schema);
357
- }
358
-
359
363
  function terminalAuditPhase() {
360
364
  return { phase_id: TERMINAL_AUDIT_PHASE_ID, title: '終端重監査', gate_policy: 'terminal-audit',
361
365
  predecessor_phase_ids: [], required_evidence_slots: ['terminal-audit'] };
@@ -400,38 +404,6 @@ export function projectTodoCoordination(events) {
400
404
  };
401
405
  }
402
406
 
403
- /**
404
- * active plan群へ接続済みのplan跨ぎ依存線を投影する。
405
- *
406
- * eventはconsumer(to)planのplan-scoped chainへ積まれる。自動発見も暗黙補完もせず、
407
- * 記録された線だけを返す。順序はtask identityで固定し、status/Ganttが同じ入力を見る。
408
- */
409
- export function projectTodoCrossPlanDependencies(members) {
410
- // 除去tombstoneを先に集め、指された接続を線として数えない(歴史は両eventとも残る)
411
- const removed = new Set();
412
- for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
413
- if (event.kind === 'cross_plan_dependency_removed') removed.add(event.payload.target_event_digest);
414
- }
415
- const dependencies = [];
416
- for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
417
- if (event.kind !== 'cross_plan_dependency') continue;
418
- if (removed.has(event.event_digest)) continue;
419
- dependencies.push({
420
- from: event.payload.from,
421
- to: event.payload.to,
422
- reason: event.payload.reason,
423
- connected_by: event.actor,
424
- connected_at: event.recorded_at,
425
- event_digest: event.event_digest,
426
- });
427
- }
428
- return dependencies.sort((left, right) => {
429
- const key = (entry) => `${entry.from.project_id}\0${entry.from.plan_key}\0${entry.from.task_id}`
430
- + `\0${entry.to.project_id}\0${entry.to.plan_key}\0${entry.to.task_id}\0${entry.event_digest}`;
431
- return key(left) < key(right) ? -1 : key(left) > key(right) ? 1 : 0;
432
- });
433
- }
434
-
435
407
  function derivedPhaseStatus(plan, taskStates, phaseStates, phaseId) {
436
408
  const state = phaseStates.get(phaseId);
437
409
  // ADR 0148: closed_unauditedも他の終端状態と同じく確定済みとして扱う。ここへ足さないと、
@@ -1046,132 +1018,7 @@ function mergedTaskKey(refValue) {
1046
1018
  return `${refValue.project_id}\0${refValue.plan_key}\0${refValue.task_id}`;
1047
1019
  }
1048
1020
 
1049
- function mergedTaskStates(store) {
1050
- return new Map(store.members.flatMap((member) => member.tasks.map((taskValue) => ([
1051
- mergedTaskKey({
1052
- project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: taskValue.task_id,
1053
- }),
1054
- taskValue.status,
1055
- ]))));
1056
- }
1057
-
1058
- function mergedTaskPhase(store, taskKey) {
1059
- for (const member of store.members) {
1060
- const task = member.plan.tasks.find((entry) => mergedTaskKey({
1061
- project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: entry.task_id,
1062
- }) === taskKey);
1063
- if (task === undefined) continue;
1064
- if (!isPhaseTodoPlanSchema(member.plan.schema)) return null;
1065
- return { schema: member.plan.schema, plan_key: member.plan.plan_key, phase_id: task.phase_id,
1066
- status: member.snapshot.phases.find(({ phase_id }) => phase_id === task.phase_id)?.status };
1067
- }
1068
- return undefined;
1069
- }
1070
-
1071
- function mergedDependencyPhaseReady(store, predecessorKey, targetKey) {
1072
- const predecessor = mergedTaskPhase(store, predecessorKey);
1073
- const target = mergedTaskPhase(store, targetKey);
1074
- if (predecessor === undefined) return false;
1075
- if (predecessor === null) return true;
1076
- if (isDecoupledPhaseTodoPlanSchema(predecessor.schema)) return true;
1077
- if (target !== null && target !== undefined && predecessor.plan_key === target.plan_key
1078
- && predecessor.phase_id === target.phase_id) return true;
1079
- return predecessor.status === 'accepted';
1080
- }
1081
-
1082
- function mergedPhaseAcceptReady(store, targetKey) {
1083
- for (const member of store.members) {
1084
- if (!isDecoupledPhaseTodoPlanSchema(member.plan.schema)) continue;
1085
- for (const edge of member.plan.phase_accept_dependencies) {
1086
- if (mergedTaskKey(edge.to) !== targetKey) continue;
1087
- const source = store.members.find((candidate) => candidate.plan.project_id === edge.from.project_id
1088
- && candidate.plan.plan_key === edge.from.plan_key);
1089
- if (source?.snapshot.phases.find(({ phase_id }) => phase_id === edge.from.phase_id)?.status !== 'accepted') {
1090
- return false;
1091
- }
1092
- }
1093
- }
1094
- return true;
1095
- }
1096
-
1097
- function mergedPredecessorKeys(store, targetKey) {
1098
- const result = [];
1099
- for (const member of store.members) {
1100
- for (const edge of member.plan.hard_dependencies) {
1101
- if (mergedTaskKey(edge.to) === targetKey) result.push(mergedTaskKey(edge.from));
1102
- }
1103
- for (const join of member.plan.joins) {
1104
- if (mergedTaskKey(join.before) === targetKey) {
1105
- for (const after of join.after) result.push(mergedTaskKey(after));
1106
- }
1107
- }
1108
- }
1109
- for (const dependency of projectTodoCrossPlanDependencies(store.members)) {
1110
- if (mergedTaskKey(dependency.to) === targetKey) result.push(mergedTaskKey(dependency.from));
1111
- }
1112
- return [...new Set(result)];
1113
- }
1114
-
1115
- function mergedSuccessorKeys(store, targetKey) {
1116
- const result = [];
1117
- for (const member of store.members) {
1118
- for (const edge of member.plan.hard_dependencies) {
1119
- if (mergedTaskKey(edge.from) === targetKey) result.push(mergedTaskKey(edge.to));
1120
- }
1121
- for (const join of member.plan.joins) {
1122
- if (join.after.some((after) => mergedTaskKey(after) === targetKey)) {
1123
- result.push(mergedTaskKey(join.before));
1124
- }
1125
- }
1126
- }
1127
- for (const dependency of projectTodoCrossPlanDependencies(store.members)) {
1128
- if (mergedTaskKey(dependency.from) === targetKey) result.push(mergedTaskKey(dependency.to));
1129
- }
1130
- return [...new Set(result)];
1131
- }
1132
-
1133
- function validateMergedTransition(store, member, event) {
1134
- const targetKey = mergedTaskKey({
1135
- project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: event.task_id,
1136
- });
1137
- const states = mergedTaskStates(store);
1138
- const taskDependenciesDone = mergedPredecessorKeys(store, targetKey)
1139
- .every((key) => states.get(key) === 'done' && mergedDependencyPhaseReady(store, key, targetKey));
1140
- const phaseAcceptReady = mergedPhaseAcceptReady(store, targetKey);
1141
- const dependenciesDone = taskDependenciesDone && phaseAcceptReady;
1142
- if (event.kind === 'start' && event.payload.start_mode !== 'historical_import'
1143
- && event.payload.start_mode !== 'rebind'
1144
- && (!phaseAcceptReady || (!taskDependenciesDone && event.payload.override_reason === null))) {
1145
- fail('STORE_INCONSISTENT', 'invalid_start_transition');
1146
- }
1147
- if (event.kind === 'done' && event.payload.done_mode === 'authored' && !dependenciesDone) {
1148
- fail('STORE_INCONSISTENT', 'invalid_done_transition');
1149
- }
1150
- if (event.kind === 'reopen' && event.payload.override_reason === null) {
1151
- const startedSuccessor = mergedSuccessorKeys(store, targetKey)
1152
- .some((key) => states.get(key) !== 'pending');
1153
- if (startedSuccessor) {
1154
- fail('STORE_INCONSISTENT', 'reopen_has_started_successor', {
1155
- next_action: `lattice todo split --plan ${member.plan.plan_key} --input <file>`,
1156
- });
1157
- }
1158
- }
1159
- if (event.kind === 'phase_reopen' && event.payload.override_reason === null) {
1160
- const startedSuccessor = member.plan.schema === 'lattice.todo_plan.v4'
1161
- ? member.plan.tasks.filter(({ phase_id }) => phase_id === event.phase_id)
1162
- .map(({ task_id }) => mergedTaskKey({ project_id: member.plan.project_id,
1163
- plan_key: member.plan.plan_key, task_id }))
1164
- .flatMap((key) => mergedSuccessorKeys(store, key))
1165
- .some((key) => states.get(key) !== 'pending')
1166
- : store.members.some((candidate) => isDecoupledPhaseTodoPlanSchema(candidate.plan.schema)
1167
- && candidate.plan.phase_accept_dependencies.some((edge) => (
1168
- edge.from.project_id === member.plan.project_id
1169
- && edge.from.plan_key === member.plan.plan_key && edge.from.phase_id === event.phase_id
1170
- && states.get(mergedTaskKey(edge.to)) !== 'pending'
1171
- )));
1172
- if (startedSuccessor) fail('STORE_INCONSISTENT', 'phase_reopen_has_started_successor');
1173
- }
1174
- }
1021
+ // Temporary adapter until Store receives the Plan callback from its caller.
1175
1022
 
1176
1023
  /**
1177
1024
  * refsから辿れるobject idの集合。repositoryごとに1度だけ数え、以後は使い回す。
@@ -1505,7 +1352,61 @@ function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache =
1505
1352
  }
1506
1353
  }
1507
1354
 
1355
+ function recoverableReadError(error) {
1356
+ return error instanceof TodoStoreError && [
1357
+ 'manifest_journal_head_mismatch', 'snapshot_stale',
1358
+ 'source_cutover_recovery_required', 'cross_plan_import_recovery_required',
1359
+ ].includes(error.detail.reason);
1360
+ }
1361
+
1508
1362
  export async function readTodoStore(options = {}) {
1363
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1364
+ let view;
1365
+ let observedError;
1366
+ try {
1367
+ view = await readTodoStoreView(options);
1368
+ const lockPresent = await lstat(path.join(repoRoot, STORE_ROOT_REF, '.write.lock'))
1369
+ .then(() => true, (error) => { if (error?.code === 'ENOENT') return false; throw error; });
1370
+ if (!view.snapshot_stale && !lockPresent) return view;
1371
+ } catch (error) {
1372
+ if (!recoverableReadError(error)) throw error;
1373
+ observedError = error;
1374
+ }
1375
+ try { return await withLock(repoRoot, () => readTodoStoreLocked(options)); }
1376
+ catch (error) {
1377
+ // A concurrent writer owns its publication window; stable readers retry it.
1378
+ if (error instanceof TodoStoreError && error.code === 'STORE_WRITE_CONFLICT') {
1379
+ if (view) return view;
1380
+ if (error.detail.reason !== 'store_locked' || error.detail.cause) throw error;
1381
+ if (observedError) throw observedError;
1382
+ }
1383
+ throw error;
1384
+ }
1385
+ }
1386
+
1387
+ async function readTodoStoreLocked(options = {}) {
1388
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1389
+ if (options.sourceCutoverRecoveryCapability !== SOURCE_CUTOVER_RECOVERY_CAPABILITY) {
1390
+ await recoverSourceCutover(repoRoot, options.now);
1391
+ }
1392
+ await recoverCrossPlanImports(repoRoot);
1393
+ const recovery = { manifestDirty: false };
1394
+ const store = await readTodoStoreView({ ...options, recovery });
1395
+ // Every member and merged graph has validated before any derived publication.
1396
+ for (const member of store.members) {
1397
+ if (!member.snapshot_stale) continue;
1398
+ await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(member.snapshot));
1399
+ member.snapshot_stale = false;
1400
+ }
1401
+ if (recovery.manifestDirty) {
1402
+ store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
1403
+ await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
1404
+ }
1405
+ store.snapshot_stale = false;
1406
+ return store;
1407
+ }
1408
+
1409
+ async function readTodoStoreView(options = {}) {
1509
1410
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1510
1411
  const barrier = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
1511
1412
  if (barrier !== null) {
@@ -1540,7 +1441,12 @@ export async function readTodoStore(options = {}) {
1540
1441
  }
1541
1442
  const journal = await readJournal(repoRoot, descriptor.journal_ref);
1542
1443
  if (journal.events.at(-1).event_digest !== descriptor.journal_head_digest) {
1543
- fail('STORE_INCONSISTENT', 'manifest_journal_head_mismatch');
1444
+ if (!options.recovery || !journal.events.some(({ event_digest: digest }) => (
1445
+ digest === descriptor.journal_head_digest))) {
1446
+ fail('STORE_INCONSISTENT', 'manifest_journal_head_mismatch');
1447
+ }
1448
+ options.recovery.manifestDirty = true;
1449
+ descriptor.journal_head_digest = journal.events.at(-1).event_digest;
1544
1450
  }
1545
1451
  let revision = null;
1546
1452
  const genesis = journal.events[0];
@@ -1625,7 +1531,7 @@ export async function readTodoStore(options = {}) {
1625
1531
  'artifact_eol_converted'].includes(error.detail.reason)) snapshotStale = true;
1626
1532
  else throw error;
1627
1533
  }
1628
- if (options.forWrite === true && snapshotStale) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
1534
+ if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
1629
1535
  // 導出済みphase状態(ADR 0147)。snapshot artifactの形式(v1/v2)には縛られず、v4/v5・
1630
1536
  // phase無しplanのどちらでも同じ形(暗黙のterminal-audit Phase込み)で常に埋める。
1631
1537
  // 消費者はここを読み、snapshot.phases(v1には存在しない)を直接読まない。
@@ -1701,11 +1607,7 @@ async function atomicWrite(absolute, bytes) {
1701
1607
  try {
1702
1608
  handle = await open(temporary, 'wx', 0o600);
1703
1609
  await handle.writeFile(bytes);
1704
- // WSL2でのNTFSパス(/mnt/以下)ではfsyncがEIOを返すことがある。データ自体は書き込まれている。
1705
- try { await handle.sync(); } catch (syncError) {
1706
- if (!(process.platform === 'linux' && /^\/mnt\//.test(absolute) && syncError?.code === 'EIO')) throw syncError;
1707
- process.stderr.write(`lattice: fsync skipped (WSL2/NTFS EIO) ${absolute}\n`);
1708
- }
1610
+ await syncPublishedFile(handle, absolute);
1709
1611
  await handle.close(); handle = null;
1710
1612
  await renamePublishedFile(temporary, absolute);
1711
1613
  await fsyncDirectory(path.dirname(absolute));
@@ -1723,10 +1625,7 @@ async function atomicWriteMode(absolute, bytes, mode) {
1723
1625
  try {
1724
1626
  handle = await open(temporary, 'wx', mode);
1725
1627
  await handle.writeFile(bytes); await handle.chmod(mode);
1726
- try { await handle.sync(); } catch (syncError) {
1727
- if (!(process.platform === 'linux' && /^\/mnt\//.test(absolute) && syncError?.code === 'EIO')) throw syncError;
1728
- process.stderr.write(`lattice: fsync skipped (WSL2/NTFS EIO) ${absolute}\n`);
1729
- }
1628
+ await syncPublishedFile(handle, absolute);
1730
1629
  await handle.close(); handle = null;
1731
1630
  await renamePublishedFile(temporary, absolute);
1732
1631
  await fsyncDirectory(path.dirname(absolute));
@@ -1737,105 +1636,42 @@ async function atomicWriteMode(absolute, bytes, mode) {
1737
1636
  }
1738
1637
 
1739
1638
 
1740
- async function createWriteLock(lockRef, { recordOwner = false } = {}) {
1741
- const handle = await open(lockRef, 'wx', 0o600);
1742
- if (!recordOwner) return handle;
1639
+ async function withLock(repoRoot, callback, {
1640
+ onProtocolStage = null, lockCapability = null, initialize = false,
1641
+ } = {}) {
1642
+ if (lockCapability === STORE_LOCK_HELD) return callback();
1743
1643
  try {
1744
- await handle.writeFile(canonicalLine({ pid: process.pid }));
1745
- await handle.sync();
1746
- return handle;
1644
+ if (!initialize) {
1645
+ const root = await lstat(path.join(repoRoot, STORE_ROOT_REF)).catch((error) => {
1646
+ if (error?.code === 'ENOENT') fail('STORE_INCONSISTENT', 'artifact_missing', { ref: MANIFEST_REF });
1647
+ throw error;
1648
+ });
1649
+ const parent = await lstat(path.join(repoRoot, '.lattice')).catch((error) => {
1650
+ if (error?.code === 'ENOENT') fail('STORE_INCONSISTENT', 'artifact_missing', { ref: MANIFEST_REF });
1651
+ throw error;
1652
+ });
1653
+ if (!root.isDirectory() || root.isSymbolicLink()
1654
+ || !parent.isDirectory() || parent.isSymbolicLink()) {
1655
+ fail('STORE_INCONSISTENT', 'unsafe_artifact_path', { ref: STORE_ROOT_REF });
1656
+ }
1657
+ }
1658
+ return await withStoreLock({
1659
+ lockPath: path.join(repoRoot, STORE_ROOT_REF, '.write.lock'),
1660
+ createParent: initialize,
1661
+ recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
1662
+ onRecoveryClaim: typeof onProtocolStage === 'function'
1663
+ ? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
1664
+ }, callback);
1747
1665
  } catch (error) {
1748
- await handle.close();
1749
- await rm(lockRef, { force: true });
1666
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
1750
1667
  throw error;
1751
1668
  }
1752
1669
  }
1753
1670
 
1754
- async function staleWriteLockOwner(lockRef) {
1755
- let record;
1756
- try { record = JSON.parse((await readFile(lockRef)).toString('utf8')); }
1757
- catch { return false; }
1758
- if (!exactRecord(record, ['pid']) || !Number.isSafeInteger(record.pid) || record.pid <= 0) return false;
1759
- try {
1760
- process.kill(record.pid, 0);
1761
- return false;
1762
- } catch (error) {
1763
- return error?.code === 'ESRCH';
1764
- }
1765
- }
1766
-
1767
- function processIsDead(pid) {
1768
- try {
1769
- process.kill(pid, 0);
1770
- return false;
1771
- } catch (error) {
1772
- return error?.code === 'ESRCH';
1773
- }
1774
- }
1775
-
1776
- async function acquireCrossPlanRecoveryClaim(recoveryClaimsRef) {
1777
- await mkdir(recoveryClaimsRef, { recursive: true, mode: 0o700 });
1778
- const claimOrder = process.hrtime.bigint().toString().padStart(20, '0');
1779
- const claimName = `${claimOrder}-${process.pid}-${randomBytes(8).toString('hex')}`;
1780
- const claimRef = path.join(recoveryClaimsRef, claimName);
1781
- await mkdir(claimRef, { mode: 0o700 });
1782
- for (const entry of await readdir(recoveryClaimsRef, { withFileTypes: true })) {
1783
- if (!entry.isDirectory() || entry.name === claimName) continue;
1784
- const parts = entry.name.split('-', 3);
1785
- const pid = Number(parts.length === 2 ? parts[0] : parts[1]);
1786
- if (Number.isSafeInteger(pid) && pid > 0 && processIsDead(pid)) {
1787
- await rm(path.join(recoveryClaimsRef, entry.name), { recursive: true, force: true });
1788
- }
1789
- }
1790
- const candidates = (await readdir(recoveryClaimsRef)).sort();
1791
- if (candidates[0] === claimName) return claimRef;
1792
- await rmdir(claimRef);
1793
- return null;
1794
- }
1795
-
1796
- async function recoverCrossPlanWriteLock(lockRef, recoveryClaimsRef, onProtocolStage) {
1797
- const claimRef = await acquireCrossPlanRecoveryClaim(recoveryClaimsRef);
1798
- if (claimRef === null) return undefined;
1799
- try {
1800
- if (typeof onProtocolStage === 'function') await onProtocolStage('cross_plan_lock_recovery_mutex_acquired');
1801
- if (!await staleWriteLockOwner(lockRef)) return undefined;
1802
- await rm(lockRef, { force: true });
1803
- try { return await createWriteLock(lockRef, { recordOwner: true }); }
1804
- catch (error) {
1805
- if (error?.code === 'EEXIST') return undefined;
1806
- throw error;
1807
- }
1808
- } finally {
1809
- await rm(claimRef, { recursive: true, force: true });
1810
- try { await rmdir(recoveryClaimsRef); }
1811
- catch (error) {
1812
- if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error;
1813
- }
1814
- }
1815
- }
1816
-
1817
- async function withLock(repoRoot, callback, { recoverDeadLock = false, onProtocolStage = null } = {}) {
1818
- const root = path.join(repoRoot, STORE_ROOT_REF);
1819
- await mkdir(root, { recursive: true });
1820
- const lockRef = path.join(root, '.write.lock');
1821
- const recoveryClaimsRef = path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF);
1822
- let handle;
1823
- try { handle = await createWriteLock(lockRef, { recordOwner: recoverDeadLock }); }
1824
- catch (error) {
1825
- if (error?.code !== 'EEXIST') throw error;
1826
- if (recoverDeadLock) {
1827
- handle = await recoverCrossPlanWriteLock(lockRef, recoveryClaimsRef, onProtocolStage);
1828
- }
1829
- }
1830
- if (handle === undefined) fail('STORE_WRITE_CONFLICT', 'store_locked');
1831
- try { return await callback(); }
1832
- finally { await handle.close(); await rm(lockRef, { force: true }); }
1833
- }
1834
-
1835
1671
  export async function rebuildTodoSnapshot(options = {}) {
1836
1672
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1837
1673
  return withLock(repoRoot, async () => {
1838
- const store = await readTodoStore({ repoRoot, now: options.now });
1674
+ const store = await readTodoStoreLocked({ repoRoot, now: options.now });
1839
1675
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
1840
1676
  if (!member) fail('STORE_INCONSISTENT', 'plan_not_active');
1841
1677
  await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(member.snapshot));
@@ -2038,9 +1874,12 @@ async function enforceTodoStructureLifecycleGate(repoRoot, member, eventInput) {
2038
1874
 
2039
1875
  export async function appendTodoEvent(options = {}) {
2040
1876
  requireWriter(options.writer, 'g5-authoring');
1877
+ if (typeof options.validateProspectiveEvent !== 'function') {
1878
+ throw new TypeError('appendTodoEvent requires a Plan-supplied validateProspectiveEvent');
1879
+ }
2041
1880
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2042
1881
  return withLock(repoRoot, async () => {
2043
- const store = await readTodoStore({
1882
+ const store = await readTodoStoreLocked({
2044
1883
  repoRoot, forWrite: true, now: options.now,
2045
1884
  // 修理扉は除去event(tombstone)の書込みだけに開く。それ以外の書込みは従来どおり
2046
1885
  // binding_stale で fail closed する(validateMergedGraph の注記を参照)
@@ -2086,7 +1925,12 @@ export async function appendTodoEvent(options = {}) {
2086
1925
  fail('STORE_WRITE_CONFLICT', 'historical_import_writer_required');
2087
1926
  }
2088
1927
  // Validate the prospective history, including hard evidence and transitions, before any write.
2089
- validateMergedTransition(store, member, event);
1928
+ const validation = options.validateProspectiveEvent({ store, member, event });
1929
+ if (validation?.ok === false) {
1930
+ const { reason, ...detail } = validation.detail;
1931
+ fail(validation.code, reason, detail);
1932
+ }
1933
+ if (validation?.ok !== true) throw new TypeError('prospective validator must return an ok result');
2090
1934
  const appendSourceCache = { commits: new Set(), blobs: new Map() };
2091
1935
  prefetchVerificationObjects(store.manifest, repoRoot,
2092
1936
  [...member.journal.events, event], appendSourceCache);
@@ -2122,6 +1966,7 @@ export async function appendTodoEvent(options = {}) {
2122
1966
  } else {
2123
1967
  await atomicWrite(activeAbsolute, Buffer.concat([member.journal.activeBytes, eventBytes]));
2124
1968
  }
1969
+ await protocolStage(options, 'event_journal_published');
2125
1970
  const tasks = replay(member.plan, [...member.journal.events, event], {
2126
1971
  now: options.now ? new Date(options.now) : new Date(),
2127
1972
  verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
@@ -2129,9 +1974,11 @@ export async function appendTodoEvent(options = {}) {
2129
1974
  });
2130
1975
  const snapshot = snapshotFor(member.plan, [...member.journal.events, event], tasks);
2131
1976
  await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(snapshot));
1977
+ await protocolStage(options, 'event_snapshot_published');
2132
1978
  member.descriptor.journal_head_digest = event.event_digest;
2133
1979
  store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
2134
1980
  await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
1981
+ await protocolStage(options, 'event_manifest_published');
2135
1982
  // snapshot artifactの形式(v1/v2)はplanのschemaで決まったまま変えない。呼び出し側
2136
1983
  // (todo-cli.mjsのphaseMutation・done advisory)がPhase状態(暗黙のterminal-audit含む)を
2137
1984
  // 見るための導出ビューは、snapshotと分けてここで別途返す。
@@ -2203,7 +2050,12 @@ export function buildTodoPlan(input) {
2203
2050
  ? { phase_accept_dependencies: plan.phase_accept_dependencies } : {}),
2204
2051
  });
2205
2052
  plan.plan_digest = todoSelfDigest(plan, 'plan_digest');
2206
- if (!validateTodoPlan(plan)) throw new TypeError('todo plan input violates its declared schema');
2053
+ if (!validateTodoPlan(plan)) {
2054
+ const { reason, path: pointer, ...values } = explainTodoPlan(plan);
2055
+ throw Object.assign(new TypeError('todo plan input violates its declared schema'), {
2056
+ detail: { violation_kind: reason, pointer, ...values },
2057
+ });
2058
+ }
2207
2059
  return plan;
2208
2060
  }
2209
2061
 
@@ -2622,7 +2474,17 @@ async function finalizeVisibleCrossPlanImport(repoRoot, transaction, { removeTra
2622
2474
  ref: artifact.staged_ref,
2623
2475
  });
2624
2476
  }
2625
- await atomicWrite(path.resolve(repoRoot, artifact.ref), bytes);
2477
+ const eventBytes = canonicalLine(transaction.marker.events[0]);
2478
+ if (!bytes.subarray(-eventBytes.length).equals(eventBytes)) {
2479
+ fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.staged_ref });
2480
+ }
2481
+ const target = await pathState(repoRoot, artifact.ref, 'STORE_INCONSISTENT', { missing: true });
2482
+ const current = target === null ? Buffer.alloc(0) : await readFile(target.absolute);
2483
+ const before = bytes.subarray(0, bytes.length - eventBytes.length);
2484
+ if (!current.equals(before) && !current.equals(bytes)) {
2485
+ fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.ref });
2486
+ }
2487
+ if (!current.equals(bytes)) await atomicWrite(path.resolve(repoRoot, artifact.ref), bytes);
2626
2488
  }
2627
2489
  if (removeTransaction) {
2628
2490
  await rm(path.resolve(repoRoot, transaction.transactionRef), { recursive: true, force: true });
@@ -2648,16 +2510,13 @@ async function assertNoCrossPlanImportRecoveryNeeded(repoRoot) {
2648
2510
  plan_key: transaction.marker.descriptor.plan_key,
2649
2511
  transaction_digest: transaction.marker.transaction_digest,
2650
2512
  state: visible ? 'manifest_activated' : 'pre_activation',
2651
- next_action: 'rerun_the_same_todo_migrate_input',
2513
+ next_action: 'lattice todo status --json',
2652
2514
  });
2653
2515
  }
2654
2516
 
2655
- async function recoverCrossPlanImports(repoRoot, { expectedTransactionDigest }) {
2517
+ async function recoverCrossPlanImports(repoRoot) {
2656
2518
  const transactions = await crossPlanImportTransactions(repoRoot);
2657
2519
  if (transactions.length === 0) return [];
2658
- if (!transactions.every(({ marker }) => marker.transaction_digest === expectedTransactionDigest)) {
2659
- await assertNoCrossPlanImportRecoveryNeeded(repoRoot);
2660
- }
2661
2520
  let manifest;
2662
2521
  try {
2663
2522
  manifest = await readArtifact(repoRoot, MANIFEST_REF, {
@@ -2686,7 +2545,7 @@ async function recoverCrossPlanImports(repoRoot, { expectedTransactionDigest })
2686
2545
  }
2687
2546
 
2688
2547
  async function recoveredImportedPlanResult(repoRoot, marker, now) {
2689
- const store = await readTodoStore({ repoRoot, forWrite: true, now });
2548
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now });
2690
2549
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === marker.descriptor.plan_key);
2691
2550
  if (member === undefined) fail('STORE_INCONSISTENT', 'cross_plan_transaction_recovery_missing_plan');
2692
2551
  return {
@@ -2706,7 +2565,7 @@ async function appendExistingCrossPlanDependency(options) {
2706
2565
  }
2707
2566
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2708
2567
  return withLock(repoRoot, async () => {
2709
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
2568
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
2710
2569
  const source = store.members.find(({ plan }) => plan.project_id === options.connectionPlan.project_id
2711
2570
  && plan.plan_key === options.connectionPlan.plan_key);
2712
2571
  if (source === undefined) {
@@ -2733,7 +2592,7 @@ async function appendExistingCrossPlanDependency(options) {
2733
2592
  snapshot: source.snapshot, descriptor: source.descriptor,
2734
2593
  crossPlanDependencies: prepared.events, connectionOnly: true,
2735
2594
  };
2736
- }, { recoverDeadLock: true, onProtocolStage: options.onProtocolStage });
2595
+ }, { onProtocolStage: options.onProtocolStage });
2737
2596
  }
2738
2597
 
2739
2598
  /** G4-only atomic import, with optional all-or-nothing store bootstrap. */
@@ -2750,28 +2609,95 @@ export async function appendImportedPlan(options = {}) {
2750
2609
  if (error?.code === 'ENOENT') return bootstrapImportedPlan(repoRoot, options);
2751
2610
  throw error;
2752
2611
  }
2612
+ if (await isUninitializedTodoStore({ repoRoot })) {
2613
+ fail('STORE_INCONSISTENT', 'artifact_missing', {
2614
+ ref: MANIFEST_REF,
2615
+ next_action: `Confirm no writer, then clear only abandoned lock/tmp residue from ${path.join(repoRoot, STORE_ROOT_REF)} and retry the same migration input; preserve any member or note data.`,
2616
+ });
2617
+ }
2618
+ }
2619
+ return appendPlanMembership(repoRoot, options, false);
2620
+ }
2621
+
2622
+ /** G5-only new membership; existing keys are never revisions or idempotent creates. */
2623
+ export async function appendAuthoredTodoPlan(options = {}) {
2624
+ requireWriter(options.writer, 'g5-authoring');
2625
+ const keys = ['repoRoot', 'writer', 'plan', 'genesis'];
2626
+ if (options.featureChain !== undefined) keys.push('featureChain');
2627
+ if (options.onProtocolStage !== undefined) keys.push('onProtocolStage');
2628
+ if (!exactRecord(options, keys)
2629
+ || (options.onProtocolStage !== undefined && typeof options.onProtocolStage !== 'function')
2630
+ || !(exactRecord(options.genesis, ['actor', 'recorded_at'])
2631
+ || exactRecord(options.genesis, ['actor', 'recorded_at', 'provenance']))) {
2632
+ throw new TypeError('authored plan addition input invalid');
2633
+ }
2634
+ return appendPlanMembership(path.resolve(options.repoRoot), options, true);
2635
+ }
2636
+
2637
+ function prepareAuthoredArtifacts(repoRoot, options, store) {
2638
+ if (!validateTodoPlan(options.plan) || options.plan.predecessor_plan_digest !== null) {
2639
+ throw new TypeError('authored plan must be a valid genesis plan');
2640
+ }
2641
+ const plan = options.plan;
2642
+ if (plan.project_id !== store.project_id) fail('STORE_WRITE_CONFLICT', 'project_id_mismatch', {
2643
+ expected: store.project_id, actual: plan.project_id,
2644
+ });
2645
+ verifyPlanNarrativeAnchors(repoRoot, plan);
2646
+ const genesis = buildPlanGenesis(plan, options.genesis);
2647
+ const events = [genesis];
2648
+ const tasks = replay(plan, events);
2649
+ validateMergedGraph([...store.members, { plan }]);
2650
+ return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
2651
+ }
2652
+
2653
+ async function assertUnpublishedPlanFiles(directory, expected) {
2654
+ const occupied = (ref) => fail('REVISION_CONFLICT', 'revision_bytes_conflict', {
2655
+ ref,
2656
+ next_action: `Restore the expected unpublished files at ${directory} or use another plan key/version; existing bytes were preserved.`,
2657
+ });
2658
+ async function visit(current, prefix = '') {
2659
+ const state = await lstat(current).catch((error) => {
2660
+ if (error?.code !== 'ENOENT') throw error;
2661
+ return null;
2662
+ });
2663
+ if (state === null) return;
2664
+ if (state.isSymbolicLink() || !state.isDirectory()) occupied(current);
2665
+ for (const entry of await readdir(current, { withFileTypes: true })) {
2666
+ const relative = `${prefix}${entry.name}`;
2667
+ if (entry.isDirectory() && [...expected.keys()].some((ref) => ref.startsWith(`${relative}/`))) {
2668
+ await visit(path.join(current, entry.name), `${relative}/`);
2669
+ } else if (!entry.isFile() || !expected.has(relative)
2670
+ || !(await readFile(path.join(current, entry.name))).equals(expected.get(relative))) {
2671
+ occupied(path.join(directory, relative));
2672
+ }
2673
+ }
2674
+ if (!sameDirectoryIdentity(state, await lstat(current))) occupied(current);
2753
2675
  }
2754
- const transactionDigest = importedPlanTransactionDigest(options);
2676
+ await visit(directory);
2677
+ }
2678
+
2679
+ async function appendPlanMembership(repoRoot, options, authored) {
2680
+ const transactionDigest = authored ? null : importedPlanTransactionDigest(options);
2755
2681
  return withLock(repoRoot, async () => {
2756
- const recovered = await recoverCrossPlanImports(repoRoot, { expectedTransactionDigest: transactionDigest });
2682
+ const recovered = await recoverCrossPlanImports(repoRoot);
2757
2683
  const recoveredOwnTransaction = recovered.find((marker) => marker.transaction_digest === transactionDigest);
2758
- if (recoveredOwnTransaction !== undefined) {
2684
+ if (!authored && recoveredOwnTransaction !== undefined) {
2759
2685
  return recoveredImportedPlanResult(repoRoot, recoveredOwnTransaction, options.now);
2760
2686
  }
2761
2687
  // 1. Validate canonical manifest bytes and every current member before preparing output.
2762
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
2688
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
2763
2689
  const expectedManifestDigest = store.manifest.manifest_digest;
2764
2690
  await protocolStage(options, 'manifest_validated');
2765
2691
 
2766
2692
  // 2. A plan key is never overwritten, merged, or treated as an idempotent success.
2767
2693
  const existing = store.members.find(({ descriptor }) => descriptor.plan_key === options.plan?.plan_key);
2768
2694
  if (existing) {
2769
- const imported = existing.journal.events[0]?.payload.historical_import === true;
2695
+ const imported = !authored && existing.journal.events[0]?.payload.historical_import === true;
2770
2696
  fail('STORE_WRITE_CONFLICT', imported ? 'plan_key_already_imported' : 'plan_key_already_exists');
2771
2697
  }
2772
2698
  await protocolStage(options, 'plan_key_absent');
2773
2699
 
2774
- const prepared = prepareImportedArtifacts(
2700
+ const prepared = authored ? prepareAuthoredArtifacts(repoRoot, options, store) : prepareImportedArtifacts(
2775
2701
  repoRoot, options, store.project_id, store.members.map(({ plan: memberPlan }) => ({ plan: memberPlan })),
2776
2702
  );
2777
2703
  const { plan, genesis, events, snapshot, tasks } = prepared;
@@ -2781,7 +2707,7 @@ export async function appendImportedPlan(options = {}) {
2781
2707
  const planRef = `${base}/plan.json`;
2782
2708
  const journalRef = `${base}/journal/active.jsonl`;
2783
2709
  const snapshotRef = `${base}/snapshot.json`;
2784
- const importedCrossPlan = prepareImportedCrossPlanDependencies({
2710
+ const importedCrossPlan = authored ? { artifacts: [], events: [] } : prepareImportedCrossPlanDependencies({
2785
2711
  store, plan, tasks, dependencies: options.crossPlanDependencies, genesis, journalRef,
2786
2712
  });
2787
2713
  const hasCrossPlanDependencies = importedCrossPlan.artifacts.length > 0;
@@ -2790,7 +2716,23 @@ export async function appendImportedPlan(options = {}) {
2790
2716
  : `${STORE_ROOT_REF}/transactions/${plan.plan_key}-${plan.plan_version}`;
2791
2717
  const transactionAbsolute = path.resolve(repoRoot, transactionRef);
2792
2718
  const finalBaseAbsolute = path.resolve(repoRoot, base);
2793
- // These paths can only be leftovers from a transaction whose plan key is still absent.
2719
+ await ensureSafeStoreDirectory(repoRoot, path.dirname(transactionAbsolute));
2720
+ await ensureSafeStoreDirectory(repoRoot, path.dirname(finalBaseAbsolute));
2721
+ const expected = new Map([
2722
+ ['plan.json', canonicalLine(plan)], ['journal/active.jsonl', Buffer.concat(events.map(canonicalLine))],
2723
+ ['snapshot.json', canonicalLine(snapshot)],
2724
+ ...(backchain === null ? [] : [['backchain.json', canonicalLine(backchain)]]),
2725
+ ]);
2726
+ const stagedExpected = new Map([...expected].map(([ref, bytes]) => [
2727
+ hasCrossPlanDependencies ? `plan/${ref}` : ref === 'journal/active.jsonl' ? 'active.jsonl' : ref,
2728
+ bytes,
2729
+ ]));
2730
+ for (const [index, artifact] of importedCrossPlan.artifacts.entries()) {
2731
+ stagedExpected.set(`plan-scoped/${index}.jsonl`, artifact.finalBytes);
2732
+ }
2733
+ await assertUnpublishedPlanFiles(transactionAbsolute, stagedExpected);
2734
+ await assertUnpublishedPlanFiles(finalBaseAbsolute, expected);
2735
+ // Only enumerated, byte-identical unpublished artifacts can be replaced.
2794
2736
  await rm(transactionAbsolute, { recursive: true, force: true });
2795
2737
  await rm(finalBaseAbsolute, { recursive: true, force: true });
2796
2738
 
@@ -2870,6 +2812,7 @@ export async function appendImportedPlan(options = {}) {
2870
2812
  await protocolStage(options, 'cross_plan_dependencies_activated');
2871
2813
  }
2872
2814
  await rm(transactionAbsolute, { recursive: true, force: true });
2815
+ if (authored) return readTodoStoreLocked({ repoRoot, forWrite: true });
2873
2816
  return {
2874
2817
  plan, genesis, events, snapshot, descriptor,
2875
2818
  crossPlanDependencies: importedCrossPlan.events,
@@ -2894,8 +2837,7 @@ export async function appendImportedPlan(options = {}) {
2894
2837
  }
2895
2838
  throw error;
2896
2839
  }
2897
- }, { recoverDeadLock: Array.isArray(options.crossPlanDependencies)
2898
- && options.crossPlanDependencies.length > 0, onProtocolStage: options.onProtocolStage });
2840
+ }, { onProtocolStage: options.onProtocolStage });
2899
2841
  }
2900
2842
 
2901
2843
  export async function initializeTodoStore(options = {}) {
@@ -2927,8 +2869,141 @@ export async function initializeTodoStore(options = {}) {
2927
2869
  if (!validateTodoManifest(manifest)) throw new TypeError('manifest input violates lattice.todo_manifest.v1');
2928
2870
  // Activation is last: a crash before this point leaves the new store/version unpublished.
2929
2871
  await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(manifest));
2930
- return readTodoStore({ repoRoot, now: options.now });
2872
+ return readTodoStoreLocked({ repoRoot, now: options.now });
2873
+ }, { initialize: true });
2874
+ }
2875
+
2876
+ const sameDirectoryIdentity = (left, right) => left !== null && right !== null
2877
+ && left.dev === right.dev && left.ino === right.ino;
2878
+
2879
+ async function transientStoreDirectory(root, allowNotes = true) {
2880
+ for (const entry of await readdir(root, { withFileTypes: true })) {
2881
+ if (entry.isFile() && (entry.name === '.write.lock' || /^\.write\.lock\..+\.tmp$/u.test(entry.name))) continue;
2882
+ if (!entry.isDirectory()) return false;
2883
+ const child = path.join(root, entry.name);
2884
+ if (allowNotes && entry.name === 'notes') {
2885
+ if (!await transientStoreDirectory(child, false)) return false;
2886
+ } else if (['.cross-plan-recovery', '.write.lock.recovery'].includes(entry.name)) {
2887
+ for (const claim of await readdir(child, { withFileTypes: true })) {
2888
+ if (!claim.isDirectory() || (await readdir(path.join(child, claim.name))).length !== 0) return false;
2889
+ }
2890
+ } else return false;
2891
+ }
2892
+ return true;
2893
+ }
2894
+
2895
+ async function uninitializedStoreLayout(repoRoot) {
2896
+ const parent = await lstat(path.join(repoRoot, '.lattice')).catch((error) => {
2897
+ if (error?.code !== 'ENOENT') throw error;
2898
+ return null;
2899
+ });
2900
+ if (parent === null) return { uninitialized: true, identity: null };
2901
+ if (parent.isSymbolicLink() || !parent.isDirectory()) {
2902
+ return { uninitialized: false, identity: null, unsafeParent: true };
2903
+ }
2904
+ const root = path.join(repoRoot, STORE_ROOT_REF);
2905
+ const identity = await lstat(root).catch((error) => {
2906
+ if (error?.code !== 'ENOENT') throw error;
2907
+ return null;
2908
+ });
2909
+ if (identity === null) return { uninitialized: true, identity };
2910
+ if (identity.isSymbolicLink() || !identity.isDirectory()) return { uninitialized: false, identity };
2911
+ try { return { identity, uninitialized: await transientStoreDirectory(root) }; }
2912
+ catch (error) {
2913
+ if (error?.code === 'ENOENT' && await lstat(root).catch((missing) => {
2914
+ if (missing?.code !== 'ENOENT') throw missing;
2915
+ return null;
2916
+ }) === null) return { uninitialized: true, identity: null };
2917
+ throw error;
2918
+ }
2919
+ }
2920
+
2921
+ /** Discovery only; liveness and the final publication decision stay in the transaction. */
2922
+ export async function isUninitializedTodoStore({ repoRoot = process.cwd() } = {}) {
2923
+ return (await uninitializedStoreLayout(path.resolve(repoRoot))).uninitialized;
2924
+ }
2925
+
2926
+ async function prepareAuthoredStoreRoot(repoRoot, options) {
2927
+ const observed = await uninitializedStoreLayout(repoRoot);
2928
+ if (observed.unsafeParent) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
2929
+ if (!observed.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
2930
+ if (observed.identity === null) return;
2931
+ const root = path.join(repoRoot, STORE_ROOT_REF);
2932
+ try { await withLock(repoRoot, async () => {
2933
+ const fresh = await uninitializedStoreLayout(repoRoot);
2934
+ if (!sameDirectoryIdentity(observed.identity, fresh.identity)) {
2935
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
2936
+ }
2937
+ if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
2938
+ const notes = path.join(root, 'notes');
2939
+ const notesIdentity = await lstat(notes).catch((error) => {
2940
+ if (error?.code !== 'ENOENT') throw error;
2941
+ return null;
2942
+ });
2943
+ if (notesIdentity !== null) {
2944
+ await withStoreLock({ lockPath: path.join(notes, '.write.lock'), createParent: false }, async () => {
2945
+ if (!sameDirectoryIdentity(notesIdentity, await lstat(notes))
2946
+ || !await transientStoreDirectory(notes, false)) {
2947
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
2948
+ }
2949
+ });
2950
+ if (!sameDirectoryIdentity(notesIdentity, await lstat(notes))) {
2951
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
2952
+ }
2953
+ try { await rmdir(notes); }
2954
+ catch (error) {
2955
+ if (!['ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error;
2956
+ throw new StoreLockError('store_locked', path.join(notes, '.write.lock'), {
2957
+ next_action: `Confirm no writer before clearing abandoned host-local note lock residue in ${notes}`,
2958
+ });
2959
+ }
2960
+ }
2961
+ await protocolStage(options, 'authoring_residue_locked');
2962
+ }); } catch (error) {
2963
+ const gone = (await uninitializedStoreLayout(repoRoot)).identity === null;
2964
+ if (gone && error instanceof TodoStoreError
2965
+ && ['store_locked', 'artifact_missing'].includes(error.detail.reason)) return;
2966
+ throw error;
2967
+ }
2968
+ await protocolStage(options, 'authoring_residue_released');
2969
+ const fresh = await uninitializedStoreLayout(repoRoot);
2970
+ if (fresh.identity === null && fresh.uninitialized) return;
2971
+ if (!sameDirectoryIdentity(observed.identity, fresh.identity)) {
2972
+ if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
2973
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
2974
+ }
2975
+ const busy = () => fail('STORE_WRITE_CONFLICT', 'store_locked', {
2976
+ lock_path: path.join(root, '.write.lock'),
2977
+ next_action: `Retry after writers exit; confirm no writer before manually clearing unidentified host-local residue in ${root}`,
2978
+ });
2979
+ if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
2980
+ const entries = await readdir(root).catch((error) => {
2981
+ if (error?.code !== 'ENOENT') throw error;
2982
+ return null;
2931
2983
  });
2984
+ if (entries === null) return;
2985
+ if (entries.length !== 0) busy();
2986
+ try { await rmdir(root); }
2987
+ catch (error) {
2988
+ if (['ENOTEMPTY', 'EEXIST'].includes(error?.code)) busy();
2989
+ if (error?.code === 'ENOENT') return;
2990
+ throw error;
2991
+ }
2992
+ await fsyncDirectory(path.dirname(root));
2993
+ }
2994
+
2995
+ async function withInitialStoreLocks(stage, currentRoot, callback) {
2996
+ await mkdir(path.join(stage, 'notes'));
2997
+ const lockOptions = (relative) => ({
2998
+ lockPath: path.join(stage, relative), createParent: false,
2999
+ releasePath: async () => {
3000
+ const root = await currentRoot();
3001
+ return root === null ? null : path.join(root, relative);
3002
+ },
3003
+ });
3004
+ return withStoreLock(lockOptions('.write.lock'), () => (
3005
+ withStoreLock(lockOptions('notes/.write.lock'), callback)
3006
+ ));
2932
3007
  }
2933
3008
 
2934
3009
  /** G5-only initial authoring transaction. Store membership appears by one final directory rename. */
@@ -2977,93 +3052,145 @@ export async function initializeAuthoredTodoStore(options = {}) {
2977
3052
  let activated = false;
2978
3053
  let stageIdentity = null;
2979
3054
  let latticeIdentity = null;
2980
- const sameIdentity = (left, right) => left !== null && right !== null
2981
- && left.dev === right.dev && left.ino === right.ino;
3055
+ const sameIdentity = sameDirectoryIdentity;
3056
+ await prepareAuthoredStoreRoot(repoRoot, options);
3057
+ await mkdir(stage, { mode: 0o700 });
3058
+ stageIdentity = await lstat(stage);
2982
3059
  try {
2983
- try { await lstat(storeRoot); fail('STORE_WRITE_CONFLICT', 'store_already_exists'); }
2984
- catch (error) {
2985
- if (error instanceof TodoStoreError) throw error;
2986
- if (error?.code === 'ENOTDIR') fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
2987
- if (error?.code !== 'ENOENT') throw error;
2988
- }
2989
- await mkdir(stage, { mode: 0o700 });
2990
- stageIdentity = await lstat(stage);
2991
- await atomicWrite(path.join(stage, base, 'plan.json'), canonicalLine(plan));
2992
- await atomicWrite(path.join(stage, base, 'journal', 'active.jsonl'), canonicalLine(genesis));
2993
- await atomicWrite(path.join(stage, base, 'snapshot.json'), canonicalLine(snapshot));
2994
- if (backchain !== null) await atomicWrite(path.join(stage, base, 'backchain.json'), canonicalLine(backchain));
2995
- await atomicWrite(path.join(stage, 'manifest.json'), canonicalLine(manifest));
2996
-
2997
- try {
2998
- const state = await lstat(latticeRoot);
2999
- if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
3000
- } catch (error) {
3001
- if (error instanceof TodoStoreError) throw error;
3002
- if (error?.code !== 'ENOENT') throw error;
3003
- await mkdir(latticeRoot, { mode: 0o700 });
3004
- createdLatticeRoot = true;
3005
- await fsyncDirectory(repoRoot);
3006
- }
3007
- await ensureLatticeEolProtection(latticeRoot);
3008
- latticeIdentity = await lstat(latticeRoot);
3009
- const stagedBeforeRename = await lstat(stage);
3010
- const parentBeforeRename = await lstat(latticeRoot);
3011
- if (!sameIdentity(stageIdentity, stagedBeforeRename)
3012
- || !sameIdentity(latticeIdentity, parentBeforeRename)
3013
- || stagedBeforeRename.isSymbolicLink() || !stagedBeforeRename.isDirectory()
3014
- || parentBeforeRename.isSymbolicLink() || !parentBeforeRename.isDirectory()) {
3015
- fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
3016
- }
3017
- try { await rename(stage, storeRoot); }
3018
- catch (error) {
3019
- if (['EEXIST', 'ENOTEMPTY'].includes(error?.code)) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
3020
- throw error;
3021
- }
3022
- renamed = true;
3023
- await fsyncDirectory(latticeRoot);
3024
- if (typeof options.onProtocolStage === 'function') await options.onProtocolStage('authoring_renamed');
3025
- const activatedStore = await lstat(storeRoot);
3026
- const activatedParent = await lstat(latticeRoot);
3027
- if (!sameIdentity(stageIdentity, activatedStore)
3028
- || !sameIdentity(latticeIdentity, activatedParent)
3029
- || activatedStore.isSymbolicLink() || !activatedStore.isDirectory()
3030
- || activatedParent.isSymbolicLink() || !activatedParent.isDirectory()) {
3031
- fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
3032
- }
3033
- const store = await readTodoStore({ repoRoot });
3034
- const member = store.members[0];
3035
- if (store.project_id !== options.projectId || store.members.length !== 1
3036
- || store.snapshot_stale !== false || member?.journal?.events?.length !== 1
3037
- || canonicalizeTodoArtifact(store.manifest) !== canonicalizeTodoArtifact(manifest)
3038
- || canonicalizeTodoArtifact(member?.descriptor) !== canonicalizeTodoArtifact(descriptor)
3039
- || canonicalizeTodoArtifact(member?.plan) !== canonicalizeTodoArtifact(plan)
3040
- || canonicalizeTodoArtifact(member?.journal?.events?.[0]) !== canonicalizeTodoArtifact(genesis)
3041
- || canonicalizeTodoArtifact(member?.snapshot) !== canonicalizeTodoArtifact(snapshot)) {
3042
- fail('STORE_WRITE_CONFLICT', 'authoring_activation_verification_failed');
3043
- }
3044
- activated = true;
3045
- return store;
3046
- } finally {
3047
- if (renamed && !activated) {
3060
+ return await withInitialStoreLocks(stage, async () => {
3061
+ const current = renamed ? storeRoot : stage;
3062
+ const identity = await lstat(current).catch((error) => {
3063
+ if (error?.code !== 'ENOENT') throw error;
3064
+ return null;
3065
+ });
3066
+ return sameIdentity(stageIdentity, identity) && identity.isDirectory() && !identity.isSymbolicLink()
3067
+ ? current : null;
3068
+ }, async () => {
3048
3069
  try {
3049
- const currentParent = await lstat(latticeRoot);
3050
- const currentStore = await lstat(storeRoot);
3051
- if (sameIdentity(latticeIdentity, currentParent) && sameIdentity(stageIdentity, currentStore)
3052
- && !currentParent.isSymbolicLink() && currentParent.isDirectory()
3053
- && !currentStore.isSymbolicLink() && currentStore.isDirectory()) {
3054
- await rm(storeRoot, { recursive: true, force: true });
3055
- await fsyncDirectory(latticeRoot);
3070
+ stageIdentity = await lstat(stage);
3071
+ await atomicWrite(path.join(stage, base, 'plan.json'), canonicalLine(plan));
3072
+ await atomicWrite(path.join(stage, base, 'journal', 'active.jsonl'), canonicalLine(genesis));
3073
+ await atomicWrite(path.join(stage, base, 'snapshot.json'), canonicalLine(snapshot));
3074
+ if (backchain !== null) await atomicWrite(path.join(stage, base, 'backchain.json'), canonicalLine(backchain));
3075
+ await atomicWrite(path.join(stage, 'manifest.json'), canonicalLine(manifest));
3076
+
3077
+ try {
3078
+ const state = await lstat(latticeRoot);
3079
+ if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
3080
+ } catch (error) {
3081
+ if (error instanceof TodoStoreError) throw error;
3082
+ if (error?.code !== 'ENOENT') throw error;
3083
+ try { await mkdir(latticeRoot, { mode: 0o700 }); createdLatticeRoot = true; }
3084
+ catch (race) { if (race?.code !== 'EEXIST') throw race; }
3085
+ await fsyncDirectory(repoRoot);
3086
+ }
3087
+ await ensureLatticeEolProtection(latticeRoot);
3088
+ latticeIdentity = await lstat(latticeRoot);
3089
+ const stagedBeforeRename = await lstat(stage);
3090
+ const parentBeforeRename = await lstat(latticeRoot);
3091
+ if (!sameIdentity(stageIdentity, stagedBeforeRename)
3092
+ || !sameIdentity(latticeIdentity, parentBeforeRename)
3093
+ || stagedBeforeRename.isSymbolicLink() || !stagedBeforeRename.isDirectory()
3094
+ || parentBeforeRename.isSymbolicLink() || !parentBeforeRename.isDirectory()) {
3095
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
3096
+ }
3097
+ try { await rename(stage, storeRoot); }
3098
+ catch (error) {
3099
+ if (['EEXIST', 'ENOTEMPTY'].includes(error?.code)) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
3100
+ if (error?.code === 'EPERM') {
3101
+ const remainingStage = await lstat(stage).catch(() => null);
3102
+ if (sameIdentity(stageIdentity, remainingStage)
3103
+ && remainingStage.isDirectory() && !remainingStage.isSymbolicLink()) {
3104
+ const destination = await lstat(storeRoot).catch(() => null);
3105
+ if (destination !== null) {
3106
+ let complete = false;
3107
+ if (destination.isDirectory() && !destination.isSymbolicLink()) {
3108
+ try {
3109
+ await readArtifact(repoRoot, MANIFEST_REF, {
3110
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes,
3111
+ validate: validateTodoManifest,
3112
+ });
3113
+ complete = sameIdentity(destination, await lstat(storeRoot));
3114
+ } catch { /* An unreadable manifest cannot prove a completed publisher. */ }
3115
+ }
3116
+ const reason = complete ? 'store_bootstrap_raced' : 'bootstrap_destination_incomplete';
3117
+ const layout = complete ? null : await uninitializedStoreLayout(repoRoot).catch(() => null);
3118
+ const nextAction = complete
3119
+ ? `Read the published Store at ${storeRoot}; add further membership with a new plan key.`
3120
+ : layout?.uninitialized
3121
+ ? `Retry the same initial operation after the writer exits; transient residue at ${storeRoot} recovers automatically.`
3122
+ : `Finish or restore the original bootstrap at ${storeRoot}, preserving existing data, then retry.`;
3123
+ throw Object.assign(new TodoStoreError('STORE_WRITE_CONFLICT', reason, reason, {
3124
+ ref: STORE_ROOT_REF, cause: error.code, next_action: nextAction,
3125
+ }), { cause: error });
3126
+ }
3127
+ }
3128
+ }
3129
+ throw error;
3130
+ }
3131
+ renamed = true;
3132
+ await fsyncDirectory(latticeRoot);
3133
+ if (typeof options.onProtocolStage === 'function') await options.onProtocolStage('authoring_renamed');
3134
+ const activatedStore = await lstat(storeRoot);
3135
+ const activatedParent = await lstat(latticeRoot);
3136
+ if (!sameIdentity(stageIdentity, activatedStore)
3137
+ || !sameIdentity(latticeIdentity, activatedParent)
3138
+ || activatedStore.isSymbolicLink() || !activatedStore.isDirectory()
3139
+ || activatedParent.isSymbolicLink() || !activatedParent.isDirectory()) {
3140
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
3141
+ }
3142
+ const store = await readTodoStoreView({ repoRoot });
3143
+ const member = store.members[0];
3144
+ if (store.project_id !== options.projectId || store.members.length !== 1
3145
+ || store.snapshot_stale !== false || member?.journal?.events?.length !== 1
3146
+ || canonicalizeTodoArtifact(store.manifest) !== canonicalizeTodoArtifact(manifest)
3147
+ || canonicalizeTodoArtifact(member?.descriptor) !== canonicalizeTodoArtifact(descriptor)
3148
+ || canonicalizeTodoArtifact(member?.plan) !== canonicalizeTodoArtifact(plan)
3149
+ || canonicalizeTodoArtifact(member?.journal?.events?.[0]) !== canonicalizeTodoArtifact(genesis)
3150
+ || canonicalizeTodoArtifact(member?.snapshot) !== canonicalizeTodoArtifact(snapshot)) {
3151
+ fail('STORE_WRITE_CONFLICT', 'authoring_activation_verification_failed');
3152
+ }
3153
+ activated = true;
3154
+ return store;
3155
+ } finally {
3156
+ if (renamed && !activated) {
3157
+ try {
3158
+ const currentParent = await lstat(latticeRoot);
3159
+ const currentStore = await lstat(storeRoot);
3160
+ if (sameIdentity(latticeIdentity, currentParent) && sameIdentity(stageIdentity, currentStore)
3161
+ && !currentParent.isSymbolicLink() && currentParent.isDirectory()
3162
+ && !currentStore.isSymbolicLink() && currentStore.isDirectory()) {
3163
+ await rm(storeRoot, { recursive: true, force: true });
3164
+ await fsyncDirectory(latticeRoot);
3165
+ }
3166
+ } catch (error) {
3167
+ if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
3168
+ }
3169
+ }
3170
+ const published = await lstat(storeRoot).catch((error) => {
3171
+ if (error?.code !== 'ENOENT') throw error;
3172
+ return null;
3173
+ });
3174
+ if (!activated && createdLatticeRoot && published === null) {
3175
+ // 自分で作ったroot直下の同梱.gitattributesを先に消さないとrmdirがENOTEMPTYで残る。
3176
+ await rm(path.join(latticeRoot, '.gitattributes'), { force: true });
3177
+ try { await rmdir(latticeRoot); }
3178
+ catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
3056
3179
  }
3057
- } catch (error) {
3058
- if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
3059
3180
  }
3060
- }
3061
- if (!activated) await rm(stage, { recursive: true, force: true });
3062
- if (!activated && createdLatticeRoot) {
3063
- // 自分で作ったroot直下の同梱.gitattributesを先に消さないとrmdirがENOTEMPTYで残る。
3064
- await rm(path.join(latticeRoot, '.gitattributes'), { force: true });
3065
- try { await rmdir(latticeRoot); }
3066
- catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
3181
+ });
3182
+ } catch (error) {
3183
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
3184
+ throw error;
3185
+ } finally {
3186
+ if (!renamed) {
3187
+ const currentStage = await lstat(stage).catch((error) => {
3188
+ if (error?.code !== 'ENOENT') throw error;
3189
+ return null;
3190
+ });
3191
+ if (sameIdentity(stageIdentity, currentStage) && currentStage.isDirectory() && !currentStage.isSymbolicLink()) {
3192
+ await rm(stage, { recursive: true, force: true });
3193
+ }
3067
3194
  }
3068
3195
  }
3069
3196
  }
@@ -3752,6 +3879,78 @@ function parseRevisionSetMarker(bytes) {
3752
3879
  });
3753
3880
  }
3754
3881
 
3882
+ async function recoverSourceCutover(repoRoot, now) {
3883
+ const barrierBytes = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
3884
+ if (barrierBytes === null) return;
3885
+ const barrier = parseCanonicalJsonLine(barrierBytes, {
3886
+ code: 'SOURCE_CUTOVER_RECOVERY_REQUIRED', reason: 'barrier_invalid',
3887
+ maxBytes: TODO_LIMITS.snapshotBytes,
3888
+ validate: (value) => (exactRecord(value, ['schema', 'revision_digest'])
3889
+ && value.schema === 'lattice.todo_source_cutover_barrier.v1' && isTodoDigest(value.revision_digest))
3890
+ || (exactRecord(value, ['schema', 'revision_set_digest', 'revision_digests'])
3891
+ && value.schema === 'lattice.todo_source_cutover_set_barrier.v1'
3892
+ && isTodoDigest(value.revision_set_digest) && Array.isArray(value.revision_digests)
3893
+ && value.revision_digests.every(isTodoDigest)),
3894
+ });
3895
+ const isSet = barrier.schema === 'lattice.todo_source_cutover_set_barrier.v1';
3896
+ const matches = [];
3897
+ async function visit(ref, depth, parse) {
3898
+ const directory = path.resolve(repoRoot, ref);
3899
+ let entries;
3900
+ try {
3901
+ const state = await lstat(directory);
3902
+ if (!state.isDirectory() || state.isSymbolicLink()) fail('REVISION_CONFLICT', 'revision_directory_unsafe');
3903
+ entries = await readdir(directory, { withFileTypes: true });
3904
+ } catch (error) { if (error?.code === 'ENOENT') return; throw error; }
3905
+ for (const entry of entries) {
3906
+ if (!isTodoIdentifier(entry.name) || !entry.isDirectory() || entry.isSymbolicLink()) {
3907
+ fail('REVISION_CONFLICT', 'revision_directory_unsafe');
3908
+ }
3909
+ const childRef = path.posix.join(ref, entry.name);
3910
+ if (depth > 1) { await visit(childRef, depth - 1, parse); continue; }
3911
+ const markerState = await pathState(repoRoot, `${childRef}/marker.json`, 'REVISION_CONFLICT', { missing: true });
3912
+ if (markerState === null) continue;
3913
+ const bytes = await exactFileOrNull(markerState.absolute);
3914
+ if (bytes === null) continue;
3915
+ const marker = parse(bytes);
3916
+ if ((isSet ? marker.revision_set_digest : marker.revision.revision_digest)
3917
+ === (isSet ? barrier.revision_set_digest : barrier.revision_digest)) matches.push(marker);
3918
+ }
3919
+ }
3920
+ if (isSet) {
3921
+ await visit(`${STORE_ROOT_REF}/transactions/revision-sets`, 1, parseRevisionSetMarker);
3922
+ } else {
3923
+ await visit(`${STORE_ROOT_REF}/transactions/revisions`, 2, parseRevisionMarker);
3924
+ await visit(`${STORE_ROOT_REF}/transactions/phase-v3`, 2, parsePhaseRevisionMarker);
3925
+ }
3926
+ if (matches.length !== 1) fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'source_cutover_recovery_required');
3927
+ const marker = matches[0];
3928
+ const genesis = isSet ? marker.entries[0].genesis : marker.genesis;
3929
+ const options = { repoRoot, now, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
3930
+ actor: genesis.actor, recordedAt: genesis.recorded_at, provenance: genesis.provenance,
3931
+ [STORE_LOCK_HELD]: STORE_LOCK_HELD };
3932
+ if (!isSet) {
3933
+ const apply = marker.revision.schema.startsWith('lattice.phase_')
3934
+ ? applyPhaseTodoRevision : applyTodoRevision;
3935
+ await apply({ ...options, revision: marker.revision });
3936
+ return;
3937
+ }
3938
+ const revisions = marker.entries.map(({ revision }) => revision);
3939
+ if (canonicalizeTodoArtifact(barrier.revision_digests) !== canonicalizeTodoArtifact(revisions
3940
+ .filter(({ schema }) => schema === 'lattice.todo_revision.v2').map(({ revision_digest: digest }) => digest))) {
3941
+ fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'barrier_invalid');
3942
+ }
3943
+ for (const schema of ['lattice.todo_revision_set.v1', 'lattice.todo_revision_set.v2', 'lattice.todo_revision_set.v3']) {
3944
+ const revisionSet = { schema, project_id: marker.project_id, revisions, revision_set_digest: '' };
3945
+ revisionSet.revision_set_digest = todoSelfDigest(revisionSet, 'revision_set_digest');
3946
+ if (revisionSet.revision_set_digest === marker.revision_set_digest && validateTodoRevisionSet(revisionSet)) {
3947
+ await applyTodoRevisionSet({ ...options, revisionSet });
3948
+ return;
3949
+ }
3950
+ }
3951
+ fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'source_cutover_recovery_required');
3952
+ }
3953
+
3755
3954
  async function rejectCompetingRevisionTransaction(repoRoot, revision) {
3756
3955
  const root = path.join(repoRoot, STORE_ROOT_REF, 'transactions', 'revisions', revision.plan_key);
3757
3956
  let names;
@@ -4261,7 +4460,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4261
4460
  }
4262
4461
  recovering = true;
4263
4462
  }
4264
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now,
4463
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
4265
4464
  ...(recovering ? { allowSourceCutoverRevisionDigest: revision.revision_digest,
4266
4465
  sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY } : {}) });
4267
4466
  const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
@@ -4450,7 +4649,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4450
4649
  await fsyncDirectory(path.dirname(barrierAbsolute));
4451
4650
  await rm(transaction, { recursive: true, force: true });
4452
4651
  return commitReceipt;
4453
- });
4652
+ }, { lockCapability: options[STORE_LOCK_HELD] });
4454
4653
  }
4455
4654
 
4456
4655
  /** Native successor transaction for first-class Phase plans; no Markdown source inventory is involved. */
@@ -4463,7 +4662,7 @@ export async function applyPhaseTodoRevision(options = {}) {
4463
4662
  return applyPhaseTodoRevisionV3(options, revision, repoRoot);
4464
4663
  }
4465
4664
  return withLock(repoRoot, async () => {
4466
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
4665
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
4467
4666
  const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
4468
4667
  if (!previous || revision.project_id !== store.project_id) fail('STORE_INCONSISTENT', 'plan_not_active');
4469
4668
  const transaction = path.join(repoRoot, STORE_ROOT_REF, 'transactions', 'phase-revisions',
@@ -4560,7 +4759,7 @@ export async function applyPhaseTodoRevision(options = {}) {
4560
4759
  await protocolStage(options, 'phase_revision_manifest_activated');
4561
4760
  await rm(transaction, { recursive: true, force: true });
4562
4761
  return phaseRevisionResult(revision, genesis, false);
4563
- });
4762
+ }, { lockCapability: options[STORE_LOCK_HELD] });
4564
4763
  }
4565
4764
 
4566
4765
  /** G5 revision transaction: exact successor, state migration, and manifest-CAS activation. */
@@ -4587,7 +4786,7 @@ export async function applyTodoRevision(options = {}) {
4587
4786
  }
4588
4787
  recovering = true;
4589
4788
  }
4590
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now,
4789
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
4591
4790
  ...(recovering ? { allowSourceCutoverRevisionDigest: revision.revision_digest,
4592
4791
  sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY } : {}) });
4593
4792
  const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
@@ -4748,7 +4947,7 @@ export async function applyTodoRevision(options = {}) {
4748
4947
  }
4749
4948
  await rm(transaction, { recursive: true, force: true });
4750
4949
  return revisionResult(revision, genesis, { recovered: recovering });
4751
- });
4950
+ }, { lockCapability: options[STORE_LOCK_HELD] });
4752
4951
  }
4753
4952
 
4754
4953
  function revisionSetResult(projectId, revisionSetDigest, entries, { recovered }) {
@@ -4822,7 +5021,7 @@ export async function applyTodoRevisionSet(options = {}) {
4822
5021
  }
4823
5022
  recovering = true;
4824
5023
  }
4825
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now,
5024
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
4826
5025
  ...(recovering ? {
4827
5026
  allowSourceCutoverRevisionSetDigest: revisionSetDigest,
4828
5027
  sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY,
@@ -5055,7 +5254,7 @@ export async function applyTodoRevisionSet(options = {}) {
5055
5254
  }
5056
5255
  await rm(transaction, { recursive: true, force: true });
5057
5256
  return revisionSetResult(projectId, revisionSetDigest, prepared, { recovered: recovering });
5058
- });
5257
+ }, { lockCapability: options[STORE_LOCK_HELD] });
5059
5258
  }
5060
5259
 
5061
5260
  /** G5 revise primitive: topology changes only by publishing a successor version. */
@@ -5063,7 +5262,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5063
5262
  requireWriter(options.writer, 'g5-authoring');
5064
5263
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
5065
5264
  return withLock(repoRoot, async () => {
5066
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5265
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5067
5266
  const previous = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
5068
5267
  if (!previous) fail('STORE_INCONSISTENT', 'plan_not_active');
5069
5268
  if (options.plan.predecessor_plan_digest !== previous.plan.plan_digest
@@ -5156,7 +5355,7 @@ export async function writeTodoIndependenceArtifact(options = {}) {
5156
5355
  fail('INDEPENDENCE_ARTIFACT_INVALID', 'independence_artifact_invalid');
5157
5356
  }
5158
5357
  return withLock(repoRoot, async () => {
5159
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5358
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5160
5359
  if (store.project_id !== artifact.project_id) {
5161
5360
  fail('INDEPENDENCE_BINDING_MISMATCH', 'project_id_mismatch', {
5162
5361
  expected: store.project_id, actual: artifact.project_id,
@@ -5249,7 +5448,7 @@ export async function writeTodoSeamProposalArtifact(options = {}) {
5249
5448
  fail('SEAM_PROPOSAL_ARTIFACT_INVALID', 'seam_proposal_artifact_invalid');
5250
5449
  }
5251
5450
  return withLock(repoRoot, async () => {
5252
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5451
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5253
5452
  if (store.project_id !== artifact.project_id) {
5254
5453
  fail('SEAM_PROPOSAL_BINDING_MISMATCH', 'project_id_mismatch', {
5255
5454
  expected: store.project_id, actual: artifact.project_id,
@@ -5414,7 +5613,7 @@ export async function writeTodoStructureSource(options = {}) {
5414
5613
  fail('INVALID_TODO_STRUCTURE_SET', explained.reason, { path: explained.path });
5415
5614
  }
5416
5615
  return withLock(repoRoot, async () => {
5417
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5616
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5418
5617
  if (store.project_id !== structureSet.project_id) {
5419
5618
  fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch', {
5420
5619
  expected: store.project_id, actual: structureSet.project_id,
@@ -5510,7 +5709,7 @@ export async function writeTodoStructureCompileArtifact(options = {}) {
5510
5709
  fail('INVALID_TODO_STRUCTURE_COMPILE_ARTIFACT', 'compile_artifact_invalid');
5511
5710
  }
5512
5711
  return withLock(repoRoot, async () => {
5513
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5712
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5514
5713
  if (store.project_id !== artifact.project_id) {
5515
5714
  fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
5516
5715
  }
@@ -5576,7 +5775,7 @@ export async function writeTodoStructureBinding(options = {}) {
5576
5775
  fail('INVALID_TODO_STRUCTURE_BINDING', 'structure_binding_invalid');
5577
5776
  }
5578
5777
  return withLock(repoRoot, async () => {
5579
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5778
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5580
5779
  if (store.project_id !== binding.project_id) {
5581
5780
  fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
5582
5781
  }
@@ -5640,7 +5839,7 @@ export async function writeTodoStructureFinalization(options = {}) {
5640
5839
  fail('INVALID_TODO_STRUCTURE_FINALIZATION', 'finalization_not_consistent');
5641
5840
  }
5642
5841
  return withLock(repoRoot, async () => {
5643
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5842
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5644
5843
  const member = activeMember(store, artifact.plan_key);
5645
5844
  if (store.project_id !== artifact.project_id || member.plan.project_id !== artifact.project_id) {
5646
5845
  fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
@@ -5756,7 +5955,7 @@ export async function appendTodoStructureRealization(options = {}) {
5756
5955
  fail('INVALID_TODO_STRUCTURE_REALIZATION', initial.reason, { path: initial.path });
5757
5956
  }
5758
5957
  return withLock(repoRoot, async () => {
5759
- const store = await readTodoStore({ repoRoot, forWrite: true, now: options.now });
5958
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
5760
5959
  const member = activeMember(store, realization.plan_key);
5761
5960
  if (store.project_id !== realization.project_id
5762
5961
  || member.plan.plan_version !== realization.plan_version) {