@quolu/lattice 0.83.0 → 0.84.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/todo-cli.mjs CHANGED
@@ -1,6 +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
5
  import { readTaskBackchainContext } from './plan-backchain.mjs';
5
6
  import { gitSync } from './git-process.mjs';
6
7
  import { createHash } from 'node:crypto';
@@ -10,11 +11,15 @@ import {
10
11
  import path from 'node:path';
11
12
  import { fileURLToPath } from 'node:url';
12
13
  import {
14
+ explainFlagCommand,
13
15
  isAuthoringPathToken,
14
16
  matchFlagCommand,
17
+ parseFlagMap,
15
18
  parseAuthoringJson,
16
19
  readAuthoringJsonFile,
20
+ repairAuthoringArtifact,
17
21
  resolveAuthoringInputPath,
22
+ resolveTodoActor,
18
23
  } from './todo-authoring-input.mjs';
19
24
 
20
25
  import {
@@ -38,11 +43,10 @@ import {
38
43
  ensureTodoDashboardActivity,
39
44
  removeTodoDashboardProject,
40
45
  } from './todo-dashboard-registry.mjs';
41
- import { readOrCreateTerminalIdSync, terminalPublicLabel } from './terminal-identity.mjs';
42
46
  import { readProjectExternalPane, readRegisteredProjectId, resolveProjectIdentity } from './project-identity.mjs';
43
47
  import { layoutTodoGantt } from './todo-gantt-layout.mjs';
44
48
  import { TODO_GANTT_SCOPES } from './todo-gantt-scope.mjs';
45
- import { loadTodoGanttPresentation } from './todo-gantt-presentation.mjs';
49
+ import { loadTodoGanttPresentation, projectTodoGanttPresentation } from './todo-gantt-presentation.mjs';
46
50
  import { loadTodoStructurePresentation } from './todo-structure-presentation.mjs';
47
51
  import { startTodoGanttLiveServer } from './todo-gantt-live.mjs';
48
52
  import {
@@ -64,11 +68,13 @@ import {
64
68
  createTodoStoreWriter,
65
69
  TodoStoreError,
66
70
  isPhaselessTodoPlanSchema,
71
+ isTodoEvidenceUncommitted,
67
72
  projectTodoCrossPlanDependencies,
68
73
  TERMINAL_AUDIT_PHASE_ID,
69
74
  todoPhaseDefinitions,
70
75
  readTodoIndependenceArtifact,
71
76
  readTodoSeamProposalArtifact,
77
+ predecessorSourceInventory,
72
78
  readTodoStore,
73
79
  readTodoStructureBinding,
74
80
  readTodoStructureRealizationChain,
@@ -142,7 +148,6 @@ import {
142
148
  TodoIndependenceError,
143
149
  } from './todo-independence.mjs';
144
150
  import {
145
- independenceStartRefusal,
146
151
  selectIndependenceGuidance,
147
152
  selectWitnessScaffoldGuidance,
148
153
  selectSeamProposalGuidance,
@@ -166,7 +171,7 @@ import {
166
171
  validateWitnessDraft,
167
172
  } from './witness-scaffold.mjs';
168
173
  import {
169
- explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
174
+ completePhaseTodoRevision, explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
170
175
  parseTodoSourceRef, todoLegacyReconciliationDigest, validatePhaseTodoRevision,
171
176
  validateTodoRevision, validateTodoRevisionSet,
172
177
  } from './todo-revision.mjs';
@@ -188,11 +193,8 @@ import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
188
193
  const CLI_ERROR_SCHEMA = 'lattice.cli_error.v2';
189
194
  const DEFAULT_GANTT_SCOPE = 'live';
190
195
  const MAX_NOTE_INPUT_BYTES = 16_384;
191
- const ACTOR_ENV_KEYS = Object.freeze([
192
- 'LATTICE_TODO_ACTOR_HOST',
193
- 'LATTICE_TODO_ACTOR_SESSION',
194
- 'LATTICE_TODO_ACTOR_AGENT',
195
- ]);
196
+ /** u03 A58: `todo done` without --evidence/--message records this text as its evidence. */
197
+ const DONE_WITHOUT_EVIDENCE_MESSAGE = '証拠の指定なしで完了した。\n';
196
198
 
197
199
  /**
198
200
  * `revise` / `revise-set` / `revise-phase` / `migrate`が配布する名前付き入力契約のJSON
@@ -222,20 +224,29 @@ async function runTodoSchemaCommand(command, stdout) {
222
224
  stdout.write(`${JSON.stringify(schema)}\n`);
223
225
  }
224
226
 
225
- function typedFailure(stderr, error) {
227
+ function typedFailure(stderr, error, context = {}) {
226
228
  const payload = {
227
229
  schema: CLI_ERROR_SCHEMA,
228
230
  code: error.code,
229
231
  message: error.message,
232
+ detail: withRefusalGuidance(error, context),
230
233
  };
231
- if (error.detail !== null && typeof error.detail === 'object'
232
- && !Array.isArray(error.detail) && Object.keys(error.detail).length > 0) {
233
- payload.detail = error.detail;
234
- }
235
234
  stderr.write(`${JSON.stringify(payload)}\n`);
236
235
  return 1;
237
236
  }
238
237
 
238
+ /** What the printers need to name a concrete repair: the command and the --plan/--task the caller typed. */
239
+ function guidanceContext(argv) {
240
+ const { flags } = parseFlagMap(argv.slice(1));
241
+ return {
242
+ family: 'todo',
243
+ command: typeof argv[0] === 'string' ? argv[0] : null,
244
+ plan: typeof flags.plan === 'string' ? flags.plan : undefined,
245
+ task: typeof flags.task === 'string' ? flags.task : undefined,
246
+ flags,
247
+ };
248
+ }
249
+
239
250
  /**
240
251
  * An error that reached here is, by definition, one none of the typed
241
252
  * TodoStoreError/TypeError branches recognized — the one case where the
@@ -265,12 +276,40 @@ const TODO_COMMAND_NAMES = Object.freeze([
265
276
  'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
266
277
  ]);
267
278
 
268
- function typedArgumentFailure(stderr, code, message, detail) {
269
- const payload = { schema: CLI_ERROR_SCHEMA, code, message, detail };
279
+ function typedArgumentFailure(stderr, code, message, detail, context = {}) {
280
+ const payload = {
281
+ schema: CLI_ERROR_SCHEMA, code, message,
282
+ detail: withRefusalGuidance({ code, message, detail }, context),
283
+ };
270
284
  stderr.write(`${JSON.stringify(payload)}\n`);
271
285
  return 2;
272
286
  }
273
287
 
288
+ const DONE_FLAG_SPEC = Object.freeze({
289
+ known: ['plan', 'task', 'evidence', 'test-result', 'message'],
290
+ required: ['plan', 'task'],
291
+ });
292
+
293
+ /** `todo done`のargument拒否を、直すflagと規則で名指す。他のcommandは従来どおり(空)。 */
294
+ function explainArgumentRefusal(argv) {
295
+ if (argv[0] !== 'done') return {};
296
+ const flagFailure = explainFlagCommand(argv, ['done'], DONE_FLAG_SPEC);
297
+ if (flagFailure !== null) return flagFailure;
298
+ const { flags } = parseFlagMap(argv.slice(1));
299
+ for (const name of ['plan', 'task']) {
300
+ if (!isTodoIdentifier(flags[name])) return { pointer: `--${name}`, rule: 'identifier_invalid', actual: flags[name] };
301
+ }
302
+ const hasMessage = typeof flags.message === 'string' && flags.message.length > 0;
303
+ if (flags.message !== undefined && !hasMessage) return { pointer: '--message', rule: 'flag_missing' };
304
+ if (flags.evidence !== undefined && !isAuthoringPathToken(flags.evidence)) {
305
+ return { pointer: '--evidence', rule: 'path_token_invalid' };
306
+ }
307
+ if (flags['test-result'] !== undefined && !isAuthoringPathToken(flags['test-result'])) {
308
+ return { pointer: '--test-result', rule: 'path_token_invalid' };
309
+ }
310
+ return {};
311
+ }
312
+
274
313
  function supportsAtomicStoreCommit(argv) {
275
314
  const command = argv[0];
276
315
  if (command === 'note') return argv[1] !== 'list';
@@ -292,7 +331,7 @@ function atomicStoreCommitUnsupported(stderr, argv) {
292
331
  'todo_command_does_not_mutate_only_the_store', {
293
332
  command: argv.slice(0, 3),
294
333
  next_action: 'remove_--commit-store_or_use_a_supported_todo_write_command',
295
- });
334
+ }, guidanceContext(argv));
296
335
  }
297
336
 
298
337
  function resolveRepoRoot(cwd) {
@@ -371,9 +410,30 @@ function within(root, candidate) {
371
410
  return candidate === root || candidate.startsWith(`${root}${path.sep}`);
372
411
  }
373
412
 
413
+ /**
414
+ * 証拠の無い判定`unknown_requires_evidence`は、証拠の無いcarry済みtaskと同じ`register_pending`
415
+ * (状態を取り込まない)として扱う(u03p A64)。機械が決められる答えを人に聞き直さない。
416
+ */
417
+ function defaultUnknownDispositions(extraction) {
418
+ const tasks = Array.isArray(extraction?.tasks) ? extraction.tasks : [];
419
+ const unknown = (task) => task?.disposition === 'unknown_requires_evidence';
420
+ if (!tasks.some(unknown)) return { extraction, defaultedPendingTaskIds: [] };
421
+ return {
422
+ extraction: repairAuthoringArtifact({ ...extraction, tasks: tasks.map((task) => (unknown(task)
423
+ ? { ...task, disposition: 'register_pending', start: null, completion: null } : task)) }),
424
+ defaultedPendingTaskIds: tasks.filter(unknown).map(({ task_id: taskId }) => taskId)
425
+ .filter(isTodoIdentifier).sort(),
426
+ };
427
+ }
428
+
374
429
  async function readMigrationInput(repoRoot, inputRef, { requireValid = true } = {}) {
375
430
  const extraction = await readAuthoringJsonFile(repoRoot, inputRef);
376
431
  if (!requireValid) return extraction;
432
+ assertValidMigrationExtraction(extraction);
433
+ return extraction;
434
+ }
435
+
436
+ function assertValidMigrationExtraction(extraction) {
377
437
  if (![TODO_EXTRACTION_SCHEMA_V3, TODO_EXTRACTION_SCHEMA_V4].includes(extraction?.schema)) {
378
438
  throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'todo_extraction_schema_unsupported', undefined, {
379
439
  expected: TODO_EXTRACTION_SCHEMA_V4,
@@ -398,7 +458,6 @@ async function readMigrationInput(repoRoot, inputRef, { requireValid = true } =
398
458
  };
399
459
  throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined, detail);
400
460
  }
401
- return extraction;
402
461
  }
403
462
 
404
463
  async function readRevisionInput(repoRoot, inputRef, {
@@ -406,8 +465,9 @@ async function readRevisionInput(repoRoot, inputRef, {
406
465
  invalidCode = 'REVISION_INVALID',
407
466
  invalidReason = 'revision_schema_or_digest_invalid',
408
467
  explain = explainTodoRevision,
468
+ complete = async (value) => value,
409
469
  } = {}) {
410
- const revision = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode });
470
+ const revision = await complete(await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode }));
411
471
  if (!validate(revision)) {
412
472
  const explained = explain === null ? null : explain(revision);
413
473
  throw new TodoStoreError(invalidCode, invalidReason, undefined,
@@ -562,47 +622,6 @@ async function readStructureSetDraft(repoRoot, inputRef) {
562
622
  });
563
623
  }
564
624
 
565
- function sanitizeActorIdentifier(raw, fallback) {
566
- const compact = String(raw ?? '').replace(/[^0-9A-Za-z._-]/gu, '-').replace(/^-+/u, '').slice(0, 128);
567
- return isTodoIdentifier(compact) ? compact : fallback;
568
- }
569
-
570
- /**
571
- * 名乗りの無い操作のhost(ADR 0197)。journalは公開repositoryへcommitされるので、OSのhost名は
572
- * 書かない——host名はOSが決めた自由文で、持ち主の名前を含むことがある。端末ごとの識別子から
573
- * 一方向に導いたlabelを使い、端末の区別は保つ。識別子を読めず作れない端末は`host`になる。
574
- */
575
- function defaultActorHost(env) {
576
- const terminalId = readOrCreateTerminalIdSync({ env });
577
- return terminalId === null ? 'host' : terminalPublicLabel(terminalId);
578
- }
579
-
580
- function mutationActor(env) {
581
- const provided = ACTOR_ENV_KEYS.map((key) => ({ key, value: env[key] }));
582
- const invalidEnvironment = provided
583
- .filter(({ value }) => typeof value === 'string' && value.length > 0 && !isTodoIdentifier(value))
584
- .map(({ key }) => key);
585
- if (invalidEnvironment.length > 0) {
586
- throw new TodoStoreError('ACTOR_UNRESOLVED', 'actor_environment_invalid', undefined, {
587
- required_environment: ACTOR_ENV_KEYS,
588
- missing_environment: [],
589
- invalid_environment: invalidEnvironment,
590
- next_action: 'set_required_actor_environment_and_retry',
591
- });
592
- }
593
- return {
594
- host: isTodoIdentifier(env.LATTICE_TODO_ACTOR_HOST)
595
- ? env.LATTICE_TODO_ACTOR_HOST
596
- : defaultActorHost(env),
597
- session: isTodoIdentifier(env.LATTICE_TODO_ACTOR_SESSION)
598
- ? env.LATTICE_TODO_ACTOR_SESSION
599
- : 'session',
600
- agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
601
- ? env.LATTICE_TODO_ACTOR_AGENT
602
- : sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'),
603
- };
604
- }
605
-
606
625
  /**
607
626
  * gate_readyの札が出た理由と次の一歩をtypedに言う(ADR 0148裁定8)。
608
627
  *
@@ -640,12 +659,46 @@ function terminalAuditDoneAdvisory(plan, phases) {
640
659
  };
641
660
  }
642
661
 
662
+ /** Task ids of a phase; a phaseless plan's implicit terminal-audit phase holds every task. */
663
+ function phaseTaskIds(plan, phaseId) {
664
+ return new Set(plan.tasks.filter((task) => isPhaselessTodoPlanSchema(plan.schema)
665
+ || task.phase_id === phaseId).map(({ task_id: id }) => id));
666
+ }
667
+
668
+ function staleAcceptanceGuidance(planKey, phaseId) {
669
+ return '受入後にこのphaseの工程が再開された。記録された受入は古い。受入し直すなら: '
670
+ + `todo phase reopen --plan ${planKey} --phase ${phaseId} --reason <text> → todo phase review → todo phase accept。`;
671
+ }
672
+
673
+ /**
674
+ * u03 A15: an accepted/closed_unaudited phase whose task was reopened after the decision.
675
+ * Derived from the journal, never persisted. A carried decision (not in this journal) precedes it all.
676
+ */
677
+ // A15 + u03p review: an accepted phase is stale after a member reopen, or while a member is
678
+ // unfinished (a revision carried the acceptance onto tasks it never saw). Derived only.
679
+ export function phaseAcceptanceStale(plan, events, phase, tasks = []) {
680
+ if (!['accepted', 'closed_unaudited'].includes(phase.status)) return false;
681
+ const decided = events.findIndex(({ event_digest: digest }) => digest === phase.decision_event_digest);
682
+ const taskIds = phaseTaskIds(plan, phase.phase_id);
683
+ return events.slice(decided + 1).some((event) => event.kind === 'reopen' && taskIds.has(event.task_id))
684
+ || tasks.some(({ task_id: id, status }) => taskIds.has(id) && !['done', 'retired'].includes(status));
685
+ }
686
+
687
+ function reopenAdvisory(plan, phases, taskId) {
688
+ const phase = phases.find((entry) => ['accepted', 'closed_unaudited'].includes(entry.status)
689
+ && phaseTaskIds(plan, entry.phase_id).has(taskId));
690
+ return phase === undefined ? null : {
691
+ phase_acceptance_stale: true, phase_id: phase.phase_id, status: phase.status,
692
+ guidance: staleAcceptanceGuidance(plan.plan_key, phase.phase_id),
693
+ };
694
+ }
695
+
643
696
  async function mutate({
644
697
  repoRoot, env, planKey, taskId, kind, payload, evidenceRef, evidenceMessage = null,
645
698
  advisory = null, noteContext = null, structureContext = null, featureContext = null,
646
699
  testResultRef = null,
647
700
  }) {
648
- const actor = mutationActor(env);
701
+ const actor = resolveTodoActor(env);
649
702
  const evidence = evidenceRef === null && evidenceMessage === null
650
703
  ? null
651
704
  : await resolveDoneEvidence({
@@ -682,10 +735,11 @@ async function mutate({
682
735
  const authoredTask = plan.tasks.find(({ task_id: current }) => current === event.task_id);
683
736
  if (authoredTask === undefined) throw new TypeError('mutation task content is missing');
684
737
  // advisoryは呼び出し側(startTask)がstart用に既に組んでいればそれを尊重し、無ければ
685
- // done時だけ終端監査の要否を調べる。block/unblock/reopenはnullのまま(既存挙動を変えない)。
738
+ // done時は終端監査の要否、reopen時は受入が古くなったphase(u03 A15)を返す。block/unblockはnull。
686
739
  // Phase状態はsnapshot(v1にはphasesキーが無い)でなく、appendTodoEventが別途返す
687
740
  // 導出ビュー`phases`から読む。
688
- const resolvedAdvisory = advisory ?? (kind === 'done' ? terminalAuditDoneAdvisory(plan, phases) : null);
741
+ const resolvedAdvisory = advisory ?? (kind === 'done' ? terminalAuditDoneAdvisory(plan, phases)
742
+ : kind === 'reopen' ? reopenAdvisory(plan, phases, event.task_id) : null);
689
743
  const includesNoteContext = kind === 'start';
690
744
  if (includesNoteContext && noteContext === null) {
691
745
  throw new TypeError('start mutation requires note context');
@@ -719,10 +773,50 @@ async function mutate({
719
773
  }
720
774
 
721
775
  /**
722
- * 恒久除去(u12)。pending/blocked/doneから`{reason, prior_status}`で閉じる。
723
- * in-progressはRuntimeに解放経路が無いので従来どおり拒否する(先にretract/blockする)。
776
+ * 恒久除去(u12)。どの状態からでも`{reason, prior_status}`で閉じる。
777
+ * in-progressは、最新のauthored startに束ねられた未acceptのintakeをRuntimeの解放手順で
778
+ * 先に解放してから閉じる(u03 A14r)。
724
779
  * 既にretiredなら成功を返しeventは足さない(応答を失った再試行をエラーにしない)。
725
780
  */
781
+ // a12: a transition whose target state already holds appends nothing and succeeds
782
+ // (`unchanged: true`), so a retry after a lost response is not an error (retire's u12 precedent).
783
+ const UNCHANGED_WHEN = {
784
+ start: ({ status }) => status === 'in-progress',
785
+ done: ({ status }) => status === 'done',
786
+ block: ({ status }) => status === 'blocked',
787
+ unblock: ({ status }) => status !== 'blocked',
788
+ retire: ({ status }) => status === 'retired',
789
+ };
790
+
791
+ /** Unchanged result, or null when the transition must go to the append path. */
792
+ function unchangedTransition(store, { env, planKey, taskId, kind }) {
793
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
794
+ const matches = member?.tasks.filter(({ task_id: current }) => current.toLowerCase() === taskId.toLowerCase()) ?? [];
795
+ // Unknown or ambiguous plan/task: the append path keeps Store's refusal.
796
+ if (matches.length !== 1 || !UNCHANGED_WHEN[kind](matches[0])) return null;
797
+ const [state] = matches;
798
+ const events = member.journal.events;
799
+ const recorded = events.findLast((event) => event.kind === kind && event.task_id === state.task_id);
800
+ // Another seat's in-progress task is not this seat's repeated start; keep the task_state refusal.
801
+ if (kind === 'start' && recorded?.actor?.agent !== resolveTodoActor(env).agent) return null;
802
+ const shown = recorded ?? events.findLast((event) => event.task_id === state.task_id) ?? events.at(-1);
803
+ const result = {
804
+ schema: 'lattice.todo_mutation_result.v2',
805
+ project_id: member.plan.project_id, plan_key: planKey, plan_version: member.plan.plan_version,
806
+ task_id: state.task_id, kind, sequence: shown.sequence, event_digest: shown.event_digest,
807
+ journal_head_digest: events.at(-1).event_digest, snapshot_digest: member.snapshot.snapshot_digest,
808
+ status: state.status, advisory: null, unchanged: true, result_digest: '',
809
+ };
810
+ result.result_digest = todoSelfDigest(result, 'result_digest');
811
+ return result;
812
+ }
813
+
814
+ /** block/unblock/done: an unchanged no-op first, else the append path. */
815
+ async function mutateUnlessUnchanged(options) {
816
+ const store = await readTodoStore({ repoRoot: options.repoRoot });
817
+ return unchangedTransition(store, options) ?? options.action();
818
+ }
819
+
726
820
  async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
727
821
  const store = await readTodoStore({ repoRoot });
728
822
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
@@ -731,32 +825,24 @@ async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
731
825
  // 未知のplan/taskはStoreの既存の拒否をそのまま通す。
732
826
  return mutate({ repoRoot, env, planKey, taskId, kind: 'retire', payload: { reason }, evidenceRef: null });
733
827
  }
734
- if (state.status === 'retired') {
735
- const events = member.journal.events;
736
- const recorded = events.findLast((event) => event.kind === 'retire' && event.task_id === taskId)
737
- ?? events.at(-1);
738
- const result = {
739
- schema: 'lattice.todo_mutation_result.v2',
740
- project_id: member.plan.project_id, plan_key: planKey, plan_version: member.plan.plan_version,
741
- task_id: taskId, kind: 'retire', sequence: recorded.sequence, event_digest: recorded.event_digest,
742
- journal_head_digest: events.at(-1).event_digest, snapshot_digest: member.snapshot.snapshot_digest,
743
- status: 'retired', advisory: null, unchanged: true, result_digest: '',
744
- };
745
- result.result_digest = todoSelfDigest(result, 'result_digest');
746
- return result;
747
- }
748
- if (state.status === 'in-progress') {
749
- throw new TodoStoreError('STORE_INCONSISTENT', 'invalid_retire_transition', undefined, {
750
- task_id: taskId, status: state.status,
751
- next_action: `lattice todo retract --plan ${planKey} --task ${taskId} --reason <text>`,
752
- });
753
- }
754
- try {
755
- return await mutate({ repoRoot, env, planKey, taskId, kind: 'retire',
756
- payload: { reason, prior_status: state.status }, evidenceRef: null });
757
- } catch (error) {
758
- throw retireStateConflict(error, { planKey, taskId, priorStatus: state.status });
759
- }
828
+ if (state.status === 'retired') return unchangedTransition(store, { env, planKey, taskId, kind: 'retire' });
829
+ const append = async () => {
830
+ try {
831
+ return await mutate({ repoRoot, env, planKey, taskId, kind: 'retire',
832
+ payload: { reason, prior_status: state.status }, evidenceRef: null });
833
+ } catch (error) {
834
+ throw retireStateConflict(error, { planKey, taskId, priorStatus: state.status });
835
+ }
836
+ };
837
+ if (state.status !== 'in-progress') return append();
838
+ // Runtime binds an intake to the latest literal start and ignores later done/reopen, so the
839
+ // release targets that start (a reopened task keeps it; a retracted start left in-progress never).
840
+ const start = member.journal.events.findLast((event) => event.task_id === taskId && event.kind === 'start');
841
+ if (start === undefined || start.payload.start_mode === 'historical_import') return append();
842
+ return withStartRetractionGuard({
843
+ repoRoot, planKey, taskId, activationEventDigest: start.event_digest,
844
+ releaseReason: 'task_retired', action: append,
845
+ });
760
846
  }
761
847
 
762
848
  async function startStructureContext({ repoRoot, store, planKey, taskId }) {
@@ -819,7 +905,21 @@ function designMemoProjection(task) {
819
905
  * silent degradeせず、呼び出し側でstart自体を止める。
820
906
  */
821
907
  async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
822
- const artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
908
+ // u03 B16/B7: an unreadable record or an unresolved HEAD makes the record unusable for this
909
+ // start; the start is recorded with the no-record advisory and a warning naming why.
910
+ let unusable = null;
911
+ let artifact = null;
912
+ let currentBaseSha = null;
913
+ try {
914
+ artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
915
+ if (artifact !== null) currentBaseSha = currentHeadSha(repoRoot);
916
+ } catch (error) {
917
+ if (!['INDEPENDENCE_ARTIFACT_INVALID', 'INDEPENDENCE_BASE_UNRESOLVED'].includes(error?.code)) throw error;
918
+ unusable = error.code === 'INDEPENDENCE_ARTIFACT_INVALID' ? 'independence_record_unreadable' : 'git_head_unresolved';
919
+ process.emitWarning(`todo start: independence record not used (${unusable}: ${error.detail?.reason ?? error.message})`,
920
+ { code: 'LATTICE_START_INDEPENDENCE_UNUSABLE' });
921
+ artifact = null;
922
+ }
823
923
  // 調整方式の宣言(ob03)。未宣言はnullで、「まだ選んでいない」を意味する。
824
924
  const coordinationMode = store.members
825
925
  .find(({ descriptor }) => descriptor.plan_key === planKey)?.coordination?.mode ?? null;
@@ -833,15 +933,12 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
833
933
  scope_expansion_recommendations: [],
834
934
  uncovered_active_task_ids: projection.active_set
835
935
  .filter((task) => task.plan_key === planKey).map(({ task_id: id }) => id),
836
- self_unknowns: [{ kind: 'witness_missing', ref: 'no_independence_record' }],
936
+ self_unknowns: [{ kind: 'witness_missing', ref: unusable ?? 'no_independence_record' }],
837
937
  guidance: selectIndependenceGuidance({
838
938
  coverage: 'missing', taskDeclared: false, taskStale: false, coordinationMode,
839
939
  }),
840
940
  };
841
941
  }
842
- // 記録があるなら鮮度の判定にHEADが要る。ここで読めないのは判定不能であり、
843
- // 助言なしで通してよい状態ではない。
844
- const currentBaseSha = currentHeadSha(repoRoot);
845
942
  const changedPaths = artifact.base_sha !== null && artifact.base_sha !== currentBaseSha
846
943
  ? changedPathsSince(repoRoot, artifact.base_sha) : null;
847
944
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
@@ -893,7 +990,7 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
893
990
  }
894
991
 
895
992
  async function startTask({
896
- repoRoot, env, planKey, taskId, overrideReason, parallelFrontier,
993
+ repoRoot, env, planKey, taskId, overrideReason,
897
994
  }) {
898
995
  const store = await readTodoStore({ repoRoot });
899
996
  // startはready判定にしかprojectionを使わず、resultを出力しない。
@@ -901,12 +998,7 @@ async function startTask({
901
998
  const readyTask = projection.next_ready.find((task) => (
902
999
  task.plan_key === planKey && task.task_id.toLowerCase() === taskId.toLowerCase()
903
1000
  ));
904
- const targetReady = readyTask !== undefined;
905
- // `--parallel-frontier`は方針の記録口で、対象がreadyでないときにだけ用法誤り。
906
- // 複数readyのplain startや直列理由の文言審査で着手を止めない(ADR 0180)。
907
- if (parallelFrontier && !targetReady) {
908
- throw new TodoStoreError('PARALLEL_DISPATCH_INVALID', 'parallel_frontier_not_applicable');
909
- }
1001
+ // u03 B8: `--parallel-frontier` is a policy flag; on a non-ready target it is simply ignored.
910
1002
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
911
1003
  if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active');
912
1004
  const taskMatches = member.plan.tasks.filter(({ task_id: candidate }) => (
@@ -924,6 +1016,8 @@ async function startTask({
924
1016
  });
925
1017
  }
926
1018
  const resolvedTaskId = readyTask?.task_id ?? taskMatches[0].task_id;
1019
+ const unchanged = unchangedTransition(store, { env, planKey, taskId: resolvedTaskId, kind: 'start' });
1020
+ if (unchanged !== null) return unchanged;
927
1021
  // noteはjournal appendより前に読む。壊れていてもstartは通す(ADR 0166 / 0181)。
928
1022
  let noteContext;
929
1023
  try {
@@ -944,24 +1038,24 @@ async function startTask({
944
1038
  next_action: `lattice todo note list --plan ${planKey} --json`,
945
1039
  };
946
1040
  }
947
- // 助言はjournalへ書く前に確定させる。計算できないならstart自体を止める。
1041
+ // 助言はjournalへ書く前に確定させる。助言はstartを止めない(u03 B1–B6)。
948
1042
  const advisory = await startAdvisory({
949
1043
  repoRoot, store, projection, planKey, taskId: resolvedTaskId,
950
1044
  });
951
- const refusal = independenceStartRefusal(advisory.guidance);
952
- if (refusal !== null) {
953
- throw new TodoStoreError('INDEPENDENCE_UNVERIFIED', refusal.code, refusal.message, {
954
- plan_key: planKey,
955
- task_id: resolvedTaskId,
956
- next_action: refusal.next_action,
957
- });
958
- }
959
1045
  const structureContext = await startStructureContext({
960
1046
  repoRoot, store, planKey, taskId: resolvedTaskId,
961
1047
  });
962
- const featureContext = await readTaskBackchainContext({
963
- repoRoot, plan: member.plan, taskId: resolvedTaskId,
964
- });
1048
+ // u03 A88: feature context is advisory; an unusable backchain degrades to the v5 result.
1049
+ let featureContext = null;
1050
+ try {
1051
+ featureContext = await readTaskBackchainContext({
1052
+ repoRoot, plan: member.plan, taskId: resolvedTaskId,
1053
+ });
1054
+ } catch (error) {
1055
+ if (error?.code !== 'PLAN_BACKCHAIN_INVALID') throw error;
1056
+ process.emitWarning(`todo start: backchain not used (${error.detail?.reason ?? error.message}: ${error.detail?.pointer ?? ''})`,
1057
+ { code: 'LATTICE_START_BACKCHAIN_UNUSABLE' });
1058
+ }
965
1059
  return mutate({ repoRoot, env, planKey, taskId: resolvedTaskId, kind: 'start',
966
1060
  payload: { override_reason: overrideReason }, evidenceRef: null, advisory, noteContext,
967
1061
  structureContext, featureContext });
@@ -1009,7 +1103,7 @@ export async function rebindStart({ repoRoot, env, planKey, taskId, reason }) {
1009
1103
  }
1010
1104
 
1011
1105
  async function retractStart({ repoRoot, env, planKey, taskId, reason }) {
1012
- const actor = mutationActor(env);
1106
+ const actor = resolveTodoActor(env);
1013
1107
  const store = await readTodoStore({ repoRoot });
1014
1108
  const binding = resolveTodoStartRetractionBinding(store, { planKey, taskId, actor });
1015
1109
  return withStartRetractionGuard({
@@ -1128,7 +1222,7 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1128
1222
  const { event, snapshot, phases } = await appendTodoEvent({
1129
1223
  validateProspectiveEvent,
1130
1224
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1131
- event: { kind, phase_id: phaseId, actor: mutationActor(env), payload },
1225
+ event: { kind, phase_id: phaseId, actor: resolveTodoActor(env), payload },
1132
1226
  });
1133
1227
  // snapshot.phasesはv1(phase無しplan)には存在しない。導出ビュー`phases`を見る
1134
1228
  // (これは暗黙のterminal-audit Phaseにも常に埋まっている)。
@@ -1156,7 +1250,7 @@ async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
1156
1250
  const { event } = await appendTodoEvent({
1157
1251
  validateProspectiveEvent,
1158
1252
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1159
- event: { kind: 'coordination_mode', actor: mutationActor(env), payload: { mode, reason } },
1253
+ event: { kind: 'coordination_mode', actor: resolveTodoActor(env), payload: { mode, reason } },
1160
1254
  });
1161
1255
  const result = {
1162
1256
  schema: 'lattice.todo_coordination_mode_result.v1', project_id: event.project_id,
@@ -1173,8 +1267,82 @@ async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
1173
1267
  return result;
1174
1268
  }
1175
1269
 
1176
- /** 開発中に発見した依存(同一plan内・plan跨ぎとも)を、consumer planのplan-scoped chainへ接続する。 */
1177
- async function dependencyConnect({
1270
+ const dependencyRef = (store, planKey, taskId) => ({
1271
+ project_id: store.project_id, plan_key: planKey, task_id: taskId });
1272
+
1273
+ /**
1274
+ * 同一plan内の依存の変更を軽量改訂として適用する(a14)。現行planから作った desired の辺だけを
1275
+ * 足す/外し、共有の applyPlanRevision(公開→履歴note→作業中taskの結び直し)に任せる。
1276
+ * 理由は plan の履歴noteに `dependency <operation> <from>→<to>: <reason>` として残る。
1277
+ */
1278
+ async function dependencyRevision({
1279
+ repoRoot, env, store, member, operation, fromTaskId, toTaskId, reason,
1280
+ }) {
1281
+ const { applyPlanRevision, desiredFromPlan } = await import('./plan-revise.mjs');
1282
+ const planKey = member.plan.plan_key;
1283
+ const desired = desiredFromPlan(member.plan, { env });
1284
+ const from = dependencyRef(store, planKey, fromTaskId);
1285
+ const to = dependencyRef(store, planKey, toTaskId);
1286
+ desired.hard_dependencies = operation === 'connect'
1287
+ ? [...desired.hard_dependencies, { from, to }]
1288
+ : desired.hard_dependencies.filter((edge) => !(edge.from.task_id === fromTaskId
1289
+ && edge.to.task_id === toTaskId));
1290
+ const applied = await applyPlanRevision({
1291
+ repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1292
+ notes: [{ task_id: fromTaskId,
1293
+ body: `dependency ${operation} ${fromTaskId}→${toTaskId}: ${reason}` }],
1294
+ });
1295
+ const result = {
1296
+ schema: 'lattice.todo_dependency_revision_result.v1', project_id: store.project_id,
1297
+ plan_key: planKey, operation, from, to, reason, actor: desired.actor,
1298
+ plan_version: applied.plan_version, revision_digest: applied.revision.revision_digest,
1299
+ rebound_task_ids: applied.rebound_task_ids, result_digest: '',
1300
+ };
1301
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1302
+ return result;
1303
+ }
1304
+
1305
+ const samePlanEdge = (member, fromTaskId, toTaskId) => member.plan.hard_dependencies.some((edge) => (
1306
+ edge.from.task_id === fromTaskId && edge.to.task_id === toTaskId));
1307
+
1308
+ /**
1309
+ * 開発中に発見した依存を接続する。同一planの辺はplan本体の軽量改訂(a14)、plan跨ぎは
1310
+ * consumer planのplan-scoped chainへ。
1311
+ */
1312
+ async function dependencyConnect(options) {
1313
+ const { repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason } = options;
1314
+ if (fromPlanKey !== toPlanKey) return dependencyConnectLedger(options);
1315
+ const store = await readTodoStore({ repoRoot });
1316
+ const member = store.members.find(({ plan }) => plan.plan_key === fromPlanKey);
1317
+ const tasks = member?.plan.tasks ?? [];
1318
+ // 台帳経路と同じ事前検査(plan不在・task不在・自己辺・既存辺・完了済み終点)の拒否を保つ。
1319
+ if (member === undefined || !tasks.some(({ task_id: id }) => id === fromTaskId)
1320
+ || !tasks.some(({ task_id: id }) => id === toTaskId) || fromTaskId === toTaskId) {
1321
+ return dependencyConnectLedger(options);
1322
+ }
1323
+ const from = dependencyRef(store, fromPlanKey, fromTaskId);
1324
+ const to = dependencyRef(store, toPlanKey, toTaskId);
1325
+ if (samePlanEdge(member, fromTaskId, toTaskId)) {
1326
+ throw new TodoStoreError('DEPENDENCY_EXISTS', 'dependency_already_in_plan', undefined, { from, to });
1327
+ }
1328
+ // 以前の同一plan接続で台帳に生きている辺を、本体へ二重に足さない(台帳経路と同じ拒否)。
1329
+ if (projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1330
+ dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1331
+ && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId))) {
1332
+ throw new TodoStoreError('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate', undefined, { from, to });
1333
+ }
1334
+ if (member.tasks.find(({ task_id: id }) => id === toTaskId)?.status === 'done') {
1335
+ throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_target_terminal');
1336
+ }
1337
+ const { lightRevisionExpresses } = await import('./plan-revise.mjs');
1338
+ // 軽量改訂で表せないplan(create v1〜v3由来・源泉束縛・compile_binding付き)は、従来どおり台帳へ積む。
1339
+ if (!lightRevisionExpresses(member)) return dependencyConnectLedger(options);
1340
+ return dependencyRevision({
1341
+ repoRoot, env, store, member, operation: 'connect', fromTaskId, toTaskId, reason });
1342
+ }
1343
+
1344
+ /** 台帳(cross_plan_dependency event)への接続。plan跨ぎの本線。 */
1345
+ async function dependencyConnectLedger({
1178
1346
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
1179
1347
  }) {
1180
1348
  const store = await readTodoStore({ repoRoot });
@@ -1211,7 +1379,7 @@ async function dependencyConnect({
1211
1379
  validateProspectiveEvent,
1212
1380
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: toPlanKey,
1213
1381
  event: {
1214
- kind: 'cross_plan_dependency', actor: mutationActor(env), payload: { from, to, reason },
1382
+ kind: 'cross_plan_dependency', actor: resolveTodoActor(env), payload: { from, to, reason },
1215
1383
  },
1216
1384
  });
1217
1385
  const result = {
@@ -1225,9 +1393,23 @@ async function dependencyConnect({
1225
1393
  return result;
1226
1394
  }
1227
1395
 
1228
- // connectの対。誤って張った線の除去(tombstone)。端点で一意に生きた接続を特定し、
1396
+ // connectの対。同一planでplan本体が持つ辺は軽量改訂で外し(a14)、それ以外は台帳の除去へ。
1397
+ async function dependencyDisconnect(options) {
1398
+ const { repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason } = options;
1399
+ if (fromPlanKey === toPlanKey) {
1400
+ const store = await readTodoStore({ repoRoot });
1401
+ const member = store.members.find(({ plan }) => plan.plan_key === fromPlanKey);
1402
+ if (member !== undefined && samePlanEdge(member, fromTaskId, toTaskId)) {
1403
+ return dependencyRevision({
1404
+ repoRoot, env, store, member, operation: 'disconnect', fromTaskId, toTaskId, reason });
1405
+ }
1406
+ }
1407
+ return dependencyDisconnectLedger(options);
1408
+ }
1409
+
1410
+ // 誤って張った線の除去(tombstone)。端点で一意に生きた接続を特定し、
1229
1411
  // その接続eventが積まれているplanのplan-scoped chainへ除去eventを積む。
1230
- async function dependencyDisconnect({
1412
+ async function dependencyDisconnectLedger({
1231
1413
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
1232
1414
  }) {
1233
1415
  const store = await readTodoStore({ repoRoot });
@@ -1239,6 +1421,7 @@ async function dependencyDisconnect({
1239
1421
  throw new TodoStoreError('DEPENDENCY_INVALID', 'cross_plan_dependency_not_found', undefined, {
1240
1422
  from: { plan_key: fromPlanKey, task_id: fromTaskId },
1241
1423
  to: { plan_key: toPlanKey, task_id: toTaskId },
1424
+ ...(fromPlanKey === toPlanKey ? { next_action: `lattice plan show ${fromPlanKey} --json` } : {}),
1242
1425
  });
1243
1426
  }
1244
1427
  const [target] = live;
@@ -1248,7 +1431,7 @@ async function dependencyDisconnect({
1248
1431
  validateProspectiveEvent,
1249
1432
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: owner.plan.plan_key,
1250
1433
  event: {
1251
- kind: 'cross_plan_dependency_removed', actor: mutationActor(env),
1434
+ kind: 'cross_plan_dependency_removed', actor: resolveTodoActor(env),
1252
1435
  payload: { target_event_digest: target.event_digest, reason },
1253
1436
  },
1254
1437
  });
@@ -1280,7 +1463,10 @@ async function phaseStatus({ repoRoot, planKey }) {
1280
1463
  // v4/v5の実Phaseがgate_readyになった場合も同じ理由で同じ案内が要る。
1281
1464
  const phases = member.phases.map((phase) => ({
1282
1465
  ...phase,
1283
- guidance: phase.status === 'gate_ready'
1466
+ acceptance_stale: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks),
1467
+ guidance: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks)
1468
+ ? staleAcceptanceGuidance(member.plan.plan_key, phase.phase_id)
1469
+ : phase.status === 'gate_ready'
1284
1470
  ? [
1285
1471
  auditGateGuidance(member.plan.plan_key, phase.phase_id),
1286
1472
  ...(structureFinalization.required && structureFinalization.status !== 'fresh'
@@ -1398,18 +1584,10 @@ async function phaseBaseline({ repoRoot, env, reason, exceptPlanKeys }) {
1398
1584
  }
1399
1585
 
1400
1586
  async function migrate({ repoRoot, inputRef }) {
1401
- const extraction = await readMigrationInput(repoRoot, inputRef);
1402
- // unresolved/空集合の早期gateは、compileTodoExtraction内部の同名gateをここでも
1403
- // 先に通しておくことで、既存のエラー優先順位を変えない。
1587
+ const { extraction, defaultedPendingTaskIds } = defaultUnknownDispositions(
1588
+ await readMigrationInput(repoRoot, inputRef, { requireValid: false }));
1589
+ assertValidMigrationExtraction(extraction);
1404
1590
  // dispatch_shapeは結果へ載せる観測であり、直列度では書込みを拒まない(ADR 0180)。
1405
- const unresolvedTaskIds = extraction.tasks
1406
- .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
1407
- .map(({ task_id: taskId }) => taskId);
1408
- if (unresolvedTaskIds.length > 0) {
1409
- throw new TodoStoreError('MIGRATION_UNRESOLVED', 'unknown_requires_evidence', undefined, {
1410
- task_ids: unresolvedTaskIds,
1411
- });
1412
- }
1413
1591
  const registered = extraction.tasks.filter(({ disposition }) => disposition.startsWith('register_'));
1414
1592
  const connectionOnly = isTodoExtractionConnectionOnly(extraction);
1415
1593
  if (registered.length === 0 && !connectionOnly) {
@@ -1449,6 +1627,7 @@ async function migrate({ repoRoot, inputRef }) {
1449
1627
  plan_version: imported.plan.plan_version,
1450
1628
  extraction_digest: extraction.extraction_digest,
1451
1629
  imported_task_count: registered.length,
1630
+ defaulted_pending_task_ids: defaultedPendingTaskIds,
1452
1631
  completed_task_count: extraction.tasks.filter(({ disposition }) => disposition === 'register_done').length,
1453
1632
  plan_ref: imported.descriptor.plan_ref,
1454
1633
  journal_ref: imported.descriptor.journal_ref,
@@ -1597,7 +1776,8 @@ function extractionAuthoringViolations(extraction, now = new Date()) {
1597
1776
  }
1598
1777
 
1599
1778
  async function migrateDryRun({ repoRoot, inputRef }) {
1600
- const extraction = await readMigrationInput(repoRoot, inputRef, { requireValid: false });
1779
+ const { extraction, defaultedPendingTaskIds } = defaultUnknownDispositions(
1780
+ await readMigrationInput(repoRoot, inputRef, { requireValid: false }));
1601
1781
  const violations = [];
1602
1782
  const tasks = Array.isArray(extraction?.tasks) ? extraction.tasks : [];
1603
1783
  const designMemoSchema = [TODO_EXTRACTION_SCHEMA_V3, TODO_EXTRACTION_SCHEMA_V4].includes(extraction?.schema);
@@ -1635,13 +1815,6 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1635
1815
  violations.push(violation);
1636
1816
  }
1637
1817
  }
1638
- const unresolvedTaskIds = tasks
1639
- .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
1640
- .map(({ task_id: taskId }) => taskId).filter(isTodoIdentifier);
1641
- if (unresolvedTaskIds.length > 0) {
1642
- violations.push({ code: 'unknown_requires_evidence', path: '/tasks',
1643
- task_ids: unresolvedTaskIds.slice(0, 64), next_action: 'adjudicate_task_disposition' });
1644
- }
1645
1818
  const registered = tasks.filter(({ disposition }) => typeof disposition === 'string'
1646
1819
  && disposition.startsWith('register_'));
1647
1820
  const connectionOnly = schemaValid && isTodoExtractionConnectionOnly(extraction);
@@ -1653,7 +1826,7 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1653
1826
  let dispatchShape = null;
1654
1827
  let plannedPlan = null;
1655
1828
  let plannedConnection = null;
1656
- if (schemaValid && unresolvedTaskIds.length === 0 && (registered.length > 0 || connectionOnly)) {
1829
+ if (schemaValid && (registered.length > 0 || connectionOnly)) {
1657
1830
  try {
1658
1831
  const compiled = compileTodoExtraction(extraction, repoRoot);
1659
1832
  if (connectionOnly) {
@@ -1709,6 +1882,7 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1709
1882
  plan_key: isTodoIdentifier(extraction?.plan_key) ? extraction.plan_key : null,
1710
1883
  violations: bounded,
1711
1884
  overflow_count: Math.max(0, violations.length - bounded.length),
1885
+ defaulted_pending_task_ids: defaultedPendingTaskIds,
1712
1886
  planned: plannedConnection !== null ? {
1713
1887
  connection_only: true,
1714
1888
  source: plannedConnection.source,
@@ -1742,7 +1916,7 @@ async function revise({ repoRoot, env, planKey, inputRef }) {
1742
1916
  }
1743
1917
  return applyTodoRevision({
1744
1918
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
1745
- actor: mutationActor(env), recordedAt: new Date().toISOString(),
1919
+ actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
1746
1920
  });
1747
1921
  }
1748
1922
 
@@ -1755,7 +1929,7 @@ async function reviseSet({ repoRoot, env, inputRef }) {
1755
1929
  });
1756
1930
  return applyTodoRevisionSet({
1757
1931
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revisionSet,
1758
- actor: mutationActor(env), recordedAt: new Date().toISOString(),
1932
+ actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
1759
1933
  });
1760
1934
  }
1761
1935
 
@@ -1764,10 +1938,19 @@ async function revisePhase({ repoRoot, env, planKey, inputRef }) {
1764
1938
  validate: validatePhaseTodoRevision, invalidCode: 'REVISION_INVALID',
1765
1939
  invalidReason: 'phase_revision_schema_or_digest_invalid',
1766
1940
  explain: explainPhaseTodoRevision,
1941
+ complete: async (value) => {
1942
+ // 先行を読めない/無いときは補わず、検証と適用が通常の診断を返す。
1943
+ const store = await readTodoStore({ repoRoot }).catch(() => null);
1944
+ const member = store?.members.find(({ plan }) => plan.plan_key === value?.plan_key);
1945
+ if (member === undefined) return value;
1946
+ return completePhaseTodoRevision(value, { member, buildPlan: buildTodoPlan,
1947
+ predecessorInventory: value?.schema === 'lattice.phase_todo_revision.v3'
1948
+ ? await predecessorSourceInventory(repoRoot, member) : null });
1949
+ },
1767
1950
  });
1768
1951
  if (revision.plan_key !== planKey) throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
1769
1952
  return applyPhaseTodoRevision({ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
1770
- revision, actor: mutationActor(env), recordedAt: new Date().toISOString() });
1953
+ revision, actor: resolveTodoActor(env), recordedAt: new Date().toISOString() });
1771
1954
  }
1772
1955
 
1773
1956
  async function splitTodo({ repoRoot, env, planKey, inputRef }) {
@@ -1783,7 +1966,7 @@ async function splitTodo({ repoRoot, env, planKey, inputRef }) {
1783
1966
  });
1784
1967
  }
1785
1968
  const compiled = await compileTodoSplit({ repoRoot, member, proposal });
1786
- const actor = mutationActor(env);
1969
+ const actor = resolveTodoActor(env);
1787
1970
  const recordedAt = new Date().toISOString();
1788
1971
  // splitのmigrationは既存taskへのidentity写像だけである。宣言を純粋に移行・検査し、
1789
1972
  // 同じcanonical bytesをwitness先へ書けることまでapply前に確定する。これにより、
@@ -1848,7 +2031,7 @@ async function status({ repoRoot }) {
1848
2031
 
1849
2032
  async function adoptDashboardRoot({ repoRoot, env }) {
1850
2033
  const store = await readTodoStoreStable({ repoRoot });
1851
- const actor = mutationActor(env);
2034
+ const actor = resolveTodoActor(env);
1852
2035
  const identity = await resolveProjectIdentity({ repoRoot, projectId: store.project_id, env });
1853
2036
  await adoptTodoDashboardActivity({
1854
2037
  repoRoot, projectId: store.project_id, displayName: identity.displayName,
@@ -1916,7 +2099,7 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
1916
2099
  planKey,
1917
2100
  planVersion: member.plan.plan_version,
1918
2101
  taskId: task?.task_id ?? null,
1919
- actor: mutationActor(env),
2102
+ actor: resolveTodoActor(env),
1920
2103
  recordedAt: new Date().toISOString(),
1921
2104
  body,
1922
2105
  supersedes,
@@ -2282,7 +2465,7 @@ async function structureCompile({ repoRoot, env, planKey, inputRef }) {
2282
2465
  next_action: `lattice todo structure --plan ${planKey} --json`,
2283
2466
  });
2284
2467
  }
2285
- const actor = mutationActor(env);
2468
+ const actor = resolveTodoActor(env);
2286
2469
  const observation = await collectTodoStructureAuthoritativeObservation({ repoRoot, structureSet });
2287
2470
  const sourceEvidence = observation.source_evidence;
2288
2471
  const gitProvenance = observation.git_provenance;
@@ -2408,7 +2591,7 @@ async function recordStructureRealization({ repoRoot, planKey, taskId, realizati
2408
2591
 
2409
2592
  async function structureRealize({ repoRoot, env, planKey, taskId, inputRef }) {
2410
2593
  const realization = await readStructureRealizationInput(repoRoot, inputRef);
2411
- const actor = mutationActor(env);
2594
+ const actor = resolveTodoActor(env);
2412
2595
  if (realization.plan_key !== planKey || realization.task_id !== taskId) {
2413
2596
  throw new TodoStoreError('STRUCTURE_REALIZATION_BINDING_MISMATCH',
2414
2597
  'cli_target_mismatch', undefined, {
@@ -2495,7 +2678,7 @@ async function structureRealizeActual({
2495
2678
  commit_oids: resolveStructureRealizationCommits(repoRoot, commitRefs),
2496
2679
  realized,
2497
2680
  supersedes: previous?.realization_digest ?? null,
2498
- actor: mutationActor(env),
2681
+ actor: resolveTodoActor(env),
2499
2682
  recorded_at: new Date().toISOString(),
2500
2683
  realization_digest: '',
2501
2684
  };
@@ -2544,7 +2727,7 @@ async function structureFinalize({ repoRoot, env, planKey }) {
2544
2727
  realizations.push(...chain);
2545
2728
  effectiveTransforms.set(task.task_id, latest.realized);
2546
2729
  }
2547
- const actor = mutationActor(env);
2730
+ const actor = resolveTodoActor(env);
2548
2731
  const observation = await collectTodoStructureAuthoritativeObservation({
2549
2732
  repoRoot, structureSet: source, effectiveTransforms,
2550
2733
  });
@@ -3523,8 +3706,23 @@ export async function renderTodoGanttForProject({
3523
3706
  : { displayName };
3524
3707
  // degraded (display of an unverified/last_verified store): every current-file overlay is
3525
3708
  // omitted, since computing one can reach strict Store validation.
3526
- const presentation = degraded ? null
3527
- : await loadTodoGanttPresentation({ repoRoot, readModel: store });
3709
+ // u03 D-gantt: an invalid presentation file only costs the lane names; the page uses the
3710
+ // defaults and says so. (Authoring input is not validated here, so nothing is stored.)
3711
+ const notices = [];
3712
+ let presentation = null;
3713
+ if (!degraded) {
3714
+ try {
3715
+ presentation = await loadTodoGanttPresentation({ repoRoot, readModel: store });
3716
+ } catch (error) {
3717
+ if (!(error instanceof TodoStoreError) || error.code !== 'PRESENTATION_INVALID') throw error;
3718
+ presentation = projectTodoGanttPresentation(store, null);
3719
+ notices.push({
3720
+ code: 'PRESENTATION_INVALID',
3721
+ message: '表示設定が不正なため、既定の表示で描いています',
3722
+ detail: { reason: error.message },
3723
+ });
3724
+ }
3725
+ }
3528
3726
  const [independence, seamProposals, notes, structures] = degraded
3529
3727
  ? [null, null, { contexts: null, warnings: [], headBindings: [] }, null]
3530
3728
  : await Promise.all([
@@ -3582,6 +3780,7 @@ export async function renderTodoGanttForProject({
3582
3780
  noteContexts: notes.contexts,
3583
3781
  noteWarnings: notes.warnings,
3584
3782
  structurePresentation: structures,
3783
+ notices,
3585
3784
  });
3586
3785
  return { store, metadata, memberBindings, rendered };
3587
3786
  }
@@ -3740,7 +3939,7 @@ function writesTodoStore(argv) {
3740
3939
  async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = false }) {
3741
3940
  if (env.LATTICE_DASHBOARD_AUTOSTART === '0') return null;
3742
3941
  let actor;
3743
- try { actor = mutationActor(env); } catch (error) { if (strict) throw error; return null; }
3942
+ try { actor = resolveTodoActor(env); } catch (error) { if (strict) throw error; return null; }
3744
3943
  const sessionId = actor.session;
3745
3944
  let store;
3746
3945
  try { store = await readTodoStoreStable({ repoRoot }); }
@@ -3777,8 +3976,17 @@ async function verify({ repoRoot, requestedPlanKey }) {
3777
3976
  await readTodoNoteEvents({ repoRoot, planKey: member.plan.plan_key });
3778
3977
  }
3779
3978
  const verifiedSourceInventories = new Map();
3979
+ const uncommittedEvidence = [];
3780
3980
  for (const member of members) {
3781
- const unverified = member.tasks.find((task) => task.evidence_unverified);
3981
+ const planKey = member.descriptor.plan_key;
3982
+ // a12: evidence waiting for a commit is an item; missing or changed evidence still refuses.
3983
+ const pending = member.tasks.filter((task) => task.evidence_unverified
3984
+ && isTodoEvidenceUncommitted({ repoRoot, store, evidence: task.evidence }));
3985
+ for (const { task_id: taskId, evidence } of pending) {
3986
+ uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, repo_id: evidence.repo_id, path: evidence.path,
3987
+ next_action: `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.` });
3988
+ }
3989
+ const unverified = member.tasks.find((task) => task.evidence_unverified && !pending.includes(task));
3782
3990
  if (unverified !== undefined) {
3783
3991
  throw new TodoStoreError('STORE_INCONSISTENT', 'evidence_unverified', 'evidence_unverified', {
3784
3992
  plan_key: member.descriptor.plan_key,
@@ -3858,11 +4066,12 @@ async function verify({ repoRoot, requestedPlanKey }) {
3858
4066
  );
3859
4067
  }
3860
4068
  const result = {
3861
- schema: 'lattice.todo_verify_result.v3',
4069
+ schema: 'lattice.todo_verify_result.v4',
3862
4070
  project_id: store.project_id,
3863
4071
  requested_plan_key: requestedPlanKey,
3864
4072
  verified_members: verifiedMembers,
3865
4073
  snapshot_stale: verifiedMembers.some((member) => member.snapshot_stale),
4074
+ uncommitted_evidence: uncommittedEvidence,
3866
4075
  result_digest: '',
3867
4076
  };
3868
4077
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -3959,7 +4168,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
3959
4168
  return 0;
3960
4169
  } catch (error) {
3961
4170
  if (typeof error?.code === 'string' && error.detail !== null
3962
- && typeof error.detail === 'object') return typedFailure(stderr, error);
4171
+ && typeof error.detail === 'object') return typedFailure(stderr, error, guidanceContext(argv));
3963
4172
  return failInternally(error);
3964
4173
  }
3965
4174
  }
@@ -4274,26 +4483,38 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4274
4483
  action = (repoRoot) => startTask({
4275
4484
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4276
4485
  overrideReason: typeof flags['override-reason'] === 'string' ? flags['override-reason'] : null,
4277
- parallelFrontier: flags['parallel-frontier'] === true,
4278
4486
  });
4279
4487
  }
4280
4488
  } else if (argv[0] === 'done') {
4281
- const flags = matchFlagCommand(argv, ['done'], {
4282
- known: ['plan', 'task', 'evidence', 'test-result', 'message'],
4283
- required: ['plan', 'task'],
4284
- });
4489
+ const flags = matchFlagCommand(argv, ['done'], DONE_FLAG_SPEC);
4285
4490
  const hasEvidence = isAuthoringPathToken(flags?.evidence);
4286
4491
  const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
4492
+ // u03 A58: both, one or neither of --evidence/--message is accepted.
4287
4493
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4288
- && hasEvidence !== hasMessage
4494
+ && (flags.evidence === undefined || hasEvidence)
4289
4495
  && (flags['test-result'] === undefined || isAuthoringPathToken(flags['test-result']))) {
4290
- action = (repoRoot) => mutate({
4291
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4292
- kind: 'done', payload: 'authored',
4293
- evidenceRef: hasEvidence ? flags.evidence : null,
4294
- evidenceMessage: hasMessage ? flags.message : null,
4295
- testResultRef: flags['test-result'] ?? null,
4296
- });
4496
+ action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4497
+ kind: 'done', action: async () => {
4498
+ let evidenceMessage = hasMessage ? flags.message : null;
4499
+ if (hasEvidence && hasMessage) {
4500
+ // The message is the record; it names the resolved file so nothing given is lost.
4501
+ const file = await resolveDoneEvidence({
4502
+ repoRoot, evidenceRef: flags.evidence, evidenceMessage: null,
4503
+ planKey: flags.plan, taskId: flags.task,
4504
+ });
4505
+ evidenceMessage = `${flags.message}\n\nevidence: ${file.repo_id}:${file.path}`
4506
+ + ` (git blob ${file.git_blob_oid}, sha256 ${file.content_digest})\n`;
4507
+ } else if (!hasEvidence && !hasMessage) {
4508
+ evidenceMessage = DONE_WITHOUT_EVIDENCE_MESSAGE;
4509
+ }
4510
+ return mutate({
4511
+ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4512
+ kind: 'done', payload: 'authored',
4513
+ evidenceRef: evidenceMessage === null ? flags.evidence : null,
4514
+ evidenceMessage,
4515
+ testResultRef: flags['test-result'] ?? null,
4516
+ });
4517
+ } });
4297
4518
  }
4298
4519
  }
4299
4520
  if (action === null && argv[0] === 'retract') {
@@ -4310,10 +4531,11 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4310
4531
  known: ['plan', 'task', 'reason'], required: ['plan', 'task', 'reason'],
4311
4532
  });
4312
4533
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4313
- action = (repoRoot) => mutate({
4314
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4315
- kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
4316
- });
4534
+ action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4535
+ kind: 'block', action: () => mutate({
4536
+ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4537
+ kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
4538
+ }) });
4317
4539
  }
4318
4540
  } else if (argv[0] === 'retire') {
4319
4541
  // 恒久除去(2026-08-29オーナー裁定)。planの形は変えず、状態遷移として工程を閉じる。
@@ -4330,10 +4552,11 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4330
4552
  known: ['plan', 'task'], required: ['plan', 'task'],
4331
4553
  });
4332
4554
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4333
- action = (repoRoot) => mutate({
4334
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4335
- kind: 'unblock', payload: {}, evidenceRef: null,
4336
- });
4555
+ action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4556
+ kind: 'unblock', action: () => mutate({
4557
+ repoRoot, env, planKey: flags.plan, taskId: flags.task,
4558
+ kind: 'unblock', payload: {}, evidenceRef: null,
4559
+ }) });
4337
4560
  }
4338
4561
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
4339
4562
  const flags = matchFlagCommand(argv, ['evidence', 'promote'], {
@@ -4378,14 +4601,15 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4378
4601
  return typedArgumentFailure(stderr, 'UNKNOWN_SUBCOMMAND', 'todo_subcommand_unknown', {
4379
4602
  command, available_commands: TODO_COMMAND_NAMES,
4380
4603
  next_action: 'lattice todo --help',
4381
- });
4604
+ }, guidanceContext(argv));
4382
4605
  }
4383
4606
  const argumentHelp = argv[0] === 'gantt' && argv[1] === 'serve'
4384
4607
  ? 'lattice todo gantt serve --help'
4385
4608
  : command === null ? 'lattice todo --help' : `lattice todo ${command} --help`;
4386
- return typedArgumentFailure(stderr, 'INVALID_ARGUMENTS', 'todo_arguments_invalid', {
4387
- command, next_action: argumentHelp,
4388
- });
4609
+ const explained = explainArgumentRefusal(argv);
4610
+ return typedArgumentFailure(stderr, 'INVALID_ARGUMENTS', 'todo_arguments_invalid',
4611
+ explained.rule === undefined ? { command, next_action: argumentHelp } : { command, ...explained },
4612
+ guidanceContext(argv));
4389
4613
  }
4390
4614
  if (atomicCommit && !supportsAtomicStoreCommit(argv)) {
4391
4615
  return atomicStoreCommitUnsupported(stderr, argv);
@@ -4408,13 +4632,17 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4408
4632
  return 0;
4409
4633
  } catch (error) {
4410
4634
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
4411
- && error.detail !== null && typeof error.detail === 'object')) return typedFailure(stderr, error);
4635
+ && error.detail !== null && typeof error.detail === 'object')) {
4636
+ return typedFailure(stderr, error, guidanceContext(argv));
4637
+ }
4412
4638
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
4413
4639
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {
4414
4640
  return typedFailure(stderr, {
4415
4641
  code: 'CONTRACT_VIOLATION',
4416
4642
  message: error.message,
4417
- });
4643
+ detail: error.detail !== null && typeof error.detail === 'object' && !Array.isArray(error.detail)
4644
+ ? error.detail : undefined,
4645
+ }, guidanceContext(argv));
4418
4646
  }
4419
4647
  return failInternally(error);
4420
4648
  }