@quolu/lattice 0.85.3 → 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/bin/lattice.mjs CHANGED
@@ -48,8 +48,9 @@ if (help !== null) {
48
48
  } else if (args[0] === 'plan' && args[1] === 'create'
49
49
  && args[2] !== '--schema' && args[2] !== '--schema-version' && args[2] !== '--template') {
50
50
  const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
51
- const spec = { known: ['input', 'serialization-reviewed'], required: ['input'],
52
- booleans: ['serialization-reviewed'] };
51
+ // --json is a no-op on this write: its output is JSON either way (a37).
52
+ const spec = { known: ['input', 'serialization-reviewed', 'json'], required: ['input'],
53
+ booleans: ['serialization-reviewed', 'json'] };
53
54
  const flags = matchFlagCommand(args, ['plan', 'create'], spec);
54
55
  if (flags === null) {
55
56
  // usage違反も欄(flag)・規則・直し方を返す(u05)。受け取った引数もdetailに残す。
@@ -111,7 +112,8 @@ if (help !== null) {
111
112
  const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
112
113
  const spec = { known: ['plan-input', 'review', 'json'], required: ['plan-input', 'review'], booleans: ['json'] };
113
114
  const flags = matchFlagCommand(args, ['plan', 'scope-review'], spec);
114
- if (flags === null || flags.json !== true) {
115
+ // --json is optional: the output is JSON either way (a37).
116
+ if (flags === null) {
115
117
  const { planArgumentFailure } = await import('../src/project-cli.mjs');
116
118
  process.exitCode = planArgumentFailure(process.stderr, args, spec);
117
119
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.85.3",
3
+ "version": "0.85.4",
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
@@ -113,6 +113,9 @@ Write commands:
113
113
  # readyならflagなしで着手する。flagの順は問わない。
114
114
  # --parallel-frontierと--override-reasonは方針・理由の記録。
115
115
  # --serial-confirmedは互換のため受理する。いずれも門ではない
116
+ retract --plan <key> --task <id> --reason <text>
117
+ # 自分の席が記録したstartを取り消してpendingへ戻す。reopenやimportで開いた工程には
118
+ # 取り消すstartが無いので、doneで閉じる
116
119
  block --plan <key> --task <id> --reason <text>
117
120
  unblock --plan <key> --task <id>
118
121
  retire --plan <key> --task <id> --reason <text>
@@ -2,6 +2,8 @@
2
2
  // (next_action) in one detail. Pure: reads only the error and the CLI context, no I/O.
3
3
  // Refusal sites keep their own keys; this fills the three keys the seat contract requires.
4
4
 
5
+ import { auditPendingNextCommands, isAuditPendingPhaseStatus } from './todo-audit-pending.mjs';
6
+
5
7
  const PLACEHOLDER = /^[a-z_]+$/u;
6
8
  // a27: one placeholder per flag for every missing-flag text (plan and todo alike).
7
9
  export const FLAG_PLACEHOLDER = Object.freeze({
@@ -35,15 +37,38 @@ const unfinishedFirst = (detail, ctx) => {
35
37
  blocked: `Unblock ${name} with \`lattice todo unblock ${on}\`, then record done on it`,
36
38
  })[first.status] ?? `Record done on ${name} first with \`lattice todo done ${on} --message <text>\` (see \`lattice todo show ${on} --json\`)`;
37
39
  };
40
+ // a36: a start without LATTICE_SEAT_ID is recorded under the OS user; after the seat sets its id that
41
+ // start looks like another seat's. Say so and give the seat contract's one-time fix.
42
+ const inProgressHolder = (detail, ctx, on) => {
43
+ const holder = typeof detail.started_by === 'string' ? detail.started_by : null;
44
+ const actors = record(ctx.actors) ? ctx.actors : {};
45
+ if (holder !== null && holder === actors.anonymous && holder !== actors.agent) {
46
+ return `It is in-progress under '${holder}', the name a start gets without LATTICE_SEAT_ID: most likely this seat's own`
47
+ + ` start from before it set LATTICE_SEAT_ID. One-time fix (seat contract): with LATTICE_SEAT_ID unset, undo that start`
48
+ + ` with \`lattice todo retract ${on} --reason <text>\` and start it again here, or finish it there first with`
49
+ + ` \`lattice todo done ${on} --message <text>\`.`;
50
+ }
51
+ return `It is already in-progress under ${holder === null ? 'another seat' : `seat '${holder}'`}; see \`${showTask(detail, ctx)}\`.`
52
+ + ` To move it to this seat run \`lattice todo start ${on} --rebind --reason <text>\`.`;
53
+ };
38
54
  const startState = (detail, ctx) => {
39
55
  const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
40
56
  return ({
41
57
  blocked: `It is blocked: run \`lattice todo unblock ${on}\`; that resumes it (no start needed).`,
42
58
  done: `It is done: to work on it again run \`lattice todo reopen ${on} --reason <text>\`.`,
43
- 'in-progress': `It is already in-progress under another seat; see \`${showTask(detail, ctx)}\`.`,
59
+ 'in-progress': inProgressHolder(detail, ctx, on),
44
60
  retired: `It is retired, which is permanent; see \`${showTask(detail, ctx)}\`.`,
45
61
  })[detail.status] ?? `Only a pending task can start; check its status with \`${showTask(detail, ctx)}\`.`;
46
62
  };
63
+ // a35: done needs in-progress; the way there depends on where the task is now (start cannot leave retired).
64
+ const doneState = (detail, ctx) => {
65
+ const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
66
+ return ({
67
+ blocked: `It is blocked: run \`lattice todo unblock ${on}\` (it resumes in-progress), then done.`,
68
+ retired: `${planOf(detail, ctx)}/${taskOf(detail, ctx)} is retired, which is permanent: it cannot be started or finished. `
69
+ + 'If the work is still needed, add it as a new task with `lattice plan revise --input <file>`.',
70
+ })[detail.status] ?? `It must be in-progress: run \`${startTask(detail, ctx)}\` first.`;
71
+ };
47
72
  const cyclePath = (detail) => (Array.isArray(detail.cycle)
48
73
  ? detail.cycle.filter(record).map((node) => `${node.plan_key}/${node.task_id ?? `phase:${node.phase_id}`}`).join(' -> ')
49
74
  : null);
@@ -67,6 +92,16 @@ const dependencyExists = {
67
92
  };
68
93
 
69
94
  /** The flag that carried the unreadable input: the one whose value is the refused path. */
95
+ const OPENED_BY_TEXT = Object.freeze({
96
+ reopen: ' because it was reopened', historical_import: ' from a historical import',
97
+ start: ' from a start',
98
+ });
99
+ /** a35: why an in-progress task is open, as a clause ('' when the store did not say). */
100
+ function openedByText(detail) {
101
+ return Object.hasOwn(OPENED_BY_TEXT, detail.opened_by ?? '') ? OPENED_BY_TEXT[detail.opened_by]
102
+ : detail.opened_by === null ? ' with no start recorded in this plan version' : '';
103
+ }
104
+
70
105
  function inputFlag(detail, ctx) {
71
106
  const flags = record(ctx.flags) ? ctx.flags : {};
72
107
  const byValue = Object.keys(flags).find((name) => flags[name] === detail.input_ref);
@@ -172,7 +207,7 @@ const REGISTRY = {
172
207
  repair: (detail, ctx) => ({
173
208
  predecessor_unfinished: `${unfinishedFirst(detail, ctx)}.`,
174
209
  acceptance_edge: phaseAcceptFirst(detail, ctx),
175
- task_state: `It must be in-progress: run \`${startTask(detail, ctx)}\` first.`,
210
+ task_state: doneState(detail, ctx),
176
211
  })[detail.cause] ?? `Check the task state with \`${showTask(detail, ctx)}\`, then rerun.`,
177
212
  },
178
213
  invalid_start_transition: {
@@ -194,13 +229,44 @@ const REGISTRY = {
194
229
  repair: (detail, ctx) => {
195
230
  const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
196
231
  return `Only a done task can be reopened; ${planOf(detail, ctx)}/${taskOf(detail, ctx)} is ${detail.status ?? 'not done'}. ` + ({
197
- 'in-progress': `It is still open: finish it with \`lattice todo done ${on}\`, or undo the start with \`lattice todo retract ${on} --reason <text>\`.`,
232
+ // a35: retract undoes only an authored start; a reopened task has none.
233
+ 'in-progress': detail.opened_by === 'start'
234
+ ? `It is still open: finish it with \`lattice todo done ${on}\`, or undo the start with \`lattice todo retract ${on} --reason <text>\`.`
235
+ : `It is still open${openedByText(detail)}: finish it with \`lattice todo done ${on}\`.`,
198
236
  pending: `It has not started: run \`lattice todo start ${on}\`.`,
199
237
  blocked: `It is blocked: resume it with \`lattice todo unblock ${on}\`.`,
200
238
  retired: `Retire is permanent, so it stays closed; see \`${showTask(detail, ctx)}\`.`,
201
239
  }[detail.status] ?? `Check its state with \`${showTask(detail, ctx)}\`.`);
202
240
  },
203
241
  },
242
+ phase_gate_not_ready: {
243
+ // a36: review and close-unaudited need gate_ready; name the phase state and the step that fits it.
244
+ repair: (detail, ctx) => {
245
+ const phase = detail.phase_id ?? ctx.flags?.phase ?? '<phase>';
246
+ const plan = planOf(detail, ctx);
247
+ const on = `--plan ${plan} --phase ${phase}`;
248
+ const status = detail.phase_status;
249
+ const head = `Phase ${plan}/${phase} is ${status ?? 'not gate_ready'}; review and close-unaudited need gate_ready. `;
250
+ if (isAuditPendingPhaseStatus(status) && status !== 'gate_ready') {
251
+ const [first, second] = auditPendingNextCommands(plan, phase, status, strings(detail.required_evidence_slots).length || 1);
252
+ return head + (status === 'reviewing'
253
+ ? `It is already in review: decide it with \`${first}\`, or \`${second}\`.`
254
+ : `Its review was rejected: run \`${first}\`, then review it again.`);
255
+ }
256
+ return head + ({
257
+ active: `Not all of its tasks are done: record done on them (\`lattice todo status --json\` lists them), then rerun.`,
258
+ locked: `Its predecessor phases are not accepted yet; see \`lattice todo phase status --plan ${plan}\`.`,
259
+ accepted: `It is already decided; to audit it again run \`lattice todo phase reopen ${on} --reason <text>\` first.`,
260
+ closed_unaudited: `It is already closed; to audit it run \`lattice todo phase reopen ${on} --reason <text>\` first.`,
261
+ }[status] ?? `See \`lattice todo phase status --plan ${plan}\`.`);
262
+ },
263
+ },
264
+ authored_start_binding_missing: {
265
+ // a35: say why there is nothing to retract and the step that closes the task instead.
266
+ repair: (detail, ctx) => `retract undoes only a start recorded by \`lattice todo start\`; `
267
+ + `${planOf(detail, ctx)}/${taskOf(detail, ctx)} is in progress${openedByText(detail)}, so there is no start to undo. `
268
+ + `Finish it with \`lattice todo done --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}\`.`,
269
+ },
204
270
  reopen_has_started_successor: {
205
271
  repair: (detail, ctx) => `A successor of ${taskOf(detail, ctx)} has already started: to reopen it anyway run \`lattice todo reopen --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)} --reason <text> --override-reason <text>\`.`,
206
272
  },
@@ -581,6 +581,47 @@ export function compileRuntimePlanV1(options = {}) {
581
581
  }
582
582
  if (ambiguous.length > 0) return nonDispatchable('QUERY_DRIFT', { ambiguous_targets: ambiguous });
583
583
 
584
+ // observation set resources。
585
+ const resources = [];
586
+ for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
587
+ const coveringQueryId = coveringByTarget.get(key);
588
+ if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
589
+ const outcome = outcomeByQueryId.get(coveringQueryId);
590
+ // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
591
+ let representative;
592
+ for (const todoId of group.todoIds) {
593
+ representative = bindingsByTodo.get(todoId).find((entry) => (
594
+ entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
595
+ ));
596
+ if (representative !== undefined) break;
597
+ }
598
+ if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
599
+ if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
600
+ const status = statusOutcome.status !== 'ready'
601
+ ? statusOutcome.status
602
+ : resolveBindingStatus(representative, outcome);
603
+ resources.push({
604
+ resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
605
+ kind: group.own.kind,
606
+ target: group.own.target,
607
+ todo_ids: [...group.todoIds].sort(compareText),
608
+ provenance: [
609
+ {
610
+ source: 'sensor',
611
+ evidence_ref: coveringQueryId,
612
+ evidence_digest: outcome.portable_digest,
613
+ status,
614
+ },
615
+ candidateProvenance(request),
616
+ ],
617
+ });
618
+ }
619
+
620
+ const ownResourceCovers = (target, leftId, rightId) => resources.some((resource) => (
621
+ resource.kind === 'path' && resource.target === target
622
+ && resource.todo_ids.includes(leftId) && resource.todo_ids.includes(rightId)
623
+ ));
624
+
584
625
  // 最新契約ではwrite scopeは予測である。既知の交差はserial conflictへ使うが、
585
626
  // 予測が足りないこと自体はunknownへ落とさない。
586
627
  const predictedWriteGroups = [];
@@ -588,15 +629,13 @@ export function compileRuntimePlanV1(options = {}) {
588
629
  for (let right = left + 1; right < todoIds.length; right += 1) {
589
630
  const leftWitness = request.manual_witness[todoIds[left]];
590
631
  const rightWitness = request.manual_witness[todoIds[right]];
591
- const leftOwnPaths = new Set(leftWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
592
- const rightOwnPaths = new Set(rightWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
593
632
  for (const leftPath of leftWitness.writes) {
594
633
  for (const rightPath of rightWitness.writes) {
595
634
  if (!pathPrefixOverlap(leftPath, rightPath)) continue;
596
- // 同一targetを両者がownsで所有主張している場合はwrite conflictとして
597
- // resource経由で扱われる。owns解決のない交差だけをunknownにする。
598
- if (leftOwnPaths.has(leftPath) && rightOwnPaths.has(rightPath)
599
- && leftPath === rightPath) continue;
635
+ // 同一targetを両者がownsで所有主張し、そのowns resourceが実際に両者を含む時だけ
636
+ // write conflictはresource経由で扱われる。予測契約では裏付けの無いownsはresourceに
637
+ // ならないので、ここで飛ばすと衝突が消える(a35、主張4)。
638
+ if (leftPath === rightPath && ownResourceCovers(leftPath, todoIds[left], todoIds[right])) continue;
600
639
  if (predictionsOnly) {
601
640
  predictedWriteGroups.push({
602
641
  target: [leftPath, rightPath].sort(compareText).join(' ↔ '),
@@ -683,42 +722,6 @@ export function compileRuntimePlanV1(options = {}) {
683
722
  }
684
723
  }
685
724
 
686
- // observation set resources。
687
- const resources = [];
688
- for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
689
- const coveringQueryId = coveringByTarget.get(key);
690
- if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
691
- const outcome = outcomeByQueryId.get(coveringQueryId);
692
- // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
693
- let representative;
694
- for (const todoId of group.todoIds) {
695
- representative = bindingsByTodo.get(todoId).find((entry) => (
696
- entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
697
- ));
698
- if (representative !== undefined) break;
699
- }
700
- if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
701
- if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
702
- const status = statusOutcome.status !== 'ready'
703
- ? statusOutcome.status
704
- : resolveBindingStatus(representative, outcome);
705
- resources.push({
706
- resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
707
- kind: group.own.kind,
708
- target: group.own.target,
709
- todo_ids: [...group.todoIds].sort(compareText),
710
- provenance: [
711
- {
712
- source: 'sensor',
713
- evidence_ref: coveringQueryId,
714
- evidence_digest: outcome.portable_digest,
715
- status,
716
- },
717
- candidateProvenance(request),
718
- ],
719
- });
720
- }
721
-
722
725
  const stateGroups = new Map();
723
726
  for (const todoId of todoIds) {
724
727
  for (const entry of request.manual_witness[todoId].state_effects) {
@@ -38,9 +38,11 @@ export function isAuditPendingPhaseStatus(status) {
38
38
  * 監査待ちでない状態を渡すのは呼び出し側の誤りなので、空配列へ丸めずに投げる。
39
39
  * 呼ぶ前に`isAuditPendingPhaseStatus`で絞ること。
40
40
  *
41
+ * `slotCount`は必須evidence slotの数。1つなら`--evidence`で足り、複数なら`--input`が要る。
42
+ *
41
43
  * @returns {string[]} 実行可能なコマンド行(1つ以上)
42
44
  */
43
- export function auditPendingNextCommands(planKey, phaseId, status) {
45
+ export function auditPendingNextCommands(planKey, phaseId, status, slotCount = 1) {
44
46
  const target = `--plan ${planKey} --phase ${phaseId}`;
45
47
  if (status === 'gate_ready') {
46
48
  return [
@@ -50,8 +52,9 @@ export function auditPendingNextCommands(planKey, phaseId, status) {
50
52
  }
51
53
  if (status === 'reviewing') {
52
54
  return [
53
- `lattice todo phase accept ${target} --input <file>`,
54
- `lattice todo phase reject ${target} --input <file>`,
55
+ // a36: --evidence fills the decision from one committed file; several slots need --input.
56
+ `lattice todo phase accept ${target} ${slotCount === 1 ? '--evidence <file>' : '--input <file>'}`,
57
+ `lattice todo phase reject ${target} --reason <text> --evidence <file>`,
55
58
  ];
56
59
  }
57
60
  if (status === 'rejected') {
@@ -36,6 +36,15 @@ function seatAgent(env) {
36
36
  return isTodoIdentifier(seat_id) ? seat_id : null;
37
37
  }
38
38
 
39
+ const anonymousAgent = (env) => (isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
40
+ ? env.LATTICE_TODO_ACTOR_AGENT : sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'));
41
+
42
+ /** a36: the agent this env writes now, and the one it wrote before setting LATTICE_SEAT_ID. No I/O. */
43
+ export function todoActorAgents(env) {
44
+ const anonymous = anonymousAgent(env);
45
+ return { agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT) ? anonymous : seatAgent(env) ?? anonymous, anonymous };
46
+ }
47
+
39
48
  // u03s A57: a set but non-identifier value is treated like an unset one (no refusal).
40
49
  export function resolveTodoActor(env) {
41
50
  return {
@@ -46,9 +55,7 @@ export function resolveTodoActor(env) {
46
55
  ? env.LATTICE_TODO_ACTOR_SESSION
47
56
  : 'session',
48
57
  // Seats on one machine share USER; the seat id keeps their `own` tasks apart (seat-contract).
49
- agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
50
- ? env.LATTICE_TODO_ACTOR_AGENT
51
- : seatAgent(env) ?? sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'),
58
+ agent: todoActorAgents(env).agent,
52
59
  };
53
60
  }
54
61
 
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 {
@@ -248,7 +250,7 @@ function typedFailure(stderr, error, context = {}) {
248
250
  }
249
251
 
250
252
  /** What the printers need to name a concrete repair: the command and the --plan/--task the caller typed. */
251
- function guidanceContext(argv) {
253
+ function guidanceContext(argv, env = {}) {
252
254
  const { flags } = parseFlagMap(argv.slice(1));
253
255
  return {
254
256
  family: 'todo',
@@ -256,6 +258,8 @@ function guidanceContext(argv) {
256
258
  plan: typeof flags.plan === 'string' ? flags.plan : undefined,
257
259
  task: typeof flags.task === 'string' ? flags.task : undefined,
258
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),
259
263
  };
260
264
  }
261
265
 
@@ -848,7 +852,17 @@ async function readStructureSetDraft(repoRoot, inputRef) {
848
852
  function auditGateGuidance(planKey, phaseId) {
849
853
  const target = `--plan ${planKey} --phase ${phaseId}`;
850
854
  return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
851
- + `(監査するなら 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}`;
852
866
  }
853
867
 
854
868
  /**
@@ -983,6 +997,28 @@ async function mutate({
983
997
  return result;
984
998
  }
985
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
+
986
1022
  /**
987
1023
  * 恒久除去(u12)。どの状態からでも`{reason, prior_status}`で閉じる。
988
1024
  * in-progressは、最新のauthored startに束ねられた未acceptのintakeをRuntimeの解放手順で
@@ -1811,7 +1847,8 @@ async function phaseStatus({ repoRoot, planKey }) {
1811
1847
  ...(structureFinalization.required && structureFinalization.status !== 'fresh'
1812
1848
  ? [`構造finalizationが${structureFinalization.status}です。先に lattice todo structure finalize --plan ${member.plan.plan_key} --json を実行してください。`]
1813
1849
  : []),
1814
- ].join('\n') : null,
1850
+ ].join('\n')
1851
+ : ['reviewing', 'rejected'].includes(phase.status) ? auditDecisionGuidance(member.plan, phase) : null,
1815
1852
  }));
1816
1853
  const result = {
1817
1854
  schema: 'lattice.phase_status_result.v2', project_id: store.project_id,
@@ -3202,7 +3239,9 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3202
3239
  {
3203
3240
  plan_key: planKey,
3204
3241
  missing_task_ids: missingReady,
3205
- 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.',
3206
3245
  },
3207
3246
  );
3208
3247
  }
@@ -3532,7 +3571,9 @@ async function witnessDraftTemplateFor({ repoRoot, planKey }) {
3532
3571
  const store = await readTodoStore({ repoRoot });
3533
3572
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3534
3573
  if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
3535
- return witnessDraftTemplate({ projectId: member.plan.project_id, 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,
3536
3577
  taskIds: member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id) });
3537
3578
  }
3538
3579
 
@@ -4292,7 +4333,7 @@ function writesTodoStore(argv) {
4292
4333
  case 'note': return second !== 'list';
4293
4334
  case 'migrate': return !argv.includes('--dry-run');
4294
4335
  case 'snapshot': return argv.includes('--rebuild');
4295
- case 'independence': return second === 'compile'
4336
+ case 'independence': return second === 'compile' || second === 'mode'
4296
4337
  || (second === 'witness' && ['migrate', 'scaffold'].includes(third) && !argv.includes('--template'));
4297
4338
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4298
4339
  || (second === 'input' && !argv.includes('--dry-run'));
@@ -4917,14 +4958,12 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4917
4958
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4918
4959
  && (flags['override-reason'] === undefined
4919
4960
  || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0))) {
4920
- action = (repoRoot) => mutate({
4961
+ action = (repoRoot) => reopenTask({
4921
4962
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4922
- kind: 'reopen',
4923
4963
  payload: {
4924
4964
  reason: flags.reason,
4925
4965
  override_reason: typeof flags['override-reason'] === 'string' ? flags['override-reason'] : null,
4926
4966
  },
4927
- evidenceRef: null,
4928
4967
  });
4929
4968
  }
4930
4969
  }
@@ -4973,7 +5012,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4973
5012
  } catch (error) {
4974
5013
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
4975
5014
  && error.detail !== null && typeof error.detail === 'object')) {
4976
- return typedFailure(stderr, error, guidanceContext(argv));
5015
+ return typedFailure(stderr, error, guidanceContext(argv, env));
4977
5016
  }
4978
5017
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
4979
5018
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {
@@ -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;
@@ -2169,7 +2210,8 @@ function resolveTargetedEvent(input, storeMember) {
2169
2210
  const status = storeMember.tasks?.find(({ task_id: id }) => id === input.task_id)?.status;
2170
2211
  if (status !== undefined && status !== 'done') {
2171
2212
  fail('TODO_TRANSITION_REFUSED', 'invalid_reopen_transition', {
2172
- cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id });
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) } : {}) });
2173
2215
  }
2174
2216
  const targetDigest = resolveDoneBindingDigest(storeMember, input.task_id);
2175
2217
  if (targetDigest === null) fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
@@ -2401,7 +2443,7 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2401
2443
  return {
2402
2444
  event, plan: member.plan, snapshot: member.snapshot,
2403
2445
  plan_scoped_head_digest: event.event_digest,
2404
- coordination: projectTodoCoordination(events),
2446
+ coordination: projectTodoCoordination(events) ?? member.coordination ?? null,
2405
2447
  };
2406
2448
  }
2407
2449
 
@@ -104,11 +104,31 @@ export function validateWitnessDraft(value) {
104
104
  return explainWitnessDraft(value).valid;
105
105
  }
106
106
 
107
- /** a32: the starting draft for a plan: every task still to do, with nothing declared yet. */
108
- export function witnessDraftTemplate({ projectId, planKey, taskIds }) {
107
+ /**
108
+ * a32: the starting draft for a plan: every task still to do.
109
+ * a35: a task the recorded witness set already declares starts from that declaration (the inverse of
110
+ * buildWitnessSet: owns back to draft entries, writes without the owned paths it adds), so adding one
111
+ * task after a revision does not mean rewriting the others.
112
+ */
113
+ export function witnessDraftTemplate({ projectId, planKey, taskIds, witnessSet = null }) {
114
+ const recorded = witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {};
115
+ const draftTask = (witness) => {
116
+ if (witness === undefined) return { owns: [], reads: [], writes: [] };
117
+ const owned = new Set(witness.owns.map(({ target }) => target));
118
+ return {
119
+ owns: witness.owns.map(({ target, creates }) => (creates ? { path: target, creates: true } : target)),
120
+ reads: [...witness.reads],
121
+ writes: witness.writes.filter((target) => !owned.has(target)),
122
+ ...(witness.unknowns.length > 0 ? { unknowns: witness.unknowns.map(({ kind, ref }) => ({ kind, ref })) } : {}),
123
+ ...(witness.concern_anchors?.length > 0 ? {
124
+ concern_anchors: witness.concern_anchors.map(({ within, symbols }) => ({ within: within.target, symbols: [...symbols] })),
125
+ } : {}),
126
+ };
127
+ };
109
128
  return {
110
- schema: WITNESS_DRAFT_SCHEMA_V2, project_id: projectId, plan_key: planKey, capacity: { executors: 1 },
111
- tasks: Object.fromEntries([...taskIds].sort(compareText).map((taskId) => [taskId, { owns: [], reads: [], writes: [] }])),
129
+ schema: WITNESS_DRAFT_SCHEMA_V2, project_id: projectId, plan_key: planKey,
130
+ capacity: { executors: witnessSet?.plan_key === planKey ? witnessSet.capacity.executors : 1 },
131
+ tasks: Object.fromEntries([...taskIds].sort(compareText).map((taskId) => [taskId, draftTask(recorded[taskId])])),
112
132
  };
113
133
  }
114
134