@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
@@ -53,6 +53,10 @@ export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
53
53
  export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
54
54
  /** a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). */
55
55
  export const TODO_CHART_META_SCHEMA = 'lattice.chart_meta.v1';
56
+ /** ADR 0204 a4: function-level conflict relations, one open relation per (task_a, task_b, path); dfd-store-relations. */
57
+ export const TODO_RELATION_EVENT_SCHEMA = 'lattice.todo_relation_event.v1';
58
+ export const TODO_RELATION_SUMMARY_SCHEMA = 'lattice.todo_relation_summary.v1';
59
+ export const TODO_RELATION_SUMMARY_OPEN = 20;
56
60
  /**
57
61
  * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
58
62
  * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
@@ -906,3 +910,61 @@ export function validateTodoChartMeta(value) {
906
910
  && (repo === null || (exactRecord(repo, ['url', 'branch', 'accepted_tip'])
907
911
  && word(repo.url) && word(repo.branch) && text(repo.accepted_tip)));
908
912
  }
913
+
914
+ // ---- ADR 0204 a4 relations ------------------------------------------------------------------------------------
915
+ const relationText = (field) => typeof field === 'string' && field.length > 0 && field.length <= 1024;
916
+ const relationSha = (field) => field === null || relationText(field);
917
+ const lineNumber = (field) => Number.isSafeInteger(field) && field >= 1;
918
+
919
+ /** One side of an overlap. A whole-file claim has no symbol and no range (both null). */
920
+ function relationEntry(entry) {
921
+ return exactRecord(entry, ['symbol', 'start_line', 'end_line', 'access'])
922
+ && ['read', 'write'].includes(entry.access)
923
+ && ((entry.symbol === null && entry.start_line === null && entry.end_line === null)
924
+ || (relationText(entry.symbol) && lineNumber(entry.start_line) && lineNumber(entry.end_line)
925
+ && entry.end_line >= entry.start_line));
926
+ }
927
+
928
+ /** The pair identity: task_a sorts before task_b, so a pair has one spelling. */
929
+ const relationKey = (value) => isTodoIdentifier(value.task_a) && isTodoIdentifier(value.task_b)
930
+ && value.task_a < value.task_b && relationText(value.path);
931
+
932
+ export const todoRelationOverlapsValid = (overlaps) => Array.isArray(overlaps) && overlaps.length > 0
933
+ && overlaps.every((overlap) => exactRecord(overlap, ['a', 'b']) && relationEntry(overlap.a) && relationEntry(overlap.b));
934
+
935
+ /** Content identity of a relation (head and time excluded): the same overlap re-found is not a new relation. */
936
+ export function todoRelationId(relation) {
937
+ return digestTodoArtifact({ task_a: relation.task_a, task_b: relation.task_b, path: relation.path,
938
+ overlaps: relation.overlaps });
939
+ }
940
+
941
+ export function validateTodoRelationEvent(value) {
942
+ try {
943
+ const common = value !== null && typeof value === 'object' && value.schema === TODO_RELATION_EVENT_SCHEMA
944
+ && Number.isSafeInteger(value.sequence) && value.sequence >= 1 && isTodoDigest(value.relation_id)
945
+ && relationKey(value) && relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
946
+ if (!common) return false;
947
+ if (value.kind === 'gone') {
948
+ return exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'head_sha', 'computed_at']);
949
+ }
950
+ return value.kind === 'relation'
951
+ && exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'overlaps', 'head_sha', 'computed_at'])
952
+ && todoRelationOverlapsValid(value.overlaps) && value.relation_id === todoRelationId(value);
953
+ } catch { return false; }
954
+ }
955
+
956
+ const summaryRelation = (entry) => exactRecord(entry, ['relation_id', 'task_a', 'task_b', 'path', 'overlaps'])
957
+ && isTodoDigest(entry.relation_id) && relationKey(entry) && todoRelationOverlapsValid(entry.overlaps);
958
+
959
+ export function validateTodoRelationSummary(value) {
960
+ try {
961
+ return exactRecord(value, ['schema', 'plan_key', 'relation_count', 'open_relations', 'open_truncated',
962
+ 'unresolved_count', 'head_sha', 'log_sequence', 'computed_at'])
963
+ && value.schema === TODO_RELATION_SUMMARY_SCHEMA && isTodoIdentifier(value.plan_key)
964
+ && isNonNegativeSafeInteger(value.relation_count) && isNonNegativeSafeInteger(value.unresolved_count)
965
+ && isNonNegativeSafeInteger(value.log_sequence) && Array.isArray(value.open_relations)
966
+ && value.open_relations.length <= TODO_RELATION_SUMMARY_OPEN && value.open_relations.every(summaryRelation)
967
+ && value.open_truncated === (value.relation_count > value.open_relations.length)
968
+ && relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
969
+ } catch { return false; }
970
+ }
@@ -0,0 +1,165 @@
1
+ // Plan/lifecycle: the functions a task changes or reads, declared once when the task is added (ADR 0204 §1, §6).
2
+ // `--owns src/a.mjs#foo,src/b.mjs` / `--reads src/c.mjs#bar` → one witness-draft row. Resolution goes through the code graph's
3
+ // public Resolve interface only; nothing here reads the sensor index.
4
+ import { existsSync } from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ import { runSensorCli } from './sensor-cli.mjs';
8
+ import { parseAnchor, proposeSymbols, resolveAnchors, SensorResolveError } from './sensor-resolve.mjs';
9
+ import { isTodoIdentifier } from './todo-contracts.mjs';
10
+ import { TodoStoreError } from './todo-store.mjs';
11
+
12
+ // A flag is a comma list; plan input (`touches`) already gives an array.
13
+ const items = (value) => (Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [])
14
+ .map((item) => item.trim()).filter(Boolean);
15
+ const sortedUnique = (values) => [...new Set(values)].sort();
16
+
17
+ /** Every path a declaration names, anchored or not (`owns`, `reads`, `writes` flags): a Set. */
18
+ export function declaredPaths({ owns, reads, writes }) {
19
+ const { paths: ownPaths, anchors: ownAnchors } = parseDeclarationList(owns);
20
+ const { paths: readPaths, anchors: readAnchors } = parseDeclarationList(reads);
21
+ return new Set([...ownPaths, ...readPaths, ...items(writes), ...[...ownAnchors, ...readAnchors].map(({ path: where }) => where)]);
22
+ }
23
+
24
+ /** `a.mjs,b.mjs#foo` → bare paths, anchors, and entries that cannot be stored (with why). */
25
+ export function parseDeclarationList(value) {
26
+ const paths = [];
27
+ const anchors = [];
28
+ const malformed = [];
29
+ for (const text of items(value)) {
30
+ if (!text.includes('#')) { paths.push(text); continue; }
31
+ const anchor = parseAnchor(text);
32
+ if (anchor === null) malformed.push({ text, reason: 'expected_path_hash_symbol' });
33
+ // The witness row stores the symbol as a dotted identifier chain (Ruby `Foo#bar` cannot be stored).
34
+ else if (!isTodoIdentifier(anchor.symbol)) malformed.push({ text, reason: 'symbol_not_a_dotted_identifier' });
35
+ else anchors.push(anchor);
36
+ }
37
+ return { paths, anchors, malformed };
38
+ }
39
+
40
+ const byWithin = (anchors) => {
41
+ const grouped = new Map();
42
+ for (const { path: within, symbol } of anchors) grouped.set(within, [...(grouped.get(within) ?? []), symbol]);
43
+ return [...grouped].map(([within, symbols]) => ({ within, symbols: sortedUnique(symbols) }));
44
+ };
45
+
46
+ async function resolveOnce(root, anchors) {
47
+ try { return await resolveAnchors({ root, anchors }); } catch (error) {
48
+ if (!(error instanceof SensorResolveError) || error.code !== 'RESOLVE_INDEX_MISSING') throw error;
49
+ }
50
+ // First use only: the maintained index does not exist yet (Observe builds it; later calls reuse it).
51
+ const sink = { write() {} };
52
+ await runSensorCli({ argv: ['init', root, '--json'], stdout: sink, stderr: sink });
53
+ return resolveAnchors({ root, anchors });
54
+ }
55
+
56
+ const unresolvedEntry = (anchor, reason, nearest = [], elsewhere = []) => ({
57
+ path: anchor.path, symbol: anchor.symbol, reason, nearest, elsewhere,
58
+ });
59
+
60
+ /**
61
+ * Resolve a task's declared functions and build its witness-draft row.
62
+ * → `{row, declaration: {written, resolved[], unresolved[], malformed[]}}`; `row` is null when `written` is false
63
+ * (a task's row is not written until every name resolves, so the next declare retries from scratch).
64
+ * `observable` false = the Store root has no code tree: functions cannot be checked, never recorded as a guess.
65
+ */
66
+ export async function buildDeclarationRow({ root, observable, owns, reads, writes, alsoResolve = [] }) {
67
+ const own = parseDeclarationList(owns);
68
+ const read = parseDeclarationList(reads);
69
+ const malformed = [...own.malformed, ...read.malformed];
70
+ const keyOf = (anchor) => `${anchor.path}\0${anchor.symbol}`;
71
+ const wanted = [...new Map([...own.anchors, ...read.anchors].map((anchor) => [keyOf(anchor), anchor])).values()];
72
+ const declaration = { written: false, resolved: [], unresolved: [], malformed };
73
+ if (malformed.length > 0) return { row: null, declaration };
74
+ // `alsoResolve`: other tasks' anchors, answered by the same Resolve call (a5 compares ranges); a miss there is not this task's refusal.
75
+ const wantedKeys = new Set(wanted.map(keyOf));
76
+ const extra = [...new Map(alsoResolve.filter((anchor) => !wantedKeys.has(keyOf(anchor))).map((anchor) => [keyOf(anchor), anchor])).values()];
77
+ let ranges = [];
78
+ if (wanted.length > 0 && !observable) {
79
+ declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'no_code_tree'));
80
+ return { row: null, declaration };
81
+ }
82
+ if (wanted.length + extra.length > 0 && observable) {
83
+ let answer;
84
+ try { answer = await resolveOnce(root, [...wanted, ...extra]); } catch (error) {
85
+ if (wanted.length === 0) return buildRow({ own, read, writes, declaration, ranges });
86
+ declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'resolve_unavailable'));
87
+ declaration.resolve_error = error?.code ?? error?.message ?? 'resolve_failed';
88
+ return { row: null, declaration };
89
+ }
90
+ const mine = answer.unresolved.filter((anchor) => wantedKeys.has(keyOf(anchor)));
91
+ declaration.unresolved = mine.map((anchor) => unresolvedEntry(
92
+ anchor, anchor.reason,
93
+ anchor.nearest.map(({ qualified }) => qualified),
94
+ anchor.elsewhere.map(({ path: where, qualified }) => `${where}#${qualified}`),
95
+ ));
96
+ ranges = answer.resolved;
97
+ declaration.resolved = answer.resolved.filter(({ path: where, symbol }) => wantedKeys.has(`${where}\0${symbol}`))
98
+ .map(({ path: where, symbol, kind, start_line: start, end_line: end }) => ({
99
+ path: where, symbol, kind, start_line: start, end_line: end,
100
+ }));
101
+ if (declaration.unresolved.length > 0) return { row: null, declaration };
102
+ }
103
+ return buildRow({ own, read, writes, declaration, ranges });
104
+ }
105
+
106
+ function buildRow({ own, read, writes, declaration, ranges }) {
107
+ const concern = byWithin(own.anchors);
108
+ const readAnchors = byWithin(read.anchors);
109
+ const row = {
110
+ owns: sortedUnique([...own.paths, ...concern.map(({ within }) => within)]),
111
+ reads: sortedUnique([...read.paths, ...readAnchors.map(({ within }) => within)]),
112
+ writes: items(writes),
113
+ ...(concern.length > 0 ? { concern_anchors: concern } : {}),
114
+ ...(readAnchors.length > 0 ? { read_anchors: readAnchors } : {}),
115
+ };
116
+ declaration.written = true;
117
+ return { row, declaration, ranges };
118
+ }
119
+
120
+ /**
121
+ * Fallback without seeds (ADR 0204 §1): identifiers in the title and design memo that name graph symbols are proposed in the
122
+ * result and never recorded; the AI that adds the task decides. Needs an existing index and a code tree; any failure = no proposal.
123
+ */
124
+ export async function proposeFromText({ root, observable, title, memo }) {
125
+ if (!observable || !existsSync(path.join(root, '.lattice/sensor/sensor.db'))) return null;
126
+ // Resolve's `snake` leaves `qualified: undefined` on a definition; a result is canonical JSON, so drop undefined here.
127
+ try { return JSON.parse(JSON.stringify(await proposeSymbols({ root, title, memo }))); } catch { return null; }
128
+ }
129
+
130
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
131
+ const isPathList = (list) => list === undefined || (Array.isArray(list) && list.every((entry) => typeof entry === 'string' && entry.trim() !== ''));
132
+
133
+ /**
134
+ * Plan input v6 (ADR 0204 §6): `tasks[].touches {owns, reads}` is read here and goes to the witness set only.
135
+ * Returns the input as v5 without `touches`, so the stored plan and its digest are the v5 ones, plus the claims to declare
136
+ * (`{task_id, owns[], reads[]}`; a task whose lists are both empty claims nothing and is left out). `pointer` prefixes a refusal.
137
+ */
138
+ export function splitTouches(input, pointer = '') {
139
+ if (input?.schema !== 'lattice.plan_create_input.v6' || !Array.isArray(input.tasks)) return { input, touches: [] };
140
+ const touches = [];
141
+ const tasks = input.tasks.map((task, index) => {
142
+ if (!isRecord(task) || !('touches' in task)) return task;
143
+ const { touches: claim, ...rest } = task;
144
+ if (!isRecord(claim) || Object.keys(claim).some((key) => key !== 'owns' && key !== 'reads')
145
+ || !isPathList(claim.owns) || !isPathList(claim.reads)) {
146
+ throw new TodoStoreError('INPUT_INVALID', 'plan_create_touches_invalid', undefined, {
147
+ pointer: `${pointer}/tasks/${index}/touches`, expected: { owns: 'string[] of path or path#function', reads: 'string[] of path or path#function' },
148
+ actual: claim, next_action: 'Write touches as {"owns": ["src/a.mjs#foo"], "reads": ["src/b.mjs"]}; both lists are optional.',
149
+ });
150
+ }
151
+ const { owns = [], reads = [] } = claim;
152
+ if (owns.length + reads.length > 0) touches.push({ task_id: rest.task_id, owns, reads });
153
+ return rest;
154
+ });
155
+ return { input: { ...input, schema: 'lattice.plan_create_input.v5', tasks }, touches };
156
+ }
157
+
158
+ /**
159
+ * The line ranges of every function the witness rows declare (`resolved` of one Resolve call), for the compile (a5b).
160
+ * No anchors → no call. Any failure → `[]`: the compile then reads every declared function as a whole-file claim, as before.
161
+ */
162
+ export async function resolveDeclaredRanges({ root, anchors }) {
163
+ if (anchors.length === 0) return [];
164
+ try { return (await resolveOnce(root, anchors)).resolved; } catch { return []; }
165
+ }
@@ -69,29 +69,17 @@ function isCleanAtHead(repoRoot, headSha) {
69
69
  }
70
70
 
71
71
  /**
72
- * HEADと同じ内容の作業木では、維持されている索引を増分syncして使う(無ければ最初の1回だけinit)。
73
- * 同期の前後でcleanとHEADを確かめ、崩れていたらnull=隔離worktreeの経路へ落とす。
74
- * 保護するもの: 未commitの状態を判定が観測しないこと。落とす先が出口で、拒否はしない。
72
+ * Observe (ADR 0204): `work(root)` を、`sha` の内容を持つ索引つきの木の上で実行する。
73
+ * HEADと同じ内容の作業木なら、維持されている索引を増分syncして使う(無ければ最初の1回だけinit)。同期の前後で
74
+ * cleanとHEADを確かめ、崩れていたら隔離worktreeへ落とす。`sha` がHEADでない、または作業木がdirtyなら、
75
+ * `sha` の使い捨てworktreeで新しく索引する。保護するもの: 未commitの状態を観測しないこと。落とす先が出口で、拒否はしない。
75
76
  */
76
- async function observeMaintainedIndex({ repoRoot, headSha, witnessSet }) {
77
- if (!isCleanAtHead(repoRoot, headSha)) return null;
78
- await runSensor(existsSync(path.join(repoRoot, '.lattice/sensor/sensor.db')) ? 'sync' : 'init', repoRoot);
79
- if (!isCleanAtHead(repoRoot, headSha)) return null;
80
- return { head_sha: headSha, sensor_evidence: await collectWitnessSensorEvidence({ cwd: repoRoot, witnessSet }) };
81
- }
82
-
83
- /** 共有repoのdirtyな状態を観測せず、current HEADの索引(維持されたもの、無ければclean worktree)でsensorを実行する。 */
84
- export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet } = {}) {
85
- if (typeof repoRoot !== 'string' || repoRoot.length === 0
86
- || witnessSet === null || typeof witnessSet !== 'object') {
87
- fail('INDEPENDENCE_OBSERVATION_INPUT_INVALID', 'observation_input_invalid');
77
+ export async function withObservedTree({ repoRoot, sha }, work) {
78
+ if (isCleanAtHead(repoRoot, sha)) {
79
+ await runSensor(existsSync(path.join(repoRoot, '.lattice/sensor/sensor.db')) ? 'sync' : 'init', repoRoot);
80
+ if (isCleanAtHead(repoRoot, sha)) return work(repoRoot);
88
81
  }
89
-
90
- const headSha = git({
91
- cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head',
92
- });
93
- const maintained = await observeMaintainedIndex({ repoRoot, headSha, witnessSet });
94
- if (maintained !== null) return maintained;
82
+ const headSha = sha;
95
83
  const temporaryRoot = await mkdtemp(path.join(tmpdir(), 'lattice-independence-observation-'));
96
84
  const observationRoot = path.join(temporaryRoot, 'worktree');
97
85
  let registered = false;
@@ -114,7 +102,7 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
114
102
  });
115
103
  }
116
104
  await runSensor('init', observationRoot);
117
- result = await collectWitnessSensorEvidence({ cwd: observationRoot, witnessSet });
105
+ result = await work(observationRoot);
118
106
  } catch (error) {
119
107
  operationError = error;
120
108
  }
@@ -139,5 +127,20 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
139
127
  });
140
128
  }
141
129
  if (operationError !== null) throw operationError;
142
- return { head_sha: headSha, sensor_evidence: result };
130
+ return result;
131
+ }
132
+
133
+ /** 共有repoのdirtyな状態を観測せず、current HEADの索引(維持されたもの、無ければclean worktree)でsensorを実行する。 */
134
+ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet } = {}) {
135
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0
136
+ || witnessSet === null || typeof witnessSet !== 'object') {
137
+ fail('INDEPENDENCE_OBSERVATION_INPUT_INVALID', 'observation_input_invalid');
138
+ }
139
+
140
+ const headSha = git({
141
+ cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head',
142
+ });
143
+ const sensorEvidence = await withObservedTree({ repoRoot, sha: headSha },
144
+ (root) => collectWitnessSensorEvidence({ cwd: root, witnessSet }));
145
+ return { head_sha: headSha, sensor_evidence: sensorEvidence };
143
146
  }
@@ -17,6 +17,8 @@ import {
17
17
  import { TODO_INDEPENDENCE_GUIDANCE_CODES } from './todo-independence-guidance.mjs';
18
18
 
19
19
  export const TODO_WITNESS_SET_SCHEMA = 'lattice.todo_witness_set.v5';
20
+ /** v5 plus `read_anchors` (ADR 0204 §6): written only when a task declares functions it reads, so v5 charts stay v5. */
21
+ export const TODO_WITNESS_SET_READ_ANCHORS_SCHEMA = 'lattice.todo_witness_set.v6';
20
22
  /**
21
23
  * まだ受理する旧witness set契約。v3以前の厳密なcompile意味を変えず、
22
24
  * 既存宣言を書き換えさせないために読み口を残す。
@@ -28,18 +30,20 @@ export const TODO_WITNESS_SET_LEGACY_SCHEMAS = Object.freeze([
28
30
  'lattice.todo_witness_set.v1',
29
31
  ]);
30
32
  export const TODO_WITNESS_SET_SCHEMAS = Object.freeze([
33
+ TODO_WITNESS_SET_READ_ANCHORS_SCHEMA,
31
34
  TODO_WITNESS_SET_SCHEMA,
32
35
  ...TODO_WITNESS_SET_LEGACY_SCHEMAS,
33
36
  ]);
34
37
  /** 宣言できる欄はversionごとに違う。どの版から使えるかを1箇所で持つ。 */
35
38
  const CONCERN_ANCHOR_SCHEMAS = Object.freeze([
39
+ TODO_WITNESS_SET_READ_ANCHORS_SCHEMA,
36
40
  TODO_WITNESS_SET_SCHEMA,
37
41
  'lattice.todo_witness_set.v4',
38
42
  'lattice.todo_witness_set.v3',
39
43
  'lattice.todo_witness_set.v2',
40
44
  ]);
41
45
  const CREATES_SCHEMAS = Object.freeze([
42
- TODO_WITNESS_SET_SCHEMA, 'lattice.todo_witness_set.v4', 'lattice.todo_witness_set.v3',
46
+ TODO_WITNESS_SET_READ_ANCHORS_SCHEMA, TODO_WITNESS_SET_SCHEMA, 'lattice.todo_witness_set.v4', 'lattice.todo_witness_set.v3',
43
47
  ]);
44
48
 
45
49
  /** 1 taskが宣言できるconcern anchorの資源数と、資源あたりのsymbol数の上限。 */
@@ -178,7 +182,7 @@ function boundedText(value, maximumBytes = 4_096) {
178
182
  export function synthesizeWitnessRunRequest(witnessSet, { baseSha, requestId }) {
179
183
  const taskIds = Object.keys(witnessSet.manual_witness).sort(compareText);
180
184
  const request = {
181
- schema: witnessSet.schema === TODO_WITNESS_SET_SCHEMA
185
+ schema: witnessSet.schema === TODO_WITNESS_SET_SCHEMA || witnessSet.schema === TODO_WITNESS_SET_READ_ANCHORS_SCHEMA
182
186
  ? RUN_REQUEST_SCHEMA
183
187
  : witnessSet.schema === 'lattice.todo_witness_set.v4'
184
188
  ? RUN_REQUEST_PREDICTION_SCHEMA
@@ -188,7 +192,7 @@ export function synthesizeWitnessRunRequest(witnessSet, { baseSha, requestId })
188
192
  capacity: witnessSet.capacity,
189
193
  todos: taskIds.map((taskId) => ({ todo_id: taskId })),
190
194
  manual_witness: Object.fromEntries(taskIds.map((taskId) => {
191
- const { concern_anchors: _concernAnchors, ...boundary } = witnessSet.manual_witness[taskId];
195
+ const { concern_anchors: _concernAnchors, read_anchors: _readAnchors, ...boundary } = witnessSet.manual_witness[taskId];
192
196
  return [taskId, boundary];
193
197
  })),
194
198
  sensor_query_set: witnessSet.sensor_query_set,
@@ -280,7 +284,7 @@ export function explainTodoWitnessSet(value) {
280
284
  for (const taskId of taskIds) {
281
285
  const witness = value.manual_witness[taskId];
282
286
  if (plain(witness) && Object.hasOwn(witness, 'lines')
283
- && value.schema !== TODO_WITNESS_SET_SCHEMA) {
287
+ && value.schema !== TODO_WITNESS_SET_SCHEMA && value.schema !== TODO_WITNESS_SET_READ_ANCHORS_SCHEMA) {
284
288
  return reject('lines_require_witness_set_v5', `/manual_witness/${taskId}/lines`);
285
289
  }
286
290
  }
@@ -297,6 +301,15 @@ export function explainTodoWitnessSet(value) {
297
301
  && witness.owns.some((own) => Object.hasOwn(own, 'creates'))) {
298
302
  return reject('creates_require_witness_set_v3', `/manual_witness/${taskId}/owns`);
299
303
  }
304
+ const readAt = `/manual_witness/${taskId}/read_anchors`;
305
+ if (Object.hasOwn(witness, 'read_anchors')) {
306
+ if (value.schema !== TODO_WITNESS_SET_READ_ANCHORS_SCHEMA) {
307
+ return reject('read_anchors_require_witness_set_v6', readAt);
308
+ }
309
+ // A read anchor sits inside a path the task reads (its own `reads` list), the way a write anchor sits inside an owned path.
310
+ const readAnchors = explainConcernAnchors(witness.read_anchors, [], witness.reads, readAt);
311
+ if (!readAnchors.valid) return reject(readAnchors.reason, readAnchors.path);
312
+ }
300
313
  const at = `/manual_witness/${taskId}/concern_anchors`;
301
314
  if (!Object.hasOwn(witness, 'concern_anchors')) continue;
302
315
  if (!CONCERN_ANCHOR_SCHEMAS.includes(value.schema)) {
@@ -10,6 +10,7 @@ import {
10
10
  } from './todo-independence-contracts.mjs';
11
11
  import { compileRuntimePlanV1, evidenceFromCollectedOutcomes } from './runtime-front-end.mjs';
12
12
  import { collectSensorEvidence } from './sensor-adapter.mjs';
13
+ import { refineResourcesByFunction } from './todo-judgment.mjs';
13
14
 
14
15
  export class TodoIndependenceError extends Error {
15
16
  constructor(code, reason, detail = {}) {
@@ -257,7 +258,7 @@ function scopeExpansionFrom({ taskIds, boundaries, previousArtifact, plan }) {
257
258
  }
258
259
 
259
260
  export function compileTodoIndependence(options = {}) {
260
- const { witnessSet, plan, baseSha, compiledAt, sensorEvidence, previousArtifact = null } = options;
261
+ const { witnessSet, plan, baseSha, compiledAt, sensorEvidence, previousArtifact = null, functionRanges = null } = options;
261
262
  if (!validateTodoWitnessSet(witnessSet)) {
262
263
  fail('INDEPENDENCE_WITNESS_INVALID', 'witness_set_invalid');
263
264
  }
@@ -285,6 +286,8 @@ export function compileTodoIndependence(options = {}) {
285
286
  planEpoch: 0,
286
287
  predecessorRefs: [],
287
288
  omitWavesOverLimit: true,
289
+ // a5b: with resolved function ranges, a path declared with functions claims only those functions (ADR 0204 §6 container ruling).
290
+ ...(functionRanges === null ? {} : { refineResources: refineResourcesByFunction({ rows: witnessSet.manual_witness, ranges: functionRanges }) }),
288
291
  });
289
292
 
290
293
  if (compiled.outcome !== 'dispatchable'
@@ -0,0 +1,141 @@
1
+ // Plan/lifecycle: the add-time conflict judgment (ADR 0204 §3). Pure: it compares one task's declared claims with every other
2
+ // unfinished task's, on resolved ranges the caller passes in. Resolve, sensor and git run outside (transactTodoRelations
3
+ // forbids them inside its lock); nothing here refuses anything.
4
+
5
+ import { digestTodoArtifact } from './todo-contracts.mjs';
6
+
7
+ const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
8
+
9
+ /**
10
+ * A task's claims per path, from its witness row: `Map<path, [{symbol, access}]>`. A path declared with anchors is a
11
+ * container: it claims only those functions. A path without anchors claims the whole file (`symbol: null`).
12
+ */
13
+ export function claimsOf(row) {
14
+ const claims = new Map();
15
+ const add = (target, claim) => claims.set(target, [...(claims.get(target) ?? []), claim]);
16
+ const anchored = (list) => new Map((list ?? []).map(({ within, symbols }) => [within.target, symbols]));
17
+ const concern = anchored(row.concern_anchors);
18
+ const readAnchor = anchored(row.read_anchors);
19
+ const written = new Set([...row.owns.filter(({ kind }) => kind === 'path').map(({ target }) => target), ...row.writes]);
20
+ for (const target of written) for (const symbol of concern.get(target) ?? [null]) add(target, { symbol, access: 'write' });
21
+ for (const target of row.reads) for (const symbol of readAnchor.get(target) ?? [null]) add(target, { symbol, access: 'read' });
22
+ return claims;
23
+ }
24
+
25
+ /** `[{path, symbol}]` of every anchored claim in `claims`, for one batched Resolve. */
26
+ export const anchorsOf = (claims) => [...claims].flatMap(([target, list]) => list
27
+ .filter(({ symbol }) => symbol !== null).map(({ symbol }) => ({ path: target, symbol })));
28
+
29
+ const rangeKey = (target, symbol) => `${target}\0${symbol}`;
30
+
31
+ /** `Map<path\0symbol, {start_line, end_line}>` from Resolve's `resolved` list. */
32
+ export const rangeIndex = (resolved) => new Map(resolved.map(({ path: target, symbol, start_line: start, end_line: end }) => [
33
+ rangeKey(target, symbol), { start_line: start, end_line: end }]));
34
+
35
+ /**
36
+ * Judge `taskId` against every other task in `rows` (`{taskId: witnessRow}`, already limited to unfinished tasks).
37
+ * `ranges` is a `rangeIndex`; an anchored claim with no range (the name no longer resolves) is read as a whole-file claim
38
+ * and counted in `unresolved` (distinct names). Overlap needs at least one write; two reads never conflict (ADR 0204, claim 4).
39
+ * → `{relations: [{task_a, task_b, path, overlaps}], gone: [{task_a, task_b, path}], unresolved}`: `gone` names the pairs of
40
+ * this task that no longer overlap on a path they once shared (the caller closes only those that are open).
41
+ */
42
+ export function judgeTask({ taskId, rows, ranges, openRelations = [], only = null }) {
43
+ const mine = claimsOf(rows[taskId]);
44
+ const relations = [];
45
+ const missing = new Set();
46
+ const side = (target, claim) => {
47
+ const range = claim.symbol === null ? undefined : ranges.get(rangeKey(target, claim.symbol));
48
+ if (claim.symbol !== null && range === undefined) missing.add(rangeKey(target, claim.symbol));
49
+ return range === undefined
50
+ ? { symbol: null, start_line: null, end_line: null, access: claim.access }
51
+ : { symbol: claim.symbol, start_line: range.start_line, end_line: range.end_line, access: claim.access };
52
+ };
53
+ const overlap = (left, right) => left.symbol === null || right.symbol === null
54
+ || !(left.end_line < right.start_line || right.end_line < left.start_line);
55
+ for (const otherId of Object.keys(rows).sort(compareText)) {
56
+ if (otherId === taskId) continue;
57
+ const [taskA, taskB] = taskId < otherId ? [taskId, otherId] : [otherId, taskId];
58
+ const theirs = claimsOf(rows[otherId]);
59
+ for (const [target, claims] of [...mine].sort(([left], [right]) => compareText(left, right))) {
60
+ const others = theirs.get(target);
61
+ if (others === undefined) continue;
62
+ const found = new Map();
63
+ for (const claim of claims) {
64
+ for (const other of others) {
65
+ if (claim.access === 'read' && other.access === 'read') continue;
66
+ // `only` narrows to one resource's meaning (a5b): 'ww' = both write, 'rw' = one writes and the other reads.
67
+ if ((only === 'ww' && (claim.access !== 'write' || other.access !== 'write')) || (only === 'rw' && claim.access === other.access)) continue;
68
+ const [first, second] = taskA === taskId ? [side(target, claim), side(target, other)] : [side(target, other), side(target, claim)];
69
+ if (!overlap(first, second)) continue;
70
+ found.set(JSON.stringify([first, second]), { a: first, b: second });
71
+ }
72
+ }
73
+ if (found.size > 0) {
74
+ relations.push({ task_a: taskA, task_b: taskB, path: target,
75
+ overlaps: [...found.entries()].sort(([left], [right]) => compareText(left, right)).map(([, entry]) => entry) });
76
+ }
77
+ }
78
+ }
79
+ const keep = new Set(relations.map(({ task_a: a, task_b: b, path: target }) => `${a}\0${b}\0${target}`));
80
+ const gone = openRelations
81
+ .filter(({ task_a: a, task_b: b, path: target }) => (a === taskId || b === taskId) && !keep.has(`${a}\0${b}\0${target}`))
82
+ .map(({ task_a: a, task_b: b, path: target }) => ({ task_a: a, task_b: b, path: target }));
83
+ return { relations, gone, unresolved: missing.size };
84
+ }
85
+
86
+ /**
87
+ * The other tasks' anchored claims on the paths `paths` (a Set) touches: what the same Resolve call must also answer so
88
+ * `judgeTask` can compare ranges. Rows are witness rows (`manual_witness`); `taskId`'s own row is skipped.
89
+ */
90
+ export function neededAnchors(rows, taskId, paths) {
91
+ const found = new Map();
92
+ for (const [otherId, row] of Object.entries(rows)) {
93
+ if (otherId === taskId) continue;
94
+ for (const anchor of anchorsOf(claimsOf(row))) if (paths.has(anchor.path)) found.set(`${anchor.path}\0${anchor.symbol}`, anchor);
95
+ }
96
+ return [...found.values()];
97
+ }
98
+
99
+ /**
100
+ * ADR 0204 a5b: narrow the compile's shared path resources to the task pairs that really overlap. A resource on path P
101
+ * (an owned path `own-…`, or a read x write `rw-…` state on P) is shared by `todo_ids`; when both tasks of a pair claim
102
+ * P and at least one of them declared functions in it, the pair stays only if `judgeTask` finds an overlap (same function,
103
+ * overlapping lines, a write on either side). A pair with no claim on exactly P, or with only whole-file claims, stays
104
+ * as the compile made it. → a function for `compileRuntimePlanV1`'s `refineResources`.
105
+ */
106
+ export function refineResourcesByFunction({ rows, ranges }) {
107
+ const comparable = (target, first, second) => {
108
+ const left = claimsOf(rows[first] ?? {owns: [], reads: [], writes: []}).get(target);
109
+ const right = claimsOf(rows[second] ?? {owns: [], reads: [], writes: []}).get(target);
110
+ return left !== undefined && right !== undefined && [...left, ...right].some(({ symbol }) => symbol !== null);
111
+ };
112
+ const overlaps = (target, first, second, only) => judgeTask({ taskId: first, rows: { [first]: rows[first], [second]: rows[second] }, ranges, only })
113
+ .relations.some(({ path: where }) => where === target);
114
+ // The path a shared resource stands for, or null when it is not one this can narrow: an owned path (`own-…`), a read x write
115
+ // state on one path (`rw-…`), or a predicted write overlap of one path with itself (`predicted-ww-…`, target `P ↔ P`).
116
+ const pathOf = (resource) => {
117
+ if (resource.kind === 'path' && resource.resource_id.startsWith('own-')) return resource.target;
118
+ if (resource.kind !== 'state') return null;
119
+ if (resource.resource_id.startsWith('rw-')) return resource.target;
120
+ const [left, right, ...rest] = resource.target.split(' ↔ ');
121
+ return resource.resource_id.startsWith('predicted-ww-') && rest.length === 0 && left === right ? left : null;
122
+ };
123
+ return (resources) => resources.flatMap((resource) => {
124
+ const target = pathOf(resource);
125
+ if (target === null || resource.todo_ids.length < 2) return [resource];
126
+ const pairs = [];
127
+ for (let left = 0; left < resource.todo_ids.length; left += 1) {
128
+ for (let right = left + 1; right < resource.todo_ids.length; right += 1) pairs.push([resource.todo_ids[left], resource.todo_ids[right]]);
129
+ }
130
+ const kept = pairs.filter(([first, second]) => !comparable(target, first, second) || overlaps(target, first, second, resource.resource_id.startsWith('rw-') ? 'rw' : 'ww'));
131
+ if (kept.length === pairs.length) return [resource];
132
+ return kept.map(([first, second]) => ({ ...resource,
133
+ resource_id: `${resource.resource_id}-fn-${digestTodoArtifact({ first, second }).slice(0, 12)}`, todo_ids: [first, second] }));
134
+ });
135
+ }
136
+
137
+ /** One relation as seen from `taskId`: `{with, path, overlaps: [{self, other}]}` (`self` is this task's side). */
138
+ export function relationView(taskId, { task_a: a, task_b: b, path: where, overlaps }) {
139
+ return { with: a === taskId ? b : a, path: where,
140
+ overlaps: overlaps.map(({ a: first, b: second }) => (a === taskId ? { self: first, other: second } : { self: second, other: first })) };
141
+ }