@quolu/lattice 0.107.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 (37) hide show
  1. package/README.ja.md +1 -1
  2. package/README.md +2 -2
  3. package/bin/lattice.mjs +5 -2
  4. package/docs/schemas/lattice.plan_create_input.v6.schema.json +384 -0
  5. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +3 -0
  6. package/docs/schemas/lattice.todo_witness_draft.v2.schema.json +14 -2
  7. package/docs/schemas/lattice.todo_witness_set.v6.schema.json +482 -0
  8. package/package.json +3 -1
  9. package/sensor/dist/bin/lattice-sensor.js +76 -0
  10. package/sensor/dist/graph/anchor-resolve.d.ts +90 -0
  11. package/sensor/dist/graph/anchor-resolve.d.ts.map +1 -0
  12. package/sensor/dist/graph/anchor-resolve.js +132 -0
  13. package/sensor/dist/graph/anchor-resolve.js.map +1 -0
  14. package/sensor/dist/graph/touched-symbols.d.ts +42 -0
  15. package/sensor/dist/graph/touched-symbols.d.ts.map +1 -0
  16. package/sensor/dist/graph/touched-symbols.js +80 -0
  17. package/sensor/dist/graph/touched-symbols.js.map +1 -0
  18. package/src/cli-help.mjs +21 -7
  19. package/src/plan-revise.mjs +12 -1
  20. package/src/plan-scope-review.mjs +1 -1
  21. package/src/project-cli.mjs +20 -3
  22. package/src/runtime-front-end.mjs +26 -9
  23. package/src/schedulability-compiler-v2.mjs +10 -4
  24. package/src/sensor-cli.mjs +82 -1
  25. package/src/sensor-resolve.mjs +116 -0
  26. package/src/sensor-touched.mjs +76 -0
  27. package/src/todo-authoring-input.mjs +1 -0
  28. package/src/todo-cli.mjs +233 -43
  29. package/src/todo-contracts.mjs +62 -0
  30. package/src/todo-declaration.mjs +165 -0
  31. package/src/todo-independence-authoritative-observation.mjs +45 -15
  32. package/src/todo-independence-contracts.mjs +18 -4
  33. package/src/todo-independence.mjs +8 -2
  34. package/src/todo-judgment.mjs +141 -0
  35. package/src/todo-relation-store.mjs +294 -0
  36. package/src/todo-store.mjs +8 -4
  37. 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',