Files
loki/scripts/test/token-drift.ts
CatoandClaude Opus 5 602a581c46 Organise navigation around the operator loop, give the header an identity, and stop Control contradicting itself (#797)
* refactor(shell): organise navigation around the operator loop, and give the header an account menu

The sidebar carried 27 destinations in four sections, one of which was named
"More" and held Approvals, Terminal, Prompts, Activity, System, Thoughts and
the PUBLIC /fleet register — seven pages whose only shared property was that
nobody had decided where they went. Alongside them sat a "Site" section:
Mission, Philosophy, Roadmap, Whitepaper and Investors, in the signed-in app
navigation.

Loki is an operator console. Its surface answers three questions, so the
sidebar now has exactly three sections and each one states its question:

  Now     — what needs me?          Today, Approvals, Feedback
  Fleet   — what is my fleet doing? Control, Projects, Activity, System
  Command — how do I act on it?     Loki, Terminal, Prompts

Private stays PIN-gated below them. The marketing pages left the signed-in
shell and stay reachable through Cmd-K, which now indexes NAV directly rather
than whatever happens to be in the sidebar — curating the sidebar must never
make a page unfindable.

Alongside that, identity:

- There was no way to sign out from the header, and nothing anywhere in the
  top bar said who was signed in. A grep of components/shell/ for "avatar",
  "UserMenu" or "ProfileMenu" returned nothing. Sign out, Settings and the
  private-zone lock lived in the sidebar footer, which is `hidden md:flex`,
  and were duplicated in the mobile Menu sheet's footer: two account menus,
  neither called one, and none where users look first.
- AccountMenu now owns all of it, in the top bar, on every viewport.
- The theme toggle moved inside it. It was the only control in the top bar
  drawn with a border and a fill (ui-theme-cycle-btn) while every signal
  beside it was a bare ghost circle (ui-topbar-btn) — a preference outweighing
  every piece of live state on the page.
- SidebarFooter is deleted. Its collapse button was marked `md:hidden` inside
  a panel marked `hidden md:flex`, so it could never render on any viewport;
  SidebarBrand has always owned the working toggle.

Two retired NAV entries are deleted rather than hidden: `agents` → /control
and `atlas` → /projects pointed at the pages that replaced them, and since
NAV_ITEMS is what AppTopBar and PageTitle scan for "which page am I on?",
the first match won — /control would have been titled "Agents". Their
redirect pages reference the targets, so the redirects stay honest.

scripts/test/navigation.ts is rewritten to defend the new structure: every
section must state its question, "more"/"misc"/"tools"/"site" are rejected by
name, account items may not appear in the sidebar, marketing items may not,
no two items may share an href, and the bottom bar must carry one entry point
per loop section.

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

* fix(control): stop the hero claiming "Idle" over a queue of six things

Observed on prod: the Control hero read "Idle — nothing queued" while a panel
titled "Needs you", badged 6, sat roughly a screen and a half below it, under
a 23-project list. One page, one question — is anything waiting on me? — and
two answers, with the confident wrong one on top.

Two distinct faults, fixed together because either alone leaves the page
contradicting itself.

1. The hero could not see the queue. deriveFleetPulse read agents, run
   outcomes and projects awaiting input, and nothing else, so the one queue on
   the page that literally counts things waiting on the operator was invisible
   to the headline that summarises them. It now takes `inbox` and ranks it
   last among the states that say something is up — a stall, a failure, a
   half-finished run and a blocked project all still outrank chores — but
   comfortably above "Idle".

   `unknown` is a separate state from `count: 0` on purpose. A queue we failed
   to read is not a queue we know to be empty; ControlInbox already refused to
   render silence as the answer "no", and the hero now refuses too.

   The count could not be lifted while it lived inside the panel rendering it,
   so the fetches moved to `useControlInbox`, called once in ControlPanel and
   passed down. One read, two consumers, one truth. It also removes a third
   copy of the /api/feedback/summary request from the page.

2. The panel was filed in the wrong tier. ControlPanel's own ordering rule
   says tiers 1-2 are about a human being blocked and "reporting never renders
   above blocking" — and a queue titled "Needs you" with a count badge is the
   definition of tier 2. It sat in tier 4. It now sits with AttentionBar and
   AgentEscalations, which it can afford because of how it was built: one line
   per group until opened, nothing auto-expanding, and nothing at all rendered
   when the queue is empty. Two rows above the fleet, not the ~1,400px of
   unbounded strips it replaced.

The `inbox` state takes the warning dot rather than neutral grey, for the
reason the `partial` state already does: grey beside the words "Waiting on
you" is the page agreeing with itself in tone while disagreeing in substance.
`unknown` stays neutral — that one really is "no idea".

Four tests pin it: a non-empty queue is never Idle, an empty one still is, an
unreadable one is not a claim of emptiness, and real trouble still outranks
chores.

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

* fix(design): un-invert the dark text ramp, and make token drift a build failure

@bitbaum/design-tokens calls itself "the design single source of truth for
OrangeCat, Loki and Solon". Solon proves it — its globals.css is 19 lines and
imports the package. Loki's is ~5,800 and declares its own ramp, with the
package present only as a devDependency used to generate the widget theme. A
comment here said the quiet part out loud: "Loki still declares its ramp
locally, so the value is kept in step by hand."

Nothing was keeping it in step. Measured: Loki and the package disagree on 32
of the 36 tokens they both define, and the disagreement has a shape — someone
transcribed the DIGITS between colour spaces without converting them.
`--text-secondary` is `oklch(0.4 0 0)` here and `0 0% 40%` there; those are 30
of 255 apart.

  light: surfaces agree within 5/255; the TEXT ramp is 20-30 apart
  dark:  text agrees within 7/255; the SURFACE ramp is 17-30 apart
         (Loki's ground is #010101, the fleet's is #121212)

Comparing them exposed a real bug, which this commit fixes. Loki's documented
ramp is primary → secondary → tertiary → muted, each quieter than the last.
The light block follows it (0.1 → 0.4 → 0.58 → 0.72). The DARK block was
written in the order primary/secondary/muted/tertiary with values descending
in THAT order — so `--text-muted` sat at 0.65 while `--text-tertiary` sat at
0.59, and text marked muted rendered BRIGHTER than text marked tertiary. The
two quietest tiers in the system, inverted, on the theme that is the default.
The two values are swapped rather than retuned, so no new colour enters the
system and the contrast range is unchanged.

The rest is a gate, not a migration. Some of the divergence is deliberate:
Loki is an operator console that sits beside a terminal, its near-black ground
is a product decision, its borders are translucent overlays rather than opaque
greys, and its typeface is Geist where the fleet's is Inter + Instrument Serif.
Adopting the package wholesale would restyle every surface and every glyph of
a running product in one unreviewable step.

So scripts/test/token-drift.ts requires every difference to be DECLARED. A
divergence listed in DIVERGENCES is a decision somebody signed; one that is
not listed fails the build. Tokens that currently agree are pinned, so
agreement cannot quietly lapse. It also asserts the text ramp descends in both
themes, and complains if a token listed as divergent has since converged —
which is how the list shrinks, one reviewable token at a time.

It is picked up automatically by scripts/test-unit.ts (which globs
scripts/test/*.ts), so it runs in `verify` and in CI without further wiring.
Verified to bite: re-introducing the ramp inversion and silently retuning a
pinned token each exit 1.

Docs corrected to match the shell as it now is: CLAUDE.md claimed ThemeToggle
ships in 8 places and described a "Today/Control/Projects + Loki + More"
mobile nav; responsive-design.md described sidebar sections "Work / Private /
Site" with account actions in two different footers.

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

* refactor(shell): stop two navigation surfaces answering a question already answered

Loki ran six navigation surfaces at once — sidebar, top bar, the
Profile/Chat/Control/Terminal strip, the mobile bottom bar, the Menu sheet and
the command palette. On a phone at /control, four were on screen together and
three were answering "where am I?".

Two of them now stand down where they add nothing.

FleetSurfaceGuide renders only with an active project. Its whole claim is that
the four tabs are views of ONE project and that moving between them preserves
it — but `fleetSurfaceHref(surface, null)` falls back to /projects, /loki,
/control and /terminal, which are four sidebar entries. So with no project it
was rendering the sidebar a second time, above every Control, Terminal and
Projects page, preserving nothing. A navigation surface that carries no
information the others lack is not a shortcut; it is a fifth nav system
charging rent.

AppTopBar drops its mobile page label on pages the bottom bar already names.
Below md the bar shows Today / Loki / Control as labelled, highlighted tabs, so
on those three the top bar's title was the third simultaneous answer after the
bottom tab and the page's own heading. It still speaks on all 15 other
destinations, where the bottom bar can only show "Menu" and genuinely cannot
say.

scripts/test/nav-surfaces.ts pins both, and pins them against the config rather
than against a screenshot: it derives the projectless hrefs from
fleetSurfaceHref and asserts each is a real sidebar destination (the premise
the first fix rests on), checks every tab carries the project when there is
one, and checks the label suppression uses the same isCurrentPath the bottom
bar does — otherwise it would silently never fire. It also holds the Menu
sheet to having no account footer, now that AccountMenu owns those actions.

Verified to bite: reverting the strip gate fails the suite.

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

* fix(ci): pre-push ran the wrong suite for scripts/test/

The hook classifies changed paths into three arms and runs the gates each one
can break. `scripts/test/` was in the `_ops` arm, and that was backwards in
both directions at once:

  • test:ops runs `scripts/hetzner/test-*.sh` and nothing else — verified: all
    18 scripts it invokes are under scripts/hetzner/. No file under
    scripts/test/ can affect its result, so editing a unit test ran eighteen
    Hetzner shell suites for nothing.
  • scripts/test/ holds the 218 .ts files that ARE the unit suite
    (scripts/test-unit.ts globs the directory). The unit suite runs in the
    `_app` arm, which scripts/test/ did not trigger. So a broken unit test
    added under scripts/test/ passed pre-push: the hook never ran the suite
    that file is a member of.

Now: `scripts/test/*.ts` → `_app` (tsc, lint, design, desktop, test:unit,
test:home). `scripts/test/*gate.sh` → `_register`, the arm that actually runs
the deploy-ref / not-behind / client-ledger / deploy-ready gates; they had no
arm that ran them before either. `_ops` keeps hetzner and site-template.

scripts/test/pre-push-routing.ts pins it by deriving both sides rather than
restating them: it parses the hook's own `touches '<regex>' && _arm=1` lines,
reads the scripts test:ops actually invokes out of package.json, and asserts
each path reaches the arm that covers it. The failure mode this guards is
invisible — a gate running the wrong suite still prints a wall of green.

Disclosure, because it matters for how this commit is read: this also unblocks
pushing this branch. test:ops fails 4 of 92 checks in a container running as
root (the .env-repair cases assert file ownership against a systemd unit's
User=), and that is not caused by this branch — confirmed by running it on a
clean worktree of origin/main, where it fails identically, 88 passed / 4
failed. The routing above is a defect on its own merits and the fix is the
same one either way; the side effect is stated rather than left to be noticed.
Those 4 ops failures remain, unaddressed by this branch, on main.

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

* chore(design): ratchet the dead ui-* rules in globals.css

check-loki-classes.mjs holds `ui-loki-*` to zero in both directions — a class
used but undefined, and a class defined but unused. The other ~1,000 `ui-*`
rules had never been checked at all, and 35 of them are referenced by nothing.

That matters more here than in most codebases. This repo's Layer 3 contract is
that every recurring visual pattern gets a named class, so the class IS the
decision. Someone looking for "how do we draw a metric card" finds
.ui-control-metric-card, -value, -label and .ui-control-metrics-grid sitting in
globals.css and reasonably concludes that is the house style. Nothing has used
them in months. Dead CSS in a system built on that premise does not read as
dead; it reads as load-bearing, and the next person builds to match it.

It is a ratchet, not a hard zero, for the reason the dead-exports ratchet
already is one: 35 rules is real work to remove safely, and a check that fails
on day one is a check that gets switched off on day two. The number may not
rise, and each deletion lowers it for good — the script fails in BOTH
directions, so cleaning up without lowering the baseline is also an error and
the gained ground cannot be given back.

Dynamic class names are honoured: `ui-dot-${kind}` appears in source as the
literal `ui-dot-`, so a token ending in a hyphen marks every matching rule
used. Without that the check reports ~77 false orphans, which is how a lint
earns being ignored. Eight such prefixes are in play.

Also deletes .ui-mobile-nav-sheet-footer, which the previous commit orphaned
when the Menu sheet's account footer moved into AccountMenu.

Verified in both directions: adding an unreferenced rule fails with "rose to
36", and deleting a genuinely dead one fails with "fell to 34 — lower the
baseline". The first attempt at that second test was itself wrong and is worth
recording: deleting `.ui-btn-pill {` changed nothing, because the class is
also targeted by a compound selector 2,500 lines further down. The checker was
right and the test was wrong — which is exactly the sort of thing a rule
counted by hand gets wrong.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-20 05:37:59 -07:00

239 lines
11 KiB
TypeScript

/**
* Loki's design tokens, checked against the fleet SSOT.
*
* ── The problem this gate exists for ─────────────────────────────────────────
* `@bitbaum/design-tokens` calls itself "the design single source of truth for
* OrangeCat, Loki and Solon". Solon proves it: its globals.css is 19 lines and
* imports the package. Loki's is ~5,800 and declares its own ramp, with the
* package present only as a devDependency used to generate the widget theme.
* A comment in globals.css said the quiet part out loud — "Loki still declares
* its ramp locally, so the value is kept in step by hand."
*
* Nothing was keeping it in step. Measured 2026-09-20, Loki and the package
* disagree on 32 of the 36 tokens they both define, and the disagreement has a
* shape: somebody transcribed the DIGITS between colour spaces without
* converting them. `--text-secondary` is `oklch(0.4 0 0)` here and `0 0% 40%`
* there. Those are not the same colour — they are 30 of 255 apart.
*
* light theme: surfaces agree within 5/255; the TEXT ramp is 20-30 apart
* (Loki's is darker — higher contrast)
* dark theme: text agrees within 7/255; the SURFACE ramp is 17-30 apart
* (Loki's ground is near-black: #010101 vs the fleet's #121212)
*
* ── Why this is a gate and not a migration ───────────────────────────────────
* Some of that divergence is deliberate. Loki is an operator console that sits
* next to a terminal, and its near-black ground is a product decision, not a
* typo. Its typeface is Geist where the fleet's is Inter + Instrument Serif.
* Adopting the package wholesale would restyle every surface and every glyph
* of a running product at once.
*
* So the rule is not "be identical". The rule is that every difference is
* DECLARED. A divergence in DIVERGENCES below is a decision somebody made and
* signed; a divergence that is not listed is drift, and fails this check. New
* matching tokens are pinned too, so a token that agrees today cannot quietly
* stop agreeing tomorrow.
*
* Run: npx tsx scripts/test/token-drift.ts
*/
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const PKG_TOKENS = require.resolve("@bitbaum/design-tokens/tokens.css");
const LOKI_TOKENS = join(here, "..", "..", "src", "app", "globals.css");
type Vars = Record<string, string>;
/** `:root { … }` / `.dark { … }` → flat map of custom property → raw value. */
function block(css: string, selector: string): Vars {
const start = css.indexOf(`${selector} {`);
if (start === -1) throw new Error(`no "${selector} {" block`);
const body = css.slice(start, css.indexOf("\n}", start));
const vars: Vars = {};
for (const m of body.matchAll(/--([a-z0-9-]+)\s*:\s*([^;]+);/g)) vars[m[1]] = m[2].trim();
return vars;
}
/**
* Tokens Loki deliberately does not take from the package, and why.
*
* Adding a line here is a design decision. Removing one — by making Loki's
* value match the package's, or by deleting Loki's declaration so the package
* supplies it — is the migration, one token at a time, each independently
* reviewable in a browser. That is the intended direction of travel.
*/
const DIVERGENCES: Record<string, string> = {
// ── Typeface: Loki is Geist, the fleet is Inter + Instrument Serif ────────
"font-sans": "Loki ships Geist (loaded in layout.tsx); the fleet face is Inter.",
"font-mono": "Geist Mono, to match font-sans. The fleet uses IBM Plex Mono.",
"tracking-display": "-0.03em suits Geist's grotesque; -0.015em suits a high-contrast serif.",
// ── Colour space: Loki is OKLCH, the package ships HSL channel triplets ───
// This is the single biggest blocker to adoption and the reason the values
// above drifted unnoticed: `oklch(0.4 0 0)` and `0 0% 40%` LOOK like the same
// number. Converging means either the package gains an OKLCH build or Loki
// converts its ramp; both are their own change, with their own visual review.
"text-primary": "OKLCH ramp; Loki's light-mode text is deliberately higher-contrast.",
"text-secondary": "OKLCH ramp — 30/255 darker than the fleet's in light mode.",
"text-tertiary": "OKLCH ramp — 26/255 darker than the fleet's in light mode.",
"text-muted": "OKLCH ramp — 20/255 darker than the fleet's in light mode.",
"text-inverted": "OKLCH ramp.",
"surface-page": "OKLCH ramp. In dark mode Loki's ground is near-black by design.",
"surface-base": "OKLCH ramp.",
"surface-raised": "OKLCH ramp.",
"surface-overlay": "OKLCH ramp.",
"surface-modal": "OKLCH ramp.",
"surface-drawer": "OKLCH ramp.",
"surface-public": "OKLCH ramp; mirrored into src/lib/palette.ts for the widget.",
// ── Borders: Loki's are translucent, the fleet's are opaque ───────────────
// Not a value difference — a mechanism difference. A translucent border
// composes over whatever surface it sits on; an opaque one does not.
"border-subtle": "Translucent overlay (white @ 8% in dark), not an opaque grey.",
"border-default": "Translucent overlay.",
"border-strong": "Translucent overlay.",
"border-interactive": "Translucent overlay.",
// ── Accent: Loki's primary accent is achromatic ───────────────────────────
// The fleet's --accent-primary IS the orange. Loki's is near-black, and the
// orange lives in --accent-warm, used sparingly on primary CTAs and focus
// rings. Same --public-accent value; different role in the system.
"accent-primary": "Achromatic. Loki's warm accent is --accent-warm, used sparingly.",
"accent-hover": "Achromatic, paired with accent-primary.",
"accent-muted": "Achromatic.",
"accent-text": "Achromatic.",
"on-accent": "OKLCH equivalent of the fleet's 0 0% 8% — same intent, different notation.",
// ── Status colours: OKLCH, and Loki's subtle variants use % not decimals ──
"status-positive": "OKLCH.",
"status-positive-subtle": "OKLCH.",
"status-warning": "OKLCH.",
"status-warning-subtle": "OKLCH.",
"status-negative": "OKLCH.",
"status-negative-subtle": "OKLCH.",
"status-neutral": "OKLCH.",
// ── Layout ────────────────────────────────────────────────────────────────
"shell-max": "90rem. Loki's shell carries a sidebar the marketing sites do not.",
};
/**
* Tokens that currently AGREE. Pinned so agreement cannot quietly lapse:
* if one of these changes on either side, this check fails and someone
* decides, rather than the two drifting apart in silence again.
*/
const MUST_MATCH = ["public-accent", "public-nav-height", "tracking-caps", "tracking-label"];
let failures = 0;
const fail = (msg: string) => {
console.error(` ✗ ${msg}`);
failures++;
};
const pkgCss = readFileSync(PKG_TOKENS, "utf8");
const lokiCss = readFileSync(LOKI_TOKENS, "utf8");
const pkg = block(pkgCss, ":root");
const loki = block(lokiCss, ":root");
const pkgDark = block(pkgCss, ".dark");
const lokiDark = block(lokiCss, ".dark");
const shared = Object.keys(pkg).filter((k) => k in loki);
// 1. Every shared token either matches, or is a declared divergence.
for (const key of shared) {
const matches = pkg[key] === loki[key];
const declared = key in DIVERGENCES;
if (matches && declared) {
fail(
`--${key} now MATCHES the package, but is still listed in DIVERGENCES. ` +
`Delete the line — and consider deleting Loki's declaration so the ` +
`package supplies it.`,
);
}
if (!matches && !declared) {
fail(
`--${key} differs from @bitbaum/design-tokens and nothing says why.\n` +
` loki: ${loki[key]}\n` +
` package: ${pkg[key]}\n` +
` Either match the package, or add a line to DIVERGENCES saying ` +
`which product decision this serves.`,
);
}
}
// 2. DIVERGENCES may not name a token that no longer exists on both sides.
for (const key of Object.keys(DIVERGENCES)) {
if (!(key in pkg)) fail(`DIVERGENCES names --${key}, which the package no longer defines.`);
else if (!(key in loki)) fail(`DIVERGENCES names --${key}, which Loki no longer defines.`);
}
// 3. The pinned agreements.
for (const key of MUST_MATCH) {
if (!(key in pkg) || !(key in loki)) {
fail(`--${key} is pinned as matching but is missing from one side.`);
} else if (pkg[key] !== loki[key]) {
fail(
`--${key} was identical to the package and no longer is.\n` +
` loki: ${loki[key]} package: ${pkg[key]}\n` +
` This is drift, not a decision. Restore it, or move it to DIVERGENCES.`,
);
}
}
// 4. The text ramp must actually descend, in BOTH themes.
//
// This is not about the package at all — it is the bug the comparison above
// exposed. Loki's documented ramp is primary → secondary → tertiary → muted,
// each quieter than the last. In the DARK theme it inverted: muted sat at
// oklch(0.65) while tertiary sat at 0.59, so text marked "muted" rendered
// BRIGHTER than text marked "tertiary" — the two least-important tiers in the
// system, the wrong way round, on the theme that is the default.
const lightness = (raw: string): number | null => {
const m = /^oklch\(\s*([0-9.]+)/.exec(raw);
return m ? Number(m[1]) : null;
};
for (const [theme, vars] of [
["light", loki],
["dark", lokiDark],
] as const) {
const ramp = ["text-primary", "text-secondary", "text-tertiary", "text-muted"];
const ls = ramp.map((k) => lightness(vars[k] ?? ""));
if (ls.some((v) => v === null)) continue; // not OKLCH any more — the migration happened
// Light theme: the ramp descends in prominence by getting LIGHTER on white.
// Dark theme: it descends by getting DARKER on black. Either way, each step
// must move away from the primary, never back towards it.
const away = theme === "light" ? 1 : -1;
for (let i = 1; i < ramp.length; i++) {
const prev = ls[i - 1] as number;
const cur = ls[i] as number;
if ((cur - prev) * away <= 0) {
fail(
`${theme} text ramp does not descend: --${ramp[i]} (${cur}) is not quieter ` +
`than --${ramp[i - 1]} (${prev}). The two tiers are the wrong way round.`,
);
}
}
}
// 5. Dark must not silently omit a ramp token the light theme defines.
for (const key of shared) {
if (key in pkgDark && !(key in lokiDark) && key in lokiDark === false) {
const themed = /^(surface|text|border|accent|status)-/.test(key);
if (themed) fail(`--${key} is themed in the package's .dark but not in Loki's.`);
}
}
if (failures > 0) {
console.error(`\n✗ token drift: ${failures} problem(s)\n`);
process.exit(1);
}
console.log(
`✓ token drift: ${shared.length} shared tokens — ` +
`${MUST_MATCH.length} pinned identical, ${Object.keys(DIVERGENCES).length} declared divergent, ` +
`text ramp descends in both themes`,
);