@quolu/lattice 0.85.1 → 0.85.3

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.
package/src/todo-cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { retireStateConflict, validateProspectiveEvent } from './todo-readiness.mjs';
2
2
  import { cliCommandKind } from './cli-command-kind.mjs';
3
3
  import { cliFailureClass } from './cli-failure-class.mjs';
4
- import { withRefusalGuidance } from './cli-refusal-guidance.mjs';
4
+ import { FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
5
5
  import { readTaskBackchainContext } from './plan-backchain.mjs';
6
6
  import { gitSync } from './git-process.mjs';
7
7
  import { createHash } from 'node:crypto';
@@ -168,8 +168,8 @@ import { collectTodoIndependenceAuthoritativeObservation } from './todo-independ
168
168
  import { applySeamProposal } from './seam-apply.mjs';
169
169
  import { todoPlanPrecedences } from './seam-verification.mjs';
170
170
  import {
171
- WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, serializeWitnessSet,
172
- validateWitnessDraft,
171
+ WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, explainWitnessDraft, serializeWitnessSet,
172
+ witnessDraftTemplate,
173
173
  } from './witness-scaffold.mjs';
174
174
  import {
175
175
  completePhaseTodoRevision, explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
@@ -215,7 +215,18 @@ const TODO_SCHEMA_COMMANDS = Object.freeze({
215
215
  structure: {
216
216
  title: 'lattice.todo_structure_set.v1', file: 'lattice.todo_structure_set.v1.schema.json',
217
217
  },
218
+ // a32: the witness route's two inputs, so a seat that chose `--set witness` can find their shape.
219
+ 'independence witness scaffold': {
220
+ title: 'lattice.todo_witness_draft.v2', file: 'lattice.todo_witness_draft.v2.schema.json',
221
+ },
222
+ 'independence compile': { title: 'lattice.todo_witness_set.v5', file: 'lattice.todo_witness_set.v5.schema.json' },
218
223
  });
224
+ const witnessTemplateCommand = (planKey) => `lattice todo independence witness scaffold --template --plan ${planKey}`;
225
+ const WITNESS_DRAFT_SCHEMA_COMMAND = 'lattice todo independence witness scaffold --schema --json';
226
+ /** a32: where a witness set comes from: the template, filled, through scaffold (which adds digest and observations). */
227
+ const witnessRoute = (planKey) => `Start from \`${witnessTemplateCommand(planKey)}\` (draft shape: \`${WITNESS_DRAFT_SCHEMA_COMMAND}\`),`
228
+ + ` fill each task's owns/reads/writes, then run \`lattice todo independence witness scaffold --plan ${planKey} --input <draft>\`;`
229
+ + ' it writes the witness set that `independence compile` reads (shape: `lattice todo independence compile --schema --json`).';
219
230
 
220
231
  async function runTodoSchemaCommand(command, stdout) {
221
232
  const spec = TODO_SCHEMA_COMMANDS[command];
@@ -228,7 +239,7 @@ async function runTodoSchemaCommand(command, stdout) {
228
239
  function typedFailure(stderr, error, context = {}) {
229
240
  const payload = {
230
241
  schema: CLI_ERROR_SCHEMA,
231
- code: error.code,
242
+ code: publicRefusalCode(error.code, error.detail?.reason),
232
243
  message: error.message,
233
244
  detail: withRefusalGuidance(error, context),
234
245
  };
@@ -319,10 +330,31 @@ const TODO_FLAG_SPECS = Object.freeze({
319
330
  'phase close-unaudited': PHASE_REASON_FLAG_SPEC,
320
331
  split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
321
332
  note: NOTE_FLAG_SPEC,
333
+ // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
334
+ 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'input'], required: ['plan', 'phase'] }),
335
+ 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'reason', 'input'], required: ['plan', 'phase'] }),
336
+ 'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
337
+ 'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
338
+ 'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
339
+ 'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
340
+ 'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
341
+ show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
342
+ 'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
343
+ structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
344
+ status: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
345
+ });
346
+ const WITNESS_TEMPLATE_FLAG_SPEC = Object.freeze({
347
+ known: ['template', 'plan', 'json'], required: ['plan'], booleans: ['template', 'json'] });
348
+ // a28: command groups, their subcommands and the one a refusal shows as the example.
349
+ const TODO_SUBCOMMANDS = Object.freeze({
350
+ dependency: { names: ['connect', 'disconnect'], example: 'connect' },
351
+ phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
352
+ evidence: { names: ['promote'], example: 'promote' },
322
353
  });
354
+ const GROUP_COMMANDS = ['dependency', 'phase', 'evidence', 'independence', 'note', 'structure'];
323
355
  const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
324
- const FLAG_PLACEHOLDER = { reason: '<text>', 'override-reason': '<text>', message: '<text>',
325
- evidence: '<file>', 'test-result': '<file>', input: '<file>' };
356
+ // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
357
+ const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
326
358
  const shellWord = (value) => (/^[\w./:@-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
327
359
 
328
360
  /** The command again, with the flags given and a placeholder for each missing required flag. */
@@ -331,7 +363,7 @@ function repairedCommand(head, spec, flags) {
331
363
  for (const name of spec.known) {
332
364
  if (typeof flags[name] === 'string' && flags[name].length > 0) words.push(`--${name}`, shellWord(flags[name]));
333
365
  else if (flags[name] === true && spec.booleans?.includes(name)) words.push(`--${name}`);
334
- else if (spec.required.includes(name)) words.push(`--${name}`, FLAG_PLACEHOLDER[name] ?? `<${name}>`);
366
+ else if (spec.required.includes(name)) words.push(`--${name}`, placeholder(name));
335
367
  }
336
368
  return words.join(' ');
337
369
  }
@@ -342,22 +374,71 @@ function dependencyFlags(argv) {
342
374
  return flags !== null && IDENTIFIER_FLAGS.slice(3).every((name) => isTodoIdentifier(flags[name])) ? flags : null;
343
375
  }
344
376
 
377
+ /** a28: a read command's flags by name (order-free, --json optional) with valid identifiers, or null. */
378
+ function readFlags(argv, head) {
379
+ const flags = matchFlagCommand(argv, head, TODO_FLAG_SPECS[head.join(' ')]);
380
+ return flags !== null && ['plan', 'task'].every((name) => flags[name] === undefined || isTodoIdentifier(flags[name]))
381
+ ? flags : null;
382
+ }
383
+
384
+ /** `phase reopen` flags by name; --override-reason, when given, is non-empty. */
385
+ function phaseReopenFlags(argv) {
386
+ const flags = matchFlagCommand(argv, ['phase', 'reopen'], TODO_FLAG_SPECS['phase reopen']);
387
+ return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase)
388
+ && (flags['override-reason'] === undefined
389
+ || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0)) ? flags : null;
390
+ }
391
+
345
392
  /** `phase review|close-unaudited` flags by name (order-free), or null. */
346
393
  function phaseReasonFlags(argv) {
347
394
  const flags = matchFlagCommand(argv, argv.slice(0, 2), PHASE_REASON_FLAG_SPEC);
348
395
  return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase) ? flags : null;
349
396
  }
350
397
 
351
- /** A todo write's argument refusal names the flag, the rule and the command to run instead. */
398
+ /** `todo` without a command, or a group without a subcommand it has; null otherwise (a28). */
399
+ function explainMissingSubcommand(argv) {
400
+ if (argv.length === 0) {
401
+ return { pointer: '<command>', rule: 'subcommand_missing', available_commands: TODO_COMMAND_NAMES,
402
+ next_action: 'Name a todo command; for the overview of every plan run `lattice todo status --json`'
403
+ + ' (every command: `lattice todo --help`).' };
404
+ }
405
+ const group = TODO_SUBCOMMANDS[argv[0]];
406
+ if (group === undefined || group.names.includes(argv[1])) return null;
407
+ const missing = typeof argv[1] !== 'string' || argv[1].startsWith('--');
408
+ const head = [argv[0], group.example];
409
+ const { flags } = parseFlagMap(argv.slice(missing ? 1 : 2));
410
+ return { pointer: missing ? '<subcommand>' : argv[1], rule: missing ? 'subcommand_missing' : 'subcommand_unknown',
411
+ available_subcommands: group.names,
412
+ next_action: `Name one of ${group.names.join(', ')} after \`lattice todo ${argv[0]}\`, e.g.`
413
+ + ` \`${repairedCommand(head, TODO_FLAG_SPECS[head.join(' ')], flags)}\`.` };
414
+ }
415
+
416
+ /** A todo argument refusal names the flag, the rule and the command to run instead. */
352
417
  function explainArgumentRefusal(argv) {
353
- if (argv[0] === 'note' && argv[1] === 'list') return {};
354
- const head = ['dependency', 'phase'].includes(argv[0]) ? argv.slice(0, 2) : argv.slice(0, 1);
355
- const spec = TODO_FLAG_SPECS[head.join(' ')];
418
+ const missingSubcommand = explainMissingSubcommand(argv);
419
+ if (missingSubcommand !== null) return missingSubcommand;
420
+ const head = argv[0] === 'independence' && argv[1] === 'witness' ? argv.slice(0, 3)
421
+ : GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
422
+ ? argv.slice(0, 2) : argv.slice(0, 1);
423
+ // a32: `scaffold --template` is a read with its own flags.
424
+ const spec = head.join(' ') === 'independence witness scaffold' && argv.includes('--template')
425
+ ? WITNESS_TEMPLATE_FLAG_SPEC : TODO_FLAG_SPECS[head.join(' ')];
356
426
  if (spec === undefined) return {};
357
427
  const { flags } = parseFlagMap(argv.slice(head.length));
358
428
  const flagFailure = explainFlagCommand(argv, head, spec);
359
429
  if (flagFailure?.rule === 'flag_missing') {
360
- return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${FLAG_PLACEHOLDER[flagFailure.pointer.slice(2)] ?? '<value>'}: \`${repairedCommand(head, spec, flags)}\`.` };
430
+ const missing = flagFailure.pointer.slice(2);
431
+ const lists = { task: ` (task ids: \`lattice plan show ${flags.plan ?? '<plan>'} --json\`)` }[missing] ?? '';
432
+ return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${placeholder(missing)}${lists}: \`${repairedCommand(head, spec, flags)}\`.` };
433
+ }
434
+ if (flagFailure?.rule === 'flag_unknown') {
435
+ // a28: a flag the command does not take is named, with the flags it does take and a command that works.
436
+ const takes = spec.known.map((name) => `--${name}`).join(', ') || 'no flags';
437
+ const { [flagFailure.pointer.slice(2)]: _dropped, ...kept } = flags;
438
+ const onePlan = flagFailure.pointer === '--plan' && typeof flags.plan === 'string'
439
+ ? `; for one plan run \`lattice plan show ${flags.plan} --json\`` : '';
440
+ return { ...flagFailure, next_action: `${flagFailure.pointer} does not apply to \`lattice todo ${head.join(' ')}\``
441
+ + ` (it takes ${takes}): \`${repairedCommand(head, spec, kept)}\`${onePlan}.` };
361
442
  }
362
443
  if (flagFailure !== null) return flagFailure;
363
444
  for (const name of IDENTIFIER_FLAGS.filter((key) => spec.known.includes(key))) {
@@ -379,8 +460,29 @@ function explainArgumentRefusal(argv) {
379
460
  next_action: `Pass either --message or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
380
461
  }
381
462
  }
382
- if (spec.known.includes('input') && flags.input !== undefined && !isAuthoringPathToken(flags.input)) {
383
- return { pointer: '--input', rule: 'path_token_invalid' };
463
+ if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
464
+ const given = ['evidence', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
465
+ if (given.length === 0) {
466
+ return { pointer: '--evidence', rule: 'flag_missing',
467
+ next_action: `Add --evidence <file> (or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
468
+ }
469
+ if (given.length === 2) {
470
+ return { pointer: '--input', rule: 'flags_exclusive',
471
+ next_action: `Pass either --evidence or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
472
+ }
473
+ if (argv[1] === 'reject' && given[0] === 'evidence' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
474
+ return { pointer: '--reason', rule: 'flag_missing',
475
+ next_action: `A reject with --evidence needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
476
+ }
477
+ if (given[0] === 'input' && flags.reason !== undefined) {
478
+ return { pointer: '--reason', rule: 'flag_unknown',
479
+ next_action: `With --input the reason is inside the decision file; drop --reason: \`${repairedCommand(head, spec, { ...flags, reason: undefined })}\`.` };
480
+ }
481
+ }
482
+ for (const name of ['input', 'evidence']) {
483
+ if (spec.known.includes(name) && flags[name] !== undefined && !isAuthoringPathToken(flags[name])) {
484
+ return { pointer: `--${name}`, rule: 'path_token_invalid' };
485
+ }
384
486
  }
385
487
  for (const name of ['override-reason', 'reason']) {
386
488
  if (spec.known.includes(name) && flags[name] !== undefined
@@ -409,7 +511,7 @@ function supportsAtomicStoreCommit(argv) {
409
511
  if (command === 'note') return argv[1] !== 'list';
410
512
  if (command === 'independence') {
411
513
  return argv[1] === 'mode'
412
- || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]));
514
+ || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]) && !argv.includes('--template'));
413
515
  }
414
516
  if (command === 'snapshot') return argv[1] === '--rebuild';
415
517
  if (command === 'migrate') return !argv.includes('--dry-run') && !argv.includes('--schema');
@@ -698,11 +800,23 @@ async function readJsonInput(repoRoot, inputRef, { validate, invalidCode, expect
698
800
  return descriptor;
699
801
  }
700
802
 
803
+ const WITNESS_SET_TOP_LEVEL_KEYS = ['schema', 'project_id', 'plan_key', 'capacity', 'sensor_query_set',
804
+ 'manual_witness', 'witness_set_digest'];
805
+ /** a32: the top-level keys a witness set lacks or should not have. */
806
+ function witnessSetKeyDiff(value) {
807
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return {};
808
+ const keys = Object.keys(value);
809
+ return { missing_keys: WITNESS_SET_TOP_LEVEL_KEYS.filter((key) => !keys.includes(key)),
810
+ unexpected_keys: keys.filter((key) => !WITNESS_SET_TOP_LEVEL_KEYS.includes(key)).sort() };
811
+ }
812
+
701
813
  /** 安全読み取りとcanonical JSON規律を共有したまま、witness set契約で検証する。 */
702
- async function readWitnessSetInput(repoRoot, inputRef) {
814
+ async function readWitnessSetInput(repoRoot, inputRef, planKey = '<key>') {
703
815
  let explained = null;
816
+ let witnessInput;
704
817
  const witnessSet = await readJsonInput(repoRoot, inputRef, {
705
818
  validate: (value) => {
819
+ witnessInput = value;
706
820
  explained = explainTodoWitnessSet(value);
707
821
  return explained.valid;
708
822
  },
@@ -710,7 +824,8 @@ async function readWitnessSetInput(repoRoot, inputRef) {
710
824
  }).catch((error) => {
711
825
  if (error?.code === 'INVALID_TODO_WITNESS_SET' && explained !== null) {
712
826
  throw new TodoStoreError('INVALID_TODO_WITNESS_SET', explained.reason, undefined, {
713
- input_ref: inputRef, path: explained.path,
827
+ input_ref: inputRef, path: explained.path, pointer: explained.path || '/',
828
+ ...witnessSetKeyDiff(witnessInput), next_action: witnessRoute(planKey),
714
829
  });
715
830
  }
716
831
  throw error;
@@ -1078,7 +1193,8 @@ async function startStructureContext({ repoRoot, store, planKey, taskId }) {
1078
1193
 
1079
1194
  function designMemoProjection(task) {
1080
1195
  if (typeof task.design_memo === 'string') {
1081
- return { status: 'available', markdown: task.design_memo, prompt: TODO_DESIGN_MEMO_PROMPT };
1196
+ // 書かれたmemo(NO_PLANを含む)には促しを繰り返さない(a27)。促しは欠けたmemoにだけ要る。
1197
+ return { status: 'available', markdown: task.design_memo, prompt: null };
1082
1198
  }
1083
1199
  return { status: 'missing_legacy', markdown: null, prompt: TODO_DESIGN_MEMO_PROMPT };
1084
1200
  }
@@ -1517,16 +1633,9 @@ async function dependencyConnect(options) {
1517
1633
  || !tasks.some(({ task_id: id }) => id === toTaskId) || fromTaskId === toTaskId) {
1518
1634
  return dependencyConnectLedger(options);
1519
1635
  }
1520
- const from = dependencyRef(store, fromPlanKey, fromTaskId);
1521
- const to = dependencyRef(store, toPlanKey, toTaskId);
1522
- if (samePlanEdge(member, fromTaskId, toTaskId)) {
1523
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'dependency_already_in_plan', undefined, { from, to });
1524
- }
1525
- // 以前の同一plan接続で台帳に生きている辺を、本体へ二重に足さない(台帳経路と同じ拒否)。
1526
- if (projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1527
- dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1528
- && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId))) {
1529
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate', undefined, { from, to });
1636
+ // a28: an edge already in the plan body or the ledger is the requested state; nothing is added twice.
1637
+ if (samePlanEdge(member, fromTaskId, toTaskId) || liveLedgerEdge(store, options)) {
1638
+ return dependencyUnchanged(store, options);
1530
1639
  }
1531
1640
  if (member.tasks.find(({ task_id: id }) => id === toTaskId)?.status === 'done') {
1532
1641
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_target_terminal');
@@ -1538,6 +1647,28 @@ async function dependencyConnect(options) {
1538
1647
  repoRoot, env, store, member, operation: 'connect', fromTaskId, toTaskId, reason });
1539
1648
  }
1540
1649
 
1650
+ /** A live ledger edge with these endpoints (cross-plan, or an earlier same-plan connect). */
1651
+ function liveLedgerEdge(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1652
+ return projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1653
+ dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1654
+ && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId));
1655
+ }
1656
+
1657
+ /** a28: connect of an existing edge succeeds unchanged, like a repeated done/block/retire (a12). */
1658
+ function dependencyUnchanged(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1659
+ const from = { project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId };
1660
+ const to = { project_id: store.project_id, plan_key: toPlanKey, task_id: toTaskId };
1661
+ const result = {
1662
+ schema: 'lattice.todo_dependency_unchanged_result.v1', project_id: store.project_id,
1663
+ operation: 'connect', from, to, unchanged: true,
1664
+ next_action: `${fromPlanKey}/${fromTaskId} -> ${toPlanKey}/${toTaskId} already exists; nothing was recorded`
1665
+ + ` (see \`lattice plan show ${toPlanKey} --json\`).`,
1666
+ result_digest: '',
1667
+ };
1668
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1669
+ return result;
1670
+ }
1671
+
1541
1672
  /** 台帳(cross_plan_dependency event)への接続。plan跨ぎの本線。 */
1542
1673
  async function dependencyConnectLedger({
1543
1674
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
@@ -1554,6 +1685,7 @@ async function dependencyConnectLedger({
1554
1685
  };
1555
1686
  const source = dependencyMember(fromPlanKey);
1556
1687
  const target = dependencyMember(toPlanKey);
1688
+ const endpoints = { fromPlanKey, fromTaskId, toPlanKey, toTaskId };
1557
1689
  if (!source.plan.tasks.some(({ task_id: taskId }) => taskId === fromTaskId)) {
1558
1690
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_task_not_found', undefined, {
1559
1691
  plan_key: fromPlanKey, task_id: fromTaskId,
@@ -1564,6 +1696,7 @@ async function dependencyConnectLedger({
1564
1696
  plan_key: toPlanKey, task_id: toTaskId,
1565
1697
  });
1566
1698
  }
1699
+ if (liveLedgerEdge(store, endpoints)) return dependencyUnchanged(store, endpoints);
1567
1700
  const from = {
1568
1701
  project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId,
1569
1702
  expected_topology_digest: source.plan.topology_digest,
@@ -2167,8 +2300,7 @@ async function splitTodo({ repoRoot, env, planKey, inputRef }) {
2167
2300
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
2168
2301
  if (witnessSet === null) {
2169
2302
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
2170
- witness_ref: todoWitnessRef(planKey),
2171
- next_action: `lattice todo independence witness scaffold --plan ${planKey} --input <draft>`,
2303
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
2172
2304
  });
2173
2305
  }
2174
2306
  const compiled = await compileTodoSplit({ repoRoot, member, proposal });
@@ -3041,7 +3173,7 @@ async function structure({ repoRoot, requestedPlanKey }) {
3041
3173
  }
3042
3174
 
3043
3175
  async function independenceCompile({ repoRoot, planKey, inputRef }) {
3044
- const witnessSet = await readWitnessSetInput(repoRoot, inputRef);
3176
+ const witnessSet = await readWitnessSetInput(repoRoot, inputRef, planKey);
3045
3177
  const storeForReady = await readTodoStore({ repoRoot });
3046
3178
  const memberForReady = storeForReady.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3047
3179
  if (!memberForReady) {
@@ -3131,7 +3263,7 @@ async function independenceWitnessMigrate({ repoRoot, planKey }) {
3131
3263
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
3132
3264
  if (witnessSet === null) {
3133
3265
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
3134
- witness_ref: todoWitnessRef(planKey),
3266
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
3135
3267
  });
3136
3268
  }
3137
3269
  const revision = member.revision;
@@ -3395,10 +3527,29 @@ async function seamProposalCompile({ repoRoot, planKey }) {
3395
3527
  * 推定はしない。何を所有し何を触るかは下書きが述べ、ここが供給するのはAIには作れないもの——
3396
3528
  * affected testのfresh観測、query setとprovenanceの配線、canonical bytesと自己digest——だけである。
3397
3529
  */
3530
+ /** a32: the starting draft for `planKey`: its tasks that are not done or retired, nothing declared yet. */
3531
+ async function witnessDraftTemplateFor({ repoRoot, planKey }) {
3532
+ const store = await readTodoStore({ repoRoot });
3533
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3534
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
3535
+ return witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
3536
+ taskIds: member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id) });
3537
+ }
3538
+
3398
3539
  async function witnessScaffold({ repoRoot, planKey, inputRef }) {
3540
+ let explained = null;
3399
3541
  const draft = await readJsonInput(repoRoot, inputRef, {
3400
- validate: validateWitnessDraft,
3542
+ validate: (value) => (explained = explainWitnessDraft(value)).valid,
3401
3543
  invalidCode: 'WITNESS_DRAFT_INVALID',
3544
+ }).catch((error) => {
3545
+ // a32: name the failing field and where the draft shape is, not a schema command that does not exist.
3546
+ if (error?.code === 'WITNESS_DRAFT_INVALID' && explained !== null && !explained.valid) {
3547
+ const { valid: _valid, reason, path: at, ...keys } = explained;
3548
+ throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
3549
+ input_ref: inputRef, pointer: at, ...keys, next_action: witnessRoute(planKey),
3550
+ });
3551
+ }
3552
+ throw error;
3402
3553
  });
3403
3554
  if (draft.plan_key !== planKey) {
3404
3555
  throw new TodoStoreError('INPUT_INVALID', 'witness_draft_plan_mismatch', undefined, {
@@ -4142,7 +4293,7 @@ function writesTodoStore(argv) {
4142
4293
  case 'migrate': return !argv.includes('--dry-run');
4143
4294
  case 'snapshot': return argv.includes('--rebuild');
4144
4295
  case 'independence': return second === 'compile'
4145
- || (second === 'witness' && ['migrate', 'scaffold'].includes(third));
4296
+ || (second === 'witness' && ['migrate', 'scaffold'].includes(third) && !argv.includes('--template'));
4146
4297
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4147
4298
  || (second === 'input' && !argv.includes('--dry-run'));
4148
4299
  case 'seam-proposal': return ['compile', 'apply', 'land'].includes(second);
@@ -4265,9 +4416,9 @@ async function verify({ repoRoot, requestedPlanKey }) {
4265
4416
  meaning: 'source_inventory_verification_state',
4266
4417
  lifecycle_blocked: false,
4267
4418
  dashboard_visibility_blocked: false,
4268
- // registered_unreconciledは何もしなくてよい状態(a22)。次の軽い改訂がreconciledにする。
4419
+ // どちらの状態も何もしなくてよい(a22)。値はnoneに揃える(a27)。次の軽い改訂がreconciledにする。
4269
4420
  schema_command: null,
4270
- next_action: reconciled ? null : 'none',
4421
+ next_action: 'none',
4271
4422
  },
4272
4423
  };
4273
4424
  });
@@ -4376,10 +4527,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4376
4527
 
4377
4528
  // `--schema --json`はstoreを読まない決定的な出力(`plan create --schema`と同じ規律)。
4378
4529
  // 通常dispatchより前に処理し、repoRoot解決やdashboard daemon起動を経由させない。
4379
- if (argv.length === 3 && argv[1] === '--schema' && argv[2] === '--json'
4380
- && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv[0])) {
4530
+ if (argv.length >= 3 && argv.at(-2) === '--schema' && argv.at(-1) === '--json'
4531
+ && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv.slice(0, -2).join(' '))) {
4381
4532
  try {
4382
- await runTodoSchemaCommand(argv[0], stdout);
4533
+ await runTodoSchemaCommand(argv.slice(0, -2).join(' '), stdout);
4383
4534
  return 0;
4384
4535
  } catch (error) {
4385
4536
  return failInternally(error);
@@ -4431,10 +4582,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4431
4582
  return { schema: 'lattice.todo_dashboard_ensure_result.v1',
4432
4583
  ensured: ensured !== null, activity: ensured };
4433
4584
  };
4434
- } else if (argv.length === 6 && argv[0] === 'show'
4435
- && argv[1] === '--plan' && isTodoIdentifier(argv[2])
4436
- && argv[3] === '--task' && isTodoIdentifier(argv[4]) && argv[5] === '--json') {
4437
- action = (repoRoot) => todoDetail({ repoRoot, planKey: argv[2], taskId: argv[4] });
4585
+ } else if (argv[0] === 'show' && readFlags(argv, ['show']) !== null) {
4586
+ const flags = readFlags(argv, ['show']);
4587
+ action = (repoRoot) => todoDetail({ repoRoot, planKey: flags.plan, taskId: flags.task });
4438
4588
  } else if ((argv.length === 1 && argv[0] === 'bindings')
4439
4589
  || (argv.length === 2 && argv[0] === 'bindings' && argv[1] === '--json')) {
4440
4590
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: null });
@@ -4458,22 +4608,20 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4458
4608
  supersedes: flags.supersedes ?? null,
4459
4609
  });
4460
4610
  }
4461
- } else if (argv.length === 5 && argv[0] === 'note' && argv[1] === 'list'
4462
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4463
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: null });
4464
- } else if (argv.length === 7 && argv[0] === 'note' && argv[1] === 'list'
4465
- && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4466
- && argv[4] === '--task' && isTodoIdentifier(argv[5]) && argv[6] === '--json') {
4467
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: argv[5] });
4611
+ } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
4612
+ const flags = readFlags(argv, ['note', 'list']);
4613
+ action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
4468
4614
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
4469
4615
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
4470
4616
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
4471
- } else if (argv.length === 8 && argv[0] === 'independence' && argv[1] === 'mode'
4472
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--set'
4473
- && TODO_COORDINATION_MODES.includes(argv[5]) && argv[6] === '--reason' && argv[7].length > 0) {
4474
- action = (repoRoot) => independenceMode({
4475
- repoRoot, env, planKey: argv[3], mode: argv[5], reason: argv[7],
4476
- });
4617
+ } else if (argv[0] === 'independence' && argv[1] === 'mode'
4618
+ && matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']) !== null) {
4619
+ const flags = matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']);
4620
+ if (isTodoIdentifier(flags.plan) && TODO_COORDINATION_MODES.includes(flags.set)) {
4621
+ action = (repoRoot) => independenceMode({
4622
+ repoRoot, env, planKey: flags.plan, mode: flags.set, reason: flags.reason,
4623
+ });
4624
+ }
4477
4625
  } else if (argv[0] === 'dependency' && argv[1] === 'connect'
4478
4626
  && dependencyFlags(argv) !== null) {
4479
4627
  const flags = dependencyFlags(argv);
@@ -4489,9 +4637,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4489
4637
  toPlanKey: flags['to-plan'], toTaskId: flags['to-task'], reason: flags.reason,
4490
4638
  });
4491
4639
  } else if (argv[0] === 'independence' && argv[1] === 'compile') {
4492
- const flags = matchFlagCommand(argv, ['independence', 'compile'], {
4493
- known: ['plan', 'input'], required: ['plan', 'input'],
4494
- });
4640
+ const flags = matchFlagCommand(argv, ['independence', 'compile'], TODO_FLAG_SPECS['independence compile']);
4495
4641
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4496
4642
  action = (repoRoot) => independenceCompile({
4497
4643
  repoRoot, planKey: flags.plan, inputRef: flags.input,
@@ -4535,11 +4681,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4535
4681
  } else if (argv.length === 5 && argv[0] === 'structure' && argv[1] === 'finalize'
4536
4682
  && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4537
4683
  action = (repoRoot) => structureFinalize({ repoRoot, env, planKey: argv[3] });
4538
- } else if (argv.length === 2 && argv[0] === 'structure' && argv[1] === '--json') {
4539
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: null });
4540
- } else if (argv.length === 4 && argv[0] === 'structure'
4541
- && argv[1] === '--plan' && isTodoIdentifier(argv[2]) && argv[3] === '--json') {
4542
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: argv[2] });
4684
+ } else if (argv[0] === 'structure' && readFlags(argv, ['structure']) !== null) {
4685
+ const flags = readFlags(argv, ['structure']);
4686
+ action = (repoRoot) => structure({ repoRoot, requestedPlanKey: flags.plan ?? null });
4543
4687
  } else if ((argv.length === 1 && argv[0] === 'independence')
4544
4688
  || (argv.length === 2 && argv[0] === 'independence' && argv[1] === '--json')) {
4545
4689
  action = (repoRoot) => independence({ repoRoot, requestedPlanKey: null });
@@ -4550,10 +4694,18 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4550
4694
  } else if (argv.length === 4 && argv[0] === 'seam-proposal' && argv[1] === 'apply'
4551
4695
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])) {
4552
4696
  action = (repoRoot) => seamProposalApply({ repoRoot, planKey: argv[3] });
4553
- } else if (argv.length === 7 && argv[0] === 'independence' && argv[1] === 'witness'
4554
- && argv[2] === 'scaffold' && argv[3] === '--plan' && isTodoIdentifier(argv[4])
4555
- && argv[5] === '--input' && isAuthoringPathToken(argv[6])) {
4556
- action = (repoRoot) => witnessScaffold({ repoRoot, planKey: argv[4], inputRef: argv[6] });
4697
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold'
4698
+ && argv.includes('--template')) {
4699
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'], WITNESS_TEMPLATE_FLAG_SPEC);
4700
+ if (flags !== null && isTodoIdentifier(flags.plan)) {
4701
+ action = (repoRoot) => witnessDraftTemplateFor({ repoRoot, planKey: flags.plan });
4702
+ }
4703
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold') {
4704
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'],
4705
+ TODO_FLAG_SPECS['independence witness scaffold']);
4706
+ if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4707
+ action = (repoRoot) => witnessScaffold({ repoRoot, planKey: flags.plan, inputRef: flags.input });
4708
+ }
4557
4709
  } else if (argv.length === 6 && argv[0] === 'seam-proposal' && argv[1] === 'land'
4558
4710
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4559
4711
  && argv[4] === '--names' && isAuthoringPathToken(argv[5])) {
@@ -4672,13 +4824,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4672
4824
  outcome, evidenceRef: flags.evidence, reason: flags.reason ?? null,
4673
4825
  });
4674
4826
  }
4675
- } else if ((argv.length === 8 || argv.length === 10) && argv[0] === 'phase'
4676
- && argv[1] === 'reopen' && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4677
- && argv[4] === '--phase' && isTodoIdentifier(argv[5])
4678
- && argv[6] === '--reason' && argv[7].length > 0
4679
- && (argv.length === 8 || (argv[8] === '--override-reason' && argv[9].length > 0))) {
4680
- action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: argv[3], phaseId: argv[5],
4681
- kind: 'phase_reopen', payload: { reason: argv[7], override_reason: argv[9] ?? null } });
4827
+ } else if (argv[0] === 'phase' && argv[1] === 'reopen' && phaseReopenFlags(argv) !== null) {
4828
+ const flags = phaseReopenFlags(argv);
4829
+ action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
4830
+ kind: 'phase_reopen', payload: { reason: flags.reason, override_reason: flags['override-reason'] ?? null } });
4682
4831
  } else if (argv[0] === 'phase' && argv[1] === 'close-unaudited'
4683
4832
  && phaseReasonFlags(argv) !== null) {
4684
4833
  const flags = phaseReasonFlags(argv);
@@ -4755,9 +4904,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4755
4904
  }) });
4756
4905
  }
4757
4906
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
4758
- const flags = matchFlagCommand(argv, ['evidence', 'promote'], {
4759
- known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'],
4760
- });
4907
+ const flags = matchFlagCommand(argv, ['evidence', 'promote'], TODO_FLAG_SPECS['evidence promote']);
4761
4908
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4762
4909
  && isAuthoringPathToken(flags.evidence)) {
4763
4910
  action = (repoRoot) => mutate({
@@ -80,7 +80,8 @@ const CATALOG = Object.freeze({
80
80
  }),
81
81
  independence_unrecorded: Object.freeze({
82
82
  message: 'このplanの並列可否はまだ判定していない。競合が無いのではなく、記録が存在しない。',
83
- next_action: 'lattice todo independence compile --plan <key> --input <file>',
83
+ // a32: the first step of the witness route is the draft template, not a file the seat cannot shape.
84
+ next_action: 'lattice todo independence witness scaffold --template --plan <key>',
84
85
  }),
85
86
  independence_task_undeclared: Object.freeze({
86
87
  message: 'この工程はwitness setで宣言されていないため、記録には含まれていない。',
@@ -309,7 +310,7 @@ export function selectSeamProposalGuidance({ coverage, unknownKinds = [], planKe
309
310
  * 足さないと、能力はあるのに機械が黙る面が残る(ADR 0130)。
310
311
  */
311
312
  export const TODO_INDEPENDENCE_WORKFLOW = Object.freeze([
312
- '1. 宣言する: .lattice/todo/witness/<plan_key>.json へ、ToDoごとのowns/reads/writes/affected_testsを書く',
313
+ '1. 宣言する: lattice todo independence witness scaffold --template --plan <key> が出す下書き(形は lattice todo independence witness scaffold --schema --json)へToDoごとのowns/reads/writesを書き、lattice todo independence witness scaffold --plan <key> --input <draft> が .lattice/todo/witness/<plan_key>.json を書く(affected_testsと自己digestは機械が埋める。形は lattice todo independence compile --schema --json)',
313
314
  ' 係争資源しか所有していないToDoは、ownsまたはwritesの内側で自分が触るsymbolをconcern_anchorsへ宣言できる(witness set v2)。並列可否の判定には写らず、切断候補の束縛だけに効く',
314
315
  ' remaining の A 工程(まだ done でない ready / blocked)も同じ witness に含める。現在の ready だけを compile すると、次の frontier の start の助言が未検証(independence_task_undeclared)になる',
315
316
  '2. 判定する: lattice todo independence compile --plan <key> --input <ref>(実sensorを引く。pretty-printやdigest未計算の下書きは機械が直す)。next_ready が witness に無い compile は拒否する',
@@ -118,9 +118,13 @@ export function createTodoReadiness(store) {
118
118
  return node?.schema !== 'lattice.todo_plan.v4' || node.phase_status === 'active';
119
119
  }
120
120
 
121
- function startedSuccessor(key) {
122
- return [...(outgoing.get(key) ?? [])].some((successor) => nodes.get(successor)?.status !== 'pending');
121
+ /** a28: the successors that already left pending, sorted, so a refusal can name them. */
122
+ function startedSuccessors(key) {
123
+ return [...(outgoing.get(key) ?? [])].map((successor) => nodes.get(successor))
124
+ .filter((node) => node !== undefined && node.status !== 'pending')
125
+ .map(({ plan_key, task_id, status }) => ({ plan_key, task_id, status })).sort(byRef);
123
126
  }
127
+ const startedSuccessor = (key) => startedSuccessors(key).length > 0;
124
128
 
125
129
  return {
126
130
  key: taskKey,
@@ -131,6 +135,7 @@ export function createTodoReadiness(store) {
131
135
  isReady: (key) => nodes.get(key)?.status === 'pending'
132
136
  && ownPhaseReady(key) && prerequisites(key).dependenciesDone,
133
137
  startedSuccessor,
138
+ startedSuccessors,
134
139
  phaseHasStartedSuccessor: (member, phaseId) => member.plan.schema === 'lattice.todo_plan.v4'
135
140
  ? member.plan.tasks.filter(({ phase_id }) => phase_id === phaseId)
136
141
  .some((task) => startedSuccessor(taskKey({ ...member.plan, ...task })))
@@ -173,8 +178,13 @@ export function validateProspectiveEvent({ store, member, event }) {
173
178
  return refused('invalid_done_transition', prerequisites.cause, prerequisites.blocking);
174
179
  }
175
180
  if (event.kind === 'reopen' && event.payload.override_reason === null && readiness.startedSuccessor(key)) {
181
+ const started = readiness.startedSuccessors(key);
182
+ const on = `--plan ${member.plan.plan_key} --task ${event.task_id}`;
176
183
  return refused('reopen_has_started_successor', 'task_state', {
177
- next_action: `lattice todo split --plan ${member.plan.plan_key} --input <file>`,
184
+ started_successors: started,
185
+ next_action: `${started.map((task) => `${task.plan_key}/${task.task_id} (${task.status})`).join(', ')}`
186
+ + ` already left pending after ${member.plan.plan_key}/${event.task_id}; to reopen it anyway run`
187
+ + ` \`lattice todo reopen ${on} --reason <text> --override-reason <text>\`.`,
178
188
  });
179
189
  }
180
190
  if (event.kind === 'phase_reopen' && event.payload.override_reason === null
@@ -2165,6 +2165,12 @@ function resolveTargetedEvent(input, storeMember) {
2165
2165
  if (input.kind === 'reopen' && exactRecord(input.payload, [
2166
2166
  'reason', 'override_reason',
2167
2167
  ])) {
2168
+ // a32: only a done task reopens; any other state is the seat's order, not a damaged store.
2169
+ const status = storeMember.tasks?.find(({ task_id: id }) => id === input.task_id)?.status;
2170
+ if (status !== undefined && status !== 'done') {
2171
+ fail('TODO_TRANSITION_REFUSED', 'invalid_reopen_transition', {
2172
+ cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id });
2173
+ }
2168
2174
  const targetDigest = resolveDoneBindingDigest(storeMember, input.task_id);
2169
2175
  if (targetDigest === null) fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
2170
2176
  return {