@quolu/lattice 0.108.0 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/bin/lattice.mjs +2 -2
  2. package/docs/schemas/lattice.plan_create_input.v6.schema.json +384 -0
  3. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +3 -0
  4. package/docs/schemas/lattice.todo_witness_draft.v2.schema.json +14 -2
  5. package/docs/schemas/lattice.todo_witness_set.v6.schema.json +482 -0
  6. package/package.json +3 -1
  7. package/sensor/dist/bin/lattice-sensor.js +76 -0
  8. package/sensor/dist/graph/anchor-resolve.d.ts +90 -0
  9. package/sensor/dist/graph/anchor-resolve.d.ts.map +1 -0
  10. package/sensor/dist/graph/anchor-resolve.js +132 -0
  11. package/sensor/dist/graph/anchor-resolve.js.map +1 -0
  12. package/sensor/dist/graph/touched-symbols.d.ts +42 -0
  13. package/sensor/dist/graph/touched-symbols.d.ts.map +1 -0
  14. package/sensor/dist/graph/touched-symbols.js +80 -0
  15. package/sensor/dist/graph/touched-symbols.js.map +1 -0
  16. package/src/cli-help.mjs +28 -6
  17. package/src/cli-refusal-guidance.mjs +3 -0
  18. package/src/function-split-verify.mjs +396 -0
  19. package/src/plan-backchain.mjs +18 -7
  20. package/src/plan-revise.mjs +26 -12
  21. package/src/plan-scope-review.mjs +1 -1
  22. package/src/project-cli.mjs +23 -3
  23. package/src/runtime-front-end.mjs +8 -3
  24. package/src/seam-apply.mjs +2 -2
  25. package/src/sensor-cli.mjs +82 -1
  26. package/src/sensor-resolve.mjs +116 -0
  27. package/src/sensor-touched.mjs +76 -0
  28. package/src/todo-authoring-input.mjs +1 -0
  29. package/src/todo-cli.mjs +303 -27
  30. package/src/todo-contracts.mjs +118 -4
  31. package/src/todo-declaration.mjs +165 -0
  32. package/src/todo-function-split.mjs +234 -0
  33. package/src/todo-gantt-html-independence.mjs +2 -2
  34. package/src/todo-gantt-html-shared.mjs +4 -1
  35. package/src/todo-gantt-html.mjs +4 -2
  36. package/src/todo-independence-authoritative-observation.mjs +26 -23
  37. package/src/todo-independence-contracts.mjs +17 -4
  38. package/src/todo-independence.mjs +4 -1
  39. package/src/todo-judgment.mjs +141 -0
  40. package/src/todo-relation-store.mjs +294 -0
  41. package/src/todo-revision.mjs +5 -5
  42. package/src/todo-split-labels.mjs +26 -0
  43. package/src/todo-split-start.mjs +100 -0
  44. package/src/todo-split-store.mjs +100 -0
  45. package/src/todo-store-view.mjs +3 -2
  46. package/src/todo-store.mjs +31 -14
  47. package/src/witness-scaffold.mjs +23 -15
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Code graph's side of ADR 0205 §3-§4: check a worker's function-split commit, and size the cut before the worker decides.
3
+ *
4
+ * The cut itself is the worker's code change; this module only observes it. It never reads the plan or the journal (the
5
+ * overlap and parallel conditions are Plan/lifecycle's), and never writes the source repository: every observation runs
6
+ * in a disposable worktree of the commit with ONE fresh index, reused for the tests, the file nodes and Resolve.
7
+ */
8
+
9
+ import { execFile, spawnSync } from 'node:child_process';
10
+ import { existsSync } from 'node:fs';
11
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import path from 'node:path';
14
+ import { promisify } from 'node:util';
15
+
16
+ import { runIsolatedTransform } from './isolation-runner.mjs';
17
+ import { computeSeamCostProfile } from './seam-cost.mjs';
18
+ import { buildOutputMounts, detectSeveredReferences } from './seam-apply.mjs';
19
+ import { compareExportSurface } from './seam-verification.mjs';
20
+ import { runSensorCli } from './sensor-cli.mjs';
21
+ import { resolveAnchors } from './sensor-resolve.mjs';
22
+ import { invokeSensorCli } from './sensor-runtime.mjs';
23
+
24
+ const execFileAsync = promisify(execFile);
25
+ const LIST_CAP = 64; // the splits record caps lists at 64 (ADR 0205 §2)
26
+ const DETAIL_CAP = 2048;
27
+ const JS_TS = /\.(?:mjs|cjs|js|jsx|ts|tsx|mts|cts)$/u;
28
+ const NODE_RUNNABLE = /\.(?:mjs|cjs|js)$/u;
29
+ const TEST_FILE = /(?:^|\/)(?:tests?|__tests__)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/u;
30
+ const sink = { write() {} };
31
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
32
+ const cap = (list) => list.slice(0, LIST_CAP);
33
+ const clip = (text) => String(text).slice(0, DETAIL_CAP);
34
+
35
+ class InputError extends Error {
36
+ constructor(code, next_action, extra = {}) {
37
+ super(code);
38
+ this.error = { code, next_action, ...extra };
39
+ }
40
+ }
41
+
42
+ const git = async (repoRoot, args, options = {}) => (await execFileAsync('git', args, {
43
+ cwd: repoRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, ...options,
44
+ })).stdout;
45
+
46
+ const safePath = (value) => typeof value === 'string' && value !== '' && !path.isAbsolute(value)
47
+ && !value.split('/').includes('..');
48
+ const wellFormed = (entry) => safePath(entry?.path) && typeof entry?.symbol === 'string' && entry.symbol !== '';
49
+
50
+ function validate({ target, map, anchors }) {
51
+ if (!wellFormed(target)) throw new InputError('map_entry_malformed', 'target must be {path, symbol} (repo-relative path)');
52
+ const seen = new Set();
53
+ for (const entry of map) {
54
+ if (!wellFormed(entry) || typeof entry.task_id !== 'string' || entry.task_id === '' || seen.has(entry.task_id)) {
55
+ throw new InputError('map_entry_malformed', 'map takes one {task_id, path, symbol} per member, repo-relative paths');
56
+ }
57
+ seen.add(entry.task_id);
58
+ }
59
+ for (const entry of anchors) {
60
+ if (!wellFormed(entry) || typeof entry.task_id !== 'string') {
61
+ throw new InputError('map_entry_malformed', 'anchors take {task_id, path, symbol}');
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * A host's chart repository usually takes in main only, so the worker's cut is not there (ADR 0205 §4): fetch what is
68
+ * missing from `origin`, objects only (`--no-write-fetch-head`, no refspec: no ref moves). False when origin cannot give it.
69
+ */
70
+ async function fetchFromOrigin(repoRoot, args) {
71
+ try {
72
+ await git(repoRoot, ['fetch', '--no-tags', '--no-recurse-submodules', '--no-write-fetch-head', ...args]);
73
+ return true;
74
+ } catch { return false; }
75
+ }
76
+
77
+ async function revParse(repoRoot, ref, what) {
78
+ const parse = () => git(repoRoot, ['rev-parse', '--verify', `${ref}^{commit}`]).then((out) => out.trim(), () => null);
79
+ // only a full sha can be asked of origin; a branch name or abbreviation is the worker's to push.
80
+ const found = await parse() ?? (/^[0-9a-f]{40}$/iu.test(ref) && await fetchFromOrigin(repoRoot, ['origin', ref]) ? await parse() : null);
81
+ if (found === null) {
82
+ throw new InputError('commit_not_found', `${what} ${ref} is in neither this repository nor its origin: push the branch, then verify again`, { ref });
83
+ }
84
+ return found;
85
+ }
86
+
87
+ /** merge-base(commit, HEAD); in a shallow clone, deepen and then unshallow until the two histories meet. */
88
+ async function mergeBaseWithHead(repoRoot, commitSha) {
89
+ const attempt = () => git(repoRoot, ['merge-base', commitSha, 'HEAD']).then((out) => out.trim(), () => null);
90
+ let found = await attempt();
91
+ if (found !== null || (await git(repoRoot, ['rev-parse', '--is-shallow-repository'])).trim() !== 'true') return found;
92
+ // shortcut: `HEAD` names origin's HEAD, which is the chart's branch on a host; deepen both sides, then everything.
93
+ for (const depth of ['--deepen=200', '--unshallow']) {
94
+ if (!await fetchFromOrigin(repoRoot, [depth, 'origin', commitSha, 'HEAD'])) break;
95
+ found = await attempt();
96
+ if (found !== null) return found;
97
+ }
98
+ return null;
99
+ }
100
+
101
+ /** `git diff --name-status`: [{status: A|M|D|..., path}]. No rename detection: a rename is a delete plus an add. */
102
+ async function changedFiles(repoRoot, base, commit) {
103
+ const fields = (await git(repoRoot, ['diff', '--name-status', '-z', '--no-renames', base, commit])).split('\0');
104
+ const changes = [];
105
+ for (let at = 0; at + 1 < fields.length; at += 2) changes.push({ status: fields[at][0], path: fields[at + 1] });
106
+ return changes;
107
+ }
108
+
109
+ const spanKey = (rows) => rows.map((row) => `${row.start_line}-${row.end_line}`).sort(compareText).join(',');
110
+
111
+ /** Runs `work` inside a disposable worktree of `ref` with one fresh index; `verifyCommands` may be filled by `work`. */
112
+ async function atRef({ repoRoot, ref, work, verifyCommands = [] }) {
113
+ const scratch = await mkdtemp(path.join(tmpdir(), 'lattice-split-index-'));
114
+ try {
115
+ return await runIsolatedTransform({
116
+ repoRoot, baseRef: ref, allowedPaths: [], verifyCommands,
117
+ transform: ({ worktreePath }) => work(worktreePath),
118
+ mounts: [
119
+ { entry: 'node_modules', target: path.join(repoRoot, 'node_modules') },
120
+ { entry: '.lattice/sensor', target: scratch },
121
+ ...await buildOutputMounts(repoRoot),
122
+ ],
123
+ verifierEnv: { LATTICE_DASHBOARD_AUTOSTART: '0' },
124
+ });
125
+ } finally {
126
+ await rm(scratch, { recursive: true, force: true });
127
+ }
128
+ }
129
+
130
+ async function indexWorktree(worktreePath) {
131
+ if (await runSensorCli({ argv: ['init', worktreePath, '--json'], stdout: sink, stderr: sink }) !== 0) {
132
+ throw new Error('sensor_init_failed');
133
+ }
134
+ }
135
+
136
+ function fileNodes(worktreePath, file) {
137
+ const result = invokeSensorCli(
138
+ (command, args, options) => spawnSync(command, args, options),
139
+ ['file-nodes', file, '--path', '.'],
140
+ { cwd: worktreePath, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
141
+ );
142
+ if (result.status !== 0) return null;
143
+ try { return JSON.parse(result.stdout)?.nodes ?? null; } catch { return null; }
144
+ }
145
+
146
+ function affectedTests(worktreePath, files) {
147
+ const result = invokeSensorCli(
148
+ (command, args, options) => spawnSync(command, args, options),
149
+ ['affected', ...files, '--path', '.', '--json'],
150
+ { cwd: worktreePath, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
151
+ );
152
+ if (result.status !== 0) return null;
153
+ try { return JSON.parse(result.stdout)?.affectedTests ?? null; } catch { return null; }
154
+ }
155
+
156
+ /** Resolve rows of each requested `{path, symbol}`: Map key `path\0symbol` -> rows; plus the misses and ambiguous names. */
157
+ async function resolveAll(root, wanted) {
158
+ const unique = [...new Map(wanted.map(({ path: p, symbol }) => [`${p}\0${symbol}`, { path: p, symbol }])).values()];
159
+ const answer = await resolveAnchors({ root, anchors: unique });
160
+ const rows = new Map();
161
+ for (const row of answer.resolved) {
162
+ const key = `${row.path}\0${row.symbol}`;
163
+ rows.set(key, [...(rows.get(key) ?? []), row]);
164
+ }
165
+ return {
166
+ rows,
167
+ unresolved: new Map(answer.unresolved.map((item) => [`${item.path}\0${item.symbol}`, item])),
168
+ ambiguous: new Map(answer.ambiguous.map((item) => [`${item.path}\0${item.symbol}`, item])),
169
+ };
170
+ }
171
+
172
+ const keyOf = ({ path: p, symbol }) => `${p}\0${symbol}`;
173
+
174
+ /** Why an entry is not usable: `{reason, nearest|candidates}` or null when it resolved to one definition. */
175
+ function missOf(resolved, entry) {
176
+ const key = keyOf(entry);
177
+ if (resolved.ambiguous.has(key)) return { reason: 'ambiguous', candidates: resolved.ambiguous.get(key).names };
178
+ if (!resolved.rows.has(key)) {
179
+ const miss = resolved.unresolved.get(key);
180
+ return { reason: 'not_found', nearest: (miss?.nearest ?? []).slice(0, 5) };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ /** The base side: ranges of the target and mapped entries before the cut, and the graph nodes of deleted non-JS files. */
186
+ async function observeBase({ repoRoot, base, target, map, deletedOther }) {
187
+ const seen = { rows: new Map(), deletedWithNodes: [] };
188
+ await atRef({
189
+ repoRoot, ref: base,
190
+ work: async (worktreePath) => {
191
+ await indexWorktree(worktreePath);
192
+ seen.rows = (await resolveAll(worktreePath, [target, ...map])).rows;
193
+ for (const file of deletedOther) {
194
+ if ((fileNodes(worktreePath, file) ?? []).length > 0) seen.deletedWithNodes.push(file);
195
+ }
196
+ },
197
+ });
198
+ return seen;
199
+ }
200
+
201
+ async function textAt(repoRoot, ref, file) {
202
+ try { return await git(repoRoot, ['show', `${ref}:${file}`]); } catch { return ''; }
203
+ }
204
+
205
+ /**
206
+ * Verify a function-split commit (ADR 0205 §4, behaviour / tests / fresh; overlap and parallel are Plan/lifecycle's).
207
+ * → `{base, commit, target, behaviour, tests, fresh, ranges, anchors_unresolved, map}` or `{error: {code, next_action}}`.
208
+ */
209
+ export async function verifyFunctionSplit({ repoRoot, commit, base, target, map = [], anchors = [] } = {}) {
210
+ try {
211
+ validate({ target, map, anchors });
212
+ const commitSha = await revParse(repoRoot, commit, 'commit');
213
+ const baseSha = base === undefined
214
+ ? await mergeBaseWithHead(repoRoot, commitSha) ?? (() => {
215
+ throw new InputError('commit_not_found', 'commit shares no history with HEAD (origin has none either): pass --base', { ref: commit });
216
+ })()
217
+ : await revParse(repoRoot, base, 'base');
218
+ if (baseSha === commitSha) {
219
+ throw new InputError('empty_diff', 'the commit is already on HEAD or equals base: pass --base <main sha before the merge>');
220
+ }
221
+ const changes = await changedFiles(repoRoot, baseSha, commitSha);
222
+ if (changes.length === 0) throw new InputError('empty_diff', 'no file differs between base and commit: pass a different --base or commit');
223
+ if (!changes.some((change) => change.path === target.path)) {
224
+ throw new InputError('target_untouched', `the diff base..commit does not touch ${target.path}: the cut must change the target file`);
225
+ }
226
+ return await observe({ repoRoot, baseSha, commitSha, changes, target, map, anchors });
227
+ } catch (error) {
228
+ if (error instanceof InputError) return { error: error.error };
229
+ const errors = error instanceof AggregateError ? error.errors : [error];
230
+ const dirty = errors.find((item) => String(item?.message).startsWith('source repository must be clean'));
231
+ if (dirty) {
232
+ return { error: { code: 'source_dirty', next_action: 'commit or stash the changes in the repository, then verify again', detail: clip(dirty.message) } };
233
+ }
234
+ throw error;
235
+ }
236
+ }
237
+
238
+ async function observe({ repoRoot, baseSha, commitSha, changes, target, map, anchors }) {
239
+ const alive = changes.filter(({ status }) => status !== 'D').map(({ path: p }) => p);
240
+ const deletedOther = changes.filter(({ status, path: p }) => status === 'D' && !JS_TS.test(p)).map(({ path: p }) => p);
241
+ const state = { failures: [], resolved: null, unobserved: null, tests: null };
242
+
243
+ let baseSeen = null;
244
+ try {
245
+ baseSeen = await observeBase({ repoRoot, base: baseSha, target, map, deletedOther });
246
+ } catch (error) {
247
+ if (String(error?.message).startsWith('source repository must be clean')) throw error;
248
+ // existed_at_base is recorded, not a condition (ADR 0205 §4): a failed base index leaves it null.
249
+ }
250
+
251
+ const verifyCommands = [];
252
+ const work = async (worktreePath) => {
253
+ try {
254
+ await indexWorktree(worktreePath);
255
+ } catch (error) {
256
+ state.indexFailure = clip(error.message);
257
+ return;
258
+ }
259
+ // behaviour: export surface per JS/TS file, the graph for every other language.
260
+ for (const { status, path: file } of changes) {
261
+ if (JS_TS.test(file)) {
262
+ const before = status === 'A' ? '' : await textAt(repoRoot, baseSha, file);
263
+ const after = status === 'D' ? '' : await readFile(path.join(worktreePath, file), 'utf8');
264
+ const { missing } = compareExportSurface({ before, after });
265
+ if (missing.length > 0) state.failures.push(`export_surface_lost:${file}:${missing.join(',')}`);
266
+ } else if (status !== 'D' && (fileNodes(worktreePath, file) ?? []).length > 0) {
267
+ state.failures.push(`export_surface_unobserved:${file}`);
268
+ }
269
+ }
270
+ for (const file of baseSeen?.deletedWithNodes ?? []) state.failures.push(`export_surface_unobserved:${file}`);
271
+ const others = {};
272
+ for (const file of alive) {
273
+ if (file !== target.path && JS_TS.test(file) && !TEST_FILE.test(file)) {
274
+ others[file] = await readFile(path.join(worktreePath, file), 'utf8');
275
+ }
276
+ }
277
+ if (alive.includes(target.path)) {
278
+ const severed = await detectSeveredReferences({ worktreePath, files: others, residualPath: target.path });
279
+ if (!severed.observed) state.failures.push('severed_observation_missing');
280
+ for (const { file, name } of severed.entries) state.failures.push(`severed_reference:${file}:${name}`);
281
+ }
282
+ state.resolved = await resolveAll(worktreePath, [target, ...map, ...anchors]);
283
+ // tests: the file-level affected tests of the changed files, the target and the mapped paths, on this index.
284
+ const roots = [...new Set([...alive, target.path, ...map.map(({ path: p }) => p)])]
285
+ .filter((file) => existsSync(path.join(worktreePath, file)));
286
+ const affected = affectedTests(worktreePath, roots);
287
+ if (affected === null) { state.testsFailure = 'affected_unavailable'; return; }
288
+ const runnable = affected.filter((file) => NODE_RUNNABLE.test(file)).sort(compareText);
289
+ state.tests = { runnable, skipped: affected.filter((file) => !NODE_RUNNABLE.test(file)).sort(compareText) };
290
+ for (const file of runnable) verifyCommands.push({ command: process.execPath, args: ['--test', file] });
291
+ };
292
+
293
+ let infra = null;
294
+ try {
295
+ await atRef({ repoRoot, ref: commitSha, work, verifyCommands });
296
+ state.testsPassed = true;
297
+ } catch (error) {
298
+ const errors = error instanceof AggregateError ? error.errors : [error];
299
+ const dirty = errors.find((item) => String(item?.message).startsWith('source repository must be clean'));
300
+ if (dirty) throw dirty;
301
+ const failed = errors.find((item) => String(item?.message).startsWith('verifier failed'));
302
+ if (failed) state.testsFailed = failed;
303
+ else infra = clip(errors.map((item) => item?.message).join(' | '));
304
+ }
305
+
306
+ return report({ baseSha, commitSha, target, map, anchors, baseSeen, state, verifyCommands, infra });
307
+ }
308
+
309
+ function report({ baseSha, commitSha, target, map, anchors, baseSeen, state, verifyCommands, infra }) {
310
+ const cause = state.indexFailure ?? infra;
311
+ const resolved = state.resolved;
312
+ const ran = verifyCommands.map(({ args }) => args[1]);
313
+ const spans = (entry) => (resolved?.rows.get(keyOf(entry)) ?? []);
314
+
315
+ const behaviourFailures = cause ? [`worktree_failed:${cause}`] : state.failures;
316
+ const behaviour = { passed: behaviourFailures.length === 0, detail: behaviourFailures.length === 0 ? 'ok' : clip(behaviourFailures.join('; ')) };
317
+
318
+ let tests;
319
+ if (cause || state.testsFailure) {
320
+ tests = { passed: false, ran: [], not_run: [], skipped: [], detail: cause ? `worktree_failed:${cause}` : state.testsFailure };
321
+ } else if (state.tests.runnable.length === 0) {
322
+ tests = { passed: false, ran: [], not_run: [], skipped: cap(state.tests.skipped), detail: 'no_test_reaches_function' };
323
+ } else if (state.testsFailed) {
324
+ const stopped = String(state.testsFailed.message).match(/--test (\S+)/u)?.[1];
325
+ const at = ran.indexOf(stopped);
326
+ tests = {
327
+ passed: false, ran: cap(ran.slice(0, at + 1)), not_run: cap(ran.slice(at + 1)), skipped: cap(state.tests.skipped),
328
+ detail: clip(state.testsFailed.message),
329
+ };
330
+ } else {
331
+ tests = { passed: true, ran: cap(ran), not_run: [], skipped: cap(state.tests.skipped), detail: 'ok' };
332
+ }
333
+
334
+ const unresolved = [];
335
+ const anchorsUnresolved = [];
336
+ const ranges = [];
337
+ const mapOut = [];
338
+ if (resolved) {
339
+ for (const entry of map) {
340
+ const miss = missOf(resolved, entry);
341
+ if (miss) unresolved.push({ task_id: entry.task_id, path: entry.path, symbol: entry.symbol, ...miss });
342
+ const before = baseSeen?.rows.get(keyOf(entry));
343
+ mapOut.push({
344
+ ...entry,
345
+ existed_at_base: baseSeen === null ? null : before !== undefined && spanKey(before) === spanKey(spans(entry)),
346
+ });
347
+ }
348
+ for (const entry of anchors) {
349
+ const miss = missOf(resolved, entry);
350
+ if (miss) anchorsUnresolved.push({ task_id: entry.task_id, path: entry.path, symbol: entry.symbol, ...miss });
351
+ }
352
+ for (const entry of [...map, ...anchors]) {
353
+ for (const row of spans(entry)) {
354
+ ranges.push({ task_id: entry.task_id, path: entry.path, symbol: entry.symbol, start_line: row.start_line, end_line: row.end_line });
355
+ }
356
+ }
357
+ }
358
+ const targetRows = resolved ? spans(target) : [];
359
+ return {
360
+ base: baseSha,
361
+ commit: commitSha,
362
+ target: {
363
+ resolved: targetRows.length > 0,
364
+ start_line: targetRows.length > 0 ? Math.min(...targetRows.map((row) => row.start_line)) : null,
365
+ end_line: targetRows.length > 0 ? Math.max(...targetRows.map((row) => row.end_line)) : null,
366
+ },
367
+ behaviour,
368
+ tests,
369
+ fresh: resolved === null
370
+ ? { passed: false, unresolved: [], detail: `worktree_failed:${cause ?? 'not_observed'}` }
371
+ : { passed: unresolved.length === 0, unresolved: cap(unresolved) },
372
+ // never capped: Plan/lifecycle's overlap check reads every row, and a lost row could turn an overlap into a pass.
373
+ ranges,
374
+ anchors_unresolved: anchorsUnresolved,
375
+ map: mapOut,
376
+ };
377
+ }
378
+
379
+ /**
380
+ * Size of the cut for `todo start S` (ADR 0205 §3): the seam-cost profile of the target function's file, every member
381
+ * owning F. Best effort: `{profile: null, reasons}` when the maintained index cannot answer. One owner key joins the member
382
+ * ids because they all own the same function; the profile's cross-task figures are therefore empty by construction.
383
+ */
384
+ export async function cutCost({ repoRoot, target, memberTaskIds } = {}) {
385
+ if (!wellFormed(target) || !Array.isArray(memberTaskIds) || memberTaskIds.length === 0) {
386
+ return { profile: null, reasons: ['target_or_members_malformed'] };
387
+ }
388
+ let sourceText;
389
+ try { sourceText = await readFile(path.join(repoRoot, target.path), 'utf8'); } catch { return { profile: null, reasons: ['source_unreadable'] }; }
390
+ // the profile names nodes by their bare name; a qualified `Cls.method` is looked up by its last part.
391
+ const name = target.symbol.split('.').at(-1);
392
+ return computeSeamCostProfile({
393
+ repoRoot, sourcePath: target.path, sourceText,
394
+ ownedSymbolsByTask: { [[...memberTaskIds].sort(compareText).join('+')]: [name] },
395
+ });
396
+ }
@@ -417,25 +417,36 @@ async function verifyExistingFeatureReferences(repoRoot, chain) {
417
417
  }
418
418
 
419
419
  const DONE_CONDITION_PLAN_SCHEMA = 'lattice.todo_plan.v8';
420
+ const SPLIT_PLAN_SCHEMA = 'lattice.todo_plan.v9';
420
421
 
421
422
  /**
422
423
  * authoring(create入力またはplan本体)から後継planの種を作る。
423
- * 作る版: v5入力か先行planがv8ならv8(v8→v7へ戻さない)、それ以外はv7。
424
+ * 作る版: 先行planがv9、または splitMarks が分割を書くならv9(v8へ戻さない)。v5入力か先行planがv8ならv8、それ以外はv7。
424
425
  * v8でdone_conditionを書いていないtask(v4入力)は、先行planの同じtaskの値を引き継ぐ
425
426
  * (書き換えも消去もしていないので意味を変えない)。新規taskはnull。
427
+ * v9のfunction_splitは作成者が書けない(ADR 0205 §2): 先行planの同じtaskの値を引き継ぎ、
428
+ * splitMarks(Map task_id → 印 | null、`todo start` の分割だけが渡す)が上書きする。
426
429
  */
427
- export function planSeed(authoring, predecessorPlanDigest, predecessorPlan = null) {
428
- const v8 = authoring.schema === 'lattice.plan_create_input.v5'
430
+ export function planSeed(authoring, predecessorPlanDigest, predecessorPlan = null, splitMarks = null) {
431
+ const marks = splitMarks ?? new Map();
432
+ const v9 = authoring.schema === SPLIT_PLAN_SCHEMA || predecessorPlan?.schema === SPLIT_PLAN_SCHEMA
433
+ || [...marks.values()].some((mark) => mark !== null);
434
+ const v8 = v9 || authoring.schema === 'lattice.plan_create_input.v5'
429
435
  || authoring.schema === DONE_CONDITION_PLAN_SCHEMA
430
436
  || predecessorPlan?.schema === DONE_CONDITION_PLAN_SCHEMA;
431
- const inherited = new Map(predecessorPlan?.schema === DONE_CONDITION_PLAN_SCHEMA
432
- ? predecessorPlan.tasks.map(({ task_id: id, done_condition: value }) => [id, value]) : []);
437
+ const carried = (field) => new Map(['lattice.todo_plan.v8', SPLIT_PLAN_SCHEMA].includes(predecessorPlan?.schema)
438
+ ? predecessorPlan.tasks.map((task) => [task.task_id, task[field] ?? null]) : []);
439
+ const inherited = carried('done_condition');
440
+ const split = carried('function_split');
433
441
  return {
434
- schema: v8 ? DONE_CONDITION_PLAN_SCHEMA : 'lattice.todo_plan.v7', project_id: authoring.project_id,
442
+ schema: v9 ? SPLIT_PLAN_SCHEMA : v8 ? DONE_CONDITION_PLAN_SCHEMA : 'lattice.todo_plan.v7', project_id: authoring.project_id,
435
443
  plan_key: authoring.plan_key, predecessor_plan_digest: predecessorPlanDigest,
436
444
  tasks: v8 ? authoring.tasks.map((task) => ({ ...task,
437
445
  done_condition: Object.hasOwn(task, 'done_condition')
438
- ? task.done_condition : inherited.get(task.task_id) ?? null })) : authoring.tasks,
446
+ ? task.done_condition : inherited.get(task.task_id) ?? null,
447
+ ...(v9 ? { function_split: marks.has(task.task_id) ? marks.get(task.task_id)
448
+ : Object.hasOwn(task, 'function_split') ? task.function_split : split.get(task.task_id) ?? null } : {}) }))
449
+ : authoring.tasks,
439
450
  phases: authoring.phases,
440
451
  hard_dependencies: authoring.hard_dependencies, joins: authoring.joins,
441
452
  phase_accept_dependencies: authoring.phase_accept_dependencies,
@@ -12,12 +12,14 @@ import {
12
12
  applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
13
  } from './todo-store.mjs';
14
14
  import { appendTodoNote } from './todo-note-store.mjs';
15
+ import { splitTouches } from './todo-declaration.mjs';
15
16
  import { planReviseNoteBody } from './todo-revision-note.mjs';
16
17
  import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
17
18
 
18
19
  export { validateBindingCarry } from './plan-binding-carry.mjs';
19
20
 
20
21
  const INPUT_SCHEMA = 'lattice.plan_revise_input.v1';
22
+ const LIGHT_PLAN_SCHEMAS = ['lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'];
21
23
 
22
24
  function fail(reason, pointer, detail = {}) {
23
25
  throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
@@ -208,7 +210,7 @@ export function resolvePlanRevision({ member, input, env = process.env, now = ne
208
210
  next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
209
211
  });
210
212
  }
211
- if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)) {
213
+ if (!LIGHT_PLAN_SCHEMAS.includes(member.plan.schema)) {
212
214
  fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
213
215
  }
214
216
  if (desired.project_id !== member.plan.project_id) {
@@ -230,7 +232,7 @@ export function compilePlanRevision({ member, input, env, now }) {
230
232
  return compileLightRevision({ member, desired, continuity });
231
233
  }
232
234
 
233
- function compileLightRevision({ member, desired, continuity }) {
235
+ function compileLightRevision({ member, desired, continuity, splitMarks = null }) {
234
236
  const taskMigration = continuity.map(({ task_id: id, policy }) => ({
235
237
  from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
236
238
  state_policy: policy === 'retire' ? 'removed'
@@ -240,7 +242,7 @@ function compileLightRevision({ member, desired, continuity }) {
240
242
  journal_head_digest: member.journal.events.at(-1).event_digest,
241
243
  plan_version: member.plan.plan_version,
242
244
  };
243
- const seed = planSeed(desired, predecessor.plan_digest, member.plan);
245
+ const seed = planSeed(desired, predecessor.plan_digest, member.plan, splitMarks);
244
246
  const phaseMigration = compileLightPhaseMigration(member.plan, seed, taskMigration,
245
247
  new Map(member.tasks.map(({ task_id: id, status }) => [id, status])));
246
248
  const version = phaseTodoRevisionPlanVersion({
@@ -280,7 +282,7 @@ export async function planReviseSchema() {
280
282
  * (v7/v8以外・源泉束縛・旧event・compile_binding付きtask)ならfalse。書く前の判定にだけ使う。
281
283
  */
282
284
  export function lightRevisionExpresses(member) {
283
- return ['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)
285
+ return LIGHT_PLAN_SCHEMAS.includes(member.plan.schema)
284
286
  && member.journal.events[0]?.schema !== 'lattice.todo_event.v2'
285
287
  && member.plan.tasks.every((task) => task.narrative_anchor === null && task.compile_binding === null);
286
288
  }
@@ -296,18 +298,19 @@ export function desiredFromPlan(plan, { env = process.env, now = new Date() } =
296
298
  next_action: `lattice todo revise-phase --plan ${plan.plan_key} --input <phase-revision.json>`,
297
299
  });
298
300
  }
299
- if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
301
+ if (!LIGHT_PLAN_SCHEMAS.includes(plan.schema)) {
300
302
  fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
301
303
  }
302
304
  const edge = ({ from, to }) => ({
303
305
  from: { project_id: from.project_id, plan_key: from.plan_key, task_id: from.task_id },
304
306
  to: { project_id: to.project_id, plan_key: to.plan_key, task_id: to.task_id } });
305
307
  return {
306
- schema: plan.schema === 'lattice.todo_plan.v8'
307
- ? 'lattice.plan_create_input.v5' : 'lattice.plan_create_input.v4',
308
+ schema: plan.schema === 'lattice.todo_plan.v7'
309
+ ? 'lattice.plan_create_input.v4' : 'lattice.plan_create_input.v5',
308
310
  project_id: plan.project_id, plan_key: plan.plan_key, plan_version: plan.plan_version,
309
311
  actor: resolveTodoActor(env), recorded_at: now.toISOString(),
310
- tasks: plan.tasks, phases: plan.phases,
312
+ // function_split is not authorable (ADR 0205 §2): planSeed carries it from the predecessor by task id.
313
+ tasks: plan.tasks.map(({ function_split: _split, ...task }) => task), phases: plan.phases,
311
314
  hard_dependencies: plan.hard_dependencies.map(edge), joins: plan.joins,
312
315
  phase_accept_dependencies: plan.phase_accept_dependencies,
313
316
  };
@@ -347,10 +350,17 @@ function unwrapPointers(error) {
347
350
  }
348
351
 
349
352
  export async function applyPlanRevision({
350
- repoRoot, input: authored, env = process.env, dryRun = false, notes: extraNotes = [],
353
+ repoRoot, input: authored, env = process.env, dryRun = false, notes: extraNotes = [], splitMarks = null,
351
354
  }) {
352
355
  const bare = isBareCreateInput(authored);
353
- const input = bare ? { schema: INPUT_SCHEMA, desired: authored } : authored;
356
+ const wrapped = bare ? { schema: INPUT_SCHEMA, desired: authored } : authored;
357
+ let input = wrapped;
358
+ let touches;
359
+ try {
360
+ const split = splitTouches(wrapped?.desired, '/desired');
361
+ touches = split.touches;
362
+ if (split.input !== wrapped?.desired) input = { ...wrapped, desired: split.input };
363
+ } catch (error) { throw bare ? unwrapPointers(error) : error; }
354
364
  const store = await readTodoStore({ repoRoot });
355
365
  const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
356
366
  let resolved;
@@ -359,17 +369,18 @@ export async function applyPlanRevision({
359
369
  const { desired, continuity } = resolved;
360
370
  // 集合の並びは正準化済みなので、同じ内容の別の並びは「変更なし」になる。
361
371
  const unchanged = continuity.every(({ policy }) => policy === 'carry')
362
- && canonicalizeTodoArtifact(planSeed(desired, null, member.plan))
372
+ && canonicalizeTodoArtifact(planSeed(desired, null, member.plan, splitMarks))
363
373
  === canonicalizeTodoArtifact(planSeed(member.plan, null));
364
374
  const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
365
375
  let revision;
366
376
  let featureChainFindings = null;
377
+ if (binding !== null && splitMarks !== null) fail('plan_revise_split_unsupported', '/', { cause: 'backchain_bound' });
367
378
  if (binding !== null && !unchanged) {
368
379
  ({ revision, findings: featureChainFindings } = await compileBackchainRevision({
369
380
  repoRoot, member, authoring: desired,
370
381
  chain: successorBackchain(binding.chain, desired, continuity) }));
371
382
  } else {
372
- revision = compileLightRevision({ member, desired, continuity });
383
+ revision = compileLightRevision({ member, desired, continuity, splitMarks });
373
384
  if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
374
385
  }
375
386
  let applied = null;
@@ -400,6 +411,8 @@ export async function applyPlanRevision({
400
411
  throw error;
401
412
  }
402
413
  }
414
+ const declarations = dryRun || touches.length === 0 ? null
415
+ : await (await import('./todo-cli.mjs')).declareTouches({ repoRoot, planKey: revision.plan_key, touches });
403
416
  const result = {
404
417
  schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
405
418
  project_id: revision.project_id, plan_key: revision.plan_key,
@@ -407,6 +420,7 @@ export async function applyPlanRevision({
407
420
  dry_run: dryRun, revision: unchanged ? null : revision, applied,
408
421
  continuity, rebound_task_ids: reboundTaskIds,
409
422
  ...(featureChainFindings === null ? {} : { feature_chain_findings: featureChainFindings }),
423
+ ...(declarations === null ? {} : { declarations }),
410
424
  result_digest: '',
411
425
  };
412
426
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -15,7 +15,7 @@ import { TodoStoreError } from './todo-store.mjs';
15
15
  const REVIEW_SCHEMA = 'lattice.plan_scope_review.v1';
16
16
  const RESULT_SCHEMA = 'lattice.plan_scope_review_result.v1';
17
17
  // a31: 席が書く既定(v5、template)も審査できる。schemaを省いた入力はv5として読む(plan createと同じ)。
18
- const PLAN_CREATE_SCHEMAS = new Set(['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5']);
18
+ const PLAN_CREATE_SCHEMAS = new Set(['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5', 'lattice.plan_create_input.v6']);
19
19
  const DEFAULT_PLAN_CREATE_SCHEMA = 'lattice.plan_create_input.v5';
20
20
  const TODO_EXTRACTION_SCHEMAS = new Set([
21
21
  'lattice.todo_extraction.v3',
@@ -44,6 +44,9 @@ import {
44
44
  import {
45
45
  computeTodoDispatchShapeForPlan,
46
46
  } from './todo-dispatch-shape.mjs';
47
+ import { splitTouches } from './todo-declaration.mjs';
48
+ import { readTodoRelationSummary } from './todo-relation-store.mjs';
49
+ import { splitLabels } from './todo-split-labels.mjs';
47
50
  import { completeCreateInput, explainFlagCommand, readAuthoringJsonFile, resolveTodoActor } from './todo-authoring-input.mjs';
48
51
  import { publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
49
52
 
@@ -151,6 +154,15 @@ export function validateProjectStatus(value) {
151
154
  * store読みは呼び出し側が済ませている。ここが払うのはplanごとの小さな記録ファイルと、
152
155
  * 記録があるときだけのHEAD照合である。readyが無いplanは述べる対象が無いので載せない。
153
156
  */
157
+ /** a5c: the plan's function-level relation count from its one summary file (ADR 0204 §5), or null when it has none. */
158
+ async function relationSummaryOf(repoRoot, planKey) {
159
+ try {
160
+ const summary = await readTodoRelationSummary({ repoRoot, planKey });
161
+ return summary === null || summary.relation_count === 0 ? null
162
+ : { relation_count: summary.relation_count, unresolved_count: summary.unresolved_count, head_sha: summary.head_sha };
163
+ } catch (error) { return { unreadable: error?.detail?.reason ?? error?.code ?? 'relations_unreadable' }; }
164
+ }
165
+
154
166
  async function summarizeIndependence({ repoRoot, store, todo }) {
155
167
  const readyPlanKeys = [...new Set(todo.next_ready.map(({ plan_key: key }) => key))].sort();
156
168
  if (readyPlanKeys.length === 0) return [];
@@ -189,8 +201,10 @@ async function summarizeIndependence({ repoRoot, store, todo }) {
189
201
  currentBaseSha: currentBaseSha ?? PLACEHOLDER_SHA,
190
202
  changedPaths: null,
191
203
  });
204
+ const functionConflicts = await relationSummaryOf(repoRoot, planKey);
192
205
  summaries.push({
193
206
  plan_key: planKey,
207
+ ...(functionConflicts === null ? {} : { function_conflicts: functionConflicts }),
194
208
  coverage: projected.coverage,
195
209
  guidance: selectIndependenceGuidance({
196
210
  coverage: projected.coverage,
@@ -445,6 +459,8 @@ export async function runSessionContext({ cwd, stdout, cliVersion, env = process
445
459
  // todoは`lattice todo status`のresultそのもの。新しい意味論を発明しない。
446
460
  todo: state.todo,
447
461
  independence,
462
+ // ADR 0205 §7: additive; `todo` above is the status projection and keeps its exact shape
463
+ ...(state.store === null || splitLabels(state.store).length === 0 ? {} : { labels: splitLabels(state.store) }),
448
464
  turn: projectTurn({
449
465
  store: state.store, todo: state.todo, actor: resolveTodoActor(env),
450
466
  // 名乗れないときの理由はstatusが既に持つ(invalidはnext_action.reason、未初期化はstate)。
@@ -827,7 +843,8 @@ export async function runPlanCreate({
827
843
  next_action: `Omit project_id (the machine fills "${projectId}") or set it to "${projectId}".`,
828
844
  });
829
845
  }
830
- const input = completeCreateInput(given, { env, now: new Date(), projectId, planVersion: 'v1' });
846
+ const { input: authored, touches } = splitTouches(given);
847
+ const input = completeCreateInput(authored, { env, now: new Date(), projectId, planVersion: 'v1' });
831
848
  validatePlanCreateInput(input);
832
849
  // a27: 同じplanの中の無いtaskを指す辺と循環は、入力の誤りとして作業を名指して返す。
833
850
  // createだけで見る(revise・dependency connectは自分の辺を名指す拒否を持つ)。Storeの検査は最後の砦のまま。
@@ -876,6 +893,8 @@ export async function runPlanCreate({
876
893
  });
877
894
  });
878
895
  const member = store.members.find(({ plan }) => plan.plan_key === input.plan_key);
896
+ const declarations = touches.length === 0 ? null
897
+ : await (await import('./todo-cli.mjs')).declareTouches({ repoRoot, planKey: input.plan_key, touches });
879
898
  const result = {
880
899
  schema: CREATE_RESULT_SCHEMA, project_id: store.project_id,
881
900
  plan_key: member.plan.plan_key, plan_version: member.plan.plan_version,
@@ -891,6 +910,7 @@ export async function runPlanCreate({
891
910
  // ADR 0147裁定3: phase無し(v3)のplan createは拒否せず、終端監査が要ることを結果へ
892
911
  // 明示するに留める。phase入力(v4/v5)ならfalse——既存のPhase gateがそのまま重監査を担う。
893
912
  terminal_audit_required: isPhaselessTodoPlanSchema(member.plan.schema),
913
+ ...(declarations === null ? {} : { declarations }),
894
914
  result_digest: '',
895
915
  };
896
916
  result.result_digest = resultDigest(result);
@@ -908,8 +928,8 @@ export async function runPlanCreate({
908
928
  * 既に機械可読に持っている。壊さずに追加のkeyを足す理由が無いので足さない。
909
929
  */
910
930
  export async function runPlanCreateSchema({ stdout, version = 5 }) {
911
- if (![1, 2, 3, 4, 5].includes(version)) throw new TypeError('unsupported plan create schema version');
912
- const expected = version === 5 ? DONE_CONDITION_CREATE_INPUT_SCHEMA : version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
931
+ if (![1, 2, 3, 4, 5, 6].includes(version)) throw new TypeError('unsupported plan create schema version');
932
+ const expected = version === 6 ? 'lattice.plan_create_input.v6' : version === 5 ? DONE_CONDITION_CREATE_INPUT_SCHEMA : version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
913
933
  : version === 3 ? DECOUPLED_PHASE_CREATE_INPUT_SCHEMA
914
934
  : version === 2 ? PHASE_CREATE_INPUT_SCHEMA : CREATE_INPUT_SCHEMA;
915
935
  const schemaUrl = new URL(`../docs/schemas/lattice.plan_create_input.v${version}.schema.json`, import.meta.url);