@quolu/lattice 0.91.0 → 0.93.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.91.0",
3
+ "version": "0.93.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等の周期実行向け)
@@ -134,6 +135,7 @@ Write commands:
134
135
  # 監査と構造finalizationは残作業であり、doneの門ではない
135
136
  reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]
136
137
  evidence promote --plan <key> --task <id> --evidence <file>
138
+ evidence anchor [--json] # 既存の証拠をgcから守る印(refs/lattice/evidence/<oid>)を付ける。commit済みにはならない
137
139
  # done状態と完了時刻を維持し、最新doneへ追記eventで証拠を再束縛する
138
140
  start --plan <key> --task <id> --rebind --reason <text> # 改訂でcarryされたin-progressへ現版のstart束縛を積み直す(ADR 0191)
139
141
  dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
@@ -304,6 +306,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
304
306
  'todo notice': 'todo notice list [--lane <lane>] [--include-acked] [--json] | ack --lane <lane> --notice <id>[,<id>...] [--json]',
305
307
  'todo notice list': 'todo notice list [--lane <lane>] [--include-acked] [--json] # lattice.todo_notice_list_result.v1',
306
308
  'todo notice ack': 'todo notice ack --lane <lane> --notice <id>[,<id>...] [--json] # lattice.todo_notice_ack_result.v1 {acked, already, closed}',
309
+ '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
310
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
308
311
  'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
309
312
  'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
@@ -343,7 +346,8 @@ const SUBCOMMAND_USAGE = Object.freeze({
343
346
  + ' [--design-memo <text>] [--after <id>[,<id>...]] [--before <id>[,<id>...]] [--reason <text>]',
344
347
  'todo done': 'todo done --plan <key> --task <id> [--evidence <file>] [--message <text>] [--test-result <markdown-file>]',
345
348
  'todo reopen': 'todo reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]',
346
- 'todo evidence': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
349
+ 'todo evidence': 'todo evidence promote --plan <key> --task <id> --evidence <file> | anchor [--json]',
350
+ 'todo evidence anchor': 'todo evidence anchor [--json] # lattice.todo_evidence_anchor_result.v1 {anchored, already, missing}',
347
351
  'todo evidence promote': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
348
352
  'todo dependency': [
349
353
  'todo dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>',
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 = {}) {
@@ -358,6 +360,7 @@ const TODO_FLAG_SPECS = Object.freeze({
358
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'] }),
363
+ 'evidence anchor': Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
361
364
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
362
365
  'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
363
366
  'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
@@ -366,6 +369,7 @@ const TODO_FLAG_SPECS = Object.freeze({
366
369
  show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
367
370
  'notice list': Object.freeze({ known: ['lane', 'include-acked', 'json'], required: [], booleans: ['include-acked', 'json'] }),
368
371
  'notice ack': Object.freeze({ known: ['lane', 'notice', 'json'], required: ['lane', 'notice'], booleans: ['json'] }),
372
+ wait: Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
369
373
  'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
370
374
  'phase status': Object.freeze({ known: ['plan', 'json'], required: ['plan'], booleans: ['json'] }),
371
375
  structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
@@ -732,6 +736,23 @@ function looksLikeEvidenceDescriptor(value) {
732
736
  return value !== null && typeof value === 'object' && !Array.isArray(value);
733
737
  }
734
738
 
739
+ // evidence-ref: every evidence blob Lattice writes is anchored here so gc keeps it. The Store's reachability walk
740
+ // excludes refs/lattice/evidence/* (seam refs still count), so an anchored blob still reads `uncommitted` until a commit reaches it.
741
+ const EVIDENCE_REF_PREFIX = 'refs/lattice/evidence/';
742
+
743
+ function anchorEvidenceBlob(repoRoot, oid) {
744
+ gitSync(['update-ref', `${EVIDENCE_REF_PREFIX}${oid}`, oid], { cwd: repoRoot, stdio: ['ignore', 'ignore', 'pipe'] });
745
+ }
746
+
747
+ function evidenceAnchored(repoRoot, oid) {
748
+ try {
749
+ gitSync(['show-ref', '--verify', '--quiet', `${EVIDENCE_REF_PREFIX}${oid}`], { cwd: repoRoot, stdio: 'ignore' });
750
+ return true;
751
+ } catch {
752
+ return false;
753
+ }
754
+ }
755
+
735
756
  function writeEvidenceBlob(repoRoot, bytes, blobPath, write = true) {
736
757
  // worktree pathから作る証拠は`git add`と同じclean filterを通す。生のCRLF bytesを
737
758
  // そのままhashすると、commit先はLFへ正規化される一方、descriptorはdangling blobを
@@ -747,6 +768,9 @@ function writeEvidenceBlob(repoRoot, bytes, blobPath, write = true) {
747
768
  if (!write) return { git_blob_oid: oid, content_digest: null };
748
769
  throw error;
749
770
  }
771
+ // Anchored before the event is appended: no recorded evidence without an anchor. A failed append leaves one ref
772
+ // keeping one blob alive (bounded, harmless).
773
+ if (write) anchorEvidenceBlob(repoRoot, oid);
750
774
  return {
751
775
  git_blob_oid: oid,
752
776
  content_digest: createHash('sha256').update(storedBytes).digest('hex'),
@@ -2244,7 +2268,8 @@ function extractionFreshnessViolations(repoRoot, extraction) {
2244
2268
  // rev-listの出力はobject数に比例して伸びる(本repo実測で既定maxBuffer 1MiB超過済み)。
2245
2269
  // 隣のgit showと同様にmaxBufferを明示しないと、ENOBUFSが握られて
2246
2270
  // source_reachability_unreadableへ誤変換される。
2247
- reachable = new Set(gitSync(['rev-list', '--objects', '--all'], {
2271
+ // evidence-ref: an anchored evidence blob is not a reachable source.
2272
+ reachable = new Set(gitSync(['rev-list', '--objects', `--exclude=${EVIDENCE_REF_PREFIX}*`, '--all'], {
2248
2273
  cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 134_217_728,
2249
2274
  }).split('\n').filter(Boolean).map((line) => line.split(' ')[0]));
2250
2275
  } catch {
@@ -4614,7 +4639,8 @@ function releasesTasks(argv) {
4614
4639
  || (command === 'dependency' && second === 'disconnect');
4615
4640
  }
4616
4641
 
4617
- async function openNotices(repoRoot) {
4642
+ /** Open notices with their waiters (wait-design); an unreadable wait file is named, its waits read as none. */
4643
+ async function openNoticeView(repoRoot) {
4618
4644
  const store = await readTodoStore({ repoRoot });
4619
4645
  const rows = new Map();
4620
4646
  for (const member of store.members) {
@@ -4622,16 +4648,57 @@ async function openNotices(repoRoot) {
4622
4648
  const recorded = await readTodoWitnessSet({ repoRoot, planKey: member.plan.plan_key }).catch(() => null);
4623
4649
  rows.set(member.plan.plan_key, new Set(Object.keys(recorded?.manual_witness ?? {})));
4624
4650
  }
4625
- return projectTodoNotices(store, { declared: (planKey, taskId) => rows.get(planKey)?.has(taskId) === true });
4651
+ const stored = await readAllTodoNoticeWaits({ repoRoot });
4652
+ // Readers return raw records: waits that ended since the file's last write are dropped here.
4653
+ const waits = stored.waits.flatMap((record) => record.waits.map((wait) => ({ plan_key: record.plan_key, ...wait })))
4654
+ .filter((wait) => waitInEffect(store, wait));
4655
+ const notices = projectTodoNotices(store, {
4656
+ declared: (planKey, taskId) => rows.get(planKey)?.has(taskId) === true, waits,
4657
+ });
4658
+ return { store, notices, waitUnreadable: stored.unreadable };
4659
+ }
4660
+
4661
+ async function openNotices(repoRoot) {
4662
+ return (await openNoticeView(repoRoot)).notices;
4663
+ }
4664
+
4665
+ /** lane -> notice_id -> [{waiting_digest, recipients}] from ack set records. */
4666
+ function ackIndex(records) {
4667
+ const index = new Map();
4668
+ for (const record of records) {
4669
+ const byId = new Map();
4670
+ for (const ack of record.acks) byId.set(ack.notice_id, [...(byId.get(ack.notice_id) ?? []), ack]);
4671
+ index.set(record.lane, byId);
4672
+ }
4673
+ return index;
4626
4674
  }
4627
4675
 
4676
+ /** Flora's amendment: who earlier acks of this notice_id covered, so a re-opened notice goes only to the rest. */
4677
+ function withAckState(notice, index) {
4678
+ const acks = index.get(notice.lane)?.get(notice.notice_id) ?? [];
4679
+ return {
4680
+ ...notice,
4681
+ acked_recipients: [...new Set(acks.flatMap(({ recipients }) => recipients))].sort(),
4682
+ acked: acks.some(({ waiting_digest: digest }) => digest === notice.waiting_digest),
4683
+ };
4684
+ }
4685
+
4686
+ const noticeRecipients = (notice) => [...new Set([notice.lane, ...notice.waiting.map(({ agent }) => agent)])].sort();
4687
+
4628
4688
  /** A committed write is never undone for its notices: an unreadable projection says so and `notice list` recovers. */
4629
4689
  async function withNotices(repoRoot, result, before) {
4630
4690
  if (result === null || typeof result !== 'object' || typeof result.result_digest !== 'string') return result;
4631
4691
  let extra;
4632
4692
  try {
4633
4693
  if (before === null) throw new Error('notices_before_unreadable');
4634
- extra = { notices: newTodoNotices(before, await openNotices(repoRoot)) };
4694
+ const released = newTodoNotices(before, await openNotices(repoRoot));
4695
+ // An unreadable ack set only means nobody counts as covered yet: delivery repeats, nothing is lost.
4696
+ const index = ackIndex(released.length === 0 ? []
4697
+ : await readAllTodoNoticeAcks({ repoRoot }).then(({ acks }) => acks, () => []));
4698
+ extra = { notices: released.map((notice) => {
4699
+ const { acked: _acked, ...rest } = withAckState(notice, index);
4700
+ return rest;
4701
+ }) };
4635
4702
  } catch (error) {
4636
4703
  extra = { notices: null, notices_unavailable: error?.detail?.reason ?? error?.message ?? 'notices_unreadable' };
4637
4704
  }
@@ -4651,27 +4718,28 @@ function noticeAckRefusal(error, lane) {
4651
4718
 
4652
4719
  /** `todo notice list`: open notices, unacked unless asked; one unreadable ack file never hides the rest. */
4653
4720
  async function noticeList({ repoRoot, lane, includeAcked }) {
4654
- const store = await readTodoStore({ repoRoot });
4655
- const open = (await openNotices(repoRoot)).filter((notice) => lane === null || notice.lane === lane);
4656
- const acked = new Map();
4721
+ const view = await openNoticeView(repoRoot);
4722
+ const open = view.notices.filter((notice) => lane === null || notice.lane === lane);
4723
+ const records = [];
4657
4724
  const ackUnreadable = [];
4658
4725
  if (lane === null) {
4659
4726
  const all = await readAllTodoNoticeAcks({ repoRoot });
4660
- for (const record of all.acks) acked.set(record.lane, new Set(record.acks.map(({ notice_id: id }) => id)));
4727
+ records.push(...all.acks);
4661
4728
  ackUnreadable.push(...all.unreadable);
4662
4729
  } else {
4663
4730
  try {
4664
4731
  const record = await readTodoNoticeAcks({ repoRoot, lane });
4665
- acked.set(lane, new Set((record?.acks ?? []).map(({ notice_id: id }) => id)));
4732
+ if (record !== null) records.push(record);
4666
4733
  } catch (error) {
4667
4734
  ackUnreadable.push(noticeAckRefusal(error, lane));
4668
4735
  }
4669
4736
  }
4670
- const notices = open.map((notice) => ({ ...notice, acked: acked.get(notice.lane)?.has(notice.notice_id) === true }))
4671
- .filter((notice) => includeAcked || !notice.acked);
4737
+ const index = ackIndex(records);
4738
+ // Acked iff (notice_id, waiting_digest) was acked: a wait added after an ack makes the notice unacked again.
4739
+ const notices = open.map((notice) => withAckState(notice, index)).filter((notice) => includeAcked || !notice.acked);
4672
4740
  const result = {
4673
- schema: 'lattice.todo_notice_list_result.v1', project_id: store.project_id, lane, notices,
4674
- ack_unreadable: ackUnreadable, result_digest: '',
4741
+ schema: 'lattice.todo_notice_list_result.v1', project_id: view.store.project_id, lane, notices,
4742
+ ack_unreadable: ackUnreadable, wait_unreadable: view.waitUnreadable, result_digest: '',
4675
4743
  };
4676
4744
  result.result_digest = todoSelfDigest(result, 'result_digest');
4677
4745
  return result;
@@ -4679,21 +4747,69 @@ async function noticeList({ repoRoot, lane, includeAcked }) {
4679
4747
 
4680
4748
  /** `todo notice ack`: an id that is no longer open is reported as closed, never refused (nothing is left to ack). */
4681
4749
  async function noticeAck({ repoRoot, env, lane, ids }) {
4682
- const store = await readTodoStore({ repoRoot });
4683
- const openIds = (await openNotices(repoRoot)).filter((notice) => notice.lane === lane).map(({ notice_id: id }) => id);
4750
+ const view = await openNoticeView(repoRoot);
4751
+ const laneNotices = view.notices.filter((notice) => notice.lane === lane);
4752
+ const openIds = laneNotices.map(({ notice_id: id }) => id);
4684
4753
  const open = new Set(openIds);
4685
- const live = ids.filter((id) => open.has(id));
4754
+ // The ack covers the notice as it is now: its waiter set (waiting_digest) and everyone it was delivered to.
4755
+ const live = laneNotices.filter(({ notice_id: id }) => ids.includes(id)).map((notice) => ({
4756
+ notice_id: notice.notice_id, waiting_digest: notice.waiting_digest, recipients: noticeRecipients(notice),
4757
+ }));
4686
4758
  const written = live.length === 0 ? { acked: [], already: [] } : await ackTodoNotices({
4687
- repoRoot, lane, noticeIds: live, openIds, actor: resolveTodoActor(env), now: new Date().toISOString(),
4759
+ repoRoot, lane, notices: live, openIds, actor: resolveTodoActor(env), now: new Date().toISOString(),
4688
4760
  });
4761
+ const idsOf = (pairs) => [...new Set(pairs.map(({ notice_id: id }) => id))].sort();
4689
4762
  const result = {
4690
- schema: 'lattice.todo_notice_ack_result.v1', project_id: store.project_id, lane,
4691
- acked: written.acked, already: written.already, closed: ids.filter((id) => !open.has(id)).sort(), result_digest: '',
4763
+ schema: 'lattice.todo_notice_ack_result.v1', project_id: view.store.project_id, lane,
4764
+ acked: idsOf(written.acked), already: idsOf(written.already), closed: ids.filter((id) => !open.has(id)).sort(),
4765
+ result_digest: '',
4692
4766
  };
4693
4767
  result.result_digest = todoSelfDigest(result, 'result_digest');
4694
4768
  return result;
4695
4769
  }
4696
4770
 
4771
+ /**
4772
+ * `todo wait` (wait-design): record that this agent stopped work and waits for T to become startable. A record, never a
4773
+ * gate: an already startable or finished T is answered with a state and nothing is written.
4774
+ */
4775
+ async function noticeWait({ repoRoot, env, planKey, taskId, reason, cancel }) {
4776
+ const view = await openNoticeView(repoRoot);
4777
+ const { store } = view;
4778
+ const member = store.members.find(({ plan }) => plan.plan_key === planKey);
4779
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
4780
+ const task = member.tasks.find(({ task_id: id }) => id === taskId);
4781
+ if (task === undefined) {
4782
+ throw new TodoStoreError('TASK_NOT_FOUND', 'task_not_found', undefined, { requested_task_id: taskId });
4783
+ }
4784
+ const { agent } = resolveTodoActor(env);
4785
+ const base = { schema: 'lattice.todo_wait_result.v1', project_id: store.project_id, plan_key: planKey, task_id: taskId, agent };
4786
+ let rest;
4787
+ if (cancel) {
4788
+ const { cancelled } = await cancelTodoNoticeWait({ repoRoot, planKey, taskId, agent });
4789
+ rest = { state: 'cancelled', cancelled, since: null, reason: null, notice: null, next_action: null };
4790
+ } else if (!['pending', 'blocked'].includes(task.status)) {
4791
+ rest = { state: 'not_pending', status: task.status, since: null, reason: null, notice: null, next_action: null };
4792
+ } else {
4793
+ const notice = view.notices.find((entry) => entry.plan_key === planKey && entry.task_id === taskId) ?? null;
4794
+ const ready = notice !== null || projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY).next_ready
4795
+ .some((entry) => entry.plan_key === planKey && entry.task_id === taskId);
4796
+ if (ready) {
4797
+ rest = { state: 'startable_now', since: null, reason: null, notice,
4798
+ next_action: notice?.next_action ?? `lattice todo start --plan ${planKey} --task ${taskId}` };
4799
+ } else {
4800
+ const now = new Date().toISOString();
4801
+ const { since } = await writeTodoNoticeWait({
4802
+ repoRoot, planKey, taskId, agent, reason: reason ?? null, now,
4803
+ keep: (wait) => waitInEffect(store, { plan_key: planKey, ...wait }),
4804
+ });
4805
+ rest = { state: 'waiting', since, reason: reason ?? null, notice: null, next_action: null };
4806
+ }
4807
+ }
4808
+ const result = { ...base, ...rest, result_digest: '' };
4809
+ result.result_digest = todoSelfDigest(result, 'result_digest');
4810
+ return result;
4811
+ }
4812
+
4697
4813
  async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = false }) {
4698
4814
  if (env.LATTICE_DASHBOARD_AUTOSTART === '0') return null;
4699
4815
  let actor;
@@ -4726,6 +4842,71 @@ async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = fa
4726
4842
  }
4727
4843
  }
4728
4844
 
4845
+ /** evidence-ref: an uncommitted item says whether gc is kept off it, and how to protect it if not. */
4846
+ function uncommittedEvidenceItem(repoRoot, store, evidence) {
4847
+ const anchored = evidenceAnchored(evidenceRepoRoot(repoRoot, store, evidence), evidence.git_blob_oid);
4848
+ return { repo_id: evidence.repo_id, path: evidence.path, anchored,
4849
+ next_action: anchored
4850
+ ? `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.`
4851
+ : 'Anchor it so gc keeps it: `lattice todo evidence anchor --json`; commit it to make it committed.' };
4852
+ }
4853
+
4854
+ function evidenceRepoRoot(repoRoot, store, evidence) {
4855
+ const ref = store.manifest.repositories.find(({ repo_id: id }) => id === evidence.repo_id)?.path ?? '.';
4856
+ return path.resolve(repoRoot, ref);
4857
+ }
4858
+
4859
+ /** The evidence descriptors a Store records: task evidence, phase decision evidence and accepted slot evidence. */
4860
+ function recordedEvidence(store) {
4861
+ const entries = [];
4862
+ for (const member of store.members) {
4863
+ const planKey = member.plan.plan_key;
4864
+ for (const task of member.tasks) {
4865
+ if (validateEvidenceDescriptor(task.evidence)) entries.push({ plan_key: planKey, task_id: task.task_id, evidence: task.evidence });
4866
+ }
4867
+ for (const event of member.journal.events) {
4868
+ if (!['phase_accept', 'phase_reject'].includes(event.kind)) continue;
4869
+ for (const evidence of [event.payload.decision_evidence, ...(event.payload.evidence_slots ?? []).map((slot) => slot.evidence)]) {
4870
+ if (validateEvidenceDescriptor(evidence)) entries.push({ plan_key: planKey, phase_id: event.phase_id, evidence });
4871
+ }
4872
+ }
4873
+ }
4874
+ return entries;
4875
+ }
4876
+
4877
+ /**
4878
+ * `todo evidence anchor` (evidence-ref): anchor evidence recorded before writes anchored it. Idempotent; run once per
4879
+ * existing chart. Evidence gc already pruned cannot come back and is listed as `missing`.
4880
+ */
4881
+ async function evidenceAnchor({ repoRoot }) {
4882
+ const store = await readTodoStore({ repoRoot });
4883
+ const anchored = [];
4884
+ const missing = [];
4885
+ const seen = new Set();
4886
+ let already = 0;
4887
+ for (const { evidence, ...owner } of recordedEvidence(store)) {
4888
+ const repo = evidenceRepoRoot(repoRoot, store, evidence);
4889
+ const key = `${repo}\0${evidence.git_blob_oid}`;
4890
+ if (seen.has(key)) continue;
4891
+ seen.add(key);
4892
+ const item = { ...owner, git_blob_oid: evidence.git_blob_oid };
4893
+ if (isTodoEvidenceUncommitted({ repoRoot, store, evidence })) {
4894
+ if (evidenceAnchored(repo, evidence.git_blob_oid)) already += 1;
4895
+ else { anchorEvidenceBlob(repo, evidence.git_blob_oid); anchored.push(item); }
4896
+ continue;
4897
+ }
4898
+ try {
4899
+ gitSync(['cat-file', '-e', evidence.git_blob_oid], { cwd: repo, stdio: 'ignore' });
4900
+ } catch {
4901
+ missing.push(item);
4902
+ }
4903
+ }
4904
+ const result = { schema: 'lattice.todo_evidence_anchor_result.v1', project_id: store.project_id,
4905
+ anchored, already, missing, result_digest: '' };
4906
+ result.result_digest = todoSelfDigest(result, 'result_digest');
4907
+ return result;
4908
+ }
4909
+
4729
4910
  async function verify({ repoRoot, requestedPlanKey }) {
4730
4911
  const store = await readTodoStore({ repoRoot });
4731
4912
  const members = selectMembers(store, requestedPlanKey);
@@ -4741,13 +4922,11 @@ async function verify({ repoRoot, requestedPlanKey }) {
4741
4922
  const pending = member.tasks.filter((task) => task.evidence_unverified
4742
4923
  && isTodoEvidenceUncommitted({ repoRoot, store, evidence: task.evidence }));
4743
4924
  for (const { task_id: taskId, evidence } of pending) {
4744
- uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, repo_id: evidence.repo_id, path: evidence.path,
4745
- next_action: `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.` });
4925
+ uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
4746
4926
  }
4747
4927
  for (const { phase_id: phaseId, decision_evidence: evidence } of member.phases) {
4748
4928
  if (decisionEvidenceState(repoRoot, store, evidence) !== 'uncommitted') continue;
4749
- uncommittedEvidence.push({ plan_key: planKey, phase_id: phaseId, repo_id: evidence.repo_id, path: evidence.path,
4750
- next_action: `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.` });
4929
+ uncommittedEvidence.push({ plan_key: planKey, phase_id: phaseId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
4751
4930
  }
4752
4931
  const unverified = member.tasks.find((task) => task.evidence_unverified && !pending.includes(task));
4753
4932
  if (unverified !== undefined) {
@@ -5019,6 +5198,14 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5019
5198
  if (isNoticeLane(flags.lane) && ids.length > 0 && ids.every((id) => /^[0-9a-f]{64}$/u.test(id))) {
5020
5199
  action = (repoRoot) => noticeAck({ repoRoot, env, lane: flags.lane, ids });
5021
5200
  }
5201
+ } else if (argv[0] === 'wait' && matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait) !== null) {
5202
+ const flags = matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait);
5203
+ const reasonOk = flags.reason === undefined
5204
+ || (typeof flags.reason === 'string' && flags.reason.length > 0 && flags.reason.length <= 1024 && !/\p{Cc}/u.test(flags.reason));
5205
+ if (isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task) && reasonOk && !(flags.cancel === true && flags.reason !== undefined)) {
5206
+ action = (repoRoot) => noticeWait({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5207
+ reason: flags.reason ?? null, cancel: flags.cancel === true });
5208
+ }
5022
5209
  } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
5023
5210
  const flags = readFlags(argv, ['note', 'list']);
5024
5211
  action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
@@ -5337,6 +5524,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5337
5524
  kind: 'unblock', payload: {}, evidenceRef: null,
5338
5525
  }) });
5339
5526
  }
5527
+ } else if (argv[0] === 'evidence' && argv[1] === 'anchor'
5528
+ && matchFlagCommand(argv, ['evidence', 'anchor'], TODO_FLAG_SPECS['evidence anchor']) !== null) {
5529
+ action = (repoRoot) => evidenceAnchor({ repoRoot });
5340
5530
  } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
5341
5531
  const flags = matchFlagCommand(argv, ['evidence', 'promote'], TODO_FLAG_SPECS['evidence promote']);
5342
5532
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
@@ -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
 
@@ -1115,7 +1115,8 @@ function reachableObjects(absoluteRepo) {
1115
1115
  if (cached !== undefined) return cached;
1116
1116
  let set;
1117
1117
  try {
1118
- const stdout = gitSync(['rev-list', '--objects', '--all'],
1118
+ // evidence-ref: Lattice's evidence anchors (refs/lattice/evidence/*, not seam refs) keep evidence from gc; anchored is not committed.
1119
+ const stdout = gitSync(['rev-list', '--objects', '--exclude=refs/lattice/evidence/*', '--all'],
1119
1120
  { cwd: absoluteRepo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
1120
1121
  maxBuffer: 256 * 1024 * 1024 });
1121
1122
  set = new Set();
@@ -3431,8 +3432,8 @@ export async function initializeTodoStore(options = {}) {
3431
3432
  const sameDirectoryIdentity = (left, right) => left !== null && right !== null
3432
3433
  && left.dev === right.dev && left.ino === right.ino;
3433
3434
 
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;
3435
+ // Host-local notice ack sets and wait files (and their temp files) of a store that is gone; see todo-notice-store.mjs.
3436
+ const NOTICE_ACK_RESIDUE = /^(?:\.gitignore|\.?(?:wait-)?[0-9a-f]{16}\.json(?:\.\d+\.[0-9a-f]{12}\.tmp)?)$/u;
3436
3437
 
3437
3438
  async function transientStoreDirectory(root, allowNotes = true, allowAcks = false) {
3438
3439
  for (const entry of await readdir(root, { withFileTypes: true })) {