@quolu/lattice 0.84.2 → 0.85.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.
package/README.ja.md CHANGED
@@ -249,7 +249,8 @@ lattice plan create --template --json # 作者が書くkeyだけの最
249
249
  ```
250
250
 
251
251
  ```bash
252
- lattice plan create --input .lattice/plan-create.json
252
+ lattice plan create --template --json > plan.json # 書き換えてから作成する。project_id・plan_versionは機械が決める
253
+ lattice plan create --input plan.json
253
254
  ```
254
255
 
255
256
  `invalid`をMarkdown fallbackへ丸めず、`next_action`に従ってstoreを診断してください。
package/bin/lattice.mjs CHANGED
@@ -7,7 +7,7 @@ import packageJson from '../package.json' with { type: 'json' };
7
7
 
8
8
  installPipeCloseGuard();
9
9
 
10
- const args = process.argv.slice(2);
10
+ const args = withImpliedJson(process.argv.slice(2));
11
11
  // 作業ディレクトリを読まないsurface。cwdが消えた席(閉じたworktree)からでも動かす。
12
12
  const CWD_FREE_COMMANDS = new Set(['runtime-errors', 'bridge', 'hooks', 'setup', 'factory-diagnostics']);
13
13
  // 内部故障の観測(下のobserveInternalFailure)が終わるのを、exit前に待つための置き場。
@@ -77,7 +77,7 @@ if (help !== null) {
77
77
  && args[2] === '--template' && args[3] === '--json') {
78
78
  const { projectCliFailure, runPlanCreateTemplate } = await import('../src/project-cli.mjs');
79
79
  try {
80
- process.exitCode = await runPlanCreateTemplate({ stdout: process.stdout });
80
+ process.exitCode = await runPlanCreateTemplate({ stdout: process.stdout, cwd: process.cwd() });
81
81
  } catch (error) {
82
82
  process.exitCode = projectCliFailure(process.stderr, error);
83
83
  }
@@ -97,17 +97,6 @@ if (help !== null) {
97
97
  } catch (error) {
98
98
  process.exitCode = projectCliFailure(process.stderr, error);
99
99
  }
100
- } else if (args.length === 7 && args[0] === 'plan' && args[1] === 'scope-review'
101
- && args[2] === '--plan-input' && args[4] === '--review' && args[6] === '--json') {
102
- const { runPlanScopeReview } = await import('../src/plan-scope-review.mjs');
103
- const { projectCliFailure } = await import('../src/project-cli.mjs');
104
- try {
105
- process.exitCode = await runPlanScopeReview({
106
- cwd: process.cwd(), planInputRef: args[3], reviewRef: args[5], stdout: process.stdout,
107
- });
108
- } catch (error) {
109
- process.exitCode = projectCliFailure(process.stderr, error);
110
- }
111
100
  } else if (args.length === 4 && args[0] === 'plan' && args[1] === 'scope-review'
112
101
  && args[2] === '--schema' && args[3] === '--json') {
113
102
  const { runPlanScopeReviewSchema } = await import('../src/plan-scope-review.mjs');
@@ -117,6 +106,25 @@ if (help !== null) {
117
106
  } catch (error) {
118
107
  process.exitCode = projectCliFailure(process.stderr, error);
119
108
  }
109
+ } else if (args[0] === 'plan' && args[1] === 'scope-review') {
110
+ // 引数違反も欄と直し方をtypedに返す(a22)。素の`plan scope-review`をusage文1行で落とさない。
111
+ const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
112
+ const spec = { known: ['plan-input', 'review', 'json'], required: ['plan-input', 'review'], booleans: ['json'] };
113
+ const flags = matchFlagCommand(args, ['plan', 'scope-review'], spec);
114
+ if (flags === null || flags.json !== true) {
115
+ const { planArgumentFailure } = await import('../src/project-cli.mjs');
116
+ process.exitCode = planArgumentFailure(process.stderr, args, spec);
117
+ } else {
118
+ const { runPlanScopeReview } = await import('../src/plan-scope-review.mjs');
119
+ const { projectCliFailure } = await import('../src/project-cli.mjs');
120
+ try {
121
+ process.exitCode = await runPlanScopeReview({
122
+ cwd: process.cwd(), planInputRef: flags['plan-input'], reviewRef: flags.review, stdout: process.stdout,
123
+ });
124
+ } catch (error) {
125
+ process.exitCode = projectCliFailure(process.stderr, error);
126
+ }
127
+ }
120
128
  } else if (args.length === 4 && args[0] === 'plan' && args[1] === 'revise'
121
129
  && args[2] === '--schema' && args[3] === '--json') {
122
130
  const { planReviseSchema } = await import('../src/plan-revise.mjs');
@@ -276,6 +284,22 @@ function observeInternalFailure(error, commandKind) {
276
284
  }).catch(() => {});
277
285
  }
278
286
 
287
+ // These commands only ever print JSON, so a missing --json is implied (a20, a24). Plan writes are
288
+ // (revise, backchain) implied only once --input carries a value, so a missing --input is still named as such.
289
+ function withImpliedJson(argv) {
290
+ if (argv.includes('--json') || argv.includes('--help') || argv.includes('-h')) return argv;
291
+ const [command, sub] = argv;
292
+ const bare = !argv.some((word) => word.startsWith('-'));
293
+ const input = argv.indexOf('--input');
294
+ const implied = (bare && argv.length === 1 && (command === 'status' || command === 'session-context'))
295
+ || (bare && argv.length === 3 && command === 'plan' && sub === 'show')
296
+ || (bare && command === 'sensor' && (sub === 'init' || sub === 'sync') && argv.length <= 3)
297
+ || (command === 'sensor' && sub === 'diff')
298
+ || (command === 'plan' && (sub === 'revise' || sub === 'backchain')
299
+ && input > 1 && typeof argv[input + 1] === 'string' && !argv[input + 1].startsWith('-'));
300
+ return implied ? [...argv, '--json'] : argv;
301
+ }
302
+
279
303
  function workingDirectory() {
280
304
  try {
281
305
  return process.cwd();
@@ -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 requires a design memo. After the complete plan is written, run `lattice plan scope-review` 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. あなたがこの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.",
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,14 +2,12 @@
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 requires a design memo. After the complete plan is written, run `lattice plan scope-review` 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), 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. あなたがこの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.",
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,
9
9
  "required": [
10
- "project_id",
11
10
  "plan_key",
12
- "plan_version",
13
11
  "tasks",
14
12
  "phases"
15
13
  ],
@@ -22,7 +22,7 @@
22
22
  "$ref": "lattice.plan_create_input.v5.schema.json"
23
23
  }
24
24
  ],
25
- "description": "同じproject_idとplan_keyのcreate-v4またはv5入力。actor・recorded_at・input_digest・空の設計メモは機械が補い、集合と配列の並びは正準化する。v5は終了条件done_conditionを持つ(plan v8を作る)。v4でも先行planがv8なら、書かない終了条件は先行planの値を引き継ぐ。plan_versionは入力形を保つために記載し、後継versionは機械算出値に置き換える。新taskはpending。消すtaskへの参照も明示的に取り除く。"
25
+ "description": "同じplan_keyのcreate-v4またはv5入力。project_idとplan_versionは書かなければ現行planの値で機械が補う(project_idを書くなら現行planと同じ値)。actor・recorded_at・input_digest・空の設計メモは機械が補い、集合と配列の並びは正準化する。v5は終了条件done_conditionを持つ(plan v8を作る)。v4でも先行planがv8なら、書かない終了条件は先行planの値を引き継ぐ。plan_versionは入力形を保つために記載し、後継versionは機械算出値に置き換える。新taskはpending。消すtaskへの参照も明示的に取り除く。"
26
26
  },
27
27
  "continuity": {
28
28
  "type": "array",
@@ -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.todo_extraction.v3.schema.json",
4
4
  "title": "lattice.todo_extraction.v3",
5
- "description": "AI-authored ToDo migration artifact. Every task carries a non-blank Markdown design_memo. After the complete plan is written, run `lattice plan scope-review` and confirm that every registered task preserves an owner-supplied work specification without adding a product purpose. If no plan exists, write NO_PLAN explicitly.",
5
+ "description": "AI-authored ToDo migration artifact. Every task carries a non-blank Markdown design_memo. 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 registered task preserves an owner-supplied work specification without adding a product purpose. If no plan exists, write NO_PLAN explicitly.",
6
6
  "$comment": "あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください。Runtime validation also enforces UTF-8 byte bounds, exact keys, strict sort order, referential integrity, disposition consistency, and the canonical self-digest.",
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.todo_extraction.v4.schema.json",
4
4
  "title": "lattice.todo_extraction.v4",
5
- "description": "AI-authored ToDo migration artifact. Every task carries a non-blank Markdown design_memo. After the complete plan is written, run `lattice plan scope-review` and confirm that every registered task preserves an owner-supplied work specification without adding a product purpose. If no plan exists, write NO_PLAN explicitly. Runtime validation accepts at most one explicit, reasoned cross-plan dependency; an empty tasks array is reserved for that one dependency between existing tasks, with the top-level plan identity naming the source plan and both endpoint topology digests.",
5
+ "description": "AI-authored ToDo migration artifact. Every task carries a non-blank Markdown design_memo. 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 registered task preserves an owner-supplied work specification without adding a product purpose. If no plan exists, write NO_PLAN explicitly. Runtime validation accepts at most one explicit, reasoned cross-plan dependency; an empty tasks array is reserved for that one dependency between existing tasks, with the top-level plan identity naming the source plan and both endpoint topology digests.",
6
6
  "$comment": "あなたがこのToDoに対して、何も考えていないならば、設計メモに `NO_PLAN` と書いてください。Runtime validation also enforces UTF-8 byte bounds, exact keys, strict sort order, referential integrity, disposition consistency, the cross-plan dependency limit, and the canonical self-digest.",
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.84.2",
3
+ "version": "0.85.1",
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
@@ -36,6 +36,9 @@ Commands:
36
36
  backchain --input <file> [--dry-run] --json
37
37
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
38
38
  show <plan_key> --json # task・依存辺・phase・状態をplan本体から1コマンドで投影する
39
+ scope-review --plan-input <file> --review <scope-review.json> --json
40
+ # 書き終えたplanの全taskが持ち主の作業仕様の内にあるかを、登録前に検査する
41
+ scope-review --schema --json # review入力のJSON Schemaを返す
39
42
  compile --request <request.json>
40
43
  compile --schema --json # lattice.run_request.v1 の JSON Schema を出す
41
44
  verify --request <request.json> --plan <plan.json>
@@ -101,7 +104,7 @@ Write commands:
101
104
  # ToDoへ作業継続に必要な方針・調査結果・注意をappend-onlyで追記する
102
105
  migrate --input <extraction.json> [--serialization-reviewed] [--json]
103
106
  migrate --input <extraction.json> --dry-run --json [--serialization-reviewed]
104
- # 既存storeへplanを追加する(plan createは空store初期化専用)。
107
+ # 既存storeへplanを追加する(extractionからの取り込み。新規planの作成はplan create)。
105
108
  # pretty-print・digest未計算・repo内絶対pathは機械が直す。空の設計メモは拒否する。
106
109
  # 結果へdispatch_shapeを載せる。--serialization-reviewedは互換のため受理するだけで門ではない
107
110
  start --plan <key> --task <id> [--parallel-frontier|--override-reason <text> [--serial-confirmed]]
@@ -122,6 +125,8 @@ Write commands:
122
125
  dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
123
126
  dependency disconnect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
124
127
  # 開発中に発見した依存を明示接続する。同一plan内の辺はplan本体を軽い改訂で書き換え(plan_versionが変わる)、plan跨ぎは台帳に積む。依存の自動推定は行わない
128
+ independence mode --plan <key> --set <witness|conversation> --reason <text>
129
+ # このplanの調整方式(witness検証で並列するか、会話で調整するか)を記録する
125
130
  independence compile --plan <key> --input <file> # witness setとsensorから並列可否を記録する
126
131
  independence witness migrate --plan <key> # revision後の宣言をtask migrationで写す
127
132
  independence witness scaffold --plan <key> --input <draft> # 下書きとfresh観測から宣言を書き出す
@@ -160,7 +165,8 @@ Write commands:
160
165
  # 自動実行はしない(明示コマンドのみ)。--exceptで指定したplanは対象から除外する
161
166
 
162
167
  Write commandsはLATTICE_TODO_ACTOR_HOST / SESSION / AGENTを受理する。
163
- 欠落はhost/session/agentのdefaultを使う。渡した値がidentifierとして不正なら拒否する。
168
+ 欠落、またはidentifierとして不正な値はunsetと同じに扱い(拒否しない)、host/session/agentのdefaultを使う。
169
+ agentのdefaultはLATTICE_SEAT_IDがあればその席id、なければOSのuser名。
164
170
 
165
171
  storeだけを書き換えるcommandの末尾へ--commit-storeを付けると、共有Git lockを取得し、
166
172
  生じた.lattice/todoの変更だけをcommitしてreceiptを返す。
@@ -172,8 +178,6 @@ ${TODO_INDEPENDENCE_WORKFLOW.join('\n')}
172
178
 
173
179
  判定していない工程は「競合が無い」ではなく「未検査」として扱われ、
174
180
  todo startのadvisoryとtodo independenceの投影が、その状況と次の一歩を返す。
175
- 記録があるのに対象工程が未宣言・失効なら todo start は拒否する。
176
- next_ready が witness に無い independence compile も拒否する。
177
181
  競合の同時起動は助言のまま。並列既定はstatusのdispatch_frontierとnext_actionが案内する。
178
182
  `,
179
183
  sensor: `Usage: lattice sensor <init|sync> [path] --json
@@ -275,7 +279,9 @@ const SUBCOMMAND_USAGE = Object.freeze({
275
279
  'todo note': 'todo note --plan <key> [--task <id>] (--message <text>|--input <file>) | list --plan <key> [--task <id>] --json',
276
280
  'todo note list': 'todo note list --plan <key> [--task <id>] --json',
277
281
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
278
- 'todo independence': 'todo independence [--plan <key>] [--json] | compile --plan <key> --input <file> | witness migrate --plan <key>',
282
+ 'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation> --reason <text>'
283
+ + ' | compile --plan <key> --input <file> | witness migrate --plan <key> | witness scaffold --plan <key> --input <draft>',
284
+ 'todo independence mode': 'todo independence mode --plan <key> --set <witness|conversation> --reason <text>',
279
285
  'todo structure': 'todo structure --schema --json | [--plan <key>] --json | input --plan <key> --input <file> [--dry-run --json] | compile --plan <key> --input <file> | realize --plan <key> --task <id> (--planned|--realized <actual-structure.json>) [--commit <HEAD|sha>]... | realize --plan <key> --task <id> --input <full-realization.json> | finalize --plan <key> --json',
280
286
  'todo seam-profile': 'todo seam-profile --plan <key> --file <path> [--json]',
281
287
  'todo seam-proposal': 'todo seam-proposal [--plan <key>] [--json] | compile --plan <key>',
@@ -306,7 +312,10 @@ const SUBCOMMAND_USAGE = Object.freeze({
306
312
  'todo reopen': 'todo reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]',
307
313
  'todo evidence': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
308
314
  'todo evidence promote': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
309
- 'todo dependency': 'todo dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
315
+ 'todo dependency': [
316
+ 'todo dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
317
+ 'todo dependency disconnect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
318
+ ].join('\n lattice '),
310
319
  'todo dependency connect': 'todo dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
311
320
  'todo dependency disconnect': 'todo dependency disconnect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
312
321
  'todo split': 'todo split --plan <key> --input <file>',
@@ -18,10 +18,46 @@ const showTask = (detail, ctx) => `lattice todo show --plan ${planOf(detail, ctx
18
18
  const startTask = (detail, ctx) => `lattice todo start --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
19
19
  // a12: name the blocking task (seat contract), falling back to the refused task's own detail.
20
20
  const blocker = (detail) => (Array.isArray(detail.blocking_tasks) ? detail.blocking_tasks.find(record) : undefined);
21
+ // a18: the step that moves the blocker on depends on its status (a pending one is started first).
21
22
  const unfinishedFirst = (detail, ctx) => {
22
23
  const first = blocker(detail);
23
24
  if (first === undefined) return `Record done on its unfinished predecessors first (see \`${showTask(detail, ctx)}\`)`;
24
- return `Record done on ${first.plan_key}/${first.task_id} (${first.status}) first (see \`lattice todo show --plan ${first.plan_key} --task ${first.task_id} --json\`)`;
25
+ const name = `${first.plan_key}/${first.task_id} (${first.status})`;
26
+ const on = `--plan ${first.plan_key} --task ${first.task_id}`;
27
+ return ({
28
+ pending: `Start ${name} first with \`lattice todo start ${on}\`, then record done on it`,
29
+ blocked: `Unblock ${name} with \`lattice todo unblock ${on}\`, then record done on it`,
30
+ })[first.status] ?? `Record done on ${name} first with \`lattice todo done ${on} --message <text>\` (see \`lattice todo show ${on} --json\`)`;
31
+ };
32
+ const startState = (detail, ctx) => {
33
+ const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
34
+ return ({
35
+ blocked: `It is blocked: run \`lattice todo unblock ${on}\`; that resumes it (no start needed).`,
36
+ done: `It is done: to work on it again run \`lattice todo reopen ${on} --reason <text>\`.`,
37
+ 'in-progress': `It is already in-progress under another seat; see \`${showTask(detail, ctx)}\`.`,
38
+ retired: `It is retired, which is permanent; see \`${showTask(detail, ctx)}\`.`,
39
+ })[detail.status] ?? `Only a pending task can start; check its status with \`${showTask(detail, ctx)}\`.`;
40
+ };
41
+ const cyclePath = (detail) => (Array.isArray(detail.cycle)
42
+ ? detail.cycle.filter(record).map((node) => `${node.plan_key}/${node.task_id ?? `phase:${node.phase_id}`}`).join(' -> ')
43
+ : null);
44
+ const edgeName = (detail) => (record(detail.from) && record(detail.to)
45
+ ? `${detail.from.plan_key}/${detail.from.task_id} -> ${detail.to.plan_key}/${detail.to.task_id}` : 'this dependency');
46
+ const dependencyCycle = {
47
+ repair: (detail) => {
48
+ const path = cyclePath(detail);
49
+ return `${edgeName(detail)} would close a cycle${path === null ? '' : ` (${path})`}: leave it out, or disconnect one edge of that path with \`lattice todo dependency disconnect\`.`;
50
+ },
51
+ };
52
+ // a23: dependency refusals name the edge or the task and a command that lists valid ones.
53
+ const depFlag = (ctx, name) => ctx.flags?.[name] ?? `<${name}>`;
54
+ const depRef = (detail) => (record(detail.ref) ? detail.ref : detail);
55
+ const missingSide = (ref, ctx) => (ctx.flags?.['to-plan'] === ref.plan_key
56
+ && (ref.task_id === undefined || ctx.flags?.['to-task'] === ref.task_id) ? 'to' : 'from');
57
+ const dependencyExists = {
58
+ pointer: '--to-task',
59
+ repair: (detail) => `${edgeName(detail)} already exists, so there is nothing to add;`
60
+ + ` see \`lattice plan show ${record(detail.to) ? detail.to.plan_key : '<plan>'} --json\`.`,
25
61
  };
26
62
 
27
63
  /** The flag that carried the unreadable input: the one whose value is the refused path. */
@@ -120,7 +156,7 @@ const REGISTRY = {
120
156
  repair: (detail, ctx) => ({
121
157
  predecessor_unfinished: `${unfinishedFirst(detail, ctx)}, or start with --override-reason <text>.`,
122
158
  acceptance_edge: phaseAcceptFirst(detail, ctx),
123
- task_state: `Only a pending task can start; check its status with \`${showTask(detail, ctx)}\`.`,
159
+ task_state: startState(detail, ctx),
124
160
  phase_state: 'Its phase is not active; check the phase status with `lattice todo status --json`.',
125
161
  })[detail.cause] ?? `Check the task state with \`${showTask(detail, ctx)}\`, then rerun.`,
126
162
  },
@@ -171,7 +207,25 @@ const REGISTRY = {
171
207
  },
172
208
  merged_cycle: {
173
209
  pointer: '/hard_dependencies',
174
- repair: () => 'Remove one dependency (including cross-plan ones) that closes the cycle, then rerun.',
210
+ repair: (detail) => `Remove one dependency (including cross-plan ones) that closes the cycle${cyclePath(detail) === null ? '' : ` ${cyclePath(detail)}`}, then rerun.`,
211
+ },
212
+ dependency_cycle: dependencyCycle,
213
+ cross_plan_dependency_cycle: dependencyCycle,
214
+ dependency_already_in_plan: dependencyExists,
215
+ cross_plan_dependency_duplicate: dependencyExists,
216
+ dependency_self_reference: {
217
+ pointer: '--to-task',
218
+ repair: (detail, ctx) => `--from-task and --to-task name the same task ${depFlag(ctx, 'to-plan')}/${depFlag(ctx, 'to-task')}; a task cannot depend on itself:`
219
+ + ` set --from-task to the task it waits on (see \`lattice plan show ${depFlag(ctx, 'to-plan')} --json\`).`,
220
+ },
221
+ dependency_task_not_found: {
222
+ pointer: (detail, ctx) => `--${missingSide(depRef(detail), ctx)}-task`,
223
+ repair: (detail) => `No task ${q(depRef(detail).task_id ?? '')} in plan ${depRef(detail).plan_key}:`
224
+ + ` run \`lattice plan show ${depRef(detail).plan_key} --json\` to list its task ids.`,
225
+ },
226
+ dependency_plan_not_found: {
227
+ pointer: (detail, ctx) => `--${missingSide(depRef(detail), ctx)}-plan`,
228
+ repair: (detail) => `${q(depRef(detail).plan_key ?? '')} is not an active plan: run \`lattice todo status --json\` to list the active plan keys.`,
175
229
  },
176
230
  join_self_edge: {
177
231
  pointer: '/joins',
package/src/hooks-cli.mjs CHANGED
@@ -788,10 +788,15 @@ async function status(host, env, stdout, source, platform, testHooks) {
788
788
  writeJson(stdout, statusResult(host, target, null, 'unreadable', 0, false, 0));
789
789
  return 1;
790
790
  }
791
- if (platform === 'win32' || await hostDirectory(env, host) === null) {
791
+ if (platform === 'win32') {
792
792
  writeJson(stdout, statusResult(host, target, shell(argv), 'unreadable', 0, false, 0));
793
793
  return 1;
794
794
  }
795
+ // The AI is not installed in this HOME; install would refuse HOST_NOT_PRESENT, so name no next action.
796
+ if (await hostDirectory(env, host) === null) {
797
+ writeJson(stdout, { ...statusResult(host, target, shell(argv), 'host_absent', 0, false, 0), next_action: null });
798
+ return 1;
799
+ }
795
800
  let config;
796
801
  try { config = await readConfig(target); } catch {
797
802
  writeJson(stdout, statusResult(host, target, shell(argv), 'unreadable', 0, false, 0));
@@ -544,9 +544,26 @@ async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
544
544
  });
545
545
  }
546
546
 
547
+ /**
548
+ * 公開前のmemberから、作業中taskごとに最新startの記録者を集める(task_id → actor)。
549
+ * 改訂後のrebind startがこの記録者を保つので、別の席が改訂しても`turn.own`は始めた席に残る(a16)。
550
+ * shortcut: このmemberにstartが無いtask(revise-phaseで運ばれたもの)は今の席で結び直す。古い版の
551
+ * journalまで遡る必要が出たらStoreの保持版readerを使う。
552
+ */
553
+ export function carriedStartActors(member) {
554
+ const actors = new Map();
555
+ if (member === null || member === undefined) return actors;
556
+ const inProgress = new Set(member.tasks.filter(({ status }) => status === 'in-progress')
557
+ .map(({ task_id: taskId }) => taskId));
558
+ for (const event of member.journal.events) {
559
+ if (event.kind === 'start' && inProgress.has(event.task_id)) actors.set(event.task_id, event.actor);
560
+ }
561
+ return actors;
562
+ }
563
+
547
564
  export async function rebindCarriedWork({ repoRoot, planKey, env,
548
565
  reason = 'ゴール変更後のplan versionへ作業中ToDoを結び直す',
549
- failureCode = 'BACKCHAIN_REBIND_PENDING' }) {
566
+ failureCode = 'BACKCHAIN_REBIND_PENDING', carriedActors = new Map() }) {
550
567
  const store = await readTodoStore({ repoRoot });
551
568
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
552
569
  const rebound = [];
@@ -557,7 +574,7 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
557
574
  const { rebindStart } = await import('./todo-cli.mjs');
558
575
  try {
559
576
  await rebindStart({ repoRoot, env, planKey, taskId: state.task_id,
560
- reason });
577
+ reason, actor: carriedActors.get(state.task_id) ?? null });
561
578
  } catch (error) {
562
579
  throw new TodoStoreError(failureCode, 'carried_task_rebind_failed', undefined, {
563
580
  task_id: state.task_id, plan_version: member.plan.plan_version,
@@ -658,7 +675,8 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
658
675
  };
659
676
  }
660
677
  const reboundTaskIds = unchanged || revision !== null
661
- ? await rebindCarriedWork({ repoRoot, planKey: chain.plan_key, env }) : [];
678
+ ? await rebindCarriedWork({ repoRoot, planKey: chain.plan_key, env,
679
+ carriedActors: carriedStartActors(member) }) : [];
662
680
  const finalStore = await readTodoStore({ repoRoot });
663
681
  const finalMember = finalStore.members.find(({ plan }) => plan.plan_key === chain.plan_key);
664
682
  const result = {
@@ -6,7 +6,7 @@ import { gitSync } from './git-process.mjs';
6
6
  import { completeCreateInput, readAuthoringJsonFile, resolveTodoActor } from './todo-authoring-input.mjs';
7
7
  import { validatePlanCreateInput } from './project-cli.mjs';
8
8
  import {
9
- compileBackchainRevision, planSeed, readPlanBackchainBinding, rebindCarriedWork,
9
+ carriedStartActors, compileBackchainRevision, planSeed, readPlanBackchainBinding, rebindCarriedWork,
10
10
  } from './plan-backchain.mjs';
11
11
  import {
12
12
  applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
@@ -174,7 +174,10 @@ export function resolvePlanRevision({ member, input, env = process.env, now = ne
174
174
  fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
175
175
  }
176
176
  if (input.schema !== INPUT_SCHEMA) fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
177
- const desired = completeCreateInput(input.desired, { env, now });
177
+ // a17: 改訂は既存planの上で行うので、project_id・plan_versionは書かなければ現行planの値で埋まる。
178
+ const desired = completeCreateInput(input.desired, {
179
+ env, now, projectId: member?.plan.project_id, planVersion: member?.plan.plan_version,
180
+ });
178
181
  try { validatePlanCreateInput(desired); }
179
182
  catch (error) {
180
183
  if (typeof error?.detail?.pointer === 'string') {
@@ -200,7 +203,13 @@ export function resolvePlanRevision({ member, input, env = process.env, now = ne
200
203
  if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)) {
201
204
  fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
202
205
  }
203
- if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
206
+ if (desired.project_id !== member.plan.project_id) {
207
+ fail('plan_revise_identity_mismatch', '/desired/project_id', {
208
+ expected: member.plan.project_id, actual: desired.project_id,
209
+ next_action: `Omit /desired/project_id (the machine fills "${member.plan.project_id}") or set it to "${member.plan.project_id}".`,
210
+ });
211
+ }
212
+ if (desired.plan_key !== member.plan.plan_key) {
204
213
  fail('plan_revise_identity_mismatch', '/desired/plan_key');
205
214
  }
206
215
  const continuity = computeContinuity(member, input,
@@ -338,7 +347,7 @@ export async function applyPlanRevision({
338
347
  try {
339
348
  reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
340
349
  reason: '工程改訂後のplan versionへ作業中ToDoを結び直す',
341
- failureCode: 'PLAN_REBIND_PENDING' });
350
+ failureCode: 'PLAN_REBIND_PENDING', carriedActors: carriedStartActors(member) });
342
351
  } catch (error) {
343
352
  // 公開後に起きたStoreの失敗は、改訂が確定済みであることを必ず報告する(2026-11-07
344
353
  // 初回使用: rebind読込の素のbinding_staleが公開済み事実を隠した)
@@ -200,7 +200,7 @@ async function summarizeIndependence({ repoRoot, store, todo }) {
200
200
  .some(({ unknowns }) => unknowns.some(({ kind }) => kind === 'record_stale')),
201
201
  conflictWithActive: projected.frontier.conflicts_with_active[0]?.severability ?? null,
202
202
  conflictBetweenReady: projected.frontier.serialize_pairs[0]?.severability ?? null,
203
- coordinationMode: member.coordination?.mode ?? null,
203
+ coordinationMode: member.coordination?.mode ?? null, planKey,
204
204
  }),
205
205
  unreadable_reason: null,
206
206
  parallel_groups: projected.frontier.parallel_groups.map(({ task_ids: ids }) => [...ids]),
@@ -278,7 +278,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
278
278
  store: { ref: STORE_REF, absolute_path: storeAbsolute },
279
279
  active_plans: [], active_runs: [], can_create_plan: true,
280
280
  next_action: {
281
- command: 'lattice plan create --input .lattice/plan-create.json',
281
+ command: 'lattice plan create --template --json',
282
282
  input_schema: CURRENT_CREATE_INPUT_SCHEMA,
283
283
  schema_command: CURRENT_CREATE_SCHEMA_COMMAND,
284
284
  },
@@ -317,14 +317,15 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
317
317
  // ready frontierが在る間はADR 0063の並列開始コマンドが勝つ
318
318
  // ——ここを監査で上書きするとdispatchが再直列化する。監査待ちはtodo statusの
319
319
  // audit_pending欄に常在するので、順位を下げても消えない。
320
- // commandはverbatim実行可能で読み取り専用のものにする。`phase review`は
321
- // `--reason <text>`のplaceholderを含みjournalを書き換えるので置かない
322
- // (`todo phase status`の結果には既に両分岐のguidanceが載っている)。
320
+ // gate_ready(全taskが終わり監査も未着手)は軽い出口close-unauditedを1行で示す(a22)。
321
+ // 監査を始めた後(reviewing/rejected)は読み取り専用の`todo phase status`が両分岐を示す。
323
322
  : todo.structure_finalization_pending.length > 0
324
323
  ? { command: todo.structure_finalization_pending[0].next_commands[0],
325
324
  reason: 'structure_finalization_pending' }
326
325
  : todo.audit_pending.length > 0
327
- ? { command: `lattice todo phase status --plan ${todo.audit_pending[0].plan_key}`,
326
+ ? { command: todo.audit_pending[0].phase_status === 'gate_ready'
327
+ ? `lattice todo phase close-unaudited --plan ${todo.audit_pending[0].plan_key} --phase ${todo.audit_pending[0].phase_id} --reason <text>`
328
+ : `lattice todo phase status --plan ${todo.audit_pending[0].plan_key}`,
328
329
  reason: 'audit_pending' }
329
330
  : { command: 'lattice todo status', reason: 'no_ready_task' };
330
331
  const result = statusResult({
@@ -721,13 +722,34 @@ export function validatePlanCreateInput(input) {
721
722
  });
722
723
  }
723
724
 
725
+ /** a17: repo root名をtodo identifierへ寄せる。小文字化し、使えない文字は'-'へ、前後の記号は落とす。 */
726
+ function identifierFromRepoRoot(repoRoot, fallback) {
727
+ const name = path.basename(repoRoot).toLowerCase().replace(/[^0-9a-z._-]+/gu, '-')
728
+ .replace(/^[^0-9a-z]+|[^0-9a-z]+$/gu, '').slice(0, 128);
729
+ return isTodoIdentifier(name) ? name : fallback;
730
+ }
731
+
724
732
  export async function runPlanCreate({
725
733
  cwd, inputRef, stdout, inputValue = null, featureChain = null, env = process.env,
726
734
  }) {
727
735
  const repoRoot = resolveRepoRoot(cwd);
728
736
  if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
729
- const input = completeCreateInput(
730
- inputValue ?? await readCanonicalInput(repoRoot, inputRef), { env, now: new Date() });
737
+ const manifest = await lstat(path.join(repoRoot, MANIFEST_REF)).catch((error) => {
738
+ if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
739
+ return null;
740
+ });
741
+ // a17: project_idは機械が決める。storeがあればそのid、無ければrepo root名。
742
+ const projectId = manifest === null
743
+ ? identifierFromRepoRoot(repoRoot, 'project') : (await readTodoStore({ repoRoot })).project_id;
744
+ const given = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
745
+ if (manifest !== null && isPlainRecord(given) && given.project_id !== undefined
746
+ && given.project_id !== null && given.project_id !== projectId) {
747
+ throw new TodoStoreError('INPUT_INVALID', 'project_id_mismatch', undefined, {
748
+ pointer: '/project_id', expected: projectId, actual: given.project_id,
749
+ next_action: `Omit project_id (the machine fills "${projectId}") or set it to "${projectId}".`,
750
+ });
751
+ }
752
+ const input = completeCreateInput(given, { env, now: new Date(), projectId, planVersion: 'v1' });
731
753
  validatePlanCreateInput(input);
732
754
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
733
755
  const dispatchShape = computeTodoDispatchShapeForPlan({
@@ -754,10 +776,6 @@ export async function runPlanCreate({
754
776
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
755
777
  ...(featureChain === null ? {} : { featureChain }),
756
778
  };
757
- const manifest = await lstat(path.join(repoRoot, MANIFEST_REF)).catch((error) => {
758
- if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
759
- return null;
760
- });
761
779
  const store = manifest === null
762
780
  ? await initializeAuthoredTodoStore({ ...options,
763
781
  projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }] })
@@ -812,15 +830,14 @@ export async function runPlanCreateSchema({ stdout, version = 5 }) {
812
830
  }
813
831
 
814
832
  /**
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`がそのまま受理する。
833
+ * `plan create --template --json`(a11・a17)。作者が書くkeyだけの最小のv5入力を出す。
834
+ * 機械が決めるkey(project_id・plan_version・actor・recorded_at・input_digest・定数のkey・辺のproject_id/plan_key)は載せない。
835
+ * plan_keyだけは、git repo内ならrepo root名から導いた値、repo外なら'main'。
836
+ * 決定的で、storeを読まない。id・題名を書き換えれば`plan create`がそのまま受理する。
818
837
  */
819
838
  export const PLAN_CREATE_TEMPLATE = Object.freeze({
820
839
  schema: DONE_CONDITION_CREATE_INPUT_SCHEMA,
821
- project_id: 'my-project',
822
- plan_key: 'my-plan',
823
- plan_version: 'v1',
840
+ plan_key: 'main',
824
841
  phases: [
825
842
  { phase_id: 'p1', title: 'First phase' },
826
843
  { phase_id: 'p2', title: 'Second phase' },
@@ -834,8 +851,11 @@ export const PLAN_CREATE_TEMPLATE = Object.freeze({
834
851
  hard_dependencies: [{ from: { task_id: 't1' }, to: { task_id: 't3' } }],
835
852
  });
836
853
 
837
- export async function runPlanCreateTemplate({ stdout }) {
838
- stdout.write(`${JSON.stringify(PLAN_CREATE_TEMPLATE)}\n`);
854
+ export async function runPlanCreateTemplate({ stdout, cwd = process.cwd() }) {
855
+ const repoRoot = resolveRepoRoot(cwd);
856
+ const template = repoRoot === null ? PLAN_CREATE_TEMPLATE
857
+ : { ...PLAN_CREATE_TEMPLATE, plan_key: identifierFromRepoRoot(repoRoot, 'main') };
858
+ stdout.write(`${JSON.stringify(template)}\n`);
839
859
  return 0;
840
860
  }
841
861
 
@@ -869,15 +889,19 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
869
889
 
870
890
  // 依存の本数: このplanの中でそのtaskへ入ってくるhard_dependencies辺と、joinで
871
891
  // 合流するafter辺の合計。cross-plan参照は数えない(plan showは単一planの投影のため)。
892
+ // retiredの端点を持つ辺は数えない(a13: retireは辺を除く。a18)。
893
+ const retired = (ref) => ref.plan_key === planKey && stateByTaskId.get(ref.task_id)?.status === 'retired';
872
894
  const dependsOnCount = new Map(plan.tasks.map((task) => [task.task_id, 0]));
873
895
  for (const edge of plan.hard_dependencies) {
874
- if (edge.to.plan_key === planKey && dependsOnCount.has(edge.to.task_id)) {
896
+ if (edge.to.plan_key === planKey && dependsOnCount.has(edge.to.task_id)
897
+ && !retired(edge.from) && !retired(edge.to)) {
875
898
  dependsOnCount.set(edge.to.task_id, dependsOnCount.get(edge.to.task_id) + 1);
876
899
  }
877
900
  }
878
901
  for (const join of plan.joins) {
879
- if (join.before.plan_key === planKey && dependsOnCount.has(join.before.task_id)) {
880
- dependsOnCount.set(join.before.task_id, dependsOnCount.get(join.before.task_id) + join.after.length);
902
+ if (join.before.plan_key === planKey && dependsOnCount.has(join.before.task_id) && !retired(join.before)) {
903
+ dependsOnCount.set(join.before.task_id,
904
+ dependsOnCount.get(join.before.task_id) + join.after.filter((ref) => !retired(ref)).length);
881
905
  }
882
906
  }
883
907
 
@@ -347,7 +347,7 @@ async function pullPlanReadiness({ repoRoot, planKey }) {
347
347
  && witnessSet?.witness_set_digest === artifact.witness_set_digest;
348
348
  return pullIntakeReadinessGuidance({
349
349
  coordinationMode: member.coordination?.mode ?? null,
350
- ready,
350
+ ready, planKey,
351
351
  });
352
352
  }
353
353
 
@@ -396,7 +396,7 @@ function pathTouches(boundary, changed) {
396
396
  async function boundaryVerdict({ repoRoot, store, member, meta, taskId, intakeBase }) {
397
397
  const pullRequired = pullIntakeReadinessGuidance({
398
398
  coordinationMode: member.coordination?.mode ?? null,
399
- ready: false,
399
+ ready: false, planKey: meta.plan_key,
400
400
  });
401
401
  let artifact;
402
402
  let witnessSet;
@@ -335,7 +335,8 @@ function projectionGuidance(value, coverage, components) {
335
335
  if (!exactRecord(value, ['code', 'message', 'next_action'])
336
336
  || !SEAM_PROPOSAL_GUIDANCE_CODES.includes(value.code)
337
337
  || !boundedText(value.message)
338
- || !isTodoIdentifier(value.next_action)) return false;
338
+ || !(value.next_action === 'none'
339
+ || (boundedText(value.next_action) && value.next_action.startsWith('lattice ')))) return false;
339
340
  const unknownKinds = Array.isArray(components)
340
341
  ? components.flatMap((component) => (Array.isArray(component?.unknowns)
341
342
  ? component.unknowns.map((unknown) => unknown?.kind) : []))