@quolu/lattice 0.82.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +1 -1
  3. package/bin/lattice-bridge-supervisor.mjs +10 -0
  4. package/bin/lattice-dashboard.mjs +3 -18
  5. package/bin/lattice-mcp.mjs +6 -3
  6. package/bin/lattice.mjs +30 -23
  7. package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
  8. package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
  9. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
  10. package/package.json +2 -1
  11. package/sensor/dist/db/index.d.ts +1 -0
  12. package/sensor/dist/db/index.d.ts.map +1 -1
  13. package/sensor/dist/db/index.js +13 -0
  14. package/sensor/dist/db/index.js.map +1 -1
  15. package/sensor/dist/index.d.ts.map +1 -1
  16. package/sensor/dist/index.js +12 -2
  17. package/sensor/dist/index.js.map +1 -1
  18. package/sensor/dist/mcp/answer-freshness.js +1 -1
  19. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  20. package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
  21. package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
  22. package/sensor/dist/mcp/daemon-paths.js +7 -1
  23. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  24. package/sensor/dist/mcp/engine.d.ts +11 -0
  25. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  26. package/sensor/dist/mcp/engine.js +83 -4
  27. package/sensor/dist/mcp/engine.js.map +1 -1
  28. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  29. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  30. package/sensor/dist/mcp/index-repair.js +93 -0
  31. package/sensor/dist/mcp/index-repair.js.map +1 -0
  32. package/sensor/dist/mcp/index.d.ts.map +1 -1
  33. package/sensor/dist/mcp/index.js +12 -7
  34. package/sensor/dist/mcp/index.js.map +1 -1
  35. package/sensor/dist/mcp/tools.d.ts +4 -0
  36. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  37. package/sensor/dist/mcp/tools.js +29 -9
  38. package/sensor/dist/mcp/tools.js.map +1 -1
  39. package/src/bridge-hub-server.mjs +46 -9
  40. package/src/cli-help.mjs +10 -8
  41. package/src/cli-refusal-guidance.mjs +354 -0
  42. package/src/dashboard-delivery.mjs +2 -1
  43. package/src/dashboard-lifecycle-journal.mjs +42 -20
  44. package/src/hooks-cli.mjs +30 -6
  45. package/src/plan-backchain.mjs +95 -41
  46. package/src/plan-revise.mjs +274 -72
  47. package/src/project-cli.mjs +301 -163
  48. package/src/project-identity.mjs +14 -0
  49. package/src/runtime-cli.mjs +38 -29
  50. package/src/runtime-control-store.mjs +22 -1
  51. package/src/runtime-decision-verifier.mjs +27 -8
  52. package/src/runtime-engine.mjs +34 -5
  53. package/src/runtime-hold-recompile.mjs +19 -15
  54. package/src/runtime-kept-worktree.mjs +136 -0
  55. package/src/runtime-lifecycle-lock.mjs +118 -30
  56. package/src/runtime-managed-supervisor.mjs +10 -10
  57. package/src/runtime-pull-intake.mjs +90 -44
  58. package/src/store-lock.mjs +142 -57
  59. package/src/todo-authoring-input.mjs +211 -2
  60. package/src/todo-cli.mjs +554 -200
  61. package/src/todo-contracts.mjs +22 -6
  62. package/src/todo-dashboard-registry.mjs +35 -6
  63. package/src/todo-gantt-display.mjs +259 -0
  64. package/src/todo-gantt-html-independence.mjs +10 -3
  65. package/src/todo-gantt-html-shared.mjs +16 -1
  66. package/src/todo-gantt-html.mjs +74 -53
  67. package/src/todo-gantt-layout.mjs +137 -59
  68. package/src/todo-gantt-live.mjs +6 -3
  69. package/src/todo-independence-guidance.mjs +4 -26
  70. package/src/todo-note-store.mjs +6 -3
  71. package/src/todo-readiness.mjs +83 -20
  72. package/src/todo-revision.mjs +156 -8
  73. package/src/todo-split.mjs +6 -3
  74. package/src/todo-status.mjs +141 -54
  75. package/src/todo-store-cache.mjs +1 -1
  76. package/src/todo-store-view.mjs +20 -2
  77. package/src/todo-store.mjs +562 -444
package/src/todo-cli.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { validateProspectiveEvent } from './todo-readiness.mjs';
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,13 +43,16 @@ import {
38
43
  ensureTodoDashboardActivity,
39
44
  removeTodoDashboardProject,
40
45
  } from './todo-dashboard-registry.mjs';
41
- import { readOrCreateTerminalIdSync, terminalPublicLabel } from './terminal-identity.mjs';
42
- import { readProjectExternalPane, resolveProjectIdentity } from './project-identity.mjs';
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';
52
+ import {
53
+ createTodoGanttDisplayReader, degradedBannerHtml, displayHeadDigest, displayResultBinding,
54
+ emptyStateHtml, projectUnverifiedStore,
55
+ } from './todo-gantt-display.mjs';
48
56
  import {
49
57
  renderTodoGanttHtml,
50
58
  TODO_GANTT_RENDERER_VERSION,
@@ -60,11 +68,13 @@ import {
60
68
  createTodoStoreWriter,
61
69
  TodoStoreError,
62
70
  isPhaselessTodoPlanSchema,
71
+ isTodoEvidenceUncommitted,
63
72
  projectTodoCrossPlanDependencies,
64
73
  TERMINAL_AUDIT_PHASE_ID,
65
74
  todoPhaseDefinitions,
66
75
  readTodoIndependenceArtifact,
67
76
  readTodoSeamProposalArtifact,
77
+ predecessorSourceInventory,
68
78
  readTodoStore,
69
79
  readTodoStructureBinding,
70
80
  readTodoStructureRealizationChain,
@@ -138,7 +148,6 @@ import {
138
148
  TodoIndependenceError,
139
149
  } from './todo-independence.mjs';
140
150
  import {
141
- independenceStartRefusal,
142
151
  selectIndependenceGuidance,
143
152
  selectWitnessScaffoldGuidance,
144
153
  selectSeamProposalGuidance,
@@ -162,7 +171,7 @@ import {
162
171
  validateWitnessDraft,
163
172
  } from './witness-scaffold.mjs';
164
173
  import {
165
- explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
174
+ completePhaseTodoRevision, explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
166
175
  parseTodoSourceRef, todoLegacyReconciliationDigest, validatePhaseTodoRevision,
167
176
  validateTodoRevision, validateTodoRevisionSet,
168
177
  } from './todo-revision.mjs';
@@ -184,11 +193,8 @@ import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
184
193
  const CLI_ERROR_SCHEMA = 'lattice.cli_error.v2';
185
194
  const DEFAULT_GANTT_SCOPE = 'live';
186
195
  const MAX_NOTE_INPUT_BYTES = 16_384;
187
- const ACTOR_ENV_KEYS = Object.freeze([
188
- 'LATTICE_TODO_ACTOR_HOST',
189
- 'LATTICE_TODO_ACTOR_SESSION',
190
- 'LATTICE_TODO_ACTOR_AGENT',
191
- ]);
196
+ /** u03 A58: `todo done` without --evidence/--message records this text as its evidence. */
197
+ const DONE_WITHOUT_EVIDENCE_MESSAGE = '証拠の指定なしで完了した。\n';
192
198
 
193
199
  /**
194
200
  * `revise` / `revise-set` / `revise-phase` / `migrate`が配布する名前付き入力契約のJSON
@@ -218,20 +224,29 @@ async function runTodoSchemaCommand(command, stdout) {
218
224
  stdout.write(`${JSON.stringify(schema)}\n`);
219
225
  }
220
226
 
221
- function typedFailure(stderr, error) {
227
+ function typedFailure(stderr, error, context = {}) {
222
228
  const payload = {
223
229
  schema: CLI_ERROR_SCHEMA,
224
230
  code: error.code,
225
231
  message: error.message,
232
+ detail: withRefusalGuidance(error, context),
226
233
  };
227
- if (error.detail !== null && typeof error.detail === 'object'
228
- && !Array.isArray(error.detail) && Object.keys(error.detail).length > 0) {
229
- payload.detail = error.detail;
230
- }
231
234
  stderr.write(`${JSON.stringify(payload)}\n`);
232
235
  return 1;
233
236
  }
234
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
+
235
250
  /**
236
251
  * An error that reached here is, by definition, one none of the typed
237
252
  * TodoStoreError/TypeError branches recognized — the one case where the
@@ -261,12 +276,40 @@ const TODO_COMMAND_NAMES = Object.freeze([
261
276
  'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
262
277
  ]);
263
278
 
264
- function typedArgumentFailure(stderr, code, message, detail) {
265
- 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
+ };
266
284
  stderr.write(`${JSON.stringify(payload)}\n`);
267
285
  return 2;
268
286
  }
269
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
+
270
313
  function supportsAtomicStoreCommit(argv) {
271
314
  const command = argv[0];
272
315
  if (command === 'note') return argv[1] !== 'list';
@@ -288,7 +331,7 @@ function atomicStoreCommitUnsupported(stderr, argv) {
288
331
  'todo_command_does_not_mutate_only_the_store', {
289
332
  command: argv.slice(0, 3),
290
333
  next_action: 'remove_--commit-store_or_use_a_supported_todo_write_command',
291
- });
334
+ }, guidanceContext(argv));
292
335
  }
293
336
 
294
337
  function resolveRepoRoot(cwd) {
@@ -367,9 +410,30 @@ function within(root, candidate) {
367
410
  return candidate === root || candidate.startsWith(`${root}${path.sep}`);
368
411
  }
369
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
+
370
429
  async function readMigrationInput(repoRoot, inputRef, { requireValid = true } = {}) {
371
430
  const extraction = await readAuthoringJsonFile(repoRoot, inputRef);
372
431
  if (!requireValid) return extraction;
432
+ assertValidMigrationExtraction(extraction);
433
+ return extraction;
434
+ }
435
+
436
+ function assertValidMigrationExtraction(extraction) {
373
437
  if (![TODO_EXTRACTION_SCHEMA_V3, TODO_EXTRACTION_SCHEMA_V4].includes(extraction?.schema)) {
374
438
  throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'todo_extraction_schema_unsupported', undefined, {
375
439
  expected: TODO_EXTRACTION_SCHEMA_V4,
@@ -394,7 +458,6 @@ async function readMigrationInput(repoRoot, inputRef, { requireValid = true } =
394
458
  };
395
459
  throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined, detail);
396
460
  }
397
- return extraction;
398
461
  }
399
462
 
400
463
  async function readRevisionInput(repoRoot, inputRef, {
@@ -402,8 +465,9 @@ async function readRevisionInput(repoRoot, inputRef, {
402
465
  invalidCode = 'REVISION_INVALID',
403
466
  invalidReason = 'revision_schema_or_digest_invalid',
404
467
  explain = explainTodoRevision,
468
+ complete = async (value) => value,
405
469
  } = {}) {
406
- const revision = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode });
470
+ const revision = await complete(await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode }));
407
471
  if (!validate(revision)) {
408
472
  const explained = explain === null ? null : explain(revision);
409
473
  throw new TodoStoreError(invalidCode, invalidReason, undefined,
@@ -558,47 +622,6 @@ async function readStructureSetDraft(repoRoot, inputRef) {
558
622
  });
559
623
  }
560
624
 
561
- function sanitizeActorIdentifier(raw, fallback) {
562
- const compact = String(raw ?? '').replace(/[^0-9A-Za-z._-]/gu, '-').replace(/^-+/u, '').slice(0, 128);
563
- return isTodoIdentifier(compact) ? compact : fallback;
564
- }
565
-
566
- /**
567
- * 名乗りの無い操作のhost(ADR 0197)。journalは公開repositoryへcommitされるので、OSのhost名は
568
- * 書かない——host名はOSが決めた自由文で、持ち主の名前を含むことがある。端末ごとの識別子から
569
- * 一方向に導いたlabelを使い、端末の区別は保つ。識別子を読めず作れない端末は`host`になる。
570
- */
571
- function defaultActorHost(env) {
572
- const terminalId = readOrCreateTerminalIdSync({ env });
573
- return terminalId === null ? 'host' : terminalPublicLabel(terminalId);
574
- }
575
-
576
- function mutationActor(env) {
577
- const provided = ACTOR_ENV_KEYS.map((key) => ({ key, value: env[key] }));
578
- const invalidEnvironment = provided
579
- .filter(({ value }) => typeof value === 'string' && value.length > 0 && !isTodoIdentifier(value))
580
- .map(({ key }) => key);
581
- if (invalidEnvironment.length > 0) {
582
- throw new TodoStoreError('ACTOR_UNRESOLVED', 'actor_environment_invalid', undefined, {
583
- required_environment: ACTOR_ENV_KEYS,
584
- missing_environment: [],
585
- invalid_environment: invalidEnvironment,
586
- next_action: 'set_required_actor_environment_and_retry',
587
- });
588
- }
589
- return {
590
- host: isTodoIdentifier(env.LATTICE_TODO_ACTOR_HOST)
591
- ? env.LATTICE_TODO_ACTOR_HOST
592
- : defaultActorHost(env),
593
- session: isTodoIdentifier(env.LATTICE_TODO_ACTOR_SESSION)
594
- ? env.LATTICE_TODO_ACTOR_SESSION
595
- : 'session',
596
- agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
597
- ? env.LATTICE_TODO_ACTOR_AGENT
598
- : sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'),
599
- };
600
- }
601
-
602
625
  /**
603
626
  * gate_readyの札が出た理由と次の一歩をtypedに言う(ADR 0148裁定8)。
604
627
  *
@@ -636,12 +659,46 @@ function terminalAuditDoneAdvisory(plan, phases) {
636
659
  };
637
660
  }
638
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
+
639
696
  async function mutate({
640
697
  repoRoot, env, planKey, taskId, kind, payload, evidenceRef, evidenceMessage = null,
641
698
  advisory = null, noteContext = null, structureContext = null, featureContext = null,
642
699
  testResultRef = null,
643
700
  }) {
644
- const actor = mutationActor(env);
701
+ const actor = resolveTodoActor(env);
645
702
  const evidence = evidenceRef === null && evidenceMessage === null
646
703
  ? null
647
704
  : await resolveDoneEvidence({
@@ -678,10 +735,11 @@ async function mutate({
678
735
  const authoredTask = plan.tasks.find(({ task_id: current }) => current === event.task_id);
679
736
  if (authoredTask === undefined) throw new TypeError('mutation task content is missing');
680
737
  // advisoryは呼び出し側(startTask)がstart用に既に組んでいればそれを尊重し、無ければ
681
- // done時だけ終端監査の要否を調べる。block/unblock/reopenはnullのまま(既存挙動を変えない)。
738
+ // done時は終端監査の要否、reopen時は受入が古くなったphase(u03 A15)を返す。block/unblockはnull。
682
739
  // Phase状態はsnapshot(v1にはphasesキーが無い)でなく、appendTodoEventが別途返す
683
740
  // 導出ビュー`phases`から読む。
684
- 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);
685
743
  const includesNoteContext = kind === 'start';
686
744
  if (includesNoteContext && noteContext === null) {
687
745
  throw new TypeError('start mutation requires note context');
@@ -703,6 +761,7 @@ async function mutate({
703
761
  advisory: resolvedAdvisory,
704
762
  ...(includesNoteContext ? {
705
763
  design_memo: designMemoProjection(authoredTask),
764
+ done_condition: authoredTask.done_condition ?? null,
706
765
  note_context: noteContext,
707
766
  structure_context: structureContext,
708
767
  ...(featureContext === null ? {} : { feature_context: featureContext }),
@@ -713,6 +772,79 @@ async function mutate({
713
772
  return result;
714
773
  }
715
774
 
775
+ /**
776
+ * 恒久除去(u12)。どの状態からでも`{reason, prior_status}`で閉じる。
777
+ * in-progressは、最新のauthored startに束ねられた未acceptのintakeをRuntimeの解放手順で
778
+ * 先に解放してから閉じる(u03 A14r)。
779
+ * 既にretiredなら成功を返しeventは足さない(応答を失った再試行をエラーにしない)。
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
+
820
+ async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
821
+ const store = await readTodoStore({ repoRoot });
822
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
823
+ const state = member?.tasks.find(({ task_id: current }) => current === taskId);
824
+ if (state === undefined) {
825
+ // 未知のplan/taskはStoreの既存の拒否をそのまま通す。
826
+ return mutate({ repoRoot, env, planKey, taskId, kind: 'retire', payload: { reason }, evidenceRef: null });
827
+ }
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
+ });
846
+ }
847
+
716
848
  async function startStructureContext({ repoRoot, store, planKey, taskId }) {
717
849
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
718
850
  if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active');
@@ -773,7 +905,21 @@ function designMemoProjection(task) {
773
905
  * silent degradeせず、呼び出し側でstart自体を止める。
774
906
  */
775
907
  async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
776
- 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
+ }
777
923
  // 調整方式の宣言(ob03)。未宣言はnullで、「まだ選んでいない」を意味する。
778
924
  const coordinationMode = store.members
779
925
  .find(({ descriptor }) => descriptor.plan_key === planKey)?.coordination?.mode ?? null;
@@ -787,15 +933,12 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
787
933
  scope_expansion_recommendations: [],
788
934
  uncovered_active_task_ids: projection.active_set
789
935
  .filter((task) => task.plan_key === planKey).map(({ task_id: id }) => id),
790
- self_unknowns: [{ kind: 'witness_missing', ref: 'no_independence_record' }],
936
+ self_unknowns: [{ kind: 'witness_missing', ref: unusable ?? 'no_independence_record' }],
791
937
  guidance: selectIndependenceGuidance({
792
938
  coverage: 'missing', taskDeclared: false, taskStale: false, coordinationMode,
793
939
  }),
794
940
  };
795
941
  }
796
- // 記録があるなら鮮度の判定にHEADが要る。ここで読めないのは判定不能であり、
797
- // 助言なしで通してよい状態ではない。
798
- const currentBaseSha = currentHeadSha(repoRoot);
799
942
  const changedPaths = artifact.base_sha !== null && artifact.base_sha !== currentBaseSha
800
943
  ? changedPathsSince(repoRoot, artifact.base_sha) : null;
801
944
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
@@ -847,7 +990,7 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
847
990
  }
848
991
 
849
992
  async function startTask({
850
- repoRoot, env, planKey, taskId, overrideReason, parallelFrontier,
993
+ repoRoot, env, planKey, taskId, overrideReason,
851
994
  }) {
852
995
  const store = await readTodoStore({ repoRoot });
853
996
  // startはready判定にしかprojectionを使わず、resultを出力しない。
@@ -855,12 +998,7 @@ async function startTask({
855
998
  const readyTask = projection.next_ready.find((task) => (
856
999
  task.plan_key === planKey && task.task_id.toLowerCase() === taskId.toLowerCase()
857
1000
  ));
858
- const targetReady = readyTask !== undefined;
859
- // `--parallel-frontier`は方針の記録口で、対象がreadyでないときにだけ用法誤り。
860
- // 複数readyのplain startや直列理由の文言審査で着手を止めない(ADR 0180)。
861
- if (parallelFrontier && !targetReady) {
862
- throw new TodoStoreError('PARALLEL_DISPATCH_INVALID', 'parallel_frontier_not_applicable');
863
- }
1001
+ // u03 B8: `--parallel-frontier` is a policy flag; on a non-ready target it is simply ignored.
864
1002
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
865
1003
  if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active');
866
1004
  const taskMatches = member.plan.tasks.filter(({ task_id: candidate }) => (
@@ -878,6 +1016,8 @@ async function startTask({
878
1016
  });
879
1017
  }
880
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;
881
1021
  // noteはjournal appendより前に読む。壊れていてもstartは通す(ADR 0166 / 0181)。
882
1022
  let noteContext;
883
1023
  try {
@@ -898,24 +1038,24 @@ async function startTask({
898
1038
  next_action: `lattice todo note list --plan ${planKey} --json`,
899
1039
  };
900
1040
  }
901
- // 助言はjournalへ書く前に確定させる。計算できないならstart自体を止める。
1041
+ // 助言はjournalへ書く前に確定させる。助言はstartを止めない(u03 B1–B6)。
902
1042
  const advisory = await startAdvisory({
903
1043
  repoRoot, store, projection, planKey, taskId: resolvedTaskId,
904
1044
  });
905
- const refusal = independenceStartRefusal(advisory.guidance);
906
- if (refusal !== null) {
907
- throw new TodoStoreError('INDEPENDENCE_UNVERIFIED', refusal.code, refusal.message, {
908
- plan_key: planKey,
909
- task_id: resolvedTaskId,
910
- next_action: refusal.next_action,
911
- });
912
- }
913
1045
  const structureContext = await startStructureContext({
914
1046
  repoRoot, store, planKey, taskId: resolvedTaskId,
915
1047
  });
916
- const featureContext = await readTaskBackchainContext({
917
- repoRoot, plan: member.plan, taskId: resolvedTaskId,
918
- });
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
+ }
919
1059
  return mutate({ repoRoot, env, planKey, taskId: resolvedTaskId, kind: 'start',
920
1060
  payload: { override_reason: overrideReason }, evidenceRef: null, advisory, noteContext,
921
1061
  structureContext, featureContext });
@@ -963,7 +1103,7 @@ export async function rebindStart({ repoRoot, env, planKey, taskId, reason }) {
963
1103
  }
964
1104
 
965
1105
  async function retractStart({ repoRoot, env, planKey, taskId, reason }) {
966
- const actor = mutationActor(env);
1106
+ const actor = resolveTodoActor(env);
967
1107
  const store = await readTodoStore({ repoRoot });
968
1108
  const binding = resolveTodoStartRetractionBinding(store, { planKey, taskId, actor });
969
1109
  return withStartRetractionGuard({
@@ -1082,7 +1222,7 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1082
1222
  const { event, snapshot, phases } = await appendTodoEvent({
1083
1223
  validateProspectiveEvent,
1084
1224
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1085
- event: { kind, phase_id: phaseId, actor: mutationActor(env), payload },
1225
+ event: { kind, phase_id: phaseId, actor: resolveTodoActor(env), payload },
1086
1226
  });
1087
1227
  // snapshot.phasesはv1(phase無しplan)には存在しない。導出ビュー`phases`を見る
1088
1228
  // (これは暗黙のterminal-audit Phaseにも常に埋まっている)。
@@ -1110,7 +1250,7 @@ async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
1110
1250
  const { event } = await appendTodoEvent({
1111
1251
  validateProspectiveEvent,
1112
1252
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1113
- event: { kind: 'coordination_mode', actor: mutationActor(env), payload: { mode, reason } },
1253
+ event: { kind: 'coordination_mode', actor: resolveTodoActor(env), payload: { mode, reason } },
1114
1254
  });
1115
1255
  const result = {
1116
1256
  schema: 'lattice.todo_coordination_mode_result.v1', project_id: event.project_id,
@@ -1127,8 +1267,82 @@ async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
1127
1267
  return result;
1128
1268
  }
1129
1269
 
1130
- /** 開発中に発見した依存(同一plan内・plan跨ぎとも)を、consumer planのplan-scoped chainへ接続する。 */
1131
- 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({
1132
1346
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
1133
1347
  }) {
1134
1348
  const store = await readTodoStore({ repoRoot });
@@ -1165,7 +1379,7 @@ async function dependencyConnect({
1165
1379
  validateProspectiveEvent,
1166
1380
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: toPlanKey,
1167
1381
  event: {
1168
- kind: 'cross_plan_dependency', actor: mutationActor(env), payload: { from, to, reason },
1382
+ kind: 'cross_plan_dependency', actor: resolveTodoActor(env), payload: { from, to, reason },
1169
1383
  },
1170
1384
  });
1171
1385
  const result = {
@@ -1179,13 +1393,26 @@ async function dependencyConnect({
1179
1393
  return result;
1180
1394
  }
1181
1395
 
1182
- // 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)。端点で一意に生きた接続を特定し、
1183
1411
  // その接続eventが積まれているplanのplan-scoped chainへ除去eventを積む。
1184
- async function dependencyDisconnect({
1412
+ async function dependencyDisconnectLedger({
1185
1413
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
1186
1414
  }) {
1187
- // 修理扉: 越境依存の固定digestが陳腐化した store でも disconnect だけは通す(todo-store.mjs 参照)
1188
- const store = await readTodoStore({ repoRoot, tolerateStaleBindings: true });
1415
+ const store = await readTodoStore({ repoRoot });
1189
1416
  const live = projectTodoCrossPlanDependencies(store.members).filter((dependency) => (
1190
1417
  dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1191
1418
  && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId
@@ -1194,6 +1421,7 @@ async function dependencyDisconnect({
1194
1421
  throw new TodoStoreError('DEPENDENCY_INVALID', 'cross_plan_dependency_not_found', undefined, {
1195
1422
  from: { plan_key: fromPlanKey, task_id: fromTaskId },
1196
1423
  to: { plan_key: toPlanKey, task_id: toTaskId },
1424
+ ...(fromPlanKey === toPlanKey ? { next_action: `lattice plan show ${fromPlanKey} --json` } : {}),
1197
1425
  });
1198
1426
  }
1199
1427
  const [target] = live;
@@ -1202,9 +1430,8 @@ async function dependencyDisconnect({
1202
1430
  const { event } = await appendTodoEvent({
1203
1431
  validateProspectiveEvent,
1204
1432
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: owner.plan.plan_key,
1205
- tolerateStaleBindings: true,
1206
1433
  event: {
1207
- kind: 'cross_plan_dependency_removed', actor: mutationActor(env),
1434
+ kind: 'cross_plan_dependency_removed', actor: resolveTodoActor(env),
1208
1435
  payload: { target_event_digest: target.event_digest, reason },
1209
1436
  },
1210
1437
  });
@@ -1236,7 +1463,10 @@ async function phaseStatus({ repoRoot, planKey }) {
1236
1463
  // v4/v5の実Phaseがgate_readyになった場合も同じ理由で同じ案内が要る。
1237
1464
  const phases = member.phases.map((phase) => ({
1238
1465
  ...phase,
1239
- 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'
1240
1470
  ? [
1241
1471
  auditGateGuidance(member.plan.plan_key, phase.phase_id),
1242
1472
  ...(structureFinalization.required && structureFinalization.status !== 'fresh'
@@ -1354,18 +1584,10 @@ async function phaseBaseline({ repoRoot, env, reason, exceptPlanKeys }) {
1354
1584
  }
1355
1585
 
1356
1586
  async function migrate({ repoRoot, inputRef }) {
1357
- const extraction = await readMigrationInput(repoRoot, inputRef);
1358
- // unresolved/空集合の早期gateは、compileTodoExtraction内部の同名gateをここでも
1359
- // 先に通しておくことで、既存のエラー優先順位を変えない。
1587
+ const { extraction, defaultedPendingTaskIds } = defaultUnknownDispositions(
1588
+ await readMigrationInput(repoRoot, inputRef, { requireValid: false }));
1589
+ assertValidMigrationExtraction(extraction);
1360
1590
  // dispatch_shapeは結果へ載せる観測であり、直列度では書込みを拒まない(ADR 0180)。
1361
- const unresolvedTaskIds = extraction.tasks
1362
- .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
1363
- .map(({ task_id: taskId }) => taskId);
1364
- if (unresolvedTaskIds.length > 0) {
1365
- throw new TodoStoreError('MIGRATION_UNRESOLVED', 'unknown_requires_evidence', undefined, {
1366
- task_ids: unresolvedTaskIds,
1367
- });
1368
- }
1369
1591
  const registered = extraction.tasks.filter(({ disposition }) => disposition.startsWith('register_'));
1370
1592
  const connectionOnly = isTodoExtractionConnectionOnly(extraction);
1371
1593
  if (registered.length === 0 && !connectionOnly) {
@@ -1405,6 +1627,7 @@ async function migrate({ repoRoot, inputRef }) {
1405
1627
  plan_version: imported.plan.plan_version,
1406
1628
  extraction_digest: extraction.extraction_digest,
1407
1629
  imported_task_count: registered.length,
1630
+ defaulted_pending_task_ids: defaultedPendingTaskIds,
1408
1631
  completed_task_count: extraction.tasks.filter(({ disposition }) => disposition === 'register_done').length,
1409
1632
  plan_ref: imported.descriptor.plan_ref,
1410
1633
  journal_ref: imported.descriptor.journal_ref,
@@ -1553,7 +1776,8 @@ function extractionAuthoringViolations(extraction, now = new Date()) {
1553
1776
  }
1554
1777
 
1555
1778
  async function migrateDryRun({ repoRoot, inputRef }) {
1556
- const extraction = await readMigrationInput(repoRoot, inputRef, { requireValid: false });
1779
+ const { extraction, defaultedPendingTaskIds } = defaultUnknownDispositions(
1780
+ await readMigrationInput(repoRoot, inputRef, { requireValid: false }));
1557
1781
  const violations = [];
1558
1782
  const tasks = Array.isArray(extraction?.tasks) ? extraction.tasks : [];
1559
1783
  const designMemoSchema = [TODO_EXTRACTION_SCHEMA_V3, TODO_EXTRACTION_SCHEMA_V4].includes(extraction?.schema);
@@ -1591,13 +1815,6 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1591
1815
  violations.push(violation);
1592
1816
  }
1593
1817
  }
1594
- const unresolvedTaskIds = tasks
1595
- .filter(({ disposition }) => disposition === 'unknown_requires_evidence')
1596
- .map(({ task_id: taskId }) => taskId).filter(isTodoIdentifier);
1597
- if (unresolvedTaskIds.length > 0) {
1598
- violations.push({ code: 'unknown_requires_evidence', path: '/tasks',
1599
- task_ids: unresolvedTaskIds.slice(0, 64), next_action: 'adjudicate_task_disposition' });
1600
- }
1601
1818
  const registered = tasks.filter(({ disposition }) => typeof disposition === 'string'
1602
1819
  && disposition.startsWith('register_'));
1603
1820
  const connectionOnly = schemaValid && isTodoExtractionConnectionOnly(extraction);
@@ -1609,7 +1826,7 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1609
1826
  let dispatchShape = null;
1610
1827
  let plannedPlan = null;
1611
1828
  let plannedConnection = null;
1612
- if (schemaValid && unresolvedTaskIds.length === 0 && (registered.length > 0 || connectionOnly)) {
1829
+ if (schemaValid && (registered.length > 0 || connectionOnly)) {
1613
1830
  try {
1614
1831
  const compiled = compileTodoExtraction(extraction, repoRoot);
1615
1832
  if (connectionOnly) {
@@ -1665,6 +1882,7 @@ async function migrateDryRun({ repoRoot, inputRef }) {
1665
1882
  plan_key: isTodoIdentifier(extraction?.plan_key) ? extraction.plan_key : null,
1666
1883
  violations: bounded,
1667
1884
  overflow_count: Math.max(0, violations.length - bounded.length),
1885
+ defaulted_pending_task_ids: defaultedPendingTaskIds,
1668
1886
  planned: plannedConnection !== null ? {
1669
1887
  connection_only: true,
1670
1888
  source: plannedConnection.source,
@@ -1698,7 +1916,7 @@ async function revise({ repoRoot, env, planKey, inputRef }) {
1698
1916
  }
1699
1917
  return applyTodoRevision({
1700
1918
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
1701
- actor: mutationActor(env), recordedAt: new Date().toISOString(),
1919
+ actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
1702
1920
  });
1703
1921
  }
1704
1922
 
@@ -1711,7 +1929,7 @@ async function reviseSet({ repoRoot, env, inputRef }) {
1711
1929
  });
1712
1930
  return applyTodoRevisionSet({
1713
1931
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revisionSet,
1714
- actor: mutationActor(env), recordedAt: new Date().toISOString(),
1932
+ actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
1715
1933
  });
1716
1934
  }
1717
1935
 
@@ -1720,10 +1938,19 @@ async function revisePhase({ repoRoot, env, planKey, inputRef }) {
1720
1938
  validate: validatePhaseTodoRevision, invalidCode: 'REVISION_INVALID',
1721
1939
  invalidReason: 'phase_revision_schema_or_digest_invalid',
1722
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
+ },
1723
1950
  });
1724
1951
  if (revision.plan_key !== planKey) throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
1725
1952
  return applyPhaseTodoRevision({ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
1726
- revision, actor: mutationActor(env), recordedAt: new Date().toISOString() });
1953
+ revision, actor: resolveTodoActor(env), recordedAt: new Date().toISOString() });
1727
1954
  }
1728
1955
 
1729
1956
  async function splitTodo({ repoRoot, env, planKey, inputRef }) {
@@ -1739,7 +1966,7 @@ async function splitTodo({ repoRoot, env, planKey, inputRef }) {
1739
1966
  });
1740
1967
  }
1741
1968
  const compiled = await compileTodoSplit({ repoRoot, member, proposal });
1742
- const actor = mutationActor(env);
1969
+ const actor = resolveTodoActor(env);
1743
1970
  const recordedAt = new Date().toISOString();
1744
1971
  // splitのmigrationは既存taskへのidentity写像だけである。宣言を純粋に移行・検査し、
1745
1972
  // 同じcanonical bytesをwitness先へ書けることまでapply前に確定する。これにより、
@@ -1804,7 +2031,7 @@ async function status({ repoRoot }) {
1804
2031
 
1805
2032
  async function adoptDashboardRoot({ repoRoot, env }) {
1806
2033
  const store = await readTodoStoreStable({ repoRoot });
1807
- const actor = mutationActor(env);
2034
+ const actor = resolveTodoActor(env);
1808
2035
  const identity = await resolveProjectIdentity({ repoRoot, projectId: store.project_id, env });
1809
2036
  await adoptTodoDashboardActivity({
1810
2037
  repoRoot, projectId: store.project_id, displayName: identity.displayName,
@@ -1838,7 +2065,8 @@ async function todoDetail({ repoRoot, planKey, taskId }) {
1838
2065
  project_id: store.project_id,
1839
2066
  plan_key: planKey,
1840
2067
  plan_version: member.plan.plan_version,
1841
- task,
2068
+ // v7以前のtaskは欄を持たないのでnullで投影する(u12)。
2069
+ task: { ...task, done_condition: task.done_condition ?? null },
1842
2070
  design_memo: designMemoProjection(task),
1843
2071
  state,
1844
2072
  note_context: context,
@@ -1871,7 +2099,7 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
1871
2099
  planKey,
1872
2100
  planVersion: member.plan.plan_version,
1873
2101
  taskId: task?.task_id ?? null,
1874
- actor: mutationActor(env),
2102
+ actor: resolveTodoActor(env),
1875
2103
  recordedAt: new Date().toISOString(),
1876
2104
  body,
1877
2105
  supersedes,
@@ -2237,7 +2465,7 @@ async function structureCompile({ repoRoot, env, planKey, inputRef }) {
2237
2465
  next_action: `lattice todo structure --plan ${planKey} --json`,
2238
2466
  });
2239
2467
  }
2240
- const actor = mutationActor(env);
2468
+ const actor = resolveTodoActor(env);
2241
2469
  const observation = await collectTodoStructureAuthoritativeObservation({ repoRoot, structureSet });
2242
2470
  const sourceEvidence = observation.source_evidence;
2243
2471
  const gitProvenance = observation.git_provenance;
@@ -2363,7 +2591,7 @@ async function recordStructureRealization({ repoRoot, planKey, taskId, realizati
2363
2591
 
2364
2592
  async function structureRealize({ repoRoot, env, planKey, taskId, inputRef }) {
2365
2593
  const realization = await readStructureRealizationInput(repoRoot, inputRef);
2366
- const actor = mutationActor(env);
2594
+ const actor = resolveTodoActor(env);
2367
2595
  if (realization.plan_key !== planKey || realization.task_id !== taskId) {
2368
2596
  throw new TodoStoreError('STRUCTURE_REALIZATION_BINDING_MISMATCH',
2369
2597
  'cli_target_mismatch', undefined, {
@@ -2450,7 +2678,7 @@ async function structureRealizeActual({
2450
2678
  commit_oids: resolveStructureRealizationCommits(repoRoot, commitRefs),
2451
2679
  realized,
2452
2680
  supersedes: previous?.realization_digest ?? null,
2453
- actor: mutationActor(env),
2681
+ actor: resolveTodoActor(env),
2454
2682
  recorded_at: new Date().toISOString(),
2455
2683
  realization_digest: '',
2456
2684
  };
@@ -2499,7 +2727,7 @@ async function structureFinalize({ repoRoot, env, planKey }) {
2499
2727
  realizations.push(...chain);
2500
2728
  effectiveTransforms.set(task.task_id, latest.realized);
2501
2729
  }
2502
- const actor = mutationActor(env);
2730
+ const actor = resolveTodoActor(env);
2503
2731
  const observation = await collectTodoStructureAuthoritativeObservation({
2504
2732
  repoRoot, structureSet: source, effectiveTransforms,
2505
2733
  });
@@ -3469,20 +3697,40 @@ async function seamProposalsForGantt({ repoRoot, store }) {
3469
3697
 
3470
3698
  export async function renderTodoGanttForProject({
3471
3699
  repoRoot, stable = false, displayName = null, env = process.env, readModel = null,
3472
- scope = DEFAULT_GANTT_SCOPE,
3700
+ scope = DEFAULT_GANTT_SCOPE, degraded = false,
3473
3701
  }) {
3474
3702
  const store = readModel
3475
3703
  ?? (stable ? await readTodoStoreStable({ repoRoot }) : await readTodoStore({ repoRoot }));
3476
3704
  const identity = displayName === null
3477
3705
  ? await resolveProjectIdentity({ repoRoot, projectId: store.project_id, env })
3478
3706
  : { displayName };
3479
- const presentation = await loadTodoGanttPresentation({ repoRoot, readModel: store });
3480
- const [independence, seamProposals, notes, structures] = await Promise.all([
3481
- independenceForGantt({ repoRoot, store }),
3482
- seamProposalsForGantt({ repoRoot, store }),
3483
- notesForGantt({ repoRoot, store }),
3484
- loadTodoStructurePresentation({ repoRoot, readModel: store }),
3485
- ]);
3707
+ // degraded (display of an unverified/last_verified store): every current-file overlay is
3708
+ // omitted, since computing one can reach strict Store validation.
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
+ }
3726
+ const [independence, seamProposals, notes, structures] = degraded
3727
+ ? [null, null, { contexts: null, warnings: [], headBindings: [] }, null]
3728
+ : await Promise.all([
3729
+ independenceForGantt({ repoRoot, store }),
3730
+ seamProposalsForGantt({ repoRoot, store }),
3731
+ notesForGantt({ repoRoot, store }),
3732
+ loadTodoStructurePresentation({ repoRoot, readModel: store }),
3733
+ ]);
3486
3734
  const layout = layoutTodoGantt(store, { scope, independence, seamProposals });
3487
3735
  // When the diagram hides history, the page also carries the full diagram so
3488
3736
  // the reader can bring it back in place. Nothing is hidden under `all`.
@@ -3490,8 +3738,9 @@ export async function renderTodoGanttForProject({
3490
3738
  ? null : layoutTodoGantt(store, {
3491
3739
  scope: 'all', independence, seamProposals,
3492
3740
  });
3493
- const narrative = await loadNarratives(store, repoRoot);
3494
- const anchorOutcomes = verifyNarrativeAnchors({
3741
+ const narrative = degraded ? { narratives: [], bindings: [] }
3742
+ : await loadNarratives(store, repoRoot);
3743
+ const anchorOutcomes = degraded ? [] : verifyNarrativeAnchors({
3495
3744
  readModel: store,
3496
3745
  narratives: narrative.narratives,
3497
3746
  });
@@ -3506,16 +3755,16 @@ export async function renderTodoGanttForProject({
3506
3755
  const memberBindings = store.members.map((member) => ({
3507
3756
  plan_key: member.descriptor.plan_key,
3508
3757
  topology_digest: member.plan.topology_digest,
3509
- journal_head_digest: member.journal.events.at(-1).event_digest,
3758
+ journal_head_digest: member.journal.events.at(-1)?.event_digest ?? null,
3510
3759
  }));
3511
3760
  const metadata = {
3512
3761
  manifest_digest: store.manifest.manifest_digest,
3513
3762
  member_bindings: memberBindings,
3514
3763
  narrative_bindings_digest: digestTodoArtifact(narrativeBindings),
3515
- presentation_digest: presentation.presentation_digest,
3764
+ presentation_digest: presentation?.presentation_digest ?? null,
3516
3765
  layout_digest: digestTodoArtifact(layout),
3517
3766
  note_bindings_digest: digestTodoArtifact(notes.headBindings),
3518
- structure_projection_digest: structures.projection_digest,
3767
+ structure_projection_digest: structures?.projection_digest ?? null,
3519
3768
  renderer_version: TODO_GANTT_RENDERER_VERSION,
3520
3769
  project_display_name: identity.displayName,
3521
3770
  folded_task_count: layout.scope.folded_task_count,
@@ -3531,36 +3780,106 @@ export async function renderTodoGanttForProject({
3531
3780
  noteContexts: notes.contexts,
3532
3781
  noteWarnings: notes.warnings,
3533
3782
  structurePresentation: structures,
3783
+ notices,
3534
3784
  });
3535
3785
  return { store, metadata, memberBindings, rendered };
3536
3786
  }
3537
3787
 
3788
+ /**
3789
+ * The two serving paths (public daemon, local live gantt) render the Store's typed
3790
+ * display result: a read-only view refuses nothing, so an inconsistent store is shown
3791
+ * as a banner state, never a 500. One-shot CLI renders keep their strict reads.
3792
+ */
3793
+ export function createTodoGanttDisplayServing({
3794
+ repoRoot, projectId, scope = DEFAULT_GANTT_SCOPE, env = process.env, reader = null, ...readers
3795
+ }) {
3796
+ reader ??= createTodoGanttDisplayReader({ repoRoot, ...readers });
3797
+ return {
3798
+ render: async ({ displayName }) => {
3799
+ const result = await reader.read();
3800
+ const { html, banner_html: bannerHtml = null } = await renderGanttDisplayResult({
3801
+ repoRoot, result, displayName, scope, env,
3802
+ });
3803
+ return { html, banner_html: bannerHtml, head_digest: await ganttDisplayHead({ repoRoot, result }),
3804
+ // 配信のたびに読む。外部ペインを差した/外した側にdaemon再起動を要求しない。
3805
+ external_pane: result.state === 'unavailable' ? null
3806
+ : await readProjectExternalPane({ repoRoot, projectId }) };
3807
+ },
3808
+ readHead: async () => ganttDisplayHead({ repoRoot, result: await reader.read() }),
3809
+ };
3810
+ }
3811
+
3812
+ async function ganttDisplayHead({ repoRoot, result }) {
3813
+ return displayHeadDigest(result, result.state === 'verified'
3814
+ ? await ganttLiveHeadDigest({ repoRoot, store: result.store }) : null);
3815
+ }
3816
+
3817
+ async function renderGanttDisplayResult({ repoRoot, result, displayName, scope, env }) {
3818
+ const render = async (store, state, dropped) => {
3819
+ const { rendered } = await renderTodoGanttForProject({
3820
+ repoRoot, stable: true, displayName, scope, env, readModel: store, degraded: true,
3821
+ });
3822
+ return { html: rendered.html, banner_html: degradedBannerHtml({
3823
+ state, verifiedAt: result.verified_at, inconsistency: result.inconsistency, dropped }) };
3824
+ };
3825
+ const storeDropped = Array.isArray(result.dropped_members) ? result.dropped_members : [];
3826
+ switch (result.state) {
3827
+ case 'verified': {
3828
+ const { rendered } = await renderTodoGanttForProject({
3829
+ repoRoot, stable: true, displayName, scope, env, readModel: result.store,
3830
+ });
3831
+ return { html: rendered.html };
3832
+ }
3833
+ case 'unverified': {
3834
+ const { store, dropped } = projectUnverifiedStore(result.store);
3835
+ const all = [...storeDropped, ...dropped];
3836
+ if (store.members.length === 0) {
3837
+ return { html: emptyStateHtml({ inconsistency: result.inconsistency, dropped: all }) };
3838
+ }
3839
+ return render(store, 'unverified', all);
3840
+ }
3841
+ case 'last_verified': return render(result.store, 'last_verified', storeDropped);
3842
+ case 'unavailable':
3843
+ return { html: emptyStateHtml({ inconsistency: result.inconsistency, dropped: storeDropped }) };
3844
+ default:
3845
+ throw new TypeError(`unknown Store display state: ${result.state}`);
3846
+ }
3847
+ }
3848
+
3849
+ // Reached only when the display read carries no project id (unavailable) and the repository
3850
+ // registered none: the empty state is still served, under this fixed route id.
3851
+ const UNREGISTERED_PROJECT_ID = 'unregistered-project';
3852
+
3853
+ /**
3854
+ * Start the local live gantt from the display read, so an inconsistent store does not stop it
3855
+ * from starting (the same stop the typed states remove from the page itself).
3856
+ */
3857
+ export async function startTodoGanttDisplayLive({
3858
+ repoRoot, port = 0, env = process.env, scope = DEFAULT_GANTT_SCOPE, onShutdown = null, ...readers
3859
+ }) {
3860
+ const reader = createTodoGanttDisplayReader({ repoRoot, ...readers });
3861
+ const { projectId: carried, planKeys } = displayResultBinding(await reader.read());
3862
+ const projectId = carried ?? await readRegisteredProjectId({ repoRoot }) ?? UNREGISTERED_PROJECT_ID;
3863
+ let identity = { displayName: projectId };
3864
+ try { identity = await resolveProjectIdentity({ repoRoot, projectId, env }); } catch (error) {
3865
+ if (carried !== null) throw error; // a readable store keeps the strict identity contract
3866
+ }
3867
+ const live = await startTodoGanttLiveServer({
3868
+ projectId, displayName: identity.displayName, port, onShutdown,
3869
+ ...createTodoGanttDisplayServing({ repoRoot, projectId, scope, env, reader }),
3870
+ });
3871
+ return { live, planKeys };
3872
+ }
3873
+
3538
3874
  async function serveGantt({ repoRoot, port, stdout, env, scope = DEFAULT_GANTT_SCOPE }) {
3539
- const initialStore = await readTodoStoreStable({ repoRoot });
3540
- const identity = await resolveProjectIdentity({ repoRoot, projectId: initialStore.project_id, env });
3541
3875
  let stop;
3542
3876
  const stopped = new Promise((resolve) => { stop = resolve; });
3543
- const live = await startTodoGanttLiveServer({
3544
- projectId: initialStore.project_id,
3545
- displayName: identity.displayName,
3546
- port,
3547
- render: async () => {
3548
- const store = await readTodoStoreStable({ repoRoot });
3549
- const { rendered } = await renderTodoGanttForProject({
3550
- repoRoot, stable: true, displayName: identity.displayName, scope, readModel: store,
3551
- });
3552
- return { html: rendered.html, head_digest: await ganttLiveHeadDigest({ repoRoot, store }),
3553
- // ローカルの動的dashboardも公開daemonと同じ口を通す(毎描画で読むので差し外しが即反映される)。
3554
- external_pane: await readProjectExternalPane({ repoRoot, projectId: store.project_id }) };
3555
- },
3556
- readHead: async () => ganttLiveHeadDigest({
3557
- repoRoot, store: await readTodoStoreStable({ repoRoot }),
3558
- }),
3559
- onShutdown: process.platform === 'win32' ? stop : null,
3877
+ const { live, planKeys } = await startTodoGanttDisplayLive({
3878
+ repoRoot, port, env, scope, onShutdown: process.platform === 'win32' ? stop : null,
3560
3879
  });
3561
3880
  const result = { schema: 'lattice.todo_gantt_live_result.v3', project_id: live.projectId,
3562
3881
  resource_scope: 'project', selection_scope: scope,
3563
- included_plan_keys: initialStore.members.map(({ descriptor }) => descriptor.plan_key).sort(),
3882
+ included_plan_keys: planKeys,
3564
3883
  media_type: 'text/html; charset=utf-8', dynamic: true,
3565
3884
  host: live.host, port: live.port, project_path: live.projectPath,
3566
3885
  url: live.url, events_url: live.eventsUrl };
@@ -3620,7 +3939,7 @@ function writesTodoStore(argv) {
3620
3939
  async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = false }) {
3621
3940
  if (env.LATTICE_DASHBOARD_AUTOSTART === '0') return null;
3622
3941
  let actor;
3623
- 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; }
3624
3943
  const sessionId = actor.session;
3625
3944
  let store;
3626
3945
  try { store = await readTodoStoreStable({ repoRoot }); }
@@ -3657,8 +3976,17 @@ async function verify({ repoRoot, requestedPlanKey }) {
3657
3976
  await readTodoNoteEvents({ repoRoot, planKey: member.plan.plan_key });
3658
3977
  }
3659
3978
  const verifiedSourceInventories = new Map();
3979
+ const uncommittedEvidence = [];
3660
3980
  for (const member of members) {
3661
- 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));
3662
3990
  if (unverified !== undefined) {
3663
3991
  throw new TodoStoreError('STORE_INCONSISTENT', 'evidence_unverified', 'evidence_unverified', {
3664
3992
  plan_key: member.descriptor.plan_key,
@@ -3738,11 +4066,12 @@ async function verify({ repoRoot, requestedPlanKey }) {
3738
4066
  );
3739
4067
  }
3740
4068
  const result = {
3741
- schema: 'lattice.todo_verify_result.v3',
4069
+ schema: 'lattice.todo_verify_result.v4',
3742
4070
  project_id: store.project_id,
3743
4071
  requested_plan_key: requestedPlanKey,
3744
4072
  verified_members: verifiedMembers,
3745
4073
  snapshot_stale: verifiedMembers.some((member) => member.snapshot_stale),
4074
+ uncommitted_evidence: uncommittedEvidence,
3746
4075
  result_digest: '',
3747
4076
  };
3748
4077
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -3839,7 +4168,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
3839
4168
  return 0;
3840
4169
  } catch (error) {
3841
4170
  if (typeof error?.code === 'string' && error.detail !== null
3842
- && typeof error.detail === 'object') return typedFailure(stderr, error);
4171
+ && typeof error.detail === 'object') return typedFailure(stderr, error, guidanceContext(argv));
3843
4172
  return failInternally(error);
3844
4173
  }
3845
4174
  }
@@ -4154,26 +4483,38 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4154
4483
  action = (repoRoot) => startTask({
4155
4484
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4156
4485
  overrideReason: typeof flags['override-reason'] === 'string' ? flags['override-reason'] : null,
4157
- parallelFrontier: flags['parallel-frontier'] === true,
4158
4486
  });
4159
4487
  }
4160
4488
  } else if (argv[0] === 'done') {
4161
- const flags = matchFlagCommand(argv, ['done'], {
4162
- known: ['plan', 'task', 'evidence', 'test-result', 'message'],
4163
- required: ['plan', 'task'],
4164
- });
4489
+ const flags = matchFlagCommand(argv, ['done'], DONE_FLAG_SPEC);
4165
4490
  const hasEvidence = isAuthoringPathToken(flags?.evidence);
4166
4491
  const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
4492
+ // u03 A58: both, one or neither of --evidence/--message is accepted.
4167
4493
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4168
- && hasEvidence !== hasMessage
4494
+ && (flags.evidence === undefined || hasEvidence)
4169
4495
  && (flags['test-result'] === undefined || isAuthoringPathToken(flags['test-result']))) {
4170
- action = (repoRoot) => mutate({
4171
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4172
- kind: 'done', payload: 'authored',
4173
- evidenceRef: hasEvidence ? flags.evidence : null,
4174
- evidenceMessage: hasMessage ? flags.message : null,
4175
- testResultRef: flags['test-result'] ?? null,
4176
- });
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
+ } });
4177
4518
  }
4178
4519
  }
4179
4520
  if (action === null && argv[0] === 'retract') {
@@ -4190,10 +4531,11 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4190
4531
  known: ['plan', 'task', 'reason'], required: ['plan', 'task', 'reason'],
4191
4532
  });
4192
4533
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4193
- action = (repoRoot) => mutate({
4194
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4195
- kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
4196
- });
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
+ }) });
4197
4539
  }
4198
4540
  } else if (argv[0] === 'retire') {
4199
4541
  // 恒久除去(2026-08-29オーナー裁定)。planの形は変えず、状態遷移として工程を閉じる。
@@ -4201,9 +4543,8 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4201
4543
  known: ['plan', 'task', 'reason'], required: ['plan', 'task', 'reason'],
4202
4544
  });
4203
4545
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4204
- action = (repoRoot) => mutate({
4205
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4206
- kind: 'retire', payload: { reason: flags.reason }, evidenceRef: null,
4546
+ action = (repoRoot) => retireTask({
4547
+ repoRoot, env, planKey: flags.plan, taskId: flags.task, reason: flags.reason,
4207
4548
  });
4208
4549
  }
4209
4550
  } else if (argv[0] === 'unblock') {
@@ -4211,10 +4552,11 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4211
4552
  known: ['plan', 'task'], required: ['plan', 'task'],
4212
4553
  });
4213
4554
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
4214
- action = (repoRoot) => mutate({
4215
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
4216
- kind: 'unblock', payload: {}, evidenceRef: null,
4217
- });
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
+ }) });
4218
4560
  }
4219
4561
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
4220
4562
  const flags = matchFlagCommand(argv, ['evidence', 'promote'], {
@@ -4247,19 +4589,27 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4247
4589
  }
4248
4590
  }
4249
4591
  if (action === null) {
4592
+ // 書込みの出力は常にJSONなので、`--json`は結果を変えない旗として受ける(seat契約)。
4593
+ // 読めなかった時だけ外して読み直すので、既に`--json`を文法に持つ命令は変わらない。
4594
+ const withoutJson = argv.filter((value) => value !== '--json');
4595
+ if (withoutJson.length < argv.length && writesTodoStore(withoutJson)) {
4596
+ return runTodoCli({ argv: atomicCommit ? [...withoutJson, '--commit-store'] : withoutJson,
4597
+ cwd, stdout, stderr, env, onInternalFailure });
4598
+ }
4250
4599
  const command = typeof argv[0] === 'string' ? argv[0] : null;
4251
4600
  if (command !== null && !TODO_COMMAND_NAMES.includes(command)) {
4252
4601
  return typedArgumentFailure(stderr, 'UNKNOWN_SUBCOMMAND', 'todo_subcommand_unknown', {
4253
4602
  command, available_commands: TODO_COMMAND_NAMES,
4254
4603
  next_action: 'lattice todo --help',
4255
- });
4604
+ }, guidanceContext(argv));
4256
4605
  }
4257
4606
  const argumentHelp = argv[0] === 'gantt' && argv[1] === 'serve'
4258
4607
  ? 'lattice todo gantt serve --help'
4259
4608
  : command === null ? 'lattice todo --help' : `lattice todo ${command} --help`;
4260
- return typedArgumentFailure(stderr, 'INVALID_ARGUMENTS', 'todo_arguments_invalid', {
4261
- command, next_action: argumentHelp,
4262
- });
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));
4263
4613
  }
4264
4614
  if (atomicCommit && !supportsAtomicStoreCommit(argv)) {
4265
4615
  return atomicStoreCommitUnsupported(stderr, argv);
@@ -4282,13 +4632,17 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4282
4632
  return 0;
4283
4633
  } catch (error) {
4284
4634
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
4285
- && 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
+ }
4286
4638
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
4287
4639
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {
4288
4640
  return typedFailure(stderr, {
4289
4641
  code: 'CONTRACT_VIOLATION',
4290
4642
  message: error.message,
4291
- });
4643
+ detail: error.detail !== null && typeof error.detail === 'object' && !Array.isArray(error.detail)
4644
+ ? error.detail : undefined,
4645
+ }, guidanceContext(argv));
4292
4646
  }
4293
4647
  return failInternally(error);
4294
4648
  }