@quolu/lattice 0.52.0 → 0.52.2

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