@quolu/lattice 0.115.0 → 0.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/lattice.mjs CHANGED
@@ -195,7 +195,12 @@ if (help !== null) {
195
195
  }
196
196
  } else if (args[0] === 'plan' && args[1] === 'backchain') {
197
197
  const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
198
- const spec = {
198
+ // One entry, three inputs: a finished chain (--input), a goal-side draft (--draft), or the draft skeleton (--template).
199
+ const spec = args.includes('--template') ? {
200
+ known: ['template', 'plan', 'json'], required: [], booleans: ['template', 'json'],
201
+ } : args.includes('--draft') ? {
202
+ known: ['draft', 'dry-run', 'json'], required: ['draft'], booleans: ['dry-run', 'json'],
203
+ } : {
199
204
  known: ['input', 'dry-run', 'json'], required: ['input'],
200
205
  booleans: ['dry-run', 'json'],
201
206
  };
@@ -207,10 +212,13 @@ if (help !== null) {
207
212
  const { runPlanBackchain } = await import('../src/plan-backchain.mjs');
208
213
  const { projectCliFailure } = await import('../src/project-cli.mjs');
209
214
  try {
210
- process.exitCode = await runPlanBackchain({
211
- cwd: process.cwd(), inputRef: flags.input, dryRun: flags['dry-run'] === true,
212
- stdout: process.stdout, env: process.env,
213
- });
215
+ process.exitCode = flags.template === true
216
+ ? await (await import('../src/plan-backchain.mjs')).runPlanBackchainTemplate({
217
+ cwd: process.cwd(), planKey: flags.plan ?? null, stdout: process.stdout })
218
+ : await runPlanBackchain({
219
+ cwd: process.cwd(), inputRef: flags.input ?? null, draftRef: flags.draft ?? null,
220
+ dryRun: flags['dry-run'] === true, stdout: process.stdout, env: process.env,
221
+ });
214
222
  } catch (error) {
215
223
  process.exitCode = projectCliFailure(process.stderr, error, { command: 'backchain', flags });
216
224
  }
@@ -325,11 +333,12 @@ function withImpliedJson(argv) {
325
333
  if (argv.includes('--json') || argv.includes('--help') || argv.includes('-h')) return argv;
326
334
  const [command, sub] = argv;
327
335
  const bare = !argv.some((word) => word.startsWith('-'));
328
- const input = argv.indexOf('--input');
336
+ const input = Math.max(argv.indexOf('--input'), argv.indexOf('--draft'));
329
337
  const implied = (bare && argv.length === 1 && (command === 'status' || command === 'session-context'))
330
338
  || (bare && argv.length === 3 && command === 'plan' && sub === 'show')
331
339
  || (bare && command === 'sensor' && (sub === 'init' || sub === 'sync') && argv.length <= 3)
332
340
  || (command === 'sensor' && (sub === 'diff' || sub === 'resolve' || sub === 'touched'))
341
+ || (command === 'plan' && sub === 'backchain' && argv.includes('--template'))
333
342
  || (command === 'plan' && (sub === 'revise' || sub === 'backchain')
334
343
  && input > 1 && typeof argv[input + 1] === 'string' && !argv[input + 1].startsWith('-'));
335
344
  return implied ? [...argv, '--json'] : argv;
@@ -344,10 +353,27 @@ function workingDirectory() {
344
353
  }
345
354
  }
346
355
 
356
+ // `enable`の署名者の指定: `--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>`。key-idとargvは対で、
357
+ // どちらも無ければ今の署名者を引き継ぐ。形の違いは null(usage)。
358
+ function reportingChange(flags) {
359
+ const dash = flags.indexOf('--');
360
+ const head = dash < 0 ? flags : flags.slice(0, dash);
361
+ const command = dash < 0 ? [] : flags.slice(dash + 1);
362
+ const values = {};
363
+ for (let index = 0; index < head.length; index += 2) {
364
+ if (head[index + 1] === undefined || !['--key-id', '--signer-cwd', '--url'].includes(head[index])) return null;
365
+ values[head[index]] = head[index + 1];
366
+ }
367
+ if ((values['--key-id'] === undefined) !== (command.length === 0)) return null;
368
+ if (values['--key-id'] === undefined && values['--signer-cwd'] !== undefined) return null;
369
+ return { ...(values['--key-id'] !== undefined && { signer: { key_id: values['--key-id'], command, cwd: values['--signer-cwd'] ?? null } }),
370
+ ...(values['--url'] !== undefined && { url: values['--url'] }) };
371
+ }
372
+
347
373
  async function runRuntimeErrorsCli(rest) {
348
374
  const runtimeErrors = await import('../src/runtime-errors.mjs');
349
375
  const usage = () => {
350
- process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable|disable|verify>> --json' })}\n`);
376
+ process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify>> --json' })}\n`);
351
377
  return 2;
352
378
  };
353
379
  const options = { version: packageJson.version };
@@ -382,10 +408,12 @@ async function runRuntimeErrorsCli(rest) {
382
408
  result = await reporting.verifyRuntimeErrorReporting(options);
383
409
  process.stdout.write(`${JSON.stringify(result)}\n`);
384
410
  return result.outcome === 'verified' ? 0 : 1;
385
- } else if (words[0] === 'reporting' && words.length === 2 && ['status', 'enable', 'disable'].includes(words[1])) {
411
+ } else if (words[0] === 'reporting' && (words[1] === 'enable' || (words.length === 2 && ['status', 'disable'].includes(words[1])))) {
386
412
  const reporting = await import('../src/runtime-error-reporting.mjs');
413
+ const change = words[1] === 'enable' ? reportingChange(words.slice(2)) : {};
414
+ if (change === null) return usage();
387
415
  result = words[1] === 'status' ? reporting.runtimeErrorReportingStatus(options)
388
- : reporting.setRuntimeErrorReporting(words[1] === 'enable', options);
416
+ : reporting.setRuntimeErrorReporting(words[1] === 'enable', options, change);
389
417
  } else if (words[0] === 'report' && (words.length === 1 || (words.length === 2 && words[1] === '--auto'))) {
390
418
  // 送れなかった時も結果は1行で返す。受領まで済んだ時と、送るものが無い時だけexit 0。
391
419
  const reporting = await import('../src/runtime-error-reporting.mjs');
@@ -23,7 +23,7 @@
23
23
  }
24
24
  },
25
25
  "features": {
26
- "type": "array", "minItems": 1, "maxItems": 2048,
26
+ "type": "array", "minItems": 1,
27
27
  "items": { "$ref": "#/$defs/feature" }
28
28
  },
29
29
  "tasks": {
@@ -45,7 +45,7 @@
45
45
  "type": "string", "minLength": 1, "maxLength": 1024,
46
46
  "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f\\u007f])[^/]+(?:/[^/]+)*$"
47
47
  },
48
- "ids": { "type": "array", "maxItems": 2048, "uniqueItems": true, "items": { "$ref": "#/$defs/identifier" } },
48
+ "ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/identifier" } },
49
49
  "nonemptyIds": { "allOf": [{ "$ref": "#/$defs/ids" }, { "minItems": 1 }] },
50
50
  "provider": {
51
51
  "oneOf": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.115.0",
3
+ "version": "0.117.0",
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
@@ -44,6 +44,10 @@ Commands:
44
44
  revise --schema --json
45
45
  backchain --input <file> [--dry-run] [--json]
46
46
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
47
+ backchain --template [--plan <key>] --json
48
+ # ゴール側から書く下書きの雛形。--planを付けると今のplanのtaskと版が入る
49
+ backchain --draft <file> [--dry-run] [--json]
50
+ # 下書きを下流から上流の順に書く(新規は final、既存は steps[].before が起点)。--dry-runで差分・継続・指摘を確認でき、指摘があっても登録できる
47
51
  show <plan_key> --json # task・依存辺・phase・状態をplan本体から1コマンドで投影する
48
52
  scope-review --plan-input <file> --review <scope-review.json> --json
49
53
  # 書き終えたplanの全taskが持ち主の作業仕様の内にあるかを、登録前に検査する
@@ -269,8 +273,9 @@ Commands:
269
273
  reopen <fingerprint>
270
274
  compact
271
275
  report 未受領の記録をBugHubの受け口へ送る(送信を有効にした端末だけ)
272
- reporting <status|enable|disable>
273
- reporting verify 空の報告を1通送り、合鍵と受け口までの経路を確かめる(記録には触れない)
276
+ reporting <status|disable>
277
+ reporting enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>] 送信を有効にする(署名者はBugHub-ES256の署名を返すcommand)
278
+ reporting verify 空の報告を1通送り、署名者と受け口までの経路を確かめる(記録には触れない)
274
279
  `,
275
280
  bridge: `Usage: lattice bridge <command> [options] --json
276
281
 
@@ -303,7 +308,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
303
308
  'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5|6> --json | --template --json',
304
309
  'plan show': 'plan show <plan_key> --json',
305
310
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
306
- 'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --schema --json',
311
+ 'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --draft <file> [--dry-run] [--json] | --template [--plan <key>] --json | --schema --json',
307
312
  'plan revise': 'plan revise [--plan <key>] --input <file> [--dry-run] [--json] | --schema --json\n\n'
308
313
  + '--input: the whole desired plan in the same shape as `plan create` (start from `plan create --template --json`),\n'
309
314
  + 'or {"schema":"lattice.plan_revise_input.v1","desired":<that plan>,"continuity":[{task_id, policy: carry|reset|retire, reason}]}.\n'
@@ -449,7 +454,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
449
454
  'runtime-errors reopen': 'runtime-errors reopen <fingerprint> --json',
450
455
  'runtime-errors compact': 'runtime-errors compact --json',
451
456
  'runtime-errors report': 'runtime-errors report --json',
452
- 'runtime-errors reporting': 'runtime-errors reporting <status|enable|disable|verify> --json',
457
+ 'runtime-errors reporting': 'runtime-errors reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify> --json',
453
458
  'bridge setup': 'bridge setup --listen <IP> [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
454
459
  'bridge reconfigure': 'bridge reconfigure [--listen <IP>] [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
455
460
  'bridge status': 'bridge status --json',
@@ -18,7 +18,6 @@ import {
18
18
 
19
19
  export const BACKCHAIN_SCHEMA = 'lattice.plan_backchain.v1';
20
20
  const CREATE_SCHEMA = 'lattice.plan_create_input.v4';
21
- const MAX_FEATURES = 2_048;
22
21
  const MAX_TEXT_BYTES = 16_384;
23
22
  const MAX_BINDING_BYTES = 8_388_608;
24
23
  const BINDING_SCHEMA = 'lattice.plan_backchain_binding.v1';
@@ -36,7 +35,7 @@ function text(value) {
36
35
 
37
36
  function identifiers(value, { nonempty = false } = {}) {
38
37
  return Array.isArray(value) && (!nonempty || value.length > 0)
39
- && value.length <= MAX_FEATURES && value.every(isTodoIdentifier)
38
+ && value.every(isTodoIdentifier)
40
39
  && new Set(value).size === value.length;
41
40
  }
42
41
 
@@ -128,8 +127,7 @@ export function validatePlanBackchain(chain, authoring) {
128
127
  || !identifiers(chain.goal.required_feature_ids, { nonempty: true })) {
129
128
  fail('goal_invalid', '/goal');
130
129
  }
131
- if (!Array.isArray(chain.features) || chain.features.length === 0
132
- || chain.features.length > MAX_FEATURES) fail('features_invalid', '/features');
130
+ if (!Array.isArray(chain.features) || chain.features.length === 0) fail('features_invalid', '/features'); // no count cap (ADR 0201); bytes bound it
133
131
  const features = new Map();
134
132
  for (const [index, feature] of chain.features.entries()) {
135
133
  if (!exactRecord(feature, [
@@ -257,7 +255,7 @@ export function validatePlanBackchain(chain, authoring) {
257
255
  }
258
256
 
259
257
  /** 決定的な順序(pointer, reason, 正準JSON)で並べ、同一の指摘は1件にする。 */
260
- function sortFindings(list) {
258
+ export function sortFindings(list) {
261
259
  const keyed = new Map(list.map((entry) => [canonicalizeTodoArtifact(entry), entry]));
262
260
  return [...keyed.entries()].sort(([left, a], [right, b]) =>
263
261
  a.pointer.localeCompare(b.pointer) || a.reason.localeCompare(b.reason)
@@ -386,34 +384,35 @@ function gitRoot(cwd) {
386
384
  } catch { fail('repository_unresolved', '/'); }
387
385
  }
388
386
 
389
- async function verifyExistingFeatureReferences(repoRoot, chain) {
387
+ /** null when the repo-relative ref is a readable regular file inside the repo, else unsafe | missing | unreadable. */
388
+ export async function existingReferenceProblem(canonicalRoot, ref) {
389
+ const absolute = path.resolve(canonicalRoot, ref);
390
+ if (!absolute.startsWith(`${canonicalRoot}${path.sep}`)) return 'unsafe';
391
+ let state;
392
+ try { state = await lstat(absolute); } catch { return 'missing'; }
393
+ let resolved;
394
+ try { resolved = await realpath(absolute); } catch { return 'unreadable'; }
395
+ return !state.isFile() || state.isSymbolicLink() || !resolved.startsWith(`${canonicalRoot}${path.sep}`)
396
+ ? 'unsafe' : null;
397
+ }
398
+
399
+ /** advisory (a draft): a receipt carried from an earlier version that is gone is reported, never invented or refused. */
400
+ async function verifyExistingFeatureReferences(repoRoot, chain, { advisory = false } = {}) {
390
401
  const canonicalRoot = await realpath(repoRoot);
402
+ const unresolved = [];
391
403
  for (const feature of chain.features) {
392
404
  if (feature.provider.kind !== 'existing') continue;
393
- const ref = feature.provider.evidence_ref;
394
- const absolute = path.resolve(canonicalRoot, ref);
395
- if (!absolute.startsWith(`${canonicalRoot}${path.sep}`)) {
396
- fail('existing_feature_reference_unsafe', `/features/${feature.feature_id}/provider`, {
397
- evidence_ref: ref,
398
- });
399
- }
400
- let state;
401
- try { state = await lstat(absolute); }
402
- catch { fail('existing_feature_reference_missing', `/features/${feature.feature_id}/provider`, {
403
- evidence_ref: ref,
404
- }); }
405
- let resolved;
406
- try { resolved = await realpath(absolute); }
407
- catch { fail('existing_feature_reference_unreadable', `/features/${feature.feature_id}/provider`, {
408
- evidence_ref: ref,
409
- }); }
410
- if (!state.isFile() || state.isSymbolicLink()
411
- || !resolved.startsWith(`${canonicalRoot}${path.sep}`)) {
412
- fail('existing_feature_reference_unsafe', `/features/${feature.feature_id}/provider`, {
413
- evidence_ref: ref,
405
+ const problem = await existingReferenceProblem(canonicalRoot, feature.provider.evidence_ref);
406
+ if (problem !== null && advisory) {
407
+ unresolved.push({ reason: 'observation_unresolved', pointer: `/features/${feature.feature_id}/provider`,
408
+ feature_id: feature.feature_id, evidence_ref: feature.provider.evidence_ref, cause: problem, carried: true });
409
+ } else if (problem !== null) {
410
+ fail(`existing_feature_reference_${problem}`, `/features/${feature.feature_id}/provider`, {
411
+ evidence_ref: feature.provider.evidence_ref,
414
412
  });
415
413
  }
416
414
  }
415
+ return unresolved;
417
416
  }
418
417
 
419
418
  const DONE_CONDITION_PLAN_SCHEMA = 'lattice.todo_plan.v8';
@@ -457,7 +456,7 @@ function featureGraphDigest(chain) {
457
456
  return digestTodoArtifact({ goal: chain.goal, features: chain.features, tasks: chain.tasks });
458
457
  }
459
458
 
460
- function taskSignature(chain, taskId) {
459
+ export function taskSignature(chain, taskId) {
461
460
  const task = chain?.tasks?.find(({ task_id: id }) => id === taskId);
462
461
  if (task === undefined) return null;
463
462
  const byId = new Map(chain.features.map((feature) => [feature.feature_id, feature]));
@@ -493,7 +492,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
493
492
  return { from_task_id: id, to_task_id: 'removed', state_policy: 'removed' };
494
493
  }
495
494
  if (decision?.policy === 'retire') fail('continuity_live_task_mismatch', '/continuity', { task_id: id });
496
- const sameContract = taskSignature(oldChain, id) === taskSignature(newChain, id);
495
+ // No earlier chain = no earlier contract to compare: absence is not a change (it would reset every task's history).
496
+ const sameContract = oldChain === null || taskSignature(oldChain, id) === taskSignature(newChain, id);
497
497
  const sameTask = oldTask.title === nextTask.title && oldTask.lane === nextTask.lane
498
498
  && oldTask.phase_id === nextTask.phase_id
499
499
  && oldTask.parent_task_id === nextTask.parent_task_id
@@ -506,7 +506,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
506
506
  || (decision === undefined && sameContract && sameTask);
507
507
  return { from_task_id: id, to_task_id: id,
508
508
  state_policy: carry ? 'carry_reconciled_metadata' : 'reset_pending' };
509
- }).sort((left, right) => left.from_task_id.localeCompare(right.from_task_id));
509
+ // Code-unit order, as validTaskMigration requires (localeCompare misorders mixed-case ids such as T and split-…).
510
+ }).sort((left, right) => (left.from_task_id < right.from_task_id ? -1 : left.from_task_id > right.from_task_id ? 1 : 0));
510
511
  }
511
512
 
512
513
  export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration) {
@@ -535,7 +536,7 @@ export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration)
535
536
  }
536
537
 
537
538
  export async function compileBackchainRevision({ repoRoot, member, chain, authoring }) {
538
- if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) {
539
+ if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) {
539
540
  fail('predecessor_plan_schema_unsupported', '/plan_key', {
540
541
  actual: member.plan.schema, next_action: 'author_a_new_backchain_plan',
541
542
  });
@@ -578,7 +579,7 @@ export async function compileBackchainRevision({ repoRoot, member, chain, author
578
579
  }
579
580
 
580
581
  async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
581
- if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) return false;
582
+ if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) return false;
582
583
  const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
583
584
  if (binding === null || featureGraphDigest(binding.chain) !== featureGraphDigest(chain)) return false;
584
585
  const amended = attachBackchainMemos(chain, authoring, { previousChain: binding.chain });
@@ -634,24 +635,55 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
634
635
  return rebound;
635
636
  }
636
637
 
637
- export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
638
+ const draftOutput = (report) => (report === null ? {} : { draft: report.summary, draft_findings: report.findings });
639
+
640
+ export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null, stdout, dryRun = false, env = process.env }) {
638
641
  const repoRoot = gitRoot(cwd);
639
- const chain = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' });
640
- failOnShape(chain);
641
- const authoring = completeCreateInput(await readAuthoringJsonFile(repoRoot, chain.authoring_ref, {
642
- invalidCode: 'PLAN_BACKCHAIN_INVALID',
643
- }), { env, now: new Date() });
644
- const { findings: featureChainFindings } = validatePlanBackchain(chain, authoring);
645
- await verifyExistingFeatureReferences(repoRoot, chain);
642
+ const loadStore = async () => {
643
+ try {
644
+ await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
645
+ return await readTodoStore({ repoRoot });
646
+ } catch (error) {
647
+ if (error?.code !== 'ENOENT') throw error;
648
+ return null;
649
+ }
650
+ };
651
+ let chain;
652
+ let authoring;
653
+ let store;
654
+ let draftReport = null;
655
+ // The seat's structured-input route passes JSON through --input: a draft is recognized by its schema.
656
+ let given = draftRef !== null ? await readAuthoringJsonFile(repoRoot, draftRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' }) : null;
657
+ if (given === null) {
658
+ given = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' });
659
+ if (given?.schema === 'lattice.plan_draft.v1') draftRef = inputRef; else draftRef = null;
660
+ }
661
+ if (draftRef !== null) {
662
+ const draft = given;
663
+ store = await loadStore();
664
+ const { compilePlanDraft } = await import('./plan-draft.mjs');
665
+ ({ chain, authoring, report: draftReport } = await compilePlanDraft({
666
+ repoRoot, draft, draftRef, store, env,
667
+ member: store?.members.find(({ plan }) => plan.plan_key === draft?.plan_key) ?? null,
668
+ }));
669
+ } else {
670
+ chain = given;
671
+ failOnShape(chain);
672
+ authoring = completeCreateInput(await readAuthoringJsonFile(repoRoot, chain.authoring_ref, {
673
+ invalidCode: 'PLAN_BACKCHAIN_INVALID',
674
+ }), { env, now: new Date() });
675
+ store = await loadStore();
676
+ }
677
+ const { findings: allFindings } = validatePlanBackchain(chain, authoring);
678
+ // A draft over a legacy plan declares only the branch it touches; tasks elsewhere are unassessed, not missing.
679
+ const featureChainFindings = draftReport === null ? allFindings
680
+ : allFindings.filter(({ reason }) => reason !== 'task_coverage_missing');
681
+ const carriedGaps = await verifyExistingFeatureReferences(repoRoot, chain, { advisory: draftReport !== null });
682
+ if (carriedGaps.length > 0) draftReport.findings = sortFindings([...draftReport.findings, ...carriedGaps]);
646
683
  let member = null;
647
- let store = null;
648
- try {
649
- await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
650
- store = await readTodoStore({ repoRoot });
684
+ if (store !== null) {
651
685
  if (store.project_id !== chain.project_id) fail('project_id_mismatch', '/project_id');
652
686
  member = store.members.find(({ plan }) => plan.plan_key === chain.plan_key) ?? null;
653
- } catch (error) {
654
- if (error?.code !== 'ENOENT') throw error;
655
687
  }
656
688
  if (member === null && (chain.continuity?.length ?? 0) > 0) {
657
689
  fail('continuity_without_predecessor', '/continuity');
@@ -679,6 +711,7 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
679
711
  : store === null ? 'create' : 'add',
680
712
  task_migration: revision?.task_migration ?? null,
681
713
  feature_chain_findings: featureChainFindings,
714
+ ...draftOutput(draftReport),
682
715
  result_digest: '',
683
716
  };
684
717
  checked.result_digest = todoSelfDigest(checked, 'result_digest');
@@ -736,6 +769,7 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
736
769
  chain_digest: effectiveChain.chain_digest, authoring_result: created,
737
770
  rebound_task_ids: reboundTaskIds,
738
771
  feature_chain_findings: featureChainFindings,
772
+ ...draftOutput(draftReport),
739
773
  operation: unchanged ? 'unchanged' : revision !== null ? 'revise'
740
774
  : store === null ? 'create' : 'add',
741
775
  journal_head_digest: finalMember.journal.events.at(-1).event_digest,
@@ -746,6 +780,25 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
746
780
  return 0;
747
781
  }
748
782
 
783
+ /** `plan backchain --template [--plan K]`: the draft skeleton, seeded from the active plan when one is named. */
784
+ export async function runPlanBackchainTemplate({ cwd, planKey = null, stdout }) {
785
+ const repoRoot = gitRoot(cwd);
786
+ let store = null;
787
+ try {
788
+ await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
789
+ store = await readTodoStore({ repoRoot });
790
+ } catch (error) {
791
+ if (error?.code !== 'ENOENT') throw error;
792
+ }
793
+ const member = planKey === null ? null : store?.members.find(({ plan }) => plan.plan_key === planKey) ?? null;
794
+ if (planKey !== null && member === null) {
795
+ fail('plan_not_active', '/plan', { plan_key: planKey, next_action: 'Run lattice todo status --json to list the active plan keys.' });
796
+ }
797
+ const { draftTemplate } = await import('./plan-draft.mjs');
798
+ stdout.write(`${JSON.stringify(await draftTemplate({ repoRoot, member, store }))}\n`);
799
+ return 0;
800
+ }
801
+
749
802
  export async function backchainSchema() {
750
803
  return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_backchain.v1.schema.json', import.meta.url), 'utf8'));
751
804
  }