@quolu/lattice 0.85.1 → 0.85.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/lattice.mjs CHANGED
@@ -122,7 +122,7 @@ if (help !== null) {
122
122
  cwd: process.cwd(), planInputRef: flags['plan-input'], reviewRef: flags.review, stdout: process.stdout,
123
123
  });
124
124
  } catch (error) {
125
- process.exitCode = projectCliFailure(process.stderr, error);
125
+ process.exitCode = projectCliFailure(process.stderr, error, { command: 'scope-review', flags });
126
126
  }
127
127
  }
128
128
  } else if (args.length === 4 && args[0] === 'plan' && args[1] === 'revise'
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.plan_create_input.v4.schema.json",
4
4
  "title": "lattice.plan_create_input.v4",
5
- "description": "Canonical initial authoring input for a phase-audited plan. Every task carries a design memo; an omitted, null or blank one is recorded as `NO_PLAN`. After the complete plan is written, run `lattice plan scope-review --plan-input <file> --review <scope-review.json> --json` (the review input: `lattice plan scope-review --schema --json`) and confirm that every task preserves an owner-supplied work specification without adding a product purpose. あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください actor, recorded_at, input_digest and tasks[].design_memo may be omitted: the machine fills the seat actor, the current time and NO_PLAN, recomputes input_digest and sorts every list into canonical order.",
5
+ "description": "Canonical initial authoring input for a phase-audited plan. Every task carries a design memo; an omitted, null or blank one is recorded as `NO_PLAN`. After the complete plan is written, run `lattice plan scope-review --plan-input <file> --review <scope-review.json> --json` (the review input: `lattice plan scope-review --schema --json`) and confirm that every task preserves an owner-supplied work specification without adding a product purpose. actor, recorded_at, input_digest and tasks[].design_memo may be omitted: the machine fills the seat actor, the current time and NO_PLAN, recomputes input_digest and sorts every list into canonical order.",
6
6
  "$comment": "Runtime validation additionally enforces canonical JSON+LF bytes, sorted identifiers and edges, unique ids, combined task/phase acyclicity, byte bounds, non-empty design_memo (omitted, null or blank becomes NO_PLAN), and input_digest (recomputed). tasks, hard_dependencies, joins, phases and phase_accept_dependencies are sorted into canonical order and exact duplicates dropped before validation.",
7
7
  "type": "object",
8
8
  "additionalProperties": false,
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.plan_create_input.v5.schema.json",
4
4
  "title": "lattice.plan_create_input.v5",
5
- "description": "Canonical initial authoring input for a phase-audited plan. Every task carries a design memo; an omitted, null or blank one is recorded as `NO_PLAN`. After the complete plan is written, run `lattice plan scope-review --plan-input <file> --review <scope-review.json> --json` (the review input: `lattice plan scope-review --schema --json`) and confirm that every task preserves an owner-supplied work specification without adding a product purpose. あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください v5 adds the per-task authored `done_condition`: plain text (or null when the author states none) that Lattice records and shows but never evaluates, never assigns and never records as done. Builds lattice.todo_plan.v8. The author writes intent: ids, titles, phases and edges (see `lattice plan create --template --json`). Every key whose value is constant or null may be omitted and the machine fills it: schema (this version), project_id (the store's project id; with no store yet, the repository directory name as a lower-case identifier; a different value is refused as project_id_mismatch), plan_version (v1; `lattice plan revise` uses the active plan's), actor (the seat actor), recorded_at (the current time; an ISO-8601 date-time with an explicit zone is normalised to UTC milliseconds), input_digest (recomputed), tasks[].design_memo (NO_PLAN), tasks[].lane (main), tasks[].narrative_ref, narrative_anchor, compile_binding, parent_task_id and done_condition (null), phases[].gate_policy (heavy), phases[].predecessor_phase_ids ([]), phases[].required_evidence_slots ([\"acceptance\"]), hard_dependencies, joins and phase_accept_dependencies ([]), and project_id/plan_key of an edge reference (this input's own). Every list is sorted into canonical order. A refusal lists every problem at once in detail.problems. Edge direction: from is the prerequisite; to starts after from is done.",
5
+ "description": "Canonical initial authoring input for a phase-audited plan. Every task carries a design memo; an omitted, null or blank one is recorded as `NO_PLAN`. After the complete plan is written, run `lattice plan scope-review --plan-input <file> --review <scope-review.json> --json` (the review input: `lattice plan scope-review --schema --json`) and confirm that every task preserves an owner-supplied work specification without adding a product purpose. v5 adds the per-task authored `done_condition`: plain text (or null when the author states none) that Lattice records and shows but never evaluates, never assigns and never records as done. Builds lattice.todo_plan.v8. The author writes intent: ids, titles, phases and edges (see `lattice plan create --template --json`). Every key whose value is constant or null may be omitted and the machine fills it: schema (this version), project_id (the store's project id; with no store yet, the repository directory name as a lower-case identifier; a different value is refused as project_id_mismatch), plan_version (v1; `lattice plan revise` uses the active plan's), actor (the seat actor), recorded_at (the current time; an ISO-8601 date-time with an explicit zone is normalised to UTC milliseconds), input_digest (recomputed), tasks[].design_memo (NO_PLAN), tasks[].lane (main), tasks[].narrative_ref, narrative_anchor, compile_binding, parent_task_id and done_condition (null), phases[].gate_policy (heavy), phases[].predecessor_phase_ids ([]), phases[].required_evidence_slots ([\"acceptance\"]), hard_dependencies, joins and phase_accept_dependencies ([]), and project_id/plan_key of an edge reference (this input's own). Every list is sorted into canonical order. A refusal lists every problem at once in detail.problems. Edge direction: from is the prerequisite; to starts after from is done.",
6
6
  "$comment": "Runtime validation additionally enforces canonical JSON+LF bytes, sorted identifiers and edges, unique ids, combined task/phase acyclicity, byte bounds, non-empty design_memo (omitted, null or blank becomes NO_PLAN), and input_digest (recomputed). v5 additionally accepts hard_dependencies, joins, each joins[].after, phase_accept_dependencies, phases, phases[].predecessor_phase_ids and phases[].required_evidence_slots in any order or with exact duplicates: they are sorted into canonical order and de-duplicated before validation. tasks are sorted by task_id. Entries with the same key but different content are still refused.",
7
7
  "type": "object",
8
8
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.85.1",
3
+ "version": "0.85.2",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
package/src/cli-help.mjs CHANGED
@@ -3,8 +3,8 @@ import { TODO_INDEPENDENCE_WORKFLOW } from './todo-independence-guidance.mjs';
3
3
  const ROOT_HELP = `Usage: lattice <command> [options]
4
4
 
5
5
  Commands:
6
- status --json Discover the current project and next action
7
- session-context --json Session開始時の現在地を1プロセスで返す(工程状態+並列可否)
6
+ status [--json] Discover the current project and next action
7
+ session-context [--json] Session開始時の現在地を1プロセスで返す(工程状態+並列可否)
8
8
  plan <command> Create, compile, or verify plans
9
9
  run <command> Start or observe compiled runs
10
10
  event verify Verify a runtime event log
@@ -31,9 +31,9 @@ Commands:
31
31
  create --schema-version <1|2|3|4|5> --json
32
32
  create --template --json # 作者が書くkeyだけの最小のv5入力(そのままplan createが受理する)
33
33
  backchain --schema --json # 最終成果から必要な機能を逆算する入力契約
34
- revise --input <file> [--dry-run] --json # 工程の全体と明示した状態移行から改訂する
34
+ revise --input <file> [--dry-run] [--json] # 工程の全体と明示した状態移行から改訂する
35
35
  revise --schema --json
36
- backchain --input <file> [--dry-run] --json
36
+ backchain --input <file> [--dry-run] [--json]
37
37
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
38
38
  show <plan_key> --json # task・依存辺・phase・状態をplan本体から1コマンドで投影する
39
39
  scope-review --plan-input <file> --review <scope-review.json> --json
@@ -180,8 +180,8 @@ ${TODO_INDEPENDENCE_WORKFLOW.join('\n')}
180
180
  todo startのadvisoryとtodo independenceの投影が、その状況と次の一歩を返す。
181
181
  競合の同時起動は助言のまま。並列既定はstatusのdispatch_frontierとnext_actionが案内する。
182
182
  `,
183
- sensor: `Usage: lattice sensor <init|sync> [path] --json
184
- lattice sensor diff <rootA> <rootB> [options] --json
183
+ sensor: `Usage: lattice sensor <init|sync> [path] [--json]
184
+ lattice sensor diff <rootA> <rootB> [options] [--json]
185
185
 
186
186
  diff options:
187
187
  --subtree-a <rel> # A側をこの部分木だけに絞り、prefixを剥がしてから突き合わせる
@@ -237,13 +237,13 @@ Windows製品hookとGrok製品hookは未対応として返し、MCPは独立し
237
237
 
238
238
  const SUBCOMMAND_USAGE = Object.freeze({
239
239
  'setup status': 'setup status [--host <claude|codex|grok|cursor|all>] [--json]',
240
- status: 'status --json',
241
- 'session-context': 'session-context --json',
240
+ status: 'status [--json]',
241
+ 'session-context': 'session-context [--json]',
242
242
  'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5> --json | --template --json',
243
243
  'plan show': 'plan show <plan_key> --json',
244
244
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
245
- 'plan backchain': 'plan backchain --input <file> [--dry-run] --json | --schema --json',
246
- 'plan revise': 'plan revise --input <file> [--dry-run] --json | --schema --json',
245
+ 'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --schema --json',
246
+ 'plan revise': 'plan revise --input <file> [--dry-run] [--json] | --schema --json',
247
247
  'plan compile': 'plan compile --request <request.json> | --schema --json',
248
248
  'plan verify': 'plan verify --request <request.json> --plan <plan.json>',
249
249
  'run start': 'run start --request <request.json> --executor <adapter>'
@@ -323,10 +323,10 @@ const SUBCOMMAND_USAGE = Object.freeze({
323
323
  'todo revise-phase': 'todo revise-phase --plan <key> --input <file> | --schema --json',
324
324
  'todo revise-set': 'todo revise-set --input <file> | --schema --json',
325
325
  'todo migrate': 'todo migrate --input <extraction.json> [--serialization-reviewed] [--json] | --input <extraction.json> --dry-run --json [--serialization-reviewed] | --schema --json',
326
- 'sensor init': 'sensor init [path] --json',
327
- 'sensor sync': 'sensor sync [path] --json',
326
+ 'sensor init': 'sensor init [path] [--json]',
327
+ 'sensor sync': 'sensor sync [path] [--json]',
328
328
  'sensor diff': 'sensor diff <rootA> <rootB> [--subtree-a <rel>] [--subtree-b <rel>]'
329
- + ' [--map-a <from>=<to>] [--map-b <from>=<to>] [--limit <n>] --json',
329
+ + ' [--map-a <from>=<to>] [--map-b <from>=<to>] [--limit <n>] [--json]',
330
330
  'runtime-errors snapshot': 'runtime-errors snapshot [--after-cursor <n>] [--limit <n>] --json',
331
331
  'runtime-errors ack': 'runtime-errors ack <cursor> --json',
332
332
  'runtime-errors diagnostics': 'runtime-errors diagnostics --json',
@@ -3,6 +3,12 @@
3
3
  // Refusal sites keep their own keys; this fills the three keys the seat contract requires.
4
4
 
5
5
  const PLACEHOLDER = /^[a-z_]+$/u;
6
+ // a27: one placeholder per flag for every missing-flag text (plan and todo alike).
7
+ export const FLAG_PLACEHOLDER = Object.freeze({
8
+ input: '<file>', 'plan-input': '<file>', review: '<file>', evidence: '<file>', 'test-result': '<file>',
9
+ request: '<file>', reason: '<text>', 'override-reason': '<text>', message: '<text>', plan: '<key>', task: '<id>',
10
+ });
11
+ const placeholderFor = (pointer) => FLAG_PLACEHOLDER[String(pointer).replace(/^--/u, '')] ?? '<value>';
6
12
  const EXAMPLE_TIMESTAMP = '2026-11-08T12:00:00.000Z';
7
13
 
8
14
  const q = (value) => (typeof value === 'string' ? `'${value}'` : JSON.stringify(value));
@@ -109,6 +115,18 @@ const revisionDigest = (what) => ({
109
115
  // rule -> { pointer?: string | (detail, ctx) => string, repair: (detail, ctx, pointer) => string }
110
116
  const REGISTRY = {
111
117
  unsorted: { repair: movedAfter },
118
+ duplicate: {
119
+ repair: (detail, ctx, pointer) => `${q(detail.actual)} appears more than once (${pointer}); give each entry its own id or remove the extra one.`,
120
+ },
121
+ dependency_cycle_in_input: {
122
+ repair: (detail) => `Tasks ${strings(detail.cycle).join(' -> ')} form a cycle: remove one of those edges from /hard_dependencies (or /joins), then rerun.`,
123
+ },
124
+ authoring_ref_invalid: {
125
+ repair: (detail, ctx, pointer) => `Set ${pointer} to the repo path of the plan create input this chain describes (for example \`plan.json\`); it is ${q(detail.actual)}. See \`${schemaCommand(ctx)}\`.`,
126
+ },
127
+ git_toplevel_unresolved: {
128
+ repair: () => 'cd into the project repository, or run `git init` there first',
129
+ },
112
130
  unsorted_or_duplicate_collection: {
113
131
  repair: (detail, ctx, pointer) => `${movedAfter(detail, ctx, pointer)} Remove the entry if ${q(detail.actual)} appears twice.`,
114
132
  },
@@ -167,7 +185,7 @@ const REGISTRY = {
167
185
  repair: (detail, ctx) => `Only a blocked task can be unblocked; check its status with \`${showTask(detail, ctx)}\`.`,
168
186
  },
169
187
  reopen_has_started_successor: {
170
- repair: (detail, ctx) => `A successor of ${taskOf(detail, ctx)} has already started: split the work with \`lattice todo split --plan ${planOf(detail, ctx)} --input <file>\`, or pass --override-reason <text> to reopen anyway.`,
188
+ repair: (detail, ctx) => `A successor of ${taskOf(detail, ctx)} has already started: to reopen it anyway run \`lattice todo reopen --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)} --reason <text> --override-reason <text>\`.`,
171
189
  },
172
190
  requested_plan_mismatch: {
173
191
  pointer: '--plan',
@@ -298,7 +316,7 @@ const REGISTRY = {
298
316
  },
299
317
 
300
318
  flag_missing: {
301
- repair: (detail, ctx, pointer) => `Add ${pointer}${detail.expected?.type === 'boolean' ? '' : ' <value>'} to \`${run(ctx)}\`.`,
319
+ repair: (detail, ctx, pointer) => `Add ${pointer}${detail.expected?.type === 'boolean' ? '' : ` ${placeholderFor(pointer)}`} to \`${run(ctx)}\`.`,
302
320
  },
303
321
  flag_takes_no_value: {
304
322
  repair: (detail, ctx, pointer) => `${pointer} is a switch: pass it without a value to \`${run(ctx)}\`.`,
@@ -390,6 +408,14 @@ function registeredPointer(entry, detail, ctx) {
390
408
  * A concrete existing next_action wins; a placeholder token (^[a-z_]+$) is replaced by the registered repair.
391
409
  * context = { family: 'todo' | 'plan', command, plan, task, flags } (all optional).
392
410
  */
411
+ // a27: a reason that only means "the value you typed names nothing" gets an input code, not
412
+ // STORE_INCONSISTENT (which says the store itself is broken). The one mapping for every error writer.
413
+ const INPUT_REFUSAL_CODES = Object.freeze({ plan_not_active: 'PLAN_NOT_FOUND' });
414
+ export function publicRefusalCode(code, reason) {
415
+ return code === 'STORE_INCONSISTENT' && Object.hasOwn(INPUT_REFUSAL_CODES, reason)
416
+ ? INPUT_REFUSAL_CODES[reason] : code;
417
+ }
418
+
393
419
  export function withRefusalGuidance({ code, message, detail }, context = {}) {
394
420
  const base = record(detail) ? detail : {};
395
421
  const rule = base.rule ?? base.violation_kind ?? base.violation_reason ?? base.reason ?? message;
package/src/hooks-cli.mjs CHANGED
@@ -1122,7 +1122,10 @@ export async function runHooksCli({
1122
1122
  }) {
1123
1123
  if (argv.length !== 3 || !['install', 'status', 'uninstall', 'emit'].includes(argv[0])
1124
1124
  || argv[1] !== '--host' || !HOSTS.has(argv[2])) {
1125
- return failure(stdout, 'USAGE', HOST_USAGE, 2);
1125
+ const known = ['install', 'status', 'uninstall', 'emit'].includes(argv[0]);
1126
+ return failure(stdout, 'USAGE', HOST_USAGE, 2, known
1127
+ ? { pointer: '--host', next_action: `lattice hooks ${argv[0]} --host <claude|codex|cursor>` }
1128
+ : { pointer: null, next_action: 'lattice hooks --help' });
1126
1129
  }
1127
1130
  const [command, , host] = argv;
1128
1131
  if (platform === 'win32') {
@@ -59,19 +59,58 @@ function registeredTasks(authoring) {
59
59
  });
60
60
  }
61
61
 
62
+ const CHAIN_KEYS = Object.freeze([
63
+ 'schema', 'authoring_ref', 'project_id', 'plan_key', 'plan_version',
64
+ 'goal', 'features', 'tasks', 'chain_digest',
65
+ ]);
66
+
67
+ /**
68
+ * a27: 上位の形の違反をすべて、pointer付きで返す。`authoring_ref`はfileを読む前にここで見るので、
69
+ * 欠けた・壊れたrefが`--input`のpathの誤りに見えることはない。
70
+ */
71
+ export function backchainShapeProblems(chain) {
72
+ if (chain === null || typeof chain !== 'object' || Array.isArray(chain)) {
73
+ return [{ violation_kind: 'type', pointer: '/', expected: { type: 'object' },
74
+ actual: { type: Array.isArray(chain) ? 'array' : chain === null ? 'null' : typeof chain } }];
75
+ }
76
+ const problems = [];
77
+ const allowed = [...CHAIN_KEYS, 'continuity'];
78
+ const actual = Object.keys(chain).sort();
79
+ const missing = CHAIN_KEYS.filter((key) => !actual.includes(key)).sort();
80
+ const unexpected = actual.filter((key) => !allowed.includes(key));
81
+ if (missing.length > 0 || unexpected.length > 0) {
82
+ problems.push({ violation_kind: 'unexpected_or_missing_keys', pointer: '/',
83
+ expected: { keys: [...CHAIN_KEYS].sort() }, actual: { keys: actual },
84
+ missing_keys: missing, unexpected_keys: unexpected });
85
+ }
86
+ if ('schema' in chain && chain.schema !== BACKCHAIN_SCHEMA) {
87
+ problems.push({ violation_kind: 'const_mismatch', pointer: '/schema',
88
+ expected: { one_of: [BACKCHAIN_SCHEMA] }, actual: chain.schema });
89
+ }
90
+ if (!isTodoRef(chain.authoring_ref)) {
91
+ problems.push({ violation_kind: 'authoring_ref_invalid', pointer: '/authoring_ref',
92
+ expected: { format: 'repo_relative_path_to_plan_create_input' }, actual: chain.authoring_ref ?? null });
93
+ }
94
+ for (const field of ['project_id', 'plan_key', 'plan_version']) {
95
+ if (field in chain && !isTodoIdentifier(chain[field])) {
96
+ problems.push({ violation_kind: 'identifier_invalid', pointer: `/${field}`,
97
+ expected: { format: 'todo_identifier' }, actual: chain[field] });
98
+ }
99
+ }
100
+ return problems;
101
+ }
102
+
103
+ function failOnShape(chain) {
104
+ const problems = backchainShapeProblems(chain);
105
+ if (problems.length > 0) fail('schema_invalid', problems[0].pointer, { ...problems[0], problems });
106
+ }
107
+
62
108
  /**
63
109
  * AIの機能分解を検査する。意味の正しさを推測せず、最終機能からの到達性と
64
110
  * producer/consumer の契約が閉じていることだけを機械が保証する。
65
111
  */
66
112
  export function validatePlanBackchain(chain, authoring) {
67
- const keys = [
68
- 'schema', 'authoring_ref', 'project_id', 'plan_key', 'plan_version',
69
- 'goal', 'features', 'tasks', 'chain_digest',
70
- ];
71
- if (!(exactRecord(chain, keys) || exactRecord(chain, [...keys, 'continuity']))
72
- || chain.schema !== BACKCHAIN_SCHEMA || !isTodoRef(chain.authoring_ref)
73
- || !isTodoIdentifier(chain.project_id) || !isTodoIdentifier(chain.plan_key)
74
- || !isTodoIdentifier(chain.plan_version)) fail('schema_invalid', '/');
113
+ failOnShape(chain);
75
114
  if (chain.continuity !== undefined && (!Array.isArray(chain.continuity)
76
115
  || chain.continuity.length > 512
77
116
  || !chain.continuity.every((entry) => exactRecord(entry, ['task_id', 'policy', 'reason'])
@@ -590,6 +629,7 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
590
629
  export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
591
630
  const repoRoot = gitRoot(cwd);
592
631
  const chain = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' });
632
+ failOnShape(chain);
593
633
  const authoring = completeCreateInput(await readAuthoringJsonFile(repoRoot, chain.authoring_ref, {
594
634
  invalidCode: 'PLAN_BACKCHAIN_INVALID',
595
635
  }), { env, now: new Date() });
@@ -58,8 +58,9 @@ async function readJsonWithinRepo(repoRoot, inputRef) {
58
58
  }
59
59
  let stats;
60
60
  try { stats = await lstat(absolute); } catch {
61
- throw new TodoStoreError('INPUT_UNREADABLE', 'input_unreadable', undefined,
62
- { input_ref: inputRef });
61
+ // a27: 無いfileは原因(input_missing)と解いた場所(repo_root)を言う。どのflagかはCLIの文脈が名指す。
62
+ throw new TodoStoreError('INPUT_UNREADABLE', 'input_missing', undefined,
63
+ { input_ref: inputRef, repo_root: canonicalRoot });
63
64
  }
64
65
  if (!stats.isFile() || stats.isSymbolicLink() || stats.size > MAX_INPUT_BYTES
65
66
  || await realpath(absolute) !== absolute) {
@@ -43,7 +43,7 @@ import {
43
43
  computeTodoDispatchShapeForPlan,
44
44
  } from './todo-dispatch-shape.mjs';
45
45
  import { completeCreateInput, explainFlagCommand, readAuthoringJsonFile, resolveTodoActor } from './todo-authoring-input.mjs';
46
- import { withRefusalGuidance } from './cli-refusal-guidance.mjs';
46
+ import { publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
47
47
 
48
48
  const STORE_REF = '.lattice/todo';
49
49
  const MANIFEST_REF = `${STORE_REF}/manifest.json`;
@@ -227,7 +227,8 @@ function invalidStatus({ cliVersion, repoRoot, reason, nextAction = null }) {
227
227
  store: { ref: STORE_REF, absolute_path: repoRoot === null ? null : path.join(repoRoot, STORE_REF) },
228
228
  active_plans: [], active_runs: [], can_create_plan: false,
229
229
  next_action: nextAction ?? {
230
- command: repoRoot === null ? 'git status' : 'lattice todo verify', reason,
230
+ // a27: repoの外では、もう一度失敗するgit statusでなく、repoを作るgit initを示す。
231
+ command: repoRoot === null ? 'git init' : 'lattice todo verify', reason,
231
232
  },
232
233
  });
233
234
  }
@@ -470,6 +471,9 @@ const isPlainRecord = (value) => value !== null && typeof value === 'object' &&
470
471
  const typeOf = (value) => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value);
471
472
 
472
473
  /** keyの過不足を`missing_keys`/`unexpected_keys`で名指す。recordでなければ全keyが足りない。 */
474
+ // a27: 機械が整列するので、隣と等しいidは重複である。順序の違反と言わない。
475
+ const orderViolation = (previous, current) => (previous === current ? 'duplicate' : 'unsorted');
476
+
473
477
  function keyShapeViolation(pointer, value, keys) {
474
478
  const actual = isPlainRecord(value) ? Object.keys(value).sort() : null;
475
479
  return {
@@ -513,7 +517,7 @@ function describePlanShapeViolation(value, { phaseInput }) {
513
517
  }
514
518
  const previous = value.tasks[index - 1]?.task_id;
515
519
  if (index > 0 && isTodoIdentifier(previous) && isTodoIdentifier(task.task_id) && !(previous < task.task_id)) {
516
- problems.push({ violation_kind: 'unsorted', pointer: `/tasks/${index}/task_id`,
520
+ problems.push({ violation_kind: orderViolation(previous, task.task_id), pointer: `/tasks/${index}/task_id`,
517
521
  expected: { greater_than: previous, order: 'ascending_unique' }, actual: task.task_id });
518
522
  }
519
523
  }
@@ -551,7 +555,8 @@ function describePlanShapeViolation(value, { phaseInput }) {
551
555
  }
552
556
  const unsorted = list.findIndex((entry, i) => i > 0 && !(list[i - 1] < entry));
553
557
  if (unsorted > 0) {
554
- problems.push({ violation_kind: 'unsorted', pointer: `/phases/${index}/${field}/${unsorted}`,
558
+ problems.push({ violation_kind: orderViolation(list[unsorted - 1], list[unsorted]),
559
+ pointer: `/phases/${index}/${field}/${unsorted}`,
555
560
  expected: { greater_than: list[unsorted - 1], order: 'ascending_unique' },
556
561
  actual: list[unsorted] });
557
562
  }
@@ -559,7 +564,7 @@ function describePlanShapeViolation(value, { phaseInput }) {
559
564
  const previous = value.phases[index - 1]?.phase_id;
560
565
  if (index > 0 && isTodoIdentifier(previous) && isTodoIdentifier(phase.phase_id)
561
566
  && !(previous < phase.phase_id)) {
562
- problems.push({ violation_kind: 'unsorted', pointer: `/phases/${index}/phase_id`,
567
+ problems.push({ violation_kind: orderViolation(previous, phase.phase_id), pointer: `/phases/${index}/phase_id`,
563
568
  expected: { greater_than: previous, order: 'ascending_unique' }, actual: phase.phase_id });
564
569
  }
565
570
  }
@@ -695,6 +700,75 @@ function describeCreateInputViolations(value) {
695
700
  return found;
696
701
  }
697
702
 
703
+ /** 辺の端が同じplanのtaskか。plan_key/project_idは補完済み(completeCreateInput)。 */
704
+ function ownRef(value, ref) {
705
+ return isPlainRecord(ref) && ref.plan_key === value.plan_key && ref.project_id === value.project_id;
706
+ }
707
+
708
+ /**
709
+ * a27: 同じplanのtaskだけで、無いtaskを指す辺と循環を、名指しで返す。plan跨ぎの辺はStoreが判定する。
710
+ * 循環は依存辺(from→to)とjoin(after→before)の有向graphで、最初に見つけた1つを`cycle`に載せる。
711
+ */
712
+ function describeCreateGraphViolations(value) {
713
+ const ids = new Set(value.tasks.map(({ task_id: id }) => id));
714
+ const known = [...ids].sort();
715
+ const problems = [];
716
+ const edges = [];
717
+ const endpoint = (ref, pointer) => {
718
+ if (!ownRef(value, ref)) return null;
719
+ if (ids.has(ref.task_id)) return ref.task_id;
720
+ problems.push({ violation_kind: 'unknown_reference', pointer: `${pointer}/task_id`,
721
+ expected: { one_of: known }, actual: ref.task_id });
722
+ return null;
723
+ };
724
+ for (const [index, edge] of (Array.isArray(value.hard_dependencies) ? value.hard_dependencies : []).entries()) {
725
+ const from = endpoint(edge?.from, `/hard_dependencies/${index}/from`);
726
+ const to = endpoint(edge?.to, `/hard_dependencies/${index}/to`);
727
+ if (from !== null && to !== null) edges.push([from, to]);
728
+ }
729
+ for (const [index, join] of (Array.isArray(value.joins) ? value.joins : []).entries()) {
730
+ const before = endpoint(join?.before, `/joins/${index}/before`);
731
+ for (const [at, ref] of (Array.isArray(join?.after) ? join.after : []).entries()) {
732
+ const after = endpoint(ref, `/joins/${index}/after/${at}`);
733
+ if (after !== null && before !== null) edges.push([after, before]);
734
+ }
735
+ }
736
+ const cycle = findCycle(known, edges);
737
+ if (cycle !== null) {
738
+ problems.push({ violation_kind: 'dependency_cycle_in_input', pointer: '/hard_dependencies',
739
+ expected: { acyclic: true }, actual: { cycle }, cycle });
740
+ }
741
+ return problems;
742
+ }
743
+
744
+ /** 有向graphの循環を1つ、閉じた路(先頭と末尾が同じ)で返す。無ければnull。 */
745
+ function findCycle(nodes, edges) {
746
+ const next = new Map(nodes.map((node) => [node, []]));
747
+ for (const [from, to] of edges) next.get(from).push(to);
748
+ const state = new Map();
749
+ const stack = [];
750
+ const visit = (node) => {
751
+ state.set(node, 'open');
752
+ stack.push(node);
753
+ for (const target of next.get(node)) {
754
+ if (state.get(target) === 'open') return [...stack.slice(stack.indexOf(target)), target];
755
+ if (!state.has(target)) {
756
+ const found = visit(target);
757
+ if (found !== null) return found;
758
+ }
759
+ }
760
+ stack.pop();
761
+ state.set(node, 'closed');
762
+ return null;
763
+ };
764
+ for (const node of nodes) {
765
+ if (state.has(node)) continue;
766
+ const found = visit(node);
767
+ if (found !== null) return found;
768
+ }
769
+ return null;
770
+ }
771
+
698
772
  export function validatePlanCreateInput(input) {
699
773
  const found = describeCreateInputViolations(input);
700
774
  const problems = found.map(({ violation }) => violation);
@@ -751,6 +825,15 @@ export async function runPlanCreate({
751
825
  }
752
826
  const input = completeCreateInput(given, { env, now: new Date(), projectId, planVersion: 'v1' });
753
827
  validatePlanCreateInput(input);
828
+ // a27: 同じplanの中の無いtaskを指す辺と循環は、入力の誤りとして作業を名指して返す。
829
+ // createだけで見る(revise・dependency connectは自分の辺を名指す拒否を持つ)。Storeの検査は最後の砦のまま。
830
+ const graphProblems = describeCreateGraphViolations(input);
831
+ if (graphProblems.length > 0) {
832
+ throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
833
+ ...graphProblems[0], problems: graphProblems,
834
+ next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
835
+ });
836
+ }
754
837
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
755
838
  const dispatchShape = computeTodoDispatchShapeForPlan({
756
839
  projectId: input.project_id,
@@ -779,7 +862,13 @@ export async function runPlanCreate({
779
862
  const store = manifest === null
780
863
  ? await initializeAuthoredTodoStore({ ...options,
781
864
  projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }] })
782
- : await appendAuthoredTodoPlan(options);
865
+ : await appendAuthoredTodoPlan(options).catch((error) => {
866
+ // a27: Storeの拒否はkeyを持たないので、断りの文が名指せるようにここで添える。
867
+ if (error?.detail?.reason !== 'plan_key_already_exists') throw error;
868
+ throw new TodoStoreError(error.code, 'plan_key_already_exists', undefined, {
869
+ ...error.detail, plan_key: input.plan_key,
870
+ });
871
+ });
783
872
  const member = store.members.find(({ plan }) => plan.plan_key === input.plan_key);
784
873
  const result = {
785
874
  schema: CREATE_RESULT_SCHEMA, project_id: store.project_id,
@@ -877,7 +966,8 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
877
966
  // 未知のplan_keyを「store不整合」と同じ扱いにするのはこのCLI全体の既定であり、
878
967
  // ここだけ別codeへ逸れると呼び出し側の分岐が増える。
879
968
  throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, {
880
- plan_key: planKey, next_action: 'check_active_plans_via_status',
969
+ plan_key: planKey, pointer: '<plan_key>',
970
+ next_action: `'${planKey}' is not an active plan: run \`lattice todo status --json\` to list the active plan keys, then rerun \`lattice plan show <plan_key> --json\` with one of them.`,
881
971
  });
882
972
  }
883
973
  const { plan, tasks, phases } = member;
@@ -982,7 +1072,7 @@ export function projectStatusFailure({ cwd, stdout, cliVersion, error }) {
982
1072
  }
983
1073
 
984
1074
  export function projectCliFailure(stderr, error, context = {}) {
985
- const code = error?.code ?? 'INTERNAL_FAILURE';
1075
+ const code = publicRefusalCode(error?.code ?? 'INTERNAL_FAILURE', error?.detail?.reason);
986
1076
  const message = error?.message ?? 'project command failed';
987
1077
  const payload = {
988
1078
  schema: 'lattice.cli_error.v2', code, message,
@@ -230,7 +230,10 @@ class CliContractError extends Error {
230
230
 
231
231
  function usageFailure(stderr, args) {
232
232
  const received = args.length === 0 ? '(none)' : args.join(' ');
233
- stderr.write(`lattice: unsupported command or arguments: ${received}\n`);
233
+ // Typed like every other refusal, with a next step (a29); the message keeps the old wording.
234
+ stderr.write(`${JSON.stringify({ schema: CLI_ERROR_SCHEMA, code: 'USAGE',
235
+ message: `unsupported command or arguments: ${received}`,
236
+ detail: { arguments: args, next_action: 'lattice --help' } })}\n`);
234
237
  return 2;
235
238
  }
236
239
 
@@ -11,10 +11,10 @@ function writeJson(stream, value) {
11
11
  stream.write(`${JSON.stringify(value)}\n`);
12
12
  }
13
13
 
14
- const USAGE = 'usage: lattice sensor <init|sync> [path] --json'
14
+ const USAGE = 'usage: lattice sensor <init|sync> [path] [--json]'
15
15
  + ' | lattice sensor diff <rootA> <rootB>'
16
16
  + ' [--subtree-a <rel>] [--subtree-b <rel>] [--map-a <from>=<to>] [--map-b <from>=<to>]'
17
- + ' [--limit <n>] --json';
17
+ + ' [--limit <n>] [--json]';
18
18
 
19
19
  function usage(stderr) {
20
20
  writeJson(stderr, { schema: 'lattice.cli_error.v2', code: 'USAGE', message: USAGE });
@@ -100,6 +100,12 @@ export async function runSensorCli({ argv, stdout, stderr }) {
100
100
  const request = parse(argv);
101
101
  if (!request) return usage(stderr);
102
102
  if (request.command === 'diff') return runDiff(request.diff, stdout, stderr);
103
+ if (!existsSync(request.path)) {
104
+ writeJson(stderr, { schema: 'lattice.cli_error.v2', code: 'LATTICE_SENSOR_PATH_MISSING',
105
+ message: `no such project path: ${request.path}`,
106
+ detail: { path: request.path, next_action: `lattice sensor ${request.command}` } });
107
+ return 1;
108
+ }
103
109
  try {
104
110
  const result = await execute(request.command, request.path);
105
111
  if (result.code !== 0 || result.signal || result.overflow) {
@@ -546,6 +546,14 @@ export function compareSensorIndexes(request) {
546
546
  const sideB = withReadSnapshot(handleB, () => loadSide(
547
547
  handleB, makePathNormalizer(request.b.subtree ?? '', request.b.mappings ?? []), 'b',
548
548
  ));
549
+ // A subtree that matches no indexed file is a typo, not an empty side: say so instead of "ok".
550
+ for (const [side, loaded, subtree] of [['a', sideA, request.a.subtree], ['b', sideB, request.b.subtree]]) {
551
+ if (subtree && loaded.counts.files === 0 && loaded.excluded.files_outside_subtree > 0) {
552
+ throw new SensorDiffError('LATTICE_SENSOR_DIFF_SUBTREE_EMPTY',
553
+ `--subtree-${side} ${subtree} matches no indexed file`,
554
+ { side, subtree, next_action: `check the path; omit --subtree-${side} to compare the whole index` });
555
+ }
556
+ }
549
557
  const comparability = assessComparability(sideA, sideB);
550
558
 
551
559
  const nodes = diffNodes(sideA, sideB);
package/src/setup-cli.mjs CHANGED
@@ -118,6 +118,8 @@ export async function runSetupCli({ argv, stdout, env = process.env, platform =
118
118
  const state = !hosts.length || features.some((feature) => feature.state === 'failed') ? 'failed'
119
119
  : features.every((feature) => feature.state === 'verified') ? 'ready' : 'partial';
120
120
  stdout.write(`${JSON.stringify({ schema: 'lattice.setup_result.v1', operation: statusOnly ? 'status' : 'setup',
121
- platform, state, ...(hosts.length ? {} : { code: 'HOST_NOT_PRESENT' }), hosts: results })}\n`);
121
+ platform, state, ...(hosts.length ? {} : { code: 'HOST_NOT_PRESENT',
122
+ message: 'このHOMEにはAIの設定フォルダがありません',
123
+ next_action: 'lattice setup --host <claude|codex|grok|cursor>' }), hosts: results })}\n`);
122
124
  return state === 'ready' ? 0 : 1;
123
125
  }
package/src/todo-cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { retireStateConflict, validateProspectiveEvent } from './todo-readiness.mjs';
2
2
  import { cliCommandKind } from './cli-command-kind.mjs';
3
3
  import { cliFailureClass } from './cli-failure-class.mjs';
4
- import { withRefusalGuidance } from './cli-refusal-guidance.mjs';
4
+ import { FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
5
5
  import { readTaskBackchainContext } from './plan-backchain.mjs';
6
6
  import { gitSync } from './git-process.mjs';
7
7
  import { createHash } from 'node:crypto';
@@ -228,7 +228,7 @@ async function runTodoSchemaCommand(command, stdout) {
228
228
  function typedFailure(stderr, error, context = {}) {
229
229
  const payload = {
230
230
  schema: CLI_ERROR_SCHEMA,
231
- code: error.code,
231
+ code: publicRefusalCode(error.code, error.detail?.reason),
232
232
  message: error.message,
233
233
  detail: withRefusalGuidance(error, context),
234
234
  };
@@ -319,10 +319,27 @@ const TODO_FLAG_SPECS = Object.freeze({
319
319
  'phase close-unaudited': PHASE_REASON_FLAG_SPEC,
320
320
  split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
321
321
  note: NOTE_FLAG_SPEC,
322
+ // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
323
+ 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'input'], required: ['plan', 'phase'] }),
324
+ 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'reason', 'input'], required: ['plan', 'phase'] }),
325
+ 'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
326
+ 'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
327
+ 'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
328
+ show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
329
+ 'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
330
+ structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
331
+ status: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
322
332
  });
333
+ // a28: command groups, their subcommands and the one a refusal shows as the example.
334
+ const TODO_SUBCOMMANDS = Object.freeze({
335
+ dependency: { names: ['connect', 'disconnect'], example: 'connect' },
336
+ phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
337
+ evidence: { names: ['promote'], example: 'promote' },
338
+ });
339
+ const GROUP_COMMANDS = ['dependency', 'phase', 'evidence', 'independence', 'note', 'structure'];
323
340
  const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
324
- const FLAG_PLACEHOLDER = { reason: '<text>', 'override-reason': '<text>', message: '<text>',
325
- evidence: '<file>', 'test-result': '<file>', input: '<file>' };
341
+ // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
342
+ const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
326
343
  const shellWord = (value) => (/^[\w./:@-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
327
344
 
328
345
  /** The command again, with the flags given and a placeholder for each missing required flag. */
@@ -331,7 +348,7 @@ function repairedCommand(head, spec, flags) {
331
348
  for (const name of spec.known) {
332
349
  if (typeof flags[name] === 'string' && flags[name].length > 0) words.push(`--${name}`, shellWord(flags[name]));
333
350
  else if (flags[name] === true && spec.booleans?.includes(name)) words.push(`--${name}`);
334
- else if (spec.required.includes(name)) words.push(`--${name}`, FLAG_PLACEHOLDER[name] ?? `<${name}>`);
351
+ else if (spec.required.includes(name)) words.push(`--${name}`, placeholder(name));
335
352
  }
336
353
  return words.join(' ');
337
354
  }
@@ -342,22 +359,68 @@ function dependencyFlags(argv) {
342
359
  return flags !== null && IDENTIFIER_FLAGS.slice(3).every((name) => isTodoIdentifier(flags[name])) ? flags : null;
343
360
  }
344
361
 
362
+ /** a28: a read command's flags by name (order-free, --json optional) with valid identifiers, or null. */
363
+ function readFlags(argv, head) {
364
+ const flags = matchFlagCommand(argv, head, TODO_FLAG_SPECS[head.join(' ')]);
365
+ return flags !== null && ['plan', 'task'].every((name) => flags[name] === undefined || isTodoIdentifier(flags[name]))
366
+ ? flags : null;
367
+ }
368
+
369
+ /** `phase reopen` flags by name; --override-reason, when given, is non-empty. */
370
+ function phaseReopenFlags(argv) {
371
+ const flags = matchFlagCommand(argv, ['phase', 'reopen'], TODO_FLAG_SPECS['phase reopen']);
372
+ return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase)
373
+ && (flags['override-reason'] === undefined
374
+ || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0)) ? flags : null;
375
+ }
376
+
345
377
  /** `phase review|close-unaudited` flags by name (order-free), or null. */
346
378
  function phaseReasonFlags(argv) {
347
379
  const flags = matchFlagCommand(argv, argv.slice(0, 2), PHASE_REASON_FLAG_SPEC);
348
380
  return flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase) ? flags : null;
349
381
  }
350
382
 
351
- /** A todo write's argument refusal names the flag, the rule and the command to run instead. */
383
+ /** `todo` without a command, or a group without a subcommand it has; null otherwise (a28). */
384
+ function explainMissingSubcommand(argv) {
385
+ if (argv.length === 0) {
386
+ return { pointer: '<command>', rule: 'subcommand_missing', available_commands: TODO_COMMAND_NAMES,
387
+ next_action: 'Name a todo command; for the overview of every plan run `lattice todo status --json`'
388
+ + ' (every command: `lattice todo --help`).' };
389
+ }
390
+ const group = TODO_SUBCOMMANDS[argv[0]];
391
+ if (group === undefined || group.names.includes(argv[1])) return null;
392
+ const missing = typeof argv[1] !== 'string' || argv[1].startsWith('--');
393
+ const head = [argv[0], group.example];
394
+ const { flags } = parseFlagMap(argv.slice(missing ? 1 : 2));
395
+ return { pointer: missing ? '<subcommand>' : argv[1], rule: missing ? 'subcommand_missing' : 'subcommand_unknown',
396
+ available_subcommands: group.names,
397
+ next_action: `Name one of ${group.names.join(', ')} after \`lattice todo ${argv[0]}\`, e.g.`
398
+ + ` \`${repairedCommand(head, TODO_FLAG_SPECS[head.join(' ')], flags)}\`.` };
399
+ }
400
+
401
+ /** A todo argument refusal names the flag, the rule and the command to run instead. */
352
402
  function explainArgumentRefusal(argv) {
353
- if (argv[0] === 'note' && argv[1] === 'list') return {};
354
- const head = ['dependency', 'phase'].includes(argv[0]) ? argv.slice(0, 2) : argv.slice(0, 1);
403
+ const missingSubcommand = explainMissingSubcommand(argv);
404
+ if (missingSubcommand !== null) return missingSubcommand;
405
+ const head = GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
406
+ ? argv.slice(0, 2) : argv.slice(0, 1);
355
407
  const spec = TODO_FLAG_SPECS[head.join(' ')];
356
408
  if (spec === undefined) return {};
357
409
  const { flags } = parseFlagMap(argv.slice(head.length));
358
410
  const flagFailure = explainFlagCommand(argv, head, spec);
359
411
  if (flagFailure?.rule === 'flag_missing') {
360
- return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${FLAG_PLACEHOLDER[flagFailure.pointer.slice(2)] ?? '<value>'}: \`${repairedCommand(head, spec, flags)}\`.` };
412
+ const missing = flagFailure.pointer.slice(2);
413
+ const lists = { task: ` (task ids: \`lattice plan show ${flags.plan ?? '<plan>'} --json\`)` }[missing] ?? '';
414
+ return { ...flagFailure, next_action: `Add ${flagFailure.pointer} ${placeholder(missing)}${lists}: \`${repairedCommand(head, spec, flags)}\`.` };
415
+ }
416
+ if (flagFailure?.rule === 'flag_unknown') {
417
+ // a28: a flag the command does not take is named, with the flags it does take and a command that works.
418
+ const takes = spec.known.map((name) => `--${name}`).join(', ') || 'no flags';
419
+ const { [flagFailure.pointer.slice(2)]: _dropped, ...kept } = flags;
420
+ const onePlan = flagFailure.pointer === '--plan' && typeof flags.plan === 'string'
421
+ ? `; for one plan run \`lattice plan show ${flags.plan} --json\`` : '';
422
+ return { ...flagFailure, next_action: `${flagFailure.pointer} does not apply to \`lattice todo ${head.join(' ')}\``
423
+ + ` (it takes ${takes}): \`${repairedCommand(head, spec, kept)}\`${onePlan}.` };
361
424
  }
362
425
  if (flagFailure !== null) return flagFailure;
363
426
  for (const name of IDENTIFIER_FLAGS.filter((key) => spec.known.includes(key))) {
@@ -379,8 +442,29 @@ function explainArgumentRefusal(argv) {
379
442
  next_action: `Pass either --message or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
380
443
  }
381
444
  }
382
- if (spec.known.includes('input') && flags.input !== undefined && !isAuthoringPathToken(flags.input)) {
383
- return { pointer: '--input', rule: 'path_token_invalid' };
445
+ if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
446
+ const given = ['evidence', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
447
+ if (given.length === 0) {
448
+ return { pointer: '--evidence', rule: 'flag_missing',
449
+ next_action: `Add --evidence <file> (or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
450
+ }
451
+ if (given.length === 2) {
452
+ return { pointer: '--input', rule: 'flags_exclusive',
453
+ next_action: `Pass either --evidence or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
454
+ }
455
+ if (argv[1] === 'reject' && given[0] === 'evidence' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
456
+ return { pointer: '--reason', rule: 'flag_missing',
457
+ next_action: `A reject with --evidence needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
458
+ }
459
+ if (given[0] === 'input' && flags.reason !== undefined) {
460
+ return { pointer: '--reason', rule: 'flag_unknown',
461
+ next_action: `With --input the reason is inside the decision file; drop --reason: \`${repairedCommand(head, spec, { ...flags, reason: undefined })}\`.` };
462
+ }
463
+ }
464
+ for (const name of ['input', 'evidence']) {
465
+ if (spec.known.includes(name) && flags[name] !== undefined && !isAuthoringPathToken(flags[name])) {
466
+ return { pointer: `--${name}`, rule: 'path_token_invalid' };
467
+ }
384
468
  }
385
469
  for (const name of ['override-reason', 'reason']) {
386
470
  if (spec.known.includes(name) && flags[name] !== undefined
@@ -1078,7 +1162,8 @@ async function startStructureContext({ repoRoot, store, planKey, taskId }) {
1078
1162
 
1079
1163
  function designMemoProjection(task) {
1080
1164
  if (typeof task.design_memo === 'string') {
1081
- return { status: 'available', markdown: task.design_memo, prompt: TODO_DESIGN_MEMO_PROMPT };
1165
+ // 書かれたmemo(NO_PLANを含む)には促しを繰り返さない(a27)。促しは欠けたmemoにだけ要る。
1166
+ return { status: 'available', markdown: task.design_memo, prompt: null };
1082
1167
  }
1083
1168
  return { status: 'missing_legacy', markdown: null, prompt: TODO_DESIGN_MEMO_PROMPT };
1084
1169
  }
@@ -1517,16 +1602,9 @@ async function dependencyConnect(options) {
1517
1602
  || !tasks.some(({ task_id: id }) => id === toTaskId) || fromTaskId === toTaskId) {
1518
1603
  return dependencyConnectLedger(options);
1519
1604
  }
1520
- const from = dependencyRef(store, fromPlanKey, fromTaskId);
1521
- const to = dependencyRef(store, toPlanKey, toTaskId);
1522
- if (samePlanEdge(member, fromTaskId, toTaskId)) {
1523
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'dependency_already_in_plan', undefined, { from, to });
1524
- }
1525
- // 以前の同一plan接続で台帳に生きている辺を、本体へ二重に足さない(台帳経路と同じ拒否)。
1526
- if (projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1527
- dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1528
- && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId))) {
1529
- throw new TodoStoreError('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate', undefined, { from, to });
1605
+ // a28: an edge already in the plan body or the ledger is the requested state; nothing is added twice.
1606
+ if (samePlanEdge(member, fromTaskId, toTaskId) || liveLedgerEdge(store, options)) {
1607
+ return dependencyUnchanged(store, options);
1530
1608
  }
1531
1609
  if (member.tasks.find(({ task_id: id }) => id === toTaskId)?.status === 'done') {
1532
1610
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_target_terminal');
@@ -1538,6 +1616,28 @@ async function dependencyConnect(options) {
1538
1616
  repoRoot, env, store, member, operation: 'connect', fromTaskId, toTaskId, reason });
1539
1617
  }
1540
1618
 
1619
+ /** A live ledger edge with these endpoints (cross-plan, or an earlier same-plan connect). */
1620
+ function liveLedgerEdge(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1621
+ return projectTodoCrossPlanDependencies(store.members).some((dependency) => (
1622
+ dependency.from.plan_key === fromPlanKey && dependency.from.task_id === fromTaskId
1623
+ && dependency.to.plan_key === toPlanKey && dependency.to.task_id === toTaskId));
1624
+ }
1625
+
1626
+ /** a28: connect of an existing edge succeeds unchanged, like a repeated done/block/retire (a12). */
1627
+ function dependencyUnchanged(store, { fromPlanKey, fromTaskId, toPlanKey, toTaskId }) {
1628
+ const from = { project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId };
1629
+ const to = { project_id: store.project_id, plan_key: toPlanKey, task_id: toTaskId };
1630
+ const result = {
1631
+ schema: 'lattice.todo_dependency_unchanged_result.v1', project_id: store.project_id,
1632
+ operation: 'connect', from, to, unchanged: true,
1633
+ next_action: `${fromPlanKey}/${fromTaskId} -> ${toPlanKey}/${toTaskId} already exists; nothing was recorded`
1634
+ + ` (see \`lattice plan show ${toPlanKey} --json\`).`,
1635
+ result_digest: '',
1636
+ };
1637
+ result.result_digest = todoSelfDigest(result, 'result_digest');
1638
+ return result;
1639
+ }
1640
+
1541
1641
  /** 台帳(cross_plan_dependency event)への接続。plan跨ぎの本線。 */
1542
1642
  async function dependencyConnectLedger({
1543
1643
  repoRoot, env, fromPlanKey, fromTaskId, toPlanKey, toTaskId, reason,
@@ -1554,6 +1654,7 @@ async function dependencyConnectLedger({
1554
1654
  };
1555
1655
  const source = dependencyMember(fromPlanKey);
1556
1656
  const target = dependencyMember(toPlanKey);
1657
+ const endpoints = { fromPlanKey, fromTaskId, toPlanKey, toTaskId };
1557
1658
  if (!source.plan.tasks.some(({ task_id: taskId }) => taskId === fromTaskId)) {
1558
1659
  throw new TodoStoreError('DEPENDENCY_INVALID', 'dependency_task_not_found', undefined, {
1559
1660
  plan_key: fromPlanKey, task_id: fromTaskId,
@@ -1564,6 +1665,7 @@ async function dependencyConnectLedger({
1564
1665
  plan_key: toPlanKey, task_id: toTaskId,
1565
1666
  });
1566
1667
  }
1668
+ if (liveLedgerEdge(store, endpoints)) return dependencyUnchanged(store, endpoints);
1567
1669
  const from = {
1568
1670
  project_id: store.project_id, plan_key: fromPlanKey, task_id: fromTaskId,
1569
1671
  expected_topology_digest: source.plan.topology_digest,
@@ -4265,9 +4367,9 @@ async function verify({ repoRoot, requestedPlanKey }) {
4265
4367
  meaning: 'source_inventory_verification_state',
4266
4368
  lifecycle_blocked: false,
4267
4369
  dashboard_visibility_blocked: false,
4268
- // registered_unreconciledは何もしなくてよい状態(a22)。次の軽い改訂がreconciledにする。
4370
+ // どちらの状態も何もしなくてよい(a22)。値はnoneに揃える(a27)。次の軽い改訂がreconciledにする。
4269
4371
  schema_command: null,
4270
- next_action: reconciled ? null : 'none',
4372
+ next_action: 'none',
4271
4373
  },
4272
4374
  };
4273
4375
  });
@@ -4431,10 +4533,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4431
4533
  return { schema: 'lattice.todo_dashboard_ensure_result.v1',
4432
4534
  ensured: ensured !== null, activity: ensured };
4433
4535
  };
4434
- } else if (argv.length === 6 && argv[0] === 'show'
4435
- && argv[1] === '--plan' && isTodoIdentifier(argv[2])
4436
- && argv[3] === '--task' && isTodoIdentifier(argv[4]) && argv[5] === '--json') {
4437
- action = (repoRoot) => todoDetail({ repoRoot, planKey: argv[2], taskId: argv[4] });
4536
+ } else if (argv[0] === 'show' && readFlags(argv, ['show']) !== null) {
4537
+ const flags = readFlags(argv, ['show']);
4538
+ action = (repoRoot) => todoDetail({ repoRoot, planKey: flags.plan, taskId: flags.task });
4438
4539
  } else if ((argv.length === 1 && argv[0] === 'bindings')
4439
4540
  || (argv.length === 2 && argv[0] === 'bindings' && argv[1] === '--json')) {
4440
4541
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: null });
@@ -4458,13 +4559,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4458
4559
  supersedes: flags.supersedes ?? null,
4459
4560
  });
4460
4561
  }
4461
- } else if (argv.length === 5 && argv[0] === 'note' && argv[1] === 'list'
4462
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4463
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: null });
4464
- } else if (argv.length === 7 && argv[0] === 'note' && argv[1] === 'list'
4465
- && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4466
- && argv[4] === '--task' && isTodoIdentifier(argv[5]) && argv[6] === '--json') {
4467
- action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: argv[5] });
4562
+ } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
4563
+ const flags = readFlags(argv, ['note', 'list']);
4564
+ action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
4468
4565
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
4469
4566
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
4470
4567
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
@@ -4489,9 +4586,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4489
4586
  toPlanKey: flags['to-plan'], toTaskId: flags['to-task'], reason: flags.reason,
4490
4587
  });
4491
4588
  } else if (argv[0] === 'independence' && argv[1] === 'compile') {
4492
- const flags = matchFlagCommand(argv, ['independence', 'compile'], {
4493
- known: ['plan', 'input'], required: ['plan', 'input'],
4494
- });
4589
+ const flags = matchFlagCommand(argv, ['independence', 'compile'], TODO_FLAG_SPECS['independence compile']);
4495
4590
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4496
4591
  action = (repoRoot) => independenceCompile({
4497
4592
  repoRoot, planKey: flags.plan, inputRef: flags.input,
@@ -4535,11 +4630,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4535
4630
  } else if (argv.length === 5 && argv[0] === 'structure' && argv[1] === 'finalize'
4536
4631
  && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
4537
4632
  action = (repoRoot) => structureFinalize({ repoRoot, env, planKey: argv[3] });
4538
- } else if (argv.length === 2 && argv[0] === 'structure' && argv[1] === '--json') {
4539
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: null });
4540
- } else if (argv.length === 4 && argv[0] === 'structure'
4541
- && argv[1] === '--plan' && isTodoIdentifier(argv[2]) && argv[3] === '--json') {
4542
- action = (repoRoot) => structure({ repoRoot, requestedPlanKey: argv[2] });
4633
+ } else if (argv[0] === 'structure' && readFlags(argv, ['structure']) !== null) {
4634
+ const flags = readFlags(argv, ['structure']);
4635
+ action = (repoRoot) => structure({ repoRoot, requestedPlanKey: flags.plan ?? null });
4543
4636
  } else if ((argv.length === 1 && argv[0] === 'independence')
4544
4637
  || (argv.length === 2 && argv[0] === 'independence' && argv[1] === '--json')) {
4545
4638
  action = (repoRoot) => independence({ repoRoot, requestedPlanKey: null });
@@ -4672,13 +4765,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4672
4765
  outcome, evidenceRef: flags.evidence, reason: flags.reason ?? null,
4673
4766
  });
4674
4767
  }
4675
- } else if ((argv.length === 8 || argv.length === 10) && argv[0] === 'phase'
4676
- && argv[1] === 'reopen' && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4677
- && argv[4] === '--phase' && isTodoIdentifier(argv[5])
4678
- && argv[6] === '--reason' && argv[7].length > 0
4679
- && (argv.length === 8 || (argv[8] === '--override-reason' && argv[9].length > 0))) {
4680
- action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: argv[3], phaseId: argv[5],
4681
- kind: 'phase_reopen', payload: { reason: argv[7], override_reason: argv[9] ?? null } });
4768
+ } else if (argv[0] === 'phase' && argv[1] === 'reopen' && phaseReopenFlags(argv) !== null) {
4769
+ const flags = phaseReopenFlags(argv);
4770
+ action = (repoRoot) => phaseMutation({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
4771
+ kind: 'phase_reopen', payload: { reason: flags.reason, override_reason: flags['override-reason'] ?? null } });
4682
4772
  } else if (argv[0] === 'phase' && argv[1] === 'close-unaudited'
4683
4773
  && phaseReasonFlags(argv) !== null) {
4684
4774
  const flags = phaseReasonFlags(argv);
@@ -4755,9 +4845,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4755
4845
  }) });
4756
4846
  }
4757
4847
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
4758
- const flags = matchFlagCommand(argv, ['evidence', 'promote'], {
4759
- known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'],
4760
- });
4848
+ const flags = matchFlagCommand(argv, ['evidence', 'promote'], TODO_FLAG_SPECS['evidence promote']);
4761
4849
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4762
4850
  && isAuthoringPathToken(flags.evidence)) {
4763
4851
  action = (repoRoot) => mutate({
@@ -118,9 +118,13 @@ export function createTodoReadiness(store) {
118
118
  return node?.schema !== 'lattice.todo_plan.v4' || node.phase_status === 'active';
119
119
  }
120
120
 
121
- function startedSuccessor(key) {
122
- return [...(outgoing.get(key) ?? [])].some((successor) => nodes.get(successor)?.status !== 'pending');
121
+ /** a28: the successors that already left pending, sorted, so a refusal can name them. */
122
+ function startedSuccessors(key) {
123
+ return [...(outgoing.get(key) ?? [])].map((successor) => nodes.get(successor))
124
+ .filter((node) => node !== undefined && node.status !== 'pending')
125
+ .map(({ plan_key, task_id, status }) => ({ plan_key, task_id, status })).sort(byRef);
123
126
  }
127
+ const startedSuccessor = (key) => startedSuccessors(key).length > 0;
124
128
 
125
129
  return {
126
130
  key: taskKey,
@@ -131,6 +135,7 @@ export function createTodoReadiness(store) {
131
135
  isReady: (key) => nodes.get(key)?.status === 'pending'
132
136
  && ownPhaseReady(key) && prerequisites(key).dependenciesDone,
133
137
  startedSuccessor,
138
+ startedSuccessors,
134
139
  phaseHasStartedSuccessor: (member, phaseId) => member.plan.schema === 'lattice.todo_plan.v4'
135
140
  ? member.plan.tasks.filter(({ phase_id }) => phase_id === phaseId)
136
141
  .some((task) => startedSuccessor(taskKey({ ...member.plan, ...task })))
@@ -173,8 +178,13 @@ export function validateProspectiveEvent({ store, member, event }) {
173
178
  return refused('invalid_done_transition', prerequisites.cause, prerequisites.blocking);
174
179
  }
175
180
  if (event.kind === 'reopen' && event.payload.override_reason === null && readiness.startedSuccessor(key)) {
181
+ const started = readiness.startedSuccessors(key);
182
+ const on = `--plan ${member.plan.plan_key} --task ${event.task_id}`;
176
183
  return refused('reopen_has_started_successor', 'task_state', {
177
- next_action: `lattice todo split --plan ${member.plan.plan_key} --input <file>`,
184
+ started_successors: started,
185
+ next_action: `${started.map((task) => `${task.plan_key}/${task.task_id} (${task.status})`).join(', ')}`
186
+ + ` already left pending after ${member.plan.plan_key}/${event.task_id}; to reopen it anyway run`
187
+ + ` \`lattice todo reopen ${on} --reason <text> --override-reason <text>\`.`,
178
188
  });
179
189
  }
180
190
  if (event.kind === 'phase_reopen' && event.payload.override_reason === null