@quolu/lattice 0.108.0 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/bin/lattice.mjs +2 -2
  2. package/docs/schemas/lattice.plan_create_input.v6.schema.json +384 -0
  3. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +3 -0
  4. package/docs/schemas/lattice.todo_witness_draft.v2.schema.json +14 -2
  5. package/docs/schemas/lattice.todo_witness_set.v6.schema.json +482 -0
  6. package/package.json +3 -1
  7. package/sensor/dist/bin/lattice-sensor.js +76 -0
  8. package/sensor/dist/graph/anchor-resolve.d.ts +90 -0
  9. package/sensor/dist/graph/anchor-resolve.d.ts.map +1 -0
  10. package/sensor/dist/graph/anchor-resolve.js +132 -0
  11. package/sensor/dist/graph/anchor-resolve.js.map +1 -0
  12. package/sensor/dist/graph/touched-symbols.d.ts +42 -0
  13. package/sensor/dist/graph/touched-symbols.d.ts.map +1 -0
  14. package/sensor/dist/graph/touched-symbols.js +80 -0
  15. package/sensor/dist/graph/touched-symbols.js.map +1 -0
  16. package/src/cli-help.mjs +28 -6
  17. package/src/cli-refusal-guidance.mjs +3 -0
  18. package/src/function-split-verify.mjs +396 -0
  19. package/src/plan-backchain.mjs +18 -7
  20. package/src/plan-revise.mjs +26 -12
  21. package/src/plan-scope-review.mjs +1 -1
  22. package/src/project-cli.mjs +23 -3
  23. package/src/runtime-front-end.mjs +8 -3
  24. package/src/seam-apply.mjs +2 -2
  25. package/src/sensor-cli.mjs +82 -1
  26. package/src/sensor-resolve.mjs +116 -0
  27. package/src/sensor-touched.mjs +76 -0
  28. package/src/todo-authoring-input.mjs +1 -0
  29. package/src/todo-cli.mjs +303 -27
  30. package/src/todo-contracts.mjs +118 -4
  31. package/src/todo-declaration.mjs +165 -0
  32. package/src/todo-function-split.mjs +234 -0
  33. package/src/todo-gantt-html-independence.mjs +2 -2
  34. package/src/todo-gantt-html-shared.mjs +4 -1
  35. package/src/todo-gantt-html.mjs +4 -2
  36. package/src/todo-independence-authoritative-observation.mjs +26 -23
  37. package/src/todo-independence-contracts.mjs +17 -4
  38. package/src/todo-independence.mjs +4 -1
  39. package/src/todo-judgment.mjs +141 -0
  40. package/src/todo-relation-store.mjs +294 -0
  41. package/src/todo-revision.mjs +5 -5
  42. package/src/todo-split-labels.mjs +26 -0
  43. package/src/todo-split-start.mjs +100 -0
  44. package/src/todo-split-store.mjs +100 -0
  45. package/src/todo-store-view.mjs +3 -2
  46. package/src/todo-store.mjs +31 -14
  47. package/src/witness-scaffold.mjs +23 -15
@@ -0,0 +1,26 @@
1
+ // ADR 0205 §7 (b6): the labels 分割待ち / 関数分割, derived from the plan already read (the `function_split` marks and the task states).
2
+ // Display only: a status is never changed, and nothing here opens a file.
3
+
4
+ export const SPLIT_WAIT_LABEL = '分割待ち';
5
+ export const SPLIT_TASK_LABEL = '関数分割';
6
+
7
+ const FINISHED = new Set(['done', 'retired']);
8
+
9
+ /**
10
+ * `[{plan_key, task_id, label}]` for one Store member: the split task of an unfinished split, and every unfinished member of it
11
+ * (the one in progress too: its status still reads 作業中, the label sits beside it). A plan without marks gives `[]`.
12
+ */
13
+ export function splitLabelsOf(member) {
14
+ const status = new Map((member.tasks ?? []).map(({ task_id: id, status: state }) => [id, state]));
15
+ const labels = [];
16
+ for (const task of member.plan.tasks) {
17
+ if (!task.function_split || FINISHED.has(status.get(task.task_id))) continue;
18
+ const entry = (taskId, label) => labels.push({ plan_key: member.plan.plan_key, task_id: taskId, label });
19
+ entry(task.task_id, SPLIT_TASK_LABEL);
20
+ for (const id of task.function_split.members) if (status.has(id) && !FINISHED.has(status.get(id))) entry(id, SPLIT_WAIT_LABEL);
21
+ }
22
+ return labels;
23
+ }
24
+
25
+ /** One list for the whole Store (`session-context`, the display read). */
26
+ export const splitLabels = (store) => store.members.flatMap(splitLabelsOf);
@@ -0,0 +1,100 @@
1
+ // ADR 0205 §1 and §3 (b4): when a task starts and writes a function another lane's in-progress task writes, plan the split task.
2
+ // Pure: reads the plan and the starting task's open relations, returns what the revision must add; todo-cli applies it.
3
+
4
+ import { createHash } from 'node:crypto';
5
+
6
+ import { relationView } from './todo-judgment.mjs';
7
+ import { TODO_SPLIT_MAX_MEMBERS } from './todo-contracts.mjs';
8
+
9
+ const compare = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
10
+ const FINISHED = new Set(['done', 'retired']);
11
+ const rangesOverlap = (left, right) => !(left.end_line < right.start_line || right.end_line < left.start_line);
12
+
13
+ /** What a split worker must do, from the split task's current mark. The one text members get (no member rule exists for B). */
14
+ export function splitGuide({ planKey, taskId, mark }) {
15
+ const target = `${mark.path}#${mark.symbol}`;
16
+ const base = `lattice todo function-split`;
17
+ return [
18
+ `Tasks ${mark.members.join(', ')} all change ${target}. You decide whether to split it so each can change its own function.`,
19
+ 'Before you cut: verify needs at least one node-runnable test that statically imports a file the cut changes (otherwise tests fails with no_test_reaches_function): check one exists, and add one in the cut commit if none does.'
20
+ + ' A cut whose changed code is not JS/TS fails behaviour (export_surface_unobserved): then decline without cutting.',
21
+ `Split: write the cut on a branch from main (each member gets its own function), push the branch, then run`
22
+ + ` \`${base} verify --plan ${planKey} --task ${taskId} --commit <sha> --map ${mark.members.map((id) => `${id}=<path#function>`).join(',')}\``
23
+ + ' (map the members whose function changed; an unmapped member keeps its declaration).'
24
+ + ' Once verify accepts, open the PR with `[skip ci]` in the commit message (verify already ran the checks for the cut), merge it,'
25
+ + ` then run \`lattice todo done --plan ${planKey} --task ${taskId} --message <what you merged>\`.`,
26
+ `Not split: run \`${base} decline --plan ${planKey} --task ${taskId} --reason <text>\`; the later tasks then wait for the one that started first.`,
27
+ ].join('\n');
28
+ }
29
+
30
+ /**
31
+ * The split task and edges one `todo start T` needs, or null (start as today).
32
+ * `read` = `readTodoTaskRelations` of T (open relations only). `member` = the Store member (plan + task states).
33
+ * → `{splits: [{task_id, path, symbol, joined, members}], tasks: [new task], edges: [{from, to}], marks: Map, notes: [{task_id, body}]}`
34
+ */
35
+ export function planSplitHold({ member, taskId, read }) {
36
+ const { plan } = member;
37
+ const planKey = plan.plan_key;
38
+ const byId = new Map(plan.tasks.map((task) => [task.task_id, task]));
39
+ const state = new Map(member.tasks.map(({ task_id: id, status }) => [id, status]));
40
+ const self = byId.get(taskId);
41
+ if (read === null) return null;
42
+ // F = U's side of a write x write overlap with an in-progress task of another lane; a whole-file claim has no function to cut.
43
+ const functions = new Map();
44
+ for (const relation of read.open) {
45
+ const { with: otherId, path: where, overlaps } = relationView(taskId, relation);
46
+ const other = byId.get(otherId);
47
+ if (state.get(otherId) !== 'in-progress' || other.lane === self.lane) continue;
48
+ for (const { self: mine, other: theirs } of overlaps) {
49
+ if (mine.access !== 'write' || theirs.access !== 'write' || mine.symbol === null || theirs.symbol === null) continue;
50
+ const key = `${where}\0${theirs.symbol}`;
51
+ const entry = functions.get(key) ?? { path: where, symbol: theirs.symbol, start_line: theirs.start_line, end_line: theirs.end_line, owners: new Set() };
52
+ entry.owners.add(otherId);
53
+ functions.set(key, entry);
54
+ }
55
+ }
56
+ const edges = [];
57
+ const marks = new Map();
58
+ const tasks = [];
59
+ const splits = [];
60
+ const notes = [];
61
+ const edgeKey = (from, to) => `${from}\0${to}`;
62
+ const have = new Set(plan.hard_dependencies.map(({ from, to }) => edgeKey(from.task_id, to.task_id)));
63
+ const edge = (from, to) => { if (!have.has(edgeKey(from, to))) { have.add(edgeKey(from, to)); edges.push({ from, to }); } };
64
+ const open = plan.tasks.filter(({ task_id: id, function_split: mark }) => mark && !FINISHED.has(state.get(id)));
65
+ for (const found of [...functions.values()].sort((left, right) => compare(`${left.path}\0${left.symbol}`, `${right.path}\0${right.symbol}`))) {
66
+ const owners = [...found.owners].sort(compare);
67
+ // Two lanes already in progress on one function (started before B, or with --override-reason) is a runtime conflict (stage C).
68
+ if (new Set(owners.map((id) => byId.get(id).lane)).size > 1) continue;
69
+ const existing = open.find(({ function_split: mark }) => mark.path === found.path && mark.symbol === found.symbol)
70
+ ?? open.find(({ function_split: mark }) => mark.path === found.path && rangesOverlap(mark, found));
71
+ if (existing !== undefined) {
72
+ const mark = marks.get(existing.task_id) ?? existing.function_split;
73
+ if (!mark.members.includes(taskId)) {
74
+ if (mark.members.length >= TODO_SPLIT_MAX_MEMBERS) continue;
75
+ marks.set(existing.task_id, { ...mark, members: [...mark.members, taskId].sort(compare) });
76
+ notes.push({ task_id: existing.task_id, body: `split ${existing.task_id}: ${taskId} started on ${found.path}#${found.symbol} and joins the split` });
77
+ }
78
+ edge(existing.task_id, taskId);
79
+ splits.push({ task_id: existing.task_id, path: mark.path, symbol: mark.symbol, joined: true, members: marks.get(existing.task_id)?.members ?? mark.members });
80
+ continue;
81
+ }
82
+ const digest = createHash('sha256').update(`${planKey}\0${found.path}\0${found.symbol}`).digest('hex').slice(0, 12);
83
+ let id = `split-${digest}`;
84
+ for (let n = 2; byId.has(id); n += 1) id = `split-${digest}-${n}`;
85
+ const mark = { path: found.path, symbol: found.symbol, start_line: found.start_line, end_line: found.end_line,
86
+ members: [...owners, taskId].sort(compare) };
87
+ const lead = byId.get(owners[0]);
88
+ tasks.push({ task_id: id, title: `Split ${found.path}#${found.symbol}`, lane: lead.lane, phase_id: lead.phase_id,
89
+ design_memo: `Added by Lattice (ADR 0205): ${owners.join(', ')} (lane ${lead.lane}) is in progress and ${taskId} (lane ${self.lane}) is starting,`
90
+ + ` both writing ${found.path}#${found.symbol}. ${taskId} waits for this task.\n\n${splitGuide({ planKey, taskId: id, mark })}` });
91
+ for (const owner of owners) edge(id, owner);
92
+ edge(id, taskId);
93
+ marks.set(id, mark);
94
+ splits.push({ task_id: id, path: mark.path, symbol: mark.symbol, joined: false, members: mark.members });
95
+ // a later function of this start may overlap the split just made: it is open now.
96
+ open.push({ task_id: id, function_split: mark });
97
+ byId.set(id, tasks.at(-1));
98
+ }
99
+ return splits.length === 0 ? null : { splits, tasks, edges, marks, notes };
100
+ }
@@ -0,0 +1,100 @@
1
+ // ADR 0205 b2: the verify outcome of one split task, `.lattice/todo/splits/<plan_key>/<task_id>.json`. docs/architecture/dfd-store-split.md
2
+ import { lstat, mkdir, readFile } 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_SPLIT_RECORD_SCHEMA, canonicalizeTodoArtifact, isTodoIdentifier, validateTodoSplitRecord,
7
+ } from './todo-contracts.mjs';
8
+ import {
9
+ TodoStoreError, atomicWrite, readTodoStore, rejectNewerTodoSchema, requireTodoStoreWriter,
10
+ } from './todo-store.mjs';
11
+
12
+ const ROOT_REF = '.lattice/todo/splits';
13
+ const RECORD_MAX_BYTES = 65_536;
14
+ const FINISHED = new Set(['done', 'retired']);
15
+
16
+ const fail = (code, reason, detail) => { throw new TodoStoreError(code, reason, reason, detail); };
17
+ const refOf = (planKey, taskId) => `${ROOT_REF}/${planKey}/${taskId}.json`;
18
+
19
+ function idsOf(planKey, taskId) {
20
+ if (!isTodoIdentifier(planKey) || !isTodoIdentifier(taskId)) throw new TypeError('planKey and taskId must be todo identifiers');
21
+ }
22
+
23
+ /** The split record of task S, or null when none was written (never listed, never scanned). Lock-free: a write replaces the file whole. */
24
+ export async function readTodoSplit({ repoRoot = process.cwd(), planKey, taskId } = {}) {
25
+ idsOf(planKey, taskId);
26
+ const ref = refOf(planKey, taskId);
27
+ let text;
28
+ try {
29
+ const absolute = path.resolve(repoRoot, ref);
30
+ const state = await lstat(absolute);
31
+ if (state.isSymbolicLink() || !state.isFile() || state.size > RECORD_MAX_BYTES) fail('STORE_INCONSISTENT', 'split_record_invalid', { ref });
32
+ text = await readFile(absolute, 'utf8');
33
+ } catch (error) {
34
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
35
+ throw error;
36
+ }
37
+ let value;
38
+ try { value = JSON.parse(text); } catch { fail('STORE_INCONSISTENT', 'split_record_invalid', { ref }); }
39
+ rejectNewerTodoSchema(value, 'todo_split_record', ref);
40
+ if (!validateTodoSplitRecord(value) || value.plan_key !== planKey || value.task_id !== taskId) {
41
+ fail('STORE_INCONSISTENT', 'split_record_invalid', { ref });
42
+ }
43
+ return value;
44
+ }
45
+
46
+ async function ensureSplitDirectory(repoRoot, planKey) {
47
+ const stale = () => fail('STORE_WRITE_CONFLICT', 'store_locked', {
48
+ next_action: 'Initialize a published Todo Store before writing a split record, then retry.',
49
+ });
50
+ for (const ref of ['.lattice', '.lattice/todo', '.lattice/todo/manifest.json']) {
51
+ const state = await lstat(path.resolve(repoRoot, ref)).catch((error) => {
52
+ if (error?.code !== 'ENOENT') throw error;
53
+ return null;
54
+ });
55
+ if (state === null || state.isSymbolicLink() || (ref.endsWith('.json') ? !state.isFile() : !state.isDirectory())) stale();
56
+ }
57
+ for (const ref of [ROOT_REF, `${ROOT_REF}/${planKey}`]) {
58
+ const absolute = path.resolve(repoRoot, ref);
59
+ await mkdir(absolute).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
60
+ const state = await lstat(absolute);
61
+ if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'split_record_invalid', { ref });
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Writes the verify outcome of split task S: `record` = `{map, commit, base, outcome, conditions, recorded_at, actor}`; the Store adds
67
+ * schema, plan_key, task_id and `attempt` (the previous attempt + 1, so a re-verify replaces the file whole). Under
68
+ * `splits/<plan_key>/.write.lock`, held only for this write (never across the verify run), taken before any Store read: never call
69
+ * this while holding the Todo Store lock. Checks, then writes: S is an unfinished task of the plan with a function_split mark, every
70
+ * map entry names a member of it. An over-bound or malformed record is a writer bug (TypeError), never truncated.
71
+ */
72
+ export async function recordTodoSplit({ repoRoot = process.cwd(), planKey, taskId, writer, record } = {}) {
73
+ requireTodoStoreWriter(writer, 'todo-splits');
74
+ idsOf(planKey, taskId);
75
+ const root = path.resolve(repoRoot);
76
+ await ensureSplitDirectory(root, planKey);
77
+ try {
78
+ return await withStoreLock({ lockPath: path.join(root, ROOT_REF, planKey, '.write.lock'), createParent: false,
79
+ waitMs: LOCK_WAIT_MS }, async (assertHeld) => {
80
+ const store = await readTodoStore({ repoRoot: root });
81
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
82
+ const mark = member?.plan.tasks.find(({ task_id: id }) => id === taskId)?.function_split ?? null;
83
+ if (mark === null) throw new TypeError('taskId is not a task of an active plan with a function_split mark');
84
+ const status = member.tasks.find(({ task_id: id }) => id === taskId)?.status;
85
+ if (FINISHED.has(status)) fail('STORE_WRITE_CONFLICT', 'split_task_finished', { plan_key: planKey, task_id: taskId, status });
86
+ const previous = await readTodoSplit({ repoRoot: root, planKey, taskId });
87
+ const value = { ...record, schema: TODO_SPLIT_RECORD_SCHEMA, plan_key: planKey, task_id: taskId,
88
+ attempt: (previous?.attempt ?? 0) + 1 };
89
+ const bytes = Buffer.from(`${canonicalizeTodoArtifact(value)}\n`, 'utf8');
90
+ if (!validateTodoSplitRecord(value) || bytes.length > RECORD_MAX_BYTES
91
+ || !value.map.every(({ task_id: id }) => mark.members.includes(id))) throw new TypeError('split record invalid');
92
+ await assertHeld();
93
+ await atomicWrite(path.resolve(root, refOf(planKey, taskId)), bytes);
94
+ return value;
95
+ });
96
+ } catch (error) {
97
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
98
+ throw error;
99
+ }
100
+ }
@@ -15,7 +15,8 @@ export function normalizeCheckoutEol(bytes) {
15
15
  }
16
16
 
17
17
  export function isPhaseTodoPlanSchema(schema) {
18
- return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(schema);
18
+ return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
19
+ 'lattice.todo_plan.v9'].includes(schema);
19
20
  }
20
21
 
21
22
  /** One finished-predecessor predicate for Store replay and readiness: done or retired (a13: retire deletes the task, so its edges count as gone). */
@@ -34,7 +35,7 @@ export function stepTodoReopenedPending(ids, event) {
34
35
  }
35
36
 
36
37
  export function isDecoupledPhaseTodoPlanSchema(schema) {
37
- return ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(schema);
38
+ return ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(schema);
38
39
  }
39
40
 
40
41
  // CLI側(migrate/plan create/最後のdone)が「終端重監査が要る」ことを通知するために
@@ -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', 'todo-splits']);
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, todo-relations or todo-splits');
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: 9, 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, todo_split_record: 1 });
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`);
@@ -1516,9 +1520,11 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1516
1520
 
1517
1521
  function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache = null) {
1518
1522
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1519
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) return;
1523
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
1524
+ 'lattice.todo_plan.v9'].includes(plan.schema)) return;
1520
1525
  const trusted = new Map((['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1521
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(trustedPlan?.schema)
1526
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
1527
+ 'lattice.todo_plan.v9'].includes(trustedPlan?.schema)
1522
1528
  ? trustedPlan.tasks : [])
1523
1529
  .map((task) => [task.task_id, task.narrative_anchor]));
1524
1530
  for (const task of plan.tasks) {
@@ -4323,19 +4329,24 @@ export async function verifyPhaseTodoRevisionSources(options = {}) {
4323
4329
  }
4324
4330
 
4325
4331
  function stateMigrationFor(previous, revision) {
4326
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
4327
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
4332
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
4333
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9']
4328
4334
  .includes(revision.desired_plan.schema)) {
4329
4335
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
4330
4336
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4331
4337
  });
4332
4338
  }
4333
- if (previous.plan.schema === 'lattice.todo_plan.v8'
4334
- && revision.desired_plan.schema !== 'lattice.todo_plan.v8') {
4339
+ if (['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
4340
+ && !['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(revision.desired_plan.schema)) {
4335
4341
  fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
4336
4342
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4337
4343
  });
4338
4344
  }
4345
+ if (previous.plan.schema === 'lattice.todo_plan.v9' && revision.desired_plan.schema !== 'lattice.todo_plan.v9') {
4346
+ fail('REVISION_INVALID', 'function_split_schema_downgrade', {
4347
+ predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4348
+ });
4349
+ }
4339
4350
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id);
4340
4351
  const migrationIds = revision.task_migration.map(({ from_task_id }) => from_task_id);
4341
4352
  if (canonicalizeTodoArtifact([...oldIds].sort()) !== canonicalizeTodoArtifact([...migrationIds].sort())) {
@@ -6032,7 +6043,7 @@ export async function createSuccessorTodoPlan(options = {}) {
6032
6043
  ['lattice.todo_plan.v1', 1], ['lattice.todo_plan.v2', 2], ['lattice.todo_plan.v3', 3],
6033
6044
  // v6はphase無しv3へdesign_memoを追加した枝であり、phase世代より後という意味ではない。
6034
6045
  ['lattice.todo_plan.v4', 4], ['lattice.todo_plan.v5', 5], ['lattice.todo_plan.v6', 3],
6035
- ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5],
6046
+ ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5], ['lattice.todo_plan.v9', 5],
6036
6047
  ]);
6037
6048
  if (schemaRank.get(plan.schema) < schemaRank.get(previous.plan.schema)) {
6038
6049
  throw new TypeError(previous.plan.schema === 'lattice.todo_plan.v2'
@@ -6040,17 +6051,23 @@ export async function createSuccessorTodoPlan(options = {}) {
6040
6051
  ? 'todo plan schema cannot regress from v2 to v1'
6041
6052
  : 'todo plan schema cannot regress');
6042
6053
  }
6043
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
6044
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
6054
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
6055
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(plan.schema)) {
6045
6056
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
6046
6057
  predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6047
6058
  });
6048
6059
  }
6049
- if (previous.plan.schema === 'lattice.todo_plan.v8' && plan.schema !== 'lattice.todo_plan.v8') {
6060
+ if (['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
6061
+ && !['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(plan.schema)) {
6050
6062
  fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
6051
6063
  predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6052
6064
  });
6053
6065
  }
6066
+ if (previous.plan.schema === 'lattice.todo_plan.v9' && plan.schema !== 'lattice.todo_plan.v9') {
6067
+ fail('REVISION_INVALID', 'function_split_schema_downgrade', {
6068
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6069
+ });
6070
+ }
6054
6071
  verifyPlanNarrativeAnchors(repoRoot, plan, previous.plan);
6055
6072
  const migration = options.genesis.task_migration ?? [];
6056
6073
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id).sort();
@@ -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 },