From 111337351adc59af3a79b25694f512a2230ce578 Mon Sep 17 00:00:00 2001 From: Claude Code Bot Date: Mon, 23 Nov 2026 16:59:21 -0800 Subject: [PATCH 1/2] feat(nos-runner-watchdog): watch the macOS pool from the same Worker The Worker now runs one tick per pool. scheduled() picks the pool from event.cron: "*/10 * * * *" is NOS (as before), and the new "5,15,25,35,45,55 * * * *" trigger is the smartwatermelon macOS pool. An unknown cron logs one line and does nothing. The GitHub calls (getRunners, getVar, setVar, scanQueue, scanRepo, mimoletteJobs) take the pool for its org, variable, label and variable visibility; they default to NOS. runTick takes the pool too: KV keys get the pool prefix (none for NOS), the token is minted from that pool's App secrets, decide() gets the pool's labels, and alerts use pool.messages. The copy of the NOS texts in index.js is gone; the old tests that assert those texts pass unedited. A pool whose App secrets are not all set logs one line and makes no fetch and no KV call, not even the skips write. Each pool runs in its own invocation, so each keeps its own 40-subrequest budget. Merging deploys nothing. Andrew deploys, with the SWM_* secrets, in the batch. Advances #252 --- workers/nos-runner-watchdog/src/github.js | 65 ++- workers/nos-runner-watchdog/src/index.js | 69 +-- workers/nos-runner-watchdog/src/pools.js | 4 +- .../test/pool-index.test.js | 409 ++++++++++++++++++ .../nos-runner-watchdog/test/pool-world.js | 126 ++++++ .../nos-runner-watchdog/test/pools.test.js | 4 +- workers/nos-runner-watchdog/wrangler.toml | 4 +- 7 files changed, 622 insertions(+), 59 deletions(-) create mode 100644 workers/nos-runner-watchdog/test/pool-index.test.js create mode 100644 workers/nos-runner-watchdog/test/pool-world.js diff --git a/workers/nos-runner-watchdog/src/github.js b/workers/nos-runner-watchdog/src/github.js index a689cc2..2985f9c 100644 --- a/workers/nos-runner-watchdog/src/github.js +++ b/workers/nos-runner-watchdog/src/github.js @@ -1,7 +1,6 @@ +import { POOLS } from "./pools.js"; + const API = "https://api.github.com"; -const ORG = "nightowlstudiollc"; -const VAR = "NOS_RUNNER"; -const LABEL = "mimolette"; /** Non-2xx from GitHub. `what` names the call; it never holds a token. */ export class GitHubError extends Error { @@ -83,30 +82,31 @@ export async function appToken(env, fetchFn, now = Date.now()) { return out.token; } -/** Online runners that carry the mimolette label, as [{name, busy}]. */ -export async function getRunners(token, fetchFn) { +/** Online runners that carry the pool's label, as [{name, busy}]. */ +export async function getRunners(token, fetchFn, pool = POOLS.nos) { const out = await call( token, "GET", - `/orgs/${ORG}/actions/runners?per_page=100`, + `/orgs/${pool.org}/actions/runners?per_page=100`, "runners", fetchFn, ); return (out.runners ?? []) .filter( (r) => - r.status === "online" && (r.labels ?? []).some((l) => l.name === LABEL), + r.status === "online" && + (r.labels ?? []).some((l) => l.name === pool.label), ) .map((r) => ({ name: r.name, busy: Boolean(r.busy) })); } -/** NOS_RUNNER value, or null when the variable does not exist. */ -export async function getVar(token, fetchFn) { +/** The pool's variable value, or null when the variable does not exist. */ +export async function getVar(token, fetchFn, pool = POOLS.nos) { try { const out = await call( token, "GET", - `/orgs/${ORG}/actions/variables/${VAR}`, + `/orgs/${pool.org}/actions/variables/${pool.variable}`, "var get", fetchFn, ); @@ -117,14 +117,14 @@ export async function getVar(token, fetchFn) { } } -/** Updates NOS_RUNNER; creates it when the update returns 404. */ -export async function setVar(token, value, fetchFn) { - const body = { name: VAR, value, visibility: "private" }; +/** Updates the pool's variable; creates it when the update returns 404. */ +export async function setVar(token, value, fetchFn, pool = POOLS.nos) { + const body = { name: pool.variable, value, visibility: pool.visibility }; try { await call( token, "PATCH", - `/orgs/${ORG}/actions/variables/${VAR}`, + `/orgs/${pool.org}/actions/variables/${pool.variable}`, "var update", fetchFn, body, @@ -134,7 +134,7 @@ export async function setVar(token, value, fetchFn) { await call( token, "POST", - `/orgs/${ORG}/actions/variables`, + `/orgs/${pool.org}/actions/variables`, "var create", fetchFn, body, @@ -177,10 +177,14 @@ export async function getJobs(token, repo, runId, fetchFn) { return out.jobs ?? []; } -/** Jobs on a mimolette runner that are still waiting or running. */ -export function mimoletteJobs(jobs, statuses = ["queued", "in_progress"]) { +/** Jobs for the pool's runner label that are still waiting or running. */ +export function mimoletteJobs( + jobs, + statuses = ["queued", "in_progress"], + pool = POOLS.nos, +) { return jobs.filter( - (j) => statuses.includes(j.status) && (j.labels ?? []).includes(LABEL), + (j) => statuses.includes(j.status) && (j.labels ?? []).includes(pool.label), ); } @@ -190,7 +194,13 @@ const SCAN_STATUSES = ["queued", "in_progress"]; export const MAX_JOB_PROBES = 3; /** One repo: its waiting runs, then jobs run by run until a queued mimolette job. Null when canFetch(n) refuses. */ -export async function scanRepo(token, repo, fetchFn, canFetch = () => true) { +export async function scanRepo( + token, + repo, + fetchFn, + canFetch = () => true, + pool = POOLS.nos, +) { // Ask for the worst case (lists + job probes) up front, so a started repo is never dropped half-read. if (!canFetch(SCAN_STATUSES.length + MAX_JOB_PROBES)) return null; const runs = []; @@ -206,7 +216,7 @@ export async function scanRepo(token, repo, fetchFn, canFetch = () => true) { for (const run of ordered.slice(0, MAX_JOB_PROBES)) { const list = await getJobs(token, repo, run.id, fetchFn); jobs.set(run.id, list); - const queued = mimoletteJobs(list, ["queued"]); + const queued = mimoletteJobs(list, ["queued"], pool); if (queued.length === 0) continue; oldestAt = Math.min(...queued.map((j) => Date.parse(j.created_at))); break; @@ -215,13 +225,24 @@ export async function scanRepo(token, repo, fetchFn, canFetch = () => true) { } /** Scans repos in rotation from cursor until canFetch(n) refuses. oldestAt is epoch ms or null. */ -export async function scanQueue(token, fetchFn, { cursor = 0, canFetch } = {}) { +export async function scanQueue( + token, + fetchFn, + { cursor = 0, canFetch } = {}, + pool = POOLS.nos, +) { const all = await listRepos(token, fetchFn); const n = all.length; const start = n > 0 ? ((cursor % n) + n) % n : 0; const repos = []; for (let i = 0; i < n; i += 1) { - const r = await scanRepo(token, all[(start + i) % n], fetchFn, canFetch); + const r = await scanRepo( + token, + all[(start + i) % n], + fetchFn, + canFetch, + pool, + ); if (!r) break; repos.push(r); } diff --git a/workers/nos-runner-watchdog/src/index.js b/workers/nos-runner-watchdog/src/index.js index 40b3ae1..c97bf29 100644 --- a/workers/nos-runner-watchdog/src/index.js +++ b/workers/nos-runner-watchdog/src/index.js @@ -1,5 +1,6 @@ import { decide } from "./decide.js"; import * as gh from "./github.js"; +import { POOLS, poolForCron, appEnv } from "./pools.js"; // Free plan allows 50 subrequests a run; KV calls are counted too, for headroom. export const CAP = 40; @@ -11,22 +12,12 @@ const RESERVE_FINAL = 1; const OPTIONAL_SHARE = 10; // A pending run is dropped after this many failed status or rerun calls. const MAX_ATTEMPTS = 6; -const FALLBACK = "ubuntu-latest"; const TOKEN_TTL = 3000; // Skipped ticks in a row (about 30 minutes) before the one "watchdog skipping" alert. const SKIP_ALERT = 3; // Sends per alert. A tick sends at most two alerts, so retries fit in the CAP headroom. const NTFY_TRIES = 3; -const MESSAGES = { - down: () => - "NOS runner down: NOS_RUNNER set to ubuntu-latest; stuck runs cancelled for re-run.", - recovered: () => "NOS runner recovered: NOS_RUNNER set to mimolette.", - online: () => "NOS runner online: NOS_RUNNER was unset, now mimolette.", - held: (v) => - `NOS runner held: NOS_RUNNER=${v}; the watchdog leaves it alone.`, -}; - // Logs name the failed call and status only, never a URL, token or topic. const describe = (e) => e instanceof gh.GitHubError ? e.message : (e?.name ?? "Error"); @@ -45,25 +36,33 @@ function makeBudget(cap) { }; } -/** One watchdog tick. deps: {fetch, now}. Every fetch and KV call is counted against CAP. */ -export async function runTick(env, { fetch: rawFetch, now }) { +/** One tick for one pool. deps: {fetch, now, pool}. Every fetch and KV call is counted against CAP. */ +export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) { + // An unconfigured pool touches nothing: no fetch, no KV, not even the skips counter. + const app = appEnv(env, pool); + if (!app) { + log(`pool ${pool.id} not configured: App secrets missing`); + return; + } const budget = makeBudget(CAP); const fetchFn = (url, init) => { budget.take(); return rawFetch(url, init); }; + // Every key carries the pool prefix; NOS has none, so its keys are unchanged. + const key = (k) => `${pool.prefix}${k}`; const kv = { get(k) { budget.take(); - return env.STATE.get(k); + return env.STATE.get(key(k)); }, put(k, v, opts) { budget.take(); - return env.STATE.put(k, v, opts); + return env.STATE.put(key(k), v, opts); }, delete(k) { budget.take(); - return env.STATE.delete(k); + return env.STATE.delete(key(k)); }, }; @@ -110,7 +109,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { const count = (skips?.count ?? 0) + 1; let notified = skips?.notified === true; if (count >= SKIP_ALERT && !notified) { - notified = await notify(`watchdog skipping: ${reasonClass(e)}`); + notified = await notify(pool.messages.skip(reasonClass(e))); } await kv.put("skips", JSON.stringify({ count, notified })); }; @@ -118,7 +117,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { let token = null; let cached = false; const mint = async () => { - token = await gh.appToken(env, fetchFn, now); + token = await gh.appToken(app, fetchFn, now); cached = false; await kv.put("token", token, { expirationTtl: TOKEN_TTL }); }; @@ -138,7 +137,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { // Required phase: any failure skips the tick; state, pendingReruns and GitHub stay untouched (the token cache may change). const sweepLikely = pending.length > 0 || - prev.lastVar === FALLBACK || + prev.lastVar === pool.fallback || prev.lastVar === null || (prev.misses ?? 0) >= 1; const scanReserve = @@ -150,12 +149,12 @@ export async function runTick(env, { fetch: rawFetch, now }) { token = await kv.get("token"); cached = Boolean(token); if (!token) await mint(); - const runners = await withToken((t) => gh.getRunners(t, fetchFn)); - const varValue = await withToken((t) => gh.getVar(t, fetchFn)); + const runners = await withToken((t) => gh.getRunners(t, fetchFn, pool)); + const varValue = await withToken((t) => gh.getVar(t, fetchFn, pool)); const canFetch = (n) => budget.canAfford(n + scanReserve); const cursor = prev.cursor ?? 0; scan = await withToken((t) => - gh.scanQueue(t, fetchFn, { cursor, canFetch }), + gh.scanQueue(t, fetchFn, { cursor, canFetch }, pool), ); repoOldest = mergeOldest(scan, prev.repoOldest ?? {}); const times = Object.values(repoOldest); @@ -170,10 +169,13 @@ export async function runTick(env, { fetch: rawFetch, now }) { return; } - const decision = decide(prev, observed); + const decision = decide(prev, observed, { + selfHosted: pool.label, + fallback: pool.fallback, + }); if (decision.setVar) { try { - await withToken((t) => gh.setVar(t, decision.setVar, fetchFn)); + await withToken((t) => gh.setVar(t, decision.setVar, fetchFn, pool)); } catch (e) { // State is not saved, so the next tick sees the same variable and decides again. await skipTick("tick skipped: var write failed", e); @@ -181,7 +183,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { } } // After a down switch, in_progress mimolette jobs stay in the sweep until the rotation covered every repo. - const fallback = decision.next.lastVar === FALLBACK; + const fallback = decision.next.lastVar === pool.fallback; const prevLeft = fallback ? (prev.downSweepLeft ?? 0) : 0; const downSweep = decision.rerunStuck || prevLeft > 0; const downSweepLeft = Math.max( @@ -199,16 +201,14 @@ export async function runTick(env, { fetch: rawFetch, now }) { }), ); if (decision.notify) { - await notify(MESSAGES[decision.notify](decision.next.lastVar)); + await notify(pool.messages[decision.notify](decision.next.lastVar)); } if (skips) { - if (skips.notified) await notify("watchdog ok: ticks are running again."); + if (skips.notified) await notify(pool.messages.ok); await kv.delete("skips"); } if (drill !== null) { - const ok = await notify( - "NOS runner drill: watchdog alert path. No action needed.", - ); + const ok = await notify(pool.messages.drill); await kv.put( "drill-result", JSON.stringify({ @@ -266,7 +266,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { // Plan cancels within the budget: each planned run keeps one call for its cancel. const planned = []; - if (decision.rerunStuck || decision.next.lastVar === FALLBACK) { + if (decision.rerunStuck || decision.next.lastVar === pool.fallback) { const statuses = downSweep ? ["queued", "in_progress"] : ["queued"]; const candidates = []; for (const r of scan.repos) { @@ -288,7 +288,7 @@ export async function runTick(env, { fetch: rawFetch, now }) { if (!r.ok) continue; jobs = r.value; } - if (gh.mimoletteJobs(jobs, statuses).length === 0) continue; + if (gh.mimoletteJobs(jobs, statuses, pool).length === 0) continue; if (!budget.canAfford(RESERVE_FINAL + planned.length + 1)) break; planned.push({ repo: c.repo, @@ -360,10 +360,17 @@ function mergeOldest(scan, carried) { } export default { + // Each cron trigger is one pool, so each pool gets its own invocation and subrequest budget. async scheduled(event, env) { + const pool = poolForCron(event?.cron); + if (!pool) { + log(`unknown cron: ${event.cron}`); + return; + } await runTick(env, { fetch: (url, init) => fetch(url, init), now: event?.scheduledTime ?? Date.now(), + pool, }); }, }; diff --git a/workers/nos-runner-watchdog/src/pools.js b/workers/nos-runner-watchdog/src/pools.js index e0a67ab..1d317e7 100644 --- a/workers/nos-runner-watchdog/src/pools.js +++ b/workers/nos-runner-watchdog/src/pools.js @@ -1,4 +1,4 @@ -// Runner pools the watchdog manages. NOS is the live pool; swmMacos is added dormant (no cron yet in wrangler.toml). +// Runner pools the watchdog manages. Each pool has its own cron in wrangler.toml; scheduled() picks the pool by cron. export const APPS = { nos: { @@ -13,7 +13,7 @@ export const APPS = { }, }; -// NOS texts are copies of index.js MESSAGES; pool_nos_messages_unchanged pins them. Task 2 switches index.js to these. +// NOS texts are the live alert texts, byte for byte; pool_nos_messages_unchanged and the index tests pin them. const NOS_MESSAGES = { down: () => "NOS runner down: NOS_RUNNER set to ubuntu-latest; stuck runs cancelled for re-run.", diff --git a/workers/nos-runner-watchdog/test/pool-index.test.js b/workers/nos-runner-watchdog/test/pool-index.test.js new file mode 100644 index 0000000..c72b5bf --- /dev/null +++ b/workers/nos-runner-watchdog/test/pool-index.test.js @@ -0,0 +1,409 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { fakeFetch, fakeKV, pkcs8Pem, GH, NOW } from "./fakes.js"; +import { + TOPIC, + NTFY, + REPOS, + varUrl, + orgUrl, + repoUrlFor, + fullFor, + jobFor, + worldFor, + bothApps, + setupFor, + st, + keyOf, + stateFor, + pendingFor, + subrequests, +} from "./pool-world.js"; +import worker, { CAP } from "../src/index.js"; +import { POOLS } from "../src/pools.js"; + +const MAC = POOLS.swmMacos; +const NOS = POOLS.nos; +const opKey = (op) => op.slice(op.indexOf(" ") + 1); + +// Runs the scheduled entry with global fetch and console swapped; returns the log lines. +async function runScheduled(event, env, fetchFn) { + const logged = []; + const saved = { + fetch: globalThis.fetch, + log: console.log, + error: console.error, + warn: console.warn, + }; + globalThis.fetch = fetchFn; + console.log = + console.error = + console.warn = + (...a) => logged.push(a.join(" ")); + try { + await worker.scheduled(event, env, { waitUntil() {} }); + } finally { + Object.assign(console, { + log: saved.log, + error: saved.error, + warn: saved.warn, + }); + globalThis.fetch = saved.fetch; + } + return logged; +} + +test("pool_nos_cron_uses_unprefixed_keys", async () => { + const f = fakeFetch(worldFor(NOS)); + const store = fakeKV({ token: "ghs_nos", state: st(NOS) }); + const env = { ...bothApps(), STATE: store }; + await runScheduled({ cron: "*/10 * * * *", scheduledTime: NOW }, env, f.fn); + assert.deepEqual(f.unexpected, []); + assert.ok(store.ops.length > 0); + const allowed = new Set([ + "state", + "token", + "pendingReruns", + "skips", + "drill", + ]); + for (const op of store.ops) assert.ok(allowed.has(opKey(op)), op); + assert.ok(f.calls.every((c) => !c.url.includes("smartwatermelon"))); +}); + +test("pool_macos_keys_all_prefixed", async () => { + const s = setupFor(MAC, worldFor(MAC), { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC), + }); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.ok(s.store.ops.length > 0); + for (const op of s.store.ops) { + assert.ok(opKey(op).startsWith("swm-macos:"), op); + } +}); + +test("pool_macos_never_calls_nos_org", async () => { + const s = setupFor( + MAC, + worldFor(MAC, { runners: [], repos: { a: [{ id: 1, age: 30 }] } }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { misses: 1 }), + }, + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.ok(s.f.calls.length > 0); + for (const c of s.f.calls) + assert.ok(!c.url.includes("nightowlstudiollc"), c.url); +}); + +const claimsOf = (call) => + JSON.parse( + Buffer.from( + call.init.headers.Authorization.split(" ")[1].split(".")[1], + "base64url", + ).toString(), + ); + +test("pool_tokens_not_shared", async () => { + const nosPem = (await pkcs8Pem()).pem; + const swmPem = (await pkcs8Pem()).pem; + const store = fakeKV({}); + const envOver = { APP_KEY_PKCS8: nosPem, SWM_APP_KEY_PKCS8: swmPem }; + const mint = (inst) => `POST ${GH}/app/installations/${inst}/access_tokens`; + const nos = setupFor( + NOS, + worldFor(NOS, { + extra: { [mint(77)]: { status: 201, json: { token: "ghs_nos" } } }, + }), + {}, + envOver, + store, + ); + const mac = setupFor( + MAC, + worldFor(MAC, { + extra: { [mint(88)]: { status: 201, json: { token: "ghs_swm" } } }, + }), + {}, + envOver, + store, + ); + await nos.tick(); + await mac.tick(); + assert.deepEqual(nos.f.unexpected, []); + assert.deepEqual(mac.f.unexpected, []); + assert.equal(store.map.get("token"), "ghs_nos"); + assert.equal(store.map.get("swm-macos:token"), "ghs_swm"); + // Each pool signs its JWT as its own App. + assert.equal(claimsOf(nos.f.calls.find((c) => c.key === mint(77))).iss, "1"); + assert.equal(claimsOf(mac.f.calls.find((c) => c.key === mint(88))).iss, "2"); + const gh = (s) => + s.f.calls.filter( + (c) => c.url.startsWith(GH) && !c.url.includes("access_tokens"), + ); + assert.ok(gh(mac).length > 0 && gh(nos).length > 0); + for (const c of gh(mac)) { + assert.equal(c.init.headers.Authorization, "Bearer ghs_swm", c.key); + } + for (const c of gh(nos)) { + assert.equal(c.init.headers.Authorization, "Bearer ghs_nos", c.key); + } + + // A second macOS tick uses its own cached token, not the NOS one. + const again = setupFor(MAC, worldFor(MAC), {}, envOver, store); + await again.tick(); + for (const c of gh(again)) { + assert.equal(c.init.headers.Authorization, "Bearer ghs_swm", c.key); + } +}); + +test("pool_macos_unconfigured_does_nothing", async () => { + const s = setupFor(MAC, worldFor(MAC, { runners: [] }), { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { misses: 1 }), + }); + delete s.env.SWM_APP_KEY_PKCS8; + const logged = []; + const saved = console.log; + console.log = (...a) => logged.push(a.join(" ")); + try { + await s.tick(); + } finally { + console.log = saved; + } + assert.equal(s.f.calls.length, 0); + assert.equal(s.store.ops.length, 0); + assert.equal(s.store.map.has(keyOf(MAC, "skips")), false); + assert.equal(logged.length, 1); +}); + +test("pool_macos_down_switches_and_alerts", async () => { + const s = setupFor( + MAC, + worldFor(MAC, { + runners: [], + repos: { + a: [ + { id: 1, age: 30 }, + { id: 2, age: 5 }, + ], + }, + }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { misses: 1 }), + }, + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + const patch = s.f.calls.filter( + (c) => + c.key === + `PATCH ${GH}/orgs/smartwatermelon/actions/variables/SWM_MACOS_RUNNER`, + ); + assert.equal(patch.length, 1); + assert.equal(JSON.parse(patch[0].init.body).value, "macos-latest"); + const alerts = s.f.calls.filter((c) => c.key === NTFY); + assert.equal(alerts.length, 1); + assert.equal(alerts[0].init.body, MAC.messages.down()); + const cancels = s.f.calls + .filter((c) => c.key.endsWith("/cancel")) + .map((c) => c.url) + .sort(); + assert.deepEqual(cancels, [ + `${repoUrlFor(MAC, "a")}/1/cancel`, + `${repoUrlFor(MAC, "a")}/2/cancel`, + ]); + assert.deepEqual( + pendingFor(MAC, s.store) + .map((p) => p.runId) + .sort(), + [1, 2], + ); + assert.equal(pendingFor(MAC, s.store)[0].repo, fullFor(MAC, "a")); + assert.equal(stateFor(MAC, s.store).lastVar, "macos-latest"); + assert.equal(s.store.map.has("pendingReruns"), false); + assert.equal(s.store.map.has("state"), false); +}); + +test("pool_macos_set_var_visibility_all", async () => { + const s = setupFor( + MAC, + worldFor(MAC, { + varValue: "macos-latest", + extra: { + [`PATCH ${varUrl(MAC)}`]: { status: 404 }, + [`POST ${orgUrl(MAC)}/actions/variables`]: { status: 201 }, + }, + }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { lastVar: "macos-latest", goods: 1 }), + }, + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + const post = s.f.calls.find( + (c) => c.key === `POST ${orgUrl(MAC)}/actions/variables`, + ); + assert.deepEqual(JSON.parse(post.init.body), { + name: "SWM_MACOS_RUNNER", + value: "mimolette-macos", + visibility: "all", + }); + const alert = s.f.calls.find((c) => c.key === NTFY); + assert.equal(alert.init.body, MAC.messages.recovered()); +}); + +test("pool_macos_ignores_mimolette_jobs", async () => { + const nosJob = (status) => + jobFor(NOS, { + status, + created_at: new Date(NOW - 50 * 60000).toISOString(), + }); + // Healthy pool, idle runners: a NOS-label job 50 minutes old must not count as queued. + const healthy = setupFor( + MAC, + worldFor(MAC, { + repos: { a: [{ id: 1, age: 50, jobs: [nosJob("queued")] }] }, + }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC), + }, + ); + await healthy.tick(); + assert.deepEqual(healthy.f.unexpected, []); + assert.equal(stateFor(MAC, healthy.store).misses, 0); + assert.deepEqual(stateFor(MAC, healthy.store).repoOldest, {}); + + // On the fallback the sweep runs, and still leaves the NOS-label run alone. + const sweep = setupFor( + MAC, + worldFor(MAC, { + varValue: "macos-latest", + repos: { a: [{ id: 1, age: 50, jobs: [nosJob("queued")] }] }, + }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { lastVar: "macos-latest" }), + }, + ); + await sweep.tick(); + assert.deepEqual(sweep.f.unexpected, []); + assert.equal( + sweep.f.calls.filter((c) => c.key.endsWith("/cancel")).length, + 0, + ); + assert.deepEqual(pendingFor(MAC, sweep.store), []); +}); + +const tenByFive = () => { + const repos = {}; + for (let r = 0; r < 10; r += 1) { + repos[`r${r}`] = Array.from({ length: 5 }, (_, i) => ({ + id: r * 10 + i, + age: 30 - i, + })); + } + return repos; +}; + +test("pool_macos_subrequests_at_most_40", async () => { + const s = setupFor( + MAC, + worldFor(MAC, { + runners: [], + repos: tenByFive(), + inProgress: Object.fromEntries( + Object.keys(tenByFive()).map((r) => [r, []]), + ), + }), + { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC, { misses: 1 }), + }, + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.ok(subrequests(s) <= CAP, `subrequests ${subrequests(s)}`); + assert.equal( + s.f.calls.filter((c) => c.key === `PATCH ${varUrl(MAC)}`).length, + 1, + ); + assert.equal(s.f.calls.filter((c) => c.key === NTFY).length, 1); + assert.equal(stateFor(MAC, s.store).lastVar, "macos-latest"); +}); + +test("pool_macos_drill_prefixed", async () => { + const s = setupFor(MAC, worldFor(MAC), { + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC), + [keyOf(MAC, "drill")]: "1", + drill: "1", + }); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + const alerts = s.f.calls.filter((c) => c.key === NTFY); + assert.equal(alerts.length, 1); + assert.equal(alerts[0].init.body, MAC.messages.drill); + const result = JSON.parse(s.store.map.get("swm-macos:drill-result")); + assert.equal(result.ok, true); + assert.equal(s.store.map.has("swm-macos:drill"), false); + assert.equal(s.store.map.get("drill"), "1"); + assert.equal(s.store.map.has("drill-result"), false); +}); + +test("pool_unknown_cron_does_nothing", async () => { + const f = fakeFetch(worldFor(NOS)); + const store = fakeKV({ token: "ghs_nos", state: st(NOS) }); + const env = { ...bothApps(), STATE: store }; + const logged = await runScheduled( + { cron: "0 * * * *", scheduledTime: NOW }, + env, + f.fn, + ); + assert.equal(f.calls.length, 0); + assert.equal(store.ops.length, 0); + assert.equal(logged.length, 1); + assert.match(logged[0], /unknown cron/); +}); + +test("pool_scheduled_logs_no_secrets", async () => { + const f = fakeFetch( + worldFor(MAC, { + runners: [], + extra: { [`PATCH ${varUrl(MAC)}`]: { status: 500 } }, + }), + ); + const store = fakeKV({ + [keyOf(MAC, "token")]: "ghs_swm_cached", + [keyOf(MAC, "state")]: st(MAC, { misses: 1 }), + }); + const env = { ...bothApps(), STATE: store }; + const logged = await runScheduled( + { cron: MAC.cron, scheduledTime: NOW }, + env, + f.fn, + ); + assert.ok(f.calls.length > 0); + assert.ok(f.calls.some((c) => c.key === `PATCH ${varUrl(MAC)}`)); + assert.ok(logged.length > 0); + for (const line of logged) { + for (const secret of [TOPIC, "ghs_swm_cached", env.SWM_APP_KEY_PKCS8]) { + assert.ok(!line.includes(secret), line); + } + } +}); + +test("pool_world_repos_route_present", () => { + // Guards the fixture: the macOS world lists swm repos only. + const w = worldFor(MAC, { repos: { a: [] } }); + assert.deepEqual(w[REPOS].json.repositories, [ + { full_name: "smartwatermelon/a" }, + ]); +}); diff --git a/workers/nos-runner-watchdog/test/pool-world.js b/workers/nos-runner-watchdog/test/pool-world.js new file mode 100644 index 0000000..0a14f80 --- /dev/null +++ b/workers/nos-runner-watchdog/test/pool-world.js @@ -0,0 +1,126 @@ +// Fixtures for any pool: world() and setup() from world.js, with the org, variable and label taken from the pool. +import { fakeFetch, fakeKV, minutesAgo, GH, NOW } from "./fakes.js"; +import { runTick } from "../src/index.js"; + +export const TOPIC = "topic-secret"; +export const NTFY = `POST https://ntfy.sh/${TOPIC}`; +export const orgUrl = (pool) => `${GH}/orgs/${pool.org}`; +export const varUrl = (pool) => + `${orgUrl(pool)}/actions/variables/${pool.variable}`; +export const runnersKey = (pool) => + `GET ${orgUrl(pool)}/actions/runners?per_page=100`; +export const REPOS = `GET ${GH}/installation/repositories?per_page=100`; +export const fullFor = (pool, r) => `${pool.org}/${r}`; +export const repoUrlFor = (pool, r) => + `${GH}/repos/${fullFor(pool, r)}/actions/runs`; + +export const runnerFor = (pool, name, busy, over = {}) => ({ + name, + busy, + status: "online", + labels: [ + { id: 1, name: "self-hosted", type: "read-only" }, + { id: 2, name: pool.label, type: "custom" }, + ], + ...over, +}); + +export const jobFor = (pool, over = {}) => ({ + id: 1, + status: "queued", + labels: [pool.label], + created_at: minutesAgo(1), + ...over, +}); + +// Same shape as world(): repos/inProgress {name: [{id, age, jobs?, attempt?}]}; jobs default to one pool-label job. +export function worldFor( + pool, + { + varValue = pool.label, + runners = [runnerFor(pool, "a", false), runnerFor(pool, "b", false)], + repos = {}, + inProgress = {}, + extra = {}, + } = {}, +) { + const names = [ + ...new Set([...Object.keys(repos), ...Object.keys(inProgress)]), + ]; + const routes = { + [runnersKey(pool)]: { json: { runners } }, + [`GET ${varUrl(pool)}`]: + varValue === null + ? { status: 404 } + : { json: { name: pool.variable, value: varValue } }, + [REPOS]: { + json: { + repositories: names.map((r) => ({ full_name: fullFor(pool, r) })), + }, + }, + [`PATCH ${varUrl(pool)}`]: { status: 204 }, + [NTFY]: { status: 200 }, + }; + const addRuns = (r, list, status) => { + routes[ + `GET ${repoUrlFor(pool, r)}?status=${status}&per_page=100&exclude_pull_requests=true` + ] = { + json: { + workflow_runs: list.map((x) => ({ + id: x.id, + created_at: minutesAgo(x.age), + run_attempt: x.attempt ?? 1, + })), + }, + }; + for (const x of list) { + const jobs = x.jobs ?? [ + jobFor(pool, { + status: status === "queued" ? "queued" : "in_progress", + created_at: minutesAgo(x.age), + }), + ]; + routes[`GET ${repoUrlFor(pool, r)}/${x.id}/jobs?per_page=100`] = { + json: { jobs }, + }; + routes[`POST ${repoUrlFor(pool, r)}/${x.id}/cancel`] = { status: 202 }; + } + }; + for (const r of names) { + addRuns(r, repos[r] ?? [], "queued"); + addRuns(r, inProgress[r] ?? [], "in_progress"); + } + return { ...routes, ...extra }; +} + +// Both App sets: NOS installation 77, swm installation 88. +export const bothApps = () => ({ + APP_ID: "1", + INSTALLATION_ID: "77", + APP_KEY_PKCS8: "not-a-key", + SWM_APP_ID: "2", + SWM_INSTALLATION_ID: "88", + SWM_APP_KEY_PKCS8: "not-a-swm-key", + NTFY_TOPIC: TOPIC, +}); + +export function setupFor(pool, routes, kv = {}, envOver = {}, store = null) { + const f = fakeFetch(routes); + const s = store ?? fakeKV(kv); + const env = { ...bothApps(), STATE: s, ...envOver }; + return { + f, + store: s, + env, + tick: (now = NOW) => runTick(env, { fetch: f.fn, now, pool }), + }; +} + +export const st = (pool, o) => + JSON.stringify({ lastVar: pool.label, misses: 0, goods: 0, ...o }); +export const keyOf = (pool, k) => `${pool.prefix}${k}`; +export const stateFor = (pool, store) => + JSON.parse(store.map.get(keyOf(pool, "state"))); +export const pendingFor = (pool, store) => + JSON.parse(store.map.get(keyOf(pool, "pendingReruns")) ?? "[]"); +export const subrequests = (s) => s.f.calls.length + s.store.ops.length; diff --git a/workers/nos-runner-watchdog/test/pools.test.js b/workers/nos-runner-watchdog/test/pools.test.js index 1b7cbcf..f4603b8 100644 --- a/workers/nos-runner-watchdog/test/pools.test.js +++ b/workers/nos-runner-watchdog/test/pools.test.js @@ -104,6 +104,6 @@ test("pool_wrangler_crons_match", () => { const m = toml.match(/^crons\s*=\s*\[([^\]]*)\]/m); assert.ok(m, "crons array present"); const crons = [...m[1].matchAll(/"([^"]*)"/g)].map((x) => x[1]); - assert.ok(crons.length > 0); - for (const c of crons) assert.notEqual(poolForCron(c), null, c); + const want = Object.values(POOLS).map((p) => p.cron); + assert.deepEqual([...crons].sort(), [...want].sort()); }); diff --git a/workers/nos-runner-watchdog/wrangler.toml b/workers/nos-runner-watchdog/wrangler.toml index 37e3376..4e53a37 100644 --- a/workers/nos-runner-watchdog/wrangler.toml +++ b/workers/nos-runner-watchdog/wrangler.toml @@ -5,11 +5,11 @@ compatibility_date = "2026-11-01" workers_dev = false [triggers] -crons = ["*/10 * * * *"] +crons = ["*/10 * * * *", "5,15,25,35,45,55 * * * *"] # Namespace nos-runner-watchdog-state, created 2026-11-12 on the nightowlstudio account. [[kv_namespaces]] binding = "STATE" id = "ddbff24fed0048d8b3cdce120f846bb9" -# Secrets, set at deploy: APP_ID, INSTALLATION_ID, APP_KEY_PKCS8, NTFY_TOPIC. +# Secrets: NTFY_TOPIC; NOS APP_ID, INSTALLATION_ID, APP_KEY_PKCS8; macOS SWM_APP_ID, SWM_INSTALLATION_ID, SWM_APP_KEY_PKCS8. From e8183711b22c4879dafdb96991b300ea2eda78e7 Mon Sep 17 00:00:00 2001 From: Claude Code Bot Date: Mon, 23 Nov 2026 17:02:30 -0800 Subject: [PATCH 2/2] fix(nos-runner-watchdog): only optional pools go quiet without secrets The previous commit made every pool return silently when any App secret was missing. For NOS that would turn a lost secret into a silent watchdog. NOS must keep the old path: the mint fails, the tick counts a skip and sends the skip alert. POOLS.swmMacos now has optional: true. Only an optional pool takes the silent return. Other pools mint from their own App's raw secret values, as before, so NOS with a missing secret behaves as on origin/main. pool_nos_missing_secret_keeps_old_path pins that. Advances #252 --- workers/nos-runner-watchdog/src/index.js | 15 +++++-- workers/nos-runner-watchdog/src/pools.js | 2 + .../test/pool-index.test.js | 40 +++++++++++++++++++ 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/workers/nos-runner-watchdog/src/index.js b/workers/nos-runner-watchdog/src/index.js index c97bf29..f2deb49 100644 --- a/workers/nos-runner-watchdog/src/index.js +++ b/workers/nos-runner-watchdog/src/index.js @@ -1,6 +1,6 @@ import { decide } from "./decide.js"; import * as gh from "./github.js"; -import { POOLS, poolForCron, appEnv } from "./pools.js"; +import { APPS, POOLS, poolForCron, appEnv } from "./pools.js"; // Free plan allows 50 subrequests a run; KV calls are counted too, for headroom. export const CAP = 40; @@ -38,12 +38,19 @@ function makeBudget(cap) { /** One tick for one pool. deps: {fetch, now, pool}. Every fetch and KV call is counted against CAP. */ export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) { - // An unconfigured pool touches nothing: no fetch, no KV, not even the skips counter. + // An optional pool without its App secrets touches nothing: no fetch, no KV, not even the skips counter. const app = appEnv(env, pool); - if (!app) { + if (!app && pool.optional) { log(`pool ${pool.id} not configured: App secrets missing`); return; } + // Other pools mint from their own App's raw values, so a missing secret fails the mint and goes through skipTick. + const a = APPS[pool.app]; + const creds = app ?? { + APP_ID: env[a.idKey], + INSTALLATION_ID: env[a.installKey], + APP_KEY_PKCS8: env[a.keyKey], + }; const budget = makeBudget(CAP); const fetchFn = (url, init) => { budget.take(); @@ -117,7 +124,7 @@ export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) { let token = null; let cached = false; const mint = async () => { - token = await gh.appToken(app, fetchFn, now); + token = await gh.appToken(creds, fetchFn, now); cached = false; await kv.put("token", token, { expirationTtl: TOKEN_TTL }); }; diff --git a/workers/nos-runner-watchdog/src/pools.js b/workers/nos-runner-watchdog/src/pools.js index 1d317e7..c5820e3 100644 --- a/workers/nos-runner-watchdog/src/pools.js +++ b/workers/nos-runner-watchdog/src/pools.js @@ -65,6 +65,8 @@ export const POOLS = { prefix: "swm-macos:", cron: "5,15,25,35,45,55 * * * *", rerunLost: true, + // Optional: with any App secret missing the tick goes quiet. NOS is not optional, so a lost secret stays loud. + optional: true, messages: MACOS_MESSAGES, }, }; diff --git a/workers/nos-runner-watchdog/test/pool-index.test.js b/workers/nos-runner-watchdog/test/pool-index.test.js index c72b5bf..c29fb4c 100644 --- a/workers/nos-runner-watchdog/test/pool-index.test.js +++ b/workers/nos-runner-watchdog/test/pool-index.test.js @@ -161,6 +161,46 @@ test("pool_tokens_not_shared", async () => { } }); +// NOS is not optional: a lost secret must stay loud (skips counter, skip alert), exactly as before pools existed. +test("pool_nos_missing_secret_keeps_old_path", async () => { + const noToken = setupFor(NOS, worldFor(NOS), { + state: st(NOS), + skips: JSON.stringify({ count: 2, notified: false }), + }); + delete noToken.env.APP_KEY_PKCS8; + await noToken.tick(); + assert.deepEqual(noToken.store.ops, [ + "get state", + "get pendingReruns", + "get skips", + "get drill", + "get token", + "put skips", + ]); + assert.deepEqual(JSON.parse(noToken.store.map.get("skips")), { + count: 3, + notified: true, + }); + assert.deepEqual( + noToken.f.calls.map((c) => [c.key, c.init.body]), + [[NTFY, "watchdog skipping: network"]], + ); + + // With a cached token the tick still runs in full. + const cached = setupFor(NOS, worldFor(NOS), { + token: "ghs_nos", + state: st(NOS), + }); + delete cached.env.APP_KEY_PKCS8; + await cached.tick(); + assert.deepEqual(cached.f.unexpected, []); + assert.ok(cached.f.calls.length > 0); + assert.deepEqual( + cached.store.puts.map((p) => p.key), + ["state"], + ); +}); + test("pool_macos_unconfigured_does_nothing", async () => { const s = setupFor(MAC, worldFor(MAC, { runners: [] }), { [keyOf(MAC, "token")]: "ghs_swm",