@quolu/lattice 0.52.2 → 0.52.4

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 (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,629 +1,629 @@
1
- import { createHash, randomBytes } from 'node:crypto';
2
- import {
3
- mkdir, open, readFile, readdir, rename, rm, stat,
4
- } from 'node:fs/promises';
5
- import path from 'node:path';
6
-
7
- import {
8
- TODO_LIMITS,
9
- TODO_NOTE_CONTEXT_SCHEMA,
10
- TODO_NOTE_EVENT_SCHEMA,
11
- TODO_NOTE_EVENT_V2_SCHEMA,
12
- canonicalizeTodoArtifact,
13
- exactRecord,
14
- isTodoDigest,
15
- isTodoIdentifier,
16
- todoSelfDigest,
17
- validateTodoPlan,
18
- validateTodoNoteContext,
19
- validateTodoNoteEvent,
20
- } from './todo-contracts.mjs';
21
- import { validatePhaseTodoRevision, validateTodoRevision } from './todo-revision.mjs';
22
-
23
- const NOTE_ROOT_REF = '.lattice/todo/notes';
24
- const SEALED_NAME = /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u;
25
- const ZERO_DIGEST = '0'.repeat(64);
26
- const MAX_SEGMENTS = 4_096;
27
-
28
- export class TodoNoteStoreError extends Error {
29
- constructor(code, reason, detail = {}) {
30
- super(reason);
31
- this.name = 'TodoNoteStoreError';
32
- this.code = code;
33
- this.detail = { reason, ...detail };
34
- }
35
- }
36
-
37
- function fail(code, reason, detail) {
38
- throw new TodoNoteStoreError(code, reason, detail);
39
- }
40
-
41
- function sha256(bytes) {
42
- return createHash('sha256').update(bytes).digest('hex');
43
- }
44
-
45
- function canonicalLine(value) {
46
- return Buffer.from(`${canonicalizeTodoArtifact(value)}\n`, 'utf8');
47
- }
48
-
49
- /**
50
- * task noteとplan noteは**別のchain file**へ積む。
51
- *
52
- * 混ぜると、plan note(`todo_note_event.v2`)を1件書いた時点で、旧CLIにとってその planの
53
- * chain全体が壊れたものになる——`parseCanonicalSegment`は1 eventずつbyte完全一致で検証し、
54
- * 1件でも通らなければchainごと`NOTE_LOG_CORRUPT`で落とすためである。noteの読みは
55
- * `todo start`の前提条件(fail closed)なので、**旧CLIでstartが通らなくなる**。しかも
56
- * store��書いたものは戻せないので、rollbackで復旧できない。
57
- *
58
- * 旧readerが読むのは`active.jsonl`と`sealed/*`だけで、plan直下を列挙しない。別名のfileへ
59
- * 積めば存在に気づかず、task noteの読み書きは1バイトも変わらない。旧CLIからplan noteは
60
- * 見えないままだが、**旧CLIではplan noteを書けない以上、読めなくても行動が変わらない**。
61
- */
62
- function notePaths(repoRoot, planKey) {
63
- if (!isTodoIdentifier(planKey)) throw new TypeError('planKey must be a todo identifier');
64
- const root = path.resolve(repoRoot, NOTE_ROOT_REF, planKey);
65
- return {
66
- root,
67
- active: path.join(root, 'active.jsonl'),
68
- sealed: path.join(root, 'sealed'),
69
- planActive: path.join(root, 'plan-active.jsonl'),
70
- planSealed: path.join(root, 'plan-sealed'),
71
- };
72
- }
73
-
74
- /** chainごとのpathと、そのchainが受けるevent schema。 */
75
- function chainRefs(repoRoot, planKey, scope) {
76
- const refs = notePaths(repoRoot, planKey);
77
- return scope === 'plan'
78
- ? { active: refs.planActive, sealed: refs.planSealed, schema: TODO_NOTE_EVENT_V2_SCHEMA }
79
- : { active: refs.active, sealed: refs.sealed, schema: TODO_NOTE_EVENT_SCHEMA };
80
- }
81
-
82
- async function readOptionalBounded(ref, { missing = false } = {}) {
83
- try {
84
- const metadata = await stat(ref);
85
- if (!metadata.isFile() || metadata.size > TODO_LIMITS.journalSegmentBytes) {
86
- fail('NOTE_LOG_CORRUPT', 'note_segment_invalid', { ref });
87
- }
88
- return await readFile(ref);
89
- } catch (error) {
90
- if (error instanceof TodoNoteStoreError) throw error;
91
- if (missing && error?.code === 'ENOENT') return null;
92
- fail('NOTE_LOG_CORRUPT', 'note_segment_unreadable', { ref });
93
- }
94
- }
95
-
96
- function parseCanonicalSegment(bytes, ref) {
97
- if (bytes.length === 0 || bytes.at(-1) !== 0x0a) {
98
- fail('NOTE_LOG_CORRUPT', 'note_segment_not_canonical', { ref });
99
- }
100
- const lines = bytes.toString('utf8').slice(0, -1).split('\n');
101
- const events = [];
102
- for (const line of lines) {
103
- let event;
104
- try { event = JSON.parse(line); } catch { fail('NOTE_LOG_CORRUPT', 'note_json_invalid', { ref }); }
105
- if (!validateTodoNoteEvent(event) || canonicalLine(event).toString('utf8') !== `${line}\n`) {
106
- fail('NOTE_LOG_CORRUPT', 'note_event_invalid', { ref });
107
- }
108
- events.push(event);
109
- }
110
- return events;
111
- }
112
-
113
- async function sealedFiles(ref) {
114
- try {
115
- const names = await readdir(ref);
116
- if (names.length > MAX_SEGMENTS || names.some((name) => !SEALED_NAME.test(name))) {
117
- fail('NOTE_LOG_CORRUPT', 'note_sealed_inventory_invalid', { ref });
118
- }
119
- return names.sort();
120
- } catch (error) {
121
- if (error instanceof TodoNoteStoreError) throw error;
122
- if (error?.code === 'ENOENT') return [];
123
- fail('NOTE_LOG_CORRUPT', 'note_sealed_inventory_unreadable', { ref });
124
- }
125
- }
126
-
127
- function validateEventChain(events, { projectId, planKey }) {
128
- for (let index = 0; index < events.length; index += 1) {
129
- const event = events[index];
130
- const previous = events[index - 1] ?? null;
131
- if (event.project_id !== projectId || event.plan_key !== planKey
132
- || event.sequence !== index + 1
133
- || event.previous_digest !== (previous?.event_digest ?? null)) {
134
- fail('NOTE_LOG_CORRUPT', 'note_digest_chain_invalid', {
135
- plan_key: planKey, sequence: event.sequence,
136
- });
137
- }
138
- }
139
- }
140
-
141
- /**
142
- * planに属する独立note chainをbyte-levelで検証して読む。missingだけは空chainである。
143
- * `scope`で読むchainを選ぶ(既定はtask chain=旧CLIと同じ経路・同じbyte)。
144
- */
145
- export async function readTodoNoteEvents(options = {}) {
146
- const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
147
- const scope = options.scope ?? 'task';
148
- if (!['plan', 'task'].includes(scope)) throw new TypeError('note chain scope must be plan or task');
149
- const { active, sealed, schema } = chainRefs(repoRoot, options.planKey, scope);
150
- const names = await sealedFiles(sealed);
151
- const events = [];
152
- let previousSegmentDigest = ZERO_DIGEST;
153
- for (const name of names) {
154
- const match = name.match(SEALED_NAME);
155
- const bytes = await readOptionalBounded(path.join(sealed, name));
156
- const segmentDigest = sha256(bytes);
157
- const segmentEvents = parseCanonicalSegment(bytes, path.join(sealed, name));
158
- if (Number(match[1]) !== segmentEvents[0]?.sequence
159
- || Number(match[2]) !== segmentEvents.at(-1)?.sequence
160
- || match[3] !== previousSegmentDigest || match[4] !== segmentDigest) {
161
- fail('NOTE_LOG_CORRUPT', 'note_seal_invalid', { ref: path.join(sealed, name) });
162
- }
163
- events.push(...segmentEvents);
164
- previousSegmentDigest = segmentDigest;
165
- }
166
- const activeBytes = await readOptionalBounded(active, { missing: true });
167
- if (activeBytes !== null) events.push(...parseCanonicalSegment(activeBytes, active));
168
- // chainの分離は「そのfileへ何が積まれるか」で守る。混ざったchainは分離の意味を失うので
169
- // 黙って受けず、読んだ時点でtypedに落とす。
170
- if (events.some((event) => event.schema !== schema)) {
171
- fail('NOTE_LOG_CORRUPT', 'note_chain_scope_mixed', { plan_key: options.planKey, scope });
172
- }
173
- if (events.length > 0) {
174
- validateEventChain(events, { projectId: events[0].project_id, planKey: options.planKey });
175
- }
176
- return {
177
- events,
178
- head_digest: events.at(-1)?.event_digest ?? null,
179
- active_bytes: activeBytes ?? Buffer.alloc(0),
180
- previous_segment_digest: previousSegmentDigest,
181
- };
182
- }
183
-
184
- async function atomicWrite(ref, bytes) {
185
- await mkdir(path.dirname(ref), { recursive: true });
186
- const temporary = path.join(path.dirname(ref),
187
- `.${path.basename(ref)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
188
- let handle;
189
- try {
190
- handle = await open(temporary, 'wx', 0o600);
191
- await handle.writeFile(bytes);
192
- await handle.sync();
193
- await handle.close();
194
- handle = null;
195
- await rename(temporary, ref);
196
- const directory = await open(path.dirname(ref), 'r');
197
- // Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
198
- // win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
199
- try { await directory.sync(); } catch (error) {
200
- if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
201
- } finally { await directory.close(); }
202
- } finally {
203
- if (handle) await handle.close();
204
- await rm(temporary, { force: true });
205
- }
206
- }
207
-
208
- async function withNoteLock(repoRoot, callback) {
209
- const root = path.resolve(repoRoot, NOTE_ROOT_REF);
210
- await mkdir(root, { recursive: true });
211
- const lockRef = path.join(root, '.write.lock');
212
- let handle;
213
- try { handle = await open(lockRef, 'wx', 0o600); }
214
- catch (error) {
215
- if (error?.code === 'EEXIST') fail('NOTE_WRITE_CONFLICT', 'note_store_locked');
216
- throw error;
217
- }
218
- try { return await callback(); }
219
- finally { await handle.close(); await rm(lockRef, { force: true }); }
220
- }
221
-
222
- /** lifecycle artifactsへ触れず、独立note chainだけへ1 eventを追記する。 */
223
- export async function appendTodoNote(options = {}) {
224
- const keys = [
225
- 'repoRoot', 'projectId', 'planKey', 'planVersion', 'taskId', 'actor',
226
- 'recordedAt', 'body', 'supersedes', 'eligibleSupersedes',
227
- ];
228
- if (!exactRecord(options, keys)
229
- || !Array.isArray(options.eligibleSupersedes)
230
- || !options.eligibleSupersedes.every(isTodoDigest)
231
- || ![options.projectId, options.planKey, options.planVersion].every(isTodoIdentifier)
232
- // taskId nullがplan単位noteの指定。scopeはeventのschemaが持つ。
233
- || !(options.taskId === null || isTodoIdentifier(options.taskId))) {
234
- throw new TypeError('todo note append options invalid');
235
- }
236
- const planScoped = options.taskId === null;
237
- const scope = planScoped ? 'plan' : 'task';
238
- const repoRoot = path.resolve(options.repoRoot);
239
- return withNoteLock(repoRoot, async () => {
240
- // sequenceとprevious_digestはchainごとに独立。note系の起点は1(journal系の0ではない)。
241
- const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope });
242
- if (options.supersedes !== null) {
243
- const target = chain.events.find(({ event_digest: digest }) => digest === options.supersedes);
244
- if (target === undefined || !options.eligibleSupersedes.includes(options.supersedes)) {
245
- // plan noteはplan noteだけを、task noteは同じtaskのnoteだけを訂正できる。
246
- // scopeを跨ぐ訂正を許すと、届く先が違うものを同じ履歴として畳むことになる。
247
- fail('NOTE_SUPERSEDES_INVALID', planScoped
248
- ? 'superseded_note_not_plan_scoped' : 'superseded_note_not_in_same_task', {
249
- plan_key: options.planKey, task_id: options.taskId,
250
- });
251
- }
252
- }
253
- const previous = chain.events.at(-1) ?? null;
254
- const event = {
255
- schema: planScoped ? TODO_NOTE_EVENT_V2_SCHEMA : TODO_NOTE_EVENT_SCHEMA,
256
- ...(planScoped ? { scope: 'plan' } : {}),
257
- project_id: options.projectId,
258
- plan_key: options.planKey,
259
- task_id: options.taskId,
260
- plan_version: options.planVersion,
261
- sequence: (previous?.sequence ?? 0) + 1,
262
- previous_digest: previous?.event_digest ?? null,
263
- actor: options.actor,
264
- recorded_at: options.recordedAt,
265
- body: options.body,
266
- supersedes: options.supersedes,
267
- event_digest: '',
268
- };
269
- event.event_digest = todoSelfDigest(event, 'event_digest');
270
- if (!validateTodoNoteEvent(event)) throw new TypeError('todo note event input invalid');
271
-
272
- const paths = chainRefs(repoRoot, options.planKey, scope);
273
- const eventBytes = canonicalLine(event);
274
- if (chain.active_bytes.length > 0
275
- && chain.active_bytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
276
- const activeEvents = parseCanonicalSegment(chain.active_bytes, paths.active);
277
- const segmentDigest = sha256(chain.active_bytes);
278
- const name = `${String(activeEvents[0].sequence).padStart(12, '0')}`
279
- + `-${String(activeEvents.at(-1).sequence).padStart(12, '0')}`
280
- + `-${chain.previous_segment_digest}-${segmentDigest}.jsonl`;
281
- await atomicWrite(path.join(paths.sealed, name), chain.active_bytes);
282
- await atomicWrite(paths.active, eventBytes);
283
- } else {
284
- await atomicWrite(paths.active, Buffer.concat([chain.active_bytes, eventBytes]));
285
- }
286
- return event;
287
- });
288
- }
289
-
290
- /** v1(task note)とv2(plan note)を、明示`scope`を持つ1つの形へ正規化する。 */
291
- function noteProjectionEntry(event, supersededBy) {
292
- return {
293
- event_digest: event.event_digest,
294
- origin_plan_version: event.plan_version,
295
- scope: event.schema === TODO_NOTE_EVENT_V2_SCHEMA ? 'plan' : 'task',
296
- origin_task_id: event.task_id,
297
- actor: event.actor,
298
- recorded_at: event.recorded_at,
299
- body: event.body,
300
- supersedes: event.supersedes,
301
- superseded_by: supersededBy ?? null,
302
- correction_state: supersededBy === undefined ? 'current' : 'superseded',
303
- };
304
- }
305
-
306
- function migrationIndex(migrations) {
307
- if (!Array.isArray(migrations)) throw new TypeError('todo note migrations must be an array');
308
- const index = new Map();
309
- for (const migration of migrations) {
310
- if (!exactRecord(migration, ['from_plan_version', 'to_plan_version', 'task_migration'])
311
- || !isTodoIdentifier(migration.from_plan_version)
312
- || !isTodoIdentifier(migration.to_plan_version)
313
- || migration.from_plan_version === migration.to_plan_version
314
- || !Array.isArray(migration.task_migration)
315
- || index.has(migration.from_plan_version)) {
316
- fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
317
- }
318
- const taskMap = new Map();
319
- for (const entry of migration.task_migration) {
320
- if (!exactRecord(entry, ['from_task_id', 'to_task_id'])
321
- || !isTodoIdentifier(entry.from_task_id)
322
- || !(entry.to_task_id === null || isTodoIdentifier(entry.to_task_id))
323
- || taskMap.has(entry.from_task_id)) {
324
- fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid');
325
- }
326
- taskMap.set(entry.from_task_id, entry.to_task_id === 'removed' ? null : entry.to_task_id);
327
- }
328
- index.set(migration.from_plan_version, {
329
- toPlanVersion: migration.to_plan_version, taskMap,
330
- });
331
- }
332
- return index;
333
- }
334
-
335
- function resolveNoteTarget(event, { currentPlanVersion, currentTaskIds, migrations }) {
336
- let version = event.plan_version;
337
- let taskId = event.task_id;
338
- const seen = new Set();
339
- while (version !== currentPlanVersion) {
340
- if (seen.has(version)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
341
- seen.add(version);
342
- const step = migrations.get(version);
343
- if (step === undefined) return { kind: 'archived' };
344
- const nextTaskId = step.taskMap.get(taskId);
345
- if (nextTaskId === undefined || nextTaskId === null) return { kind: 'archived' };
346
- version = step.toPlanVersion;
347
- taskId = nextTaskId;
348
- }
349
- return currentTaskIds.has(taskId) ? { kind: 'active', taskId } : { kind: 'archived' };
350
- }
351
-
352
- /**
353
- * 既存task_migrationを合成し、現行taskへ渡すbounded contextとremoved taskのarchived束を作る。
354
- * note listはこの全履歴を使えるが、通常詳細/startはcontextを自動同梱する。
355
- */
356
- export function projectTodoNoteContext(options = {}) {
357
- if (!exactRecord(options, [
358
- 'projectId', 'planKey', 'currentPlanVersion', 'currentTaskId',
359
- 'currentTaskIds', 'events', 'planEvents', 'migrations',
360
- ]) || ![options.projectId, options.planKey, options.currentPlanVersion, options.currentTaskId]
361
- .every(isTodoIdentifier) || !Array.isArray(options.currentTaskIds)
362
- || !options.currentTaskIds.every(isTodoIdentifier)
363
- || !options.currentTaskIds.includes(options.currentTaskId)
364
- || !Array.isArray(options.events) || !options.events.every(validateTodoNoteEvent)
365
- || !Array.isArray(options.planEvents) || !options.planEvents.every(validateTodoNoteEvent)) {
366
- throw new TypeError('todo note projection options invalid');
367
- }
368
- const currentTaskIds = new Set(options.currentTaskIds);
369
- const migrations = migrationIndex(options.migrations);
370
- // 訂正はscopeを跨げないので、supersedeの追跡もchainごとに閉じる。
371
- const supersededBy = new Map();
372
- for (const event of [...options.events, ...options.planEvents]) {
373
- if (event.project_id !== options.projectId || event.plan_key !== options.planKey) {
374
- fail('NOTE_LOG_CORRUPT', 'note_identity_mismatch');
375
- }
376
- if (event.supersedes !== null) supersededBy.set(event.supersedes, event.event_digest);
377
- }
378
-
379
- const taskCurrent = [];
380
- const archived = [];
381
- const sequenceOf = (events) => new Map(events.map((event) => [event.event_digest, event.sequence]));
382
- const taskSequence = sequenceOf(options.events);
383
- const planSequence = sequenceOf(options.planEvents);
384
- for (const event of options.events) {
385
- const entry = noteProjectionEntry(event, supersededBy.get(event.event_digest));
386
- const target = resolveNoteTarget(event, {
387
- currentPlanVersion: options.currentPlanVersion, currentTaskIds, migrations,
388
- });
389
- if (target.kind === 'archived') archived.push(entry);
390
- else if (target.taskId === options.currentTaskId) taskCurrent.push(entry);
391
- }
392
- // plan noteは特定のtaskに属さないので、task migrationで宛先を失うことがない。全taskの
393
- // contextへ載せる——工程レベルの義務は「次に着手する誰か」へ届くべきもので、誰が着手するかは
394
- // 書いた時点で分からない。
395
- const planCurrent = options.planEvents
396
- .map((event) => noteProjectionEntry(event, supersededBy.get(event.event_digest)));
397
- taskCurrent.sort((left, right) => taskSequence.get(right.event_digest)
398
- - taskSequence.get(left.event_digest));
399
- planCurrent.sort((left, right) => planSequence.get(right.event_digest)
400
- - planSequence.get(left.event_digest));
401
- // 2本のsequenceは独立なので、混ぜた全順序は時刻にもsequenceにも作れない(時刻は
402
- // future_clock_skewがある以上信用できない)。決定的な規則で並べる: plan単位の申し送りは
403
- // task固有のものより文脈が広いので先に読ませる。
404
- const current = [...planCurrent, ...taskCurrent];
405
- archived.reverse();
406
-
407
- const notes = [];
408
- let usedBytes = 0;
409
- for (const entry of current) {
410
- const bytes = Buffer.byteLength(entry.body, 'utf8');
411
- if (usedBytes + bytes > TODO_LIMITS.noteContextBytes) continue;
412
- notes.push(entry);
413
- usedBytes += bytes;
414
- }
415
- const context = {
416
- schema: TODO_NOTE_CONTEXT_SCHEMA,
417
- project_id: options.projectId,
418
- plan_key: options.planKey,
419
- task_id: options.currentTaskId,
420
- notes,
421
- // headはchainごとに言う。合成すると「どちらのheadか」と連結順を定義する必要が生まれ、
422
- // 順序が決まっていなければ同じ状態から違うdigestが出る。
423
- note_head_digest: taskCurrent[0]?.event_digest ?? null,
424
- plan_note_head_digest: planCurrent[0]?.event_digest ?? null,
425
- // overflowはcontext全体の予算の話でchainの性質ではないので、ここは合成でよい。
426
- overflow_count: current.length - notes.length,
427
- // plan noteを載せる以上、案内はplan全体を返す形でなければ「full」ではない。
428
- full_history_command: `lattice todo note list --plan ${options.planKey} --json`,
429
- context_digest: '',
430
- };
431
- context.context_digest = todoSelfDigest(context, 'context_digest');
432
- if (!validateTodoNoteContext(context)) {
433
- fail('NOTE_PROJECTION_INVALID', 'note_context_invalid');
434
- }
435
- return { context, archived, history: current };
436
- }
437
-
438
- async function readCanonicalJson(ref, { missing = false } = {}) {
439
- let bytes;
440
- try {
441
- const metadata = await stat(ref);
442
- if (!metadata.isFile() || metadata.size > TODO_LIMITS.snapshotBytes) {
443
- fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_invalid', { ref });
444
- }
445
- bytes = await readFile(ref);
446
- } catch (error) {
447
- if (error instanceof TodoNoteStoreError) throw error;
448
- if (missing && error?.code === 'ENOENT') return null;
449
- fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_unreadable', { ref });
450
- }
451
- let value;
452
- try { value = JSON.parse(bytes.toString('utf8')); }
453
- catch { fail('NOTE_PROJECTION_INVALID', 'note_projection_json_invalid', { ref }); }
454
- if (!bytes.equals(canonicalLine(value))) {
455
- fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_not_canonical', { ref });
456
- }
457
- return value;
458
- }
459
-
460
- async function readNoteMigrations(repoRoot, planKey, eventVersions) {
461
- const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
462
- let entries;
463
- try { entries = await readdir(base, { withFileTypes: true }); }
464
- catch (error) {
465
- if (error?.code === 'ENOENT' && eventVersions.size === 0) return [];
466
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_unreadable', { plan_key: planKey });
467
- }
468
- const versions = new Set();
469
- const migrations = [];
470
- for (const entry of entries) {
471
- if (!entry.isDirectory() || !isTodoIdentifier(entry.name)) {
472
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
473
- }
474
- const versionRoot = path.join(base, entry.name);
475
- // A revision directory is published before manifest activation. A crash during
476
- // that window can leave an unreferenced directory containing only a journal
477
- // stub. It is not a historical plan until its canonical plan artifact exists.
478
- // Do not make that unreachable residue poison note projection; if a note event
479
- // names this version, the origin-version check below still fails closed.
480
- const plan = await readCanonicalJson(path.join(versionRoot, 'plan.json'), { missing: true });
481
- if (plan === null) continue;
482
- if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
483
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
484
- }
485
- versions.add(entry.name);
486
- const revision = await readCanonicalJson(path.join(versionRoot, 'revision.json'), { missing: true });
487
- if (revision === null) continue;
488
- if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
489
- || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
490
- || !Array.isArray(revision.task_migration)) {
491
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
492
- }
493
- migrations.push({
494
- from_plan_version: revision.predecessor.plan_version,
495
- to_plan_version: entry.name,
496
- task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
497
- from_task_id: fromTaskId, to_task_id: toTaskId,
498
- })),
499
- });
500
- }
501
- if ([...eventVersions].some((version) => !versions.has(version))) {
502
- fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
503
- }
504
- return migrations;
505
- }
506
-
507
- /** active store memberと歴史revisionから、通常供給用contextを一回で読む。 */
508
- export async function readTodoNoteContext(options = {}) {
509
- if (!exactRecord(options, ['repoRoot', 'store', 'planKey', 'taskId'])
510
- || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.taskId)
511
- || options.store === null || typeof options.store !== 'object') {
512
- throw new TypeError('todo note context read options invalid');
513
- }
514
- const repoRoot = path.resolve(options.repoRoot);
515
- const member = options.store.members?.find(({ descriptor }) => (
516
- descriptor.plan_key === options.planKey
517
- ));
518
- if (member === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_plan_not_active', {
519
- plan_key: options.planKey,
520
- });
521
- const task = member.plan.tasks.find(({ task_id: taskId }) => taskId === options.taskId);
522
- if (task === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_task_not_active', {
523
- plan_key: options.planKey, task_id: options.taskId,
524
- });
525
- const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
526
- const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
527
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
528
- new Set(chain.events.map(({ plan_version: version }) => version)));
529
- return projectTodoNoteContext({
530
- projectId: member.plan.project_id,
531
- planKey: options.planKey,
532
- currentPlanVersion: member.plan.plan_version,
533
- currentTaskId: task.task_id,
534
- currentTaskIds: member.plan.tasks.map(({ task_id: taskId }) => taskId),
535
- events: chain.events,
536
- planEvents: planChain.events,
537
- migrations,
538
- });
539
- }
540
-
541
- /**
542
- * status面の`plan_notes`欄の素材を、store内の全planぶん一度に読む。
543
- *
544
- * plan単位noteは「工程に属する義務」で、着手する誰かのcontextへは届くが、**まだ誰も
545
- * 着手していない工程の義務はどこにも出ない**。statusはそれを出す唯一の面なので、
546
- * ここでは本文を一切運ばない——載せるのは件数・帰属・次の一手だけで、中身は
547
- * `note list`が持つ(`audit_pending`が330字のproseを落としたのと同じ判断・ADR 0159)。
548
- *
549
- * noteを持たないplanはentryごと出さない。「全plan常に1行」は、前campaignの
550
- * witness `coverage: missing`と同じ「満杯で始まるので読み飛ばされる欄」になる。
551
- *
552
- * chainが壊れているplanが1つでもあれば`readTodoNoteEvents`のtyped errorがそのまま出る
553
- * (fail closed)。壊れた義務記録を「義務なし」と同じ空へ丸めない。
554
- */
555
- export async function readTodoPlanNotesForStatus(options = {}) {
556
- if (!exactRecord(options, ['repoRoot', 'store'])
557
- || options.store === null || typeof options.store !== 'object'
558
- || !Array.isArray(options.store.members)) {
559
- throw new TypeError('todo plan notes read options invalid');
560
- }
561
- const repoRoot = path.resolve(options.repoRoot);
562
- const summaries = [];
563
- for (const member of options.store.members) {
564
- const planKey = member.plan.plan_key;
565
- // plan noteは専用chainに在る。schemaでの選別は要らない——読む先そのものが分かれている。
566
- const chain = await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' });
567
- const superseded = new Set(chain.events
568
- .filter(({ supersedes }) => supersedes !== null)
569
- .map(({ supersedes }) => supersedes));
570
- // 訂正されたnoteは数えない。数えると訂正するほど件数が増える。
571
- const current = chain.events
572
- .filter((event) => !superseded.has(event.event_digest))
573
- .sort((left, right) => right.sequence - left.sequence);
574
- if (current.length === 0) continue;
575
- summaries.push({
576
- plan_key: planKey,
577
- // `note_context.note_head_digest`はtask chainのheadを指す。同名で別のchainを指すと
578
- // 型が同じdigestなので取り違えてもvalidatorを通る——名前で区別する(room [211])。
579
- plan_note_head_digest: current[0].event_digest,
580
- count: current.length,
581
- latest: current.slice(0, TODO_LIMITS.statusPlanNoteLatest).map((event) => ({
582
- event_digest: event.event_digest,
583
- actor_agent: event.actor.agent,
584
- recorded_at: event.recorded_at,
585
- })),
586
- // 欄だけでは読まれない。届いた先で次に何を打てばいいかを名指しする。
587
- next_commands: [`lattice todo note list --plan ${planKey} --json`],
588
- });
589
- }
590
- summaries.sort((left, right) => (
591
- left.plan_key < right.plan_key ? -1 : left.plan_key > right.plan_key ? 1 : 0));
592
- return summaries;
593
- }
594
-
595
- /** Gantt用に1 planのchain/historyを一度だけ読み、全task contextへ投影する。 */
596
- export async function readTodoNoteContextsForPlan(options = {}) {
597
- if (!exactRecord(options, ['repoRoot', 'store', 'planKey'])
598
- || !isTodoIdentifier(options.planKey)
599
- || options.store === null || typeof options.store !== 'object') {
600
- throw new TypeError('todo note contexts read options invalid');
601
- }
602
- const repoRoot = path.resolve(options.repoRoot);
603
- const member = options.store.members?.find(({ descriptor }) => (
604
- descriptor.plan_key === options.planKey
605
- ));
606
- if (member === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_plan_not_active', {
607
- plan_key: options.planKey,
608
- });
609
- const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
610
- const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
611
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
612
- new Set(chain.events.map(({ plan_version: version }) => version)));
613
- const currentTaskIds = member.plan.tasks.map(({ task_id: taskId }) => taskId);
614
- const projected = member.plan.tasks.map((task) => projectTodoNoteContext({
615
- projectId: member.plan.project_id,
616
- planKey: options.planKey,
617
- currentPlanVersion: member.plan.plan_version,
618
- currentTaskId: task.task_id,
619
- currentTaskIds,
620
- events: chain.events,
621
- planEvents: planChain.events,
622
- migrations,
623
- }));
624
- return {
625
- contexts: projected.map(({ context }) => context),
626
- archived: projected[0]?.archived ?? [],
627
- note_head_digest: chain.head_digest,
628
- };
629
- }
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import {
3
+ mkdir, open, readFile, readdir, rename, rm, stat,
4
+ } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+
7
+ import {
8
+ TODO_LIMITS,
9
+ TODO_NOTE_CONTEXT_SCHEMA,
10
+ TODO_NOTE_EVENT_SCHEMA,
11
+ TODO_NOTE_EVENT_V2_SCHEMA,
12
+ canonicalizeTodoArtifact,
13
+ exactRecord,
14
+ isTodoDigest,
15
+ isTodoIdentifier,
16
+ todoSelfDigest,
17
+ validateTodoPlan,
18
+ validateTodoNoteContext,
19
+ validateTodoNoteEvent,
20
+ } from './todo-contracts.mjs';
21
+ import { validatePhaseTodoRevision, validateTodoRevision } from './todo-revision.mjs';
22
+
23
+ const NOTE_ROOT_REF = '.lattice/todo/notes';
24
+ const SEALED_NAME = /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u;
25
+ const ZERO_DIGEST = '0'.repeat(64);
26
+ const MAX_SEGMENTS = 4_096;
27
+
28
+ export class TodoNoteStoreError extends Error {
29
+ constructor(code, reason, detail = {}) {
30
+ super(reason);
31
+ this.name = 'TodoNoteStoreError';
32
+ this.code = code;
33
+ this.detail = { reason, ...detail };
34
+ }
35
+ }
36
+
37
+ function fail(code, reason, detail) {
38
+ throw new TodoNoteStoreError(code, reason, detail);
39
+ }
40
+
41
+ function sha256(bytes) {
42
+ return createHash('sha256').update(bytes).digest('hex');
43
+ }
44
+
45
+ function canonicalLine(value) {
46
+ return Buffer.from(`${canonicalizeTodoArtifact(value)}\n`, 'utf8');
47
+ }
48
+
49
+ /**
50
+ * task noteとplan noteは**別のchain file**へ積む。
51
+ *
52
+ * 混ぜると、plan note(`todo_note_event.v2`)を1件書いた時点で、旧CLIにとってその planの
53
+ * chain全体が壊れたものになる——`parseCanonicalSegment`は1 eventずつbyte完全一致で検証し、
54
+ * 1件でも通らなければchainごと`NOTE_LOG_CORRUPT`で落とすためである。noteの読みは
55
+ * `todo start`の前提条件(fail closed)なので、**旧CLIでstartが通らなくなる**。しかも
56
+ * store��書いたものは戻せないので、rollbackで復旧できない。
57
+ *
58
+ * 旧readerが読むのは`active.jsonl`と`sealed/*`だけで、plan直下を列挙しない。別名のfileへ
59
+ * 積めば存在に気づかず、task noteの読み書きは1バイトも変わらない。旧CLIからplan noteは
60
+ * 見えないままだが、**旧CLIではplan noteを書けない以上、読めなくても行動が変わらない**。
61
+ */
62
+ function notePaths(repoRoot, planKey) {
63
+ if (!isTodoIdentifier(planKey)) throw new TypeError('planKey must be a todo identifier');
64
+ const root = path.resolve(repoRoot, NOTE_ROOT_REF, planKey);
65
+ return {
66
+ root,
67
+ active: path.join(root, 'active.jsonl'),
68
+ sealed: path.join(root, 'sealed'),
69
+ planActive: path.join(root, 'plan-active.jsonl'),
70
+ planSealed: path.join(root, 'plan-sealed'),
71
+ };
72
+ }
73
+
74
+ /** chainごとのpathと、そのchainが受けるevent schema。 */
75
+ function chainRefs(repoRoot, planKey, scope) {
76
+ const refs = notePaths(repoRoot, planKey);
77
+ return scope === 'plan'
78
+ ? { active: refs.planActive, sealed: refs.planSealed, schema: TODO_NOTE_EVENT_V2_SCHEMA }
79
+ : { active: refs.active, sealed: refs.sealed, schema: TODO_NOTE_EVENT_SCHEMA };
80
+ }
81
+
82
+ async function readOptionalBounded(ref, { missing = false } = {}) {
83
+ try {
84
+ const metadata = await stat(ref);
85
+ if (!metadata.isFile() || metadata.size > TODO_LIMITS.journalSegmentBytes) {
86
+ fail('NOTE_LOG_CORRUPT', 'note_segment_invalid', { ref });
87
+ }
88
+ return await readFile(ref);
89
+ } catch (error) {
90
+ if (error instanceof TodoNoteStoreError) throw error;
91
+ if (missing && error?.code === 'ENOENT') return null;
92
+ fail('NOTE_LOG_CORRUPT', 'note_segment_unreadable', { ref });
93
+ }
94
+ }
95
+
96
+ function parseCanonicalSegment(bytes, ref) {
97
+ if (bytes.length === 0 || bytes.at(-1) !== 0x0a) {
98
+ fail('NOTE_LOG_CORRUPT', 'note_segment_not_canonical', { ref });
99
+ }
100
+ const lines = bytes.toString('utf8').slice(0, -1).split('\n');
101
+ const events = [];
102
+ for (const line of lines) {
103
+ let event;
104
+ try { event = JSON.parse(line); } catch { fail('NOTE_LOG_CORRUPT', 'note_json_invalid', { ref }); }
105
+ if (!validateTodoNoteEvent(event) || canonicalLine(event).toString('utf8') !== `${line}\n`) {
106
+ fail('NOTE_LOG_CORRUPT', 'note_event_invalid', { ref });
107
+ }
108
+ events.push(event);
109
+ }
110
+ return events;
111
+ }
112
+
113
+ async function sealedFiles(ref) {
114
+ try {
115
+ const names = await readdir(ref);
116
+ if (names.length > MAX_SEGMENTS || names.some((name) => !SEALED_NAME.test(name))) {
117
+ fail('NOTE_LOG_CORRUPT', 'note_sealed_inventory_invalid', { ref });
118
+ }
119
+ return names.sort();
120
+ } catch (error) {
121
+ if (error instanceof TodoNoteStoreError) throw error;
122
+ if (error?.code === 'ENOENT') return [];
123
+ fail('NOTE_LOG_CORRUPT', 'note_sealed_inventory_unreadable', { ref });
124
+ }
125
+ }
126
+
127
+ function validateEventChain(events, { projectId, planKey }) {
128
+ for (let index = 0; index < events.length; index += 1) {
129
+ const event = events[index];
130
+ const previous = events[index - 1] ?? null;
131
+ if (event.project_id !== projectId || event.plan_key !== planKey
132
+ || event.sequence !== index + 1
133
+ || event.previous_digest !== (previous?.event_digest ?? null)) {
134
+ fail('NOTE_LOG_CORRUPT', 'note_digest_chain_invalid', {
135
+ plan_key: planKey, sequence: event.sequence,
136
+ });
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * planに属する独立note chainをbyte-levelで検証して読む。missingだけは空chainである。
143
+ * `scope`で読むchainを選ぶ(既定はtask chain=旧CLIと同じ経路・同じbyte)。
144
+ */
145
+ export async function readTodoNoteEvents(options = {}) {
146
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
147
+ const scope = options.scope ?? 'task';
148
+ if (!['plan', 'task'].includes(scope)) throw new TypeError('note chain scope must be plan or task');
149
+ const { active, sealed, schema } = chainRefs(repoRoot, options.planKey, scope);
150
+ const names = await sealedFiles(sealed);
151
+ const events = [];
152
+ let previousSegmentDigest = ZERO_DIGEST;
153
+ for (const name of names) {
154
+ const match = name.match(SEALED_NAME);
155
+ const bytes = await readOptionalBounded(path.join(sealed, name));
156
+ const segmentDigest = sha256(bytes);
157
+ const segmentEvents = parseCanonicalSegment(bytes, path.join(sealed, name));
158
+ if (Number(match[1]) !== segmentEvents[0]?.sequence
159
+ || Number(match[2]) !== segmentEvents.at(-1)?.sequence
160
+ || match[3] !== previousSegmentDigest || match[4] !== segmentDigest) {
161
+ fail('NOTE_LOG_CORRUPT', 'note_seal_invalid', { ref: path.join(sealed, name) });
162
+ }
163
+ events.push(...segmentEvents);
164
+ previousSegmentDigest = segmentDigest;
165
+ }
166
+ const activeBytes = await readOptionalBounded(active, { missing: true });
167
+ if (activeBytes !== null) events.push(...parseCanonicalSegment(activeBytes, active));
168
+ // chainの分離は「そのfileへ何が積まれるか」で守る。混ざったchainは分離の意味を失うので
169
+ // 黙って受けず、読んだ時点でtypedに落とす。
170
+ if (events.some((event) => event.schema !== schema)) {
171
+ fail('NOTE_LOG_CORRUPT', 'note_chain_scope_mixed', { plan_key: options.planKey, scope });
172
+ }
173
+ if (events.length > 0) {
174
+ validateEventChain(events, { projectId: events[0].project_id, planKey: options.planKey });
175
+ }
176
+ return {
177
+ events,
178
+ head_digest: events.at(-1)?.event_digest ?? null,
179
+ active_bytes: activeBytes ?? Buffer.alloc(0),
180
+ previous_segment_digest: previousSegmentDigest,
181
+ };
182
+ }
183
+
184
+ async function atomicWrite(ref, bytes) {
185
+ await mkdir(path.dirname(ref), { recursive: true });
186
+ const temporary = path.join(path.dirname(ref),
187
+ `.${path.basename(ref)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
188
+ let handle;
189
+ try {
190
+ handle = await open(temporary, 'wx', 0o600);
191
+ await handle.writeFile(bytes);
192
+ await handle.sync();
193
+ await handle.close();
194
+ handle = null;
195
+ await rename(temporary, ref);
196
+ const directory = await open(path.dirname(ref), 'r');
197
+ // Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
198
+ // win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
199
+ try { await directory.sync(); } catch (error) {
200
+ if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
201
+ } finally { await directory.close(); }
202
+ } finally {
203
+ if (handle) await handle.close();
204
+ await rm(temporary, { force: true });
205
+ }
206
+ }
207
+
208
+ async function withNoteLock(repoRoot, callback) {
209
+ const root = path.resolve(repoRoot, NOTE_ROOT_REF);
210
+ await mkdir(root, { recursive: true });
211
+ const lockRef = path.join(root, '.write.lock');
212
+ let handle;
213
+ try { handle = await open(lockRef, 'wx', 0o600); }
214
+ catch (error) {
215
+ if (error?.code === 'EEXIST') fail('NOTE_WRITE_CONFLICT', 'note_store_locked');
216
+ throw error;
217
+ }
218
+ try { return await callback(); }
219
+ finally { await handle.close(); await rm(lockRef, { force: true }); }
220
+ }
221
+
222
+ /** lifecycle artifactsへ触れず、独立note chainだけへ1 eventを追記する。 */
223
+ export async function appendTodoNote(options = {}) {
224
+ const keys = [
225
+ 'repoRoot', 'projectId', 'planKey', 'planVersion', 'taskId', 'actor',
226
+ 'recordedAt', 'body', 'supersedes', 'eligibleSupersedes',
227
+ ];
228
+ if (!exactRecord(options, keys)
229
+ || !Array.isArray(options.eligibleSupersedes)
230
+ || !options.eligibleSupersedes.every(isTodoDigest)
231
+ || ![options.projectId, options.planKey, options.planVersion].every(isTodoIdentifier)
232
+ // taskId nullがplan単位noteの指定。scopeはeventのschemaが持つ。
233
+ || !(options.taskId === null || isTodoIdentifier(options.taskId))) {
234
+ throw new TypeError('todo note append options invalid');
235
+ }
236
+ const planScoped = options.taskId === null;
237
+ const scope = planScoped ? 'plan' : 'task';
238
+ const repoRoot = path.resolve(options.repoRoot);
239
+ return withNoteLock(repoRoot, async () => {
240
+ // sequenceとprevious_digestはchainごとに独立。note系の起点は1(journal系の0ではない)。
241
+ const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope });
242
+ if (options.supersedes !== null) {
243
+ const target = chain.events.find(({ event_digest: digest }) => digest === options.supersedes);
244
+ if (target === undefined || !options.eligibleSupersedes.includes(options.supersedes)) {
245
+ // plan noteはplan noteだけを、task noteは同じtaskのnoteだけを訂正できる。
246
+ // scopeを跨ぐ訂正を許すと、届く先が違うものを同じ履歴として畳むことになる。
247
+ fail('NOTE_SUPERSEDES_INVALID', planScoped
248
+ ? 'superseded_note_not_plan_scoped' : 'superseded_note_not_in_same_task', {
249
+ plan_key: options.planKey, task_id: options.taskId,
250
+ });
251
+ }
252
+ }
253
+ const previous = chain.events.at(-1) ?? null;
254
+ const event = {
255
+ schema: planScoped ? TODO_NOTE_EVENT_V2_SCHEMA : TODO_NOTE_EVENT_SCHEMA,
256
+ ...(planScoped ? { scope: 'plan' } : {}),
257
+ project_id: options.projectId,
258
+ plan_key: options.planKey,
259
+ task_id: options.taskId,
260
+ plan_version: options.planVersion,
261
+ sequence: (previous?.sequence ?? 0) + 1,
262
+ previous_digest: previous?.event_digest ?? null,
263
+ actor: options.actor,
264
+ recorded_at: options.recordedAt,
265
+ body: options.body,
266
+ supersedes: options.supersedes,
267
+ event_digest: '',
268
+ };
269
+ event.event_digest = todoSelfDigest(event, 'event_digest');
270
+ if (!validateTodoNoteEvent(event)) throw new TypeError('todo note event input invalid');
271
+
272
+ const paths = chainRefs(repoRoot, options.planKey, scope);
273
+ const eventBytes = canonicalLine(event);
274
+ if (chain.active_bytes.length > 0
275
+ && chain.active_bytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
276
+ const activeEvents = parseCanonicalSegment(chain.active_bytes, paths.active);
277
+ const segmentDigest = sha256(chain.active_bytes);
278
+ const name = `${String(activeEvents[0].sequence).padStart(12, '0')}`
279
+ + `-${String(activeEvents.at(-1).sequence).padStart(12, '0')}`
280
+ + `-${chain.previous_segment_digest}-${segmentDigest}.jsonl`;
281
+ await atomicWrite(path.join(paths.sealed, name), chain.active_bytes);
282
+ await atomicWrite(paths.active, eventBytes);
283
+ } else {
284
+ await atomicWrite(paths.active, Buffer.concat([chain.active_bytes, eventBytes]));
285
+ }
286
+ return event;
287
+ });
288
+ }
289
+
290
+ /** v1(task note)とv2(plan note)を、明示`scope`を持つ1つの形へ正規化する。 */
291
+ function noteProjectionEntry(event, supersededBy) {
292
+ return {
293
+ event_digest: event.event_digest,
294
+ origin_plan_version: event.plan_version,
295
+ scope: event.schema === TODO_NOTE_EVENT_V2_SCHEMA ? 'plan' : 'task',
296
+ origin_task_id: event.task_id,
297
+ actor: event.actor,
298
+ recorded_at: event.recorded_at,
299
+ body: event.body,
300
+ supersedes: event.supersedes,
301
+ superseded_by: supersededBy ?? null,
302
+ correction_state: supersededBy === undefined ? 'current' : 'superseded',
303
+ };
304
+ }
305
+
306
+ function migrationIndex(migrations) {
307
+ if (!Array.isArray(migrations)) throw new TypeError('todo note migrations must be an array');
308
+ const index = new Map();
309
+ for (const migration of migrations) {
310
+ if (!exactRecord(migration, ['from_plan_version', 'to_plan_version', 'task_migration'])
311
+ || !isTodoIdentifier(migration.from_plan_version)
312
+ || !isTodoIdentifier(migration.to_plan_version)
313
+ || migration.from_plan_version === migration.to_plan_version
314
+ || !Array.isArray(migration.task_migration)
315
+ || index.has(migration.from_plan_version)) {
316
+ fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
317
+ }
318
+ const taskMap = new Map();
319
+ for (const entry of migration.task_migration) {
320
+ if (!exactRecord(entry, ['from_task_id', 'to_task_id'])
321
+ || !isTodoIdentifier(entry.from_task_id)
322
+ || !(entry.to_task_id === null || isTodoIdentifier(entry.to_task_id))
323
+ || taskMap.has(entry.from_task_id)) {
324
+ fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid');
325
+ }
326
+ taskMap.set(entry.from_task_id, entry.to_task_id === 'removed' ? null : entry.to_task_id);
327
+ }
328
+ index.set(migration.from_plan_version, {
329
+ toPlanVersion: migration.to_plan_version, taskMap,
330
+ });
331
+ }
332
+ return index;
333
+ }
334
+
335
+ function resolveNoteTarget(event, { currentPlanVersion, currentTaskIds, migrations }) {
336
+ let version = event.plan_version;
337
+ let taskId = event.task_id;
338
+ const seen = new Set();
339
+ while (version !== currentPlanVersion) {
340
+ if (seen.has(version)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
341
+ seen.add(version);
342
+ const step = migrations.get(version);
343
+ if (step === undefined) return { kind: 'archived' };
344
+ const nextTaskId = step.taskMap.get(taskId);
345
+ if (nextTaskId === undefined || nextTaskId === null) return { kind: 'archived' };
346
+ version = step.toPlanVersion;
347
+ taskId = nextTaskId;
348
+ }
349
+ return currentTaskIds.has(taskId) ? { kind: 'active', taskId } : { kind: 'archived' };
350
+ }
351
+
352
+ /**
353
+ * 既存task_migrationを合成し、現行taskへ渡すbounded contextとremoved taskのarchived束を作る。
354
+ * note listはこの全履歴を使えるが、通常詳細/startはcontextを自動同梱する。
355
+ */
356
+ export function projectTodoNoteContext(options = {}) {
357
+ if (!exactRecord(options, [
358
+ 'projectId', 'planKey', 'currentPlanVersion', 'currentTaskId',
359
+ 'currentTaskIds', 'events', 'planEvents', 'migrations',
360
+ ]) || ![options.projectId, options.planKey, options.currentPlanVersion, options.currentTaskId]
361
+ .every(isTodoIdentifier) || !Array.isArray(options.currentTaskIds)
362
+ || !options.currentTaskIds.every(isTodoIdentifier)
363
+ || !options.currentTaskIds.includes(options.currentTaskId)
364
+ || !Array.isArray(options.events) || !options.events.every(validateTodoNoteEvent)
365
+ || !Array.isArray(options.planEvents) || !options.planEvents.every(validateTodoNoteEvent)) {
366
+ throw new TypeError('todo note projection options invalid');
367
+ }
368
+ const currentTaskIds = new Set(options.currentTaskIds);
369
+ const migrations = migrationIndex(options.migrations);
370
+ // 訂正はscopeを跨げないので、supersedeの追跡もchainごとに閉じる。
371
+ const supersededBy = new Map();
372
+ for (const event of [...options.events, ...options.planEvents]) {
373
+ if (event.project_id !== options.projectId || event.plan_key !== options.planKey) {
374
+ fail('NOTE_LOG_CORRUPT', 'note_identity_mismatch');
375
+ }
376
+ if (event.supersedes !== null) supersededBy.set(event.supersedes, event.event_digest);
377
+ }
378
+
379
+ const taskCurrent = [];
380
+ const archived = [];
381
+ const sequenceOf = (events) => new Map(events.map((event) => [event.event_digest, event.sequence]));
382
+ const taskSequence = sequenceOf(options.events);
383
+ const planSequence = sequenceOf(options.planEvents);
384
+ for (const event of options.events) {
385
+ const entry = noteProjectionEntry(event, supersededBy.get(event.event_digest));
386
+ const target = resolveNoteTarget(event, {
387
+ currentPlanVersion: options.currentPlanVersion, currentTaskIds, migrations,
388
+ });
389
+ if (target.kind === 'archived') archived.push(entry);
390
+ else if (target.taskId === options.currentTaskId) taskCurrent.push(entry);
391
+ }
392
+ // plan noteは特定のtaskに属さないので、task migrationで宛先を失うことがない。全taskの
393
+ // contextへ載せる——工程レベルの義務は「次に着手する誰か」へ届くべきもので、誰が着手するかは
394
+ // 書いた時点で分からない。
395
+ const planCurrent = options.planEvents
396
+ .map((event) => noteProjectionEntry(event, supersededBy.get(event.event_digest)));
397
+ taskCurrent.sort((left, right) => taskSequence.get(right.event_digest)
398
+ - taskSequence.get(left.event_digest));
399
+ planCurrent.sort((left, right) => planSequence.get(right.event_digest)
400
+ - planSequence.get(left.event_digest));
401
+ // 2本のsequenceは独立なので、混ぜた全順序は時刻にもsequenceにも作れない(時刻は
402
+ // future_clock_skewがある以上信用できない)。決定的な規則で並べる: plan単位の申し送りは
403
+ // task固有のものより文脈が広いので先に読ませる。
404
+ const current = [...planCurrent, ...taskCurrent];
405
+ archived.reverse();
406
+
407
+ const notes = [];
408
+ let usedBytes = 0;
409
+ for (const entry of current) {
410
+ const bytes = Buffer.byteLength(entry.body, 'utf8');
411
+ if (usedBytes + bytes > TODO_LIMITS.noteContextBytes) continue;
412
+ notes.push(entry);
413
+ usedBytes += bytes;
414
+ }
415
+ const context = {
416
+ schema: TODO_NOTE_CONTEXT_SCHEMA,
417
+ project_id: options.projectId,
418
+ plan_key: options.planKey,
419
+ task_id: options.currentTaskId,
420
+ notes,
421
+ // headはchainごとに言う。合成すると「どちらのheadか」と連結順を定義する必要が生まれ、
422
+ // 順序が決まっていなければ同じ状態から違うdigestが出る。
423
+ note_head_digest: taskCurrent[0]?.event_digest ?? null,
424
+ plan_note_head_digest: planCurrent[0]?.event_digest ?? null,
425
+ // overflowはcontext全体の予算の話でchainの性質ではないので、ここは合成でよい。
426
+ overflow_count: current.length - notes.length,
427
+ // plan noteを載せる以上、案内はplan全体を返す形でなければ「full」ではない。
428
+ full_history_command: `lattice todo note list --plan ${options.planKey} --json`,
429
+ context_digest: '',
430
+ };
431
+ context.context_digest = todoSelfDigest(context, 'context_digest');
432
+ if (!validateTodoNoteContext(context)) {
433
+ fail('NOTE_PROJECTION_INVALID', 'note_context_invalid');
434
+ }
435
+ return { context, archived, history: current };
436
+ }
437
+
438
+ async function readCanonicalJson(ref, { missing = false } = {}) {
439
+ let bytes;
440
+ try {
441
+ const metadata = await stat(ref);
442
+ if (!metadata.isFile() || metadata.size > TODO_LIMITS.snapshotBytes) {
443
+ fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_invalid', { ref });
444
+ }
445
+ bytes = await readFile(ref);
446
+ } catch (error) {
447
+ if (error instanceof TodoNoteStoreError) throw error;
448
+ if (missing && error?.code === 'ENOENT') return null;
449
+ fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_unreadable', { ref });
450
+ }
451
+ let value;
452
+ try { value = JSON.parse(bytes.toString('utf8')); }
453
+ catch { fail('NOTE_PROJECTION_INVALID', 'note_projection_json_invalid', { ref }); }
454
+ if (!bytes.equals(canonicalLine(value))) {
455
+ fail('NOTE_PROJECTION_INVALID', 'note_projection_artifact_not_canonical', { ref });
456
+ }
457
+ return value;
458
+ }
459
+
460
+ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
461
+ const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
462
+ let entries;
463
+ try { entries = await readdir(base, { withFileTypes: true }); }
464
+ catch (error) {
465
+ if (error?.code === 'ENOENT' && eventVersions.size === 0) return [];
466
+ fail('NOTE_PROJECTION_INVALID', 'note_plan_history_unreadable', { plan_key: planKey });
467
+ }
468
+ const versions = new Set();
469
+ const migrations = [];
470
+ for (const entry of entries) {
471
+ if (!entry.isDirectory() || !isTodoIdentifier(entry.name)) {
472
+ fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
473
+ }
474
+ const versionRoot = path.join(base, entry.name);
475
+ // A revision directory is published before manifest activation. A crash during
476
+ // that window can leave an unreferenced directory containing only a journal
477
+ // stub. It is not a historical plan until its canonical plan artifact exists.
478
+ // Do not make that unreachable residue poison note projection; if a note event
479
+ // names this version, the origin-version check below still fails closed.
480
+ const plan = await readCanonicalJson(path.join(versionRoot, 'plan.json'), { missing: true });
481
+ if (plan === null) continue;
482
+ if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
483
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
484
+ }
485
+ versions.add(entry.name);
486
+ const revision = await readCanonicalJson(path.join(versionRoot, 'revision.json'), { missing: true });
487
+ if (revision === null) continue;
488
+ if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
489
+ || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
490
+ || !Array.isArray(revision.task_migration)) {
491
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
492
+ }
493
+ migrations.push({
494
+ from_plan_version: revision.predecessor.plan_version,
495
+ to_plan_version: entry.name,
496
+ task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
497
+ from_task_id: fromTaskId, to_task_id: toTaskId,
498
+ })),
499
+ });
500
+ }
501
+ if ([...eventVersions].some((version) => !versions.has(version))) {
502
+ fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
503
+ }
504
+ return migrations;
505
+ }
506
+
507
+ /** active store memberと歴史revisionから、通常供給用contextを一回で読む。 */
508
+ export async function readTodoNoteContext(options = {}) {
509
+ if (!exactRecord(options, ['repoRoot', 'store', 'planKey', 'taskId'])
510
+ || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.taskId)
511
+ || options.store === null || typeof options.store !== 'object') {
512
+ throw new TypeError('todo note context read options invalid');
513
+ }
514
+ const repoRoot = path.resolve(options.repoRoot);
515
+ const member = options.store.members?.find(({ descriptor }) => (
516
+ descriptor.plan_key === options.planKey
517
+ ));
518
+ if (member === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_plan_not_active', {
519
+ plan_key: options.planKey,
520
+ });
521
+ const task = member.plan.tasks.find(({ task_id: taskId }) => taskId === options.taskId);
522
+ if (task === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_task_not_active', {
523
+ plan_key: options.planKey, task_id: options.taskId,
524
+ });
525
+ const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
526
+ const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
527
+ const migrations = await readNoteMigrations(repoRoot, options.planKey,
528
+ new Set(chain.events.map(({ plan_version: version }) => version)));
529
+ return projectTodoNoteContext({
530
+ projectId: member.plan.project_id,
531
+ planKey: options.planKey,
532
+ currentPlanVersion: member.plan.plan_version,
533
+ currentTaskId: task.task_id,
534
+ currentTaskIds: member.plan.tasks.map(({ task_id: taskId }) => taskId),
535
+ events: chain.events,
536
+ planEvents: planChain.events,
537
+ migrations,
538
+ });
539
+ }
540
+
541
+ /**
542
+ * status面の`plan_notes`欄の素材を、store内の全planぶん一度に読む。
543
+ *
544
+ * plan単位noteは「工程に属する義務」で、着手する誰かのcontextへは届くが、**まだ誰も
545
+ * 着手していない工程の義務はどこにも出ない**。statusはそれを出す唯一の面なので、
546
+ * ここでは本文を一切運ばない——載せるのは件数・帰属・次の一手だけで、中身は
547
+ * `note list`が持つ(`audit_pending`が330字のproseを落としたのと同じ判断・ADR 0159)。
548
+ *
549
+ * noteを持たないplanはentryごと出さない。「全plan常に1行」は、前campaignの
550
+ * witness `coverage: missing`と同じ「満杯で始まるので読み飛ばされる欄」になる。
551
+ *
552
+ * chainが壊れているplanが1つでもあれば`readTodoNoteEvents`のtyped errorがそのまま出る
553
+ * (fail closed)。壊れた義務記録を「義務なし」と同じ空へ丸めない。
554
+ */
555
+ export async function readTodoPlanNotesForStatus(options = {}) {
556
+ if (!exactRecord(options, ['repoRoot', 'store'])
557
+ || options.store === null || typeof options.store !== 'object'
558
+ || !Array.isArray(options.store.members)) {
559
+ throw new TypeError('todo plan notes read options invalid');
560
+ }
561
+ const repoRoot = path.resolve(options.repoRoot);
562
+ const summaries = [];
563
+ for (const member of options.store.members) {
564
+ const planKey = member.plan.plan_key;
565
+ // plan noteは専用chainに在る。schemaでの選別は要らない——読む先そのものが分かれている。
566
+ const chain = await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' });
567
+ const superseded = new Set(chain.events
568
+ .filter(({ supersedes }) => supersedes !== null)
569
+ .map(({ supersedes }) => supersedes));
570
+ // 訂正されたnoteは数えない。数えると訂正するほど件数が増える。
571
+ const current = chain.events
572
+ .filter((event) => !superseded.has(event.event_digest))
573
+ .sort((left, right) => right.sequence - left.sequence);
574
+ if (current.length === 0) continue;
575
+ summaries.push({
576
+ plan_key: planKey,
577
+ // `note_context.note_head_digest`はtask chainのheadを指す。同名で別のchainを指すと
578
+ // 型が同じdigestなので取り違えてもvalidatorを通る——名前で区別する(room [211])。
579
+ plan_note_head_digest: current[0].event_digest,
580
+ count: current.length,
581
+ latest: current.slice(0, TODO_LIMITS.statusPlanNoteLatest).map((event) => ({
582
+ event_digest: event.event_digest,
583
+ actor_agent: event.actor.agent,
584
+ recorded_at: event.recorded_at,
585
+ })),
586
+ // 欄だけでは読まれない。届いた先で次に何を打てばいいかを名指しする。
587
+ next_commands: [`lattice todo note list --plan ${planKey} --json`],
588
+ });
589
+ }
590
+ summaries.sort((left, right) => (
591
+ left.plan_key < right.plan_key ? -1 : left.plan_key > right.plan_key ? 1 : 0));
592
+ return summaries;
593
+ }
594
+
595
+ /** Gantt用に1 planのchain/historyを一度だけ読み、全task contextへ投影する。 */
596
+ export async function readTodoNoteContextsForPlan(options = {}) {
597
+ if (!exactRecord(options, ['repoRoot', 'store', 'planKey'])
598
+ || !isTodoIdentifier(options.planKey)
599
+ || options.store === null || typeof options.store !== 'object') {
600
+ throw new TypeError('todo note contexts read options invalid');
601
+ }
602
+ const repoRoot = path.resolve(options.repoRoot);
603
+ const member = options.store.members?.find(({ descriptor }) => (
604
+ descriptor.plan_key === options.planKey
605
+ ));
606
+ if (member === undefined) fail('NOTE_TASK_NOT_FOUND', 'note_plan_not_active', {
607
+ plan_key: options.planKey,
608
+ });
609
+ const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
610
+ const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
611
+ const migrations = await readNoteMigrations(repoRoot, options.planKey,
612
+ new Set(chain.events.map(({ plan_version: version }) => version)));
613
+ const currentTaskIds = member.plan.tasks.map(({ task_id: taskId }) => taskId);
614
+ const projected = member.plan.tasks.map((task) => projectTodoNoteContext({
615
+ projectId: member.plan.project_id,
616
+ planKey: options.planKey,
617
+ currentPlanVersion: member.plan.plan_version,
618
+ currentTaskId: task.task_id,
619
+ currentTaskIds,
620
+ events: chain.events,
621
+ planEvents: planChain.events,
622
+ migrations,
623
+ }));
624
+ return {
625
+ contexts: projected.map(({ context }) => context),
626
+ archived: projected[0]?.archived ?? [],
627
+ note_head_digest: chain.head_digest,
628
+ };
629
+ }