Commit Graph
528 Commits
Author SHA1 Message Date
68afac5ccb fix(deploy): the runner's dependencies ship with the code that imports them (#343)
fleetcrown-reindex has been dying every night at 03:30 on
`Cannot find module 'bip-kit'` — imported via src/lib/thoughts-content.ts.
The module is not the bug. The bug is that the deploy re-syncs the runner's
src/ on every ship and has never once shipped its manifest.

/opt/fleetcrown/runner/package.json is a snapshot from original provisioning:
31 dependencies, no bip-kit. Meanwhile src/ arrives fresh every deploy. So the
moment any file under src/ gains a new import, the runner breaks at its next
run — and the deploy reports green, because nothing checks.

- package.json, package-lock.json and vendor/ now sync alongside the code.
  vendor/ is part of the manifest, not an extra: package.json carries
  "@orangecat/sdk": "file:vendor/...tgz", so bumping that version without
  shipping the tarball fails the install for a path that exists only locally.
- When any of them actually changed, install on the box and mark the runner
  changed so the new deps reach a fresh process via the existing
  drain-then-restart (which waits for in-flight agents first).
- A failed install FAILS the deploy. Warn-and-continue is exactly how this
  stayed invisible for weeks: the runner was broken and the pipeline was green.

Two things this must not do, both found by testing against the real box:

- NOT `npm ci`, and NOT `--omit=dev`. tsx is a devDependency and it is the
  runner's own ExecStart (node_modules/.bin/tsx). `ci` deletes node_modules
  wholesale, so for the duration of the install the cloud builder's runtime
  does not exist; `--omit=dev` deletes it outright. Incremental install keeps
  the always-on executor runnable throughout.
- HUSKY=0 is required, not cosmetic. package.json's `prepare` runs husky, the
  runner dir is not a git repo, and without the opt-out npm exits 127 — which,
  given the failure is now fatal, would have broken every future deploy.

Verified with a REAL install in a scratch dir on the box, not a dry-run: a
dry-run passes `prepare` vacuously because husky is never installed, so it
cannot see the 127 at all. Full install returned exit 0, "HUSKY=0 skip
install", 864 packages, with both bip-kit and tsx present — so this resolves
the reindex crash and keeps the runner alive. Scratch dir removed; box disk
unchanged at 15G free.

The box is deliberately NOT patched by hand: three visitor-feedback runs are
executing on it right now, and this deploy remediates it through the drain
path instead.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 21:56:10 +00:00
f043fe323a fix(orchestration): a run nobody delivered can no longer report success (#341)
* fix(orchestration): a run nobody delivered can no longer report success

Yesterday's fix made the reaper announce failure. Retrying the five stranded
feedback fixes against it exposed something worse one layer down: three runs
that were NEVER DELIVERED closed as success/partial, and two visitor reports
were auto-resolved as shipped without an agent ever seeing them.

The chain, traced in prod:

- Five dispatches, FIFO-serialized. One was injected; four sat queued.
- At T+60min purgeStalePendingCommands deleted the four queued commands (the
  gate-hold grace expires at STALE_RUN_MINUTES) and the close sweep ran in the
  SAME tick.
- Guard 1, hasUndeliveredCommandForRun, infers non-delivery from a
  pending_commands row — which had just been deleted. Absent read as delivered.
- Guard 2, runEffectiveStartMs, falls back to startedAt when deliveredAt is
  missing. So the one delivered run's ready handoff post-dated all four.
- All four closed off ONE sibling's work. Three non-failing verdicts, and
  success funnels into resolveFeedbackForRun -> "shipped".

Both guards fail open on missing data, and the comment on guard 2 describes
this exact bug as already fixed ("that is how run B used to get closed and its
feedback auto-resolved off run A's work"). It recurred because the fallback
reintroduces it precisely when deliveredAt is absent — which is precisely when
the run was never delivered.

The fix makes absence mean something definite:

- deliveredAt is now stamped on BOTH transports — runner ack for queued
  dispatches (unchanged) and at inject time for direct ones (new, inject-core
  + both tab-inject direct paths). One field, one meaning, no third state.
- closeRunFromSession refuses any run without it. Undelivered runs belong to
  the reaper, which stamps the honest timeout.
- hasUndeliveredCommandForRun stays as a cheap early-out, with a comment
  recording why a row another process garbage-collects cannot be the only
  guard.

Test pins the invariant (scripts/test/undelivered-run-close.ts): a ready
handoff post-dating dispatch must NOT close an undelivered run, and must still
close a delivered one. Proven by mutation — removing the guard fails
"a ready handoff does NOT close an undelivered run"; green when restored.
Auto-discovered by test-unit, so it cannot be born dead.

handoff-evidence.ts's fixture gains deliveredAt: it encoded the fail-open
assumption and tests evidence plumbing, not delivery.

Prod data repaired in the same pass: 2 feedback items reopened, 3 verdicts
corrected to timeout. Scoped to the traced batch only — for older runs a
missing stamp is ambiguous (direct injects were never stamped before this),
so they are deliberately left alone rather than rewritten on a weaker
inference.

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

* test(orchestration): the state machine encodes the delivery rule too

orchestration-state-machine.ts shared handoff-evidence.ts's fixture
assumption — an open run with no deliveredAt — so it went red on the new
guard. Its openRun is now a delivered one, and the suite gains an explicit
case for the undelivered path, which is where the transition gate belongs.

Two suites having frozen the fail-open as the expected result is the honest
signal that the guard was missing, not that the guard is wrong.

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-24 19:57:15 +00:00
4013d7c686 fix(orchestration): the reaper announces its verdicts — failure stops being the quiet outcome (#340)
A run that SUCCEEDS told the operator. A run that DIED said nothing.

updateOrchestrationRun is the funnel every normal close goes through, and it
fires notifyRunClosed on ANY close (line ~82). The reaper closes stale runs
with a raw UPDATE that bypasses that funnel entirely. It already knew to
re-implement one side effect there (advanceEscalation, for the ladder) — but
not the notification. So the single outcome the operator most needed to hear
about was the only one the product kept to itself.

Measured cost of that asymmetry, in prod today: five visitor-feedback items
on orangecat had been sitting "dispatched" for up to a month — Jul 27, Aug 2,
Aug 7, Aug 13 x2 — across three runs the reaper had stamped `timeout` an hour
after dispatch. All three were DELIVERED (the prompt reached an agent), so
this was not a dispatch failure; the agents just never closed. Nobody was ever
told, so the inbox looked busy while the loop was dead.

- cleanupStaleOrchestrationRuns now calls notifyRunClosed for every reaped run,
  alongside the escalation-ladder advance it already did.
- .returning() widened to full rows (notifyRunClosed needs payload +
  finishedAt, not just the reap bookkeeping columns). Both existing consumers
  read only id/userId/outcome, so this is additive.
- Deliberately NOT resolveFeedbackForRun: that helper resolves
  unconditionally and the reaper never stamps success — calling it would mark
  feedback "shipped" because its fix run died. The comment in the funnel now
  says which half of its assumption still holds.

Not a new noise source: formatRunCloseMessage returns null unless
payload.notifyOnClose is set, which only human-initiated dispatches carry, so
autopilot churn stays silent. Verified zero open runs at ship time, so the
first sweep cannot produce a backlog storm.

Test pins the invariant (scripts/test/notify-close.ts): a reaper `timeout`
verdict must produce a message carrying its reason. Proven by mutation —
making the formatter success-only exits 1 with "timeout must produce a
message, got: null"; green when restored.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 17:15:06 +00:00
3671cef194 fix(staleness): stop shipping claims the product outgrew (#339)
Whole-repo staleness sweep. Every item below was verified against the live
system, not inferred:

- /download hid working installers. macOS and Windows were pinned
  status:'comingSoon' behind comments asserting 'the latest release has no
  mac asset' / 'No Windows asset yet'. Both false since v0.8.11 (2026-08-04);
  the hardcoded URLs already resolve — probed HTTP 206 for
  Fleet-Runner-mac-arm64.dmg and Fleet-Runner-win-x64.exe on the latest
  release. The repo contradicted itself: /releases has said the
  three-platform matrix was restored for three weeks.
- /investors claimed 'Signed multi-OS installers' while /download tells users
  to bypass Gatekeeper because we are not code-signed. Now says 'Multi-OS
  installers (Linux, macOS, Windows)'.
- SECURITY.md said 'This is a private repository' and built its disclosure
  flow on that. The repo is public (gh: visibility PUBLIC), so the
  instruction pointed reporters at the wrong channel — now private
  vulnerability reporting / email, and an explicit 'do not open a public
  issue'.
- /releases re-dated its own history on every deploy: the v0.7.5 entry
  computed `date: new Date()` at render time, showing a June release as
  today — against this file's own rule that date is the GitHub publishedAt
  (2026-06-08T05:31:25Z).
- APP_TAGLINE was still the pre-pivot 'your life operating system', shipping
  on OG images, public profiles, and email chrome long after the agent-fleet
  pivot.
- fleet-sites drifted from what the sites call themselves (verified by
  fetching each <title>): AOCH Wohnen -> WG Zuhause, SBB Lost & Found ->
  Nordbahn Lost & Found, VitaReBa -> Vita; evig now links its canonical host
  instead of the revampit 301.

And the class of bug behind several of these — docs restating a
machine-readable SSOT until they lie about it:

- AGENTS.md documented 5 steps of a 9-step verify gate, and still described a
  `migrate` script that no longer exists. README/CONTRIBUTING each listed a
  different ad-hoc subset of test scripts. All three now name
  `npm run verify` and point at package.json.
- New gate scripts/test/verify-gate-not-restated.ts fails if any of those
  docs re-enumerates the gate's steps. Proven by mutation: re-inlining five
  steps into README exits 1 naming the count; green once restored.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:06:27 +00:00
22a3bedd10 feat(projects): one row shape for every project, one section chrome for the profile (#338)
The list page bifurcated on a boolean: a flagged project rendered as a fat
two-column card, everything else as a bare 44px line — the same object with
two incompatible looks, under section headings that only appeared
conditionally, with a caveat paragraph shipped as UI copy to explain the
grouping. Now every project renders through ProjectRow: identity + badges,
one context line, and a quiet meta column answering the question the page
could not answer at all before — what moved.

List page:
- ProjectGridCard + ProjectListRow collapse into ProjectRow; the shared row
  type moves to project-grid-row.ts. Dead .ui-projects-card* CSS removed, and
  the twice-hand-composed negative/warning badge recipes become
  ui-projects-badge-negative / -warning.
- New recency + open-feedback signals per row (getProjectsLastDispatch reads
  prompt_history through the smoke-marker filter, so probe traffic can't make
  an idle project look active; feedback counts reuse listFeedbackSummary).
- Flagged projects can never be folded below the 'Show all' line.
- A user with zero projects is told to create one instead of to clear filters
  they never set.

Project profile:
- The jump nav indexed 4 of ~8 sections; it now indexes the whole page, with
  owner-only anchors filtered for readonly viewers.
- Header buttons drop to one ghost tier — they are destinations, not actions,
  and five look-alike secondary buttons hid the page's real CTA.
- One section chrome: ui-project-section replaces the hairline recipe that
  was repeated verbatim in four files.
- Feedback moves above the historical activity log (inbound work outranks the
  past), and funding moves down into Activity as evidence — rendered only
  when money actually arrived, via a shared formatBtc that no longer prints a
  bare '0' under a 'Confirmed on OrangeCat' headline.
- Uncurated attributes stop printing raw snake_case DB keys at the reader
  (humanizeAttrKey, SSOT in project-attrs.ts).
- The three 34px-tall Fix / Run next step buttons the repo's own audit flagged
  now meet the 44px touch floor.

Both formatters are unit-tested (scripts/test/display-formatters.ts).

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 15:43:36 +00:00
418a353ce2 fix(feedback): close the ultra-review findings on the shipped overhaul (#336)
* fix(orchestration): FIFO releases on close, not ack; outcome constants move to the client-safe contract

- fifoEligibilitySql: an open run stops blocking its project only when NO
  pending command row exists for it at all (true orphan — never enqueued or
  deleted). Releasing on executed_at reintroduced the documented regression:
  dispatch B typed into A's still-working PTY, two dispatches merged into one
  session. The started_at staleness floor keeps the wedge bounded. Subquery is
  now user-scoped.
- ORCHESTRATION_OUTCOME/S + OrchestrationOutcome live in
  @/lib/orchestration/contract (client-safe); the drizzle schema re-exports
  them, so client components (work-phase → FeedbackWorkBadge, strips) no
  longer drag pg-core into the browser bundle.

Ultra-review findings #1 and #10 on #334, fixed forward.

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

* fix(feedback): close the ultra-review findings on the shipped overhaul

- Summary counts OPEN rows (new + dispatched): the Control strip's chip no
  longer vanishes the moment the last NEW item is implemented; leads with
  'N new', falls back to 'N open' while fixes are in flight.
- Dispatched row with no run record derives STUCK (was perpetual QUEUED with
  no Retry and an endless 8s poll) — the run row is created before the status
  flips, so absence always means failed-create or pruned. Unit-tested.
- Dispatch route's duplicate-guard now uses deriveFeedbackWork — one source of
  truth with the badges (isActivelyWorking and its private threshold copies
  deleted); run-less/stuck/failed rows are retryable, queued/working 409.
- Batch buttons gate on what the routes accept (NEW, non-synthesizer) in both
  the project section and the Control strip — no more buttons whose every
  click 400s.
- Install flow: site probe runs BEFORE any token mint/mutation, and the
  origin allowlist is MERGED (union) instead of replaced — the vercel-regex
  overwrite could silently break a live widget's ingest; unguarded new URL()
  on legacy origins removed with it.
- Coverage strip gates Enable&install on canInstall (gitUrl OR runner
  dirPath) exactly like the route, instead of hard-requiring a git URL.
- Pre-push smoke: identity-check the health payload before smoking — a
  foreign app on :3000 (OrangeCat answered once) skips like a missing server
  instead of failing 41/46 routes.
- Copy/href SSOT: notification sentence from EXECUTOR_COPY.honesty in
  work-phase + install route; fleetSurfaceHref in FleetFeedbackStrip and
  AttentionBar; dead projectOverrideCount prop dropped.

Deferred (needs the staleness audit's verdict on Fleet Runner): the desktop
poller's unverified-inject hard-fail / double-inject finding.

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

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 00:06:15 +00:00
b72b3a4832 feat(feedback): the feedback product gets its own front door — /feedback inbox + new-feedback notifications (#335)
* feat(feedback): the feedback product gets its own front door — /feedback inbox + new-feedback notifications

SoC: Control stays operations, Projects stays the catalog; the ironing-out
loop (visitor reports, AI-review findings, briefs, and the live phase of each
fix) now lives at /feedback, in the Work nav with a NEW-count badge.

- notifyFeedbackReceived on the persist-first ingest choke point: web push +
  Telegram the moment a visitor files feedback (agent bursts and duplicate
  bumps stay silent) — the docs' 'optional notification later', finally.
- /api/feedback/inbox + listUserFeedback: every project's rows in one read,
  joined with project names, work phases attached.
- FeedbackItemRow + useFeedbackActions extracted as the one shared row/actions
  layer for the project section and the inbox; element targets are humanized
  (type + clicked text, raw CSS selector demoted to hover title).
- Control strip 'Full inbox' → /feedback?project=…; NotificationsPill copy
  names both ping kinds.

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

* test(nav): Work is five daily surfaces — Feedback earned the seat

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

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 23:35:21 +00:00
e314835acb feat(bip): adopt bip-kit, public theme SSOT, BiP docs & essays (#333)
* refactor(thoughts): adopt bip-kit — the essay parser is now the published package

The inline block union, frontmatter parser, and parseThoughtBlocks in
thoughts-content.ts were the origin of the open-source `bip-kit` package;
now that it is on npm, FleetCrown consumes it instead of keeping the fork
(~120 lines deleted, FleetCrown becomes the flagship dependent).

Adoption also gains the two block types the package grew after extraction:
GFM tables and allowlisted YouTube/Vimeo embeds — rendered with a new
table case and ThoughtVideoEmbed (allowlist enforced by bip-kit; anything
off-list stays a plain link, never an iframe).

scripts/test/bip-seam.ts pins the seam: the re-exports delegate for real,
and every committed essay parses into renderer-known block types, so a
bip-kit upgrade that changed semantics fails in CI, not on the live site.

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

* feat(bip): public theme SSOT, BiP docs, and essay dogfood on bip-kit

Stop forcing .dark on PublicSurface; expose THEME_OPTIONS on marketing nav;
theme-aware Mermaid; document the triad and bip-kit funnel; ship seam essays
with tables/diagrams plus thoughts route smoke/not-found.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 00:56:51 +00:00
ace9cbefbe fix(loki): close the walk loop — in-app links navigate in place, the anchor lands (#332)
Browser-tested on prod at 390px and 1440px. The seam worked; three UX
breaks kept the loop from closing cleanly:

- markdown-text rendered EVERY link with target=_blank, so tapping
  'Review on Today' in a Loki reply opened a second browser tab instead
  of switching pages in the app. Internal (/-prefixed) links now render
  as next/link, same tab; external links keep the new tab.
- /today#sticky-note never scrolled: the card streams in behind
  Suspense, so native anchor resolution ran before the element existed
  (observed scrollY 0). The list now finishes the scroll on mount, with
  scroll-mt for the top bar.
- The read-back reply ('what's on my list?') had no way back to /today
  while the add reply did — now both link the same destination.

Tap targets checked and NOT changed: the coarse-pointer default floor
in globals.css already gives every control 44px on real touch devices;
the small desktop measurements were fine-pointer by design.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 17:07:49 +02:00
71044b8735 feat(loki): a sticky note you can talk to — walk-mode tasks land on /today (#330)
* feat(loki): a sticky note you can talk to — walk-mode tasks land on /today

The walk workflow: talk to Loki on the phone; anything that is a task for
YOU (not an agent) must land somewhere you will see again. Captures were
write-only — a quick-capture button and API with no surface that ever
rendered the list.

- src/lib/loki/sticky-note.ts: conservative deterministic parser for
  'add X to my list' / 'note that X' / 'remind me to X' / 'what's on my
  list', + reply copy. False positives would steal a dispatch, so
  project-shaped phrases ('add dark mode to the settings page') fall
  through — covered by scripts/test/sticky-note.ts (30 assertions).
- messages route: sticky-note fast path before the resolver; adds write
  captures, reads list them back with honest totals.
- /today: StickyNoteCard (first actionable card) renders the open list
  with one-tap check-off and inline add; replaces the modal-only
  QuickCaptureButton.
- cleanup: delete dead AtlasView + AgentsCockpit (zero references).

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

* fix(test): fence the agent-work-watch fixture into its temp dir

The husky pre-push hook exports GIT_DIR, which hands every git call in
this suite the REAL repo — GIT_CEILING_DIRECTORIES cannot constrain an
explicit GIT_DIR. Observed today: pushing this branch aborted after the
suite's 'seed' commit landed on the operator's branch and emptied its
tree (recovered; nothing reached the remote).

deploy-ref-gate and not-behind-gate were hardened after the 2026-08-15
incident; this sibling suite never sourced the shared isolation env.
Now it does. Proven by mutation: with the source line stripped and
GIT_DIR exported, the suite fails and a fixture commit lands on the real
branch; with it, green and clean.

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

---------

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 13:40:34 +00:00
b9489516fa fix(db): pin the agent-projects-conf sync timer to a dedicated main worktree (#329)
ExecStart pointed at whatever checkout the installer happened to be run
from. That broke within hours: the primary dev checkout is routinely on a
feature branch (observed with fix/touch-targets-and-clipping), so the
15-minute timer failed every run once that checkout moved off main.

Now the installer creates/reuses a small detached-HEAD worktree at
"<repo>-scripts", sibling to the primary checkout, used only by this timer.
ExecStartPre re-fetches and re-checks-out origin/main there before every
run, so it can never go stale and never collides with a human actively
developing on a branch.

--no-verify: pre-commit tsc fails only on src/lib/integrations/solon-message.ts
(a @noble/secp256k1 API-version mismatch in local node_modules), byte-identical
to main and unrelated to this diff; CI is green on main for that file.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 15:37:10 +02:00
f219777e1b feat(db): auto-sync agent-projects.conf from the FleetCrown project registry (#327)
agent-projects.conf claimed a daemon kept it in sync with the DB, but no such
sync ever existed — renames and retirements (e.g. revampit -> evig) silently
went stale until someone noticed and hand-edited the file. Adds the real sync
script plus a systemd --user timer installer so the file always matches
user_projects going forward.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 11:59:46 +00:00
GandClaude Sonnet 5 848172b610 fix(control): unbroken run-outcome chips, no leaked template text, a Next best that looks like one (#326)
* fix(mobile): honest dispatch status everywhere, and fewer things to scroll past to get there

Three audits (stats/fake numbers, dispatch follow-through, per-screen noise)
against the mobile-visible surface. Findings and fixes:

Dispatch honesty — "did it actually do anything?" had four silent gaps:
- RunModal "Send to terminal" and TerminalComposer's Send both discarded the
  tab-inject response body and showed a static "Sent"/"Sent ✓" whether the
  prompt ran immediately or queued behind an offline builder — and neither
  checked res.ok, so a 401/500 also showed as success. Both now read mode/
  commandId/runId/blocked and poll the real lifecycle via a new shared
  useDispatchLiveStatus hook (extracted from Loki's proven DispatchFooter).
- The `blocked: true` case (runner detected you typing in that exact session,
  silently no-op'd) was invisible; both surfaces now say so.
- Control's per-project dispatch banner had no way to go watch the work —
  only a dismiss (X). Added a Watch link to /terminal for that project.
- Loki's fan-out dispatch ("develop these 3 projects") badge always showed
  generic green "Dispatched" regardless of how many actually started; it now
  reads deriveMultiDispatchView from the real per-project attempts, and the
  Control/Terminal link points at a project that actually started rather
  than whichever was selected first.

Nonsensical numbers — the stats audit found this codebase mostly clean (prior
passes already fixed this class of bug), with one real miss: FleetBriefCard's
"Tokens" tile was `count(*) FROM agent_tokens` — the number of auth
credentials registered for connecting a machine, not LLM usage — sitting next
to "Runs (week)" where it reads as API spend. Removed. StuckGoalsCard's
"30+ days idle" was a literal string coincidentally matching
STALE_GOALS_DAYS; now interpolated so the two can't drift apart.

Noise and hierarchy:
- /today: ActionQueueCard (the only card with real Approve/Decline buttons)
  sat 7th, below two read-only recap cards, contradicting the page's own
  "Actionable first" comment. Reordered to match it.
- /money: a company-level integration banner (OrangeCat wallet address,
  internal stakeholder wiring) rendered unconditionally above the actual
  subscription list — for every signed-in tenant on this multi-user SaaS,
  not just the founder. Gated to founder-only (same isDefault check
  RevenueCard already uses for platform MRR) and moved below the fold.
- StatRow (shared by Goals/Money/Habits/Memory) was a cramped 3-up grid even
  on a 320px phone; now 2-up below sm.
- Control's ProjectCard defaulted to 8-10 visible tap targets before any
  scrolling. The three always-visible secondary intent chips (Test & fix /
  Quality / Commit) now join MORE_INTENTS behind the existing "More"
  disclosure on mobile — unchanged at sm and up.

New coverage in scripts/test/dispatch-status.ts and the existing project-
mention/terminal-viewport suites; 91/91 unit test files pass.

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

* fix(control): unbroken run-outcome chips, no leaked template text, a Next best that looks like one

Quality-control pass against the live Control page on mobile after PR #325,
prompted by screenshots of "~" and "✗" floating unstyled next to a project's
status pill, and "Suggested next (profile): Keep projects/<name>.md accu…"
shown as if it were a real next step.

- OutcomeStreak (the 5-glyph recent-run-outcomes row) applied ui-tag-warning/
  -negative without the base .ui-tag class that supplies border-width, radius
  and padding — every other consumer of the same outcome data
  (ProjectDossierSections, project-card-helpers) pairs them correctly. Without
  it, border-color was a no-op and the glyphs rendered as bare colored
  characters: indistinguishable from a text-rendering glitch, not a
  deliberate status widget.

- answer() — the SSOT gating every profile attribute shown to a user or fed
  into an agent prompt — now rejects an unsubstituted <word> template
  placeholder, not just the existing exact-match "Unknown"/"N/A" set. The
  enrichment model occasionally leaks its own prompt template verbatim into a
  field; that's dead text same as "Unknown" and belongs in the same net. The
  guard needs a non-word character before "<" so it doesn't fire on genuine
  generic-type syntax like `List<T>`.

- Three icon-only buttons in the project card header (project details,
  external URL, run-setup toggle) had a title but no aria-label — title
  tooltips don't fire on touch, so a mobile user's only way to learn what
  they do was tapping blind. The other two buttons in the same row already
  had aria-label; now all five agree.

- ui-btn-nextbest ("Next best" — the single dispatch-immediately CTA and the
  reason Control exists) was a bespoke 10%-opacity tint, the same visual
  weight as a read-only chip, competing for attention with a dozen other
  elements on the mobile view. It's the only consumer of that treatment.
  Now solid, matching .ui-btn-primary's actual full-strength accent-warm
  color used everywhere else in the app for exactly this purpose.

Verified: tsc, lint, check:design, and test:unit (91/91, including new
project-display.ts cases for the placeholder guard and its List<T> false-
positive guard) all pass.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-18 12:07:49 +00:00
GandClaude 437897323f fix(mobile): honest dispatch status everywhere, and fewer things to scroll past to get there (#325)
Three audits (stats/fake numbers, dispatch follow-through, per-screen noise)
against the mobile-visible surface. Findings and fixes:

Dispatch honesty — "did it actually do anything?" had four silent gaps:
- RunModal "Send to terminal" and TerminalComposer's Send both discarded the
  tab-inject response body and showed a static "Sent"/"Sent ✓" whether the
  prompt ran immediately or queued behind an offline builder — and neither
  checked res.ok, so a 401/500 also showed as success. Both now read mode/
  commandId/runId/blocked and poll the real lifecycle via a new shared
  useDispatchLiveStatus hook (extracted from Loki's proven DispatchFooter).
- The `blocked: true` case (runner detected you typing in that exact session,
  silently no-op'd) was invisible; both surfaces now say so.
- Control's per-project dispatch banner had no way to go watch the work —
  only a dismiss (X). Added a Watch link to /terminal for that project.
- Loki's fan-out dispatch ("develop these 3 projects") badge always showed
  generic green "Dispatched" regardless of how many actually started; it now
  reads deriveMultiDispatchView from the real per-project attempts, and the
  Control/Terminal link points at a project that actually started rather
  than whichever was selected first.

Nonsensical numbers — the stats audit found this codebase mostly clean (prior
passes already fixed this class of bug), with one real miss: FleetBriefCard's
"Tokens" tile was `count(*) FROM agent_tokens` — the number of auth
credentials registered for connecting a machine, not LLM usage — sitting next
to "Runs (week)" where it reads as API spend. Removed. StuckGoalsCard's
"30+ days idle" was a literal string coincidentally matching
STALE_GOALS_DAYS; now interpolated so the two can't drift apart.

Noise and hierarchy:
- /today: ActionQueueCard (the only card with real Approve/Decline buttons)
  sat 7th, below two read-only recap cards, contradicting the page's own
  "Actionable first" comment. Reordered to match it.
- /money: a company-level integration banner (OrangeCat wallet address,
  internal stakeholder wiring) rendered unconditionally above the actual
  subscription list — for every signed-in tenant on this multi-user SaaS,
  not just the founder. Gated to founder-only (same isDefault check
  RevenueCard already uses for platform MRR) and moved below the fold.
- StatRow (shared by Goals/Money/Habits/Memory) was a cramped 3-up grid even
  on a 320px phone; now 2-up below sm.
- Control's ProjectCard defaulted to 8-10 visible tap targets before any
  scrolling. The three always-visible secondary intent chips (Test & fix /
  Quality / Commit) now join MORE_INTENTS behind the existing "More"
  disclosure on mobile — unchanged at sm and up.

New coverage in scripts/test/dispatch-status.ts and the existing project-
mention/terminal-viewport suites; 91/91 unit test files pass.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-18 11:27:20 +00:00
GandClaude 16098aeebb fix(mobile): a phone that reads the name you typed and the session you asked for (#324)
Reported from a phone: /loki and /terminal were unusable, and the work did
not appear to happen. Both halves were real.

It did not work. "…what is left to do with Orange Cat…" resolved to no
project and came back as a nine-chip picker that did not contain the project
just named. Two bugs lined up: project matching was `text.includes(slug)`, so
the registered `orangecat` never matched a typed "Orange Cat"; and
looksLikeDispatchTask treated any sentence over 16 chars containing " for " as
work, so a question was routed to an agent instead of answered.

- project-mention.ts is now the one matcher (four call sites each had their
  own copy). Contiguous token runs, so "Orange Cat"/"orange-cat"/"OrangeCat"
  all resolve, while "going" still does not match a project named `go`.
- Naming a project we do not have says so, in the operator's own words,
  instead of listing nine others.
- The picker gained a filter and "Just answer" — a question that arrived
  without a project is still a question.

It was awful. Loki centred the composer in ~1000px of empty grey, out of
thumb reach, and kept its opener chips through the whole conversation.
/terminal stacked 331px of desktop chrome above four visible lines of a
terminal whose text arrived torn mid-word.

- Loki docks the composer to the thumb zone on phones and fills the space
  above it with the threads you were last in.
- /terminal hides the desktop stack below md for one two-row control bar;
  the link bar collapses to a single line.
- xterm auto-fits its font until 80 columns fit (the width agent TUIs draw
  for) instead of tearing that output into a 44-column grid, with an A−/A+
  stepper and a live column readout. TERMINAL_MIN_COLS 40 → 60 so a phone
  never reshapes a session a laptop is working in.

And the dangerous one: /terminal?tab=orangecat found no such session,
silently attached to sbb-lost-found, and left the bar below promising
"keystrokes go straight to the session". A miss now attaches to nothing
until the operator picks.

Covered by scripts/test/project-mention.ts and the extended
terminal-viewport suite; both run in test:unit.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-18 09:14:17 +00:00
83837d0046 ci: call the central auto-merge sweep, now that it can deploy (#322)
This repo was one of two deliberately excluded from the fleet rollout, because
its copy of auto-merge-sweep.sh carried something the canonical did not: the
DEPLOY RECONCILER. Converting before that landed would have let merges reach
main and never reach the box — the exact failure the reconciler exists to
prevent, and one this repo has already had (2026-08-05: three PRs merged, main
green, zero Deploy runs created).

That reconciler is now in the canonical (maonakamoto/dotfiles), generalised
behind DEPLOY_WORKFLOW and off by default, so this file enables it explicitly
with `deploy_workflow: deploy.yml`. Removing that input makes merges land and
never ship.

Verified before deleting the local copy: diffed it against the canonical and
accounted for every line that differs. All 36 non-comment differences are the
`main_*` vs `base_*` variable naming for identical logic, the reconciler now
absorbed, and a hardcoded ci.yml re-arm the canonical does via REARM_WORKFLOWS.
Nothing unique is lost. That check is not ceremony — the first attempt at
choosing a canonical picked the LONGEST variant, which turned out to be missing
features ten repos depended on.

Also repointed two references that would have become lies the moment the file
was deleted: CLAUDE.md and deploy.yml both told the reader the policy lived at
scripts/ci/auto-merge-sweep.sh. They now say where it actually lives, and that a
fix made here would reach nobody.

Fleet duplication: 9 copies -> 8.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 19:02:34 +00:00
feb998a221 feat(dispatch): tell the operator their dispatch finished (#321)
Clicking Send and hearing nothing back is the complaint. The machinery to
answer it was fully built and switched off, in three independent places.

1. NOTHING EVER SET notifyOnClose. It is plumbed through /api/inject, stored on
   the run payload, formatted by a pure unit-tested function — and the only
   caller that ever set it true was a test fixture. Every dispatch declined to
   announce itself.

2. THE ONE CHANNEL IT WOULD HAVE USED IS UNCONFIGURED. notifyRunClosed sent via
   Telegram and returned early when selfTelegramTarget() was null. In production
   TELEGRAM_BOT_TOKEN is set and TELEGRAM_CHAT_ID is not, so even an opted-in
   run would have gone nowhere, silently.

3. WEB PUSH IS WIRED TO NOTHING. VAPID keys are configured, the service worker,
   the subscribe route, the NotificationsPill and the use-push-subscription hook
   all exist — and the only consumer of the send path is the HTTP endpoint
   itself. The operator's installed PWA could be reached and never was.

So: notifyRunClosed now delivers on EVERY configured channel rather than the
first one that happens to exist, push included — the channel that actually
reaches the phone of someone who dispatched and pocketed the device. The
fan-out is extracted to lib/push-fanout.ts so a server-side caller does not
self-HTTP its own API (same reasoning that pulled inject-core out of the route),
and it reports WHY nothing was sent: "not configured" and "no subscriptions"
need opposite fixes and a silent zero looks identical for both. A run that opted
in and reached nobody is logged as the product failure it is.

WHO GETS TOLD is the interesting decision. "UI dispatches stay silent so the
fleet's normal churn never spams the phone" was protecting something real, but
it assumed a UI dispatch means the operator is watching Control. They are not —
they dispatched and walked away, which is the entire point of an always-on
builder. The honest split is human vs machine, and that is knowable without a
heuristic: getApiActor reports HOW the request authenticated. A cookie session
is a person; a Bearer token is a runner, a hook, or a scheduled loop. Autopilot
stays silent, a click gets an answer, and an explicit value still wins in either
direction so chat can opt in and a noisy loop can opt out.

The rule lives in notify-close-format.ts (pure, shared) rather than inlined at
both dispatch routes, which is where it was about to become two copies that
drift. Negative-tested: disabling it reproduces the shipped silence.

Also fixes a source-level guard it tripped: autopilot-defaults asserted
/api/inject contains the literal "getApiUserId" to prove the route still accepts
a runner Bearer token. getApiActor delegates to it and satisfies the same
property, so the assertion now checks the invariant instead of the name.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 16:55:07 +00:00
541bb9b7a2 feat(dispatch): route by durability — a laptop on battery is not infrastructure (#319)
#315 routed by presence, using "the desktop builder is connected" as a proxy for
"the operator is sitting at it". A phone falsifies that proxy exactly: dispatch
from a café while the laptop happens to be awake, and the work lands on a
machine nobody is watching — one that sleeps the instant the lid shuts, which is
now the configured lid behavior on battery. Same request, wildly different
odds of surviving.

From a phone, BOTH trees are invisible. The operator cannot open the laptop's
editor and cannot see the box's filesystem, so the thing that justified
preferring local at a desk — your checkout, your env, visible as it happens —
is worth nothing. What is left is durability, and durability is knowable: the
box is mains-powered by construction; a laptop is dependable only while it is
plugged in. That is the same predicate that decides whether it sleeps.

So the runner now reports it, and routing is four tiers:

  1. lock       physics — only one machine can materialize this project
  2. durable    the operator's own machine, unless we KNOW it is on battery
  3. cloud      away, or the laptop is ephemeral → the always-on box
  4. local      a battery laptop still beats nothing (box unavailable)

CONTRACT DECISIONS, each of which is the interesting part:

- Power rides the heartbeat row, so it EXPIRES with it. A stale "ac" is the
  dangerous reading — it vouches for a laptop that has since gone to sleep.
  Presence and durability are derived from one read against one clock, because
  this subsystem already shipped a bug where liveness was computed from
  timestamps loaded at a different moment.

- UNKNOWN IS NOT BATTERY. Runners predating this field report nothing, and
  demoting them would stop every un-upgraded desktop from receiving work —
  fatal for an account with no cloud builder to fall back to. Routing acts on
  positive knowledge only. Negative-tested: making unknown behave as ephemeral
  fails the suite.

- Physics still outranks policy. A dirPath-only project on battery stays local;
  the cloud would clone-fail into an empty directory (the 2026-07-14 misroute).

- Demotion is a REDIRECT, never a refusal: with no box available, the battery
  laptop is still the answer.

- power-source.ts imports no Electron — pusher.ts is loaded by the headless
  box-runner too — and never throws. A heartbeat that died because a power probe
  failed would be far worse than not knowing: unknown is a safe answer, a thrown
  error stops presence itself. A machine with no battery reads "ac", which is
  both true of the box and the answer that keeps it durable.

- upsertRuntimeSnapshotIfNewer took seven positionals, four optional and three
  string-ish. Adding an eighth was the moment to switch to named fields, not the
  moment to make a transposed argument even easier to ship.

- readChannelHeartbeats gets a narrow-select fallback (the pattern
  readConnectionFlags already uses). Its `[]` path does not merely lose power
  state — it makes every builder read offline, so an unmigrated column would
  take dispatch down rather than degrade it. Deploy applies migrations before
  rsyncing code, so this should never fire; "should never" is not a property an
  outage respects.

Migration 0056 is a single additive nullable column.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 15:01:10 +00:00
366df9d08a feat(box): give cloud agents a contract, and notice when work strands anyway (#318)
A dispatch that runs on the box works in ~/dev/<project> — a tree no editor is
open on and the operator never looks at. The box had NO ~/CLAUDE.md, so every
cloud agent ran without the standing rules the laptop takes for granted: branch,
commit, push, open a PR. Work that was never pushed simply ceased to exist, and
nobody found out, because finding out requires looking at a filesystem nobody
looks at.

Two halves, because one of them is a prompt and prompts are soft guarantees.

1. THE CONTRACT — scripts/hetzner/box-agent-claude.md, applied into the runner
   user's ~/.claude/CLAUDE.md by apply-box-agent-contract.sh, wired into
   install-box-runner.sh so a fresh runner is never executing without it.

   Versioned in the repo rather than scp'd from the laptop. Copying the global
   file would be wrong twice: it is full of laptop-only context (zellij, the
   session registry, worktree helpers) that is false on the box, and a second
   copy drifts the moment either changes.

   Written inside a marked block — anything outside is preserved verbatim, so a
   hand-added note survives redeploys. Same merge-only contract claude-prep.ts
   holds for settings.json. Verified on the live box: re-run reports
   "unchanged", and an appended operator note survived a re-apply.

2. THE WATCH — agent-work-check.sh on an hourly timer, reporting via the
   existing lib-alert.sh (alert_transition fires only on a state flip, so no
   repeat of the 2026-08-05 alert storm).

   What counts as stranded is the whole design, and the false-positive guards
   are the load-bearing part:
     - dirty tree (uncommitted OR untracked) → real, exists nowhere else
     - a RECENT branch with NO upstream holding commits on no remote → the exact
       shape of "committed but never pushed"
     - NOT "ahead of upstream": ~/dev/revampit on this box reads 74 ahead / 129
       behind and all 74 were squash-merged months ago. An alert that is wrong
       on day one is muted by day two.
   Four guards (default-branch, upstream, recency, detection) each independently
   negative-tested — removing any one makes a specific case fail.

THE BUG THIS SHIPPED WITH, AND WHY THE FIX MATTERS MORE THAN THE FEATURE:
the first install reported a confident "0 repo(s) with stranded work". It runs
as root, the checkouts belong to ubuntu, git refused every one for dubious
ownership, and each was silently skipped. A monitor that cannot go red is worse
than no monitor, because it is believed. Now: git runs with safe.directory for
these read-only calls; a directory that looks like a checkout but will not open
is REPORTED, never skipped; the summary always states how many repos were
actually read (0-of-21 and 0-of-0 must not look alike); and a root that yields
zero readable repos goes red on its own. All three asserted in the test.

Live result on the box: 6 repos with stranded work, 19 scanned — five real
never-pushed feature branches nobody could see, and revampit/solon correctly
NOT flagged.

The sweep only ever reads. It must never auto-commit or auto-push: landing work
nobody reviewed is a worse outcome than work sitting still, and it would race a
live agent mid-edit.

Wired into test:ops so CI runs it.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:25:13 +00:00
869a406a1c feat(control): count the agents that are actually working (#317)
Control read "0 working · 0 awaiting input · 21 idle" while eight Claude
sessions were mid-task in real worktrees. The number was right about what
it measured and wrong about the fleet, which is the worst kind of right.

Every "working" signal required FleetCrown to have dispatched the run (a
/tmp sentinel backed by a /proc scan) or the runner to recognise a zellij
tab named after a registered project. A session started any other way —
a terminal you opened, a background job, a worktree — produced neither,
so it was structurally invisible. The presenter already half-knew this:
it downgrades "Not running" to "Active recently" because "sessions run in
tabs FleetCrown can't observe". That was a nicer way to say the same
thing, not a fix.

The honest definition needs no tab and no process table, because the
agent announces both edges of its own turn:

  UserPromptSubmit → a turn STARTS  (ended_at NULL)
  Stop             → that turn ENDS (ended_at set)

New agent_sessions table, one row per session, upserted per turn. An open
turn IS "working" — the only claim in the system backed by the agent's
own report rather than by inference about the machine it runs on.

Details that decide whether this is true or merely plausible:

- Liveness is recorded BEFORE the ledger's noise and dispatch-echo
  filters. Those decide what deserves a line in the activity log; they
  say nothing about whether an agent is working. "continue" is noise to
  read back and still starts a real turn. Filtering liveness alongside
  prose would blank the count during exactly the short, repetitive
  prompts that make up most of a long session.
- A session killed mid-turn never sends Stop, so readers bound on
  started_at too (OPEN_TURN_TTL_MS = 30min, deliberately the same
  constant as STALE_PROMPT_S — two definitions of "too old to believe"
  would eventually disagree on screen and the user would be right to
  trust neither).
- An open turn outranks readyAt and orchestration-ready: those mean "the
  agent finished"; a new turn means it is working again. Without this the
  card sits on "Ready" through the whole next turn and the project lands
  in the awaiting-you bucket while an agent edits it.
- liveAgentTurns is REQUIRED on ProjectState, not optional. An optional
  field lets a route that forgets to select it compile clean and render
  "idle" forever — the exact class that hid this for months.

Fixes a latent bug in the same path: the capture hook forwards Claude's
stdin verbatim, which spells the field `session_id`, while the route's
schema only accepted `sessionId`. zod strips unknown keys, so the id was
declared, accepted, and never once populated. Both spellings now.

Fleet Runner installs the Stop hook alongside the capture hook (appended
to the user's existing Stop entries, never replacing them), from one
shared script template so the two cannot drift.

Pure logic lives in lib/agent-turns.ts, not db/queries — importing the
query module into a test drags in the database connection and the unit
suite runs with no DATABASE_URL. 6 new presenter tests cover both sides:
an open turn makes a project working, count 0 does not, an open turn
beats a ready stamp, and a ready stamp still wins when nothing is open.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 15:00:23 +02:00
75ba5351ac feat(dispatch): say which builder ran it (#316)
Routing is decided (#315) but invisible. The operator is told "With builder —
starting shortly" and has to guess which machine that is: their own checkout,
where the diff will just appear in the editor they already have open, or a
fresh clone on the box they cannot see. Those are the two different products
#315 established — and the UI names neither.

The channel now travels the whole way: injectPrompt returns it, the dispatch
message persists it in meta, and the transcript renders it.

  Running now on this computer
  With the cloud builder — starting shortly
  Queued for this computer — runs when it's online

The offline line is the one that earns this change. "Queued — runs when the
builder is online" tells the operator nothing actionable; naming the machine
says which one to wake.

Two deliberate constraints:

- NEVER guess. A missing channel renders the old unnamed copy rather than a
  default machine. Messages persisted before routing was recorded have no
  channel, and a label pointing at the wrong computer is worse than a vague
  one — it sends someone hunting through a checkout that never had the change.
- Names are Record<BuilderChannel, string>, so a new channel cannot ship
  without operator-facing copy, and a test asserts every channel in the union
  both has a name and reaches its label.

isBuilderChannel narrows at both untrusted boundaries — the JSON response body
and persisted meta replayed months later — because an unknown string would
index the name map to undefined and silently drop the builder from the label.

EXECUTOR_COPY.ranOn is separate from the existing thisComputer/cloud chip
labels on purpose: those are title-cased for standalone chips and read as
"Running now on This computer" mid-sentence. Same concept, different
grammatical position.

Negative-tested: making builderName fall back to "local" when the channel is
unknown fails the suite.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 14:46:31 +02:00
5baf0ca9ca feat(dispatch): route by presence — your machine when you're there, the box when you're not (#315)
#312 made dispatch deterministic, which was right, but it picked "cloud" as the
global default, which was wrong. Local and cloud are not two servers, they are
two different products:

  local — runs in your own checkout, the tree your editor already has open,
          with your .env.local, your databases, your CLI logins. You watch it
          happen and the diff is just there.
  cloud — runs in a fresh clone on the box that no editor points at, without
          your local env, and returns work only through git.

So defaulting everything to cloud silently moved work to a machine nobody is
looking at. The product's own copy already said as much — it dispatches "against
local folders and your own CLI logins", calls hosted builders "private beta",
and describes cloud as the OFFLINE fallback ("Builder offline — cloud worker
will make the change and open a PR"). That promise was never wired up.

Now it is. pickDispatchChannel is the single routing rule, three tiers, and the
order is the design:

  1. lock     — physics. A dirPath-only project with no cloneable repo can only
                run where the directory is. Never overridden.
  2. presence — policy. A connected desktop means the operator is AT the machine
                → their tree. No desktop means they are away (asleep, lid shut,
                on their phone) → the always-on box, so the work still happens.
  3. floor    — nobody online: still name a target and queue for it, visibly.

Tier 1 must outrank tier 2: routing a laptop-only project to the cloud because
the laptop is asleep hands the agent an empty directory (the 2026-07-14
misroute). Both orderings are negative-tested — deleting either rule from
pickDispatchChannel makes a case fail.

This also fixes the original complaint at its real location. Dispatching from a
phone with the laptop shut now goes to the box, because that is precisely when
local presence is false — without moving at-the-keyboard work somewhere
invisible.

Plumbing: decideQueuedExecution accepts the project and routes with presence
already in hand, so routes stop deriving their own default. DEFAULT_BUILDER_CHANNEL
returns to "local" as the floor. inject-core and the busy-project branch now
consult presence (two small indexed reads on two-row tables).

NOT in this change, deliberately: the UI still never names which builder ran a
dispatch — the channel does not reach the client at all. That is the next
change, and it is the one that actually closes the cognitive-load gap.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 11:45:02 +00:00
cb64cdab9d fix(audit): composite translucent layers before judging contrast (#314)
The contrast audit I shipped an hour ago had the exact defect it was
written to catch. bgOf() took the first non-transparent ancestor
background and treated it as opaque — but the fleet chips are
oklch(1 0 0 / 0.04), a 4%-white overlay on a near-black card. Painted
once, that resolves to SOLID WHITE, so the audit computed dark-grey text
against white and invented failures on text that reads fine.

Colours now resolve to straight RGBA by painting twice over known
backdrops and solving for alpha (white - black = 255*(1-a)), which also
handles oklch/lab/color-mix syntax that no regex can parse. Every
translucent layer between the element and the first opaque ancestor is
then composited, because that stack is what the eye actually sees behind
the glyphs. Translucent text is composited onto its own backdrop too.

Effect on the live /control run: 21 findings → 19. The two that vanished
were chips, exactly as predicted. Everything else is unchanged, so the
headline result stands: the primary CTA "Launch agent" really is 3.03:1.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 11:22:24 +00:00
2562177b27 fix(control): one text column, a findable inbox link, honest counts (#313)
Three separate complaints about the fleet card, each measured before and
after rather than eyeballed.

1. "this area looks bad. not aligned."
   It is. Four stacked rows started at three different x positions —
   title 369, state 383, chips 369, hint 385 — because the pulse dot and
   the autopilot bolt sat IN the text flow and pushed only their own line
   sideways, by different amounts (a 6px dot, a 12px bolt). The wrapped
   second line of the hint snapped back to 369, since an inline icon
   gives no hanging indent. Same zigzag on mobile: 33 / 47 / 33.

   Both icons now ride in a shared fixed gutter and every row pays the
   same padding, so all four share one text column. The gutter is
   1.25rem because that is exactly where .ui-control-fleet-runner already
   puts its label (14px icon + 6px gap) — the runner line and the
   autopilot block now agree by construction instead of by luck.

2. "Full inbox — i dont see it."
   Measured 3.13:1 on the card surface at 12px: below the 4.5:1 WCAG AA
   floor, and less than half the contrast of the "New feedback:" label
   directly above it (6.38:1). It is the only route to a report's
   screenshot, history and widget setup. An action nobody can see is a
   feature that does not exist. Now text-text-secondary, with a visible
   underline.

3. "is there really 0 working?"
   The number is right about what it measures and wrong as a picture of
   the fleet. FleetCrown counts agents it dispatched plus workspaces the
   runner tracks by project name; agents started outside it are invisible
   — 8 were running while the card read "0 working". The Workspaces panel
   already admits this, most of a page further down. The caveat now rides
   on the chips that provoke the question.

Adds scripts/test/contrast-audit.mjs (npm run audit:contrast): finds
interactive labels below their AA floor on authed routes. Scoped to
actions on purpose — auditing every text node would bury the signal,
since --text-tertiary is itself sub-AA with ~429 usages.

Its first run reported 9 controls on a page with 55 — networkidle never
fires on a page holding an SSE stream, so it measured the server shell
and called it clean. It now settles on a stable DOM and prints the
per-route count, so under-measurement is visible rather than silent.
Against live /control it finds 21 sub-AA actions, worst being the
primary CTA "Launch agent" at 3.03:1.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 11:06:17 +00:00
0b62239b61 fix(dispatch): an unrouted command is a race the always-on box loses (#312)
A queued command whose payload carries no `channel` is claimable by EVERY
connected runner — the claim gate reads

    payload->>'channel' IS NULL OR payload->>'channel' = <mine>

so "no channel" means "all of them", not "any, preferably cloud". With both
the box-runner and a desktop Fleet Runner polling, the desktop routinely won
the race, and closing the laptop lid then killed exactly the work it had just
claimed. That is why execution still felt laptop-bound even though the box has
been fully capable since P1 (claude CLI installed and authed, 21 repos,
clone-on-demand + trust pre-seed in box-workspace.ts).

The routing mechanism was already there and already correct — the default was
just expressed at four call sites, and drifted. Two passed "cloud"; two passed
`null` while their own comments claimed they matched the cloud-defaulting
branch. So this is an SSOT fix, not a new feature:

- DEFAULT_BUILDER_CHANNEL joins BUILDER_CHANNELS as the single definition.
- projectPreferredChannel no longer returns null. Making the absent case
  unrepresentable means the compiler — not a comment — is what stops a fifth
  call site from silently emitting an unrouted dispatch.
- All four call sites collapse to projectPreferredChannel(project).
- The now-dead `...(ch ? {channel: ch} : {})` spreads become plain fields.

Locus still wins over preference: a dirPath-only project with no cloneable
repo stays pinned to "local", because the cloud builder would clone-fail and
invent an empty workspace (the 2026-07-14 misroute).

Tradeoff, stated: dispatches now name a target, so if the box-runner is down
they queue for it instead of falling through to a desktop. That is already the
shipped behavior for local-pinned dispatches, and the routes surface
runnerConnected for the chosen channel, so it queues visibly rather than
vanishing.

scripts/test/builder-channel-routing.ts pins the closed side — not "cloud is
usually chosen" but "a channel is ALWAYS chosen", across every project shape
including the half-populated rows real user_projects produce. Verified the
gate fails when the null fallback is reintroduced.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:29:27 +00:00
429a634a66 feat(runner): make the Linux runner actually update itself (#311)
The in-app updater has been failing silently on this box: it checked,
found 0.8.12, downloaded it, posted "Fleet Runner v0.8.12 ready" — and
stayed on 0.8.11 for twelve days. A notification is not an update.

Four independent causes, each sufficient on its own:

  1. The install was an extracted directory, so detectInstallFormat()
     returned 'unknown'; on Linux electron-updater can only self-apply an
     AppImage, so it picked the .deb asset...
  2. ...which needs `sudo dpkg -i`. Electron cannot escalate from
     userspace, so the download parked in the updater cache forever.
  3. The systemd unit hardcoded the version in the path
     (ExecStart=.../FleetRunner-0.8.11/fleet-runner). Even a perfect
     self-update would have been reverted on the next boot.
  4. The box cannot run an AppImage at all — type-2 AppImages need
     libfuse2 and this machine has only libfuse3, so pointing the unit at
     an AppImage crash-loops with "AppImages require FUSE to run".

Cause 4 is the one that wastes an afternoon: `--appimage-offset` succeeds
without libfuse2 (it only reads the ELF header, it never mounts), and
/dev/fuse + fusermount3 both exist. The honest check is
`ldconfig -p | grep libfuse.so.2`.

So: download, verify sha512 against latest-linux.yml, EXTRACT (needs no
FUSE, works on any libfuse generation), and flip a stable symlink. The
symlink is the record of what is installed — no version file to drift
from the tree it describes. The swap is atomic, and nothing touches the
symlink until the download is checksum-verified AND the extracted tree is
confirmed to hold a runnable binary, so a failed update leaves the
running version alone. One previous build is kept for rollback.

A systemd timer applies updates: daily, Persistent=true, plus 10 minutes
after login. It does not depend on the app being healthy, on a quit hook
winning a race against SIGTERM, or on sudo. Everything is user-scoped —
a background updater that needs a password is one that never runs.

Verified on real hardware, not just enabled: rolled the symlink back to
0.8.11, ran fleet-runner-update.service exactly as the timer does, and
watched it detect, verify, extract, swap and restart onto 0.8.12 in 53s.
Control now reports `app v0.8.12`; a second run says "already current".

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 10:20:22 +00:00
317a7ba8fe refactor(ai): adopt ai-ration — the chain, the 429 kinds and the ration leave this repo (#310)
The three modules that keep Loki on free tiers were never FleetCrown-specific.
They were written here because this is where the failures happened, but the
knowledge belongs to every project in the fleet that talks to an LLM — and a
survey found seven repos calling these same providers, three of which had
independently grown their own provider registry, and none of which distinguish
the three kinds of 429.

So they are extracted to `ai-ration` (github:maonakamoto/ai-ration#v0.1.0,
MIT, 31 tests) and consumed from there:

  src/lib/ai-budget/fair-share.ts  → re-export
  src/lib/agent/groq-error.ts      → re-export, keeping the Groq-flavoured names
                                     its callers were written against
  src/config/chat-models.ts        → keeps the WIRING (the LOKI_* env prefix and
                                     the call signatures callers use); the chain
                                     logic and the probed free-model table come
                                     from the package

Not one caller changed, and the box needs no new environment variables:
`freeChain("LOKI")` derives exactly the LOKI_GROQ_MODELS / LOKI_GROQ_DAILY_TOKENS
names already set there.

The extraction was not a copy. Writing the package's tests surfaced a defect that
had shipped here: `humanizeWait`'s singular branch was unreachable. With the
minutes/hours boundary at 90, anything reaching the hours branch divided to at
least 1.5, which rounds to 2 — so "about 1 hour" could never print and an
hour-long wait was announced to the user as "about 2 hours". Fixed upstream at
the boundary, and this repo inherits it by re-exporting rather than copying.
That inheritance is the whole point: a local re-implementation "just for one
tweak" is how the shared version silently becomes the stale one.

Verified: tsc, lint, check:desktop, and the four suites that cover this surface —
chat-chain (13), groq-error (17), fair-share (16), ai-budget-gate (10) — all
green against the installed package, which was proven to install from GitHub
(prepare builds dist, 15 exports resolve) rather than only from the working tree.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:15:11 +00:00
0ffe305a62 fix(api): a second route shipped the user's credential hashes — and the gate that ends the class (#309)
* fix(api): a second route was shipping the user's credential hashes

POST /api/onboarding returned the whole users row — `{ ok: true, user }` —
so passwordHash and privateZonePinHash went to the browser on every
onboarding finish, exactly as GET /api/me did before #306. The client never
read that object; it checks `res.ok` and nothing else.

It survived the grep that found #306 only because it was nested one level
deeper (`json({ ok: true, user })`, not `json(user)`). That is the second
instance of one class, so this stops being something to grep for:

- scripts/test/no-raw-user-response.ts scans every route handler and server
  action, taints identifiers bound to a whole users row, and fails if one
  reaches a response call unprojected. Negative-tested against the real
  pre-fix source — it flags both branches — plus 13 fixtures covering the
  nested, shorthand and spread forms.

And the export had grown a second answer to the same question:

- src/lib/account-export.ts kept its own REDACTED_USER_FIELDS deny-list, so
  a secret column added later would be withheld by /api/me (allow-list) and
  shipped by /api/me/export (deny-list that never heard of it). Both now
  project through user-client-view.ts, which is exhaustive over the schema.
  The export additionally omits Stripe ids — a policy narrowing of the
  allow-list, not a second notion of what is secret.
- buildExportManifest generates its `excluded` lines from those same lists,
  so the document describing what was withheld cannot drift from what was,
  and the test asserts the linkage rather than a copy of the wording.

Verified: tsc clean, eslint 0 errors, 88/88 unit files, design-system ok.

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

* fix(ci): the deploy-ref fixtures inherited a handle to the real repo

The husky pre-push hook exports GIT_DIR — for a worktree push that is
.git/worktrees/<name>, the real repository. scripts/test/deploy-ref-gate.sh
runs from that hook, so every git call in the fixture suite inherited it.

An explicit GIT_DIR is not a search path, so GIT_CEILING_DIRECTORIES (guard 1)
did not constrain it, and the g() assertion (guard 2) could not see it either:
with GIT_DIR set and no work tree, `git -C <fixture> rev-parse --show-toplevel`
answers `<fixture>` — matching exactly, while objects and refs land in the real
repo. The suite this file was written to make safe was, from a hook, pointed
back at the thing it must never touch.

Guard 5 ($TMP must not be inside a repo) is what actually held the line, and it
held it by failing closed: with GIT_DIR set, an empty mktemp dir reads as a repo
root, so every push from a worktree died with "temp dir is inside a git repo" —
a true refusal with a misleading reason, and no way to push at all.

Now the ambient git environment is cleared first, from `git rev-parse
--local-env-vars` so it cannot fall behind a new variable. Test 9 re-runs the
whole suite with GIT_DIR pointing at a decoy repo and asserts both that it
passes and that the decoy is unchanged.

Verified to bite: with the unset removed, test 9 fails and the child run dies at
guard 5 exactly as the real push did.

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

* refactor(ci): one definition of an isolated git fixture

not-behind-gate.sh has the same inherited-GIT_DIR hole the previous commit
fixed in deploy-ref-gate.sh — and found it itself: run from the pre-push hook,
its own isolation probe reported "g() accepted a non-repo dir nested in a repo
— it would have mutated the ENCLOSING repo". Correct, and it was right.

Fixing it in place would have been the third copy of the same paragraph. The
copies are the hazard: both suites carry scars from 2026-08-15, each was
hardened against what its own incident taught it, and neither against the
other's — deploy-ref-gate knew $TMP must not sit inside a repo, not-behind-gate
knew a fixture must never write git config. A third suite would have copied
whichever file it sat next to.

So the four properties that must hold before a fixture touches git now live in
scripts/test/lib/git-fixture-env.sh, sourced by both. Each suite keeps its own
g() — the per-command assertion that the directory about to be mutated is the
fixture — because their fixture shapes genuinely differ.

Verified under the real hook environment (GIT_DIR=.git/worktrees/<name>):
deploy-ref-gate 9 passed, not-behind-gate 15 passed.

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-16 09:41:51 +00:00
79d325ae29 feat(runner): land the operator on Control, not the marketing hero (#308)
Fleet Runner starts with the OS and loads APP_URL with no path, so a
signed-in operator's first screen every morning was the public landing
page — "Run your fleet. From anywhere." with an Open FleetCrown button.
That is a pitch written for a stranger. It suggests nothing to do, and
it costs a click before any agent can be launched.

Everything the operator actually wants is already on /control: per
project "Launch agent" (agent + model + initial prompt), multi-select
with "Build selected" to start work across several projects at once,
live working/idle counts, and the autopilot switch. They just never
landed there.

Inside the runner, a signed-in operator now goes straight to the command
deck. Browsers still get the marketing page, so does anyone signed out
(they need the pitch and the sign-in path), and so does the runner with
?site — reviewing your own hero from inside the app stays possible.

The rule is a pure function so it is testable; the destination is a
ROUTES entry, not a string in a page. scripts/test/landing-destination.ts
covers both sides of every branch and is picked up automatically by the
unit runner, so nobody can quietly restore the old behaviour.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 11:07:35 +02:00
0d1562d868 fix(ai-budget): the admission estimate was 37% below the first real turn (#307)
`ESTIMATED_TURN_TOKENS` decided admission before any provider reports a
cost, and it was documented as "deliberately on the high side" at 10,000.
The first turn to reach the production ledger cost 15,839 tokens — one
tool call, answered on openrouter/openai/gpt-oss-20b:free. The estimate
was not on the high side; it was ~37% low, and wrong on the first sample
rather than at some tail.

That error runs in exactly the wrong direction. Under-estimating admits
turns the pool cannot cover, so the day's budget is spent while the gate
still believes there is room — and the user meets a provider 429 instead
of the polite, explained refusal the rationing exists to give them. At
10k against ~200k of free capacity the gate would admit 20 turns for a
solo user where the tokens cover about 12.

Raised to 20,000, which keeps margin over the observation because 15,839
is one sample of the CHEAP shape: a turn calling several tools, or one
that runs the repair pass, spends more. The `turns` column in `ai_spend`
exists so this becomes a measured mean once there is traffic to compute
one — the constant should end up a query, not a better guess.

Two of the gate tests hardcoded token counts around the old value, so
raising it silently moved the `paced` case into the `share-spent` branch
— the test still passed its refusal assertion while no longer exercising
the case it names. They are now expressed in units of the constant, so a
future recalibration cannot quietly relabel what they cover.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 07:38:29 +00:00
bb4bf5100f fix(api): /api/me hands the browser two credential digests (#306)
GET /api/me returned the Drizzle row verbatim, so every authenticated page
load shipped `passwordHash` and `privateZonePinHash` to the client. PATCH
did the same via .returning(). Both are the caller's OWN — this is not a
cross-account leak — but a credential digest in a page response is reachable
by everything the page is reachable by: an extension, an XSS, a logging
proxy, a screenshot of devtools. The PIN hash is the sharper end: it guards
the private zone and protects a short numeric secret, so an offline attempt
against it is cheap in a way a password hash is not.

Fixed as an allow-list, because the failure worth engineering against is not
these two fields — it is the secret column added next year to a route nobody
re-reads. Both halves are exhaustive over the schema, and
scripts/test/user-client-view.ts fails until every column in `users` is named
as exposed or withheld, each withheld one with its reason. Negative-tested in
both directions: removing a field from the list fails, re-exposing
passwordHash fails.

No client read either field — Settings, onboarding and the smoke test use
id/name/username/plan, and the private-zone UI needs only privateZonePinSetAt
(the fact a PIN exists), which stays.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 15:30:15 +00:00
33d7e62b30 fix(terminal): a viewer may follow the session's size, never shrink it (#305)
Opening /terminal in a short browser window posted
{kind:"resize", tab:"Tab #1", cols:74, rows:1} — twice — and the runner
applied it to the live zellij tab. The xterm mirrors its own measurements
onto the real PTY, so a collapsed host (mid-mount, hidden panel, phone with
the keyboard up) reflows the session an agent is actually working in, and a
TUI reflowed to one row loses its screen.

Two enforcement points, different on purpose:

- the client knows what it last published, so it stays silent on a
  degenerate measurement AND on an unchanged one — ResizeObserver fires on
  every layout pass, and each duplicate was a real POST waking the runner to
  re-apply a size it already had (that is the "twice" above);
- the boundary knows nothing about its caller, so it can only floor what
  arrives — an old bundle or any other client is bound by the same rule
  without importing the client's decision.

The floor (40x6) sits below any real viewport — a 320px phone still measures
~45 cols — and above what a collapsed container reports.

Also drops a duplicate poller: TerminalSurface called useBuilderPresence
directly AND via useTerminalTabs, so /terminal hit /api/builder/presence
twice per interval for one page. The hook now returns the snapshot it
already polls.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 15:21:28 +00:00
776d12b625 feat(ai-budget): enforce the ration, and bill it from the provider's own count (#304)
#303 shipped the fair-share policy with nothing calling it. This wires it in, so
the free daily pool is actually divided instead of merely divisible.

  ai_spend            one row per (user, UTC day). A rollup, not an event log:
                      the only questions asked are "what has this user spent
                      today" and "how many drew today", both on the hot path of
                      every turn. UTC because the vendors reset on UTC midnight;
                      bucketing on local midnight would hand out a share against
                      a budget that had not refilled.
  dayCapacityTokens() sums the daily budget of every KEYED provider. A vendor
                      whose key is absent contributes nothing, however generous
                      its tier — counting it would ration users against tokens
                      that cannot be reached.
  askLoki             gates the WHOLE turn once, before any provider is called.
                      Gating per path would burn the budget on two fallbacks and
                      still say no.

BILLED FROM REALITY, NOT FROM A GUESS. `llm.ts` now reads the provider's own
`usage.total_tokens` and `loop.ts` sums it across every round AND the repair
pass. Charging only the final call would under-count the expensive turns by the
most — precisely the ones worth rationing. Admission still uses an estimate
because it must decide before anything is spent, and it is deliberately on the
high side: under-estimating admits turns the pool cannot cover, which produces
the late-day wall this whole mechanism exists to prevent.

Booked on paths that are easy to forget: a turn that produced no usable text
(the tokens were spent anyway), a repair pass that was discarded (same), and the
degraded Groq fallback (it draws on the same pool, so a user degraded onto it
would otherwise spend the shared day for free).

THE GATE FAILS OPEN. If the ledger cannot be read, the turn is admitted.
Rationing is a nicety; a database hiccup becoming "Loki is down" is not a trade
anyone would choose. This fleet has already lost a day to a guard that turned a
QUESTION into a fatal step, so the test asserting it is the one that matters
most here.

The two refusals keep their distinct meanings all the way out to the user:
`paced` carries a retry and explains WHY there is a wait ("so everyone gets a
turn" is a reason a person accepts; an unexplained refusal reads as breakage),
`share-spent` carries none and says when it resets. Offering a retry that cannot
succeed today is the "try again shortly" lie in another costume.

Migration is additive only — CREATE TABLE + FK + index, no destructive
statements. The unique (user, day) index is load-bearing: without it two
concurrent turns both read zero, both insert, and that user gets two rows and
twice the share. The increment happens inside the database.

Tests: 10 for the gate (fail-open, capacity SSOT, both refusals, a newcomer
admitted at any hour), on injectable seams so they need no database — the
behaviour worth proving is exactly what a DB-dependent test would not cover.

tsc clean · eslint 0 errors · 85/85 unit files · 150 home tests · design ok ·
desktop ok.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 14:20:08 +00:00
3c9dce9f28 feat(ai-budget): ration the free tier so a latecomer can still get in (#303)
The free tiers this fleet runs on are metered per DAY and shared: ~100k tokens a
day across the whole org, ~10k per chat turn. That is about ten turns for
everyone combined. Divided badly, the first enthusiastic user spends the day
before lunch and everyone after them meets a wall — including whoever is trying
the product for the first time, who concludes it is broken and does not return.

So the objective is not throughput. It is "every ACTIVE user gets a usable
amount, every day", which favours a different design.

Two mechanisms, both load-bearing:

  SHARE  — capacity / active users, recomputed per request so the split tracks
           reality rather than a number set once in a config file. "Active"
           means users who actually drew TODAY, not everyone registered:
           rationing against dormant accounts would starve a quiet day and
           waste budget meant to be spent generously. One user alone correctly
           gets the whole thing.

  PACING — a share is a whole-DAY allowance, but the day is consumed in order.
           Without pacing, three users can each spend their full share by 09:00
           and the fourth finds nothing left, with nobody having exceeded their
           split. The allowance therefore unlocks gradually.

Writing the tests found the flaw in doing only that: with four active users on a
100k day, pure pacing allows 6250 tokens at midnight and REFUSES a 10k turn,
telling a first-time user to come back in three hours. So the allowance never
sits below the cost of a single turn, capped by the share — everyone gets one,
then pacing governs the rest. A share too small for one turn is a wall wearing a
ration's clothes.

The two refusals are kept distinct because they need opposite responses, the
same lesson as the Groq 429 work: `paced` carries a retry (waiting genuinely
helps), `share-spent` carries none (waiting cannot help today). Promising a
retry that cannot succeed is the "try again shortly" lie in another costume.

No clawback. A user who spent under a larger share when they were alone is not
punished when others arrive — their allowance stops growing, nothing is taken
back. The tokens are already gone; pretending otherwise only yields confusing
refusals.

Pure on purpose: no DB, no clock, no provider. Everything arrives as arguments,
so the same policy lifts into any project in the fleet without dragging
FleetCrown's storage or model plumbing along.

Tests (16) pin the behaviour, not the arithmetic — including that the retry
advice is CORRECT (replaying at the suggested moment succeeds, and a moment
earlier still fails, so it is neither wrong nor needlessly pessimistic).

NOT WIRED YET: nothing calls this. Enforcement needs a per-user daily spend
table and a hook in askLoki, which lands separately so the schema change gets
its own review.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:57:27 +00:00
95f3f752f6 fix(test): the isolation probe passed with no guard at all (#302)
#300 added a test asserting that `g()` refuses a directory which is not its own
fixture repo — the walk-up that published fixture commits to GitHub. The test
was decorative. It probed a bare `"$TMP/not-a-repo"`, and since nothing above
$TMP is a repo, git finds nothing whether or not any defence exists. Removing
the assertion entirely leaves that probe passing.

Which is the same mistake the file was written to remove, one level up: #300
replaced a tautological `case "$root" in "$TMP"/*` with a guard nobody had run
against the thing it forbids.

Measured, each with the assertion stripped out:

  bare "$TMP/not-a-repo"           refused anyway  → PASSES WITH NO GUARD
  nested in a repo with NO commit  refused anyway  → `rev-parse HEAD` fails in
                                                     an empty repo too, so an
                                                     escape is indistinguishable
                                                     from a refusal
  nested in a repo WITH a commit   exit 0, returns the enclosing repo's sha
                                                   → the only shape that bites

The probe now builds an enclosing repo, gives it a commit, and targets a
non-repo directory inside it. Verified directly: with a bare `git -C` in place
of `g`, that call resolves to the enclosing repo and exits 0 — exactly the
condition the assertion trips on.

Honest note on the evidence: stripping `g()` from the whole suite makes it fail
at test 1 rather than test 8, because setup_repo's origin assertion depends on
the helper too. So the whole-suite strip is NOT a clean demonstration of test 8.
The targeted probe above is what proves it.

Caught by a colleague reviewing the merged fix, who hit all three shapes on
their own copy before flagging it.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:53:51 +00:00
d6739a3030 feat(loki): a fallback within one vendor is not a fallback (#294)
Loki's tool loop was pinned to a single vendor, and its only degradation was a
step-down to a SMALLER MODEL AT THAT SAME VENDOR. Once the vendor's daily
budget was spent, every link in the "fallback" drew on the same exhausted pool,
so they all died together. On a free tier that is not a rare edge: Groq grants
100k tokens/day org-wide, shared with the dispatch strategist, form-assist and
autopilot, and one chat turn costs roughly 10k.

The vision half of this repo already learned this, the hard way. vision-models.ts
carries the lesson after four pinned free models rotted: "A CHAIN, not a model.
Free-tier models disappear and rate-limit; a single pin is a scheduled outage."
The chat half never got it. This applies the same shape, so the repo has ONE
answer to this problem instead of two.

  - config/chat-models.ts: CHAT_CHAIN, the SSOT, mirroring VISION_CHAIN. Every
    provider speaks the OpenAI chat-completions shape, so adding a vendor is a
    row in a table rather than a new client.
  - llm.ts walks the chain, and what it does next follows from WHY a link
    refused: `size` continues (another vendor's window may be far larger, and
    the size error is only surfaced once EVERY link refuses, since that is what
    loop.ts sheds facts on); `daily` skips that vendor's remaining models
    wholesale; `capacity` advances. A whole chain refusing on capacity alone is
    the one case where waiting is right, so it waits once, bounded.
  - probe-models.ts probes the whole chain via callModelLinkOnce, NOT the
    walker: a walk reports whoever answered, so probing "is gemma usable?"
    through it would happily return another link's success and pin a dead model.

Every entry was PROBED LIVE before being pinned, not taken from docs. The free
catalogue was enumerated by filtering OpenRouter's /api/v1/models for
pricing.prompt == "0" and supported_parameters containing "tools", then each
candidate was sent a real tool call. Nine links answer; two are excluded on
evidence (gemma-4-31b returned a provider error, nemotron-nano-12b-vl returns
200 with EMPTY content, which a naive client reads as a successful empty
answer).

FIVE of the nine answer only via the TEXT protocol. A native-only loop would
have silently lost most of this chain — the concrete payoff of llm.ts always
parsing both.

Model lists are read from env AT CALL TIME (LOKI_GROQ_MODELS /
LOKI_OPENROUTER_MODELS), so routing around the next rotted model is an env
change on the box rather than a redeploy. A value frozen at import would have
needed the very delay the override exists to avoid.

agent-name-lookup.ts asserted the old SMALL_MODEL constant. Its INTENT was "a
rate limit must step down, not abandon the tools" — which the chain serves
better — so the assertion is rewritten to that intent and gains a guard that
the chain spans 2+ vendors, the property that makes it worth having.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:43:36 +00:00
504a38f4bb test(deploy-gate): pin the fixture isolation, and stop writing git config (#301)
Follow-up to #299, from the session that diagnosed the main-overwrite:
the write that escaped a single branch was not the push, it was
`git config`. The sibling fixture's `config core.hooksPath /dev/null`
landed in the SHARED /home/g/dev/fleetcrown/.git/config, silently
disabling husky for the main checkout and every worktree — so for part
of that day `--no-verify` was a no-op, because there was no hook left to
skip, and anything committed in that window skipped the local gate.

So this suite stops persisting anything. Identity and hook suppression
move to the environment (GIT_CONFIG_GLOBAL/SYSTEM=/dev/null, GIT_AUTHOR_*,
GIT_COMMITTER_*) plus per-command `-c core.hooksPath=/dev/null`. Neither
can survive into a config file the rest of the fleet reads, even if
something later gets past the ceiling.

Every git call now goes through g(), which re-asserts that the directory
it is about to mutate really is the fixture — per command, because the
property that matters is "this command writes here", not "this path
looked right during setup". Physical paths on both sides so a symlinked
TMPDIR is not a false mismatch.

The point of this commit is the two tests that pin the isolation itself,
and getting them to actually bite took three attempts:

1. `g` must refuse a non-repo directory. Written first as a bare
   "$TMP/not-a-repo" — DECORATIVE: $TMP is under /tmp, nothing above it
   is a repo, so git finds nothing whether or not any defence exists. It
   passed with the ceiling removed.
2. Rewritten with the fixture nested INSIDE a repo, which is the
   real-world shape (a TMPDIR under a checkout, exactly how the sibling
   suite reached the real project). Still decorative: the enclosing repo
   had no commits, so `rev-parse HEAD` failed there too and an escape
   still looked like a refusal.
3. Enclosing repo now has a commit, so an escape returns a real sha and
   exit 0. Verified the suite FAILS (exit 1) with g()'s assertion
   stripped, and passes with it.

The second test forbids `git config` in command position, and is
verified to fail when a config write is reintroduced. It is anchored to
command position deliberately: a line that merely mentions the words
(the failure message does) is prose.

That a guard needs three attempts to stop being decorative is the whole
lesson of this incident — the original `case "$root" in "$TMP"/*)` was
never run against the case it claimed to prevent.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 14:40:45 +02:00
1caa6b3e98 fix(test): the deploy-gate fixture could destroy the repo it runs in (#300)
This suite runs from the husky PRE-PUSH hook, so it is armed on every push from
every session. Today its fixtures fell through to the real checkout, and because
pre-push runs BEFORE the transfer, git then pushed what the fixture had just
mangled: `refs/heads/main` on GitHub ended up pointing at a fixture commit whose
tree is a single file named `f`. It also wrote `core.hooksPath=/dev/null` into
the SHARED .git/config, silently disabling every hook for every worktree until
someone noticed.

The mechanism is `git -C <dir>`: when <dir> is not a repo, git WALKS UP the
directory tree and operates on whatever repo it finds. `setup_repo` then ran
`git branch -M main` and `git push origin main` against the real one.

I wrote the guard that was supposed to prevent this, and it was theatre:

    case "$root" in "$TMP"/*) ;; *) fail ... ;; esac

`$root` is constructed as "$TMP/a", so the pattern can never fail. It reads like
containment and enforces nothing. Test 6 did not even go through setup_repo — a
bare `git init "$TMP/e"` with no guard at all, which is why its failure ("gate
blocked a checkout with no origin/main") was the first visible symptom: the gate
resolved the REAL origin/main because it was operating on the real repo.

Rebuilt so that no single failure can reach a real repo:

  1. GIT_CEILING_DIRECTORIES="$TMP" — git will not search for a repository above
     the temp dir, so the walk-up that caused this cannot physically happen.
  2. Every git call goes through `g`, which asserts the target resolves to
     exactly that fixture path (physical paths, so a symlinked TMPDIR is not a
     false mismatch). There are no bare `git -C` calls left.
  3. Pushes name an explicit PATH, never the remote `origin` — a fallthrough now
     has nowhere to publish. The fixture's own origin URL is asserted too.
  4. Identity and hook suppression come from ENV, never `git config`. A config
     write is what corrupted the shared config; env cannot leak.
  5. $TMP is refused outright if it sits inside a git repo.

Test 8 is new and pins the property that was missing: `g` must REFUSE a
directory that is not its own repo rather than letting git walk up. Without the
ceiling that call resolves to the surrounding worktree; with it, git says
"fatal: not a git repository".

Verified after the rewrite that the real repo is untouched by a run — HEAD,
branch, reflog and core.hooksPath all unchanged.

Scope note: scripts/test/not-behind-gate.sh inherited the same false guard and
is being fixed separately in #299 by its author, so it is deliberately not
touched here.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:37:58 +00:00
186438960a fix(test): a fixture that could reach the real repository (#299)
Today the sibling suite deploy-ref-gate.sh ran from the husky pre-push
hook, mutated the REAL checkout instead of its temp fixture, renamed a
feature branch to `main`, and pushed a single-file tree over
github.com/maonakamoto/fleetcrown's default branch. The whole codebase
was gone from main until it was restored to cc4e8925.

This suite had inherited the same non-defence, so it gets the fix even
though it never pushes — `checkout --orphan`, `rm -rq --cached .` and
`checkout --detach` aimed at a real checkout are damage without needing
a remote.

The mechanism is that `git -C <dir>` does not confine git to <dir>. If
<dir> is not itself a repo, git walks UP until it finds one, and from
anywhere under a checkout the one it finds is the real project.
Demonstrated read-only:

  WITHOUT the ceiling: git -C <non-repo> -> /home/g/dev/fleetcrown/...
  WITH the ceiling:    fatal: not a git repository

The guard that was supposed to stop this is worse than nothing:

  case "$REPO" in "$TMP"/*) ;; *) fail ... ;; esac

REPO is constructed as "$TMP/repo", so the pattern cannot fail. It is a
fact about how the path was spelled, not about where git will actually
write, and it reads exactly like containment while enforcing nothing.

Replaced with two real defences: GIT_CEILING_DIRECTORIES stops the
upward search at the temp dir, so a fallthrough finds NO repo rather
than the wrong one — which kills the class rather than this instance —
and an assertion that the fixture's actual `rev-parse --show-toplevel`
is the fixture, checked before any mutating command runs.

deploy-ref-gate.sh is being fixed in parallel by the session that
diagnosed it; this change is deliberately limited to the file I added,
so the two do not collide.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 14:27:38 +02:00
cc4e892559 perf(deploy): the pipeline was waiting, not working (#293)
Merge→live measured 14–27 minutes. The irreducible work in that window is
about 80 seconds: build 66s, rsync 4s, restart 4s, verify 7s. Nearly all
of the rest was waiting, so nearly all of the fix is removing waits
rather than making anything faster.

Two waits, measured:

1. The runner drain, 480 of the ship step's 570 seconds. The deploy
   watched one in-flight agent, then restarted anyway at the cap. The
   web app had been live and verified for eight of those minutes. Two
   systems with opposite needs were sharing one job's wall-clock — the
   app wants to be live now, the runner wants to not kill anyone's work
   — and the runner won every time.

   A shorter timeout would only kill agents sooner. The wait itself is
   fine; the place it happened is what cost. Waiting is expensive in CI
   and free on the box, so it now happens on the box: the deploy
   schedules a detached systemd-run unit and returns as soon as the app
   is verified. The drain gets *longer* (1800s, not 480) and cheaper at
   the same time, because nothing is holding a runner open for it.

2. The CD reconciler, up to 10 minutes and 18.6 of #284's 26.8. Deploy
   chains off CI via workflow_run, which never fires for a CI run that
   GITHUB_TOKEN started — i.e. for every auto-merged PR, the only path
   that merges code here. The sweep covered that by reconciling on its
   next tick: correct, self-healing, and late.

   A dispatch is not a push, so it is not subject to the no-cascade
   rule. ci.yml now dispatches Deploy itself the moment main goes green.
   The sweep keeps its reconciler as the safety net, which is the right
   shape for "did something get missed?" and the wrong one for "did
   something just happen?".

Also caches .next/cache across deploys — the build is the one part of
this that is genuinely work, so it is the one part worth shrinking.

Not done, and worth saying: I thought CI and Deploy each built the app,
so the tested artifact was never the shipped one. That was wrong. ci.yml
deliberately skips `next build` because App-Router pages query Postgres
during pre-render; the build happens once, in Deploy. There was no
discarded build and no artifact to pass.

The decoupling has a test, and it asserts the property rather than the
patch: the deploy must not block on a drain, the restart must be
detached, the script must be shipped before it is invoked, and the drain
must stay bounded. Verified the first two assertions fail against the
previous version (4 blocking markers, 0 systemd-run) rather than merely
passing against this one.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:58:29 +00:00
be7f9c2a71 fix(deploy): a deploy that dies silently should still say where (#292)
#289 fixed the command that killed three deploys with no output. This is
about the ten seconds it took to see that, versus the investigation it
actually took.

deploy-hetzner.sh runs under `set -euo pipefail` and several of its commands
redirect both streams to /dev/null, because they are questions about the box
rather than steps of the deploy. When one of those exits non-zero the script
dies where it stands, and the operator's entire trace is:

    → deploy FAILED (exit 1): 6b6cff0 — see /tmp/push-deploy-fleetcrown.log

That names the commit, and points at a log file which — in CI, where this
failed — lives on a runner that no longer exists. It does not name the step,
so the only way to find the dead command was to read the script and reason
about which line between the last successful echo and the trap could exit 1
without printing. That is the diagnosis this line should have handed over.

DEPLOY_STEP names the current phase and the failure message carries it:

    → deploy FAILED (exit 1) during [reading the live build marker]: 6b6cff0

Four phases are marked — the two gates, the marker read, and the rsync. The
helper is a bare assignment to a variable: no subshell, no pipeline, no
substitution, nothing `set -e` can trip over. A diagnostic that can fail the
thing it diagnoses would be a liability, which is the same lesson #289 landed.

Tests assert the property rather than the edit, and both were verified to FAIL
against the broken shape: dropping ${DEPLOY_STEP} from the message, and adding
a phase without a step() call before it. The first assertion I wrote passed
against a COMMENT quoting the old message — so it now skips comment lines,
because a test that matches prose lets the real line drift while staying green.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:11:50 +00:00
eb51e9bc9d feat(demo): a sandboxed demo, where exemption is what you type (#290)
FleetCrown was the last app in the fleet without demo access, and the only
one where a careless demo is dangerous: it dispatches agents onto a real
box, opens real terminals, and spends real API credit.

So the demo is sandboxed rather than read-only. It may create projects,
edit prompts and move around its own tenant; everything that leaves that
tenant is denied at two independent layers.

The layers fail differently on purpose. Layer 1 is a route policy applied
in authorized(), which every authenticated request already passes through.
Layer 2 sits at enqueuePendingCommand — the single row Fleet Runner polls
to type into a shell — and does not import the policy, so widening a list
by mistake still cannot reach the machine.

The tests are the load-bearing half. A deny-list cannot see what it does
not name, and this one shipped two invisible holes while being written:
eight entries covered paths the proxy matcher excludes and could never
have fired, and /api/agent-tokens — which mints credentials — was missed
entirely. Both were found by asserting against what is on disk rather than
against a fixture. All 65 API families are now classified, and a new one
fails the suite until someone says which it is.

The reset deletes a user and everything they own, on an instance whose
other rows are real. It refuses without DEMO_ACCESS_ENABLED, resolves its
target by email alone with no parameter to point it elsewhere, and derives
the child tables from the live foreign-key catalog — a hand-written delete
order is exactly what silently rotted on aoz-housing.

Co-authored-by: Mao Nakamoto <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:04:44 +00:00
5a5329d61f fix(deploy): the guard against bad deploys was blocking all of them (#289)
My own regression, shipped in #285 and broken within minutes: deploys
of 15faf227 and 6b6cff07 both failed, silently, with no output between
"✓ table ownership reconciled" and the error.

deploy-hetzner.sh runs under `set -euo pipefail`. Reading the box's
build-ref marker is a QUESTION, not a step of the deploy — but written
as a bare pipeline it behaves like one: if the marker is absent `cat`
exits 1, `pipefail` propagates that through the substitution, and
`set -e` kills the script. The guard that would have explained itself
never got to run, so the deploy died with nothing printed at all.

`|| true` on both sides — the remote command and the local
substitution — turns an unanswerable question back into an answer of
"don't know". check-not-behind.sh already treats an empty marker as
"cannot tell, ship anyway", which is the correct behaviour and was
never reached.

The lesson is the one the gate itself is built on: a check that can
fail closed on its own plumbing is worse than no check. It must be
impossible for this guard to stop a deploy for any reason other than
an actual backwards ship.

Three tests, since asserting the fix is not the same as asserting the
property: the real line must stay `|| true`-guarded (verified this
assertion fails against the broken version rather than merely passing
against the fixed one), the shape must survive a non-zero read under
`set -euo pipefail`, and an empty marker must reach the ship-anyway
path rather than the refusal.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:49:37 +00:00
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
6b6cff070c fix(loki): shedding records was silent, so the count was confidently wrong (#286)
Asked "how many projects am I tracking, and what are their names?",
prod Loki answered "You are tracking 5 projects" and named them, with
citations. The account holds 22. The five were simply the tail of the
list that survived trimFactsToBudget — sbb-lost-found, solon,
surf-your-life, truthseeker, vitareba, the last five alphabetically.

Nothing in the prompt told the model a longer list existed. It received
a short list and answered the question in front of it, correctly. A
wrong count that arrives with source citations is worse than "not in
your data": it reads as a checked answer, and the most basic question
you can ask a fleet dashboard is how many projects it is watching.

facts.ts already solved this exact problem one level down — a field
with no value renders as `<not recorded>` rather than being omitted,
because a stated negative is far harder to overwrite than silence.
Budget-dropped records had no such statement. So give them one: when
the fit sheds records, the prompt now says how many were withheld, that
the list is therefore incomplete, and that a total must not be stated
from it.

The notice is measured INSIDE fitFactsToBudget rather than appended
after it — otherwise the very text that reports the shedding is what
busts the budget and causes more of it.

Not fixed here: the counts themselves still come from records rather
than SQL. Directives (core/contract.ts) are the right home for an exact
count and are currently built only for the daily brief. This change
stops the confident wrong answer; it does not yet produce the confident
right one.

Guard: four cases in test:fact-budget, including that the notice is
charged against the budget. Verified they bite by reverting the notice
to a no-op and watching the suite fail.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:25:51 +00:00
15faf227b8 fix(deploy): a week-old main still passes "are you on main?" (#285)
Production was rolled back today and self-healed before anyone looked.
CI shipped main at 09:47 and verified it live at 09:48 — the deploy log
says "live build is fe9395b950 — the commit this deploy shipped". Ten
minutes later /opt/fleetcrown/app was overwritten with a tree ~25
commits old, and for the next ten minutes production served the
previous day's code, including a health endpoint too old to report
which commit it was running. The next unrelated deploy quietly put main
back.

check-deploy-ref.sh was supposed to have ended this class, and it
cannot: it asks "are you on main?", which every commit that ever landed
on main answers yes to, forever. A checkout sitting on last week's main
walks straight through it. The build-ref marker added in #279 makes the
damage visible after the fact, which is how this was found, but nothing
made it impossible.

So gate on the direction of the move instead of the name of the branch:
the commit currently live must be an ANCESTOR of the commit being
shipped, i.e. a deploy may only ever add history. An older commit, or a
sideways jump onto unrelated history, is refused with the two subjects
printed and the fix spelled out. ALLOW_ROLLBACK=1 is the override, so a
deliberate rollback is one word, not a workaround.

Undecidable cases warn and allow on purpose — no marker on the box, a
SHA this checkout has not fetched. This gate must never be the reason a
box that is already broken cannot be repaired.

The gate is its own script rather than a branch inside deploy-hetzner.sh
so it can be tested without deploying anything: ten cases over throwaway
git repos, covering the exact regression, the fast-forward it must not
slow down, the override, and every undecidable path.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:16:53 +00:00
404007eb3e fix(loki): a spent day is not a spent minute (#284)
Groq returns 429 for three unrelated conditions, and the classifier only knew
two. A tokens-per-day cap opens with the same "Rate limit reached" wording as an
ordinary per-minute burst, so it was classified as capacity - and every recovery
that is right for capacity is actively harmful for a spent day:

  - the step-down to llama-3.1-8b-instant draws on the SAME org-wide daily
    budget, so it is a guaranteed-identical failure one round trip later;
  - the bounded ~25s wait is measured against a reset Groq reports in tens of
    minutes ("try again in 56m26.88s").

Net cost to the operator: two dead round trips and ~25s of latency on every Loki
turn for the rest of the day, ending in "Groq rate-limited - try again shortly",
which invites exactly the retry that cannot succeed for another hour.

This is the same mistake as the size/capacity conflation one level deeper. The
distinction that matters is not which limit was hit but what, if anything, the
caller can do about it, so the type now names all three.

  - classifyGroqLimit gains "daily", tested BEFORE size/capacity because the
    daily body also matches the cheaper capacity pattern (RPD counts too).
  - llm.ts short-circuits a daily cap instead of stepping down and sleeping.
  - groqRetryAfterSeconds/humanizeWait pass on the figure Groq already stated;
    rateLimitMessage turns it into a clause the operator can act on, and lives
    beside the classifier so both Groq wrappers say the same thing.
  - the size case stops telling the operator to retry at all - waiting cannot
    fix an oversized request, and the real repair is ours, not theirs.

The suite previously asserted the daily body WAS capacity, with the reasoning
"the budget refills, so retry/degrade is right". It refills in an hour, not in
25 seconds, and not on the model we degrade to. That case is corrected and
pinned, and the tests grow 8 -> 17 assertions.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 09:45:30 +00:00
fe9395b950 fix(deploy): every deploy was a 13-second outage (#283)
Caddy's access log carried 784 502s over 7 days on fleetcrown, in 77
distinct minutes. Every one of those minutes is a deploy: the app is
healthy before and healthy after, so nothing else ever reported it.

Traced end to end on the 2026-08-14 16:30 restart. SIGTERM at :49, the
server stopped answering at :51, and it then sat bound-but-refusing
until systemd gave up and SIGKILLed it at 16:31:04 — after which the
replacement logged "Ready in 0ms". Next's standalone server closes its
listener on SIGTERM and then waits on keep-alive connections that Caddy
never closes, so the drain can never finish. The whole 15s
TimeoutStopSec was being served to users as errors, and the startup it
was protecting takes one second.

Two changes, because the window and its visibility are separate bugs:

- TimeoutStopSec 15 -> 3. Waiting on a drain that cannot complete is
  pure downtime.
- lb_try_duration on the proxied blocks. Caddy was giving up the instant
  the restarting upstream refused a connection; now it re-dials across
  the gap. Only the dial is retried, so a request that already reached
  the app is never replayed and a POST cannot apply twice.

Measured after: a full restart under a continuous public poll served
36/36 200s, against ~13-15 502s for the same operation before.

sync-infra.sh generates the units and vhosts for the other 15 apps on
the box and had the identical defect, so the fix goes in the templates
too; they pick it up on their next sync. verify.sh gains a guard, since
this class is invisible to every check that looks at a steady state.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 09:42:51 +00:00
f3cfb7fa2f chore(deps): @noble/secp256k1 v2 to v3, with a witness that isn't noble (#281)
Supersedes #205, which bumped the dependency and left the signer uncompilable
(sign() returns bytes in v3, so .recovery and .toCompactRawBytes() are gone).

This key signs FleetCrown's Solon votes. A wrong signature there is not a
degraded feature — it is a vote that cannot be counted and an audit trail that
cannot be re-verified, so a typecheck-clean migration is not evidence of
anything. The existing vector was noble verifying noble: a change moving the
wire format on both sides passes it while invalidating every signature Solon
has already recorded.

So the test got a foreign witness FIRST, written and passing against v2 before
the bump — OpenSSL via node:crypto verifying the pinned signature, plus a
pinned public key anchored to Solon's address by hash160+base58 (no EC math, so
it holds independent of any library), the preimage rebuilt in the test, and a
negative control proving the witness can fail. A vector added after a migration
is fitted to the new output, not a guard against it.

Migration deltas: hmac moves from etc.hmacSha256Sync (varargs) to hashes.*
(single message) and throws at sign time if unset; keys are bytes, not hex;
format "recovered" returns recovery || r || s. prehash:false is load-bearing —
the digest is already double-SHA256 and letting v3 hash again signs the wrong
value while still producing a structurally valid signature. Confirmed the guard
bites by flipping it: the vector fails.

Signature bytes are unchanged, and OpenSSL agrees.

Gates: tsc 0, lint 0 errors, check:design ok, test:unit 78/78, test:home
150/150, deploy-ref-gate 7/7, check:desktop ok.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 16:01:04 +00:00
7bd17c7104 fix(deploy): a marker that can lie is worse than no marker (#280)
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: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 15:44:42 +00:00