@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,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
  /**
@@ -15,6 +15,11 @@ import {
15
15
 
16
16
  const execFileAsync = promisify(execFile);
17
17
  const STORE_REF = '.lattice/todo';
18
+ const STORE_PATHS = [STORE_REF,
19
+ ':(exclude,glob).lattice/todo/**/.write.lock*',
20
+ ':(exclude,glob).lattice/todo/**/.write.lock*/**',
21
+ ':(exclude,glob).lattice/todo/.cross-plan-recovery/**',
22
+ ];
18
23
  const LOCK_NAME = 'lattice-todo-store-commit.lock';
19
24
 
20
25
  export class TodoStoreGitTransactionError extends Error {
@@ -104,7 +109,7 @@ async function headTarget(repoRoot, env) {
104
109
 
105
110
  async function storeStatus(repoRoot, env) {
106
111
  const result = await git(repoRoot,
107
- ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', STORE_REF], { env });
112
+ ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', ...STORE_PATHS], { env });
108
113
  return fields(result.stdout);
109
114
  }
110
115
 
@@ -142,13 +147,13 @@ async function prepareSharedIndex({ repoRoot, commitSha, env }) {
142
147
  await lockHandle.close();
143
148
  lockHandle = null;
144
149
  const isolatedEnv = { ...env, GIT_INDEX_FILE: lockPath };
145
- await git(repoRoot, ['reset', '--quiet', commitSha, '--', STORE_REF], { env: isolatedEnv });
150
+ await git(repoRoot, ['reset', '--quiet', commitSha, '--', ...STORE_PATHS], { env: isolatedEnv });
146
151
  const indexCompared = await git(repoRoot,
147
- ['diff', '--quiet', '--cached', commitSha, '--', STORE_REF], {
152
+ ['diff', '--quiet', '--cached', commitSha, '--', ...STORE_PATHS], {
148
153
  env: isolatedEnv, allowExitCodes: [0, 1],
149
154
  });
150
155
  const worktreeCompared = await git(repoRoot,
151
- ['diff', '--quiet', commitSha, '--', STORE_REF], {
156
+ ['diff', '--quiet', commitSha, '--', ...STORE_PATHS], {
152
157
  env: isolatedEnv, allowExitCodes: [0, 1],
153
158
  });
154
159
  if (indexCompared.exitCode !== 0 || worktreeCompared.exitCode !== 0) {
@@ -221,9 +226,9 @@ async function buildDetachedCommit({ repoRoot, commonDir, headBefore, message, e
221
226
  GIT_INDEX_FILE: indexPath,
222
227
  };
223
228
  await git(repoRoot, ['read-tree', headBefore], { env: isolatedEnv });
224
- await git(repoRoot, ['add', '-A', '--', STORE_REF], { env: isolatedEnv });
229
+ await git(repoRoot, ['add', '-A', '--', ...STORE_PATHS], { env: isolatedEnv });
225
230
  const changed = fields((await git(repoRoot,
226
- ['diff', '--cached', '--name-only', '-z', '--', STORE_REF], { env: isolatedEnv })).stdout);
231
+ ['diff', '--cached', '--name-only', '-z', '--', ...STORE_PATHS], { env: isolatedEnv })).stdout);
227
232
  if (changed.length === 0) fail('STORE_COMMIT_NO_CHANGES', 'todo_store_mutation_changed_no_paths');
228
233
  if (changed.some((ref) => ref !== STORE_REF && !ref.startsWith(`${STORE_REF}/`))) {
229
234
  fail('STORE_COMMIT_SCOPE_VIOLATION', 'todo_store_commit_contains_outside_path', {
@@ -0,0 +1,47 @@
1
+ /* Pure projections shared by Store and Plan; no I/O or lifecycle mutation. */
2
+
3
+ export function isPhaseTodoPlanSchema(schema) {
4
+ return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
5
+ }
6
+
7
+ export function isDecoupledPhaseTodoPlanSchema(schema) {
8
+ return ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
9
+ }
10
+
11
+ // CLI側(migrate/plan create/最後のdone)が「終端重監査が要る」ことを通知するために
12
+ // 同じ判定を再利用する。判定基準を二重管理しないよう、ここから公開する。
13
+ export function isPhaselessTodoPlanSchema(schema) {
14
+ return !isPhaseTodoPlanSchema(schema);
15
+ }
16
+
17
+ /**
18
+ * active plan群へ接続済みのplan跨ぎ依存線を投影する。
19
+ *
20
+ * eventはconsumer(to)planのplan-scoped chainへ積まれる。自動発見も暗黙補完もせず、
21
+ * 記録された線だけを返す。順序はtask identityで固定し、status/Ganttが同じ入力を見る。
22
+ */
23
+ export function projectTodoCrossPlanDependencies(members) {
24
+ // 除去tombstoneを先に集め、指された接続を線として数えない(歴史は両eventとも残る)
25
+ const removed = new Set();
26
+ for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
27
+ if (event.kind === 'cross_plan_dependency_removed') removed.add(event.payload.target_event_digest);
28
+ }
29
+ const dependencies = [];
30
+ for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
31
+ if (event.kind !== 'cross_plan_dependency') continue;
32
+ if (removed.has(event.event_digest)) continue;
33
+ dependencies.push({
34
+ from: event.payload.from,
35
+ to: event.payload.to,
36
+ reason: event.payload.reason,
37
+ connected_by: event.actor,
38
+ connected_at: event.recorded_at,
39
+ event_digest: event.event_digest,
40
+ });
41
+ }
42
+ return dependencies.sort((left, right) => {
43
+ const key = (entry) => `${entry.from.project_id}\0${entry.from.plan_key}\0${entry.from.task_id}`
44
+ + `\0${entry.to.project_id}\0${entry.to.plan_key}\0${entry.to.task_id}\0${entry.event_digest}`;
45
+ return key(left) < key(right) ? -1 : key(left) > key(right) ? 1 : 0;
46
+ });
47
+ }