@quolu/lattice 0.85.2 → 0.85.4

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/src/todo-cli.mjs CHANGED
@@ -3,6 +3,7 @@ import { cliCommandKind } from './cli-command-kind.mjs';
3
3
  import { cliFailureClass } from './cli-failure-class.mjs';
4
4
  import { FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
5
5
  import { readTaskBackchainContext } from './plan-backchain.mjs';
6
+ import { auditPendingNextCommands } from './todo-audit-pending.mjs';
6
7
  import { gitSync } from './git-process.mjs';
7
8
  import { createHash } from 'node:crypto';
8
9
  import {
@@ -20,6 +21,7 @@ import {
20
21
  repairAuthoringArtifact,
21
22
  resolveAuthoringInputPath,
22
23
  resolveTodoActor,
24
+ todoActorAgents,
23
25
  } from './todo-authoring-input.mjs';
24
26
 
25
27
  import {
@@ -168,8 +170,8 @@ import { collectTodoIndependenceAuthoritativeObservation } from './todo-independ
168
170
  import { applySeamProposal } from './seam-apply.mjs';
169
171
  import { todoPlanPrecedences } from './seam-verification.mjs';
170
172
  import {
171
- WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, serializeWitnessSet,
172
- validateWitnessDraft,
173
+ WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, explainWitnessDraft, serializeWitnessSet,
174
+ witnessDraftTemplate,
173
175
  } from './witness-scaffold.mjs';
174
176
  import {
175
177
  completePhaseTodoRevision, explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
@@ -215,7 +217,18 @@ const TODO_SCHEMA_COMMANDS = Object.freeze({
215
217
  structure: {
216
218
  title: 'lattice.todo_structure_set.v1', file: 'lattice.todo_structure_set.v1.schema.json',
217
219
  },
220
+ // a32: the witness route's two inputs, so a seat that chose `--set witness` can find their shape.
221
+ 'independence witness scaffold': {
222
+ title: 'lattice.todo_witness_draft.v2', file: 'lattice.todo_witness_draft.v2.schema.json',
223
+ },
224
+ 'independence compile': { title: 'lattice.todo_witness_set.v5', file: 'lattice.todo_witness_set.v5.schema.json' },
218
225
  });
226
+ const witnessTemplateCommand = (planKey) => `lattice todo independence witness scaffold --template --plan ${planKey}`;
227
+ const WITNESS_DRAFT_SCHEMA_COMMAND = 'lattice todo independence witness scaffold --schema --json';
228
+ /** a32: where a witness set comes from: the template, filled, through scaffold (which adds digest and observations). */
229
+ const witnessRoute = (planKey) => `Start from \`${witnessTemplateCommand(planKey)}\` (draft shape: \`${WITNESS_DRAFT_SCHEMA_COMMAND}\`),`
230
+ + ` fill each task's owns/reads/writes, then run \`lattice todo independence witness scaffold --plan ${planKey} --input <draft>\`;`
231
+ + ' it writes the witness set that `independence compile` reads (shape: `lattice todo independence compile --schema --json`).';
219
232
 
220
233
  async function runTodoSchemaCommand(command, stdout) {
221
234
  const spec = TODO_SCHEMA_COMMANDS[command];
@@ -237,7 +250,7 @@ function typedFailure(stderr, error, context = {}) {
237
250
  }
238
251
 
239
252
  /** What the printers need to name a concrete repair: the command and the --plan/--task the caller typed. */
240
- function guidanceContext(argv) {
253
+ function guidanceContext(argv, env = {}) {
241
254
  const { flags } = parseFlagMap(argv.slice(1));
242
255
  return {
243
256
  family: 'todo',
@@ -245,6 +258,8 @@ function guidanceContext(argv) {
245
258
  plan: typeof flags.plan === 'string' ? flags.plan : undefined,
246
259
  task: typeof flags.task === 'string' ? flags.task : undefined,
247
260
  flags,
261
+ // a36: who this seat is now and was before LATTICE_SEAT_ID, so a start refusal can name its own old start.
262
+ actors: todoActorAgents(env),
248
263
  };
249
264
  }
250
265
 
@@ -325,11 +340,15 @@ const TODO_FLAG_SPECS = Object.freeze({
325
340
  'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
326
341
  'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
327
342
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
343
+ 'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
344
+ 'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
328
345
  show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
329
346
  'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
330
347
  structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
331
348
  status: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
332
349
  });
350
+ const WITNESS_TEMPLATE_FLAG_SPEC = Object.freeze({
351
+ known: ['template', 'plan', 'json'], required: ['plan'], booleans: ['template', 'json'] });
333
352
  // a28: command groups, their subcommands and the one a refusal shows as the example.
334
353
  const TODO_SUBCOMMANDS = Object.freeze({
335
354
  dependency: { names: ['connect', 'disconnect'], example: 'connect' },
@@ -402,9 +421,12 @@ function explainMissingSubcommand(argv) {
402
421
  function explainArgumentRefusal(argv) {
403
422
  const missingSubcommand = explainMissingSubcommand(argv);
404
423
  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);
407
- const spec = TODO_FLAG_SPECS[head.join(' ')];
424
+ const head = argv[0] === 'independence' && argv[1] === 'witness' ? argv.slice(0, 3)
425
+ : GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
426
+ ? argv.slice(0, 2) : argv.slice(0, 1);
427
+ // a32: `scaffold --template` is a read with its own flags.
428
+ const spec = head.join(' ') === 'independence witness scaffold' && argv.includes('--template')
429
+ ? WITNESS_TEMPLATE_FLAG_SPEC : TODO_FLAG_SPECS[head.join(' ')];
408
430
  if (spec === undefined) return {};
409
431
  const { flags } = parseFlagMap(argv.slice(head.length));
410
432
  const flagFailure = explainFlagCommand(argv, head, spec);
@@ -493,7 +515,7 @@ function supportsAtomicStoreCommit(argv) {
493
515
  if (command === 'note') return argv[1] !== 'list';
494
516
  if (command === 'independence') {
495
517
  return argv[1] === 'mode'
496
- || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]));
518
+ || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]) && !argv.includes('--template'));
497
519
  }
498
520
  if (command === 'snapshot') return argv[1] === '--rebuild';
499
521
  if (command === 'migrate') return !argv.includes('--dry-run') && !argv.includes('--schema');
@@ -782,11 +804,23 @@ async function readJsonInput(repoRoot, inputRef, { validate, invalidCode, expect
782
804
  return descriptor;
783
805
  }
784
806
 
807
+ const WITNESS_SET_TOP_LEVEL_KEYS = ['schema', 'project_id', 'plan_key', 'capacity', 'sensor_query_set',
808
+ 'manual_witness', 'witness_set_digest'];
809
+ /** a32: the top-level keys a witness set lacks or should not have. */
810
+ function witnessSetKeyDiff(value) {
811
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return {};
812
+ const keys = Object.keys(value);
813
+ return { missing_keys: WITNESS_SET_TOP_LEVEL_KEYS.filter((key) => !keys.includes(key)),
814
+ unexpected_keys: keys.filter((key) => !WITNESS_SET_TOP_LEVEL_KEYS.includes(key)).sort() };
815
+ }
816
+
785
817
  /** 安全読み取りとcanonical JSON規律を共有したまま、witness set契約で検証する。 */
786
- async function readWitnessSetInput(repoRoot, inputRef) {
818
+ async function readWitnessSetInput(repoRoot, inputRef, planKey = '<key>') {
787
819
  let explained = null;
820
+ let witnessInput;
788
821
  const witnessSet = await readJsonInput(repoRoot, inputRef, {
789
822
  validate: (value) => {
823
+ witnessInput = value;
790
824
  explained = explainTodoWitnessSet(value);
791
825
  return explained.valid;
792
826
  },
@@ -794,7 +828,8 @@ async function readWitnessSetInput(repoRoot, inputRef) {
794
828
  }).catch((error) => {
795
829
  if (error?.code === 'INVALID_TODO_WITNESS_SET' && explained !== null) {
796
830
  throw new TodoStoreError('INVALID_TODO_WITNESS_SET', explained.reason, undefined, {
797
- input_ref: inputRef, path: explained.path,
831
+ input_ref: inputRef, path: explained.path, pointer: explained.path || '/',
832
+ ...witnessSetKeyDiff(witnessInput), next_action: witnessRoute(planKey),
798
833
  });
799
834
  }
800
835
  throw error;
@@ -817,7 +852,17 @@ async function readStructureSetDraft(repoRoot, inputRef) {
817
852
  function auditGateGuidance(planKey, phaseId) {
818
853
  const target = `--plan ${planKey} --phase ${phaseId}`;
819
854
  return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
820
- + `(監査するなら lattice todo phase review ${target} --reason <text> → accept ${target} --input <file>)`;
855
+ + `(監査するなら lattice todo phase review ${target} --reason <text> → accept ${target} --evidence <file>)`;
856
+ }
857
+
858
+ /** a36: reviewing and rejected phases say their next command too (the same lines as audit_pending). */
859
+ function auditDecisionGuidance(plan, phase) {
860
+ const slots = todoPhaseDefinitions(plan).find(({ phase_id: id }) => id === phase.phase_id)
861
+ ?.required_evidence_slots.length ?? 1;
862
+ const [first, second] = auditPendingNextCommands(plan.plan_key, phase.phase_id, phase.status, slots);
863
+ return phase.status === 'reviewing'
864
+ ? `監査中(review済み)。受け入れるなら: ${first}(通らないなら: ${second})`
865
+ : `監査が通らなかった。やり直すなら: ${first}`;
821
866
  }
822
867
 
823
868
  /**
@@ -952,6 +997,28 @@ async function mutate({
952
997
  return result;
953
998
  }
954
999
 
1000
+ /**
1001
+ * a36: a reopened task stays in its last starter's `turn.own` (seat contract). When that is not
1002
+ * this seat, the result names the holder and the one command that moves the task here.
1003
+ */
1004
+ async function reopenTask({ repoRoot, env, planKey, taskId, payload }) {
1005
+ const result = await mutate({ repoRoot, env, planKey, taskId, kind: 'reopen', payload, evidenceRef: null });
1006
+ const store = await readTodoStore({ repoRoot });
1007
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === result.plan_key);
1008
+ const holder = member?.journal.events
1009
+ .findLast((event) => event.kind === 'start' && event.task_id === result.task_id)?.actor?.agent ?? null;
1010
+ if (holder === resolveTodoActor(env).agent) return result;
1011
+ const hinted = {
1012
+ ...result, started_by: holder,
1013
+ next_action: `${result.plan_key}/${result.task_id} is in-progress again under`
1014
+ + ` ${holder === null ? 'no seat (no start in this plan version)' : `seat '${holder}', which started it last`};`
1015
+ + ` to work on it from this seat run \`lattice todo start --plan ${result.plan_key} --task ${result.task_id} --rebind --reason <text>\`.`,
1016
+ result_digest: '',
1017
+ };
1018
+ hinted.result_digest = todoSelfDigest(hinted, 'result_digest');
1019
+ return hinted;
1020
+ }
1021
+
955
1022
  /**
956
1023
  * 恒久除去(u12)。どの状態からでも`{reason, prior_status}`で閉じる。
957
1024
  * in-progressは、最新のauthored startに束ねられた未acceptのintakeをRuntimeの解放手順で
@@ -1780,7 +1847,8 @@ async function phaseStatus({ repoRoot, planKey }) {
1780
1847
  ...(structureFinalization.required && structureFinalization.status !== 'fresh'
1781
1848
  ? [`構造finalizationが${structureFinalization.status}です。先に lattice todo structure finalize --plan ${member.plan.plan_key} --json を実行してください。`]
1782
1849
  : []),
1783
- ].join('\n') : null,
1850
+ ].join('\n')
1851
+ : ['reviewing', 'rejected'].includes(phase.status) ? auditDecisionGuidance(member.plan, phase) : null,
1784
1852
  }));
1785
1853
  const result = {
1786
1854
  schema: 'lattice.phase_status_result.v2', project_id: store.project_id,
@@ -2269,8 +2337,7 @@ async function splitTodo({ repoRoot, env, planKey, inputRef }) {
2269
2337
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
2270
2338
  if (witnessSet === null) {
2271
2339
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
2272
- witness_ref: todoWitnessRef(planKey),
2273
- next_action: `lattice todo independence witness scaffold --plan ${planKey} --input <draft>`,
2340
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
2274
2341
  });
2275
2342
  }
2276
2343
  const compiled = await compileTodoSplit({ repoRoot, member, proposal });
@@ -3143,7 +3210,7 @@ async function structure({ repoRoot, requestedPlanKey }) {
3143
3210
  }
3144
3211
 
3145
3212
  async function independenceCompile({ repoRoot, planKey, inputRef }) {
3146
- const witnessSet = await readWitnessSetInput(repoRoot, inputRef);
3213
+ const witnessSet = await readWitnessSetInput(repoRoot, inputRef, planKey);
3147
3214
  const storeForReady = await readTodoStore({ repoRoot });
3148
3215
  const memberForReady = storeForReady.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3149
3216
  if (!memberForReady) {
@@ -3172,7 +3239,9 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3172
3239
  {
3173
3240
  plan_key: planKey,
3174
3241
  missing_task_ids: missingReady,
3175
- next_action: independenceCompileCommand(planKey),
3242
+ // a35: compiling the same set again cannot add them; the template keeps what is declared.
3243
+ next_action: `Declare ${missingReady.join(', ')} in the witness set. ${witnessRoute(planKey)}`
3244
+ + ' The template keeps the declarations already recorded, so only the new tasks need filling.',
3176
3245
  },
3177
3246
  );
3178
3247
  }
@@ -3233,7 +3302,7 @@ async function independenceWitnessMigrate({ repoRoot, planKey }) {
3233
3302
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
3234
3303
  if (witnessSet === null) {
3235
3304
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
3236
- witness_ref: todoWitnessRef(planKey),
3305
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
3237
3306
  });
3238
3307
  }
3239
3308
  const revision = member.revision;
@@ -3497,10 +3566,31 @@ async function seamProposalCompile({ repoRoot, planKey }) {
3497
3566
  * 推定はしない。何を所有し何を触るかは下書きが述べ、ここが供給するのはAIには作れないもの——
3498
3567
  * affected testのfresh観測、query setとprovenanceの配線、canonical bytesと自己digest——だけである。
3499
3568
  */
3569
+ /** a32: the starting draft for `planKey`: its tasks that are not done or retired, nothing declared yet. */
3570
+ async function witnessDraftTemplateFor({ repoRoot, planKey }) {
3571
+ const store = await readTodoStore({ repoRoot });
3572
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3573
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
3574
+ // a35: start from what is already declared. An unreadable set only loses the prefill, not the template.
3575
+ const witnessSet = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
3576
+ return witnessDraftTemplate({ projectId: member.plan.project_id, planKey, witnessSet,
3577
+ taskIds: member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id) });
3578
+ }
3579
+
3500
3580
  async function witnessScaffold({ repoRoot, planKey, inputRef }) {
3581
+ let explained = null;
3501
3582
  const draft = await readJsonInput(repoRoot, inputRef, {
3502
- validate: validateWitnessDraft,
3583
+ validate: (value) => (explained = explainWitnessDraft(value)).valid,
3503
3584
  invalidCode: 'WITNESS_DRAFT_INVALID',
3585
+ }).catch((error) => {
3586
+ // a32: name the failing field and where the draft shape is, not a schema command that does not exist.
3587
+ if (error?.code === 'WITNESS_DRAFT_INVALID' && explained !== null && !explained.valid) {
3588
+ const { valid: _valid, reason, path: at, ...keys } = explained;
3589
+ throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
3590
+ input_ref: inputRef, pointer: at, ...keys, next_action: witnessRoute(planKey),
3591
+ });
3592
+ }
3593
+ throw error;
3504
3594
  });
3505
3595
  if (draft.plan_key !== planKey) {
3506
3596
  throw new TodoStoreError('INPUT_INVALID', 'witness_draft_plan_mismatch', undefined, {
@@ -4243,8 +4333,8 @@ function writesTodoStore(argv) {
4243
4333
  case 'note': return second !== 'list';
4244
4334
  case 'migrate': return !argv.includes('--dry-run');
4245
4335
  case 'snapshot': return argv.includes('--rebuild');
4246
- case 'independence': return second === 'compile'
4247
- || (second === 'witness' && ['migrate', 'scaffold'].includes(third));
4336
+ case 'independence': return second === 'compile' || second === 'mode'
4337
+ || (second === 'witness' && ['migrate', 'scaffold'].includes(third) && !argv.includes('--template'));
4248
4338
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4249
4339
  || (second === 'input' && !argv.includes('--dry-run'));
4250
4340
  case 'seam-proposal': return ['compile', 'apply', 'land'].includes(second);
@@ -4478,10 +4568,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4478
4568
 
4479
4569
  // `--schema --json`はstoreを読まない決定的な出力(`plan create --schema`と同じ規律)。
4480
4570
  // 通常dispatchより前に処理し、repoRoot解決やdashboard daemon起動を経由させない。
4481
- if (argv.length === 3 && argv[1] === '--schema' && argv[2] === '--json'
4482
- && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv[0])) {
4571
+ if (argv.length >= 3 && argv.at(-2) === '--schema' && argv.at(-1) === '--json'
4572
+ && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv.slice(0, -2).join(' '))) {
4483
4573
  try {
4484
- await runTodoSchemaCommand(argv[0], stdout);
4574
+ await runTodoSchemaCommand(argv.slice(0, -2).join(' '), stdout);
4485
4575
  return 0;
4486
4576
  } catch (error) {
4487
4577
  return failInternally(error);
@@ -4565,12 +4655,14 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4565
4655
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
4566
4656
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
4567
4657
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
4568
- } else if (argv.length === 8 && argv[0] === 'independence' && argv[1] === 'mode'
4569
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--set'
4570
- && TODO_COORDINATION_MODES.includes(argv[5]) && argv[6] === '--reason' && argv[7].length > 0) {
4571
- action = (repoRoot) => independenceMode({
4572
- repoRoot, env, planKey: argv[3], mode: argv[5], reason: argv[7],
4573
- });
4658
+ } else if (argv[0] === 'independence' && argv[1] === 'mode'
4659
+ && matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']) !== null) {
4660
+ const flags = matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']);
4661
+ if (isTodoIdentifier(flags.plan) && TODO_COORDINATION_MODES.includes(flags.set)) {
4662
+ action = (repoRoot) => independenceMode({
4663
+ repoRoot, env, planKey: flags.plan, mode: flags.set, reason: flags.reason,
4664
+ });
4665
+ }
4574
4666
  } else if (argv[0] === 'dependency' && argv[1] === 'connect'
4575
4667
  && dependencyFlags(argv) !== null) {
4576
4668
  const flags = dependencyFlags(argv);
@@ -4643,10 +4735,18 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4643
4735
  } else if (argv.length === 4 && argv[0] === 'seam-proposal' && argv[1] === 'apply'
4644
4736
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])) {
4645
4737
  action = (repoRoot) => seamProposalApply({ repoRoot, planKey: argv[3] });
4646
- } else if (argv.length === 7 && argv[0] === 'independence' && argv[1] === 'witness'
4647
- && argv[2] === 'scaffold' && argv[3] === '--plan' && isTodoIdentifier(argv[4])
4648
- && argv[5] === '--input' && isAuthoringPathToken(argv[6])) {
4649
- action = (repoRoot) => witnessScaffold({ repoRoot, planKey: argv[4], inputRef: argv[6] });
4738
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold'
4739
+ && argv.includes('--template')) {
4740
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'], WITNESS_TEMPLATE_FLAG_SPEC);
4741
+ if (flags !== null && isTodoIdentifier(flags.plan)) {
4742
+ action = (repoRoot) => witnessDraftTemplateFor({ repoRoot, planKey: flags.plan });
4743
+ }
4744
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold') {
4745
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'],
4746
+ TODO_FLAG_SPECS['independence witness scaffold']);
4747
+ if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4748
+ action = (repoRoot) => witnessScaffold({ repoRoot, planKey: flags.plan, inputRef: flags.input });
4749
+ }
4650
4750
  } else if (argv.length === 6 && argv[0] === 'seam-proposal' && argv[1] === 'land'
4651
4751
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4652
4752
  && argv[4] === '--names' && isAuthoringPathToken(argv[5])) {
@@ -4858,14 +4958,12 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4858
4958
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4859
4959
  && (flags['override-reason'] === undefined
4860
4960
  || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0))) {
4861
- action = (repoRoot) => mutate({
4961
+ action = (repoRoot) => reopenTask({
4862
4962
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4863
- kind: 'reopen',
4864
4963
  payload: {
4865
4964
  reason: flags.reason,
4866
4965
  override_reason: typeof flags['override-reason'] === 'string' ? flags['override-reason'] : null,
4867
4966
  },
4868
- evidenceRef: null,
4869
4967
  });
4870
4968
  }
4871
4969
  }
@@ -4914,7 +5012,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4914
5012
  } catch (error) {
4915
5013
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
4916
5014
  && error.detail !== null && typeof error.detail === 'object')) {
4917
- return typedFailure(stderr, error, guidanceContext(argv));
5015
+ return typedFailure(stderr, error, guidanceContext(argv, env));
4918
5016
  }
4919
5017
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
4920
5018
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {
@@ -80,7 +80,8 @@ const CATALOG = Object.freeze({
80
80
  }),
81
81
  independence_unrecorded: Object.freeze({
82
82
  message: 'このplanの並列可否はまだ判定していない。競合が無いのではなく、記録が存在しない。',
83
- next_action: 'lattice todo independence compile --plan <key> --input <file>',
83
+ // a32: the first step of the witness route is the draft template, not a file the seat cannot shape.
84
+ next_action: 'lattice todo independence witness scaffold --template --plan <key>',
84
85
  }),
85
86
  independence_task_undeclared: Object.freeze({
86
87
  message: 'この工程はwitness setで宣言されていないため、記録には含まれていない。',
@@ -309,7 +310,7 @@ export function selectSeamProposalGuidance({ coverage, unknownKinds = [], planKe
309
310
  * 足さないと、能力はあるのに機械が黙る面が残る(ADR 0130)。
310
311
  */
311
312
  export const TODO_INDEPENDENCE_WORKFLOW = Object.freeze([
312
- '1. 宣言する: .lattice/todo/witness/<plan_key>.json へ、ToDoごとのowns/reads/writes/affected_testsを書く',
313
+ '1. 宣言する: lattice todo independence witness scaffold --template --plan <key> が出す下書き(形は lattice todo independence witness scaffold --schema --json)へToDoごとのowns/reads/writesを書き、lattice todo independence witness scaffold --plan <key> --input <draft> が .lattice/todo/witness/<plan_key>.json を書く(affected_testsと自己digestは機械が埋める。形は lattice todo independence compile --schema --json)',
313
314
  ' 係争資源しか所有していないToDoは、ownsまたはwritesの内側で自分が触るsymbolをconcern_anchorsへ宣言できる(witness set v2)。並列可否の判定には写らず、切断候補の束縛だけに効く',
314
315
  ' remaining の A 工程(まだ done でない ready / blocked)も同じ witness に含める。現在の ready だけを compile すると、次の frontier の start の助言が未検証(independence_task_undeclared)になる',
315
316
  '2. 判定する: lattice todo independence compile --plan <key> --input <ref>(実sensorを引く。pretty-printやdigest未計算の下書きは機械が直す)。next_ready が witness に無い compile は拒否する',
@@ -4,7 +4,7 @@ import {
4
4
  isPhaseTodoPlanSchema,
5
5
  projectTodoCrossPlanDependencies,
6
6
  } from './todo-store-view.mjs';
7
- import { TodoStoreError } from './todo-store.mjs';
7
+ import { TodoStoreError, todoPhaseDefinitions } from './todo-store.mjs';
8
8
 
9
9
  function taskKey(ref) {
10
10
  return `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`;
@@ -187,6 +187,17 @@ export function validateProspectiveEvent({ store, member, event }) {
187
187
  + ` \`lattice todo reopen ${on} --reason <text> --override-reason <text>\`.`,
188
188
  });
189
189
  }
190
+ // a36: review and close-unaudited need gate_ready; any other phase state is ordinary, not damage.
191
+ if (event.kind === 'phase_review' || event.kind === 'phase_close_unaudited') {
192
+ const phase = (member.phases ?? []).find(({ phase_id: id }) => id === event.phase_id);
193
+ if (phase !== undefined && phase.status !== 'gate_ready') {
194
+ const definition = todoPhaseDefinitions(member.plan).find(({ phase_id: id }) => id === event.phase_id);
195
+ return refused('phase_gate_not_ready', 'phase_state', {
196
+ plan_key: member.plan.plan_key, phase_id: event.phase_id, phase_status: phase.status,
197
+ required_evidence_slots: [...(definition?.required_evidence_slots ?? [])],
198
+ });
199
+ }
200
+ }
190
201
  if (event.kind === 'phase_reopen' && event.payload.override_reason === null
191
202
  && readiness.phaseHasStartedSuccessor(member, event.phase_id)) {
192
203
  return refused('phase_reopen_has_started_successor', 'task_state');
@@ -194,7 +205,12 @@ export function validateProspectiveEvent({ store, member, event }) {
194
205
  // Keep merged refusal priority; replay still owns missing target/binding checks.
195
206
  const status = readiness.status(key);
196
207
  if (authoredStart && status !== undefined) {
197
- if (status !== 'pending') return refused('invalid_start_transition', 'task_state', { status });
208
+ if (status !== 'pending') {
209
+ // a36: name who holds an in-progress task, so the refusal can tell an own anonymous start apart.
210
+ const holder = status === 'in-progress' ? member.journal.events
211
+ .findLast((entry) => entry.kind === 'start' && entry.task_id === event.task_id)?.actor?.agent : undefined;
212
+ return refused('invalid_start_transition', 'task_state', { status, ...(holder === undefined ? {} : { started_by: holder }) });
213
+ }
198
214
  if (!readiness.ownPhaseReady(key)) {
199
215
  return refused('invalid_start_transition', 'phase_state', { phase_status: readiness.ownPhaseStatus(key) });
200
216
  }
@@ -413,7 +413,8 @@ function collectAuditPending(member, sink) {
413
413
  phase_status: phase.status,
414
414
  implicit,
415
415
  required_evidence_slots: [...definition.required_evidence_slots],
416
- next_commands: auditPendingNextCommands(member.plan.plan_key, phase.phase_id, phase.status),
416
+ next_commands: auditPendingNextCommands(member.plan.plan_key, phase.phase_id, phase.status,
417
+ definition.required_evidence_slots.length),
417
418
  });
418
419
  }
419
420
  }
@@ -798,6 +798,21 @@ function replay(plan, events, { verifyEvidence, verifyImportSource } = {}) {
798
798
  return [...states.values()].sort((left, right) => left.task_id < right.task_id ? -1 : left.task_id > right.task_id ? 1 : 0);
799
799
  }
800
800
 
801
+ /**
802
+ * a35: what put the task in progress in this plan version: 'start' (authored, retractable),
803
+ * 'historical_import', 'reopen', or null (no event here, e.g. carried by a revision).
804
+ * Only an authored start has something for `todo retract` to undo.
805
+ */
806
+ function todoOpenedBy(member, taskId) {
807
+ let openedBy = null;
808
+ for (const event of member.journal.events) {
809
+ if (event.task_id !== taskId) continue;
810
+ if (event.kind === 'start') openedBy = event.payload.start_mode === 'historical_import' ? 'historical_import' : 'start';
811
+ else if (event.kind === 'reopen') openedBy = 'reopen';
812
+ }
813
+ return openedBy;
814
+ }
815
+
801
816
  /** 最新のauthored startだけを撤回対象として返す。readとappendの双方で同じbindingを検証する。 */
802
817
  export function resolveTodoStartRetractionBinding(store, { planKey, taskId, actor }) {
803
818
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
@@ -817,7 +832,8 @@ export function resolveTodoStartRetractionBinding(store, { planKey, taskId, acto
817
832
  else if (event.kind === 'done' || event.kind === 'start_retracted') binding = null;
818
833
  }
819
834
  if (binding === null) {
820
- fail('START_RETRACTION_INVALID', 'authored_start_binding_missing', { task_id: canonicalTaskId });
835
+ fail('START_RETRACTION_INVALID', 'authored_start_binding_missing', {
836
+ plan_key: planKey, task_id: canonicalTaskId, opened_by: todoOpenedBy(member, canonicalTaskId) });
821
837
  }
822
838
  if (binding.actor.host !== actor.host || binding.actor.session !== actor.session
823
839
  || binding.actor.agent !== actor.agent) {
@@ -1574,7 +1590,8 @@ async function readTodoStoreView(options = {}) {
1574
1590
  // 調整方式の宣言(ob03)。lifecycle journalとは別chainから読む。phasesと同じく
1575
1591
  // snapshot artifactの形式には縛られない導出ビューで、未宣言はnull(「まだ選んでいない」)。
1576
1592
  const planScoped = await readPlanScopedJournal(repoRoot, descriptor.journal_ref);
1577
- const coordination = projectTodoCoordination(planScoped.events);
1593
+ const coordination = projectTodoCoordination(planScoped.events)
1594
+ ?? await inheritedTodoCoordination(repoRoot, plan);
1578
1595
  loaded.push({ descriptor, plan, revision, journal, plan_scoped: planScoped,
1579
1596
  snapshot: snapshotStale ? expectedSnapshot : snapshot,
1580
1597
  tasks, phases, coordination, snapshot_stale: snapshotStale });
@@ -1587,25 +1604,49 @@ async function readTodoStoreView(options = {}) {
1587
1604
  };
1588
1605
  }
1589
1606
 
1607
+ /** The plan's other retained versions, by plan digest (unreadable ones are skipped). */
1608
+ async function retainedPlanVersions(repoRoot, activePlan) {
1609
+ const base = `${STORE_ROOT_REF}/plans/${activePlan.plan_key}`;
1610
+ const byDigest = new Map();
1611
+ let names = [];
1612
+ try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1613
+ for (const version of names) {
1614
+ if (version === activePlan.plan_version || !isTodoIdentifier(version)) continue;
1615
+ const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1616
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1617
+ }).catch(() => null);
1618
+ if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1619
+ }
1620
+ return byDigest;
1621
+ }
1622
+
1623
+ /**
1624
+ * a35: the coordination declaration belongs to the plan, not to one version (ADR 0160 Decision 2).
1625
+ * A revision starts an empty plan-scoped chain, so a version that has not declared its own reads the
1626
+ * newest declaration along its retained predecessors. Read only: nothing is copied into the new chain.
1627
+ * An unreadable predecessor ends the walk as undeclared, which is what the version showed before a35.
1628
+ */
1629
+ async function inheritedTodoCoordination(repoRoot, plan) {
1630
+ if (!plan.predecessor_plan_digest) return null;
1631
+ const byDigest = await retainedPlanVersions(repoRoot, plan);
1632
+ for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < byDigest.size; steps += 1) {
1633
+ const predecessor = byDigest.get(digest);
1634
+ if (predecessor === undefined) return null;
1635
+ const chain = await readPlanScopedJournal(repoRoot, predecessor.journalRef).catch(() => null);
1636
+ if (chain === null) return null;
1637
+ const declared = projectTodoCoordination(chain.events);
1638
+ if (declared !== null) return declared;
1639
+ digest = predecessor.plan.predecessor_plan_digest;
1640
+ }
1641
+ return null;
1642
+ }
1643
+
1590
1644
  /**
1591
1645
  * Composes the source plan's recorded task migrations back to the version whose topology the
1592
1646
  * connection names (u03): returns the source task id it maps to now, 'removed', or null (unknown).
1593
1647
  */
1594
1648
  async function carriedSourceTask(repoRoot, source, ref, versionsCache) {
1595
- if (!versionsCache.has(source)) {
1596
- const base = `${STORE_ROOT_REF}/plans/${source.plan.plan_key}`;
1597
- const byDigest = new Map();
1598
- let names = [];
1599
- try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1600
- for (const version of names) {
1601
- if (version === source.plan.plan_version || !isTodoIdentifier(version)) continue;
1602
- const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1603
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1604
- }).catch(() => null);
1605
- if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1606
- }
1607
- versionsCache.set(source, byDigest);
1608
- }
1649
+ if (!versionsCache.has(source)) versionsCache.set(source, await retainedPlanVersions(repoRoot, source.plan));
1609
1650
  const byDigest = versionsCache.get(source);
1610
1651
  // Newest first: the active genesis maps its predecessor's ids onto the active ids.
1611
1652
  const migrations = [source.journal.events[0].payload.task_migration ?? []];
@@ -1698,7 +1739,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1698
1739
  if (target.plan_scoped.events.length === owner.plan_scoped.events.length) continue;
1699
1740
  await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), target.plan_scoped.activeBytes);
1700
1741
  owner.plan_scoped = target.plan_scoped;
1701
- owner.coordination = projectTodoCoordination(target.plan_scoped.events);
1742
+ owner.coordination = projectTodoCoordination(target.plan_scoped.events) ?? owner.coordination;
1702
1743
  }
1703
1744
  store.cross_plan_findings = findings;
1704
1745
  return repairs;
@@ -2165,6 +2206,13 @@ function resolveTargetedEvent(input, storeMember) {
2165
2206
  if (input.kind === 'reopen' && exactRecord(input.payload, [
2166
2207
  'reason', 'override_reason',
2167
2208
  ])) {
2209
+ // a32: only a done task reopens; any other state is the seat's order, not a damaged store.
2210
+ const status = storeMember.tasks?.find(({ task_id: id }) => id === input.task_id)?.status;
2211
+ if (status !== undefined && status !== 'done') {
2212
+ fail('TODO_TRANSITION_REFUSED', 'invalid_reopen_transition', {
2213
+ cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id,
2214
+ ...(status === 'in-progress' ? { opened_by: todoOpenedBy(storeMember, input.task_id) } : {}) });
2215
+ }
2168
2216
  const targetDigest = resolveDoneBindingDigest(storeMember, input.task_id);
2169
2217
  if (targetDigest === null) fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
2170
2218
  return {
@@ -2395,7 +2443,7 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2395
2443
  return {
2396
2444
  event, plan: member.plan, snapshot: member.snapshot,
2397
2445
  plan_scoped_head_digest: event.event_digest,
2398
- coordination: projectTodoCoordination(events),
2446
+ coordination: projectTodoCoordination(events) ?? member.coordination ?? null,
2399
2447
  };
2400
2448
  }
2401
2449