@quolu/lattice 0.99.0 → 0.101.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
@@ -7,18 +7,38 @@ import packageJson from '../package.json' with { type: 'json' };
7
7
 
8
8
  installPipeCloseGuard();
9
9
 
10
- const args = withImpliedJson(process.argv.slice(2));
10
+ let args = withImpliedJson(process.argv.slice(2));
11
11
  // 作業ディレクトリを読まないsurface。cwdが消えた席(閉じたworktree)からでも動かす。
12
- const CWD_FREE_COMMANDS = new Set(['runtime-errors', 'bridge', 'hooks', 'setup', 'factory-diagnostics']);
12
+ const CWD_FREE_COMMANDS = new Set(['runtime-errors', 'bridge', 'hooks', 'setup', 'factory-diagnostics', 'charts']);
13
13
  // 内部故障の観測(下のobserveInternalFailure)が終わるのを、exit前に待つための置き場。
14
14
  let pendingObservation = Promise.resolve();
15
15
  installSqliteExperimentalWarningFilter();
16
16
  const help = renderCliHelp(args);
17
+ // K8/K5 (a101, docs/architecture/dfd-charts-read.md): a host addresses a chart by project id; a Store-creating
18
+ // command makes it, and a failed run removes only the dir it made (below the dispatch).
19
+ let chartCreated = null;
20
+ let chartRefusal = null;
21
+ if (help === null && args[0] !== '--version' && !CWD_FREE_COMMANDS.has(args[0])
22
+ && process.env.LATTICE_CHARTS_ROOT && process.env.LATTICE_PROJECT_ID) {
23
+ const { enterAddressedChart } = await import('../src/chart-cli.mjs');
24
+ try {
25
+ const chart = await enterAddressedChart({ env: process.env, argv: args, cwd: workingDirectory() ?? '.' });
26
+ args = chart.argv;
27
+ chartCreated = chart.created;
28
+ process.chdir(chart.dir);
29
+ } catch (error) {
30
+ chartRefusal = error;
31
+ }
32
+ }
17
33
 
18
34
  if (help !== null) {
19
35
  process.stdout.write(help);
20
36
  } else if (args.length === 1 && args[0] === '--version') {
21
37
  process.stdout.write(`${packageJson.version}\n`);
38
+ } else if (chartRefusal !== null) {
39
+ process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: chartRefusal?.code ?? 'INTERNAL_FAILURE',
40
+ message: chartRefusal?.message ?? String(chartRefusal), detail: chartRefusal?.detail ?? null })}\n`);
41
+ process.exitCode = 1;
22
42
  } else if (!CWD_FREE_COMMANDS.has(args[0]) && workingDirectory() === null) {
23
43
  // 呼び出し元のcwdが削除済み(閉じたworktreeに残ったshell等)。`process.cwd()`のENOENTが
24
44
  // 各分岐で生のstackや内部故障(LATTICE.CLI_INTERNAL_FAILED)として漏れていた。製品の故障ではなく
@@ -29,6 +49,10 @@ if (help !== null) {
29
49
  detail: { next_action: 'cd_to_existing_project_directory_then_retry' },
30
50
  })}\n`);
31
51
  process.exitCode = 1;
52
+ } else if (args[0] === 'charts' || args[0] === 'chart') {
53
+ const { runChartCli } = await import('../src/chart-cli.mjs');
54
+ process.exitCode = await runChartCli({ argv: args, cwd: process.cwd(), env: process.env,
55
+ stdout: process.stdout, stderr: process.stderr, created: chartCreated !== null });
32
56
  } else if (args.length === 2 && args[0] === 'session-context' && args[1] === '--json') {
33
57
  const { runSessionContext } = await import('../src/project-cli.mjs');
34
58
  process.exitCode = await runSessionContext({
@@ -254,6 +278,12 @@ if (help !== null) {
254
278
  }
255
279
 
256
280
  await pendingObservation;
281
+ if (chartCreated !== null && (process.exitCode ?? 0) !== 0) {
282
+ // shortcut: an exception that escapes the dispatch skips this removal; every branch above returns a typed exit.
283
+ const { rm } = await import('node:fs/promises');
284
+ process.chdir(process.env.LATTICE_CHARTS_ROOT);
285
+ await rm(chartCreated, { recursive: true, force: true });
286
+ }
257
287
  await scheduleRuntimeErrorReport();
258
288
 
259
289
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.99.0",
3
+ "version": "0.101.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",
@@ -0,0 +1,339 @@
1
+ // Host connection (a101, docs/architecture/dfd-charts-read.md): K8 addressing, K5 chart creation, K1/K2 chart list
2
+ // and change tokens, K4 naming, K7 code-chart repo. A host reads charts only through these commands.
3
+
4
+ import { execFile } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import { appendFile, lstat, mkdir, readdir, readFile, rm } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { Writable } from 'node:stream';
9
+ import { promisify } from 'node:util';
10
+
11
+ import { parseFlagMap } from './todo-authoring-input.mjs';
12
+ import { TODO_CHARTS_ROOT_ENV } from './todo-external.mjs';
13
+ import {
14
+ readTodoChartMeta, readTodoStoreDisplaySource, TodoStoreError, writeTodoChartMeta,
15
+ } from './todo-store.mjs';
16
+
17
+ export const PROJECT_ID_ENV = 'LATTICE_PROJECT_ID';
18
+ const SEAT_ID_ENV = 'LATTICE_SEAT_ID';
19
+ const MANIFEST = path.join('.lattice', 'todo', 'manifest.json');
20
+ // Relative file arguments keep meaning the caller's cwd after K8 moves the process into the chart.
21
+ const FILE_FLAGS = new Set(['--input', '--plan-input', '--review']);
22
+ const runGit = promisify(execFile);
23
+
24
+ /** A project id names one direct child of the charts root, never a path. */
25
+ function isChartId(id) {
26
+ return typeof id === 'string' && id !== '' && id !== '.' && id !== '..' && !/[/\\\0]/u.test(id);
27
+ }
28
+
29
+ /** Commands that make the chart when it does not exist yet (K5). Reads never create one. */
30
+ function createsChart(argv) {
31
+ return (argv[0] === 'plan' && argv[1] === 'create' && !['--schema', '--schema-version', '--template'].includes(argv[2]))
32
+ || (argv[0] === 'chart' && argv[1] === 'set');
33
+ }
34
+
35
+ function refusal(code, reason, detail) {
36
+ return new TodoStoreError(code, reason, undefined, detail);
37
+ }
38
+
39
+ async function lstatOrNull(target) {
40
+ try { return await lstat(target); } catch (error) {
41
+ if (error?.code === 'ENOENT') return null;
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * K8 + K5: with `LATTICE_CHARTS_ROOT` and `LATTICE_PROJECT_ID` both set, the command runs in `<root>/<id>`.
48
+ * Returns `null` when not addressed, else `{dir, created, argv}` (`created` = the dir this run made, for removal on
49
+ * failure). Throws `CHART_PATH_INVALID` (named protection: writes outside the root or through a link) or
50
+ * `CHART_NOT_FOUND` (protection: a read would otherwise run on the caller's cwd, the wrong chart; self-exit: create it).
51
+ */
52
+ export async function enterAddressedChart({ env, argv, cwd }) {
53
+ const rootValue = env[TODO_CHARTS_ROOT_ENV];
54
+ const id = env[PROJECT_ID_ENV];
55
+ if (typeof rootValue !== 'string' || rootValue === '' || typeof id !== 'string' || id === '') return null;
56
+ const root = path.resolve(rootValue);
57
+ const dir = path.join(root, id);
58
+ if (!isChartId(id)) {
59
+ throw refusal('CHART_PATH_INVALID', 'chart_id_not_a_name', { project_id: id,
60
+ next_action: `Set ${PROJECT_ID_ENV} to a chart directory name (no path separators).` });
61
+ }
62
+ let stat = await lstatOrNull(dir);
63
+ let created = null;
64
+ if (stat === null && createsChart(argv)) {
65
+ await mkdir(root, { recursive: true });
66
+ try {
67
+ await mkdir(dir, { mode: 0o700 });
68
+ created = dir;
69
+ } catch (error) {
70
+ if (error?.code !== 'EEXIST') throw error;
71
+ }
72
+ stat = await lstat(dir);
73
+ if (created !== null) {
74
+ try { await runGit('git', ['init', '--quiet'], { cwd: dir }); } catch (error) {
75
+ await rm(dir, { recursive: true, force: true });
76
+ throw error;
77
+ }
78
+ }
79
+ }
80
+ if (stat === null) {
81
+ throw refusal('CHART_NOT_FOUND', 'chart_missing', { project_id: id, path: dir,
82
+ next_action: 'lattice chart set --name <text> (or plan create --input <file>) creates the chart' });
83
+ }
84
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
85
+ throw refusal('CHART_PATH_INVALID', 'chart_path_not_a_directory', { project_id: id, path: dir,
86
+ next_action: `Remove or rename ${dir}; a chart is a plain directory under ${TODO_CHARTS_ROOT_ENV}.` });
87
+ }
88
+ const absolute = argv.map((word, index) => (FILE_FLAGS.has(argv[index - 1]) && !word.startsWith('--')
89
+ && !path.isAbsolute(word) ? path.resolve(cwd, word) : word));
90
+ return { dir, created, argv: absolute };
91
+ }
92
+
93
+ const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
94
+ const reasonOf = (error) => error?.detail?.reason ?? error?.code ?? 'chart_unreadable';
95
+
96
+ /** One chart's identity and change token; never throws (K1/K2). */
97
+ async function readChart(root, id) {
98
+ const dir = path.join(root, id);
99
+ const findings = [];
100
+ let meta = null;
101
+ let display = null;
102
+ try { meta = await readTodoChartMeta({ repoRoot: dir }); } catch (error) {
103
+ findings.push({ project_id: id, reason: reasonOf(error) });
104
+ }
105
+ try { display = await readTodoStoreDisplaySource({ repoRoot: dir }); } catch (error) {
106
+ findings.push({ project_id: id, reason: reasonOf(error) });
107
+ }
108
+ return { meta, findings, source: meta === null || display === null ? null : digest([display, meta]) };
109
+ }
110
+
111
+ /** Direct children of the root that hold a Store manifest, sorted; a missing root has none. */
112
+ async function chartIds(root) {
113
+ let entries;
114
+ try { entries = await readdir(root, { withFileTypes: true }); } catch (error) {
115
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
116
+ throw error;
117
+ }
118
+ const ids = [];
119
+ for (const entry of entries) {
120
+ if (entry.isDirectory() && await lstatOrNull(path.join(root, entry.name, MANIFEST)) !== null) ids.push(entry.name);
121
+ }
122
+ return ids.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
123
+ }
124
+
125
+ function chartsRoot(env) {
126
+ const value = env[TODO_CHARTS_ROOT_ENV];
127
+ return typeof value === 'string' && value !== '' ? path.resolve(value) : null;
128
+ }
129
+
130
+ /** K1 `lattice.charts_list_result.v1`. */
131
+ export async function listCharts(env) {
132
+ const root = chartsRoot(env);
133
+ if (root === null) {
134
+ return { schema: 'lattice.charts_list_result.v1', charts_root: null, charts: [],
135
+ findings: [{ project_id: null, reason: 'charts_root_unset' }] };
136
+ }
137
+ const charts = [];
138
+ const findings = [];
139
+ for (const id of await chartIds(root)) {
140
+ const chart = await readChart(root, id);
141
+ findings.push(...chart.findings);
142
+ charts.push({ project_id: id, name: chart.meta?.name ?? null, created_by: chart.meta?.created_by ?? null,
143
+ created_at: chart.meta?.created_at ?? null, source: chart.source });
144
+ }
145
+ return { schema: 'lattice.charts_list_result.v1', charts_root: root, charts, findings };
146
+ }
147
+
148
+ /** K2 `lattice.charts_source_result.v1`; no ids = every chart; an id with no chart (or unreadable) is null. */
149
+ export async function chartSources(env, ids) {
150
+ const root = chartsRoot(env);
151
+ const chosen = ids.length > 0 ? ids : root === null ? [] : await chartIds(root);
152
+ const charts = {};
153
+ for (const id of chosen) {
154
+ const present = root !== null && isChartId(id) && await lstatOrNull(path.join(root, id, MANIFEST)) !== null;
155
+ charts[id] = present ? (await readChart(root, id)).source : null;
156
+ }
157
+ return { schema: 'lattice.charts_source_result.v1', charts };
158
+ }
159
+
160
+ /** BellTeam's rule: 1-40 characters, already trimmed, no control characters. */
161
+ function validChartName(value) {
162
+ return typeof value === 'string' && value === value.trim() && [...value].length >= 1 && [...value].length <= 40
163
+ && !/\p{Cc}/u.test(value);
164
+ }
165
+
166
+ async function repoRoot(cwd) {
167
+ try {
168
+ return path.resolve((await runGit('git', ['rev-parse', '--show-toplevel'], { cwd })).stdout.trim());
169
+ } catch {
170
+ throw refusal('REPO_UNRESOLVED', 'git_toplevel_unresolved');
171
+ }
172
+ }
173
+
174
+ function projectIdOf(env, dir) {
175
+ return env[PROJECT_ID_ENV] || path.basename(dir);
176
+ }
177
+
178
+ /** K4 `chart set --name <text> [--created-by <id>]`; `created` = K5 made the chart in this run. */
179
+ async function chartSet({ cwd, env, flags, created }) {
180
+ const name = typeof flags.name === 'string' ? flags.name.trim() : null;
181
+ if (!validChartName(name)) {
182
+ throw refusal('CHART_NAME_INVALID', 'chart_name_invalid', { field: '--name',
183
+ rule: '1-40 characters after trimming, no control characters',
184
+ next_action: 'lattice chart set --name <text>' });
185
+ }
186
+ const explicit = typeof flags['created-by'] === 'string' ? flags['created-by'].trim() : undefined;
187
+ if (explicit !== undefined && !validChartName(explicit)) {
188
+ throw refusal('CHART_NAME_INVALID', 'chart_created_by_invalid', { field: '--created-by',
189
+ rule: '1-40 characters after trimming, no control characters',
190
+ next_action: 'lattice chart set --name <text> --created-by <id>' });
191
+ }
192
+ const dir = await repoRoot(cwd);
193
+ const createdBy = explicit ?? (created ? env[SEAT_ID_ENV] || null : undefined);
194
+ const { meta, unchanged } = await writeTodoChartMeta({ repoRoot: dir,
195
+ patch: { name, ...(createdBy === undefined ? {} : { created_by: createdBy }) } });
196
+ return { schema: 'lattice.chart_set_result.v1', project_id: projectIdOf(env, dir), name: meta.name,
197
+ created_by: meta.created_by, created_at: meta.created_at, unchanged };
198
+ }
199
+
200
+ const URL_PATTERN = /^(?:https:\/\/|ssh:\/\/|file:\/\/|git@)[^\s\p{Cc}]+$/u;
201
+
202
+ /** K7 bind: record `{url, branch, accepted_tip}`; a new url or branch drops the old baseline. */
203
+ async function chartRepoBind({ cwd, env, flags }) {
204
+ const { url, branch } = flags;
205
+ if (typeof url !== 'string' || !URL_PATTERN.test(url)) {
206
+ throw refusal('CHART_REPO_INVALID', 'repo_url_invalid', { field: '--url',
207
+ rule: 'https://, ssh://, file:// or git@ URL without spaces', next_action: 'lattice chart repo bind --url <url> --branch <branch>' });
208
+ }
209
+ const branchOk = typeof branch === 'string' && await runGit('git', ['check-ref-format', '--branch', branch], { cwd })
210
+ .then(() => true, () => false);
211
+ if (!branchOk) {
212
+ throw refusal('CHART_REPO_INVALID', 'repo_branch_invalid', { field: '--branch',
213
+ rule: 'a valid git branch name', next_action: 'lattice chart repo bind --url <url> --branch <branch>' });
214
+ }
215
+ const dir = await repoRoot(cwd);
216
+ const current = (await readTodoChartMeta({ repoRoot: dir })).repo;
217
+ const same = current?.url === url && current?.branch === branch;
218
+ const { meta, unchanged } = await writeTodoChartMeta({ repoRoot: dir,
219
+ patch: { repo: { url, branch, accepted_tip: same ? current.accepted_tip ?? null : null } } });
220
+ return { schema: 'lattice.chart_repo_result.v1', project_id: projectIdOf(env, dir), status: 'bound',
221
+ repo: meta.repo, unchanged };
222
+ }
223
+
224
+ /** Run the bundled sensor in process; `{command, exit_code, code}` (`code` = its typed error code or null). */
225
+ async function runSensor(command, dir) {
226
+ const { runSensorCli } = await import('./sensor-cli.mjs');
227
+ let errorText = '';
228
+ const sink = () => new Writable({ write(chunk, _encoding, done) { errorText += chunk; done(); } });
229
+ const exitCode = await runSensorCli({ argv: [command, dir, '--json'], stdout: sink(), stderr: sink() });
230
+ const code = errorText.split('\n').map((line) => { try { return JSON.parse(line).code; } catch { return null; } })
231
+ .find((value) => typeof value === 'string') ?? null;
232
+ return { command, exit_code: exitCode, code };
233
+ }
234
+
235
+ /**
236
+ * K7 sync. Named protection: never reset, clean, force or repoint; tracked edits make it `dirty` and a HEAD that is
237
+ * not the accepted baseline makes it `diverged` (nothing moves). Self-exit: a failed step is reported and the next
238
+ * sync tries again. A depth-1 tip has no parent, so `--ff-only` cannot see the link: HEAD moves only from the baseline.
239
+ */
240
+ async function chartRepoSync({ cwd, env }) {
241
+ const dir = await repoRoot(cwd);
242
+ const meta = await readTodoChartMeta({ repoRoot: dir });
243
+ const result = (status, fields = {}) => ({ schema: 'lattice.chart_repo_result.v1', project_id: projectIdOf(env, dir),
244
+ status, tip: null, accepted_tip: meta.repo?.accepted_tip ?? null, sensor: null, failure: null, ...fields });
245
+ if (meta.repo === null || meta.repo === undefined) {
246
+ return result('failed', { failure: { step: 'bind', message: 'no repository bound to this chart',
247
+ next_action: 'lattice chart repo bind --url <url> --branch <branch>' } });
248
+ }
249
+ const { url, branch } = meta.repo;
250
+ const git = async (step, args) => {
251
+ try { return (await runGit('git', args, { cwd: dir })).stdout.trim(); } catch (error) {
252
+ throw Object.assign(new Error(String(error?.stderr || error?.message).trim().split('\n')[0]), { step });
253
+ }
254
+ };
255
+ const optional = (args) => runGit('git', args, { cwd: dir }).then(({ stdout }) => stdout.trim() || null, () => null);
256
+ try {
257
+ const exclude = path.join(dir, '.git', 'info', 'exclude');
258
+ const excluded = await readFile(exclude, 'utf8').catch(() => '');
259
+ if (!excluded.split(/\r?\n/u).includes('.lattice/')) {
260
+ await mkdir(path.dirname(exclude), { recursive: true });
261
+ await appendFile(exclude, `${excluded === '' || excluded.endsWith('\n') ? '' : '\n'}.lattice/\n`);
262
+ }
263
+ if (await git('status', ['status', '--porcelain', '--untracked-files=no'])) return result('dirty');
264
+ // A lazily fetching (promisor) clone fetches each missing blob on every full object walk; never fetch lazily.
265
+ for (const key of ['remote.origin.promisor', 'remote.origin.partialclonefilter', 'extensions.partialclone']) {
266
+ await optional(['config', '--unset-all', key]);
267
+ }
268
+ // Charts moved before 0.101.0 kept the baseline in refs/remotes/origin/<branch>.
269
+ const accepted = meta.repo.accepted_tip ?? await optional(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`]);
270
+ await git('fetch', ['fetch', '--quiet', '--depth=1', '--no-tags', url, branch]);
271
+ const tip = await git('fetch', ['rev-parse', 'FETCH_HEAD']);
272
+ const head = await optional(['rev-parse', '--verify', '--quiet', 'HEAD']);
273
+ if (head !== null && head !== tip && head !== accepted) return result('diverged', { tip, accepted_tip: accepted });
274
+ if (head !== tip) await git('checkout', ['checkout', '--quiet', '-B', branch, tip]);
275
+ if (meta.repo.accepted_tip !== tip) {
276
+ await writeTodoChartMeta({ repoRoot: dir, patch: { repo: { url, branch, accepted_tip: tip } } });
277
+ }
278
+ let sensor = await runSensor('sync', dir);
279
+ if (sensor.code === 'LATTICE_SENSOR_NOT_INITIALIZED') sensor = await runSensor('init', dir);
280
+ if (sensor.exit_code !== 0) {
281
+ return result('failed', { tip, accepted_tip: tip, sensor,
282
+ failure: { step: 'sensor', message: sensor.code ?? 'sensor failed' } });
283
+ }
284
+ return result(head === tip ? 'current' : 'synced', { tip, accepted_tip: tip, sensor });
285
+ } catch (error) {
286
+ return result('failed', { failure: { step: error?.step ?? 'sync', message: String(error?.message ?? error) } });
287
+ }
288
+ }
289
+
290
+ function usage(stderr, args) {
291
+ stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: `usage: lattice ${args}`,
292
+ detail: { next_action: 'lattice chart --help' } })}\n`);
293
+ return 2;
294
+ }
295
+
296
+ function failure(stderr, error) {
297
+ stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: error?.code ?? 'INTERNAL_FAILURE',
298
+ message: error?.message ?? String(error), detail: error?.detail ?? null })}\n`);
299
+ return 1;
300
+ }
301
+
302
+ /** `lattice charts list|source` (root-level, never addressed) and `lattice chart set|repo bind|repo sync`. */
303
+ export async function runChartCli({ argv, cwd, env, stdout, stderr, created = false }) {
304
+ const words = argv.filter((word) => word !== '--json');
305
+ const [group, command, sub] = words;
306
+ try {
307
+ let result;
308
+ if (group === 'charts' && command === 'list' && words.length === 2) {
309
+ result = await listCharts(env);
310
+ } else if (group === 'charts' && command === 'source') {
311
+ const ids = [];
312
+ for (let index = 2; index < words.length; index += 2) {
313
+ if (words[index] !== '--project' || words[index + 1] === undefined) return usage(stderr, 'charts source [--project <id>]... [--json]');
314
+ ids.push(words[index + 1]);
315
+ }
316
+ result = await chartSources(env, ids);
317
+ } else if (group === 'chart' && command === 'set') {
318
+ const { flags, rest } = parseFlagMap(words.slice(2));
319
+ if (rest.length > 0 || Object.keys(flags).some((key) => !['name', 'created-by'].includes(key))) {
320
+ return usage(stderr, 'chart set --name <text> [--created-by <id>] [--json]');
321
+ }
322
+ result = await chartSet({ cwd, env, flags, created });
323
+ } else if (group === 'chart' && command === 'repo' && sub === 'bind') {
324
+ const { flags, rest } = parseFlagMap(words.slice(3));
325
+ if (rest.length > 0 || Object.keys(flags).some((key) => !['url', 'branch'].includes(key))) {
326
+ return usage(stderr, 'chart repo bind --url <url> --branch <branch> [--json]');
327
+ }
328
+ result = await chartRepoBind({ cwd, env, flags });
329
+ } else if (group === 'chart' && command === 'repo' && sub === 'sync' && words.length === 3) {
330
+ result = await chartRepoSync({ cwd, env });
331
+ } else {
332
+ return usage(stderr, `${group} --help`);
333
+ }
334
+ stdout.write(`${JSON.stringify(result)}\n`);
335
+ return 0;
336
+ } catch (error) {
337
+ return failure(stderr, error);
338
+ }
339
+ }
package/src/cli-help.mjs CHANGED
@@ -15,6 +15,12 @@ Commands:
15
15
  bridge <command> Configure the optional network bridge
16
16
  hooks <command> Install and run sensor-awareness hooks
17
17
  setup [status] AI別のMCP登録・製品hook準備・接続確認
18
+ charts <list|source> LATTICE_CHARTS_ROOT配下の工程表一覧と変更検知(host向け, a101)
19
+ chart <set|repo> 工程表の名前・作成者とコード工程表のrepo(host向け, a101)
20
+
21
+ Environment:
22
+ LATTICE_CHARTS_ROOT + LATTICE_PROJECT_ID 両方あれば <root>/<id> の工程表で動く。
23
+ 無ければ plan create / chart set が作る(git init込み)
18
24
 
19
25
  Options:
20
26
  -h, --help Show help
@@ -312,6 +318,14 @@ const SUBCOMMAND_USAGE = Object.freeze({
312
318
  'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # lattice.todo_wait_result.v1 {state: waiting|startable_now|not_pending|cancelled}',
313
319
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
314
320
  'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
321
+ charts: 'charts list [--json] | source [--project <id>]... [--json] # LATTICE_CHARTS_ROOT配下の全工程表を1プロセスで読む',
322
+ 'charts list': 'charts list [--json] # lattice.charts_list_result.v1 {charts_root, charts:[{project_id, name, created_by, created_at, source}], findings}',
323
+ 'charts source': 'charts source [--project <id>]... [--json] # lattice.charts_source_result.v1 {charts:{<id>: <source>|null}}(--project無し=全工程表)',
324
+ chart: 'chart set --name <text> [--created-by <id>] [--json] | repo bind --url <url> --branch <branch> [--json] | repo sync [--json]',
325
+ 'chart set': 'chart set --name <text> [--created-by <id>] [--json] # lattice.chart_set_result.v1(名前は1-40字・制御文字なし。--created-byは作成者が空の時だけ)',
326
+ 'chart repo': 'chart repo bind --url <url> --branch <branch> [--json] | sync [--json] # lattice.chart_repo_result.v1',
327
+ 'chart repo bind': 'chart repo bind --url <url> --branch <branch> [--json] # コード工程表のrepoを記録する',
328
+ 'chart repo sync': 'chart repo sync [--json] # depth-1 fetch、accepted_tipからだけ前進(reset/forceしない)、その後sensor。status current|synced|dirty|diverged|failed',
315
329
  'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
316
330
  'todo display source': 'todo display source [--json] # lattice.todo_store_display_source.v1(安い変更検知。変わった時だけreadする)',
317
331
  'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation|enforced> --reason <text>'
@@ -603,26 +603,23 @@ export function carriedStartActors(member) {
603
603
  export async function rebindCarriedWork({ repoRoot, planKey, env,
604
604
  reason = 'ゴール変更後のplan versionへ作業中ToDoを結び直す',
605
605
  failureCode = 'BACKCHAIN_REBIND_PENDING', carriedActors = new Map() }) {
606
+ // perf-rebind: one store read for every carried task (was 5 full passes per task through rebindStart).
606
607
  const store = await readTodoStore({ repoRoot });
607
608
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
608
- const rebound = [];
609
- for (const state of member.tasks.filter(({ status }) => status === 'in-progress')) {
610
- const hasCurrentStart = member.journal.events.some((event) => event.kind === 'start'
611
- && event.task_id === state.task_id && event.payload?.start_mode !== 'historical_import');
612
- if (hasCurrentStart) continue;
613
- const { rebindStart } = await import('./todo-cli.mjs');
614
- try {
615
- await rebindStart({ repoRoot, env, planKey, taskId: state.task_id,
616
- reason, actor: carriedActors.get(state.task_id) ?? null });
617
- } catch (error) {
609
+ const rebound = member.tasks.filter(({ status, task_id: taskId }) => status === 'in-progress'
610
+ && !member.journal.events.some((event) => event.kind === 'start'
611
+ && event.task_id === taskId && event.payload?.start_mode !== 'historical_import'))
612
+ .map(({ task_id: taskId }) => taskId);
613
+ const { rebindCarriedStarts } = await import('./todo-cli.mjs');
614
+ await rebindCarriedStarts({ repoRoot, env, store, planKey, reason,
615
+ tasks: rebound.map((taskId) => ({ task_id: taskId, actor: carriedActors.get(taskId) ?? null })),
616
+ onFailure: (taskId, error) => {
618
617
  throw new TodoStoreError(failureCode, 'carried_task_rebind_failed', undefined, {
619
- task_id: state.task_id, plan_version: member.plan.plan_version,
618
+ task_id: taskId, plan_version: member.plan.plan_version,
620
619
  cause_code: error?.code ?? 'unknown',
621
- next_action: `lattice todo start --plan ${planKey} --task ${state.task_id} --rebind --reason <text>`,
620
+ next_action: `lattice todo start --plan ${planKey} --task ${taskId} --rebind --reason <text>`,
622
621
  });
623
- }
624
- rebound.push(state.task_id);
625
- }
622
+ } });
626
623
  return rebound;
627
624
  }
628
625
 
@@ -864,7 +864,9 @@ export async function runPlanCreate({
864
864
  };
865
865
  const store = manifest === null
866
866
  ? await initializeAuthoredTodoStore({ ...options,
867
- projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }] })
867
+ projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }],
868
+ // K4 (a101): the seat that creates the Store is the chart's creator unless one is already recorded.
869
+ chartCreator: env.LATTICE_SEAT_ID || null })
868
870
  : await appendAuthoredTodoPlan(options).catch((error) => {
869
871
  // a27: Storeの拒否はkeyを持たないので、断りの文が名指せるようにここで添える。
870
872
  if (error?.detail?.reason !== 'plan_key_already_exists') throw error;
package/src/todo-cli.mjs CHANGED
@@ -174,6 +174,7 @@ import { newTodoNotices, projectTodoNotices, waitInEffect } from './todo-notices
174
174
  import {
175
175
  externalCycle, readTodoExternalChart, readTodoExternalTasks, withTodoExternalTasks,
176
176
  } from './todo-external.mjs';
177
+ import { projectTodoTrees } from './todo-trees.mjs';
177
178
  import { projectTodoBlockers, todoBlockerKey } from './todo-blockers.mjs';
178
179
  import {
179
180
  ackTodoNotices, cancelTodoNoticeWait, readAllTodoNoticeAcks, readAllTodoNoticeWaits, readTodoNoticeAcks, writeTodoNoticeWait,
@@ -976,6 +977,12 @@ function reopenAdvisory(plan, phases, taskId) {
976
977
  };
977
978
  }
978
979
 
980
+ /** The prospective validator with `external` (xchart predecessor states) bound into the locked store. */
981
+ function externalValidator(external) {
982
+ return external.length === 0 ? validateProspectiveEvent
983
+ : (input) => validateProspectiveEvent({ ...input, store: { ...input.store, external_tasks: external } });
984
+ }
985
+
979
986
  async function mutate({
980
987
  repoRoot, env, planKey, taskId, kind, payload, evidenceRef, evidenceMessage = null,
981
988
  advisory = null, noteContext = null, structureContext = null, featureContext = null,
@@ -985,8 +992,7 @@ async function mutate({
985
992
  // xchart: start and authored done check predecessors on other charts too, read before the lock.
986
993
  const external = externalTasks ?? (kind === 'start' || (kind === 'done' && payload === 'authored')
987
994
  ? (await readTodoExternalTasks(await readTodoStore({ repoRoot }), env)).external_tasks : []);
988
- const validator = external.length === 0 ? validateProspectiveEvent
989
- : (input) => validateProspectiveEvent({ ...input, store: { ...input.store, external_tasks: external } });
995
+ const validator = externalValidator(external);
990
996
  const evidence = evidenceRef === null && evidenceMessage === null
991
997
  ? null
992
998
  : await resolveDoneEvidence({
@@ -1398,11 +1404,15 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
1398
1404
  };
1399
1405
  }
1400
1406
 
1401
- /** xchart: the display envelope plus `external_tasks`, so a host computing readiness from it sees other charts too. */
1407
+ /**
1408
+ * xchart: the display envelope plus `external_tasks`, so a host computing readiness from it sees other charts too;
1409
+ * a100: plus `trees`, each task tree and its size, so the host never computes the graph.
1410
+ */
1402
1411
  async function displayRead(repoRoot, env) {
1403
1412
  const display = await readTodoStoreForDisplay({ repoRoot });
1404
1413
  const externalTasks = display.store ? (await readTodoExternalTasks(display.store, env)).external_tasks : [];
1405
- return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks };
1414
+ return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1415
+ trees: display.store ? projectTodoTrees(display.store) : [] };
1406
1416
  }
1407
1417
 
1408
1418
  /** xchart: the Store plus its external predecessors' states; every readiness reader reads through this. */
@@ -1585,6 +1595,27 @@ export async function rebindStart({ repoRoot, env, planKey, taskId, reason, acto
1585
1595
  });
1586
1596
  }
1587
1597
 
1598
+ /**
1599
+ * perf-rebind: rebind every carried in-progress task after a revision with the same start event and validator as
1600
+ * `rebindStart`, but one store read and one external-chart read for all of them (the caller has the store and drops the
1601
+ * per-task result, so no per-task store or note-context read). Each event is still its own locked append, so a
1602
+ * refusal names its task. `tasks: [{task_id, actor}]`; calls `onFailure(taskId, error)` and stops at the first refusal.
1603
+ */
1604
+ export async function rebindCarriedStarts({ repoRoot, env, store, planKey, tasks, reason, onFailure }) {
1605
+ if (tasks.length === 0) return;
1606
+ const validator = externalValidator((await readTodoExternalTasks(store, env)).external_tasks);
1607
+ const writer = createTodoStoreWriter({ caller: 'g5-authoring' });
1608
+ for (const { task_id: taskId, actor } of tasks) {
1609
+ try {
1610
+ await appendTodoEvent({ validateProspectiveEvent: validator, repoRoot, writer, planKey,
1611
+ event: { kind: 'start', task_id: taskId, actor: actor ?? resolveTodoActor(env),
1612
+ payload: { start_mode: 'rebind', reason } } });
1613
+ } catch (error) {
1614
+ onFailure(taskId, error);
1615
+ }
1616
+ }
1617
+ }
1618
+
1588
1619
  async function retractStart({ repoRoot, env, planKey, taskId, reason }) {
1589
1620
  const store = await readTodoStore({ repoRoot });
1590
1621
  const binding = resolveTodoStartRetractionBinding(store, { planKey, taskId });
@@ -44,6 +44,8 @@ export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
44
44
  // Per-lane startable-notice ack set and per-plan waits (host-local; todo-notice-store.mjs).
45
45
  export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
46
46
  export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
47
+ /** a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). */
48
+ export const TODO_CHART_META_SCHEMA = 'lattice.chart_meta.v1';
47
49
  /**
48
50
  * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
49
51
  * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
@@ -846,3 +848,14 @@ export function validateTodoSnapshot(value) {
846
848
  && isTodoDigest(value.snapshot_digest) && value.snapshot_digest === todoSelfDigest(value, 'snapshot_digest');
847
849
  } catch { return false; }
848
850
  }
851
+
852
+ export function validateTodoChartMeta(value) {
853
+ const text = (field) => field === null || (typeof field === 'string' && field.length > 0 && field.length <= 1024);
854
+ const word = (field) => typeof field === 'string' && field.length > 0 && field.length <= 1024;
855
+ const { repo } = value ?? {};
856
+ return exactRecord(value, ['schema', 'name', 'created_by', 'created_at', 'repo'])
857
+ && value.schema === TODO_CHART_META_SCHEMA && text(value.name) && text(value.created_by)
858
+ && (value.created_at === null || isStrictTodoTimestamp(value.created_at))
859
+ && (repo === null || (exactRecord(repo, ['url', 'branch', 'accepted_tip'])
860
+ && word(repo.url) && word(repo.branch) && text(repo.accepted_tip)));
861
+ }
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
8
8
  import { syncPublishedFile } from './fs-publish.mjs';
9
9
  import { normalizeCheckoutEol } from './todo-store-view.mjs';
10
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
10
11
 
11
12
  import {
12
13
  TODO_LIMITS,
@@ -504,31 +505,38 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
504
505
  fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
505
506
  }
506
507
  const versionRoot = path.join(base, entry.name);
507
- // A revision directory is published before manifest activation. A crash during
508
- // that window can leave an unreferenced directory containing only a journal
509
- // stub. It is not a historical plan until its canonical plan artifact exists.
510
- // Do not make that unreachable residue poison note projection; if a note event
511
- // names this version, the origin-version check below still fails closed.
512
- const plan = await readCanonicalJson(path.join(versionRoot, 'plan.json'), { missing: true });
513
- if (plan === null) continue;
514
- if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
515
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
516
- }
517
- versions.add(entry.name);
518
- const revision = await readCanonicalJson(path.join(versionRoot, 'revision.json'), { missing: true });
519
- if (revision === null) continue;
520
- if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
521
- || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
522
- || !Array.isArray(revision.task_migration)) {
523
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
524
- }
525
- migrations.push({
526
- from_plan_version: revision.predecessor.plan_version,
527
- to_plan_version: entry.name,
528
- task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
529
- from_task_id: fromTaskId, to_task_id: toTaskId,
530
- })),
508
+ const planPath = path.join(versionRoot, 'plan.json');
509
+ const revisionPath = path.join(versionRoot, 'revision.json');
510
+ // perf-store: validated once per process while both files are unchanged (todo-version-memo).
511
+ const version = await memoByFileIdentity([planPath, revisionPath], async () => {
512
+ // A revision directory is published before manifest activation. A crash during
513
+ // that window can leave an unreferenced directory containing only a journal
514
+ // stub. It is not a historical plan until its canonical plan artifact exists.
515
+ // Do not make that unreachable residue poison note projection; if a note event
516
+ // names this version, the origin-version check below still fails closed.
517
+ const plan = await readCanonicalJson(planPath, { missing: true });
518
+ if (plan === null) return null;
519
+ if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
520
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
521
+ }
522
+ const revision = await readCanonicalJson(revisionPath, { missing: true });
523
+ if (revision === null) return { migration: null };
524
+ if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
525
+ || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
526
+ || !Array.isArray(revision.task_migration)) {
527
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
528
+ }
529
+ return { migration: {
530
+ from_plan_version: revision.predecessor.plan_version,
531
+ to_plan_version: entry.name,
532
+ task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
533
+ from_task_id: fromTaskId, to_task_id: toTaskId,
534
+ })),
535
+ } };
531
536
  });
537
+ if (version === null) continue;
538
+ versions.add(entry.name);
539
+ if (version.migration !== null) migrations.push(structuredClone(version.migration));
532
540
  }
533
541
  if ([...eventVersions].some((version) => !versions.has(version))) {
534
542
  fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
@@ -19,11 +19,13 @@ import { randomBytes } from 'node:crypto';
19
19
  import { fsyncDirectory } from './fs-dir-sync.mjs';
20
20
  import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
21
21
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
22
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
22
23
  import {
23
24
  lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
24
25
  } from 'node:fs/promises';
25
26
  import path from 'node:path';
26
27
  import {
28
+ TODO_CHART_META_SCHEMA,
27
29
  TODO_COORDINATION_MODES,
28
30
  TODO_EVENT_KINDS,
29
31
  TODO_LIMITS,
@@ -38,6 +40,7 @@ import {
38
40
  isTodoRef,
39
41
  todoSelfDigest,
40
42
  validateEvidenceDescriptor,
43
+ validateTodoChartMeta,
41
44
  validateTodoImportSource,
42
45
  validateTodoEvent,
43
46
  validateTodoManifest,
@@ -151,7 +154,7 @@ function rejectUnsupportedRevisionSchema(value, { family, supportedSchemas }) {
151
154
 
152
155
  // Reader registration (newer-value-says-upgrade): the newest schema of each Store record family this
153
156
  // reader knows. Bump it in the same diff that teaches the validator a new version.
154
- export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1 });
157
+ export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1, chart_meta: 1 });
155
158
  const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest']]);
156
159
  const vocabularyWord = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}$/u.test(value);
157
160
 
@@ -1685,37 +1688,67 @@ async function readTodoStoreView(options = {}) {
1685
1688
  };
1686
1689
  }
1687
1690
 
1691
+ /**
1692
+ * One retained version's plan identity `{plan, journalRef}` (plan = its plan/predecessor/topology digests), or null when
1693
+ * unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
1694
+ */
1695
+ async function retainedPlanVersion(repoRoot, base, version) {
1696
+ const ref = `${base}/${version}/plan.json`;
1697
+ const plan = await memoByFileIdentity([path.resolve(repoRoot, ref)], async () => {
1698
+ const value = await readArtifact(repoRoot, ref, {
1699
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1700
+ }).catch(() => null);
1701
+ return value === null ? null : { plan_digest: value.plan_digest,
1702
+ predecessor_plan_digest: value.predecessor_plan_digest, topology_digest: value.topology_digest };
1703
+ });
1704
+ return plan === null ? null : { plan, journalRef: `${base}/${version}/journal/active.jsonl` };
1705
+ }
1706
+
1707
+ async function retainedVersionNames(repoRoot, base, activePlan) {
1708
+ let names = [];
1709
+ try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1710
+ return names.filter((version) => version !== activePlan.plan_version && isTodoIdentifier(version));
1711
+ }
1712
+
1688
1713
  /** The plan's other retained versions, by plan digest (unreadable ones are skipped). */
1689
1714
  async function retainedPlanVersions(repoRoot, activePlan) {
1690
1715
  const base = `${STORE_ROOT_REF}/plans/${activePlan.plan_key}`;
1691
1716
  const byDigest = new Map();
1692
- let names = [];
1693
- try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1694
- for (const version of names) {
1695
- if (version === activePlan.plan_version || !isTodoIdentifier(version)) continue;
1696
- const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1697
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1698
- }).catch(() => null);
1699
- if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1717
+ for (const version of await retainedVersionNames(repoRoot, base, activePlan)) {
1718
+ const retained = await retainedPlanVersion(repoRoot, base, version);
1719
+ if (retained !== null) byDigest.set(retained.plan.plan_digest, retained);
1700
1720
  }
1701
1721
  return byDigest;
1702
1722
  }
1703
1723
 
1704
1724
  /**
1705
1725
  * a35: the coordination declaration belongs to the plan, not to one version (ADR 0160 Decision 2).
1706
- * A revision starts an empty plan-scoped chain, so a version that has not declared its own reads the
1726
+ * A revision does not copy the declaration into the new plan-scoped chain, so a version that has not declared its own reads the
1707
1727
  * newest declaration along its retained predecessors. Read only: nothing is copied into the new chain.
1708
1728
  * An unreadable predecessor ends the walk as undeclared, which is what the version showed before a35.
1709
1729
  */
1710
1730
  async function inheritedTodoCoordination(repoRoot, plan) {
1711
1731
  if (!plan.predecessor_plan_digest) return null;
1712
- const byDigest = await retainedPlanVersions(repoRoot, plan);
1713
- for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < byDigest.size; steps += 1) {
1714
- const predecessor = byDigest.get(digest);
1732
+ // perf-store: versions are read lazily, only until the walk finds the predecessor it needs.
1733
+ const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}`;
1734
+ const names = await retainedVersionNames(repoRoot, base, plan);
1735
+ const byDigest = new Map();
1736
+ let scanned = 0;
1737
+ const find = async (digest) => {
1738
+ while (!byDigest.has(digest) && scanned < names.length) {
1739
+ const retained = await retainedPlanVersion(repoRoot, base, names[scanned]);
1740
+ scanned += 1;
1741
+ if (retained !== null) byDigest.set(retained.plan.plan_digest, retained);
1742
+ }
1743
+ return byDigest.get(digest);
1744
+ };
1745
+ for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < names.length; steps += 1) {
1746
+ const predecessor = await find(digest);
1715
1747
  if (predecessor === undefined) return null;
1716
- const chain = await readPlanScopedJournal(repoRoot, predecessor.journalRef).catch(() => null);
1717
- if (chain === null) return null;
1718
- const declared = projectTodoCoordination(chain.events);
1748
+ const declared = await memoByFileIdentity([path.resolve(repoRoot, planScopedJournalRef(predecessor.journalRef))],
1749
+ () => readPlanScopedJournal(repoRoot, predecessor.journalRef)
1750
+ .then((chain) => projectTodoCoordination(chain.events), () => undefined));
1751
+ if (declared === undefined) return null;
1719
1752
  if (declared !== null) return declared;
1720
1753
  digest = predecessor.plan.predecessor_plan_digest;
1721
1754
  }
@@ -2575,6 +2608,49 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2575
2608
  };
2576
2609
  }
2577
2610
 
2611
+ /**
2612
+ * edge-carry: a successor's plan-scoped chain starts with the predecessor's live incoming connections, so a revision
2613
+ * no longer drops them. `to` and a same-plan `from` follow the genesis task_migration onto the successor topology; a
2614
+ * removed endpoint, a self edge or a duplicate after mapping drops the edge; any other `from` stays as recorded (its
2615
+ * own plan's revision is the u03 repair's, another chart's is Plan's). Actor, time and provenance stay the
2616
+ * connection's, so the bytes depend only on the predecessor chain and the successor and a resumed transaction rebuilds
2617
+ * them. Coordination declarations are not copied (read-time inheritance, a35).
2618
+ */
2619
+ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration) {
2620
+ const live = new Set(projectTodoCrossPlanDependencies(store.members).map(({ event_digest: digest }) => digest));
2621
+ const ids = new Map(taskMigration.map(({ from_task_id: from, to_task_id: to }) => [from, to]));
2622
+ const carry = (ref) => {
2623
+ if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
2624
+ const taskId = ids.get(ref.task_id);
2625
+ return taskId === undefined || taskId === 'removed' ? null
2626
+ : { ...ref, task_id: taskId, expected_topology_digest: plan.topology_digest };
2627
+ };
2628
+ const successor = { plan, plan_scoped: { ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0) } };
2629
+ const seen = new Set();
2630
+ for (const event of previous.plan_scoped?.events ?? []) {
2631
+ if (event.kind !== 'cross_plan_dependency' || !live.has(event.event_digest)) continue;
2632
+ const from = carry(event.payload.from); const to = carry(event.payload.to);
2633
+ if (from === null || to === null || mergedTaskKey(from) === mergedTaskKey(to)) continue;
2634
+ const key = `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`;
2635
+ if (seen.has(key)) continue;
2636
+ seen.add(key);
2637
+ const carried = buildPlanScopedEvent(successor, { kind: event.kind, actor: event.actor,
2638
+ recorded_at: event.recorded_at, provenance: event.provenance,
2639
+ payload: { from, to, reason: event.payload.reason } });
2640
+ successor.plan_scoped.activeBytes = Buffer.concat([successor.plan_scoped.activeBytes,
2641
+ planScopedEventBytes(successor, carried)]);
2642
+ successor.plan_scoped.events.push(carried);
2643
+ }
2644
+ return successor.plan_scoped;
2645
+ }
2646
+
2647
+ /** Written before the manifest switch; the version is not active yet, so a retry rewrites it from the current predecessor. */
2648
+ async function writeCarriedPlanScopedChain(repoRoot, chain) {
2649
+ const absolute = path.resolve(repoRoot, chain.ref);
2650
+ if (chain.events.length === 0) await rm(absolute, { force: true });
2651
+ else await atomicWrite(absolute, chain.activeBytes);
2652
+ }
2653
+
2578
2654
  /** Rebind existing connections to a carried source without changing their endpoints. */
2579
2655
  export async function rebindTodoCrossPlanDependencies(options = {}) {
2580
2656
  requireWriter(options.writer, 'g5-authoring');
@@ -3663,11 +3739,96 @@ async function withInitialStoreLocks(stage, currentRoot, callback) {
3663
3739
  }
3664
3740
 
3665
3741
  /** G5-only initial authoring transaction. Store membership appears by one final directory rename. */
3742
+ const CHART_META_REF = '.lattice/chart.json';
3743
+ const CHART_META_MAX_BYTES = 65_536;
3744
+ const CHART_META_PATCH_KEYS = ['name', 'created_by', 'repo'];
3745
+
3746
+ /** The recorded chart identity, or null when `.lattice/chart.json` does not exist. */
3747
+ async function readChartMetaRecord(repoRoot) {
3748
+ const absolute = path.join(repoRoot, CHART_META_REF);
3749
+ const invalid = () => fail('STORE_INCONSISTENT', 'chart_meta_invalid', { ref: CHART_META_REF });
3750
+ let bytes;
3751
+ try {
3752
+ const state = await lstat(absolute);
3753
+ if (state.isSymbolicLink() || !state.isFile() || state.size > CHART_META_MAX_BYTES) invalid();
3754
+ bytes = normalizeCheckoutEol(await readFile(absolute));
3755
+ } catch (error) {
3756
+ if (error instanceof TodoStoreError) throw error;
3757
+ if (error?.code === 'ENOENT') return null;
3758
+ if (error?.code === 'ENOTDIR') invalid();
3759
+ throw error;
3760
+ }
3761
+ let value;
3762
+ try { value = JSON.parse(decodeUtf8(bytes, 'STORE_INCONSISTENT', 'chart_meta_invalid')); }
3763
+ catch (error) { if (error instanceof TodoStoreError) throw error; invalid(); }
3764
+ rejectNewerTodoSchema(value, 'chart_meta', CHART_META_REF);
3765
+ if (!validateTodoChartMeta(value)) invalid();
3766
+ return value;
3767
+ }
3768
+
3769
+ const chartMetaView = (record) => ({ name: record?.name ?? null, created_by: record?.created_by ?? null,
3770
+ created_at: record?.created_at ?? null, repo: record?.repo ?? null });
3771
+
3772
+ /**
3773
+ * a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). Read only, no lock, no Store needed: a missing file
3774
+ * reads all null; a malformed one STORE_INCONSISTENT/chart_meta_invalid; a newer schema UNSUPPORTED_SCHEMA.
3775
+ */
3776
+ export async function readTodoChartMeta({ repoRoot = process.cwd() } = {}) {
3777
+ return chartMetaView(await readChartMetaRecord(path.resolve(repoRoot)));
3778
+ }
3779
+
3780
+ /**
3781
+ * a101 K4: patch {name?, created_by?, repo?} (absent key = keep). `created_by` applies only while unrecorded and
3782
+ * `created_at` is stamped when the file is first created: the creator is never overwritten. Works before the first plan
3783
+ * (creates `.lattice/`). The read-modify-write holds `.lattice/.chart.write.lock` so two writers cannot both see an
3784
+ * unrecorded creator (identified lock, proven-dead recovery). Name rules are the CLI's.
3785
+ */
3786
+ export async function writeTodoChartMeta({ repoRoot = process.cwd(), patch = {} } = {}) {
3787
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch)
3788
+ || Object.keys(patch).some((key) => !CHART_META_PATCH_KEYS.includes(key))) {
3789
+ throw new TypeError('chart meta patch invalid');
3790
+ }
3791
+ const root = path.resolve(repoRoot);
3792
+ const latticeRoot = path.join(root, '.lattice');
3793
+ const parent = await lstat(latticeRoot).catch((error) => {
3794
+ if (error?.code !== 'ENOENT') throw error;
3795
+ return null;
3796
+ });
3797
+ if (parent === null) {
3798
+ await mkdir(latticeRoot, { mode: 0o700 }).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
3799
+ } else if (parent.isSymbolicLink() || !parent.isDirectory()) {
3800
+ fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
3801
+ }
3802
+ try {
3803
+ return await withStoreLock({ lockPath: path.join(latticeRoot, '.chart.write.lock'), createParent: false,
3804
+ waitMs: LOCK_WAIT_MS }, async () => {
3805
+ const current = await readChartMetaRecord(root);
3806
+ const next = {
3807
+ schema: TODO_CHART_META_SCHEMA,
3808
+ name: 'name' in patch ? patch.name : current?.name ?? null,
3809
+ created_by: current?.created_by ?? patch.created_by ?? null,
3810
+ created_at: current === null ? new Date().toISOString() : current.created_at,
3811
+ repo: 'repo' in patch ? patch.repo : current?.repo ?? null,
3812
+ };
3813
+ if (!validateTodoChartMeta(next)) throw new TypeError('chart meta patch invalid');
3814
+ if (current !== null && canonicalizeTodoArtifact(next) === canonicalizeTodoArtifact(current)) {
3815
+ return { meta: chartMetaView(current), unchanged: true };
3816
+ }
3817
+ await atomicWrite(path.join(root, CHART_META_REF), canonicalLine(next));
3818
+ return { meta: chartMetaView(next), unchanged: false };
3819
+ });
3820
+ } catch (error) {
3821
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
3822
+ throw error;
3823
+ }
3824
+ }
3825
+
3666
3826
  export async function initializeAuthoredTodoStore(options = {}) {
3667
3827
  requireWriter(options.writer, 'g5-authoring');
3668
3828
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
3669
3829
  const optionKeys = [
3670
3830
  'repoRoot', 'writer', 'projectId', 'repositories', 'plan', 'genesis',
3831
+ ...(options.chartCreator === undefined ? [] : ['chartCreator']),
3671
3832
  ];
3672
3833
  const allowedOptions = options.featureChain === undefined ? optionKeys : [...optionKeys, 'featureChain'];
3673
3834
  if (!(exactRecord(options, allowedOptions)
@@ -3712,8 +3873,9 @@ export async function initializeAuthoredTodoStore(options = {}) {
3712
3873
  await prepareAuthoredStoreRoot(repoRoot, options);
3713
3874
  await mkdir(stage, { mode: 0o700 });
3714
3875
  stageIdentity = await lstat(stage);
3876
+ let created;
3715
3877
  try {
3716
- return await withInitialStoreLocks(stage, async () => {
3878
+ created = await withInitialStoreLocks(stage, async () => {
3717
3879
  const current = renamed ? storeRoot : stage;
3718
3880
  const identity = await lstat(current).catch((error) => {
3719
3881
  if (error?.code !== 'ENOENT') throw error;
@@ -3849,6 +4011,11 @@ export async function initializeAuthoredTodoStore(options = {}) {
3849
4011
  }
3850
4012
  }
3851
4013
  }
4014
+ // a101 K4: the creating run is the chart's creator (only while unrecorded). After activation, so the rollback above
4015
+ // never meets chart.json; the Store is published, so a chart.json fault is the readers' finding, not this run's failure.
4016
+ try { await writeTodoChartMeta({ repoRoot, patch: { created_by: options.chartCreator ?? null } }); }
4017
+ catch (error) { if (!(error instanceof TodoStoreError)) throw error; }
4018
+ return created;
3852
4019
  }
3853
4020
 
3854
4021
  async function sourceItemBytes(repoRoot, sourceRef) {
@@ -4873,8 +5040,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4873
5040
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4874
5041
  const stateMigration = stateMigrationFor(previous, revision);
4875
5042
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
5043
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan, journalRef, stateMigration);
4876
5044
  validateMergedGraph(store.members.map((member) => member === previous
4877
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member));
5045
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member));
4878
5046
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4879
5047
  previous_digest: revision.predecessor.journal_head_digest, actor: options.actor,
4880
5048
  recorded_at: options.recordedAt, provenance: options.provenance ?? null,
@@ -4997,6 +5165,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4997
5165
  await publishRevisionArtifact(path.join(transaction, 'phase-revision-commit-receipt.json'),
4998
5166
  path.resolve(repoRoot, commitReceiptRef), canonicalLine(commitReceipt));
4999
5167
  await protocolStage(options, 'phase_v3_commit_receipt_durable');
5168
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5000
5169
  const nextManifest = { schema: 'lattice.todo_manifest.v2', project_id: currentManifest.project_id,
5001
5170
  repositories: currentManifest.repositories, members, manifest_digest: '' };
5002
5171
  nextManifest.manifest_digest = todoSelfDigest(nextManifest, 'manifest_digest');
@@ -5043,8 +5212,12 @@ export async function applyPhaseTodoRevision(options = {}) {
5043
5212
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5044
5213
  const stateMigration = stateMigrationFor(previous, revision);
5045
5214
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
5215
+ const base = `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}`;
5216
+ const revisionRef = `${base}/revision.json`; const planRef = `${base}/plan.json`;
5217
+ const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5218
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan, journalRef, stateMigration);
5046
5219
  const prospective = store.members.map((member) => member === previous
5047
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5220
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5048
5221
  validateMergedGraph(prospective);
5049
5222
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
5050
5223
  previous_digest: revision.predecessor.journal_head_digest,
@@ -5071,9 +5244,6 @@ export async function applyPhaseTodoRevision(options = {}) {
5071
5244
  }));
5072
5245
  }
5073
5246
  await protocolStage(options, 'phase_revision_marker_durable');
5074
- const base = `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}`;
5075
- const revisionRef = `${base}/revision.json`; const planRef = `${base}/plan.json`;
5076
- const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5077
5247
  const tasks = replay(revision.desired_plan, [genesis], {
5078
5248
  now: options.now ? new Date(options.now) : new Date(),
5079
5249
  verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
@@ -5096,6 +5266,7 @@ export async function applyPhaseTodoRevision(options = {}) {
5096
5266
  else if (!existing.equals(bytes)) fail('REVISION_CONFLICT', 'revision_bytes_conflict');
5097
5267
  await protocolStage(options, stage);
5098
5268
  }
5269
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5099
5270
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5100
5271
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5101
5272
  });
@@ -5192,8 +5363,11 @@ export async function applyTodoRevision(options = {}) {
5192
5363
  }
5193
5364
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5194
5365
  const stateMigration = stateMigrationFor(previous, revision);
5366
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan,
5367
+ `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}/journal/active.jsonl`,
5368
+ stateMigration);
5195
5369
  const prospective = store.members.map((member) => member === previous
5196
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5370
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5197
5371
  validateMergedGraph(prospective);
5198
5372
 
5199
5373
  const candidateGenesis = buildRevisionGenesis(revision.desired_plan, {
@@ -5270,6 +5444,7 @@ export async function applyTodoRevision(options = {}) {
5270
5444
  }
5271
5445
 
5272
5446
  try {
5447
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5273
5448
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5274
5449
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5275
5450
  });
@@ -5462,13 +5637,16 @@ export async function applyTodoRevisionSet(options = {}) {
5462
5637
  : buildRevisionGenesis(revision.desired_plan, {
5463
5638
  ...commonGenesis, reconciliation_digest: revision.reconciliation.reconciliation_digest,
5464
5639
  });
5465
- prepared.push({ revision, previous, stateMigration, phaseStateMigration, genesis, cutoverImages });
5640
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan,
5641
+ `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}/journal/active.jsonl`,
5642
+ stateMigration);
5643
+ prepared.push({ revision, previous, stateMigration, phaseStateMigration, genesis, cutoverImages, carriedChain });
5466
5644
  }
5467
5645
 
5468
- const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key,
5469
- entry.revision.desired_plan]));
5646
+ const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key, entry]));
5470
5647
  validateMergedGraph(store.members.map((member) => desiredByPlan.has(member.descriptor.plan_key)
5471
- ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key), plan_scoped: null } : member));
5648
+ ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key).revision.desired_plan,
5649
+ plan_scoped: desiredByPlan.get(member.descriptor.plan_key).carriedChain } : member));
5472
5650
 
5473
5651
  await ensureSafeStoreDirectory(repoRoot, transaction);
5474
5652
  const mixedPhaseSet = prepared.some(({ revision }) => ([
@@ -5570,6 +5748,7 @@ export async function applyTodoRevisionSet(options = {}) {
5570
5748
  }
5571
5749
 
5572
5750
  try {
5751
+ for (const entry of prepared) await writeCarriedPlanScopedChain(repoRoot, entry.carriedChain);
5573
5752
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5574
5753
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5575
5754
  });
@@ -5670,10 +5849,11 @@ export async function createSuccessorTodoPlan(options = {}) {
5670
5849
  const genesis = buildPlanGenesis(plan, {
5671
5850
  ...options.genesis, previous_digest: previous.journal.events.at(-1).event_digest,
5672
5851
  });
5673
- const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: null } : member);
5674
- validateMergedGraph(prospective);
5675
5852
  const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}/${plan.plan_version}`;
5676
5853
  const planRef = `${base}/plan.json`; const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5854
+ const carriedChain = carriedPlanScopedChain(store, previous, plan, journalRef, migration);
5855
+ const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: carriedChain } : member);
5856
+ validateMergedGraph(prospective);
5677
5857
  try { await lstat(path.resolve(repoRoot, planRef)); fail('STORE_WRITE_CONFLICT', 'successor_version_exists'); }
5678
5858
  catch (error) { if (error instanceof TodoStoreError) throw error; if (error?.code !== 'ENOENT') throw error; }
5679
5859
  const tasks = replay(plan, [genesis], { now: options.now ? new Date(options.now) : new Date() });
@@ -5683,6 +5863,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5683
5863
  await atomicWrite(path.resolve(repoRoot, planRef), canonicalLine(plan));
5684
5864
  await atomicWrite(path.resolve(repoRoot, journalRef), canonicalLine(genesis));
5685
5865
  await atomicWrite(path.resolve(repoRoot, snapshotRef), canonicalLine(snapshot));
5866
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5686
5867
  Object.assign(previous.descriptor, {
5687
5868
  active_plan_version: plan.plan_version, plan_ref: planRef, journal_ref: journalRef,
5688
5869
  snapshot_ref: snapshotRef, topology_digest: plan.topology_digest,
@@ -0,0 +1,71 @@
1
+ // Task trees (a100, docs/architecture/dfd-display-trees.md): connected components of this chart's tasks, so a host
2
+ // shows each tree's size without computing the graph itself. Pure; never throws on a malformed member or edge.
3
+
4
+ import { isFinishedTodoTaskState, projectTodoCrossPlanDependencies } from './todo-store-view.mjs';
5
+
6
+ const list = (value) => (Array.isArray(value) ? value : []);
7
+ const isRef = (ref) => ref !== null && typeof ref === 'object';
8
+ const key = (projectId, planKey, taskId) => `${projectId}\0${planKey}\0${taskId}`;
9
+ const byCodeUnit = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
10
+
11
+ // Only well-formed ledger events reach the shared projection, so one bad event never drops the others.
12
+ function wellFormedLedger(member) {
13
+ const events = list(member?.plan_scoped?.events).filter((event) => isRef(event?.payload) && (
14
+ event.kind === 'cross_plan_dependency' ? isRef(event.payload.from) && isRef(event.payload.to)
15
+ : event.kind === 'cross_plan_dependency_removed'));
16
+ return { plan_scoped: { events } };
17
+ }
18
+
19
+ /** `[{tree_id, tasks:[{plan_key, task_id}], total, finished}]` over every task of `store.members`. */
20
+ export function projectTodoTrees(store) {
21
+ const members = list(store?.members).filter((member) => isRef(member?.plan));
22
+ const nodes = new Map();
23
+ const parent = new Map();
24
+ for (const { plan, tasks } of members) {
25
+ const states = new Map(list(tasks).map((state) => [state?.task_id, state]));
26
+ for (const task of list(plan.tasks)) {
27
+ if (typeof task?.task_id !== 'string') continue;
28
+ const id = key(plan.project_id, plan.plan_key, task.task_id);
29
+ nodes.set(id, { plan_key: plan.plan_key, task_id: task.task_id,
30
+ finished: isFinishedTodoTaskState(states.get(task.task_id)) });
31
+ parent.set(id, id);
32
+ }
33
+ }
34
+ const root = (id) => {
35
+ while (parent.get(id) !== id) id = parent.get(id);
36
+ return id;
37
+ };
38
+ // An edge with an endpoint that is not a task here (another chart, a removed task, a bad ref) is skipped.
39
+ const join = (from, to) => {
40
+ if (!isRef(from) || !isRef(to)) return;
41
+ const left = key(from.project_id, from.plan_key, from.task_id);
42
+ const right = key(to.project_id, to.plan_key, to.task_id);
43
+ if (nodes.has(left) && nodes.has(right)) parent.set(root(left), root(right));
44
+ };
45
+ for (const { plan } of members) {
46
+ for (const edge of list(plan.hard_dependencies)) join(edge?.from, edge?.to);
47
+ for (const entry of list(plan.joins)) for (const after of list(entry?.after)) join(after, entry.before);
48
+ for (const task of list(plan.tasks)) {
49
+ const parentId = task?.parent_task_id;
50
+ if (typeof parentId === 'string') join({ ...plan, task_id: parentId }, { ...plan, task_id: task.task_id });
51
+ }
52
+ }
53
+ for (const edge of projectTodoCrossPlanDependencies(members.map(wellFormedLedger))) join(edge.from, edge.to);
54
+
55
+ const trees = new Map();
56
+ for (const id of nodes.keys()) {
57
+ const tree = root(id);
58
+ if (!trees.has(tree)) trees.set(tree, []);
59
+ trees.get(tree).push(nodes.get(id));
60
+ }
61
+ return [...trees.values()].map((members) => {
62
+ const tasks = members.sort((left, right) => byCodeUnit(left.plan_key, right.plan_key)
63
+ || byCodeUnit(left.task_id, right.task_id));
64
+ return {
65
+ tree_id: tasks.map((task) => `${task.plan_key}/${task.task_id}`).sort(byCodeUnit)[0],
66
+ tasks: tasks.map(({ plan_key, task_id }) => ({ plan_key, task_id })),
67
+ total: tasks.length,
68
+ finished: tasks.filter((task) => task.finished).length,
69
+ };
70
+ }).sort((left, right) => byCodeUnit(left.tree_id, right.tree_id));
71
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * perf-store: per-process memo for values derived from retained plan-version files (Store internal).
3
+ *
4
+ * A retained version directory is immutable history, but every Store read used to re-read and strictly re-validate
5
+ * all of them (206 versions on a production plan: one `todo add` spent ~40 s re-digesting the same bytes). The memo
6
+ * keys by absolute file paths and serves a value only while each file's identity (dev, ino, size, mtime, ctime) is
7
+ * unchanged, so a replaced or newly published file is read again. A failing computation is not memoized.
8
+ * Callers keep their own readdir, so new versions appear. Values stay small (digests, migrations), never whole plans.
9
+ */
10
+ import { lstat } from 'node:fs/promises';
11
+
12
+ const memo = new Map();
13
+
14
+ async function fileIdentity(absolute) {
15
+ try {
16
+ const state = await lstat(absolute, { bigint: true });
17
+ return `${state.dev}:${state.ino}:${state.size}:${state.mtimeNs}:${state.ctimeNs}`;
18
+ } catch (error) {
19
+ return error?.code === 'ENOENT' ? '-' : `!${error?.code}`;
20
+ }
21
+ }
22
+
23
+ export async function memoByFileIdentity(files, compute) {
24
+ const key = files.join('\0');
25
+ const identity = (await Promise.all(files.map(fileIdentity))).join('|');
26
+ const hit = memo.get(key);
27
+ if (hit !== undefined && hit.identity === identity) return hit.value;
28
+ const value = await compute();
29
+ memo.set(key, { identity, value });
30
+ return value;
31
+ }