@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
@@ -0,0 +1,294 @@
1
+ // ADR 0204 a4: per-plan function-level conflict relations. docs/architecture/dfd-store-relations.md
2
+ import { appendFile, lstat, mkdir, readFile, readdir, rename, rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
5
+ import {
6
+ TODO_RELATION_EVENT_SCHEMA, TODO_RELATION_SUMMARY_OPEN, TODO_RELATION_SUMMARY_SCHEMA,
7
+ canonicalizeTodoArtifact, exactRecord, isStrictTodoTimestamp, isTodoIdentifier, todoRelationId,
8
+ todoRelationOverlapsValid, validateTodoRelationEvent, validateTodoRelationSummary,
9
+ } from './todo-contracts.mjs';
10
+ import {
11
+ TodoStoreError, atomicWrite, readTodoStore, readTodoWitnessSet, rejectNewerTodoSchema, requireTodoStoreWriter,
12
+ writeTodoWitnessSet,
13
+ } from './todo-store.mjs';
14
+
15
+ const ROOT_REF = '.lattice/todo/relations';
16
+ const TASK_FILE_MAX_BYTES = 4_194_304;
17
+ const LOG_SEGMENT_BYTES = 4_194_304;
18
+ const SUMMARY_MAX_BYTES = 65_536;
19
+ const FINISHED = new Set(['done', 'retired']);
20
+
21
+ const fail = (code, reason, detail) => { throw new TodoStoreError(code, reason, reason, detail); };
22
+ const line = (value) => Buffer.from(`${canonicalizeTodoArtifact(value)}\n`, 'utf8');
23
+ const keyOf = ({ task_a: a, task_b: b, path: p }) => `${a}\0${b}\0${p}`;
24
+ const refs = (planKey) => ({ dir: `${ROOT_REF}/${planKey}`, open: `${ROOT_REF}/${planKey}/open`,
25
+ log: `${ROOT_REF}/${planKey}/log.jsonl`, summary: `${ROOT_REF}/${planKey}/summary.json`,
26
+ task: (taskId) => `${ROOT_REF}/${planKey}/open/${taskId}.json` });
27
+
28
+ function planKeyOf(planKey) {
29
+ if (!isTodoIdentifier(planKey)) throw new TypeError('planKey must be a todo identifier');
30
+ return planKey;
31
+ }
32
+
33
+ /** A file under the relation directory: missing = null; a symlink, non-file or oversize file is invalid. */
34
+ async function readBounded(repoRoot, ref, maxBytes) {
35
+ const absolute = path.resolve(repoRoot, ref);
36
+ try {
37
+ const state = await lstat(absolute);
38
+ if (state.isSymbolicLink() || !state.isFile() || state.size > maxBytes) {
39
+ fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref });
40
+ }
41
+ return await readFile(absolute, 'utf8');
42
+ } catch (error) {
43
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ function parseLines(text, ref, validate, family) {
49
+ if (text === null || text === '') return [];
50
+ if (!text.endsWith('\n')) fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref });
51
+ return text.slice(0, -1).split('\n').map((entry) => {
52
+ let value;
53
+ try { value = JSON.parse(entry); } catch { fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref }); }
54
+ if (!validate(value)) {
55
+ rejectNewerTodoSchema(value, family, ref);
56
+ fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref });
57
+ }
58
+ return value;
59
+ });
60
+ }
61
+
62
+ /** The open relations of one task: its file, one `relation` event per line (missing file = none). */
63
+ async function readTaskFile(repoRoot, planKey, taskId) {
64
+ const ref = refs(planKey).task(taskId);
65
+ const about = (event) => validateTodoRelationEvent(event) && event.kind === 'relation'
66
+ && (event.task_a === taskId || event.task_b === taskId);
67
+ return parseLines(await readBounded(repoRoot, ref, TASK_FILE_MAX_BYTES), ref, about, 'todo_relation_event');
68
+ }
69
+
70
+ /**
71
+ * The plan's relation summary, or null when it has none (a missing file is "no records", not an error).
72
+ * Reads exactly this one small file and never verifies it (ADR 0203).
73
+ */
74
+ export async function readTodoRelationSummary({ repoRoot = process.cwd(), planKey } = {}) {
75
+ const ref = refs(planKeyOf(planKey)).summary;
76
+ const text = await readBounded(path.resolve(repoRoot), ref, SUMMARY_MAX_BYTES);
77
+ if (text === null) return null;
78
+ let value;
79
+ try { value = JSON.parse(text); } catch { fail('STORE_INCONSISTENT', 'relation_summary_invalid', { ref }); }
80
+ rejectNewerTodoSchema(value, 'todo_relation_summary', ref);
81
+ if (!validateTodoRelationSummary(value) || value.plan_key !== planKey) {
82
+ fail('STORE_INCONSISTENT', 'relation_summary_invalid', { ref });
83
+ }
84
+ return value;
85
+ }
86
+
87
+ /**
88
+ * a4c: one task's open relations and the plan's counts, from two small bounded files (the summary and `open/<task>.json`);
89
+ * never the history. → null when the plan has no open relation, else
90
+ * `{relation_count, unresolved_count, head_sha, open: [{task_a, task_b, path, overlaps}]}` (this task's, by pair and path).
91
+ * Unreadable or damaged: STORE_INCONSISTENT, as the summary read.
92
+ */
93
+ export async function readTodoTaskRelations({ repoRoot = process.cwd(), planKey, taskId } = {}) {
94
+ if (!isTodoIdentifier(taskId)) throw new TypeError('taskId must be a todo identifier');
95
+ const root = path.resolve(repoRoot);
96
+ const summary = await readTodoRelationSummary({ repoRoot: root, planKey });
97
+ if (summary === null || summary.relation_count === 0) return null;
98
+ const open = (await readTaskFile(root, planKey, taskId)).map(({ task_a: a, task_b: b, path: where, overlaps }) => ({
99
+ task_a: a, task_b: b, path: where, overlaps })).sort((left, right) => (keyOf(left) < keyOf(right) ? -1 : 1));
100
+ return { relation_count: summary.relation_count, unresolved_count: summary.unresolved_count, head_sha: summary.head_sha, open };
101
+ }
102
+
103
+ /** Every task file of the plan: `Map<taskId, Map<key, event>>` (the open set; names that are not task ids are ignored). */
104
+ async function readOpenFiles(repoRoot, planKey) {
105
+ const names = await readdir(path.resolve(repoRoot, refs(planKey).open)).catch((error) => {
106
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
107
+ throw error;
108
+ });
109
+ const files = new Map();
110
+ for (const name of names) {
111
+ const taskId = name.endsWith('.json') ? name.slice(0, -5) : null;
112
+ if (!isTodoIdentifier(taskId)) continue;
113
+ files.set(taskId, new Map((await readTaskFile(repoRoot, planKey, taskId)).map((event) => [keyOf(event), event])));
114
+ }
115
+ return files;
116
+ }
117
+
118
+ async function ensureRelationDirectory(repoRoot, planKey) {
119
+ const stale = () => fail('STORE_WRITE_CONFLICT', 'store_locked', {
120
+ next_action: 'Initialize a published Todo Store before writing relations, then retry.',
121
+ });
122
+ for (const ref of ['.lattice', '.lattice/todo', '.lattice/todo/manifest.json']) {
123
+ const state = await lstat(path.resolve(repoRoot, ref)).catch((error) => {
124
+ if (error?.code !== 'ENOENT') throw error;
125
+ return null;
126
+ });
127
+ if (state === null || state.isSymbolicLink() || (ref.endsWith('.json') ? !state.isFile() : !state.isDirectory())) stale();
128
+ }
129
+ for (const ref of [ROOT_REF, refs(planKey).dir, refs(planKey).open]) {
130
+ const absolute = path.resolve(repoRoot, ref);
131
+ await mkdir(absolute).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
132
+ const state = await lstat(absolute);
133
+ if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref });
134
+ }
135
+ }
136
+
137
+ const sameOverlaps = (left, right) => canonicalizeTodoArtifact(left) === canonicalizeTodoArtifact(right);
138
+
139
+ function checkInput(result) {
140
+ if (result === null || typeof result !== 'object' || Array.isArray(result)
141
+ || Object.keys(result).some((key) => !['witnessSet', 'relations', 'gone', 'headSha', 'unresolvedCount', 'computedAt']
142
+ .includes(key))) throw new TypeError('relation update result invalid');
143
+ const relations = result.relations ?? [];
144
+ const gone = result.gone ?? [];
145
+ const pair = (value, keys) => exactRecord(value, keys) && isTodoIdentifier(value.task_a)
146
+ && isTodoIdentifier(value.task_b) && value.task_a < value.task_b
147
+ && typeof value.path === 'string' && value.path.length > 0 && value.path.length <= 1024;
148
+ if (!Array.isArray(relations) || !Array.isArray(gone)
149
+ || !relations.every((entry) => pair(entry, ['task_a', 'task_b', 'path', 'overlaps'])
150
+ && todoRelationOverlapsValid(entry.overlaps))
151
+ || !gone.every((entry) => pair(entry, ['task_a', 'task_b', 'path']))
152
+ || new Set(relations.map(keyOf)).size !== relations.length
153
+ || (result.headSha !== undefined && result.headSha !== null
154
+ && (typeof result.headSha !== 'string' || result.headSha.length === 0 || result.headSha.length > 1024))
155
+ || (result.unresolvedCount !== undefined
156
+ && !(Number.isSafeInteger(result.unresolvedCount) && result.unresolvedCount >= 0))
157
+ || (result.computedAt !== undefined && !isStrictTodoTimestamp(result.computedAt))) {
158
+ throw new TypeError('relation update result invalid');
159
+ }
160
+ return { relations, gone };
161
+ }
162
+
163
+ /** The history log: appended, never read. At LOG_SEGMENT_BYTES the file is sealed under its last sequence and a new one starts. */
164
+ async function appendHistory(repoRoot, logRef, lastSequence, events) {
165
+ const absolute = path.resolve(repoRoot, logRef);
166
+ const state = await lstat(absolute).catch((error) => {
167
+ if (error?.code !== 'ENOENT') throw error;
168
+ return null;
169
+ });
170
+ if (state !== null && (state.isSymbolicLink() || !state.isFile())) fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref: logRef });
171
+ if (state !== null && state.size >= LOG_SEGMENT_BYTES) {
172
+ await rename(absolute, path.resolve(path.dirname(absolute), `log-${lastSequence}.jsonl`));
173
+ }
174
+ await appendFile(absolute, Buffer.concat(events.map(line)), { mode: 0o644 });
175
+ }
176
+
177
+ /**
178
+ * ADR 0204: one transaction over a plan's witness set and relation record, so two adds at once never miss each other.
179
+ * Under `relations/<planKey>/.write.lock` Store reads the witness set, the open relations and the plan's unfinished task
180
+ * ids, calls `update({witnessSet, openRelations, logSequence, unfinishedTaskIds})` (no Resolve, sensor or git inside:
181
+ * it only compares resolved ranges), then writes witness set, log, summary in that order. A crash between them leaves the
182
+ * row without its relations; the next write of that task recomputes its pairs (ids are content digests).
183
+ * Open relations are one per {task_a, task_b, path}: a changed one replaces the old, an identical one is a no-op, `gone`
184
+ * closes by key, and a relation of a task that is no longer unfinished is closed without being asked.
185
+ * Never call this while holding the Todo Store lock: this takes the relations lock first, then reads the Store.
186
+ */
187
+ export async function transactTodoRelations({ repoRoot = process.cwd(), planKey, writer, update } = {}) {
188
+ requireTodoStoreWriter(writer, 'todo-relations');
189
+ planKeyOf(planKey);
190
+ if (typeof update !== 'function') throw new TypeError('update must be a function');
191
+ const root = path.resolve(repoRoot);
192
+ const { dir, log: logRef, summary: summaryRef } = refs(planKey);
193
+ await ensureRelationDirectory(root, planKey);
194
+ try {
195
+ return await withStoreLock({ lockPath: path.join(root, dir, '.write.lock'), createParent: false,
196
+ waitMs: LOCK_WAIT_MS }, async (assertHeld) => {
197
+ const store = await readTodoStore({ repoRoot: root });
198
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
199
+ if (member === undefined) throw new TypeError('planKey is not an active plan of this Store');
200
+ const unfinished = new Set(member.tasks.filter(({ status }) => !FINISHED.has(status)).map(({ task_id: id }) => id));
201
+ const files = await readOpenFiles(root, planKey);
202
+ const dirty = new Set();
203
+ const open = new Map();
204
+ for (const entries of files.values()) {
205
+ for (const [key, event] of entries) if ((open.get(key)?.sequence ?? 0) < event.sequence) open.set(key, event);
206
+ }
207
+ // A relation lives in both its tasks' files; a crash between the two writes leaves one side: complete it.
208
+ const place = (event) => {
209
+ for (const id of [event.task_a, event.task_b]) {
210
+ if (!files.has(id)) files.set(id, new Map());
211
+ const held = files.get(id).get(keyOf(event));
212
+ if (held?.sequence !== event.sequence || held.relation_id !== event.relation_id) {
213
+ files.get(id).set(keyOf(event), event);
214
+ dirty.add(id);
215
+ }
216
+ }
217
+ };
218
+ const unplace = (event) => {
219
+ for (const id of [event.task_a, event.task_b]) if (files.get(id)?.delete(keyOf(event))) dirty.add(id);
220
+ };
221
+ for (const event of open.values()) place(event);
222
+ const previous = await readTodoRelationSummary({ repoRoot: root, planKey });
223
+ const witnessSet = await readTodoWitnessSet({ repoRoot: root, planKey });
224
+ const lastSequence = Math.max(previous?.log_sequence ?? 0, ...[...open.values()].map(({ sequence }) => sequence));
225
+
226
+ const result = await update({ witnessSet, openRelations: [...open.values()].map((event) => structuredClone(event)),
227
+ logSequence: lastSequence, unfinishedTaskIds: [...unfinished].sort() });
228
+ const { relations, gone } = checkInput(result ?? {});
229
+ const computedAt = result?.computedAt ?? new Date().toISOString();
230
+ const headSha = result?.headSha === undefined ? previous?.head_sha ?? null : result.headSha;
231
+ const unresolvedCount = result?.unresolvedCount ?? previous?.unresolved_count ?? 0;
232
+
233
+ const appended = [];
234
+ let sequence = lastSequence;
235
+ const close = (event) => {
236
+ open.delete(keyOf(event));
237
+ unplace(event);
238
+ appended.push({ schema: TODO_RELATION_EVENT_SCHEMA, kind: 'gone', sequence: ++sequence,
239
+ relation_id: event.relation_id, task_a: event.task_a, task_b: event.task_b, path: event.path,
240
+ head_sha: headSha, computed_at: computedAt });
241
+ };
242
+ for (const event of [...open.values()]) {
243
+ if (!unfinished.has(event.task_a) || !unfinished.has(event.task_b)) close(event);
244
+ }
245
+ for (const entry of gone) if (open.has(keyOf(entry))) close(open.get(keyOf(entry)));
246
+ let added = 0;
247
+ for (const entry of relations) {
248
+ if (!unfinished.has(entry.task_a) || !unfinished.has(entry.task_b)) continue;
249
+ const id = todoRelationId(entry);
250
+ const current = open.get(keyOf(entry));
251
+ if (current !== undefined && current.relation_id === id && sameOverlaps(current.overlaps, entry.overlaps)) continue;
252
+ if (current !== undefined) close(current);
253
+ const event = { schema: TODO_RELATION_EVENT_SCHEMA, kind: 'relation', sequence: ++sequence, relation_id: id,
254
+ task_a: entry.task_a, task_b: entry.task_b, path: entry.path, overlaps: entry.overlaps,
255
+ head_sha: headSha, computed_at: computedAt };
256
+ if (!validateTodoRelationEvent(event)) throw new TypeError('relation update result invalid');
257
+ open.set(keyOf(entry), event);
258
+ place(event);
259
+ appended.push(event);
260
+ added += 1;
261
+ }
262
+
263
+ const openList = [...open.values()].sort((left, right) => right.sequence - left.sequence);
264
+ const summary = { schema: TODO_RELATION_SUMMARY_SCHEMA, plan_key: planKey, relation_count: openList.length,
265
+ open_relations: openList.slice(0, TODO_RELATION_SUMMARY_OPEN).map(({ relation_id: id, task_a: a, task_b: b,
266
+ path: p, overlaps }) => ({ relation_id: id, task_a: a, task_b: b, path: p, overlaps })),
267
+ open_truncated: openList.length > TODO_RELATION_SUMMARY_OPEN, unresolved_count: unresolvedCount,
268
+ head_sha: headSha, log_sequence: sequence, computed_at: computedAt };
269
+ const stable = ({ computed_at: _at, ...rest }) => canonicalizeTodoArtifact(rest);
270
+ // The summary is recounted from the task files, so a crash that left it behind is healed by any later write.
271
+ const summaryChanged = previous === null
272
+ ? appended.length > 0 || openList.length > 0 || result?.headSha !== undefined || result?.unresolvedCount !== undefined
273
+ : stable(summary) !== stable(previous);
274
+
275
+ await assertHeld();
276
+ let writtenWitness = witnessSet;
277
+ if (result?.witnessSet !== undefined && result.witnessSet !== null) {
278
+ writtenWitness = (await writeTodoWitnessSet({ repoRoot: root, witnessSet: result.witnessSet })).witnessSet;
279
+ }
280
+ for (const id of [...dirty].sort()) {
281
+ const target = path.resolve(root, refs(planKey).task(id));
282
+ if (files.get(id).size === 0) await rm(target, { force: true });
283
+ else await atomicWrite(target, Buffer.concat([...files.get(id).values()].sort((l, r) => l.sequence - r.sequence).map(line)));
284
+ }
285
+ if (summaryChanged) await atomicWrite(path.resolve(root, summaryRef), line(summary));
286
+ if (appended.length > 0) await appendHistory(root, logRef, lastSequence, appended);
287
+ return { witnessSet: writtenWitness, summary: summaryChanged ? summary : previous, appended: added,
288
+ gone: appended.length - added };
289
+ });
290
+ } catch (error) {
291
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
292
+ throw error;
293
+ }
294
+ }
@@ -93,7 +93,7 @@ const CROSS_PLAN_IMPORT_TRANSACTION_SCHEMA = 'lattice.todo_cross_plan_import_tra
93
93
  const SOURCE_CUTOVER_BARRIER_REF = `${STORE_ROOT_REF}/source-cutover-recovery.json`;
94
94
  const SOURCE_CUTOVER_RECOVERY_CAPABILITY = Symbol('lattice.todo.source-cutover-recovery');
95
95
  const STORE_LOCK_HELD = Symbol('lattice.todo.lock-held');
96
- const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring']);
96
+ const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring', 'todo-relations']);
97
97
  const TODO_REVISION_SCHEMAS = Object.freeze([
98
98
  'lattice.todo_revision.v1', 'lattice.todo_revision.v2',
99
99
  ]);
@@ -114,7 +114,7 @@ export class TodoStoreError extends Error {
114
114
 
115
115
  export function createTodoStoreWriter(options = {}) {
116
116
  if (!exactRecord(options, ['caller']) || !WRITER_CALLERS.has(options.caller)) {
117
- throw new TypeError('todo store writer caller must be g4-migration or g5-authoring');
117
+ throw new TypeError('todo store writer caller must be g4-migration, g5-authoring or todo-relations');
118
118
  }
119
119
  return Object.freeze({ schema: 'lattice.todo_store_writer.v1', caller: options.caller });
120
120
  }
@@ -160,8 +160,10 @@ function rejectUnsupportedRevisionSchema(value, { family, supportedSchemas }) {
160
160
 
161
161
  // Reader registration (newer-value-says-upgrade): the newest schema of each Store record family this
162
162
  // reader knows. Bump it in the same diff that teaches the validator a new version.
163
- export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1, chart_meta: 1 });
164
- const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest']]);
163
+ export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1, chart_meta: 1,
164
+ todo_relation_event: 1, todo_relation_summary: 1, todo_witness_set: 6 });
165
+ const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest'],
166
+ [validateTodoWitnessSet, 'todo_witness_set']]);
165
167
  const vocabularyWord = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}$/u.test(value);
166
168
 
167
169
  function newerSchema(value, family) {
@@ -198,6 +200,8 @@ export function rejectNewerTodoSchema(value, family, ref) {
198
200
  if (newer !== null) failNewer(newer, ref);
199
201
  }
200
202
 
203
+ export function requireTodoStoreWriter(writer, caller) { requireWriter(writer, caller); }
204
+
201
205
  function requireWriter(writer, caller) {
202
206
  if (!exactRecord(writer, ['schema', 'caller']) || writer.schema !== 'lattice.todo_store_writer.v1'
203
207
  || writer.caller !== caller) throw new TypeError(`writer capability for ${caller} required`);
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import { canonicalizeTodoArtifact, isTodoIdentifier, isTodoRef, todoSelfDigest } from './todo-contracts.mjs';
15
- import { TODO_WITNESS_SET_SCHEMA } from './todo-independence-contracts.mjs';
15
+ import { TODO_WITNESS_SET_READ_ANCHORS_SCHEMA, TODO_WITNESS_SET_SCHEMA } from './todo-independence-contracts.mjs';
16
16
 
17
17
  const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
18
18
  const sortedUnique = (values) => [...new Set(values)].sort(compareText);
@@ -66,10 +66,12 @@ function explainDraftTask(task, schema) {
66
66
  && isTodoIdentifier(entry.kind) && typeof entry.ref === 'string' && entry.ref.length > 0))) {
67
67
  return { reason: 'invalid_unknowns', path: '/unknowns' };
68
68
  }
69
- if (task.concern_anchors !== undefined && !(Array.isArray(task.concern_anchors)
70
- && task.concern_anchors.every((anchor) => plainObject(anchor) && isTodoRef(anchor.within)
71
- && Array.isArray(anchor.symbols) && anchor.symbols.length > 0 && anchor.symbols.every(isTodoIdentifier)))) {
72
- return { reason: 'invalid_concern_anchors', path: '/concern_anchors' };
69
+ for (const key of ['concern_anchors', 'read_anchors']) {
70
+ if (task[key] !== undefined && !(Array.isArray(task[key])
71
+ && task[key].every((anchor) => plainObject(anchor) && isTodoRef(anchor.within)
72
+ && Array.isArray(anchor.symbols) && anchor.symbols.length > 0 && anchor.symbols.every(isTodoIdentifier)))) {
73
+ return { reason: `invalid_${key}`, path: `/${key}` };
74
+ }
73
75
  }
74
76
  return null;
75
77
  }
@@ -123,6 +125,9 @@ export function witnessDraftTemplate({ projectId, planKey, taskIds, witnessSet =
123
125
  ...(witness.concern_anchors?.length > 0 ? {
124
126
  concern_anchors: witness.concern_anchors.map(({ within, symbols }) => ({ within: within.target, symbols: [...symbols] })),
125
127
  } : {}),
128
+ ...(witness.read_anchors?.length > 0 ? {
129
+ read_anchors: witness.read_anchors.map(({ within, symbols }) => ({ within: within.target, symbols: [...symbols] })),
130
+ } : {}),
126
131
  };
127
132
  };
128
133
  return {
@@ -185,6 +190,13 @@ export function buildWitnessSet({ draft, observationByPath } = {}) {
185
190
  reasons.push(`anchor_outside_owned:${taskId}:${anchor.within}`);
186
191
  }
187
192
  }
193
+ const readTargets = new Set(Array.isArray(task.reads) ? task.reads : []);
194
+ for (const anchor of task.read_anchors ?? []) {
195
+ if (!readTargets.has(anchor.within)) reasons.push(`read_anchor_outside_reads:${taskId}:${anchor.within}`);
196
+ }
197
+ const anchorEntries = (anchors) => [...anchors]
198
+ .map((anchor) => ({ within: { kind: 'path', target: anchor.within }, symbols: sortedUnique(anchor.symbols) }))
199
+ .sort((left, right) => compareText(left.within.target, right.within.target));
188
200
  manualWitness[taskId] = {
189
201
  owns: owns.map(({ target, creates }) => (
190
202
  creates ? { kind: 'path', target, creates: true } : { kind: 'path', target }
@@ -205,21 +217,17 @@ export function buildWitnessSet({ draft, observationByPath } = {}) {
205
217
  .map(({ kind, ref }) => ({ kind, ref }))
206
218
  .sort((left, right) => compareText(`${left.kind}\u0000${left.ref}`, `${right.kind}\u0000${right.ref}`)),
207
219
  ...(Array.isArray(task.concern_anchors) && task.concern_anchors.length > 0
208
- ? {
209
- concern_anchors: [...task.concern_anchors]
210
- .map((anchor) => ({
211
- within: { kind: 'path', target: anchor.within },
212
- symbols: sortedUnique(anchor.symbols),
213
- }))
214
- .sort((left, right) => compareText(left.within.target, right.within.target)),
215
- }
216
- : {}),
220
+ ? { concern_anchors: anchorEntries(task.concern_anchors) } : {}),
221
+ ...(Array.isArray(task.read_anchors) && task.read_anchors.length > 0
222
+ ? { read_anchors: anchorEntries(task.read_anchors) } : {}),
217
223
  };
218
224
  }
219
225
  if (reasons.length > 0) return reject(reasons);
220
226
 
221
227
  const witnessSet = {
222
- schema: TODO_WITNESS_SET_SCHEMA,
228
+ // v6 only when some task reads functions: charts that do not use reads keep v5 and older readers (ADR 0204 §6).
229
+ schema: Object.values(manualWitness).some((witness) => witness.read_anchors !== undefined)
230
+ ? TODO_WITNESS_SET_READ_ANCHORS_SCHEMA : TODO_WITNESS_SET_SCHEMA,
223
231
  project_id: draft.project_id,
224
232
  plan_key: draft.plan_key,
225
233
  capacity: { executors: draft.capacity.executors },