@quolu/lattice 0.85.0 → 0.85.2

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';
@@ -228,7 +228,7 @@ async function runTodoSchemaCommand(command, stdout) {
228
228
  function typedFailure(stderr, error, context = {}) {
229
229
  const payload = {
230
230
  schema: CLI_ERROR_SCHEMA,
231
- code: error.code,
231
+ code: publicRefusalCode(error.code, error.detail?.reason),
232
232
  message: error.message,
233
233
  detail: withRefusalGuidance(error, context),
234
234
  };
@@ -293,6 +293,8 @@ const DONE_FLAG_SPEC = Object.freeze({
293
293
  });
294
294
 
295
295
  const REASON_FLAG_SPEC = Object.freeze({ known: ['plan', 'task', 'reason'], required: ['plan', 'task', 'reason'] });
296
+ const PHASE_REASON_FLAG_SPEC = Object.freeze({ known: ['plan', 'phase', 'reason'], required: ['plan', 'phase', 'reason'] });
297
+ const NOTE_FLAG_SPEC = Object.freeze({ known: ['plan', 'task', 'message', 'input', 'supersedes'], required: ['plan'] });
296
298
  const DEPENDENCY_FLAG_SPEC = Object.freeze({
297
299
  known: ['from-plan', 'from-task', 'to-plan', 'to-task', 'reason'],
298
300
  required: ['from-plan', 'from-task', 'to-plan', 'to-task', 'reason'],
@@ -312,10 +314,32 @@ const TODO_FLAG_SPECS = Object.freeze({
312
314
  reopen: Object.freeze({ known: ['plan', 'task', 'reason', 'override-reason'], required: ['plan', 'task', 'reason'] }),
313
315
  'dependency connect': DEPENDENCY_FLAG_SPEC,
314
316
  'dependency disconnect': DEPENDENCY_FLAG_SPEC,
317
+ // a23: the remaining writes whose refusal pointed only at --help.
318
+ 'phase review': PHASE_REASON_FLAG_SPEC,
319
+ 'phase close-unaudited': PHASE_REASON_FLAG_SPEC,
320
+ split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
321
+ note: NOTE_FLAG_SPEC,
322
+ // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
323
+ 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'input'], required: ['plan', 'phase'] }),
324
+ 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'reason', 'input'], required: ['plan', 'phase'] }),
325
+ 'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
326
+ 'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
327
+ 'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
328
+ show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
329
+ 'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
330
+ structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
331
+ status: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
315
332
  });
316
- const IDENTIFIER_FLAGS = ['plan', 'task', 'from-plan', 'from-task', 'to-plan', 'to-task'];
317
- const FLAG_PLACEHOLDER = { reason: '<text>', 'override-reason': '<text>', message: '<text>',
318
- evidence: '<file>', 'test-result': '<file>' };
333
+ // a28: command groups, their subcommands and the one a refusal shows as the example.
334
+ const TODO_SUBCOMMANDS = Object.freeze({
335
+ dependency: { names: ['connect', 'disconnect'], example: 'connect' },
336
+ phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
337
+ evidence: { names: ['promote'], example: 'promote' },
338
+ });
339
+ const GROUP_COMMANDS = ['dependency', 'phase', 'evidence', 'independence', 'note', 'structure'];
340
+ const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
341
+ // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
342
+ const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
319
343
  const shellWord = (value) => (/^[\w./:@-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
320
344
 
321
345
  /** The command again, with the flags given and a placeholder for each missing required flag. */
@@ -324,7 +348,7 @@ function repairedCommand(head, spec, flags) {
324
348
  for (const name of spec.known) {
325
349
  if (typeof flags[name] === 'string' && flags[name].length > 0) words.push(`--${name}`, shellWord(flags[name]));
326
350
  else if (flags[name] === true && spec.booleans?.includes(name)) words.push(`--${name}`);
327
- else if (spec.required.includes(name)) words.push(`--${name}`, FLAG_PLACEHOLDER[name] ?? `<${name}>`);
351
+ else if (spec.required.includes(name)) words.push(`--${name}`, placeholder(name));
328
352
  }
329
353
  return words.join(' ');
330
354
  }
@@ -332,23 +356,116 @@ function repairedCommand(head, spec, flags) {
332
356
  /** `dependency connect|disconnect` flags by name (order-free), or null. */
333
357
  function dependencyFlags(argv) {
334
358
  const flags = matchFlagCommand(argv, argv.slice(0, 2), DEPENDENCY_FLAG_SPEC);
335
- return flags !== null && IDENTIFIER_FLAGS.slice(2).every((name) => isTodoIdentifier(flags[name])) ? flags : null;
359
+ return flags !== null && IDENTIFIER_FLAGS.slice(3).every((name) => isTodoIdentifier(flags[name])) ? flags : null;
360
+ }
361
+
362
+ /** a28: a read command's flags by name (order-free, --json optional) with valid identifiers, or null. */
363
+ function readFlags(argv, head) {
364
+ const flags = matchFlagCommand(argv, head, TODO_FLAG_SPECS[head.join(' ')]);
365
+ return flags !== null && ['plan', 'task'].every((name) => flags[name] === undefined || isTodoIdentifier(flags[name]))
366
+ ? flags : null;
367
+ }
368
+
369
+ /** `phase reopen` flags by name; --override-reason, when given, is non-empty. */
370
+ function phaseReopenFlags(argv) {
371
+ const flags = matchFlagCommand(argv, ['phase', 'reopen'], TODO_FLAG_SPECS['phase reopen']);
372
+ return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase)
373
+ && (flags['override-reason'] === undefined
374
+ || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0)) ? flags : null;
375
+ }
376
+
377
+ /** `phase review|close-unaudited` flags by name (order-free), or null. */
378
+ function phaseReasonFlags(argv) {
379
+ const flags = matchFlagCommand(argv, argv.slice(0, 2), PHASE_REASON_FLAG_SPEC);
380
+ return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase) ? flags : null;
381
+ }
382
+
383
+ /** `todo` without a command, or a group without a subcommand it has; null otherwise (a28). */
384
+ function explainMissingSubcommand(argv) {
385
+ if (argv.length === 0) {
386
+ return { pointer: '<command>', rule: 'subcommand_missing', available_commands: TODO_COMMAND_NAMES,
387
+ next_action: 'Name a todo command; for the overview of every plan run `lattice todo status --json`'
388
+ + ' (every command: `lattice todo --help`).' };
389
+ }
390
+ const group = TODO_SUBCOMMANDS[argv[0]];
391
+ if (group === undefined || group.names.includes(argv[1])) return null;
392
+ const missing = typeof argv[1] !== 'string' || argv[1].startsWith('--');
393
+ const head = [argv[0], group.example];
394
+ const { flags } = parseFlagMap(argv.slice(missing ? 1 : 2));
395
+ return { pointer: missing ? '<subcommand>' : argv[1], rule: missing ? 'subcommand_missing' : 'subcommand_unknown',
396
+ available_subcommands: group.names,
397
+ next_action: `Name one of ${group.names.join(', ')} after \`lattice todo ${argv[0]}\`, e.g.`
398
+ + ` \`${repairedCommand(head, TODO_FLAG_SPECS[head.join(' ')], flags)}\`.` };
336
399
  }
337
400
 
338
- /** A todo write's argument refusal names the flag, the rule and the command to run instead. */
401
+ /** A todo argument refusal names the flag, the rule and the command to run instead. */
339
402
  function explainArgumentRefusal(argv) {
340
- const head = argv[0] === 'dependency' ? argv.slice(0, 2) : argv.slice(0, 1);
403
+ const missingSubcommand = explainMissingSubcommand(argv);
404
+ if (missingSubcommand !== null) return missingSubcommand;
405
+ const head = GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
406
+ ? argv.slice(0, 2) : argv.slice(0, 1);
341
407
  const spec = TODO_FLAG_SPECS[head.join(' ')];
342
408
  if (spec === undefined) return {};
343
409
  const { flags } = parseFlagMap(argv.slice(head.length));
344
410
  const flagFailure = explainFlagCommand(argv, head, spec);
345
411
  if (flagFailure?.rule === 'flag_missing') {
346
- return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${FLAG_PLACEHOLDER[flagFailure.pointer.slice(2)] ?? '<value>'}: \`${repairedCommand(head, spec, flags)}\`.` };
412
+ const missing = flagFailure.pointer.slice(2);
413
+ const lists = { task: ` (task ids: \`lattice plan show ${flags.plan ?? '<plan>'} --json\`)` }[missing] ?? '';
414
+ return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${placeholder(missing)}${lists}: \`${repairedCommand(head, spec, flags)}\`.` };
415
+ }
416
+ if (flagFailure?.rule === 'flag_unknown') {
417
+ // a28: a flag the command does not take is named, with the flags it does take and a command that works.
418
+ const takes = spec.known.map((name) => `--${name}`).join(', ') || 'no flags';
419
+ const { [flagFailure.pointer.slice(2)]: _dropped, ...kept } = flags;
420
+ const onePlan = flagFailure.pointer === '--plan' && typeof flags.plan === 'string'
421
+ ? `; for one plan run \`lattice plan show ${flags.plan} --json\`` : '';
422
+ return { ...flagFailure, next_action: `${flagFailure.pointer} does not apply to \`lattice todo ${head.join(' ')}\``
423
+ + ` (it takes ${takes}): \`${repairedCommand(head, spec, kept)}\`${onePlan}.` };
347
424
  }
348
425
  if (flagFailure !== null) return flagFailure;
349
426
  for (const name of IDENTIFIER_FLAGS.filter((key) => spec.known.includes(key))) {
427
+ if (flags[name] === undefined && !spec.required.includes(name)) continue;
350
428
  if (!isTodoIdentifier(flags[name])) return { pointer: `--${name}`, rule: 'identifier_invalid', actual: flags[name] };
351
429
  }
430
+ if (argv[0] === 'note') {
431
+ const given = ['message', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
432
+ if (given.length === 0) {
433
+ return { pointer: '--message', rule: 'flag_missing',
434
+ next_action: `Add --message <text> (or --input <file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'message'] }, flags)}\`.` };
435
+ }
436
+ if (flags.supersedes !== undefined && !isTodoDigest(flags.supersedes)) {
437
+ return { pointer: '--supersedes', rule: 'digest_invalid', actual: flags.supersedes,
438
+ next_action: `Pass the note_digest of the note to replace (see \`lattice todo note list --plan ${flags.plan} --json\`).` };
439
+ }
440
+ if (given.length === 2) {
441
+ return { pointer: '--input', rule: 'flags_exclusive',
442
+ next_action: `Pass either --message or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
443
+ }
444
+ }
445
+ if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
446
+ const given = ['evidence', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
447
+ if (given.length === 0) {
448
+ return { pointer: '--evidence', rule: 'flag_missing',
449
+ next_action: `Add --evidence <file> (or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
450
+ }
451
+ if (given.length === 2) {
452
+ return { pointer: '--input', rule: 'flags_exclusive',
453
+ next_action: `Pass either --evidence or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
454
+ }
455
+ if (argv[1] === 'reject' && given[0] === 'evidence' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
456
+ return { pointer: '--reason', rule: 'flag_missing',
457
+ next_action: `A reject with --evidence needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
458
+ }
459
+ if (given[0] === 'input' && flags.reason !== undefined) {
460
+ return { pointer: '--reason', rule: 'flag_unknown',
461
+ next_action: `With --input the reason is inside the decision file; drop --reason: \`${repairedCommand(head, spec, { ...flags, reason: undefined })}\`.` };
462
+ }
463
+ }
464
+ for (const name of ['input', 'evidence']) {
465
+ if (spec.known.includes(name) && flags[name] !== undefined && !isAuthoringPathToken(flags[name])) {
466
+ return { pointer: `--${name}`, rule: 'path_token_invalid' };
467
+ }
468
+ }
352
469
  for (const name of ['override-reason', 'reason']) {
353
470
  if (spec.known.includes(name) && flags[name] !== undefined
354
471
  && !(typeof flags[name] === 'string' && flags[name].length > 0)) {
@@ -434,7 +551,8 @@ function selectNoteTask(member, requestedTaskId) {
434
551
  }
435
552
 
436
553
  async function readNoteTextInput(repoRoot, inputRef) {
437
- const located = await resolveAuthoringInputPath(repoRoot, inputRef, { inlineFlag: '--message' });
554
+ // a23: the text is stored in the journal, so (like plan input) a file outside the repo is read too.
555
+ const located = await resolveAuthoringInputPath(repoRoot, inputRef, { inlineFlag: '--message', allowOutsideRepo: true });
438
556
  const bytes = await readFile(located.absolute);
439
557
  if (bytes.length > MAX_NOTE_INPUT_BYTES) {
440
558
  throw new TodoStoreError('INPUT_TOO_LARGE', 'note_input_too_large');
@@ -567,23 +685,30 @@ function looksLikeEvidenceDescriptor(value) {
567
685
  return value !== null && typeof value === 'object' && !Array.isArray(value);
568
686
  }
569
687
 
570
- function writeEvidenceBlob(repoRoot, bytes, blobPath) {
688
+ function writeEvidenceBlob(repoRoot, bytes, blobPath, write = true) {
571
689
  // worktree pathから作る証拠は`git add`と同じclean filterを通す。生のCRLF bytesを
572
690
  // そのままhashすると、commit先はLFへ正規化される一方、descriptorはdangling blobを
573
691
  // 指すため、commit後もhard検証を通せない。
574
- const oid = gitSync(['hash-object', '-w', `--path=${blobPath}`, '--stdin'], {
692
+ const oid = gitSync(['hash-object', ...(write ? ['-w'] : []), `--path=${blobPath}`, '--stdin'], {
575
693
  cwd: repoRoot, input: bytes, encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'],
576
694
  }).trim();
577
- const storedBytes = gitSync(['cat-file', 'blob', oid], {
578
- cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'],
579
- });
695
+ let storedBytes;
696
+ try {
697
+ storedBytes = gitSync(['cat-file', 'blob', oid], { cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'] });
698
+ } catch (error) {
699
+ // a23: a comparison-only hash writes nothing; content never stored has no digest to compare.
700
+ if (!write) return { git_blob_oid: oid, content_digest: null };
701
+ throw error;
702
+ }
580
703
  return {
581
704
  git_blob_oid: oid,
582
705
  content_digest: createHash('sha256').update(storedBytes).digest('hex'),
583
706
  };
584
707
  }
585
708
 
586
- async function resolveDoneEvidence({ repoRoot, evidenceRef, evidenceMessage, planKey, taskId }) {
709
+ async function resolveDoneEvidence({
710
+ repoRoot, evidenceRef, evidenceMessage, planKey, taskId, write = true, inlineFlag = null,
711
+ }) {
587
712
  if (typeof evidenceMessage === 'string') {
588
713
  const bytes = Buffer.from(evidenceMessage, 'utf8');
589
714
  const sourceDigest = createHash('sha256').update(bytes).digest('hex');
@@ -592,16 +717,16 @@ async function resolveDoneEvidence({ repoRoot, evidenceRef, evidenceMessage, pla
592
717
  evidence_id: evidenceIdFor(planKey, taskId),
593
718
  repo_id: 'self',
594
719
  path: evidencePath,
595
- ...writeEvidenceBlob(repoRoot, bytes, evidencePath),
720
+ ...writeEvidenceBlob(repoRoot, bytes, evidencePath, write),
596
721
  media_type: 'text/markdown',
597
722
  anchor_digest: null,
598
723
  };
599
- if (!validateEvidenceDescriptor(descriptor) || !isTodoRef(descriptor.path)) {
724
+ if (write && (!validateEvidenceDescriptor(descriptor) || !isTodoRef(descriptor.path))) {
600
725
  throw new TodoStoreError('INVALID_EVIDENCE', 'authored_evidence_descriptor_invalid');
601
726
  }
602
727
  return descriptor;
603
728
  }
604
- const located = await resolveAuthoringInputPath(repoRoot, evidenceRef, { inlineFlag: '--message' });
729
+ const located = await resolveAuthoringInputPath(repoRoot, evidenceRef, { inlineFlag });
605
730
  const bytes = await readFile(located.absolute);
606
731
  let text;
607
732
  try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
@@ -624,11 +749,11 @@ async function resolveDoneEvidence({ repoRoot, evidenceRef, evidenceMessage, pla
624
749
  evidence_id: evidenceIdFor(planKey, taskId),
625
750
  repo_id: 'self',
626
751
  path: located.inputRef,
627
- ...writeEvidenceBlob(repoRoot, bytes, located.inputRef),
752
+ ...writeEvidenceBlob(repoRoot, bytes, located.inputRef, write),
628
753
  media_type: mediaTypeFor(located.inputRef),
629
754
  anchor_digest: null,
630
755
  };
631
- if (!validateEvidenceDescriptor(descriptor)) {
756
+ if (write && !validateEvidenceDescriptor(descriptor)) {
632
757
  throw new TodoStoreError('INVALID_EVIDENCE', 'authored_evidence_descriptor_invalid');
633
758
  }
634
759
  return descriptor;
@@ -686,23 +811,13 @@ async function readStructureSetDraft(repoRoot, inputRef) {
686
811
  }
687
812
 
688
813
  /**
689
- * gate_readyの札が出た理由と次の一歩をtypedに言う(ADR 0148裁定8)。
690
- *
691
- * 0.36.0で入れた終端監査gate(ADR 0147)は、これから終わる工程だけでなく過去に完了した
692
- * 工程まで監査待ちにしてしまっていた——原因を言わないgateは、なぜ止まっているかを
693
- * 説明しないのと同じなので、ここでその経緯を明示する。次の一歩は2択で書く:
694
- * 今から監査する(review→accept)か、監査せず歴史として閉じる(close-unaudited、
695
- * 複数plan一括ならbaseline)か。
814
+ * gate_readyの次の一歩を1行で言う(ADR 0148裁定8・a22)。全taskが終わった席には、軽い出口
815
+ * (監査せず閉じるclose-unaudited)を先に、監査する道(review→accept)を後に示す。経緯の説明は載せない。
696
816
  */
697
817
  function auditGateGuidance(planKey, phaseId) {
698
- return '全ToDoがdoneになり監査待ち(gate_ready)。0.36.0で入れた終端監査gateは、'
699
- + 'これから終わる工程だけでなく過去に完了した工程まで監査待ちにしてしまっていた'
700
- + '(ADR 0148で修正)。今から監査するなら: '
701
- + `todo phase review --plan ${planKey} --phase ${phaseId} --reason <text> → `
702
- + `todo phase accept --plan ${planKey} --phase ${phaseId} --input <file>。`
703
- + '監査せず歴史として閉じるなら: '
704
- + `todo phase close-unaudited --plan ${planKey} --phase ${phaseId} --reason <text>`
705
- + '(複数planをまとめて畳むなら todo phase baseline --reason <text> [--except <plan_key>]...)。';
818
+ const target = `--plan ${planKey} --phase ${phaseId}`;
819
+ return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
820
+ + `(監査するなら lattice todo phase review ${target} --reason <text> → accept ${target} --input <file>)`;
706
821
  }
707
822
 
708
823
  /**
@@ -766,6 +881,8 @@ async function mutate({
766
881
  ? null
767
882
  : await resolveDoneEvidence({
768
883
  repoRoot, evidenceRef, evidenceMessage, planKey, taskId,
884
+ // Only an authored done takes --message as the inline alternative to --evidence.
885
+ inlineFlag: kind === 'done' && payload === 'authored' ? '--message' : null,
769
886
  });
770
887
  const testResult = testResultRef === null ? null : await readTestResultInput(repoRoot, testResultRef);
771
888
  const materializedEvidence = typeof evidenceMessage === 'string'
@@ -851,8 +968,21 @@ const UNCHANGED_WHEN = {
851
968
  retire: ({ status }) => status === 'retired',
852
969
  };
853
970
 
854
- /** Unchanged result, or null when the transition must go to the append path. */
855
- function unchangedTransition(store, { env, planKey, taskId, kind, notRecorded = [] }) {
971
+ // a23: what a repeated transition drops (given content differing from the record), and how to keep it.
972
+ const NOT_RECORDED_NEXT = {
973
+ done: (on, flags) => `was already done; ${flags} not recorded. Keep the text with \`lattice todo note ${on} --message <text>\`,`
974
+ + ` or replace the record: \`lattice todo reopen ${on} --reason <text>\`, then start and done again.`,
975
+ block: (on, flags) => `was already blocked; ${flags} not recorded. Keep the text with \`lattice todo note ${on} --message <text>\`,`
976
+ + ` or record the new reason: \`lattice todo unblock ${on}\`, then \`lattice todo block ${on} --reason <text>\`.`,
977
+ retire: (on, flags) => `was already retired (permanent); ${flags} not recorded.`
978
+ + ` Keep the text with \`lattice todo note ${on} --message <text>\`.`,
979
+ };
980
+
981
+ /**
982
+ * Unchanged result, or null when the transition must go to the append path.
983
+ * `dropped(recordedEvent)` returns the given flags whose content the record does not hold.
984
+ */
985
+ async function unchangedTransition(store, { env, planKey, taskId, kind, dropped = async () => [] }) {
856
986
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
857
987
  const matches = member?.tasks.filter(({ task_id: current }) => current.toLowerCase() === taskId.toLowerCase()) ?? [];
858
988
  // Unknown or ambiguous plan/task: the append path keeps Store's refusal.
@@ -863,18 +993,17 @@ function unchangedTransition(store, { env, planKey, taskId, kind, notRecorded =
863
993
  // Another seat's in-progress task is not this seat's repeated start; keep the task_state refusal.
864
994
  if (kind === 'start' && recorded?.actor?.agent !== resolveTodoActor(env).agent) return null;
865
995
  const shown = recorded ?? events.findLast((event) => event.task_id === state.task_id) ?? events.at(-1);
996
+ const notRecorded = await dropped(recorded);
866
997
  const result = {
867
998
  schema: 'lattice.todo_mutation_result.v2',
868
999
  project_id: member.plan.project_id, plan_key: planKey, plan_version: member.plan.plan_version,
869
1000
  task_id: state.task_id, kind, sequence: shown.sequence, event_digest: shown.event_digest,
870
1001
  journal_head_digest: events.at(-1).event_digest, snapshot_digest: member.snapshot.snapshot_digest,
871
1002
  status: state.status, advisory: null, unchanged: true,
872
- // a18: a repeated done appends nothing, so say which given content was not recorded.
1003
+ // a18: a repeated transition appends nothing, so say which given content was not recorded.
873
1004
  ...(notRecorded.length === 0 ? {} : {
874
1005
  not_recorded: notRecorded,
875
- next_action: `${planKey}/${state.task_id} was already done; ${notRecorded.join(', ')} not recorded.`
876
- + ` Keep the text with \`lattice todo note --plan ${planKey} --task ${state.task_id} --message <text>\`,`
877
- + ` or replace the record: \`lattice todo reopen --plan ${planKey} --task ${state.task_id} --reason <text>\`, then start and done again.`,
1006
+ next_action: `${planKey}/${state.task_id} ${NOT_RECORDED_NEXT[kind](`--plan ${planKey} --task ${state.task_id}`, notRecorded.join(', '))}`,
878
1007
  }),
879
1008
  result_digest: '',
880
1009
  };
@@ -885,7 +1014,46 @@ function unchangedTransition(store, { env, planKey, taskId, kind, notRecorded =
885
1014
  /** block/unblock/done: an unchanged no-op first, else the append path. */
886
1015
  async function mutateUnlessUnchanged(options) {
887
1016
  const store = await readTodoStore({ repoRoot: options.repoRoot });
888
- return unchangedTransition(store, options) ?? options.action();
1017
+ return (await unchangedTransition(store, options)) ?? options.action();
1018
+ }
1019
+
1020
+ /** a23: block/retire drop a --reason that differs from the recorded one. */
1021
+ const reasonDropped = (reason) => async (recorded) => (recorded?.payload?.reason === reason ? [] : ['--reason']);
1022
+
1023
+ /** The evidence a `todo done` records: the message (naming the file when both are given), the file, or the default text. */
1024
+ async function doneEvidenceInput({ repoRoot, flags, write = true }) {
1025
+ const hasEvidence = isAuthoringPathToken(flags.evidence);
1026
+ const hasMessage = typeof flags.message === 'string' && flags.message.length > 0;
1027
+ if (hasEvidence && hasMessage) {
1028
+ // The message is the record; it names the resolved file so nothing given is lost.
1029
+ const file = await resolveDoneEvidence({
1030
+ repoRoot, evidenceRef: flags.evidence, evidenceMessage: null, planKey: flags.plan, taskId: flags.task,
1031
+ write, inlineFlag: '--message',
1032
+ });
1033
+ return { evidenceRef: null, evidenceMessage: `${flags.message}\n\nevidence: ${file.repo_id}:${file.path}`
1034
+ + ` (git blob ${file.git_blob_oid}, sha256 ${file.content_digest})\n` };
1035
+ }
1036
+ if (hasEvidence) return { evidenceRef: flags.evidence, evidenceMessage: null };
1037
+ return { evidenceRef: null, evidenceMessage: hasMessage ? flags.message : DONE_WITHOUT_EVIDENCE_MESSAGE };
1038
+ }
1039
+
1040
+ /**
1041
+ * a23: the content flags of a repeated done that the recorded done does not hold. Compared by git blob,
1042
+ * hashed without writing; a file that cannot be read counts as differing.
1043
+ */
1044
+ async function doneDropped({ repoRoot, flags, recorded }) {
1045
+ const given = (names) => names.filter((name) => flags[name] !== undefined).map((name) => `--${name}`);
1046
+ const sameEvidence = async () => {
1047
+ const evidence = await resolveDoneEvidence({ repoRoot, ...await doneEvidenceInput({ repoRoot, flags, write: false }),
1048
+ planKey: flags.plan, taskId: flags.task, write: false });
1049
+ return evidence.git_blob_oid === recorded?.payload?.evidence?.git_blob_oid;
1050
+ };
1051
+ const sameTestResult = async () => (await readTestResultInput(repoRoot, flags['test-result'])) === recorded?.payload?.test_result;
1052
+ const differs = async (same) => { try { return !(await same()); } catch { return true; } };
1053
+ return [
1054
+ ...(given(['message', 'evidence']).length > 0 && await differs(sameEvidence) ? given(['message', 'evidence']) : []),
1055
+ ...(flags['test-result'] !== undefined && await differs(sameTestResult) ? ['--test-result'] : []),
1056
+ ];
889
1057
  }
890
1058
 
891
1059
  /** a18: the live tasks with an edge (plan, join or ledger) from the task being retired, sorted. */
@@ -916,7 +1084,9 @@ async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
916
1084
  // 未知のplan/taskはStoreの既存の拒否をそのまま通す。
917
1085
  return mutate({ repoRoot, env, planKey, taskId, kind: 'retire', payload: { reason }, evidenceRef: null });
918
1086
  }
919
- if (state.status === 'retired') return unchangedTransition(store, { env, planKey, taskId, kind: 'retire' });
1087
+ if (state.status === 'retired') {
1088
+ return unchangedTransition(store, { env, planKey, taskId, kind: 'retire', dropped: reasonDropped(reason) });
1089
+ }
920
1090
  const dependents = retireDependents(store, member, taskId);
921
1091
  const append = async () => {
922
1092
  let result;
@@ -992,7 +1162,8 @@ async function startStructureContext({ repoRoot, store, planKey, taskId }) {
992
1162
 
993
1163
  function designMemoProjection(task) {
994
1164
  if (typeof task.design_memo === 'string') {
995
- return { status: 'available', markdown: task.design_memo, prompt: TODO_DESIGN_MEMO_PROMPT };
1165
+ // 書かれたmemo(NO_PLANを含む)には促しを繰り返さない(a27)。促しは欠けたmemoにだけ要る。
1166
+ return { status: 'available', markdown: task.design_memo, prompt: null };
996
1167
  }
997
1168
  return { status: 'missing_legacy', markdown: null, prompt: TODO_DESIGN_MEMO_PROMPT };
998
1169
  }
@@ -1116,7 +1287,7 @@ async function startTask({
1116
1287
  });
1117
1288
  }
1118
1289
  const resolvedTaskId = readyTask?.task_id ?? taskMatches[0].task_id;
1119
- const unchanged = unchangedTransition(store, { env, planKey, taskId: resolvedTaskId, kind: 'start' });
1290
+ const unchanged = await unchangedTransition(store, { env, planKey, taskId: resolvedTaskId, kind: 'start' });
1120
1291
  if (unchanged !== null) return unchanged;
1121
1292
  // noteはjournal appendより前に読む。壊れていてもstartは通す(ADR 0166 / 0181)。
1122
1293
  let noteContext;
@@ -1431,16 +1602,9 @@ async function dependencyConnect(options) {
1431
1602
  || !tasks.some(({ task_id: id }) => id === toTaskId) || fromTaskId === toTaskId) {
1432
1603
  return dependencyConnectLedger(options);
1433
1604
  }
1434
- const from = dependencyRef(store, fromPlanKey, fromTaskId);
1435
- const to = dependencyRef(store, toPlanKey, toTaskId);
1436
- if (samePlanEdge(member, fromTaskId, toTaskId)) {
1437
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'dependency_already_in_plan', undefined, { from, to });
1438
- }
1439
- // 以前の同一plan接続で台帳に生きている辺を、本体へ二重に足さない(台帳経路と同じ拒否)。
1440
- if (projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1441
- dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1442
- && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId))) {
1443
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate', undefined, { from, to });
1605
+ // a28: an edge already in the plan body or the ledger is the requested state; nothing is added twice.
1606
+ if (samePlanEdge(member, fromTaskId, toTaskId) || liveLedgerEdge(store, options)) {
1607
+ return dependencyUnchanged(store, options);
1444
1608
  }
1445
1609
  if (member.tasks.find(({ task_id: id }) => id === toTaskId)?.status === 'done') {
1446
1610
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_target_terminal');
@@ -1452,6 +1616,28 @@ async function dependencyConnect(options) {
1452
1616
  repoRoot, env, store, member, operation: 'connect', fromTaskId, toTaskId, reason });
1453
1617
  }
1454
1618
 
1619
+ /** A live ledger edge with these endpoints (cross-plan, or an earlier same-plan connect). */
1620
+ function liveLedgerEdge(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1621
+ return projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1622
+ dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1623
+ && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId));
1624
+ }
1625
+
1626
+ /** a28: connect of an existing edge succeeds unchanged, like a repeated done/block/retire (a12). */
1627
+ function dependencyUnchanged(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1628
+ const from = { project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId };
1629
+ const to = { project_id: store.project_id, plan_key: toPlanKey, task_id: toTaskId };
1630
+ const result = {
1631
+ schema: 'lattice.todo_dependency_unchanged_result.v1', project_id: store.project_id,
1632
+ operation: 'connect', from, to, unchanged: true,
1633
+ next_action: `${fromPlanKey}/${fromTaskId} -> ${toPlanKey}/${toTaskId} already exists; nothing was recorded`
1634
+ + ` (see \`lattice plan show ${toPlanKey} --json\`).`,
1635
+ result_digest: '',
1636
+ };
1637
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1638
+ return result;
1639
+ }
1640
+
1455
1641
  /** 台帳(cross_plan_dependency event)への接続。plan跨ぎの本線。 */
1456
1642
  async function dependencyConnectLedger({
1457
1643
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
@@ -1468,6 +1654,7 @@ async function dependencyConnectLedger({
1468
1654
  };
1469
1655
  const source = dependencyMember(fromPlanKey);
1470
1656
  const target = dependencyMember(toPlanKey);
1657
+ const endpoints = { fromPlanKey, fromTaskId, toPlanKey, toTaskId };
1471
1658
  if (!source.plan.tasks.some(({ task_id: taskId }) => taskId === fromTaskId)) {
1472
1659
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_task_not_found', undefined, {
1473
1660
  plan_key: fromPlanKey, task_id: fromTaskId,
@@ -1478,6 +1665,7 @@ async function dependencyConnectLedger({
1478
1665
  plan_key: toPlanKey, task_id: toTaskId,
1479
1666
  });
1480
1667
  }
1668
+ if (liveLedgerEdge(store, endpoints)) return dependencyUnchanged(store, endpoints);
1481
1669
  const from = {
1482
1670
  project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId,
1483
1671
  expected_topology_digest: source.plan.topology_digest,
@@ -4179,9 +4367,9 @@ async function verify({ repoRoot, requestedPlanKey }) {
4179
4367
  meaning: 'source_inventory_verification_state',
4180
4368
  lifecycle_blocked: false,
4181
4369
  dashboard_visibility_blocked: false,
4182
- // 席の経路は軽い改訂(plan revise)。反映後のplanはreconciledになる。
4183
- schema_command: reconciled ? null : 'lattice plan revise --schema --json',
4184
- next_action: reconciled ? null : 'lattice plan revise --input <revision.json> --json',
4370
+ // どちらの状態も何もしなくてよい(a22)。値はnoneに揃える(a27)。次の軽い改訂がreconciledにする。
4371
+ schema_command: null,
4372
+ next_action: 'none',
4185
4373
  },
4186
4374
  };
4187
4375
  });
@@ -4216,7 +4404,7 @@ async function verify({ repoRoot, requestedPlanKey }) {
4216
4404
  // ここへ届くのは検証が通った結果だけ。注意が要るのはsnapshot古さとcommit前の証拠)。
4217
4405
  function verifyVerdictLine(result) {
4218
4406
  const members = result.verified_members.map((member) => `${member.plan_key} ${member.reconciliation_state}${
4219
- member.reconciliation_state === 'reconciled' ? '' : ', lifecycle not blocked'}`);
4407
+ member.reconciliation_state === 'reconciled' ? '' : ', nothing to do'}`);
4220
4408
  const notes = [];
4221
4409
  if (result.snapshot_stale) notes.push('snapshot stale');
4222
4410
  if (result.uncommitted_evidence.length > 0) {
@@ -4345,10 +4533,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4345
4533
  return { schema: 'lattice.todo_dashboard_ensure_result.v1',
4346
4534
  ensured: ensured !== null, activity: ensured };
4347
4535
  };
4348
- } else if (argv.length === 6 && argv[0] === 'show'
4349
- && argv[1] === '--plan' && isTodoIdentifier(argv[2])
4350
- && argv[3] === '--task' && isTodoIdentifier(argv[4]) && argv[5] === '--json') {
4351
- action = (repoRoot) => todoDetail({ repoRoot, planKey: argv[2], taskId: argv[4] });
4536
+ } else if (argv[0] === 'show' && readFlags(argv, ['show']) !== null) {
4537
+ const flags = readFlags(argv, ['show']);
4538
+ action = (repoRoot) => todoDetail({ repoRoot, planKey: flags.plan, taskId: flags.task });
4352
4539
  } else if ((argv.length === 1 && argv[0] === 'bindings')
4353
4540
  || (argv.length === 2 && argv[0] === 'bindings' && argv[1] === '--json')) {
4354
4541
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: null });
@@ -4357,10 +4544,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4357
4544
  && (argv.length === 3 || argv[3] === '--json')) {
4358
4545
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: argv[2] });
4359
4546
  } else if (argv[0] === 'note' && argv[1] !== 'list') {
4360
- const flags = matchFlagCommand(argv, ['note'], {
4361
- known: ['plan', 'task', 'message', 'input', 'supersedes'],
4362
- required: ['plan'],
4363
- });
4547
+ const flags = matchFlagCommand(argv, ['note'], NOTE_FLAG_SPEC);
4364
4548
  const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
4365
4549
  const hasInput = isAuthoringPathToken(flags?.input);
4366
4550
  if (flags !== null && isTodoIdentifier(flags.plan)
@@ -4375,13 +4559,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4375
4559
  supersedes: flags.supersedes ?? null,
4376
4560
  });
4377
4561
  }
4378
- } else if (argv.length === 5 && argv[0] === 'note' && argv[1] === 'list'
4379
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4380
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: null });
4381
- } else if (argv.length === 7 && argv[0] === 'note' && argv[1] === 'list'
4382
- && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4383
- && argv[4] === '--task' && isTodoIdentifier(argv[5]) && argv[6] === '--json') {
4384
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: argv[5] });
4562
+ } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
4563
+ const flags = readFlags(argv, ['note', 'list']);
4564
+ action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
4385
4565
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
4386
4566
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
4387
4567
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
@@ -4406,9 +4586,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4406
4586
  toPlanKey: flags['to-plan'], toTaskId: flags['to-task'], reason: flags.reason,
4407
4587
  });
4408
4588
  } else if (argv[0] === 'independence' && argv[1] === 'compile') {
4409
- const flags = matchFlagCommand(argv, ['independence', 'compile'], {
4410
- known: ['plan', 'input'], required: ['plan', 'input'],
4411
- });
4589
+ const flags = matchFlagCommand(argv, ['independence', 'compile'], TODO_FLAG_SPECS['independence compile']);
4412
4590
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4413
4591
  action = (repoRoot) => independenceCompile({
4414
4592
  repoRoot, planKey: flags.plan, inputRef: flags.input,
@@ -4452,11 +4630,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4452
4630
  } else if (argv.length === 5 && argv[0] === 'structure' && argv[1] === 'finalize'
4453
4631
  && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4454
4632
  action = (repoRoot) => structureFinalize({ repoRoot, env, planKey: argv[3] });
4455
- } else if (argv.length === 2 && argv[0] === 'structure' && argv[1] === '--json') {
4456
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: null });
4457
- } else if (argv.length === 4 && argv[0] === 'structure'
4458
- && argv[1] === '--plan' && isTodoIdentifier(argv[2]) && argv[3] === '--json') {
4459
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: argv[2] });
4633
+ } else if (argv[0] === 'structure' && readFlags(argv, ['structure']) !== null) {
4634
+ const flags = readFlags(argv, ['structure']);
4635
+ action = (repoRoot) => structure({ repoRoot, requestedPlanKey: flags.plan ?? null });
4460
4636
  } else if ((argv.length === 1 && argv[0] === 'independence')
4461
4637
  || (argv.length === 2 && argv[0] === 'independence' && argv[1] === '--json')) {
4462
4638
  action = (repoRoot) => independence({ repoRoot, requestedPlanKey: null });
@@ -4544,9 +4720,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4544
4720
  action = (repoRoot) => revise({ repoRoot, env, planKey: flags.plan, inputRef: flags.input });
4545
4721
  }
4546
4722
  } else if (argv[0] === 'split') {
4547
- const flags = matchFlagCommand(argv, ['split'], {
4548
- known: ['plan', 'input'], required: ['plan', 'input'],
4549
- });
4723
+ const flags = matchFlagCommand(argv, ['split'], TODO_FLAG_SPECS.split);
4550
4724
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4551
4725
  action = (repoRoot) => splitTodo({ repoRoot, env, planKey: flags.plan, inputRef: flags.input });
4552
4726
  }
@@ -4567,12 +4741,11 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4567
4741
  } else if (argv.length === 4 && argv[0] === 'phase' && argv[1] === 'status'
4568
4742
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])) {
4569
4743
  action = (repoRoot) => phaseStatus({ repoRoot, planKey: argv[3] });
4570
- } else if (argv.length === 8 && argv[0] === 'phase' && argv[1] === 'review'
4571
- && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4572
- && argv[4] === '--phase' && isTodoIdentifier(argv[5])
4573
- && argv[6] === '--reason' && argv[7].length > 0) {
4574
- action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: argv[3], phaseId: argv[5],
4575
- kind: 'phase_review', payload: { reason: argv[7] } });
4744
+ } else if (argv[0] === 'phase' && argv[1] === 'review'
4745
+ && phaseReasonFlags(argv) !== null) {
4746
+ const flags = phaseReasonFlags(argv);
4747
+ action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
4748
+ kind: 'phase_review', payload: { reason: flags.reason } });
4576
4749
  } else if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
4577
4750
  const outcome = argv[1];
4578
4751
  const flags = matchFlagCommand(argv, ['phase', outcome], {
@@ -4592,19 +4765,15 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4592
4765
  outcome, evidenceRef: flags.evidence, reason: flags.reason ?? null,
4593
4766
  });
4594
4767
  }
4595
- } else if ((argv.length === 8 || argv.length === 10) && argv[0] === 'phase'
4596
- && argv[1] === 'reopen' && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4597
- && argv[4] === '--phase' && isTodoIdentifier(argv[5])
4598
- && argv[6] === '--reason' && argv[7].length > 0
4599
- && (argv.length === 8 || (argv[8] === '--override-reason' && argv[9].length > 0))) {
4600
- action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: argv[3], phaseId: argv[5],
4601
- kind: 'phase_reopen', payload: { reason: argv[7], override_reason: argv[9] ?? null } });
4602
- } else if (argv.length === 8 && argv[0] === 'phase' && argv[1] === 'close-unaudited'
4603
- && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4604
- && argv[4] === '--phase' && isTodoIdentifier(argv[5])
4605
- && argv[6] === '--reason' && argv[7].length > 0) {
4606
- action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: argv[3], phaseId: argv[5],
4607
- kind: 'phase_close_unaudited', payload: { reason: argv[7] } });
4768
+ } else if (argv[0] === 'phase' && argv[1] === 'reopen' && phaseReopenFlags(argv) !== null) {
4769
+ const flags = phaseReopenFlags(argv);
4770
+ action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
4771
+ kind: 'phase_reopen', payload: { reason: flags.reason, override_reason: flags['override-reason'] ?? null } });
4772
+ } else if (argv[0] === 'phase' && argv[1] === 'close-unaudited'
4773
+ && phaseReasonFlags(argv) !== null) {
4774
+ const flags = phaseReasonFlags(argv);
4775
+ action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
4776
+ kind: 'phase_close_unaudited', payload: { reason: flags.reason } });
4608
4777
  } else if (argv.length >= 4 && argv[0] === 'phase' && argv[1] === 'baseline'
4609
4778
  && argv[2] === '--reason' && argv[3].length > 0
4610
4779
  && parseBaselineExceptFlags(argv.slice(4)) !== null) {
@@ -4629,36 +4798,17 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4629
4798
  }
4630
4799
  } else if (argv[0] === 'done') {
4631
4800
  const flags = matchFlagCommand(argv, ['done'], DONE_FLAG_SPEC);
4632
- const hasEvidence = isAuthoringPathToken(flags?.evidence);
4633
- const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
4634
4801
  // u03 A58: both, one or neither of --evidence/--message is accepted.
4635
4802
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4636
- && (flags.evidence === undefined || hasEvidence)
4803
+ && (flags.evidence === undefined || isAuthoringPathToken(flags.evidence))
4637
4804
  && (flags['test-result'] === undefined || isAuthoringPathToken(flags['test-result']))) {
4638
4805
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4639
- kind: 'done', notRecorded: ['message', 'evidence', 'test-result']
4640
- .filter((name) => flags[name] !== undefined).map((name) => `--${name}`),
4641
- action: async () => {
4642
- let evidenceMessage = hasMessage ? flags.message : null;
4643
- if (hasEvidence && hasMessage) {
4644
- // The message is the record; it names the resolved file so nothing given is lost.
4645
- const file = await resolveDoneEvidence({
4646
- repoRoot, evidenceRef: flags.evidence, evidenceMessage: null,
4647
- planKey: flags.plan, taskId: flags.task,
4648
- });
4649
- evidenceMessage = `${flags.message}\n\nevidence: ${file.repo_id}:${file.path}`
4650
- + ` (git blob ${file.git_blob_oid}, sha256 ${file.content_digest})\n`;
4651
- } else if (!hasEvidence && !hasMessage) {
4652
- evidenceMessage = DONE_WITHOUT_EVIDENCE_MESSAGE;
4653
- }
4654
- return mutate({
4655
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4656
- kind: 'done', payload: 'authored',
4657
- evidenceRef: evidenceMessage === null ? flags.evidence : null,
4658
- evidenceMessage,
4659
- testResultRef: flags['test-result'] ?? null,
4660
- });
4661
- } });
4806
+ kind: 'done', dropped: (recorded) => doneDropped({ repoRoot, flags, recorded }),
4807
+ action: async () => mutate({
4808
+ repoRoot, env, planKey: flags.plan, taskId: flags.task, kind: 'done', payload: 'authored',
4809
+ ...await doneEvidenceInput({ repoRoot, flags }),
4810
+ testResultRef: flags['test-result'] ?? null,
4811
+ }) });
4662
4812
  }
4663
4813
  }
4664
4814
  if (action === null && argv[0] === 'retract') {
@@ -4672,7 +4822,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4672
4822
  const flags = matchFlagCommand(argv, ['block'], TODO_FLAG_SPECS.block);
4673
4823
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4674
4824
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4675
- kind: 'block', action: () => mutate({
4825
+ kind: 'block', dropped: reasonDropped(flags.reason), action: () => mutate({
4676
4826
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4677
4827
  kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
4678
4828
  }) });
@@ -4695,9 +4845,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4695
4845
  }) });
4696
4846
  }
4697
4847
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
4698
- const flags = matchFlagCommand(argv, ['evidence', 'promote'], {
4699
- known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'],
4700
- });
4848
+ const flags = matchFlagCommand(argv, ['evidence', 'promote'], TODO_FLAG_SPECS['evidence promote']);
4701
4849
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4702
4850
  && isAuthoringPathToken(flags.evidence)) {
4703
4851
  action = (repoRoot) => mutate({