@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
package/src/todo-cli.mjs CHANGED
@@ -201,6 +201,14 @@ import {
201
201
  readTodoPlanNotesForStatus,
202
202
  } from './todo-note-store.mjs';
203
203
  import { dependencyNoteBody, todoAddNoteBody } from './todo-revision-note.mjs';
204
+ import { buildDeclarationRow, declaredPaths, proposeFromText, resolveDeclaredRanges } from './todo-declaration.mjs';
205
+ import { anchorsOf, claimsOf, judgeTask, neededAnchors, rangeIndex, relationView } from './todo-judgment.mjs';
206
+ import { readTodoRelationSummary, readTodoTaskRelations, transactTodoRelations } from './todo-relation-store.mjs';
207
+ import { planSplitHold, splitGuide } from './todo-split-start.mjs';
208
+ import { cutCost } from './function-split-verify.mjs';
209
+ import { reorganizeNotSplit, splitDoneGate, verifySplit } from './todo-function-split.mjs';
210
+ import { splitLabels, splitLabelsOf } from './todo-split-labels.mjs';
211
+ import { readTodoSplit } from './todo-split-store.mjs';
204
212
  import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
205
213
  import { commitTodoStoreMutation } from './todo-store-git-transaction.mjs';
206
214
  import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
@@ -302,7 +310,7 @@ const TODO_COMMAND_NAMES = Object.freeze([
302
310
  'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
303
311
  'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
304
312
  'unblock', 'retire', 'done', 'reopen', 'split', 'revise', 'revise-phase', 'revise-set',
305
- 'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers', 'compact',
313
+ 'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers', 'compact', 'function-split',
306
314
  ]);
307
315
 
308
316
  function typedArgumentFailure(stderr, code, message, detail, context = {}) {
@@ -343,7 +351,7 @@ const TODO_FLAG_SPECS = Object.freeze({
343
351
  reopen: Object.freeze({ known: ['plan', 'task', 'reason', 'override-reason'], required: ['plan', 'task', 'reason'] }),
344
352
  'dependency connect': DEPENDENCY_FLAG_SPEC,
345
353
  add: Object.freeze({
346
- known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason'],
354
+ known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason', 'owns', 'reads'],
347
355
  required: ['plan', 'task', 'title'],
348
356
  }),
349
357
  'dependency disconnect': DEPENDENCY_FLAG_SPEC,
@@ -356,6 +364,8 @@ const TODO_FLAG_SPECS = Object.freeze({
356
364
  'phase review': PHASE_REASON_FLAG_SPEC,
357
365
  'phase close-unaudited': PHASE_REASON_FLAG_SPEC,
358
366
  split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
367
+ 'function-split verify': Object.freeze({ known: ['plan', 'task', 'commit', 'base', 'map'], required: ['plan', 'task', 'commit', 'map'] }),
368
+ 'function-split decline': REASON_FLAG_SPEC,
359
369
  note: NOTE_FLAG_SPEC,
360
370
  // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
361
371
  'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message'], required: ['plan', 'phase'] }),
@@ -387,7 +397,7 @@ const TODO_SUBCOMMANDS = Object.freeze({
387
397
  connect: { names: ['condition', 'priority'], example: 'priority' },
388
398
  phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
389
399
  });
390
- const GROUP_COMMANDS = ['dependency', 'predecessor', 'connect', 'phase', 'independence', 'note', 'structure'];
400
+ const GROUP_COMMANDS = ['dependency', 'predecessor', 'connect', 'phase', 'independence', 'note', 'structure', 'function-split'];
391
401
  const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
392
402
  // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
393
403
  const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
@@ -560,7 +570,7 @@ function supportsAtomicStoreCommit(argv) {
560
570
  if (command === 'snapshot') return argv[1] === '--rebuild';
561
571
  if (command === 'migrate') return !argv.includes('--dry-run') && !argv.includes('--schema');
562
572
  if (['revise', 'split', 'revise-set', 'revise-phase', 'start', 'retract', 'block',
563
- 'unblock', 'retire', 'done', 'reopen', 'add'].includes(command)) return true;
573
+ 'unblock', 'retire', 'done', 'reopen', 'add', 'function-split'].includes(command)) return true;
564
574
  if (command === 'phase') return argv[1] !== 'status';
565
575
  return false;
566
576
  }
@@ -1275,6 +1285,7 @@ async function displayRead(repoRoot, env) {
1275
1285
  const externalTasks = display.store ? (await readTodoExternalTasks(display.store, env)).external_tasks : [];
1276
1286
  return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1277
1287
  trees: display.store ? projectTodoTrees(display.store) : [],
1288
+ ...(display.store && splitLabels(display.store).length > 0 ? { labels: splitLabels(display.store) } : {}),
1278
1289
  connections: display.store ? await displayConnections(repoRoot, { ...display.store, external_tasks: externalTasks }) : [] };
1279
1290
  }
1280
1291
 
@@ -1345,9 +1356,17 @@ async function startTask({
1345
1356
  };
1346
1357
  }
1347
1358
  // 助言はjournalへ書く前に確定させる。助言はstartを止めない(u03 B1–B6)。
1348
- const advisory = await startAdvisory({
1359
+ const startAdvice = await startAdvisory({
1349
1360
  repoRoot, store, projection, planKey, taskId: resolvedTaskId,
1350
1361
  });
1362
+ const got = await readTaskRelations({ repoRoot, planKey, taskId: resolvedTaskId });
1363
+ const relations = relationsFrom(resolvedTaskId, got);
1364
+ const advisory = relations === null ? startAdvice : { ...startAdvice, relations };
1365
+ // ADR 0205 §1: a held task never reaches the gates; --override-reason (witness or enforced) starts it as today.
1366
+ if (readyTask !== undefined) {
1367
+ const held = await holdForSplit({ repoRoot, env, member, planKey, taskId: resolvedTaskId, read: got.read ?? null, overrideReason });
1368
+ if (held !== null) return held;
1369
+ }
1351
1370
  if (member.coordination?.mode === 'enforced' && !(await noCodeTask({ repoRoot, member, taskId: resolvedTaskId }))) {
1352
1371
  enforcedStartGate({ advisory, planKey, taskId: resolvedTaskId, overrideReason });
1353
1372
  }
@@ -1365,9 +1384,90 @@ async function startTask({
1365
1384
  process.emitWarning(`todo start: backchain not used (${error.detail?.reason ?? error.message}: ${error.detail?.pointer ?? ''})`,
1366
1385
  { code: 'LATTICE_START_BACKCHAIN_UNUSABLE' });
1367
1386
  }
1368
- return mutate({ repoRoot, env, planKey, taskId: resolvedTaskId, kind: 'start',
1387
+ const started = await mutate({ repoRoot, env, planKey, taskId: resolvedTaskId, kind: 'start',
1369
1388
  payload: { override_reason: overrideReason }, advisory, noteContext,
1370
1389
  structureContext, featureContext, externalTasks: store.external_tasks ?? [] });
1390
+ return withSplitGuide({ repoRoot, member, planKey, taskId: resolvedTaskId, started });
1391
+ }
1392
+
1393
+ /**
1394
+ * ADR 0205 §1 (b4): `todo start T` writes a function an in-progress task of another lane writes → add S (or join the open S on
1395
+ * that function) in one revision and keep T pending. null = start as today: no such overlap, no lane, override, a conversation
1396
+ * plan, or a plan a light revision cannot take (an unknown state is not dangerous: the warning names it, nothing is refused).
1397
+ */
1398
+ async function holdForSplit({ repoRoot, env, member, planKey, taskId, read, overrideReason }) {
1399
+ if (overrideReason !== null || member.coordination?.mode === 'conversation') return null;
1400
+ const hold = planSplitHold({ member, taskId, read });
1401
+ if (hold === null) return null;
1402
+ const { applyPlanRevision, desiredFromPlan, lightRevisionExpresses } = await import('./plan-revise.mjs');
1403
+ const unsupported = (reason) => { process.emitWarning(`todo start: split not used (${reason})`, { code: 'LATTICE_START_SPLIT_UNSUPPORTED' }); return null; };
1404
+ if (!lightRevisionExpresses(member)) return unsupported('split_unsupported: the plan cannot take a light revision');
1405
+ const desired = desiredFromPlan(member.plan, { env });
1406
+ const ref = (id) => ({ project_id: member.plan.project_id, plan_key: planKey, task_id: id });
1407
+ desired.tasks = [...desired.tasks, ...hold.tasks];
1408
+ desired.hard_dependencies = [...desired.hard_dependencies, ...hold.edges.map(({ from, to }) => ({ from: ref(from), to: ref(to) }))];
1409
+ let applied;
1410
+ try {
1411
+ applied = await applyPlanRevision({ repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1412
+ notes: hold.notes, splitMarks: hold.marks });
1413
+ } catch (error) {
1414
+ if (error?.detail?.reason === 'plan_revise_split_unsupported') {
1415
+ return unsupported('split_unsupported: the plan is bound to a feature chain');
1416
+ }
1417
+ throw error;
1418
+ }
1419
+ const lanes = hold.splits.map(({ task_id: id }) => [...hold.tasks, ...member.plan.tasks].find(({ task_id: other }) => other === id)?.lane);
1420
+ const result = { schema: 'lattice.todo_start_split_result.v1', project_id: member.plan.project_id, plan_key: planKey,
1421
+ plan_version: applied.plan_version, task_id: taskId, status: 'pending', splits: hold.splits,
1422
+ next_action: `wait: ${hold.splits.map(({ task_id: id }, index) => `${id} is in lane ${lanes[index]}`).join('; ')}; the chart offers ${taskId} again when every split it waits on is done or withdrawn.`,
1423
+ result_digest: '' };
1424
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1425
+ return result;
1426
+ }
1427
+
1428
+ /** What the function-split commands need from this module: retire a task, and declare a row again (resolved at HEAD). */
1429
+ const splitDeps = (repoRoot, planKey) => ({
1430
+ retire: (options) => retireTask(options),
1431
+ declareRow: ({ taskId, flags }) => declareTaskRow({ repoRoot, planKey, taskId, flags, observable: headResolves(repoRoot) }),
1432
+ });
1433
+
1434
+ /** ADR 0205 §3: starting the split task S shows the worker its members, the size of the cut and what to do (no member rule exists). */
1435
+ async function withSplitGuide({ repoRoot, member, planKey, taskId, started }) {
1436
+ const mark = member.plan.tasks.find(({ task_id: id }) => id === taskId)?.function_split ?? null;
1437
+ if (mark === null || started.kind !== 'start') return started;
1438
+ const cost = await cutCost({ repoRoot, target: { path: mark.path, symbol: mark.symbol }, memberTaskIds: mark.members })
1439
+ .catch(() => ({ profile: null, reasons: ['cut_cost_failed'] }));
1440
+ const { result_digest: _digest, ...rest } = started;
1441
+ const result = { ...rest, function_split: { path: mark.path, symbol: mark.symbol, members: mark.members, cut_cost: cost,
1442
+ guide: splitGuide({ planKey, taskId, mark }) }, result_digest: '' };
1443
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1444
+ return result;
1445
+ }
1446
+
1447
+ /**
1448
+ * a5c/a5d: the open function-level relations of one task, for `todo start` and `todo show` (ADR 0204 §5). One call reads the
1449
+ * plan's summary and this task's own small file, never the history (ADR 0203, a4c).
1450
+ * → null when the plan has none (the field is then left out), else `{open: [relationView], plan_relation_count, unresolved_count,
1451
+ * head_sha}`; an unreadable record is named, never refused: an unknown state is not dangerous.
1452
+ */
1453
+ async function taskRelations({ repoRoot, planKey, taskId }) {
1454
+ return relationsFrom(taskId, await readTaskRelations({ repoRoot, planKey, taskId }));
1455
+ }
1456
+
1457
+ /** `{read}` (null = the plan has none) or `{unreadable}`: `todo start` keeps the raw read for the split check. */
1458
+ async function readTaskRelations({ repoRoot, planKey, taskId }) {
1459
+ try {
1460
+ return { read: await readTodoTaskRelations({ repoRoot, planKey, taskId }) };
1461
+ } catch (error) {
1462
+ return { unreadable: error?.detail?.reason ?? error?.code ?? 'relations_unreadable' };
1463
+ }
1464
+ }
1465
+
1466
+ function relationsFrom(taskId, { read = null, unreadable = null }) {
1467
+ if (unreadable !== null) return { unreadable };
1468
+ if (read === null) return null;
1469
+ return { open: read.open.map((relation) => relationView(taskId, relation)),
1470
+ plan_relation_count: read.relation_count, unresolved_count: read.unresolved_count, head_sha: read.head_sha };
1371
1471
  }
1372
1472
 
1373
1473
  /** declare-without-git: HEAD does not resolve (no commit) and the plan's witness set records this task's row. */
@@ -1396,7 +1496,9 @@ const declareCommand = (planKey, taskId) => `lattice todo independence witness d
1396
1496
  * An unreadable chart meta means no lane is marked (the gates apply).
1397
1497
  */
1398
1498
  async function noCodeTask({ repoRoot, member, taskId }) {
1399
- const lane = member.plan.tasks.find(({ task_id: id }) => id === taskId)?.lane;
1499
+ const { lane, function_split: split } = member.plan.tasks.find(({ task_id: id }) => id === taskId) ?? {};
1500
+ // ADR 0205 §3: a split task overlaps its own members by construction and carries no witness row.
1501
+ if (split) return true;
1400
1502
  return (await readTodoChartMeta({ repoRoot }).catch(() => null))?.no_code_lanes?.includes(lane) ?? false;
1401
1503
  }
1402
1504
 
@@ -1691,9 +1793,10 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1691
1793
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1692
1794
  notes: [{ task_id: taskId, body: todoAddNoteBody(taskId, reason) }],
1693
1795
  });
1796
+ const declaration = await declareOnAdd({ repoRoot, planKey, taskId, flags });
1694
1797
  const result = {
1695
- schema: 'lattice.todo_task_add_result.v1', project_id: store.project_id, plan_key: planKey,
1696
- task_id: taskId, after, before, reason, actor: desired.actor,
1798
+ schema: 'lattice.todo_task_add_result.v2', project_id: store.project_id, plan_key: planKey,
1799
+ task_id: taskId, after, before, reason, actor: desired.actor, declaration,
1697
1800
  plan_version: applied.plan_version, revision_digest: applied.revision?.revision_digest ?? null,
1698
1801
  rebound_task_ids: applied.rebound_task_ids, result_digest: '',
1699
1802
  };
@@ -1701,6 +1804,41 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1701
1804
  return result;
1702
1805
  }
1703
1806
 
1807
+ /**
1808
+ * ADR 0204: the functions the new task changes, written once now. The task is already added; nothing here can refuse the add,
1809
+ * so a failure comes back as `declaration` (`written: false`) and the same flags are given again to `witness declare`.
1810
+ * Without seeds the title and design memo are searched for names that exist in the code graph; those are proposed, never recorded.
1811
+ */
1812
+ async function declareOnAdd({ repoRoot, planKey, taskId, flags }) {
1813
+ const seeded = (value) => typeof value === 'string' || Array.isArray(value);
1814
+ if (!seeded(flags.owns) && !seeded(flags.reads)) {
1815
+ const proposed = await proposeFromText({ root: repoRoot, observable: headResolves(repoRoot), title: flags.title, memo: flags['design-memo'] });
1816
+ return { written: false, resolved: [], unresolved: [], malformed: [], proposed };
1817
+ }
1818
+ try {
1819
+ const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable: headResolves(repoRoot) });
1820
+ return declared.declaration;
1821
+ } catch (error) {
1822
+ if (!(error instanceof TodoStoreError)) throw error;
1823
+ return { written: false, resolved: [], unresolved: [], malformed: [],
1824
+ refused: { code: error.code, ...error.detail } };
1825
+ }
1826
+ }
1827
+
1828
+ /**
1829
+ * Plan create/revise input `tasks[].touches` (ADR 0204 §6): declared after the plan is written, one row per task through the same
1830
+ * path as `todo add`. A task's failure comes back under its id and never undoes the plan. → `{task_id: declaration}`, or null.
1831
+ * shortcut: one Resolve and one witness write per task; batch them when a plan routinely declares dozens of tasks.
1832
+ */
1833
+ export async function declareTouches({ repoRoot, planKey, touches }) {
1834
+ if (touches.length === 0) return null;
1835
+ const declarations = {};
1836
+ for (const { task_id: taskId, owns, reads } of touches) {
1837
+ declarations[taskId] = await declareOnAdd({ repoRoot, planKey, taskId, flags: { owns, reads } });
1838
+ }
1839
+ return declarations;
1840
+ }
1841
+
1704
1842
  const samePlanEdge = (member, fromTaskId, toTaskId) => member.plan.hard_dependencies.some((edge) => (
1705
1843
  edge.from.task_id === fromTaskId && edge.to.task_id === toTaskId));
1706
1844
 
@@ -2691,6 +2829,11 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
2691
2829
  const featureContext = await readTaskBackchainContext({
2692
2830
  repoRoot, plan: member.plan, taskId: task.task_id,
2693
2831
  });
2832
+ const relations = await taskRelations({ repoRoot, planKey, taskId: task.task_id });
2833
+ const labels = splitLabelsOf(member).filter(({ task_id: id }) => id === task.task_id).map(({ label }) => label);
2834
+ // the verify record is read by `todo show S` only (ADR 0205 §2); an unreadable one is named, never a refusal
2835
+ const splitRecord = task.function_split ? await readTodoSplit({ repoRoot, planKey, taskId: task.task_id })
2836
+ .catch((error) => ({ unreadable: error?.detail?.reason ?? error?.code ?? 'split_record_unreadable' })) : undefined;
2694
2837
  const result = {
2695
2838
  schema: featureContext === null ? 'lattice.todo_detail_result.v3' : 'lattice.todo_detail_result.v4',
2696
2839
  project_id: store.project_id,
@@ -2702,6 +2845,9 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
2702
2845
  state,
2703
2846
  prerequisites: taskPrerequisites(store, member, task.task_id),
2704
2847
  note_context: context,
2848
+ ...(relations === null ? {} : { relations }),
2849
+ ...(labels.length === 0 ? {} : { labels }),
2850
+ ...(splitRecord === undefined ? {} : { split_record: splitRecord }),
2705
2851
  ...(featureContext === null ? {} : { feature_context: featureContext }),
2706
2852
  result_digest: '',
2707
2853
  };
@@ -3494,6 +3640,10 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3494
3640
  // INDEPENDENCE_ARTIFACT_INVALIDでtyped fail」を既に区別している。ここでcatchすると
3495
3641
  // **corrupt/permission/I-Oまで「初回」へ化けて履歴が黙って切れる**(suzune の監査で実測・room [1148])。
3496
3642
  const previousArtifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
3643
+ // a5b: resolve the declared functions once so the compile judges a path declared with functions by those functions only.
3644
+ const anchors = Object.values(witnessSet.manual_witness).flatMap((row) => anchorsOf(claimsOf(row)));
3645
+ const functionRanges = anchors.length === 0 ? null
3646
+ : rangeIndex(await resolveDeclaredRanges({ root: repoRoot, anchors }));
3497
3647
  const artifact = compileTodoIndependence({
3498
3648
  witnessSet,
3499
3649
  plan: member.plan,
@@ -3501,6 +3651,7 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3501
3651
  compiledAt: new Date().toISOString(),
3502
3652
  sensorEvidence: observation.sensor_evidence,
3503
3653
  previousArtifact,
3654
+ functionRanges,
3504
3655
  });
3505
3656
  const { ref } = await writeTodoIndependenceArtifact({ repoRoot, artifact });
3506
3657
  // compile成功後にだけ、受理した宣言をruntime readerが要求するcanonical bytesで固定する。
@@ -3865,8 +4016,8 @@ async function witnessScaffold({ repoRoot, planKey, inputRef }) {
3865
4016
  return scaffoldWitnessDraft({ repoRoot, planKey, draft });
3866
4017
  }
3867
4018
 
3868
- /** The scaffold itself: fresh observation, wiring and digest for a checked draft, then the write. */
3869
- async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
4019
+ /** The fresh observation a witness set carries: the affected tests of every owned path. → `{paths, observationByPath}`. */
4020
+ async function observeWitnessDraft({ repoRoot, draft }) {
3870
4021
  const { queries, paths } = buildWitnessObservationQuerySet(draft);
3871
4022
  const collected = await collectSensorEvidence({ cwd: repoRoot, querySet: { queries } });
3872
4023
  const observationByPath = {};
@@ -3883,6 +4034,12 @@ async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
3883
4034
  changedFiles: [...entry.data.changedFiles],
3884
4035
  };
3885
4036
  });
4037
+ return { paths, observationByPath };
4038
+ }
4039
+
4040
+ /** The scaffold itself: fresh observation, wiring and digest for a checked draft, then the write. */
4041
+ async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
4042
+ const { paths, observationByPath } = await observeWitnessDraft({ repoRoot, draft });
3886
4043
  const { witnessSet, reasons } = buildWitnessSet({ draft, observationByPath });
3887
4044
  if (witnessSet === null) {
3888
4045
  // 理由コードは具体的なのに次の一手が汎用だと、何をどう直すのかが伝わらない。
@@ -3946,29 +4103,28 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3946
4103
  next_action: `${planKey}/${taskId} is ${state.status}; only unfinished tasks are declared (see \`lattice todo status --json\`).`,
3947
4104
  });
3948
4105
  }
3949
- const recorded = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
3950
- const template = await witnessDraftTemplateFor({ repoRoot, planKey });
3951
- const keep = new Set([...Object.keys(recorded?.plan_key === planKey ? recorded.manual_witness : {}), taskId]);
3952
- const list = (value) => (typeof value === 'string' ? value.split(',').map((item) => item.trim()).filter(Boolean) : []);
3953
- const row = { owns: list(flags.owns), reads: list(flags.reads), writes: list(flags.writes) };
3954
- const draft = { ...template, tasks: Object.fromEntries(Object.entries(template.tasks)
3955
- .filter(([id]) => keep.has(id)).map(([id, task]) => [id, id === taskId ? row : task])) };
3956
- if (!validateWitnessDraft(draft)) {
3957
- const { valid: _valid, reason, path: at, ...keys } = explainWitnessDraft(draft);
3958
- throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
3959
- pointer: at, ...keys, next_action: witnessRoute(planKey) });
3960
- }
3961
- const scaffolded = await scaffoldWitnessDraft({ repoRoot, planKey, draft });
4106
+ const observable = headResolves(repoRoot);
4107
+ const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable });
4108
+ const base = {
4109
+ schema: 'lattice.todo_witness_declare_result.v2', project_id: member.plan.project_id, plan_key: planKey,
4110
+ task_id: taskId, declaration: declared.declaration,
4111
+ };
4112
+ if (declared.scaffolded === null) {
4113
+ // Names that do not resolve never fail the command (ADR 0204 §6): the row stays unwritten and the same declare retries.
4114
+ const result = { ...base, witness_ref: null, witness_set_digest: null, compiled: false, waiting_for: [], compile: null,
4115
+ next_action: declarationNextAction(planKey, taskId, declared.declaration), result_digest: '' };
4116
+ result.result_digest = todoSelfDigest(result, 'result_digest');
4117
+ return result;
4118
+ }
4119
+ const { row, scaffolded, keep } = declared;
3962
4120
  const waitingFor = projectTodoStatus(await readTodoStoreForReadiness({ repoRoot, env }), TODO_STATUS_DISPATCH_ONLY).next_ready
3963
4121
  .filter((task) => task.plan_key === planKey && !keep.has(task.task_id))
3964
4122
  .map(({ task_id: id }) => id).sort();
3965
4123
  // declare-without-git: a Store root with no commit cannot be observed, so the row is recorded and not compiled.
3966
- const observable = headResolves(repoRoot);
3967
4124
  const compile = observable
3968
4125
  ? await independenceCompile({ repoRoot, planKey, inputRef: scaffolded.witness_ref }) : null;
3969
4126
  const result = {
3970
- schema: 'lattice.todo_witness_declare_result.v1', project_id: member.plan.project_id, plan_key: planKey,
3971
- task_id: taskId, ...row, witness_ref: scaffolded.witness_ref,
4127
+ ...base, owns: row.owns, reads: row.reads, writes: row.writes, witness_ref: scaffolded.witness_ref,
3972
4128
  witness_set_digest: scaffolded.witness_set_digest, compiled: compile !== null, waiting_for: waitingFor,
3973
4129
  compile,
3974
4130
  ...(observable ? {} : {
@@ -3982,6 +4138,94 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3982
4138
  return result;
3983
4139
  }
3984
4140
 
4141
+ /** What to do when a declaration was not written: the names that failed, with the nearest ones. */
4142
+ function declarationNextAction(planKey, taskId, declaration) {
4143
+ const parts = [];
4144
+ for (const { text, reason } of declaration.malformed) parts.push(`${text} (${reason}; write path#function, e.g. src/a.mjs#foo or src/a.mjs#Klass.method)`);
4145
+ for (const entry of declaration.unresolved) {
4146
+ const near = entry.nearest.length > 0 ? ` nearest: ${entry.nearest.join(', ')}` : '';
4147
+ const where = entry.elsewhere.length > 0 ? ` found elsewhere: ${entry.elsewhere.join(', ')}` : '';
4148
+ parts.push(`${entry.path}#${entry.symbol} (${entry.reason});${near}${where}`.replace(/;$/u, ''));
4149
+ }
4150
+ return `${planKey}/${taskId}'s functions were not recorded: ${parts.join('; ')}. Correct the names and run the same declaration again;`
4151
+ + ' the task itself is unchanged.';
4152
+ }
4153
+
4154
+ /**
4155
+ * One task's witness row from `--owns/--reads/--writes` (paths, or path#function): resolves the functions through the
4156
+ * code graph and, when every name resolves, writes the plan's witness set with the row and the task's conflict relations
4157
+ * in one `transactTodoRelations` call (ADR 0204 §3, a5). `scaffolded: null` = not written. Never refused for a conflict:
4158
+ * `conflicts` lists the tasks this one overlaps, `[]` when none.
4159
+ * Resolve and the fresh observation run before the Store lock; if another declaration changed the set meanwhile (a row or
4160
+ * path this attempt did not resolve or observe), the call writes nothing and the attempt runs again (three at most).
4161
+ */
4162
+ async function declareTaskRow({ repoRoot, planKey, taskId, flags, observable }) {
4163
+ const store = await readTodoStore({ repoRoot });
4164
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
4165
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
4166
+ const writer = createTodoStoreWriter({ caller: 'todo-relations' });
4167
+ const mine = declaredPaths(flags);
4168
+ const headSha = observable ? currentHeadSha(repoRoot) : null;
4169
+ const peek = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
4170
+ let alsoResolve = neededAnchors(peek?.plan_key === planKey ? peek.manual_witness : {}, taskId, mine);
4171
+ for (let attempt = 0; attempt < 3; attempt += 1) {
4172
+ const { row, declaration, ranges } = await buildDeclarationRow({
4173
+ root: repoRoot, observable, owns: flags.owns, reads: flags.reads, writes: flags.writes, alsoResolve });
4174
+ if (row === null) return { declaration, scaffolded: null };
4175
+ const resolved = new Set([...alsoResolve, ...declaration.resolved].map(({ path: where, symbol }) => `${where}\0${symbol}`));
4176
+ const draftFor = (witnessSet, unfinishedTaskIds) => {
4177
+ const template = witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
4178
+ witnessSet: witnessSet?.plan_key === planKey ? witnessSet : null, taskIds: unfinishedTaskIds });
4179
+ const keep = new Set([...Object.keys(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}), taskId]);
4180
+ const draft = { ...template, tasks: Object.fromEntries(Object.entries(template.tasks)
4181
+ .filter(([id]) => keep.has(id)).map(([id, task]) => [id, id === taskId ? row : task])) };
4182
+ if (!validateWitnessDraft(draft)) {
4183
+ const { valid: _valid, reason, path: at, ...keys } = explainWitnessDraft(draft);
4184
+ throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
4185
+ pointer: at, ...keys, next_action: witnessRoute(planKey) });
4186
+ }
4187
+ return { draft, keep };
4188
+ };
4189
+ const unfinishedNow = member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id);
4190
+ const first = draftFor(peek, unfinishedNow);
4191
+ const observed = await observeWitnessDraft({ repoRoot, draft: first.draft });
4192
+ const known = new Set(observed.paths);
4193
+ let outcome = null;
4194
+ let stale = null;
4195
+ await transactTodoRelations({ repoRoot, planKey, writer, update: ({ witnessSet, openRelations, unfinishedTaskIds }) => {
4196
+ const { draft, keep } = draftFor(witnessSet, unfinishedTaskIds);
4197
+ const missingPaths = buildWitnessObservationQuerySet(draft).paths.filter((target) => !known.has(target));
4198
+ const needed = neededAnchors(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}, taskId, mine);
4199
+ if (missingPaths.length > 0 || needed.some(({ path: where, symbol }) => !resolved.has(`${where}\0${symbol}`))) {
4200
+ stale = needed;
4201
+ return {};
4202
+ }
4203
+ const built = buildWitnessSet({ draft, observationByPath: observed.observationByPath });
4204
+ if (built.witnessSet === null) {
4205
+ const guidance = selectWitnessScaffoldGuidance(built.reasons);
4206
+ throw new TodoStoreError('WITNESS_SCAFFOLD_INCOMPLETE', 'witness_scaffold_incomplete', undefined, {
4207
+ reasons: built.reasons, guidance, next_action: guidance.next_action });
4208
+ }
4209
+ const judged = judgeTask({ taskId, rows: built.witnessSet.manual_witness, ranges: rangeIndex(ranges), openRelations });
4210
+ outcome = { witnessSet: built.witnessSet, judged, keep, paths: observed.paths };
4211
+ return { witnessSet: built.witnessSet, relations: judged.relations, gone: judged.gone, headSha,
4212
+ unresolvedCount: judged.unresolved };
4213
+ } });
4214
+ if (outcome !== null) {
4215
+ const { witnessSet, judged, keep, paths } = outcome;
4216
+ declaration.conflicts = judged.relations.map((relation) => relationView(taskId, relation));
4217
+ const ref = todoWitnessRef(planKey);
4218
+ return { row, declaration, keep, scaffolded: {
4219
+ schema: 'lattice.todo_witness_scaffold_result.v1', project_id: member.plan.project_id, plan_key: planKey, witness_ref: ref,
4220
+ observed_paths: paths, task_count: Object.keys(witnessSet.manual_witness).length,
4221
+ witness_set_digest: witnessSet.witness_set_digest, next_action: independenceCompileCommand(planKey, ref) } };
4222
+ }
4223
+ alsoResolve = stale;
4224
+ }
4225
+ throw new TodoStoreError('STORE_WRITE_CONFLICT', 'witness_set_changing', undefined, {
4226
+ next_action: `Other declarations on ${planKey} kept changing the witness set; run the same declaration again.` });
4227
+ }
4228
+
3985
4229
  /**
3986
4230
  * 着地時に使うsurface名。提案が出すhash由来の仮名を、人が読む名前へ置き換える。
3987
4231
  *
@@ -4697,11 +4941,24 @@ function writesTodoStore(argv) {
4697
4941
  case 'phase': return second !== 'status';
4698
4942
  case 'start': case 'retract': case 'block': case 'unblock': case 'retire': case 'done':
4699
4943
  case 'reopen': case 'split': case 'revise': case 'revise-phase': case 'revise-set': case 'add':
4944
+ case 'function-split':
4700
4945
  return true;
4701
4946
  default: return false;
4702
4947
  }
4703
4948
  }
4704
4949
 
4950
+ /**
4951
+ * a5: `todo done` / `todo retire` do not take the relations lock, so a finished task can leave an open relation. One empty
4952
+ * transaction closes it, and only when the plan has relations at all (one small read otherwise). Never fails the command:
4953
+ * the next write of the plan closes it the same way.
4954
+ */
4955
+ async function settleRelations({ repoRoot, planKey }) {
4956
+ try {
4957
+ if (((await readTodoRelationSummary({ repoRoot, planKey }))?.relation_count ?? 0) === 0) return;
4958
+ await transactTodoRelations({ repoRoot, planKey, writer: createTodoStoreWriter({ caller: 'todo-relations' }), update: () => ({}) });
4959
+ } catch { /* shortcut: relations left open until the plan's next write; no relation is ever worth failing a done */ }
4960
+ }
4961
+
4705
4962
  /** g4: the todo commands that write a new plan version (the plan revise command carries on its own in bin/lattice.mjs). */
4706
4963
  function revisesPlan(argv) {
4707
4964
  return ['add', 'revise', 'revise-phase', 'revise-set', 'split', 'dependency', 'predecessor'].includes(argv[0])
@@ -5447,6 +5704,21 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5447
5704
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
5448
5705
  action = (repoRoot) => revise({ repoRoot, env, planKey: flags.plan, inputRef: flags.input });
5449
5706
  }
5707
+ } else if (argv[0] === 'function-split' && argv[1] === 'verify') {
5708
+ const flags = matchFlagCommand(argv, ['function-split', 'verify'], TODO_FLAG_SPECS['function-split verify']);
5709
+ if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
5710
+ && ['commit', 'map'].every((name) => typeof flags[name] === 'string' && flags[name].length > 0)
5711
+ && (flags.base === undefined || (typeof flags.base === 'string' && flags.base.length > 0))) {
5712
+ action = (repoRoot) => verifySplit({ repoRoot, env, planKey: flags.plan, taskId: flags.task, commit: flags.commit,
5713
+ base: flags.base, mapText: flags.map, deps: splitDeps(repoRoot, flags.plan) });
5714
+ }
5715
+ } else if (argv[0] === 'function-split' && argv[1] === 'decline') {
5716
+ const flags = matchFlagCommand(argv, ['function-split', 'decline'], TODO_FLAG_SPECS['function-split decline']);
5717
+ if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
5718
+ && typeof flags.reason === 'string' && flags.reason.length > 0) {
5719
+ action = (repoRoot) => reorganizeNotSplit({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5720
+ reason: flags.reason, deps: splitDeps(repoRoot, flags.plan) });
5721
+ }
5450
5722
  } else if (argv[0] === 'split') {
5451
5723
  const flags = matchFlagCommand(argv, ['split'], TODO_FLAG_SPECS.split);
5452
5724
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
@@ -5531,6 +5803,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5531
5803
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5532
5804
  kind: 'done', dropped: (recorded) => doneDropped({ repoRoot, flags, recorded }),
5533
5805
  action: async () => {
5806
+ await splitDoneGate({ repoRoot, planKey: flags.plan, taskId: flags.task, deps: splitDeps(repoRoot, flags.plan) });
5534
5807
  const result = await mutate({
5535
5808
  repoRoot, env, planKey: flags.plan, taskId: flags.task, kind: 'done', payload: 'authored',
5536
5809
  message: await doneMessage({ repoRoot, flags }),
@@ -5636,6 +5909,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5636
5909
  const result = releasesTasks(argv) ? await withNotices(repoRoot, written, before, env) : written;
5637
5910
  if (result !== null) stdout.write(`${plainVerify ? verifyVerdictLine(result) : JSON.stringify(result)}\n`);
5638
5911
  if (!atomicCommit && revisesPlan(argv)) await carryIndependenceAfterRevision({ cwd });
5912
+ if (!atomicCommit && ['done', 'retire'].includes(argv[0]) && typeof result?.plan_key === 'string') {
5913
+ await settleRelations({ repoRoot, planKey: result.plan_key });
5914
+ }
5639
5915
  return 0;
5640
5916
  } catch (error) {
5641
5917
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'