diff --git a/.changeset/trigger-notices.md b/.changeset/trigger-notices.md index fbb79683..b5124246 100644 --- a/.changeset/trigger-notices.md +++ b/.changeset/trigger-notices.md @@ -7,4 +7,4 @@ The notice a receiver sends for a trigger, defined - The protocol defines a notice (`control-notice.json`): a receiver's unsigned word that something changed on a topic the machine listed, as a closed set of short typed fields with no session, words, folder, level or tool. It travels in a new `notices` list beside `messages` in a poll answer, at most 50 at a time, and is acked at `POST {control}/notices/ack` (`control-notice-ack.json`) with its outcome alone: what ran is never said. - A machine's hello can carry `triggers`: whether triggers are on and the topics a receiver may send notices on. A receiver's well-known file can say `control.notices`. -- `sessionpipe-core` exports `parseNotice`, `noticesIn` and `noticeAck`, which read a notice against the generated definition and build its ack. Nothing runs on a notice yet. +- `sessionpipe-core` exports `parseNotice`, `noticesIn` and `noticeAck`, which read a notice against the generated definition and build its ack. diff --git a/.changeset/triggers.md b/.changeset/triggers.md new file mode 100644 index 00000000..58e667ac --- /dev/null +++ b/.changeset/triggers.md @@ -0,0 +1,18 @@ +--- +"sessionpipe": minor +"sessionpipe-core": minor +"sessionpipe-receiver": minor +--- + +The background service takes a receiver's notices and runs the rules they fit + +- Every hello says `triggers`: on, with the topics each receiver may send notices on, or off. A hello goes at once when that changes: a rule added, paused, resumed or removed, `sessionpipe triggers on|off`, a pause the machine made, or a second pairing on a rule's receiver. Hellos go one at a time, so the last one a receiver hears is what is so now. +- Each notice of a poll answer, at most 50, is checked in the order CONTROL.md §14.7 gives: its id, the switch, its shape and times, whether it expired, whether this receiver sent it in the last 25 hours, and the first rule it fits. Its id is recorded on disk before anything runs, so a notice runs at most once, across a restart too. One that can't be recorded is not acked and runs nothing; the receiver sends it again. +- A notice sent again while its run is still getting ready (a sign-in check, say) is not acked until the run says `taken` or `ran`: the receiver never hears `duplicate` first. +- Each notice is acked at `POST {control}/notices/ack`, 50 at a time, and its ack is kept on disk until the receiver accepts it. One ack waits per notice: the final one replaces `taken`, and `duplicate` never goes out ahead of it. At most 2 000 wait for one receiver; past that the oldest that is neither `ran` nor `taken` is dropped. An ack goes back to the pairing its notice came from, even when another pairing on the same host was added meanwhile. +- `sessionpipe triggers off` holds for the next notice at once, before the file watcher notices the change. +- A run that waits is saved before its notice is told `taken`, so a crash between the two can't leave a `taken` that never gets a final ack. +- A receiver that sends notices on every answer is polled at most once a second, and this computer remembers at most 20 000 of one receiver's notice ids at a time; past that a new notice waits. +- Two pairings on one host: neither can trigger a rule, and both are told triggers are off. A second service that doesn't run the rules says off, acks nothing and writes none of their files. +- `sessionpipe-core` exports `receiverName`, the name a rule gives its receiver, so `trigger add` and the service read it the same way. An address with no host names no receiver. +- `sessionpipe-receiver` exports the notices half of a receiver as plain functions over one machine's state: `onHello`, `offer`, `forPoll` and `onAcks`, and a file to keep it in. A receiver built on them sends only topics the last hello listed, keeps one notice per subject, and never lets `duplicate` or a later final replace a `ran` it already has. diff --git a/packages/cli/src/control/cli.ts b/packages/cli/src/control/cli.ts index 4cdcbab2..ab83117b 100644 --- a/packages/cli/src/control/cli.ts +++ b/packages/cli/src/control/cli.ts @@ -43,7 +43,7 @@ import { ControlDaemon, DaemonRunning, type Status } from "./daemon.js"; import { ask, socketPath } from "./local.js"; import { installService, off, pair, removeKey, uninstallService, withoutInherit } from "./pair.js"; import { CLAUDE_NOT_FOUND } from "./route.js"; -import { readRules, rulesOf, triggersFile } from "./rules-file.js"; +import { readRules, rulesOf, rulesStamp, triggersFile } from "./rules-file.js"; import { loadSdk } from "./sdk.js"; import { askOn, @@ -473,6 +473,7 @@ async function runDaemon(out: (s?: string) => void, distDir: string): Promise process.exit(0), pool, rules: () => rulesOf(readRules()), + rulesStamp: () => rulesStamp(), }); try { await d.start(); diff --git a/packages/cli/src/control/daemon.ts b/packages/cli/src/control/daemon.ts index fdb471b0..204e00b0 100644 --- a/packages/cli/src/control/daemon.ts +++ b/packages/cli/src/control/daemon.ts @@ -23,6 +23,7 @@ import path from "node:path"; import { acpControl, antigravityControl, + type ControlHelloTriggers, claudeAccountDirs, claudeAccounts, claudeControl, @@ -38,12 +39,16 @@ import { type Login, machineName, makeEvent, + type NoticeResult, + noticeAck, + noticesIn, Outbox, type Reading, type RunOptions, type RunResult, readConfig, realFolderProblem, + receiverName, redactDeep, redactSecrets, type Session, @@ -86,6 +91,15 @@ import * as inbox from "./inbox.js"; import { Lines, type Turn } from "./line.js"; import { type AskRequest, ask, type Health, type LocalReply, type LocalRequest } from "./local.js"; import { type Held, lockHolder, takeLock as takeLockFile } from "./lockfile.js"; +import { + NOTICE_ACK_RETRY_MS, + NOTICE_ACK_WAIT_MS, + NOTICE_ACKS_PER_POST, + NOTICE_POLL_GAP_MS, + NoticeAckOutbox, + NoticeSeen, + takeNotice, +} from "./notices.js"; import { poolRequestOf, runPoolRequest } from "./pool.js"; import { type Following, @@ -634,6 +648,10 @@ export interface DaemonDeps { * null for none, or a file refused whole. Read at start and on `reloadRules()`. Absent: * this daemon runs no rules. */ rules?: () => TriggersFile | null; + /** What tells the rules file changed (its inode, size and time) without reading it: looked at + * before the notices of a poll answer are taken, so `trigger off` holds for a notice that + * arrives before the file's watcher has said so. Absent: only `reloadRules()` reads it. */ + rulesStamp?: () => string; /** The time zone a rule's clock and day are read in; the machine's own when unsaid. */ triggerZone?: string; /** How often the rules' clock is looked at (30 s; tests shorten it). */ @@ -954,6 +972,11 @@ export class ControlDaemon { private claimSaid = false; private triggerClaimProblem: string | null = null; private rulesNow: TriggersFile | null = null; + private rulesStampNow: string | undefined; + /** The notices step's stores (control/notices.ts), the claim holder's only: a daemon without + * the claim takes no notice, acks none and writes neither file. */ + private noticeSeen: NoticeSeen | null = null; + private noticeAcks: NoticeAckOutbox | null = null; private triggerTimer: NodeJS.Timeout | null = null; /** Triggered runs waiting for the headless slot, by message id: told when they have it. */ private readonly slotted = new Map void>(); @@ -1007,6 +1030,10 @@ export class ControlDaemon { this.triggerClaimProblem = null; const deps = this.deps; const record = path.join(this.dir, "triggers-state.json"); + const seen = new NoticeSeen(path.join(this.dir, "notices-seen.jsonl"), deps.now); + const box = new NoticeAckOutbox(path.join(this.dir, "notice-acks.jsonl"), deps.now); + this.noticeSeen = seen; + this.noticeAcks = box; this.triggers = new TriggerEngine({ now: deps.now, ...(deps.triggerZone ? { zone: deps.triggerZone } : {}), @@ -1025,7 +1052,13 @@ export class ControlDaemon { // is no wider than its own (Codex has no edits). offered: (h) => this.startEntry(h)?.permissions, run: (job, on) => this.runTrigger(job, on), - // `ack`, the notice's outcome for its receiver, is the notices step's to wire. + // A notice's outcome, for the pairing whose name the rule says (§14.4), and whether a + // waiting run's notice came from it (the dedup store says so across a restart). + ack: (name, id, result) => this.ackNotice(box, name, id, result), + received: (name, id) => { + const r = this.receiverNamed(name); + return r !== null && seen.has(r.control + r.machine, id); + }, // Over the size an honest record can reach, it is no record (trigger-state.ts). load: () => readStateFile(record, deps.log), save: (s) => writePrivate(record, s), @@ -1036,6 +1069,9 @@ export class ControlDaemon { this.triggers?.load(this.rulesNow); this.triggers?.check(); }); + // Loading the rules said a hello at once when it changed what one says (`changed`); acks a + // daemon before this one left are sent now. + void this.flushNoticeAcks(); } // --- lifecycle ------------------------------------------------------------------ @@ -1050,9 +1086,9 @@ export class ControlDaemon { // pool is on, every Claude Code request on this machine goes through it. await this.syncPool(); for (const r of this.cfg.receivers) void this.pollLoop(r); - this.helloTimer = setInterval(() => void this.helloAll(), HELLO_EVERY_MS); + this.helloTimer = setInterval(() => void this.helloNow(), HELLO_EVERY_MS); this.helloTimer.unref(); - void this.helloAll(); + void this.helloNow(); void this.flushAcks(); // The person's rules, and their clock: looked at now (a tick missed while the daemon was // stopped is run or refused `missed` at once) and every half minute after. @@ -1093,6 +1129,7 @@ export class ControlDaemon { if (this.helloSoon) clearTimeout(this.helloSoon); if (this.ownTimer) clearInterval(this.ownTimer); if (this.triggerTimer) clearInterval(this.triggerTimer); + clearTimeout(this.noticeRetry); // A triggered run that waits in a session's line, or for the headless slot, waits again in the // record: the next daemon takes it up (§14.7). // Only the daemon that holds the claim ever wrote the record, and it lets go of the claim. @@ -1253,7 +1290,7 @@ export class ControlDaemon { /** The pool changed what a hello says (pool/index.ts `onChange`): say it now, as a * folder change does. */ poolChanged(): void { - if (this.running) void this.helloAll(); + if (this.running) void this.helloNow(); } /** Null when the daemon holds nothing, so a restart would interrupt nothing; otherwise @@ -1374,6 +1411,9 @@ export class ControlDaemon { reload(cfg: ControlConfig): void { const known = new Set(this.cfg.receivers.map((r) => r.control + r.machine)); const told = JSON.stringify([this.cfg.folders, this.cfg.mode, this.cfg.name, askOn(this.cfg)]); + // Whose a receiver's name is (§14.1) may have changed: a pairing added on its host, or one of + // two that shared it removed. Its hello's `triggers` says so at once. + const names = new Map(this.cfg.receivers.map((r) => [r.control + r.machine, this.nameOf(r)])); this.cfg = cfg; // An agent driven over ACP runs, and has its permission requests answered, in the mode it // was opened in (ADAPTERS.md): one that would run otherwise now is let go of when idle, @@ -1389,8 +1429,12 @@ export class ControlDaemon { // `control folders`, `control mode`, `ask on|off` or a `--rename-machine` changed what a // hello says: say it now, so the receiver doesn't wait up to ten minutes for the next one. // Either way every receiver hears it: a hello says the same thing twice harmlessly. - const changed = JSON.stringify([cfg.folders, cfg.mode, cfg.name, askOn(cfg)]) !== told; - if (this.running && (paired.length > 0 || changed)) void this.helloAll(); + const changed = + JSON.stringify([cfg.folders, cfg.mode, cfg.name, askOn(cfg)]) !== told || + cfg.receivers.some( + (r) => names.has(r.control + r.machine) && names.get(r.control + r.machine) !== this.nameOf(r), + ); + if (this.running && (paired.length > 0 || changed)) void this.helloNow(); } status(): Status { @@ -1867,9 +1911,10 @@ export class ControlDaemon { } if (res.status === 200) { let fresh = 0; + let notices = 0; this.receiving++; try { - const body = (await Promise.race([res.json(), left])) as { messages?: Carried[] }; + const body = (await Promise.race([res.json(), left])) as { messages?: Carried[]; notices?: unknown }; // Looked up again: a key may have been added while this poll was parked. const cur = this.cfg.receivers.find((x) => x.control + x.machine === key) ?? r; // Not awaited: a headless turn can run for half an hour, and the next @@ -1883,6 +1928,8 @@ export class ControlDaemon { ), ); } + // Then its notices (§14.7), after the messages and whatever they are. + notices = this.takeNotices(cur, body); } finally { this.receiving--; } @@ -1892,9 +1939,17 @@ export class ControlDaemon { st.error = null; st.authBackoff = 0; backoff = 0; - // Only messages already in hand (a receiver that ignores `taken`): don't - // turn the long-poll into a spin. - if (!fresh) await sleep(2000); + if (notices) { + // Every notice of this answer acked before the next poll, as far as the receiver lets + // (§14.4), and a receiver that sends notices on every answer is polled at a bounded rate. + await Promise.race([this.flushNoticeAcks(), sleep(NOTICE_ACK_WAIT_MS)]); + await sleep(NOTICE_POLL_GAP_MS); + } else { + void this.flushNoticeAcks(); + // Only messages already in hand (a receiver that ignores `taken`): don't + // turn the long-poll into a spin. + if (!fresh) await sleep(2000); + } } else if (res.status === 204) { st.last = this.deps.now(); st.error = null; @@ -1948,7 +2003,7 @@ export class ControlDaemon { if (this.helloSoon) return; this.helloSoon = setTimeout(() => { this.helloSoon = null; - void this.helloAll(); + void this.helloNow(); }, 1500); this.helloSoon.unref(); } @@ -1984,6 +2039,50 @@ export class ControlDaemon { return isSink(r) ? sessionToolsFrom(r.tools) : (this.sessionTools.get(r.control + r.machine) ?? []); } + private helloing: Promise | null = null; + private helloAgain = false; + /** One hello round at a time: one asked for while another is on its way runs once it is done, + * so what the receiver heard last is what is so now (on, off, on in quick succession ends on). */ + private helloNow(): Promise { + if (this.helloing) { + this.helloAgain = true; + return this.helloing; + } + const round = async () => { + try { + do { + this.helloAgain = false; + await this.helloAll(); + } while (this.helloAgain && this.running); + } finally { + this.helloing = null; + } + void this.flushNoticeAcks(); + }; + this.helloing = round(); + return this.helloing; + } + + /** What a hello to `r` says of triggers: the engine's word for its name when this daemon holds + * the rules' claim and the name is this pairing's alone; off otherwise. */ + private helloTriggersFor(r: PairedReceiver): ControlHelloTriggers { + const name = this.nameOf(r); + return this.triggers && name !== null ? this.triggers.helloFor(name) : { on: false, topics: [] }; + } + + /** A pairing's name as a rule says it (§14.1), or null when it has none or another pairing + * shares it: a notice from either could not be told apart, so neither triggers a rule. */ + private nameOf(r: PairedReceiver): string | null { + const name = receiverName(r.url); + return name !== null && this.receiverNamed(name) === r ? name : null; + } + + /** The one pairing a rule's receiver name stands for, or null. */ + private receiverNamed(name: string): PairedReceiver | null { + const all = this.cfg.receivers.filter((x) => receiverName(x.url) === name); + return all.length === 1 ? (all[0] as PairedReceiver) : null; + } + private async helloAll(): Promise { void this.refreshSessionTools(); const waiting = [...this.live].filter(([, l]) => l.waiter).map(([k]) => k); @@ -2028,6 +2127,8 @@ export class ControlDaemon { handoff: true, // The machine's skills inventory (§2 `skills`). skills: helloSkills(this.deps.skillsEnv), + // Whether triggers are on, and the topics this receiver may send notices on (§14.3). + triggers: this.helloTriggersFor(r), }; const res = await this.post(r, "/hello", body).catch(() => null); const st = this.polling.get(r.control + r.machine); @@ -2131,6 +2232,120 @@ export class ControlDaemon { } } + // --- notices (CONTROL.md §14) --------------------------------------------------- + + /** A poll answer's notices (§14.7 steps 1 to 6, control/notices.ts), at most NOTICES_PER_POLL: + * the rest stay unacked and come again. Only the daemon that holds the rules' claim takes any. + * Says how many there were. */ + private takeNotices(r: PairedReceiver, body: unknown): number { + const { notices } = noticesIn(body); + const engine = this.triggers; + const seen = this.noticeSeen; + const box = this.noticeAcks; + if (!notices.length || !engine || !seen || !box) return 0; + this.safely(() => { + // `trigger off` written a moment ago holds now, not when the file's watcher looks. + if (this.deps.rulesStamp && this.deps.rulesStamp() !== this.rulesStampNow) this.reloadRules(); + const name = this.nameOf(r); + const receiver = r.control + r.machine; + const now = this.deps.now(); + let held = 0; + for (const raw of notices) { + const step = takeNotice(raw, { + now, + on: !!this.rulesNow?.on && name !== null, + seen, + receiver, + match: (n) => engine.firstMatch(name as string, n), + inHand: (id) => engine.inHand(name as string, id), + }); + if (step.do === "ack") box.add({ receiver, ...noticeAck(step.id, step.result, now) }); + else if (step.do === "fire") { + // Its outcome goes back to this pairing, whatever pairs with its host by then. + this.noticeFrom.set(`${name}\0${step.id}`, receiver); + if (this.noticeFrom.size > this.noticeFromMax) + this.noticeFrom.delete(this.noticeFrom.keys().next().value as string); + engine.fire(step.rule, { kind: "notice", receiver: name as string, notice: step.notice }); + } else if (step.do === "hold" && step.why === "unrecorded") held++; + } + if (held) this.deps.log(`${r.url}: ${held} notice(s) could not be recorded; they come again`); + }); + return notices.length; + } + + /** The engine's outcome for a notice from the receiver named `name`, kept until it is accepted. */ + private ackNotice(box: NoticeAckOutbox, name: string, id: string, result: NoticeResult): void { + // The pairing the notice came from; one a run read from the record names, the name's own + // (a name no longer one pairing's alone has nobody to tell). A pairing gone by the time the + // ack is sent drops it (sendNoticeAcks). + const k = `${name}\0${id}`; + const r = this.receiverNamed(name); + const to = this.noticeFrom.get(k) ?? (r ? r.control + r.machine : null); + if (result.outcome !== "taken") this.noticeFrom.delete(k); + if (to !== null) { + box.add({ receiver: to, ...noticeAck(id, result, this.deps.now()) }); + void this.flushNoticeAcks(); + } + } + + /** Notices taken from a poll, by receiver name and id: the pairing each came from, until its + * final ack is kept. */ + private readonly noticeFrom = new Map(); + /** A notice whose final the engine never says (it was already said once) would stay: the + * oldest go past this many, their acks then routed by name. */ + private noticeFromMax = 10_000; + + private noticeFlush: Promise | null = null; + private noticeRetry: NodeJS.Timeout | undefined; + private noticeFlushAgain = false; + /** Send the notice acks that wait to `POST {control}/notices/ack`, NOTICE_ACKS_PER_POST at a + * time; a 2xx takes a batch off. One send at a time; asked again meanwhile, it goes again + * after. What a receiver refused waits for the next poll answer, hello or ack. */ + private flushNoticeAcks(): Promise { + if (this.noticeFlush) { + this.noticeFlushAgain = true; + return this.noticeFlush; + } + const round = async () => { + try { + do { + this.noticeFlushAgain = false; + // A disk that won't take the outbox is said in the log, and tried again soon: this runs + // with nobody waiting on it, and a receiver that took the acks sends nothing to poll for. + await this.sendNoticeAcks().catch((e) => { + this.deps.log(`notice acks: ${String(e)}; tried again in ${NOTICE_ACK_RETRY_MS / 1000} s`); + clearTimeout(this.noticeRetry); + this.noticeRetry = setTimeout(() => void this.flushNoticeAcks(), NOTICE_ACK_RETRY_MS); + this.noticeRetry.unref(); + }); + } while (this.noticeFlushAgain && this.running); + } finally { + this.noticeFlush = null; + } + }; + this.noticeFlush = round(); + return this.noticeFlush; + } + + private async sendNoticeAcks(): Promise { + const box = this.noticeAcks; + if (!box) return; + // A pairing that is gone has nobody to tell. + box.only(new Set(this.cfg.receivers.map((r) => r.control + r.machine))); + const all = box.all(); + for (const r of this.cfg.receivers) { + const mine = all.filter((a) => a.receiver === r.control + r.machine); + for (let i = 0; i < mine.length; i += NOTICE_ACKS_PER_POST) { + const batch = mine.slice(i, i + NOTICE_ACKS_PER_POST); + const ok = await this.post(r, "/notices/ack", { acks: batch.map(({ receiver: _r, ...a }) => a) }) + .then((res) => res.status >= 200 && res.status < 300) + .catch(() => false); + if (!ok) break; + box.sent(batch); + } + } + } + // --- one message ---------------------------------------------------------------- async handle(r: PairedReceiver, m: Carried): Promise { @@ -2282,7 +2497,7 @@ export class ControlDaemon { return fetched[0]!.bytes; }, }); - if (out.outcome === "delivered" || out.code === "skill") void this.helloAll(); + if (out.outcome === "delivered" || out.code === "skill") void this.helloNow(); this.deps.log( `skill ${String(cmd.skill_action)} ${String(cmd.skill_slug)}: ${out.outcome}${out.outcome === "delivered" ? "" : ` — ${out.detail}`}`, ); @@ -5194,6 +5409,7 @@ export class ControlDaemon { /** The rules file, read again (`/triggers.json` changed): the engine drops what may * no longer run and looks at the clock at once. */ reloadRules(): void { + this.rulesStampNow = this.deps.rulesStamp?.(); this.rulesNow = this.deps.rules?.() ?? null; this.safely(() => { this.claimTriggers(); @@ -5223,10 +5439,12 @@ export class ControlDaemon { return lifted; } - /** What a hello says of triggers changed (a rule, a pause, the switch). The hello's - * `triggers` is the notices step's (§14.3); this is where it sends one at once. */ + /** What a hello says of triggers changed (a rule, a pause, the switch): every receiver hears it + * at once (§14.3). Only a running daemon has an engine to say so (claimTriggers), and a + * stopped one's is suspended. */ private triggersChanged(): void { this.deps.log("trigger rules changed"); + void this.helloNow(); } /** The harnesses a rule may run: those an ask may start, but an ACP agent, which takes no diff --git a/packages/cli/src/control/notices.ts b/packages/cli/src/control/notices.ts new file mode 100644 index 00000000..624ccfa5 --- /dev/null +++ b/packages/cli/src/control/notices.ts @@ -0,0 +1,338 @@ +// SPDX-License-Identifier: Apache-2.0 +// The notices step (spec/CONTROL.md §14.7 steps 1 to 6): what the daemon does with each notice +// of a poll answer before the engine (control/triggers.ts) is asked to run anything. The id read, +// the switch, the shape and the times, the 25-hour dedup and the match, in that order, in one +// function (`takeNotice`), with the two stores it needs: the ids seen from each receiver, and the +// acks not yet accepted. Both files are the claim holder's only (`triggers-state.lock`): a daemon +// without the claim reads no notice and writes neither. +// +// /control/notices-seen.jsonl {"r":"","i":"01KB…","t":1764000000000} +// /control/notice-acks.jsonl {"receiver":"","id":"01KB…","outcome":"ran","at":"…Z","session":"…"} + +import { + appendFileSync, + closeSync, + existsSync, + fsyncSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + unlinkSync, + writeSync, +} from "node:fs"; +import path from "node:path"; +import { + type ControlNotice, + NOTICE_SEEN_MS, + type NoticeAck, + type NoticeResult, + noticeId, + parseNotice, + type TriggerRule, + writeWhole, +} from "@sessionpipe/core"; + +/** Live ids a machine keeps per receiver. Notices are unsigned, so a paired receiver could send + * fresh ids without end: past this many, a notice is held (not acked, nothing runs) until the + * oldest age out. A day of an honest board is far below it. */ +export const NOTICE_SEEN_MAX = 20_000; +/** Acks a machine keeps waiting for one receiver. A receiver that answers every ack with an error + * while it sends fresh ids that are refused at once could otherwise grow the outbox without end: + * past this many, the oldest that is neither `ran` nor `taken` gives way. */ +export const NOTICE_ACK_MAX = 2_000; +/** The pause before polling again after an answer that carried notices. */ +export const NOTICE_POLL_GAP_MS = 1_000; +/** How long a poll that produced acks waits for them to land before it polls again (§14.4: a + * machine SHOULD ack every notice of an answer before it polls that receiver again). */ +export const NOTICE_ACK_WAIT_MS = 3_000; +/** How soon a send of the acks that failed on this machine's own disk is tried again. */ +export const NOTICE_ACK_RETRY_MS = 5_000; +/** Acks per `POST {control}/notices/ack` (control-notice-ack.json). */ +export const NOTICE_ACKS_PER_POST = 50; +const DAY_MS = 24 * 3600_000; + +/** The ids each receiver sent in the last 25 hours, as NonceStore keeps nonces: in memory, + * appended and synced before `record` returns, the file rewritten with only the live window at + * start and once a day. A line a crash cut short is skipped. */ +export class NoticeSeen { + private readonly ids = new Map>(); + private compacted = 0; + + constructor( + private readonly file: string, + private readonly now: () => number = Date.now, + ) { + let raw = ""; + try { + raw = readFileSync(file, "utf8"); + } catch {} + const cut = this.now() - NOTICE_SEEN_MS; + for (const line of raw.split("\n")) { + if (!line) continue; + try { + const { r, i, t } = JSON.parse(line) as { r: unknown; i: unknown; t: unknown }; + if (typeof r === "string" && typeof i === "string" && typeof t === "number" && t > cut) this.mine(r).set(i, t); + } catch {} + } + this.compact(); + } + + private mine(r: string): Map { + let m = this.ids.get(r); + if (!m) { + m = new Map(); + this.ids.set(r, m); + } + return m; + } + + /** `id` came from `r` within the last 25 hours. */ + has(r: string, id: string): boolean { + const t = this.ids.get(r)?.get(id); + return t !== undefined && t > this.now() - NOTICE_SEEN_MS; + } + + /** Record `id` from `r`, on disk before this returns. Throws when it can't: the write failed, + * or `r` already has NOTICE_SEEN_MAX live ids. Either way nothing may run for it. */ + record(r: string, id: string): void { + const at = this.now(); + if (at - this.compacted >= DAY_MS) this.compact(); + const m = this.mine(r); + if (m.size >= NOTICE_SEEN_MAX) { + for (const [i, t] of m) if (t <= at - NOTICE_SEEN_MS) m.delete(i); + if (m.size >= NOTICE_SEEN_MAX) throw new Error(`${NOTICE_SEEN_MAX} notices in 25 hours from one receiver`); + } + mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 }); + const fd = openSync(this.file, "a", 0o600); + try { + appendFileSync(fd, `${JSON.stringify({ r, i: id, t: at })}\n`); + fsyncSync(fd); + } finally { + closeSync(fd); + } + m.set(id, at); + } + + /** Rewrite the file with only the live window. */ + compact(): void { + const at = this.now(); + this.compacted = at; + const lines: string[] = []; + for (const [r, m] of this.ids) { + for (const [i, t] of m) + if (t <= at - NOTICE_SEEN_MS) m.delete(i); + else lines.push(JSON.stringify({ r, i, t })); + if (!m.size) this.ids.delete(r); + } + if (!existsSync(this.file) && !lines.length) return; + // Only a smaller file: one that can't be rewritten is still read whole, and `record` says + // whether the disk takes anything. + try { + writeSynced(this.file, lines.length ? `${lines.join("\n")}\n` : ""); + } catch {} + } +} + +/** Write a file whole and on disk before it takes the old one's place, so a crash or a power cut + * leaves the old file or the new one, never an empty one. The file beside it goes if anything + * fails. */ +function writeSynced(file: string, text: string): void { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const beside = `${file}.${process.pid}.tmp`; + try { + const fd = openSync(beside, "w", 0o600); + try { + writeSync(fd, text); + fsyncSync(fd); + } finally { + closeSync(fd); + } + renameSync(beside, file); + } catch (e) { + try { + unlinkSync(beside); + } catch {} + throw e; + } +} + +/** A notice's ack waiting for its receiver to accept it, and which pairing it is for. */ +export interface StoredNoticeAck extends NoticeAck { + receiver: string; +} + +const isFinal = (o: NoticeAck["outcome"]): boolean => o !== "taken" && o !== "duplicate"; +const keyOf = (a: StoredNoticeAck): string => `${a.receiver}\0${a.id}`; +/** What waits for a notice once `a` is added to `was`: only a final replaces what waits, and only + * what is not final itself. */ +const merged = (was: StoredNoticeAck | undefined, a: StoredNoticeAck): StoredNoticeAck => + !was || (isFinal(a.outcome) && !isFinal(was.outcome)) ? a : was; +/** Worth more than the rest when one must give way: the session a run went to, a run that waits. */ +const precious = (a: StoredNoticeAck): boolean => a.outcome === "ran" || a.outcome === "taken"; + +/** Notice acks not yet accepted, as AckOutbox keeps a command's: on disk before they are sent, + * so a restart sends rather than forgets. At most one waits per notice: a `taken` gives way to + * the final that follows it, a `duplicate` is not added while anything waits for that notice + * (the receiver would learn it before the session), and nothing ever goes back to `taken`. One + * older than 25 hours is no use to anyone (its notice expired) and is dropped, and a receiver has + * at most NOTICE_ACK_MAX waiting. Every change is on disk before it is made here: a write that + * fails throws and changes nothing. */ +export class NoticeAckOutbox { + /** By receiver and id, oldest first. */ + private pending = new Map(); + /** How many wait for each receiver. */ + private counts = new Map(); + + constructor( + private readonly file: string, + private readonly now: () => number = Date.now, + ) { + let raw = ""; + try { + raw = readFileSync(file, "utf8"); + } catch {} + const lines = raw.split("\n").filter(Boolean); + let next = new Map(); + for (const line of lines) { + try { + const a = JSON.parse(line) as StoredNoticeAck; + if (typeof a?.receiver === "string" && typeof a.id === "string" && typeof a.outcome === "string") + next = this.with(next, a); + } catch {} + } + next = this.live(next); + this.keep(next); + // Written back only when reading changed it: a line cut short, one past its time, two for one + // notice. Not written, it is read the same way next time. + if (next.size !== lines.length) + try { + this.write(next); + } catch {} + } + + /** `list` with `a` added under the outbox's rules, the receiver's cap kept. */ + private with(list: Map, a: StoredNoticeAck): Map { + const k = keyOf(a); + const next = new Map(list); + next.set(k, merged(list.get(k), a)); + const theirs = [...next.values()].filter((x) => x.receiver === a.receiver); + if (theirs.length > NOTICE_ACK_MAX) { + const out = theirs.find((x) => !precious(x)) ?? theirs.find((x) => x.outcome !== "ran") ?? theirs[0]; + next.delete(keyOf(out as StoredNoticeAck)); + } + return next; + } + + private live(list: Map): Map { + const cut = this.now() - NOTICE_SEEN_MS; + return new Map([...list].filter(([, a]) => Date.parse(a.at) > cut)); + } + + private write(list: Map): void { + mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 }); + const body = [...list.values()].map((a) => JSON.stringify(a)).join("\n"); + writeWhole(this.file, body ? `${body}\n` : ""); + } + + private keep(next: Map): void { + this.pending = next; + this.counts = new Map(); + for (const a of next.values()) this.counts.set(a.receiver, (this.counts.get(a.receiver) ?? 0) + 1); + } + + /** Make `next` the outbox: on disk first. */ + private commit(next: Map): void { + this.write(next); + this.keep(next); + } + + /** Every ack that waits, oldest first. */ + all(): StoredNoticeAck[] { + const next = this.live(this.pending); + if (next.size !== this.pending.size) this.commit(next); + return [...this.pending.values()]; + } + + add(a: StoredNoticeAck): void { + const k = keyOf(a); + const was = this.pending.get(k); + if (merged(was, a) === was) return; + // A new ack under the receiver's cap: one line appended, then one entry. A final in place of + // `taken`, or one that makes room: the file rewritten. + const n = this.counts.get(a.receiver) ?? 0; + if (!was && n < NOTICE_ACK_MAX) { + mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 }); + appendFileSync(this.file, `${JSON.stringify(a)}\n`, { mode: 0o600 }); + this.pending.set(k, a); + this.counts.set(a.receiver, n + 1); + } else this.commit(this.with(this.pending, a)); + } + + /** Accepted by their receiver: gone, unless something replaced them meanwhile. */ + sent(acks: readonly StoredNoticeAck[]): void { + const next = new Map(this.pending); + for (const a of acks) if (next.get(keyOf(a)) === a) next.delete(keyOf(a)); + if (next.size !== this.pending.size) this.commit(next); + } + + /** Only these pairings' acks are kept: one no longer paired has nobody to tell. */ + only(receivers: ReadonlySet): void { + const next = new Map([...this.pending].filter(([, a]) => receivers.has(a.receiver))); + if (next.size !== this.pending.size) this.commit(next); + } +} + +/** What to do with one notice of a poll answer. `drop`: nothing to ack, its id can't be read. + * `hold`: no ack and nothing runs, so the receiver sends it again (it could not be recorded, or + * its first ack has not gone out yet). + * `ack`: answered here, nothing runs. `fire`: the engine runs `rule` for it, and says its + * outcome. */ +export type NoticeStep = + | { do: "drop" } + | { do: "hold"; id: string; why: "unrecorded" | "in_hand" } + | { do: "ack"; id: string; result: NoticeResult } + | { do: "fire"; id: string; rule: string; notice: ControlNotice }; + +export interface NoticeCtx { + now: number; + /** Triggers are on, the rules file read whole, and this receiver's name is its own. */ + on: boolean; + seen: NoticeSeen; + /** The pairing the notice came from (`control + machine`): what `seen` keys it by. */ + receiver: string; + /** The first rule that takes it (§14.7 step 6), the machine's pauses counted. */ + match(n: ControlNotice): TriggerRule | null; + /** The engine has this notice in hand and has said nothing of it yet (a run that is still + * looking before it begins or waits). */ + inHand(id: string): boolean; +} + +/** One notice, §14.7 steps 1 to 6 in order, stopping at the first that fails. The id is recorded + * before anything runs: a crash after it means the notice comes again as `duplicate` and runs + * nothing, at most once as the spec chooses. */ +export function takeNotice(raw: unknown, ctx: NoticeCtx): NoticeStep { + const id = noticeId(raw); + if (id === null) return { do: "drop" }; + if (!ctx.on) return { do: "ack", id, result: { outcome: "refused", code: "triggers_off" } }; + const r = parseNotice(raw, ctx.now); + if (!r.ok) + return { + do: "ack", + id, + result: r.code === "expired" ? { outcome: "expired" } : { outcome: "refused", code: "bad_notice" }, + }; + // Sent again before its first ack went out: held, so `duplicate` never reaches the receiver + // ahead of the `taken` or `ran` that is coming. + if (ctx.seen.has(ctx.receiver, id)) + return ctx.inHand(id) ? { do: "hold", id, why: "in_hand" } : { do: "ack", id, result: { outcome: "duplicate" } }; + try { + ctx.seen.record(ctx.receiver, id); + } catch { + return { do: "hold", id, why: "unrecorded" }; + } + const rule = ctx.match(r.notice); + return rule + ? { do: "fire", id, rule: rule.name, notice: r.notice } + : { do: "ack", id, result: { outcome: "no_match" } }; +} diff --git a/packages/cli/src/control/rules-file.ts b/packages/cli/src/control/rules-file.ts index 4e312f8a..6ba4bb48 100644 --- a/packages/cli/src/control/rules-file.ts +++ b/packages/cli/src/control/rules-file.ts @@ -22,6 +22,17 @@ export const triggersFile = (env: NodeJS.ProcessEnv = process.env): string => export const triggerStateFile = (env: NodeJS.ProcessEnv = process.env): string => path.join(controlState(env), "triggers-state.json"); +/** What tells the rules file changed without reading it: its inode, size and time ("none" when + * it is not there). The daemon looks before it takes a poll's notices. */ +export function rulesStamp(env: NodeJS.ProcessEnv = process.env): string { + try { + const s = statSync(triggersFile(env)); + return `${s.ino}:${s.size}:${s.mtimeMs}`; + } catch { + return "none"; + } +} + /** The rules file as a machine reads it: not there, read whole, or refused whole with every * problem (CONTROL.md §14.1: "a file that does not fit this, or is not there, is read as no * rules with triggers off"). */ diff --git a/packages/cli/src/control/triggers.ts b/packages/cli/src/control/triggers.ts index a0a704e3..5434d37b 100644 --- a/packages/cli/src/control/triggers.ts +++ b/packages/cli/src/control/triggers.ts @@ -299,6 +299,11 @@ export class TriggerEngine { /** Notices this engine was given by `fire`, and those already given their final ack. */ private readonly heard = new Set(); private readonly finals = new Set(); + /** Notices given to `fire` whose first ack has not gone out (a run still looking before it + * begins or waits): one sent again meanwhile is held, never `duplicate` ahead of its outcome. + * Every other way through `fire` says something at once, and a rule runs one at a time (the + * next waits, told `taken`), so this holds at most one notice per rule. */ + private readonly unsaid = new Set(); /** The daemon stopped (`suspend`): nothing more is done, said or saved. */ private stopped = false; @@ -403,6 +408,11 @@ export class TriggerEngine { return this.file ? firstRule({ ...this.file, rules: this.rules() }, receiver, n) : null; } + /** A notice from `receiver` this engine took and has said nothing of yet. */ + inHand(receiver: string, id: string): boolean { + return this.unsaid.has(`${receiver}\n${id}`); + } + /** The rules the machine has paused itself, by name. */ pausedByMachine(): string[] { return Object.entries(this.state.rules) @@ -434,6 +444,7 @@ export class TriggerEngine { const k = `${cause.receiver}\n${cause.notice.id}`; this.heard.add(k); if (this.heard.size > 10_000) this.heard.delete(this.heard.values().next().value as string); + this.unsaid.add(k); } let taken: Waiting | null = null; try { @@ -789,10 +800,12 @@ export class TriggerEngine { // run's own deadline, refused for what it waits for when that passes. running.queued = true; w.reason = why; - if (!w.told) this.tell(w.cause, { outcome: "taken" }); + const said = w.told; w.told = true; - // Its count is on disk from here, as a waiting run's is. + // Its count is on disk from here, as a waiting run's is: saved before `taken` is said, so + // a crash between the two never leaves a `taken` with no run to give its final ack. this.saved(); + if (!said) this.tell(w.cause, { outcome: "taken" }); }, began: (session) => { if (gone()) return; @@ -839,20 +852,22 @@ export class TriggerEngine { } w.reason = reason; this.waits.push(w); - if (!w.told) this.tell(w.cause, { outcome: "taken" }); const said = w.told; w.told = true; - if (!said) - this.deps.log( - `trigger ${w.rule}: waits (${reason === "held" ? "a window holds its session" : reason === "busy" ? "its own earlier run is still going" : "the machine's caps on starts are reached"})`, - ); + // On disk before `taken` is said (see `queued`). this.saved(); + if (said) return; + this.tell(w.cause, { outcome: "taken" }); + this.deps.log( + `trigger ${w.rule}: waits (${reason === "held" ? "a window holds its session" : reason === "busy" ? "its own earlier run is still going" : "the machine's caps on starts are reached"})`, + ); } /** A notice's ack: only for a notice this machine received, and one final ack at most. */ private tell(cause: Cause, r: NoticeResult): void { if (cause.kind !== "notice") return; const key = `${cause.receiver}\n${cause.notice.id}`; + this.unsaid.delete(key); if (!this.heard.has(key) && !this.deps.received?.(cause.receiver, cause.notice.id)) return; if (r.outcome !== "taken") { if (this.finals.has(key)) return; diff --git a/packages/cli/src/triggers.ts b/packages/cli/src/triggers.ts index b5f30540..1a459428 100644 --- a/packages/cli/src/triggers.ts +++ b/packages/cli/src/triggers.ts @@ -45,6 +45,7 @@ import { readConfig, realFolderProblem, realPath, + receiverName, ruleFolder, type StartPermission, sampleNotice, @@ -708,28 +709,28 @@ function buildRule(p: Parsed, d: TriggerDeps, h: Here, f: TriggersFile) { const notes: string[] = []; // Where it comes from: a receiver's notices on a topic, or a clock. - const receiverName = one(p, "--on"); + const onName = one(p, "--on"); const every = one(p, "--every"); - if (!!receiverName === !!every) + if (!!onName === !!every) throw new Refusal( 'a rule runs on a receiver\'s notices (--on --topic ) or on a clock (--every "mon 09:00"): one of the two', "sessionpipe trigger add --help", ); let source: TriggerRule["source"]; let pairedUrl: string | null = null; - if (receiverName) { + if (onName) { const topic = one(p, "--topic"); if (!topic) throw new Refusal( "a rule on a receiver's notices names their topic: --topic ", "sessionpipe trigger add --help", ); - const host = hostOf(receiverName); - const paired = (control?.receivers ?? []).filter((r) => hostOf(r.url) === host); + const host = receiverName(onName); + const paired = (control?.receivers ?? []).filter((r) => receiverName(r.url) === host); if (!paired.length) throw new Refusal( - `this computer isn't paired with ${visible(host ?? receiverName)}: a rule takes notices only from a receiver it is paired with`, - `sessionpipe control pair ${host ?? receiverName}`, + `this computer isn't paired with ${visible(host ?? onName)}: a rule takes notices only from a receiver it is paired with`, + `sessionpipe control pair ${host ?? onName}`, ); if (paired.length > 1) throw new Refusal( @@ -869,12 +870,12 @@ async function add(p: Parsed, o: TriggerOut, d: TriggerDeps): Promise { const wk = await d.wellKnown(pairedUrl); if (wk.control?.notices !== true) warn.push( - `${hostOf(pairedUrl)} doesn't say it sends notices (control.notices in its well-known file), so this rule will never run until it does.`, + `${receiverName(pairedUrl)} doesn't say it sends notices (control.notices in its well-known file), so this rule will never run until it does.`, ); } catch (e) { warn.push( // Never the other side's own text (an error's words carry bytes of the body): ours. - `${hostOf(pairedUrl)}'s well-known file couldn't be read now, so whether it sends notices isn't known.`, + `${receiverName(pairedUrl)}'s well-known file couldn't be read now, so whether it sends notices isn't known.`, ); } } @@ -952,18 +953,6 @@ function checkWhole(f: TriggersFile, env: NodeJS.ProcessEnv): string | null { return v.ok ? null : said(v.problems[0] as string).replace(/^\$\.rules\[\d+\](?: \([^)]*\))?: /, ""); } -/** The receiver's name as a rule says it: the host (and port, when not the default) of its - * address, lowercase. A bracketed IPv6 address is no name a rule takes. */ -export function hostOf(s: string): string | null { - try { - const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `https://${s}`); - const host = u.host.toLowerCase(); - return host.startsWith("[") ? null : host; - } catch { - return null; - } -} - async function list(p: Parsed, o: TriggerOut, d: TriggerDeps): Promise { const h = await here(d); if (p.flags.has("--json")) return printJson(o, "trigger-list", listOf(h)); diff --git a/packages/cli/test/control-notices-live.test.ts b/packages/cli/test/control-notices-live.test.ts new file mode 100644 index 00000000..9cd4ce8e --- /dev/null +++ b/packages/cli/test/control-notices-live.test.ts @@ -0,0 +1,475 @@ +// SPDX-License-Identifier: Apache-2.0 +// Notices on the wire (CONTROL.md §14.3, §14.4, §14.7): a daemon paired with the test receiver, +// whose notices are the reference receiver's own state machine (packages/receiver/src/notices.ts). +// The hello's `triggers`, a notice in a poll answer, `POST {control}/notices/ack`, the 25-hour +// dedup across a restart, a receiver that misbehaves, two daemons and two pairings on one host. +// The agent is a stand-in `claude` that logs how it was run. +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + utimesSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { runHeadless, type TriggerRule, type TriggersFile } from "@sessionpipe/core"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { ControlDaemon, type DaemonDeps } from "../src/control/daemon.js"; +import { NOTICE_POLL_GAP_MS } from "../src/control/notices.js"; +import type { ControlConfig, PairedReceiver } from "../src/control/store.js"; +import type { TriggerState } from "../src/control/triggers.js"; +import { jsonLines } from "./helpers/lines.js"; +import { FakeReceiver } from "./helpers/receiver.js"; + +const SID = "8c132906-8c3f-4814-870a-afc3d05e1d2e"; +const unix = process.platform !== "win32"; + +let tmp: string; +let state: string; +let project: string; +let configDir: string; +let calls: string; +let fakeClaude: string; +let file: TriggersFile | null; +let logs: string[]; +let rx: FakeReceiver; +const daemons: ControlDaemon[] = []; +const receivers: FakeReceiver[] = []; + +interface Run { + argv: string[]; + triggered_by: string | null; +} +const runs = (): Run[] => (existsSync(calls) ? jsonLines(calls) : []); +const until = async (ok: () => boolean, ms = 8000) => { + for (const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 25))) if (ok()) return; + throw new Error("waited too long"); +}; +const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); +/** A notice id: a ULID's 26 characters. */ +const nid = (i: number) => `01KB4M2Q8V3T6Y9C0D1E2F${String(i).padStart(4, "0")}`; +const nameOf = (r: FakeReceiver) => new URL(r.url).host; + +function writeFake(): void { + writeFileSync( + fakeClaude, + `#!/usr/bin/env node +const fs = require("fs"); +const a = process.argv.slice(2); +fs.appendFileSync(${JSON.stringify(calls)}, JSON.stringify({ argv: a, triggered_by: process.env.SESSIONPIPE_TRIGGERED_BY || null }) + "\\n"); +const i = a.indexOf("--resume"), j = a.indexOf("--session-id"); +const sid = i >= 0 ? a[i + 1] : j >= 0 ? a[j + 1] : "x"; +process.stdout.write(JSON.stringify({ type: "result", result: "done", session_id: sid, is_error: false })); +`, + ); + chmodSync(fakeClaude, 0o755); +} + +function transcript(sid: string): void { + const dir = path.join(configDir, "projects", project.replace(/[^a-zA-Z0-9]/g, "-")); + mkdirSync(dir, { recursive: true }); + const f = path.join(dir, `${sid}.jsonl`); + writeFileSync(f, `${JSON.stringify({ type: "user", cwd: project, message: { content: "hi" } })}\n`); + const past = new Date("2026-01-01T00:00:00.000Z"); + utimesSync(f, past, past); +} +const holdRow = () => path.join(configDir, "sessions", `${process.pid}.json`); +const holds = (sid: string) => + writeFileSync(holdRow(), JSON.stringify({ sessionId: sid, pid: process.pid, kind: "interactive" })); + +const paired = (r: FakeReceiver, machine = r.machine): PairedReceiver => ({ + url: r.url, + control: `${r.url}/api/sessionpipe/v1/control`, + rpId: "localhost", + machine, + token: r.token, + keys: [{ ...r.passkey.key, added_at: new Date().toISOString() }], + paired_at: new Date().toISOString(), +}); +const keyOf = (r: FakeReceiver, machine = r.machine) => `${r.url}/api/sessionpipe/v1/control${machine}`; + +const card = (over: Partial = {}): TriggerRule => ({ + name: "card", + paused: false, + source: { receiver: nameOf(rx), topic: "acme/tasks" }, + target: { start: "claude-code" }, + folder: project, + level: "edits", + cap: { per_day: 5 }, + words: "Card {subject}.", + ...over, +}); +const on = (...rules: TriggerRule[]): TriggersFile => ({ v: 1, on: true, rules }); + +/** A notice as a receiver would send it, made now. */ +const raw = (id: string, over: Record = {}) => ({ + id, + topic: "acme/tasks", + event: "record.updated", + subject: "X-001", + at: new Date().toISOString(), + expires_at: new Date(Date.now() + 3600_000).toISOString(), + ...over, +}); + +async function receiver(): Promise { + const r = new FakeReceiver(); + await r.start(); + receivers.push(r); + return r; +} + +async function startDaemon( + o: { receivers?: PairedReceiver[]; sock?: string; extra?: Partial } = {}, +): Promise { + const c: ControlConfig = { + name: "studio-mac", + folders: [project], + mode: "auto", + receivers: o.receivers ?? [paired(rx)], + }; + const d = new ControlDaemon(c, state, o.sock ?? path.join(tmp, `control-${daemons.length}.sock`), { + now: Date.now, + fetch, + log: (s) => { + logs.push(s); + if (process.env.SP_DEBUG) console.error(`[daemon] ${s}`); + }, + claudeDirs: () => [configDir], + claude: () => ({ + bin: fakeClaude, + caps: { + hasMode: true, + modes: ["default", "dontAsk", "acceptEdits", "plan", "auto"], + promptsNone: false, + fork: true, + }, + }), + run: runHeadless, + env: { ...process.env, CLAUDE_CONFIG_DIR: configDir }, + harnesses: () => ["claude-code"], + rules: () => file, + triggerZone: "UTC", + triggerCheckMs: 50, + ...o.extra, + }); + daemons.push(d); + await d.start(); + return d; +} + +/** The last hello a receiver heard says this of triggers. */ +const heard = (r: FakeReceiver, t: unknown) => () => JSON.stringify(r.hellos.at(-1)?.triggers) === JSON.stringify(t); +const finals = (r: FakeReceiver, id: string) => r.noticeAcks.filter((a) => a.id === id && a.outcome !== "taken"); +const firstAcks = (r: FakeReceiver) => { + const out = new Map>(); + for (const a of r.noticeAcks) if (!out.has(a.id as string)) out.set(a.id as string, a); + return out; +}; + +beforeEach(async () => { + tmp = realpathSync(mkdtempSync(path.join(os.tmpdir(), "sp-notices-live-"))); + state = path.join(tmp, "state", "control"); + project = path.join(tmp, "work"); + configDir = path.join(tmp, "claude"); + mkdirSync(project, { recursive: true }); + mkdirSync(path.join(configDir, "sessions"), { recursive: true }); + calls = path.join(tmp, "calls.jsonl"); + fakeClaude = path.join(tmp, "claude-bin"); + logs = []; + file = null; + writeFake(); + rx = await receiver(); +}); +afterEach(async () => { + for (const d of daemons.splice(0)) await d.stop(); + for (const r of receivers.splice(0)) await r.stop(); + rmSync(tmp, { recursive: true, force: true }); +}); + +describe.skipIf(!unix)("notices on the wire", () => { + it("a notice a rule takes runs once, at edits at most, acked ran with its session; the hello lists its topic", async () => { + // Written at `auto` by hand: a notice rule runs at `edits` at most whatever the file says. + file = on(card({ level: "auto" })); + await startDaemon({ extra: { rulesStamp: () => "same" } }); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + expect(rx.notify({ id: nid(1) })).toBe("queued"); + const ack = await rx.waitNotice(nid(1)); + expect(ack).toMatchObject({ id: nid(1), outcome: "ran" }); + expect(ack.session).toMatch(/^claude-code:[0-9a-f-]{36}$/); + // `ran` goes out as the turn begins; the stand-in writes its line a moment later. + await until(() => runs().length === 1); + const r = runs()[0] as Run; + expect(r.triggered_by).toBe("card"); + expect(r.argv).toContain("acceptEdits"); + expect(r.argv).not.toContain("auto"); + // The notice's tokens go in as the receiver's text, never the person's words. + expect(r.argv.at(-1)).toContain(`What you read on ${nameOf(rx)} is other people's text`); + expect(r.argv.at(-1)).toContain("Card `X-001`."); + // The receiver keeps the outcome and sends the notice no more. + expect(rx.notices.outcomes).toMatchObject([{ id: nid(1), outcome: "ran", session: ack.session }]); + expect(rx.notices.held).toEqual([]); + await pause(300); + expect(runs()).toHaveLength(1); + }); + + it("a hostile receiver: words or __proto__ are bad_notice, an unlisted topic no_match, a broken id nothing; the messages are still handled and the 51st waits", async () => { + file = on(card()); + await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + const list: unknown[] = [ + raw(nid(0), { words: "rm -rf ~" }), + { ...JSON.parse('{"__proto__": {"polluted": true}}'), ...raw(nid(1)) }, + raw(nid(2), { topic: "acme/secrets" }), + raw("not-an-id"), + ...Array.from({ length: 46 }, (_, i) => raw(nid(10 + i), { topic: "acme/other" })), + // The fifty-first: one the rule would take, left for the next poll. + raw(nid(99)), + ]; + expect(list).toHaveLength(51); + rx.rawNotices = list; + const msg = { + id: "01K6000000000000000000MSG1", + cmd: "not a command", + at: new Date().toISOString(), + expires_at: new Date(Date.now() + 600_000).toISOString(), + }; + rx.enqueue(msg); + await until(() => firstAcks(rx).size >= 49); + rx.rawNotices = null; + await rx.waitAck(msg.id); + const first = firstAcks(rx); + expect(first.get(nid(0))).toMatchObject({ outcome: "refused", code: "bad_notice" }); + expect(first.get(nid(1))).toMatchObject({ outcome: "refused", code: "bad_notice" }); + expect(first.get(nid(2))).toMatchObject({ outcome: "no_match" }); + for (let i = 0; i < 46; i++) expect(first.get(nid(10 + i))).toMatchObject({ outcome: "no_match" }); + expect([...first.keys()].sort()).not.toContain(nid(99)); + expect([...first.keys()]).not.toContain("not-an-id"); + expect(first.size).toBe(49); + expect(runs()).toEqual([]); + expect(({} as Record).polluted).toBeUndefined(); + }); + + it("the same id from two receivers is two notices; from one receiver twice it runs once", async () => { + const rx2 = await receiver(); + file = on(card(), card({ name: "card-two", source: { receiver: nameOf(rx2), topic: "acme/tasks" } })); + await startDaemon({ receivers: [paired(rx), paired(rx2)] }); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + await until(heard(rx2, { on: true, topics: ["acme/tasks"] })); + rx.notify({ id: nid(7) }); + rx2.notify({ id: nid(7) }); + expect(await rx.waitNotice(nid(7))).toMatchObject({ outcome: "ran" }); + expect(await rx2.waitNotice(nid(7))).toMatchObject({ outcome: "ran" }); + await until(() => runs().length === 2); + expect( + runs() + .map((r) => r.triggered_by) + .sort(), + ).toEqual(["card", "card-two"]); + // The first receiver sends it again, as one that lost its ack would. + rx.rawNotices = [raw(nid(7))]; + await until(() => finals(rx, nid(7)).some((a) => a.outcome === "duplicate")); + rx.rawNotices = null; + expect(runs()).toHaveLength(2); + // The receiver kept the session: a duplicate never replaces the ack it had. + expect(rx.notices.outcomes).toMatchObject([{ id: nid(7), outcome: "ran" }]); + }); + + it("an id recorded before a crash comes again as duplicate and runs nothing", async () => { + file = on(card()); + mkdirSync(state, { recursive: true }); + writeFileSync( + path.join(state, "notices-seen.jsonl"), + `${JSON.stringify({ r: keyOf(rx), i: nid(3), t: Date.now() - 60_000 })}\n`, + ); + await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + rx.notify({ id: nid(3) }); + expect(await rx.waitNotice(nid(3))).toMatchObject({ outcome: "duplicate" }); + await pause(200); + expect(runs()).toEqual([]); + }); + + it("a run that waits outlives a restart: taken once, then one run and one final ack", async () => { + transcript(SID); + holds(SID); + file = on(card({ target: { continue: `claude-code:${SID}` } })); + const first = await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + rx.notify({ id: nid(5) }); + await until(() => rx.noticeAcks.some((a) => a.id === nid(5) && a.outcome === "taken")); + expect(rx.notices.taken.map((h) => h.notice.id)).toEqual([nid(5)]); + await first.stop(); + daemons.splice(daemons.indexOf(first), 1); + const kept = JSON.parse(readFileSync(path.join(state, "triggers-state.json"), "utf8")) as TriggerState; + expect(kept.waiting).toMatchObject([{ rule: "card", told: true }]); + rmSync(holdRow()); + await startDaemon(); + const ack = await rx.waitNotice(nid(5)); + expect(ack).toEqual(expect.objectContaining({ outcome: "ran", session: `claude-code:${SID}` })); + await pause(300); + expect(runs()).toHaveLength(1); + expect(rx.noticeAcks.filter((a) => a.id === nid(5)).map((a) => a.outcome)).toEqual(["taken", "ran"]); + }); + + it("a receiver that refuses notice acks: one waits per notice, nothing runs twice; sent once it takes them", async () => { + file = on(card()); + await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + rx.noticeAckStatus = 500; + rx.notify({ id: nid(6) }); + await until(() => runs().length === 1); + const polled = rx.polls.length; + // Sent again on every poll (no ack accepted), and a duplicate each time, which never queues + // behind the ran that waits. + await until(() => rx.polls.length >= polled + 2, 10_000); + const box = path.join(state, "notice-acks.jsonl"); + expect(jsonLines<{ id: string; outcome: string }>(box)).toMatchObject([{ id: nid(6), outcome: "ran" }]); + expect(runs()).toHaveLength(1); + // A connection dropped unanswered is no ack either. + rx.noticeAckStatus = 0; + const tried = rx.noticeAcks.length; + await until(() => rx.noticeAcks.length > tried, 10_000); + expect(jsonLines<{ id: string; outcome: string }>(box)).toMatchObject([{ id: nid(6), outcome: "ran" }]); + if (unix) { + // The receiver takes them now, but the outbox can't be rewritten: said in the log, kept. + chmodSync(state, 0o500); + chmodSync(box, 0o400); + rx.noticeAckStatus = 202; + try { + await until(() => logs.some((l) => l.startsWith("notice acks: ") && l.endsWith("tried again in 5 s"))); + } finally { + chmodSync(state, 0o700); + chmodSync(box, 0o600); + } + } + rx.noticeAckStatus = 202; + await until(() => rx.notices.outcomes.some((o) => o.id === nid(6) && o.outcome === "ran"), 10_000); + await until(() => readFileSync(box, "utf8") === ""); + expect(runs()).toHaveLength(1); + }); + + it("triggers off written a moment ago holds for the next notice, before the file's watcher looks", async () => { + let stamp = "1"; + file = on(card()); + await startDaemon({ extra: { rulesStamp: () => stamp } }); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + // `trigger off` wrote the file; the watcher has not said so yet. + file = { ...file, on: false }; + stamp = "2"; + rx.notify({ id: nid(8) }); + expect(await rx.waitNotice(nid(8))).toMatchObject({ outcome: "refused", code: "triggers_off" }); + expect(runs()).toEqual([]); + await until(heard(rx, { on: false, topics: [] })); + }); + + it("two daemons: the one without the rules' claim says off, acks nothing and writes none of their files", async () => { + const rx2 = await receiver(); + file = on(card({ source: { receiver: nameOf(rx2), topic: "acme/tasks" } })); + await startDaemon(); + await until(heard(rx, { on: true, topics: [] })); + const files = ["triggers-state.json", "notices-seen.jsonl", "notice-acks.jsonl"].map((f) => path.join(state, f)); + const before = files.map((f) => (existsSync(f) ? readFileSync(f, "utf8") : null)); + rx2.rawNotices = [raw(nid(9))]; + await startDaemon({ receivers: [paired(rx2)] }); + expect(logs).toContain("another daemon runs the trigger rules; this one runs none until it stops"); + await until(() => rx2.polls.length >= 3, 10_000); + expect(rx2.hellos.map((h) => h.triggers)).toEqual(rx2.hellos.map(() => ({ on: false, topics: [] }))); + expect(rx2.noticeAcks).toEqual([]); + expect(files.map((f) => (existsSync(f) ? readFileSync(f, "utf8") : null))).toEqual(before); + expect(runs()).toEqual([]); + }); + + it("two pairings on one host: neither triggers a rule; one added says off at once, and a waiting run's ack still goes to the pairing it came from", async () => { + transcript(SID); + holds(SID); + file = on(card({ target: { continue: `claude-code:${SID}` } })); + const d = await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + // The daemon keeps the pairing of 10 000 notices at most; here of one, so the first notice's is + // let go of when the second comes, and its outcome is routed by name alone. + (d as unknown as { noticeFromMax: number }).noticeFromMax = 1; + rx.notify({ id: nid(15), subject: "X-002" }); + await until(() => rx.noticeAcks.some((a) => a.id === nid(15) && a.outcome === "taken")); + rx.notify({ id: nid(11) }); + await until(() => rx.noticeAcks.some((a) => a.id === nid(11) && a.outcome === "taken")); + // A second pairing with the same host: whose name it is can't be told any more. + d.reload({ name: "studio-mac", folders: [project], mode: "auto", receivers: [paired(rx), paired(rx, "m_other")] }); + await until(heard(rx, { on: false, topics: [] })); + rx.rawNotices = [raw(nid(12))]; + await until(() => finals(rx, nid(12)).length > 0); + rx.rawNotices = null; + expect(finals(rx, nid(12))[0]).toMatchObject({ outcome: "refused", code: "triggers_off" }); + // The runs taken before go on, their rule unchanged. The one whose pairing is kept is told on + // it; the other has nobody to tell, its name no longer one pairing's alone. + rmSync(holdRow()); + expect(await rx.waitNotice(nid(11))).toMatchObject({ outcome: "ran", session: `claude-code:${SID}` }); + await until(() => runs().length === 2); + await pause(300); + expect(finals(rx, nid(15))).toEqual([]); + }); + + it("a notice sent again while its run is still looking (a slow sign-in check) is held: never duplicate before its outcome", async () => { + file = on(card()); + await startDaemon({ + extra: { + login: async () => { + await pause(1500); + return { loggedIn: true }; + }, + }, + }); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + const polled = rx.polls.length; + rx.notify({ id: nid(16) }); + expect(await rx.waitNotice(nid(16))).toMatchObject({ outcome: "ran" }); + // The receiver sent it again while the run looked: the poll gap is shorter than the look. + expect(rx.polls.length).toBeGreaterThanOrEqual(polled + 1); + // `taken` once the look is done, then `ran`: nothing before them, and no `duplicate` at all. + expect(rx.noticeAcks.filter((a) => a.id === nid(16)).map((a) => a.outcome)).toEqual(["taken", "ran"]); + await until(() => runs().length === 1); + }); + + it("hello on, off, on in quick succession ends on", async () => { + file = on(card()); + const d = await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + for (const f of [{ ...file, on: false }, file, { ...file, on: false }, file]) { + file = f; + d.reloadRules(); + } + await pause(500); + expect(rx.hellos.at(-1)?.triggers).toEqual({ on: true, topics: ["acme/tasks"] }); + }); + + it("a receiver that sends notices on every answer is polled at a bounded rate", async () => { + file = on(card()); + await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + rx.rawNotices = [raw(nid(13), { topic: "acme/other" })]; + const from = rx.polls.length; + await pause(3200); + const times = rx.polls.slice(from); + expect(times.length).toBeGreaterThanOrEqual(2); + expect(times.length).toBeLessThanOrEqual(4); + for (let i = 1; i < times.length; i++) + expect((times[i] as number) - (times[i - 1] as number)).toBeGreaterThanOrEqual(NOTICE_POLL_GAP_MS - 50); + expect(firstAcks(rx).get(nid(13))).toMatchObject({ outcome: "no_match" }); + }); + + it("an id that can't be recorded is held: no ack, nothing runs, said in the log", async () => { + file = on(card()); + mkdirSync(path.join(state, "notices-seen.jsonl"), { recursive: true }); + await startDaemon(); + await until(heard(rx, { on: true, topics: ["acme/tasks"] })); + rx.notify({ id: nid(14) }); + await until(() => logs.some((l) => l.endsWith("1 notice(s) could not be recorded; they come again"))); + expect(rx.noticeAcks).toEqual([]); + expect(runs()).toEqual([]); + }); +}); diff --git a/packages/cli/test/control-notices.test.ts b/packages/cli/test/control-notices.test.ts new file mode 100644 index 00000000..35a66396 --- /dev/null +++ b/packages/cli/test/control-notices.test.ts @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: Apache-2.0 +// The notices step's own corners (control/notices.ts): the 25-hour dedup store, the acks that +// wait for their receiver, and §14.7 steps 1 to 6 in order. The scenario files drive the same +// function through the engine (trigger-engine-fixtures.test.ts); the daemon's poll, live. +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { type ControlNotice, NOTICE_SEEN_MS, type TriggerRule } from "@sessionpipe/core"; +import { afterAll, describe, expect, it } from "vitest"; +import { + NOTICE_ACK_MAX, + NOTICE_SEEN_MAX, + NoticeAckOutbox, + NoticeSeen, + type StoredNoticeAck, + takeNotice, +} from "../src/control/notices.js"; + +const tmp = mkdtempSync(path.join(os.tmpdir(), "sp-notices-")); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); +let n = 0; +const fresh = (name: string) => path.join(tmp, `${++n}`, name); + +const T0 = Date.parse("2026-11-24T09:14:05.000Z"); +const R = "https://board.example/api/sessionpipe/v1/controlm_1"; +const ID = "01KB4M2Q8V3T6Y9C0D1E2F3G4H"; +const notice = (over: Record = {}): ControlNotice => + ({ + id: ID, + topic: "acme/tasks", + event: "record.updated", + subject: "X-001", + at: "2026-11-24T09:14:02.000Z", + expires_at: "2026-11-25T09:14:02.000Z", + ...over, + }) as ControlNotice; +const rule = { name: "card" } as TriggerRule; + +describe("NoticeSeen", () => { + it("records an id before it answers, on disk; a restart still knows it; another receiver's is another notice", () => { + let now = T0; + const file = fresh("notices-seen.jsonl"); + const s = new NoticeSeen(file, () => now); + expect(existsSync(file)).toBe(false); + expect(s.has(R, ID)).toBe(false); + s.record(R, ID); + expect(s.has(R, ID)).toBe(true); + expect(s.has("other", ID)).toBe(false); + if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); + expect(new NoticeSeen(file, () => now).has(R, ID)).toBe(true); + now += NOTICE_SEEN_MS; + expect(s.has(R, ID)).toBe(false); + // Read again past its 25 hours: forgotten, and the file rewritten empty. + expect(new NoticeSeen(file, () => now).has(R, ID)).toBe(false); + expect(readFileSync(file, "utf8")).toBe(""); + }); + + it("skips a line a crash cut short, and lines that are not its own", () => { + const file = fresh("notices-seen.jsonl"); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync( + file, + [ + JSON.stringify({ r: R, i: ID, t: T0 }), + '{"r":"x","i":"01KB', + JSON.stringify({ r: 1, i: ID, t: T0 }), + JSON.stringify({ r: R, i: 2, t: T0 }), + JSON.stringify({ r: R, i: "B", t: "now" }), + "", + ].join("\n"), + ); + const s = new NoticeSeen(file, () => T0); + expect(s.has(R, ID)).toBe(true); + expect(readFileSync(file, "utf8")).toBe(`${JSON.stringify({ r: R, i: ID, t: T0 })}\n`); + }); + + it("compacts once a day as it records", () => { + let now = T0; + const file = fresh("notices-seen.jsonl"); + const s = new NoticeSeen(file, () => now); + s.record(R, ID); + s.record("other", "01KB4M2Q8V3T6Y9C0D1E2F3G4J"); + now += NOTICE_SEEN_MS + 1; + s.record(R, "01KB4M2Q8V3T6Y9C0D1E2F3G4K"); + expect(readFileSync(file, "utf8").trim().split("\n")).toEqual([ + JSON.stringify({ r: R, i: "01KB4M2Q8V3T6Y9C0D1E2F3G4K", t: now }), + ]); + }); + + it("compaction is synced and leaves no file beside it; one that fails leaves the old file whole", () => { + let now = T0; + const file = fresh("notices-seen.jsonl"); + const s = new NoticeSeen(file, () => now); + s.record(R, ID); + s.compact(); + expect(readdirSync(path.dirname(file))).toEqual(["notices-seen.jsonl"]); + expect(readFileSync(file, "utf8")).toBe(`${JSON.stringify({ r: R, i: ID, t: T0 })}\n`); + if (process.platform === "win32") return; + chmodSync(path.dirname(file), 0o500); + try { + now += NOTICE_SEEN_MS; + s.compact(); + } finally { + chmodSync(path.dirname(file), 0o700); + } + expect(readdirSync(path.dirname(file))).toEqual(["notices-seen.jsonl"]); + expect(readFileSync(file, "utf8")).toBe(`${JSON.stringify({ r: R, i: ID, t: T0 })}\n`); + }); + + it("throws when the disk won't take it", () => { + const file = fresh("notices-seen.jsonl"); + mkdirSync(file, { recursive: true }); + const s = new NoticeSeen(file, () => T0); + expect(() => s.record(R, ID)).toThrow(); + expect(s.has(R, ID)).toBe(false); + }); + + it(`holds at most ${NOTICE_SEEN_MAX} live ids per receiver; ones past 25 hours make room`, () => { + let now = T0; + const file = fresh("notices-seen.jsonl"); + mkdirSync(path.dirname(file), { recursive: true }); + const lines = Array.from({ length: NOTICE_SEEN_MAX }, (_, i) => + JSON.stringify({ r: R, i: `x${i}`, t: T0 - NOTICE_SEEN_MS + 3600_000 + i }), + ); + writeFileSync(file, `${lines.join("\n")}\n`); + const s = new NoticeSeen(file, () => now); + expect(() => s.record(R, ID)).toThrow(`${NOTICE_SEEN_MAX} notices in 25 hours from one receiver`); + // Another receiver is not held by this one's flood. + s.record("other", ID); + // Two hours on (no daily compaction due yet), the flood is past its 25 hours. + now = T0 + 2 * 3600_000; + s.record(R, ID); + expect(s.has(R, ID)).toBe(true); + }); +}); + +describe("NoticeAckOutbox", () => { + const ack = (outcome: StoredNoticeAck["outcome"], o: Partial = {}): StoredNoticeAck => + ({ receiver: R, id: ID, outcome, at: new Date(T0).toISOString(), ...o }) as StoredNoticeAck; + + it("one ack waits per notice: a final replaces taken; nothing replaces a final; duplicate waits behind anything", () => { + const file = fresh("notice-acks.jsonl"); + const o = new NoticeAckOutbox(file, () => T0); + o.add(ack("taken")); + o.add(ack("duplicate")); + o.add(ack("taken")); + expect(o.all().map((a) => a.outcome)).toEqual(["taken"]); + o.add(ack("ran", { session: "codex:1" })); + expect(o.all()).toEqual([ack("ran", { session: "codex:1" })]); + o.add(ack("failed")); + o.add(ack("taken")); + o.add(ack("duplicate")); + expect(o.all()).toEqual([ack("ran", { session: "codex:1" })]); + // A final after a duplicate that still waits: the final. + o.add(ack("duplicate", { id: "01KB4M2Q8V3T6Y9C0D1E2F3G4J" })); + o.add(ack("no_match", { id: "01KB4M2Q8V3T6Y9C0D1E2F3G4J" })); + o.add(ack("taken", { receiver: "other" })); + expect( + new NoticeAckOutbox(file, () => T0).all().map((a) => `${a.receiver === R ? "r" : "o"} ${a.outcome}`), + ).toEqual(["r ran", "r no_match", "o taken"]); + if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); + }); + + it("an ack accepted goes; one that replaced it meanwhile stays; a receiver no longer paired loses its", () => { + const file = fresh("notice-acks.jsonl"); + const o = new NoticeAckOutbox(file, () => T0); + o.add(ack("taken")); + o.add(ack("no_match", { receiver: "other" })); + const sending = o.all(); + o.add(ack("ran", { session: "codex:1" })); + o.sent(sending); + expect(o.all()).toEqual([ack("ran", { session: "codex:1" })]); + o.sent(sending); + o.only(new Set([R])); + expect(o.all()).toHaveLength(1); + o.only(new Set()); + expect(new NoticeAckOutbox(file, () => T0).all()).toEqual([]); + expect(readFileSync(file, "utf8")).toBe(""); + }); + + it(`a hostile receiver's flood: at most ${NOTICE_ACK_MAX} wait for it, ran and taken kept, another receiver untouched`, () => { + const file = fresh("notice-acks.jsonl"); + const o = new NoticeAckOutbox(file, () => T0); + const id = (i: number) => `01KB4M2Q8V3T6Y9C0D${String(i).padStart(8, "0")}`; + o.add(ack("ran", { id: id(0), session: "codex:1" })); + o.add(ack("taken", { id: id(1) })); + o.add(ack("no_match", { receiver: "other", id: id(2) })); + for (let i = 10; i < 10 + NOTICE_ACK_MAX * 2; i++) o.add(ack("refused", { id: id(i), code: "bad_notice" })); + const mine = o.all().filter((a) => a.receiver === R); + expect(mine).toHaveLength(NOTICE_ACK_MAX); + expect(mine.slice(0, 2).map((a) => a.outcome)).toEqual(["ran", "taken"]); + // The newest of the flood are the ones kept. + expect(mine.at(-1)?.id).toBe(id(9 + NOTICE_ACK_MAX * 2)); + expect(o.all().filter((a) => a.receiver === "other")).toHaveLength(1); + expect(readFileSync(file, "utf8").trim().split("\n")).toHaveLength(NOTICE_ACK_MAX + 1); + // Read again, the same. + expect(new NoticeAckOutbox(file, () => T0).all()).toEqual(o.all()); + }); + + it("at the cap with only ran and taken waiting, a taken gives way first, then the oldest", () => { + const o = new NoticeAckOutbox(fresh("notice-acks.jsonl"), () => T0); + const id = (i: number) => `01KB4M2Q8V3T6Y9C0D${String(i).padStart(8, "0")}`; + o.add(ack("ran", { id: id(0), session: "codex:1" })); + for (let i = 1; i < NOTICE_ACK_MAX; i++) o.add(ack("taken", { id: id(i) })); + o.add(ack("taken", { id: id(NOTICE_ACK_MAX) })); + expect(o.all()[0]?.outcome).toBe("ran"); + expect(o.all().some((a) => a.id === id(1))).toBe(false); + const ran = new NoticeAckOutbox(fresh("notice-acks.jsonl"), () => T0); + for (let i = 0; i <= NOTICE_ACK_MAX; i++) ran.add(ack("ran", { id: id(i), session: "codex:1" })); + expect(ran.all()).toHaveLength(NOTICE_ACK_MAX); + expect(ran.all()[0]?.id).toBe(id(1)); + }); + + it("read back, one ack per notice whatever the file says; written again only when reading changed it", () => { + const file = fresh("notice-acks.jsonl"); + mkdirSync(path.dirname(file), { recursive: true }); + const lines = [ack("taken"), ack("ran", { session: "codex:1" }), ack("duplicate"), ack("taken")]; + writeFileSync(file, `${lines.map((a) => JSON.stringify(a)).join("\n")}\n`); + expect(new NoticeAckOutbox(file, () => T0).all()).toEqual([ack("ran", { session: "codex:1" })]); + expect(readFileSync(file, "utf8")).toBe(`${JSON.stringify(ack("ran", { session: "codex:1" }))}\n`); + }); + + it.skipIf(process.platform === "win32")("a write the disk refuses throws and changes nothing", () => { + const file = fresh("notice-acks.jsonl"); + const o = new NoticeAckOutbox(file, () => T0); + o.add(ack("taken")); + // Neither beside it nor in place: the folder and the file both refuse. + chmodSync(path.dirname(file), 0o500); + chmodSync(file, 0o400); + try { + expect(() => o.add(ack("ran", { session: "codex:1" }))).toThrow(); + expect(o.all()).toEqual([ack("taken")]); + expect(() => o.sent(o.all())).toThrow(); + expect(() => o.only(new Set())).toThrow(); + expect(o.all()).toEqual([ack("taken")]); + } finally { + chmodSync(path.dirname(file), 0o700); + chmodSync(file, 0o600); + } + // A file it can't rewrite on reading is still read. + writeFileSync(file, `${JSON.stringify(ack("taken"))}\n{"torn\n`); + chmodSync(path.dirname(file), 0o500); + chmodSync(file, 0o400); + try { + expect(new NoticeAckOutbox(file, () => T0).all()).toEqual([ack("taken")]); + } finally { + chmodSync(path.dirname(file), 0o700); + chmodSync(file, 0o600); + } + }); + + it("past 25 hours an ack is dropped, and a line a crash cut short is skipped", () => { + let now = T0; + const file = fresh("notice-acks.jsonl"); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync( + file, + [JSON.stringify(ack("taken")), '{"receiver":"x","id":', JSON.stringify({ receiver: R, id: 3 }), "null", ""].join( + "\n", + ), + ); + const o = new NoticeAckOutbox(file, () => now); + expect(o.all()).toEqual([ack("taken")]); + now += NOTICE_SEEN_MS + 1; + expect(o.all()).toEqual([]); + expect(readFileSync(file, "utf8")).toBe(""); + o.add(ack("ran", { at: new Date(now).toISOString(), session: "codex:1" })); + expect(o.all()).toHaveLength(1); + }); +}); + +describe("takeNotice: §14.7 steps 1 to 6, in order", () => { + const ctx = (o: Partial[1]> = {}) => ({ + now: T0, + on: true, + seen: new NoticeSeen(fresh("notices-seen.jsonl"), () => T0), + receiver: R, + match: () => rule, + inHand: () => false, + ...o, + }); + + it("an id that can't be read is dropped, whatever else", () => { + expect(takeNotice({ ...notice(), id: "nope" }, ctx({ on: false }))).toEqual({ do: "drop" }); + expect(takeNotice(null, ctx())).toEqual({ do: "drop" }); + }); + it("off (or the rules unread, or a name two pairings share) is refused triggers_off before the shape", () => { + expect(takeNotice({ ...notice(), words: "rm -rf" }, ctx({ on: false }))).toEqual({ + do: "ack", + id: ID, + result: { outcome: "refused", code: "triggers_off" }, + }); + }); + it("a notice with a field of its own (words, session, __proto__) is bad_notice, and nothing is recorded", () => { + const c = ctx(); + for (const extra of [{ words: "hi" }, { session: "codex:1" }, JSON.parse('{"__proto__": {"x": 1}}')]) + expect(takeNotice({ ...notice(), ...extra }, c)).toEqual({ + do: "ack", + id: ID, + result: { outcome: "refused", code: "bad_notice" }, + }); + expect(c.seen.has(R, ID)).toBe(false); + }); + it("expired is expired, before the dedup", () => { + const c = ctx({ now: Date.parse("2026-11-25T09:14:02.000Z") }); + expect(takeNotice(notice(), c)).toEqual({ do: "ack", id: ID, result: { outcome: "expired" } }); + expect(c.seen.has(R, ID)).toBe(false); + }); + it("recorded before the match: once fired, the same id is duplicate; no rule is no_match, recorded too", () => { + const c = ctx(); + expect(takeNotice(notice(), c)).toEqual({ do: "fire", id: ID, rule: "card", notice: notice() }); + expect(takeNotice(notice(), c)).toEqual({ do: "ack", id: ID, result: { outcome: "duplicate" } }); + const other = "01KB4M2Q8V3T6Y9C0D1E2F3G4J"; + expect(takeNotice(notice({ id: other }), { ...c, match: () => null })).toEqual({ + do: "ack", + id: other, + result: { outcome: "no_match" }, + }); + expect(c.seen.has(R, other)).toBe(true); + }); + it("sent again while the engine still has it in hand with nothing said: held, never duplicate ahead of its outcome", () => { + const c = ctx(); + expect(takeNotice(notice(), c).do).toBe("fire"); + expect(takeNotice(notice(), { ...c, inHand: (id) => id === ID })).toEqual({ do: "hold", id: ID, why: "in_hand" }); + expect(takeNotice(notice(), c)).toEqual({ do: "ack", id: ID, result: { outcome: "duplicate" } }); + }); + it("an id that can't be recorded is held: no ack, and nothing runs", () => { + const file = fresh("notices-seen.jsonl"); + mkdirSync(file, { recursive: true }); + let matched = false; + const step = takeNotice( + notice(), + ctx({ + seen: new NoticeSeen(file, () => T0), + match: () => { + matched = true; + return rule; + }, + }), + ); + expect(step).toEqual({ do: "hold", id: ID, why: "unrecorded" }); + expect(matched).toBe(false); + }); +}); diff --git a/packages/cli/test/helpers/receiver.ts b/packages/cli/test/helpers/receiver.ts index bf7485cc..06a31a06 100644 --- a/packages/cli/test/helpers/receiver.ts +++ b/packages/cli/test/helpers/receiver.ts @@ -2,12 +2,23 @@ // A receiver that speaks the control half of HTTP.md §3, in-process, for the daemon // tests: well-known, pairing (with a passkey's proof), the per-machine poll with // redelivery until acked (paused by `taken`), acks, hello, off and the files a start -// names (GET {control}/files/{sha256}). The person's side (signing) uses the core -// test authenticator, so every signature is real. +// names (GET {control}/files/{sha256}), and notices (CONTROL.md §14) through the reference +// receiver's own state machine (packages/receiver/src/notices.ts). The person's side (signing) +// uses the core test authenticator, so every signature is real. import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; +import type { ControlNotice } from "@sessionpipe/core"; import { sha256 } from "../../../core/src/control/verify.js"; import { commandStr, DayKey, DeviceKeySim, nonce, Passkey } from "../../../core/test/helpers/authenticator.js"; +import { + emptyNotices, + forPoll, + type MachineNotices, + type OfferResult, + offer, + onAcks, + onHello, +} from "../../../receiver/src/notices.js"; export interface Queued { id: string; @@ -35,6 +46,16 @@ export class FakeReceiver { readonly hellos: Record[] = []; readonly pairs: Record[] = []; readonly polls: number[] = []; + /** The machine's notices as the reference receiver keeps them. */ + notices: MachineNotices = emptyNotices(); + /** Every notice ack posted, accepted or not, in the order they came. */ + readonly noticeAcks: Record[] = []; + /** A misbehaving receiver: these go out as the poll's `notices` on every poll, as they are, + * whatever the machine's hello said. */ + rawNotices: unknown[] | null = null; + /** What `POST {control}/notices/ack` answers; 202 checks the body first (400 when it is not one), + * and 0 drops the connection unanswered. */ + noticeAckStatus = 202; /** How long a message just handed over is held back before it is handed over again. * The daemon asks again the moment a poll answers, before its ack for that answer has * landed; handed the same message, it waits two seconds before its next poll, so as @@ -137,6 +158,48 @@ export class FakeReceiver { return q; } + /** The receiver has news on a topic: held for the machine when its last hello allows it. */ + notify(input: Partial & { id: string }): OfferResult { + const now = Date.now(); + const r = offer( + this.notices, + { + topic: "acme/tasks", + event: "record.updated", + subject: "X-001", + at: new Date(now).toISOString(), + expires_at: new Date(now + 3600_000).toISOString(), + ...input, + }, + now, + ); + this.notices = r.m; + for (const w of this.waiters.splice(0)) w(); + return r.result; + } + + /** The final ack a notice got (the latest that is not `taken`). */ + noticeFinal(id: string): Record | undefined { + return this.noticeAcks.filter((a) => a.id === id && a.outcome !== "taken").at(-1); + } + + async waitNotice(id: string, ms = 10_000): Promise> { + const until = Date.now() + ms; + while (Date.now() < until) { + const a = this.noticeFinal(id); + if (a) return a; + await new Promise((r) => setTimeout(r, 20)); + } + throw new Error(`no final notice ack for ${id}; acks: ${JSON.stringify(this.noticeAcks)}`); + } + + private noticesNow(): unknown[] { + if (this.rawNotices) return this.rawNotices; + const r = forPoll(this.notices, Date.now()); + this.notices = r.m; + return r.notices; + } + enqueue(q: Queued): void { const list = this.queue.get(this.machine) ?? []; list.push(q); @@ -247,9 +310,23 @@ export class FakeReceiver { if (!machineAuth) return send(401); if (u.pathname.startsWith(`${base}/files/`) && req.method === "GET") return this.serveFile(u, req, res); if (u.pathname === `${base}/hello`) { - this.hellos.push(await this.body(req)); + const b = await this.body(req); + this.hellos.push(b); + this.notices = onHello(this.notices, b); return send(204); } + if (u.pathname === `${base}/notices/ack` && req.method === "POST") { + const b = (await this.body(req)) as { acks?: Record[] }; + this.noticeAcks.push(...(Array.isArray(b.acks) ? b.acks : [])); + if (this.noticeAckStatus === 0) { + req.socket.destroy(); + return; + } + if (this.noticeAckStatus !== 202) return send(this.noticeAckStatus); + const r = onAcks(this.notices, b, Date.now()); + this.notices = r.m; + return send(r.ok ? 202 : 400); + } if (u.pathname === `${base}/ack`) { const b = (await this.body(req)) as { acks?: Record[] }; for (const a of b.acks ?? []) { @@ -274,9 +351,13 @@ export class FakeReceiver { const until = Date.now() + wait; for (;;) { const p = this.pending(); - if (p.length) { + const notices = this.noticesNow(); + if (p.length || notices.length) { for (const q of p) q.servedAt = Date.now(); - return send(200, { messages: p.map(({ takenAt: _t, servedAt: _s, ...q }) => q) }); + return send(200, { + messages: p.map(({ takenAt: _t, servedAt: _s, ...q }) => q), + ...(notices.length ? { notices } : {}), + }); } if (Date.now() >= until || req.destroyed) return send(204); await new Promise((r) => { diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 48cc2452..1f9ec5a3 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -317,6 +317,22 @@ describe("shared door handlers", () => { }); }); + it("AgentService.Ask from outside any session: no `from` and an empty chain", async () => { + const seen: unknown[] = []; + const ctx = makeCtx({ + socketAskMany: async (_sock, req) => { + seen.push(req); + return { op: "answer", ask_id: "a2", session: "codex:2", text: "ok", ms: 1 }; + }, + }); + delete ctx.env.CLAUDE_CODE_SESSION_ID; + delete ctx.env.CODEX_SESSION_ID; + delete ctx.env.SESSIONPIPE_ASK_CHAIN; + await invokeDoor("AgentService.Ask", { target: "codex", task: "hello" }, ctx); + expect(seen[0]).toMatchObject({ op: "ask", harness: "codex", chain: [] }); + expect(seen[0]).not.toHaveProperty("from"); + }); + it("AgentService.Ask sets `from`, resolves relative `cwd`, validates target/permission, and maps daemon replies", async () => { const seen: unknown[] = []; const ctx = makeCtx({ diff --git a/packages/cli/test/trigger-engine-fixtures.test.ts b/packages/cli/test/trigger-engine-fixtures.test.ts index 906839d0..9161c9b4 100644 --- a/packages/cli/test/trigger-engine-fixtures.test.ts +++ b/packages/cli/test/trigger-engine-fixtures.test.ts @@ -6,28 +6,26 @@ // folder, the harness and the levels it takes, the session a rule continues, the caps on starts, // a window that holds a session, the clock, waking, turning off, the machine's own pause. // -// Steps 1 to 6 of §14.7 are not the engine's: the notices step reads the id, the switch, the -// shape, the expiry, the dedup and the match, then calls `fire`. Here they are done by the test, -// as that step will do them, with core's functions and the engine's own `firstMatch`; the poll's -// messages are the command path's. So notice-duplicate, notice-broken-id and notice-bad-shape run -// here too, and what they check beyond the engine waits for the notices on the wire. -import { readdirSync, readFileSync } from "node:fs"; +// Steps 1 to 6 of §14.7 are the notices step's (control/notices.ts `takeNotice`): the id, the +// switch, the shape, the expiry, the 25-hour dedup in its own store and the match, then `fire`, as +// the daemon's poll does them. The poll's messages are the command path's. +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { checkTriggers, type MachineMode, type NoticeResult, - noticeId, noticesIn, - parseNotice, type StartPermission, type TriggerHistoryLine, type TriggerPlaces, type TriggersFile, } from "@sessionpipe/core"; -import { describe, expect, it } from "vitest"; +import { afterAll, describe, expect, it } from "vitest"; import { localDay, zoneOf } from "../src/control/clock.js"; +import { NoticeSeen, takeNotice } from "../src/control/notices.js"; import { type RunEvents, TriggerEngine, type TriggerJob, type TriggerState } from "../src/control/triggers.js"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); @@ -37,6 +35,9 @@ const files = readdirSync(dir) .filter((f) => f.endsWith(".json") && !PURE.has(f)) .sort(); const H = 3600_000; +const tmp = mkdtempSync(path.join(os.tmpdir(), "sp-trigger-fx-")); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); +let cases = 0; interface Ack { id: string; @@ -149,7 +150,13 @@ function play(c: Case): void { // A minute before the first step: what the case starts from was already so. let now = Date.parse(c.steps[0]!.asleep ?? c.steps[0]!.at) - 60_000; const sessions = structuredClone(c.sessions ?? {}); - const seen = new Map((c.seen ?? []).map((x) => [`${x.receiver}|${x.id}`, Date.parse(x.at)])); + // The machine's dedup store, as the case found it. + const seenFile = path.join(tmp, `seen-${++cases}.jsonl`); + writeFileSync( + seenFile, + (c.seen ?? []).map((x) => `${JSON.stringify({ r: x.receiver, i: x.id, t: Date.parse(x.at) })}\n`).join(""), + ); + const seen = new NoticeSeen(seenFile, () => now); // The machine's caps on starts, as the daemon counts them (startSession): starts in progress, // and starts in a sliding hour, the case's `last_hour` made at its first step's instant. let running = c.starts?.running ?? 0; @@ -297,26 +304,18 @@ function play(c: Case): void { if (s.poll) { const { notices, left } = noticesIn(s.poll.body); for (const raw of notices) { - const id = noticeId(raw); - if (id === null) continue; - if (!file?.on) { - acks.push({ id, outcome: "refused", code: "triggers_off" }); - continue; - } - const r = parseNotice(raw, now); - if (!r.ok) { - acks.push(r.code === "expired" ? { id, outcome: "expired" } : { id, outcome: "refused", code: "bad_notice" }); - continue; - } - const key = `${s.poll.receiver}|${id}`; - if (seen.has(key) && now - (seen.get(key) as number) < 25 * H) { - acks.push({ id, outcome: "duplicate" }); - continue; - } - seen.set(key, now); - const rule = e.firstMatch(s.poll.receiver, r.notice); - if (!rule) acks.push({ id, outcome: "no_match" }); - else e.fire(rule.name, { kind: "notice", receiver: s.poll.receiver, notice: r.notice }); + const step = takeNotice(raw, { + now, + on: !!file?.on, + seen, + receiver: s.poll.receiver, + match: (n) => e.firstMatch((s.poll as NonNullable).receiver, n), + inHand: (id) => e.inHand((s.poll as NonNullable).receiver, id), + }); + expect(step.do, `${where}: nothing is held`).not.toBe("hold"); + if (step.do === "ack") acks.push({ id: step.id, ...step.result }); + else if (step.do === "fire") + e.fire(step.rule, { kind: "notice", receiver: s.poll.receiver, notice: step.notice }); } const past = (s.poll.body.notices ?? []).slice(50).map((n) => (n as { id: string }).id); expect(s.expect.unacked ?? [], where).toEqual(past); diff --git a/packages/cli/test/trigger-engine.test.ts b/packages/cli/test/trigger-engine.test.ts index d6752647..3bef43b0 100644 --- a/packages/cli/test/trigger-engine.test.ts +++ b/packages/cli/test/trigger-engine.test.ts @@ -315,6 +315,29 @@ describe("one run", () => { expect(s.acks.at(-1)).toEqual({ id: notice().id, outcome: "refused", code: "held" }); expect(s.saved?.rules.card?.today?.runs).toBe(0); }); + it("a run that waits is on disk before its notice is told taken: a crash between the two loses no final ack", () => { + for (const how of ["queued", "window"] as const) { + // What the disk had each time a `taken` was said. + const atTaken: number[] = []; + let disk: TriggerState | undefined; + const x = rig({ + ...(how === "queued" ? { answer: (on: RunEvents) => on.queued("held") } : {}), + save: (st) => { + disk = structuredClone(st); + }, + }); + if (how === "window") x.s.session = { held: true, folder: "~/work" }; + const told = x.s.acks.push.bind(x.s.acks); + x.s.acks.push = (...a) => { + for (const ack of a) if (ack.outcome === "taken") atTaken.push(disk?.waiting.length ?? 0); + return told(...a); + }; + x.e.load(file(card({ target: { continue: SID } }))); + x.take(notice({ expires_at: "2026-11-24T10:00:00.000Z" })); + expect(atTaken, how).toEqual([1]); + expect(disk?.waiting[0]?.told, how).toBe(true); + } + }); it("a waiting run whose cause does not fit its rule's source is dropped when read", () => { const { e, s } = rig({ saved: { diff --git a/packages/cli/test/triggers-cli.test.ts b/packages/cli/test/triggers-cli.test.ts index 08d98550..e5595cb5 100644 --- a/packages/cli/test/triggers-cli.test.ts +++ b/packages/cli/test/triggers-cli.test.ts @@ -28,7 +28,6 @@ import { Refusal } from "../src/refusal.js"; import { makeUi, PLAIN, plain, type Ui } from "../src/style.js"; import { defaultTriggerDeps, - hostOf, levelHere, levelMeans, printJson, @@ -703,10 +702,6 @@ describe("corners", () => { }), ); expect(sessionThere("codex:abc", env)).toBe(true); - expect(hostOf("https://Board.Example:443/x")).toBe("board.example"); - expect(hostOf("localhost:8891")).toBe("localhost:8891"); - expect(hostOf("http://[::1]:80")).toBeNull(); - expect(hostOf("http://[bad")).toBeNull(); expect(levelMeans("droid", "safe", "~/w")).toBe("droid runs at its own safe level."); }); it("every refusal a history line can carry, in words; how long a run took", async () => { diff --git a/packages/core/src/triggers/index.ts b/packages/core/src/triggers/index.ts index ae0f378a..4382a543 100644 --- a/packages/core/src/triggers/index.ts +++ b/packages/core/src/triggers/index.ts @@ -6,6 +6,7 @@ export * from "./line.js"; export * from "./notice.js"; export * from "./pattern.js"; export * from "./places.js"; +export * from "./receiver.js"; export * from "./rules.js"; export * from "./text.js"; export * from "./words.js"; diff --git a/packages/core/src/triggers/receiver.ts b/packages/core/src/triggers/receiver.ts new file mode 100644 index 00000000..06a3cd9f --- /dev/null +++ b/packages/core/src/triggers/receiver.ts @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// A receiver's name as a rule says it (CONTROL.md §14.1, `source.receiver`). One function, so +// `trigger add`, which writes the name into a rule, and the daemon, which matches a notice's +// receiver against it and says each receiver's topics in its hello, can never disagree. + +/** The receiver's name: the host (and port, when not the default) of its address, lowercase. + * A bare host is read as `https://`. A bracketed IPv6 address, or an address with no host, is no name a rule takes. */ +export function receiverName(url: string): string | null { + try { + const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`); + const host = u.host.toLowerCase(); + // A URL with no host (`file:///etc/passwd`) names no receiver either. + return !host || host.startsWith("[") ? null : host; + } catch { + return null; + } +} diff --git a/packages/core/test/trigger-receiver.test.ts b/packages/core/test/trigger-receiver.test.ts new file mode 100644 index 00000000..6108e180 --- /dev/null +++ b/packages/core/test/trigger-receiver.test.ts @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +import { describe, expect, it } from "vitest"; +import { receiverName } from "../src/index.js"; + +describe("receiverName", () => { + it("is the host and a port that is not the default, lowercase", () => { + expect(receiverName("https://Board.Example:443/x")).toBe("board.example"); + expect(receiverName("https://board.example:8443/api/sessionpipe/v1/control")).toBe("board.example:8443"); + expect(receiverName("localhost:8891")).toBe("localhost:8891"); + expect(receiverName("http://localhost:8891/")).toBe("localhost:8891"); + }); + it("is no name for a bracketed IPv6 address or a broken address", () => { + expect(receiverName("http://[::1]:80")).toBeNull(); + expect(receiverName("http://[bad")).toBeNull(); + expect(receiverName("file:///etc/passwd")).toBeNull(); + }); +}); diff --git a/packages/receiver/src/index.ts b/packages/receiver/src/index.ts index 47cf3718..cf2d6fda 100644 --- a/packages/receiver/src/index.ts +++ b/packages/receiver/src/index.ts @@ -1,3 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 /** Package entry. Filled in by the milestone that builds this package (see ROADMAP.md). */ export const PROTOCOL_VERSION = 1 as const; +export * from "./notices.js"; diff --git a/packages/receiver/src/notices.ts b/packages/receiver/src/notices.ts new file mode 100644 index 00000000..6ccbcfa0 --- /dev/null +++ b/packages/receiver/src/notices.ts @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: Apache-2.0 +// The notices a receiver holds for one machine (spec/CONTROL.md §14.2 to §14.4): what its last +// hello allows, what waits for delivery, what a machine said it took, and what became of each. +// Every function but the file pair is pure: it returns a new state and never changes the one +// it was given. Everything a machine sends is untrusted JSON, read against a schema first. +import { mkdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { + type ControlHelloTriggers, + type ControlNotice, + NOTICE_SEEN_MS, + NOTICES_PER_POLL, + type NoticeAck, + parseNotice, + problems, + writeWhole, +} from "@sessionpipe/core"; +import { type JsonSchema, SCHEMAS } from "@sessionpipe/core/schema"; + +/** A notice waiting at the receiver; `seq` is the order it was offered in. */ +export interface HeldNotice { + notice: ControlNotice; + seq: number; +} + +/** What a machine said became of a notice; `until` (epoch ms) is when it may be forgotten. */ +export interface NoticeOutcome { + id: string; + outcome: NoticeAck["outcome"]; + at: string; + session?: string; + code?: string; + until: number; +} + +export interface MachineNotices { + v: 1; + /** The last hello's `triggers`; null when it said none (a daemon that predates triggers). */ + triggers: ControlHelloTriggers | null; + /** Deliverable: sent on every poll until acked. */ + held: HeldNotice[]; + /** Acked `taken`: not sent again; kept until its `expires_at`. */ + taken: HeldNotice[]; + outcomes: NoticeOutcome[]; + seq: number; +} + +/** At most this many notices, held and taken together, for one machine. */ +export const NOTICES_HELD_MAX = 200; +/** At most this many outcomes remembered for one machine; the oldest go first. */ +export const NOTICE_OUTCOMES_MAX = 1000; + +/** What `offer` made of a notice. `queued`: new, or its id was already there (nothing + * changes). `replaced`: it took the place of the held notice on the same topic and subject. + * `not_listed`: the last hello did not list its topic. `off`: the last hello had no triggers + * or `on: false`. `full`: every place is taken by a notice a machine acked `taken`. `bad`: + * not a notice (`why` says why). */ +export type OfferResult = "queued" | "replaced" | "not_listed" | "off" | "full" | "bad"; + +export function emptyNotices(): MachineNotices { + return { v: 1, triggers: null, held: [], taken: [], outcomes: [], seq: 0 }; +} + +const TRIGGERS_SCHEMA = SCHEMAS["control-hello"].properties.triggers; + +/** Take the hello's `triggers`, and drop the held notices it no longer allows. */ +export function onHello(m: MachineNotices, hello: unknown): MachineNotices { + const said = + hello && typeof hello === "object" && Object.hasOwn(hello, "triggers") + ? (hello as { triggers: unknown }).triggers + : undefined; + let triggers: ControlHelloTriggers | null = null; + if (said !== undefined && problems(TRIGGERS_SCHEMA, said).length === 0) { + const t = said as ControlHelloTriggers; + // Copied, so nothing of the machine's object lives on in the state. + triggers = { on: t.on, topics: [...t.topics] }; + } + const next = { ...m, triggers }; + return { ...next, held: m.held.filter((h) => allowed(next, h.notice)) }; +} + +function allowed(m: MachineNotices, n: ControlNotice): boolean { + return m.triggers?.on === true && m.triggers.topics.includes(n.topic); +} + +/** Forget what has expired: notices at their `expires_at`, outcomes past `until`, and the + * oldest outcomes past the cap. */ +function prune(m: MachineNotices, now: number): MachineNotices { + const live = (h: HeldNotice) => Date.parse(h.notice.expires_at) > now; + return { + ...m, + held: m.held.filter(live), + taken: m.taken.filter(live), + outcomes: m.outcomes.filter((o) => o.until > now).slice(-NOTICE_OUTCOMES_MAX), + }; +} + +const known = (m: MachineNotices, id: string): boolean => + m.held.some((h) => h.notice.id === id) || + m.taken.some((h) => h.notice.id === id) || + m.outcomes.some((o) => o.id === id); + +/** Hold a notice for the machine. One deliverable notice per topic and subject: the later + * offer wins. An id the state already knows (held, taken or answered) changes nothing, so + * offering the same notice twice is safe. */ +export function offer( + m: MachineNotices, + input: unknown, + now: number, +): { m: MachineNotices; result: OfferResult; why?: string } { + const p = prune(m, now); + const read = parseNotice(input, now); + if (!read.ok) return { m: p, result: "bad", why: read.why }; + const n = read.notice; + if (p.triggers?.on !== true) return { m: p, result: "off" }; + if (!p.triggers.topics.includes(n.topic)) return { m: p, result: "not_listed" }; + if (known(p, n.id)) return { m: p, result: "queued" }; + const same = (h: HeldNotice) => h.notice.topic === n.topic && h.notice.subject === n.subject; + const replaced = p.held.some(same); + let held = p.held.filter((h) => !same(h)); + if (held.length + p.taken.length >= NOTICES_HELD_MAX) { + if (held.length === 0) return { m: p, result: "full" }; + // Held is in offer order, so the first is the oldest deliverable. + held = held.slice(1); + } + const seq = p.seq + 1; + // A copy of the notice: the caller's object may change after this. + held = [...held, { notice: { ...n }, seq }]; + return { m: { ...p, held, seq }, result: replaced ? "replaced" : "queued" }; +} + +/** The notices for one poll answer: the oldest held, at most NOTICES_PER_POLL. They stay + * held, and are sent again on every poll, until the machine acks them. */ +export function forPoll(m: MachineNotices, now: number): { m: MachineNotices; notices: ControlNotice[] } { + const p = prune(m, now); + const notices = p.held + .filter((h) => allowed(p, h.notice)) + .slice(0, NOTICES_PER_POLL) + .map((h) => h.notice); + return { m: p, notices }; +} + +const BASE_ACK = SCHEMAS["control-notice-ack"]; +/** The generated schema leaves both objects open; this reader closes them, as §14.4's + * "closed" shape asks, so a member nobody named fails the whole body. */ +const ACK_SCHEMA = { + ...BASE_ACK, + additionalProperties: false, + properties: { + acks: { + ...BASE_ACK.properties.acks, + items: { ...BASE_ACK.properties.acks.items, additionalProperties: false }, + }, + }, +} satisfies JsonSchema; + +/** Take a machine's acks. A body that is not the closed shape changes nothing (`ok: false`). + * `taken` pauses delivery until `expires_at`; a final outcome ends the notice and replaces + * whatever was recorded; `duplicate` is recorded only when nothing else is, and never + * replaces an outcome. The same ack twice lands once. */ +export function onAcks(m: MachineNotices, body: unknown, now: number): { m: MachineNotices; ok: boolean } { + if (problems(ACK_SCHEMA, body).length > 0) return { m, ok: false }; + const acks = (body as { acks: NoticeAck[] }).acks; + // `session` comes only with `ran` and `code` only with `refused` (core's NoticeResult). + if ( + acks.some( + (a) => + (a.outcome === "ran") !== (a.session !== undefined) || (a.outcome === "refused") !== (a.code !== undefined), + ) + ) + return { m, ok: false }; + let s = prune(m, now); + for (const a of acks) s = ackOne(s, a); + return { m: s, ok: true }; +} + +function ackOne(m: MachineNotices, a: NoticeAck): MachineNotices { + const h = m.held.find((x) => x.notice.id === a.id) ?? m.taken.find((x) => x.notice.id === a.id); + const was = m.outcomes.find((o) => o.id === a.id); + if (!h && !was) return m; + // Kept as long as a machine remembers the id: 25 hours from the notice's `at`. + const until = h ? Date.parse(h.notice.at) + NOTICE_SEEN_MS : (was as NoticeOutcome).until; + const record: NoticeOutcome = { id: a.id, outcome: a.outcome, at: a.at, until }; + if (a.session !== undefined) record.session = a.session; + if (a.code !== undefined) record.code = a.code; + const others = m.outcomes.filter((o) => o.id !== a.id); + const held = m.held.filter((x) => x.notice.id !== a.id); + if (a.outcome === "taken") { + if (was && was.outcome !== "taken") return m; + const taken = h && m.held.includes(h) ? [...m.taken, h] : m.taken; + return { ...m, held, taken, outcomes: [...others, record] }; + } + // A duplicate never replaces an outcome. Without one, the machine saw the notice before, so + // like a final outcome it ends delivery. And once it ran, the session it ran in stays: a + // machine gives one final ack, so another one after it is not believed. + if (a.outcome === "duplicate" && was) return m; + if (was?.outcome === "ran" && a.outcome !== "ran") return m; + return { ...m, held, taken: m.taken.filter((x) => x.notice.id !== a.id), outcomes: [...others, record] }; +} + +const HELD_SCHEMA = { + type: "object", + properties: { notice: SCHEMAS["control-notice"], seq: { type: "integer", minimum: 1 } }, + required: ["notice", "seq"], + additionalProperties: false, +} satisfies JsonSchema; + +const ACK_ITEM = BASE_ACK.properties.acks.items.properties; +const FILE_SCHEMA = { + type: "object", + properties: { + v: { const: 1 }, + triggers: { anyOf: [{ type: "null" }, { ...TRIGGERS_SCHEMA, additionalProperties: false }] }, + held: { type: "array", items: HELD_SCHEMA }, + taken: { type: "array", items: HELD_SCHEMA }, + outcomes: { + type: "array", + items: { + type: "object", + properties: { + id: ACK_ITEM.id, + outcome: ACK_ITEM.outcome, + at: ACK_ITEM.at, + session: ACK_ITEM.session, + code: ACK_ITEM.code, + until: { type: "number" }, + }, + required: ["id", "outcome", "at", "until"], + additionalProperties: false, + }, + }, + seq: { type: "integer", minimum: 0 }, + }, + required: ["v", "triggers", "held", "taken", "outcomes", "seq"], + additionalProperties: false, +} satisfies JsonSchema; + +/** One machine's notices from its file. A file that is missing, torn, or not this shape + * reads as empty: the receiver starts over rather than trusting part of it. */ +export function readMachineNotices(file: string): MachineNotices { + try { + const j: unknown = JSON.parse(readFileSync(file, "utf8")); + return problems(FILE_SCHEMA, j).length === 0 ? (j as MachineNotices) : emptyNotices(); + } catch { + return emptyNotices(); + } +} + +/** Write one machine's notices whole: its folder made if need be (0700), a file beside it, then a + * rename, mode 0600. */ +export function writeMachineNotices(file: string, m: MachineNotices): void { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + writeWhole(file, `${JSON.stringify(m)}\n`); +} diff --git a/packages/receiver/test/notices.test.ts b/packages/receiver/test/notices.test.ts new file mode 100644 index 00000000..4490771f --- /dev/null +++ b/packages/receiver/test/notices.test.ts @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: Apache-2.0 +// The notices a receiver holds for one machine: hello, offer, poll and acks (CONTROL.md §14), +// and the file they are kept in. +import { existsSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { ControlNotice } from "@sessionpipe/core"; +import { afterAll, describe, expect, it } from "vitest"; +import { + emptyNotices, + forPoll, + type MachineNotices, + NOTICE_OUTCOMES_MAX, + NOTICES_HELD_MAX, + offer, + onAcks, + onHello, + readMachineNotices, + writeMachineNotices, +} from "../src/index.js"; + +const NOW = Date.parse("2026-11-24T10:00:00.000Z"); +const HOUR = 3600_000; +const iso = (ms: number) => new Date(ms).toISOString(); +const B32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +/** A ULID per number, so ids sort as they are made. */ +const id = (i: number) => `01KB4M2Q8V3T6Y9C0D1E2F3G${B32[Math.floor(i / 32)]}${B32[i % 32]}`; + +function notice(i: number, over: Partial = {}): ControlNotice { + return { + id: id(i), + topic: "acme/tasks", + event: "record.updated", + subject: `X-${i}`, + at: iso(NOW - 60_000), + expires_at: iso(NOW + HOUR), + ...over, + }; +} + +function deepFreeze(v: T): T { + if (v && typeof v === "object") { + for (const x of Object.values(v)) deepFreeze(x); + Object.freeze(v); + } + return v; +} + +const on = (topics = ["acme/tasks"]) => onHello(emptyNotices(), { triggers: { on: true, topics } }); + +/** Offer every notice in turn, each expected to land. */ +function offered(m: MachineNotices, ns: ControlNotice[], now = NOW): MachineNotices { + for (const n of ns) { + const r = offer(m, n, now); + expect(r.result).toBe("queued"); + m = r.m; + } + return m; +} + +const ack = (m: MachineNotices, acks: object[], now = NOW) => onAcks(deepFreeze(m), { acks }, now); +const ids = (m: MachineNotices) => forPoll(m, NOW).notices.map((n) => n.id); +const outcome = (m: MachineNotices, i: number) => m.outcomes.find((o) => o.id === id(i)); + +describe("the hello", () => { + it("takes triggers, copied, and reads anything else as none", () => { + const hello = { triggers: { on: true, topics: ["acme/tasks"] } }; + const m = onHello(deepFreeze(emptyNotices()), hello); + expect(m.triggers).toEqual({ on: true, topics: ["acme/tasks"] }); + expect(m.triggers?.topics).not.toBe(hello.triggers.topics); + for (const h of [null, "hi", [], {}, { triggers: { on: "yes", topics: [] } }, { triggers: { on: true } }]) + expect(onHello(m, h).triggers).toBeNull(); + // An inherited `triggers` is not the hello's own. + expect(onHello(m, Object.create({ triggers: { on: true, topics: [] } })).triggers).toBeNull(); + }); + + it("on to off drops every held notice; a topic leaving drops its own", () => { + let m = on(["acme/tasks", "acme/bugs"]); + m = offered(m, [notice(1), notice(2, { topic: "acme/bugs" })]); + deepFreeze(m); + expect(onHello(m, { triggers: { on: false, topics: [] } }).held).toEqual([]); + expect(onHello(m, {}).held).toEqual([]); + expect(onHello(m, { triggers: { on: true, topics: ["acme/bugs"] } }).held.map((h) => h.notice.id)).toEqual([id(2)]); + }); + + it("keeps taken notices when the topic leaves: a machine still owes their final ack", () => { + let m = offered(on(), [notice(1)]); + m = ack(m, [{ id: id(1), outcome: "taken", at: iso(NOW) }]).m; + expect(onHello(m, { triggers: { on: false, topics: [] } }).taken).toHaveLength(1); + }); +}); + +describe("offer", () => { + it("refuses what is not a notice", () => { + const m = on(); + expect(offer(m, { ...notice(1), extra: 1 }, NOW)).toMatchObject({ result: "bad", why: expect.any(String) }); + const proto = JSON.parse(`{"__proto__":{"x":1},${JSON.stringify(notice(1)).slice(1)}`); + expect(offer(m, proto, NOW).result).toBe("bad"); + expect(offer(m, notice(1, { expires_at: iso(NOW - 1) }), NOW)).toEqual({ + m, + result: "bad", + why: "the notice expired", + }); + }); + + it("is off without triggers or with on false, and refuses an unlisted topic", () => { + expect(offer(emptyNotices(), notice(1), NOW).result).toBe("off"); + const off = onHello(emptyNotices(), { triggers: { on: false, topics: [] } }); + expect(offer(off, notice(1), NOW).result).toBe("off"); + expect(offer(on(), notice(1, { topic: "acme/other" }), NOW).result).toBe("not_listed"); + }); + + it("holds one notice per topic and subject: the later offer wins, at the back", () => { + let m = offered(on(), [notice(1), notice(2)]); + const r = offer(deepFreeze(m), notice(3, { subject: "X-1", state: "done" }), NOW); + expect(r.result).toBe("replaced"); + m = r.m; + expect(ids(m)).toEqual([id(2), id(3)]); + expect(m.held.map((h) => h.seq)).toEqual([2, 3]); + }); + + it("an id it already knows changes nothing", () => { + let m = offered(on(), [notice(1), notice(2)]); + expect(offer(m, notice(1), NOW)).toEqual({ m, result: "queued" }); + m = ack(m, [{ id: id(1), outcome: "taken", at: iso(NOW) }]).m; + expect(offer(m, notice(1), NOW)).toEqual({ m, result: "queued" }); + m = ack(m, [{ id: id(2), outcome: "no_match", at: iso(NOW) }]).m; + expect(offer(m, notice(2), NOW)).toEqual({ m, result: "queued" }); + }); + + it("keeps a copy, not the caller's object", () => { + const n = notice(1); + const m = offered(on(), [n]); + n.subject = "changed"; + expect(m.held[0]?.notice.subject).toBe("X-1"); + }); + + it("caps held and taken at 200, dropping the oldest deliverable first", () => { + let m = offered(on(), [notice(0)]); + m = ack(m, [{ id: id(0), outcome: "taken", at: iso(NOW) }]).m; + m = offered( + m, + Array.from({ length: NOTICES_HELD_MAX - 1 }, (_, i) => notice(i + 1)), + ); + const r = offer(deepFreeze(m), notice(NOTICES_HELD_MAX), NOW); + expect(r.result).toBe("queued"); + expect(r.m.held).toHaveLength(NOTICES_HELD_MAX - 1); + expect(r.m.held[0]?.notice.id).toBe(id(2)); + expect(r.m.taken.map((h) => h.notice.id)).toEqual([id(0)]); + }); + + it("is full when every place is taken", () => { + let m = offered( + on(), + Array.from({ length: NOTICES_HELD_MAX }, (_, i) => notice(i)), + ); + for (let i = 0; i < NOTICES_HELD_MAX; i += 50) + m = ack( + m, + Array.from({ length: 50 }, (_, j) => ({ id: id(i + j), outcome: "taken", at: iso(NOW) })), + ).m; + expect(m.taken).toHaveLength(NOTICES_HELD_MAX); + expect(offer(m, notice(NOTICES_HELD_MAX), NOW)).toEqual({ m, result: "full" }); + }); +}); + +describe("the poll", () => { + it("gives the 50 oldest of 51, and again until they are acked", () => { + const m = offered( + on(), + Array.from({ length: 51 }, (_, i) => notice(i)), + ); + const first = forPoll(deepFreeze(m), NOW).notices.map((n) => n.id); + expect(first).toEqual(Array.from({ length: 50 }, (_, i) => id(i))); + expect(ids(m)).toEqual(first); + const after = ack( + m, + first.slice(0, 10).map((x) => ({ id: x, outcome: "no_match", at: iso(NOW) })), + ).m; + expect(ids(after)).toEqual(Array.from({ length: 50 }, (_, i) => id(i + 10)).slice(0, 41)); + }); + + it("forgets notices at their expires_at", () => { + const m = offered(on(), [notice(1, { expires_at: iso(NOW + 1000) }), notice(2)]); + const r = forPoll(m, NOW + 1000); + expect(r.notices.map((n) => n.id)).toEqual([id(2)]); + expect(r.m.held).toHaveLength(1); + }); + + it("sends only what the last hello allows, even from a state written by hand", () => { + const m = offered(on(["acme/tasks", "acme/bugs"]), [notice(1), notice(2, { topic: "acme/bugs" })]); + const narrowed = { ...m, triggers: { on: true, topics: ["acme/bugs"] } }; + expect(ids(narrowed)).toEqual([id(2)]); + expect(ids({ ...m, triggers: null })).toEqual([]); + }); +}); + +describe("acks", () => { + const base = () => offered(on(), [notice(1), notice(2), notice(3)]); + + it("taken pauses delivery until expires_at, then it is forgotten", () => { + const m = ack(base(), [{ id: id(1), outcome: "taken", at: iso(NOW) }]).m; + expect(ids(m)).toEqual([id(2), id(3)]); + expect(m.taken.map((h) => h.notice.id)).toEqual([id(1)]); + expect(outcome(m, 1)).toMatchObject({ outcome: "taken", until: NOW - 60_000 + 25 * HOUR }); + const later = forPoll(m, NOW + HOUR).m; + expect(later.taken).toEqual([]); + expect(later.held).toEqual([]); + expect(outcome(later, 1)?.outcome).toBe("taken"); + }); + + it("a final outcome replaces taken and ends the notice", () => { + let m = ack(base(), [{ id: id(1), outcome: "taken", at: iso(NOW) }]).m; + m = ack(m, [{ id: id(1), outcome: "ran", at: iso(NOW + 1), session: "claude-code:abc" }]).m; + expect(m.taken).toEqual([]); + expect(outcome(m, 1)).toMatchObject({ outcome: "ran", session: "claude-code:abc" }); + // A late taken does not undo it. + expect(ack(m, [{ id: id(1), outcome: "taken", at: iso(NOW + 2) }]).m).toEqual(m); + const refused = ack(base(), [{ id: id(2), outcome: "refused", code: "cooldown", at: iso(NOW) }]).m; + expect(outcome(refused, 2)).toMatchObject({ outcome: "refused", code: "cooldown" }); + }); + + it("taken again, after the notice expired, keeps the outcome's own lifetime", () => { + let m = ack(base(), [{ id: id(1), outcome: "taken", at: iso(NOW) }]).m; + m = forPoll(m, NOW + HOUR).m; + const r = onAcks(m, { acks: [{ id: id(1), outcome: "taken", at: iso(NOW + HOUR) }] }, NOW + HOUR); + expect(outcome(r.m, 1)).toMatchObject({ outcome: "taken", at: iso(NOW + HOUR), until: NOW - 60_000 + 25 * HOUR }); + expect(r.m.taken).toEqual([]); + }); + + it("ran after duplicate keeps the session; duplicate after ran changes nothing", () => { + let m = ack(base(), [{ id: id(1), outcome: "duplicate", at: iso(NOW) }]).m; + expect(ids(m)).toEqual([id(2), id(3)]); + expect(outcome(m, 1)?.outcome).toBe("duplicate"); + m = ack(m, [{ id: id(1), outcome: "ran", at: iso(NOW + 1), session: "codex:s1" }]).m; + expect(outcome(m, 1)).toMatchObject({ outcome: "ran", session: "codex:s1", until: NOW - 60_000 + 25 * HOUR }); + expect(ack(m, [{ id: id(1), outcome: "duplicate", at: iso(NOW + 2) }]).m).toEqual(m); + // A second, different final after `ran` is not believed: the session stays. + expect(ack(m, [{ id: id(1), outcome: "failed", at: iso(NOW + 3) }]).m).toEqual(m); + expect(ack(m, [{ id: id(1), outcome: "refused", code: "cap", at: iso(NOW + 3) }]).m).toEqual(m); + const taken = ack(base(), [{ id: id(2), outcome: "taken", at: iso(NOW) }]).m; + expect(ack(taken, [{ id: id(2), outcome: "duplicate", at: iso(NOW) }]).m).toEqual(taken); + }); + + it("the same ack twice lands once", () => { + const a = { id: id(1), outcome: "taken", at: iso(NOW) }; + const once = ack(base(), [a]).m; + const twice = ack(once, [a]).m; + expect(twice.taken).toEqual(once.taken); + expect(twice.outcomes).toEqual(once.outcomes); + const ran = { id: id(2), outcome: "ran", at: iso(NOW), session: "codex:s2" }; + const both = ack(base(), [ran, ran]).m; + expect(both.outcomes.filter((o) => o.id === id(2))).toHaveLength(1); + }); + + it("ignores an id it does not know", () => { + const m = base(); + const r = ack(m, [{ id: id(9), outcome: "ran", at: iso(NOW), session: "codex:s" }]); + expect(r).toEqual({ m, ok: true }); + }); + + it("refuses a body that is not the closed shape, changing nothing", () => { + const m = base(); + const one = { id: id(1), outcome: "no_match", at: iso(NOW) }; + for (const body of [ + {}, + { acks: [] }, + { acks: Array.from({ length: 51 }, () => one) }, + { acks: [one], extra: 1 }, + { acks: [{ ...one, extra: 1 }] }, + { acks: [{ ...one, outcome: "ran" }] }, + { acks: [{ ...one, session: "codex:s" }] }, + { acks: [{ ...one, outcome: "refused" }] }, + { acks: [{ ...one, code: "cap" }] }, + JSON.parse(`{"acks":[${JSON.stringify(one)}],"__proto__":{"x":1}}`), + ]) + expect(onAcks(m, body, NOW)).toEqual({ m, ok: false }); + }); + + it("forgets outcomes 25 hours after the notice, and keeps at most the newest 1000", () => { + const m = ack(base(), [{ id: id(1), outcome: "no_match", at: iso(NOW) }]).m; + expect(forPoll(m, NOW - 60_000 + 25 * HOUR).m.outcomes).toEqual([]); + const many: MachineNotices = { + ...emptyNotices(), + outcomes: Array.from({ length: NOTICE_OUTCOMES_MAX + 1 }, (_, i) => ({ + id: id(i), + outcome: "no_match" as const, + at: iso(NOW), + until: NOW + HOUR, + })), + }; + expect(forPoll(many, NOW).m.outcomes[0]?.id).toBe(id(1)); + }); +}); + +describe("the file", () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "sp-notices-")); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + it("round trips, whole, at 0600, with no temp file left", () => { + let m = offered(on(), [notice(1), notice(2, { state: "todo", for: "studio-claude", by: "u-41c9" })]); + m = ack(m, [ + { id: id(1), outcome: "taken", at: iso(NOW) }, + { id: id(2), outcome: "refused", code: "cap", at: iso(NOW) }, + ]).m; + const file = path.join(dir, "machine.json"); + writeMachineNotices(file, m); + expect(readMachineNotices(file)).toEqual(m); + if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); + expect(readdirSync(dir)).toEqual(["machine.json"]); + }); + + it("makes the machine's folder when it is not there", () => { + const file = path.join(dir, "machines", "m_1", "notices.json"); + writeMachineNotices(file, on()); + expect(readMachineNotices(file)).toEqual(on()); + if (process.platform !== "win32") expect(statSync(path.dirname(file)).mode & 0o777).toBe(0o700); + }); + + it("reads a missing, torn or foreign file as empty", () => { + const file = path.join(dir, "other.json"); + expect(existsSync(file)).toBe(false); + expect(readMachineNotices(file)).toEqual(emptyNotices()); + writeFileSync(file, '{"v":1,"triggers":null,"held":['); + expect(readMachineNotices(file)).toEqual(emptyNotices()); + writeFileSync(file, JSON.stringify({ ...emptyNotices(), v: 2 })); + expect(readMachineNotices(file)).toEqual(emptyNotices()); + writeFileSync(file, JSON.stringify({ ...emptyNotices(), held: [{ notice: { id: "x" }, seq: 1 }] })); + expect(readMachineNotices(file)).toEqual(emptyNotices()); + }); +}); diff --git a/packages/receiver/tsconfig.json b/packages/receiver/tsconfig.json index 00e4c17e..650e8f11 100644 --- a/packages/receiver/tsconfig.json +++ b/packages/receiver/tsconfig.json @@ -5,7 +5,7 @@ "outDir": "dist", "paths": { "@sessionpipe/core": ["../core/dist/src/index.d.ts"], - "@sessionpipe/core/schema": ["../core/dist/schema/v1.d.ts"] + "@sessionpipe/core/schema": ["../core/dist/src/schema/index.d.ts"] } }, "include": ["src"]