@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
@@ -53,6 +53,14 @@ export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
53
53
  export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
54
54
  /** a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). */
55
55
  export const TODO_CHART_META_SCHEMA = 'lattice.chart_meta.v1';
56
+ /** ADR 0204 a4: function-level conflict relations, one open relation per (task_a, task_b, path); dfd-store-relations. */
57
+ export const TODO_RELATION_EVENT_SCHEMA = 'lattice.todo_relation_event.v1';
58
+ export const TODO_RELATION_SUMMARY_SCHEMA = 'lattice.todo_relation_summary.v1';
59
+ export const TODO_RELATION_SUMMARY_OPEN = 20;
60
+ /** ADR 0205 b2: the verify outcome of one split task, one file `.lattice/todo/splits/<plan_key>/<task_id>.json`; dfd-store-split. */
61
+ export const TODO_SPLIT_RECORD_SCHEMA = 'lattice.todo_split_record.v1';
62
+ export const TODO_SPLIT_CONDITIONS = Object.freeze(['behaviour', 'tests', 'fresh', 'overlap', 'parallel']);
63
+ export const TODO_SPLIT_MAX_MEMBERS = 64;
56
64
  /**
57
65
  * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
58
66
  * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
@@ -402,6 +410,25 @@ function taskV8(value) {
402
410
  ]) && taskV6(rest) && (doneCondition === null || isTodoDesignMemo(doneCondition));
403
411
  }
404
412
 
413
+ const splitText = (value) => typeof value === 'string' && value.length > 0 && Buffer.byteLength(value, 'utf8') <= 1_024
414
+ && !CONTROL.test(value);
415
+
416
+ /** ADR 0205 §2: the split mark. `members` are sorted unique task ids (start order is never stored); the range is a snapshot. */
417
+ const functionSplit = (value) => exactRecord(value, ['path', 'symbol', 'start_line', 'end_line', 'members'])
418
+ && isTodoRef(value.path) && splitText(value.symbol)
419
+ && Number.isSafeInteger(value.start_line) && value.start_line >= 1
420
+ && Number.isSafeInteger(value.end_line) && value.end_line >= value.start_line
421
+ && Array.isArray(value.members) && value.members.length >= 2 && value.members.length <= TODO_SPLIT_MAX_MEMBERS
422
+ && value.members.every((id, index) => isTodoIdentifier(id) && (index === 0 || compareText(value.members[index - 1], id) < 0));
423
+
424
+ function taskV9(value) {
425
+ const { function_split: split, ...rest } = value ?? {};
426
+ return exactRecord(value, [
427
+ 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
428
+ 'compile_binding', 'parent_task_id', 'phase_id', 'done_condition', 'function_split',
429
+ ]) && taskV8(rest) && (split === null || functionSplit(split));
430
+ }
431
+
405
432
  function phaseV1(value) {
406
433
  return exactRecord(value, [
407
434
  'phase_id', 'title', 'gate_policy', 'predecessor_phase_ids', 'required_evidence_slots',
@@ -472,14 +499,15 @@ export function explainTodoPlan(value) {
472
499
  : ['lattice.todo_plan.v4', 'lattice.todo_plan.v5'].includes(value?.schema) ? taskV4
473
500
  : value?.schema === 'lattice.todo_plan.v6' ? taskV5
474
501
  : value?.schema === 'lattice.todo_plan.v7' ? taskV6
475
- : value?.schema === 'lattice.todo_plan.v8' ? taskV8 : null;
502
+ : value?.schema === 'lattice.todo_plan.v8' ? taskV8
503
+ : value?.schema === 'lattice.todo_plan.v9' ? taskV9 : null;
476
504
  const planKeys = [
477
505
  'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
478
506
  'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
479
507
  ];
480
508
  const phased = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7',
481
- 'lattice.todo_plan.v8'].includes(value?.schema);
482
- const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
509
+ 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(value?.schema);
510
+ const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9']
483
511
  .includes(value?.schema);
484
512
  if (phased) planKeys.push('phases');
485
513
  if (decoupled) planKeys.push('phase_accept_dependencies');
@@ -495,6 +523,12 @@ export function explainTodoPlan(value) {
495
523
  if (new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length) {
496
524
  return reject('duplicate_task_id', '/tasks');
497
525
  }
526
+ if (value.schema === 'lattice.todo_plan.v9') {
527
+ const ids = new Set(value.tasks.map(({ task_id: id }) => id));
528
+ const stray = value.tasks.findIndex(({ task_id: id, function_split: split }) => split !== null
529
+ && (split.members.includes(id) || !split.members.every((member) => ids.has(member))));
530
+ if (stray >= 0) return reject('function_split_members_invalid', `/tasks/${stray}/function_split/members`);
531
+ }
498
532
  if (!Array.isArray(value.hard_dependencies)) {
499
533
  return reject('bounded_collection_violation', '/hard_dependencies');
500
534
  }
@@ -512,7 +546,7 @@ export function explainTodoPlan(value) {
512
546
  if (!isTodoDigest(value[field])) return reject('digest_invalid', `/${field}`);
513
547
  }
514
548
  if (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
515
- 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(value.schema)
549
+ 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8', 'lattice.todo_plan.v9'].includes(value.schema)
516
550
  && !validParentGraph(value.tasks)) return reject('parent_graph_invalid', '/tasks');
517
551
  if (phased) {
518
552
  if (!Array.isArray(value.phases) || value.phases.length === 0) return reject('bounded_collection_violation', '/phases');
@@ -906,3 +940,83 @@ export function validateTodoChartMeta(value) {
906
940
  && (repo === null || (exactRecord(repo, ['url', 'branch', 'accepted_tip'])
907
941
  && word(repo.url) && word(repo.branch) && text(repo.accepted_tip)));
908
942
  }
943
+
944
+ // ---- ADR 0204 a4 relations ------------------------------------------------------------------------------------
945
+ const relationText = (field) => typeof field === 'string' && field.length > 0 && field.length <= 1024;
946
+ const relationSha = (field) => field === null || relationText(field);
947
+ const lineNumber = (field) => Number.isSafeInteger(field) && field >= 1;
948
+
949
+ /** One side of an overlap. A whole-file claim has no symbol and no range (both null). */
950
+ function relationEntry(entry) {
951
+ return exactRecord(entry, ['symbol', 'start_line', 'end_line', 'access'])
952
+ && ['read', 'write'].includes(entry.access)
953
+ && ((entry.symbol === null && entry.start_line === null && entry.end_line === null)
954
+ || (relationText(entry.symbol) && lineNumber(entry.start_line) && lineNumber(entry.end_line)
955
+ && entry.end_line >= entry.start_line));
956
+ }
957
+
958
+ /** The pair identity: task_a sorts before task_b, so a pair has one spelling. */
959
+ const relationKey = (value) => isTodoIdentifier(value.task_a) && isTodoIdentifier(value.task_b)
960
+ && value.task_a < value.task_b && relationText(value.path);
961
+
962
+ export const todoRelationOverlapsValid = (overlaps) => Array.isArray(overlaps) && overlaps.length > 0
963
+ && overlaps.every((overlap) => exactRecord(overlap, ['a', 'b']) && relationEntry(overlap.a) && relationEntry(overlap.b));
964
+
965
+ /** Content identity of a relation (head and time excluded): the same overlap re-found is not a new relation. */
966
+ export function todoRelationId(relation) {
967
+ return digestTodoArtifact({ task_a: relation.task_a, task_b: relation.task_b, path: relation.path,
968
+ overlaps: relation.overlaps });
969
+ }
970
+
971
+ export function validateTodoRelationEvent(value) {
972
+ try {
973
+ const common = value !== null && typeof value === 'object' && value.schema === TODO_RELATION_EVENT_SCHEMA
974
+ && Number.isSafeInteger(value.sequence) && value.sequence >= 1 && isTodoDigest(value.relation_id)
975
+ && relationKey(value) && relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
976
+ if (!common) return false;
977
+ if (value.kind === 'gone') {
978
+ return exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'head_sha', 'computed_at']);
979
+ }
980
+ return value.kind === 'relation'
981
+ && exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'overlaps', 'head_sha', 'computed_at'])
982
+ && todoRelationOverlapsValid(value.overlaps) && value.relation_id === todoRelationId(value);
983
+ } catch { return false; }
984
+ }
985
+
986
+ const summaryRelation = (entry) => exactRecord(entry, ['relation_id', 'task_a', 'task_b', 'path', 'overlaps'])
987
+ && isTodoDigest(entry.relation_id) && relationKey(entry) && todoRelationOverlapsValid(entry.overlaps);
988
+
989
+ export function validateTodoRelationSummary(value) {
990
+ try {
991
+ return exactRecord(value, ['schema', 'plan_key', 'relation_count', 'open_relations', 'open_truncated',
992
+ 'unresolved_count', 'head_sha', 'log_sequence', 'computed_at'])
993
+ && value.schema === TODO_RELATION_SUMMARY_SCHEMA && isTodoIdentifier(value.plan_key)
994
+ && isNonNegativeSafeInteger(value.relation_count) && isNonNegativeSafeInteger(value.unresolved_count)
995
+ && isNonNegativeSafeInteger(value.log_sequence) && Array.isArray(value.open_relations)
996
+ && value.open_relations.length <= TODO_RELATION_SUMMARY_OPEN && value.open_relations.every(summaryRelation)
997
+ && value.open_truncated === (value.relation_count > value.open_relations.length)
998
+ && relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
999
+ } catch { return false; }
1000
+ }
1001
+
1002
+ const splitCondition = (value) => exactRecord(value, ['passed', 'detail']) && typeof value.passed === 'boolean'
1003
+ && typeof value.detail === 'string' && Buffer.byteLength(value.detail, 'utf8') <= 2_048;
1004
+ const splitMapEntry = (value) => exactRecord(value, ['task_id', 'path', 'symbol'])
1005
+ && isTodoIdentifier(value.task_id) && isTodoRef(value.path) && splitText(value.symbol);
1006
+
1007
+ /** ADR 0205 §2: `accepted` only when all five conditions passed; the map has at most one entry per task, sorted by task_id. */
1008
+ export function validateTodoSplitRecord(value) {
1009
+ try {
1010
+ return exactRecord(value, ['schema', 'plan_key', 'task_id', 'attempt', 'map', 'commit', 'base', 'outcome',
1011
+ 'conditions', 'recorded_at', 'actor'])
1012
+ && value.schema === TODO_SPLIT_RECORD_SCHEMA && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.task_id)
1013
+ && Number.isSafeInteger(value.attempt) && value.attempt >= 1
1014
+ && Array.isArray(value.map) && value.map.length <= TODO_SPLIT_MAX_MEMBERS && value.map.every(splitMapEntry)
1015
+ && value.map.every((entry, index) => index === 0 || compareText(value.map[index - 1].task_id, entry.task_id) < 0)
1016
+ && /^[0-9a-f]{40}$/u.test(value.commit) && /^[0-9a-f]{40}$/u.test(value.base)
1017
+ && ['accepted', 'rejected'].includes(value.outcome)
1018
+ && exactRecord(value.conditions, TODO_SPLIT_CONDITIONS) && TODO_SPLIT_CONDITIONS.every((key) => splitCondition(value.conditions[key]))
1019
+ && (value.outcome === 'rejected' || TODO_SPLIT_CONDITIONS.every((key) => value.conditions[key].passed))
1020
+ && isStrictTodoTimestamp(value.recorded_at) && actor(value.actor);
1021
+ } catch { return false; }
1022
+ }
@@ -0,0 +1,165 @@
1
+ // Plan/lifecycle: the functions a task changes or reads, declared once when the task is added (ADR 0204 §1, §6).
2
+ // `--owns src/a.mjs#foo,src/b.mjs` / `--reads src/c.mjs#bar` → one witness-draft row. Resolution goes through the code graph's
3
+ // public Resolve interface only; nothing here reads the sensor index.
4
+ import { existsSync } from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ import { runSensorCli } from './sensor-cli.mjs';
8
+ import { parseAnchor, proposeSymbols, resolveAnchors, SensorResolveError } from './sensor-resolve.mjs';
9
+ import { isTodoIdentifier } from './todo-contracts.mjs';
10
+ import { TodoStoreError } from './todo-store.mjs';
11
+
12
+ // A flag is a comma list; plan input (`touches`) already gives an array.
13
+ const items = (value) => (Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [])
14
+ .map((item) => item.trim()).filter(Boolean);
15
+ const sortedUnique = (values) => [...new Set(values)].sort();
16
+
17
+ /** Every path a declaration names, anchored or not (`owns`, `reads`, `writes` flags): a Set. */
18
+ export function declaredPaths({ owns, reads, writes }) {
19
+ const { paths: ownPaths, anchors: ownAnchors } = parseDeclarationList(owns);
20
+ const { paths: readPaths, anchors: readAnchors } = parseDeclarationList(reads);
21
+ return new Set([...ownPaths, ...readPaths, ...items(writes), ...[...ownAnchors, ...readAnchors].map(({ path: where }) => where)]);
22
+ }
23
+
24
+ /** `a.mjs,b.mjs#foo` → bare paths, anchors, and entries that cannot be stored (with why). */
25
+ export function parseDeclarationList(value) {
26
+ const paths = [];
27
+ const anchors = [];
28
+ const malformed = [];
29
+ for (const text of items(value)) {
30
+ if (!text.includes('#')) { paths.push(text); continue; }
31
+ const anchor = parseAnchor(text);
32
+ if (anchor === null) malformed.push({ text, reason: 'expected_path_hash_symbol' });
33
+ // The witness row stores the symbol as a dotted identifier chain (Ruby `Foo#bar` cannot be stored).
34
+ else if (!isTodoIdentifier(anchor.symbol)) malformed.push({ text, reason: 'symbol_not_a_dotted_identifier' });
35
+ else anchors.push(anchor);
36
+ }
37
+ return { paths, anchors, malformed };
38
+ }
39
+
40
+ const byWithin = (anchors) => {
41
+ const grouped = new Map();
42
+ for (const { path: within, symbol } of anchors) grouped.set(within, [...(grouped.get(within) ?? []), symbol]);
43
+ return [...grouped].map(([within, symbols]) => ({ within, symbols: sortedUnique(symbols) }));
44
+ };
45
+
46
+ async function resolveOnce(root, anchors) {
47
+ try { return await resolveAnchors({ root, anchors }); } catch (error) {
48
+ if (!(error instanceof SensorResolveError) || error.code !== 'RESOLVE_INDEX_MISSING') throw error;
49
+ }
50
+ // First use only: the maintained index does not exist yet (Observe builds it; later calls reuse it).
51
+ const sink = { write() {} };
52
+ await runSensorCli({ argv: ['init', root, '--json'], stdout: sink, stderr: sink });
53
+ return resolveAnchors({ root, anchors });
54
+ }
55
+
56
+ const unresolvedEntry = (anchor, reason, nearest = [], elsewhere = []) => ({
57
+ path: anchor.path, symbol: anchor.symbol, reason, nearest, elsewhere,
58
+ });
59
+
60
+ /**
61
+ * Resolve a task's declared functions and build its witness-draft row.
62
+ * → `{row, declaration: {written, resolved[], unresolved[], malformed[]}}`; `row` is null when `written` is false
63
+ * (a task's row is not written until every name resolves, so the next declare retries from scratch).
64
+ * `observable` false = the Store root has no code tree: functions cannot be checked, never recorded as a guess.
65
+ */
66
+ export async function buildDeclarationRow({ root, observable, owns, reads, writes, alsoResolve = [] }) {
67
+ const own = parseDeclarationList(owns);
68
+ const read = parseDeclarationList(reads);
69
+ const malformed = [...own.malformed, ...read.malformed];
70
+ const keyOf = (anchor) => `${anchor.path}\0${anchor.symbol}`;
71
+ const wanted = [...new Map([...own.anchors, ...read.anchors].map((anchor) => [keyOf(anchor), anchor])).values()];
72
+ const declaration = { written: false, resolved: [], unresolved: [], malformed };
73
+ if (malformed.length > 0) return { row: null, declaration };
74
+ // `alsoResolve`: other tasks' anchors, answered by the same Resolve call (a5 compares ranges); a miss there is not this task's refusal.
75
+ const wantedKeys = new Set(wanted.map(keyOf));
76
+ const extra = [...new Map(alsoResolve.filter((anchor) => !wantedKeys.has(keyOf(anchor))).map((anchor) => [keyOf(anchor), anchor])).values()];
77
+ let ranges = [];
78
+ if (wanted.length > 0 && !observable) {
79
+ declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'no_code_tree'));
80
+ return { row: null, declaration };
81
+ }
82
+ if (wanted.length + extra.length > 0 && observable) {
83
+ let answer;
84
+ try { answer = await resolveOnce(root, [...wanted, ...extra]); } catch (error) {
85
+ if (wanted.length === 0) return buildRow({ own, read, writes, declaration, ranges });
86
+ declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'resolve_unavailable'));
87
+ declaration.resolve_error = error?.code ?? error?.message ?? 'resolve_failed';
88
+ return { row: null, declaration };
89
+ }
90
+ const mine = answer.unresolved.filter((anchor) => wantedKeys.has(keyOf(anchor)));
91
+ declaration.unresolved = mine.map((anchor) => unresolvedEntry(
92
+ anchor, anchor.reason,
93
+ anchor.nearest.map(({ qualified }) => qualified),
94
+ anchor.elsewhere.map(({ path: where, qualified }) => `${where}#${qualified}`),
95
+ ));
96
+ ranges = answer.resolved;
97
+ declaration.resolved = answer.resolved.filter(({ path: where, symbol }) => wantedKeys.has(`${where}\0${symbol}`))
98
+ .map(({ path: where, symbol, kind, start_line: start, end_line: end }) => ({
99
+ path: where, symbol, kind, start_line: start, end_line: end,
100
+ }));
101
+ if (declaration.unresolved.length > 0) return { row: null, declaration };
102
+ }
103
+ return buildRow({ own, read, writes, declaration, ranges });
104
+ }
105
+
106
+ function buildRow({ own, read, writes, declaration, ranges }) {
107
+ const concern = byWithin(own.anchors);
108
+ const readAnchors = byWithin(read.anchors);
109
+ const row = {
110
+ owns: sortedUnique([...own.paths, ...concern.map(({ within }) => within)]),
111
+ reads: sortedUnique([...read.paths, ...readAnchors.map(({ within }) => within)]),
112
+ writes: items(writes),
113
+ ...(concern.length > 0 ? { concern_anchors: concern } : {}),
114
+ ...(readAnchors.length > 0 ? { read_anchors: readAnchors } : {}),
115
+ };
116
+ declaration.written = true;
117
+ return { row, declaration, ranges };
118
+ }
119
+
120
+ /**
121
+ * Fallback without seeds (ADR 0204 §1): identifiers in the title and design memo that name graph symbols are proposed in the
122
+ * result and never recorded; the AI that adds the task decides. Needs an existing index and a code tree; any failure = no proposal.
123
+ */
124
+ export async function proposeFromText({ root, observable, title, memo }) {
125
+ if (!observable || !existsSync(path.join(root, '.lattice/sensor/sensor.db'))) return null;
126
+ // Resolve's `snake` leaves `qualified: undefined` on a definition; a result is canonical JSON, so drop undefined here.
127
+ try { return JSON.parse(JSON.stringify(await proposeSymbols({ root, title, memo }))); } catch { return null; }
128
+ }
129
+
130
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
131
+ const isPathList = (list) => list === undefined || (Array.isArray(list) && list.every((entry) => typeof entry === 'string' && entry.trim() !== ''));
132
+
133
+ /**
134
+ * Plan input v6 (ADR 0204 §6): `tasks[].touches {owns, reads}` is read here and goes to the witness set only.
135
+ * Returns the input as v5 without `touches`, so the stored plan and its digest are the v5 ones, plus the claims to declare
136
+ * (`{task_id, owns[], reads[]}`; a task whose lists are both empty claims nothing and is left out). `pointer` prefixes a refusal.
137
+ */
138
+ export function splitTouches(input, pointer = '') {
139
+ if (input?.schema !== 'lattice.plan_create_input.v6' || !Array.isArray(input.tasks)) return { input, touches: [] };
140
+ const touches = [];
141
+ const tasks = input.tasks.map((task, index) => {
142
+ if (!isRecord(task) || !('touches' in task)) return task;
143
+ const { touches: claim, ...rest } = task;
144
+ if (!isRecord(claim) || Object.keys(claim).some((key) => key !== 'owns' && key !== 'reads')
145
+ || !isPathList(claim.owns) || !isPathList(claim.reads)) {
146
+ throw new TodoStoreError('INPUT_INVALID', 'plan_create_touches_invalid', undefined, {
147
+ pointer: `${pointer}/tasks/${index}/touches`, expected: { owns: 'string[] of path or path#function', reads: 'string[] of path or path#function' },
148
+ actual: claim, next_action: 'Write touches as {"owns": ["src/a.mjs#foo"], "reads": ["src/b.mjs"]}; both lists are optional.',
149
+ });
150
+ }
151
+ const { owns = [], reads = [] } = claim;
152
+ if (owns.length + reads.length > 0) touches.push({ task_id: rest.task_id, owns, reads });
153
+ return rest;
154
+ });
155
+ return { input: { ...input, schema: 'lattice.plan_create_input.v5', tasks }, touches };
156
+ }
157
+
158
+ /**
159
+ * The line ranges of every function the witness rows declare (`resolved` of one Resolve call), for the compile (a5b).
160
+ * No anchors → no call. Any failure → `[]`: the compile then reads every declared function as a whole-file claim, as before.
161
+ */
162
+ export async function resolveDeclaredRanges({ root, anchors }) {
163
+ if (anchors.length === 0) return [];
164
+ try { return (await resolveOnce(root, anchors)).resolved; } catch { return []; }
165
+ }
@@ -0,0 +1,234 @@
1
+ // ADR 0205 §3-§6 (b5): `todo function-split verify|decline`, the not-split reorganization, and the gate and rewrite of `todo done S`.
2
+ // todo-cli passes the pieces that live in it (`deps.declareRow`, `deps.retire`); nothing here touches the sensor or git except
3
+ // through Neve's `verifyFunctionSplit`.
4
+
5
+ import { resolveTodoActor } from './todo-authoring-input.mjs';
6
+ import { verifyFunctionSplit } from './function-split-verify.mjs';
7
+ import { measureWaveCount } from './seam-verification.mjs';
8
+ import { parseAnchor } from './sensor-resolve.mjs';
9
+ import { appendTodoNote } from './todo-note-store.mjs';
10
+ import { anchorsOf, claimsOf, judgeTask, rangeIndex } from './todo-judgment.mjs';
11
+ import { readTodoSplit, recordTodoSplit } from './todo-split-store.mjs';
12
+ import {
13
+ createTodoStoreWriter, readTodoStore, readTodoWitnessSet, TodoStoreError,
14
+ } from './todo-store.mjs';
15
+
16
+ const FINISHED = new Set(['done', 'retired']);
17
+ const CONDITIONS = ['behaviour', 'tests', 'fresh', 'overlap', 'parallel'];
18
+ const refuse = (reason, detail) => new TodoStoreError('TODO_TRANSITION_REFUSED', reason, undefined, detail);
19
+ // A record detail is bounded (2 KiB) by the Store contract; a longer cause is cut here, the full one is in the verify result.
20
+ const clip = (text) => (Buffer.byteLength(text, 'utf8') <= 2_000 ? text : `${Buffer.from(text, 'utf8').subarray(0, 1_990).toString('utf8')}...`);
21
+
22
+ /** `--map U=src/a.js#f,T=src/b.js#g` → `[{task_id, path, symbol}]` sorted by task id; members only, one entry each. */
23
+ export function parseSplitMap(text, members) {
24
+ const entries = [];
25
+ for (const item of String(text).split(',').map((part) => part.trim()).filter(Boolean)) {
26
+ const at = item.indexOf('=');
27
+ const anchor = at < 0 ? null : parseAnchor(item.slice(at + 1));
28
+ const taskId = at < 0 ? '' : item.slice(0, at);
29
+ if (anchor === null || !members.includes(taskId) || entries.some((entry) => entry.task_id === taskId)) {
30
+ throw new TodoStoreError('INPUT_INVALID', 'function_split_map_invalid', undefined, {
31
+ pointer: '--map', entry: item, members,
32
+ next_action: `--map takes one <task>=<path>#<function> per member of the split (${members.join(', ')}), comma separated.`,
33
+ });
34
+ }
35
+ entries.push({ task_id: taskId, path: anchor.path, symbol: anchor.symbol });
36
+ }
37
+ if (entries.length === 0) {
38
+ throw new TodoStoreError('INPUT_INVALID', 'function_split_map_invalid', undefined, { pointer: '--map', members,
39
+ next_action: '--map needs at least one entry; to make no cut run `lattice todo function-split decline`.' });
40
+ }
41
+ return entries.sort((left, right) => (left.task_id < right.task_id ? -1 : 1));
42
+ }
43
+
44
+ /** The split task S, its mark and the plan it lives in; refuses when it is not an unfinished split task. */
45
+ function splitTask(store, planKey, taskId) {
46
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
47
+ const task = member?.plan.tasks.find(({ task_id: id }) => id === taskId);
48
+ const status = member?.tasks.find(({ task_id: id }) => id === taskId)?.status;
49
+ if (task === undefined) throw new TodoStoreError('TASK_NOT_FOUND', 'task_not_found', undefined, { requested_task_id: taskId });
50
+ if (!task.function_split) {
51
+ throw refuse('not_a_split_task', { plan_key: planKey, task_id: taskId, next_action: `${planKey}/${taskId} is not a function-split task (\`lattice todo status --json\` shows them).` });
52
+ }
53
+ return { member, task, mark: task.function_split, status };
54
+ }
55
+
56
+ /** `row` with its write anchor on `from` replaced by `to`; null when it has none (already moved, or never on it). */
57
+ export function moveAnchor(row, from, to) {
58
+ const group = row.concern_anchors?.find(({ within }) => within.target === from.path);
59
+ if (group === undefined || !group.symbols.includes(from.symbol)) return null;
60
+ const groups = (row.concern_anchors ?? []).map((entry) => (entry === group
61
+ ? { ...entry, symbols: entry.symbols.filter((symbol) => symbol !== from.symbol) } : entry));
62
+ const target = groups.find(({ within }) => within.target === to.path);
63
+ const moved = target === undefined
64
+ ? [...groups, { within: { kind: 'path', target: to.path }, symbols: [to.symbol] }]
65
+ : groups.map((entry) => (entry === target ? { ...entry, symbols: [...new Set([...entry.symbols, to.symbol])].sort() } : entry));
66
+ const concern = moved.filter(({ symbols }) => symbols.length > 0);
67
+ const kept = new Set(concern.map(({ within }) => within.target));
68
+ return { ...row,
69
+ concern_anchors: concern,
70
+ // a file left with no anchor must not become a whole-file claim
71
+ owns: [...row.owns.filter(({ target: where }) => where !== from.path || kept.has(where)),
72
+ ...(row.owns.some(({ target: where }) => where === to.path) ? [] : [{ kind: 'path', target: to.path }])] };
73
+ }
74
+
75
+ /** The `--owns/--reads/--writes` flags that declare `row` again (`declareTaskRow` takes flags). */
76
+ // shortcut: `creates` and `unknowns` of the old row are not expressible as flags and are dropped; add them if a split task ever needs them.
77
+ export function flagsOf(row) {
78
+ const tokens = (paths, anchors) => paths.flatMap((target) => {
79
+ const symbols = anchors?.find(({ within }) => within.target === target)?.symbols ?? [];
80
+ return symbols.length > 0 ? symbols.map((symbol) => `${target}#${symbol}`) : [target];
81
+ });
82
+ const owned = new Set(row.owns.map(({ target }) => target));
83
+ return { owns: tokens(row.owns.map(({ target }) => target), row.concern_anchors), reads: tokens(row.reads, row.read_anchors),
84
+ writes: row.writes.filter((target) => !owned.has(target)) };
85
+ }
86
+
87
+ /** Overlap and parallel (ADR 0205 §4) over the mapped members, from Neve's ranges at the commit. */
88
+ function judgeMapped({ rows, lanes, ranges }) {
89
+ const ids = Object.keys(rows).sort();
90
+ const index = rangeIndex([...ranges.reduce((merged, row) => {
91
+ const key = `${row.path}\0${row.symbol}`;
92
+ const known = merged.get(key);
93
+ merged.set(key, known === undefined ? { ...row } : { ...known, start_line: Math.min(known.start_line, row.start_line), end_line: Math.max(known.end_line, row.end_line) });
94
+ return merged;
95
+ }, new Map()).values()]);
96
+ const pairs = ids.flatMap((left, at) => ids.slice(at + 1).map((right) => [left, right])).filter(([left, right]) => lanes.get(left) !== lanes.get(right));
97
+ const still = (only) => pairs.filter(([left, right]) => judgeTask({ taskId: left, rows: { [left]: rows[left], [right]: rows[right] }, ranges: index, only })
98
+ .relations.some(({ task_a: a, task_b: b }) => (a === left && b === right) || (a === right && b === left)));
99
+ const writing = still('ww');
100
+ const anyConflict = still(null);
101
+ // one executor per member: the waves then count only what the conflicts force (a single executor serializes everything)
102
+ const before = measureWaveCount({ taskIds: ids, conflictPairs: pairs, executors: ids.length });
103
+ const after = measureWaveCount({ taskIds: ids, conflictPairs: anyConflict, executors: ids.length });
104
+ return {
105
+ overlap: { passed: writing.length === 0, detail: writing.length === 0 ? 'ok' : clip(`still write the same lines: ${writing.map((pair) => pair.join('/')).join(', ')}`) },
106
+ parallel: before.waves !== null && after.waves !== null && after.waves < before.waves
107
+ ? { passed: true, detail: `waves ${before.waves} -> ${after.waves}` }
108
+ : { passed: false, detail: clip(`waves ${before.waves ?? before.reason} -> ${after.waves ?? after.reason}: not lower`) },
109
+ };
110
+ }
111
+
112
+ /**
113
+ * `todo function-split verify` (ADR 0205 §3-§4): Neve's checks on the worker's commit, then overlap and parallel, recorded on S.
114
+ * Input errors refuse and reorganize nothing. A rejected outcome is written first and then reorganized as not split.
115
+ */
116
+ export async function verifySplit({ repoRoot, env, planKey, taskId, commit, base, mapText, deps }) {
117
+ const { member, mark, status } = splitTask(await readTodoStore({ repoRoot }), planKey, taskId);
118
+ if (FINISHED.has(status)) throw refuse('split_task_finished', { plan_key: planKey, task_id: taskId, status });
119
+ const map = parseSplitMap(mapText, mark.members);
120
+ const witness = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
121
+ const rowOf = (id) => witness?.plan_key === planKey ? witness.manual_witness[id] : undefined;
122
+ const anchors = map.flatMap(({ task_id: id }) => (rowOf(id) === undefined ? [] : anchorsOf(claimsOf(rowOf(id))).map((anchor) => ({ task_id: id, ...anchor }))));
123
+ const target = { path: mark.path, symbol: mark.symbol };
124
+ const answer = await verifyFunctionSplit({ repoRoot, commit, ...(base === undefined ? {} : { base }), target, map, anchors });
125
+ if (answer.error !== undefined) {
126
+ throw new TodoStoreError('INPUT_INVALID', `function_split_${answer.error.code}`, undefined, { ...answer.error, pointer: '--commit' });
127
+ }
128
+ const rows = {};
129
+ for (const entry of map) {
130
+ const row = rowOf(entry.task_id);
131
+ if (row !== undefined) rows[entry.task_id] = moveAnchor(row, target, entry) ?? row;
132
+ }
133
+ const lanes = new Map(member.plan.tasks.map(({ task_id: id, lane }) => [id, lane]));
134
+ const judged = judgeMapped({ rows, lanes, ranges: answer.ranges });
135
+ const conditions = {
136
+ behaviour: { passed: answer.behaviour.passed, detail: clip(answer.behaviour.detail) },
137
+ tests: { passed: answer.tests.passed, detail: clip(answer.tests.detail) },
138
+ fresh: { passed: answer.fresh.passed, detail: answer.fresh.passed ? 'ok' : clip(answer.fresh.detail ?? JSON.stringify(answer.fresh.unresolved)) },
139
+ ...judged,
140
+ };
141
+ const outcome = CONDITIONS.every((name) => conditions[name].passed) ? 'accepted' : 'rejected';
142
+ await recordTodoSplit({ repoRoot, planKey, taskId, writer: createTodoStoreWriter({ caller: 'todo-splits' }), record: {
143
+ map, commit: answer.commit, base: answer.base, outcome, conditions, recorded_at: new Date().toISOString(), actor: resolveTodoActor(env) } });
144
+ const failed = CONDITIONS.filter((name) => !conditions[name].passed);
145
+ const result = { schema: 'lattice.todo_function_split_verify_result.v1', project_id: member.plan.project_id, plan_key: planKey,
146
+ task_id: taskId, outcome, commit: answer.commit, base: answer.base, conditions, tests_ran: answer.tests.ran, target: answer.target };
147
+ if (outcome === 'accepted') {
148
+ return { ...result, next_action: `open the PR with \`[skip ci]\` in the commit message, merge it, then \`lattice todo done --plan ${planKey} --task ${taskId} --message <what you merged>\`.` };
149
+ }
150
+ const reason = `verify rejected (${failed.join(', ')}): ${failed.map((name) => `${name}: ${conditions[name].detail}`).join(' | ')}`;
151
+ return { ...result, reorganized: await reorganizeNotSplit({ repoRoot, env, planKey, taskId, reason: clip(reason), deps }),
152
+ next_action: 'the split is withdrawn; the later tasks now wait for the one that started first.' };
153
+ }
154
+
155
+ /** Does `from` already reach `to` through the plan's hard dependencies? */
156
+ const reaches = (plan, from, to) => {
157
+ const seen = new Set();
158
+ const stack = [from];
159
+ while (stack.length > 0) {
160
+ const current = stack.pop();
161
+ if (current === to) return true;
162
+ if (seen.has(current)) continue;
163
+ seen.add(current);
164
+ for (const edge of plan.hard_dependencies) if (edge.from.task_id === current) stack.push(edge.to.task_id);
165
+ }
166
+ return false;
167
+ };
168
+
169
+ /**
170
+ * Not split (D6, D7): the member in progress that started first becomes the predecessor of the unfinished members that have
171
+ * not started, each member gets a note with the reason, then S is retired. The edges go first, so a crash leaves S open and
172
+ * the same command finishes the job; with no member in progress there is no edge and the next start detects again.
173
+ */
174
+ export async function reorganizeNotSplit({ repoRoot, env, planKey, taskId, reason, deps }) {
175
+ const store = await readTodoStore({ repoRoot });
176
+ const { member, mark, status } = splitTask(store, planKey, taskId);
177
+ if (status === 'retired') return deps.retire({ repoRoot, env, planKey, taskId, reason });
178
+ if (status === 'done') throw refuse('split_task_finished', { plan_key: planKey, task_id: taskId, status });
179
+ const state = new Map(member.tasks.map((task) => [task.task_id, task]));
180
+ const open = mark.members.filter((id) => state.has(id) && !FINISHED.has(state.get(id).status));
181
+ const lead = open.filter((id) => state.get(id).status === 'in-progress')
182
+ .sort((left, right) => (state.get(left).started_at < state.get(right).started_at ? -1 : 1))[0];
183
+ const edges = lead === undefined ? [] : open.filter((id) => state.get(id).status !== 'in-progress' && !reaches(member.plan, lead, id))
184
+ .map((id) => ({ from: lead, to: id }));
185
+ let planVersion = member.plan.plan_version;
186
+ if (edges.length > 0) {
187
+ const { applyPlanRevision, desiredFromPlan } = await import('./plan-revise.mjs');
188
+ const desired = desiredFromPlan(member.plan, { env });
189
+ const ref = (id) => ({ project_id: member.plan.project_id, plan_key: planKey, task_id: id });
190
+ desired.hard_dependencies = [...desired.hard_dependencies, ...edges.map(({ from, to }) => ({ from: ref(from), to: ref(to) }))];
191
+ planVersion = (await applyPlanRevision({ repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired } })).plan_version;
192
+ }
193
+ const actor = resolveTodoActor(env);
194
+ for (const id of open) {
195
+ await appendTodoNote({ repoRoot, projectId: member.plan.project_id, planKey, planVersion, taskId: id, actor,
196
+ recordedAt: new Date().toISOString(), supersedes: null, eligibleSupersedes: [],
197
+ body: `function split ${taskId} on ${mark.path}#${mark.symbol} was not made: ${reason}${lead !== undefined && id !== lead && state.get(id).status !== 'in-progress' ? `; ${id} now waits for ${lead}` : ''}` });
198
+ }
199
+ const retired = await deps.retire({ repoRoot, env, planKey, taskId, reason });
200
+ return { schema: 'lattice.todo_function_split_decline_result.v1', project_id: member.plan.project_id, plan_key: planKey,
201
+ task_id: taskId, outcome: 'declined', reason, predecessor_edges: edges, retired: { kind: retired.kind, status: retired.status } };
202
+ }
203
+
204
+ /**
205
+ * The gate and the rewrite of `todo done S` (ADR 0205 §5): needs an accepted record, then each unfinished mapped member's
206
+ * write anchor on F becomes its mapped function through the ADR 0204 declaration path (resolved at the repository's HEAD, so
207
+ * relations are judged again and close where the overlap is gone). A row without the anchor is skipped: the rewrite is idempotent.
208
+ */
209
+ export async function splitDoneGate({ repoRoot, planKey, taskId, deps }) {
210
+ // shortcut: one more Store read on every `todo done` to learn whether the task is a split task; read the mark from the done's own read if that cost shows.
211
+ const member = (await readTodoStore({ repoRoot })).members.find(({ descriptor }) => descriptor.plan_key === planKey);
212
+ const mark = member?.plan.tasks.find(({ task_id: id }) => id === taskId)?.function_split;
213
+ if (!mark) return;
214
+ const record = await readTodoSplit({ repoRoot, planKey, taskId });
215
+ if (record === null || record.outcome !== 'accepted') {
216
+ throw refuse('split_not_accepted', { plan_key: planKey, task_id: taskId, outcome: record?.outcome ?? null,
217
+ next_action: `\`lattice todo function-split verify --plan ${planKey} --task ${taskId} --commit <sha> --map <task>=<path#function>,...\`, or \`lattice todo function-split decline --plan ${planKey} --task ${taskId} --reason <text>\`.` });
218
+ }
219
+ const witness = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
220
+ const status = new Map(member.tasks.map((task) => [task.task_id, task.status]));
221
+ const target = { path: mark.path, symbol: mark.symbol };
222
+ const unresolved = [];
223
+ for (const entry of record.map) {
224
+ const row = witness?.plan_key === planKey ? witness.manual_witness[entry.task_id] : undefined;
225
+ const moved = row === undefined || FINISHED.has(status.get(entry.task_id)) ? null : moveAnchor(row, target, entry);
226
+ if (moved === null) continue;
227
+ const written = await deps.declareRow({ taskId: entry.task_id, flags: flagsOf(moved) });
228
+ if (written.scaffolded === null) unresolved.push({ task_id: entry.task_id, path: entry.path, symbol: entry.symbol, ...written.declaration });
229
+ }
230
+ if (unresolved.length > 0) {
231
+ throw refuse('split_map_unresolved', { plan_key: planKey, task_id: taskId, unresolved,
232
+ next_action: 'The new functions are not in this repository yet: merge the split PR, sync the repository (`lattice chart repo sync`), then run `todo done` again.' });
233
+ }
234
+ }
@@ -1,4 +1,4 @@
1
- import { DOCUMENT_STATUS, SEVERABILITY_LABEL, escapeHtmlAttribute, escapeHtmlText, foldIndex, planActivity, presentationLookup, refKey, renderConnectionArea, renderPhaseProgress, renderRelationList, renderSeamProposalOverview, renderTaskIndex, statusMarkup, taskReference } from './todo-gantt-html-shared.mjs';
1
+ import { DOCUMENT_STATUS, SEVERABILITY_LABEL, escapeHtmlAttribute, escapeHtmlText, foldIndex, planActivity, presentationLookup, refKey, renderConnectionArea, renderPhaseProgress, renderRelationList, renderSeamProposalOverview, renderSplitLabel, renderTaskIndex, statusMarkup, taskReference } from './todo-gantt-html-shared.mjs';
2
2
  import {
3
3
  hasTodoStructurePresentation,
4
4
  renderTodoStructureNoscript,
@@ -254,7 +254,7 @@ export function renderRightPane(
254
254
  : '<p class="fold-note">完走済みのため図には描いていません。図に出すには動的dashboardを <code>lattice todo gantt serve --port &lt;port&gt; --scope all</code> で起動してください。</p>';
255
255
  const workLog = notesEnabled ? renderNoteContext(section.noteContext, hostDisplayNames) : '';
256
256
  const designMemo = renderDesignMemo(section.task) + renderDoneCondition(section.task);
257
- return `<article class="task-detail" data-detail-key="${escapeHtmlAttribute(key)}" hidden><header><span class="detail-status status-${escapeHtmlAttribute(section.state.status)}">${escapeHtmlText(status.mark)} ${escapeHtmlText(status.label)}</span><span class="detail-reference">${escapeHtmlText(taskReference(section, lookup))}</span></header><h1>${escapeHtmlText(section.task.title)}</h1><p class="detail-category"><strong>カテゴリ:</strong> ${escapeHtmlText(category)}</p>${categoryDescription}<p><strong>正規ID:</strong> <code>${escapeHtmlText(`${section.ref.plan_key}/${section.task.task_id}`)}</code></p>${blockedReason}${renderConnectionArea(section.connections)}${readiness}${independenceNote}${foldedNote}${designMemo}<section><h2>前提工程</h2>${renderRelationList(incoming.get(key), sectionByKey, lookup, '登録済みの前提工程はありません。', folds)}</section><section><h2>後続工程</h2>${renderRelationList(outgoing.get(key), sectionByKey, lookup, '登録済みの後続工程はありません。', folds)}</section>${workLog}<p class="anchor-status">${escapeHtmlText(anchorText)}</p><details class="task-diagnostics"><summary>開発者向け診断</summary><dl><dt>canonical ref</dt><dd><code>${escapeHtmlText(`${section.ref.project_id}/${section.ref.plan_key}/${section.task.task_id}`)}</code></dd><dt>anchor</dt><dd>${escapeHtmlText(section.anchorOutcome.anchored ? 'verified' : section.anchorOutcome.reason)}</dd></dl></details></article>`;
257
+ return `<article class="task-detail" data-detail-key="${escapeHtmlAttribute(key)}" hidden><header><span class="detail-status status-${escapeHtmlAttribute(section.state.status)}">${escapeHtmlText(status.mark)} ${escapeHtmlText(status.label)}</span>${renderSplitLabel(section.splitLabel)}<span class="detail-reference">${escapeHtmlText(taskReference(section, lookup))}</span></header><h1>${escapeHtmlText(section.task.title)}</h1><p class="detail-category"><strong>カテゴリ:</strong> ${escapeHtmlText(category)}</p>${categoryDescription}<p><strong>正規ID:</strong> <code>${escapeHtmlText(`${section.ref.plan_key}/${section.task.task_id}`)}</code></p>${blockedReason}${renderConnectionArea(section.connections)}${readiness}${independenceNote}${foldedNote}${designMemo}<section><h2>前提工程</h2>${renderRelationList(incoming.get(key), sectionByKey, lookup, '登録済みの前提工程はありません。', folds)}</section><section><h2>後続工程</h2>${renderRelationList(outgoing.get(key), sectionByKey, lookup, '登録済みの後続工程はありません。', folds)}</section>${workLog}<p class="anchor-status">${escapeHtmlText(anchorText)}</p><details class="task-diagnostics"><summary>開発者向け診断</summary><dl><dt>canonical ref</dt><dd><code>${escapeHtmlText(`${section.ref.project_id}/${section.ref.plan_key}/${section.task.task_id}`)}</code></dd><dt>anchor</dt><dd>${escapeHtmlText(section.anchorOutcome.anchored ? 'verified' : section.anchorOutcome.reason)}</dd></dl></details></article>`;
258
258
  }).join('');
259
259
  const taskIndex = renderTaskIndex(sections, lookup, folds, planActivity(readModel));
260
260
  const structureButton = hasTodoStructurePresentation(structurePresentation)
@@ -73,6 +73,9 @@ export function renderConnectionChips(connections = []) {
73
73
  return `${open === 0 ? '' : `<span class="connection-chip">他条件に接続 ${open}</span>`}${priority === 0 ? '' : '<span class="connection-chip">優先接続</span>'}`;
74
74
  }
75
75
 
76
+ /** ADR 0205 §7: the 分割待ち / 関数分割 chip, drawn beside the status (which it never replaces). */
77
+ export const renderSplitLabel = (label) => (label === null || label === undefined ? '' : `<span class="connection-chip">${escapeHtmlText(label)}</span>`);
78
+
76
79
  export function renderTaskIndexEntry(section, lookup) {
77
80
  const key = refKey(section.ref);
78
81
  const status = DOCUMENT_STATUS[section.state.status] ?? { mark: '?', label: '状態不明' };
@@ -81,7 +84,7 @@ export function renderTaskIndexEntry(section, lookup) {
81
84
  // A ToDo the diagram does not draw keeps its row here — the index is the
82
85
  // complete list — and it selects its own detail, which exists either way.
83
86
  const selectKey = key;
84
- return `<li><button type="button" data-select-node-key="${escapeHtmlAttribute(selectKey)}"><span class="task-index-status status-${escapeHtmlAttribute(section.state.status)}" role="img" aria-label="${escapeHtmlAttribute(status.label)}">${escapeHtmlText(status.mark)}</span><span class="task-index-reference">${escapeHtmlText(taskReference(section, lookup))}</span><strong>${escapeHtmlText(section.task.title)}</strong>${blockedReason}${renderConnectionChips(section.connections)}</button></li>`;
87
+ return `<li><button type="button" data-select-node-key="${escapeHtmlAttribute(selectKey)}"><span class="task-index-status status-${escapeHtmlAttribute(section.state.status)}" role="img" aria-label="${escapeHtmlAttribute(status.label)}">${escapeHtmlText(status.mark)}</span>${renderSplitLabel(section.splitLabel)}<span class="task-index-reference">${escapeHtmlText(taskReference(section, lookup))}</span><strong>${escapeHtmlText(section.task.title)}</strong>${blockedReason}${renderConnectionChips(section.connections)}</button></li>`;
85
88
  }
86
89
 
87
90
  /** plan_key -> 最終活動時刻。journalの末尾eventが、そのplanが最後に動いた時点。 */
@@ -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
  }