@quolu/lattice 0.108.0 → 0.109.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 (34) 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 +20 -6
  17. package/src/plan-revise.mjs +12 -1
  18. package/src/plan-scope-review.mjs +1 -1
  19. package/src/project-cli.mjs +20 -3
  20. package/src/runtime-front-end.mjs +8 -3
  21. package/src/sensor-cli.mjs +82 -1
  22. package/src/sensor-resolve.mjs +116 -0
  23. package/src/sensor-touched.mjs +76 -0
  24. package/src/todo-authoring-input.mjs +1 -0
  25. package/src/todo-cli.mjs +195 -22
  26. package/src/todo-contracts.mjs +62 -0
  27. package/src/todo-declaration.mjs +165 -0
  28. package/src/todo-independence-authoritative-observation.mjs +26 -23
  29. package/src/todo-independence-contracts.mjs +17 -4
  30. package/src/todo-independence.mjs +4 -1
  31. package/src/todo-judgment.mjs +141 -0
  32. package/src/todo-relation-store.mjs +294 -0
  33. package/src/todo-store.mjs +8 -4
  34. package/src/witness-scaffold.mjs +23 -15
@@ -5,7 +5,9 @@ import path from 'node:path';
5
5
  import { promisify } from 'node:util';
6
6
  import sensorPackage from '../sensor/package.json' with { type: 'json' };
7
7
  import { compareSensorIndexes, parseSensorDiffArgs, SensorDiffError } from './sensor-diff.mjs';
8
+ import { parseAnchor, resolveAnchors, SensorResolveError } from './sensor-resolve.mjs';
8
9
  import { spawnSensorCli } from './sensor-runtime.mjs';
10
+ import { touchedFunctions } from './sensor-touched.mjs';
9
11
 
10
12
  const MAX_CAPTURE_BYTES = 1024 * 1024;
11
13
  const MAX_DIAGNOSTIC_BYTES = 16 * 1024;
@@ -17,7 +19,9 @@ function writeJson(stream, value) {
17
19
  const USAGE = 'usage: lattice sensor <init|sync> [path] [--json]'
18
20
  + ' | lattice sensor diff <rootA> <rootB>'
19
21
  + ' [--subtree-a <rel>] [--subtree-b <rel>] [--map-a <from>=<to>] [--map-b <from>=<to>]'
20
- + ' [--limit <n>] [--json]';
22
+ + ' [--limit <n>] [--json]'
23
+ + ' | lattice sensor resolve <path#symbol>... [--path <root>] [--related] [--json]'
24
+ + ' | lattice sensor touched <from> [<to>] [--path <root>] [--json]';
21
25
 
22
26
  function usage(stderr) {
23
27
  writeJson(stderr, { schema: 'lattice.cli_error.v2', code: 'USAGE', message: USAGE });
@@ -27,6 +31,28 @@ function usage(stderr) {
27
31
  function parse(argv) {
28
32
  if (argv.at(-1) !== '--json') return null;
29
33
  const words = argv.slice(0, -1);
34
+ if (words[0] === 'resolve') {
35
+ const anchors = [];
36
+ let root = '.';
37
+ let related = false;
38
+ for (let i = 1; i < words.length; i++) {
39
+ if (words[i] === '--related') related = true;
40
+ else if (words[i] === '--path') { root = words[++i]; if (root === undefined) return null; }
41
+ else if (words[i].startsWith('-')) return null;
42
+ else anchors.push(words[i]);
43
+ }
44
+ return anchors.length === 0 ? null : { command: 'resolve', resolve: { anchors, root, related } };
45
+ }
46
+ if (words[0] === 'touched') {
47
+ const refs = [];
48
+ let root = '.';
49
+ for (let i = 1; i < words.length; i++) {
50
+ if (words[i] === '--path') { root = words[++i]; if (root === undefined) return null; }
51
+ else if (words[i].startsWith('-')) return null;
52
+ else refs.push(words[i]);
53
+ }
54
+ return refs.length < 1 || refs.length > 2 ? null : { command: 'touched', touched: { from: refs[0], to: refs[1] ?? 'HEAD', root } };
55
+ }
30
56
  if (words[0] === 'diff') {
31
57
  const request = parseSensorDiffArgs(words.slice(1));
32
58
  return request === null ? null : { command: 'diff', diff: request };
@@ -60,6 +86,59 @@ function runDiff(request, stdout, stderr) {
60
86
  }
61
87
  }
62
88
 
89
+ /**
90
+ * a3 (ADR 0204 Resolve): `path#symbol` → line spans. An anchor that does not resolve is an answer (`unresolved`, with the
91
+ * nearest names), exit 0; malformed text is listed, never guessed. No index → the same typed error as `sensor sync`.
92
+ */
93
+ async function runResolve({ anchors, root, related }, stdout, stderr) {
94
+ try {
95
+ const parsed = anchors.map((text) => ({ text, anchor: parseAnchor(text) }));
96
+ const result = await resolveAnchors({ root: path.resolve(root), anchors: parsed.flatMap((p) => p.anchor ?? []), related });
97
+ writeJson(stdout, {
98
+ schema: 'lattice.sensor_resolve_result.v1',
99
+ sensor_version: sensorPackage.version,
100
+ ...result,
101
+ malformed: parsed.filter((p) => p.anchor === null).map((p) => p.text),
102
+ });
103
+ return 0;
104
+ } catch (error) {
105
+ const typed = error instanceof SensorResolveError;
106
+ writeJson(stderr, {
107
+ schema: 'lattice.cli_error.v2',
108
+ code: error?.code === 'RESOLVE_INDEX_MISSING' ? 'LATTICE_SENSOR_NOT_INITIALIZED'
109
+ : error?.code === 'LATTICE_SENSOR_UNAVAILABLE' ? error.code : 'LATTICE_SENSOR_COMMAND_FAILED',
110
+ message: 'LatticeSensor resolve failed',
111
+ detail: typed ? { ...error.detail, next_action: error.code === 'RESOLVE_INDEX_MISSING' ? `lattice sensor init ${root} --json` : null }
112
+ : { cause: error?.message ?? 'unknown error' },
113
+ });
114
+ return 1;
115
+ }
116
+ }
117
+
118
+ /** a6 (ADR 0204 Touched): commit range -> changed symbols. A bad ref or git failure is typed; unattributed hunks are an answer. */
119
+ async function runTouched({ from, to, root }, stdout, stderr) {
120
+ try {
121
+ writeJson(stdout, {
122
+ schema: 'lattice.sensor_touched_result.v1',
123
+ sensor_version: sensorPackage.version,
124
+ ...await touchedFunctions({ repoRoot: path.resolve(root), from, to }),
125
+ });
126
+ return 0;
127
+ } catch (error) {
128
+ const notInitialized = error?.code === 'RESOLVE_INDEX_MISSING';
129
+ writeJson(stderr, {
130
+ schema: 'lattice.cli_error.v2',
131
+ code: notInitialized ? 'LATTICE_SENSOR_NOT_INITIALIZED'
132
+ : error?.code === 'LATTICE_SENSOR_UNAVAILABLE' ? error.code
133
+ : error?.code === 'TOUCHED_GIT_FAILED' ? 'LATTICE_SENSOR_TOUCHED_GIT_FAILED' : 'LATTICE_SENSOR_COMMAND_FAILED',
134
+ message: 'LatticeSensor touched failed',
135
+ detail: { ...(error?.detail ?? { cause: error?.message ?? 'unknown error' }),
136
+ next_action: notInitialized ? `lattice sensor init ${root} --json` : null },
137
+ });
138
+ return 1;
139
+ }
140
+ }
141
+
63
142
  /**
64
143
  * g2: the index (`.lattice/sensor/`, ~143 MB) must not be committed by `git add -A` in a product clone; not a git work tree = nothing to do.
65
144
  * Only the index: `.lattice/todo` may be tracked or added in the same repo (ignoring all of `.lattice/` broke `git add .lattice/todo`).
@@ -122,6 +201,8 @@ export async function runSensorCli({ argv, stdout, stderr }) {
122
201
  const request = parse(argv);
123
202
  if (!request) return usage(stderr);
124
203
  if (request.command === 'diff') return runDiff(request.diff, stdout, stderr);
204
+ if (request.command === 'resolve') return runResolve(request.resolve, stdout, stderr);
205
+ if (request.command === 'touched') return runTouched(request.touched, stdout, stderr);
125
206
  if (!existsSync(request.path)) {
126
207
  writeJson(stderr, { schema: 'lattice.cli_error.v2', code: 'LATTICE_SENSOR_PATH_MISSING',
127
208
  message: `no such project path: ${request.path}`,
@@ -0,0 +1,116 @@
1
+ // Code graph role, public interface "Resolve" (ADR 0204 §4, a3). Plan/lifecycle calls these two functions; it never reads
2
+ // `sensor/` or the index. One sensor process per call; the index must exist (Observe makes it).
3
+ import { spawn } from 'node:child_process';
4
+
5
+ import { sensorCliInvocation } from './sensor-runtime.mjs';
6
+
7
+ export class SensorResolveError extends Error {
8
+ constructor(code, message, detail = {}) {
9
+ super(message);
10
+ this.name = 'SensorResolveError';
11
+ this.code = code;
12
+ this.detail = detail;
13
+ }
14
+ }
15
+
16
+ /** `path#symbol` → `{path, symbol}`. Splits at the FIRST `#` (Ruby `Foo#bar` stays in the symbol); null = malformed. */
17
+ export function parseAnchor(text) {
18
+ if (typeof text !== 'string') return null;
19
+ const at = text.indexOf('#');
20
+ if (at <= 0 || at === text.length - 1) return null;
21
+ const path = text.slice(0, at).trim();
22
+ const symbol = text.slice(at + 1).trim();
23
+ return path === '' || symbol === '' ? null : { path, symbol };
24
+ }
25
+
26
+ // An identifier a person means as code: camelCase, snake_case, a Capitalised.dotted chain, or one in backticks / followed by `(`.
27
+ const CODE_TOKEN = /`([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)`|\b([A-Za-z_$][\w$]*)\(|\b([A-Z][\w$]*\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*|[A-Za-z_$][\w$]*[_][\w$]*|[a-z][a-z0-9]*[A-Z][\w$]*|[A-Z][a-z0-9]+[A-Z][\w$]*)\b/gu;
28
+ const MAX_NAMES = 30;
29
+
30
+ /** Identifier candidates in a task's title / design memo, in order of appearance, last dotted part only. */
31
+ export function identifiersFromText(...texts) {
32
+ const names = new Set();
33
+ for (const text of texts) {
34
+ if (typeof text !== 'string') continue;
35
+ for (const match of text.matchAll(CODE_TOKEN)) {
36
+ const raw = match[1] ?? match[2] ?? match[3];
37
+ const name = raw.split('.').at(-1);
38
+ if (name.length >= 3) names.add(name);
39
+ if (names.size >= MAX_NAMES) return [...names];
40
+ }
41
+ }
42
+ return [...names];
43
+ }
44
+
45
+ /** One sensor process, JSON on stdin and stdout; shared by Resolve and Touched. */
46
+ export function runSensorJson({ command, root, request }) {
47
+ const invocation = sensorCliInvocation([command, '--path', root]);
48
+ return new Promise((resolve, reject) => {
49
+ const child = spawn(invocation.command, invocation.args, {
50
+ stdio: ['pipe', 'pipe', 'pipe'], shell: false,
51
+ env: { ...process.env, LATTICE_SENSOR_NO_UPDATE_CHECK: '1', DO_NOT_TRACK: '1', NO_COLOR: '1' },
52
+ });
53
+ const out = [];
54
+ const err = [];
55
+ child.stdout.on('data', (chunk) => out.push(chunk));
56
+ child.stderr.on('data', (chunk) => err.push(chunk));
57
+ child.once('error', reject);
58
+ child.once('close', (code) => {
59
+ const stderr = Buffer.concat(err).toString('utf8').trim();
60
+ if (code !== 0) {
61
+ reject(new SensorResolveError(
62
+ /not initialized/u.test(stderr) ? 'RESOLVE_INDEX_MISSING' : 'RESOLVE_SENSOR_FAILED',
63
+ `sensor ${command} failed`, { exit_code: code, stderr },
64
+ ));
65
+ return;
66
+ }
67
+ try { resolve(JSON.parse(Buffer.concat(out).toString('utf8'))); } catch (error) {
68
+ reject(new SensorResolveError('RESOLVE_OUTPUT_INVALID', `sensor ${command} returned invalid JSON`, { cause: error.message }));
69
+ }
70
+ });
71
+ child.stdin.end(JSON.stringify(request));
72
+ });
73
+ }
74
+
75
+ const snake = ({ startLine, endLine, qualified, ...rest }) => ({ ...rest, qualified, start_line: startLine, end_line: endLine });
76
+
77
+ /**
78
+ * Resolve `{path, symbol}[]` against the maintained index of `root`.
79
+ * → `{resolved: [{path, symbol, qualified, kind, start_line, end_line, related?}], unresolved: [{path, symbol, reason, nearest[], elsewhere[]}],
80
+ * ambiguous: [{path, symbol, names[]}]}`
81
+ * Exact match only. A symbol with several definitions in its file (overloads, same name in two classes) returns every span, and
82
+ * `ambiguous` names the case when they are different definitions. `unresolved` is an answer, not an error.
83
+ */
84
+ export async function resolveAnchors({ root, anchors, related = false }) {
85
+ const result = await runSensorJson({ command: 'resolve', root, request: { anchors, related } });
86
+ const moveRelated = (node) => (node.related === undefined ? node : {
87
+ ...node,
88
+ related: Object.fromEntries(Object.entries(node.related).map(([key, value]) => [key,
89
+ Array.isArray(value) ? value.map(snake) : value])),
90
+ });
91
+ return {
92
+ resolved: result.resolved.map((node) => moveRelated(snake(node))),
93
+ unresolved: result.unresolved.map((anchor) => ({
94
+ ...anchor, nearest: anchor.nearest.map(snake), elsewhere: anchor.elsewhere.map(snake),
95
+ })),
96
+ ambiguous: result.ambiguous,
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Seed fallback (2b): identifiers in the task's title and design memo that name graph symbols exactly. A proposal for the AI
102
+ * that adds the task; nothing is recorded. `missed` says what the text did not name, so "no proposal" is never read as "touches
103
+ * nothing".
104
+ * → `{proposed: [{name, definitions: [{path, symbol, kind, start_line, end_line}]}], too_common: [name], not_found: [name]}`
105
+ */
106
+ export async function proposeSymbols({ root, title, memo }) {
107
+ const names = identifiersFromText(title, memo);
108
+ if (names.length === 0) return { proposed: [], too_common: [], not_found: [] };
109
+ const { named } = await runSensorJson({ command: 'resolve', root, request: { names } });
110
+ return {
111
+ proposed: named.filter((n) => n.definitions.length > 0)
112
+ .map((n) => ({ name: n.name, definitions: n.definitions.map(snake) })),
113
+ too_common: named.filter((n) => n.tooCommon).map((n) => n.name),
114
+ not_found: named.filter((n) => !n.tooCommon && n.definitions.length === 0).map((n) => n.name),
115
+ };
116
+ }
@@ -0,0 +1,76 @@
1
+ // Code graph role, public interface "Touched" (ADR 0204 §4, a6): commit range -> the symbols the hunks changed.
2
+ // Plan/lifecycle records the answer on the task; it never reads the diff or the index itself.
3
+ import { gitSpawnSync } from './git-process.mjs';
4
+ import { runSensorJson, SensorResolveError } from './sensor-resolve.mjs';
5
+ import { withObservedTree } from './todo-independence-authoritative-observation.mjs';
6
+
7
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u;
8
+
9
+ function gitText(repoRoot, args) {
10
+ const result = gitSpawnSync(['-c', 'core.quotepath=off', ...args], {
11
+ cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024,
12
+ });
13
+ if (result.error !== undefined || result.status !== 0) {
14
+ throw new SensorResolveError('TOUCHED_GIT_FAILED', `git ${args[0]} failed`, { stderr: result.stderr?.trim() ?? result.error?.message });
15
+ }
16
+ return result.stdout;
17
+ }
18
+
19
+ /** `"a b.js"` (git quotes names with special characters) or `a/b.js` -> `b.js`; `/dev/null` -> null. */
20
+ function pathOf(text, prefix) {
21
+ const name = text.endsWith('\t') ? text.slice(0, -1) : text;
22
+ if (name === '/dev/null') return null;
23
+ const unquoted = name.startsWith('"') ? JSON.parse(name) : name;
24
+ return unquoted.startsWith(prefix) ? unquoted.slice(prefix.length) : unquoted;
25
+ }
26
+
27
+ /** `git diff -U0 --find-renames` text -> `[{path, old_path, status, hunks: [{old_start, old_count, new_start, new_count}]}]`. */
28
+ export function parseUnifiedZeroDiff(text) {
29
+ const files = [];
30
+ let file = null;
31
+ for (const line of text.split('\n')) {
32
+ if (line.startsWith('diff --git ')) {
33
+ const names = / a\/(.+) b\/(.+)$/u.exec(line);
34
+ file = { path: names?.[2] ?? '', old_path: null, status: 'modified', hunks: [] };
35
+ files.push(file);
36
+ } else if (file === null) {
37
+ continue;
38
+ } else if (line.startsWith('@@')) {
39
+ const match = HUNK.exec(line);
40
+ if (match !== null) {
41
+ file.hunks.push({
42
+ old_start: Number(match[1]), old_count: match[2] === undefined ? 1 : Number(match[2]),
43
+ new_start: Number(match[3]), new_count: match[4] === undefined ? 1 : Number(match[4]),
44
+ });
45
+ }
46
+ } else if (file.hunks.length > 0) {
47
+ continue; // hunk content: a removed `-- sql comment` reads like a `---` header, so headers are only read before the first hunk
48
+ } else if (line.startsWith('new file mode')) file.status = 'added';
49
+ else if (line.startsWith('deleted file mode')) file.status = 'deleted';
50
+ else if (line.startsWith('rename from ')) { file.status = 'renamed'; file.old_path = line.slice(12); }
51
+ else if (line.startsWith('rename to ')) file.path = line.slice(10);
52
+ else if (line.startsWith('Binary files ') || line.startsWith('GIT binary patch')) file.status = 'binary';
53
+ else if (line.startsWith('+++ ')) { const now = pathOf(line.slice(4), 'b/'); if (now !== null) file.path = now; }
54
+ }
55
+ return files;
56
+ }
57
+
58
+ /**
59
+ * Which symbols did `from..to` change? `to` need not be HEAD: a clean HEAD uses the maintained index (Observe), anything else a
60
+ * disposable worktree of `to` with a fresh index. Never reads the working tree's uncommitted state.
61
+ * -> `{from_sha, to_sha, touched: [{path, symbol, kind, start_line, end_line}], unattributed: [{path, reason, old_range, new_range}]}`
62
+ * `unattributed` (imports, top-level code, deleted functions, renames, binary or unindexed files) counts as file-level, never as
63
+ * "touched nothing".
64
+ */
65
+ export async function touchedFunctions({ repoRoot, from, to = 'HEAD' }) {
66
+ const resolve = (ref) => gitText(repoRoot, ['rev-parse', '--verify', `${ref}^{commit}`]).trim();
67
+ const fromSha = resolve(from);
68
+ const toSha = resolve(to);
69
+ const files = parseUnifiedZeroDiff(gitText(repoRoot, [
70
+ 'diff', '--no-color', '--no-ext-diff', '--unified=0', '--find-renames', fromSha, toSha,
71
+ ]));
72
+ if (files.length === 0) return { from_sha: fromSha, to_sha: toSha, touched: [], unattributed: [] };
73
+ const answer = await withObservedTree({ repoRoot, sha: toSha },
74
+ (root) => runSensorJson({ command: 'touched', root, request: { files } }));
75
+ return { from_sha: fromSha, to_sha: toSha, touched: answer.touched, unattributed: answer.unattributed };
76
+ }
@@ -66,6 +66,7 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
66
66
  'lattice.todo_witness_set.v3': 'witness_set_digest',
67
67
  'lattice.todo_witness_set.v4': 'witness_set_digest',
68
68
  'lattice.todo_witness_set.v5': 'witness_set_digest',
69
+ 'lattice.todo_witness_set.v6': 'witness_set_digest',
69
70
  'lattice.todo_extraction.v2': 'extraction_digest',
70
71
  'lattice.todo_extraction.v3': 'extraction_digest',
71
72
  'lattice.todo_extraction.v4': 'extraction_digest',
package/src/todo-cli.mjs CHANGED
@@ -201,6 +201,9 @@ import {
201
201
  readTodoPlanNotesForStatus,
202
202
  } from './todo-note-store.mjs';
203
203
  import { dependencyNoteBody, todoAddNoteBody } from './todo-revision-note.mjs';
204
+ import { buildDeclarationRow, declaredPaths, proposeFromText, resolveDeclaredRanges } from './todo-declaration.mjs';
205
+ import { anchorsOf, claimsOf, judgeTask, neededAnchors, rangeIndex, relationView } from './todo-judgment.mjs';
206
+ import { readTodoRelationSummary, readTodoTaskRelations, transactTodoRelations } from './todo-relation-store.mjs';
204
207
  import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
205
208
  import { commitTodoStoreMutation } from './todo-store-git-transaction.mjs';
206
209
  import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
@@ -343,7 +346,7 @@ const TODO_FLAG_SPECS = Object.freeze({
343
346
  reopen: Object.freeze({ known: ['plan', 'task', 'reason', 'override-reason'], required: ['plan', 'task', 'reason'] }),
344
347
  'dependency connect': DEPENDENCY_FLAG_SPEC,
345
348
  add: Object.freeze({
346
- known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason'],
349
+ known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason', 'owns', 'reads'],
347
350
  required: ['plan', 'task', 'title'],
348
351
  }),
349
352
  'dependency disconnect': DEPENDENCY_FLAG_SPEC,
@@ -1345,9 +1348,11 @@ async function startTask({
1345
1348
  };
1346
1349
  }
1347
1350
  // 助言はjournalへ書く前に確定させる。助言はstartを止めない(u03 B1–B6)。
1348
- const advisory = await startAdvisory({
1351
+ const startAdvice = await startAdvisory({
1349
1352
  repoRoot, store, projection, planKey, taskId: resolvedTaskId,
1350
1353
  });
1354
+ const relations = await taskRelations({ repoRoot, planKey, taskId: resolvedTaskId });
1355
+ const advisory = relations === null ? startAdvice : { ...startAdvice, relations };
1351
1356
  if (member.coordination?.mode === 'enforced' && !(await noCodeTask({ repoRoot, member, taskId: resolvedTaskId }))) {
1352
1357
  enforcedStartGate({ advisory, planKey, taskId: resolvedTaskId, overrideReason });
1353
1358
  }
@@ -1370,6 +1375,23 @@ async function startTask({
1370
1375
  structureContext, featureContext, externalTasks: store.external_tasks ?? [] });
1371
1376
  }
1372
1377
 
1378
+ /**
1379
+ * a5c/a5d: the open function-level relations of one task, for `todo start` and `todo show` (ADR 0204 §5). One call reads the
1380
+ * plan's summary and this task's own small file, never the history (ADR 0203, a4c).
1381
+ * → null when the plan has none (the field is then left out), else `{open: [relationView], plan_relation_count, unresolved_count,
1382
+ * head_sha}`; an unreadable record is named, never refused: an unknown state is not dangerous.
1383
+ */
1384
+ async function taskRelations({ repoRoot, planKey, taskId }) {
1385
+ try {
1386
+ const read = await readTodoTaskRelations({ repoRoot, planKey, taskId });
1387
+ if (read === null) return null;
1388
+ return { open: read.open.map((relation) => relationView(taskId, relation)),
1389
+ plan_relation_count: read.relation_count, unresolved_count: read.unresolved_count, head_sha: read.head_sha };
1390
+ } catch (error) {
1391
+ return { unreadable: error?.detail?.reason ?? error?.code ?? 'relations_unreadable' };
1392
+ }
1393
+ }
1394
+
1373
1395
  /** declare-without-git: HEAD does not resolve (no commit) and the plan's witness set records this task's row. */
1374
1396
  async function declaredWithoutHead({ repoRoot, planKey, taskId }) {
1375
1397
  if (headResolves(repoRoot)) return false;
@@ -1691,9 +1713,10 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1691
1713
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1692
1714
  notes: [{ task_id: taskId, body: todoAddNoteBody(taskId, reason) }],
1693
1715
  });
1716
+ const declaration = await declareOnAdd({ repoRoot, planKey, taskId, flags });
1694
1717
  const result = {
1695
- schema: 'lattice.todo_task_add_result.v1', project_id: store.project_id, plan_key: planKey,
1696
- task_id: taskId, after, before, reason, actor: desired.actor,
1718
+ schema: 'lattice.todo_task_add_result.v2', project_id: store.project_id, plan_key: planKey,
1719
+ task_id: taskId, after, before, reason, actor: desired.actor, declaration,
1697
1720
  plan_version: applied.plan_version, revision_digest: applied.revision?.revision_digest ?? null,
1698
1721
  rebound_task_ids: applied.rebound_task_ids, result_digest: '',
1699
1722
  };
@@ -1701,6 +1724,41 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1701
1724
  return result;
1702
1725
  }
1703
1726
 
1727
+ /**
1728
+ * ADR 0204: the functions the new task changes, written once now. The task is already added; nothing here can refuse the add,
1729
+ * so a failure comes back as `declaration` (`written: false`) and the same flags are given again to `witness declare`.
1730
+ * Without seeds the title and design memo are searched for names that exist in the code graph; those are proposed, never recorded.
1731
+ */
1732
+ async function declareOnAdd({ repoRoot, planKey, taskId, flags }) {
1733
+ const seeded = (value) => typeof value === 'string' || Array.isArray(value);
1734
+ if (!seeded(flags.owns) && !seeded(flags.reads)) {
1735
+ const proposed = await proposeFromText({ root: repoRoot, observable: headResolves(repoRoot), title: flags.title, memo: flags['design-memo'] });
1736
+ return { written: false, resolved: [], unresolved: [], malformed: [], proposed };
1737
+ }
1738
+ try {
1739
+ const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable: headResolves(repoRoot) });
1740
+ return declared.declaration;
1741
+ } catch (error) {
1742
+ if (!(error instanceof TodoStoreError)) throw error;
1743
+ return { written: false, resolved: [], unresolved: [], malformed: [],
1744
+ refused: { code: error.code, ...error.detail } };
1745
+ }
1746
+ }
1747
+
1748
+ /**
1749
+ * Plan create/revise input `tasks[].touches` (ADR 0204 §6): declared after the plan is written, one row per task through the same
1750
+ * path as `todo add`. A task's failure comes back under its id and never undoes the plan. → `{task_id: declaration}`, or null.
1751
+ * shortcut: one Resolve and one witness write per task; batch them when a plan routinely declares dozens of tasks.
1752
+ */
1753
+ export async function declareTouches({ repoRoot, planKey, touches }) {
1754
+ if (touches.length === 0) return null;
1755
+ const declarations = {};
1756
+ for (const { task_id: taskId, owns, reads } of touches) {
1757
+ declarations[taskId] = await declareOnAdd({ repoRoot, planKey, taskId, flags: { owns, reads } });
1758
+ }
1759
+ return declarations;
1760
+ }
1761
+
1704
1762
  const samePlanEdge = (member, fromTaskId, toTaskId) => member.plan.hard_dependencies.some((edge) => (
1705
1763
  edge.from.task_id === fromTaskId && edge.to.task_id === toTaskId));
1706
1764
 
@@ -2691,6 +2749,7 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
2691
2749
  const featureContext = await readTaskBackchainContext({
2692
2750
  repoRoot, plan: member.plan, taskId: task.task_id,
2693
2751
  });
2752
+ const relations = await taskRelations({ repoRoot, planKey, taskId: task.task_id });
2694
2753
  const result = {
2695
2754
  schema: featureContext === null ? 'lattice.todo_detail_result.v3' : 'lattice.todo_detail_result.v4',
2696
2755
  project_id: store.project_id,
@@ -2702,6 +2761,7 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
2702
2761
  state,
2703
2762
  prerequisites: taskPrerequisites(store, member, task.task_id),
2704
2763
  note_context: context,
2764
+ ...(relations === null ? {} : { relations }),
2705
2765
  ...(featureContext === null ? {} : { feature_context: featureContext }),
2706
2766
  result_digest: '',
2707
2767
  };
@@ -3494,6 +3554,10 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3494
3554
  // INDEPENDENCE_ARTIFACT_INVALIDでtyped fail」を既に区別している。ここでcatchすると
3495
3555
  // **corrupt/permission/I-Oまで「初回」へ化けて履歴が黙って切れる**(suzune の監査で実測・room [1148])。
3496
3556
  const previousArtifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
3557
+ // a5b: resolve the declared functions once so the compile judges a path declared with functions by those functions only.
3558
+ const anchors = Object.values(witnessSet.manual_witness).flatMap((row) => anchorsOf(claimsOf(row)));
3559
+ const functionRanges = anchors.length === 0 ? null
3560
+ : rangeIndex(await resolveDeclaredRanges({ root: repoRoot, anchors }));
3497
3561
  const artifact = compileTodoIndependence({
3498
3562
  witnessSet,
3499
3563
  plan: member.plan,
@@ -3501,6 +3565,7 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3501
3565
  compiledAt: new Date().toISOString(),
3502
3566
  sensorEvidence: observation.sensor_evidence,
3503
3567
  previousArtifact,
3568
+ functionRanges,
3504
3569
  });
3505
3570
  const { ref } = await writeTodoIndependenceArtifact({ repoRoot, artifact });
3506
3571
  // compile成功後にだけ、受理した宣言をruntime readerが要求するcanonical bytesで固定する。
@@ -3865,8 +3930,8 @@ async function witnessScaffold({ repoRoot, planKey, inputRef }) {
3865
3930
  return scaffoldWitnessDraft({ repoRoot, planKey, draft });
3866
3931
  }
3867
3932
 
3868
- /** The scaffold itself: fresh observation, wiring and digest for a checked draft, then the write. */
3869
- async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
3933
+ /** The fresh observation a witness set carries: the affected tests of every owned path. → `{paths, observationByPath}`. */
3934
+ async function observeWitnessDraft({ repoRoot, draft }) {
3870
3935
  const { queries, paths } = buildWitnessObservationQuerySet(draft);
3871
3936
  const collected = await collectSensorEvidence({ cwd: repoRoot, querySet: { queries } });
3872
3937
  const observationByPath = {};
@@ -3883,6 +3948,12 @@ async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
3883
3948
  changedFiles: [...entry.data.changedFiles],
3884
3949
  };
3885
3950
  });
3951
+ return { paths, observationByPath };
3952
+ }
3953
+
3954
+ /** The scaffold itself: fresh observation, wiring and digest for a checked draft, then the write. */
3955
+ async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
3956
+ const { paths, observationByPath } = await observeWitnessDraft({ repoRoot, draft });
3886
3957
  const { witnessSet, reasons } = buildWitnessSet({ draft, observationByPath });
3887
3958
  if (witnessSet === null) {
3888
3959
  // 理由コードは具体的なのに次の一手が汎用だと、何をどう直すのかが伝わらない。
@@ -3946,29 +4017,28 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3946
4017
  next_action: `${planKey}/${taskId} is ${state.status}; only unfinished tasks are declared (see \`lattice todo status --json\`).`,
3947
4018
  });
3948
4019
  }
3949
- const recorded = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
3950
- const template = await witnessDraftTemplateFor({ repoRoot, planKey });
3951
- const keep = new Set([...Object.keys(recorded?.plan_key === planKey ? recorded.manual_witness : {}), taskId]);
3952
- const list = (value) => (typeof value === 'string' ? value.split(',').map((item) => item.trim()).filter(Boolean) : []);
3953
- const row = { owns: list(flags.owns), reads: list(flags.reads), writes: list(flags.writes) };
3954
- const draft = { ...template, tasks: Object.fromEntries(Object.entries(template.tasks)
3955
- .filter(([id]) => keep.has(id)).map(([id, task]) => [id, id === taskId ? row : task])) };
3956
- if (!validateWitnessDraft(draft)) {
3957
- const { valid: _valid, reason, path: at, ...keys } = explainWitnessDraft(draft);
3958
- throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
3959
- pointer: at, ...keys, next_action: witnessRoute(planKey) });
3960
- }
3961
- const scaffolded = await scaffoldWitnessDraft({ repoRoot, planKey, draft });
4020
+ const observable = headResolves(repoRoot);
4021
+ const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable });
4022
+ const base = {
4023
+ schema: 'lattice.todo_witness_declare_result.v2', project_id: member.plan.project_id, plan_key: planKey,
4024
+ task_id: taskId, declaration: declared.declaration,
4025
+ };
4026
+ if (declared.scaffolded === null) {
4027
+ // Names that do not resolve never fail the command (ADR 0204 §6): the row stays unwritten and the same declare retries.
4028
+ const result = { ...base, witness_ref: null, witness_set_digest: null, compiled: false, waiting_for: [], compile: null,
4029
+ next_action: declarationNextAction(planKey, taskId, declared.declaration), result_digest: '' };
4030
+ result.result_digest = todoSelfDigest(result, 'result_digest');
4031
+ return result;
4032
+ }
4033
+ const { row, scaffolded, keep } = declared;
3962
4034
  const waitingFor = projectTodoStatus(await readTodoStoreForReadiness({ repoRoot, env }), TODO_STATUS_DISPATCH_ONLY).next_ready
3963
4035
  .filter((task) => task.plan_key === planKey && !keep.has(task.task_id))
3964
4036
  .map(({ task_id: id }) => id).sort();
3965
4037
  // declare-without-git: a Store root with no commit cannot be observed, so the row is recorded and not compiled.
3966
- const observable = headResolves(repoRoot);
3967
4038
  const compile = observable
3968
4039
  ? await independenceCompile({ repoRoot, planKey, inputRef: scaffolded.witness_ref }) : null;
3969
4040
  const result = {
3970
- schema: 'lattice.todo_witness_declare_result.v1', project_id: member.plan.project_id, plan_key: planKey,
3971
- task_id: taskId, ...row, witness_ref: scaffolded.witness_ref,
4041
+ ...base, owns: row.owns, reads: row.reads, writes: row.writes, witness_ref: scaffolded.witness_ref,
3972
4042
  witness_set_digest: scaffolded.witness_set_digest, compiled: compile !== null, waiting_for: waitingFor,
3973
4043
  compile,
3974
4044
  ...(observable ? {} : {
@@ -3982,6 +4052,94 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3982
4052
  return result;
3983
4053
  }
3984
4054
 
4055
+ /** What to do when a declaration was not written: the names that failed, with the nearest ones. */
4056
+ function declarationNextAction(planKey, taskId, declaration) {
4057
+ const parts = [];
4058
+ for (const { text, reason } of declaration.malformed) parts.push(`${text} (${reason}; write path#function, e.g. src/a.mjs#foo or src/a.mjs#Klass.method)`);
4059
+ for (const entry of declaration.unresolved) {
4060
+ const near = entry.nearest.length > 0 ? ` nearest: ${entry.nearest.join(', ')}` : '';
4061
+ const where = entry.elsewhere.length > 0 ? ` found elsewhere: ${entry.elsewhere.join(', ')}` : '';
4062
+ parts.push(`${entry.path}#${entry.symbol} (${entry.reason});${near}${where}`.replace(/;$/u, ''));
4063
+ }
4064
+ return `${planKey}/${taskId}'s functions were not recorded: ${parts.join('; ')}. Correct the names and run the same declaration again;`
4065
+ + ' the task itself is unchanged.';
4066
+ }
4067
+
4068
+ /**
4069
+ * One task's witness row from `--owns/--reads/--writes` (paths, or path#function): resolves the functions through the
4070
+ * code graph and, when every name resolves, writes the plan's witness set with the row and the task's conflict relations
4071
+ * in one `transactTodoRelations` call (ADR 0204 §3, a5). `scaffolded: null` = not written. Never refused for a conflict:
4072
+ * `conflicts` lists the tasks this one overlaps, `[]` when none.
4073
+ * Resolve and the fresh observation run before the Store lock; if another declaration changed the set meanwhile (a row or
4074
+ * path this attempt did not resolve or observe), the call writes nothing and the attempt runs again (three at most).
4075
+ */
4076
+ async function declareTaskRow({ repoRoot, planKey, taskId, flags, observable }) {
4077
+ const store = await readTodoStore({ repoRoot });
4078
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
4079
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
4080
+ const writer = createTodoStoreWriter({ caller: 'todo-relations' });
4081
+ const mine = declaredPaths(flags);
4082
+ const headSha = observable ? currentHeadSha(repoRoot) : null;
4083
+ const peek = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
4084
+ let alsoResolve = neededAnchors(peek?.plan_key === planKey ? peek.manual_witness : {}, taskId, mine);
4085
+ for (let attempt = 0; attempt < 3; attempt += 1) {
4086
+ const { row, declaration, ranges } = await buildDeclarationRow({
4087
+ root: repoRoot, observable, owns: flags.owns, reads: flags.reads, writes: flags.writes, alsoResolve });
4088
+ if (row === null) return { declaration, scaffolded: null };
4089
+ const resolved = new Set([...alsoResolve, ...declaration.resolved].map(({ path: where, symbol }) => `${where}\0${symbol}`));
4090
+ const draftFor = (witnessSet, unfinishedTaskIds) => {
4091
+ const template = witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
4092
+ witnessSet: witnessSet?.plan_key === planKey ? witnessSet : null, taskIds: unfinishedTaskIds });
4093
+ const keep = new Set([...Object.keys(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}), taskId]);
4094
+ const draft = { ...template, tasks: Object.fromEntries(Object.entries(template.tasks)
4095
+ .filter(([id]) => keep.has(id)).map(([id, task]) => [id, id === taskId ? row : task])) };
4096
+ if (!validateWitnessDraft(draft)) {
4097
+ const { valid: _valid, reason, path: at, ...keys } = explainWitnessDraft(draft);
4098
+ throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
4099
+ pointer: at, ...keys, next_action: witnessRoute(planKey) });
4100
+ }
4101
+ return { draft, keep };
4102
+ };
4103
+ const unfinishedNow = member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id);
4104
+ const first = draftFor(peek, unfinishedNow);
4105
+ const observed = await observeWitnessDraft({ repoRoot, draft: first.draft });
4106
+ const known = new Set(observed.paths);
4107
+ let outcome = null;
4108
+ let stale = null;
4109
+ await transactTodoRelations({ repoRoot, planKey, writer, update: ({ witnessSet, openRelations, unfinishedTaskIds }) => {
4110
+ const { draft, keep } = draftFor(witnessSet, unfinishedTaskIds);
4111
+ const missingPaths = buildWitnessObservationQuerySet(draft).paths.filter((target) => !known.has(target));
4112
+ const needed = neededAnchors(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}, taskId, mine);
4113
+ if (missingPaths.length > 0 || needed.some(({ path: where, symbol }) => !resolved.has(`${where}\0${symbol}`))) {
4114
+ stale = needed;
4115
+ return {};
4116
+ }
4117
+ const built = buildWitnessSet({ draft, observationByPath: observed.observationByPath });
4118
+ if (built.witnessSet === null) {
4119
+ const guidance = selectWitnessScaffoldGuidance(built.reasons);
4120
+ throw new TodoStoreError('WITNESS_SCAFFOLD_INCOMPLETE', 'witness_scaffold_incomplete', undefined, {
4121
+ reasons: built.reasons, guidance, next_action: guidance.next_action });
4122
+ }
4123
+ const judged = judgeTask({ taskId, rows: built.witnessSet.manual_witness, ranges: rangeIndex(ranges), openRelations });
4124
+ outcome = { witnessSet: built.witnessSet, judged, keep, paths: observed.paths };
4125
+ return { witnessSet: built.witnessSet, relations: judged.relations, gone: judged.gone, headSha,
4126
+ unresolvedCount: judged.unresolved };
4127
+ } });
4128
+ if (outcome !== null) {
4129
+ const { witnessSet, judged, keep, paths } = outcome;
4130
+ declaration.conflicts = judged.relations.map((relation) => relationView(taskId, relation));
4131
+ const ref = todoWitnessRef(planKey);
4132
+ return { row, declaration, keep, scaffolded: {
4133
+ schema: 'lattice.todo_witness_scaffold_result.v1', project_id: member.plan.project_id, plan_key: planKey, witness_ref: ref,
4134
+ observed_paths: paths, task_count: Object.keys(witnessSet.manual_witness).length,
4135
+ witness_set_digest: witnessSet.witness_set_digest, next_action: independenceCompileCommand(planKey, ref) } };
4136
+ }
4137
+ alsoResolve = stale;
4138
+ }
4139
+ throw new TodoStoreError('STORE_WRITE_CONFLICT', 'witness_set_changing', undefined, {
4140
+ next_action: `Other declarations on ${planKey} kept changing the witness set; run the same declaration again.` });
4141
+ }
4142
+
3985
4143
  /**
3986
4144
  * 着地時に使うsurface名。提案が出すhash由来の仮名を、人が読む名前へ置き換える。
3987
4145
  *
@@ -4702,6 +4860,18 @@ function writesTodoStore(argv) {
4702
4860
  }
4703
4861
  }
4704
4862
 
4863
+ /**
4864
+ * a5: `todo done` / `todo retire` do not take the relations lock, so a finished task can leave an open relation. One empty
4865
+ * transaction closes it, and only when the plan has relations at all (one small read otherwise). Never fails the command:
4866
+ * the next write of the plan closes it the same way.
4867
+ */
4868
+ async function settleRelations({ repoRoot, planKey }) {
4869
+ try {
4870
+ if (((await readTodoRelationSummary({ repoRoot, planKey }))?.relation_count ?? 0) === 0) return;
4871
+ await transactTodoRelations({ repoRoot, planKey, writer: createTodoStoreWriter({ caller: 'todo-relations' }), update: () => ({}) });
4872
+ } catch { /* shortcut: relations left open until the plan's next write; no relation is ever worth failing a done */ }
4873
+ }
4874
+
4705
4875
  /** g4: the todo commands that write a new plan version (the plan revise command carries on its own in bin/lattice.mjs). */
4706
4876
  function revisesPlan(argv) {
4707
4877
  return ['add', 'revise', 'revise-phase', 'revise-set', 'split', 'dependency', 'predecessor'].includes(argv[0])
@@ -5636,6 +5806,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5636
5806
  const result = releasesTasks(argv) ? await withNotices(repoRoot, written, before, env) : written;
5637
5807
  if (result !== null) stdout.write(`${plainVerify ? verifyVerdictLine(result) : JSON.stringify(result)}\n`);
5638
5808
  if (!atomicCommit && revisesPlan(argv)) await carryIndependenceAfterRevision({ cwd });
5809
+ if (!atomicCommit && ['done', 'retire'].includes(argv[0]) && typeof result?.plan_key === 'string') {
5810
+ await settleRelations({ repoRoot, planKey: result.plan_key });
5811
+ }
5639
5812
  return 0;
5640
5813
  } catch (error) {
5641
5814
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'