@quolu/lattice 0.90.0 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.90.0",
3
+ "version": "0.92.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
package/src/cli-help.mjs CHANGED
@@ -103,6 +103,7 @@ Read commands:
103
103
 
104
104
  Write commands:
105
105
  notice ack --lane <lane> --notice <id>[,<id>...] [--json] # 届けた知らせに印を付ける(閉じた知らせはclosedで返す)
106
+ wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # 手を止めてこの工程を待つ印。着手できたら知らせにwaitingが載る(記録だけで、何も止めない)
106
107
  repair-eol --json # Git checkoutでCRLF化された既存storeをcanonical LFへ戻し、EOL保護を追加する
107
108
  dashboard adopt --json # 衝突したproject_idの配信元rootを現在repoへ明示的に移す
108
109
  dashboard ensure --json # daemon生存保証の冪等入口(launchd等の周期実行向け)
@@ -173,8 +174,8 @@ Write commands:
173
174
  # 実際に受理する最新契約のJSON Schemaを返す(storeを読まない)。
174
175
  # 入力が契約に合わないときは、違反フィールドのpathがerror detailへ載る
175
176
  phase review --plan <key> --phase <id> --reason <text>
176
- phase accept --plan <key> --phase <id> --evidence <file> # 監査fileから入力を機械が組む
177
- phase reject --plan <key> --phase <id> --reason <text> --evidence <file>
177
+ phase accept --plan <key> --phase <id> --evidence <file> | --message <text> # 監査file/文から入力を機械が組む
178
+ phase reject --plan <key> --phase <id> --reason <text> --evidence <file> | --message <text>
178
179
  phase <accept|reject> --plan <key> --phase <id> --input <file>
179
180
  phase reopen --plan <key> --phase <id> --reason <text> [--override-reason <text>]
180
181
  phase close-unaudited --plan <key> --phase <id> --reason <text>
@@ -304,6 +305,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
304
305
  'todo notice': 'todo notice list [--lane <lane>] [--include-acked] [--json] | ack --lane <lane> --notice <id>[,<id>...] [--json]',
305
306
  'todo notice list': 'todo notice list [--lane <lane>] [--include-acked] [--json] # lattice.todo_notice_list_result.v1',
306
307
  'todo notice ack': 'todo notice ack --lane <lane> --notice <id>[,<id>...] [--json] # lattice.todo_notice_ack_result.v1 {acked, already, closed}',
308
+ 'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # lattice.todo_wait_result.v1 {state: waiting|startable_now|not_pending|cancelled}',
307
309
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
308
310
  'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
309
311
  'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
@@ -329,8 +331,8 @@ const SUBCOMMAND_USAGE = Object.freeze({
329
331
  + ' | baseline --reason <text> [--except <plan_key>]...',
330
332
  'todo phase status': 'todo phase status --plan <key> [--json]',
331
333
  'todo phase review': 'todo phase review --plan <key> --phase <id> --reason <text>',
332
- 'todo phase accept': 'todo phase accept --plan <key> --phase <id> --evidence <file> | --input <file>',
333
- 'todo phase reject': 'todo phase reject --plan <key> --phase <id> --reason <text> --evidence <file> | --input <file>',
334
+ 'todo phase accept': 'todo phase accept --plan <key> --phase <id> --evidence <file> | --message <text> | --input <file>',
335
+ 'todo phase reject': 'todo phase reject --plan <key> --phase <id> --reason <text> --evidence <file> | --message <text> | --input <file>',
334
336
  'todo phase reopen': 'todo phase reopen --plan <key> --phase <id> --reason <text> [--override-reason <text>]',
335
337
  'todo phase close-unaudited': 'todo phase close-unaudited --plan <key> --phase <id> --reason <text>',
336
338
  'todo phase baseline': 'todo phase baseline --reason <text> [--except <plan_key>]...',
package/src/todo-cli.mjs CHANGED
@@ -169,8 +169,10 @@ import {
169
169
  } from './seam-proposal-contracts.mjs';
170
170
  import { compileSeamProposalArtifact, declaredConcernSymbols } from './seam-proposal.mjs';
171
171
  import { collectSensorEvidence } from './sensor-adapter.mjs';
172
- import { newTodoNotices, projectTodoNotices } from './todo-notices.mjs';
173
- import { ackTodoNotices, readAllTodoNoticeAcks, readTodoNoticeAcks } from './todo-notice-store.mjs';
172
+ import { newTodoNotices, projectTodoNotices, waitInEffect } from './todo-notices.mjs';
173
+ import {
174
+ ackTodoNotices, cancelTodoNoticeWait, readAllTodoNoticeAcks, readAllTodoNoticeWaits, readTodoNoticeAcks, writeTodoNoticeWait,
175
+ } from './todo-notice-store.mjs';
174
176
  import { collectTodoIndependenceAuthoritativeObservation } from './todo-independence-authoritative-observation.mjs';
175
177
  import { applySeamProposal } from './seam-apply.mjs';
176
178
  import { todoPlanPrecedences } from './seam-verification.mjs';
@@ -305,7 +307,7 @@ const TODO_COMMAND_NAMES = Object.freeze([
305
307
  'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
306
308
  'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
307
309
  'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
308
- 'retract', 'dependency', 'add', 'notice',
310
+ 'retract', 'dependency', 'add', 'notice', 'wait',
309
311
  ]);
310
312
 
311
313
  function typedArgumentFailure(stderr, code, message, detail, context = {}) {
@@ -354,8 +356,8 @@ const TODO_FLAG_SPECS = Object.freeze({
354
356
  split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
355
357
  note: NOTE_FLAG_SPEC,
356
358
  // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
357
- 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'input'], required: ['plan', 'phase'] }),
358
- 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'reason', 'input'], required: ['plan', 'phase'] }),
359
+ 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'input'], required: ['plan', 'phase'] }),
360
+ 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'reason', 'input'], required: ['plan', 'phase'] }),
359
361
  'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
360
362
  'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
361
363
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
@@ -366,6 +368,7 @@ const TODO_FLAG_SPECS = Object.freeze({
366
368
  show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
367
369
  'notice list': Object.freeze({ known: ['lane', 'include-acked', 'json'], required: [], booleans: ['include-acked', 'json'] }),
368
370
  'notice ack': Object.freeze({ known: ['lane', 'notice', 'json'], required: ['lane', 'notice'], booleans: ['json'] }),
371
+ wait: Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
369
372
  'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
370
373
  'phase status': Object.freeze({ known: ['plan', 'json'], required: ['plan'], booleans: ['json'] }),
371
374
  structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
@@ -489,18 +492,19 @@ function explainArgumentRefusal(argv) {
489
492
  }
490
493
  }
491
494
  if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
492
- const given = ['evidence', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
495
+ const given = ['evidence', 'message', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
493
496
  if (given.length === 0) {
494
497
  return { pointer: '--evidence', rule: 'flag_missing',
495
- next_action: `Add --evidence <file> (or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
498
+ next_action: `Add --evidence <file> (or --message <text>, or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
496
499
  }
497
- if (given.length === 2) {
498
- return { pointer: '--input', rule: 'flags_exclusive',
499
- next_action: `Pass either --evidence or --input, not both: \`${repairedCommand(head, spec, { ...flags, input: undefined })}\`.` };
500
+ if (given.length > 1) {
501
+ const [keep, drop] = given;
502
+ return { pointer: `--${drop}`, rule: 'flags_exclusive',
503
+ next_action: `Pass one of --evidence, --message or --input: \`${repairedCommand(head, spec, { ...flags, ...Object.fromEntries(given.filter((name) => name !== keep).map((name) => [name, undefined])) })}\`.` };
500
504
  }
501
- if (argv[1] === 'reject' && given[0] === 'evidence' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
505
+ if (argv[1] === 'reject' && given[0] !== 'input' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
502
506
  return { pointer: '--reason', rule: 'flag_missing',
503
- next_action: `A reject with --evidence needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
507
+ next_action: `A reject with --${given[0]} needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
504
508
  }
505
509
  if (given[0] === 'input' && flags.reason !== undefined) {
506
510
  return { pointer: '--reason', rule: 'flag_unknown',
@@ -876,8 +880,9 @@ async function readStructureSetDraft(repoRoot, inputRef) {
876
880
  function auditGateGuidance(planKey, phaseId, auditRequired = false) {
877
881
  const target = `--plan ${planKey} --phase ${phaseId}`;
878
882
  const audit = `lattice todo phase review ${target} --reason <text> → accept ${target} --evidence <file>`;
879
- // ADR 0200 gate 5: an enforced plan's heavy phase refuses close-unaudited, so only the audit is offered.
880
- if (auditRequired) return `全ToDoがdone。このplanはenforcedでheavyの段階なので監査する: ${audit}`;
883
+ // ADR 0200 gate 5: an enforced plan's heavy phase refuses close-unaudited, so only the audit is offered,
884
+ // with the --message route for a seat that cannot write a file into the Store root.
885
+ if (auditRequired) return `全ToDoがdone。このplanはenforcedでheavyの段階なので監査する: ${audit}(fileを置けないなら --message <text>)`;
881
886
  return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
882
887
  + `(監査するなら ${audit})`;
883
888
  }
@@ -1585,7 +1590,8 @@ const PHASE_DECISION_EXPECTED = Object.freeze({
1585
1590
  reject: '{ "schema": "lattice.phase_reject_input.v1", "review_event_digest": "<phase reviewのevent_digest>",'
1586
1591
  + ' "reason": "<text>", "decision_evidence": <evidence記述子>, "input_digest": "" }',
1587
1592
  note: 'input_digestは入口が計算する。証拠fileがcommit済みなら、`--evidence <file>`で'
1588
- + 'review_event_digest・記述子・必須slotを機械が埋める。evidence記述子の形はEVIDENCE_DESCRIPTOR_EXPECTEDを見る。',
1593
+ + 'review_event_digest・記述子・必須slotを機械が埋める。fileを置けないなら`--message <text>`でも同じく埋まる'
1594
+ + '(commitまではuncommitted)。evidence記述子の形はEVIDENCE_DESCRIPTOR_EXPECTEDを見る。',
1589
1595
  });
1590
1596
 
1591
1597
  async function phaseDecision({ repoRoot, env, planKey, phaseId, outcome, inputRef }) {
@@ -1622,7 +1628,9 @@ async function phaseDecision({ repoRoot, env, planKey, phaseId, outcome, inputRe
1622
1628
  * fileから作る。必須slotが1つならその証拠で埋める。複数slotへ1つの証拠を流用すると
1623
1629
  * 「各slotを別々に確かめた」ことを偽るので、その場合は`--input`で明示させる。
1624
1630
  */
1625
- async function phaseDecisionFromEvidence({ repoRoot, env, planKey, phaseId, outcome, evidenceRef, reason }) {
1631
+ async function phaseDecisionFromEvidence({
1632
+ repoRoot, env, planKey, phaseId, outcome, evidenceRef = null, evidenceMessage = null, reason,
1633
+ }) {
1626
1634
  const store = await readTodoStore({ repoRoot });
1627
1635
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
1628
1636
  if (member === undefined) {
@@ -1649,8 +1657,9 @@ async function phaseDecisionFromEvidence({ repoRoot, env, planKey, phaseId, outc
1649
1657
  next_action: `lattice todo phase accept --plan ${planKey} --phase ${phaseId} --input <file>`,
1650
1658
  });
1651
1659
  }
1660
+ // A --message becomes message evidence exactly as in `todo done`: no file inside the Store root is needed.
1652
1661
  const evidence = await resolveDoneEvidence({
1653
- repoRoot, evidenceRef, evidenceMessage: null, planKey, taskId: `${phaseId}-${outcome}`,
1662
+ repoRoot, evidenceRef, evidenceMessage, planKey, taskId: `${phaseId}-${outcome}`,
1654
1663
  });
1655
1664
  const payload = outcome === 'accept'
1656
1665
  ? { review_event_digest: state.review_event_digest, decision_evidence: evidence,
@@ -1659,6 +1668,12 @@ async function phaseDecisionFromEvidence({ repoRoot, env, planKey, phaseId, outc
1659
1668
  return phaseMutation({ repoRoot, env, planKey, phaseId, kind: `phase_${outcome}`, payload });
1660
1669
  }
1661
1670
 
1671
+ /** A phase decision's evidence: committed, uncommitted (no ref reaches it yet, e.g. `--message` on a root with no commit) or null. */
1672
+ function decisionEvidenceState(repoRoot, store, evidence) {
1673
+ if (evidence === null || evidence === undefined) return null;
1674
+ return isTodoEvidenceUncommitted({ repoRoot, store, evidence }) ? 'uncommitted' : 'committed';
1675
+ }
1676
+
1662
1677
  async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload }) {
1663
1678
  if (kind === 'phase_close_unaudited') {
1664
1679
  // ADR 0200 gate 5: an enforced plan keeps the audit its author required for a heavy phase.
@@ -1668,7 +1683,8 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1668
1683
  if (phaseAuditRequired(member, phase?.gate_policy)) {
1669
1684
  throw new TodoStoreError('TODO_TRANSITION_REFUSED', 'enforced_heavy_phase_unaudited', undefined, {
1670
1685
  plan_key: planKey, phase_id: phaseId,
1671
- next_action: `Audit it: \`lattice todo phase review --plan ${planKey} --phase ${phaseId} --reason <text>\` then \`lattice todo phase accept --plan ${planKey} --phase ${phaseId} --evidence <file>\`;`
1686
+ next_action: `Audit it: \`lattice todo phase review --plan ${planKey} --phase ${phaseId} --reason <text>\` then \`lattice todo phase accept --plan ${planKey} --phase ${phaseId} --evidence <file>\``
1687
+ + ` (or \`--message <text>\` when no file can be written into the Store root);`
1672
1688
  + ' or revise the phase to a non-heavy gate_policy with `lattice plan revise` (recorded).',
1673
1689
  });
1674
1690
  }
@@ -1687,7 +1703,10 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1687
1703
  plan_key: event.plan_key, plan_version: event.plan_version, phase_id: event.phase_id,
1688
1704
  kind: event.kind, sequence: event.sequence, event_digest: event.event_digest,
1689
1705
  journal_head_digest: event.event_digest, snapshot_digest: snapshot.snapshot_digest,
1690
- status: phase.status, result_digest: '',
1706
+ status: phase.status,
1707
+ decision_evidence_state: phase.decision_evidence === null || phase.decision_evidence === undefined ? null
1708
+ : decisionEvidenceState(repoRoot, await readTodoStore({ repoRoot }), phase.decision_evidence),
1709
+ result_digest: '',
1691
1710
  };
1692
1711
  result.result_digest = todoSelfDigest(result, 'result_digest');
1693
1712
  return result;
@@ -2017,6 +2036,7 @@ async function phaseStatus({ repoRoot, planKey }) {
2017
2036
  // v4/v5の実Phaseがgate_readyになった場合も同じ理由で同じ案内が要る。
2018
2037
  const phases = member.phases.map((phase) => ({
2019
2038
  ...phase,
2039
+ decision_evidence_state: decisionEvidenceState(repoRoot, store, phase.decision_evidence),
2020
2040
  acceptance_stale: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks),
2021
2041
  guidance: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks)
2022
2042
  ? staleAcceptanceGuidance(member.plan.plan_key, phase.phase_id)
@@ -4597,7 +4617,8 @@ function releasesTasks(argv) {
4597
4617
  || (command === 'dependency' && second === 'disconnect');
4598
4618
  }
4599
4619
 
4600
- async function openNotices(repoRoot) {
4620
+ /** Open notices with their waiters (wait-design); an unreadable wait file is named, its waits read as none. */
4621
+ async function openNoticeView(repoRoot) {
4601
4622
  const store = await readTodoStore({ repoRoot });
4602
4623
  const rows = new Map();
4603
4624
  for (const member of store.members) {
@@ -4605,16 +4626,57 @@ async function openNotices(repoRoot) {
4605
4626
  const recorded = await readTodoWitnessSet({ repoRoot, planKey: member.plan.plan_key }).catch(() => null);
4606
4627
  rows.set(member.plan.plan_key, new Set(Object.keys(recorded?.manual_witness ?? {})));
4607
4628
  }
4608
- return projectTodoNotices(store, { declared: (planKey, taskId) => rows.get(planKey)?.has(taskId) === true });
4629
+ const stored = await readAllTodoNoticeWaits({ repoRoot });
4630
+ // Readers return raw records: waits that ended since the file's last write are dropped here.
4631
+ const waits = stored.waits.flatMap((record) => record.waits.map((wait) => ({ plan_key: record.plan_key, ...wait })))
4632
+ .filter((wait) => waitInEffect(store, wait));
4633
+ const notices = projectTodoNotices(store, {
4634
+ declared: (planKey, taskId) => rows.get(planKey)?.has(taskId) === true, waits,
4635
+ });
4636
+ return { store, notices, waitUnreadable: stored.unreadable };
4637
+ }
4638
+
4639
+ async function openNotices(repoRoot) {
4640
+ return (await openNoticeView(repoRoot)).notices;
4609
4641
  }
4610
4642
 
4643
+ /** lane -> notice_id -> [{waiting_digest, recipients}] from ack set records. */
4644
+ function ackIndex(records) {
4645
+ const index = new Map();
4646
+ for (const record of records) {
4647
+ const byId = new Map();
4648
+ for (const ack of record.acks) byId.set(ack.notice_id, [...(byId.get(ack.notice_id) ?? []), ack]);
4649
+ index.set(record.lane, byId);
4650
+ }
4651
+ return index;
4652
+ }
4653
+
4654
+ /** Flora's amendment: who earlier acks of this notice_id covered, so a re-opened notice goes only to the rest. */
4655
+ function withAckState(notice, index) {
4656
+ const acks = index.get(notice.lane)?.get(notice.notice_id) ?? [];
4657
+ return {
4658
+ ...notice,
4659
+ acked_recipients: [...new Set(acks.flatMap(({ recipients }) => recipients))].sort(),
4660
+ acked: acks.some(({ waiting_digest: digest }) => digest === notice.waiting_digest),
4661
+ };
4662
+ }
4663
+
4664
+ const noticeRecipients = (notice) => [...new Set([notice.lane, ...notice.waiting.map(({ agent }) => agent)])].sort();
4665
+
4611
4666
  /** A committed write is never undone for its notices: an unreadable projection says so and `notice list` recovers. */
4612
4667
  async function withNotices(repoRoot, result, before) {
4613
4668
  if (result === null || typeof result !== 'object' || typeof result.result_digest !== 'string') return result;
4614
4669
  let extra;
4615
4670
  try {
4616
4671
  if (before === null) throw new Error('notices_before_unreadable');
4617
- extra = { notices: newTodoNotices(before, await openNotices(repoRoot)) };
4672
+ const released = newTodoNotices(before, await openNotices(repoRoot));
4673
+ // An unreadable ack set only means nobody counts as covered yet: delivery repeats, nothing is lost.
4674
+ const index = ackIndex(released.length === 0 ? []
4675
+ : await readAllTodoNoticeAcks({ repoRoot }).then(({ acks }) => acks, () => []));
4676
+ extra = { notices: released.map((notice) => {
4677
+ const { acked: _acked, ...rest } = withAckState(notice, index);
4678
+ return rest;
4679
+ }) };
4618
4680
  } catch (error) {
4619
4681
  extra = { notices: null, notices_unavailable: error?.detail?.reason ?? error?.message ?? 'notices_unreadable' };
4620
4682
  }
@@ -4634,27 +4696,28 @@ function noticeAckRefusal(error, lane) {
4634
4696
 
4635
4697
  /** `todo notice list`: open notices, unacked unless asked; one unreadable ack file never hides the rest. */
4636
4698
  async function noticeList({ repoRoot, lane, includeAcked }) {
4637
- const store = await readTodoStore({ repoRoot });
4638
- const open = (await openNotices(repoRoot)).filter((notice) => lane === null || notice.lane === lane);
4639
- const acked = new Map();
4699
+ const view = await openNoticeView(repoRoot);
4700
+ const open = view.notices.filter((notice) => lane === null || notice.lane === lane);
4701
+ const records = [];
4640
4702
  const ackUnreadable = [];
4641
4703
  if (lane === null) {
4642
4704
  const all = await readAllTodoNoticeAcks({ repoRoot });
4643
- for (const record of all.acks) acked.set(record.lane, new Set(record.acks.map(({ notice_id: id }) => id)));
4705
+ records.push(...all.acks);
4644
4706
  ackUnreadable.push(...all.unreadable);
4645
4707
  } else {
4646
4708
  try {
4647
4709
  const record = await readTodoNoticeAcks({ repoRoot, lane });
4648
- acked.set(lane, new Set((record?.acks ?? []).map(({ notice_id: id }) => id)));
4710
+ if (record !== null) records.push(record);
4649
4711
  } catch (error) {
4650
4712
  ackUnreadable.push(noticeAckRefusal(error, lane));
4651
4713
  }
4652
4714
  }
4653
- const notices = open.map((notice) => ({ ...notice, acked: acked.get(notice.lane)?.has(notice.notice_id) === true }))
4654
- .filter((notice) => includeAcked || !notice.acked);
4715
+ const index = ackIndex(records);
4716
+ // Acked iff (notice_id, waiting_digest) was acked: a wait added after an ack makes the notice unacked again.
4717
+ const notices = open.map((notice) => withAckState(notice, index)).filter((notice) => includeAcked || !notice.acked);
4655
4718
  const result = {
4656
- schema: 'lattice.todo_notice_list_result.v1', project_id: store.project_id, lane, notices,
4657
- ack_unreadable: ackUnreadable, result_digest: '',
4719
+ schema: 'lattice.todo_notice_list_result.v1', project_id: view.store.project_id, lane, notices,
4720
+ ack_unreadable: ackUnreadable, wait_unreadable: view.waitUnreadable, result_digest: '',
4658
4721
  };
4659
4722
  result.result_digest = todoSelfDigest(result, 'result_digest');
4660
4723
  return result;
@@ -4662,21 +4725,69 @@ async function noticeList({ repoRoot, lane, includeAcked }) {
4662
4725
 
4663
4726
  /** `todo notice ack`: an id that is no longer open is reported as closed, never refused (nothing is left to ack). */
4664
4727
  async function noticeAck({ repoRoot, env, lane, ids }) {
4665
- const store = await readTodoStore({ repoRoot });
4666
- const openIds = (await openNotices(repoRoot)).filter((notice) => notice.lane === lane).map(({ notice_id: id }) => id);
4728
+ const view = await openNoticeView(repoRoot);
4729
+ const laneNotices = view.notices.filter((notice) => notice.lane === lane);
4730
+ const openIds = laneNotices.map(({ notice_id: id }) => id);
4667
4731
  const open = new Set(openIds);
4668
- const live = ids.filter((id) => open.has(id));
4732
+ // The ack covers the notice as it is now: its waiter set (waiting_digest) and everyone it was delivered to.
4733
+ const live = laneNotices.filter(({ notice_id: id }) => ids.includes(id)).map((notice) => ({
4734
+ notice_id: notice.notice_id, waiting_digest: notice.waiting_digest, recipients: noticeRecipients(notice),
4735
+ }));
4669
4736
  const written = live.length === 0 ? { acked: [], already: [] } : await ackTodoNotices({
4670
- repoRoot, lane, noticeIds: live, openIds, actor: resolveTodoActor(env), now: new Date().toISOString(),
4737
+ repoRoot, lane, notices: live, openIds, actor: resolveTodoActor(env), now: new Date().toISOString(),
4671
4738
  });
4739
+ const idsOf = (pairs) => [...new Set(pairs.map(({ notice_id: id }) => id))].sort();
4672
4740
  const result = {
4673
- schema: 'lattice.todo_notice_ack_result.v1', project_id: store.project_id, lane,
4674
- acked: written.acked, already: written.already, closed: ids.filter((id) => !open.has(id)).sort(), result_digest: '',
4741
+ schema: 'lattice.todo_notice_ack_result.v1', project_id: view.store.project_id, lane,
4742
+ acked: idsOf(written.acked), already: idsOf(written.already), closed: ids.filter((id) => !open.has(id)).sort(),
4743
+ result_digest: '',
4675
4744
  };
4676
4745
  result.result_digest = todoSelfDigest(result, 'result_digest');
4677
4746
  return result;
4678
4747
  }
4679
4748
 
4749
+ /**
4750
+ * `todo wait` (wait-design): record that this agent stopped work and waits for T to become startable. A record, never a
4751
+ * gate: an already startable or finished T is answered with a state and nothing is written.
4752
+ */
4753
+ async function noticeWait({ repoRoot, env, planKey, taskId, reason, cancel }) {
4754
+ const view = await openNoticeView(repoRoot);
4755
+ const { store } = view;
4756
+ const member = store.members.find(({ plan }) => plan.plan_key === planKey);
4757
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
4758
+ const task = member.tasks.find(({ task_id: id }) => id === taskId);
4759
+ if (task === undefined) {
4760
+ throw new TodoStoreError('TASK_NOT_FOUND', 'task_not_found', undefined, { requested_task_id: taskId });
4761
+ }
4762
+ const { agent } = resolveTodoActor(env);
4763
+ const base = { schema: 'lattice.todo_wait_result.v1', project_id: store.project_id, plan_key: planKey, task_id: taskId, agent };
4764
+ let rest;
4765
+ if (cancel) {
4766
+ const { cancelled } = await cancelTodoNoticeWait({ repoRoot, planKey, taskId, agent });
4767
+ rest = { state: 'cancelled', cancelled, since: null, reason: null, notice: null, next_action: null };
4768
+ } else if (!['pending', 'blocked'].includes(task.status)) {
4769
+ rest = { state: 'not_pending', status: task.status, since: null, reason: null, notice: null, next_action: null };
4770
+ } else {
4771
+ const notice = view.notices.find((entry) => entry.plan_key === planKey && entry.task_id === taskId) ?? null;
4772
+ const ready = notice !== null || projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY).next_ready
4773
+ .some((entry) => entry.plan_key === planKey && entry.task_id === taskId);
4774
+ if (ready) {
4775
+ rest = { state: 'startable_now', since: null, reason: null, notice,
4776
+ next_action: notice?.next_action ?? `lattice todo start --plan ${planKey} --task ${taskId}` };
4777
+ } else {
4778
+ const now = new Date().toISOString();
4779
+ const { since } = await writeTodoNoticeWait({
4780
+ repoRoot, planKey, taskId, agent, reason: reason ?? null, now,
4781
+ keep: (wait) => waitInEffect(store, { plan_key: planKey, ...wait }),
4782
+ });
4783
+ rest = { state: 'waiting', since, reason: reason ?? null, notice: null, next_action: null };
4784
+ }
4785
+ }
4786
+ const result = { ...base, ...rest, result_digest: '' };
4787
+ result.result_digest = todoSelfDigest(result, 'result_digest');
4788
+ return result;
4789
+ }
4790
+
4680
4791
  async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = false }) {
4681
4792
  if (env.LATTICE_DASHBOARD_AUTOSTART === '0') return null;
4682
4793
  let actor;
@@ -4727,6 +4838,11 @@ async function verify({ repoRoot, requestedPlanKey }) {
4727
4838
  uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, repo_id: evidence.repo_id, path: evidence.path,
4728
4839
  next_action: `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.` });
4729
4840
  }
4841
+ for (const { phase_id: phaseId, decision_evidence: evidence } of member.phases) {
4842
+ if (decisionEvidenceState(repoRoot, store, evidence) !== 'uncommitted') continue;
4843
+ uncommittedEvidence.push({ plan_key: planKey, phase_id: phaseId, repo_id: evidence.repo_id, path: evidence.path,
4844
+ next_action: `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.` });
4845
+ }
4730
4846
  const unverified = member.tasks.find((task) => task.evidence_unverified && !pending.includes(task));
4731
4847
  if (unverified !== undefined) {
4732
4848
  throw new TodoStoreError('STORE_INCONSISTENT', 'evidence_unverified', 'evidence_unverified', {
@@ -4997,6 +5113,14 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4997
5113
  if (isNoticeLane(flags.lane) && ids.length > 0 && ids.every((id) => /^[0-9a-f]{64}$/u.test(id))) {
4998
5114
  action = (repoRoot) => noticeAck({ repoRoot, env, lane: flags.lane, ids });
4999
5115
  }
5116
+ } else if (argv[0] === 'wait' && matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait) !== null) {
5117
+ const flags = matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait);
5118
+ const reasonOk = flags.reason === undefined
5119
+ || (typeof flags.reason === 'string' && flags.reason.length > 0 && flags.reason.length <= 1024 && !/\p{Cc}/u.test(flags.reason));
5120
+ if (isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task) && reasonOk && !(flags.cancel === true && flags.reason !== undefined)) {
5121
+ action = (repoRoot) => noticeWait({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5122
+ reason: flags.reason ?? null, cancel: flags.cancel === true });
5123
+ }
5000
5124
  } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
5001
5125
  const flags = readFlags(argv, ['note', 'list']);
5002
5126
  action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
@@ -5204,21 +5328,29 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5204
5328
  } else if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
5205
5329
  const outcome = argv[1];
5206
5330
  const flags = matchFlagCommand(argv, ['phase', outcome], {
5207
- known: ['plan', 'phase', 'input', 'evidence', 'reason'], required: ['plan', 'phase'],
5331
+ known: ['plan', 'phase', 'input', 'evidence', 'message', 'reason'], required: ['plan', 'phase'],
5208
5332
  });
5333
+ const reasonFits = outcome === 'accept' ? flags?.reason === undefined
5334
+ : typeof flags?.reason === 'string' && flags.reason.length > 0;
5209
5335
  const base = flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase);
5210
- if (base && isAuthoringPathToken(flags.input) && flags.evidence === undefined && flags.reason === undefined) {
5336
+ if (base && isAuthoringPathToken(flags.input) && flags.evidence === undefined && flags.message === undefined
5337
+ && flags.reason === undefined) {
5211
5338
  action = (repoRoot) => phaseDecision({
5212
5339
  repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5213
5340
  outcome, inputRef: flags.input,
5214
5341
  });
5215
- } else if (base && flags.input === undefined && isAuthoringPathToken(flags.evidence)
5216
- && (outcome === 'accept' ? flags.reason === undefined
5217
- : typeof flags.reason === 'string' && flags.reason.length > 0)) {
5342
+ } else if (base && flags.input === undefined && flags.message === undefined
5343
+ && isAuthoringPathToken(flags.evidence) && reasonFits) {
5218
5344
  action = (repoRoot) => phaseDecisionFromEvidence({
5219
5345
  repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5220
5346
  outcome, evidenceRef: flags.evidence, reason: flags.reason ?? null,
5221
5347
  });
5348
+ } else if (base && flags.input === undefined && flags.evidence === undefined
5349
+ && typeof flags.message === 'string' && flags.message.length > 0 && reasonFits) {
5350
+ action = (repoRoot) => phaseDecisionFromEvidence({
5351
+ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5352
+ outcome, evidenceMessage: flags.message, reason: flags.reason ?? null,
5353
+ });
5222
5354
  }
5223
5355
  } else if (argv[0] === 'phase' && argv[1] === 'reopen' && phaseReopenFlags(argv) !== null) {
5224
5356
  const flags = phaseReopenFlags(argv);
@@ -41,8 +41,9 @@ export const TODO_NOTE_EVENT_SCHEMA = 'lattice.todo_note_event.v1';
41
41
  * task noteの読み書きは1バイトも変わらない。
42
42
  */
43
43
  export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
44
- // Per-lane startable-notice ack set (host-local; todo-notice-store.mjs).
45
- export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v1';
44
+ // Per-lane startable-notice ack set and per-plan waits (host-local; todo-notice-store.mjs).
45
+ export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
46
+ export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
46
47
  /**
47
48
  * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
48
49
  * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
@@ -4,135 +4,183 @@ import path from 'node:path';
4
4
 
5
5
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
6
6
  import {
7
- TODO_LIMITS, TODO_NOTICE_ACKS_SCHEMA, canonicalizeTodoArtifact, exactRecord, isStrictTodoTimestamp, isTodoDigest, isTodoIdentifier,
8
- todoSelfDigest,
7
+ TODO_LIMITS, TODO_NOTICE_ACKS_SCHEMA, TODO_NOTICE_WAITS_SCHEMA, canonicalizeTodoArtifact, digestTodoArtifact, exactRecord,
8
+ isStrictTodoTimestamp, isTodoDigest, isTodoIdentifier, todoSelfDigest,
9
9
  } from './todo-contracts.mjs';
10
10
  import { TodoStoreError, atomicWrite, rejectNewerTodoSchema } from './todo-store.mjs';
11
11
 
12
- export { TODO_NOTICE_ACKS_SCHEMA };
12
+ export { TODO_NOTICE_ACKS_SCHEMA, TODO_NOTICE_WAITS_SCHEMA };
13
13
 
14
14
  /**
15
- * Per-lane ack set of startable notices (dfd-done-notice.md, row "Store: ack set").
16
- * Host-local delivery state, not a plan fact: it is git-ignored (its own .gitignore), has its own lock, and never touches the
17
- * lifecycle journals. Losing it means a notice is delivered again, never lost.
15
+ * Per-lane ack set of startable notices and per-plan waits (dfd-done-notice.md, rows "Store: ack set",
16
+ * "Store: waits record", "Store: ack key"). Host-local delivery state, not a plan fact: git-ignored (its own
17
+ * .gitignore), one lock for both, never touching the lifecycle journals. Losing an ack means a notice is
18
+ * delivered again; losing a wait loses the wake mark (the notice still lists) until `todo wait` runs again.
18
19
  */
19
20
  export const TODO_NOTICE_ROOT_REF = '.lattice/todo/notices';
21
+ const ACKS_V1_SCHEMA = 'lattice.todo_notice_acks.v1';
20
22
  const LANE_FILE = /^[0-9a-f]{16}\.json$/u;
23
+ const WAIT_FILE = /^wait-[0-9a-f]{16}\.json$/u;
21
24
 
22
25
  const fail = (code, reason, detail) => { throw new TodoStoreError(code, reason, reason, detail); };
23
26
  const canonicalLine = (value) => `${canonicalizeTodoArtifact(value)}\n`;
24
27
  // Lane is the exact string the plan records (bot id or name); bounded so the record stays bounded.
25
28
  const isLane = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256
26
29
  && !/\p{Cc}/u.test(value);
30
+ const isReason = (value) => value === null || (typeof value === 'string' && value.length > 0 && value.length <= 1024
31
+ && !/\p{Cc}/u.test(value));
27
32
  const isActor = (value) => exactRecord(value, ['host', 'session', 'agent'])
28
33
  && [value.host, value.session, value.agent].every(isTodoIdentifier);
29
- const isAck = (value) => exactRecord(value, ['notice_id', 'acked_at', 'actor'])
30
- && isTodoDigest(value.notice_id) && isStrictTodoTimestamp(value.acked_at) && isActor(value.actor);
31
- const sortedUnique = (ids) => ids.every((id, index) => index === 0 || ids[index - 1] < id);
34
+ const sortedUnique = (keys) => keys.every((key, index) => index === 0 || keys[index - 1] < key);
35
+ const byKey = (keyOf) => (left, right) => (keyOf(left) < keyOf(right) ? -1 : 1);
36
+ // Digests are fixed-length hex and identifiers never hold \0, so these keys sort like the tuples.
37
+ const ackKey = ({ notice_id: id, waiting_digest: digest }) => `${id}:${digest}`;
38
+ const waitKey = ({ task_id: task, agent }) => `${task}\0${agent}`;
39
+ const pairOf = ({ notice_id, waiting_digest }) => ({ notice_id, waiting_digest });
40
+
41
+ const hex16 = (text) => createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16);
42
+ const laneRef = (lane) => path.posix.join(TODO_NOTICE_ROOT_REF, `${hex16(lane)}.json`);
43
+ const waitRef = (planKey) => path.posix.join(TODO_NOTICE_ROOT_REF, `wait-${hex16(planKey)}.json`);
32
44
 
33
- const laneFileName = (lane) => `${createHash('sha256').update(lane, 'utf8').digest('hex').slice(0, 16)}.json`;
34
- const laneRef = (lane) => path.posix.join(TODO_NOTICE_ROOT_REF, laneFileName(lane));
45
+ /**
46
+ * The ack key's waiter-set digest: sha256 hex of the canonical sorted `[[agent, since], ...]`.
47
+ * Plan imports this and never computes it itself; the Store needs digest([]) to read v1 acks.
48
+ */
49
+ export function todoNoticeWaitingDigest(waiters) {
50
+ if (!Array.isArray(waiters) || !waiters.every((w) => isLane(w?.agent) && isStrictTodoTimestamp(w?.since))) {
51
+ throw new TypeError('todoNoticeWaitingDigest waiters invalid');
52
+ }
53
+ const pairs = waiters.map(({ agent, since }) => [agent, since])
54
+ .sort(([la, ls], [ra, rs]) => (la < ra || (la === ra && ls < rs) ? -1 : 1));
55
+ return digestTodoArtifact(pairs);
56
+ }
57
+ const NO_WAITERS_DIGEST = todoNoticeWaitingDigest([]);
35
58
 
36
- function sealed(lane, acks) {
59
+ const isRecipients = (value, lane) => Array.isArray(value) && value.length > 0 && value.every(isLane)
60
+ && sortedUnique(value) && value.includes(lane);
61
+ const isAckV1 = (value) => exactRecord(value, ['notice_id', 'acked_at', 'actor'])
62
+ && isTodoDigest(value.notice_id) && isStrictTodoTimestamp(value.acked_at) && isActor(value.actor);
63
+ const isAck = (value, lane) => exactRecord(value, ['notice_id', 'waiting_digest', 'recipients', 'acked_at', 'actor'])
64
+ && isTodoDigest(value.notice_id) && isTodoDigest(value.waiting_digest) && isRecipients(value.recipients, lane)
65
+ && isStrictTodoTimestamp(value.acked_at) && isActor(value.actor);
66
+ const isWait = (value) => exactRecord(value, ['task_id', 'agent', 'since', 'reason'])
67
+ && isTodoIdentifier(value.task_id) && isLane(value.agent) && isStrictTodoTimestamp(value.since) && isReason(value.reason);
68
+
69
+ function sealedAcks(lane, acks) {
37
70
  const record = { schema: TODO_NOTICE_ACKS_SCHEMA, lane, acks, acks_digest: '' };
38
71
  record.acks_digest = todoSelfDigest(record, 'acks_digest');
39
72
  return record;
40
73
  }
41
74
 
42
- // Every refusal names the lane file, so one bad lane never hides another.
43
- async function readLaneFile(repoRoot, ref) {
44
- const corrupt = (reason) => fail('STORE_CORRUPT', reason, {
45
- ref,
46
- next_action: `${ref} is a host-local notice ack set, not plan data. Delete it to start the lane's acks over`
47
- + ' (its open notices are listed and delivered again), or run `lattice todo notice ack` to replace it.',
48
- });
75
+ function sealedWaits(planKey, waits) {
76
+ const record = { schema: TODO_NOTICE_WAITS_SCHEMA, plan_key: planKey, waits, waits_digest: '' };
77
+ record.waits_digest = todoSelfDigest(record, 'waits_digest');
78
+ return record;
79
+ }
80
+
81
+ // Both file kinds: every refusal names the file, so one bad file never hides another.
82
+ const ACK_FILE = {
83
+ family: 'todo_notice_acks', label: 'notice_acks', digest: 'acks_digest',
84
+ advice: 'is a host-local notice ack set, not plan data. Delete it to start the lane\'s acks over'
85
+ + ' (its open notices are listed and delivered again), or run `lattice todo notice ack` to replace it.',
86
+ // A v1 file is returned as its v2 reading: no waiters, the lane as the only recipient.
87
+ parse(record) {
88
+ const v1 = record.schema === ACKS_V1_SCHEMA;
89
+ if (!exactRecord(record, ['schema', 'lane', 'acks', 'acks_digest']) || (!v1 && record.schema !== TODO_NOTICE_ACKS_SCHEMA)
90
+ || !isLane(record.lane) || !Array.isArray(record.acks) || !isTodoDigest(record.acks_digest)
91
+ || !record.acks.every((ack) => (v1 ? isAckV1(ack) : isAck(ack, record.lane)))
92
+ || !sortedUnique(record.acks.map(v1 ? ({ notice_id: id }) => id : ackKey))) return null;
93
+ return {
94
+ ref: laneRef(record.lane),
95
+ view: () => (v1 ? sealedAcks(record.lane, record.acks.map(({ notice_id, acked_at, actor }) => ({
96
+ notice_id, waiting_digest: NO_WAITERS_DIGEST, recipients: [record.lane], acked_at, actor,
97
+ }))) : record),
98
+ };
99
+ },
100
+ };
101
+ const WAIT_RECORD = {
102
+ family: 'todo_notice_waits', label: 'notice_waits', digest: 'waits_digest',
103
+ advice: 'is a host-local notice wait file, not plan data. Delete it to drop the plan\'s wake marks'
104
+ + ' (re-run `lattice todo wait` to restore one), or run `lattice todo wait` to replace it.',
105
+ parse(record) {
106
+ if (!exactRecord(record, ['schema', 'plan_key', 'waits', 'waits_digest']) || record.schema !== TODO_NOTICE_WAITS_SCHEMA
107
+ || !isTodoIdentifier(record.plan_key) || !Array.isArray(record.waits) || !record.waits.every(isWait)
108
+ || !sortedUnique(record.waits.map(waitKey)) || !isTodoDigest(record.waits_digest)) return null;
109
+ return { ref: waitRef(record.plan_key), view: () => record };
110
+ },
111
+ };
112
+
113
+ async function readNoticeFile(repoRoot, ref, kind) {
114
+ const corrupt = (reason) => fail('STORE_CORRUPT', `${kind.label}_${reason}`, { ref, next_action: `${ref} ${kind.advice}` });
49
115
  let bytes;
50
116
  try {
51
117
  const state = await lstat(path.resolve(repoRoot, ref));
52
- if (!state.isFile()) corrupt('notice_acks_not_file');
53
- if (state.size > TODO_LIMITS.journalSegmentBytes) corrupt('notice_acks_too_large');
118
+ if (!state.isFile()) corrupt('not_file');
119
+ if (state.size > TODO_LIMITS.journalSegmentBytes) corrupt('too_large');
54
120
  bytes = await readFile(path.resolve(repoRoot, ref), 'utf8');
55
121
  } catch (error) {
56
122
  if (error instanceof TodoStoreError) throw error;
57
123
  if (error?.code === 'ENOENT') return null;
58
- corrupt('notice_acks_unreadable');
124
+ corrupt('unreadable');
59
125
  }
60
126
  let record;
61
- try { record = JSON.parse(bytes); } catch { corrupt('notice_acks_json_invalid'); }
62
- rejectNewerTodoSchema(record, 'todo_notice_acks', ref);
63
- if (!exactRecord(record, ['schema', 'lane', 'acks', 'acks_digest']) || record.schema !== TODO_NOTICE_ACKS_SCHEMA
64
- || !isLane(record.lane) || !Array.isArray(record.acks) || !record.acks.every(isAck)
65
- || !sortedUnique(record.acks.map(({ notice_id: id }) => id)) || !isTodoDigest(record.acks_digest)) {
66
- corrupt('notice_acks_shape_invalid');
67
- }
68
- if (canonicalLine(record) !== bytes) corrupt('notice_acks_not_canonical');
69
- if (record.acks_digest !== todoSelfDigest(record, 'acks_digest')) corrupt('notice_acks_digest_mismatch');
70
- if (laneRef(record.lane) !== ref) corrupt('notice_acks_lane_mismatch');
71
- return record;
72
- }
73
-
74
- /** The lane's ack set, or null when the lane has none. */
75
- export async function readTodoNoticeAcks({ repoRoot, lane } = {}) {
76
- if (typeof repoRoot !== 'string' || !isLane(lane)) throw new TypeError('readTodoNoticeAcks options invalid');
77
- const ref = laneRef(lane);
78
- const record = await readLaneFile(path.resolve(repoRoot), ref);
79
- // A different lane whose hash prefix collides is not this lane's record.
80
- if (record !== null && record.lane !== lane) {
81
- fail('STORE_CORRUPT', 'notice_acks_lane_mismatch', { ref, lane, recorded_lane: record.lane });
82
- }
83
- return record;
127
+ try { record = JSON.parse(bytes); } catch { corrupt('json_invalid'); }
128
+ rejectNewerTodoSchema(record, kind.family, ref);
129
+ const parsed = kind.parse(record);
130
+ if (parsed === null) corrupt('shape_invalid');
131
+ if (canonicalLine(record) !== bytes) corrupt('not_canonical');
132
+ if (record[kind.digest] !== todoSelfDigest(record, kind.digest)) corrupt('digest_mismatch');
133
+ if (parsed.ref !== ref) corrupt(kind === ACK_FILE ? 'lane_mismatch' : 'plan_mismatch');
134
+ return parsed.view();
84
135
  }
85
136
 
86
- /** Every lane's ack set; an unreadable lane file is named in `unreadable` and never hides the others. */
87
- export async function readAllTodoNoticeAcks({ repoRoot } = {}) {
88
- if (typeof repoRoot !== 'string') throw new TypeError('readAllTodoNoticeAcks options invalid');
137
+ async function readAllNoticeFiles(repoRoot, pattern, kind, fileField) {
89
138
  const root = path.resolve(repoRoot);
90
139
  let names;
91
- try { names = (await readdir(path.resolve(root, TODO_NOTICE_ROOT_REF))).filter((name) => LANE_FILE.test(name)).sort(); }
140
+ try { names = (await readdir(path.resolve(root, TODO_NOTICE_ROOT_REF))).filter((name) => pattern.test(name)).sort(); }
92
141
  catch (error) {
93
- if (error?.code === 'ENOENT') return { acks: [], unreadable: [] };
94
- return { acks: [], unreadable: [{ lane_file: TODO_NOTICE_ROOT_REF, code: 'STORE_CORRUPT', reason: 'notice_acks_unreadable' }] };
142
+ if (error?.code === 'ENOENT') return { records: [], unreadable: [] };
143
+ return { records: [], unreadable: [{ [fileField]: TODO_NOTICE_ROOT_REF, code: 'STORE_CORRUPT', reason: `${kind.label}_unreadable` }] };
95
144
  }
96
- const acks = [];
145
+ const records = [];
97
146
  const unreadable = [];
98
147
  for (const name of names) {
99
148
  const ref = path.posix.join(TODO_NOTICE_ROOT_REF, name);
100
149
  try {
101
- const record = await readLaneFile(root, ref);
102
- if (record !== null) acks.push(record);
150
+ const record = await readNoticeFile(root, ref, kind);
151
+ if (record !== null) records.push(record);
103
152
  } catch (error) {
104
153
  if (!(error instanceof TodoStoreError)) throw error;
105
- unreadable.push({ lane_file: ref, code: error.code, reason: error.detail.reason });
154
+ unreadable.push({ [fileField]: ref, code: error.code, reason: error.detail.reason });
106
155
  }
107
156
  }
108
- return { acks, unreadable };
157
+ return { records, unreadable };
109
158
  }
110
159
 
111
- /**
112
- * Record acks for `noticeIds` (each must be in `openIds`, the lane's open notices Plan read) and drop
113
- * acks whose notice is no longer open, so the set stays bounded by the open notices.
114
- * An unreadable older file is replaced (its acks were already unusable: list shows them unacked);
115
- * a newer Lattice's file is refused, never downgraded.
116
- */
117
- export async function ackTodoNotices({ repoRoot, lane, noticeIds, openIds, actor, now } = {}) {
118
- if (typeof repoRoot !== 'string' || !isLane(lane) || !Array.isArray(noticeIds) || noticeIds.length === 0
119
- || !Array.isArray(openIds) || ![...noticeIds, ...openIds].every(isTodoDigest)
120
- || !isActor(actor) || !isStrictTodoTimestamp(now)) {
121
- throw new TypeError('ackTodoNotices options invalid');
160
+ // The current record, or null when missing, unreadable or another key's (prefix collision): the write replaces it.
161
+ // A newer Lattice's file is refused, never downgraded.
162
+ async function replaceableRecord(root, ref, kind, owns) {
163
+ try {
164
+ const record = await readNoticeFile(root, ref, kind);
165
+ return record !== null && owns(record) ? record : null;
166
+ } catch (error) {
167
+ if (!(error instanceof TodoStoreError) || error.code !== 'STORE_CORRUPT') throw error;
168
+ return null;
122
169
  }
123
- const open = new Set(openIds);
124
- if (!noticeIds.every((id) => open.has(id))) throw new TypeError('ackTodoNotices noticeIds must be open notices');
125
- const root = path.resolve(repoRoot);
170
+ }
171
+
172
+ async function underNoticesLock(root, { create }, body) {
126
173
  const directory = path.resolve(root, TODO_NOTICE_ROOT_REF);
127
- try { await mkdir(directory); }
128
- catch (error) {
129
- // Protects against creating a Store skeleton outside a published Store; leaves once the Store exists.
130
- if (error?.code === 'ENOENT') {
131
- fail('STORE_WRITE_CONFLICT', 'store_missing', { next_action: 'Initialize the Todo Store, then retry the ack.' });
174
+ if (create) {
175
+ try { await mkdir(directory); }
176
+ catch (error) {
177
+ // Protects against creating a Store skeleton outside a published Store; leaves once the Store exists.
178
+ if (error?.code === 'ENOENT') {
179
+ fail('STORE_WRITE_CONFLICT', 'store_missing', { next_action: 'Initialize the Todo Store, then retry.' });
180
+ }
181
+ if (error?.code !== 'EEXIST') throw error;
132
182
  }
133
- if (error?.code !== 'EEXIST') throw error;
134
183
  }
135
- const ref = laneRef(lane);
136
184
  try {
137
185
  return await withStoreLock({ lockPath: path.join(directory, '.write.lock'), createParent: false, waitMs: LOCK_WAIT_MS },
138
186
  async () => {
@@ -140,27 +188,120 @@ export async function ackTodoNotices({ repoRoot, lane, noticeIds, openIds, actor
140
188
  await writeFile(path.join(directory, '.gitignore'), '*\n', { flag: 'wx' }).catch((error) => {
141
189
  if (error?.code !== 'EEXIST') throw error;
142
190
  });
143
- let current = null;
144
- try { current = await readLaneFile(root, ref); }
145
- catch (error) {
146
- if (!(error instanceof TodoStoreError) || error.code !== 'STORE_CORRUPT') throw error;
147
- }
148
- // A colliding lane's record is not ours to keep; it is replaced like any unreadable file.
149
- const kept = (current?.lane === lane ? current.acks : []).filter(({ notice_id: id }) => open.has(id));
150
- const keptIds = new Set(kept.map(({ notice_id: id }) => id));
151
- const requested = [...new Set(noticeIds)].sort();
152
- const already = requested.filter((id) => keptIds.has(id));
153
- const acked = requested.filter((id) => !keptIds.has(id));
154
- const acks = [...kept, ...acked.map((id) => ({ notice_id: id, acked_at: now, actor }))]
155
- .sort((left, right) => (left.notice_id < right.notice_id ? -1 : 1));
156
- const next = sealed(lane, acks);
157
- if (current === null || next.acks_digest !== current.acks_digest) {
158
- await atomicWrite(path.resolve(root, ref), Buffer.from(canonicalLine(next), 'utf8'));
159
- }
160
- return { acked, already };
191
+ return body();
161
192
  });
162
193
  } catch (error) {
163
194
  if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
164
195
  throw error;
165
196
  }
166
197
  }
198
+
199
+ /** The lane's ack set (a v1 file as its v2 reading), or null when the lane has none. */
200
+ export async function readTodoNoticeAcks({ repoRoot, lane } = {}) {
201
+ if (typeof repoRoot !== 'string' || !isLane(lane)) throw new TypeError('readTodoNoticeAcks options invalid');
202
+ const ref = laneRef(lane);
203
+ const record = await readNoticeFile(path.resolve(repoRoot), ref, ACK_FILE);
204
+ // A different lane whose hash prefix collides is not this lane's record.
205
+ if (record !== null && record.lane !== lane) {
206
+ fail('STORE_CORRUPT', 'notice_acks_lane_mismatch', { ref, lane, recorded_lane: record.lane });
207
+ }
208
+ return record;
209
+ }
210
+
211
+ /** Every lane's ack set; an unreadable lane file is named in `unreadable` and never hides the others. */
212
+ export async function readAllTodoNoticeAcks({ repoRoot } = {}) {
213
+ if (typeof repoRoot !== 'string') throw new TypeError('readAllTodoNoticeAcks options invalid');
214
+ const { records, unreadable } = await readAllNoticeFiles(repoRoot, LANE_FILE, ACK_FILE, 'lane_file');
215
+ return { acks: records, unreadable };
216
+ }
217
+
218
+ /**
219
+ * Record acks for `notices` (each `{notice_id, waiting_digest, recipients}` with notice_id in `openIds`, the lane's
220
+ * open notices Plan read) and drop acks whose notice is no longer open. Every digest variant of an open notice is
221
+ * kept, so the recipients already informed stay known; an existing pair is `already` and keeps its first entry.
222
+ */
223
+ export async function ackTodoNotices({ repoRoot, lane, notices, openIds, actor, now } = {}) {
224
+ if (typeof repoRoot !== 'string' || !isLane(lane) || !Array.isArray(notices) || notices.length === 0
225
+ || !notices.every((n) => exactRecord(n, ['notice_id', 'waiting_digest', 'recipients']) && isTodoDigest(n.notice_id)
226
+ && isTodoDigest(n.waiting_digest) && isRecipients(n.recipients, lane))
227
+ || !Array.isArray(openIds) || !openIds.every(isTodoDigest) || !isActor(actor) || !isStrictTodoTimestamp(now)) {
228
+ throw new TypeError('ackTodoNotices options invalid');
229
+ }
230
+ const open = new Set(openIds);
231
+ if (!notices.every(({ notice_id: id }) => open.has(id))) throw new TypeError('ackTodoNotices notices must be open notices');
232
+ const root = path.resolve(repoRoot);
233
+ const ref = laneRef(lane);
234
+ return underNoticesLock(root, { create: true }, async () => {
235
+ const current = await replaceableRecord(root, ref, ACK_FILE, (record) => record.lane === lane);
236
+ const kept = (current?.acks ?? []).filter(({ notice_id: id }) => open.has(id));
237
+ const keptKeys = new Set(kept.map(ackKey));
238
+ const requested = [...new Map(notices.map((n) => [ackKey(n), n])).values()].sort(byKey(ackKey));
239
+ const already = requested.filter((n) => keptKeys.has(ackKey(n)));
240
+ const acked = requested.filter((n) => !keptKeys.has(ackKey(n)));
241
+ const acks = [...kept, ...acked.map(({ notice_id, waiting_digest, recipients }) => ({
242
+ notice_id, waiting_digest, recipients, acked_at: now, actor,
243
+ }))].sort(byKey(ackKey));
244
+ const next = sealedAcks(lane, acks);
245
+ // An unchanged v1 file reads the same, so it is left for an older Lattice that still reads it.
246
+ if (current === null || next.acks_digest !== current.acks_digest) {
247
+ await atomicWrite(path.resolve(root, ref), Buffer.from(canonicalLine(next), 'utf8'));
248
+ }
249
+ return { acked: acked.map(pairOf), already: already.map(pairOf) };
250
+ });
251
+ }
252
+
253
+ /** Every plan's wait record, raw (Plan applies its in-effect check); an unreadable file is named in `unreadable`. */
254
+ export async function readAllTodoNoticeWaits({ repoRoot } = {}) {
255
+ if (typeof repoRoot !== 'string') throw new TypeError('readAllTodoNoticeWaits options invalid');
256
+ const { records, unreadable } = await readAllNoticeFiles(repoRoot, WAIT_FILE, WAIT_RECORD, 'wait_file');
257
+ return { waits: records, unreadable };
258
+ }
259
+
260
+ /**
261
+ * Record that `agent` waits for `taskId`. `keep(wait)` is Plan's synchronous, pure in-effect predicate; it runs under
262
+ * the lock on the existing waits and each write drops the ones it rejects. A wait still in effect keeps its `since`
263
+ * and takes the new reason (`recorded: false`). Plan checks the new wait itself before calling.
264
+ */
265
+ export async function writeTodoNoticeWait({ repoRoot, planKey, taskId, agent, reason, now, keep } = {}) {
266
+ if (typeof repoRoot !== 'string' || !isTodoIdentifier(planKey) || !isTodoIdentifier(taskId) || !isLane(agent)
267
+ || !isReason(reason) || !isStrictTodoTimestamp(now) || typeof keep !== 'function') {
268
+ throw new TypeError('writeTodoNoticeWait options invalid');
269
+ }
270
+ const root = path.resolve(repoRoot);
271
+ const ref = waitRef(planKey);
272
+ return underNoticesLock(root, { create: true }, async () => {
273
+ const current = await replaceableRecord(root, ref, WAIT_RECORD, (record) => record.plan_key === planKey);
274
+ const kept = (current?.waits ?? []).filter((wait) => keep(wait));
275
+ const key = waitKey({ task_id: taskId, agent });
276
+ const existing = kept.find((wait) => waitKey(wait) === key);
277
+ const since = existing?.since ?? now;
278
+ const waits = [...kept.filter((wait) => wait !== existing), { task_id: taskId, agent, since, reason }].sort(byKey(waitKey));
279
+ const next = sealedWaits(planKey, waits);
280
+ if (current === null || next.waits_digest !== current.waits_digest) {
281
+ await atomicWrite(path.resolve(root, ref), Buffer.from(canonicalLine(next), 'utf8'));
282
+ }
283
+ return { recorded: existing === undefined, since };
284
+ });
285
+ }
286
+
287
+ /** Remove `agent`'s wait for `taskId`; `cancelled: false` when there was none (an unreadable file holds none). */
288
+ export async function cancelTodoNoticeWait({ repoRoot, planKey, taskId, agent } = {}) {
289
+ if (typeof repoRoot !== 'string' || !isTodoIdentifier(planKey) || !isTodoIdentifier(taskId) || !isLane(agent)) {
290
+ throw new TypeError('cancelTodoNoticeWait options invalid');
291
+ }
292
+ const root = path.resolve(repoRoot);
293
+ const ref = waitRef(planKey);
294
+ try { await lstat(path.resolve(root, TODO_NOTICE_ROOT_REF)); }
295
+ catch (error) {
296
+ if (error?.code === 'ENOENT') return { cancelled: false };
297
+ throw error;
298
+ }
299
+ return underNoticesLock(root, { create: false }, async () => {
300
+ const current = await replaceableRecord(root, ref, WAIT_RECORD, (record) => record.plan_key === planKey);
301
+ const key = waitKey({ task_id: taskId, agent });
302
+ const waits = (current?.waits ?? []).filter((wait) => waitKey(wait) !== key);
303
+ if (current === null || waits.length === current.waits.length) return { cancelled: false };
304
+ await atomicWrite(path.resolve(root, ref), Buffer.from(canonicalLine(sealedWaits(planKey, waits)), 'utf8'));
305
+ return { cancelled: true };
306
+ });
307
+ }
@@ -2,6 +2,7 @@
2
2
  // Store journals. Lattice records and shows; a notice starts nothing and gates nothing.
3
3
 
4
4
  import { digestTodoArtifact } from './todo-contracts.mjs';
5
+ import { todoNoticeWaitingDigest } from './todo-notice-store.mjs';
5
6
  import { createTodoReadiness } from './todo-readiness.mjs';
6
7
  import { projectTodoStatus, TODO_STATUS_DISPATCH_ONLY } from './todo-status.mjs';
7
8
 
@@ -20,11 +21,33 @@ function triggerOf(member, event, ref) {
20
21
  };
21
22
  }
22
23
 
24
+ /**
25
+ * wait-design: a wait is in effect while its task is pending or blocked and has no own start or retire after `since`.
26
+ * shortcut: a start-then-retract in an earlier plan version followed by a revise can bring a wait back (that version's
27
+ * events are not in this journal); chosen over a revise silently dropping waits (Owner ruling 2). Upgrade when revisions
28
+ * carry the task's event history.
29
+ */
30
+ export function waitInEffect(store, wait) {
31
+ const member = store.members.find(({ plan }) => plan.plan_key === wait.plan_key);
32
+ const task = member?.tasks.find(({ task_id: id }) => id === wait.task_id);
33
+ if (task === undefined || !['pending', 'blocked'].includes(task.status)) return false;
34
+ return !member.journal.events.some((event) => event.task_id === wait.task_id
35
+ && ['start', 'retire'].includes(event.kind) && event.recorded_at > wait.since);
36
+ }
37
+
38
+ function noticeSummary(planKey, task, waiting) {
39
+ const head = `${planKey}/${task.task_id} 「${task.title}」 can start now.`;
40
+ return waiting.length === 0
41
+ ? `${head} Information, not a request: whether and when to start is the lane's call.`
42
+ : `${head} ${waiting.map(({ agent, since }) => `${agent} waiting since ${since}`).join(', ')}.`;
43
+ }
44
+
23
45
  /**
24
46
  * Open notices: ready tasks (`next_ready`, the same rule as `todo status`) that waited on something.
25
47
  * `declared(planKey, taskId)` says whether an enforced plan's witness set records the task's row.
48
+ * `waits` are the waits in effect (`waitInEffect`), `[{plan_key, task_id, agent, since, reason}]`.
26
49
  */
27
- export function projectTodoNotices(store, { lane = null, declared = () => true } = {}) {
50
+ export function projectTodoNotices(store, { lane = null, declared = () => true, waits = [] } = {}) {
28
51
  const readiness = createTodoReadiness(store);
29
52
  const members = new Map(store.members.map((member) => [member.plan.plan_key, member]));
30
53
  const notices = [];
@@ -54,6 +77,9 @@ export function projectTodoNotices(store, { lane = null, declared = () => true }
54
77
  .sort((left, right) => byText(left.event_digest, right.event_digest));
55
78
  const planKey = member.plan.plan_key;
56
79
  const mode = member.coordination?.mode ?? null;
80
+ const waiting = waits.filter((wait) => wait.plan_key === planKey && wait.task_id === task.task_id)
81
+ .map(({ agent, since, reason }) => ({ agent, since, reason: reason ?? null }))
82
+ .sort((left, right) => byText(left.agent, right.agent));
57
83
  notices.push({
58
84
  notice_id: digestTodoArtifact([planKey, member.plan.plan_version, task.task_id,
59
85
  unique.map(({ event_digest: digest }) => digest)]),
@@ -65,7 +91,10 @@ export function projectTodoNotices(store, { lane = null, declared = () => true }
65
91
  done_condition: task.done_condition ?? null,
66
92
  coordination_mode: mode,
67
93
  triggers: unique,
68
- // Same rule as the enforced done hints (#141): offer what the start path accepts.
94
+ waiting,
95
+ waiting_digest: todoNoticeWaitingDigest(waiting.map(({ agent, since }) => ({ agent, since }))),
96
+ summary: noticeSummary(planKey, task, waiting),
97
+ // The command if the lane starts; information, never an assignment. Same rule as the enforced done hints (#141): offer what the start path accepts.
69
98
  next_action: mode === 'enforced' && !declared(planKey, task.task_id)
70
99
  ? `lattice todo independence witness declare --plan ${planKey} --task ${task.task_id} --owns <path>[,<path>...]`
71
100
  : `lattice todo start --plan ${planKey} --task ${task.task_id}`,
@@ -130,7 +130,7 @@ function rejectUnsupportedRevisionSchema(value, { family, supportedSchemas }) {
130
130
 
131
131
  // Reader registration (newer-value-says-upgrade): the newest schema of each Store record family this
132
132
  // reader knows. Bump it in the same diff that teaches the validator a new version.
133
- export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 1 });
133
+ export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1 });
134
134
  const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest']]);
135
135
  const vocabularyWord = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}$/u.test(value);
136
136
 
@@ -3431,8 +3431,8 @@ export async function initializeTodoStore(options = {}) {
3431
3431
  const sameDirectoryIdentity = (left, right) => left !== null && right !== null
3432
3432
  && left.dev === right.dev && left.ino === right.ino;
3433
3433
 
3434
- // Host-local notice ack sets (and their temp files) of a store that is gone; see todo-notice-store.mjs.
3435
- const NOTICE_ACK_RESIDUE = /^(?:\.gitignore|\.?[0-9a-f]{16}\.json(?:\.\d+\.[0-9a-f]{12}\.tmp)?)$/u;
3434
+ // Host-local notice ack sets and wait files (and their temp files) of a store that is gone; see todo-notice-store.mjs.
3435
+ const NOTICE_ACK_RESIDUE = /^(?:\.gitignore|\.?(?:wait-)?[0-9a-f]{16}\.json(?:\.\d+\.[0-9a-f]{12}\.tmp)?)$/u;
3436
3436
 
3437
3437
  async function transientStoreDirectory(root, allowNotes = true, allowAcks = false) {
3438
3438
  for (const entry of await readdir(root, { withFileTypes: true })) {