Files
loki/scripts/test-unit.ts
T
1647fe7987 fix(sweep): a test that rotted behind a wrong excuse, and a box spec off by 2x (#480)
Three follow-ups from sweeping the earlier findings. Two of the four I had
carried forward did NOT survive checking and are dropped: /api/control/dispatch
is a real route, so the docs referencing it are correct; and
scripts/test/push-notifications.ts exists. Verifying first is why this commit
is smaller than the list that prompted it.

1. THE TEST NOBODY RAN, FOR A REASON THAT WAS NEVER TRUE

scripts/test/push-notifications.ts read scripts/agent-hook-bridge.sh, which was
deleted on 2026-06-11 in 956ccf64 ("delete the bash daemon and bridge files").
It threw ENOENT and the suite exited 1. Its entry in test-unit.ts SKIP said
"needs push/web-push env — run manually". That was never the reason: every
check in the file is a static file read and it needs no environment at all.

A wrong skip reason is worse than no skip. It answers the question that would
have found the bug, so the red looked accounted for and nobody looked again for
three months.

Retargeted rather than deleted. The behaviour moved instead of going away — a
closing run reaches the operator through notify-close.ts → pushToUser →
push-fanout — and scripts/test/notify-close.ts covers that module without
mentioning push at all. So "an agent finished, tell the operator" was asserted
by nobody. Deleting the check would have quietly ratified that hole.

Removed from SKIP, so it now runs in test:unit (132/132) and therefore in CI.
Mutation-proven: renaming the pushToUser call fails with "notify-close must
call pushToUser" (exit 1); restored, exit 0.

2. THE BOX IS HALF THE MACHINE THE DOCS DESCRIBE

Measured 2026-09-04: nproc 4, 7746 MiB, 75 G disk, 4 GB swap. That is a CX33.
Three docs said CX43, 8 vCPU / 16 GB, 40 GB disk — every figure but the swap
wrong, in the direction that matters: planning against 16 GB on an 8 GB box is
how you meet the OOM killer.

src/app/api/system/hetzner/route.ts has said "the box is a cx33" all along, so
this was code and docs disagreeing with the code being right. Note the shape of
the drift: CPU and RAM went DOWN while disk went UP (40→75), which is what a
disk-inclusive rescale to a smaller tier looks like — plausibly to escape the
disk-full problem the old caveat describes. The June runbook entry is kept as
history and marked superseded rather than rewritten.

The docs now point at /api/system/hetzner instead of restating numbers. A
hardcoded spec is a second source of truth that rots silently, which is exactly
what happened here between June and September.

3. THE COMPOSER STATUS, FINISHED

#479 gave this line its own row below `sm` but kept `sm:truncate`, which left it
at 57% on a 1440 viewport — "Autopilot on: queue is empty, so FleetCr…". That is
the same defect as the phone's 14%, just less obvious, and there is no `title`
here so the remainder is unreachable at every width. It now wraps everywhere.
Costs one toolbar line when the sentence is long; truncating cost the half of
the sentence that says what will happen.

pnpm run verify passes (repo moved to pnpm in #478).


Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 11:16:58 +00:00

122 lines
5.5 KiB
TypeScript

// Discover-and-run every pure unit test under scripts/test/*.ts in parallel.
//
// Why this exists: the ~30 test:* scripts were wired one-by-one into ci.yml /
// pre-push, so only ~12 ran automatically and a newly-added test:* was born
// dead (never run by CI). This runner globs the directory, so any new pure
// test is picked up for free. Infra-dependent tests are explicitly skipped
// (with a reason) — they run where their infra exists, not in this suite.
//
// Environment-independent by construction: every test listed here passes with
// NO DATABASE_URL and no running server (verified), so it behaves identically
// on a laptop and in CI. Run: npx tsx scripts/test-unit.ts
import { readdirSync, existsSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { spawn } from "child_process";
const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
const TEST_DIR = join(SCRIPTS_DIR, "test");
// Invoke the local tsx binary directly (not `npx tsx`): npx adds resolution
// overhead and a second esbuild service per child, which thrashes esbuild on a
// 2-core box. .bin/tsx is one process per test.
const TSX_BIN = join(SCRIPTS_DIR, "..", "node_modules", ".bin", "tsx");
// Files under scripts/test/ that are NOT part of the pure suite. Keep the
// reason — this list is the honest boundary between unit tests and the ones
// that need real infra (they stay wired where that infra is available).
const SKIP: Record<string, string> = {
"print-session-token.ts": "helper — prints a token, not a test",
"print-private-zone-cookie.ts": "helper — prints the private-zone unlock, not a test",
"authenticated-smoke.ts":
"needs a running server + FLEETCROWN_SESSION_TOKEN (pre-push/prod dogfood)",
"rag-retrieval.ts": "needs EMBEDDINGS_BASE_URL (fastembed service)",
// push-notifications.ts was here, excluded as "needs push/web-push env —
// run manually". It never needed env: every check is a static file read. It
// was failing because scripts/agent-hook-bridge.sh was deleted on 2026-06-11
// (956ccf64), and the skip entry gave a reason that was never the real one —
// so the failure looked accounted for and nobody looked for three months.
// A wrong skip reason is worse than no skip: it answers the question that
// would have found the bug.
"inject-prompt.ts": "needs a live DB (only passes locally via .env.local)",
"verify-project-brief.ts": "needs a live DB + Groq API (network + GROQ_API_KEY)",
};
/**
* Tests that are skipped ONLY while their prerequisite is absent, rather than
* skipped forever.
*
* The difference matters. An entry in SKIP above is a permanent exclusion, and
* six of them had quietly become "this path is verified by nobody": the
* entitlement suite — signature verification, actor lookup, grant writes,
* dedupe, expiry — is the billing boundary, and it had never once run in CI.
* It does not need a SEEDED database, only a migrated one, which CI can now
* provide (see .github/workflows/ci.yml). So it runs wherever DATABASE_URL
* exists and steps aside politely where it does not, instead of being
* excluded on every machine forever because some machines lack a database.
*/
const SKIP_UNLESS_ENV: Record<string, string> = {
"orangecat-entitlement-e2e.ts": "DATABASE_URL",
};
for (const [file, envVar] of Object.entries(SKIP_UNLESS_ENV)) {
if (!process.env[envVar]) {
SKIP[file] = `needs ${envVar} — runs in CI against the migrated service DB`;
}
}
const MAX_PARALLEL = Number(process.env.TEST_UNIT_PARALLEL ?? 2);
const files = readdirSync(TEST_DIR)
.filter((f) => f.endsWith(".ts") && !(f in SKIP))
.sort();
const skipped = Object.entries(SKIP);
if (skipped.length) {
console.log(`↷ skipping ${skipped.length} infra-dependent test(s):`);
for (const [f, why] of skipped) console.log(` ${f} — ${why}`);
}
console.log(`→ running ${files.length} unit tests (parallel ${MAX_PARALLEL})\n`);
const runner = existsSync(TSX_BIN) ? TSX_BIN : "npx";
const baseArgs = existsSync(TSX_BIN) ? [] : ["tsx"];
function run(file: string): Promise<{ file: string; ok: boolean; tail: string }> {
return new Promise((resolve) => {
const child = spawn(runner, [...baseArgs, join(TEST_DIR, file)], {
stdio: ["ignore", "pipe", "pipe"],
});
let out = "";
child.stdout.on("data", (d) => (out += d));
child.stderr.on("data", (d) => (out += d));
child.on("error", (err) => resolve({ file, ok: false, tail: `spawn error: ${err.message}` }));
child.on("close", (code) => {
const tail = out.trim().split("\n").slice(-1)[0] ?? "";
resolve({ file, ok: code === 0, tail });
});
});
}
// No top-level await: tsx transforms this file to CJS (no "type":"module"),
// which rejects top-level await. Orchestrate inside an async main() instead.
async function main(): Promise<number> {
const results: { file: string; ok: boolean; tail: string }[] = [];
const queue = [...files];
async function worker() {
let f: string | undefined;
while ((f = queue.shift())) {
const r = await run(f);
results.push(r);
console.log(
`${r.ok ? "✓" : "✗"} ${r.file.replace(/\.ts$/, "")}${r.ok ? "" : `\n ${r.tail}`}`,
);
}
}
await Promise.all(Array.from({ length: MAX_PARALLEL }, worker));
const failed = results.filter((r) => !r.ok);
console.log(`\n${results.length - failed.length}/${results.length} unit test files passed`);
if (failed.length) console.error(`✗ failed: ${failed.map((r) => r.file).join(", ")}`);
return failed.length ? 1 : 0;
}
main().then((code) => process.exit(code));