Public: anyone can read this; the crew can change it.
The Captain says a need once, files it for the crew, and shows what it costs #16574
Check · Review · Land · Live done — Landed and live in production.
talk-captain-once → main 0 commits 1 thread · 1 unresolved
16 files
changed +684
−59
- docs/features/talk-captain.md
- src/actions/accounts.ts
- src/core/migration-pins/20261127233000-routine-said.pin
- src/core/migrations/20261127233000-routine-said.ts
- src/core/talk_routines.ts
- src/crew/captain_cost.ts
- src/crew/notify.ts
- src/crew/routine_once.ts
- src/crew/routine_report.ts
- src/crew/routines.ts
- src/tui/screens/captain.ts
- src/web/pages/captain.ts
- test/data-browser.test.ts
- test/talk-captain-once.test.ts
- test/talk-captain.test.ts
- test/talk-checkin-story.test.ts
docs/features/talk-captain.md +5 −3
| @@ -8,11 +8,13 @@ Talk is where the forge's owner steers it. What the owner used to do in a Claude | ||
| 8 | 8 | |
| 9 | 9 | - **Instructions.** In Talk a message that asks for work is an instruction acted on at once, with the person's own powers through the MCP and within what their role allows: file issues, assign, steer, reopen parked pulls, merge, lend credit. How the agent answers (the answer first, depth when asked, results shown, how each thing is known) is in `docs/features/talk-voice.md`. Real money, DNS and a dark roll are held as a write with Do it and Not now buttons in the thread (`crew/conversation_brief.ts`, `crew/conversation_confirm.ts`). |
| 10 | 10 | - **Memory** (`core/talk_memory.ts`, Settings › Captain, `/settings/captain`). Short durable rules and decisions, up to 60 of 400 characters. Every Talk turn carries them in its system prompt (`memoryBrief`). The first visit offers the starting rules (never `rm`, tokens off argv, never dark without a go, ask first on money, DNS and a dark roll); delete them and they stay gone. |
| 11 | - **Routines** (`core/talk_routines.ts`, `crew/routines.ts`, `crew/routine_report.ts`). The hourly forge check-in, the friends watch and the morning paper, each with an editable schedule: every 15 to 1440 minutes, or daily at an hour (UTC). Each posts at most three lines into the owner's **Captain** thread; only a report that says something needs the owner reaches the phone (the notify URL, `crew/notify.ts`). The lines are computed, not written by a model, so a routine costs no spend. A forge that was down runs an owed routine once on waking. **Post now** on the settings page runs one at once. | |
| 11 | - **Routines** (`core/talk_routines.ts`, `crew/routines.ts`, `crew/routine_report.ts`). The hourly forge check-in, the friends watch and the morning paper, each with an editable schedule: every 15 to 1440 minutes, or daily at an hour (UTC). Each posts at most three lines into the owner's **Captain** thread; only a report that says something new needs the owner reaches the phone (the notify URL, `crew/notify.ts`). The lines are computed, not written by a model, so a routine costs no spend. A forge that was down runs an owed routine once on waking. **Post now** on the settings page runs one at once, and says so when there is nothing new. | |
| 12 | - **Said once** (`crew/routine_once.ts`, the `said` column of `talk_routine`). Each need has a key (a vitals cause, a red trunk's repository, `stuck` for every stuck run) and the routine keeps what it last said under it. The check-in and the friends watch post only what is new (`Needs you:`), worse (its measure, a number with a unit such as GiB, % or runs, moved the bad way by a tenth or more, with the old one: `Worse: The database is 5.1 GiB. (was 4.6)`; less free disk is worse, a smaller database is not, and words that change with no measure, a time say, are never worse) or cleared (`Cleared:`), what shipped and who joined since the last run; nothing new posts nothing. A need the crew can fix that still stands a day after it was first said is filed once as an issue on the forge's own repository (`FORGE_REPO`) with its evidence, and the thread says `Filed #N for the crew`. The issue stays open for the crew; the need is silent until it closes (said once again if it remains) or gets worse. A need whose control is a settings page is the admin's alone and never filed. "I've seen it" (or "got it", "noted") in the thread keeps every need said so far quiet until it gets worse. | |
| 13 | - **Cost** (`crew/captain_cost.ts`). Each post ends with, and the Captain page (first, under Cost) and the terminal screen show, the last 24 hours: `check-in and friends: no model, $0 · watches $X (N wakes) · your turns here $Y`, read from `conversation_run`. | |
| 12 | 14 | - **Watches** (`core/talk_watch.ts`, `crew/watches.ts`, `http/mcp/tools/talk_watch.ts`, #16557). A fourth routine kind: a short brief the agent leaves itself and what it waits for, as data the forge reads without a model: a pull is green, landed or changed (`pull_green`, `pull_landed`, `pull_changed`), a run ended (`run_ended`), an issue gained a comment (`issue_comment`), a check on main turned green (`main_green`), a pull merged (`merge_since`). "Done" is stated up front (`pull trevato/forge#16532 landed`). Each look (every 5 minutes by default, on the routines' minute clock) is free: nothing changed means nothing happens and nothing is spent. A change starts one ordinary Talk turn as the owner through `talk()` in the Captain thread, with the brief, the change and the memory, so the same limits apply (12 a minute, the account's budget, resting); a refused turn is tried again at the next look. A forge that was down looks once on waking, so it wakes once. The forge, not the agent, ends a watch: when its condition is met, at 7 days ("ran out"), or at its spend cap (default $2, at most $20; what its wake turns cost, found by the `[Watch <id>]` mark each starts with); each says so in one line in the thread. Safety: only the owner (a site admin who is a person) has one; at most 5 live; the agent may only propose one with the `talk_watch` tool, which is held for a Do it like money (`crew/conversation_confirm.ts`); a watch's own turn cannot start another (`wakeRunning`); a watch's turn has the owner's role at most and every write stays held as before. The owner lists, adds, pauses, deletes and ends them in Settings › Captain and in the terminal screen (`w` adds `pull_green owner/name#123: brief`, `p` pauses, `e` is Ends now, `d` deletes), each showing what it waits for, when it last looked, its wakes and what it has spent. |
| 13 | 15 | - **Resume.** A thread resumes its Claude session (#10457). When the last turn left the context 85% full, the next turn starts a fresh session from the thread's stored record and the memory, and the thread says so (`CONTEXT_RENEWED_LINE`). |
| 14 | - **Terminal** (`tui/screens/captain.ts`, palette › Captain, owner only). The rules, then the three routines, in one list. `a` adds a rule; `enter` edits the rule or the routine's schedule under the cursor; `d` deletes a rule; `space` turns a routine on or off; `p` posts a routine now; `r` reads again. A schedule is typed as minutes, `45` for every 45 minutes (15 to 1440), or `at 7` (also `daily 7`) for daily at 07:00 UTC. | |
| 16 | - **Terminal** (`tui/screens/captain.ts`, palette › Captain, owner only). The day's cost, the rules, then the three routines, in one list. `a` adds a rule; `enter` edits the rule or the routine's schedule under the cursor; `d` deletes a rule; `space` turns a routine on or off; `p` posts a routine now; `r` reads again. A schedule is typed as minutes, `45` for every 45 minutes (15 to 1440), or `at 7` (also `daily 7`) for daily at 07:00 UTC. | |
| 15 | 17 | |
| 16 | The check-in also names the releases cut since the last one and the pillars that merged work (`crew/routine_facts_story.ts`), in one clause of its third line, since the last check-in (`lastAt`; the git changelog is cached by head oid, so this costs a `rev-parse` between releases); it never reaches the phone for that alone. | |
| 18 | The check-in also names the releases cut since the last one and the pillars that merged work (`crew/routine_facts_story.ts`), in one line, since the last check-in (`lastAt`; the git changelog is cached by head oid, so this costs a `rev-parse` between releases); it never reaches the phone for that alone. | |
| 17 | 19 | |
| 18 | 20 | Not here yet: child forges stuck; a watch on a kind of change not listed above. |
src/actions/accounts.ts +2 −1
| @@ -330,9 +330,10 @@ export function newAccountLines( | ||
| 330 | 330 | db: Database, |
| 331 | 331 | user: User, |
| 332 | 332 | now: number = Date.now(), |
| 333 | sinceMs: number = now - NEW_FOR_MS, | |
| 333 | 334 | ): { id: string; line: string; items: readonly string[] }[] { |
| 334 | 335 | if (!user.isAdmin || user.kind !== "user") return []; |
| 335 | const since = new Date(now - NEW_FOR_MS).toISOString(); | |
| 336 | const since = new Date(sinceMs).toISOString(); | |
| 336 | 337 | return readAccounts(db) |
| 337 | 338 | .filter( |
| 338 | 339 | (a) => |
src/core/migration-pins/20261127233000-routine-said.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | a89838c1f586e7e6f988be37a26fd074631843328a18d0bbb41244c8345de3b4 |
src/core/migrations/20261127233000-routine-said.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | // The Captain says a need once (crew/routine_once.ts): what each routine last said, by line key, as | |
| 2 | // JSON ({ key: { text, at, figure, filed?, seen? } }). '{}' for a routine before this, which then | |
| 3 | // says its standing needs once more and is quiet after. Additive. | |
| 4 | export default ` | |
| 5 | ALTER TABLE talk_routine ADD COLUMN said TEXT NOT NULL DEFAULT '{}'; | |
| 6 | `; |
src/core/talk_routines.ts +18
| @@ -97,3 +97,21 @@ export function markRan(db: Database, userId: string, kind: RoutineKind, convers | ||
| 97 | 97 | "INSERT INTO talk_routine (user_id, kind, every_min, at_hour, last_at, conversation_id) VALUES (?1,?2,?5,?6,?3,?4) ON CONFLICT (user_id, kind) DO UPDATE SET last_at = ?3, conversation_id = ?4", |
| 98 | 98 | ).run(userId, kind, now.toISOString(), conversationId, d.everyMin, d.atHour); |
| 99 | 99 | } |
| 100 | ||
| 101 | /** | |
| 102 | * What a routine last said, by line key (`crew/routine_once.ts`); empty for one that never said. | |
| 103 | */ | |
| 104 | export function saidOf(db: Database, userId: string, kind: RoutineKind): Record<string, unknown> { | |
| 105 | const row = db.query<{ said: string }, [string, string]>("SELECT said FROM talk_routine WHERE user_id = ?1 AND kind = ?2").get(userId, kind); | |
| 106 | try { | |
| 107 | const parsed = JSON.parse(row?.said ?? "{}") as unknown; | |
| 108 | return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {}; | |
| 109 | } catch { | |
| 110 | return {}; | |
| 111 | } | |
| 112 | } | |
| 113 | ||
| 114 | /** Keep what a routine said, after it ran (`markRan` made the row). */ | |
| 115 | export function keepSaid(db: Database, userId: string, kind: RoutineKind, said: Readonly<Record<string, unknown>>): void { | |
| 116 | db.query("UPDATE talk_routine SET said = ?3 WHERE user_id = ?1 AND kind = ?2").run(userId, kind, JSON.stringify(said)); | |
| 117 | } |
src/crew/captain_cost.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * What the Captain cost the owner over the last day. The check-in and the friends watch call no | |
| 3 | * model (`routine_report.ts`), so they are $0 by construction; the spend is the watches' woken | |
| 4 | * turns (their prompt starts with `WAKE_MARK`) and the owner's own turns in the Captain thread, | |
| 5 | * both read from `conversation_run`. Shown on the Captain page, its terminal screen and each post. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { dollars } from "../core/conversation_cost.ts"; | |
| 10 | import { WAKE_MARK } from "../core/talk_watch.ts"; | |
| 11 | ||
| 12 | export const COST_DAY_MS = 86_400_000; | |
| 13 | ||
| 14 | export interface DayCost { | |
| 15 | readonly watchesUsd: number; | |
| 16 | readonly wakes: number; | |
| 17 | /** The owner's own turns in the Captain thread. */ | |
| 18 | readonly turnsUsd: number; | |
| 19 | } | |
| 20 | ||
| 21 | /** | |
| 22 | * The last 24 hours for `userId`; `threadId` is their Captain thread, null before its first post. | |
| 23 | */ | |
| 24 | export function dayCost(db: Database, userId: string, threadId: string | null, now: number): DayCost { | |
| 25 | const since = new Date(now - COST_DAY_MS).toISOString(); | |
| 26 | const wake = `${WAKE_MARK}%`; | |
| 27 | const w = db | |
| 28 | .query< | |
| 29 | { s: number | null; n: number }, | |
| 30 | [string, string, string] | |
| 31 | >("SELECT SUM(cost_usd) AS s, COUNT(*) AS n FROM conversation_run WHERE user_id = ?1 AND started_at >= ?2 AND prompt LIKE ?3") | |
| 32 | .get(userId, since, wake); | |
| 33 | const t = | |
| 34 | threadId === null | |
| 35 | ? undefined | |
| 36 | : db | |
| 37 | .query< | |
| 38 | { s: number | null }, | |
| 39 | [string, string, string, string] | |
| 40 | >("SELECT SUM(cost_usd) AS s FROM conversation_run WHERE user_id = ?1 AND started_at >= ?2 AND conversation_id = ?3 AND prompt NOT LIKE ?4") | |
| 41 | .get(userId, since, threadId, wake); | |
| 42 | return { watchesUsd: w?.s ?? 0, wakes: w?.n ?? 0, turnsUsd: t?.s ?? 0 }; | |
| 43 | } | |
| 44 | ||
| 45 | const usd = (n: number): string => (n === 0 ? "$0" : dollars(n)); | |
| 46 | ||
| 47 | /** | |
| 48 | * One line: "Last 24 h: check-in and friends: no model, $0 · watches $X (N wakes) · your turns here | |
| 49 | * $Y". | |
| 50 | */ | |
| 51 | export const costLine = (c: DayCost): string => | |
| 52 | `Last 24 h: check-in and friends: no model, $0 · watches ${usd(c.watchesUsd)} (${c.wakes} ${c.wakes === 1 ? "wake" : "wakes"}) · your turns here ${usd(c.turnsUsd)}`; |
src/crew/notify.ts +3 −3
| @@ -295,16 +295,16 @@ export function redLines( | ||
| 295 | 295 | app: App, |
| 296 | 296 | user: User, |
| 297 | 297 | _now = Date.now(), |
| 298 | ): { id: string; line: string; items: readonly string[]; link: string }[] { | |
| 298 | ): { id: string; repoId: string; line: string; items: readonly string[]; link: string }[] { | |
| 299 | 299 | if (user.kind !== "user") return []; |
| 300 | const out: { id: string; line: string; items: readonly string[]; link: string }[] = []; | |
| 300 | const out: { id: string; repoId: string; line: string; items: readonly string[]; link: string }[] = []; | |
| 301 | 301 | for (const { id } of app.db |
| 302 | 302 | .query<{ id: string }, [string]>("SELECT id FROM repo WHERE owner_id = ?1 AND archived_at IS NULL") |
| 303 | 303 | .all(user.id)) { |
| 304 | 304 | const red = redMain(app.db, id); |
| 305 | 305 | if (red === undefined || red.limit) continue; |
| 306 | 306 | const key = `red:${red.runId}`; |
| 307 | out.push({ id: key, line: redSentence(red, 0), items: [key], link: redHref(red) }); | |
| 307 | out.push({ id: key, repoId: id, line: redSentence(red, 0), items: [key], link: redHref(red) }); | |
| 308 | 308 | } |
| 309 | 309 | return out; |
| 310 | 310 | } |
src/crew/routine_once.ts added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | /** | |
| 2 | * The Captain says a need once (#11011's routines, the owner's "never nagging"). Each need has a | |
| 3 | * key (a vitals cause, a red trunk's repository, stuck runs), and the routine keeps what it last | |
| 4 | * said under that key. A post carries only what is new, what got worse (its figure moved the bad | |
| 5 | * way by a tenth or more, with the figure it had), and what cleared. Nothing changed: nothing is | |
| 6 | * posted. A figure that moves the good way, or words that change with no figure, are kept quietly. | |
| 7 | * | |
| 8 | * A need still there a day after it was first said, that the crew can fix, is filed once for the | |
| 9 | * crew (`file`, done by `routines.ts`) and is then silent until its issue closes (said once again | |
| 10 | * if it remains) or it gets worse. A need only an admin can fix (its control is a settings page), | |
| 11 | * or one the owner said they have seen, is silent until it gets worse. Pure: needs and memory in, | |
| 12 | * lines, memory and what to file out. | |
| 13 | */ | |
| 14 | ||
| 15 | export interface Need { | |
| 16 | /** What the need is, across posts: a vitals cause, `red:owner/name`, `stuck`. */ | |
| 17 | readonly key: string; | |
| 18 | readonly text: string; | |
| 19 | /** Only an admin's own control fixes it: never filed for the crew. */ | |
| 20 | readonly adminOnly: boolean; | |
| 21 | /** Where to look, for the issue's evidence. */ | |
| 22 | readonly href?: string; | |
| 23 | /** Its measure when the words do not carry a stable one (a count); null for none. */ | |
| 24 | readonly figure?: number | null; | |
| 25 | /** Less is worse (free space); else more is worse. Read from the words when not given. */ | |
| 26 | readonly lowerIsWorse?: boolean; | |
| 27 | } | |
| 28 | ||
| 29 | export interface Said { | |
| 30 | readonly text: string; | |
| 31 | /** When it was first said (or said again after its issue closed). */ | |
| 32 | readonly at: string; | |
| 33 | readonly figure: number | null; | |
| 34 | /** The issue filed for it, once. */ | |
| 35 | readonly filed?: number; | |
| 36 | /** The owner said they had seen it: silent until it gets worse. */ | |
| 37 | readonly seen?: true; | |
| 38 | } | |
| 39 | ||
| 40 | export type Memory = Readonly<Record<string, Said>>; | |
| 41 | ||
| 42 | /** A need is filed for the crew once it has stood this long since it was first said. */ | |
| 43 | export const FILE_AFTER_MS = 86_400_000; | |
| 44 | /** A figure must move by this share to be said again as worse. */ | |
| 45 | export const WORSE_BY = 0.1; | |
| 46 | ||
| 47 | /** | |
| 48 | * A sentence's measure: the first number with a unit of size or count (4.6 in "The database is 4.6 | |
| 49 | * GiB", 9 in "9% free"), never one inside a name, a time or an id ("scout/forge2", "22:49Z"). | |
| 50 | * Minutes are not a measure: an age grows by itself. | |
| 51 | */ | |
| 52 | export function figureOf(text: string): number | null { | |
| 53 | const m = /(?<![\w:.\/#-])(\d+(?:\.\d+)?)\s*(%|[KMGT]i?B\b|(?:requests?|runs?|pulls?|checks?|errors?|branch(?:es)?|apps?|forges?|tests?)\b)/i.exec(text); | |
| 54 | return m === null ? null : Number(m[1]); | |
| 55 | } | |
| 56 | ||
| 57 | /** What is left (free space, headroom) is worse when it is less; anything else, when it is more. */ | |
| 58 | export const lowerIsWorse = (text: string): boolean => /\b(free|left|remaining|headroom)\b/i.test(text); | |
| 59 | ||
| 60 | /** The need's measure: its own, else the one its words carry. */ | |
| 61 | export const measureOf = (n: Pick<Need, "text" | "figure">): number | null => (n.figure !== undefined ? n.figure : figureOf(n.text)); | |
| 62 | ||
| 63 | /** | |
| 64 | * Whether the need is worse than what was said: its measure moved the bad way by a tenth or more | |
| 65 | * of the figure said. A move the good way, or words with no measure, are never worse. | |
| 66 | */ | |
| 67 | export function worse(prev: Pick<Said, "figure">, n: Pick<Need, "text" | "figure" | "lowerIsWorse">): boolean { | |
| 68 | const now = measureOf(n); | |
| 69 | if (now === null || prev.figure === null) return false; | |
| 70 | const moved = (n.lowerIsWorse ?? lowerIsWorse(n.text)) ? prev.figure - now : now - prev.figure; | |
| 71 | if (moved <= 0) return false; | |
| 72 | return prev.figure === 0 || moved / Math.abs(prev.figure) >= WORSE_BY; | |
| 73 | } | |
| 74 | ||
| 75 | export interface Once { | |
| 76 | readonly lines: readonly string[]; | |
| 77 | /** Something new or worse: what reaches the phone. */ | |
| 78 | readonly pushes: boolean; | |
| 79 | readonly memory: Memory; | |
| 80 | /** Needs to file for the crew now, each once. */ | |
| 81 | readonly file: readonly Need[]; | |
| 82 | } | |
| 83 | ||
| 84 | /** | |
| 85 | * Today's needs against what was last said. `closed`: keys whose filed issue has closed since. | |
| 86 | */ | |
| 87 | export function sayOnce(needs: readonly Need[], memory: Memory, now: Date, closed: ReadonlySet<string> = new Set()): Once { | |
| 88 | const at = now.toISOString(); | |
| 89 | const next: Record<string, Said> = {}; | |
| 90 | const lines: string[] = []; | |
| 91 | const file: Need[] = []; | |
| 92 | let pushes = false; | |
| 93 | for (const n of needs) { | |
| 94 | const prev = memory[n.key]; | |
| 95 | const figure = measureOf(n); | |
| 96 | if (prev === undefined) { | |
| 97 | lines.push(`Needs you: ${n.text}`); | |
| 98 | next[n.key] = { text: n.text, at, figure }; | |
| 99 | pushes = true; | |
| 100 | continue; | |
| 101 | } | |
| 102 | if (prev.filed !== undefined && closed.has(n.key)) { | |
| 103 | lines.push(`Needs you again (#${String(prev.filed)} closed): ${n.text}`); | |
| 104 | next[n.key] = { text: n.text, at, figure }; | |
| 105 | pushes = true; | |
| 106 | continue; | |
| 107 | } | |
| 108 | if (worse(prev, n)) { | |
| 109 | const was = prev.figure === null || figure === null ? "" : ` (was ${String(prev.figure)})`; | |
| 110 | lines.push(`Worse: ${n.text}${was}`); | |
| 111 | next[n.key] = { text: n.text, at: prev.at, figure, ...(prev.filed === undefined ? {} : { filed: prev.filed }) }; | |
| 112 | pushes = true; | |
| 113 | continue; | |
| 114 | } | |
| 115 | // Better, or the same within a tenth: kept quietly. Only a better figure becomes the new mark, | |
| 116 | // so a slow creep the bad way still adds up to a tenth. | |
| 117 | const down = n.lowerIsWorse ?? lowerIsWorse(n.text); | |
| 118 | const better = figure !== null && prev.figure !== null && (down ? figure > prev.figure : figure < prev.figure); | |
| 119 | next[n.key] = better ? { ...prev, text: n.text, figure } : prev; | |
| 120 | if (!n.adminOnly && prev.filed === undefined && prev.seen !== true && now.getTime() - Date.parse(prev.at) >= FILE_AFTER_MS) | |
| 121 | file.push(n); | |
| 122 | } | |
| 123 | for (const [key, prev] of Object.entries(memory)) if (!needs.some((n) => n.key === key)) lines.push(`Cleared: ${prev.text}`); | |
| 124 | return { lines, pushes, memory: next, file }; | |
| 125 | } | |
| 126 | ||
| 127 | /** The owner's words that say they have seen what was posted: "I've seen it", "got it", "noted". */ | |
| 128 | export const SEEN = /\b(seen|saw it|got it|noted)\b/i; | |
| 129 | ||
| 130 | /** Every need marked seen (the owner answered "seen" after the last post). */ | |
| 131 | export const seenAll = (memory: Memory): Memory => | |
| 132 | Object.fromEntries(Object.entries(memory).map(([k, s]) => [k, { ...s, seen: true as const }])); | |
| 133 | ||
| 134 | /** Mark one need filed as issue `number`. */ | |
| 135 | export const filedAs = (memory: Memory, key: string, number: number): Memory => | |
| 136 | memory[key] === undefined ? memory : { ...memory, [key]: { ...memory[key]!, filed: number } }; |
src/crew/routine_report.ts +55 −26
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | /** |
| 2 | * What a Talk routine says (#11011): at most three plain lines, and whether | |
| 3 | * anything needs the person (only then does it reach their phone). `facts` reads | |
| 4 | * the forge; `compose` turns plain facts into lines and is where the words | |
| 5 | * and the rules live, so a test can hold them without a forge. | |
| 2 | * What a Talk routine says (#11011): a few plain lines, and whether anything | |
| 3 | * needs the person (only then does it reach their phone). `facts` reads the | |
| 4 | * forge; `compose` turns plain facts into lines and is where the words and the | |
| 5 | * rules live, so a test can hold them without a forge. The check-in and the | |
| 6 | * friends watch say a need once (`routine_once.ts`): only what is new, worse or | |
| 7 | * cleared since their last post. | |
| 6 | 8 | */ |
| 7 | 9 | |
| 8 | 10 | import type { App } from "../app.ts"; |
| @@ -13,6 +15,8 @@ import { askLinesFor } from "../web/studio/asks.ts"; | ||
| 13 | 15 | import type { RoutineKind } from "../core/talk_routines.ts"; |
| 14 | 16 | import type { User } from "../core/users.ts"; |
| 15 | 17 | import { storyFacts, type Story } from "./routine_facts_story.ts"; |
| 18 | import { sayOnce, type Need, type Once } from "./routine_once.ts"; | |
| 19 | import type { Degraded } from "../kernel/vitals.ts"; | |
| 16 | 20 | |
| 17 | 21 | export const LINES_MAX = 3; |
| 18 | 22 | |
| @@ -20,16 +24,16 @@ export interface Facts extends Story { | ||
| 20 | 24 | /** The forge's own words for what is wrong, empty when healthy. */ |
| 21 | 25 | readonly health: readonly string[]; |
| 22 | 26 | readonly redMain: readonly string[]; |
| 27 | /** The forge's needs, keyed for saying once: `needsOf`. */ | |
| 28 | readonly needs: readonly Need[]; | |
| 23 | 29 | /** What the person is asked to decide. */ |
| 24 | 30 | readonly asks: number; |
| 25 | 31 | /** Crew member name to the runs it holds now. */ |
| 26 | 32 | readonly holds: Readonly<Record<string, number>>; |
| 27 | readonly grokbotPulls: number; | |
| 28 | readonly mergedLastHour: number; | |
| 33 | /** Accounts made since the routine last posted. */ | |
| 29 | 34 | readonly newPeople: readonly string[]; |
| 30 | 35 | /** Waiting account requests. */ |
| 31 | 36 | readonly waiting: number; |
| 32 | readonly stuckRuns: number; | |
| 33 | 37 | /** Day-long figures for the paper. */ |
| 34 | 38 | readonly mergedToday: number; |
| 35 | 39 | readonly openedToday: number; |
| @@ -60,23 +64,48 @@ const holdsText = (holds: Readonly<Record<string, number>>): string => { | ||
| 60 | 64 | return names.length === 0 ? "the crew holds nothing" : `crew: ${names.map(([n, c]) => `${n} ${c}`).join(", ")}`; |
| 61 | 65 | }; |
| 62 | 66 | |
| 63 | /** Pure: facts and a kind in, at most three lines and the need out. */ | |
| 64 | export function compose(kind: RoutineKind, f: Facts): Report { | |
| 67 | /** | |
| 68 | * The needs a check-in says once: each vitals cause under its own key (every stuck run is one | |
| 69 | * need, `stuck`, its figure the count), and a red trunk on the person's own repository under the | |
| 70 | * vitals key for it. A need whose control is a settings page is the admin's alone. | |
| 71 | */ | |
| 72 | export function needsOf(degraded: readonly Degraded[], red: readonly { readonly repoId: string; readonly line: string; readonly link: string }[]): Need[] { | |
| 73 | const out: Need[] = []; | |
| 74 | const stuck = degraded.filter((d) => d.cause.startsWith("stuck:")); | |
| 75 | for (const d of degraded) if (!d.cause.startsWith("stuck:")) out.push({ key: d.cause, text: d.sentence, adminOnly: d.href.startsWith("/settings"), href: d.href }); | |
| 76 | if (stuck.length > 0) out.push({ key: "stuck", text: stuck.length === 1 ? stuck[0]!.sentence : `${stuck.length} runs are stuck.`, adminOnly: false, href: stuck[0]!.href, figure: stuck.length }); | |
| 77 | for (const r of red) if (!out.some((n) => n.key === `red:${r.repoId}`)) out.push({ key: `red:${r.repoId}`, text: r.line, adminOnly: false, href: r.link, figure: null }); | |
| 78 | return out; | |
| 79 | } | |
| 80 | ||
| 81 | /** | |
| 82 | * What a routine says once: the check-in the forge's needs, the friends watch the waiting requests | |
| 83 | * (the admin's to allow). | |
| 84 | */ | |
| 85 | export function needsFor(kind: RoutineKind, f: Facts): readonly Need[] { | |
| 86 | if (kind === "checkin") return f.needs; | |
| 87 | if (kind === "friends") return f.waiting === 0 ? [] : [{ key: "waiting", text: `${plural(f.waiting, "request")} for an account waiting for your allow.`, adminOnly: true, href: "/settings/accounts", figure: f.waiting }]; | |
| 88 | return []; | |
| 89 | } | |
| 90 | ||
| 91 | /** At most `LINES_MAX` lines: past it, the rest is counted on the last. */ | |
| 92 | const capped = (lines: readonly string[]): string[] => | |
| 93 | lines.length <= LINES_MAX ? [...lines] : [...lines.slice(0, LINES_MAX - 1), `${lines.length - LINES_MAX + 1} more: see /system.`]; | |
| 94 | ||
| 95 | /** | |
| 96 | * Pure: facts and a kind in, the lines and the need out. The check-in and the friends watch say | |
| 97 | * `once` (by default everything, as for a routine that never posted) and what shipped or who | |
| 98 | * joined since the last post; with nothing of either they have no lines, and nothing is posted. | |
| 99 | */ | |
| 100 | export function compose(kind: RoutineKind, f: Facts, once: Once = sayOnce(needsFor(kind, f), {}, new Date(0))): Report { | |
| 65 | 101 | if (kind === "checkin") { |
| 66 | const trouble = [...f.health, ...f.redMain]; | |
| 67 | const lines = [ | |
| 68 | trouble.length === 0 ? "Forge healthy, trunk green." : `Needs you: ${trouble.slice(0, 2).join("; ")}.`, | |
| 69 | `${plural(f.asks, "ask")} for you, ${plural(f.grokbotPulls, "grokbot pull")} open, ${plural(f.mergedLastHour, "merge")} in the last hour.`, | |
| 70 | `${holdsText(f.holds)}${f.stuckRuns > 0 ? `; ${plural(f.stuckRuns, "run")} stuck` : ""}${storyText(f) === "" ? "" : `; ${storyText(f)}`}.`, | |
| 71 | ]; | |
| 72 | return { lines, needs: trouble.length > 0 || f.stuckRuns > 0 }; | |
| 102 | const story = storyText(f); | |
| 103 | return { lines: capped([...once.lines, ...(story === "" ? [] : [`Shipped: ${story}.`])]), needs: once.pushes }; | |
| 73 | 104 | } |
| 74 | 105 | if (kind === "friends") { |
| 75 | const lines: string[] = []; | |
| 76 | lines.push(f.newPeople.length === 0 ? "No new sign-ups." : `New: ${f.newPeople.slice(0, 5).join(", ")}${f.newPeople.length > 5 ? ` and ${f.newPeople.length - 5} more` : ""}.`); | |
| 77 | if (f.waiting > 0) lines.push(`${plural(f.waiting, "request")} for an account waiting for your allow.`); | |
| 78 | if (f.stuckRuns > 0) lines.push(`${plural(f.stuckRuns, "run")} stuck.`); | |
| 79 | return { lines: lines.slice(0, LINES_MAX), needs: f.waiting > 0 }; | |
| 106 | const n = f.newPeople; | |
| 107 | const joined = n.length === 0 ? [] : [`New: ${n.slice(0, 5).join(", ")}${n.length > 5 ? ` and ${n.length - 5} more` : ""}.`]; | |
| 108 | return { lines: capped([...joined, ...once.lines]), needs: once.pushes }; | |
| 80 | 109 | } |
| 81 | 110 | const lines = [ |
| 82 | 111 | f.health.length === 0 && f.redMain.length === 0 ? "Overnight the forge stayed healthy." : `Overnight: ${[...f.health, ...f.redMain].slice(0, 2).join("; ")}.`, |
| @@ -101,19 +130,19 @@ export async function facts(app: App, user: User, now: number, sinceMs = now - 3 | ||
| 101 | 130 | .all()) |
| 102 | 131 | holds[r.name] = r.n; |
| 103 | 132 | const count = (sql: string, ...args: string[]): number => db.query<{ n: number }, string[]>(sql).get(...args)?.n ?? 0; |
| 104 | const accounts = newAccountLines(db, user, now); | |
| 133 | // Made after the last post: one made in its millisecond was named by it. | |
| 134 | const accounts = newAccountLines(db, user, now, sinceMs + 1); | |
| 135 | const red = redLines(app, user, now); | |
| 105 | 136 | const story = await storyFacts(app, sinceMs); |
| 106 | 137 | return { |
| 107 | 138 | ...story, |
| 108 | 139 | health: vitals.needs.slice(0, 3), |
| 109 | redMain: redLines(app, user, now).map((l) => l.line), | |
| 140 | redMain: red.map((l) => l.line), | |
| 141 | needs: needsOf(vitals.degraded, red), | |
| 110 | 142 | asks: askLinesFor(db, user).length, |
| 111 | 143 | holds, |
| 112 | grokbotPulls: count("SELECT COUNT(*) AS n FROM issue i JOIN user u ON u.id = i.author_id WHERE i.kind = 'pull' AND i.state = 'open' AND u.username = 'grokbot'"), | |
| 113 | mergedLastHour: count("SELECT COUNT(*) AS n FROM pull WHERE merged_at >= ?1", iso(now - 3_600_000)), | |
| 114 | 144 | newPeople: accounts.map((a) => a.line.split(" ")[0] ?? "").filter((n) => n !== ""), |
| 115 | 145 | waiting: count("SELECT COUNT(*) AS n FROM account_request WHERE state = 'waiting'"), |
| 116 | stuckRuns: vitals.stuck.length, | |
| 117 | 146 | mergedToday: count("SELECT COUNT(*) AS n FROM pull WHERE merged_at >= ?1", iso(now - DAY)), |
| 118 | 147 | openedToday: count("SELECT COUNT(*) AS n FROM issue WHERE kind = 'pull' AND created_at >= ?1", iso(now - DAY)), |
| 119 | 148 | }; |
src/crew/routines.ts +80 −8
| @@ -5,42 +5,114 @@ | ||
| 5 | 5 | * instruction the agent acts on at once. Only a report that says something |
| 6 | 6 | * needs the person goes to their phone (`crew/notify.ts`'s URL and sender). |
| 7 | 7 | * What a routine says is deterministic (`routine_report.ts`): no model, no spend. |
| 8 | * | |
| 9 | * The check-in and the friends watch say a need once (`routine_once.ts`) and post nothing when | |
| 10 | * nothing is new. A need the crew can fix that still stands a day after it was first said is filed | |
| 11 | * once as an issue on the forge's own repository, for the crew, and the thread says so; the issue | |
| 12 | * stays open for the crew to close. Each post ends with what the Captain cost over the last day. | |
| 8 | 13 | */ |
| 9 | 14 | |
| 10 | 15 | import { during } from "../perf/jobs.ts"; |
| 11 | 16 | import type { App } from "../app.ts"; |
| 12 | 17 | import { appendTurn } from "../core/conversations.ts"; |
| 13 | import { due, listRoutines, markRan, ROUTINE_NAMES, type RoutineKind } from "../core/talk_routines.ts"; | |
| 18 | import { due, keepSaid, listRoutines, markRan, ROUTINE_NAMES, saidOf, type RoutineKind } from "../core/talk_routines.ts"; | |
| 14 | 19 | import { getUserById, type User } from "../core/users.ts"; |
| 15 | import { compose, facts, type Report } from "./routine_report.ts"; | |
| 20 | import { forgeRepo } from "../core/forge_repo.ts"; | |
| 21 | import { tell } from "../actions/tell.ts"; | |
| 22 | import { compose, facts, needsFor, type Report } from "./routine_report.ts"; | |
| 23 | import { filedAs, sayOnce, SEEN, seenAll, type Memory, type Need } from "./routine_once.ts"; | |
| 24 | import { costLine, dayCost } from "./captain_cost.ts"; | |
| 16 | 25 | import { notifyUrlOf, post, type Sender } from "./notify.ts"; |
| 17 | 26 | import { lookDue } from "./watches.ts"; |
| 18 | 27 | import { captainThread } from "./captain_thread.ts"; |
| 19 | 28 | |
| 20 | /** The text posted: the routine's name, then its lines. */ | |
| 21 | export const routineText = (kind: RoutineKind, report: Report): string => `**${ROUTINE_NAMES[kind]}**\n${report.lines.map((l) => `- ${l}`).join("\n")}`; | |
| 29 | /** The text posted: the routine's name, its lines, then the day's cost when given. */ | |
| 30 | export const routineText = (kind: RoutineKind, report: Report, cost?: string): string => | |
| 31 | `**${ROUTINE_NAMES[kind]}**\n${report.lines.map((l) => `- ${l}`).join("\n")}${cost === undefined ? "" : `\n\n_${cost}_`}`; | |
| 22 | 32 | |
| 23 | 33 | export interface Posted { |
| 24 | 34 | readonly kind: RoutineKind; |
| 25 | 35 | readonly conversationId: string; |
| 36 | /** False when nothing was new: no post. */ | |
| 37 | readonly posted: boolean; | |
| 26 | 38 | readonly pushed: boolean; |
| 27 | 39 | } |
| 28 | 40 | |
| 29 | /** Run one routine now for `user`: post its lines, push only when it needs them. */ | |
| 41 | /** Whether the owner said they had seen it in the thread since the routine's last post. */ | |
| 42 | const seenSince = (app: App, threadId: string | null, lastAt: string | null): boolean => | |
| 43 | threadId !== null && | |
| 44 | lastAt !== null && | |
| 45 | app.db | |
| 46 | .query<{ text: string }, [string, string]>("SELECT text FROM conversation_turn WHERE conversation_id = ?1 AND role = 'person' AND created_at > ?2") | |
| 47 | .all(threadId, lastAt) | |
| 48 | .some((t) => SEEN.test(t.text)); | |
| 49 | ||
| 50 | /** The keys whose filed issue on the forge's repository has closed. */ | |
| 51 | function closedOf(app: App, memory: Memory): Set<string> { | |
| 52 | const repo = forgeRepo(app); | |
| 53 | const out = new Set<string>(); | |
| 54 | if (repo === undefined) return out; | |
| 55 | const q = app.db.query<{ state: string }, [string, number]>("SELECT state FROM issue WHERE repo_id = ?1 AND number = ?2"); | |
| 56 | for (const [key, s] of Object.entries(memory)) if (s.filed !== undefined && q.get(repo.id, s.filed)?.state === "closed") out.add(key); | |
| 57 | return out; | |
| 58 | } | |
| 59 | ||
| 60 | /** | |
| 61 | * File one need for the crew on the forge's own repository, with its evidence; its number, or | |
| 62 | * undefined. | |
| 63 | */ | |
| 64 | async function fileNeed(app: App, user: User, n: Need, firstSaid: string): Promise<number | undefined> { | |
| 65 | const repo = forgeRepo(app); | |
| 66 | if (repo === undefined) return undefined; | |
| 67 | const text = [ | |
| 68 | n.text, | |
| 69 | `The Captain first said this at ${firstSaid.slice(0, 16).replace("T", " ")} UTC and it still stands a day later.`, | |
| 70 | `Evidence: the forge's vitals (cause \`${n.key}\`)${n.href === undefined ? "" : `, see ${n.href}`}.`, | |
| 71 | ].join("\n\n"); | |
| 72 | const told = await tell(app, user, repo, text); | |
| 73 | if (!told.ok) { | |
| 74 | app.log.warn("captain could not file a need", { key: n.key, error: told.error }); | |
| 75 | return undefined; | |
| 76 | } | |
| 77 | return told.value.issue.number; | |
| 78 | } | |
| 79 | ||
| 80 | /** | |
| 81 | * Run one routine now for `user`: post what is new, file what has stood a day, push only when it | |
| 82 | * needs them. | |
| 83 | */ | |
| 30 | 84 | export async function runRoutine(app: App, user: User, kind: RoutineKind, now: Date, send: Sender = post): Promise<Posted> { |
| 31 | 85 | const row = listRoutines(app.db, user.id).find((r) => r.kind === kind)!; |
| 86 | const f = await facts(app, user, now.getTime(), row.lastAt === null ? undefined : Date.parse(row.lastAt)); | |
| 87 | let memory = saidOf(app.db, user.id, kind) as Memory; | |
| 88 | if (seenSince(app, row.conversationId, row.lastAt)) memory = seenAll(memory); | |
| 89 | const once = sayOnce(needsFor(kind, f), memory, now, closedOf(app, memory)); | |
| 90 | const report = kind === "paper" ? compose(kind, f) : compose(kind, f, once); | |
| 91 | let kept = once.memory; | |
| 92 | const filed: string[] = []; | |
| 93 | for (const n of once.file) { | |
| 94 | const number = await fileNeed(app, user, n, kept[n.key]!.at); | |
| 95 | if (number === undefined) continue; | |
| 96 | kept = filedAs(kept, n.key, number); | |
| 97 | filed.push(`Filed #${number} for the crew: ${n.text}`); | |
| 98 | } | |
| 99 | const lines = [...report.lines, ...filed]; | |
| 32 | 100 | const thread = captainThread(app, user.id, row.conversationId); |
| 33 | const report = compose(kind, await facts(app, user, now.getTime(), row.lastAt === null ? undefined : Date.parse(row.lastAt))); | |
| 34 | appendTurn(app.db, user.id, thread.id, { role: "agent", text: routineText(kind, report) }); | |
| 101 | if (lines.length > 0) { | |
| 102 | const cost = costLine(dayCost(app.db, user.id, thread.id, now.getTime())); | |
| 103 | appendTurn(app.db, user.id, thread.id, { role: "agent", text: routineText(kind, { ...report, lines }, cost) }); | |
| 104 | } | |
| 35 | 105 | // Marked before the push: a dead endpoint must not make the routine run again. |
| 36 | 106 | markRan(app.db, user.id, kind, thread.id, now); |
| 107 | keepSaid(app.db, user.id, kind, kept); | |
| 108 | if (lines.length === 0) return { kind, conversationId: thread.id, posted: false, pushed: false }; | |
| 37 | 109 | const url = report.needs ? notifyUrlOf(app.db, user.id) : undefined; |
| 38 | 110 | let pushed = false; |
| 39 | 111 | if (url !== undefined) { |
| 40 | 112 | const base = app.config.url ?? ""; |
| 41 | 113 | pushed = await send(url, `${ROUTINE_NAMES[kind]}: ${report.lines[0] ?? ""}\n${base}/talk/${thread.id}`, { title: ROUTINE_NAMES[kind] }); |
| 42 | 114 | } |
| 43 | return { kind, conversationId: thread.id, pushed }; | |
| 115 | return { kind, conversationId: thread.id, posted: true, pushed }; | |
| 44 | 116 | } |
| 45 | 117 | |
| 46 | 118 | /** One pass over every admin's routines: each due one runs. A failing routine is logged and does not stop the rest. */ |
src/tui/screens/captain.ts +12 −6
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Settings › Captain in the terminal (#11011): the standing rules Talk |
| 3 | * remembers and the three routines with their schedules, from the same reads | |
| 3 | * remembers, what the Captain cost over the last day, and the three routines | |
| 4 | * with their schedules, from the same reads | |
| 4 | 5 | * and writes as /settings/captain (`talk_memory`, `talk_routines`, |
| 5 | 6 | * `runRoutine`). Owner only: a site admin who is a person. |
| 6 | 7 | * |
| @@ -9,6 +10,7 @@ | ||
| 9 | 10 | */ |
| 10 | 11 | |
| 11 | 12 | import { runRoutine } from "../../crew/routines.ts"; |
| 13 | import { costLine, dayCost } from "../../crew/captain_cost.ts"; | |
| 12 | 14 | import { addMemory, editMemory, MEMORY_TEXT_MAX, MEMORY_WORDS, removeMemory, rulesOf, type Memory } from "../../core/talk_memory.ts"; |
| 13 | 15 | import { EVERY_MAX, EVERY_MIN, listRoutines, ROUTINE_NAMES, setRoutine, type Routine } from "../../core/talk_routines.ts"; |
| 14 | 16 | import { createWatch, deleteWatch, endWatch, listWatches, pauseWatch, waitsText, WATCH_KINDS, WATCH_WORDS, type Watch } from "../../core/talk_watch.ts"; |
| @@ -33,7 +35,7 @@ export function parseSchedule(text: string): { everyMin: number; atHour: number | ||
| 33 | 35 | |
| 34 | 36 | export const scheduleText = (r: Pick<Routine, "everyMin" | "atHour">): string => (r.atHour === null ? String(r.everyMin) : `at ${r.atHour}`); |
| 35 | 37 | |
| 36 | type Line = { kind: "rule"; rule: Memory } | { kind: "routine"; routine: Routine } | { kind: "watch"; watch: Watch }; | |
| 38 | type Line = { kind: "cost"; text: string } | { kind: "rule"; rule: Memory } | { kind: "routine"; routine: Routine } | { kind: "watch"; watch: Watch }; | |
| 37 | 39 | |
| 38 | 40 | /** |
| 39 | 41 | * "pull_green trevato/forge#16532: merge it once green" is a watch: its kind, its target, then the |
| @@ -49,7 +51,9 @@ const watchMeta = (w: Watch): string => | ||
| 49 | 51 | |
| 50 | 52 | export function captainRows(lines: readonly Line[]): ListRow[] { |
| 51 | 53 | return lines.map((l) => |
| 52 | l.kind === "rule" | |
| 54 | l.kind === "cost" | |
| 55 | ? { title: l.text, meta: "cost" } | |
| 56 | : l.kind === "rule" | |
| 53 | 57 | ? { title: l.rule.text, meta: "rule" } |
| 54 | 58 | : l.kind === "watch" |
| 55 | 59 | ? { title: `Watch: ${waitsText(l.watch)}`, meta: watchMeta(l.watch) } |
| @@ -61,7 +65,9 @@ export function captainScreen(f: Session, ctx: Ctx): Screen { | ||
| 61 | 65 | const state = new ListState(); |
| 62 | 66 | let lines: Line[] = []; |
| 63 | 67 | const read = async (): Promise<void> => { |
| 64 | lines = [...rulesOf(f.app.db, f.user!.id).map((rule): Line => ({ kind: "rule", rule })), ...listRoutines(f.app.db, f.user!.id).map((routine): Line => ({ kind: "routine", routine })), ...listWatches(f.app.db, f.user!.id).map((watch): Line => ({ kind: "watch", watch }))]; | |
| 68 | const routines = listRoutines(f.app.db, f.user!.id); | |
| 69 | const cost: Line = { kind: "cost", text: costLine(dayCost(f.app.db, f.user!.id, routines.find((r) => r.conversationId !== null)?.conversationId ?? null, Date.now())) }; | |
| 70 | lines = [cost, ...rulesOf(f.app.db, f.user!.id).map((rule): Line => ({ kind: "rule", rule })), ...routines.map((routine): Line => ({ kind: "routine", routine })), ...listWatches(f.app.db, f.user!.id).map((watch): Line => ({ kind: "watch", watch }))]; | |
| 65 | 71 | state.clamp(lines.length); |
| 66 | 72 | ctx.invalidate(); |
| 67 | 73 | }; |
| @@ -137,8 +143,8 @@ export function captainScreen(f: Session, ctx: Ctx): Screen { | ||
| 137 | 143 | } else if (e.key === "p" && at?.kind === "routine") { |
| 138 | 144 | const kind = at.routine.kind; |
| 139 | 145 | runAsync(ctx, async () => { |
| 140 | await runRoutine(f.app, f.user!, kind, new Date()); | |
| 141 | ctx.toast(`${ROUTINE_NAMES[kind]} posted to your Captain thread in Talk.`, "success"); | |
| 146 | const posted = await runRoutine(f.app, f.user!, kind, new Date()); | |
| 147 | ctx.toast(posted.posted ? `${ROUTINE_NAMES[kind]} posted to your Captain thread in Talk.` : `${ROUTINE_NAMES[kind]}: nothing new since the last post.`, "success"); | |
| 142 | 148 | await read(); |
| 143 | 149 | }); |
| 144 | 150 | } else if (e.key === "r") refresh(); |
src/web/pages/captain.ts +6 −1
| @@ -11,6 +11,7 @@ import { addMemory, editMemory, MEMORY_TEXT_MAX, MEMORY_WORDS, removeMemory, rul | ||
| 11 | 11 | import { EVERY_MAX, EVERY_MIN, listRoutines, ROUTINE_KINDS, ROUTINE_NAMES, setRoutine } from "../../core/talk_routines.ts"; |
| 12 | 12 | import { CAP_DEFAULT, CAP_MAX, createWatch, deleteWatch, endWatch, KIND_WORDS, listWatches, pauseWatch, waitsText, WATCH_BRIEF_MAX, WATCH_KINDS, WATCH_WORDS } from "../../core/talk_watch.ts"; |
| 13 | 13 | import { runRoutine } from "../../crew/routines.ts"; |
| 14 | import { costLine, dayCost } from "../../crew/captain_cost.ts"; | |
| 14 | 15 | import type { Ctx } from "../../http/context.ts"; |
| 15 | 16 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 16 | 17 | import { forbiddenPage, notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; |
| @@ -36,6 +37,10 @@ function view(ctx: Ctx, error?: string, status = 200): Response { | ||
| 36 | 37 | const routines = listRoutines(ctx.app.db, user.id); |
| 37 | 38 | const watches = listWatches(ctx.app.db, user.id); |
| 38 | 39 | const body: Html = html`<section class="settings-block"> |
| 40 | <h2>Cost</h2> | |
| 41 | <p class="muted small" data-cost>${costLine(dayCost(ctx.app.db, user.id, routines.find((r) => r.conversationId !== null)?.conversationId ?? null, Date.now()))}.</p> | |
| 42 | </section> | |
| 43 | <section class="settings-block"> | |
| 39 | 44 | <h2>Memory</h2> |
| 40 | 45 | ${error ? html`<p class="field-error" role="alert">${error}</p>` : null} |
| 41 | 46 | <ul class="list">${memory.map((m) => html`<li class="row"> |
| @@ -147,7 +152,7 @@ export async function captainAct(ctx: Ctx): Promise<Response> { | ||
| 147 | 152 | if (what === "run") { |
| 148 | 153 | if (!(ROUTINE_KINDS as readonly string[]).includes(kind)) return view(ctx, "That is not a routine.", 422); |
| 149 | 154 | const posted = await runRoutine(ctx.app, user, kind as (typeof ROUTINE_KINDS)[number], new Date()); |
| 150 | return flashTo(ctx, `/talk/${posted.conversationId}`, { message: "Posted." }); | |
| 155 | return flashTo(ctx, `/talk/${posted.conversationId}`, { message: posted.posted ? "Posted." : "Nothing new since the last post." }); | |
| 151 | 156 | } |
| 152 | 157 | const hour = field(form, "hour").trim(); |
| 153 | 158 | const saved = setRoutine(db, user.id, kind, { enabled: field(form, "enabled") === "1", everyMin: Number(field(form, "every")), atHour: hour === "" ? null : Number(hour) }); |
test/data-browser.test.ts +3
| @@ -64,6 +64,9 @@ const AUDITED_CLEAR: string[] = [ | ||
| 64 | 64 | // A connection's last test, in words: what answered, never a key (core/connections.ts). |
| 65 | 65 | "subscription.test_said", |
| 66 | 66 | "subscription_limit.said", |
| 67 | // What the Captain last said, per need (`crew/routine_once.ts`): the forge's own vitals | |
| 68 | // sentences. | |
| 69 | "talk_routine.said", | |
| 67 | 70 | "user_key.blob", |
| 68 | 71 | "webhook_ping.payload", |
| 69 | 72 | "week_projection.body", |
test/talk-captain-once.test.ts added +286
| @@ -0,0 +1,286 @@ | ||
| 1 | /** | |
| 2 | * The Captain says a need once (`crew/routine_once.ts`): new, worse with its old figure, or | |
| 3 | * cleared, and nothing when nothing changed. A need the crew can fix that stands a day is filed | |
| 4 | * once on the forge's own repository and stays open; it is said again only when that issue closes | |
| 5 | * or the need gets worse. "I've seen it" and an admin-only need stay quiet until worse. Each post | |
| 6 | * and the Captain page say what the last day cost. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { appendTurn, listTurns } from "../src/core/conversations.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { keepSaid, saidOf } from "../src/core/talk_routines.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { costLine, dayCost } from "../src/crew/captain_cost.ts"; | |
| 19 | import { FILE_AFTER_MS, figureOf, lowerIsWorse, sayOnce, seenAll, worse, type Memory, type Need } from "../src/crew/routine_once.ts"; | |
| 20 | import { compose, needsOf, type Facts } from "../src/crew/routine_report.ts"; | |
| 21 | import { runRoutine } from "../src/crew/routines.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | const T = Date.parse("2026-11-20T10:30:00Z"); | |
| 28 | const at = (ms: number): Date => new Date(T + ms); | |
| 29 | const H = 3_600_000; | |
| 30 | ||
| 31 | describe("say once", () => { | |
| 32 | const db: Need = { key: "db-size", text: "The database is 4.6 GiB.", adminOnly: false }; | |
| 33 | const keys: Need = { key: "disk", text: "Disk is nearly full: 9% free.", adminOnly: true }; | |
| 34 | ||
| 35 | test("a new need is said; the same need again is not; nothing changed is no lines", () => { | |
| 36 | const one = sayOnce([db], {}, at(0)); | |
| 37 | expect(one.lines).toEqual(["Needs you: The database is 4.6 GiB."]); | |
| 38 | expect(one.pushes).toBe(true); | |
| 39 | const two = sayOnce([db], one.memory, at(H)); | |
| 40 | expect(two).toMatchObject({ lines: [], pushes: false, file: [] }); | |
| 41 | expect(two.memory).toEqual(one.memory); | |
| 42 | }); | |
| 43 | ||
| 44 | test("worse is a figure moved by a tenth, said with the figure it had", () => { | |
| 45 | const one = sayOnce([db], {}, at(0)).memory; | |
| 46 | expect(sayOnce([{ ...db, text: "The database is 4.8 GiB." }], one, at(H)).lines).toEqual([]); | |
| 47 | const up = sayOnce([{ ...db, text: "The database is 5.1 GiB." }], one, at(H)); | |
| 48 | expect(up.lines).toEqual(["Worse: The database is 5.1 GiB. (was 4.6)"]); | |
| 49 | expect(up.pushes).toBe(true); | |
| 50 | expect(up.memory["db-size"]!.at).toBe(one["db-size"]!.at); | |
| 51 | // A slow creep adds up: 4.9 is under a tenth past 4.6, 5.1 is past it. | |
| 52 | const creep = sayOnce([{ ...db, text: "The database is 4.9 GiB." }], one, at(H)); | |
| 53 | expect(creep.lines).toEqual([]); | |
| 54 | expect(sayOnce([{ ...db, text: "The database is 5.1 GiB." }], creep.memory, at(2 * H)).lines).toEqual(["Worse: The database is 5.1 GiB. (was 4.6)"]); | |
| 55 | }); | |
| 56 | ||
| 57 | test("a move the good way is never worse: more free disk is kept quietly, and the next fall is measured from it", () => { | |
| 58 | const disk: Need = { key: "disk", text: "Disk is nearly full: 9% free.", adminOnly: true }; | |
| 59 | const one = sayOnce([disk], {}, at(0)).memory; | |
| 60 | const roomier = sayOnce([{ ...disk, text: "Disk is nearly full: 12% free." }], one, at(H)); | |
| 61 | expect(roomier).toMatchObject({ lines: [], pushes: false }); | |
| 62 | expect(roomier.memory["disk"]!.figure).toBe(12); | |
| 63 | const fell = sayOnce([{ ...disk, text: "Disk is nearly full: 10% free." }], roomier.memory, at(2 * H)); | |
| 64 | expect(fell.lines).toEqual(["Worse: Disk is nearly full: 10% free. (was 12)"]); | |
| 65 | // The database shrinking is better too. | |
| 66 | const smaller = sayOnce([{ ...db, text: "The database is 3.9 GiB." }], sayOnce([db], {}, at(0)).memory, at(H)); | |
| 67 | expect(smaller.lines).toEqual([]); | |
| 68 | expect(lowerIsWorse("Disk is nearly full: 9% free.")).toBe(true); | |
| 69 | expect(lowerIsWorse("The database is 4.6 GiB.")).toBe(false); | |
| 70 | }); | |
| 71 | ||
| 72 | test("the measure is a number with a unit, never one in a name, a time or an id; words alone are never worse", () => { | |
| 73 | expect(figureOf("The database is 4.6 GiB, past the 2 GiB Bun maps: as of 22:49Z")).toBe(4.6); | |
| 74 | expect(figureOf("Disk is nearly full: 9% free.")).toBe(9); | |
| 75 | expect(figureOf("2 branches of scout/forge2 cannot be backed up")).toBe(2); | |
| 76 | expect(figureOf("as of 22:49Z main is red on scout/forge2 at run 01m8f4s7")).toBeNull(); | |
| 77 | expect(figureOf("Run 01m8 is stuck: no heartbeat for 42 min")).toBeNull(); | |
| 78 | const red: Need = { key: "red:r", text: "Main is red on a/b since 21:03Z.", adminOnly: false }; | |
| 79 | const one = sayOnce([red], {}, at(0)).memory; | |
| 80 | expect(sayOnce([{ ...red, text: "Main is red on a/b since 22:41Z." }], one, at(H)).lines).toEqual([]); | |
| 81 | expect(worse({ figure: null }, { text: "other words" })).toBe(false); | |
| 82 | // A count given outright wins over the words: two stuck runs, then three. | |
| 83 | const stuck: Need = { key: "stuck", text: "Run x is stuck: no heartbeat for 12 min.", adminOnly: false, figure: 1 }; | |
| 84 | const s1 = sayOnce([stuck], {}, at(0)).memory; | |
| 85 | expect(sayOnce([{ ...stuck, text: "Run x is stuck: no heartbeat for 72 min." }], s1, at(H)).lines).toEqual([]); | |
| 86 | expect(sayOnce([{ ...stuck, text: "3 runs are stuck.", figure: 3 }], s1, at(H)).lines).toEqual(["Worse: 3 runs are stuck. (was 1)"]); | |
| 87 | }); | |
| 88 | ||
| 89 | test("a need gone is cleared once", () => { | |
| 90 | const one = sayOnce([db, keys], {}, at(0)).memory; | |
| 91 | const gone = sayOnce([keys], one, at(H)); | |
| 92 | expect(gone.lines).toEqual(["Cleared: The database is 4.6 GiB."]); | |
| 93 | expect(gone.pushes).toBe(false); | |
| 94 | expect(sayOnce([keys], gone.memory, at(2 * H)).lines).toEqual([]); | |
| 95 | }); | |
| 96 | ||
| 97 | test("a day on, only a need the crew can fix is filed, once; seen and admin-only stay quiet", () => { | |
| 98 | const one = sayOnce([db, keys], {}, at(0)).memory; | |
| 99 | expect(sayOnce([db, keys], one, at(FILE_AFTER_MS - 1)).file).toEqual([]); | |
| 100 | const day = sayOnce([db, keys], one, at(FILE_AFTER_MS)); | |
| 101 | expect(day.file.map((n) => n.key)).toEqual(["db-size"]); | |
| 102 | expect(day.lines).toEqual([]); | |
| 103 | expect(sayOnce([db, keys], seenAll(one), at(FILE_AFTER_MS)).file).toEqual([]); | |
| 104 | const filed: Memory = { "db-size": { ...one["db-size"]!, filed: 41 } }; | |
| 105 | expect(sayOnce([db], filed, at(2 * FILE_AFTER_MS)).file).toEqual([]); | |
| 106 | const reopened = sayOnce([db], filed, at(2 * FILE_AFTER_MS), new Set(["db-size"])); | |
| 107 | expect(reopened.lines).toEqual(["Needs you again (#41 closed): The database is 4.6 GiB."]); | |
| 108 | expect(reopened.memory["db-size"]!.filed).toBeUndefined(); | |
| 109 | }); | |
| 110 | ||
| 111 | test("seen is silent until worse, and worse forgets the seen", () => { | |
| 112 | const one = seenAll(sayOnce([db], {}, at(0)).memory); | |
| 113 | expect(sayOnce([db], one, at(H)).lines).toEqual([]); | |
| 114 | const up = sayOnce([{ ...db, text: "The database is 6 GiB." }], one, at(H)); | |
| 115 | expect(up.lines).toHaveLength(1); | |
| 116 | expect(up.memory["db-size"]!.seen).toBeUndefined(); | |
| 117 | }); | |
| 118 | }); | |
| 119 | ||
| 120 | describe("the needs the check-in keys", () => { | |
| 121 | test("a settings page is the admin's alone; stuck runs are one need; a red trunk keys by its repository", () => { | |
| 122 | const d = (cause: string, href: string, sentence = `${cause} is off.`) => ({ cause, sentence, since: "", href, broken: false }); | |
| 123 | const needs = needsOf( | |
| 124 | [d("disk", "/settings/capacity"), d("db-size", "/system"), d("stuck:r1", "/runs/1"), d("stuck:r2", "/runs/2"), d("red:R1", "/a/b")], | |
| 125 | [ | |
| 126 | { repoId: "R1", line: "main is red on a/b.", link: "/a/b/runs/9" }, | |
| 127 | { repoId: "R2", line: "main is red on a/c.", link: "/a/c/runs/8" }, | |
| 128 | ], | |
| 129 | ); | |
| 130 | expect(needs.map((n) => [n.key, n.adminOnly])).toEqual([ | |
| 131 | ["disk", true], | |
| 132 | ["db-size", false], | |
| 133 | ["red:R1", false], | |
| 134 | ["stuck", false], | |
| 135 | ["red:R2", false], | |
| 136 | ]); | |
| 137 | expect(needs.find((n) => n.key === "stuck")!.text).toBe("2 runs are stuck."); | |
| 138 | }); | |
| 139 | ||
| 140 | test("the friends watch names who joined and says the waiting requests once", () => { | |
| 141 | const quiet: Facts = { | |
| 142 | health: [], | |
| 143 | redMain: [], | |
| 144 | needs: [], | |
| 145 | asks: 0, | |
| 146 | holds: {}, | |
| 147 | newPeople: [], | |
| 148 | waiting: 0, | |
| 149 | mergedToday: 0, | |
| 150 | openedToday: 0, | |
| 151 | releases: [], | |
| 152 | pillarsMoved: [], | |
| 153 | }; | |
| 154 | expect(compose("friends", quiet).lines).toEqual([]); | |
| 155 | expect(compose("checkin", quiet).lines).toEqual([]); | |
| 156 | expect(compose("friends", { ...quiet, newPeople: ["ana"] })).toEqual({ lines: ["New: ana."], needs: false }); | |
| 157 | const told = compose("friends", { ...quiet, waiting: 2 }); | |
| 158 | expect(told).toEqual({ lines: ["Needs you: 2 requests for an account waiting for your allow."], needs: true }); | |
| 159 | }); | |
| 160 | }); | |
| 161 | ||
| 162 | describe("the runner", () => { | |
| 163 | let dir: string; | |
| 164 | let app: App; | |
| 165 | let servers: Servers; | |
| 166 | let owner: User; | |
| 167 | let grown: { baselineBytes: number; rssBytes: number; since: number } | undefined; | |
| 168 | const GIB = 1024 ** 3; | |
| 169 | ||
| 170 | beforeAll(async () => { | |
| 171 | dir = await mkdtemp(join(tmpdir(), "forge-captain-once-")); | |
| 172 | app = createApp({ | |
| 173 | dataDir: dir, | |
| 174 | port: 0, | |
| 175 | forgeRepo: "skipper/engine", | |
| 176 | disk: () => ({ freeBytes: 900 * GIB, totalBytes: 1000 * GIB }), | |
| 177 | hostFree: () => 64 * GIB, | |
| 178 | memoryWatch: { grown: () => grown }, | |
| 179 | }); | |
| 180 | servers = await serve(app); | |
| 181 | const u = await createUser(app.db, { | |
| 182 | origin: "seed", | |
| 183 | trusted: true, | |
| 184 | username: "skipper", | |
| 185 | email: "[email protected]", | |
| 186 | password: "a-good-passphrase", | |
| 187 | adminIfFirst: true, | |
| 188 | }); | |
| 189 | if (!u.ok) throw new Error(u.error); | |
| 190 | owner = u.value; | |
| 191 | const repo = await createRepo(app, owner, { name: "engine", visibility: "public" }); | |
| 192 | if (!repo.ok) throw new Error(repo.error); | |
| 193 | }, 30_000); | |
| 194 | ||
| 195 | afterAll(async () => { | |
| 196 | servers.stop(); | |
| 197 | await rm(dir, { recursive: true, force: true }); | |
| 198 | }); | |
| 199 | ||
| 200 | const texts = (id: string): string[] => { | |
| 201 | const t = listTurns(app.db, owner.id, id, { limit: 200 }); | |
| 202 | if (!t.ok) throw new Error(t.error); | |
| 203 | return t.value.map((x) => x.text); | |
| 204 | }; | |
| 205 | const growth = (): string[] => Object.keys(saidOf(app.db, owner.id, "checkin")).filter((k) => k === "memory-growth"); | |
| 206 | ||
| 207 | test("a need is said once, filed for the crew a day on, and said again when its issue closes", async () => { | |
| 208 | grown = { baselineBytes: 400 * 1024 ** 2, rssBytes: 900 * 1024 ** 2, since: T - H }; | |
| 209 | const first = await runRoutine(app, owner, "checkin", at(0), async () => true); | |
| 210 | expect(first.posted).toBe(true); | |
| 211 | const said = texts(first.conversationId).at(-1)!; | |
| 212 | expect(said).toMatch(/Needs you: .*/); | |
| 213 | expect(said).toContain("Last 24 h: check-in and friends: no model, $0 · watches $0 (0 wakes) · your turns here $0"); | |
| 214 | expect(growth()).toEqual(["memory-growth"]); | |
| 215 | ||
| 216 | const hour = await runRoutine(app, owner, "checkin", at(H), async () => true); | |
| 217 | expect(hour).toMatchObject({ posted: false, pushed: false }); | |
| 218 | ||
| 219 | const day = await runRoutine(app, owner, "checkin", at(FILE_AFTER_MS), async () => true); | |
| 220 | expect(day.posted).toBe(true); | |
| 221 | const filedLine = texts(day.conversationId).at(-1)!; | |
| 222 | const number = Number(/Filed #(\d+) for the crew: /.exec(filedLine)?.[1]); | |
| 223 | expect(number).toBeGreaterThan(0); | |
| 224 | const issue = app.db | |
| 225 | .query< | |
| 226 | { state: string; title: string; body: string }, | |
| 227 | [number] | |
| 228 | >("SELECT i.state, i.title, i.body FROM issue i JOIN repo r ON r.id = i.repo_id WHERE r.name = 'engine' AND i.number = ?1") | |
| 229 | .get(number)!; | |
| 230 | expect(issue.state).toBe("open"); | |
| 231 | expect(issue.body).toContain("memory-growth"); | |
| 232 | ||
| 233 | // Filed: silent while the issue is open, even days on. | |
| 234 | expect((await runRoutine(app, owner, "checkin", at(3 * FILE_AFTER_MS), async () => true)).posted).toBe(false); | |
| 235 | expect(app.db.query("SELECT COUNT(*) AS n FROM issue i JOIN repo r ON r.id = i.repo_id WHERE r.name = 'engine'").get()).toEqual({ | |
| 236 | n: 1, | |
| 237 | }); | |
| 238 | ||
| 239 | app.db.query("UPDATE issue SET state = 'closed' WHERE number = ?1").run(number); | |
| 240 | const again = await runRoutine(app, owner, "checkin", at(3 * FILE_AFTER_MS + H), async () => true); | |
| 241 | expect(again.posted).toBe(true); | |
| 242 | expect(texts(again.conversationId).at(-1)).toContain(`Needs you again (#${number} closed): `); | |
| 243 | ||
| 244 | grown = undefined; | |
| 245 | const cleared = await runRoutine(app, owner, "checkin", at(3 * FILE_AFTER_MS + 2 * H), async () => true); | |
| 246 | expect(texts(cleared.conversationId).at(-1)).toContain("Cleared: "); | |
| 247 | expect(growth()).toEqual([]); | |
| 248 | }); | |
| 249 | ||
| 250 | test("I've seen it keeps a need quiet: it is never filed", async () => { | |
| 251 | keepSaid(app.db, owner.id, "checkin", {}); | |
| 252 | grown = { baselineBytes: 400 * 1024 ** 2, rssBytes: 900 * 1024 ** 2, since: T - H }; | |
| 253 | const base = 10 * FILE_AFTER_MS; | |
| 254 | const one = await runRoutine(app, owner, "checkin", at(base), async () => true); | |
| 255 | expect(one.posted).toBe(true); | |
| 256 | appendTurn(app.db, owner.id, one.conversationId, { role: "person", text: "I've seen it, leave it." }); | |
| 257 | // The turn is said on the test's clock: after the post it answers. | |
| 258 | app.db.query("UPDATE conversation_turn SET created_at = ?1 WHERE text = 'I''ve seen it, leave it.'").run(at(base + H).toISOString()); | |
| 259 | const later = await runRoutine(app, owner, "checkin", at(base + 2 * FILE_AFTER_MS), async () => true); | |
| 260 | expect(later.posted).toBe(false); | |
| 261 | expect(Object.values(saidOf(app.db, owner.id, "checkin")).every((s) => (s as { filed?: number }).filed === undefined)).toBe(true); | |
| 262 | grown = undefined; | |
| 263 | }); | |
| 264 | ||
| 265 | test("the day's cost counts watch wakes and the owner's own turns, and shows on the Captain page", async () => { | |
| 266 | const thread = (await runRoutine(app, owner, "paper", new Date(), async () => true)).conversationId; | |
| 267 | const now = Date.now(); | |
| 268 | const run = (id: string, conversation: string, prompt: string, usd: number, ago: number) => | |
| 269 | app.db | |
| 270 | .query( | |
| 271 | "INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, cost_usd, started_at) VALUES (?1, ?2, ?3, 'ok', ?4, ?5, ?6)", | |
| 272 | ) | |
| 273 | .run(id, conversation, owner.id, prompt, usd, new Date(now - ago).toISOString()); | |
| 274 | run("w1", thread, "[Watch abc] the pull went green", 0.25, H); | |
| 275 | run("w2", thread, "[Watch abc] it merged", 0.5, 2 * H); | |
| 276 | run("t1", thread, "what is red?", 1.25, H); | |
| 277 | run("old", thread, "yesterday's question", 9, 25 * H); | |
| 278 | const cost = dayCost(app.db, owner.id, thread, now); | |
| 279 | expect(cost).toEqual({ watchesUsd: 0.75, wakes: 2, turnsUsd: 1.25 }); | |
| 280 | expect(costLine(cost)).toBe("Last 24 h: check-in and friends: no model, $0 · watches $0.75 (2 wakes) · your turns here $1.25"); | |
| 281 | const page = await fetch(`${servers.url}/settings/captain`, { | |
| 282 | headers: { cookie: `forge_session=${createSession(app.db, owner.id).token}` }, | |
| 283 | }); | |
| 284 | expect(await page.text()).toContain("watches $0.75 (2 wakes) · your turns here $1.25"); | |
| 285 | }); | |
| 286 | }); |
test/talk-captain.test.ts +16 −7
| @@ -50,7 +50,7 @@ afterAll(async () => { | ||
| 50 | 50 | await rm(dir, { recursive: true, force: true }); |
| 51 | 51 | }); |
| 52 | 52 | |
| 53 | const quiet: Facts = { health: [], redMain: [], asks: 0, holds: {}, grokbotPulls: 0, mergedLastHour: 0, newPeople: [], waiting: 0, stuckRuns: 0, mergedToday: 0, openedToday: 0, releases: [], pillarsMoved: [] }; | |
| 53 | const quiet: Facts = { health: [], redMain: [], needs: [], asks: 0, holds: {}, newPeople: [], waiting: 0, mergedToday: 0, openedToday: 0, releases: [], pillarsMoved: [] }; | |
| 54 | 54 | |
| 55 | 55 | describe("memory", () => { |
| 56 | 56 | test("is the person's own, bounded, and in the brief", () => { |
| @@ -141,8 +141,8 @@ describe("what a routine says", () => { | ||
| 141 | 141 | expect(told.needs).toBe(false); |
| 142 | 142 | const many = compose("checkin", { ...quiet, releases: ["1", "2", "3", "4", "5"], pillarsMoved: [] }); |
| 143 | 143 | expect(many.lines.join(" ")).toContain("released 5 (to 5)"); |
| 144 | expect(many.lines).toHaveLength(3); | |
| 145 | expect(compose("checkin", quiet).lines.join(" ")).not.toMatch(/released|moved/); | |
| 144 | expect(many.lines).toHaveLength(1); | |
| 145 | expect(compose("checkin", quiet).lines).toEqual([]); | |
| 146 | 146 | }); |
| 147 | 147 | test("releases since an instant, oldest first", () => { |
| 148 | 148 | const entries = [{ version: "0.7.3", date: "2026-11-10T11:00:00Z" }, { version: "0.7.2", date: "2026-11-10T10:00:00Z" }, { version: "0.7.1", date: "2026-11-10T08:00:00Z" }]; |
| @@ -153,13 +153,16 @@ describe("what a routine says", () => { | ||
| 153 | 153 | for (const kind of ["checkin", "friends", "paper"] as const) { |
| 154 | 154 | expect(compose(kind, quiet).lines.length).toBeLessThanOrEqual(LINES_MAX); |
| 155 | 155 | expect(compose(kind, quiet).needs).toBe(false); |
| 156 | const loud = compose(kind, { ...quiet, health: ["disk is nearly full"], waiting: 2, newPeople: ["a", "b", "c", "d", "e", "f", "g"], stuckRuns: 1 }); | |
| 156 | const needs = ["a", "b", "c", "d"].map((key) => ({ key, text: `${key} is off.`, adminOnly: false })); | |
| 157 | const loud = compose(kind, { ...quiet, health: ["disk is nearly full"], needs, waiting: 2, newPeople: ["a", "b", "c", "d", "e", "f", "g"] }); | |
| 157 | 158 | expect(loud.lines.length).toBeLessThanOrEqual(LINES_MAX); |
| 158 | 159 | } |
| 159 | expect(compose("checkin", { ...quiet, redMain: ["main is red"] })).toMatchObject({ needs: true }); | |
| 160 | const four = compose("checkin", { ...quiet, needs: ["a", "b", "c", "d"].map((key) => ({ key, text: `${key} is off.`, adminOnly: false })) }); | |
| 161 | expect(four.lines.at(-1)).toBe("2 more: see /system."); | |
| 162 | expect(compose("checkin", { ...quiet, needs: [{ key: "red:r", text: "main is red", adminOnly: false }] })).toMatchObject({ needs: true }); | |
| 160 | 163 | expect(compose("friends", { ...quiet, waiting: 1 }).needs).toBe(true); |
| 161 | 164 | expect(compose("friends", { ...quiet, newPeople: ["ana"] }).needs).toBe(false); |
| 162 | expect(compose("checkin", { ...quiet, holds: { juniper: 2 }, grokbotPulls: 1 }).lines.join(" ")).toContain("juniper 2"); | |
| 165 | expect(compose("paper", { ...quiet, holds: { juniper: 2 } }).lines.join(" ")).toContain("juniper 2"); | |
| 163 | 166 | }); |
| 164 | 167 | }); |
| 165 | 168 | |
| @@ -176,7 +179,10 @@ describe("the runner", () => { | ||
| 176 | 179 | expect(new Set(done.map((d) => d.conversationId)).size).toBe(1); |
| 177 | 180 | const turns = listTurns(app.db, owner.id, done[0]!.conversationId, { limit: 50 }); |
| 178 | 181 | if (!turns.ok) throw new Error("turns"); |
| 179 | expect(turns.value.map((t) => t.role)).toEqual(["agent", "agent", "agent"]); | |
| 182 | // Only what has something new posts: the paper always, the others when a need or a person is | |
| 183 | // new. | |
| 184 | expect(done.find((d) => d.kind === "paper")!.posted).toBe(true); | |
| 185 | expect(turns.value.map((t) => t.role)).toEqual(done.filter((d) => d.posted).map(() => "agent")); | |
| 180 | 186 | expect(turns.value[0]!.text).toContain("**"); |
| 181 | 187 | expect(sent).toEqual([]); |
| 182 | 188 | // Ran now: nothing is due a minute later, and a person who is not an admin gets none. |
| @@ -195,6 +201,9 @@ describe("the runner", () => { | ||
| 195 | 201 | expect(sent).toHaveLength(1); |
| 196 | 202 | expect(sent[0]).toContain("https://ntfy.example/topic|Friends watch:"); |
| 197 | 203 | expect(sent[0]).toContain(`/talk/${posted.conversationId}`); |
| 204 | // Said once: the same waiting request is not posted or pushed again. | |
| 205 | expect(await runRoutine(app, owner, "friends", new Date(), async (url, body) => (sent.push(`${url}|${body}`), true))).toMatchObject({ posted: false, pushed: false }); | |
| 206 | expect(sent).toHaveLength(1); | |
| 198 | 207 | }); |
| 199 | 208 | }); |
| 200 | 209 |
test/talk-checkin-story.test.ts +3 −4
| @@ -115,10 +115,9 @@ describe("runRoutine's window is the last check-in", () => { | ||
| 115 | 115 | const text = (id: string) => turnsOf(id).map((t) => t.text).join("\n"); |
| 116 | 116 | expect(text(one.conversationId)).toContain("released 0.1.1, 0.1.2; moved: P0 Trust 1"); |
| 117 | 117 | expect(listRoutines(app.db, alice.id).find((r) => r.kind === "checkin")!.lastAt).toBe(first.toISOString()); |
| 118 | const before = turnsOf(one.conversationId).length; | |
| 118 | 119 | const two = await runRoutine(app, alice, "checkin", new Date(T + 120_000), async () => true); |
| 119 | const turns = turnsOf(two.conversationId); | |
| 120 | const last = turns[turns.length - 1]!.text; | |
| 121 | expect(last).toContain("Forge check-in"); | |
| 122 | expect(last).not.toMatch(/released|moved/); | |
| 120 | const after = turnsOf(two.conversationId).slice(before).map((t) => t.text).join("\n"); | |
| 121 | expect(after).not.toMatch(/released|moved/); | |
| 123 | 122 | }); |
| 124 | 123 | }); |
new above
offline
Math.absmakes an improvement count as worse. A figure that falls, or a free-space percentage that rises, is posted asWorse:and pushed to the phone. Give a Need a direction (higher is worse or lower is worse), or haveneedsOfsupply the figure already signed so that only a worsening move counts. Add a test where the figure moves the good way and expect no lines.