Files
loki/scripts/test/precommit-pathspec.ts
T
d3f55225d3 fix(signals): three checks that reported something other than what they measured (#402)
* fix(crons): a scheduled job that records nothing cannot be diagnosed

The frontier self-improvement loop ran from 2026-06-24 to 2026-08-27 and
surfaced zero proposals. A taxonomy shipped on 2026-08-25 to say WHY —
dead model / unreadable reply / model found no match / everything deduped
— and it worked: the first night it ran it answered "unparseable".

That answer was going to expire the next morning. The outcome existed only
in the HTTP response body, which fc-cron.sh echoes into the systemd
journal, and this box's journal is size-capped with no time limit: the
frontier-digest unit holds about ONE day. Sixty-four nights of evidence
about the loop had already been discarded one day at a time, which is why
"drafted: 0" was all anyone could ever recover.

Two of eighteen cron-authed routes persisted nothing. The other sixteen
already used logDebug, so this conforms to the convention rather than
inventing one — and it is the right sink because prune-debug-logs keeps
error rows 90 days and info/warn 30, so the runs worth a postmortem are
the ones that survive to have one.

- frontier-digest logs generation outcome, drafts, surfaced, judge
  failures and panel reachability, at a level that separates a fault in
  the machinery (dead model, unreadable reply, panel never voted) from
  the loop working as designed (no match today). Both used to end in the
  same drafted: 0.
- send-digest-emails logs its send results. It catches per-user failures
  so one bad address cannot stop the batch, which also means every send
  could fail while the route answered ok: true and systemd recorded a
  success.
- generateProposals now returns rawSample on "unparseable". Without the
  text, "unparseable" is the same which-of-several-causes question one
  level down: a refusal, a prose preamble and a truncated object all fail
  to parse and each needs a different fix.

Also normalises the log source to crons/<name>. Twelve routes used that
and five used api/crons/<name>, so a query for cron activity silently
returned about two-thirds of it. Nothing filters on source today, so this
is hygiene rather than a live bug — but it was a wrong answer waiting for
the first person to ask.

The gate closes the class rather than the two instances: every route
demanding requireCronAuth must call logDebug under its own source name.
Comments are stripped before matching, the match is call-shaped so an
import cannot satisfy it, and a floor fails the scan if it stops finding
routes. Proven by six mutations, each red then green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

* fix(signals): three checks that reported something other than what they measured

Last week this app produced 231 warnings. 216 of them meant "nothing
happened", and six real errors sat underneath — a telemetry sensor dead
for 78 days, a runner two versions behind, an email probe timing out.
A channel degrades to the reliability of its worst entry, and the rational
response to a mostly-wrong list is to stop reading it.

Three separate causes, one shape: the signal was not attached to the thing
it claimed to describe.

1. The pre-commit hook lints nothing, and says so reassuringly.

   GLOBS was unquoted, so the SHELL expanded "src/**/*.ts" before git saw
   it — and POSIX sh has no globstar, so ** collapsed to one level. The
   variable became 230 literal paths, all exactly two levels deep, and
   nothing deeper could ever match. Almost all code here is deeper.
   Measured on a commit touching 10 TypeScript files: it matched 0 and
   printed "no staged TypeScript — nothing to lint", which is a statement
   about its own pathspec wearing the clothes of a statement about the
   commit.

   ':(glob)' does two jobs: it makes ** mean "any depth" to git, and since
   no file can be named ':(glob)…' the unquoted expansion stays literal.
   Reach goes from 230 shallow paths to 1147 files, 905 of them deeper
   than two levels.

   verify still runs in full on pre-push and in CI, so nothing unlinted
   reached origin. What was lost is the fast local loop the hook exists
   for.

2. The env checker read a different variable than the app.

   checkEnv() tested the bare TELEGRAM_CHAT_ID; every consumer reads it
   through envAlias, which looks only at APP_/FLEETCROWN_/COCKPIT_ and
   never the bare name. Wrong in both directions:

     - false alarm — prod has APP_TELEGRAM_CHAT_ID set and delivery works
       (confirmed live with a read-only getChat), yet it warned at every
       boot: 48 of the week's 231 warnings.
     - false quiet — and the message told the operator to set
       TELEGRAM_CHAT_ID, which silences the warning while
       selfTelegramTarget() still returns null and every notification
       still vanishes. A fix that removes the signal and not the fault is
       worse than no check.

   The message now names the prefixed variable that actually works.

3. check-pending-approvals warned about the world, hourly.

   It warned whenever a stale approval existed — a fact about the world,
   and the world does not change hourly. 168 identical warnings in seven
   days, every one with expired/raised/pinged/cleared all zero. The state
   is not lost: an open pending_approvals alert already represents an
   ongoing condition once instead of sixty-eight times.

   The alert records what is true; the log records what happened.

Gates, both derived from source rather than a list, six mutations each red
then green: the pathspec test is behavioural — it re-runs the hook's own
assignment in the hook's own shell and asks git what it matches, so it
stays honest however the line is rewritten, where a grep for ':(glob)'
would only prove today's spelling. The env test derives the rule: whatever
the app resolves through envAlias, the checker must too.

No gate for (3). "Log level reflects work done, not state observed" is a
real class, but every static check I could write for it produces false
positives on jobs whose work IS an observation. Verified by watching the
warn rate in prod instead, and left un-encoded deliberately rather than
silently.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 19:38:18 +00:00

78 lines
3.3 KiB
TypeScript

/**
* The pre-commit hook's pathspec actually reaches the files in this repo.
* Run: npx tsx scripts/test/precommit-pathspec.ts
*
* The class this closes: a hook that lints nothing and says so reassuringly.
* `.husky/pre-commit` held
*
* GLOBS="src/**\/*.ts src/**\/*.tsx home/**\/*.ts home/**\/*.tsx"
* git diff --cached --name-only $FILTER -- $GLOBS
*
* and because `$GLOBS` is unquoted the SHELL expands it before git sees it.
* POSIX sh has no globstar, so `**` collapses to one level: the variable became
* 230 literal paths, all exactly two levels deep, and nothing deeper could ever
* match. Almost all code here is deeper than that. Measured 2026-08-27 on a
* commit touching 10 TypeScript files: it matched 0 and printed "no staged
* TypeScript — nothing to lint" — a statement about its own pathspec dressed up
* as a statement about the commit.
*
* This test is deliberately BEHAVIOURAL rather than a grep for `:(glob)`. It
* re-runs the hook's own assignment in the same shell the hook uses and asks
* git what it matches, so it stays honest no matter how the line is rewritten —
* a grep would only prove today's fix is still spelled the same way.
*/
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
const HOOK = ".husky/pre-commit";
const hook = readFileSync(HOOK, "utf8");
const globsLine = hook.split("\n").find((l) => /^GLOBS=/.test(l.trim()));
assert.ok(globsLine, `no GLOBS= assignment in ${HOOK} — the pathspec moved; update this test with it`);
// Same shell, same unquoted expansion the hook performs.
const matched = execFileSync("sh", ["-c", `${globsLine}\ngit ls-files -- $GLOBS`], {
encoding: "utf8",
maxBuffer: 8 * 1024 * 1024,
})
.split("\n")
.filter(Boolean);
// A floor: a pathspec matching nothing would otherwise satisfy every
// "contains" assertion below by vacuous truth in the wrong direction.
assert.ok(
matched.length > 300,
`the pre-commit pathspec matches only ${matched.length} file(s) — it is not reaching the tree`,
);
// The actual regression: files more than two directories deep. This is where
// almost all of src/ lives, and it is exactly what the broken form missed.
const deep = matched.filter((f) => f.startsWith("src/") && f.split("/").length >= 4);
assert.ok(
deep.length > 100,
`the pre-commit pathspec matches ${deep.length} deep src/ file(s) — ` +
`it is only reaching shallow paths, which is the shell-globstar bug returning. ` +
`Keep the ':(glob)' prefix so git, not the shell, interprets '**'.`,
);
// Both roots the hook claims to cover must actually be covered.
for (const root of ["src/", "home/"]) {
assert.ok(
matched.some((f) => f.startsWith(root)),
`the pre-commit pathspec matches no ${root} files, though the hook lists it`,
);
}
// And a file we know is deep — named, so a future reshuffle that quietly stops
// covering API routes is loud rather than absorbed by the counts above.
const sentinel = "src/app/api/crons/frontier-digest/route.ts";
assert.ok(
matched.includes(sentinel),
`the pre-commit pathspec does not match ${sentinel} (5 levels deep) — deep routes are unlinted`,
);
console.log(
`✓ pre-commit pathspec: ${matched.length} file(s) reachable, ${deep.length} of them deeper than two levels`,
);