@quolu/lattice 0.83.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.
@@ -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';
@@ -41,22 +41,23 @@ import {
41
41
  import {
42
42
  computeTodoDispatchShapeForPlan,
43
43
  } from './todo-dispatch-shape.mjs';
44
- 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';
45
46
 
46
47
  const STORE_REF = '.lattice/todo';
47
48
  const MANIFEST_REF = `${STORE_REF}/manifest.json`;
48
49
  const STATUS_SCHEMA = 'lattice.project_status.v1';
49
- const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v1';
50
+ const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v2';
50
51
  /** HEADが読めない環境でも投影を組めるようにする。記録があるときは実HEADで置き換わる。 */
51
52
  const PLACEHOLDER_SHA = '0'.repeat(40);
52
53
  const CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v1';
53
54
  const PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v2';
54
55
  const DECOUPLED_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v3';
55
56
  const MEMO_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v4';
56
- // v5 = v4 + 作成者が書く終了条件`done_condition`(u12)。planはv8になる。既定入力はv4のまま。
57
+ // v5 = v4 + 作成者が書く終了条件`done_condition`(u12)。planはv8になる。既定入力はa11でv5になった。
57
58
  const DONE_CONDITION_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v5';
58
- const CURRENT_CREATE_INPUT_SCHEMA = MEMO_PHASE_CREATE_INPUT_SCHEMA;
59
- const CURRENT_CREATE_SCHEMA_COMMAND = 'lattice plan create --schema-version 4 --json';
59
+ const CURRENT_CREATE_INPUT_SCHEMA = DONE_CONDITION_CREATE_INPUT_SCHEMA;
60
+ const CURRENT_CREATE_SCHEMA_COMMAND = 'lattice plan create --schema-version 5 --json';
60
61
  const CREATE_RESULT_SCHEMA = 'lattice.plan_create_result.v1';
61
62
 
62
63
  /** create入力schemaが作るplan schema。v4→v7、v5→v8。 */
@@ -306,7 +307,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
306
307
  }));
307
308
  const state = activeRuns.length > 0 ? 'active_run' : 'ready';
308
309
  const next = activeRuns.length > 0
309
- ? { command: 'lattice todo status', reason: 'active_run_present' }
310
+ ? { command: 'lattice session-context --json', reason: 'active_run_present' }
310
311
  : todo.next_ready.length > 0
311
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' : ''}`,
312
313
  reason: todo.next_ready.length > 1 ? 'parallel_frontier_present' : 'next_ready_present' }
@@ -386,6 +387,35 @@ export async function runProjectStatus({ cwd, stdout, stderr = process.stderr, c
386
387
  return state.exitCode;
387
388
  }
388
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
+
389
419
  /**
390
420
  * session開始時の現在地を1プロセス・1 store読みで返す(ADR 0131)。
391
421
  *
@@ -396,7 +426,7 @@ export async function runProjectStatus({ cwd, stdout, stderr = process.stderr, c
396
426
  *
397
427
  * dashboard活動の登録は行わない。現在地を知るために呼ぶ面であり、常駐面を起こす面ではない。
398
428
  */
399
- export async function runSessionContext({ cwd, stdout, cliVersion }) {
429
+ export async function runSessionContext({ cwd, stdout, cliVersion, env = process.env }) {
400
430
  const state = await resolveProjectState({ cwd, cliVersion });
401
431
  const independence = state.store === null || state.todo === null
402
432
  ? [] : await summarizeIndependence({ repoRoot: state.repoRoot, store: state.store, todo: state.todo });
@@ -407,6 +437,11 @@ export async function runSessionContext({ cwd, stdout, cliVersion }) {
407
437
  // todoは`lattice todo status`のresultそのもの。新しい意味論を発明しない。
408
438
  todo: state.todo,
409
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
+ }),
410
445
  result_digest: '',
411
446
  };
412
447
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -428,101 +463,125 @@ async function readCanonicalInput(repoRoot, inputRef) {
428
463
  }
429
464
  }
430
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
+
431
481
  /**
432
482
  * buildTodoPlanは通ったか否かしか返さない。authorが実際に書くtasks・phasesについて、
433
- * 落ちた最初の条件をpointer付きで名指しする。ここで拾えない違反だけ総称へ落とす。
434
- * 整列要求(task_id昇順など)はJSON Schemaに書けないので、ここが唯一の案内面になる。
483
+ * 落ちた条件を独立なものすべてpointer付きで名指しする(a11)。整列要求(task_id昇順など)は
484
+ * JSON Schemaに書けないので、ここが唯一の案内面になる。機械が整列するので`unsorted`は
485
+ * めったに出ないが、他の指摘を隠さない。文書順で返す。
435
486
  */
436
487
  function describePlanShapeViolation(value, { phaseInput }) {
437
- const TASK_KEYS = ['task_id', 'title', 'lane', 'design_memo', 'narrative_ref',
438
- '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'] : []),
439
494
  ...(value.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA ? ['done_condition'] : [])];
440
495
  const PHASE_KEYS = ['phase_id', 'title', 'gate_policy', 'predecessor_phase_ids',
441
496
  'required_evidence_slots'];
442
497
 
443
498
  if (value.tasks.length === 0) {
444
- return { violation_kind: 'empty', pointer: '/tasks',
445
- expected: { min_items: 1 }, actual: { length: 0 } };
499
+ problems.push({ violation_kind: 'empty', pointer: '/tasks',
500
+ expected: { min_items: 1 }, actual: { length: 0 } });
446
501
  }
447
502
  for (const [index, task] of value.tasks.entries()) {
448
- if (!exactRecord(task, TASK_KEYS)) {
449
- return { violation_kind: 'unexpected_or_missing_keys', pointer: `/tasks/${index}`,
450
- expected: { keys: [...TASK_KEYS].sort() },
451
- actual: (task === null || typeof task !== 'object')
452
- ? { type: task === null ? 'null' : typeof task }
453
- : { keys: Object.keys(task).sort() } };
454
- }
503
+ if (!exactRecord(task, TASK_KEYS)) problems.push(keyShapeViolation(`/tasks/${index}`, task, TASK_KEYS));
504
+ if (!isPlainRecord(task)) continue;
455
505
  for (const field of ['task_id', 'lane', 'phase_id']) {
456
- if (!isTodoIdentifier(task[field])) {
457
- return { violation_kind: 'identifier_invalid', pointer: `/tasks/${index}/${field}`,
458
- 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] });
459
509
  }
460
510
  }
461
- if (index > 0 && !(value.tasks[index - 1].task_id < task.task_id)) {
462
- return { violation_kind: 'unsorted', pointer: `/tasks/${index}/task_id`,
463
- expected: { greater_than: value.tasks[index - 1].task_id, order: 'ascending_unique' },
464
- 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 });
465
515
  }
466
516
  }
467
- if (!phaseInput) return null;
517
+ if (!phaseInput) return problems;
468
518
 
469
519
  if (!Array.isArray(value.phases) || value.phases.length === 0) {
470
- return { violation_kind: 'empty', pointer: '/phases', expected: { min_items: 1 },
471
- 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;
472
523
  }
473
524
  for (const [index, phase] of value.phases.entries()) {
474
- if (!exactRecord(phase, PHASE_KEYS)) {
475
- return { violation_kind: 'unexpected_or_missing_keys', pointer: `/phases/${index}`,
476
- expected: { keys: [...PHASE_KEYS].sort() },
477
- actual: (phase === null || typeof phase !== 'object')
478
- ? { type: phase === null ? 'null' : typeof phase }
479
- : { keys: Object.keys(phase).sort() } };
480
- }
525
+ if (!exactRecord(phase, PHASE_KEYS)) problems.push(keyShapeViolation(`/phases/${index}`, phase, PHASE_KEYS));
526
+ if (!isPlainRecord(phase)) continue;
481
527
  for (const field of ['phase_id', 'gate_policy']) {
482
- if (!isTodoIdentifier(phase[field])) {
483
- return { violation_kind: 'identifier_invalid', pointer: `/phases/${index}/${field}`,
484
- 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] });
485
531
  }
486
532
  }
487
- if (!Array.isArray(phase.required_evidence_slots) || phase.required_evidence_slots.length === 0) {
488
- 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',
489
536
  pointer: `/phases/${index}/required_evidence_slots`,
490
537
  expected: { min_items: 1, note: 'Phase gateが要求する証跡slotを1つ以上挙げる' },
491
- actual: Array.isArray(phase.required_evidence_slots)
492
- ? { length: 0 } : { type: typeof phase.required_evidence_slots } };
538
+ actual: Array.isArray(slots) ? { length: 0 } : { type: typeof slots } });
493
539
  }
494
540
  for (const field of ['predecessor_phase_ids', 'required_evidence_slots']) {
495
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
+ }
496
549
  const unsorted = list.findIndex((entry, i) => i > 0 && !(list[i - 1] < entry));
497
550
  if (unsorted > 0) {
498
- return { violation_kind: 'unsorted', pointer: `/phases/${index}/${field}/${unsorted}`,
551
+ problems.push({ violation_kind: 'unsorted', pointer: `/phases/${index}/${field}/${unsorted}`,
499
552
  expected: { greater_than: list[unsorted - 1], order: 'ascending_unique' },
500
- actual: list[unsorted] };
553
+ actual: list[unsorted] });
501
554
  }
502
555
  }
503
- if (index > 0 && !(value.phases[index - 1].phase_id < phase.phase_id)) {
504
- return { violation_kind: 'unsorted', pointer: `/phases/${index}/phase_id`,
505
- expected: { greater_than: value.phases[index - 1].phase_id, order: 'ascending_unique' },
506
- 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 });
507
561
  }
508
562
  }
509
- const phaseIds = new Set(value.phases.map(({ phase_id }) => phase_id));
510
- const orphan = value.tasks.findIndex(({ phase_id }) => !phaseIds.has(phase_id));
511
- if (orphan >= 0) {
512
- return { violation_kind: 'unknown_reference', pointer: `/tasks/${orphan}/phase_id`,
513
- 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
+ }
514
569
  }
515
- return null;
570
+ return problems;
516
571
  }
517
572
 
573
+ // 最初に返す違反の優先順(従来どおり)。同じ順位なら文書順で先のもの。
574
+ const RANK = Object.freeze({ memo: 0, done: 1, input: 2, authorable: 3, shape: 4, graph: 5 });
575
+
518
576
  /**
519
- * plan create入力の違反を、通ったか否かでなく「どこがどう違うか」で返す。
520
- * 以前は巨大な `||` 連鎖と `catch { return false }` で理由を捨てており、
521
- * 呼び手には pointer `/` と `validation: failed` しか届かなかった。
522
- * 直せない指摘は指摘ではないので、最初に落ちた条件をpointer付きで返す。
523
- * 違反が無ければ null。
577
+ * plan create入力の違反を、通ったか否かでなく「どこがどう違うか」で、独立なものすべて返す(a11)。
578
+ * 以前は巨大な `||` 連鎖と `catch { return false }` で理由を捨てており、呼び手には pointer `/` と
579
+ * `validation: failed` しか届かなかった。直せない指摘は指摘ではないので、各違反をpointer付きで返し、
580
+ * 呼び手が1回で直せるようにする。{ rank, violation }の文書順の配列。違反が無ければ空。
524
581
  */
525
- function describeCreateInputViolation(value) {
582
+ function describeCreateInputViolations(value) {
583
+ const found = [];
584
+ const add = (rank, violation) => found.push({ rank, violation });
526
585
  const phaseInput = [PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
527
586
  MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value?.schema);
528
587
  const decoupledPhaseInput = [DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
@@ -534,136 +593,139 @@ function describeCreateInputViolation(value) {
534
593
  if (phaseInput) keys.push('phases');
535
594
  if (decoupledPhaseInput) keys.push('phase_accept_dependencies');
536
595
 
537
- if (!exactRecord(value, keys)) {
538
- const actual = (value === null || typeof value !== 'object' || Array.isArray(value))
539
- ? { type: value === null ? 'null' : typeof value }
540
- : { keys: Object.keys(value).sort() };
541
- return { violation_kind: 'unexpected_or_missing_keys', pointer: '/',
542
- expected: { keys: [...keys].sort() }, actual };
543
- }
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;
544
600
  const schemas = [CREATE_INPUT_SCHEMA, PHASE_CREATE_INPUT_SCHEMA,
545
601
  DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA,
546
602
  DONE_CONDITION_CREATE_INPUT_SCHEMA];
547
- if (!schemas.includes(value.schema)) {
548
- return { violation_kind: 'const_mismatch', pointer: '/schema',
549
- expected: { one_of: schemas }, actual: value.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 });
550
606
  }
551
607
  for (const field of ['project_id', 'plan_key', 'plan_version']) {
552
- if (!isTodoIdentifier(value[field])) {
553
- return { violation_kind: 'identifier_invalid', pointer: `/${field}`,
554
- 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] });
555
611
  }
556
612
  }
557
- if (!exactRecord(value.actor, ['host', 'session', 'agent'])) {
558
- return { violation_kind: 'unexpected_or_missing_keys', pointer: '/actor',
559
- expected: { keys: ['agent', 'host', 'session'] },
560
- actual: (value.actor === null || typeof value.actor !== 'object')
561
- ? { type: value.actor === null ? 'null' : typeof value.actor }
562
- : { keys: Object.keys(value.actor).sort() } };
563
- }
564
- for (const field of ['host', 'session', 'agent']) {
565
- if (!isTodoIdentifier(value.actor[field])) {
566
- return { violation_kind: 'identifier_invalid', pointer: `/actor/${field}`,
567
- 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
+ }
568
624
  }
569
625
  }
570
- if (!isStrictTodoTimestamp(value.recorded_at)) {
571
- return { violation_kind: 'timestamp_invalid', pointer: '/recorded_at',
572
- 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 });
573
629
  }
574
- if (!isTodoDigest(value.input_digest)
575
- || value.input_digest !== todoSelfDigest(value, 'input_digest')) {
576
- 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',
577
633
  expected: todoSelfDigest(value, 'input_digest'),
578
- actual: { type: typeof value.input_digest, matches_canonical_input: false } };
634
+ actual: { type: typeof value.input_digest, matches_canonical_input: false } });
579
635
  }
580
636
  if (!Array.isArray(value.tasks)) {
581
- return { violation_kind: 'type', pointer: '/tasks', expected: { type: 'array' },
582
- 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
+ }
583
660
  }
584
661
  for (const [index, task] of value.tasks.entries()) {
585
662
  for (const field of ['narrative_anchor', 'compile_binding']) {
586
663
  if (task?.[field] !== null) {
587
- return { violation_kind: 'not_authorable_at_create', pointer: `/tasks/${index}/${field}`,
588
- 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] });
589
666
  }
590
667
  }
591
668
  }
592
- try {
593
- buildTodoPlan({
594
- schema: planSchemaForCreateInput(value.schema), project_id: value.project_id,
595
- plan_key: value.plan_key, plan_version: value.plan_version,
596
- predecessor_plan_digest: null, tasks: value.tasks,
597
- hard_dependencies: value.hard_dependencies, joins: value.joins,
598
- ...(phaseInput ? { phases: value.phases } : {}),
599
- ...(decoupledPhaseInput ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
600
- });
601
- } catch (error) {
602
- // Author-specific fields keep their existing diagnostic priority.
603
- const shape = describePlanShapeViolation(value, { phaseInput });
604
- if (shape !== null) return shape;
605
- return {
606
- violation_kind: error?.detail?.violation_kind ?? error?.reason ?? error?.code ?? 'topology_invalid',
607
- pointer: error?.detail?.pointer ?? '/',
608
- expected: error?.detail?.expected ?? { schema: value.schema },
609
- actual: error?.detail?.actual ?? { message: String(error?.message ?? error) },
610
- };
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
+ }
611
691
  }
612
- return null;
692
+ return found;
613
693
  }
614
694
 
615
695
  export function validatePlanCreateInput(input) {
616
- if (![MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input?.schema)) {
617
- throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
618
- violation_kind: 'const_mismatch', pointer: '/schema',
619
- expected: MEMO_PHASE_CREATE_INPUT_SCHEMA,
620
- accepted: [MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA],
621
- actual: typeof input?.schema === 'string' ? input.schema : { type: typeof input?.schema },
622
- next_action: CURRENT_CREATE_SCHEMA_COMMAND,
623
- });
624
- }
625
- if (!Array.isArray(input.tasks)) {
696
+ const found = describeCreateInputViolations(input);
697
+ const problems = found.map(({ violation }) => violation);
698
+ if (!Array.isArray(input?.tasks)) {
626
699
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
627
700
  violation_kind: 'type', pointer: '/tasks', expected: { type: 'array', min_items: 1 },
628
- actual: { type: input.tasks === null ? 'null' : typeof input.tasks },
629
- next_action: CURRENT_CREATE_SCHEMA_COMMAND,
701
+ actual: { type: input?.tasks === null ? 'null' : typeof input?.tasks },
702
+ problems, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
630
703
  });
631
704
  }
632
- const invalidMemoIndex = input.tasks.findIndex((task) => !isTodoDesignMemo(task?.design_memo));
633
- if (invalidMemoIndex >= 0) {
634
- 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) {
635
710
  throw new TodoStoreError('DESIGN_MEMO_REQUIRED', 'plan_create_design_memo_required', undefined, {
636
- violation_kind: explained.reason, pointer: `/tasks/${invalidMemoIndex}/design_memo`,
637
- expected: explained.expected, actual: explained.actual,
638
- 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,
639
712
  });
640
713
  }
641
- if (input.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA) {
642
- // design_memoと同じ本文規則。違いはnull(終了条件なし)を許すことだけ。
643
- const invalidIndex = input.tasks.findIndex((task) => task?.done_condition !== null
644
- && !isTodoDesignMemo(task?.done_condition));
645
- if (invalidIndex >= 0) {
646
- const explained = explainTodoDesignMemo(input.tasks[invalidIndex]?.done_condition);
647
- throw new TodoStoreError('INPUT_INVALID', 'plan_create_done_condition_invalid', undefined, {
648
- violation_kind: explained.reason, pointer: `/tasks/${invalidIndex}/done_condition`,
649
- expected: { ...explained.expected, nullable: true }, actual: explained.actual,
650
- next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
651
- });
652
- }
653
- }
654
- const violation = describeCreateInputViolation(input);
655
- if (violation !== null) {
656
- throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
657
- ...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,
658
718
  next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
659
719
  });
660
- }
661
720
  }
662
721
 
663
- 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
+ }) {
664
725
  const repoRoot = resolveRepoRoot(cwd);
665
726
  if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
666
- const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
727
+ const input = completeCreateInput(
728
+ inputValue ?? await readCanonicalInput(repoRoot, inputRef), { env, now: new Date() });
667
729
  validatePlanCreateInput(input);
668
730
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
669
731
  const dispatchShape = computeTodoDispatchShapeForPlan({
@@ -722,15 +784,15 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
722
784
  }
723
785
 
724
786
  /**
725
- * `--schema --json`(版指定なし)の既定はCURRENT_CREATE_INPUT_SCHEMAと同じv4にする。
787
+ * `--schema --json`(版指定なし)の既定はCURRENT_CREATE_INPUT_SCHEMAと同じv5にする。
726
788
  * 既定がv1のままだと、素の`--schema`を叩いたAIが古いv1(Phaseを表現できない)を
727
789
  * 受け取り、実運用で通らない入力を作ってしまう(実際に踏んだ)。
728
790
  * `--schema-version 1`は互換のため引き続き取得できる(bin/lattice.mjs側で許可)。
729
791
  *
730
- * 「どの版を返したか」は返すJSON Schema自身の`title`(例: `lattice.plan_create_input.v4`)が
792
+ * 「どの版を返したか」は返すJSON Schema自身の`title`(例: `lattice.plan_create_input.v5`)が
731
793
  * 既に機械可読に持っている。壊さずに追加のkeyを足す理由が無いので足さない。
732
794
  */
733
- export async function runPlanCreateSchema({ stdout, version = 4 }) {
795
+ export async function runPlanCreateSchema({ stdout, version = 5 }) {
734
796
  if (![1, 2, 3, 4, 5].includes(version)) throw new TypeError('unsupported plan create schema version');
735
797
  const expected = version === 5 ? DONE_CONDITION_CREATE_INPUT_SCHEMA : version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
736
798
  : version === 3 ? DECOUPLED_PHASE_CREATE_INPUT_SCHEMA
@@ -747,6 +809,34 @@ export async function runPlanCreateSchema({ stdout, version = 4 }) {
747
809
  }
748
810
  }
749
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
+
750
840
  const PLAN_SHOW_RESULT_SCHEMA = 'lattice.plan_show_result.v1';
751
841
 
752
842
  /**
@@ -824,6 +914,10 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
824
914
  has_phases: phaseInput,
825
915
  phases: phaseList,
826
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 ?? [],
827
921
  topology: {
828
922
  task_count: dispatchShape.task_count,
829
923
  critical_path_length: dispatchShape.critical_path_length,
@@ -861,12 +955,32 @@ export function projectStatusFailure({ cwd, stdout, cliVersion, error }) {
861
955
  return 1;
862
956
  }
863
957
 
864
- 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';
865
961
  const payload = {
866
- schema: 'lattice.cli_error.v2', code: error?.code ?? 'INTERNAL_FAILURE',
867
- 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 }),
868
964
  };
869
- if (error?.detail && Object.keys(error.detail).length > 0) payload.detail = error.detail;
870
965
  stderr.write(`${JSON.stringify(payload)}\n`);
871
966
  return 1;
872
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
+ }