@quolu/lattice 0.52.3 → 0.53.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 (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. 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
+ }