Files
loki/scripts/test-unit.ts
T
84a0edd70d fix(mobile): a dialog you cannot close, on pages nothing could test (#287)
* fix(deploy): a marker that can lie is worse than no marker

Two flaws in #279, found before its deploy ran.

1. The stamp preferred GITHUB_SHA over the checked-out commit. deploy.yml's
   workflow_run path checks out `workflow_run.head_sha`, which is not always the
   run's GITHUB_SHA, so the marker could name a commit that was never compiled.
   Since the deploy compares the live marker against the shipped ref, a lying
   marker manufactures a false alarm. Git HEAD is literally what was built, so
   it now comes first; GITHUB_SHA is the last resort for checkouts with no .git.

2. A mismatch rolled the box back. The realistic cause of a mismatch is a second
   deploy landing behind this one — and reverting to app.prev would discard the
   NEWER build, turning a benign race into exactly the incident the check exists
   to catch. It now reports loudly and leaves the running build alone. What was
   missing before was never the ability to revert; it was ever being TOLD that
   the box serves something else. That, plus /api/health, is the fix.

Both are pinned by tests, including one asserting the mismatch path does not
call rollback_box.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(mobile): a dialog you cannot close, on pages nothing could test

Testing prod in a real phone viewport turned up two defects and the reason
neither was ever going to be caught.

THE OVERLAYS

The mobile navigation sheet — the only route to half the app on a phone —
ignored Escape and let the page keep scrolling behind it. Checking the other
overlays found the same thing twice more: the floating Loki assistant could be
opened with a key (`?`) and not closed with one, and the sessions drawer and
command palette both cover the app while the page scrolls underneath.

The cause is structural. `useEscapeToClose` was a private helper inside
modal.tsx, so the behaviour was reachable only by using <Modal>/<Drawer>; every
hand-rolled overlay started from zero and had to remember. Some did. Three did
not — and CommandPalette already carries a comment about fixing "the user's
'Escape doesn't close' complaint", so this is the class's third appearance, not
its first.

The hook moves to hooks/use-escape-to-close.ts, and scripts/test/overlay-contract.ts
enforces the rule: anything claiming role="dialog" handles Escape, and the
overlays that cover the app lock what is behind them. Fixing the fourth instance
by hand would have cost more than that file.

THE BLIND HALF

/people, /money, /habits, /events, /goals and /memory sit behind the PIN, so the
prod smoke skipped them, the UI dogfood's flows failed as "skipped", and the
responsive audit's page list never included them. Three checks, one hole, in the
same place — and it read as coverage: 97 green probes, 84 green viewport checks.

The PIN was never the boundary. The unlock is an HMAC under AUTH_SECRET, and
anything holding AUTH_SECRET can already mint a session as any user — which is
exactly what print-session-token.ts does. So the format moves to a request-free
module and the tooling mints its own unlock. Nothing new is granted; the tests
just stop pretending a third of the product does not exist. The PIN keeps
guarding what it was built to guard: a person at a keyboard.

The smoke now proves the gate before walking through it — a session without the
unlock must be refused — so bypassing it adds an assertion instead of removing
one. 97 probes to 129, all green against production.

VERIFIED IN PROD

- 129/129 authenticated probes, including the private zone for the first time
- 84 viewport checks across 320/390/768/1440, no horizontal overflow, now
  including the six private pages
- new audit:mobile drives a touch Chromium: every page's last element is
  reachable above the floating nav at max scroll, and the menu sheet closes on
  the close button, a backdrop tap, and Escape

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:29:20 +00:00

89 lines
4.2 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": "needs push/web-push env — run manually",
"inject-prompt.ts": "needs a live DB (only passes locally via .env.local)",
"orangecat-entitlement-e2e.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)",
};
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));