@quolu/lattice 0.85.3 → 0.85.5

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.5",
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
@@ -87,6 +87,8 @@ Read commands:
87
87
  show --plan <key> --task <id> --json # 個別ToDoと最新bounded note contextを追加操作なしで返す
88
88
  note list --plan <key> [--task <id>] --json # note全履歴の診断面(通常read/startでは不要)
89
89
  bindings [--plan <key>] [--json] # compile_binding付きTaskをTODO identityつきで投影する
90
+ display read [--json] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す
91
+ display source [--json] # 安い変更検知(lattice.todo_store_display_source.v1)。変わった時だけreadする
90
92
  independence [--plan <key>] [--json] # readyを検証済み並列・要直列・未検査へ分けて投影する
91
93
  structure --schema --json # plan定義後に入力する論理dataflow契約をstore非依存で返す
92
94
  structure [--plan <key>] --json # 保存済み構造をsensor再実行なしでfreshness・finding付き投影する
@@ -113,6 +115,9 @@ Write commands:
113
115
  # readyならflagなしで着手する。flagの順は問わない。
114
116
  # --parallel-frontierと--override-reasonは方針・理由の記録。
115
117
  # --serial-confirmedは互換のため受理する。いずれも門ではない
118
+ retract --plan <key> --task <id> --reason <text>
119
+ # 自分の席が記録したstartを取り消してpendingへ戻す。reopenやimportで開いた工程には
120
+ # 取り消すstartが無いので、doneで閉じる
116
121
  block --plan <key> --task <id> --reason <text>
117
122
  unblock --plan <key> --task <id>
118
123
  retire --plan <key> --task <id> --reason <text>
@@ -287,6 +292,9 @@ const SUBCOMMAND_USAGE = Object.freeze({
287
292
  'todo note': 'todo note --plan <key> [--task <id>] (--message <text>|--input <file>) | list --plan <key> [--task <id>] --json',
288
293
  'todo note list': 'todo note list --plan <key> [--task <id>] [--json]',
289
294
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
295
+ 'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
296
+ 'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
297
+ 'todo display source': 'todo display source [--json] # lattice.todo_store_display_source.v1(安い変更検知。変わった時だけreadする)',
290
298
  'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation> --reason <text>'
291
299
  + ' | compile --plan <key> --input <file> | compile --schema --json | witness migrate --plan <key>'
292
300
  + ' | witness scaffold --template --plan <key> [--json] | witness scaffold --schema --json | witness scaffold --plan <key> --input <draft>',
@@ -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) {
@@ -11,6 +11,8 @@ const CLAIM = /^([0-9a-f]{64})-([1-9][0-9]*)-([0-9a-f]{64})-([0-9a-f]{16})$/u;
11
11
  // its heartbeat mtime is older than LOCK_STALE_MS; every holder touches its lock and claim.
12
12
  export const LOCK_STALE_MS = 10 * 60_000;
13
13
  export const LOCK_HEARTBEAT_MS = 30_000;
14
+ // Several seats share one store: a writer waits out another live process this long, then refuses.
15
+ export const LOCK_WAIT_MS = 30_000;
14
16
  // Weak identity when own observation is unavailable: never PID-recovered, only heartbeat-stale.
15
17
  const WEAK = 'unobserved';
16
18
  const NO_HARD_LINK = ['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'];
@@ -167,10 +169,12 @@ async function recoveryClaim(claimsPath, owner, lockPath) {
167
169
  // Timestamp ordering could let a delayed earlier publisher enter twice.
168
170
  const candidates = await readdir(claimsPath);
169
171
  if (candidates.length === 1 && candidates[0] === name) return claimPath;
170
- throw new StoreLockError('store_locked', lockPath, {
172
+ const contended = new StoreLockError('store_locked', lockPath, {
171
173
  recovery_claims_path: claimsPath,
172
174
  next_action: `Retry after recovery claimants exit; for foreign or unidentified claims, confirm no writer on their recorded host before clearing only abandoned entries in ${claimsPath}`,
173
175
  });
176
+ contended.contended = true;
177
+ throw contended;
174
178
  } catch (error) {
175
179
  await rmdir(claimPath);
176
180
  throw error;
@@ -206,7 +210,7 @@ async function removeClaim(claimPath, claimsPath) {
206
210
 
207
211
  /** Complete ownership is linked atomically; recovery never removes a live owner. */
208
212
  export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath}.recovery`,
209
- onRecoveryClaim = null, createParent = true, releasePath = () => lockPath }, callback) {
213
+ onRecoveryClaim = null, createParent = true, releasePath = () => lockPath, waitMs = 0 }, callback) {
210
214
  if (createParent) await mkdir(path.dirname(lockPath), { recursive: true });
211
215
  ownStart ??= observeStartIdentityRaw(process.pid).catch((error) => { ownStart = undefined; throw error; });
212
216
  ownHost ??= observeProcessHostIdentityRaw().then((value) => {
@@ -259,6 +263,8 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
259
263
  fileIdentity = await handle.stat();
260
264
  }
261
265
  finally { await handle.close(); }
266
+ const deadline = Date.now() + waitMs;
267
+ let pause = 10;
262
268
  for (;;) {
263
269
  try { await link(temporary, lockPath); acquired = true; break; }
264
270
  catch (error) {
@@ -279,14 +285,33 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
279
285
  }
280
286
  const existing = await readOwner(lockPath);
281
287
  if (existing === null) continue;
282
- if (!await abandoned(existing, host)) throw busy(existing, lockPath);
288
+ const backOff = async (refusal) => {
289
+ if (Date.now() >= deadline) throw refusal;
290
+ await new Promise((resolve) => { setTimeout(resolve, pause + Math.random() * pause); });
291
+ pause = Math.min(pause * 2, 250);
292
+ };
293
+ // A live owner is waited out until the deadline. Our own PID (re-entry) would wait on
294
+ // ourselves, and an unidentified owner keeps its refusal, so both refuse at once.
295
+ const waitFor = async (live) => {
296
+ const self = live.owner?.pid === process.pid && live.owner?.host === host;
297
+ if (live.owner === null || self) throw busy(live, lockPath);
298
+ await backOff(busy(live, lockPath));
299
+ };
300
+ if (!await abandoned(existing, host)) { await waitFor(existing); continue; }
283
301
  if (claimPath === null) {
284
- claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath);
302
+ try { claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath); }
303
+ catch (error) {
304
+ // Several writers judged the same just-exited owner at once; none is sole, so all back off.
305
+ if (error?.contended !== true) throw error;
306
+ await backOff(error);
307
+ continue;
308
+ }
285
309
  if (onRecoveryClaim) await onRecoveryClaim();
286
310
  }
287
311
  const fresh = await readOwner(lockPath);
288
312
  if (fresh !== null) {
289
- if (!await abandoned(fresh, host)) throw busy(fresh, lockPath);
313
+ // The judged owner released and a new live writer linked in meanwhile.
314
+ if (!await abandoned(fresh, host)) { await waitFor(fresh); continue; }
290
315
  await removeJudged(lockPath, fresh.info);
291
316
  }
292
317
  }
@@ -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 {
@@ -85,6 +87,8 @@ import {
85
87
  readTodoWitnessSet,
86
88
  todoWitnessRef,
87
89
  writeTodoWitnessSet,
90
+ readTodoStoreDisplaySource,
91
+ readTodoStoreForDisplay,
88
92
  readTodoStoreStable,
89
93
  rebuildTodoSnapshot,
90
94
  writeTodoIndependenceArtifact,
@@ -248,7 +252,7 @@ function typedFailure(stderr, error, context = {}) {
248
252
  }
249
253
 
250
254
  /** What the printers need to name a concrete repair: the command and the --plan/--task the caller typed. */
251
- function guidanceContext(argv) {
255
+ function guidanceContext(argv, env = {}) {
252
256
  const { flags } = parseFlagMap(argv.slice(1));
253
257
  return {
254
258
  family: 'todo',
@@ -256,6 +260,8 @@ function guidanceContext(argv) {
256
260
  plan: typeof flags.plan === 'string' ? flags.plan : undefined,
257
261
  task: typeof flags.task === 'string' ? flags.task : undefined,
258
262
  flags,
263
+ // a36: who this seat is now and was before LATTICE_SEAT_ID, so a start refusal can name its own old start.
264
+ actors: todoActorAgents(env),
259
265
  };
260
266
  }
261
267
 
@@ -283,7 +289,7 @@ function internalFailure(stderr, error) {
283
289
  }
284
290
 
285
291
  const TODO_COMMAND_NAMES = Object.freeze([
286
- 'status', 'show', 'note', 'bindings', 'independence', 'structure', 'seam-profile', 'seam-proposal',
292
+ 'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
287
293
  'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
288
294
  'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
289
295
  'retract', 'dependency',
@@ -848,7 +854,17 @@ async function readStructureSetDraft(repoRoot, inputRef) {
848
854
  function auditGateGuidance(planKey, phaseId) {
849
855
  const target = `--plan ${planKey} --phase ${phaseId}`;
850
856
  return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
851
- + `(監査するなら lattice todo phase review ${target} --reason <text> → accept ${target} --input <file>)`;
857
+ + `(監査するなら lattice todo phase review ${target} --reason <text> → accept ${target} --evidence <file>)`;
858
+ }
859
+
860
+ /** a36: reviewing and rejected phases say their next command too (the same lines as audit_pending). */
861
+ function auditDecisionGuidance(plan, phase) {
862
+ const slots = todoPhaseDefinitions(plan).find(({ phase_id: id }) => id === phase.phase_id)
863
+ ?.required_evidence_slots.length ?? 1;
864
+ const [first, second] = auditPendingNextCommands(plan.plan_key, phase.phase_id, phase.status, slots);
865
+ return phase.status === 'reviewing'
866
+ ? `監査中(review済み)。受け入れるなら: ${first}(通らないなら: ${second})`
867
+ : `監査が通らなかった。やり直すなら: ${first}`;
852
868
  }
853
869
 
854
870
  /**
@@ -983,6 +999,28 @@ async function mutate({
983
999
  return result;
984
1000
  }
985
1001
 
1002
+ /**
1003
+ * a36: a reopened task stays in its last starter's `turn.own` (seat contract). When that is not
1004
+ * this seat, the result names the holder and the one command that moves the task here.
1005
+ */
1006
+ async function reopenTask({ repoRoot, env, planKey, taskId, payload }) {
1007
+ const result = await mutate({ repoRoot, env, planKey, taskId, kind: 'reopen', payload, evidenceRef: null });
1008
+ const store = await readTodoStore({ repoRoot });
1009
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === result.plan_key);
1010
+ const holder = member?.journal.events
1011
+ .findLast((event) => event.kind === 'start' && event.task_id === result.task_id)?.actor?.agent ?? null;
1012
+ if (holder === resolveTodoActor(env).agent) return result;
1013
+ const hinted = {
1014
+ ...result, started_by: holder,
1015
+ next_action: `${result.plan_key}/${result.task_id} is in-progress again under`
1016
+ + ` ${holder === null ? 'no seat (no start in this plan version)' : `seat '${holder}', which started it last`};`
1017
+ + ` to work on it from this seat run \`lattice todo start --plan ${result.plan_key} --task ${result.task_id} --rebind --reason <text>\`.`,
1018
+ result_digest: '',
1019
+ };
1020
+ hinted.result_digest = todoSelfDigest(hinted, 'result_digest');
1021
+ return hinted;
1022
+ }
1023
+
986
1024
  /**
987
1025
  * 恒久除去(u12)。どの状態からでも`{reason, prior_status}`で閉じる。
988
1026
  * in-progressは、最新のauthored startに束ねられた未acceptのintakeをRuntimeの解放手順で
@@ -1811,7 +1849,8 @@ async function phaseStatus({ repoRoot, planKey }) {
1811
1849
  ...(structureFinalization.required && structureFinalization.status !== 'fresh'
1812
1850
  ? [`構造finalizationが${structureFinalization.status}です。先に lattice todo structure finalize --plan ${member.plan.plan_key} --json を実行してください。`]
1813
1851
  : []),
1814
- ].join('\n') : null,
1852
+ ].join('\n')
1853
+ : ['reviewing', 'rejected'].includes(phase.status) ? auditDecisionGuidance(member.plan, phase) : null,
1815
1854
  }));
1816
1855
  const result = {
1817
1856
  schema: 'lattice.phase_status_result.v2', project_id: store.project_id,
@@ -3202,7 +3241,9 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3202
3241
  {
3203
3242
  plan_key: planKey,
3204
3243
  missing_task_ids: missingReady,
3205
- next_action: independenceCompileCommand(planKey),
3244
+ // a35: compiling the same set again cannot add them; the template keeps what is declared.
3245
+ next_action: `Declare ${missingReady.join(', ')} in the witness set. ${witnessRoute(planKey)}`
3246
+ + ' The template keeps the declarations already recorded, so only the new tasks need filling.',
3206
3247
  },
3207
3248
  );
3208
3249
  }
@@ -3532,7 +3573,9 @@ async function witnessDraftTemplateFor({ repoRoot, planKey }) {
3532
3573
  const store = await readTodoStore({ repoRoot });
3533
3574
  const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3534
3575
  if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
3535
- return witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
3576
+ // a35: start from what is already declared. An unreadable set only loses the prefill, not the template.
3577
+ const witnessSet = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
3578
+ return witnessDraftTemplate({ projectId: member.plan.project_id, planKey, witnessSet,
3536
3579
  taskIds: member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id) });
3537
3580
  }
3538
3581
 
@@ -4292,7 +4335,7 @@ function writesTodoStore(argv) {
4292
4335
  case 'note': return second !== 'list';
4293
4336
  case 'migrate': return !argv.includes('--dry-run');
4294
4337
  case 'snapshot': return argv.includes('--rebuild');
4295
- case 'independence': return second === 'compile'
4338
+ case 'independence': return second === 'compile' || second === 'mode'
4296
4339
  || (second === 'witness' && ['migrate', 'scaffold'].includes(third) && !argv.includes('--template'));
4297
4340
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4298
4341
  || (second === 'input' && !argv.includes('--dry-run'));
@@ -4592,6 +4635,12 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4592
4635
  && argv[1] === '--plan' && isTodoIdentifier(argv[2])
4593
4636
  && (argv.length === 3 || argv[3] === '--json')) {
4594
4637
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: argv[2] });
4638
+ } else if (argv[0] === 'display' && (argv[1] === 'read' || argv[1] === 'source')
4639
+ && (argv.length === 2 || (argv.length === 3 && argv[2] === '--json'))) {
4640
+ // Host display read (BellTeam module): a typed inconsistency is a state, never a refusal.
4641
+ action = argv[1] === 'read'
4642
+ ? async (repoRoot) => ({ schema: 'lattice.todo_display_read_result.v1', ...await readTodoStoreForDisplay({ repoRoot }) })
4643
+ : (repoRoot) => readTodoStoreDisplaySource({ repoRoot });
4595
4644
  } else if (argv[0] === 'note' && argv[1] !== 'list') {
4596
4645
  const flags = matchFlagCommand(argv, ['note'], NOTE_FLAG_SPEC);
4597
4646
  const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
@@ -4917,14 +4966,12 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4917
4966
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
4918
4967
  && (flags['override-reason'] === undefined
4919
4968
  || (typeof flags['override-reason'] === 'string' && flags['override-reason'].length > 0))) {
4920
- action = (repoRoot) => mutate({
4969
+ action = (repoRoot) => reopenTask({
4921
4970
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
4922
- kind: 'reopen',
4923
4971
  payload: {
4924
4972
  reason: flags.reason,
4925
4973
  override_reason: typeof flags['override-reason'] === 'string' ? flags['override-reason'] : null,
4926
4974
  },
4927
- evidenceRef: null,
4928
4975
  });
4929
4976
  }
4930
4977
  }
@@ -4973,7 +5020,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4973
5020
  } catch (error) {
4974
5021
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
4975
5022
  && error.detail !== null && typeof error.detail === 'object')) {
4976
- return typedFailure(stderr, error, guidanceContext(argv));
5023
+ return typedFailure(stderr, error, guidanceContext(argv, env));
4977
5024
  }
4978
5025
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
4979
5026
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {
@@ -4,7 +4,7 @@ import {
4
4
  lstat, mkdir, open, readFile, readdir, rename, rm, stat,
5
5
  } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { StoreLockError, withStoreLock } from './store-lock.mjs';
7
+ import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
8
8
  import { syncPublishedFile } from './fs-publish.mjs';
9
9
  import { normalizeCheckoutEol } from './todo-store-view.mjs';
10
10
 
@@ -236,7 +236,7 @@ async function withNoteLock(repoRoot, callback) {
236
236
  }
237
237
  }
238
238
  await ensureNoteDirectory(root);
239
- return await withStoreLock({ lockPath: path.join(root, '.write.lock'), createParent: false }, callback);
239
+ return await withStoreLock({ lockPath: path.join(root, '.write.lock'), createParent: false, waitMs: LOCK_WAIT_MS }, callback);
240
240
  }
241
241
  catch (error) {
242
242
  if (error instanceof StoreLockError) {
@@ -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
  }
@@ -17,7 +17,7 @@ export {
17
17
  import { randomBytes } from 'node:crypto';
18
18
  import { fsyncDirectory } from './fs-dir-sync.mjs';
19
19
  import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
20
- import { StoreLockError, withStoreLock } from './store-lock.mjs';
20
+ import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
21
21
  import {
22
22
  lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
23
23
  } from 'node:fs/promises';
@@ -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;
@@ -2081,6 +2122,7 @@ async function withLock(repoRoot, callback, {
2081
2122
  return await withStoreLock({
2082
2123
  lockPath: path.join(repoRoot, STORE_ROOT_REF, '.write.lock'),
2083
2124
  createParent: initialize,
2125
+ waitMs: LOCK_WAIT_MS,
2084
2126
  recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
2085
2127
  onRecoveryClaim: typeof onProtocolStage === 'function'
2086
2128
  ? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
@@ -2169,7 +2211,8 @@ function resolveTargetedEvent(input, storeMember) {
2169
2211
  const status = storeMember.tasks?.find(({ task_id: id }) => id === input.task_id)?.status;
2170
2212
  if (status !== undefined && status !== 'done') {
2171
2213
  fail('TODO_TRANSITION_REFUSED', 'invalid_reopen_transition', {
2172
- cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id });
2214
+ cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id,
2215
+ ...(status === 'in-progress' ? { opened_by: todoOpenedBy(storeMember, input.task_id) } : {}) });
2173
2216
  }
2174
2217
  const targetDigest = resolveDoneBindingDigest(storeMember, input.task_id);
2175
2218
  if (targetDigest === null) fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
@@ -2401,7 +2444,7 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2401
2444
  return {
2402
2445
  event, plan: member.plan, snapshot: member.snapshot,
2403
2446
  plan_scoped_head_digest: event.event_digest,
2404
- coordination: projectTodoCoordination(events),
2447
+ coordination: projectTodoCoordination(events) ?? member.coordination ?? null,
2405
2448
  };
2406
2449
  }
2407
2450
 
@@ -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