@quolu/lattice 0.109.0 → 0.110.1

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.
@@ -7,8 +7,9 @@ import { renderDiagramLegend, renderRightPane } from './todo-gantt-html-independ
7
7
  import { escapeHtmlAttribute, escapeHtmlText, noticesBannerHtml, refKey } from './todo-gantt-html-shared.mjs';
8
8
  import { CSS, NESTED_CSS } from './todo-gantt-html-style.mjs';
9
9
  import { TODO_STRUCTURE_PRESENTATION_SCHEMA } from './todo-structure-presentation.mjs';
10
+ import { splitLabelsOf } from './todo-split-labels.mjs';
10
11
 
11
- export const TODO_GANTT_RENDERER_VERSION = 'lattice.todo_gantt_renderer.v20';
12
+ export const TODO_GANTT_RENDERER_VERSION = 'lattice.todo_gantt_renderer.v21';
12
13
  export const TODO_GANTT_PROSE_MAX_BYTES = 8 * 1024 * 1024;
13
14
  export const TODO_GANTT_HTML_MAX_BYTES = 24 * 1024 * 1024;
14
15
  const PROSE_OMITTED_TEXT = '(表示上限のため省略)';
@@ -89,6 +90,7 @@ function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts,
89
90
  };
90
91
  for (const member of readModel.members) {
91
92
  const states = new Map(member.tasks.map((state) => [state.task_id, state]));
93
+ const splitLabelOf = new Map(splitLabelsOf(member).map(({ task_id: id, label }) => [id, label]));
92
94
  for (const task of member.plan.tasks) {
93
95
  // retired(恒久除去)は図にも詳細パネルにも出さない。履歴と理由はsnapshot/journalが持つ。
94
96
  if (states.get(task.task_id)?.status === 'retired') continue;
@@ -124,7 +126,7 @@ function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts,
124
126
  }
125
127
  result.push({
126
128
  ref, task: shownTask, state: states.get(task.task_id), narrativeRef, anchorOutcome, noteContext,
127
- connections: connected.get(refKey(ref)) ?? [],
129
+ connections: connected.get(refKey(ref)) ?? [], splitLabel: splitLabelOf.get(task.task_id) ?? null,
128
130
  });
129
131
  }
130
132
  }
@@ -519,7 +519,7 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
519
519
  // perf-store: validated once per process while the files are unchanged (todo-version-memo).
520
520
  const version = await memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
521
521
  // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
522
- const compact = await readVersionCompact(versionRoot).catch(() => fail('NOTE_PROJECTION_INVALID',
522
+ const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
523
523
  'note_historical_plan_invalid', { plan_version: entry.name }));
524
524
  if (compact !== null) {
525
525
  if (compact.plan_key !== planKey || compact.plan_version !== entry.name) {
@@ -561,7 +561,8 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
561
561
  });
562
562
  if (version === null) continue;
563
563
  versions.add(entry.name);
564
- if (version.migration !== null) migrations.push(structuredClone(version.migration));
564
+ // The memoized migration is only read (migrationIndex copies it into its own Map), so it is shared, not cloned.
565
+ if (version.migration !== null) migrations.push(version.migration);
565
566
  }
566
567
  if ([...eventVersions].some((version) => !versions.has(version))) {
567
568
  fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
@@ -69,14 +69,14 @@ export function phaseTodoRevisionPlanVersion({
69
69
  }) {
70
70
  const versionDigest = digestTodoArtifact({
71
71
  schema: featureGraphDigest !== null ? 'lattice.phase_todo_revision_version.v3'
72
- : ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(desiredPlan.schema)
72
+ : ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(desiredPlan.schema)
73
73
  ? 'lattice.phase_todo_revision_version.v2' : 'lattice.phase_todo_revision_version.v1', project_id: projectId,
74
74
  plan_key: planKey, predecessor, desired_topology: {
75
75
  schema: desiredPlan.schema, project_id: desiredPlan.project_id,
76
76
  plan_key: desiredPlan.plan_key, predecessor_plan_digest: desiredPlan.predecessor_plan_digest,
77
77
  tasks: desiredPlan.tasks, phases: desiredPlan.phases,
78
78
  hard_dependencies: desiredPlan.hard_dependencies, joins: desiredPlan.joins,
79
- ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(desiredPlan.schema)
79
+ ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(desiredPlan.schema)
80
80
  ? { phase_accept_dependencies: desiredPlan.phase_accept_dependencies } : {}),
81
81
  }, task_migration: taskMigration, phase_migration: phaseMigration,
82
82
  ...(featureGraphDigest === null ? {} : { feature_graph_digest: featureGraphDigest }),
@@ -305,7 +305,7 @@ export function validatePhaseTodoRevision(value) {
305
305
  || !(revisionV3
306
306
  ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(value.desired_plan.schema)
307
307
  : (revisionV4 || revisionV5)
308
- ? ['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(value.desired_plan.schema)
308
+ ? ['lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(value.desired_plan.schema)
309
309
  : value.desired_plan.schema === (revisionV2 ? 'lattice.todo_plan.v5' : 'lattice.todo_plan.v4'))
310
310
  || value.desired_plan.project_id !== value.project_id
311
311
  || value.desired_plan.plan_key !== value.plan_key
@@ -856,7 +856,7 @@ export function explainPhaseTodoRevision(value) {
856
856
  if (!predecessorCheck.valid) return predecessorCheck;
857
857
  if (!validateTodoPlan(value.desired_plan)) return reject('desired_plan_invalid', '/desired_plan');
858
858
  const expectedPlanSchemas = revisionV3 ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
859
- : (revisionV4 || revisionV5) ? ['lattice.todo_plan.v7', 'lattice.todo_plan.v8']
859
+ : (revisionV4 || revisionV5) ? ['lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9']
860
860
  : [revisionV2 ? 'lattice.todo_plan.v5' : 'lattice.todo_plan.v4'];
861
861
  if (!expectedPlanSchemas.includes(value.desired_plan.schema)) {
862
862
  return reject('desired_plan_schema_mismatch', '/desired_plan/schema');
@@ -1037,7 +1037,7 @@ export function validateTodoRevisionSet(value) {
1037
1037
  }
1038
1038
 
1039
1039
  const PHASE_PREDECESSOR_SCHEMAS = new Set([
1040
- 'lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
1040
+ 'lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9',
1041
1041
  ]);
1042
1042
  const sourceKey = (entry) => `${entry.source_ref}\0${entry.source_digest}`;
1043
1043
 
@@ -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', 'todo-relations']);
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, g5-authoring or todo-relations');
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,8 @@ 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
- todo_relation_event: 1, todo_relation_summary: 1, todo_witness_set: 6 });
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
165
  const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest'],
166
166
  [validateTodoWitnessSet, 'todo_witness_set']]);
167
167
  const vocabularyWord = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}$/u.test(value);
@@ -414,12 +414,14 @@ function planScopedJournalRef(journalRef) {
414
414
  *
415
415
  * lifecycle journalと違いgenesisを持たない——planの存在はjournalが証明しており、この
416
416
  * chainはそこへ後から積まれる宣言だけを持つ。壊れている記録はnullや空へ丸めずtyped failにする。
417
+ * `verify: false`(通常の読み・k4)はlifecycle journalと同じく、eventごとのcanonical再確認とhash chain全検証を省く。
418
+ * `todo verify`(`verifyHistory`)だけが`verify: true`で全部を確かめる。
417
419
  */
418
- async function readPlanScopedJournal(repoRoot, journalRef) {
420
+ async function readPlanScopedJournal(repoRoot, journalRef, { verify = true } = {}) {
419
421
  const ref = planScopedJournalRef(journalRef);
420
422
  const absolute = path.resolve(repoRoot, ref);
421
423
  // s1-seal: sealed segments first, then the active file (same rules as the lifecycle journal).
422
- const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY);
424
+ const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY, { canonical: verify });
423
425
  let bytes = null;
424
426
  try {
425
427
  const state = await lstat(absolute);
@@ -433,11 +435,11 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
433
435
  // A crash between sealing and the active replacement leaves an active equal to the newest sealed segment.
434
436
  const redundant = bytes === null || segments.at(-1)?.bytes.equals(bytes) === true;
435
437
  const events = [...segments.flatMap(({ events: entries }) => entries),
436
- ...(redundant ? [] : parseJournalSegment(bytes, ref))];
438
+ ...(redundant ? [] : parseJournalSegment(bytes, ref, { canonical: verify }))];
437
439
  if (!events.every(({ kind }) => TODO_PLAN_SCOPED_EVENT_KINDS.includes(kind))) {
438
440
  fail('STORE_CORRUPT', 'plan_scoped_journal_kind_invalid');
439
441
  }
440
- const failures = verifyLinearHashChain({
442
+ const failures = !verify ? new Set() : verifyLinearHashChain({
441
443
  entries: events,
442
444
  canonicalize: canonicalizeTodoArtifact,
443
445
  digestField: 'event_digest',
@@ -1520,9 +1522,11 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1520
1522
 
1521
1523
  function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache = null) {
1522
1524
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1523
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) return;
1525
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
1526
+ 'lattice.todo_plan.v9'].includes(plan.schema)) return;
1524
1527
  const trusted = new Map((['lattice.todo_plan.v2', 'lattice.todo_plan.v3', 'lattice.todo_plan.v4',
1525
- 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(trustedPlan?.schema)
1528
+ 'lattice.todo_plan.v5', 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8',
1529
+ 'lattice.todo_plan.v9'].includes(trustedPlan?.schema)
1526
1530
  ? trustedPlan.tasks : [])
1527
1531
  .map((task) => [task.task_id, task.narrative_anchor]));
1528
1532
  for (const task of plan.tasks) {
@@ -1730,7 +1734,7 @@ async function readTodoStoreView(options = {}) {
1730
1734
  const phases = projectPhaseStates(plan, journal.events, new Map(tasks.map((task) => [task.task_id, task])));
1731
1735
  // 調整方式の宣言(ob03)。lifecycle journalとは別chainから読む。phasesと同じく
1732
1736
  // snapshot artifactの形式には縛られない導出ビューで、未宣言はnull(「まだ選んでいない」)。
1733
- const planScoped = await readPlanScopedJournal(repoRoot, descriptor.journal_ref);
1737
+ const planScoped = await readPlanScopedJournal(repoRoot, descriptor.journal_ref, { verify: verifyHistory });
1734
1738
  const coordination = projectTodoCoordination(planScoped.events)
1735
1739
  ?? await inheritedTodoCoordination(repoRoot, plan);
1736
1740
  loaded.push({ descriptor, plan, revision, journal, plan_scoped: planScoped,
@@ -1750,7 +1754,7 @@ async function readTodoStoreView(options = {}) {
1750
1754
  * unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
1751
1755
  */
1752
1756
  async function retainedPlanVersion(repoRoot, base, version) {
1753
- const compact = await readCompactRecord(repoRoot, base, version).catch(() => null);
1757
+ const compact = await readCompactRecord(repoRoot, base, version, { verify: false }).catch(() => null);
1754
1758
  if (compact !== null) {
1755
1759
  return { plan: { plan_digest: compact.plan_digest, predecessor_plan_digest: compact.predecessor_plan_digest,
1756
1760
  topology_digest: compact.topology_digest }, journalRef: `${base}/${version}/journal/active.jsonl` };
@@ -1767,10 +1771,10 @@ async function retainedPlanVersion(repoRoot, base, version) {
1767
1771
  }
1768
1772
 
1769
1773
  /** b10: a retained version's compact record (see todo-version-compact), or null while it still holds its own files. */
1770
- async function readCompactRecord(repoRoot, base, version) {
1774
+ async function readCompactRecord(repoRoot, base, version, { verify = true } = {}) {
1771
1775
  const directory = path.resolve(repoRoot, base, version);
1772
- return memoByFileIdentity([path.join(directory, TODO_VERSION_COMPACT_FILE)], () => readVersionCompact(directory)
1773
- .catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` })));
1776
+ return readVersionCompact(directory, undefined, { verify })
1777
+ .catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` }));
1774
1778
  }
1775
1779
 
1776
1780
  /** b10: one retained version's full `{plan, revision}` (revision null for a genesis version): its own files or its compact record. */
@@ -1912,8 +1916,8 @@ async function inheritedTodoCoordination(repoRoot, plan) {
1912
1916
  const predecessor = await find(digest);
1913
1917
  if (predecessor === undefined) return null;
1914
1918
  const declared = await memoByFileIdentity([path.resolve(repoRoot, planScopedJournalRef(predecessor.journalRef))],
1915
- () => readPlanScopedJournal(repoRoot, predecessor.journalRef)
1916
- .then((chain) => projectTodoCoordination(chain.events), () => undefined));
1919
+ () => readPlanScopedJournal(repoRoot, predecessor.journalRef, { verify: false })
1920
+ .then((chain) => projectTodoCoordination(chain.events), () => undefined), 'read');
1917
1921
  if (declared === undefined) return null;
1918
1922
  if (declared !== null) return declared;
1919
1923
  digest = predecessor.plan.predecessor_plan_digest;
@@ -4327,19 +4331,24 @@ export async function verifyPhaseTodoRevisionSources(options = {}) {
4327
4331
  }
4328
4332
 
4329
4333
  function stateMigrationFor(previous, revision) {
4330
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
4331
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
4334
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
4335
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9']
4332
4336
  .includes(revision.desired_plan.schema)) {
4333
4337
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
4334
4338
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4335
4339
  });
4336
4340
  }
4337
- if (previous.plan.schema === 'lattice.todo_plan.v8'
4338
- && revision.desired_plan.schema !== 'lattice.todo_plan.v8') {
4341
+ if (['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
4342
+ && !['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(revision.desired_plan.schema)) {
4339
4343
  fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
4340
4344
  predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4341
4345
  });
4342
4346
  }
4347
+ if (previous.plan.schema === 'lattice.todo_plan.v9' && revision.desired_plan.schema !== 'lattice.todo_plan.v9') {
4348
+ fail('REVISION_INVALID', 'function_split_schema_downgrade', {
4349
+ predecessor_schema: previous.plan.schema, desired_schema: revision.desired_plan.schema,
4350
+ });
4351
+ }
4343
4352
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id);
4344
4353
  const migrationIds = revision.task_migration.map(({ from_task_id }) => from_task_id);
4345
4354
  if (canonicalizeTodoArtifact([...oldIds].sort()) !== canonicalizeTodoArtifact([...migrationIds].sort())) {
@@ -6036,7 +6045,7 @@ export async function createSuccessorTodoPlan(options = {}) {
6036
6045
  ['lattice.todo_plan.v1', 1], ['lattice.todo_plan.v2', 2], ['lattice.todo_plan.v3', 3],
6037
6046
  // v6はphase無しv3へdesign_memoを追加した枝であり、phase世代より後という意味ではない。
6038
6047
  ['lattice.todo_plan.v4', 4], ['lattice.todo_plan.v5', 5], ['lattice.todo_plan.v6', 3],
6039
- ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5],
6048
+ ['lattice.todo_plan.v7', 5], ['lattice.todo_plan.v8', 5], ['lattice.todo_plan.v9', 5],
6040
6049
  ]);
6041
6050
  if (schemaRank.get(plan.schema) < schemaRank.get(previous.plan.schema)) {
6042
6051
  throw new TypeError(previous.plan.schema === 'lattice.todo_plan.v2'
@@ -6044,17 +6053,23 @@ export async function createSuccessorTodoPlan(options = {}) {
6044
6053
  ? 'todo plan schema cannot regress from v2 to v1'
6045
6054
  : 'todo plan schema cannot regress');
6046
6055
  }
6047
- if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(previous.plan.schema)
6048
- && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
6056
+ if (['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
6057
+ && !['lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(plan.schema)) {
6049
6058
  fail('REVISION_INVALID', 'design_memo_schema_downgrade', {
6050
6059
  predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6051
6060
  });
6052
6061
  }
6053
- if (previous.plan.schema === 'lattice.todo_plan.v8' && plan.schema !== 'lattice.todo_plan.v8') {
6062
+ if (['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(previous.plan.schema)
6063
+ && !['lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(plan.schema)) {
6054
6064
  fail('REVISION_INVALID', 'done_condition_schema_downgrade', {
6055
6065
  predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6056
6066
  });
6057
6067
  }
6068
+ if (previous.plan.schema === 'lattice.todo_plan.v9' && plan.schema !== 'lattice.todo_plan.v9') {
6069
+ fail('REVISION_INVALID', 'function_split_schema_downgrade', {
6070
+ predecessor_schema: previous.plan.schema, desired_schema: plan.schema,
6071
+ });
6072
+ }
6058
6073
  verifyPlanNarrativeAnchors(repoRoot, plan, previous.plan);
6059
6074
  const migration = options.genesis.task_migration ?? [];
6060
6075
  const oldIds = previous.plan.tasks.map(({ task_id }) => task_id).sort();
@@ -10,6 +10,7 @@
10
10
  import { readFile } from 'node:fs/promises';
11
11
  import { gunzipSync, gzipSync } from 'node:zlib';
12
12
  import { canonicalizeTodoArtifact, isTodoDigest, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
13
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
13
14
 
14
15
  export const TODO_VERSION_COMPACT_SCHEMA = 'lattice.todo_version_compact.v1';
15
16
  export const TODO_VERSION_COMPACT_FILE = 'compact.json.gz';
@@ -69,7 +70,8 @@ export function buildVersionCompact({ retained, anchor, revision }) {
69
70
  return record;
70
71
  }
71
72
 
72
- export function validateVersionCompact(value) {
73
+ /** `verify: false` (a read) checks the record's shape only; the self digest is recomputed for `verify` (writers, `todo verify`). */
74
+ export function validateVersionCompact(value, { verify = true } = {}) {
73
75
  const keys = ['schema', 'project_id', 'plan_key', 'plan_version', 'plan_digest', 'predecessor_plan_digest', 'predecessor_plan_version',
74
76
  'topology_digest', 'anchor_plan_version', 'anchor_plan_digest', 'plan_patch', 'revision', 'compact_digest'];
75
77
  return isObject(value) && Object.keys(value).length === keys.length && keys.every((key) => key in value)
@@ -79,7 +81,7 @@ export function validateVersionCompact(value) {
79
81
  && (value.predecessor_plan_digest === null || isTodoDigest(value.predecessor_plan_digest))
80
82
  && (value.predecessor_plan_version === null || isTodoIdentifier(value.predecessor_plan_version))
81
83
  && isObject(value.plan_patch) && (value.revision === null || isObject(value.revision))
82
- && value.compact_digest === todoSelfDigest(value, 'compact_digest');
84
+ && (!verify || value.compact_digest === todoSelfDigest(value, 'compact_digest'));
83
85
  }
84
86
 
85
87
  /** The exact plan of `record`, from its anchor's full plan. Throws when the result does not match plan_digest's plan. */
@@ -96,15 +98,22 @@ export const reconstructRevision = (record, plan) => (record.revision === null ?
96
98
  /** The record as stored: canonical JSON line, gzip-packed (a revision's per-task migration is long and repetitive). */
97
99
  export const packVersionCompact = (record) => gzipSync(Buffer.from(`${canonicalizeTodoArtifact(record)}\n`, 'utf8'), { level: 9 });
98
100
 
99
- /** The compact record in `directory`, or null when there is none. Throws when the file is not a canonical, digest-true record. */
100
- export async function readVersionCompact(directory, maxBytes = 8 * 1024 * 1024) {
101
- let packed;
102
- try { packed = await readFile(`${directory}/${TODO_VERSION_COMPACT_FILE}`); } catch (error) {
103
- if (error?.code === 'ENOENT') return null;
104
- throw error;
105
- }
106
- const text = gunzipSync(packed, { maxOutputLength: maxBytes }).toString('utf8');
107
- const value = JSON.parse(text);
108
- if (text !== `${canonicalizeTodoArtifact(value)}\n` || !validateVersionCompact(value)) throw new Error('compact_record_invalid');
109
- return value;
101
+ /**
102
+ * The compact record in `directory`, or null when there is none. Throws when the file is not a canonical, digest-true record.
103
+ * `verify: false` (ADR 0204 k4, a retained version is immutable history) skips the canonical re-serialization and the self digest
104
+ * and keeps the shape check: one gunzip and one parse per version, which a read pays for every retained version of a plan.
105
+ */
106
+ export async function readVersionCompact(directory, maxBytes = 8 * 1024 * 1024, { verify = true } = {}) {
107
+ // perf-store: a retained version is immutable, and the store reader and the note reader both ask for it in one process.
108
+ return memoByFileIdentity([`${directory}/${TODO_VERSION_COMPACT_FILE}`], async () => {
109
+ let packed;
110
+ try { packed = await readFile(`${directory}/${TODO_VERSION_COMPACT_FILE}`); } catch (error) {
111
+ if (error?.code === 'ENOENT') return null;
112
+ throw error;
113
+ }
114
+ const text = gunzipSync(packed, { maxOutputLength: maxBytes }).toString('utf8');
115
+ const value = JSON.parse(text);
116
+ if ((verify && text !== `${canonicalizeTodoArtifact(value)}\n`) || !validateVersionCompact(value, { verify })) throw new Error('compact_record_invalid');
117
+ return value;
118
+ }, verify ? 'verify' : 'read');
110
119
  }
@@ -20,8 +20,9 @@ async function fileIdentity(absolute) {
20
20
  }
21
21
  }
22
22
 
23
- export async function memoByFileIdentity(files, compute) {
24
- const key = files.join('\0');
23
+ /** `mode` separates values computed from the same files under different checks (a read's and a writer's). */
24
+ export async function memoByFileIdentity(files, compute, mode = '') {
25
+ const key = `${files.join('\0')}\0#${mode}`;
25
26
  const identity = (await Promise.all(files.map(fileIdentity))).join('|');
26
27
  const hit = memo.get(key);
27
28
  if (hit !== undefined && hit.identity === identity) return hit.value;