From 7d1867877da9c4de0395f06e91d5f7ab430a031e Mon Sep 17 00:00:00 2001 From: w4ffl35 <25737761+w4ffl35@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:57:30 -0700 Subject: [PATCH 1/4] Fleet test skip: name bridge path, shared probe + regression tests (#180) --- .../__tests__/fleet-test-source.test.ts | 112 ++++++++++++++++++ .../__tests__/fleet-test-source.ts | 2 +- .../fleet-budget-integration.test.ts | 36 ++---- 3 files changed, 120 insertions(+), 30 deletions(-) create mode 100644 src/campaigncontrol/__tests__/fleet-test-source.test.ts diff --git a/src/campaigncontrol/__tests__/fleet-test-source.test.ts b/src/campaigncontrol/__tests__/fleet-test-source.test.ts new file mode 100644 index 0000000..8645f09 --- /dev/null +++ b/src/campaigncontrol/__tests__/fleet-test-source.test.ts @@ -0,0 +1,112 @@ +import assert from "node:assert/strict" +import * as fs from "node:fs/promises" +import * as os from "node:os" +import * as path from "node:path" +import { + isFleetTestSourceAvailable, + requiredFleetTestRoot, + shouldSkipFleetTest, +} from "./fleet-test-source.js" +import { runMain, type SuiteTest } from "../../test-runner.js" + +const ENV_KEY = "FLEET_SECURITY_WATCH_TEST_ROOT" +const BRIDGE_REL = path.join("operations", "campaign_budget_bridge.py") + +async function withEnv( + value: string | undefined, + fn: () => void | Promise, +): Promise { + const saved = process.env[ENV_KEY] + try { + if (value === undefined) delete process.env[ENV_KEY] + else process.env[ENV_KEY] = value + await fn() + } finally { + if (saved === undefined) delete process.env[ENV_KEY] + else process.env[ENV_KEY] = saved + } +} + +interface StagedRoot { root: string; cleanup: () => Promise } + +async function stagedRoot(): Promise { + const root = await fs.mkdtemp( + path.join(os.tmpdir(), "hcl-fleet-probe-")) + await fs.mkdir(path.join(root, "operations"), { recursive: true }) + await fs.writeFile(path.join(root, BRIDGE_REL), "# staged bridge fixture\n") + return { root, cleanup: () => fs.rm(root, { recursive: true, force: true }) } +} + +function captureLog(fn: () => boolean): { skipped: boolean; lines: string[] } { + const lines: string[] = [] + const original = console.log + console.log = (message?: unknown): void => { + lines.push(String(message)) + } + try { + return { skipped: fn(), lines } + } finally { + console.log = original + } +} + +async function unsetEnvSkipsWithOneLine(): Promise { + await withEnv(undefined, () => { + assert.equal(isFleetTestSourceAvailable(), false) + const { skipped, lines } = captureLog(() => shouldSkipFleetTest("probe")) + assert.equal(skipped, true) + assert.equal(lines.length, 1) + assert.match(lines[0], /^SKIP probe: Fleet source not staged$/) + assert.throws(() => requiredFleetTestRoot(), /staging step/) + }) +} + +async function bogusPathFailsNamingBridge(): Promise { + const bogus = path.join(os.tmpdir(), "hcl-fleet-definitely-absent") + await withEnv(bogus, () => { + assert.equal(isFleetTestSourceAvailable(), false) + assert.throws( + () => requiredFleetTestRoot(), + new RegExp(`unavailable at.*${"campaign_budget_bridge\\.py"}`), + ) + assert.throws(() => shouldSkipFleetTest("probe"), /campaign_budget_bridge/) + }) +} + +async function filePathFailsWithoutCrash(): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "hcl-fleet-file-")) + const file = path.join(dir, "not-a-directory") + try { + await fs.writeFile(file, "digest") + await withEnv(file, () => { + assert.equal(isFleetTestSourceAvailable(), false) + assert.throws(() => requiredFleetTestRoot(), /campaign_budget_bridge/) + }) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +} + +async function stagedSourceRunsWithoutSkip(): Promise { + const { root, cleanup } = await stagedRoot() + try { + await withEnv(root, () => { + assert.equal(isFleetTestSourceAvailable(), true) + assert.equal(requiredFleetTestRoot(), path.resolve(root)) + const { skipped, lines } = captureLog(() => shouldSkipFleetTest("probe")) + assert.equal(skipped, false) + assert.deepEqual(lines, []) + }) + } finally { + await cleanup() + } +} + +const tests: readonly SuiteTest[] = [ + ["unset env skips with one line", unsetEnvSkipsWithOneLine], + ["missing bridge fails naming the bridge", bogusPathFailsNamingBridge], + ["file path fails without a crash", filePathFailsWithoutCrash], + ["staged source never skips", stagedSourceRunsWithoutSkip], +] + +runMain("fleet-test-source", tests) diff --git a/src/campaigncontrol/__tests__/fleet-test-source.ts b/src/campaigncontrol/__tests__/fleet-test-source.ts index 2435a62..ca0fe28 100644 --- a/src/campaigncontrol/__tests__/fleet-test-source.ts +++ b/src/campaigncontrol/__tests__/fleet-test-source.ts @@ -57,7 +57,7 @@ export function requiredFleetTestRoot(): string { const root = path.resolve(configured) const bridge = path.join(root, "operations/campaign_budget_bridge.py") if (!existsSync(bridge)) { - throw new Error(`Required Fleet test bridge is unavailable at ${root}`) + throw new Error(`Required Fleet test bridge is unavailable at ${bridge}`) } return root } diff --git a/src/rsi/__tests__/fleet-budget-integration.test.ts b/src/rsi/__tests__/fleet-budget-integration.test.ts index 0e562a1..3fa7de0 100644 --- a/src/rsi/__tests__/fleet-budget-integration.test.ts +++ b/src/rsi/__tests__/fleet-budget-integration.test.ts @@ -1,7 +1,6 @@ import assert from "node:assert/strict" import { createHash } from "node:crypto" import { spawnSync } from "node:child_process" -import { existsSync } from "node:fs" import * as fs from "node:fs/promises" import * as os from "node:os" import * as path from "node:path" @@ -9,20 +8,11 @@ import { test } from "node:test" import { FleetBudgetInferenceLedger } from "../fleet-budget-ledger.js" import { RSI_MUSE_OPENROUTER_BILLING_MODEL, RSI_MUSE_OPENROUTER_MODEL, startOpenRouterBroker } from "../inference-broker.js" import type { OpenRouterBrokerLimits } from "../inference-broker.js" +import { requiredFleetTestRoot, shouldSkipFleetTest } from "../../campaigncontrol/__tests__/fleet-test-source.js" -// fleetSourceRoot (below) throws when no private Fleet checkout is -// present; probe it here so the file SKIPs instead of failing. Function -// declarations hoist, so calling it before its definition is safe. -let fleetSourcePresent = true -try { - fleetSourceRoot() -} catch { - fleetSourcePresent = false -} -if (!fleetSourcePresent) { - console.log("SKIP fleet-budget integration: private source absent") - process.exit(0) -} +// Shared probe (#180): SKIP (exit 0) when the private Fleet source is +// not staged; throw naming the bridge when the env root is misconfigured. +if (shouldSkipFleetTest("fleet-budget integration")) process.exit(0) const fakeKey = "fleet-integration-private-test-key" const keyIdentity = createHash("sha256").update(fakeKey).digest("hex") @@ -48,22 +38,10 @@ function setupPaths(home: string) { return { campaign, control, credential: path.join(campaign, "test-key"), config: path.join(campaign, "config.json"), controlFile: path.join(control, "control.json") } } -function isPrivateFleetSource(root: string): boolean { - const bridge = path.join(root, "operations", "campaign_budget_bridge.py") - if (!existsSync(bridge) || !existsSync(path.join(root, "operations", "campaign_budget.py"))) return false - const remote = spawnSync("git", ["remote", "get-url", "origin"], { cwd: root, encoding: "utf8", timeout: 2_000 }) - return remote.status === 0 && /^(?:git@github\.com:Capsize-Games\/fleet-security-watch\.git|https:\/\/github\.com\/Capsize-Games\/fleet-security-watch\.git)$/.test(remote.stdout.trim()) -} - function fleetSourceRoot(): string { - const candidates = [ - path.resolve(process.cwd(), "../fleet-security-watch"), - path.resolve(process.cwd(), "../../fleet-security-watch"), - path.join(os.homedir(), "Projects", "fleet-security-watch"), - ] - const root = candidates.find(isPrivateFleetSource) - if (!root) throw new Error("private Fleet source checkout is unavailable for the real-bridge integration test") - return root + // Shared staged root (#180): the CI staging step sets + // FLEET_SECURITY_WATCH_TEST_ROOT; entry already skipped when unset. + return requiredFleetTestRoot() } async function privateDir(directory: string) { await fs.mkdir(directory, { recursive: true, mode: 0o700 }); await fs.chmod(directory, 0o700) } From f6f32b25d9babff5ecf7cda0052fb0970dc2b76a Mon Sep 17 00:00:00 2001 From: w4ffl35 <25737761+w4ffl35@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:00:17 -0700 Subject: [PATCH 2/4] Dashboard startup warns when control-plane token is unset (#187) --- src/dashboard/__tests__/server.test.ts | 117 ++++++++++++++++++++++--- src/dashboard/server.ts | 25 ++++++ 2 files changed, 130 insertions(+), 12 deletions(-) diff --git a/src/dashboard/__tests__/server.test.ts b/src/dashboard/__tests__/server.test.ts index e59e2e5..bfd4e90 100644 --- a/src/dashboard/__tests__/server.test.ts +++ b/src/dashboard/__tests__/server.test.ts @@ -14,7 +14,7 @@ import * as os from "node:os" import * as path from "node:path" import { setTimeout as sleep } from "node:timers/promises" -import { startDashboardServer } from "../server.js" +import { startDashboardServer, warnControlPlaneAuth } from "../server.js" import type { Server } from "node:http" import { eventsFilePath } from "../../engine/events.js" import { runMain } from "../../test-runner.js" @@ -347,17 +347,110 @@ async function testNonGetPostMethodsStillRejected(): Promise { // ─── Runner ────────────────────────────────────────────────────────────────── -const tests: Array<[string, () => Promise]> = [ - ["server: GET /api/session/:id/events returns the feed + nextOffset", testEventsEndpointReturnsFeedWithNextOffset], - ["server: events endpoint is incremental via ?since=", testEventsEndpointIncrementalSince], - ["server: events endpoint requires repo (param or --repo)", testEventsEndpointMissingRepoParam], - ["server: events endpoint for an unknown session -> empty feed, 200", testEventsEndpointMissingSessionIsEmpty], - ["server: POST pause/resume write/remove .harness.pause-requested in the worktree", testPauseResumeWriteRemoveMarker], - ["server: POST pause for an unknown session -> 404", testPauseUnknownSessionIs404], - ["server: POST /message writes the .harness.inject-message marker (text + injectedAt)", testMessageEndpointWritesMarker], - ["server: POST /message validates + rejects unknown sessions (404/400/405)", testMessageEndpointValidatesAndRejectsUnknown], - ["server: POST /message respects the same optional bearer-token gate as pause/answer", testMessageEndpointRespectsAuthGate], - ["server: non-GET/non-POST methods to unrelated routes are still rejected (405)", testNonGetPostMethodsStillRejected], +/** Capture stderr written during fn(). */ +function captureStderr(fn: () => void): string { + let output = "" + const orig = process.stderr.write.bind(process.stderr) + const spy = ((chunk: unknown): boolean => { + output += String(chunk) + return true + }) as typeof process.stderr.write + process.stderr.write = spy + try { + fn() + return output + } finally { + process.stderr.write = orig + } +} + +/** Capture stderr across an async fn(). */ +async function captureStderrAsync( + fn: () => Promise, +): Promise { + let output = "" + const orig = process.stderr.write.bind(process.stderr) + const spy = ((chunk: unknown): boolean => { + output += String(chunk) + return true + }) as typeof process.stderr.write + process.stderr.write = spy + try { + await fn() + return output + } finally { + process.stderr.write = orig + } +} + +function testWarnWithoutTokenNamesRiskAndLoopback(): void { + const output = captureStderr(() => warnControlPlaneAuth({})) + assert.match(output, /WARNING/) + assert.match(output, /unauthenticated/) + assert.match(output, /127\.0\.0\.1/) + assert.match(output, /HEADLESSCODE_DASHBOARD_TOKEN/) +} + +function testWarnWithTokenGatesWithoutLeaking(): void { + const out = captureStderr( + () => warnControlPlaneAuth({ token: "sekret-token-value" })) + assert.match(out, /gated/) + assert.ok(!out.includes("sekret-token-value")) + assert.ok(!out.includes("WARNING")) +} + +function testWarnEmptyStringCountsAsUnset(): void { + // Compose ships the token as "" — cli.ts maps that to undefined, + // so the empty string must take the warning path here too. + const output = captureStderr(() => warnControlPlaneAuth({ token: "" })) + assert.match(output, /WARNING/) +} + +async function testStartupWithoutTokenWarns(): Promise { + const dir = await tmpRepo() + const output = await captureStderrAsync(async () => { + const { server, port } = await startServer(dir) + try { + const { status } = await getJson( + `http://127.0.0.1:${port}`, "/api/summary") + assert.ok(status === 200 || status === 500) + } finally { + server.close() + } + }) + await fs.rm(dir, { recursive: true, force: true }) + assert.match(output, /WARNING/) + assert.match(output, /unauthenticated/) +} + +async function testStartupWithTokenShowsGated(): Promise { + const repo = await tmpRepo() + const output = await captureStderrAsync(async () => { + const server = await startDashboardServer( + { port: 0, repo, token: "sekret" }) + server.close() + }) + await fs.rm(repo, { recursive: true, force: true }) + assert.match(output, /gated/) + assert.ok(!output.includes("sekret")) +} + +const tests: Array<[string, () => void | Promise]> = [ + ["server: events feed", testEventsEndpointReturnsFeedWithNextOffset], + ["server: events incremental via since", testEventsEndpointIncrementalSince], + ["server: events require repo", testEventsEndpointMissingRepoParam], + ["server: unknown session feed", testEventsEndpointMissingSessionIsEmpty], + ["server: pause/resume marker", testPauseResumeWriteRemoveMarker], + ["server: pause unknown 404", testPauseUnknownSessionIs404], + ["server: POST /message writes marker", testMessageEndpointWritesMarker], + ["server: message validates", testMessageEndpointValidatesAndRejectsUnknown], + ["server: POST /message respects auth", testMessageEndpointRespectsAuthGate], + ["server: rejected methods 405", testNonGetPostMethodsStillRejected], + ["server: warn loopback", testWarnWithoutTokenNamesRiskAndLoopback], + ["server: warn no leak", testWarnWithTokenGatesWithoutLeaking], + ["server: empty-string token warns", testWarnEmptyStringCountsAsUnset], + ["server: startup without token warns", testStartupWithoutTokenWarns], + ["server: startup with token shows gated", testStartupWithTokenShowsGated], ] runMain("dashboard server", tests) diff --git a/src/dashboard/server.ts b/src/dashboard/server.ts index 642ff50..c56336c 100644 --- a/src/dashboard/server.ts +++ b/src/dashboard/server.ts @@ -194,6 +194,30 @@ export interface DashboardServerOptions { stopGraceMs?: number } +/** + * Emit the control-plane auth status once at startup (#187). No token + * (including the empty-string compose failure mode) means every control + * route is unauthenticated loopback-only — loud on stderr, not silent. + * Never prints the token itself. + */ +export function warnControlPlaneAuth(options: { token?: string }): void { + if (options.token) { + process.stderr.write( + "[dashboard] control-plane routes are gated " + + "by HEADLESSCODE_DASHBOARD_TOKEN\n", + ) + return + } + process.stderr.write( + "[dashboard] WARNING: no HEADLESSCODE_DASHBOARD_TOKEN set — " + + "control-plane routes (POST /api/session/*, " + + "POST /api/tool/execute, POST /api/checkpoints/restore, " + + "settings writes) are unauthenticated. " + + "Bound to 127.0.0.1 only. " + + "Set HEADLESSCODE_DASHBOARD_TOKEN to gate them.\n", + ) +} + /** Start the dashboard HTTP server. Resolves once it's listening. */ export function startDashboardServer(options: DashboardServerOptions): Promise { const server = http.createServer((req, res) => { @@ -218,6 +242,7 @@ export function startDashboardServer(options: DashboardServerOptions): Promise { server.removeListener("error", reject) + warnControlPlaneAuth(options) resolve(server) }) }) From f0a5ce4f4b5e63bbc8e87ddc6591cbd5167ddec3 Mon Sep 17 00:00:00 2001 From: w4ffl35 <25737761+w4ffl35@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:01:57 -0700 Subject: [PATCH 3/4] Document test tiers 0-4 so a red run is diagnosable (#181) --- CONTRIBUTING.md | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1213d36..42a76c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,6 +61,39 @@ suite detects the missing binary, prints a clear skip message, and exits 0 spawn/watch/review flows against a local mock LLM server, not just unit-level logic. +## Testing + +`npm test` is fail-fast over every `src/**/*.test.ts` file: the first +failure stops the run, so a red line early in the output can hide hundreds +of unrun files behind it. The tiers below already exist implicitly — this +table names them so a red run is diagnosable without guessing which +external dependency a failure needs. + +| Tier | Command | Needs | Time | A failure means | +| --- | --- | --- | --- | --- | +| 0 — typecheck | `npx tsc --noEmit` | Nothing (no deps beyond `npm install`) | ~1 min | A real type error in `src/`; fix the code, never silence with `any` / `@ts-ignore` / `!`. | +| 1 — unit + fake tests | `npm test` (full) or `npm test -- ` / `npx tsx ` while iterating | Nothing: no network, no key, no private source | Minutes (~~330 files, fail-fast) | A real regression — unless the line says `SKIP`, see below. | +| 2 — private Fleet integration | Same `npm test` run, files matching `fleet` / `repository-budget-v2` | Staged `FLEET_SECURITY_WATCH_TEST_ROOT` (private CI only, via `scripts/stage-fleet-test-source.mjs`) | Skips in seconds without it | `SKIP