@quolu/lattice 0.79.4 → 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 (73) hide show
  1. package/bin/lattice-dashboard.mjs +6 -5
  2. package/bin/lattice-mcp.mjs +2 -1
  3. package/docs/bridge-setup.md +8 -0
  4. package/docs/schemas/lattice.plan_create_input.v4.schema.json +8 -4
  5. package/docs/schemas/lattice.todo_extraction.v3.schema.json +5 -3
  6. package/docs/schemas/lattice.todo_extraction.v4.schema.json +5 -3
  7. package/package.json +1 -1
  8. package/sensor/dist/mcp/index.d.ts +3 -1
  9. package/sensor/dist/mcp/index.d.ts.map +1 -1
  10. package/sensor/dist/mcp/index.js +7 -2
  11. package/sensor/dist/mcp/index.js.map +1 -1
  12. package/sensor/dist/mcp/proxy.d.ts +2 -0
  13. package/sensor/dist/mcp/proxy.d.ts.map +1 -1
  14. package/sensor/dist/mcp/proxy.js +9 -3
  15. package/sensor/dist/mcp/proxy.js.map +1 -1
  16. package/sensor/dist/mcp/session.d.ts +7 -0
  17. package/sensor/dist/mcp/session.d.ts.map +1 -1
  18. package/sensor/dist/mcp/session.js +4 -1
  19. package/sensor/dist/mcp/session.js.map +1 -1
  20. package/sensor/dist/mcp/transport.d.ts +5 -5
  21. package/sensor/dist/mcp/transport.d.ts.map +1 -1
  22. package/sensor/dist/mcp/transport.js +14 -6
  23. package/sensor/dist/mcp/transport.js.map +1 -1
  24. package/src/dashboard-lifecycle-journal.mjs +3 -1
  25. package/src/fs-publish.mjs +9 -0
  26. package/src/mcp-startup-receipt.mjs +99 -0
  27. package/src/project-cli.mjs +2 -2
  28. package/src/runtime-os-observation.mjs +18 -1
  29. package/src/setup-config.mjs +7 -3
  30. package/src/store-lock.mjs +250 -0
  31. package/src/todo-cli.mjs +6 -0
  32. package/src/todo-contracts.mjs +95 -50
  33. package/src/todo-migration.mjs +35 -10
  34. package/src/todo-note-store.mjs +45 -12
  35. package/src/todo-readiness.mjs +154 -0
  36. package/src/todo-status.mjs +4 -33
  37. package/src/todo-store-cache.mjs +50 -6
  38. package/src/todo-store-git-transaction.mjs +11 -6
  39. package/src/todo-store-view.mjs +47 -0
  40. package/src/todo-store.mjs +597 -398
  41. package/src/artifact-contracts-v2.mjs +0 -325
  42. package/src/boundary-compiler.mjs +0 -712
  43. package/src/bounded-seam.mjs +0 -230
  44. package/src/control-compiler.mjs +0 -532
  45. package/src/rc1-black-box-oracle.mjs +0 -906
  46. package/src/rc1-comparison.mjs +0 -154
  47. package/src/rc1-evidence-bundle.mjs +0 -456
  48. package/src/rc1-v4-campaign.mjs +0 -708
  49. package/src/rc1-v4-transform.mjs +0 -467
  50. package/src/rc1-v5-artifact-set.mjs +0 -855
  51. package/src/rc1-v5-behavior-evidence.mjs +0 -594
  52. package/src/rc1-v5-campaign.mjs +0 -797
  53. package/src/rc1-v5-transform.mjs +0 -421
  54. package/src/rc1-v6-artifact-set.mjs +0 -807
  55. package/src/rc1-v6-behavior-evidence.mjs +0 -273
  56. package/src/rc1-v6-campaign.mjs +0 -623
  57. package/src/rc1-v6-causal-binding.mjs +0 -473
  58. package/src/rc1-v6-measurement.mjs +0 -313
  59. package/src/rc2-artifact-set.mjs +0 -1584
  60. package/src/rc2-campaign.mjs +0 -1495
  61. package/src/rc2-delivery-policy-front-end.mjs +0 -1079
  62. package/src/rc2-delivery-policy-oracle.mjs +0 -134
  63. package/src/rc2-delivery-policy-transform.mjs +0 -1127
  64. package/src/rc2-rc1-transfer-front-end.mjs +0 -511
  65. package/src/rc3-actual-dogfood.mjs +0 -652
  66. package/src/rc3-dogfood-scaffold.mjs +0 -315
  67. package/src/rc3-scripted-campaign.mjs +0 -1383
  68. package/src/rc4-stage1-dogfood.mjs +0 -673
  69. package/src/runtime-scripted-executor.mjs +0 -163
  70. package/src/runtime-worktree-executor.mjs +0 -199
  71. package/src/seam-transform.mjs +0 -554
  72. package/src/treatment-compiler.mjs +0 -728
  73. package/src/treatment-runner.mjs +0 -656
@@ -425,7 +425,20 @@ function validParentGraph(tasks) {
425
425
  return true;
426
426
  }
427
427
 
428
- export function validateTodoPlan(value) {
428
+ export function explainTodoOrder(values, key, pointer) {
429
+ for (let index = 1; index < values.length; index += 1) {
430
+ const previous = key(values[index - 1]);
431
+ const actual = key(values[index]);
432
+ if (compareText(previous, actual) >= 0) {
433
+ return { reason: 'unsorted_or_duplicate_collection', path: `${pointer}/${index}`,
434
+ expected: { order: 'ascending_unique', greater_than: previous }, actual };
435
+ }
436
+ }
437
+ return null;
438
+ }
439
+
440
+ export function explainTodoPlan(value) {
441
+ const reject = (reason, pointer) => ({ reason, path: pointer });
429
442
  try {
430
443
  const taskValidator = value?.schema === 'lattice.todo_plan.v1' ? taskV1
431
444
  : value?.schema === 'lattice.todo_plan.v2' ? taskV2
@@ -437,60 +450,92 @@ export function validateTodoPlan(value) {
437
450
  'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
438
451
  'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
439
452
  ];
440
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
441
- .includes(value?.schema)) planKeys.push('phases');
442
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema)) {
443
- planKeys.push('phase_accept_dependencies');
453
+ const phased = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
454
+ .includes(value?.schema);
455
+ const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema);
456
+ if (phased) planKeys.push('phases');
457
+ if (decoupled) planKeys.push('phase_accept_dependencies');
458
+ if (!exactRecord(value, planKeys)) return reject('unexpected_or_missing_keys', '/');
459
+ if (taskValidator === null) return reject('schema_mismatch', '/schema');
460
+ for (const field of ['project_id', 'plan_key', 'plan_version']) {
461
+ if (!isTodoIdentifier(value[field])) return reject('identifier_invalid', `/${field}`);
462
+ }
463
+ if (!nullableDigest(value.predecessor_plan_digest)) return reject('digest_invalid', '/predecessor_plan_digest');
464
+ if (!Array.isArray(value.tasks) || value.tasks.length === 0
465
+ || value.tasks.length > TODO_LIMITS.tasksPerPlan) return reject('bounded_collection_violation', '/tasks');
466
+ const invalidTask = value.tasks.findIndex((task) => !taskValidator(task));
467
+ if (invalidTask >= 0) return reject('task_shape_invalid', `/tasks/${invalidTask}`);
468
+ if (new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length) {
469
+ return reject('duplicate_task_id', '/tasks');
470
+ }
471
+ if (!Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan) {
472
+ return reject('bounded_collection_violation', '/hard_dependencies');
473
+ }
474
+ const invalidEdge = value.hard_dependencies.findIndex((edge) => !exactRecord(edge, ['from', 'to'])
475
+ || !nodeRef(edge.from) || !nodeRef(edge.to));
476
+ if (invalidEdge >= 0) return reject('edge_shape_invalid', `/hard_dependencies/${invalidEdge}`);
477
+ if (!Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan) {
478
+ return reject('bounded_collection_violation', '/joins');
479
+ }
480
+ const invalidJoin = value.joins.findIndex((join) => !exactRecord(join, ['id', 'after', 'before'])
481
+ || !isTodoIdentifier(join.id) || !Array.isArray(join.after) || join.after.length === 0
482
+ || join.after.length > TODO_LIMITS.tasksPerPlan || !join.after.every(nodeRef) || !nodeRef(join.before));
483
+ if (invalidJoin >= 0) return reject('join_shape_invalid', `/joins/${invalidJoin}`);
484
+ for (const field of ['topology_digest', 'plan_digest']) {
485
+ if (!isTodoDigest(value[field])) return reject('digest_invalid', `/${field}`);
486
+ }
487
+ if (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
488
+ 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
489
+ && !validParentGraph(value.tasks)) return reject('parent_graph_invalid', '/tasks');
490
+ if (phased) {
491
+ if (!Array.isArray(value.phases) || value.phases.length === 0
492
+ || value.phases.length > TODO_LIMITS.tasksPerPlan) return reject('bounded_collection_violation', '/phases');
493
+ const invalidPhase = value.phases.findIndex((phase) => !phaseV1(phase));
494
+ if (invalidPhase >= 0) return reject('phase_shape_invalid', `/phases/${invalidPhase}`);
495
+ const order = explainTodoOrder(value.phases, (phase) => phase.phase_id, '/phases');
496
+ if (order !== null) return order;
497
+ const orphanTask = value.tasks.findIndex(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id));
498
+ if (orphanTask >= 0) return reject('unknown_phase_reference', `/tasks/${orphanTask}/phase_id`);
499
+ if (!validPhaseGraph(value.phases)) return reject('phase_graph_invalid', '/phases');
500
+ }
501
+ if (decoupled) {
502
+ if (!Array.isArray(value.phase_accept_dependencies)
503
+ || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan) {
504
+ return reject('bounded_collection_violation', '/phase_accept_dependencies');
505
+ }
506
+ const invalid = value.phase_accept_dependencies.findIndex((edge) => !exactRecord(edge, ['from', 'to'])
507
+ || !phaseRef(edge.from) || !nodeRef(edge.to));
508
+ if (invalid >= 0) return reject('edge_shape_invalid', `/phase_accept_dependencies/${invalid}`);
509
+ const order = explainTodoOrder(value.phase_accept_dependencies,
510
+ (edge) => `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`, '/phase_accept_dependencies');
511
+ if (order !== null) return order;
512
+ }
513
+ for (const [values, key, pointer] of [
514
+ [value.tasks, (task) => task.task_id, '/tasks'],
515
+ [value.hard_dependencies, (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`, '/hard_dependencies'],
516
+ [value.joins, (join) => join.id, '/joins'],
517
+ ]) {
518
+ const order = explainTodoOrder(values, key, pointer);
519
+ if (order !== null) return order;
520
+ }
521
+ for (const [index, join] of value.joins.entries()) {
522
+ const order = explainTodoOrder(join.after, refKey, `/joins/${index}/after`);
523
+ if (order !== null) return order;
444
524
  }
445
- if (!exactRecord(value, planKeys) || taskValidator === null || !isTodoIdentifier(value.project_id)
446
- || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
447
- || !nullableDigest(value.predecessor_plan_digest) || !Array.isArray(value.tasks)
448
- || value.tasks.length === 0 || value.tasks.length > TODO_LIMITS.tasksPerPlan
449
- || !value.tasks.every(taskValidator) || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
450
- || !Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan
451
- || !value.hard_dependencies.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
452
- || !Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan
453
- || !value.joins.every((join) => exactRecord(join, ['id', 'after', 'before']) && isTodoIdentifier(join.id)
454
- && Array.isArray(join.after) && join.after.length > 0 && join.after.length <= TODO_LIMITS.tasksPerPlan
455
- && join.after.every(nodeRef) && nodeRef(join.before))
456
- || !isTodoDigest(value.topology_digest) || !isTodoDigest(value.plan_digest)
457
- || (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
458
- 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
459
- && !validParentGraph(value.tasks))) return false;
460
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
461
- && (!Array.isArray(value.phases) || value.phases.length === 0
462
- || value.phases.length > TODO_LIMITS.tasksPerPlan || !value.phases.every(phaseV1)
463
- || value.phases.some((entry, index) => index > 0
464
- && compareText(value.phases[index - 1].phase_id, entry.phase_id) >= 0)
465
- || new Set(value.phases.map(({ phase_id }) => phase_id)).size !== value.phases.length
466
- || value.tasks.some(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id))
467
- || !validPhaseGraph(value.phases))) return false;
468
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
469
- && (!Array.isArray(value.phase_accept_dependencies)
470
- || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan
471
- || !value.phase_accept_dependencies.every((edge) => exactRecord(edge, ['from', 'to'])
472
- && phaseRef(edge.from) && nodeRef(edge.to))
473
- || value.phase_accept_dependencies.some((edge, index) => index > 0
474
- && compareText(`${phaseRefKey(value.phase_accept_dependencies[index - 1].from)}\0${refKey(value.phase_accept_dependencies[index - 1].to)}`,
475
- `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`) >= 0))) return false;
476
- if (value.tasks.some((entry, index) => index > 0 && compareText(value.tasks[index - 1].task_id, entry.task_id) >= 0)
477
- || value.hard_dependencies.some((edge, index) => index > 0
478
- && compareText(`${refKey(value.hard_dependencies[index - 1].from)}\0${refKey(value.hard_dependencies[index - 1].to)}`,
479
- `${refKey(edge.from)}\0${refKey(edge.to)}`) >= 0)
480
- || value.joins.some((join, index) => index > 0 && compareText(value.joins[index - 1].id, join.id) >= 0)
481
- || value.joins.some((join) => join.after.some((entry, index) => index > 0
482
- && compareText(refKey(join.after[index - 1]), refKey(entry)) >= 0))) return false;
483
525
  const topology = {
484
526
  project_id: value.project_id, plan_key: value.plan_key, plan_version: value.plan_version,
485
527
  tasks: value.tasks, hard_dependencies: value.hard_dependencies, joins: value.joins,
486
- ...(['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
487
- ? { phases: value.phases } : {}),
488
- ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
489
- ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
528
+ ...(phased ? { phases: value.phases } : {}),
529
+ ...(decoupled ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
490
530
  };
491
- return value.topology_digest === digestTodoArtifact(topology)
492
- && value.plan_digest === todoSelfDigest(value, 'plan_digest');
493
- } catch { return false; }
531
+ if (value.topology_digest !== digestTodoArtifact(topology)) return reject('topology_digest_mismatch', '/topology_digest');
532
+ if (value.plan_digest !== todoSelfDigest(value, 'plan_digest')) return reject('plan_digest_mismatch', '/plan_digest');
533
+ return null;
534
+ } catch { return reject('diagnosis_failed', '/'); }
535
+ }
536
+
537
+ export function validateTodoPlan(value) {
538
+ return explainTodoPlan(value) === null;
494
539
  }
495
540
 
496
541
  export function validateEvidenceDescriptor(value) { return evidence(value); }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  TODO_LIMITS,
3
3
  exactRecord,
4
+ explainTodoOrder,
4
5
  isStrictTodoTimestamp,
5
6
  isTodoDigest,
6
7
  isTodoDesignMemo,
@@ -56,7 +57,7 @@ function refKey(value) {
56
57
  }
57
58
 
58
59
  function sortedStrictly(values, key = (value) => value) {
59
- return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
60
+ return explainTodoOrder(values, key, '') === null;
60
61
  }
61
62
 
62
63
  function sourceLocation(value) {
@@ -191,12 +192,9 @@ function explainKeys(value, requiredKeys, at) {
191
192
  }
192
193
 
193
194
  function explainSortedStrictly(values, key, at) {
194
- for (let index = 1; index < values.length; index += 1) {
195
- if (!(key(values[index - 1]) < key(values[index]))) {
196
- return reject('unsorted_or_duplicate_collection', `${at}/${index}`);
197
- }
198
- }
199
- return { valid: true };
195
+ const violation = explainTodoOrder(values, key, at);
196
+ return violation === null ? { valid: true }
197
+ : { valid: false, ...violation };
200
198
  }
201
199
 
202
200
  /**
@@ -275,8 +273,27 @@ export function explainTodoExtraction(value) {
275
273
  if (new Set(value.tasks.map(({ task_id: taskId }) => taskId)).size !== value.tasks.length) {
276
274
  return reject('duplicate_task_id', '/tasks');
277
275
  }
278
- if (!validateEdges(value.hard_dependencies, schema)) return reject('hard_dependencies_invalid', '/hard_dependencies');
279
- if (!validateJoins(value.joins)) return reject('joins_invalid', '/joins');
276
+ if (!validateEdges(value.hard_dependencies, schema)) {
277
+ if (Array.isArray(value.hard_dependencies)
278
+ && value.hard_dependencies.every((edge) => nodeRef(edge?.from) && nodeRef(edge?.to))) {
279
+ const order = explainSortedStrictly(value.hard_dependencies,
280
+ (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`, '/hard_dependencies');
281
+ if (!order.valid) return order;
282
+ }
283
+ return reject('hard_dependencies_invalid', '/hard_dependencies');
284
+ }
285
+ if (!validateJoins(value.joins)) {
286
+ if (Array.isArray(value.joins) && value.joins.every((join) => isTodoIdentifier(join?.id)
287
+ && Array.isArray(join.after) && join.after.every(nodeRef))) {
288
+ const order = explainSortedStrictly(value.joins, (join) => join.id, '/joins');
289
+ if (!order.valid) return order;
290
+ for (const [index, join] of value.joins.entries()) {
291
+ const afterOrder = explainSortedStrictly(join.after, refKey, `/joins/${index}/after`);
292
+ if (!afterOrder.valid) return afterOrder;
293
+ }
294
+ }
295
+ return reject('joins_invalid', '/joins');
296
+ }
280
297
  if (!isTodoDigest(value.extraction_digest)) return reject('invalid_digest', '/extraction_digest');
281
298
  const expectedDigest = todoSelfDigest(value, 'extraction_digest');
282
299
  if (value.extraction_digest !== expectedDigest) {
@@ -520,5 +537,13 @@ export function compileTodoExtraction(value, repoRoot) {
520
537
 
521
538
  export async function appendTodoExtraction({ repoRoot, extraction }) {
522
539
  const request = compileTodoExtraction(extraction, repoRoot);
523
- return appendImportedPlan(request);
540
+ try { return await appendImportedPlan(request); }
541
+ catch (error) {
542
+ if (!(error instanceof TypeError) || error.detail?.pointer === undefined) throw error;
543
+ const index = /^\/tasks\/(\d+)(?:\/|$)/u.exec(error.detail.pointer)?.[1];
544
+ throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined, {
545
+ ...error.detail, pointer_space: 'todo_plan',
546
+ ...(index === undefined ? {} : { task_id: request.plan.tasks[Number(index)].task_id }),
547
+ });
548
+ }
524
549
  }
@@ -1,9 +1,11 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { fsyncDirectory } from './fs-dir-sync.mjs';
3
3
  import {
4
- mkdir, open, readFile, readdir, rename, rm, stat,
4
+ lstat, mkdir, open, readFile, readdir, rename, rm, stat,
5
5
  } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
+ import { StoreLockError, withStoreLock } from './store-lock.mjs';
8
+ import { syncPublishedFile } from './fs-publish.mjs';
7
9
 
8
10
  import {
9
11
  TODO_LIMITS,
@@ -151,6 +153,7 @@ export async function readTodoNoteEvents(options = {}) {
151
153
  const names = await sealedFiles(sealed);
152
154
  const events = [];
153
155
  let previousSegmentDigest = ZERO_DIGEST;
156
+ let lastSealedBytes = null;
154
157
  for (const name of names) {
155
158
  const match = name.match(SEALED_NAME);
156
159
  const bytes = await readOptionalBounded(path.join(sealed, name));
@@ -163,9 +166,11 @@ export async function readTodoNoteEvents(options = {}) {
163
166
  }
164
167
  events.push(...segmentEvents);
165
168
  previousSegmentDigest = segmentDigest;
169
+ lastSealedBytes = bytes;
166
170
  }
167
171
  const activeBytes = await readOptionalBounded(active, { missing: true });
168
- if (activeBytes !== null) events.push(...parseCanonicalSegment(activeBytes, active));
172
+ const duplicateActive = activeBytes !== null && lastSealedBytes?.equals(activeBytes) === true;
173
+ if (activeBytes !== null && !duplicateActive) events.push(...parseCanonicalSegment(activeBytes, active));
169
174
  // chainの分離は「そのfileへ何が積まれるか」で守る。混ざったchainは分離の意味を失うので
170
175
  // 黙って受けず、読んだ時点でtypedに落とす。
171
176
  if (events.some((event) => event.schema !== schema)) {
@@ -177,20 +182,19 @@ export async function readTodoNoteEvents(options = {}) {
177
182
  return {
178
183
  events,
179
184
  head_digest: events.at(-1)?.event_digest ?? null,
180
- active_bytes: activeBytes ?? Buffer.alloc(0),
185
+ active_bytes: duplicateActive ? Buffer.alloc(0) : activeBytes ?? Buffer.alloc(0),
181
186
  previous_segment_digest: previousSegmentDigest,
182
187
  };
183
188
  }
184
189
 
185
190
  async function atomicWrite(ref, bytes) {
186
- await mkdir(path.dirname(ref), { recursive: true });
187
191
  const temporary = path.join(path.dirname(ref),
188
192
  `.${path.basename(ref)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
189
193
  let handle;
190
194
  try {
191
195
  handle = await open(temporary, 'wx', 0o600);
192
196
  await handle.writeFile(bytes);
193
- await handle.sync();
197
+ await syncPublishedFile(handle, ref);
194
198
  await handle.close();
195
199
  handle = null;
196
200
  await rename(temporary, ref);
@@ -201,18 +205,45 @@ async function atomicWrite(ref, bytes) {
201
205
  }
202
206
  }
203
207
 
208
+ async function ensureNoteDirectory(root) {
209
+ try { await mkdir(root); }
210
+ catch (error) {
211
+ if (error?.code === 'ENOENT') fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
212
+ next_action: 'Retry after initialization or recovery finishes publishing the Todo Store.',
213
+ });
214
+ if (error?.code !== 'EEXIST') throw error;
215
+ }
216
+ const state = await lstat(root);
217
+ if (state.isSymbolicLink() || !state.isDirectory()) fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
218
+ next_action: `Restore a real note directory at ${root}, then retry.`,
219
+ });
220
+ }
221
+
204
222
  async function withNoteLock(repoRoot, callback) {
205
223
  const root = path.resolve(repoRoot, NOTE_ROOT_REF);
206
- await mkdir(root, { recursive: true });
207
- const lockRef = path.join(root, '.write.lock');
208
- let handle;
209
- try { handle = await open(lockRef, 'wx', 0o600); }
224
+ try {
225
+ for (const ref of ['.lattice', '.lattice/todo', '.lattice/todo/manifest.json']) {
226
+ const state = await lstat(path.resolve(repoRoot, ref)).catch((error) => {
227
+ if (error?.code !== 'ENOENT') throw error;
228
+ return null;
229
+ });
230
+ if (state === null || state.isSymbolicLink()
231
+ || (ref.endsWith('.json') ? !state.isFile() : !state.isDirectory())) {
232
+ fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
233
+ next_action: 'Initialize a published Todo Store before writing notes, then retry.',
234
+ });
235
+ }
236
+ }
237
+ await ensureNoteDirectory(root);
238
+ return await withStoreLock({ lockPath: path.join(root, '.write.lock'), createParent: false }, callback);
239
+ }
210
240
  catch (error) {
211
- if (error?.code === 'EEXIST') fail('NOTE_WRITE_CONFLICT', 'note_store_locked');
241
+ if (error instanceof StoreLockError) {
242
+ fail('NOTE_WRITE_CONFLICT', error.reason === 'store_locked' ? 'note_store_locked' : error.reason,
243
+ error.detail);
244
+ }
212
245
  throw error;
213
246
  }
214
- try { return await callback(); }
215
- finally { await handle.close(); await rm(lockRef, { force: true }); }
216
247
  }
217
248
 
218
249
  /** lifecycle artifactsへ触れず、独立note chainだけへ1 eventを追記する。 */
@@ -266,6 +297,7 @@ export async function appendTodoNote(options = {}) {
266
297
  if (!validateTodoNoteEvent(event)) throw new TypeError('todo note event input invalid');
267
298
 
268
299
  const paths = chainRefs(repoRoot, options.planKey, scope);
300
+ await ensureNoteDirectory(path.dirname(paths.active));
269
301
  const eventBytes = canonicalLine(event);
270
302
  if (chain.active_bytes.length > 0
271
303
  && chain.active_bytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
@@ -274,6 +306,7 @@ export async function appendTodoNote(options = {}) {
274
306
  const name = `${String(activeEvents[0].sequence).padStart(12, '0')}`
275
307
  + `-${String(activeEvents.at(-1).sequence).padStart(12, '0')}`
276
308
  + `-${chain.previous_segment_digest}-${segmentDigest}.jsonl`;
309
+ await ensureNoteDirectory(paths.sealed);
277
310
  await atomicWrite(path.join(paths.sealed, name), chain.active_bytes);
278
311
  await atomicWrite(paths.active, eventBytes);
279
312
  } else {
@@ -0,0 +1,154 @@
1
+ import {
2
+ isDecoupledPhaseTodoPlanSchema,
3
+ isPhaseTodoPlanSchema,
4
+ projectTodoCrossPlanDependencies,
5
+ } from './todo-store-view.mjs';
6
+
7
+ function taskKey(ref) {
8
+ return `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`;
9
+ }
10
+
11
+ function phaseKey(ref) {
12
+ return `${ref.project_id}\0${ref.plan_key}\0${ref.phase_id}`;
13
+ }
14
+
15
+ /** Build once per read view; never read derived snapshot caches or mutate the input. */
16
+ export function createTodoReadiness(store) {
17
+ const nodes = new Map();
18
+ const phases = new Map();
19
+ const incoming = new Map();
20
+ const outgoing = new Map();
21
+ const acceptanceIncoming = new Map();
22
+ const acceptanceOutgoing = new Map();
23
+ for (const member of store.members) {
24
+ const { plan } = member;
25
+ const states = new Map(member.tasks.map((state) => [state.task_id, state.status]));
26
+ const phaseStates = new Map((member.phases ?? []).map((phase) => [phase.phase_id, phase.status]));
27
+ for (const phase of member.phases ?? []) phases.set(phaseKey({ ...plan, ...phase }), phase.status);
28
+ for (const task of plan.tasks) {
29
+ const key = taskKey({ ...plan, ...task });
30
+ nodes.set(key, {
31
+ status: states.get(task.task_id),
32
+ schema: plan.schema,
33
+ plan_key: plan.plan_key,
34
+ phase_id: isPhaseTodoPlanSchema(plan.schema) ? task.phase_id : null,
35
+ phase_status: phaseStates.get(task.phase_id),
36
+ });
37
+ incoming.set(key, new Set());
38
+ outgoing.set(key, new Set());
39
+ acceptanceIncoming.set(key, new Set());
40
+ }
41
+ }
42
+ const connect = (from, to) => {
43
+ const source = taskKey(from);
44
+ const target = taskKey(to);
45
+ incoming.get(target)?.add(source);
46
+ outgoing.get(source)?.add(target);
47
+ };
48
+ for (const member of store.members) {
49
+ for (const edge of member.plan.hard_dependencies) connect(edge.from, edge.to);
50
+ for (const join of member.plan.joins) {
51
+ for (const after of join.after) connect(after, join.before);
52
+ }
53
+ if (isDecoupledPhaseTodoPlanSchema(member.plan.schema)) {
54
+ for (const edge of member.plan.phase_accept_dependencies) {
55
+ const source = phaseKey(edge.from);
56
+ const target = taskKey(edge.to);
57
+ acceptanceIncoming.get(target)?.add(source);
58
+ if (!acceptanceOutgoing.has(source)) acceptanceOutgoing.set(source, new Set());
59
+ acceptanceOutgoing.get(source).add(target);
60
+ }
61
+ }
62
+ }
63
+ for (const edge of projectTodoCrossPlanDependencies(store.members)) connect(edge.from, edge.to);
64
+
65
+ function dependencyPhaseReady(predecessor, target) {
66
+ if (predecessor === undefined) return false;
67
+ if (!isPhaseTodoPlanSchema(predecessor.schema)) return true;
68
+ if (isDecoupledPhaseTodoPlanSchema(predecessor.schema)) return true;
69
+ if (target !== undefined && predecessor.plan_key === target.plan_key
70
+ && predecessor.phase_id === target.phase_id) return true;
71
+ return predecessor.phase_status === 'accepted';
72
+ }
73
+
74
+ function prerequisites(key) {
75
+ const predecessors = [...(incoming.get(key) ?? [])].map((source) => nodes.get(source));
76
+ const predecessorsDone = predecessors.every((node) => node?.status === 'done');
77
+ const predecessorPhasesReady = predecessors.every((node) => dependencyPhaseReady(node, nodes.get(key)));
78
+ const taskDependenciesDone = predecessorsDone && predecessorPhasesReady;
79
+ const phaseAcceptReady = [...(acceptanceIncoming.get(key) ?? [])]
80
+ .every((source) => phases.get(source) === 'accepted');
81
+ return {
82
+ taskDependenciesDone,
83
+ phaseAcceptReady,
84
+ dependenciesDone: taskDependenciesDone && phaseAcceptReady,
85
+ cause: !phaseAcceptReady ? 'acceptance_edge'
86
+ : !predecessorsDone ? 'predecessor_unfinished'
87
+ : !predecessorPhasesReady ? 'acceptance_edge' : null,
88
+ };
89
+ }
90
+
91
+ function ownPhaseReady(key) {
92
+ const node = nodes.get(key);
93
+ return node?.schema !== 'lattice.todo_plan.v4' || node.phase_status === 'active';
94
+ }
95
+
96
+ function startedSuccessor(key) {
97
+ return [...(outgoing.get(key) ?? [])].some((successor) => nodes.get(successor)?.status !== 'pending');
98
+ }
99
+
100
+ return {
101
+ key: taskKey,
102
+ status: (key) => nodes.get(key)?.status,
103
+ prerequisites,
104
+ ownPhaseReady,
105
+ isReady: (key) => nodes.get(key)?.status === 'pending'
106
+ && ownPhaseReady(key) && prerequisites(key).dependenciesDone,
107
+ startedSuccessor,
108
+ phaseHasStartedSuccessor: (member, phaseId) => member.plan.schema === 'lattice.todo_plan.v4'
109
+ ? member.plan.tasks.filter(({ phase_id }) => phase_id === phaseId)
110
+ .some((task) => startedSuccessor(taskKey({ ...member.plan, ...task })))
111
+ : [...(acceptanceOutgoing.get(phaseKey({ ...member.plan, phase_id: phaseId })) ?? [])]
112
+ .some((key) => nodes.get(key)?.status !== 'pending'),
113
+ };
114
+ }
115
+
116
+ function refused(reason, cause, detail = {}) {
117
+ return { ok: false, code: 'STORE_INCONSISTENT', detail: { reason, cause, ...detail } };
118
+ }
119
+
120
+ /** Prospective policy only; Store retains historical replay, evidence and identity validation. */
121
+ export function validateProspectiveEvent({ store, member, event }) {
122
+ const readiness = createTodoReadiness(store);
123
+ const key = readiness.key({ ...member.plan, task_id: event.task_id });
124
+ const prerequisites = readiness.prerequisites(key);
125
+ const authoredStart = event.kind === 'start' && event.payload.start_mode !== 'historical_import'
126
+ && event.payload.start_mode !== 'rebind';
127
+ if (authoredStart && (!prerequisites.phaseAcceptReady
128
+ || (!prerequisites.taskDependenciesDone && event.payload.override_reason === null))) {
129
+ return refused('invalid_start_transition', prerequisites.cause);
130
+ }
131
+ if (event.kind === 'done' && event.payload.done_mode === 'authored' && !prerequisites.dependenciesDone) {
132
+ return refused('invalid_done_transition', prerequisites.cause);
133
+ }
134
+ if (event.kind === 'reopen' && event.payload.override_reason === null && readiness.startedSuccessor(key)) {
135
+ return refused('reopen_has_started_successor', 'task_state', {
136
+ next_action: `lattice todo split --plan ${member.plan.plan_key} --input <file>`,
137
+ });
138
+ }
139
+ if (event.kind === 'phase_reopen' && event.payload.override_reason === null
140
+ && readiness.phaseHasStartedSuccessor(member, event.phase_id)) {
141
+ return refused('phase_reopen_has_started_successor', 'task_state');
142
+ }
143
+ // Keep merged refusal priority; replay still owns missing target/binding checks.
144
+ const status = readiness.status(key);
145
+ if (authoredStart && status !== undefined) {
146
+ if (status !== 'pending') return refused('invalid_start_transition', 'task_state');
147
+ if (!readiness.ownPhaseReady(key)) return refused('invalid_start_transition', 'phase_state');
148
+ }
149
+ if (event.kind === 'done' && event.payload.done_mode === 'authored'
150
+ && status !== undefined && status !== 'in-progress') {
151
+ return refused('invalid_done_transition', 'task_state');
152
+ }
153
+ return { ok: true };
154
+ }
@@ -1,3 +1,4 @@
1
+ import { createTodoReadiness } from './todo-readiness.mjs';
1
2
  import {
2
3
  AUDIT_PENDING_PHASE_STATUSES,
3
4
  auditPendingNextCommands,
@@ -381,13 +382,6 @@ function buildTodoGraph(readModel) {
381
382
  const memberHeads = [];
382
383
  const auditPending = [];
383
384
  const coordination = [];
384
- // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
385
- // (readTodoStoreが常にmember.phasesとして埋める。ADR 0147)。
386
- const phaseStatuses = new Map(readModel.members.flatMap((member) => (
387
- (member.phases ?? []).map((phase) => [
388
- `${member.plan.project_id}\0${member.plan.plan_key}\0${phase.phase_id}`, phase.status,
389
- ])
390
- )));
391
385
  const members = [...readModel.members].sort((left, right) => {
392
386
  const leftKey = left?.descriptor?.plan_key ?? '';
393
387
  const rightKey = right?.descriptor?.plan_key ?? '';
@@ -425,8 +419,6 @@ function buildTodoGraph(readModel) {
425
419
  }),
426
420
  });
427
421
  const states = new Map(member.tasks.map((state) => [state.task_id, state]));
428
- // snapshot artifactの形式には縛られない導出ビュー(member.phases)を読む(ADR 0147)。
429
- const phases = new Map((member.phases ?? []).map((state) => [state.phase_id, state]));
430
422
  collectAuditPending(member, auditPending);
431
423
  // 調整方式の宣言(ob03)。member.coordinationはstoreがplan-scoped chainから投影した
432
424
  // 導出ビューで、未宣言はnull。宣言済みだけをここへ載せる。
@@ -457,13 +449,6 @@ function buildTodoGraph(readModel) {
457
449
  label: displayText(task.title, task.task_id, TODO_STATUS_LABEL_LIMIT),
458
450
  status: state.status,
459
451
  blocked_reason: state.blocked_reason,
460
- plan_schema: member.plan.schema,
461
- phase_id: ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(member.plan.schema)
462
- ? task.phase_id : null,
463
- phase_status: ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(member.plan.schema)
464
- ? phases.get(task.phase_id)?.status : null,
465
- phase_ready: member.plan.schema !== 'lattice.todo_plan.v4'
466
- || phases.get(task.phase_id)?.status === 'active',
467
452
  });
468
453
  incoming.set(key, new Set());
469
454
  }
@@ -477,7 +462,6 @@ function buildTodoGraph(readModel) {
477
462
  }
478
463
  incoming.get(toKey).add(fromKey);
479
464
  };
480
- const phaseAcceptIncoming = new Map([...nodes.keys()].map((key) => [key, new Set()]));
481
465
  for (const member of members) {
482
466
  for (const edge of member.plan.hard_dependencies) addPredecessor(edge.from, edge.to);
483
467
  for (const join of member.plan.joins) {
@@ -487,9 +471,6 @@ function buildTodoGraph(readModel) {
487
471
  for (const edge of member.plan.phase_accept_dependencies) {
488
472
  const target = refKey(edge.to);
489
473
  if (!nodes.has(target)) fail('TODO_STATUS_INVALID_INPUT', 'todo_status_dependency_dangling');
490
- phaseAcceptIncoming.get(target).add(
491
- `${edge.from.project_id}\0${edge.from.plan_key}\0${edge.from.phase_id}`,
492
- );
493
474
  }
494
475
  }
495
476
  }
@@ -506,22 +487,12 @@ function buildTodoGraph(readModel) {
506
487
  coordination.sort((left, right) => (
507
488
  left.plan_key < right.plan_key ? -1 : left.plan_key > right.plan_key ? 1 : 0));
508
489
 
509
- return { nodes, incoming, phaseAcceptIncoming, phaseStatuses, memberHeads, auditPending, coordination };
490
+ return { nodes, incoming, memberHeads, auditPending, coordination, readiness: createTodoReadiness(readModel) };
510
491
  }
511
492
 
512
493
  /** 先行完了とphase gateを満たしたpending taskだけがreadyになる。 */
513
- function isNodeReady(node, { nodes, incoming, phaseAcceptIncoming, phaseStatuses }) {
514
- return node.status === 'pending' && node.phase_ready
515
- && [...incoming.get(node.key)].every((key) => {
516
- const predecessor = nodes.get(key);
517
- return predecessor.status === 'done'
518
- && (predecessor.plan_schema !== 'lattice.todo_plan.v4'
519
- || predecessor.phase_id === null
520
- || (predecessor.plan_key === node.plan_key && predecessor.phase_id === node.phase_id)
521
- || predecessor.phase_status === 'accepted');
522
- })
523
- && [...phaseAcceptIncoming.get(node.key)]
524
- .every((key) => phaseStatuses.get(key) === 'accepted');
494
+ function isNodeReady(node, { readiness }) {
495
+ return readiness.isReady(node.key);
525
496
  }
526
497
 
527
498
  /**