@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
@@ -13,7 +13,7 @@ import {
13
13
  isTodoIdentifier,
14
14
  todoSelfDigest,
15
15
  } from './todo-contracts.mjs';
16
- import { projectTodoStatus } from './todo-status.mjs';
16
+ import { projectTodoStatus, todoStatusBlockedReason, todoStatusTaskDisplay } from './todo-status.mjs';
17
17
  import { readTodoPlanNotesForStatus } from './todo-note-store.mjs';
18
18
  import { projectIndependenceFrontier } from './todo-independence.mjs';
19
19
  import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
@@ -32,6 +32,7 @@ import {
32
32
  createTodoStoreWriter,
33
33
  initializeAuthoredTodoStore,
34
34
  isUninitializedTodoStore,
35
+ isPhaseTodoPlanSchema,
35
36
  isPhaselessTodoPlanSchema,
36
37
  readTodoIndependenceArtifact,
37
38
  readTodoStore,
@@ -40,22 +41,33 @@ import {
40
41
  import {
41
42
  computeTodoDispatchShapeForPlan,
42
43
  } from './todo-dispatch-shape.mjs';
43
- import { readAuthoringJsonFile } from './todo-authoring-input.mjs';
44
+ import { completeCreateInput, explainFlagCommand, readAuthoringJsonFile, resolveTodoActor } from './todo-authoring-input.mjs';
45
+ import { withRefusalGuidance } from './cli-refusal-guidance.mjs';
44
46
 
45
47
  const STORE_REF = '.lattice/todo';
46
48
  const MANIFEST_REF = `${STORE_REF}/manifest.json`;
47
49
  const STATUS_SCHEMA = 'lattice.project_status.v1';
48
- const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v1';
50
+ const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v2';
49
51
  /** HEADが読めない環境でも投影を組めるようにする。記録があるときは実HEADで置き換わる。 */
50
52
  const PLACEHOLDER_SHA = '0'.repeat(40);
51
53
  const CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v1';
52
54
  const PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v2';
53
55
  const DECOUPLED_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v3';
54
56
  const MEMO_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v4';
55
- const CURRENT_CREATE_INPUT_SCHEMA = MEMO_PHASE_CREATE_INPUT_SCHEMA;
56
- const CURRENT_CREATE_SCHEMA_COMMAND = 'lattice plan create --schema-version 4 --json';
57
+ // v5 = v4 + 作成者が書く終了条件`done_condition`(u12)。planはv8になる。既定入力はa11でv5になった。
58
+ const DONE_CONDITION_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v5';
59
+ const CURRENT_CREATE_INPUT_SCHEMA = DONE_CONDITION_CREATE_INPUT_SCHEMA;
60
+ const CURRENT_CREATE_SCHEMA_COMMAND = 'lattice plan create --schema-version 5 --json';
57
61
  const CREATE_RESULT_SCHEMA = 'lattice.plan_create_result.v1';
58
62
 
63
+ /** create入力schemaが作るplan schema。v4→v7、v5→v8。 */
64
+ function planSchemaForCreateInput(schema) {
65
+ return schema === DONE_CONDITION_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v8'
66
+ : schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
67
+ : schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
68
+ : schema === PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3';
69
+ }
70
+
59
71
  function resolveRepoRoot(cwd) {
60
72
  try {
61
73
  // gitはWindowsでもforward slashを返すため、OS nativeへ正規化して
@@ -295,7 +307,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
295
307
  }));
296
308
  const state = activeRuns.length > 0 ? 'active_run' : 'ready';
297
309
  const next = activeRuns.length > 0
298
- ? { command: 'lattice todo status', reason: 'active_run_present' }
310
+ ? { command: 'lattice session-context --json', reason: 'active_run_present' }
299
311
  : todo.next_ready.length > 0
300
312
  ? { command: `lattice todo start --plan ${todo.next_ready[0].plan_key} --task ${todo.next_ready[0].task_id}${todo.next_ready.length > 1 ? ' --parallel-frontier' : ''}`,
301
313
  reason: todo.next_ready.length > 1 ? 'parallel_frontier_present' : 'next_ready_present' }
@@ -375,6 +387,35 @@ export async function runProjectStatus({ cwd, stdout, stderr = process.stderr, c
375
387
  return state.exitCode;
376
388
  }
377
389
 
390
+ /**
391
+ * turn開始時にseatが見る「次に取れる工程」と「自分の途中の工程」(a3、seat-contract)。記録して見せるだけで、選びも割り当てもしない。
392
+ * `own`は、現在のjournalで最後の`start`を同じagentが記録した in-progress/blocked の工程。
393
+ * storeまたはtodoが無い(未初期化・読めない)ときは空2つと`warning`を返し、投げない。
394
+ */
395
+ export function projectTurn({ store, todo, actor, reason = 'store_unavailable' }) {
396
+ if (store === null || todo === null) return { actor, startable: [], own: [], warning: { reason } };
397
+ const own = [];
398
+ for (const member of store.members) {
399
+ const lastStart = new Map();
400
+ for (const event of member.journal.events) if (event.kind === 'start') lastStart.set(event.task_id, event);
401
+ for (const state of member.tasks) {
402
+ if (state.status !== 'in-progress' && state.status !== 'blocked') continue;
403
+ if (lastStart.get(state.task_id)?.actor?.agent !== actor.agent) continue;
404
+ const task = member.plan.tasks.find(({ task_id: id }) => id === state.task_id);
405
+ const { label, done_condition: doneCondition } = todoStatusTaskDisplay(task);
406
+ own.push({
407
+ plan_key: member.plan.plan_key, task_id: state.task_id, label, status: state.status,
408
+ started_at: state.started_at,
409
+ blocked_reason: state.status === 'blocked' ? todoStatusBlockedReason(state.blocked_reason) : null,
410
+ done_condition: doneCondition,
411
+ });
412
+ }
413
+ }
414
+ const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
415
+ own.sort((a, b) => order(a.plan_key, b.plan_key) || order(a.task_id, b.task_id));
416
+ return { actor, startable: todo.next_ready, own };
417
+ }
418
+
378
419
  /**
379
420
  * session開始時の現在地を1プロセス・1 store読みで返す(ADR 0131)。
380
421
  *
@@ -385,7 +426,7 @@ export async function runProjectStatus({ cwd, stdout, stderr = process.stderr, c
385
426
  *
386
427
  * dashboard活動の登録は行わない。現在地を知るために呼ぶ面であり、常駐面を起こす面ではない。
387
428
  */
388
- export async function runSessionContext({ cwd, stdout, cliVersion }) {
429
+ export async function runSessionContext({ cwd, stdout, cliVersion, env = process.env }) {
389
430
  const state = await resolveProjectState({ cwd, cliVersion });
390
431
  const independence = state.store === null || state.todo === null
391
432
  ? [] : await summarizeIndependence({ repoRoot: state.repoRoot, store: state.store, todo: state.todo });
@@ -396,6 +437,11 @@ export async function runSessionContext({ cwd, stdout, cliVersion }) {
396
437
  // todoは`lattice todo status`のresultそのもの。新しい意味論を発明しない。
397
438
  todo: state.todo,
398
439
  independence,
440
+ turn: projectTurn({
441
+ store: state.store, todo: state.todo, actor: resolveTodoActor(env),
442
+ // 名乗れないときの理由はstatusが既に持つ(invalidはnext_action.reason、未初期化はstate)。
443
+ reason: state.result.state === 'invalid' ? state.result.next_action.reason : state.result.state,
444
+ }),
399
445
  result_digest: '',
400
446
  };
401
447
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -417,104 +463,129 @@ async function readCanonicalInput(repoRoot, inputRef) {
417
463
  }
418
464
  }
419
465
 
466
+ const isPlainRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
467
+ const typeOf = (value) => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value);
468
+
469
+ /** keyの過不足を`missing_keys`/`unexpected_keys`で名指す。recordでなければ全keyが足りない。 */
470
+ function keyShapeViolation(pointer, value, keys) {
471
+ const actual = isPlainRecord(value) ? Object.keys(value).sort() : null;
472
+ return {
473
+ violation_kind: 'unexpected_or_missing_keys', pointer,
474
+ expected: { keys: [...keys].sort() },
475
+ actual: actual === null ? { type: typeOf(value) } : { keys: actual },
476
+ missing_keys: keys.filter((key) => actual === null || !actual.includes(key)).sort(),
477
+ unexpected_keys: actual === null ? [] : actual.filter((key) => !keys.includes(key)),
478
+ };
479
+ }
480
+
420
481
  /**
421
482
  * buildTodoPlanは通ったか否かしか返さない。authorが実際に書くtasks・phasesについて、
422
- * 落ちた最初の条件をpointer付きで名指しする。ここで拾えない違反だけ総称へ落とす。
423
- * 整列要求(task_id昇順など)はJSON Schemaに書けないので、ここが唯一の案内面になる。
483
+ * 落ちた条件を独立なものすべてpointer付きで名指しする(a11)。整列要求(task_id昇順など)は
484
+ * JSON Schemaに書けないので、ここが唯一の案内面になる。機械が整列するので`unsorted`は
485
+ * めったに出ないが、他の指摘を隠さない。文書順で返す。
424
486
  */
425
487
  function describePlanShapeViolation(value, { phaseInput }) {
426
- const TASK_KEYS = ['task_id', 'title', 'lane', 'design_memo', 'narrative_ref',
427
- 'narrative_anchor', 'compile_binding', 'parent_task_id', 'phase_id'];
488
+ const problems = [];
489
+ const TASK_KEYS = ['task_id', 'title', 'lane', 'narrative_ref',
490
+ 'narrative_anchor', 'compile_binding', 'parent_task_id',
491
+ ...(phaseInput ? ['phase_id'] : []),
492
+ ...([MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value.schema)
493
+ ? ['design_memo'] : []),
494
+ ...(value.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA ? ['done_condition'] : [])];
428
495
  const PHASE_KEYS = ['phase_id', 'title', 'gate_policy', 'predecessor_phase_ids',
429
496
  'required_evidence_slots'];
430
497
 
431
498
  if (value.tasks.length === 0) {
432
- return { violation_kind: 'empty', pointer: '/tasks',
433
- expected: { min_items: 1 }, actual: { length: 0 } };
499
+ problems.push({ violation_kind: 'empty', pointer: '/tasks',
500
+ expected: { min_items: 1 }, actual: { length: 0 } });
434
501
  }
435
502
  for (const [index, task] of value.tasks.entries()) {
436
- if (!exactRecord(task, TASK_KEYS)) {
437
- return { violation_kind: 'unexpected_or_missing_keys', pointer: `/tasks/${index}`,
438
- expected: { keys: [...TASK_KEYS].sort() },
439
- actual: (task === null || typeof task !== 'object')
440
- ? { type: task === null ? 'null' : typeof task }
441
- : { keys: Object.keys(task).sort() } };
442
- }
503
+ if (!exactRecord(task, TASK_KEYS)) problems.push(keyShapeViolation(`/tasks/${index}`, task, TASK_KEYS));
504
+ if (!isPlainRecord(task)) continue;
443
505
  for (const field of ['task_id', 'lane', 'phase_id']) {
444
- if (!isTodoIdentifier(task[field])) {
445
- return { violation_kind: 'identifier_invalid', pointer: `/tasks/${index}/${field}`,
446
- expected: { format: 'todo_identifier' }, actual: task[field] };
506
+ if (field in task && !isTodoIdentifier(task[field])) {
507
+ problems.push({ violation_kind: 'identifier_invalid', pointer: `/tasks/${index}/${field}`,
508
+ expected: { format: 'todo_identifier' }, actual: task[field] });
447
509
  }
448
510
  }
449
- if (index > 0 && !(value.tasks[index - 1].task_id < task.task_id)) {
450
- return { violation_kind: 'unsorted', pointer: `/tasks/${index}/task_id`,
451
- expected: { greater_than: value.tasks[index - 1].task_id, order: 'ascending_unique' },
452
- actual: task.task_id };
511
+ const previous = value.tasks[index - 1]?.task_id;
512
+ if (index > 0 && isTodoIdentifier(previous) && isTodoIdentifier(task.task_id) && !(previous < task.task_id)) {
513
+ problems.push({ violation_kind: 'unsorted', pointer: `/tasks/${index}/task_id`,
514
+ expected: { greater_than: previous, order: 'ascending_unique' }, actual: task.task_id });
453
515
  }
454
516
  }
455
- if (!phaseInput) return null;
517
+ if (!phaseInput) return problems;
456
518
 
457
519
  if (!Array.isArray(value.phases) || value.phases.length === 0) {
458
- return { violation_kind: 'empty', pointer: '/phases', expected: { min_items: 1 },
459
- actual: Array.isArray(value.phases) ? { length: 0 } : { type: typeof value.phases } };
520
+ problems.push({ violation_kind: 'empty', pointer: '/phases', expected: { min_items: 1 },
521
+ actual: Array.isArray(value.phases) ? { length: 0 } : { type: typeof value.phases } });
522
+ return problems;
460
523
  }
461
524
  for (const [index, phase] of value.phases.entries()) {
462
- if (!exactRecord(phase, PHASE_KEYS)) {
463
- return { violation_kind: 'unexpected_or_missing_keys', pointer: `/phases/${index}`,
464
- expected: { keys: [...PHASE_KEYS].sort() },
465
- actual: (phase === null || typeof phase !== 'object')
466
- ? { type: phase === null ? 'null' : typeof phase }
467
- : { keys: Object.keys(phase).sort() } };
468
- }
525
+ if (!exactRecord(phase, PHASE_KEYS)) problems.push(keyShapeViolation(`/phases/${index}`, phase, PHASE_KEYS));
526
+ if (!isPlainRecord(phase)) continue;
469
527
  for (const field of ['phase_id', 'gate_policy']) {
470
- if (!isTodoIdentifier(phase[field])) {
471
- return { violation_kind: 'identifier_invalid', pointer: `/phases/${index}/${field}`,
472
- expected: { format: 'todo_identifier' }, actual: phase[field] };
528
+ if (field in phase && !isTodoIdentifier(phase[field])) {
529
+ problems.push({ violation_kind: 'identifier_invalid', pointer: `/phases/${index}/${field}`,
530
+ expected: { format: 'todo_identifier' }, actual: phase[field] });
473
531
  }
474
532
  }
475
- if (!Array.isArray(phase.required_evidence_slots) || phase.required_evidence_slots.length === 0) {
476
- return { violation_kind: 'empty',
533
+ const slots = phase.required_evidence_slots;
534
+ if ('required_evidence_slots' in phase && (!Array.isArray(slots) || slots.length === 0)) {
535
+ problems.push({ violation_kind: 'empty',
477
536
  pointer: `/phases/${index}/required_evidence_slots`,
478
537
  expected: { min_items: 1, note: 'Phase gateが要求する証跡slotを1つ以上挙げる' },
479
- actual: Array.isArray(phase.required_evidence_slots)
480
- ? { length: 0 } : { type: typeof phase.required_evidence_slots } };
538
+ actual: Array.isArray(slots) ? { length: 0 } : { type: typeof slots } });
481
539
  }
482
540
  for (const field of ['predecessor_phase_ids', 'required_evidence_slots']) {
483
541
  const list = phase[field];
542
+ if (!Array.isArray(list)) {
543
+ if (field in phase && field === 'predecessor_phase_ids') {
544
+ problems.push({ violation_kind: 'type', pointer: `/phases/${index}/${field}`,
545
+ expected: { type: 'array' }, actual: { type: typeOf(list) } });
546
+ }
547
+ continue;
548
+ }
484
549
  const unsorted = list.findIndex((entry, i) => i > 0 && !(list[i - 1] < entry));
485
550
  if (unsorted > 0) {
486
- return { violation_kind: 'unsorted', pointer: `/phases/${index}/${field}/${unsorted}`,
551
+ problems.push({ violation_kind: 'unsorted', pointer: `/phases/${index}/${field}/${unsorted}`,
487
552
  expected: { greater_than: list[unsorted - 1], order: 'ascending_unique' },
488
- actual: list[unsorted] };
553
+ actual: list[unsorted] });
489
554
  }
490
555
  }
491
- if (index > 0 && !(value.phases[index - 1].phase_id < phase.phase_id)) {
492
- return { violation_kind: 'unsorted', pointer: `/phases/${index}/phase_id`,
493
- expected: { greater_than: value.phases[index - 1].phase_id, order: 'ascending_unique' },
494
- actual: phase.phase_id };
556
+ const previous = value.phases[index - 1]?.phase_id;
557
+ if (index > 0 && isTodoIdentifier(previous) && isTodoIdentifier(phase.phase_id)
558
+ && !(previous < phase.phase_id)) {
559
+ problems.push({ violation_kind: 'unsorted', pointer: `/phases/${index}/phase_id`,
560
+ expected: { greater_than: previous, order: 'ascending_unique' }, actual: phase.phase_id });
495
561
  }
496
562
  }
497
- const phaseIds = new Set(value.phases.map(({ phase_id }) => phase_id));
498
- const orphan = value.tasks.findIndex(({ phase_id }) => !phaseIds.has(phase_id));
499
- if (orphan >= 0) {
500
- return { violation_kind: 'unknown_reference', pointer: `/tasks/${orphan}/phase_id`,
501
- expected: { one_of: [...phaseIds].sort() }, actual: value.tasks[orphan].phase_id };
563
+ const phaseIds = new Set(value.phases.map((phase) => phase?.phase_id));
564
+ for (const [index, task] of value.tasks.entries()) {
565
+ if (isPlainRecord(task) && isTodoIdentifier(task.phase_id) && !phaseIds.has(task.phase_id)) {
566
+ problems.push({ violation_kind: 'unknown_reference', pointer: `/tasks/${index}/phase_id`,
567
+ expected: { one_of: [...phaseIds].filter(isTodoIdentifier).sort() }, actual: task.phase_id });
568
+ }
502
569
  }
503
- return null;
570
+ return problems;
504
571
  }
505
572
 
573
+ // 最初に返す違反の優先順(従来どおり)。同じ順位なら文書順で先のもの。
574
+ const RANK = Object.freeze({ memo: 0, done: 1, input: 2, authorable: 3, shape: 4, graph: 5 });
575
+
506
576
  /**
507
- * plan create入力の違反を、通ったか否かでなく「どこがどう違うか」で返す。
508
- * 以前は巨大な `||` 連鎖と `catch { return false }` で理由を捨てており、
509
- * 呼び手には pointer `/` と `validation: failed` しか届かなかった。
510
- * 直せない指摘は指摘ではないので、最初に落ちた条件をpointer付きで返す。
511
- * 違反が無ければ null。
577
+ * plan create入力の違反を、通ったか否かでなく「どこがどう違うか」で、独立なものすべて返す(a11)。
578
+ * 以前は巨大な `||` 連鎖と `catch { return false }` で理由を捨てており、呼び手には pointer `/` と
579
+ * `validation: failed` しか届かなかった。直せない指摘は指摘ではないので、各違反をpointer付きで返し、
580
+ * 呼び手が1回で直せるようにする。{ rank, violation }の文書順の配列。違反が無ければ空。
512
581
  */
513
- function describeCreateInputViolation(value) {
582
+ function describeCreateInputViolations(value) {
583
+ const found = [];
584
+ const add = (rank, violation) => found.push({ rank, violation });
514
585
  const phaseInput = [PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
515
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(value?.schema);
586
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value?.schema);
516
587
  const decoupledPhaseInput = [DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
517
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(value?.schema);
588
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value?.schema);
518
589
  const keys = [
519
590
  'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
520
591
  'tasks', 'hard_dependencies', 'joins', 'input_digest',
@@ -522,123 +593,139 @@ function describeCreateInputViolation(value) {
522
593
  if (phaseInput) keys.push('phases');
523
594
  if (decoupledPhaseInput) keys.push('phase_accept_dependencies');
524
595
 
525
- if (!exactRecord(value, keys)) {
526
- const actual = (value === null || typeof value !== 'object' || Array.isArray(value))
527
- ? { type: value === null ? 'null' : typeof value }
528
- : { keys: Object.keys(value).sort() };
529
- return { violation_kind: 'unexpected_or_missing_keys', pointer: '/',
530
- expected: { keys: [...keys].sort() }, actual };
531
- }
596
+ const topLevelOk = exactRecord(value, keys);
597
+ if (!topLevelOk) add(RANK.input, keyShapeViolation('/', value, keys));
598
+ if (!isPlainRecord(value)) return found;
599
+ const present = (field) => field in value;
532
600
  const schemas = [CREATE_INPUT_SCHEMA, PHASE_CREATE_INPUT_SCHEMA,
533
- DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA];
534
- if (!schemas.includes(value.schema)) {
535
- return { violation_kind: 'const_mismatch', pointer: '/schema',
536
- expected: { one_of: schemas }, actual: value.schema };
601
+ DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA,
602
+ DONE_CONDITION_CREATE_INPUT_SCHEMA];
603
+ if (present('schema') && !schemas.includes(value.schema)) {
604
+ add(RANK.input, { violation_kind: 'const_mismatch', pointer: '/schema',
605
+ expected: { one_of: schemas }, actual: value.schema });
537
606
  }
538
607
  for (const field of ['project_id', 'plan_key', 'plan_version']) {
539
- if (!isTodoIdentifier(value[field])) {
540
- return { violation_kind: 'identifier_invalid', pointer: `/${field}`,
541
- expected: { format: 'todo_identifier' }, actual: value[field] };
608
+ if (present(field) && !isTodoIdentifier(value[field])) {
609
+ add(RANK.input, { violation_kind: 'identifier_invalid', pointer: `/${field}`,
610
+ expected: { format: 'todo_identifier' }, actual: value[field] });
542
611
  }
543
612
  }
544
- if (!exactRecord(value.actor, ['host', 'session', 'agent'])) {
545
- return { violation_kind: 'unexpected_or_missing_keys', pointer: '/actor',
546
- expected: { keys: ['agent', 'host', 'session'] },
547
- actual: (value.actor === null || typeof value.actor !== 'object')
548
- ? { type: value.actor === null ? 'null' : typeof value.actor }
549
- : { keys: Object.keys(value.actor).sort() } };
550
- }
551
- for (const field of ['host', 'session', 'agent']) {
552
- if (!isTodoIdentifier(value.actor[field])) {
553
- return { violation_kind: 'identifier_invalid', pointer: `/actor/${field}`,
554
- expected: { format: 'todo_identifier' }, actual: value.actor[field] };
613
+ if (present('actor')) {
614
+ if (!exactRecord(value.actor, ['host', 'session', 'agent'])) {
615
+ add(RANK.input, keyShapeViolation('/actor', value.actor, ['host', 'session', 'agent']));
616
+ }
617
+ if (isPlainRecord(value.actor)) {
618
+ for (const field of ['host', 'session', 'agent']) {
619
+ if (field in value.actor && !isTodoIdentifier(value.actor[field])) {
620
+ add(RANK.input, { violation_kind: 'identifier_invalid', pointer: `/actor/${field}`,
621
+ expected: { format: 'todo_identifier' }, actual: value.actor[field] });
622
+ }
623
+ }
555
624
  }
556
625
  }
557
- if (!isStrictTodoTimestamp(value.recorded_at)) {
558
- return { violation_kind: 'timestamp_invalid', pointer: '/recorded_at',
559
- expected: { format: 'strict_iso8601_utc_milliseconds' }, actual: value.recorded_at };
626
+ if (present('recorded_at') && !isStrictTodoTimestamp(value.recorded_at)) {
627
+ add(RANK.input, { violation_kind: 'timestamp_invalid', pointer: '/recorded_at',
628
+ expected: { format: 'strict_iso8601_utc_milliseconds' }, actual: value.recorded_at });
560
629
  }
561
- if (!isTodoDigest(value.input_digest)
562
- || value.input_digest !== todoSelfDigest(value, 'input_digest')) {
563
- return { violation_kind: 'input_digest_mismatch', pointer: '/input_digest',
630
+ if (topLevelOk && (!isTodoDigest(value.input_digest)
631
+ || value.input_digest !== todoSelfDigest(value, 'input_digest'))) {
632
+ add(RANK.input, { violation_kind: 'input_digest_mismatch', pointer: '/input_digest',
564
633
  expected: todoSelfDigest(value, 'input_digest'),
565
- actual: { type: typeof value.input_digest, matches_canonical_input: false } };
634
+ actual: { type: typeof value.input_digest, matches_canonical_input: false } });
566
635
  }
567
636
  if (!Array.isArray(value.tasks)) {
568
- return { violation_kind: 'type', pointer: '/tasks', expected: { type: 'array' },
569
- actual: { type: value.tasks === null ? 'null' : typeof value.tasks } };
637
+ if (present('tasks')) {
638
+ add(RANK.input, { violation_kind: 'type', pointer: '/tasks', expected: { type: 'array' },
639
+ actual: { type: value.tasks === null ? 'null' : typeof value.tasks } });
640
+ }
641
+ return found;
642
+ }
643
+ // 設計メモ・終了条件は従来どおり専用のcode/reasonで先に返す(validatePlanCreateInput)。
644
+ if ([MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value.schema)) {
645
+ for (const [index, task] of value.tasks.entries()) {
646
+ if (isTodoDesignMemo(task?.design_memo)) continue;
647
+ const explained = explainTodoDesignMemo(task?.design_memo);
648
+ add(RANK.memo, { violation_kind: explained.reason, pointer: `/tasks/${index}/design_memo`,
649
+ expected: explained.expected, actual: explained.actual });
650
+ }
651
+ }
652
+ if (value.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA) {
653
+ // design_memoと同じ本文規則。違いはnull(終了条件なし)を許すことだけ。
654
+ for (const [index, task] of value.tasks.entries()) {
655
+ if (task?.done_condition === null || isTodoDesignMemo(task?.done_condition)) continue;
656
+ const explained = explainTodoDesignMemo(task?.done_condition);
657
+ add(RANK.done, { violation_kind: explained.reason, pointer: `/tasks/${index}/done_condition`,
658
+ expected: { ...explained.expected, nullable: true }, actual: explained.actual });
659
+ }
570
660
  }
571
661
  for (const [index, task] of value.tasks.entries()) {
572
662
  for (const field of ['narrative_anchor', 'compile_binding']) {
573
663
  if (task?.[field] !== null) {
574
- return { violation_kind: 'not_authorable_at_create', pointer: `/tasks/${index}/${field}`,
575
- expected: null, actual: task?.[field] };
664
+ add(RANK.authorable, { violation_kind: 'not_authorable_at_create',
665
+ pointer: `/tasks/${index}/${field}`, expected: null, actual: task?.[field] });
576
666
  }
577
667
  }
578
668
  }
579
- try {
580
- buildTodoPlan({
581
- schema: value.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
582
- : decoupledPhaseInput ? 'lattice.todo_plan.v5'
583
- : phaseInput ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3', project_id: value.project_id,
584
- plan_key: value.plan_key, plan_version: value.plan_version,
585
- predecessor_plan_digest: null, tasks: value.tasks,
586
- hard_dependencies: value.hard_dependencies, joins: value.joins,
587
- ...(phaseInput ? { phases: value.phases } : {}),
588
- ...(decoupledPhaseInput ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
589
- });
590
- } catch (error) {
591
- // Author-specific fields keep their existing diagnostic priority.
592
- const shape = describePlanShapeViolation(value, { phaseInput });
593
- if (shape !== null) return shape;
594
- return {
595
- violation_kind: error?.detail?.violation_kind ?? error?.reason ?? error?.code ?? 'topology_invalid',
596
- pointer: error?.detail?.pointer ?? '/',
597
- expected: error?.detail?.expected ?? { schema: value.schema },
598
- actual: error?.detail?.actual ?? { message: String(error?.message ?? error) },
599
- };
669
+ if (schemas.includes(value.schema)) {
670
+ for (const violation of describePlanShapeViolation(value, { phaseInput })) add(RANK.shape, violation);
671
+ }
672
+ // 形の指摘が1つも無い時だけ、グラフ(循環・未知の辺の端)を調べる。
673
+ if (found.length === 0) {
674
+ try {
675
+ buildTodoPlan({
676
+ schema: planSchemaForCreateInput(value.schema), project_id: value.project_id,
677
+ plan_key: value.plan_key, plan_version: value.plan_version,
678
+ predecessor_plan_digest: null, tasks: value.tasks,
679
+ hard_dependencies: value.hard_dependencies, joins: value.joins,
680
+ ...(phaseInput ? { phases: value.phases } : {}),
681
+ ...(decoupledPhaseInput ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
682
+ });
683
+ } catch (error) {
684
+ add(RANK.graph, {
685
+ violation_kind: error?.detail?.violation_kind ?? error?.reason ?? error?.code ?? 'topology_invalid',
686
+ pointer: error?.detail?.pointer ?? '/',
687
+ expected: error?.detail?.expected ?? { schema: value.schema },
688
+ actual: error?.detail?.actual ?? { message: String(error?.message ?? error) },
689
+ });
690
+ }
600
691
  }
601
- return null;
692
+ return found;
602
693
  }
603
694
 
604
695
  export function validatePlanCreateInput(input) {
605
- if (input?.schema !== MEMO_PHASE_CREATE_INPUT_SCHEMA) {
606
- throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
607
- violation_kind: 'const_mismatch', pointer: '/schema',
608
- expected: MEMO_PHASE_CREATE_INPUT_SCHEMA,
609
- actual: typeof input?.schema === 'string' ? input.schema : { type: typeof input?.schema },
610
- next_action: CURRENT_CREATE_SCHEMA_COMMAND,
611
- });
612
- }
613
- if (!Array.isArray(input.tasks)) {
696
+ const found = describeCreateInputViolations(input);
697
+ const problems = found.map(({ violation }) => violation);
698
+ if (!Array.isArray(input?.tasks)) {
614
699
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
615
700
  violation_kind: 'type', pointer: '/tasks', expected: { type: 'array', min_items: 1 },
616
- actual: { type: input.tasks === null ? 'null' : typeof input.tasks },
617
- next_action: CURRENT_CREATE_SCHEMA_COMMAND,
701
+ actual: { type: input?.tasks === null ? 'null' : typeof input?.tasks },
702
+ problems, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
618
703
  });
619
704
  }
620
- const invalidMemoIndex = input.tasks.findIndex((task) => !isTodoDesignMemo(task?.design_memo));
621
- if (invalidMemoIndex >= 0) {
622
- const explained = explainTodoDesignMemo(input.tasks[invalidMemoIndex]?.design_memo);
705
+ if (found.length === 0) return;
706
+ // 返す先頭の違反は従来の優先順(設計メモ→終了条件→その他)。problemsは文書順の全件。
707
+ const first = found.reduce((best, entry) => (entry.rank < best.rank ? entry : best));
708
+ const { violation } = first;
709
+ if (first.rank === RANK.memo) {
623
710
  throw new TodoStoreError('DESIGN_MEMO_REQUIRED', 'plan_create_design_memo_required', undefined, {
624
- violation_kind: explained.reason, pointer: `/tasks/${invalidMemoIndex}/design_memo`,
625
- expected: explained.expected, actual: explained.actual,
626
- prompt: TODO_DESIGN_MEMO_PROMPT, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
711
+ ...violation, problems, prompt: TODO_DESIGN_MEMO_PROMPT, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
627
712
  });
628
713
  }
629
- const violation = describeCreateInputViolation(input);
630
- if (violation !== null) {
631
- throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
632
- ...violation,
714
+ throw new TodoStoreError('INPUT_INVALID',
715
+ first.rank === RANK.done ? 'plan_create_done_condition_invalid' : 'plan_create_schema_invalid',
716
+ undefined, {
717
+ ...violation, problems,
633
718
  next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
634
719
  });
635
- }
636
720
  }
637
721
 
638
- export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
722
+ export async function runPlanCreate({
723
+ cwd, inputRef, stdout, inputValue = null, featureChain = null, env = process.env,
724
+ }) {
639
725
  const repoRoot = resolveRepoRoot(cwd);
640
726
  if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
641
- const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
727
+ const input = completeCreateInput(
728
+ inputValue ?? await readCanonicalInput(repoRoot, inputRef), { env, now: new Date() });
642
729
  validatePlanCreateInput(input);
643
730
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
644
731
  const dispatchShape = computeTodoDispatchShapeForPlan({
@@ -651,16 +738,15 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
651
738
  const options = {
652
739
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
653
740
  plan: buildTodoPlan({
654
- schema: input.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
655
- : input.schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
656
- : input.schema === PHASE_CREATE_INPUT_SCHEMA
657
- ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3', project_id: input.project_id,
741
+ schema: planSchemaForCreateInput(input.schema), project_id: input.project_id,
658
742
  plan_key: input.plan_key, plan_version: input.plan_version,
659
743
  predecessor_plan_digest: null, tasks: input.tasks,
660
744
  hard_dependencies: input.hard_dependencies, joins: input.joins,
661
745
  ...([PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
662
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema) ? { phases: input.phases } : {}),
663
- ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema)
746
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input.schema)
747
+ ? { phases: input.phases } : {}),
748
+ ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA,
749
+ DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input.schema)
664
750
  ? { phase_accept_dependencies: input.phase_accept_dependencies } : {}),
665
751
  }),
666
752
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
@@ -698,17 +784,17 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
698
784
  }
699
785
 
700
786
  /**
701
- * `--schema --json`(版指定なし)の既定はCURRENT_CREATE_INPUT_SCHEMAと同じv4にする。
787
+ * `--schema --json`(版指定なし)の既定はCURRENT_CREATE_INPUT_SCHEMAと同じv5にする。
702
788
  * 既定がv1のままだと、素の`--schema`を叩いたAIが古いv1(Phaseを表現できない)を
703
789
  * 受け取り、実運用で通らない入力を作ってしまう(実際に踏んだ)。
704
790
  * `--schema-version 1`は互換のため引き続き取得できる(bin/lattice.mjs側で許可)。
705
791
  *
706
- * 「どの版を返したか」は返すJSON Schema自身の`title`(例: `lattice.plan_create_input.v4`)が
792
+ * 「どの版を返したか」は返すJSON Schema自身の`title`(例: `lattice.plan_create_input.v5`)が
707
793
  * 既に機械可読に持っている。壊さずに追加のkeyを足す理由が無いので足さない。
708
794
  */
709
- export async function runPlanCreateSchema({ stdout, version = 4 }) {
710
- if (![1, 2, 3, 4].includes(version)) throw new TypeError('unsupported plan create schema version');
711
- const expected = version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
795
+ export async function runPlanCreateSchema({ stdout, version = 5 }) {
796
+ if (![1, 2, 3, 4, 5].includes(version)) throw new TypeError('unsupported plan create schema version');
797
+ const expected = version === 5 ? DONE_CONDITION_CREATE_INPUT_SCHEMA : version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
712
798
  : version === 3 ? DECOUPLED_PHASE_CREATE_INPUT_SCHEMA
713
799
  : version === 2 ? PHASE_CREATE_INPUT_SCHEMA : CREATE_INPUT_SCHEMA;
714
800
  const schemaUrl = new URL(`../docs/schemas/lattice.plan_create_input.v${version}.schema.json`, import.meta.url);
@@ -723,6 +809,34 @@ export async function runPlanCreateSchema({ stdout, version = 4 }) {
723
809
  }
724
810
  }
725
811
 
812
+ /**
813
+ * `plan create --template --json`(a11)。作者が書くkeyだけの最小のv5入力を出す。
814
+ * 機械が埋めるkey(actor・recorded_at・input_digest・定数のkey・辺のproject_id/plan_key)は載せない。
815
+ * 決定的で、storeもrepositoryも読まない。id・題名を書き換えれば`plan create`がそのまま受理する。
816
+ */
817
+ export const PLAN_CREATE_TEMPLATE = Object.freeze({
818
+ schema: DONE_CONDITION_CREATE_INPUT_SCHEMA,
819
+ project_id: 'my-project',
820
+ plan_key: 'my-plan',
821
+ plan_version: 'v1',
822
+ phases: [
823
+ { phase_id: 'p1', title: 'First phase' },
824
+ { phase_id: 'p2', title: 'Second phase' },
825
+ ],
826
+ tasks: [
827
+ { task_id: 't1', title: 'First task', phase_id: 'p1', design_memo: 'NO_PLAN' },
828
+ { task_id: 't2', title: 'Second task', phase_id: 'p1' },
829
+ { task_id: 't3', title: 'Third task', phase_id: 'p2' },
830
+ ],
831
+ // from is the prerequisite; to starts after from is done.
832
+ hard_dependencies: [{ from: { task_id: 't1' }, to: { task_id: 't3' } }],
833
+ });
834
+
835
+ export async function runPlanCreateTemplate({ stdout }) {
836
+ stdout.write(`${JSON.stringify(PLAN_CREATE_TEMPLATE)}\n`);
837
+ return 0;
838
+ }
839
+
726
840
  const PLAN_SHOW_RESULT_SCHEMA = 'lattice.plan_show_result.v1';
727
841
 
728
842
  /**
@@ -745,8 +859,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
745
859
  });
746
860
  }
747
861
  const { plan, tasks, phases } = member;
748
- const phaseInput = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
749
- .includes(plan.schema);
862
+ const phaseInput = isPhaseTodoPlanSchema(plan.schema);
750
863
  const stateByTaskId = new Map(tasks.map((state) => [state.task_id, state]));
751
864
  // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
752
865
  // (readTodoStoreが常に member.phases として埋める。ADR 0147)。
@@ -772,6 +885,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
772
885
  lane: task.lane,
773
886
  phase_id: phaseInput ? task.phase_id : null,
774
887
  state: stateByTaskId.get(task.task_id).status,
888
+ done_condition: task.done_condition ?? null,
775
889
  depends_on_count: dependsOnCount.get(task.task_id) ?? 0,
776
890
  }));
777
891
 
@@ -800,6 +914,10 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
800
914
  has_phases: phaseInput,
801
915
  phases: phaseList,
802
916
  tasks: taskList,
917
+ // a11: 辺の向きは from=前提、to=fromが終わってから始まる。planが持つとおりに出す。
918
+ hard_dependencies: plan.hard_dependencies,
919
+ joins: plan.joins,
920
+ phase_accept_dependencies: plan.phase_accept_dependencies ?? [],
803
921
  topology: {
804
922
  task_count: dispatchShape.task_count,
805
923
  critical_path_length: dispatchShape.critical_path_length,
@@ -837,12 +955,32 @@ export function projectStatusFailure({ cwd, stdout, cliVersion, error }) {
837
955
  return 1;
838
956
  }
839
957
 
840
- export function projectCliFailure(stderr, error) {
958
+ export function projectCliFailure(stderr, error, context = {}) {
959
+ const code = error?.code ?? 'INTERNAL_FAILURE';
960
+ const message = error?.message ?? 'project command failed';
841
961
  const payload = {
842
- schema: 'lattice.cli_error.v2', code: error?.code ?? 'INTERNAL_FAILURE',
843
- message: error?.message ?? 'project command failed',
962
+ schema: 'lattice.cli_error.v2', code, message,
963
+ detail: withRefusalGuidance({ code, message, detail: error?.detail }, { family: 'plan', ...context }),
844
964
  };
845
- if (error?.detail && Object.keys(error.detail).length > 0) payload.detail = error.detail;
846
965
  stderr.write(`${JSON.stringify(payload)}\n`);
847
966
  return 1;
848
967
  }
968
+
969
+ /**
970
+ * `plan create|revise|backchain`の引数違反(exit 2)。usage文1行ではなく、直すflagと規則を
971
+ * cli_error.v2で返す(u05)。`--json`必須のcommandで欠けていればそれを名指す。
972
+ */
973
+ export function planArgumentFailure(stderr, args, spec) {
974
+ const head = args.slice(0, 2);
975
+ const explained = explainFlagCommand(args, head, spec)
976
+ ?? (spec.booleans?.includes('json') ? { pointer: '--json', rule: 'flag_missing', expected: { type: 'boolean' } } : {});
977
+ const message = 'plan_arguments_invalid';
978
+ const payload = {
979
+ schema: 'lattice.cli_error.v2', code: 'INVALID_ARGUMENTS', message,
980
+ detail: withRefusalGuidance({ code: 'INVALID_ARGUMENTS', message,
981
+ detail: { command: head.join(' '), arguments: args, ...explained } },
982
+ { family: 'plan', command: head[1] }),
983
+ };
984
+ stderr.write(`${JSON.stringify(payload)}\n`);
985
+ return 2;
986
+ }