Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 -- <substring>` / `npx tsx <test-file>` 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 <label>: Fleet source not staged` + exit 0 = expected on a public checkout, not a failure. A hard error naming `operations/campaign_budget_bridge.py` = the env var is set but points nowhere usable (misconfiguration, not absence). |
| 3 — e2e shells | `bash scripts/e2e/run.sh` (Phase 1 CLI vs mock OpenRouter); `scripts/e2e-phase*/run.sh` for orchestrator / watcher / QA / deploy flows | `npm install` only; mock server is local, no key, no network | Minutes each | The harness/CLI contract broke end-to-end; Tier 1 passing + Tier 3 red points at spawn/watch/review wiring, not unit logic. |
| 4 — live / opt-in | Playwright browser tests inside `npm test` (`src/tools/__tests__/browser-action.test.ts`); GPU / Ollama / live-model runs | `npx playwright install chromium` for the browser tests (without it the file prints a `skip browser_action suite` line and exits 0); live runs need their own credentials/hardware | Varies | Browser file skipping = environment gap, not a regression. A live-model failure reproduces only with that backend/key — record which one in the issue. |

Notes:

- Tier 2 skip line is exact: `SKIP <label>: Fleet source not staged`.
Match that wording when adding a new Fleet-dependent entry — use the
shared `shouldSkipFleetTest(label)` probe in
`src/campaigncontrol/__tests__/fleet-test-source.ts` and exit 0.
- Tier 4 browser skip line is exact: `skip browser_action suite:
Chromium is not installed for Playwright`. Do not convert skips to
failures to "make CI stricter" — the skips are the contract that lets a
fresh public clone reach a green Tier 0+1 run.
- CI (`.github/workflows/ci.yml`) runs only on the private maintenance
repo: typecheck, standards/architecture gates, full `npm test` (with the
Fleet source staged and the Playwright browser installed), and
`scripts/e2e/run.sh`. Public contributors get no CI signal — a green
Tier 0+1 run plus clean Tier 2 skips is the merge-ready bar from a
public checkout.

## Repository conventions

- **No new runtime dependencies without a real reason.** The project
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ shell commands safe by itself.
| `npm run typecheck` | TypeScript type check. |
| `npm run smoke` | Vendored prompt-builder smoke test; no network. |
| `npm test` | Unit tests using local/fake dependencies where provided. |
| `CONTRIBUTING.md` → Testing | Test tiers: what each tier needs and what a red run means. |
| `npm run cli -- --dry-run --workspace .` | Build this repository's system prompt. |
| `bash scripts/e2e/run.sh` | Phase 1 CLI integration against mock OpenRouter. |
| `bash scripts/e2e-phase2/run.sh` | Orchestrator spawn/watch/review integration. |
Expand Down
112 changes: 112 additions & 0 deletions src/campaigncontrol/__tests__/fleet-test-source.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>,
): Promise<void> {
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<void> }

async function stagedRoot(): Promise<StagedRoot> {
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<void> {
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<void> {
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<void> {
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<void> {
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)
2 changes: 1 addition & 1 deletion src/campaigncontrol/__tests__/fleet-test-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
117 changes: 105 additions & 12 deletions src/dashboard/__tests__/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -347,17 +347,110 @@ async function testNonGetPostMethodsStillRejected(): Promise<void> {

// ─── Runner ──────────────────────────────────────────────────────────────────

const tests: Array<[string, () => Promise<void>]> = [
["server: GET /api/session/:id/events returns the feed + nextOffset", testEventsEndpointReturnsFeedWithNextOffset],
["server: events endpoint is incremental via ?since=<offset>", 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<void>,
): Promise<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 {
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<void> {
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<void> {
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<void>]> = [
["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)
25 changes: 25 additions & 0 deletions src/dashboard/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<http.Server> {
const server = http.createServer((req, res) => {
Expand All @@ -218,6 +242,7 @@ export function startDashboardServer(options: DashboardServerOptions): Promise<h
server.once("error", reject)
server.listen(options.port, "127.0.0.1", () => {
server.removeListener("error", reject)
warnControlPlaneAuth(options)
resolve(server)
})
})
Expand Down
Loading