@quolu/lattice 0.115.0 → 0.116.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.
package/bin/lattice.mjs CHANGED
@@ -344,10 +344,27 @@ function workingDirectory() {
344
344
  }
345
345
  }
346
346
 
347
+ // `enable`の署名者の指定: `--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>`。key-idとargvは対で、
348
+ // どちらも無ければ今の署名者を引き継ぐ。形の違いは null(usage)。
349
+ function reportingChange(flags) {
350
+ const dash = flags.indexOf('--');
351
+ const head = dash < 0 ? flags : flags.slice(0, dash);
352
+ const command = dash < 0 ? [] : flags.slice(dash + 1);
353
+ const values = {};
354
+ for (let index = 0; index < head.length; index += 2) {
355
+ if (head[index + 1] === undefined || !['--key-id', '--signer-cwd', '--url'].includes(head[index])) return null;
356
+ values[head[index]] = head[index + 1];
357
+ }
358
+ if ((values['--key-id'] === undefined) !== (command.length === 0)) return null;
359
+ if (values['--key-id'] === undefined && values['--signer-cwd'] !== undefined) return null;
360
+ return { ...(values['--key-id'] !== undefined && { signer: { key_id: values['--key-id'], command, cwd: values['--signer-cwd'] ?? null } }),
361
+ ...(values['--url'] !== undefined && { url: values['--url'] }) };
362
+ }
363
+
347
364
  async function runRuntimeErrorsCli(rest) {
348
365
  const runtimeErrors = await import('../src/runtime-errors.mjs');
349
366
  const usage = () => {
350
- process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable|disable|verify>> --json' })}\n`);
367
+ process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify>> --json' })}\n`);
351
368
  return 2;
352
369
  };
353
370
  const options = { version: packageJson.version };
@@ -382,10 +399,12 @@ async function runRuntimeErrorsCli(rest) {
382
399
  result = await reporting.verifyRuntimeErrorReporting(options);
383
400
  process.stdout.write(`${JSON.stringify(result)}\n`);
384
401
  return result.outcome === 'verified' ? 0 : 1;
385
- } else if (words[0] === 'reporting' && words.length === 2 && ['status', 'enable', 'disable'].includes(words[1])) {
402
+ } else if (words[0] === 'reporting' && (words[1] === 'enable' || (words.length === 2 && ['status', 'disable'].includes(words[1])))) {
386
403
  const reporting = await import('../src/runtime-error-reporting.mjs');
404
+ const change = words[1] === 'enable' ? reportingChange(words.slice(2)) : {};
405
+ if (change === null) return usage();
387
406
  result = words[1] === 'status' ? reporting.runtimeErrorReportingStatus(options)
388
- : reporting.setRuntimeErrorReporting(words[1] === 'enable', options);
407
+ : reporting.setRuntimeErrorReporting(words[1] === 'enable', options, change);
389
408
  } else if (words[0] === 'report' && (words.length === 1 || (words.length === 2 && words[1] === '--auto'))) {
390
409
  // 送れなかった時も結果は1行で返す。受領まで済んだ時と、送るものが無い時だけexit 0。
391
410
  const reporting = await import('../src/runtime-error-reporting.mjs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.115.0",
3
+ "version": "0.116.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
package/src/cli-help.mjs CHANGED
@@ -269,8 +269,9 @@ Commands:
269
269
  reopen <fingerprint>
270
270
  compact
271
271
  report 未受領の記録をBugHubの受け口へ送る(送信を有効にした端末だけ)
272
- reporting <status|enable|disable>
273
- reporting verify 空の報告を1通送り、合鍵と受け口までの経路を確かめる(記録には触れない)
272
+ reporting <status|disable>
273
+ reporting enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>] 送信を有効にする(署名者はBugHub-ES256の署名を返すcommand)
274
+ reporting verify 空の報告を1通送り、署名者と受け口までの経路を確かめる(記録には触れない)
274
275
  `,
275
276
  bridge: `Usage: lattice bridge <command> [options] --json
276
277
 
@@ -449,7 +450,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
449
450
  'runtime-errors reopen': 'runtime-errors reopen <fingerprint> --json',
450
451
  'runtime-errors compact': 'runtime-errors compact --json',
451
452
  'runtime-errors report': 'runtime-errors report --json',
452
- 'runtime-errors reporting': 'runtime-errors reporting <status|enable|disable|verify> --json',
453
+ 'runtime-errors reporting': 'runtime-errors reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify> --json',
453
454
  'bridge setup': 'bridge setup --listen <IP> [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
454
455
  'bridge reconfigure': 'bridge reconfigure [--listen <IP>] [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
455
456
  'bridge status': 'bridge status --json',
@@ -1,10 +1,10 @@
1
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
1
+ import { createHash, createPublicKey, randomBytes, randomUUID, verify } from 'node:crypto';
2
+ import { spawn } from 'node:child_process';
2
3
  import {
3
- existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync,
4
+ closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync,
4
5
  } from 'node:fs';
5
6
  import http from 'node:http';
6
7
  import https from 'node:https';
7
- import { homedir, platform as hostPlatform } from 'node:os';
8
8
  import { dirname, join } from 'node:path';
9
9
 
10
10
  import {
@@ -12,6 +12,7 @@ import {
12
12
  acknowledgeRuntimeErrors,
13
13
  ensureSafeDir,
14
14
  ensureSafeFile,
15
+ readRuntimeErrorReportingConfig,
15
16
  replaceStoreFile,
16
17
  runtimeErrorCollectionSupported,
17
18
  runtimeErrorReportingConfigPath,
@@ -19,19 +20,22 @@ import {
19
20
  runtimeErrorsDiagnostics,
20
21
  runtimeErrorsSnapshot,
21
22
  runtimeErrorsStatePath,
22
- windowsLocalAppData,
23
+ validReportingSigner,
24
+ validReportingUrl,
23
25
  } from './runtime-errors.mjs';
24
26
 
25
27
  /**
26
- * runtime error記録を、Lattice自身がBugHubの製品報告の受け口へ送る(ADR 0193)。
28
+ * runtime error記録を、Lattice自身がBugHubの製品報告の受け口へ送る(ADR 0193・0197)。
27
29
  *
28
- * - 既定では通信しない。端末で`runtime-errors reporting enable`を打ち、BugHubの持ち主が合鍵のfileを
29
- * 置いた端末だけが送る。どちらかが欠ければ、networkへ触れない。
30
- * - 秘密は通信に載せない。本文のSHA-256と時刻へのHMAC-SHA256署名だけを`Authorization`に付ける。
31
- * - 受領済みにするのは、200・`accepted: true`・`report_id`一致・応答の署名一致がそろった時だけ。
32
- * そろわなければ「届いたか不明」として記録を未受領のまま残し、後から今の累計を送り直す。
30
+ * - 既定では通信しない。端末で`runtime-errors reporting enable`を打ち、署名者(`--key-id`と署名commandの
31
+ * argv)を設定した端末だけが送る。どちらかが欠ければ、networkへ触れない。
32
+ * - 秘密は端末に無い。署名の鍵は認証仲介の中だけにある。Latticeは「ts + LF + 本文SHA-256のhex」を
33
+ * 署名者commandへ渡し、返る生r‖s(ES256)を`Authorization: BugHub-ES256`に付ける。
34
+ * - 受領済みにするのは、200・`accepted: true`・`report_id`一致・応答のES256署名がBugHubの応答用公開鍵で
35
+ * 合うことがそろった時だけ。そろわなければ「届いたか不明」として記録を未受領のまま残し、後から今の累計を送り直す。
36
+ * - 署名できなければ送らない。記録は残り、届かなかった送信と同じく後から送り直す。
33
37
  * - 送るのは`runtime-errors snapshot`が出す項目だけ。message本文・path・引数・stackは記録に無い。
34
- * - `reporting verify`は、記録を載せない空の報告を1通送って、合鍵・署名・受け口までの経路を確かめる。
38
+ * - `reporting verify`は、記録を載せない空の報告を1通送って、署名者・署名・受け口までの経路を確かめる。
35
39
  * 受け口は受領を記録するだけで、issueも通知も動かない。storeの記録と受領の印には触れない。
36
40
  */
37
41
 
@@ -40,6 +44,16 @@ const RESULT_SCHEMA = 'lattice.runtime_error_report_result.v1';
40
44
  const STATUS_SCHEMA = 'lattice.runtime_error_reporting_status.v1';
41
45
  const DELIVERY_SCHEMA = 'lattice.runtime_error_delivery.v1';
42
46
  const PRODUCT_ID = 'lattice';
47
+ // BugHubの製品報告の受け口(LAN内。製品共通の1本)。設定の`url`で差し替えられる。
48
+ const DEFAULT_INTAKE_URL = 'http://192.168.1.2:39310/api/products/v1/runtime-errors';
49
+ // BugHubの応答用公開鍵(ES256)。BugHubの応答署名はこの鍵でだけ確かめる。鍵が替わる時は新版を出す。
50
+ const BUGHUB_RESPONSE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
51
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEX+kilvDhn190l4Z+iR5J4KusmOSJ
52
+ ZVBQjMaLGOshDFzUwB7IxiJsgLMpQzOdoEWM21DCBpL1QyY1COU2cmuE1g==
53
+ -----END PUBLIC KEY-----
54
+ `;
55
+ const SIGNER_TIMEOUT_MS = 30_000;
56
+ const SIGNER_OUTPUT_MAX_BYTES = 1024;
43
57
  const REQUEST_TIMEOUT_MS = 10_000;
44
58
  const RESPONSE_MAX_BYTES = 64 * 1024;
45
59
  const REPORT_MAX_BYTES = 512 * 1024;
@@ -47,95 +61,85 @@ const REPORT_MAX_RECORDS = 256;
47
61
  // BugHubは端末×製品ごとに1分に1回まで受ける。届かなかった同じ中身の送り直しは1時間に1回まで。
48
62
  const MIN_ATTEMPT_INTERVAL_MS = 60_000;
49
63
  const RETRY_INTERVAL_MS = 60 * 60_000;
50
- const KEY_ID = /^[A-Za-z0-9._:-]{1,128}$/;
51
64
  const REJECTION_CODE = /^[a-z][a-z0-9_]{0,63}$/;
52
- const OUTCOMES = Object.freeze(['delivered', 'nothing_pending', 'disabled', 'unsupported', 'credential_missing',
53
- 'credential_unsafe', 'throttled', 'rejected', 'unconfirmed', 'store_unavailable']);
65
+ const OUTCOMES = Object.freeze(['delivered', 'nothing_pending', 'disabled', 'unsupported', 'signer_missing',
66
+ 'signer_refused', 'signer_failed', 'throttled', 'rejected', 'unconfirmed', 'store_unavailable']);
54
67
 
55
68
  const plain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
56
69
  const exact = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
57
70
 
58
- /** 合鍵の置き場(BugHubの契約)。Windowsは`%LOCALAPPDATA%\bughub\product-credentials\`。 */
59
- export function productCredentialPath(env = process.env, platform = hostPlatform()) {
60
- const base = platform === 'win32' ? join(windowsLocalAppData(env), 'bughub') : join(env.HOME || homedir(), '.config', 'bughub');
61
- return join(base, 'product-credentials', `${PRODUCT_ID}.json`);
71
+ const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
72
+
73
+ /** 署名者へ渡す文字列: `ts + "\n" + SHA-256(送るバイト列)の16進`。末尾に改行は付けない。 */
74
+ export function reportSigningText(ts, bodyBytes) {
75
+ return `${ts}\n${sha256Hex(bodyBytes)}`;
62
76
  }
63
77
 
64
- /**
65
- * Windowsの合鍵が本人・SYSTEM・Administratorsだけのものか。DACLの読み取りは出力fileを置く場所が要るので、
66
- * 絞ったstoreのフォルダを使う(無ければ作る)。合鍵のフォルダへは何も書かない。
67
- */
68
- function windowsCredentialUnsafeReason(path, options) {
69
- const storeDir = dirname(options.storePath ?? runtimeErrorsStatePath(options.env ?? process.env));
78
+ /** 生r‖s(64バイト)か、そのbase64(パディングあり)を、64バイトへ直す。 */
79
+ function signatureBytes(output) {
80
+ if (output.length === 64) return output;
81
+ const text = output.toString('utf8').trim();
82
+ return /^[A-Za-z0-9+/]{86}==$/.test(text) ? Buffer.from(text, 'base64') : null;
83
+ }
84
+
85
+ /** 応答の署名: BugHubの応答用公開鍵で`report_id + "\n" + received_at`へのES256署名を確かめる。別の機器が返した200を受領済みにしない。 */
86
+ export function receiptSignatureValid(publicKeyPem, reportId, receivedAt, sig) {
87
+ if (typeof receivedAt !== 'string' || typeof sig !== 'string' || !/^[A-Za-z0-9+/]{86}==$/.test(sig)) return false;
70
88
  try {
71
- ensureSafeDir(storeDir);
89
+ return verify('sha256', Buffer.from(`${reportId}\n${receivedAt}`, 'utf8'),
90
+ { key: createPublicKey(publicKeyPem), dsaEncoding: 'ieee-p1363' }, Buffer.from(sig, 'base64'));
72
91
  } catch {
73
- return 'acl_unverifiable';
74
- }
75
- try {
76
- ensureSafeFile(path, storeDir);
77
- return null;
78
- } catch {
79
- return 'acl_not_owner_only';
92
+ return false;
80
93
  }
81
94
  }
82
95
 
83
96
  /**
84
- * 合鍵のfileを読む。BugHubの持ち主が置く形(symlinkでなく、POSIXは本人所有・0600、Windowsは
85
- * 本人・SYSTEM・Administratorsだけに権限)以外は使わない。秘密は戻り値の中だけに留め、結果や記録へ写さない。
97
+ * 署名者commandを走らせて署名を得る。入力は、storeの(本人だけの)folderに置いたfileから標準入力へ渡す
98
+ * ——pipeでは、Windowsのsshが固まる。入力fileは必ず消す。exit 1は断られた、それ以外・時間切れ・起動できない
99
+ * ・形の違う出力は失敗。結果に署名者の出力は載せない。
86
100
  */
87
- export function readProductCredential(options = {}) {
88
- const path = options.credentialPath ?? productCredentialPath(options.env ?? process.env);
89
- let stats;
90
- try {
91
- stats = lstatSync(path);
92
- } catch (error) {
93
- return error?.code === 'ENOENT' ? { status: 'missing' } : { status: 'unsafe', reason: 'unreadable' };
94
- }
95
- if (!stats.isFile() || stats.isSymbolicLink()) return { status: 'unsafe', reason: 'not_regular_file' };
96
- if (hostPlatform() === 'win32') {
97
- const reason = windowsCredentialUnsafeReason(path, options);
98
- if (reason !== null) return { status: 'unsafe', reason };
99
- } else {
100
- if ((stats.mode & 0o777) !== 0o600) return { status: 'unsafe', reason: 'mode_not_0600' };
101
- if (typeof process.getuid === 'function' && stats.uid !== process.getuid()) return { status: 'unsafe', reason: 'owner_mismatch' };
102
- }
103
- let value;
101
+ async function signWithSigner(signer, signingText, options) {
102
+ const env = options.env ?? process.env;
103
+ const dir = dirname(options.storePath ?? runtimeErrorsStatePath(env));
104
+ const input = join(dir, `.signer-input-${process.pid}-${randomBytes(6).toString('hex')}`);
105
+ let fd = null;
104
106
  try {
105
- value = JSON.parse(readFileSync(path, 'utf8'));
107
+ ensureSafeDir(dir);
108
+ writeFileSync(input, signingText, { mode: 0o600, flag: 'wx' });
109
+ fd = openSync(input, 'r');
106
110
  } catch {
107
- return { status: 'unsafe', reason: 'not_json' };
108
- }
109
- if (!plain(value) || !exact(value, ['url', 'key_id', 'secret'])
110
- || typeof value.url !== 'string' || typeof value.key_id !== 'string' || typeof value.secret !== 'string'
111
- || !KEY_ID.test(value.key_id) || value.secret.length < 16 || value.secret.length > 1024) {
112
- return { status: 'unsafe', reason: 'invalid_shape' };
111
+ if (fd !== null) closeSync(fd);
112
+ rmSync(input, { force: true });
113
+ return { outcome: 'signer_failed', reason: 'input_not_written' };
113
114
  }
114
- let url;
115
115
  try {
116
- url = new URL(value.url);
117
- } catch {
118
- return { status: 'unsafe', reason: 'invalid_url' };
119
- }
120
- if (!['http:', 'https:'].includes(url.protocol) || url.username !== '' || url.password !== '') {
121
- return { status: 'unsafe', reason: 'invalid_url' };
116
+ const run = await new Promise((resolve) => {
117
+ let child;
118
+ try {
119
+ child = spawn(signer.command[0], signer.command.slice(1), { cwd: signer.cwd ?? undefined,
120
+ stdio: [fd, 'pipe', 'ignore'], windowsHide: true });
121
+ } catch {
122
+ resolve({ reason: 'spawn_failed' });
123
+ return;
124
+ }
125
+ const chunks = [];
126
+ let size = 0;
127
+ const timer = setTimeout(() => { child.kill('SIGKILL'); resolve({ reason: 'timeout' }); }, options.signerTimeoutMs ?? SIGNER_TIMEOUT_MS);
128
+ child.stdout.on('data', (chunk) => {
129
+ size += chunk.length;
130
+ if (size <= SIGNER_OUTPUT_MAX_BYTES) chunks.push(chunk);
131
+ });
132
+ child.once('error', () => { clearTimeout(timer); resolve({ reason: 'spawn_failed' }); });
133
+ child.once('close', (code) => { clearTimeout(timer); resolve({ code, stdout: size > SIGNER_OUTPUT_MAX_BYTES ? null : Buffer.concat(chunks) }); });
134
+ });
135
+ if (run.code === 1) return { outcome: 'signer_refused', reason: 'signer_refused' };
136
+ if (run.code !== 0) return { outcome: 'signer_failed', reason: run.reason ?? 'signer_exit' };
137
+ const sig = run.stdout === null ? null : signatureBytes(run.stdout);
138
+ return sig === null ? { outcome: 'signer_failed', reason: 'signature_malformed' } : { sig };
139
+ } finally {
140
+ closeSync(fd);
141
+ rmSync(input, { force: true });
122
142
  }
123
- return { status: 'ok', credential: { url, keyId: value.key_id, secret: value.secret } };
124
- }
125
-
126
- const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
127
- const hmacHex = (secret, text) => createHmac('sha256', Buffer.from(secret, 'utf8')).update(text, 'utf8').digest('hex');
128
-
129
- /** `sig = HMAC-SHA256(secret, ts + "\n" + SHA-256(送るバイト列の16進))`。秘密は文字列のままUTF-8で鍵にする。 */
130
- export function signReport(secret, ts, bodyBytes) {
131
- return hmacHex(secret, `${ts}\n${sha256Hex(bodyBytes)}`);
132
- }
133
-
134
- /** 応答の署名: `HMAC-SHA256(secret, report_id + "\n" + received_at)`。別の機器が返した200を受領済みにしない。 */
135
- export function receiptSignatureMatches(secret, reportId, receivedAt, sig) {
136
- if (typeof receivedAt !== 'string' || typeof sig !== 'string' || !/^[0-9a-f]{64}$/.test(sig)) return false;
137
- const expected = Buffer.from(hmacHex(secret, `${reportId}\n${receivedAt}`), 'hex');
138
- return timingSafeEqual(expected, Buffer.from(sig, 'hex'));
139
143
  }
140
144
 
141
145
  /** snapshotの未受領分から、受け口へ送る本文を組む。項目はsnapshotが出すものをそのまま載せる。 */
@@ -205,14 +209,14 @@ function throttleReason(options, delivery, highWatermark) {
205
209
  export function runtimeErrorReportingStatus(options = {}) {
206
210
  const supported = runtimeErrorCollectionSupported(options);
207
211
  const enabled = runtimeErrorReportingEnabled(options);
208
- const credential = supported ? readProductCredential(options) : { status: 'missing' };
212
+ const signer = supported ? readRuntimeErrorReportingConfig(options)?.signer ?? null : null;
209
213
  const diagnostics = runtimeErrorsDiagnostics(options);
210
214
  const delivery = supported ? readDelivery(options) : emptyDelivery();
211
215
  return {
212
216
  schema: STATUS_SCHEMA,
213
217
  reporting: !supported ? 'unsupported' : enabled ? 'enabled' : 'disabled',
214
- credential: credential.status === 'ok' ? 'present' : credential.status,
215
- credential_reason: credential.status === 'unsafe' ? credential.reason : null,
218
+ signer: signer === null ? 'missing' : 'configured',
219
+ key_id: signer?.key_id ?? null,
216
220
  collection: diagnostics.collection,
217
221
  store_status: diagnostics.status,
218
222
  pending_count: diagnostics.pending_count,
@@ -221,12 +225,20 @@ export function runtimeErrorReportingStatus(options = {}) {
221
225
  };
222
226
  }
223
227
 
224
- /** 送信の設定をLattice自身のfileへ書く。dotagentsの設定は読みも書きもしない。 */
225
- export function setRuntimeErrorReporting(enabled, options = {}) {
228
+ /**
229
+ * 送信の設定をLattice自身のfileへ書く。dotagentsの設定は読みも書きもしない。
230
+ * `change.signer`・`change.url`を渡した時だけ署名者・宛先を置き換え、渡さなければ今の設定を引き継ぐ。
231
+ */
232
+ export function setRuntimeErrorReporting(enabled, options = {}, change = {}) {
226
233
  if (typeof enabled !== 'boolean') throw Error('invalid_enabled');
227
234
  if (!runtimeErrorCollectionSupported(options)) throw Error('reporting_unsupported');
235
+ if (change.signer !== undefined && !validReportingSigner(change.signer)) throw Error('invalid_signer');
236
+ if (change.url !== undefined && !validReportingUrl(change.url)) throw Error('invalid_url');
228
237
  const env = options.env ?? process.env;
229
238
  const path = options.reportingConfigPath ?? runtimeErrorReportingConfigPath(env);
239
+ const current = readRuntimeErrorReportingConfig({ ...options, reportingConfigPath: path });
240
+ const signer = change.signer ?? current?.signer ?? null;
241
+ const url = change.url ?? current?.url ?? null;
230
242
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
231
243
  try {
232
244
  if (lstatSync(path).isSymbolicLink()) throw Error('config_unsafe');
@@ -235,7 +247,8 @@ export function setRuntimeErrorReporting(enabled, options = {}) {
235
247
  }
236
248
  const temporary = join(dirname(path), `.runtime-error-reporting-${process.pid}-${randomBytes(6).toString('hex')}`);
237
249
  try {
238
- writeFileSync(temporary, `${JSON.stringify({ schema: REPORTING_CONFIG_SCHEMA, enabled })}\n`, { mode: 0o600, flag: 'wx' });
250
+ const config = { schema: REPORTING_CONFIG_SCHEMA, enabled, ...(signer && { signer }), ...(url && { url }) };
251
+ writeFileSync(temporary, `${JSON.stringify(config)}\n`, { mode: 0o600, flag: 'wx' });
239
252
  replaceStoreFile(temporary, path);
240
253
  } finally {
241
254
  rmSync(temporary, { force: true });
@@ -279,9 +292,9 @@ function parseJson(text) {
279
292
 
280
293
  /**
281
294
  * 報告を1通、署名して送り、受領を確かめる。`accepted`を返すのは、200・`accepted: true`・`report_id`一致・
282
- * 応答の署名一致がそろった時だけ。戻り値に秘密・key_id・宛先は入れない。
295
+ * 応答のES256署名一致がそろった時だけ。署名できなければ送らない。戻り値に署名・key_id・宛先は入れない。
283
296
  */
284
- async function sendReport({ url, keyId, secret }, snapshot, options) {
297
+ async function sendReport(config, snapshot, options) {
285
298
  const now = nowMs(options);
286
299
  const ts = Math.floor(now / 1000);
287
300
  // `observed_at`は、載せる記録のどの時刻よりも前にしない(BugHubは観測より後の記録を断る)。秒へ切り捨てると、
@@ -293,17 +306,21 @@ async function sendReport({ url, keyId, secret }, snapshot, options) {
293
306
  const bodyBytes = Buffer.from(JSON.stringify(report), 'utf8');
294
307
  if (bodyBytes.length > REPORT_MAX_BYTES) return { outcome: 'too_large', reason: 'report_too_large', http_status: null };
295
308
 
296
- const response = await post(url, {
309
+ const signed = await signWithSigner(config.signer, reportSigningText(ts, bodyBytes), options);
310
+ if (signed.sig === undefined) return { outcome: signed.outcome, reason: signed.reason, http_status: null };
311
+
312
+ const response = await post(new URL(options.url ?? config.url ?? DEFAULT_INTAKE_URL), {
297
313
  'Content-Type': 'application/json',
298
314
  'Content-Length': String(bodyBytes.length),
299
- Authorization: `BugHub-HMAC-SHA256 key_id=${keyId}, ts=${ts}, sig=${signReport(secret, String(ts), bodyBytes)}`,
315
+ Authorization: `BugHub-ES256 key_id=${config.signer.key_id}, ts=${ts}, sig=${signed.sig.toString('base64')}`,
300
316
  }, bodyBytes, options.timeoutMs ?? REQUEST_TIMEOUT_MS);
301
317
 
302
318
  if (response.status === null) return { outcome: 'unconfirmed', reason: response.reason, http_status: null };
303
319
  const body = parseJson(response.body);
304
320
  if (response.status === 200) {
305
321
  if (body === null || body.accepted !== true || body.report_id !== report.report_id
306
- || !receiptSignatureMatches(secret, report.report_id, body.received_at, body.sig)) {
322
+ || body.sig_alg !== 'ES256'
323
+ || !receiptSignatureValid(options.responseKeyPem ?? BUGHUB_RESPONSE_PUBLIC_KEY, report.report_id, body.received_at, body.sig)) {
307
324
  return { outcome: 'unconfirmed', reason: 'receipt_not_verified', http_status: 200 };
308
325
  }
309
326
  return { outcome: 'accepted', reason: null, http_status: 200 };
@@ -319,9 +336,8 @@ async function sendReport({ url, keyId, secret }, snapshot, options) {
319
336
  export async function reportRuntimeErrors(options = {}) {
320
337
  if (!runtimeErrorCollectionSupported(options)) return result('unsupported');
321
338
  if (!runtimeErrorReportingEnabled(options)) return result('disabled');
322
- const credential = readProductCredential(options);
323
- if (credential.status === 'missing') return result('credential_missing');
324
- if (credential.status !== 'ok') return result('credential_unsafe', { reason: credential.reason });
339
+ const config = readRuntimeErrorReportingConfig(options);
340
+ if (!config?.signer) return result('signer_missing');
325
341
 
326
342
  let pending;
327
343
  let delivery;
@@ -350,7 +366,7 @@ export async function reportRuntimeErrors(options = {}) {
350
366
  return result(outcome, { sent, acknowledged_through: pending.cursor.acknowledged_through, ...extra });
351
367
  };
352
368
 
353
- const answer = await sendReport(credential.credential, pending, options);
369
+ const answer = await sendReport(config, pending, options);
354
370
  if (answer.outcome === 'too_large') return result('rejected', { reason: 'report_too_large', sent });
355
371
  if (answer.outcome !== 'accepted') return finish(answer.outcome, { reason: answer.reason, http_status: answer.http_status });
356
372
  try {
@@ -363,26 +379,24 @@ export async function reportRuntimeErrors(options = {}) {
363
379
  }
364
380
 
365
381
  /**
366
- * 記録を載せない空の報告を1通送り、合鍵・署名・受け口までの経路を確かめる(`reporting verify`)。
367
- * 送る条件は`report`と同じで、送信を有効にしていない端末と合鍵の無い端末はnetworkへ触れない。
382
+ * 記録を載せない空の報告を1通送り、署名者・署名・受け口までの経路を確かめる(`reporting verify`)。
383
+ * 送る条件は`report`と同じで、送信を有効にしていない端末と署名者の無い端末はnetworkへ触れない。
368
384
  * storeの記録・受領の印・送る時機の記録には触れない。受け口は端末×製品ごとに1分に1回まで受けるので、
369
385
  * 直前に送っていれば429で断られる。
370
386
  */
371
387
  export async function verifyRuntimeErrorReporting(options = {}) {
372
388
  if (!runtimeErrorCollectionSupported(options)) return result('unsupported');
373
389
  if (!runtimeErrorReportingEnabled(options)) return result('disabled');
374
- const credential = readProductCredential(options);
375
- if (credential.status === 'missing') return result('credential_missing');
376
- if (credential.status !== 'ok') return result('credential_unsafe', { reason: credential.reason });
377
- const answer = await sendReport(credential.credential, { runtime_errors: [], resolutions: [] }, options);
390
+ const config = readRuntimeErrorReportingConfig(options);
391
+ if (!config?.signer) return result('signer_missing');
392
+ const answer = await sendReport(config, { runtime_errors: [], resolutions: [] }, options);
378
393
  if (answer.outcome === 'accepted') return result('verified', { http_status: 200 });
379
394
  return result(answer.outcome, { reason: answer.reason, http_status: answer.http_status });
380
395
  }
381
396
 
382
397
  /**
383
398
  * 自動送信の入口が、子processを起こす前に見る軽い判定。設定が無い端末(外の利用者)では、
384
- * 設定fileの有無を1回見るだけで終わる。合鍵は、送るものがある時だけ確かめる——Windowsでは
385
- * 合鍵の確認が外のprogramを起こすので、毎回のCLI実行には載せない。
399
+ * 設定fileの有無を1回見るだけで終わる。署名者commandは、送る時だけ走らせる——毎回のCLI実行には載せない。
386
400
  */
387
401
  export function runtimeErrorAutoReportDue(options = {}) {
388
402
  if (!runtimeErrorReportingEnabled(options)) return false;
@@ -390,7 +404,7 @@ export function runtimeErrorAutoReportDue(options = {}) {
390
404
  const diagnostics = runtimeErrorsDiagnostics(options);
391
405
  if (diagnostics.status !== 'ready' || diagnostics.pending_count === 0) return false;
392
406
  if (throttleReason(options, readDelivery(options), diagnostics.high_watermark) !== null) return false;
393
- return readProductCredential(options).status === 'ok';
407
+ return readRuntimeErrorReportingConfig(options)?.signer != null;
394
408
  } catch {
395
409
  return false;
396
410
  }
@@ -114,27 +114,55 @@ export function runtimeErrorReportingConfigPath(env = process.env, platform = ho
114
114
  return join(env.HOME || homedir(), '.config', 'lattice', 'runtime-error-reporting.json');
115
115
  }
116
116
 
117
+ /** 署名者の設定(秘密なし)。key_idはBugHubの発行名、commandはargv(shellを通さない)、cwdは認証仲介が呼び出し元として見るfolder。 */
118
+ const SIGNER_KEY_ID = /^[A-Za-z0-9._:-]{1,128}$/;
119
+ const text = (value) => typeof value === 'string' && value.length >= 1 && value.length <= 4096 && !value.includes('\0');
120
+ export function validReportingSigner(value) {
121
+ return plain(value) && exact(value, ['key_id', 'command', 'cwd'])
122
+ && typeof value.key_id === 'string' && SIGNER_KEY_ID.test(value.key_id)
123
+ && Array.isArray(value.command) && value.command.length >= 1 && value.command.length <= 64 && value.command.every(text)
124
+ && (value.cwd === null || text(value.cwd));
125
+ }
126
+
127
+ export function validReportingUrl(value) {
128
+ try {
129
+ const url = new URL(value);
130
+ return typeof value === 'string' && value.length <= 2048 && ['http:', 'https:'].includes(url.protocol) && url.username === '' && url.password === '';
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
117
136
  /**
118
- * Lattice自身の送信設定(ADR 0193)。端末で`runtime-errors reporting enable`を打った時だけ有効になる。
137
+ * Lattice自身の送信設定(ADR 0193・0197)。端末で`runtime-errors reporting enable`を打った時だけ有効になる。
138
+ * `signer`(BugHub-ES256の署名者)と`url`(既定の受け口の差し替え)は任意。形の違う`signer`・`url`は無いものとして読む。
119
139
  * `LATTICE_RUNTIME_ERROR_REPORTING=0`は既定の置き場を読まない——試験と自動化が、その端末の本物の設定を
120
140
  * 拾って送信しないための口。`options.reportingConfigPath`を明示した呼び出しはそのfileを読む。
141
+ * 設定が無い・読めない・形が違う時は`null`。
121
142
  */
122
- export function runtimeErrorReportingEnabled(options = {}) {
123
- if (!collectionSupported(options)) return false;
143
+ export function readRuntimeErrorReportingConfig(options = {}) {
144
+ if (!collectionSupported(options)) return null;
124
145
  const env = options.env ?? process.env;
125
- if (options.reportingConfigPath === undefined && env.LATTICE_RUNTIME_ERROR_REPORTING === '0') return false;
146
+ if (options.reportingConfigPath === undefined && env.LATTICE_RUNTIME_ERROR_REPORTING === '0') return null;
126
147
  try {
127
148
  const path = options.reportingConfigPath ?? runtimeErrorReportingConfigPath(env);
128
149
  const stats = lstatSync(path);
129
- if (!stats.isFile() || stats.isSymbolicLink()) return false;
150
+ if (!stats.isFile() || stats.isSymbolicLink()) return null;
130
151
  const config = JSON.parse(readFileSync(path, 'utf8'));
131
- return plain(config) && exact(config, ['schema', 'enabled'])
132
- && config.schema === REPORTING_CONFIG_SCHEMA && config.enabled === true;
152
+ if (!plain(config) || !Object.keys(config).every((key) => ['schema', 'enabled', 'signer', 'url'].includes(key))
153
+ || config.schema !== REPORTING_CONFIG_SCHEMA || typeof config.enabled !== 'boolean') return null;
154
+ return { enabled: config.enabled,
155
+ signer: validReportingSigner(config.signer) ? config.signer : null,
156
+ url: validReportingUrl(config.url) ? config.url : null };
133
157
  } catch {
134
- return false;
158
+ return null;
135
159
  }
136
160
  }
137
161
 
162
+ export function runtimeErrorReportingEnabled(options = {}) {
163
+ return readRuntimeErrorReportingConfig(options)?.enabled === true;
164
+ }
165
+
138
166
  function collectionEnabled(options = {}) {
139
167
  return factoryCollectionEnabled(options) || runtimeErrorReportingEnabled(options);
140
168
  }
@@ -240,7 +268,7 @@ export function ensureSafeDir(dir) {
240
268
 
241
269
  /**
242
270
  * `scratchDir`はWindowsだけが使う: DACLの読み取りが出力fileを置くフォルダ。既定はそのfileのフォルダ。
243
- * storeの外のfile(合鍵)を確かめる時は、絞ってあるstoreのフォルダを渡す。
271
+ * storeの外のfileを確かめる時は、絞ってあるfolderを渡す。
244
272
  */
245
273
  export function ensureSafeFile(path, scratchDir = dirname(path)) {
246
274
  const stats = lstatSync(path);
package/src/todo-cli.mjs CHANGED
@@ -200,6 +200,7 @@ import {
200
200
  appendTodoNote,
201
201
  readTodoNoteContext,
202
202
  readTodoNoteContextsForPlan,
203
+ readTodoNoteSource,
203
204
  readTodoNoteEvents,
204
205
  readTodoPlanNotesForStatus,
205
206
  } from './todo-note-store.mjs';
@@ -2935,11 +2936,16 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
2935
2936
  const body = inputRef === null ? message : await readNoteTextInput(repoRoot, inputRef);
2936
2937
  // 訂正はscopeを跨げない。plan noteはplan chainの中だけ、task noteは自分のtaskの中だけを
2937
2938
  // 訂正できる。contextはplan noteも載せるので、task側はscopeで絞らないと跨げてしまう。
2938
- const eligibleSupersedes = task === null
2939
- ? (await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' })).events
2940
- .map(({ event_digest: digest }) => digest)
2941
- : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id }))
2942
- .history.filter(({ scope }) => scope === 'task').map(({ event_digest: digest }) => digest);
2939
+ // w2: the note chains and the version lineage are read once, before anything is written (a broken history still refuses first),
2940
+ // and the context is projected once, after the append. Only a correction needs the history before it (eligibleSupersedes
2941
+ // is read only when supersedes is set).
2942
+ const source = task === null ? null : await readTodoNoteSource({ repoRoot, store, planKey, taskId: task.task_id });
2943
+ let eligibleSupersedes = [];
2944
+ if (supersedes !== null) {
2945
+ eligibleSupersedes = task === null
2946
+ ? (await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' })).events.map(({ event_digest: digest }) => digest)
2947
+ : source.project().history.filter(({ scope }) => scope === 'task').map(({ event_digest: digest }) => digest);
2948
+ }
2943
2949
  const event = await appendTodoNote({
2944
2950
  repoRoot,
2945
2951
  projectId: store.project_id,
@@ -2954,8 +2960,7 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
2954
2960
  });
2955
2961
  // plan noteはどのtaskのcontextにも載るので、1つを選んで返すと嘘になる。全部読むなら
2956
2962
  // `note list --plan <k>`。書けたことの証拠はeventそのものが持つ。
2957
- const context = task === null
2958
- ? null : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id })).context;
2963
+ const context = source === null ? null : source.project([event]).context;
2959
2964
  const result = {
2960
2965
  schema: 'lattice.todo_note_append_result.v2',
2961
2966
  project_id: store.project_id,
@@ -9,6 +9,7 @@ import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
9
9
  import { normalizeCheckoutEol } from './todo-store-view.mjs';
10
10
  import { memoByFileIdentity } from './todo-version-memo.mjs';
11
11
  import { TODO_VERSION_COMPACT_FILE, readVersionCompact } from './todo-version-compact.mjs';
12
+ import { publishDerivedPlanCache, readDerivedPlanCache } from './todo-store.mjs';
12
13
 
13
14
  import {
14
15
  TODO_LIMITS,
@@ -338,50 +339,83 @@ function noteProjectionEntry(event, supersededBy) {
338
339
  };
339
340
  }
340
341
 
341
- function migrationIndex(migrations) {
342
+ /**
343
+ * One migration's entries that change a task, `[from, to | null]` (null: removed). A migration lists every task of its
344
+ * predecessor (the writer refuses an incomplete one: predecessor_task_migration_incomplete), so an entry that keeps the id
345
+ * says nothing and is left out; this is what keeps the lineage small on a plan with thousands of tasks and versions.
346
+ */
347
+ function changedTaskMoves(taskMigration, planVersion) {
348
+ const seen = new Set();
349
+ const moves = [];
350
+ for (const entry of taskMigration) {
351
+ const to = entry?.to_task_id === 'removed' ? null : entry?.to_task_id;
352
+ if (!isTodoIdentifier(entry?.from_task_id) || !(to === null || isTodoIdentifier(to)) || seen.has(entry.from_task_id)) {
353
+ fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid', { plan_version: planVersion });
354
+ }
355
+ seen.add(entry.from_task_id);
356
+ if (to !== entry.from_task_id) moves.push([entry.from_task_id, to]);
357
+ }
358
+ return moves;
359
+ }
360
+
361
+ /**
362
+ * w2-impl: where a note's origin (plan version, task) ends up at the head, without walking every later version per note.
363
+ * `versions` runs from the oldest version to the head along the predecessor chain; `moves` are `[index, from, to | null]`:
364
+ * the migration from versions[index] to versions[index + 1] renamed or removed `from`, in ascending index order.
365
+ */
366
+ class NoteLineage {
367
+ constructor(versions, moves) {
368
+ this.versions = versions;
369
+ this.positions = new Map(versions.map((version, index) => [version, index]));
370
+ this.moves = new Map();
371
+ for (const [index, from, to] of moves) {
372
+ if (!this.moves.has(from)) this.moves.set(from, []);
373
+ this.moves.get(from).push([index, to]);
374
+ }
375
+ }
376
+
377
+ /** The head task id that `taskId` of `version` became (callers check it is still in the plan), or null: removed, or a version off the chain. */
378
+ resolve(version, taskId) {
379
+ let index = this.positions.get(version);
380
+ if (index === undefined) return null;
381
+ for (let task = taskId; ;) {
382
+ // shortcut: linear in the task's own moves (a few), upgrade if one task is renamed thousands of times
383
+ const move = this.moves.get(task)?.find(([at]) => at >= index);
384
+ if (move === undefined) return task;
385
+ if (move[1] === null) return null;
386
+ [index, task] = [move[0] + 1, move[1]];
387
+ }
388
+ }
389
+ }
390
+
391
+ /** The lineage of a hand-made migration list (the pure projector's input): its chain ending at `head`; versions off that chain resolve to null. */
392
+ function lineageFromMigrations(migrations, head) {
342
393
  if (!Array.isArray(migrations)) throw new TypeError('todo note migrations must be an array');
343
- const index = new Map();
394
+ const byTo = new Map();
395
+ const froms = new Set();
344
396
  for (const migration of migrations) {
345
397
  if (!exactRecord(migration, ['from_plan_version', 'to_plan_version', 'task_migration'])
346
398
  || !isTodoIdentifier(migration.from_plan_version)
347
399
  || !isTodoIdentifier(migration.to_plan_version)
348
400
  || migration.from_plan_version === migration.to_plan_version
349
401
  || !Array.isArray(migration.task_migration)
350
- || index.has(migration.from_plan_version)) {
402
+ || froms.has(migration.from_plan_version) || byTo.has(migration.to_plan_version)) {
351
403
  fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
352
404
  }
353
- const taskMap = new Map();
354
- for (const entry of migration.task_migration) {
355
- if (!exactRecord(entry, ['from_task_id', 'to_task_id'])
356
- || !isTodoIdentifier(entry.from_task_id)
357
- || !(entry.to_task_id === null || isTodoIdentifier(entry.to_task_id))
358
- || taskMap.has(entry.from_task_id)) {
359
- fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid');
360
- }
361
- taskMap.set(entry.from_task_id, entry.to_task_id === 'removed' ? null : entry.to_task_id);
362
- }
363
- index.set(migration.from_plan_version, {
364
- toPlanVersion: migration.to_plan_version, taskMap,
365
- });
405
+ froms.add(migration.from_plan_version);
406
+ byTo.set(migration.to_plan_version, { from: migration.from_plan_version,
407
+ moves: changedTaskMoves(migration.task_migration, migration.to_plan_version) });
366
408
  }
367
- return index;
368
- }
369
-
370
- function resolveNoteTarget(event, { currentPlanVersion, currentTaskIds, migrations }) {
371
- let version = event.plan_version;
372
- let taskId = event.task_id;
373
- const seen = new Set();
374
- while (version !== currentPlanVersion) {
375
- if (seen.has(version)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
376
- seen.add(version);
377
- const step = migrations.get(version);
378
- if (step === undefined) return { kind: 'archived' };
379
- const nextTaskId = step.taskMap.get(taskId);
380
- if (nextTaskId === undefined || nextTaskId === null) return { kind: 'archived' };
381
- version = step.toPlanVersion;
382
- taskId = nextTaskId;
409
+ const versions = [head];
410
+ const steps = [];
411
+ for (let version = head; byTo.has(version);) {
412
+ const step = byTo.get(version);
413
+ if (versions.includes(step.from)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
414
+ versions.unshift(step.from);
415
+ steps.unshift(step.moves);
416
+ version = step.from;
383
417
  }
384
- return currentTaskIds.has(taskId) ? { kind: 'active', taskId } : { kind: 'archived' };
418
+ return new NoteLineage(versions, steps.flatMap((moves, index) => moves.map(([from, to]) => [index, from, to])));
385
419
  }
386
420
 
387
421
  /**
@@ -401,7 +435,8 @@ export function projectTodoNoteContext(options = {}) {
401
435
  throw new TypeError('todo note projection options invalid');
402
436
  }
403
437
  const currentTaskIds = new Set(options.currentTaskIds);
404
- const migrations = migrationIndex(options.migrations);
438
+ const lineage = options.migrations instanceof NoteLineage
439
+ ? options.migrations : lineageFromMigrations(options.migrations, options.currentPlanVersion);
405
440
  // 訂正はscopeを跨げないので、supersedeの追跡もchainごとに閉じる。
406
441
  const supersededBy = new Map();
407
442
  for (const event of [...options.events, ...options.planEvents]) {
@@ -418,11 +453,9 @@ export function projectTodoNoteContext(options = {}) {
418
453
  const planSequence = sequenceOf(options.planEvents);
419
454
  for (const event of options.events) {
420
455
  const entry = noteProjectionEntry(event, supersededBy.get(event.event_digest));
421
- const target = resolveNoteTarget(event, {
422
- currentPlanVersion: options.currentPlanVersion, currentTaskIds, migrations,
423
- });
424
- if (target.kind === 'archived') archived.push(entry);
425
- else if (target.taskId === options.currentTaskId) taskCurrent.push(entry);
456
+ const target = lineage.resolve(event.plan_version, event.task_id);
457
+ if (target === null || !currentTaskIds.has(target)) archived.push(entry);
458
+ else if (target === options.currentTaskId) taskCurrent.push(entry);
426
459
  }
427
460
  // plan noteは特定のtaskに属さないので、task migrationで宛先を失うことがない。全taskの
428
461
  // contextへ載せる——工程レベルの義務は「次に着手する誰か」へ届くべきもので、誰が着手するかは
@@ -498,80 +531,125 @@ async function readCanonicalJson(ref, { missing = false } = {}) {
498
531
  return value;
499
532
  }
500
533
 
501
- async function readNoteMigrations(repoRoot, planKey, eventVersions) {
502
- const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
503
- let entries;
504
- try { entries = await readdir(base, { withFileTypes: true }); }
505
- catch (error) {
506
- if (error?.code === 'ENOENT' && eventVersions.size === 0) return [];
507
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_unreadable', { plan_key: planKey });
508
- }
509
- const versions = new Set();
510
- const migrations = [];
511
- for (const entry of entries) {
512
- if (!entry.isDirectory() || !isTodoIdentifier(entry.name)) {
513
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
514
- }
515
- const versionRoot = path.join(base, entry.name);
516
- const planPath = path.join(versionRoot, 'plan.json');
517
- const revisionPath = path.join(versionRoot, 'revision.json');
518
- const compactPath = path.join(versionRoot, TODO_VERSION_COMPACT_FILE);
519
- // perf-store: validated once per process while the files are unchanged (todo-version-memo).
520
- const version = await memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
521
- // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
522
- const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
523
- 'note_historical_plan_invalid', { plan_version: entry.name }));
524
- if (compact !== null) {
525
- if (compact.plan_key !== planKey || compact.plan_version !== entry.name) {
526
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
527
- }
528
- const migration = compact.revision?.task_migration;
529
- if (compact.revision === null) return { migration: null };
530
- if (compact.predecessor_plan_version === null || !Array.isArray(migration)) {
531
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
532
- }
533
- return { migration: { from_plan_version: compact.predecessor_plan_version, to_plan_version: entry.name,
534
- task_migration: migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
535
- from_task_id: fromTaskId, to_task_id: toTaskId })) } };
536
- }
537
- // A revision directory is published before manifest activation. A crash during
538
- // that window can leave an unreferenced directory containing only a journal
539
- // stub. It is not a historical plan until its canonical plan artifact exists.
540
- // Do not make that unreachable residue poison note projection; if a note event
541
- // names this version, the origin-version check below still fails closed.
542
- const plan = await readCanonicalJson(planPath, { missing: true });
543
- if (plan === null) return null;
544
- if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
545
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
534
+ /**
535
+ * One retained version as the lineage needs it: `{predecessor, moves}` (its predecessor's version name, null for the first
536
+ * version, and `changedTaskMoves` of the migration into it), or null when the version does not exist.
537
+ */
538
+ function readVersionMigration(base, name, planKey) {
539
+ const versionRoot = path.join(base, name);
540
+ const planPath = path.join(versionRoot, 'plan.json');
541
+ const revisionPath = path.join(versionRoot, 'revision.json');
542
+ const compactPath = path.join(versionRoot, TODO_VERSION_COMPACT_FILE);
543
+ // perf-store: validated once per process while the files are unchanged (todo-version-memo). w2: the memo holds only the
544
+ // moves, not the whole 3,321-entry task_migration (that array times 4,204 versions was the 1.6 GB).
545
+ return memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
546
+ const record = (predecessor, taskMigration) => {
547
+ if (predecessor === name) fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
548
+ return { predecessor, moves: changedTaskMoves(taskMigration, name) };
549
+ };
550
+ // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
551
+ const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
552
+ 'note_historical_plan_invalid', { plan_version: name }));
553
+ if (compact !== null) {
554
+ if (compact.plan_key !== planKey || compact.plan_version !== name) {
555
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: name });
546
556
  }
547
- const revision = await readCanonicalJson(revisionPath, { missing: true });
548
- if (revision === null) return { migration: null };
549
- if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
550
- || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
551
- || !Array.isArray(revision.task_migration)) {
552
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
557
+ if (compact.revision === null) return { predecessor: null, moves: [] };
558
+ if (compact.predecessor_plan_version === null || !Array.isArray(compact.revision?.task_migration)) {
559
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: name });
553
560
  }
554
- return { migration: {
555
- from_plan_version: revision.predecessor.plan_version,
556
- to_plan_version: entry.name,
557
- task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
558
- from_task_id: fromTaskId, to_task_id: toTaskId,
559
- })),
560
- } };
561
+ return record(compact.predecessor_plan_version, compact.revision.task_migration);
562
+ }
563
+ // A revision directory is published before manifest activation. A crash during
564
+ // that window can leave an unreferenced directory containing only a journal
565
+ // stub. It is not a historical plan until its canonical plan artifact exists.
566
+ // Do not make that unreachable residue poison note projection; if a note event
567
+ // names this version, the origin-version check below still fails closed.
568
+ const plan = await readCanonicalJson(planPath, { missing: true });
569
+ if (plan === null) return null;
570
+ if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== name) {
571
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: name });
572
+ }
573
+ const revision = await readCanonicalJson(revisionPath, { missing: true });
574
+ if (revision === null) return { predecessor: null, moves: [] };
575
+ if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
576
+ || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
577
+ || !Array.isArray(revision.task_migration)) {
578
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: name });
579
+ }
580
+ return record(revision.predecessor.plan_version, revision.task_migration);
581
+ });
582
+ }
583
+
584
+ const LINEAGE_CACHE_DIRECTORY = '.lattice/generated/store-note-lineage';
585
+ const LINEAGE_CACHE_SCHEMA = 'lattice.todo_note_lineage_cache.v1';
586
+ // shortcut: a shorter chain reads in well under 0.1 s, so an ordinary `todo start` on a small plan leaves no file in a user's git tree; upgrade if a short chain gets slow
587
+ const LINEAGE_CACHE_MIN_VERSIONS = 32;
588
+
589
+ /** The cached `{versions, moves}` of a plan's lineage up to some head, or null for any miss (absent, unreadable, wrong plan, bad digest, bad shape). */
590
+ async function readLineageCache(root, planKey) {
591
+ const body = await readDerivedPlanCache(root, LINEAGE_CACHE_DIRECTORY, LINEAGE_CACHE_SCHEMA, planKey);
592
+ if (body === null || !Array.isArray(body.versions) || body.versions.length === 0
593
+ || !body.versions.every(isTodoIdentifier) || new Set(body.versions).size !== body.versions.length
594
+ || !Array.isArray(body.moves) || !body.moves.every((move, at) => Array.isArray(move) && move.length === 3
595
+ && Number.isInteger(move[0]) && move[0] >= 0 && move[0] < body.versions.length - 1
596
+ && (at === 0 || move[0] >= body.moves[at - 1][0])
597
+ && isTodoIdentifier(move[1]) && (move[2] === null || isTodoIdentifier(move[2])))) return null;
598
+ return body;
599
+ }
600
+
601
+ /**
602
+ * w2-impl: the lineage of `headVersion`, from the head back along its predecessors. Derived cache
603
+ * `.lattice/generated/store-note-lineage/<plan_key>.json` (best effort, never truth: any miss reads the chain; a failed write
604
+ * never fails the read; written only for a chain of at least LINEAGE_CACHE_MIN_VERSIONS versions): a cached head equal
605
+ * to this one costs no version read, a head some revisions later reads only the versions after the cached head. Only a chain
606
+ * that reaches the first version (or the cached head, itself rooted) is cached, so a version directory that is missing for a
607
+ * while can never leave a short lineage behind. Versions off the head's chain
608
+ * (unpublished residue) are not read; a note naming a version that does not exist at all is still refused.
609
+ */
610
+ async function readNoteLineage(repoRoot, planKey, headVersion, eventVersions) {
611
+ const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
612
+ const lineage = await memoByFileIdentity([path.join(base, headVersion, 'plan.json')], async () => {
613
+ const cached = await readLineageCache(repoRoot, planKey);
614
+ const stop = cached?.versions.at(-1) ?? null;
615
+ if (stop === headVersion) return new NoteLineage(cached.versions, cached.moves);
616
+ const fresh = []; // newest first
617
+ for (let name = headVersion, seen = new Set(); name !== null && name !== stop;) {
618
+ if (seen.has(name)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
619
+ seen.add(name);
620
+ const record = await readVersionMigration(base, name, planKey);
621
+ if (record === null) break;
622
+ fresh.push({ name, ...record });
623
+ name = record.predecessor;
624
+ }
625
+ fresh.reverse();
626
+ const extends_ = stop !== null && fresh[0]?.predecessor === stop;
627
+ const rooted = extends_ || fresh[0]?.predecessor === null;
628
+ const versions = [...(extends_ ? cached.versions : []), ...fresh.map(({ name }) => name)];
629
+ const moves = extends_ ? [...cached.moves] : [];
630
+ fresh.forEach(({ moves: changed }, at) => {
631
+ const index = (extends_ ? cached.versions.length : 0) + at - 1; // the migration into this version
632
+ if (index >= 0) for (const [from, to] of changed) moves.push([index, from, to]);
561
633
  });
562
- if (version === null) continue;
563
- versions.add(entry.name);
564
- // The memoized migration is only read (migrationIndex copies it into its own Map), so it is shared, not cloned.
565
- if (version.migration !== null) migrations.push(version.migration);
566
- }
567
- if ([...eventVersions].some((version) => !versions.has(version))) {
568
- fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
634
+ if (rooted && fresh.length > 0 && versions.length >= LINEAGE_CACHE_MIN_VERSIONS) {
635
+ await publishDerivedPlanCache(repoRoot, LINEAGE_CACHE_DIRECTORY, { schema: LINEAGE_CACHE_SCHEMA, plan_key: planKey,
636
+ versions, moves }).catch(() => {});
637
+ }
638
+ return new NoteLineage(versions, moves);
639
+ }, 'note-lineage');
640
+ for (const version of eventVersions) {
641
+ if (!lineage.positions.has(version) && await readVersionMigration(base, version, planKey) === null) {
642
+ fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
643
+ }
569
644
  }
570
- return migrations;
645
+ return lineage;
571
646
  }
572
647
 
573
- /** active store memberと歴史revisionから、通常供給用contextを一回で読む。 */
574
- export async function readTodoNoteContext(options = {}) {
648
+ /**
649
+ * active store memberと歴史revisionから、1 taskのnote contextの素材を一回で読む。`project(extra)`がcontextを作る。
650
+ * `extra`は読んだ後に積んだtask note(appendNoteが今書いたもの)で、素材を読み直さずに入れる。
651
+ */
652
+ export async function readTodoNoteSource(options = {}) {
575
653
  if (!exactRecord(options, ['repoRoot', 'store', 'planKey', 'taskId'])
576
654
  || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.taskId)
577
655
  || options.store === null || typeof options.store !== 'object') {
@@ -590,18 +668,22 @@ export async function readTodoNoteContext(options = {}) {
590
668
  });
591
669
  const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
592
670
  const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
593
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
671
+ const lineage = await readNoteLineage(repoRoot, options.planKey, member.plan.plan_version,
594
672
  new Set(chain.events.map(({ plan_version: version }) => version)));
595
- return projectTodoNoteContext({
673
+ return { project: (extra = []) => projectTodoNoteContext({
596
674
  projectId: member.plan.project_id,
597
675
  planKey: options.planKey,
598
676
  currentPlanVersion: member.plan.plan_version,
599
677
  currentTaskId: task.task_id,
600
678
  currentTaskIds: member.plan.tasks.map(({ task_id: taskId }) => taskId),
601
- events: chain.events,
679
+ events: [...chain.events, ...extra],
602
680
  planEvents: planChain.events,
603
- migrations,
604
- });
681
+ migrations: lineage,
682
+ }) };
683
+ }
684
+
685
+ export async function readTodoNoteContext(options = {}) {
686
+ return (await readTodoNoteSource(options)).project();
605
687
  }
606
688
 
607
689
  /**
@@ -676,7 +758,7 @@ export async function readTodoNoteContextsForPlan(options = {}) {
676
758
  });
677
759
  const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
678
760
  const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
679
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
761
+ const migrations = await readNoteLineage(repoRoot, options.planKey, member.plan.plan_version,
680
762
  new Set(chain.events.map(({ plan_version: version }) => version)));
681
763
  const currentTaskIds = member.plan.tasks.map(({ task_id: taskId }) => taskId);
682
764
  const projected = member.plan.tasks.map((task) => projectTodoNoteContext({
@@ -2039,36 +2039,49 @@ function taskAddedGenesis(event) {
2039
2039
  }
2040
2040
 
2041
2041
  const TASK_ADDED_CACHE_DIRECTORY = '.lattice/generated/store-task-added';
2042
- const TASK_ADDED_CACHE_SCHEMA = 'lattice.todo_task_added_cache.v1';
2042
+ const TASK_ADDED_CACHE_SCHEMA = 'lattice.todo_task_added_cache.v2'; // v1 held null for plan-create tasks; a v1 file is a miss
2043
2043
 
2044
- /** The cached `task_id -> [at, agent] | null` of one plan head, or null for any miss (absent, unreadable, wrong plan, bad digest). */
2045
- async function readTaskAddedCache(root, planKey) {
2044
+ /**
2045
+ * A derived per-plan cache file `<directory>/<plan_key>.json` (a body plus its `cache_digest`), or null for any miss: absent,
2046
+ * unreadable, wrong schema or plan, bad digest. Derived data is never truth: a miss is a recomputation (n3, w2).
2047
+ */
2048
+ export async function readDerivedPlanCache(root, directory, schema, planKey) {
2046
2049
  try {
2047
- const bytes = await readFile(path.resolve(root, TASK_ADDED_CACHE_DIRECTORY, `${planKey}.json`));
2050
+ const bytes = await readFile(path.resolve(root, directory, `${planKey}.json`));
2048
2051
  if (bytes.length > TODO_LIMITS.snapshotBytes) return null;
2049
2052
  const { cache_digest: digest, ...body } = JSON.parse(bytes.toString('utf8'));
2050
- if (body.schema !== TASK_ADDED_CACHE_SCHEMA || body.plan_key !== planKey || typeof body.head_plan_digest !== 'string'
2051
- || body.tasks === null || typeof body.tasks !== 'object' || digest !== sha256Bytes(Buffer.from(JSON.stringify(body), 'utf8'))) return null;
2052
- return { head: body.head_plan_digest, tasks: new Map(Object.entries(body.tasks)) };
2053
+ return body.schema === schema && body.plan_key === planKey && digest === sha256Bytes(Buffer.from(JSON.stringify(body), 'utf8')) ? body : null;
2053
2054
  } catch { return null; }
2054
2055
  }
2055
2056
 
2056
- async function publishTaskAddedCache(repoRoot, plan, added) {
2057
+ /** Atomically writes `body` (with `schema` and `plan_key`) as the derived cache of its plan. Callers ignore a failure: a lost write is a later recomputation. */
2058
+ export async function publishDerivedPlanCache(repoRoot, directory, body) {
2057
2059
  const root = await canonicalRepoRoot(repoRoot); // macOS tmp is a symlink: ensureGeneratedDirectory wants the real path
2058
- const ref = `${TASK_ADDED_CACHE_DIRECTORY}/${plan.plan_key}.json`;
2060
+ const ref = `${directory}/${body.plan_key}.json`;
2059
2061
  await ensureGeneratedDirectory(root, ref);
2060
- const body = { schema: TASK_ADDED_CACHE_SCHEMA, plan_key: plan.plan_key, head_plan_digest: plan.plan_digest,
2061
- tasks: Object.fromEntries(plan.tasks.map(({ task_id: id }) => [id, added.has(id) ? [added.get(id).at, added.get(id).agent] : null])) };
2062
2062
  const text = JSON.stringify(body);
2063
2063
  await atomicWrite(path.resolve(root, ref), Buffer.from(`${text.slice(0, -1)},"cache_digest":"${sha256Bytes(Buffer.from(text, 'utf8'))}"}`, 'utf8'));
2064
2064
  }
2065
2065
 
2066
+ /** The cached `task_id -> [at, agent] | null` of one plan head, or null for any miss. */
2067
+ async function readTaskAddedCache(root, planKey) {
2068
+ const body = await readDerivedPlanCache(root, TASK_ADDED_CACHE_DIRECTORY, TASK_ADDED_CACHE_SCHEMA, planKey);
2069
+ if (body === null || typeof body.head_plan_digest !== 'string' || body.tasks === null || typeof body.tasks !== 'object') return null;
2070
+ return { head: body.head_plan_digest, tasks: new Map(Object.entries(body.tasks)) };
2071
+ }
2072
+
2073
+ function publishTaskAddedCache(repoRoot, plan, added) {
2074
+ return publishDerivedPlanCache(repoRoot, TASK_ADDED_CACHE_DIRECTORY, { schema: TASK_ADDED_CACHE_SCHEMA, plan_key: plan.plan_key,
2075
+ head_plan_digest: plan.plan_digest,
2076
+ tasks: Object.fromEntries(plan.tasks.map(({ task_id: id }) => [id, added.has(id) ? [added.get(id).at, added.get(id).agent] : null])) });
2077
+ }
2078
+
2066
2079
  /**
2067
2080
  * n3-store-task-added: who added each task and when, for the member's active plan, from the retained revisions. A task is
2068
2081
  * new in a version when it is not a `to_task_id` of that version's genesis `task_migration`; a carried one follows
2069
2082
  * `to_task_id` -> `from_task_id` into the predecessor (two from ids onto one id: the first wins). One pass back along
2070
2083
  * `predecessor_plan_digest` resolves every task: `{at, agent}` = that genesis's `recorded_at` and `actor.agent` (null
2071
- * when absent). A task that came with plan create has no entry. Read only for the Store: a missing or unreadable version ends
2084
+ * when absent). A task that came with plan create gets the first version's genesis (the plan's creator). Read only for the Store: a missing or unreadable version ends
2072
2085
  * the walk and leaves the tasks not yet resolved without an entry. A walk that reached the first version is kept in the
2073
2086
  * derived `.lattice/generated/store-task-added/<plan_key>.json` (best effort, never truth: a miss walks), so the next
2074
2087
  * revision's read stops at the cached head after its own genesis. Memoized per process by the active plan.json's identity.
@@ -2079,7 +2092,9 @@ export async function readTodoTaskAdded({ repoRoot = process.cwd(), member }) {
2079
2092
  return memoByFileIdentity([path.resolve(root, member.descriptor.plan_ref)], async () => {
2080
2093
  const added = new Map();
2081
2094
  let genesis = taskAddedGenesis(member.journal.events[0]);
2082
- if (genesis === null || genesis.predecessor === null) return added;
2095
+ if (genesis === null) return added;
2096
+ const created = (tasks) => { for (const task of tasks) added.set(task, { at: genesis.at, agent: genesis.agent }); };
2097
+ if (genesis.predecessor === null) { created(plan.tasks.map(({ task_id: id }) => id)); return added; }
2083
2098
  const cache = await readTaskAddedCache(root, plan.plan_key);
2084
2099
  const fromCache = (id, tasks) => {
2085
2100
  const entry = cache.tasks.get(id);
@@ -2112,8 +2127,8 @@ export async function readTodoTaskAdded({ repoRoot = process.cwd(), member }) {
2112
2127
  const predecessor = byDigest.get(genesis.predecessor);
2113
2128
  const prior = predecessor === undefined || steps > byDigest.size ? null : await readRetainedGenesis(root, predecessor.journalRef);
2114
2129
  if (prior === null) break;
2115
- if (prior.predecessor === null) { complete = true; break; } // the first version holds no add: its tasks came with plan create
2116
2130
  genesis = prior;
2131
+ if (prior.predecessor === null) { created([...open.values()].flat()); complete = true; break; } // the first version: its tasks came with plan create, by its creator
2117
2132
  }
2118
2133
  } catch { /* an unreadable version leaves the tasks not yet resolved without an entry */ }
2119
2134
  if (complete) await publishTaskAddedCache(root, plan, added).catch(() => {}); // derived: a lost write is a later walk