From a9caf45bfd87a5904baa273808f5b90172062451 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 14:18:53 +0000 Subject: [PATCH 1/2] pm-console: run queue and GitHub operations at the edge while the laptop is away MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The edge runs the real Ops and Work classes in the Durable Object once the laptop has been quiet for 60s, through a new edge run translator (edge/src/direct.ts): fleet gh api argv become GitHub REST calls, fleet secrets get becomes a Worker secret, and the queue store is already reached by fetch. Laptop-only verbs answer needs the laptop. Direct reads: board, prs, priorities, asks. Direct writes: ask.send, ask.reply, ask.close, issue.comment, need.comment, issue.rank, task.move. A new prompt files its issue at the edge and holds only prompt.enqueue for the laptop, which runs ops.enqueue on return; a reply posts its comment once at the edge and is never repeated. The no-twice rule stands: an action relayed with no answer is only ever resolved by the laptop. EdgeConfig gains queueDbUrl, queueTokenName, promptLabel, needsRepos. scripts/expose.py gains --edge-direct (off by default, remembered like --edge) provisioning GITHUB_TOKEN, QUEUE_TOKEN and EDGE_DIRECT; health reports the capability and an hourly self-check of one read of each kind. This supersedes the approach of PR #12548 for the PR read: its dedicated readOpenPullRequests/freshRead is replaced by Ops.prs() through the same run/fetch, so the PR read shares the one path. Tests: bun test 130 pass (was 110) — 13 direct translator tests, 6 new edge integration tests, 1 enqueue-hook test. The edge bundles: wrangler deploy --dry-run, 126.87 KiB. Refs #12518 --- .github/workflows/pm-console-edge-deploy.yml | 16 +- pm-stack/console/edge/README.md | 41 +- pm-stack/console/edge/src/direct.ts | 194 +++++++ pm-stack/console/edge/src/edge.ts | 189 ++++++- pm-stack/console/edge/src/worker.ts | 12 + pm-stack/console/edge/wrangler.jsonc | 7 +- pm-stack/console/scripts/edge-demo.ts | 4 + pm-stack/console/scripts/edge-smoke.ts | 4 + pm-stack/console/scripts/expose.py | 115 ++++- pm-stack/console/src/actions.ts | 23 +- pm-stack/console/src/docs.ts | 21 + pm-stack/console/src/edge-proto.ts | 23 +- pm-stack/console/src/ops.ts | 25 +- pm-stack/console/src/server.ts | 4 + pm-stack/console/src/work.ts | 31 +- pm-stack/console/test/direct.test.ts | 176 +++++++ pm-stack/console/test/edge.test.ts | 517 ++++++++++++++++++- pm-stack/console/test/work.test.ts | 42 ++ 18 files changed, 1403 insertions(+), 41 deletions(-) create mode 100644 pm-stack/console/edge/src/direct.ts create mode 100644 pm-stack/console/test/direct.test.ts diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 0e6425a8cd..8fb096d5dd 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -11,12 +11,16 @@ name: pm-console-edge deploy # CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge # deploys with. # -# The Worker has no secrets: the keys it uses it makes itself, or are -# published by the host. It has no route here either. The host's -# pm-stack/console/scripts/expose.py sends the hostname through it once -# it answers its health check, and `expose.py --edge off` takes the -# hostname off it again, which is the rollback that needs no deploy. A -# manual run with rollback_version puts an earlier version back. +# The Worker has no secrets from this deploy: the keys it uses it makes +# itself, or are published by the host. Three secrets are optional, put +# there by the host's scripts/expose.py --edge-direct (off by default): +# GITHUB_TOKEN and QUEUE_TOKEN, which let it act itself while the laptop +# is away, and EDGE_DIRECT, the opt-in that must read `on`. It has no +# route here either. The host's pm-stack/console/scripts/expose.py sends +# the hostname through it once it answers its health check, and +# `expose.py --edge off` takes the hostname off it again, which is the +# rollback that needs no deploy. A manual run with rollback_version puts +# an earlier version back. # # Until both secrets exist the job says so in its summary and skips the # upload instead of failing. diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 18890a7619..dc841894cd 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -11,10 +11,11 @@ runs the fleet's tools can be reached. | -------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------- | | The app's page, script and icons | edge | unchanged | | Checking who is calling | edge, and again on the laptop | the edge still answers the owner; anyone it is unsure of gets nothing | -| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | served as of the last report, with that time shown | +| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | the board, pull requests, ranked issues and prompts refresh from GitHub and the queue store after one minute of silence; the rest stays as of the last report | | Notifications: keys, subscriptions, sending | edge | unchanged; and one says the laptop has gone quiet | | Linked phones and the widget's summary | edge | unchanged | | Actions safe to do late (prompts, answers, comments, …) | laptop, relayed at once | held at the edge, run once when it is back, dropped after a day and said so | +| Direct actions (reply to or close a prompt, comment, rank an issue, move a task) | edge, once the laptop has been quiet for a minute | run at the edge through the laptop's own classes, and never sent to the laptop, so they are not done twice; a new prompt is filed at the edge and only its queue task is held for the laptop | | Actions not safe to do late (merge, units, unblock, …) | laptop, relayed at once | refused, saying why | | The dashboard's own pages, logs, one pull request's page | laptop | a plain notice with a link to the app | @@ -31,7 +32,9 @@ Cloudflare Access ── sign-in (email code; Google once its client exists) pm-console-edge (this Worker, on the hostname's route) ├─ src/worker.ts wiring: the object, the app's files, the laptop ├─ src/entry.ts what to do with a request - └─ src/edge.ts the state, in one Durable Object + ├─ src/edge.ts the state, in one Durable Object + └─ src/direct.ts the laptop's own classes (Ops, Work) with stand-ins + for GitHub and the queue store, for while it is away │ same hostname, through the tunnel laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts ``` @@ -77,7 +80,21 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts only actions on the late list, and records each in its audit log as `via: edge-held` with who took it and when. -The Worker has no secrets configured. The keys it uses it made itself +Three secrets are optional, put there by the laptop's +`scripts/expose.py --edge-direct on` (off by default, remembered): +`GITHUB_TOKEN` (the repository automation token), `QUEUE_TOKEN` (the +queue store token), and `EDGE_DIRECT`, the explicit opt-in that must +read `on` for either to be used. With them, the edge reads the board, +pull requests, ranked issues and prompts itself, and runs the direct +actions, once the laptop has been quiet for a minute; without them, or +with the flag off, it serves only the laptop's last report and holds +what the owner does, as before. `/console/health` says whether the +flag is on, whether each token is present, whether the direct +capability is ready, and the result of the self-check: one direct read +of each kind, run when the secrets arrive and at most once an hour +after. A secret is sent only to its own service — the GitHub token +only to GitHub, the queue token only to the queue store — and is never +returned by health. The other keys the Worker uses it made itself (notification signing) or were published to it (the laptop's, the sign-in issuer's). @@ -116,10 +133,18 @@ simply what is behind the hostname. ## Limits worth knowing -- State at the edge is the laptop's last report. With the laptop gone it - ages, and the app says how old it is; it does not go on changing. -- Reading the queue and filing a prompt straight from the edge, with the - laptop off, is not built: it needs the queue store's and GitHub's - credentials at the edge. +- State at the edge is the laptop's last report, except for the board, + pull requests, ranked issues and prompts, which the edge reads itself + after the laptop has been quiet for a minute. The rest ages, and the + app says how old it is. +- A new prompt filed at the edge still needs the laptop for its queue + task: the issue is filed at once and only the task is held, as + `prompt.enqueue`, for the laptop's return. The queue task is never + written from the edge itself: there is no fleet binary there, and + copying the queue's rows by hand would break its contract. +- An action the edge runs itself is never sent to the laptop, so the + laptop cannot repeat it; an action that was relayed and got no answer + is only ever resolved by the laptop, which wrote its name down before + starting. That is the rule against doing anything twice. - The storage is one Durable Object. A section larger than one stored value is kept in pieces. diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts new file mode 100644 index 0000000000..5ff4e4294b --- /dev/null +++ b/pm-stack/console/edge/src/direct.ts @@ -0,0 +1,194 @@ +// What the edge can do itself while the laptop is away: the laptop +// console's own classes, with stand-ins only where they touch the +// outside world. +// +// Ops and Work take a `run` function and a `fetch`. At the edge, `run` +// turns `fleet gh api` argv into GitHub REST calls and +// `fleet secrets get ` into the Worker secret, and +// refuses every other fleet verb as needing the laptop; `fetch` is the +// Worker's own, which already reaches the queue store. So board, pull +// requests, ranked issues and prompts are read, and the one-call writes +// are run, by the same code the laptop runs — nothing here re-implements +// their shapes. +// +// What stays the laptop's: `fleet queue enqueue` (the fleet binary is +// not here), `fleet bridge`, `systemctl`, and anything that reads the +// dashboard or the decisions file, which live on the laptop alone. +// A new prompt is filed at the edge and only its queue task is held for +// the laptop, as `prompt.enqueue`: the issue is never filed twice. +import { OpError } from "../../src/errors.ts"; +import type { Config } from "../../src/config.ts"; +import type { EdgeConfig } from "../../src/edge-proto.ts"; +import { Ops, type Fetch, type Run, type RunResult } from "../../src/ops.ts"; +import { Work } from "../../src/work.ts"; + +/** Sections the edge reads itself once the laptop has gone quiet. */ +export const DIRECT_READ_SECTIONS = ["board", "prs", "priorities", "asks"] as const; +/** Actions the edge runs itself once the laptop has gone quiet. */ +export const DIRECT_ACTIONS = [ + "ask.send", + "ask.reply", + "ask.close", + "issue.comment", + "need.comment", + "issue.rank", + "task.move", +] as const; + +export interface DirectSecrets { + githubToken?: string; + queueToken?: string; +} + +/** One `fleet gh api` call as a GitHub REST call. `argv` is what follows + * `api`: an optional `-X METHOD`, the path, `-f key=value` pairs, and + * `--input -` for a JSON body on stdin. A failed call answers the way + * the fleet binary would: a non-zero code with the body's own words on + * stderr, so callers that look for them (the prompt label's + * `already_exists`) still find them. */ +async function ghApi( + argv: string[], + stdin: string | undefined, + token: string | undefined, + fetchImpl: Fetch, +): Promise { + if (!token) throw new OpError(502, "the edge has no GitHub token"); + let method = "GET"; + let path = ""; + const fields: [string, string][] = []; + let useStdin = false; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === "-X") method = argv[++i] ?? "GET"; + else if (arg === "-f") { + const pair = argv[++i] ?? ""; + const at = pair.indexOf("="); + if (at < 0) throw new OpError(502, `fleet gh api: -f needs key=value, got ${pair}`); + fields.push([pair.slice(0, at), pair.slice(at + 1)]); + } else if (arg === "--input") { + if (argv[++i] !== "-") throw new OpError(502, "fleet gh api: --input takes -"); + useStdin = true; + } else if (path === "") path = arg; + else throw new OpError(502, `fleet gh api: unexpected argument ${arg}`); + } + if (path === "") throw new OpError(502, "fleet gh api: no path"); + let url = `https://api.github.com/${path}`; + let body: string | undefined; + if (method === "GET") { + if (fields.length > 0) { + const query = new URLSearchParams(fields); + url += (url.includes("?") ? "&" : "?") + query.toString(); + } + } else if (useStdin) { + body = stdin; + } else if (fields.length > 0) { + body = JSON.stringify(Object.fromEntries(fields)); + } + const res = await fetchImpl(url, { + method, + headers: { + accept: "application/vnd.github+json", + authorization: `Bearer ${token}`, + "x-github-api-version": "2022-11-28", + ...(body === undefined ? {} : { "content-type": "application/json" }), + }, + ...(body === undefined ? {} : { body }), + signal: AbortSignal.timeout(20_000), + }); + // The body is read as JSON and written back out, so an empty answer + // (a 204) stays empty and an error body keeps its own words for the + // caller. + const text = await (async () => { + try { + return JSON.stringify(await res.json()); + } catch { + return ""; + } + })(); + if (!res.ok) { + return { code: 1, stdout: "", stderr: text === "" ? `GitHub answered http ${res.status}` : text }; + } + return { code: 0, stdout: text, stderr: "" }; +} + +/** The edge's `run`: GitHub through REST, the queue token from its + * Worker secret, and everything else refused as the laptop's. */ +export function edgeRun(config: Config, secrets: DirectSecrets, fetchImpl: Fetch): Run { + return async (argv, opts) => { + const [bin, verb, ...rest] = argv; + if (bin === config.fleetBin && verb === "gh" && rest[0] === "api") { + return ghApi(rest.slice(1), opts?.stdin, secrets.githubToken, fetchImpl); + } + if (bin === config.fleetBin && verb === "secrets" && rest[0] === "get") { + const name = rest[1]; + if (name === config.queueTokenName && secrets.queueToken) { + return { code: 0, stdout: `${secrets.queueToken}\n`, stderr: "" }; + } + throw new OpError(502, `the edge has no secret named ${name ?? "?"}`); + } + throw new OpError(502, "needs the laptop"); + }; +} + +/** The laptop console's config, as the edge knows it: what the host + * reported, and nothing the edge cannot use left blank. The dashboard + * is null, so anything that reads it refuses rather than reaching + * somewhere it cannot. */ +export function directConfig(edge: EdgeConfig): Config { + return { + port: 0, + bind: "127.0.0.1", + owners: edge.owners, + certNames: edge.certNames, + issuers: edge.issuers, + repo: edge.repo, + queue: edge.queue, + queueDbUrl: edge.queueDbUrl, + queueTokenName: edge.queueTokenName, + fleetBin: "fleet", + unitPatterns: [], + protectedUnits: [], + auditFile: "", + dashboardUrl: null, + androidPackage: edge.androidPackage, + androidFingerprints: edge.androidFingerprints, + androidApk: "", + devicesFile: "", + edgeUrl: null, + edgeKeyFile: "", + edgeDoneFile: "", + decisionsFile: "", + promptLabel: edge.promptLabel, + needsRepos: edge.needsRepos, + }; +} + +export interface DirectOptions { + githubToken?: string; + queueToken?: string; + fetchImpl?: Fetch; +} + +/** The laptop's own classes, wired for the edge. */ +export function directClasses(edge: EdgeConfig, options: DirectOptions): { ops: Ops; work: Work } { + const config = directConfig(edge); + const fetchImpl = options.fetchImpl ?? (fetch as unknown as Fetch); + const ops = new Ops(config, edgeRun(config, options, fetchImpl), fetchImpl); + return { ops, work: new Work(ops) }; +} + +/** One section, read by the class that reads it on the laptop. */ +export async function directRead(section: string, ops: Ops, work: Work): Promise { + switch (section) { + case "board": + return work.board(); + case "prs": + return ops.prs(); + case "priorities": + return ops.priorities(); + case "asks": + return work.asks(); + default: + throw new Error(`not a section the edge reads itself: ${section}`); + } +} diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 89a47cd991..9d11d20285 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -17,8 +17,9 @@ // presents a sign-in token that verifies; the host is whoever signs with // the key the host itself published through its tunnel; a phone is // whoever holds a token this service issued. -import { type Action, ownActions } from "../../src/actions.ts"; +import { actions, type Action, ownActions } from "../../src/actions.ts"; import { AuthError, type Identity, identify } from "../../src/auth.ts"; +import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from "./direct.ts"; import { Devices, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { @@ -87,6 +88,10 @@ const AUDIT_KEPT = 300; const WATCHING_MS = 90_000; /** The host is reported silent after this long without a sync. */ export const SILENT_MS = 10 * 60_000; +/** The laptop is quiet long enough to bypass it for safe reads and writes. */ +const DIRECT_READ_AFTER_MS = 60_000; +/** How often the self-check may run again. */ +const SELF_CHECK_EVERY_MS = 60 * 60_000; const KEY_FETCH_EVERY_MS = 30_000; const STATIC: Record = { "app.js": "text/javascript; charset=utf-8", @@ -123,6 +128,14 @@ export interface EdgeOptions { now?: () => number; /** Reaches the sign-in issuer's keys and the push services. */ fetchImpl?: typeof fetch; + /** What the edge may do itself while the laptop is away: the switch, + * the two tokens, and the fetch the direct reads and writes use. */ + direct?: { + enabled: boolean; + githubToken?: string; + queueToken?: string; + fetchImpl?: typeof fetch; + }; /** Ask to be woken at a time: the check for a silent host. */ setAlarm?: (at: number) => Promise; } @@ -131,6 +144,12 @@ export class Edge { private kv: KV; private now: () => number; private fetchImpl: typeof fetch; + private direct?: EdgeOptions["direct"]; + /** When each section was last read directly, so a fresh read is not + * made more often than the section's own interval. */ + private directAt = new Map(); + /** The last self-check: one direct read of each kind, and how it went. */ + private selfCheckResult: { at: number; kinds: Record } | null = null; private setAlarm: (at: number) => Promise; private cfg: EdgeConfig | null | undefined; private mirrors = new Map(); @@ -156,6 +175,7 @@ export class Edge { this.kv = options.kv; this.now = options.now ?? Date.now; this.fetchImpl = options.fetchImpl ?? fetch; + this.direct = options.direct; this.setAlarm = options.setAlarm ?? (async () => {}); this.docs = new Docs( Object.fromEntries( @@ -305,6 +325,155 @@ export class Edge { } } + // ---- doing it here while the laptop is away -------------------------- + + /** The laptop has been quiet long enough to bypass it. */ + private directQuiet(): boolean { + return this.now() - (this.hostSeen ?? 0) >= DIRECT_READ_AFTER_MS; + } + + /** The switch is on and both tokens are here: the edge may act itself. + * The quiet gate is separate, so health can say the capability is + * ready even while the laptop is still reporting. */ + private directCapable(): boolean { + return this.direct?.enabled === true && Boolean(this.direct.githubToken) && Boolean(this.direct.queueToken); + } + + /** May act itself right now: capable, and the laptop known quiet. */ + private directReady(): boolean { + return this.directCapable() && this.directQuiet(); + } + + /** The laptop's own classes, wired for the edge. Null while the + * capability is not there. */ + private directClasses(cfg: EdgeConfig | null): ReturnType | null { + if (cfg === null || !this.directCapable()) return null; + return directClasses(cfg, { + githubToken: this.direct?.githubToken, + queueToken: this.direct?.queueToken, + fetchImpl: this.direct?.fetchImpl as never, + }); + } + + /** One direct read of a section, recorded in the mirror the documents + * are built from. A section is not read again within its own interval, + * and a failed read keeps the last good copy and says why. After an + * action of this side's own, the read is forced: the change must show + * at once, not when the interval runs out. */ + private async directReadSection(name: string, cfg: EdgeConfig | null, force = false): Promise { + const now = this.now(); + const last = this.directAt.get(name) ?? 0; + if (!force && now - last < (SECTIONS[name] ?? 0)) return; + this.directAt.set(name, now); + const direct = this.directClasses(cfg); + if (!direct) return; + try { + this.docs.record(name, await directRead(name, direct.ops, direct.work), now); + } catch (error) { + this.docs.recordFailure(name, error); + } + } + + /** The sections of one document that the edge reads itself, when it may. */ + private async directRefresh(doc: DocName): Promise { + const names = doc === "core" ? ["board", "asks"] : doc === "ops" ? ["prs", "priorities"] : []; + if (names.length === 0 || !this.directReady()) return; + const cfg = await this.config(); + for (const name of names) await this.directReadSection(name, cfg); + if (names.some((n) => WATCHED.includes(n))) { + await this.notifier.tick().catch(() => {}); + } + } + + /** The self-check: one direct read of each kind, run when the + * capability arrives and at most once an hour after, its result kept + * for health. It proves the path without taking the laptop down. */ + private async maybeSelfCheck(cfg: EdgeConfig | null): Promise { + const direct = this.directClasses(cfg); + if (!direct) return; + const now = this.now(); + const stored = (await this.kv.get("selfcheck")) as { at: number; kinds: Record } | undefined; + if (stored && now - stored.at < SELF_CHECK_EVERY_MS) { + this.selfCheckResult = stored; + return; + } + const kinds: Record = {}; + for (const name of DIRECT_READ_SECTIONS) { + try { + await directRead(name, direct.ops, direct.work); + kinds[name] = { ok: true }; + } catch (error) { + kinds[name] = { ok: false, error: (error as Error).message.slice(0, 200) }; + } + } + this.selfCheckResult = { at: now, kinds }; + await this.kv.put("selfcheck", this.selfCheckResult); + } + + /** The stand-in for the queue's enqueue in a prompt the edge files or + * answers itself: the issue already exists on GitHub, so only its + * queue task is left, held for the laptop's return as prompt.enqueue. + * The packet carries the issue's number; the text is the owner's own. */ + private enqueueRecorder( + args: Record, + by: string, + ): (packet: unknown) => Promise<{ code: number; stdout: string; stderr: string }> { + return async (packet) => { + const issue = Number( + (packet as { payload?: { issue?: { number?: unknown } } })?.payload?.issue?.number, + ); + if (!Number.isSafeInteger(issue) || issue <= 0) { + throw new Error("the prompt's issue could not be read from its packet"); + } + const at = new Date(this.now()).toISOString(); + const held = await this.heldList(); + held.push({ + id: crypto.randomUUID(), + kind: "prompt.enqueue", + args: { issue, text: String(args.text ?? ""), at }, + who: by, + at, + }); + await this.saveHeld(); + return { code: 0, stdout: "", stderr: "" }; + }; + } + + /** An action this side runs itself through the laptop's own classes, + * recorded before and after like own(). Only the sections it touched + * that the edge reads itself are read again at once. */ + private async directAct(kind: string, args: Record, by: string, via: string): Promise { + const cfg = await this.config(); + const direct = this.directClasses(cfg); + if (!direct) throw new Error("the edge cannot act itself right now"); + const table = actions(direct.ops, direct.work, this.push, this.phones.devices); + const action = table[kind]; + const base = { at: new Date(this.now()).toISOString(), who: by, via, action: kind, args: action.audit(args) }; + await this.audit({ ...base, phase: "start" }); + const entry = { id: crypto.randomUUID(), kind, at: base.at, by, note: "" }; + try { + let result: unknown; + if (kind === "ask.send") result = await direct.work.ask(args, this.enqueueRecorder(args, by)); + else if (kind === "ask.reply") result = await direct.work.askReply(args, this.enqueueRecorder(args, by)); + else result = await action.run(args); + await this.audit({ ...base, phase: "done", ok: true }); + await this.logAct({ ...entry, status: "done" }); + for (const name of action.touch) { + if ((DIRECT_READ_SECTIONS as readonly string[]).includes(name)) { + await this.directReadSection(name, cfg, true); + } + } + if (action.touch.some((n) => WATCHED.includes(n))) { + await this.notifier.tick().catch(() => {}); + } + return json({ ok: true, result }); + } catch (error) { + await this.audit({ ...base, phase: "done", ok: false, error: (error as Error).message }); + await this.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + throw error; + } + } + // ---- the host's report ------------------------------------------------- /** The host's public key, given by the stateless part after it asked @@ -498,10 +667,18 @@ export class Edge { // Public: nothing here says anything about the fleet. if (path === `${BASE}/health` && method === "GET") { await this.ready(); + // The self-check runs when the capability is there: one direct + // read of each kind, and how it went. Nothing here is a secret. + await this.maybeSelfCheck(cfg); return json({ ok: true, edge: true, configured: cfg !== null, + directEnabled: this.direct?.enabled === true, + githubTokenConfigured: Boolean(this.direct?.githubToken), + queueTokenConfigured: Boolean(this.direct?.queueToken), + directReady: this.directCapable(), + selfCheck: this.selfCheckResult, hostSeen: this.hostSeen || null, // Since this object last started: requests it answered as the // owner's, and requests it left to the host to judge. @@ -570,6 +747,9 @@ export class Edge { } if (seg.length === 2 && seg[0] === "doc" && DOC_NAMES.includes(seg[1] as DocName)) { this.lastDocAt = this.now(); + // A document the edge reads itself: refresh its sections + // directly first, when the laptop has gone quiet. + await this.directRefresh(seg[1] as DocName); const res = docResponse(req, await this.docs.doc(seg[1] as DocName)); // When the host last reported, beside the document rather than // in it: it changes with every report and the content does not. @@ -601,6 +781,13 @@ export class Edge { return json({ error: "args: expected an object" }, 400); } if (!Object.hasOwn(this.table, kind)) { + // One the edge does itself: while the laptop is known quiet it + // runs here, through the laptop's own classes, and is never + // sent to the laptop — so the laptop cannot do it a second + // time. Otherwise it is the host's to do, as before. + if ((DIRECT_ACTIONS as readonly string[]).includes(kind) && this.directReady()) { + return await this.directAct(kind, args as Record, by, who.via); + } // The host's to do. The stateless part relays it, and if the // host cannot be reached comes back to have it held. // It is named here, before it goes anywhere. If the host's answer diff --git a/pm-stack/console/edge/src/worker.ts b/pm-stack/console/edge/src/worker.ts index 934517fe6a..40dd447338 100644 --- a/pm-stack/console/edge/src/worker.ts +++ b/pm-stack/console/edge/src/worker.ts @@ -16,6 +16,12 @@ interface Env { ASSETS: { fetch(request: Request): Promise }; PUBLIC_HOST: string; VERSION?: string; + /** What the edge may do itself while the laptop is away. The tokens + * are Worker secrets, put there by scripts/expose.py --edge-direct; + * the flag is the explicit opt-in, off unless set to `on`. */ + GITHUB_TOKEN?: string; + QUEUE_TOKEN?: string; + EDGE_DIRECT?: string; /** Local development only: where the host is, when it is not simply * behind this hostname's route. Never set where this is deployed. */ HOST_ORIGIN?: string; @@ -35,6 +41,12 @@ export class PmEdge extends DurableObject { await ctx.storage.delete(key); }, }, + direct: { + enabled: env.EDGE_DIRECT === "on", + githubToken: env.GITHUB_TOKEN, + queueToken: env.QUEUE_TOKEN, + fetchImpl: fetch, + }, setAlarm: (at) => ctx.storage.setAlarm(at), }); } diff --git a/pm-stack/console/edge/wrangler.jsonc b/pm-stack/console/edge/wrangler.jsonc index 9465a33ecf..adf3a4aa02 100644 --- a/pm-stack/console/edge/wrangler.jsonc +++ b/pm-stack/console/edge/wrangler.jsonc @@ -28,8 +28,11 @@ }, // One object holds the state: the copy of what the host last // reported, what is held for it, notification subscriptions and keys, - // linked phones. No secrets are configured: every key it uses it made - // itself, or was published by the host. + // linked phones. Three secrets are optional, put there by + // scripts/expose.py --edge-direct (off by default): GITHUB_TOKEN and + // QUEUE_TOKEN, which let the Worker read and write GitHub and the + // queue store itself while the laptop is away, and EDGE_DIRECT, the + // explicit opt-in that must read `on` for either to be used. "durable_objects": { "bindings": [{ "name": "PM", "class_name": "PmEdge" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PmEdge"] }] } diff --git a/pm-stack/console/scripts/edge-demo.ts b/pm-stack/console/scripts/edge-demo.ts index ba74e751b8..2b91012c41 100644 --- a/pm-stack/console/scripts/edge-demo.ts +++ b/pm-stack/console/scripts/edge-demo.ts @@ -100,6 +100,10 @@ const link = new EdgeLink({ androidPackage: demoDeps.cfg.androidPackage, androidFingerprints: [], androidApp: false, + queueDbUrl: demoDeps.cfg.queueDbUrl, + queueTokenName: demoDeps.cfg.queueTokenName, + promptLabel: demoDeps.cfg.promptLabel, + needsRepos: demoDeps.cfg.needsRepos, }), run: heldRunner(demoDeps), fetchImpl: (async (url: string, init: RequestInit) => { diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index 85b3b943c1..61e7dd7d99 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -74,6 +74,10 @@ const link = new EdgeLink({ androidPackage: cfg.androidPackage, androidFingerprints: [], androidApp: false, + queueDbUrl: cfg.queueDbUrl, + queueTokenName: cfg.queueTokenName, + promptLabel: cfg.promptLabel, + needsRepos: cfg.needsRepos, }), run: heldRunner(deps), log: (line) => console.log(` host: ${line}`), diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 155b6376b4..00bc57c1db 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -32,6 +32,14 @@ happens only once the Worker answers its health check and says it is built for this hostname; until then, and after `--edge off`, the hostname goes straight to this host. +7. With `--edge-direct on`, the Worker also gets the two tokens it needs + to act itself while the laptop is away (the repository automation + token and the queue store token) and the explicit opt-in that lets it + use them. Off by default, remembered like `--edge`, and nothing is + uploaded on a run that does not change the choice. Turning it off + turns the opt-in off; the tokens stay on the Worker, inert without + it. The Worker says in /console/health whether the flag is on and + whether each token is there. The gate comes first and the routes last, so the origin is never reachable without sign-in in front of it. If the console does not come @@ -40,7 +48,8 @@ Every secret is read by name through `fleet secrets get` and stays in memory. Nothing printed is a secret. -Usage: expose.py [--check] [--edge on|off] [--host pm.security.cab] [--owner ADDRESS] +Usage: expose.py [--check] [--edge on|off] [--edge-direct on|off] + [--host pm.security.cab] [--owner ADDRESS] [--google-stdin] [--status] --owner whose sign-in is let in. Needed the first time; after that the console's environment file remembers it. The address @@ -56,14 +65,21 @@ nothing. --edge off take the hostname off the edge Worker; remembered by later runs (the timer's included) until --edge on. + --edge-direct on + let the edge Worker act itself while the laptop is away: + upload the GitHub and queue tokens and turn the opt-in + on; remembered by later runs until --edge-direct off. + Off by default. """ from __future__ import annotations import argparse import json +import os import pathlib import re +import shutil import subprocess import sys import time @@ -95,6 +111,12 @@ WORKER = "pm-console-edge" GOOGLE_ID = "google.access-sso.client-id" GOOGLE_SECRET = "google.access-sso.client-secret" +# Bitwarden names for the two tokens the edge Worker acts with while the +# laptop is away: the repository automation token (the same name the +# queue-transport-alert deploy uses), and the queue store token, whose +# name the console's environment file may override. +GITHUB_TOKEN_SECRET = "github.developing-today-code-automation" +QUEUE_TOKEN_DEFAULT = "turso.fleet-queue-rw-token" def secret(name: str) -> str: @@ -215,6 +237,87 @@ def edge_choice(state: pathlib.Path, choice: str | None, keep: bool) -> bool: return not marker.exists() or marker.read_text().strip() != "off" +def direct_choice(state: pathlib.Path, choice: str | None, keep: bool) -> bool: + """Whether the edge Worker may act itself while the laptop is away. + A choice given now decides, and with `keep` it is written to a file, + so a timer's run keeps what was last asked for. With no choice given + the file decides, and with no file the answer is no: off by default.""" + marker = state / "edge-direct" + if choice is not None: + if keep: + state.mkdir(parents=True, exist_ok=True, mode=0o700) + marker.write_text(choice + "\n") + return choice != "off" + return marker.exists() and marker.read_text().strip() == "on" + + +def ensure_edge_direct( + cf: Cloudflare, + account: str, + env: pathlib.Path, + choice: str | None, + check: bool, +) -> None: + """Upload the two tokens the edge Worker acts with, and its opt-in, + or turn the opt-in off. Nothing is uploaded on a run that does not + change the choice, so the timer's runs leave the secrets alone. + A secret is read by name through `fleet secrets get` and piped to + `wrangler secret put`; it is never printed or written to a file.""" + state = env.parent + # Read what is remembered before the choice overwrites it: only a + # change uploads anything. + marker = state / "edge-direct" + current = marker.exists() and marker.read_text().strip() == "on" + wanted = direct_choice(state, choice, keep=not check) + if wanted == current: + return + if wanted: + what = "edge direct: upload the GitHub and queue tokens and turn direct actions on" + else: + what = "edge direct: turn direct actions off" + cf.changes.append(what) + if check: + return + edge_dir = pathlib.Path(__file__).resolve().parent.parent / "edge" + wrangler = shutil.which("wrangler") or str(edge_dir / "node_modules" / ".bin" / "wrangler") + if not wrangler or not pathlib.Path(wrangler).exists(): + raise SystemExit( + "wrangler is not installed here; run `npm ci` in pm-stack/console/edge, then rerun" + ) + envs = {**os.environ, "CLOUDFLARE_API_TOKEN": cf.token, "CLOUDFLARE_ACCOUNT_ID": account} + + def put(name: str, value: str) -> None: + done = subprocess.run( + [wrangler, "secret", "put", name], + input=value, + capture_output=True, + text=True, + cwd=edge_dir, + env=envs, + check=False, + ) + if done.returncode != 0: + raise SystemExit( + f"wrangler secret put {name} failed ({(done.stderr or '').strip()[:200]}); " + "the edge Worker was not given its secrets" + ) + + if wanted: + github = secret(GITHUB_TOKEN_SECRET) + queue_name = env_values(env).get("PM_CONSOLE_QUEUE_TOKEN_NAME") or QUEUE_TOKEN_DEFAULT + queue = secret(queue_name) + if not github: + raise SystemExit(f"secret {GITHUB_TOKEN_SECRET} is not readable here") + if not queue: + raise SystemExit(f"secret {queue_name} is not readable here") + put("GITHUB_TOKEN", github) + put("QUEUE_TOKEN", queue) + put("EDGE_DIRECT", "on") + else: + # The tokens stay, inert without the opt-in; only the flag moves. + put("EDGE_DIRECT", "off") + + def worker_ready(cf: Cloudflare, account: str, host: str) -> bool: """True when the edge Worker is deployed, answers its health check as the edge, and is built for this hostname (it treats any other as @@ -605,6 +708,13 @@ def main() -> int: help="send the hostname through the edge Worker, or straight to this host; " "the choice is kept for later runs (default: on, once the Worker answers)", ) + parser.add_argument( + "--edge-direct", + choices=["on", "off"], + help="let the edge Worker act itself while the laptop is away: upload " + "its GitHub and queue tokens and turn the opt-in on; the choice is " + "kept for later runs (default: off)", + ) args = parser.parse_args() env = pathlib.Path.home() / ".local/state/pm-console/.env" # Refused here, before anything is asked of Cloudflare. @@ -700,6 +810,9 @@ def main() -> int: # Last: by now the host is up, knows where the edge is, and is # reachable behind the hostname the Worker will sit on. ensure_edge_route(cf, zone, args.host, edge) + # The direct switch is independent of the route: it only decides + # whether the Worker already deployed may act itself. + ensure_edge_direct(cf, account, env, args.edge_direct, args.check) else: raise SystemExit( "the Access application has no audience tag; not routing the hostname" diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index ed9f955dab..0957f2d7f6 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -9,7 +9,7 @@ import type { Docs } from "./docs.ts"; import { OpError } from "./errors.ts"; import type { Ops } from "./ops.ts"; import type { Push } from "./push.ts"; -import type { Work } from "./work.ts"; +import { promptPacket, type Work } from "./work.ts"; type Args = Record; export interface Action { @@ -69,6 +69,27 @@ export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): R "ask.send": { run: (a) => work.ask(a), touch: ["asks", "board"], audit: () => ({}) }, "ask.reply": { run: (a) => work.askReply(a), touch: ["asks", "board"], audit: ids("issue") }, "ask.close": { run: (a) => work.askClose(a), touch: ["asks"], audit: ids("issue") }, + // The second half of a prompt the edge filed while the laptop was + // away: the issue already exists, so only its queue task is left. + // The edge holds this, never the whole ask, so the issue is never + // filed twice. The arguments are checked again here: the edge is + // trusted for the held actions it sends, and a bad one is refused + // rather than enqueued. + "prompt.enqueue": { + run: async (a) => { + const issue = Number(a.issue); + if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number"); + if (typeof a.text !== "string" || a.text.trim() === "" || a.text.length > 8000) + throw new OpError(400, "text: required, at most 8000 characters"); + if (typeof a.at !== "string" || a.at === "") throw new OpError(400, "at: required"); + const queued = await ops.enqueue( + promptPacket(ops.cfg.repo, ops.cfg.queue, issue, a.text, a.at), + ); + return { issue, queued: queued.code === 0 }; + }, + touch: ["board"], + audit: ids("issue"), + }, "question.answer": { run: (a) => work.answer(a), touch: ["questions", "questionCount"], diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index d74c154c28..45feaaa82d 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -116,6 +116,27 @@ export class Docs { await Promise.all(names.map((n) => this.refresh(n))); } + /** Record a section read by another trusted source, such as the edge + * reading GitHub or the queue store while the laptop is away. */ + record(name: string, data: unknown, at = this.now()): void { + const s = this.sections.get(name); + if (!s) return; + s.data = data; + s.at = at; + s.goodAt = at; + s.ok = true; + s.error = null; + } + + /** Keep the last good value, but say that a fresh read failed. */ + recordFailure(name: string, error: unknown): void { + const s = this.sections.get(name); + if (!s) return; + s.at = this.now(); + s.ok = false; + s.error = (error as Error).message.slice(0, 300); + } + private stale(s: Section): boolean { return this.now() - s.at > s.ttlMs; } diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 0d721ca335..cbe1be1479 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -20,7 +20,11 @@ import type { Issuer } from "./config.ts"; /** What the edge needs to know to recognise the owner. It comes from the - * host in every sync, so there is one place it is set. */ + * host in every sync, so there is one place it is set. The last four + * fields are what the edge needs to read and write by itself while the + * laptop is away: where the queue store is and which token opens it, how + * the owner's prompts are marked, and which repositories hold his + * needs-me items. */ export interface EdgeConfig { owners: string[]; certNames: string[]; @@ -31,6 +35,10 @@ export interface EdgeConfig { androidFingerprints: string[]; /** Whether the host has a signed Android build to hand out. */ androidApp: boolean; + queueDbUrl: string; + queueTokenName: string; + promptLabel: string; + needsRepos: string[]; } export interface SyncSection { @@ -83,7 +91,9 @@ export interface SyncResponse { /** Actions that may be done late, when the host is back. The rest act on * something that may have changed by then (a merge, a unit, a task's - * state), so they are refused while the host cannot be reached. */ + * state), so they are refused while the host cannot be reached. + * `prompt.enqueue` is the second half of a prompt the edge filed itself: + * the issue already exists, so only the queue task is left to do. */ export const HOLDABLE = new Set([ "ask.send", "ask.reply", @@ -97,6 +107,7 @@ export const HOLDABLE = new Set([ "issue.rank", "task.move", "message.send", + "prompt.enqueue", ]); /** A held action older than this is dropped, and said to have been. */ export const HELD_FOR_MS = 24 * 60 * 60_000; @@ -189,6 +200,10 @@ export function edgeConfig(value: unknown): EdgeConfig | null { }); } if (typeof v.repo !== "string" || typeof v.queue !== "string" || typeof v.androidPackage !== "string") return null; + if (typeof v.queueDbUrl !== "string" || !/^https:\/\//.test(v.queueDbUrl)) return null; + if (typeof v.queueTokenName !== "string" || v.queueTokenName === "") return null; + if (typeof v.promptLabel !== "string" || v.promptLabel === "") return null; + if (!strings(v.needsRepos)) return null; return { owners: v.owners.map((o) => o.toLowerCase()), certNames: v.certNames, @@ -198,5 +213,9 @@ export function edgeConfig(value: unknown): EdgeConfig | null { androidPackage: v.androidPackage, androidFingerprints: v.androidFingerprints, androidApp: v.androidApp === true, + queueDbUrl: v.queueDbUrl, + queueTokenName: v.queueTokenName, + promptLabel: v.promptLabel, + needsRepos: v.needsRepos, }; } diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 3f7978a5ff..f0e85a68f2 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -4,9 +4,12 @@ // services through `systemctl --user`. Nothing here builds a shell // command line: each call is an argument vector, and text a person // typed travels on stdin or as a single argument. -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; +// +// The edge Worker imports this module and runs Ops with stand-ins for +// `run` and `fetch`, so nothing this module needs at load time may come +// from the filesystem: node:fs is imported lazily inside enqueue(), the +// one method that touches the disk, and the expose script's path is +// resolved inside expose(). import type { Config } from "./config.ts"; import { OpError } from "./errors.ts"; @@ -164,9 +167,6 @@ function id(value: unknown, name: string): number { return Number(s); } -/** scripts/expose.py, beside this package's sources. */ -const EXPOSE = join(import.meta.dir, "..", "scripts", "expose.py"); - export class Ops { private queueToken: string | null = null; @@ -398,6 +398,11 @@ export class Ops { /** Hand one packet to the queue. `fleet queue enqueue` reads a packet * file, not stdin, so the packet lives in a private file for the call. */ async enqueue(packet: unknown): Promise { + // The filesystem is the laptop's only: this import is lazy so the + // edge Worker, which never calls this, can import this module. + const { mkdtempSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); const dir = mkdtempSync(join(tmpdir(), "pm-console-")); const file = join(dir, "packet.json"); try { @@ -479,8 +484,12 @@ export class Ops { /** The script that keeps the public address as declared. It is the one * place that talks to the sign-in gate, so sign-in is read and changed * through it. */ - private expose(args: string[], stdin?: string) { - return this.run(["python3", EXPOSE, ...args], { stdin, timeoutMs: 120_000 }); + private async expose(args: string[], stdin?: string) { + // Resolved here, not at load: the edge imports this module and never + // calls this, and import.meta.dir is the laptop's. + const { join } = await import("node:path"); + const script = join(import.meta.dir, "..", "scripts", "expose.py"); + return this.run(["python3", script, ...args], { stdin, timeoutMs: 120_000 }); } /** Which sign-in methods are on, and what Google has to be told to diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 0ff23b34e3..8ae9a814ca 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -583,6 +583,10 @@ if (import.meta.main) { androidPackage: cfg.androidPackage, androidFingerprints: cfg.androidFingerprints, androidApp: await Bun.file(cfg.androidApk).exists(), + queueDbUrl: cfg.queueDbUrl, + queueTokenName: cfg.queueTokenName, + promptLabel: cfg.promptLabel, + needsRepos: cfg.needsRepos, }), run: heldRunner(deps), }) diff --git a/pm-stack/console/src/work.ts b/pm-stack/console/src/work.ts index 2d13b0a651..18ffcd9e1e 100644 --- a/pm-stack/console/src/work.ts +++ b/pm-stack/console/src/work.ts @@ -5,8 +5,7 @@ // Every write is something the fleet already understands: an answer to a // decision set through the dashboard's own endpoint, an issue and a // queue task, a comment, a label. -import { readFile } from "node:fs/promises"; -import { OpError, type Ops, PRIORITY_SCALE, type Row } from "./ops.ts"; +import { OpError, type Ops, PRIORITY_SCALE, type Row, type RunResult } from "./ops.ts"; const P = "CASE WHEN json_valid(payload) THEN payload ELSE '{}' END"; const G = "CASE WHEN json_valid(progress) THEN progress ELSE '{}' END"; @@ -132,7 +131,10 @@ export class Work { constructor( private ops: Ops, - private read: (path: string) => Promise = (path) => readFile(path, "utf8"), + // The decisions file lives on the laptop: the import is lazy so the + // edge Worker, which never reads it, can import this module. + private read: (path: string) => Promise = async (path) => + (await import("node:fs/promises")).readFile(path, "utf8"), private clock: () => Date = () => new Date(), ) {} @@ -525,8 +527,14 @@ export class Work { this.labelReady = true; } - /** Turn the owner's words into an issue and a top-band task, in one pass. */ - async ask(args: Record) { + /** Turn the owner's words into an issue and a top-band task, in one pass. + * `enqueue` is a stand-in point: the edge files the issue itself and + * holds the enqueue for the laptop's return instead of running the + * fleet binary, which is not there. */ + async ask( + args: Record, + enqueue: (packet: unknown) => Promise = (p) => this.ops.enqueue(p), + ) { const text = words(args.text, "text", 8000); await this.ensureLabel(); const first = text.split("\n")[0].trim(); @@ -535,7 +543,7 @@ export class Work { body: `${text}\n\n---\n${ASK_NOTE}\n${OWNER_PROMPT_MARK}`, labels: [this.ops.cfg.promptLabel, "expedite"], })) as { number: number; html_url: string }; - const queued = await this.ops.enqueue( + const queued = await enqueue( promptPacket(this.repo, this.ops.cfg.queue, made.number, text, this.clock().toISOString()), ); return { @@ -548,8 +556,13 @@ export class Work { }; } - /** The owner answers back on one of his prompts; the fleet is woken for it. */ - async askReply(args: Record) { + /** The owner answers back on one of his prompts; the fleet is woken for it. + * `enqueue` is a stand-in point, as in ask(): the edge posts the reply + * itself and holds the enqueue for the laptop's return. */ + async askReply( + args: Record, + enqueue: (packet: unknown) => Promise = (p) => this.ops.enqueue(p), + ) { const issue = Number(args.issue); if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number"); const text = words(args.text, "text", 8000); @@ -566,7 +579,7 @@ export class Work { if (current.state === "closed") { await this.ops.gh(["-X", "PATCH", `repos/${this.repo}/issues/${issue}`], { state: "open" }); } - const queued = await this.ops.enqueue( + const queued = await enqueue( promptPacket(this.repo, this.ops.cfg.queue, issue, text, this.clock().toISOString()), ); return { issue, queued: queued.code === 0 }; diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts new file mode 100644 index 0000000000..10723dcc41 --- /dev/null +++ b/pm-stack/console/test/direct.test.ts @@ -0,0 +1,176 @@ +// The edge's stand-ins for the laptop console's classes: `fleet gh api` +// argv become GitHub REST calls, the queue token comes from its Worker +// secret, and every other fleet verb is refused as the laptop's. +// +// Oracles: the exact request the stand-in fetch receives (method, URL, +// headers, body), and the exact RunResult the classes see back. +import { describe, expect, test } from "bun:test"; +import { readConfig } from "../src/config.ts"; +import { directClasses, directConfig, directRead, edgeRun } from "../edge/src/direct.ts"; +import type { Fetch } from "../src/ops.ts"; +import type { EdgeConfig } from "../src/edge-proto.ts"; + +const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: "owner@example.com" }); +const edgeConfig: EdgeConfig = { + owners: ["owner@example.com"], + certNames: [], + issuers: [], + repo: "developing-today/code", + queue: "repo-health-code-pilot", + androidPackage: "today.developing.pmconsole", + androidFingerprints: [], + androidApp: false, + queueDbUrl: cfg.queueDbUrl, + queueTokenName: cfg.queueTokenName, + promptLabel: cfg.promptLabel, + needsRepos: cfg.needsRepos, +}; + +function harness() { + const calls: { url: string; init: { method: string; headers: Record; body?: string } }[] = []; + const answer: { ok: boolean; status: number; body: unknown } = { + ok: true, + status: 200, + body: [{ number: 1 }], + }; + const fetchImpl = (async (url: string, init: { method: string; headers: Record; body?: string }) => { + calls.push({ url, init }); + return { ok: answer.ok, status: answer.status, json: async () => answer.body }; + }) as unknown as Fetch; + const run = edgeRun(directConfig(edgeConfig), { githubToken: "gh-test", queueToken: "queue-test" }, fetchImpl); + return { calls, answer, fetchImpl, run }; +} + +describe("the edge's run: GitHub through REST", () => { + test("a GET with -f pairs becomes a query string, with the token on it", async () => { + const h = harness(); + const out = await h.run(["fleet", "gh", "api", "search/issues", "-f", "q=repo:x is:open", "-f", "per_page=100", "-f", "page=2"]); + expect(h.calls).toHaveLength(1); + expect(h.calls[0].url).toBe( + "https://api.github.com/search/issues?q=repo%3Ax+is%3Aopen&per_page=100&page=2", + ); + expect(h.calls[0].init.method).toBe("GET"); + expect(h.calls[0].init.headers.authorization).toBe("Bearer gh-test"); + expect(h.calls[0].init.headers["x-github-api-version"]).toBe("2022-11-28"); + expect(out).toEqual({ code: 0, stdout: "[{\"number\":1}]", stderr: "" }); + }); + + test("a path that already carries a query keeps it, and -f pairs join it", async () => { + const h = harness(); + await h.run(["fleet", "gh", "api", "repos/x/issues?labels=a&state=all", "-f", "per_page=20"]); + expect(h.calls[0].url).toBe("https://api.github.com/repos/x/issues?labels=a&state=all&per_page=20"); + }); + + test("a POST with --input sends the stdin JSON as the body", async () => { + const h = harness(); + await h.run(["fleet", "gh", "api", "-X", "POST", "repos/x/issues/7/comments", "--input", "-"], { + stdin: JSON.stringify({ body: "hello" }), + }); + expect(h.calls[0].init.method).toBe("POST"); + expect(h.calls[0].init.body).toBe(JSON.stringify({ body: "hello" })); + }); + + test("a PUT with -f sends the fields as a JSON body", async () => { + const h = harness(); + await h.run(["fleet", "gh", "api", "-X", "PUT", "repos/x/pulls/3/merge", "-f", "merge_method=merge"]); + expect(h.calls[0].init.method).toBe("PUT"); + expect(h.calls[0].init.body).toBe(JSON.stringify({ merge_method: "merge" })); + }); + + test("a DELETE sends no body, and an empty answer stays empty", async () => { + const h = harness(); + h.answer.body = null; + const out = await h.run(["fleet", "gh", "api", "-X", "DELETE", "repos/x/issues/7/labels/now"]); + expect(h.calls[0].init.method).toBe("DELETE"); + expect(h.calls[0].init.body).toBeUndefined(); + expect(out).toEqual({ code: 0, stdout: "null", stderr: "" }); + }); + + test("a failed call answers non-zero with the body's own words, so already_exists is found", async () => { + const h = harness(); + h.answer.ok = false; + h.answer.status = 422; + h.answer.body = { message: "Validation Failed", errors: [{ code: "already_exists", field: "name" }] }; + const out = await h.run(["fleet", "gh", "api", "-X", "POST", "repos/x/labels", "--input", "-"], { + stdin: "{}", + }); + expect(out.code).toBe(1); + expect(out.stdout).toBe(""); + expect(out.stderr).toContain("already_exists"); + }); + + test("without a GitHub token the call is refused before it is made", async () => { + const h = harness(); + const noToken = edgeRun( + directConfig(edgeConfig), + { queueToken: "queue-test" }, + h.fetchImpl, + ); + await expect(noToken(["fleet", "gh", "api", "repos/x/pulls"])).rejects.toThrow(/no GitHub token/); + expect(h.calls).toHaveLength(0); + }); +}); + +describe("the edge's run: secrets and the laptop's verbs", () => { + test("the queue token is answered by the name the config gives it", async () => { + const h = harness(); + const out = await h.run(["fleet", "secrets", "get", "turso.fleet-queue-rw-token"]); + expect(out).toEqual({ code: 0, stdout: "queue-test\n", stderr: "" }); + }); + + test("any other secret name is refused, and the value is never the answer to a wrong name", async () => { + const h = harness(); + await expect(h.run(["fleet", "secrets", "get", "something.else"])).rejects.toThrow(/no secret named/); + }); + + test("the queue verb, the bridge and systemctl are the laptop's", async () => { + const h = harness(); + for (const argv of [ + ["fleet", "queue", "enqueue", "packet.json", "--queue", "repo-health-code-pilot"], + ["fleet", "bridge", "agents"], + ["systemctl", "--user", "restart", "pm-console.service"], + ["python3", "scripts/expose.py", "--status"], + ]) { + await expect(h.run(argv)).rejects.toThrow(/needs the laptop/); + } + expect(h.calls).toHaveLength(0); + }); +}); + +describe("the direct classes", () => { + test("the config the edge builds carries what the classes need and nothing it cannot use", () => { + const config = directConfig(edgeConfig); + expect(config.repo).toBe("developing-today/code"); + expect(config.queue).toBe("repo-health-code-pilot"); + expect(config.queueDbUrl).toBe(edgeConfig.queueDbUrl); + expect(config.queueTokenName).toBe(edgeConfig.queueTokenName); + expect(config.promptLabel).toBe(edgeConfig.promptLabel); + expect(config.needsRepos).toEqual(edgeConfig.needsRepos); + expect(config.dashboardUrl).toBeNull(); + }); + + test("each direct section is read by the class that reads it on the laptop, and nothing else is", async () => { + const seen: string[] = []; + const ops = { prs: async () => (seen.push("prs"), [] as unknown[]), priorities: async () => (seen.push("priorities"), {}) }; + const work = { board: async () => (seen.push("board"), {}), asks: async () => (seen.push("asks"), []) }; + for (const section of ["board", "prs", "priorities", "asks"]) { + await directRead(section, ops as never, work as never); + } + expect(seen).toEqual(["board", "prs", "priorities", "asks"]); + await expect(directRead("sessions", ops as never, work as never)).rejects.toThrow(/not a section the edge reads/); + }); + + test("the classes run unchanged on the stand-ins: the queue store is reached by fetch", async () => { + const h = harness(); + const { ops } = directClasses(edgeConfig, { + githubToken: "gh-test", + queueToken: "queue-test", + fetchImpl: h.fetchImpl, + }); + h.answer.body = { results: [{ type: "ok", response: { result: { cols: [{ name: "n" }], rows: [[{ value: 3 }]] } } }] }; + const rows = await ops.sql("SELECT count(*) AS n FROM tasks WHERE queue = ?", ["repo-health-code-pilot"]); + expect(rows).toEqual([{ n: 3 }]); + expect(h.calls[0].url).toBe(`${cfg.queueDbUrl}/v2/pipeline`); + expect(h.calls[0].init.headers.Authorization).toBe("Bearer queue-test"); + }); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index cc9428d307..8754227f71 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -51,10 +51,12 @@ const SECTION_NAMES = [ "more", ]; -async function setup() { +async function setup(options: { direct?: boolean } = {}) { const now = { t: START }; const clock = () => now.t; const access = await signer("k1"); + const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: OWNER }); + cfg.issuers = [ISSUER]; const pushes: { url: string; body: Uint8Array; authorization: string }[] = []; const pushFailures = { remaining: 0 }; const outward = async (url: string | URL | Request, init?: { body?: unknown; headers?: Record }) => { @@ -71,6 +73,301 @@ async function setup() { throw new Error(`unexpected fetch ${u}`); }; + // ---- the outside world, as the edge reaches it directly -------------- + // GitHub and the queue store, standing in for the real ones: the edge's + // direct reads and writes go through these, and only these. The data + // here is newer than the host's last report, as it would be after the + // laptop has been away for a while. + const githubCalls: { method: string; url: string; body?: string }[] = []; + const queueCalls: { sql: string; args: (string | number)[] }[] = []; + const ghIssues: Record< + number, + { number: number; title: string; body: string; html_url: string; state: string; created_at: string; updated_at: string; comments: number } + > = { + 201: { + number: 201, + title: "Owner: Do the docs", + body: "Do the docs\n\n---\nAn instruction from the owner.", + html_url: "https://github.com/developing-today/code/issues/201", + state: "open", + created_at: "2026-11-22T11:00:00Z", + updated_at: "2026-11-22T12:31:00Z", + comments: 1, + }, + 202: { + number: 202, + title: "Owner: Check the queue", + body: "Check the queue", + html_url: "https://github.com/developing-today/code/issues/202", + state: "open", + created_at: "2026-11-22T11:30:00Z", + updated_at: "2026-11-22T12:32:00Z", + comments: 0, + }, + }; + const ghComments: Record = { + 201: [{ body: "Done: the docs are updated.", created_at: "2026-11-22T12:31:00Z", user: { type: "User" } }], + }; + const ghLabels: Record = { 201: ["owner/prompt"], 202: ["owner/prompt"], 301: ["now"] }; + const ghLabelNames = new Set(["owner/prompt"]); + const ghPrs = [ + { + number: 55, + title: "Fresh PR", + draft: false, + html_url: "https://github.com/developing-today/code/pull/55", + created_at: "2026-11-22T12:30:00Z", + user: { login: "worker" }, + head: { ref: "queue/55" }, + }, + ]; + const ghSearch = [ + { + number: 301, + title: "Ranked fresh", + html_url: "https://github.com/developing-today/code/issues/301", + updated_at: "2026-11-22T12:31:00Z", + comments: 2, + labels: [{ name: "now" }], + }, + ]; + let ghNextIssue = 500; + const queueTasks: { + id: number; + title: string; + priority: number; + status: string; + attempts: number; + claimed: string | null; + lease: string | null; + created: string; + worker: string | null; + lane: string | null; + model: string | null; + kind: string | null; + issue: number | null; + pr: number | null; + step: string | null; + goal: string | null; + }[] = [ + { + id: 21047, + title: "Owner prompt developing-today/code#201: Do the docs", + priority: 10, + status: "claimed", + attempts: 1, + claimed: "2026-11-22T12:00:00", + lease: "2026-11-22T12:45:00", + created: "2026-11-22T11:00:00", + worker: "xaltha", + lane: null, + model: "muse", + kind: "triage", + issue: 201, + pr: null, + step: "reading the issue", + goal: "Carry out the owner's instruction", + }, + { + id: 21048, + title: "Next task", + priority: 20, + status: "queued", + attempts: 0, + claimed: null, + lease: null, + created: "2026-11-22T11:30:00", + worker: null, + lane: null, + model: null, + kind: "triage", + issue: 301, + pr: null, + step: null, + goal: "Triage", + }, + { + id: 21049, + title: "Blocked task", + priority: 30, + status: "blocked", + attempts: 2, + claimed: null, + lease: null, + created: "2026-11-22T10:00:00", + worker: null, + lane: null, + model: null, + kind: "triage", + issue: null, + pr: null, + step: null, + goal: null, + }, + ]; + const TASK_COLS = ["id", "title", "priority", "status", "attempts", "claimed", "lease", "created", "worker", "lane", "model", "kind", "issue", "pr", "step", "goal"]; + const taskRow = (t: (typeof queueTasks)[number]) => + TASK_COLS.map((c) => ({ value: (t as Record)[c] ?? null })); + const queueAnswer = (sql: string, args: (string | number)[]) => { + const cols = (names: string[]) => names.map((name) => ({ name })); + const rows = (rs: { value: string | number | null }[][]) => rs; + if (sql.includes("count(*) AS n") && sql.includes("GROUP BY status")) { + const counts = new Map(); + for (const t of queueTasks) counts.set(t.status, (counts.get(t.status) ?? 0) + 1); + return { + cols: cols(["status", "n"]), + rows: rows([...counts.entries()].map(([status, n]) => [{ value: status }, { value: n }])), + }; + } + // The single-row reads first: they also carry a status clause. + if (sql.startsWith("SELECT priority FROM tasks")) { + const found = queueTasks.find((t) => t.id === Number(args[0]) && t.status === "queued"); + return { cols: cols(["priority"]), rows: rows(found ? [[{ value: found.priority }]] : []) }; + } + if (sql.startsWith("UPDATE tasks SET priority")) { + const found = queueTasks.find((t) => t.id === Number(args[1]) && t.status === "queued"); + if (found) found.priority = Number(args[0]); + return { cols: cols([]), rows: [], affected_row_count: found ? 1 : 0 }; + } + if (sql.includes("status = 'claimed'")) { + return { cols: cols(TASK_COLS), rows: rows(queueTasks.filter((t) => t.status === "claimed").map(taskRow)) }; + } + if (sql.includes("status = 'queued'")) { + return { cols: cols(TASK_COLS), rows: rows(queueTasks.filter((t) => t.status === "queued").map(taskRow)) }; + } + if (sql.includes("status = 'blocked'")) { + return { + cols: cols(["why", "n"]), + rows: rows([[{ value: "waiting on the owner" }, { value: queueTasks.filter((t) => t.status === "blocked").length }]]), + }; + } + if (sql.includes("dedupe_key IN")) { + const keys = args.slice(1) as string[]; + return { + cols: cols(["dedupe_key", "status", "worker"]), + rows: rows( + queueTasks + .filter((t) => t.issue !== null && keys.includes(`repo-health:v1:triage:${cfg.repo}:issue:${t.issue}`)) + .map((t) => [ + { value: `repo-health:v1:triage:${cfg.repo}:issue:${t.issue}` }, + { value: t.status }, + { value: t.worker }, + ]), + ), + }; + } + throw new Error(`unexpected queue SQL: ${sql}`); + }; + const githubAnswer = (method: string, url: string, body?: string) => { + const u = new URL(url); + const path = u.pathname.replace(/^\/repos\/developing-today\/code\//, ""); + const ok = (data: unknown, status = 200) => ({ ok: true, status, json: async () => data }); + const fail = (status: number, data: unknown) => ({ ok: false, status, json: async () => data }); + if (method === "GET" && path === "pulls") return ok(ghPrs); + if (method === "GET" && u.pathname === "/search/issues") return ok({ items: ghSearch, total_count: ghSearch.length }); + if (method === "GET" && path === "issues") { + return ok( + Object.values(ghIssues) + .sort((a, b) => b.updated_at.localeCompare(a.updated_at)) + .map((i) => ({ ...i, pull_request: undefined })), + ); + } + const issueMatch = /^issues\/(\d+)$/.exec(path); + if (method === "GET" && issueMatch) { + const n = Number(issueMatch[1]); + return ok({ number: n, state: ghIssues[n]?.state ?? "open", labels: (ghLabels[n] ?? []).map((name) => ({ name })) }); + } + const commentsMatch = /^issues\/(\d+)\/comments$/.exec(path); + if (method === "GET" && commentsMatch) return ok(ghComments[Number(commentsMatch[1])] ?? []); + if (method === "POST" && commentsMatch) { + const n = Number(commentsMatch[1]); + const parsed = JSON.parse(body ?? "{}") as { body?: string }; + (ghComments[n] ??= []).push({ + body: parsed.body ?? "", + created_at: new Date(now.t).toISOString(), + user: { type: "User" }, + }); + if (ghIssues[n]) { + ghIssues[n].comments = (ghComments[n] ?? []).length; + ghIssues[n].updated_at = new Date(now.t).toISOString(); + } + return ok({ html_url: `https://github.com/developing-today/code/issues/${n}#issuecomment-1` }, 201); + } + if (method === "POST" && path === "issues") { + const parsed = JSON.parse(body ?? "{}") as { title?: string; body?: string; labels?: string[] }; + const n = ghNextIssue++; + ghIssues[n] = { + number: n, + title: parsed.title ?? "", + body: parsed.body ?? "", + html_url: `https://github.com/developing-today/code/issues/${n}`, + state: "open", + created_at: new Date(now.t).toISOString(), + updated_at: new Date(now.t).toISOString(), + comments: 0, + }; + ghLabels[n] = parsed.labels ?? []; + return ok({ number: n, title: parsed.title, html_url: ghIssues[n].html_url }, 201); + } + if (method === "PATCH" && issueMatch) { + const n = Number(issueMatch[1]); + const parsed = JSON.parse(body ?? "{}") as { state?: string }; + if (parsed.state) ghIssues[n].state = parsed.state; + ghIssues[n].updated_at = new Date(now.t).toISOString(); + return ok({ number: n, state: ghIssues[n].state }); + } + const labelsMatch = /^issues\/(\d+)\/labels$/.exec(path); + if (method === "POST" && labelsMatch) { + const n = Number(labelsMatch[1]); + const parsed = JSON.parse(body ?? "{}") as { labels?: string[] }; + for (const label of parsed.labels ?? []) if (!ghLabels[n].includes(label)) ghLabels[n].push(label); + return ok(ghLabels[n].map((name) => ({ name })), 201); + } + const labelMatch = /^issues\/(\d+)\/labels\/(.+)$/.exec(path); + if (method === "DELETE" && labelMatch) { + const n = Number(labelMatch[1]); + ghLabels[n] = ghLabels[n].filter((l) => l !== decodeURIComponent(labelMatch[2])); + return ok({}); + } + if (method === "POST" && path === "labels") { + const parsed = JSON.parse(body ?? "{}") as { name?: string }; + if (parsed.name && ghLabelNames.has(parsed.name)) { + return fail(422, { message: "Validation Failed", errors: [{ resource: "Label", code: "already_exists", field: "name" }] }); + } + if (parsed.name) ghLabelNames.add(parsed.name); + return ok({ name: parsed.name }, 201); + } + throw new Error(`unexpected GitHub call ${method} ${url}`); + }; + const directFetch = (async ( + url: string, + init: { method?: string; headers?: Record; body?: string }, + ) => { + const u = String(url); + const method = init?.method ?? "GET"; + if (u.startsWith("https://api.github.com/")) { + githubCalls.push({ method, url: u, body: init?.body }); + return githubAnswer(method, u, init?.body); + } + if (u === `${cfg.queueDbUrl}/v2/pipeline`) { + const parsed = JSON.parse(init?.body ?? "{}") as { + requests?: { stmt?: { sql: string; args: { value: string }[] } }[]; + }; + const results: unknown[] = []; + for (const req of parsed.requests ?? []) { + if (!req.stmt) { + results.push({ type: "ok" }); + continue; + } + const args = (req.stmt.args ?? []).map((a) => a.value); + queueCalls.push({ sql: req.stmt.sql, args }); + results.push({ type: "ok", response: { result: queueAnswer(req.stmt.sql, args) } }); + } + return { ok: true, status: 200, json: async () => ({ results }) }; + } + throw new Error(`unexpected direct fetch ${u}`); + }) as never; + // ---- the edge ---------------------------------------------------------- const stored = new Map(); /** Every key written to the edge's storage, in order. */ @@ -91,6 +388,9 @@ async function setup() { kv, now: clock, fetchImpl: outward as never, + direct: options.direct + ? { enabled: true, githubToken: "gh-test", queueToken: "queue-test", fetchImpl: directFetch } + : undefined, setAlarm: async (at) => { alarm.at = at; }, @@ -98,8 +398,6 @@ async function setup() { const edge = { now: makeEdge() }; // ---- the host ---------------------------------------------------------- - const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: OWNER }); - cfg.issuers = [ISSUER]; const data: Record = { board: { counts: { claimed: 1, queued: 2 }, now: [{ id: 1, title: "First task" }], next: [], blocked: [] }, sessions: { moving: [], waiting: [] }, @@ -159,6 +457,15 @@ async function setup() { touch: [], audit: (a) => ({ issue: a.issue }), }, + // The laptop's half of a prompt the edge filed: enqueue its task. + "prompt.enqueue": { + run: async (a) => { + ran.push({ kind: "prompt.enqueue", args: a }); + return { issue: a.issue, queued: true }; + }, + touch: ["board"], + audit: (a) => ({ issue: a.issue }), + }, "pr.merge": { run: async (a) => { ran.push({ kind: "pr.merge", args: a }); @@ -213,6 +520,10 @@ async function setup() { androidPackage: cfg.androidPackage, androidFingerprints: [], androidApp: true, + queueDbUrl: cfg.queueDbUrl, + queueTokenName: cfg.queueTokenName, + promptLabel: cfg.promptLabel, + needsRepos: cfg.needsRepos, }; // ---- the Worker's routing, with the two wired together ----------------- @@ -350,6 +661,14 @@ async function setup() { table, access, edgeConfig, + githubCalls, + queueCalls, + ghIssues, + ghComments, + ghLabels, + ghPrs, + ghSearch, + queueTasks, }; } @@ -366,6 +685,11 @@ describe("before the host's first report", () => { ok: true, edge: true, configured: false, + directEnabled: false, + githubTokenConfigured: false, + queueTokenConfigured: false, + directReady: false, + selfCheck: null, hostSeen: null, answered: 0, deferred: 0, @@ -1203,3 +1527,190 @@ describe("notifications and phones, from the edge", () => { expect(w.hostSaw).toEqual([]); }); }); + +describe("direct reads and writes while the host is away", () => { + /** The host has reported, then gone quiet for a minute. */ + async function quiet() { + const w = await setup({ direct: true }); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + w.net.edgeUp = false; + w.now.t += 60_000; + w.hostSaw.length = 0; + return w; + } + /** Only the laptop's doc pokes, never an ask for it to do anything. */ + const onlyPokes = (w: Awaited>) => + w.hostSaw.every((s) => s.startsWith("GET /console/api/doc/")); + + test("the board, pull requests, ranked issues and prompts come from GitHub and the queue store after a minute of silence", async () => { + const w = await setup({ direct: true }); + await w.hostReads(); + await w.link.now.once(); + // Before the minute is up the host's copy is served, and nothing is read directly. + const stale = await w.core(); + expect(stale.doc.board).toEqual(w.data.board); + expect(stale.doc.asks).toEqual([]); + expect(w.githubCalls).toEqual([]); + expect(w.queueCalls).toEqual([]); + // A minute of silence: the next read is fresh. + w.net.hostUp = false; + w.net.edgeUp = false; + w.now.t += 60_000; + w.hostSaw.length = 0; + const { doc } = await w.core(); + expect(doc.board.counts).toEqual({ claimed: 1, queued: 1, blocked: 1 }); + expect(doc.board.now.map((t: { id: number }) => t.id)).toEqual([21047]); + expect(doc.board.next.map((t: { id: number }) => t.id)).toEqual([21048]); + expect(doc.asks.map((a: { issue: number }) => a.issue)).toEqual([202, 201]); + expect(doc.asks[1].replies).toEqual([ + { you: false, at: "2026-11-22T12:31:00", text: "Done: the docs are updated." }, + ]); + const ops = await w.browse("/console/api/doc/ops"); + const opsDoc = (await ops.json()) as { + prs: unknown[]; + priorities: { issues: { number: number; rank: string }[] }; + }; + expect(opsDoc.prs).toEqual([ + { + number: 55, + title: "Fresh PR", + draft: false, + url: "https://github.com/developing-today/code/pull/55", + created: "2026-11-22T12:30", + author: "worker", + branch: "queue/55", + }, + ]); + expect(opsDoc.priorities.issues.map((i) => i.number)).toEqual([301]); + expect(opsDoc.priorities.issues[0].rank).toBe("now"); + // The reads went to GitHub and the queue store; the laptop was never asked for anything. + expect(onlyPokes(w)).toBe(true); + expect(w.githubCalls.map((c) => c.url)).toContain( + "https://api.github.com/repos/developing-today/code/pulls?state=open&per_page=60", + ); + expect(w.queueCalls.some((c) => c.sql.includes("GROUP BY status"))).toBe(true); + }); + + test("a reply to a prompt is posted once at the edge and not repeated when the laptop returns", async () => { + const w = await quiet(); + const res = await w.act("ask.reply", { issue: 201, text: "Thanks — noted." }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ ok: true, result: { issue: 201, queued: true } }); + const comments = w.githubCalls.filter((c) => c.method === "POST" && c.url.includes("/issues/201/comments")); + expect(comments).toHaveLength(1); + expect(JSON.parse(comments[0].body ?? "{}").body).toContain("Thanks — noted."); + // The reply shows up in the next read at the edge. + const { doc } = await w.core(); + const asked = doc.asks.find((a: { issue: number }) => a.issue === 201) as { + replies: { you: boolean; text: string }[]; + }; + expect(asked.replies[asked.replies.length - 1]).toEqual({ you: true, at: "2026-11-22T12:01:00", text: "Thanks — noted." }); + // Only the queue task waits for the laptop. + expect((w.stored.get("held") as { kind: string }[]).map((h) => h.kind)).toEqual(["prompt.enqueue"]); + // The laptop returns: it runs the held enqueue once, and the reply is not posted again. + w.net.hostUp = true; + w.net.edgeUp = true; + w.now.t += 60_000; + const first = await w.link.now.once(); + expect(first?.commands.map((c) => c.kind)).toEqual(["prompt.enqueue"]); + expect(w.ran.filter((r) => r.kind === "prompt.enqueue")).toHaveLength(1); + w.now.t += 1_000; + const second = await w.link.now.once(); + expect(second?.commands).toEqual([]); + expect(w.ran.filter((r) => r.kind === "prompt.enqueue")).toHaveLength(1); + expect(w.githubCalls.filter((c) => c.method === "POST" && c.url.includes("/issues/201/comments"))).toHaveLength(1); + }); + + test("a new prompt is filed at the edge and only its queue task waits for the laptop", async () => { + const w = await quiet(); + const res = await w.act("ask.send", { text: "File this from the edge" }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + ok: true, + result: { issue: 500, url: "https://github.com/developing-today/code/issues/500", queued: true }, + }); + expect(w.githubCalls.filter((c) => c.method === "POST" && c.url.endsWith("/issues"))).toHaveLength(1); + const held = w.stored.get("held") as { kind: string; args: Record }[]; + expect(held).toHaveLength(1); + expect(held[0].kind).toBe("prompt.enqueue"); + expect(held[0].args.issue).toBe(500); + // The laptop returns and enqueues it once; the issue is not filed again. + w.net.hostUp = true; + w.net.edgeUp = true; + w.now.t += 60_000; + await w.link.now.once(); + expect(w.ran.filter((r) => r.kind === "prompt.enqueue")).toHaveLength(1); + expect(w.githubCalls.filter((c) => c.method === "POST" && c.url.endsWith("/issues"))).toHaveLength(1); + }); + + test("closing a prompt, ranking an issue, commenting on a need and moving a task run at the edge", async () => { + const w = await quiet(); + const closed = await w.act("ask.close", { issue: 202 }); + expect(closed.status).toBe(200); + expect(await closed.json()).toEqual({ ok: true, result: { issue: 202, closed: true } }); + expect(w.ghIssues[202].state).toBe("closed"); + const ranked = await w.act("issue.rank", { issue: 301, rank: "next" }); + expect(ranked.status).toBe(200); + expect(await ranked.json()).toEqual({ ok: true, result: { issue: 301, rank: "next" } }); + expect(w.ghLabels[301]).toEqual(["next"]); + const need = await w.act("need.comment", { ref: "developing-today/code#301", text: "Noted." }); + expect(need.status).toBe(200); + expect((w.ghComments[301] ?? []).some((c) => c.body.startsWith("Noted."))).toBe(true); + const moved = await w.act("task.move", { task: 21048, to: "first" }); + expect(moved.status).toBe(200); + expect(await moved.json()).toEqual({ ok: true, result: { task: 21048, priority: 10 } }); + expect(w.queueTasks.find((t) => t.id === 21048)?.priority).toBe(10); + // Nothing was held for the laptop: all four were done here. + expect((w.stored.get("held") as unknown[] | undefined) ?? []).toEqual([]); + expect(onlyPokes(w)).toBe(true); + // And the board the edge serves already shows the move. + const { doc } = await w.core(); + expect(doc.board.next.find((t: { id: number }) => t.id === 21048)?.priority).toBe(10); + }); + + test("health reports the direct capability and the self-check", async () => { + const w = await setup({ direct: true }); + await w.hostReads(); + await w.link.now.once(); + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health.directEnabled).toBe(true); + expect(health.githubTokenConfigured).toBe(true); + expect(health.queueTokenConfigured).toBe(true); + expect(health.directReady).toBe(true); + const selfCheck = health.selfCheck as { at: number; kinds: Record }; + expect(selfCheck.at).toBe(START); + expect(Object.keys(selfCheck.kinds).sort()).toEqual(["asks", "board", "priorities", "prs"]); + expect(Object.values(selfCheck.kinds).every((k) => k.ok)).toBe(true); + // A second health read reuses the stored self-check: no more direct reads. + const calls = w.githubCalls.length + w.queueCalls.length; + await w.browse("/console/health", { token: null }); + expect(w.githubCalls.length + w.queueCalls.length).toBe(calls); + }); + + test("without the direct switch, or before the laptop is quiet, actions go to the host as before", async () => { + // No direct switch: the host is away, so the action is held, not run here. + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + w.net.edgeUp = false; + const held = await w.act("issue.comment", { issue: 14, text: "late" }); + expect(await held.json()).toEqual({ ok: true, held: true, result: null }); + expect(w.githubCalls).toEqual([]); + expect(w.queueCalls).toEqual([]); + // Direct switch on but the laptop still reporting: the action goes to the host. + // A second setup signs with a fresh key under the same kid, so the + // cached key set from the first setup must go first. + clearJwksCache(); + const d = await setup({ direct: true }); + await d.hostReads(); + await d.link.now.once(); + const res = await d.act("issue.comment", { issue: 14, text: "now" }); + expect(res.status).toBe(200); + expect(d.ran).toEqual([{ kind: "issue.comment", args: { issue: 14, text: "now" } }]); + expect(d.githubCalls).toEqual([]); + expect(d.queueCalls).toEqual([]); + }); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index ac22898fd5..1352d10e0b 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -505,6 +505,48 @@ describe("what the owner asks for in his own words", () => { await expect(work.askReply({ issue: "12501/comments", text: "x" })).rejects.toThrow(OpError); }); + test("a custom enqueue hook takes the queue task instead of the laptop's command", async () => { + const w = world({ + commands: (argv) => + argv.includes(`repos/${REPO}/issues`) ? JSON.stringify({ number: 12501, html_url: "https://x/12501" }) : "{}", + }); + const work = new Work(w.ops, undefined, () => new Date("2026-11-22T06:00:00Z")); + const held: unknown[] = []; + const hook = async (packet: unknown) => { + held.push(packet); + return { code: 0, stdout: "", stderr: "" }; + }; + // A new prompt: the issue is filed at once, the task goes to the hook. + expect(await work.ask({ text: "Do the docs" }, hook)).toEqual({ + issue: 12501, + url: "https://x/12501", + queued: true, + }); + expect(held).toHaveLength(1); + expect(held[0]).toEqual( + promptPacket(REPO, "repo-health-code-pilot", 12501, "Do the docs", "2026-11-22T06:00:00.000Z"), + ); + expect(w.calls.some((c) => c.argv[1] === "queue")).toBe(false); + // A reply: the comment is posted at once, the task goes to the hook. + const issue = (state: string, labels: string[]) => + JSON.stringify({ state, labels: labels.map((name) => ({ name })) }); + const r = world({ + commands: (argv) => + argv[3] === `repos/${REPO}/issues/12501` ? issue("open", ["owner/prompt"]) : JSON.stringify({ id: 777 }), + }); + const replyWork = new Work(r.ops, undefined, () => new Date("2026-11-22T06:00:00Z")); + expect(await replyWork.askReply({ issue: 12501, text: "also do the docs" }, hook)).toEqual({ + issue: 12501, + queued: true, + }); + expect(held).toHaveLength(2); + expect(held[1]).toMatchObject({ + priority: 10, + dedupe_key: `repo-health:v1:triage:${REPO}:issue:12501`, + }); + expect(r.calls.some((c) => c.argv[1] === "queue")).toBe(false); + }); + test("each prompt shows where it stands", async () => { const found = (n: number, state: string, comments: number) => ({ number: n, From d59a57f3c908612b8e3c02cf4470f0b91143259b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 16:08:02 +0000 Subject: [PATCH 2/2] pm-console: answer Codex review on #12579 - direct.ts: send an explicit User-Agent with GitHub REST requests; Workers supplies none and GitHub requires it. - edge-proto.ts: accept configs stored or reported before direct mode (new direct fields empty); gate direct capabilities on the config carrying them instead of refusing the whole config. - edge.ts: hydrate the durable mirror before a first direct read, so a failed read after a restart keeps last-good data; keep notification refreshes from reloading the mirror over freshly read sections. - actions.ts: a failed deferred prompt.enqueue throws, so the held action is reported failed instead of recorded done with no queue task. - expose.py: remember the direct-mode choice only after the Worker has it, so a failed run retries instead of assuming the mode is set. Tests: 134/134 console tests (bun test), 19/19 expose tests; each new test fails against the pre-fix code. --- pm-stack/console/edge/src/direct.ts | 3 + pm-stack/console/edge/src/edge.ts | 41 +++++++++--- pm-stack/console/scripts/expose.py | 15 ++++- pm-stack/console/scripts/test_expose.py | 78 +++++++++++++++++++++-- pm-stack/console/src/actions.ts | 12 +++- pm-stack/console/src/edge-proto.ts | 23 ++++--- pm-stack/console/src/notify.ts | 8 ++- pm-stack/console/test/console.test.ts | 20 ++++++ pm-stack/console/test/direct.test.ts | 3 + pm-stack/console/test/edge.test.ts | 84 ++++++++++++++++++++++++- 10 files changed, 257 insertions(+), 30 deletions(-) diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 5ff4e4294b..ddbb7772a8 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -89,6 +89,9 @@ async function ghApi( headers: { accept: "application/vnd.github+json", authorization: `Bearer ${token}`, + // The Workers runtime supplies no User-Agent of its own, and + // GitHub requires one: without it every direct call is refused. + "user-agent": "pm-console-edge", "x-github-api-version": "2022-11-28", ...(body === undefined ? {} : { "content-type": "application/json" }), }, diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 9d11d20285..08bc19fbe0 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -340,14 +340,21 @@ export class Edge { } /** May act itself right now: capable, and the laptop known quiet. */ - private directReady(): boolean { - return this.directCapable() && this.directQuiet(); + private directReady(cfg: EdgeConfig | null): boolean { + return this.directCapable() && this.directConfigReady(cfg) && this.directQuiet(); + } + + /** The config carries what direct mode needs: a config stored or + * reported before direct mode existed has these empty, and the edge + * serves the offline app from it without acting itself. */ + private directConfigReady(cfg: EdgeConfig | null): boolean { + return cfg !== null && cfg.queueDbUrl !== "" && cfg.queueTokenName !== "" && cfg.promptLabel !== ""; } /** The laptop's own classes, wired for the edge. Null while the * capability is not there. */ private directClasses(cfg: EdgeConfig | null): ReturnType | null { - if (cfg === null || !this.directCapable()) return null; + if (cfg === null || !this.directCapable() || !this.directConfigReady(cfg)) return null; return directClasses(cfg, { githubToken: this.direct?.githubToken, queueToken: this.direct?.queueToken, @@ -367,6 +374,10 @@ export class Edge { this.directAt.set(name, now); const direct = this.directClasses(cfg); if (!direct) return; + // After a restart the in-memory sections are empty even though the + // durable mirror holds the host's last copy: load it first, so a + // failed first read keeps last-good data instead of nothing. + if (this.docs.good(name) === null) await this.docs.refresh(name); try { this.docs.record(name, await directRead(name, direct.ops, direct.work), now); } catch (error) { @@ -377,11 +388,15 @@ export class Edge { /** The sections of one document that the edge reads itself, when it may. */ private async directRefresh(doc: DocName): Promise { const names = doc === "core" ? ["board", "asks"] : doc === "ops" ? ["prs", "priorities"] : []; - if (names.length === 0 || !this.directReady()) return; + if (names.length === 0) return; const cfg = await this.config(); + if (!this.directReady(cfg)) return; for (const name of names) await this.directReadSection(name, cfg); - if (names.some((n) => WATCHED.includes(n))) { - await this.notifier.tick().catch(() => {}); + // The notifier is told of the sections just read directly, so its + // refresh does not reload the laptop's mirror over them. + const watched = names.filter((n) => WATCHED.includes(n)); + if (watched.length > 0) { + await this.notifier.tick(watched).catch(() => {}); } } @@ -464,7 +479,12 @@ export class Edge { } } if (action.touch.some((n) => WATCHED.includes(n))) { - await this.notifier.tick().catch(() => {}); + // The sections just read directly are not reloaded from the + // laptop's mirror by the notifier's refresh. + const refreshed = action.touch.filter( + (n) => (DIRECT_READ_SECTIONS as readonly string[]).includes(n) && WATCHED.includes(n), + ); + await this.notifier.tick(refreshed).catch(() => {}); } return json({ ok: true, result }); } catch (error) { @@ -677,7 +697,10 @@ export class Edge { directEnabled: this.direct?.enabled === true, githubTokenConfigured: Boolean(this.direct?.githubToken), queueTokenConfigured: Boolean(this.direct?.queueToken), - directReady: this.directCapable(), + // Ready to act itself once the laptop is quiet: the switch and + // tokens are here, and the config carries what direct mode + // needs. The quiet gate itself is not part of this answer. + directReady: this.directCapable() && this.directConfigReady(cfg), selfCheck: this.selfCheckResult, hostSeen: this.hostSeen || null, // Since this object last started: requests it answered as the @@ -785,7 +808,7 @@ export class Edge { // runs here, through the laptop's own classes, and is never // sent to the laptop — so the laptop cannot do it a second // time. Otherwise it is the host's to do, as before. - if ((DIRECT_ACTIONS as readonly string[]).includes(kind) && this.directReady()) { + if ((DIRECT_ACTIONS as readonly string[]).includes(kind) && this.directReady(cfg)) { return await this.directAct(kind, args as Record, by, who.via); } // The host's to do. The stateless part relays it, and if the diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 00bc57c1db..1e188a60ef 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -262,13 +262,17 @@ def ensure_edge_direct( or turn the opt-in off. Nothing is uploaded on a run that does not change the choice, so the timer's runs leave the secrets alone. A secret is read by name through `fleet secrets get` and piped to - `wrangler secret put`; it is never printed or written to a file.""" + `wrangler secret put`; it is never printed or written to a file. + The choice is remembered only after the Worker has it: a run that + fails part-way leaves the old marker, so the next run tries again + instead of assuming the mode is already set.""" state = env.parent # Read what is remembered before the choice overwrites it: only a - # change uploads anything. + # change uploads anything. Nothing is written here: the marker moves + # only once the remote changes below have succeeded. marker = state / "edge-direct" current = marker.exists() and marker.read_text().strip() == "on" - wanted = direct_choice(state, choice, keep=not check) + wanted = direct_choice(state, choice, keep=False) if wanted == current: return if wanted: @@ -316,6 +320,11 @@ def put(name: str, value: str) -> None: else: # The tokens stay, inert without the opt-in; only the flag moves. put("EDGE_DIRECT", "off") + # The Worker has the change now, so the choice is remembered; a + # failure above raises before this line and leaves the old marker. + if choice is not None: + state.mkdir(parents=True, exist_ok=True, mode=0o700) + marker.write_text(choice + "\n") def worker_ready(cf: Cloudflare, account: str, host: str) -> bool: diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 5c56062547..3336bc5193 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -144,10 +144,16 @@ def up(self, origin, seconds=20): return self.running -def run(account, home, *args, machine=None, owner=OWNER, stdin=None): +def run(account, home, *args, machine=None, owner=OWNER, stdin=None, secrets=None, wrangler_path=None): """One run of the script. What it printed is left in account.printed.""" argv = ["expose.py", *(["--owner", owner] if owner else []), *args] machine = machine or Machine() + real_which = expose.shutil.which + + def secret(name): + if secrets is not None and name in secrets: + return secrets[name] + return "token" if name.startswith("cloudflare.") else "" def health(url): if account.health_misses > 0: @@ -162,10 +168,11 @@ def health(url): with ( mock.patch.object(expose, "Cloudflare", lambda token, check: account), + mock.patch.object(expose, "secret", secret), mock.patch.object( - expose, - "secret", - lambda name: "token" if name.startswith("cloudflare.") else "", + expose.shutil, + "which", + lambda cmd, *a, **k: wrangler_path if wrangler_path is not None else real_which(cmd, *a, **k), ), mock.patch.object(expose.pathlib.Path, "home", lambda: pathlib.Path(home)), mock.patch.object(expose.subprocess, "run", machine.systemctl), @@ -505,6 +512,69 @@ def test_edge_off_is_remembered_and_edge_on_brings_it_back(self): ) self.assertEqual(self.env()["PM_CONSOLE_EDGE_URL"], f"https://{HOST}") + def test_direct_choice_is_remembered_only_after_it_is_applied(self): + account = Account() + run(account, self.home) + marker = pathlib.Path(self.home) / ".local/state/pm-console/edge-direct" + fake = pathlib.Path(self.home) / "wrangler" + fake.write_text("#!/bin/sh\n") + # The tokens cannot be read here: the run fails, and nothing is + # remembered, so a later run still tries to turn direct mode on. + with self.assertRaisesRegex(SystemExit, "is not readable here"): + run(account, self.home, "--edge-direct", "on", wrangler_path=str(fake)) + self.assertFalse(marker.exists()) + # Readable now: the tokens are uploaded and the choice is remembered. + secrets = { + expose.GITHUB_TOKEN_SECRET: "gh-test", + expose.QUEUE_TOKEN_DEFAULT: "queue-test", + } + machine = Machine() + self.assertEqual( + run( + account, + self.home, + "--edge-direct", + "on", + machine=machine, + secrets=secrets, + wrangler_path=str(fake), + ), + 0, + ) + self.assertEqual(marker.read_text().strip(), "on") + self.assertEqual(machine.commands.count("put"), 3) + # A later run with the same choice uploads nothing again. + machine = Machine() + self.assertEqual( + run( + account, + self.home, + "--edge-direct", + "on", + machine=machine, + secrets=secrets, + wrangler_path=str(fake), + ), + 0, + ) + self.assertEqual(account.changes, []) + self.assertNotIn("put", machine.commands) + # Turning it off is remembered the same way, once the Worker has it. + self.assertEqual( + run( + account, + self.home, + "--edge-direct", + "off", + machine=machine, + secrets=secrets, + wrangler_path=str(fake), + ), + 0, + ) + self.assertEqual(marker.read_text().strip(), "off") + self.assertEqual(machine.commands.count("put"), 1) + def test_another_workers_route_on_the_hostname_is_left_alone(self): for foreign in ( {"id": "x", "pattern": f"{HOST}/*", "script": "someone-elses"}, diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index 0957f2d7f6..45ca56ba17 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -82,10 +82,20 @@ export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): R if (typeof a.text !== "string" || a.text.trim() === "" || a.text.length > 8000) throw new OpError(400, "text: required, at most 8000 characters"); if (typeof a.at !== "string" || a.at === "") throw new OpError(400, "at: required"); + // A failed enqueue is thrown, not answered as "not queued": this + // runs late, so nobody is listening for the answer, and a + // `queued: false` would be recorded done and the held prompt + // acknowledged as sent with no queue task behind it. const queued = await ops.enqueue( promptPacket(ops.cfg.repo, ops.cfg.queue, issue, a.text, a.at), ); - return { issue, queued: queued.code === 0 }; + if (queued.code !== 0) { + throw new OpError( + 502, + `the queue task could not be filed: ${(queued.stderr || queued.stdout || "the queue did not answer").trim().slice(0, 200)}`, + ); + } + return { issue, queued: true }; }, touch: ["board"], audit: ids("issue"), diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index cbe1be1479..706c10ab8f 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -24,7 +24,10 @@ import type { Issuer } from "./config.ts"; * fields are what the edge needs to read and write by itself while the * laptop is away: where the queue store is and which token opens it, how * the owner's prompts are marked, and which repositories hold his - * needs-me items. */ + * needs-me items. They are absent from configs stored or reported + * before direct mode existed: those still validate, with the fields + * empty, and direct capabilities stay off until a config carries them + * (see Edge.directConfigReady). */ export interface EdgeConfig { owners: string[]; certNames: string[]; @@ -200,10 +203,12 @@ export function edgeConfig(value: unknown): EdgeConfig | null { }); } if (typeof v.repo !== "string" || typeof v.queue !== "string" || typeof v.androidPackage !== "string") return null; - if (typeof v.queueDbUrl !== "string" || !/^https:\/\//.test(v.queueDbUrl)) return null; - if (typeof v.queueTokenName !== "string" || v.queueTokenName === "") return null; - if (typeof v.promptLabel !== "string" || v.promptLabel === "") return null; - if (!strings(v.needsRepos)) return null; + // The direct fields: present ones must be well-formed, absent ones + // are a config from before direct mode, which still validates. + if (v.queueDbUrl !== undefined && (typeof v.queueDbUrl !== "string" || !/^https:\/\//.test(v.queueDbUrl))) return null; + if (v.queueTokenName !== undefined && typeof v.queueTokenName !== "string") return null; + if (v.promptLabel !== undefined && typeof v.promptLabel !== "string") return null; + if (v.needsRepos !== undefined && !strings(v.needsRepos)) return null; return { owners: v.owners.map((o) => o.toLowerCase()), certNames: v.certNames, @@ -213,9 +218,9 @@ export function edgeConfig(value: unknown): EdgeConfig | null { androidPackage: v.androidPackage, androidFingerprints: v.androidFingerprints, androidApp: v.androidApp === true, - queueDbUrl: v.queueDbUrl, - queueTokenName: v.queueTokenName, - promptLabel: v.promptLabel, - needsRepos: v.needsRepos, + queueDbUrl: typeof v.queueDbUrl === "string" ? v.queueDbUrl : "", + queueTokenName: typeof v.queueTokenName === "string" ? v.queueTokenName : "", + promptLabel: typeof v.promptLabel === "string" ? v.promptLabel : "", + needsRepos: strings(v.needsRepos) ? v.needsRepos : [], }; } diff --git a/pm-stack/console/src/notify.ts b/pm-stack/console/src/notify.ts index 474a5cc119..64fd63e4af 100644 --- a/pm-stack/console/src/notify.ts +++ b/pm-stack/console/src/notify.ts @@ -132,13 +132,15 @@ export class Notifier { return this.seen; } - /** One pass. Does nothing while no device is subscribed. */ - async tick(): Promise { + /** One pass. Does nothing while no device is subscribed. Sections in + * `skip` were just read from their live source and are compared as + * they are, not reloaded from the mirror first. */ + async tick(skip: string[] = []): Promise { if (this.busy) return 0; this.busy = true; try { if ((await this.push.status()).devices === 0) return 0; - await this.docs.touch(WATCHED); + await this.docs.touch(WATCHED.filter((n) => !skip.includes(n))); const now = Object.fromEntries(WATCHED.map((n) => [n, this.docs.good(n)])) as State; const { messages, seen } = changes(await this.load(), now); for (const m of messages) await this.push.send(m.cls, m); diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index 70e5342b31..0177db9d1e 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -16,6 +16,7 @@ import { beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { actions } from "../src/actions.ts"; import { AuthError, authorize, @@ -434,6 +435,25 @@ describe("operations", () => { expect(r.calls.length).toBe(1); }); + test("a failed deferred prompt enqueue is reported, not recorded done", async () => { + // The laptop runs this late, with nobody listening for the answer: + // a nonzero enqueue must throw, so the held action is reported + // failed and the edge does not acknowledge a queue task that was + // never filed. + const r = recorder(() => ({ code: 1, stderr: "queue is down" })); + const ops = new Ops(CFG, r.run); + const table = actions(ops, {} as never); + await expect( + table["prompt.enqueue"].run({ issue: 201, text: "Do the docs", at: "2026-11-22T12:00:00Z" }), + ).rejects.toThrow(/queue is down/); + // And the good path still answers queued. + const ok = recorder(() => ({ code: 0, stderr: "" })); + const good = actions(new Ops(CFG, ok.run), {} as never); + await expect( + good["prompt.enqueue"].run({ issue: 201, text: "Do the docs", at: "2026-11-22T12:00:00Z" }), + ).resolves.toEqual({ issue: 201, queued: true }); + }); + test("the queue is read with bound parameters and never written", async () => { const r = recorder(() => "secret-token\n"); const sent: { url: string; body: { requests: { stmt?: { sql: string; args: unknown[] } }[] }; auth: string }[] = []; diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index 10723dcc41..9d12f22525 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -52,6 +52,9 @@ describe("the edge's run: GitHub through REST", () => { expect(h.calls[0].init.method).toBe("GET"); expect(h.calls[0].init.headers.authorization).toBe("Bearer gh-test"); expect(h.calls[0].init.headers["x-github-api-version"]).toBe("2022-11-28"); + // The Workers runtime supplies no User-Agent of its own, and GitHub + // requires one: the call must carry this program's. + expect(h.calls[0].init.headers["user-agent"]).toBe("pm-console-edge"); expect(out).toEqual({ code: 0, stdout: "[{\"number\":1}]", stderr: "" }); }); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 8754227f71..718f3bbd56 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -19,7 +19,7 @@ import { clearJwksCache, identify } from "../src/auth.ts"; import { readConfig } from "../src/config.ts"; import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; -import { type EdgeConfig, keyId, newKeyPair, sign } from "../src/edge-proto.ts"; +import { type EdgeConfig, edgeConfig as parseEdgeConfig, keyId, newKeyPair, sign } from "../src/edge-proto.ts"; import { OpError } from "../src/errors.ts"; import { Ops } from "../src/ops.ts"; import { type Deps, handle, heldRunner, marked } from "../src/server.ts"; @@ -339,10 +339,14 @@ async function setup(options: { direct?: boolean } = {}) { } throw new Error(`unexpected GitHub call ${method} ${url}`); }; + /** The direct source, made to fail by a test that turns it on. */ + const directDown = { on: false }; const directFetch = (async ( url: string, init: { method?: string; headers?: Record; body?: string }, ) => { + // Made to fail by a test: the direct source is down, not the data. + if (directDown.on) throw new Error("the direct source is down"); const u = String(url); const method = init?.method ?? "GET"; if (u.startsWith("https://api.github.com/")) { @@ -661,6 +665,7 @@ async function setup(options: { direct?: boolean } = {}) { table, access, edgeConfig, + directDown, githubCalls, queueCalls, ghIssues, @@ -1713,4 +1718,81 @@ describe("direct reads and writes while the host is away", () => { expect(d.githubCalls).toEqual([]); expect(d.queueCalls).toEqual([]); }); + + test("a config stored before direct mode still serves the offline app, without acting itself", async () => { + const w = await setup({ direct: true }); + await w.hostReads(); + await w.link.now.once(); + // What an older Worker stored: the same settings, without the fields + // direct mode added. That shape still validates, with those empty. + const legacy = { ...w.edgeConfig } as Record; + delete legacy.queueDbUrl; + delete legacy.queueTokenName; + delete legacy.promptLabel; + delete legacy.needsRepos; + expect(parseEdgeConfig(legacy)).toMatchObject({ + repo: w.edgeConfig.repo, + queueDbUrl: "", + queueTokenName: "", + promptLabel: "", + needsRepos: [], + }); + w.stored.set("cfg", legacy); + w.edge.now = w.makeEdge(); + // The laptop is out of reach: the app is still served from the + // mirror, not relayed to a host that cannot answer. + w.net.hostUp = false; + w.net.edgeUp = false; + const { res, doc } = await w.core(); + expect(res.status).toBe(200); + expect(doc.board).toEqual(w.data.board); + expect(doc.asks).toEqual([]); + expect(w.githubCalls).toEqual([]); + expect(w.queueCalls).toEqual([]); + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health.configured).toBe(true); + expect(health.directReady).toBe(false); + }); + + test("a notification about a directly read reply is sent, and the fresh read is not overwritten", async () => { + const w = await setup({ direct: true }); + const phone = await browser(); + await w.hostReads(); + await w.link.now.once(); + // Subscribing primes the notifier on the host's last copy: no replies yet. + expect((await w.act("push.on", { subscription: phone.subscription, label: "Pocket" })).status).toBe(200); + expect(w.pushes).toHaveLength(0); + // The laptop goes quiet; the next read comes from GitHub, where the + // fleet has since answered prompt #201. + w.net.hostUp = false; + w.net.edgeUp = false; + w.now.t += 60_000; + const { doc } = await w.core(); + const asked = doc.asks.find((a: { issue: number }) => a.issue === 201) as { + replies: { you: boolean; at: string; text: string }[]; + }; + expect(asked.replies).toEqual([ + { you: false, at: "2026-11-22T12:31:00", text: "Done: the docs are updated." }, + ]); + // The notifier saw that fresh reply, not the mirror's empty asks. + expect(w.pushes).toHaveLength(1); + expect(JSON.parse(await phone.open(w.pushes[0].body)).title).toBe("The fleet replied on #201"); + }); + + test("after a restart, a failed first direct read still shows the mirrored copy", async () => { + const w = await setup({ direct: true }); + await w.hostReads(); + await w.link.now.once(); + // The edge restarts: nothing is in memory, but the mirror is durable. + w.edge.now = w.makeEdge(); + w.directDown.on = true; + w.net.hostUp = false; + w.net.edgeUp = false; + w.now.t += 60_000; + const { doc } = await w.core(); + expect(doc.board).toEqual(w.data.board); + expect(doc.asks).toEqual([]); + expect(doc.health.board).toEqual({ ok: false, error: expect.stringContaining("the direct source is down") }); + expect(doc.health.asks.ok).toBe(false); + }); });