@quolu/lattice 0.83.0 → 0.84.1

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