@quolu/lattice 0.91.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 +1 -1
- package/src/cli-help.mjs +2 -0
- package/src/todo-cli.mjs +123 -21
- package/src/todo-contracts.mjs +3 -2
- package/src/todo-notice-store.mjs +236 -95
- package/src/todo-notices.mjs +31 -2
- package/src/todo-store.mjs +3 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "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等の周期実行向け)
|
|
@@ -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)',
|
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 {
|
|
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 = {}) {
|
|
@@ -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'] }),
|
|
@@ -4614,7 +4617,8 @@ function releasesTasks(argv) {
|
|
|
4614
4617
|
|| (command === 'dependency' && second === 'disconnect');
|
|
4615
4618
|
}
|
|
4616
4619
|
|
|
4617
|
-
|
|
4620
|
+
/** Open notices with their waiters (wait-design); an unreadable wait file is named, its waits read as none. */
|
|
4621
|
+
async function openNoticeView(repoRoot) {
|
|
4618
4622
|
const store = await readTodoStore({ repoRoot });
|
|
4619
4623
|
const rows = new Map();
|
|
4620
4624
|
for (const member of store.members) {
|
|
@@ -4622,16 +4626,57 @@ async function openNotices(repoRoot) {
|
|
|
4622
4626
|
const recorded = await readTodoWitnessSet({ repoRoot, planKey: member.plan.plan_key }).catch(() => null);
|
|
4623
4627
|
rows.set(member.plan.plan_key, new Set(Object.keys(recorded?.manual_witness ?? {})));
|
|
4624
4628
|
}
|
|
4625
|
-
|
|
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;
|
|
4641
|
+
}
|
|
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;
|
|
4626
4652
|
}
|
|
4627
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
|
+
|
|
4628
4666
|
/** A committed write is never undone for its notices: an unreadable projection says so and `notice list` recovers. */
|
|
4629
4667
|
async function withNotices(repoRoot, result, before) {
|
|
4630
4668
|
if (result === null || typeof result !== 'object' || typeof result.result_digest !== 'string') return result;
|
|
4631
4669
|
let extra;
|
|
4632
4670
|
try {
|
|
4633
4671
|
if (before === null) throw new Error('notices_before_unreadable');
|
|
4634
|
-
|
|
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
|
+
}) };
|
|
4635
4680
|
} catch (error) {
|
|
4636
4681
|
extra = { notices: null, notices_unavailable: error?.detail?.reason ?? error?.message ?? 'notices_unreadable' };
|
|
4637
4682
|
}
|
|
@@ -4651,27 +4696,28 @@ function noticeAckRefusal(error, lane) {
|
|
|
4651
4696
|
|
|
4652
4697
|
/** `todo notice list`: open notices, unacked unless asked; one unreadable ack file never hides the rest. */
|
|
4653
4698
|
async function noticeList({ repoRoot, lane, includeAcked }) {
|
|
4654
|
-
const
|
|
4655
|
-
const open =
|
|
4656
|
-
const
|
|
4699
|
+
const view = await openNoticeView(repoRoot);
|
|
4700
|
+
const open = view.notices.filter((notice) => lane === null || notice.lane === lane);
|
|
4701
|
+
const records = [];
|
|
4657
4702
|
const ackUnreadable = [];
|
|
4658
4703
|
if (lane === null) {
|
|
4659
4704
|
const all = await readAllTodoNoticeAcks({ repoRoot });
|
|
4660
|
-
|
|
4705
|
+
records.push(...all.acks);
|
|
4661
4706
|
ackUnreadable.push(...all.unreadable);
|
|
4662
4707
|
} else {
|
|
4663
4708
|
try {
|
|
4664
4709
|
const record = await readTodoNoticeAcks({ repoRoot, lane });
|
|
4665
|
-
|
|
4710
|
+
if (record !== null) records.push(record);
|
|
4666
4711
|
} catch (error) {
|
|
4667
4712
|
ackUnreadable.push(noticeAckRefusal(error, lane));
|
|
4668
4713
|
}
|
|
4669
4714
|
}
|
|
4670
|
-
const
|
|
4671
|
-
|
|
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);
|
|
4672
4718
|
const result = {
|
|
4673
|
-
schema: 'lattice.todo_notice_list_result.v1', project_id: store.project_id, lane, notices,
|
|
4674
|
-
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: '',
|
|
4675
4721
|
};
|
|
4676
4722
|
result.result_digest = todoSelfDigest(result, 'result_digest');
|
|
4677
4723
|
return result;
|
|
@@ -4679,21 +4725,69 @@ async function noticeList({ repoRoot, lane, includeAcked }) {
|
|
|
4679
4725
|
|
|
4680
4726
|
/** `todo notice ack`: an id that is no longer open is reported as closed, never refused (nothing is left to ack). */
|
|
4681
4727
|
async function noticeAck({ repoRoot, env, lane, ids }) {
|
|
4682
|
-
const
|
|
4683
|
-
const
|
|
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);
|
|
4684
4731
|
const open = new Set(openIds);
|
|
4685
|
-
|
|
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
|
+
}));
|
|
4686
4736
|
const written = live.length === 0 ? { acked: [], already: [] } : await ackTodoNotices({
|
|
4687
|
-
repoRoot, lane,
|
|
4737
|
+
repoRoot, lane, notices: live, openIds, actor: resolveTodoActor(env), now: new Date().toISOString(),
|
|
4688
4738
|
});
|
|
4739
|
+
const idsOf = (pairs) => [...new Set(pairs.map(({ notice_id: id }) => id))].sort();
|
|
4689
4740
|
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(),
|
|
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: '',
|
|
4692
4744
|
};
|
|
4693
4745
|
result.result_digest = todoSelfDigest(result, 'result_digest');
|
|
4694
4746
|
return result;
|
|
4695
4747
|
}
|
|
4696
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
|
+
|
|
4697
4791
|
async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = false }) {
|
|
4698
4792
|
if (env.LATTICE_DASHBOARD_AUTOSTART === '0') return null;
|
|
4699
4793
|
let actor;
|
|
@@ -5019,6 +5113,14 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
|
|
|
5019
5113
|
if (isNoticeLane(flags.lane) && ids.length > 0 && ids.every((id) => /^[0-9a-f]{64}$/u.test(id))) {
|
|
5020
5114
|
action = (repoRoot) => noticeAck({ repoRoot, env, lane: flags.lane, ids });
|
|
5021
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
|
+
}
|
|
5022
5124
|
} else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
|
|
5023
5125
|
const flags = readFlags(argv, ['note', 'list']);
|
|
5024
5126
|
action = (repoRoot) => listNotes({ repoRoot, planKey: flags.plan, taskId: flags.task ?? null });
|
package/src/todo-contracts.mjs
CHANGED
|
@@ -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.
|
|
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,
|
|
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,
|
|
16
|
-
* Host-local delivery state, not a plan fact:
|
|
17
|
-
* lifecycle journals. Losing
|
|
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
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
34
|
-
|
|
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
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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('
|
|
53
|
-
if (state.size > TODO_LIMITS.journalSegmentBytes) corrupt('
|
|
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('
|
|
124
|
+
corrupt('unreadable');
|
|
59
125
|
}
|
|
60
126
|
let record;
|
|
61
|
-
try { record = JSON.parse(bytes); } catch { corrupt('
|
|
62
|
-
rejectNewerTodoSchema(record,
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
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) =>
|
|
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 {
|
|
94
|
-
return {
|
|
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
|
|
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
|
|
102
|
-
if (record !== null)
|
|
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({
|
|
154
|
+
unreadable.push({ [fileField]: ref, code: error.code, reason: error.detail.reason });
|
|
106
155
|
}
|
|
107
156
|
}
|
|
108
|
-
return {
|
|
157
|
+
return { records, unreadable };
|
|
109
158
|
}
|
|
110
159
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function underNoticesLock(root, { create }, body) {
|
|
126
173
|
const directory = path.resolve(root, TODO_NOTICE_ROOT_REF);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/todo-notices.mjs
CHANGED
|
@@ -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
|
-
|
|
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}`,
|
package/src/todo-store.mjs
CHANGED
|
@@ -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 })) {
|