Commit Graph
645 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 6be463cd3f fix(telegram): the self-only allowlist was a caller obligation nobody performed (#519)
sendTelegramMessage's docblock said "the caller is responsible for the self-only
allowlist check BEFORE calling this". Eight call sites, zero checks —
isAllowedTelegramTarget had no caller anywhere in the repo.

Nothing leaked, and that is the uncomfortable part: it held only because every
call site happens to pass selfTelegramTarget(). The blast radius the guard was
written to bound was bounded by coincidence instead. The first flow that lets a
recipient be requested — a Loki action, an operator-typed target — would have
inherited an unguarded send to an arbitrary chat, with a docblock saying someone
else had already checked.

The guard now runs inside the send. An empty chatId resolves to the operator's
own chat, which is what isAllowedTelegramTarget has always meant by "empty =>
default to self", and with no chat id configured every send is refused rather
than guessed at. No behaviour change for the eight existing callers, verified
one by one: all pass selfTelegramTarget().

scripts/test/telegram-allowlist.ts — 15 assertions, in the unit suite by
discovery (139/139). Both configurations run in child processes with their own
env, the shape activity-time-zone-stable.ts already uses and for the same
reason: tsx compiles to CJS and cannot `await import`. TELEGRAM_BOT_TOKEN is
left unset on purpose, so a send that REACHES the transport fails on the missing
token — that is what separates "refused by the allowlist" from "attempted", and
the mutation shows it: removing the guard turns both refusals into
"no TELEGRAM_BOT_TOKEN configured".

TWO THINGS THE TEST CAUGHT IN ITSELF.

The first version silently tested the wrong path. It set TELEGRAM_CHAT_ID, but
the constant is envAlias("TELEGRAM_CHAT_ID"), which reads APP_ / FLEETCROWN_ /
COCKPIT_ prefixed names and never the bare one — so the "configured" probe was
exercising the UNCONFIGURED path. Five assertions failed and that is how it was
found; a test asserting only refusals would have passed while proving nothing.

The module's own comment was wrong for the same reason ("Sourced from
TELEGRAM_CHAT_ID (env, via constants)"). Corrected to name the real keys, since
setting the bare name configures nothing and looks like it worked.

isAllowedTelegramTarget removed from the dead-export ratchet BASELINE. 12 -> 3.

verify green (13 steps, exit 0, 139/139 unit files).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:03:30 +00:00
CatoandClaude Opus 5 63c677718f fix(gates): three of my own BASELINE reasons were false — and the check now says so (#518)
#511 recorded seven dead exports with the consequence of each being dead. Three
of those consequences were wrong. I found them by going to fix one.

  getProjectDefinitionOfDone  I wrote "the autopilot stop-gate bar is stored and
                              never read, so definition_of_done gates nothing".
                              gate-and-close.ts:88 reads it, through the sibling
                              getProjectGoalConfig — which returns the bar AND
                              the turn cap in one fetch, so this wrapper also
                              threw half the result away.
  addOrgMember                I wrote "nothing adds a member to an org, so an
                              org can only ever contain whoever created it".
                              The team-invite flow inserts the membership
                              (db/queries/invitations.ts:69) and createOrg seeds
                              the owner's. This was a third writer, unused.
  isOrangeCatPayReady         I wrote that a missing ORANGECAT_PAY_URL_* shows
                              the user a dead upgrade path. /pricing resolves
                              per plan via orangeCatPayUrl(plan.key) and falls
                              back to "Start free" — strictly better than this
                              aggregate, which would have gated all three tiers
                              on any one of them.

One error, three times: inferring "the capability is missing" from "this symbol
is unreferenced". They are different claims and the first does not imply the
second. In each case a LIVE SIBLING in the same file already did the job, so the
export was redundant rather than evidence of a gap. All three are deleted here
and their entries removed.

The file's own docblock argues a dead export is misinformation. I put three
pieces of misinformation into it.

A fourth was imprecise rather than false. enqueueImport said the import queue
"has no producer — no surface can start one". Importing works: /api/people/import
and the OpenClaw sync both call applyImportedBook and write contacts straight in.
What has no producer is the accept/discard REVIEW that config/book.ts calls the
point of import — enqueueImport proposes an IMPORT_PERSON draft per unplaceable
contact, and execute-action.ts still handles that type, so the reviewing half is
live with nothing feeding it. Rewritten to say that, and left as a product call:
whether review was dropped deliberately is not for a deletion to decide.

THE GATE NOW MAKES THIS HARDER. Every finding prints the exports in the same
file that ARE used:

  isAllowedTelegramTarget  src/lib/actions/telegram-send.ts
    live in the same file: selfTelegramTarget, sendTelegramMessage  <- does one
    already do this job?

That is exactly the context whose absence produced all three bad reasons, placed
where it gets read. When no export in the file is used it says so, pointing at
the file rather than the symbol. Mutation-proved: a fake PROBE_DEAD_EXPORT in
oc-pay.ts reports "live in the same file: orangeCatPayUrl".

Baseline 12 -> 4, and the remaining four are now verified individually rather
than asserted.

verify green (13 steps, exit 0, 138/138 unit files).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 11:16:19 +00:00
CatoandClaude Opus 5 38f6cf4a7c fix(people): contact details were text you had to copy, not links (#517)
reachChannels() returned {label, value} and built no hrefs at all, so both
surfaces that show someone's contact details rendered them as inert text — on
rows whose entire purpose is reaching that person. mailtoHref existed with no
caller anywhere; whatsappHref was referenced only by its own test.

It now returns an href per channel, and channelHref(key, value) is exported so
every surface builds links the same way:

  email      mailto:
  phone      tel:+<digits>            (>= 6 digits)
  whatsapp   https://wa.me/<digits>   (>= 8 digits)
  telegram   https://t.me/<handle>    handles only
  in-person, other   none

Every href is assembled from a FIXED scheme plus a sanitised fragment, never
the raw attribute. A person attribute is user-entered text, and dropping it
into an href unfiltered is how `javascript:` ends up one click from the
operator. Telegram links handles only on purpose: a t.me link built from a
phone number is an invite, not a profile, and guessing between the two silently
opens the wrong chat.

I FIXED THE INSTANCE BEFORE I FIXED THE CLASS. The first version wired only
CheckinPersonRow (Today) and left PersonChannelsSection (/people detail) still
printing the same emails and numbers as inert spans. Making a dead function
live in one of the two places that needed it is not the fix.

So the test no longer asserts "the row links". It iterates REACH_SURFACES and
asserts each renders the href, carries rel="noopener noreferrer", and imports
from the shared builder — a third surface has a list to join rather than a
habit to rediscover. PersonCard was checked and left alone: it uses the channel
NAME to log an interaction and renders no contact value.

scripts/test/people-reach.ts extended. Its existing deepEqual caught the shape
change immediately, which is how I know it was live and not decorative. Added
per-channel construction, the honest-null cases (3-digit phone, email with no
@, a phone number in the telegram field), and a hostile-input loop asserting
every built href matches tel:+ / wa.me / t.me / mailto: for `javascript:`,
`data:`, and a whitespace-padded variant. Mutation-proved on a copy: raw value
as href fails, telegram trusting its input fails, either surface dropping its
href fails by name.

mailtoHref removed from the dead-export ratchet BASELINE — the ratchet failed
on its own when the function came alive ("mailtoHref is referenced again"),
which is the stale-entry check doing its job. Baseline 8 -> 7.

Not verified in a browser: no dev server was up and both surfaces need a
session, so the markup is covered by tsc, the design-system check and the ui-*
classes being real, not by clicking a link.

verify green (13 steps, exit 0, 138/138 unit files).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 09:58:04 +00:00
CatoandClaude Opus 5 11a0cc7330 fix(prompts): a custom prompt's {{variables}} were dispatched as literal braces (#516)
The `prompts.variables` column, a parser that fills it, and a renderer that
handles defaults have all existed in `src/db/queries/prompts.ts` since the
feature shipped. No UI could reach them: that module imports `db`, so a client
component cannot. Four surfaces each rolled their own substitution instead —

  RunModal              template.replaceAll("{{project_name}}", name)
  ScheduleModal         template.replaceAll("{{project_name}}", name)
  PromptPicker          substituteProjectName()
  ProjectPromptLibrary  substituteProjectName()

— and all four handle exactly one variable, no defaults, exact spelling only.

That is invisible in the built-in library, whose 37 placeholders are every one
of them `{{project_name}}`. It is wrong for USER-OWNED prompts, which reach the
same two modals through `asTemplate()` in UserPromptsSection and may declare
anything. A body with `{{ticket_id}}` was dispatched to the agent with the
braces intact; through ScheduleModal it was baked into a cron job's stored
message and re-sent, with braces, on every tick.

`src/lib/prompt-vars.ts` now owns the parser and the renderer with no `db`
import; `db/queries/prompts.ts` re-exports them so server import paths are
unchanged, and `substituteProjectName` delegates instead of keeping a second
regex — which also fixes `{{ project_name }}` (spaced), a spelling the parser
has always accepted and that helper's own regex never matched.

Both modals now resolve EVERY declared variable and render an input for each
one that is not project_name, with the declared default as its placeholder.
RunModal shows how many are still unfilled. An unfilled variable with no
default deliberately stays visible as `{{name}}` in the preview rather than
blanking: a half-filled prompt should be obvious before dispatch, not produce a
confident instruction with a hole in it.

scripts/test/prompt-vars.ts — 22 assertions, in the unit suite by discovery
(138/138). Three of them are structural: neither modal may hand-roll a `{{`
substitution again, and `db/queries/prompts.ts` must re-export rather than
define. Proven falsifiable by mutation on a copy: blanking an unfilled variable
fails, giving substituteProjectName its old private regex back fails two, and
restoring RunModal's replaceAll fails the no-private-copy check.

`renderPromptBody` removed from the dead-export ratchet BASELINE — it has a
caller now. The ratchet's own stale-entry check enforces that removal.

Not verified in a browser: no dev server was up and /prompts needs a session,
so the modal markup is covered by tsc, the design-system check, and the class
names being real, not by looking at it.

verify green (13 steps, exit 0).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 09:19:18 +00:00
CatoandClaude Fable 5 0585ab32c0 chore(thoughts): adopt bip-kit 0.2.1 — retire the local mermaid island and shiki workarounds (#515)
bip-kit 0.2.1 upstreamed both reasons the local copies existed:

- MermaidBlock now does canvas color normalization (oklch/lab tokens no
  longer blank diagrams) and class-based theme detection (next-themes
  attribute="class" works), so src/components/thoughts/MermaidDiagram.tsx
  is deleted in favor of bip-kit/react/mermaid. Its orphaned PALETTE
  fallback groups go with it; the one value email still used
  (darkFallback.textTertiary) moves to the canonical dark mirror group.

- setHighlighterLoader(() => import("shiki")) is the supported seam for
  standalone builds: the literal import lives in our code, so the bundler
  ships shiki like any other dependency. The serverExternalPackages
  "shiki" entry and deploy-local.sh's node_modules/shiki symlink (and the
  load-bearing static-import assertion) are all removed; node-pty's
  handling stays untouched.

Verified on the assembled standalone locally: code essay serves 56
--shiki-light spans with NO top-level node_modules/shiki present, and the
mermaid essay renders a themed SVG in both dark and light (labels flip
near-white/near-black; per-theme re-render confirmed).


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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-07 05:52:19 +00:00
CatoandClaude Opus 5 a48e7c52dd docs(billing): the docs still described a rail that was deleted yesterday (#514)
#508 removed the Stripe rail. Four living docs kept describing it, and one of
them is named in CLAUDE.md as an SSOT — so the wrong answer was the documented
answer.

- `development/cloud-local-workflows.md` listed `Stripe billing | STRIPE_*` in
  the env-gated feature table. Replaced with the rail that exists:
  `ORANGECAT_PAY_URL_{PERSONAL,PRO,TEAM}`, names checked against lib/oc-pay.ts.
- `sustainability-gates.md` Gate 3 argued from a `quantity: 1` hardcode in
  `src/app/api/stripe/checkout/route.ts`. The gate did not go stale, it
  HARDENED: that route is gone and the BTC rail is a static per-plan URL with no
  quantity concept, so there is no seat number left in the purchase path to
  correct. Per-seat Team is now a build, not a config change.
- `oc-rail-monetization-scope.md` claimed the Stripe webhook "already calls"
  updateUserBilling and that /pricing has an isStripeReady() seam to reuse. The
  write survives (via /api/orangecat/entitlement, plus scripts/grant-plan.ts);
  the seam does not — the BTC CTA is the default case now, not one to add.
- `development/user-flow-audit.md` asserted `/api/stripe/portal` returns 503. It
  returns 404. CH01-CH04 and the CH04 runbook tested four deleted endpoints;
  retired with a pointer to what replaced them.

`scripts/grant-plan.ts` said it performs "the SAME write the Stripe webhook
does" — updated to name the entitlement route instead.

Two findings that were not about Stripe:

`docs/self-improvement-plan.md` enumerated three `insertPromptHistory` call
sites. There are four — `api/control/tab-inject` was missing — and all three
line numbers had drifted (270→397, 452→514, 80→138). Following that list would
have shipped the runId linking with one dispatch path still unlinked. Line
numbers dropped in favour of "grep the symbol"; same for `src/auth.ts:234` in
the OC scope doc, which now points at line 268's unrelated code.

`src/config/demo.ts` still denied `/api/checkout` under its "money" heading long
after #508 deleted that route — a deny rule for a route on no disk, which made
the billing section of the sandbox policy look staffed.

demo-sandbox.ts already had the reverse check for DEMO_SAFE_FAMILIES ("a family
listed as safe that no longer exists is dead reassurance"); the denied lists had
no equivalent, which is why that entry survived. Added the mirror check — it
caught `/api/checkout` on its first run — and mutation-proved it with a fake
prefix. 262 assertions.

Also measured and did NOT gate: doc path references (314) and `pnpm run`
commands (77) both came back clean once false positives were removed, and the
dominant pattern is prose naming a file precisely to record its REMOVAL, which
grep cannot tell from rot. A gate there would fire on the correct docs and stay
silent on the wrong ones. CLAUDE.md's own four flagged paths were all correct,
and all 22 routes in its Views table exist.

verify green (13 steps, exit 0).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 05:05:54 +00:00
CatoandClaude Fable 5 084f17c054 fix(deploy): link node_modules/shiki into the standalone — the tracer never will (#513)
Second half of the shiki saga (#510 shipped tracing globs that copied
nothing; #512 added serverExternalPackages + a static import, which got the
.pnpm store files traced but still no highlighting in prod).

Hermetic diagnosis (standalone copied OUTSIDE the repo tree, so the dev
node_modules can no longer leak into Node's resolution walk — which is
exactly how the earlier local verification fooled itself): Turbopack's
externalized import of shiki resolves through its own module wrapper, but
bip-kit loads the peer via `new Function("s","return import(s)")` — plain
Node resolution from the server chunk path. Next emits the .pnpm store
entries yet never the top-level node_modules/shiki symlink, so that import
finds nothing and ArticleBody silently degrades to the mono fallback.
With the link created: bp-codeblock-highlighted spans with dual-theme
--shiki-light/--shiki-dark vars. Without: bp-pre fallback. Reproduced both
ways before shipping.

deploy-local.sh (the postbuild that already supplies what the tracer can't
see — static assets, content, node-pty's native binary) now creates the
symlink, version-agnostically, from the store entry it finds. The static
import also becomes load-bearing (bare `import "shiki"` was tree-shaken:
shiki declares sideEffects:false) and asserts at module load, so a missing
peer is a loud failure instead of a quiet styling regression.


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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-06 22:37:46 +00:00
CatoandClaude Fable 5 96cdfd182f feat(thoughts): adopt bip-kit v0.2's reference renderer (#510)
Replace the hand-written block switch + ri() inline re-parser in
/thoughts/[slug] with ArticleBody from bip-kit/react, and adopt
bip-kit/styles.css with FleetCrown's design tokens mapped onto the
--bp-* theming contract (route-scoped CSS, not globals).

New capabilities live on every essay:
- sticky <Toc /> with scroll-spy (xl right rail, hides under 3 headings)
- heading anchor ids (slugified, umlaut-aware)
- Shiki syntax highlighting, server-side, dual-theme via --shiki-* vars
- <ReadingProgress /> hairline (warm accent)
- <Lightbox /> zoom on figures
- the full v0.2 vocabulary (callouts, pullquotes, footnotes, charts,
  stats, math, galleries) for future essays

Kept, deliberately local:
- MermaidDiagram island (now the components.mermaid override): bip-kit's
  MermaidBlock keys on data-theme only and passes computed oklch straight
  to mermaid's color parser, which rejects it — the exact initialize()
  throw that once blanked every diagram here. Canvas normalization stays.
- Inline local-SVG figures (ThoughtArticleBody splits the block stream
  around them) so repo-authored diagrams keep reading design tokens and
  flipping with the theme; alt-as-caption is preserved by promoting
  captioned image blocks to figure blocks.

Also:
- ThemeProvider now mirrors the theme to data-theme alongside class —
  the fleet convention bip-kit's dark scopes (shiki token colors) key on.
- next.config traces shiki into the standalone build: bip-kit loads it
  through a bundler-hidden dynamic import the tracer cannot see, so prod
  would otherwise silently fall back to unhighlighted code.
- bip-seam test updated to pin the v0.2 vocabulary.
- ThoughtVideoEmbed deleted (bip-kit's allowlisted VideoEmbed renders
  embed blocks).

68-essay compat diff (v0.1 vs v0.2 parse, histograms): identical except
(a) mermaid fences code->mermaid (wanted), (b) 34 bare `---` lines across
10 essays that rendered as literal "---" paragraphs now render as <hr>,
(c) one bare `>` separator line in the levelsio essay that rendered as a
stray ">" paragraph now merges its two quote paragraphs into one
blockquote. All three match authored intent.


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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-06 21:44:26 +00:00
CatoandClaude Opus 5 e59f679289 chore(gates): a dead export is a lie about what the system does — gate it (#511)
markAgentMessageRead was the only writer of `read: true` and had no caller, so
the Control escalation banner was permanent by construction (#507). That was
found by hand. This is the check that finds the next one.

`scripts/test/dead-exports-ratchet.ts` fails when a NEW export in
src/db/queries, src/config or src/lib has no reference anywhere. Existing ones
are recorded with the consequence of being dead, so the list is worked down
rather than ignored — and a recorded entry that becomes referenced fails too,
so it cannot rot into a lie. It joins the 137-file unit suite by discovery.

49 dead exports found. 36 deleted, 1 wired up, 12 recorded.

The deletions were mostly aliases and shims whose consumers never existed:
PUBLIC_NAV_LINKS ("kept for backwards compatibility"), SITE_NAV_ITEMS ("kept
as a named export for any legacy import"), BEACON_SETTINGS_PATH ("kept for
runner fallback reads only"), ROBOT_ENTITY_TYPE ("used by tests" — no test
used it), BOOK_ACTION_TYPE (a second copy of values ACTION_TYPE owns), and
RESERVED_ACTION_PROPOSE_SOLON_CHANGE, reserved "so the name is stable when the
flow lands" — a name is stabilised by having consumers.

Two carry more weight. isRunnerRequest was a @deprecated legacy env-token auth
path that "always maps to the default user and is not multi-tenant safe";
deleting it removes that credential check from the codebase. closeStaleAgentTurns
is now called by the hourly reap-stale-runs janitor: its docblock promised
agent_sessions "does not accumulate rows that look open forever", a guarantee
nothing provided.

Two bugs in the gate itself, both caught by mutation:

  - It indexed its own file, so every name in BASELINE and in the docblock's
    worked examples looked referenced. It reported "0 dead" over five that
    were, and closeStaleAgentTurns — an example in its own docblock — was
    invisible to it.
  - It counted prose as a reference. Excluding .md surfaced three more,
    including renderPromptBody, which docs/AUDIT_REPORT_2026-07-13.md had
    already named as dead two months ago. A report is read once; a gate is
    read on every push.

OUTCOMES_MATCH_DB_SCHEMA is a compile-time drift assertion whose runtime value
is inert — no reader is what a working assertion looks like. Ratcheting it
would have pressured someone into deleting a real check, so
INTENTIONALLY_UNREFERENCED is a separate category from debt, with an assertion
that no name sits in both lists.

All four assertions proven falsifiable by mutation on a copy: a new dead export
fails, a revived BASELINE entry fails, a name in both lists fails, and removing
the exemption makes the compile-time assertion surface.

Recorded, not fixed — each with its consequence, three worth naming:

  - isAllowedTelegramTarget: sendTelegramMessage's docblock says the caller
    must run the self-only allowlist check, and none of the eight call sites
    does. What bounds the blast radius today is structural — every caller
    passes selfTelegramTarget(), so no attacker-chosen chat id is reachable.
    It must be wired the moment any flow lets a recipient be requested.
  - renderPromptBody: RunModal substitutes one variable via
    replaceAll("{{project_name}}", …), so every other {{var}} and every
    declared default reaches the agent as a literal placeholder. Fixing it
    means moving the function out of db/queries and changing what a run
    sends — its own change, not a deletion.
  - mailtoHref: reachChannels() returns {label, value} and builds no hrefs, so
    the People reach row is not clickable at all.

verify green (all 13 steps, exit 0).


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 21:39:56 +00:00
CatoandClaude Opus 5 81bf2041be chore(billing): remove the Stripe rail, which was never configured anywhere (#508)
STRIPE_SECRET_KEY and the seven other STRIPE_* vars appear zero times outside
src/ and zero times in .env.example, so isStripeReady() could only ever return
false. Three API routes, a checkout route, a tier grid and a "Manage
subscription" button were all gated on it and permanently unreachable.

Confirmed empty in production before touching the schema:

    select count(*) filter (where stripe_customer_id    is not null),
           count(*) filter (where stripe_subscription_id is not null),
           count(*) from users;
    →  0 | 0 | 7

So this removes no data and, more to the point, changes nothing a user sees:
every code path already fell through to the branch below it.

WHAT STAYS. Plans are real and untouched. They are granted through the
OrangeCat/Bitcoin rail (/api/orangecat/entitlement -> recordOcBillingGrant),
with the expiry cron reverting a lapsed pass to free. The pricing CTA cascade
loses only its unreachable middle step: free -> TBA -> [stripe] -> BTC ->
start-free.

WHAT WAS ACTIVELY WRONG. Because isStripeReady() was false, the one part of
Billing that DID render was a notice telling the reader to "add
STRIPE_SECRET_KEY and price IDs" — an environment variable shown to a person
who does not deploy the app and could not act on it. That is the same mistake
NotificationsPill's comment already calls out. Billing now states the plan and
links to /pricing.

Removed: lib/stripe.ts, api/stripe/{checkout,portal,webhook}, api/checkout/
[plan], getUserByStripeCustomerId, two user columns (migration 0063), two
entries from the user-client-view redaction lists, the api/stripe/webhook entry
in proxy.ts's public matcher, the stripe npm dependency, and the smoke/auth
probes for routes that no longer exist.

BillingSettings drops "use client" — with the handlers gone it holds no state,
no effect and no search-param read.

Two mentions deliberately KEPT because they are not the rail: the placeholder
prose describing what a user might build ("Simple dashboard, automated
reminders, Stripe payments…") and the demo project's stack string.

pnpm run verify green. 28 files, 519 deletions.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 17:04:53 +00:00
CatoandClaude Opus 5 b5394c98fb fix(widget): a long name in "Name / email" threw the whole report away (#505)
Found by a code-health audit; these are the two findings that were verifiably
BREAKING something rather than merely untidy.

── The widget dropped reports ────────────────────────────────────────────────

/api/feedback validates with zod and, on ANY failure, returns the single string
"Invalid submission" naming no field. The widget renders that and the visitor's
report is gone.

Of the five string fields it sends, three were clamped to exactly the route's
`.max()` and two were not:

    url        .slice(0, 1000)   matches max(1000)   ✅
    pageTitle  .slice(0, 300)    matches max(300)    ✅
    suggestion textarea maxLength = MAX_LEN 2000     ✅
    contact    (unclamped)       server max(200)     ✗
    page       (unclamped)       server max(300)     ✗

The contact <input> had no `maxLength` either, so a visitor pasting a signature
into "Name / email" — or anyone on a page with a very long pathname — lost
everything they had typed, with no field named and nothing logged. This is the
only surface strangers on other people's sites touch.

The author plainly knew the rule: MAX_SHOT_CHARS carries the comment "ingest
caps the data URL at 600k chars". It was applied 3 times of 5, which is what a
hand-mirrored constant does.

scripts/test/widget-server-caps-mirror.ts now reads the caps out of the zod
schema and asserts the widget clamps to the same numbers, so the two cannot
drift again. Mutation-proven: drop the contact clamp -> 8 passed, 1 failed.

── A tap target 16px under the floor ─────────────────────────────────────────

ProjectProvision's chip carried `ui-btn-chip gap-1.5 px-3 py-1.5 text-xs`.

`ui-btn-chip` is NOT in the coarse-pointer floor list in globals.css — it
reaches 44px through its own `py-3`. Overriding that to `py-1.5 text-xs`
without adding `ui-tap` produced roughly 28px on a phone, visibly shorter than
the seven identical sibling chips (ProjectBriefFill ×4, BusinessPlanSection,
ProjectDocSync) which all carry `ui-tap`.

audit:responsive reports zero undersized targets and is right to: this button
lives on /projects/[id], and the audit's page list has /projects but no detail
page. The gate is not wrong, its coverage is — worth knowing before trusting a
green run on a page it never opens.

pnpm run verify green.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 09:17:29 -07:00
CatoandMao Nakamoto 8f9001c308 fix(ops): retry fc-cron through the deploy-restart connection-refused window (#502)
check-runner-stall paged (fc-cron@check-runner-stall.service failed, curl
exit 7 on 127.0.0.1:4002) because its *:30 tick landed inside the ~13s window
fleetcrown-app.service documents on every deploy restart, where the port sits
bound-but-refusing between the old process's SIGKILL and the new one's ready.
The app was healthy again by the very next tick.

fc-cron.sh now retries only on curl's connection-refused (exit 7) a few times
before giving up, so a deploy landing on any *:15/*:30/*:45 cron minute no
longer pages for an outage that self-resolves in seconds. Real HTTP failures
still fail on the first try.

Co-authored-by: Mao Nakamoto <maonakamoto@users.noreply.github.com>
2026-09-05 14:53:46 +00:00
9017717127 feat(mobile): summary stats become one line, and the widget stops covering Loki (#496)
Two things, both measured rather than assumed.

── The stat cards ────────────────────────────────────────────────────────────

StatCard rendered a kicker, a 2xl number and a sub-line inside a padded card —
about 130px — and three of them stacked two-up. /goals therefore spent ~280px
of an 844px phone on "19 active · 24% avg progress · 23 total" before the first
goal, and none of those figures is a decision. You scrolled past all of it to
reach the list the page is named after.

Below `sm` they are now one horizontally scrollable line of chips, value first.
Nothing is dropped — label, value and sub all survive; the layout reorders with
flex `order` rather than duplicating markup. From `sm` up, where height is free,
it stays the card grid it always was.

The chip strip is not a new invention: /today's SummaryBar already answers this
exact job, so this borrows an idiom the app has proven instead of adding a
second way to show the same thing. Lands on /goals, /money, /habits and /memory
from one change.

StatCard no longer builds on <Card>: Card hard-codes the padding and radius the
chip shape would have to fight.

Checked before trusting it, because this repo has a recorded Tailwind 4 trap
about variants inside `@layer components`: the LIVE stylesheet already compiles
`.ui-card-padding`'s sm:/md: variants to real `@media (min-width:40rem)` and
`(min-width:48rem)` rules, so the pattern works in this build.

── The goal row ──────────────────────────────────────────────────────────────

Four icon controls per goal — Loki, copy, archive, delete. `ui-hover-reveal`
kept them out of the way on desktop, but a phone has no hover, so on the
viewport with the least room all four were permanently visible next to the
goal's own title. None of them is the action a person repeats (that is editing
progress, inline in the card body), so all four move behind one RowActions
trigger. The two prompt helpers gain optional `className`/`label` so they can
render as words in a menu instead of a lone glyph among sentences.

── The feedback widget on /loki ──────────────────────────────────────────────

Measured at 390px: the launcher's centre resolved to
`textarea.ui-loki-composer-input`. It covered the box you type into, on the
page whose whole purpose is typing into it.

NOT a failure of the widget's avoidance logic, which is worth stating because
the obvious fix would have been wrong: `INTERACTIVE` already matches `textarea`
and the 260px shift cap was never reached. autoAvoid moved the launcher 164px
up and correctly found a clear spot — then the composer reflowed under it when
the conversation list loaded. The widget re-checks at two fixed moments after
paint, not on layout change, so a late reflow wins. Fixing that properly means
a ResizeObserver in a bundle that runs on other people's sites.

So /loki joins /terminal in FEEDBACK_WIDGET_EXCLUDED_PREFIXES, for the reason
already written there: the surface has its own composer.

feedback-widget-reach.ts asserted /loki WAS reachable and duly failed. It now
asserts the exclusion with the measurement behind it, so the change reads as a
decision rather than a typo, plus a /lokis near-miss case.

pnpm run verify green.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 13:21:25 +00:00
ee52eabfb7 refactor(email): move transport to @bitbaum/mail-kit (#495)
Replace the Resend SDK transport in src/lib/email.ts with the fleet's
@bitbaum/mail-kit. Templates and the sendEmail/sendEmailFire signatures
stay; the transport underneath is now sendMail (never throws — the
awaitable sendEmail preserves its old throw-on-failure contract for
callers). Sender SSOT moves from EMAIL_FROM to RESEND_FROM (mail-kit's
env contract) with conventionalFrom(APP_NAME) as the fleet-default
fallback; APP_EMAIL_FROM is gone from brand.ts and the env preflight now
warns on missing RESEND_FROM. The email-canary cron probes via
mailHealth() instead of a hand-rolled /domains fetch, and the digest
cron passes an idempotency key so a retried tick cannot double-send.
The resend dependency is removed.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-05 11:24:54 +00:00
87bac87e96 fix(activity): pin the time formatters, ending the React #418 on /activity (#494)
/activity threw away its hydrated tree on every viewport, in production only.
This was written off earlier as "intermittent, diminishing returns". It was
neither — it was two faults of the same kind, one of them rare enough to look
like noise.

MEASURED, on ONE page load: 1798 words server, 1798 words client, and every
clock differing by exactly two hours.

    server   Sent 10:18   Sent 09:54   Partial 04:00
    client   Sent 12:18   Sent 11:54   Partial 06:00

UTC on the box, Europe/Zurich in the browser. Five formatters in
activity-shared.ts called toLocaleTimeString/toLocaleDateString with no
`timeZone`, so they read the RUNTIME's zone — and their callers
(ActivityEventRow, EventStream, NeedsYouCard, ActivityTimeline) are
"use client", so they render in both processes.

Pinned to DEFAULT_TIMEZONE, which already exists as the app's SSOT. Pinning
beats the mounted-gate the greeting uses: these are PAST events, not "now", so
there is no reader-dependent answer to defer to and deferring would only trade
a wrong first paint for an empty one.

formatDayHeading carried the same fault in a two-hour window: it compared
`new Date(y, m-1, d)` against now.getFullYear()/getMonth()/getDate(), all
runtime-zone, so between 00:00 and 02:00 Zurich the box was still on yesterday
while the browser was already on today. THAT is why the failure presented as
intermittent — one run in three. It now compares calendar-date strings in a
fixed zone, and formats the fallback as UTC midnight rendered in UTC, because
a bucket key names a calendar day rather than an instant.

The first hypothesis was WRONG and is worth recording: the pulse's
"busiest: 20 at 09:21" label looked like the culprit, but ActivityPulse is a
server component and the client never re-renders it. Two measurement attempts
were wrong before one worked — a detached DOMParser document has no layout so
innerText collapsed the page to a single line, and rendering with JS disabled
skipped everything because React streams suspended content into `<div hidden>`
that only a script unhides. Both made the page look like it had no server
render at all.

The gate (scripts/test/activity-time-zone-stable.ts) runs the formatters in
three child processes — UTC, Europe/Zurich, Pacific/Honolulu — and compares
their output. Grepping the source for "timeZone" would pass a formatter pinned
to the WRONG zone and would say nothing about date arithmetic. Its fixture is
22:30 UTC deliberately: that is 00:30 the next day in Zurich, so a noon
fixture would pass on the broken code.

Mutation-proven: remove the pins → 4 of 5 fail, reporting 22:30 / 00:30 /
12:30 — the production symptom exactly; restore → 5/5. Picked up automatically
by test-unit's directory glob.

pnpm run verify green.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 10:49:10 +00:00
a3dc681e0c fix(activity): show the ask, not the retrieval block wrapped around it (#492)
/activity exists to answer "what did I ask for?". Every row of the Needs-you
list on production answered:

    asked: ## Relevant context from your other projects…

That is retrieval scaffolding, presented as the operator's own question.

The recovery machinery was already right. ENVELOPE_BLOCK_PATTERNS carried

    ## Background context from your other projects        (inject-prompt.ts)

while the RAG block emits

    ## Relevant context from your other projects (retrieved)
                                       (db/queries/knowledge-embeddings.ts)

Different heading, so the pattern never matched, so the block survived into
the preview. Nothing failed — the list's own comment predicts exactly this:
"a block that changes upstream stops matching". It did, and the degraded
behaviour was invisible because a noisy preview still renders.

A second hand-kept list checking the first would rot the same way, so
scripts/test/dispatch-headings-stripped.ts DISCOVERS the headings from the
pipeline source and tests behaviour: build a dispatch around each one, assert
the heading does not survive and the task does. It is picked up automatically
by test-unit's directory glob (134/134).

Getting that fixture right mattered twice: background blocks run to
end-of-input unless the "Project context & goals" sentinel follows them, and
the exit contract genuinely consumes to the end. The first version failed on
every heading for reasons unrelated to the bug.

Mutation-proven: drop the new pattern → 9 passed, 1 failed, naming that
heading; restore → 10/10.

Also on the pages themselves:

/people printed the name twice. The alias filter excluded an alias equal to
the WHOLE name, so a person stored as ["Manuel", "Riegner"] rendered
"Manuel Riegner" with "Manuel · Riegner" beneath it — the name again, split
up, dressed as extra information, on most of 2,749 rows. An alias whose every
word already appears in the name is now dropped.

Its "+ Details" button did not show details — clicking the card does that.
It opens the log form with channel/direction/summary, so it says "Log details".

/money's burn tile joined currencies with " + ": "50.00 CHF + 329.60 USD",
which wrapped mid-figure at 390px and claimed a sum that cannot exist without
an FX rate this page does not have. One line per currency. StatCard's `value`
widens to ReactNode; every existing caller passes a string and is unaffected.

pnpm run verify green.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 09:53:04 +00:00
cf3d9ed52e fix(deploy): hand the VAPID public key to the build, so push can work at all (#490)
#488 stopped the hydration failure by rendering nothing until past the server
render. It could not restore the feature: the browser still received an empty
NEXT_PUBLIC_VAPID_PUBLIC_KEY, so subscribe() had no application server key and
push notifications were dead in production regardless.

The missing half was never in the code. deploy.yml's build step declared no
`env:` at all, so every NEXT_PUBLIC_* was inlined empty while the box ran with
this one set. Fixed by creating the repo variable and passing it to the build.

A variable, not a secret: the value is compiled into the client bundle and
handed to every browser that subscribes. Hiding it would be theatre, and a
secret's log masking would only obscure the verification.

Verified before trusting the value, because a wrong key fails silently at send
time and this one gets baked into every future bundle:

  - decodes to 65 bytes, first byte 0x04 — a valid uncompressed P-256 point
  - the public key is the MATE of VAPID_PRIVATE_KEY on the box (derived the
    point from the private scalar and compared; no secret printed)
  - VAPID_SUBJECT is a valid mailto:/https: scheme

One trap on the way: the box stores the value quote-wrapped (len 89 = 87 + 2).
dotenv strips those when the server loads them, so runtime was fine — but
copying it verbatim into the variable would have inlined literal quotes and
produced a broken key that looks correct in every listing.

The gate's KNOWN_GAPS entry is deleted rather than edited, so removing either
the variable or the env: line now fails the check instead of silently killing
push again. Mutation-proven both ways: line removed -> 4 passed, 1 failed
naming the var; restored -> 5 passed, 0 failed.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 08:27:25 +00:00
bfaf7b67cc fix(shell): the React #418 on every authenticated page, and the gate for its class (#488)
A NEXT_PUBLIC_* value has TWO origins and nothing checked they agree: the
SERVER reads it at RUNTIME, the BROWSER gets whatever was INLINED at BUILD
time. deploy.yml's build step declares no `env:` at all, so the client bundle
ships with every NEXT_PUBLIC_* empty while the box runs with
NEXT_PUBLIC_VAPID_PUBLIC_KEY set.

NotificationsPill returns null when `publicKeyMissing`. So the server said
"configured, render the bell" and the client's first render said "not
configured, render nothing" — React threw the tree away. Every authenticated
page, production only.

PROVEN, not inferred:
  server-rendered HTML          1 notifications button
  hydrated DOM                  0
  VAPID key in client chunks    0 of 17 (1.1MB scanned)
  /opt/fleetcrown/app/.env      sets exactly one NEXT_PUBLIC_* — that key

Six other hypotheses were tested and DISPROVED first, each by a discriminating
test rather than a plausible story: the feedback widget (blocking widget.js
leaves the error), the banner's localStorage (flag is null, both sides compute
false), ThemeToggle (already mounted-guarded), AppShell (defers to an effect),
HTML caching (no-store), and the server's UTC clock vs the browser's — that
last one fit the evidence perfectly and was killed by forcing three browser
timezones and getting one error in all three.

THE FIX. Render nothing until past the server render, so the first render is
unconditional whatever the environment says. Via useSyncExternalStore rather
than mounted-in-an-effect, because BrandVersion already does it that way and
react-hooks/set-state-in-effect bans the other. Verified against a local
production build: the SSR HTML went from 1 notifications button to 0.

This is defence, not the whole cure. While the key is missing from the bundle,
push notifications are genuinely DEAD in prod — the browser sees an empty key,
so subscribe() cannot run. Closing that needs a repo secret (none exists:
`gh secret list` shows only HETZNER_SSH_KEY and RELEASES_REPO_TOKEN) plus an
env: entry on the build step. That is George's to do; it is recorded in the
gate rather than in a message that scrolls away.

THE GATE. scripts/test/public-env-inlined.ts compares what src/ reads against
what actually reaches the bundle — deploy.yml's build env AND next.config.ts's
own `env:` block, because a checker that knows one mechanism and not the other
cries wolf. It narrows to vars .env.example says a deployment SETS: one absent
from both build and runtime cannot diverge, both sides just use the default.
Both narrowings came from the check being wrong first — it initially flagged
six vars including NEXT_PUBLIC_BUILD_SHA, which visibly renders in the footer.

Mutation-proven: remove a recorded gap -> 5 passed, 1 failed, naming the var;
restore -> 6/6.

pnpm run verify passes (133/133 unit files, `✓ public-env-inlined`).


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 16:30:21 +00:00
55a3c0e4e0 fix(ci): catch an unbumped desktop change on the PR, not on main (#486)
Today a dependabot bump turned main red and stopped the merge queue. The gate
was right; its TIMING was racy, and the race is the whole bug.

What happened, in order:

  #482 merges, mints fleet-runner-v0.8.16.
  #411 (dependabot, touches ONLY desktop/package-lock.json) had already run its
       CI while v0.8.15 was newest. Against v0.8.15 its base ALREADY read
       0.8.16, so "version is ahead of released" held — CI PASSED.
  #411 merges. Newest tag is now v0.8.16, the only desktop change since it is
       that lockfile, and the identical check goes RED on main.

Both evaluations were correct. The gap is between them, and everyone else pays:
the sweep merges nothing onto a red base, so every unrelated PR stalls behind a
bot's dependency bump. #483 failed CI on a diff that touched no desktop file.

The existing question is cumulative — "has anything changed since the last
tag" — and its answer moves when a tag is minted, i.e. for reasons outside the
branch. So ask a second question that has no race in it:

  does the diff of THIS BRANCH touch desktop/, and if so
  does THIS BRANCH bump desktop/package.json?

Decided entirely within the branch, identically before and after any tag
appears. It fires on the PR — one blocked bot PR a human can see — instead of
after the merge, where it is a red main and a stopped queue. On main itself the
branch diff is empty and the rule does not apply; the cumulative check still
guards there.

Mutation-proven:
  desktop change, no bump  -> exit 1, "this branch changes desktop/ but does
                              not bump desktop/package.json", naming the file
  + bump, no changelog     -> exit 1 on the pre-existing changelog rule
                              (the two compose; a bump alone is still not
                              publishable)
  neither                  -> passes, rule correctly silent

This is the fix I would rather have than the automation I had offered — opening
a bump PR after the fact repairs the outage; this prevents it.

pnpm run verify passes.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 13:50:19 +00:00
5e4192e4d1 fix(control): stop offering back the prompts nobody reuses, and the clamp that never clamped (#482)
Found by using /control in a browser as a user, on a phone-width window,
start to finish: pick a project, type a prompt, send it, follow the outcome.

1. "PASTE FROM HISTORY" WAS SHOWING THE OPPOSITE OF WHAT IT PROMISES

The card offered back conversational asides — "you do it. open in browser and
do it" — as reusable work. Not a rendering bug: those really were dispatches.
The selection was wrong.

Measured on prod, 30 days: 1859 distinct custom prompts, of which 1823 (98%)
were sent exactly ONCE. The query ordered by recency, so it surfaced the three
most recent one-offs — by definition the prompts least likely to be wanted
again — while the genuinely reused ones sat unoffered: "continue" 115×, a
git-diff review prompt 63×, "go ahead" 14×, "keep going" 8×.

Requiring two uses cuts the pool from 1859 to 36 and leaves exactly what the
feature is named for. Nothing is lost: Activity keeps every dispatch with a
re-run control. One-offs just stop competing for space on the card.

2. THE CLAMP I SHIPPED IN #479 WAS INERT, AND I COULD NOT SEE IT

`block ... line-clamp-2` computes to `display: block; -webkit-line-clamp: 2`.
`-webkit-line-clamp` does nothing without `display: -webkit-box`, and
Tailwind's `block` utility overrode it. It LOOKED fixed because an unclamped
box just wraps — which reads fine until the sentence is long.

Checked live in the browser: a 460-character next_step grew that box from 48px
to 96px and pushed the composer, the thing you act with, off the bottom of the
viewport. So my "it renders fully now" was measuring the ABSENCE of a clamp.

Dropping `block` makes it work; three lines, not two, so a typical next_step
(~256 chars) still reads in full and a pathological one is bounded and
reachable (clicking loads the whole text into the composer).

THE GATE: responsive-audit now flags a line-clamp that is declared but not
enforced. It cannot test `display === "-webkit-box"` — Chrome reported
`flow-root` for a clamp working correctly — so it tests BEHAVIOUR: an element
declaring N lines that renders more than N. Run against live prod it says:

  "Suggested next (profile)…"[ui-link-subtle-button.block.line-clamp-2]
  declared 2 lines, renders 4 (display:block)

naming the offending class. That is this exact bug, caught in shipped code.

3. A FAILURE MESSAGE THAT NAMED THE WRONG AGENT

A real dispatch returned: "launched claude (pty) + injected, but the agent
isn't generating yet … Retry, or switch the project agent away from grok if
this repeats." One sentence naming the agent that ran and, as advice, one that
did not — a literal left over from when grok was the default. `agent` was in
scope; the auth branch above it interpolates it correctly.

Gated in failure-message-pairing: a failure message that NAMES an agent must
interpolate ${agent}. Stated that way rather than "no agent ids", because the
auth message legitimately says `~/.claude/.credentials.json` and `claude
setup-token` — a real path and a real command — and already names the right
agent. The check joins `+` continuations so a message split across two lines is
judged whole; per-line it got that one wrong.

Mutation-proven: restoring the "grok" literal → 20 passed, 1 failed, naming the
line. Restored → 21/21.

pnpm run verify passes.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 12:20:44 +00:00
1647fe7987 fix(sweep): a test that rotted behind a wrong excuse, and a box spec off by 2x (#480)
Three follow-ups from sweeping the earlier findings. Two of the four I had
carried forward did NOT survive checking and are dropped: /api/control/dispatch
is a real route, so the docs referencing it are correct; and
scripts/test/push-notifications.ts exists. Verifying first is why this commit
is smaller than the list that prompted it.

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

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

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

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

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

2. THE BOX IS HALF THE MACHINE THE DOCS DESCRIBE

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

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

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

3. THE COMPOSER STATUS, FINISHED

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

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


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 11:16:58 +00:00
65dea6f303 chore: pnpm — the fleet has one package manager (#478)
* chore: pnpm — the fleet has one package manager

- packageManager pnpm@11.25.0; lockfile via pnpm import, package-lock.json
  removed; npm "workspaces" replaced by pnpm-workspace.yaml packages
  (packages/agent), and bridge/ joins the workspace — one install, one
  lockfile, its own package-lock.json removed
- npm "overrides" (fast-uri pin) moved to pnpm-workspace.yaml (pnpm ignores
  the npm-only field)
- allowBuilds: better-sqlite3, node-pty, @sentry/cli, native toolchain, and
  the two git-hosted deps (@fleet/ai-forms, limitkit — pnpm wants the exact
  resolved spec, keys move with the pinned tags); temporary
  minimumReleaseAgeExclude for our own @bitbaum/ai-kit@0.6.2
- phantom deps declared: @auth/core (src/auth.ts augments @auth/core/jwt —
  TS2664 under pnpm's strict layout), dotenv, sharp (scripts)
- CI/audit/deploy workflows: pnpm/action-setup@v6, store-dir pinned outside
  the action's bin dir, cache: pnpm, frozen-lockfile; deploy's separate
  `npm --prefix bridge ci` is covered by the workspace install; Next cache
  key hashes pnpm-lock.yaml; npm audit → pnpm audit
- desktop-release: root install → pnpm; desktop/ itself STAYS an npm package
  (own package-lock.json, electron toolchain untouched)
- husky: pre-push staleness gate now compares pnpm-lock.yaml against
  node_modules/.modules.yaml; hooks + scripts (deploy-hetzner, hetzner/deploy,
  install-app, doctor, smoke) converted to pnpm
- check-deploy-ready fleet gate now recognizes pnpm verify/test lines too

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

* fix: prettier-format pnpm-workspace.yaml — format:check gates verify

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

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-04 10:35:27 +00:00
60dac488b1 fix(control): a sentence you can read, and the check that noticed it (#479)
/control's "Suggested next" line carried `truncate` — one line, ellipsis. On
prod that rendered "Suggested next (profile): Conduct a 1-month baseline m…":
594 of its 644 pixels hidden at 390px, 432 at 1440. The remainder existed
only in the `title` tooltip, and a phone has no hover.

It is the card's one actionable sentence, and clicking it loads the text into
the composer — so the sentence IS the decision, and a tenth of a sentence is
not one. OutcomeStreak.tsx, in this same directory, documents having already
fixed this exact mistake for its glyph row. /activity has always clamped the
same "what's next" content to two lines (ActivityEventRow). This makes the
three agree: line-clamp-2.

Same class in the composer's status line, worse: it shared a row with four
icons and Send, leaving it 72px — measured at 0% shown at 320px and 14% at
390px. Shorter copy cannot fix that; no sentence fits 72px. It needed the
width, so below `sm` it wraps onto a row of its own (order-last w-full) and
from `sm` up it stays exactly as it was.

THE GATE, and why it is not a lint rule.

responsive-audit already looks for clipped text, and deliberately EXEMPTS
`text-overflow: ellipsis` as "a deliberate design choice". That exemption is
right for what it was written for — a project name in a narrow rail, a
filename, an id — and 76 files under src/components truncate exactly that way.
A rule banning `truncate`, or `truncate` beside a `title`, would fire on ~42
legitimate sites and be turned off within a week.

The distinction is prose, which a static rule cannot judge but a real viewport
can measure. So the check lives where the viewports are: flag an ellipsis only
when the text READS as a sentence (>=60 chars, >=8 spaces — an id has neither)
AND under half of it is visible (a chip losing its tail is fine; a line showing
its first eight words is not).

Proven by mutation, in one environment, with only the classNames differing:
  - with `truncate`  -> 2 findings ("40% shown, -552px", "22% shown, -402px")
  - with the fix     -> silent at 320 / 390 / 768 / 1440
and it flags none of the 76 legitimate truncations.

Verified against prod before the fix (2 findings at 320 and at 390, silent at
768/1440 where the line fits) and against a local server after it.

npm run verify passes.

Separately observed and NOT addressed here: /control logs a React #418
hydration mismatch at every viewport.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 10:30:47 +00:00
1572e993e7 fix(control): the second wording of "no zellij", and a remedy nothing rendered (#477)
Two defects, one class, found by sweeping for the neighbours of #476.

1. `no zellij session found` fell through to RETRY. This is how the Fleet
   Runner desktop app words the condition that the cloud words as "no zellij
   session is running on the connected computer" — poller.ts:881, three lines
   from the `tab not found:` string fixed in #476. Only one of the pair had
   been taught to the classifier, so fixing that one left this one shipping a
   Retry that can never succeed.

2. FAILURE_REMEDY.START_TERMINAL had ZERO consumers in AttentionBar. So
   fixing (1) alone would have made things worse, not better: a correctly
   classified failure would render no action at all, leaving the row with
   nothing but Dismiss. A remedy nothing renders is a classification that
   silently does nothing.

Also names FOCUS_TIMED_OUT_DESKTOP (`did not gain focus`). That one already
reached the right answer — a focus race IS retryable — but by accident, via a
default that happened to suit it. An accidental right answer is
indistinguishable from a wrong one until the default changes.

The gate is the point. scripts/test/failure-message-pairing.ts reads the
literals poller.ts actually throws and asserts each is recognised by a NAMED
phrase, then asserts every remedy the classifier can return is rendered by
AttentionBar. Producer and matcher are two definitions of the same sentence in
two independently-released codebases; counting instances was never going to
work. Reword either side, or add a remedy with no UI, and this fails first.

Proven by mutation, both halves:
  - drop the NO_TERMINAL_DESKTOP matcher  -> 14 passed, 1 failed
  - drop the START_TERMINAL render branch -> 14 passed, 1 failed

npm run verify passes; the test runs inside test:unit by directory glob, so
it is live in CI without wiring.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 09:45:40 +00:00
CatoandMao Nakamoto 0c932c2251 fix(control): a Retry button that could never work, reported through the widget (#476)
Filed from /control via the feedback widget — "what is this? can you fix?"
against an element reading:

  focus_tab → fleetcrown failed: tab not found: fleetcrown … Retry

focus-failure.ts already exists to prevent exactly this. Its own note says a
Retry beside "tab not found" is a lie, because retrying re-issues an
identical command against a target that is identically absent. It also
predicts how the protection would break:

  "a message and a classifier that each spell the same sentence
   independently are two definitions that drift the first time someone
   rewords the copy — and the drift is silent, since a misclassified
   failure still renders a plausible button."

That is what happened, across a boundary the note did not consider. Two
codebases word the SAME condition differently:

  cloud    "no zellij tab with that name in any active session"  → matched
  desktop  "tab not found: <name>"  (desktop/src/main/poller.ts) → NOT matched

So focusing a project through a local Fleet Runner fell through to RETRY and
drew a button that could never succeed.

Fixed in the classifier rather than only in the desktop app, deliberately:
Fleet Runner is versioned and released independently, so every operator on
an older build would keep sending the old wording. A classifier that only
understands the newest client is one that lies about older ones.

Tests use the reported string verbatim — including the trailing "4m agoOpen
on ControlRetry" the element picker captured, since that is what actually
reaches the function — plus casing, precedence against NO_TERMINAL, and two
near-misses ("tab closed by user") that must stay retryable. Proven by
mutation: removing the new match fails the assertion.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 18:17:02 -07:00
34f6d27ea6 fix(ops): the box register follows revampit to evig, and conformance notices a unit that lost its guards (#475)
revampit was renamed to evig on the box on 2026-09-02 (/opt/revampit -> /opt/evig,
revampit-app -> evig-app). The app repo caught up. This repo — which holds the
box register and the tooling that watches it — did not, and two of the stale
references were load-bearing:

  - verify.sh ran `systemctl is-active revampit-app` for a unit that no longer
    exists (`inactive`, exit 4), so the full-fleet sweep was permanently FAIL
    and never once checked the app that replaced it. A sweep that always fails
    is a sweep nobody reads.
  - uptime-sweep.sh watched revampit.orangecat.ch, which is now a Caddy `redir`
    block — a static 308 the sweep counts as up. That entry answers "is Caddy
    alive", not "is the app alive", and would have reported up through an evig
    outage. Pointed at evig.orangecat.ch, it probes /api/health for real.

The rest is register hygiene with no live consequence: the push-deploy hook
installed a command at /home/g/dev/revampit/scripts/selfhost-deploy-revampit.sh
(neither path exists any more), and three runner sandboxes listed a
/opt/revampit that is gone while omitting the /opt/evig that replaced it.

The automation, because a fix that only repairs today is worth 1x:

runtime-conformance-audit.sh now asks whether an enabled *-app.service still
has its guardrails — a memory cap and an OnFailure. A rename moves the unit
file; it does NOT move the .service.d/ drop-ins beside it. evig-app ran for two
days with MemoryMax=infinity on a shared box and no failure alert because its
drop-ins were still in the old unit's directory, and nothing noticed, because
these drop-ins are box state that no repo describes. Every other app unit on
the box carries both, which is what makes an exception a finding rather than a
preference. The audit already runs every 6h and alerts per finding, so this
class now pages instead of waiting to be stumbled over.

Evidence, on the real box:

  # after restoring evig-app's drop-ins by hand
  $ sudo bash runtime-conformance-audit.sh
  checked 26 app dirs on node 24.20.0
  findings=0 unreadable=0

  # negative control: move the drop-ins away again
  FINDING|evig|unit has no memory cap (MemoryMax=infinity) on a shared box
  FINDING|evig|unit has no OnFailure= — it can die without alerting anyone

  $ bash scripts/hetzner/verify.sh
  OK   evig                   systemd=active   local=200  public=200
  ... 23 checks, exit 0

`npm run verify` green: tsc clean, eslint 0 errors / 3 warnings, 130/130 unit
test files, 150 home tests, 66 uptime-sweep tests, all ops suites.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 00:55:37 +00:00
CatoandMao Nakamoto 39aae9a651 fix(widget): don't offer a mic the site's policy forbids (#474)
Reported: "Microphone permission denied" on both FleetCrown and OrangeCat.
Measured in the browser rather than guessed:

  orangecat.ch  featurePolicyAllowsMic: false
                permissionState: "denied"   (not "prompt")
                getUserMedia -> NotAllowedError
  fleetcrown    featurePolicyAllowsMic: true
                permissionState: "prompt"   (works)

Two different situations behind one error message. OrangeCat sends
`permissions-policy: camera=(), microphone=(), geolocation=()` from
next.config.js. `microphone=()` is an EMPTY allowlist — denied for every
origin including the site itself — so the browser never shows a prompt at
all. There is nothing the visitor can allow.

The bug is ours: navigator.mediaDevices.getUserMedia still EXISTS in that
state, so isVoiceSupported() passed and we drew a "Speak" button that could
only ever fail, then blamed the visitor's permissions for it.

isVoiceSupported now consults document.featurePolicy, so a policy-blocked
site simply never sees the button — the same progressive enhancement the
function already applied to a missing MediaRecorder or an insecure origin.

An unknown answer means ALLOWED, deliberately: featurePolicy is
non-standard and absent in some browsers, and hiding a working mic there
would be a worse failure than a click that fails with a readable message.

This is the half that is centrally fixable — one bundle, every customer
site, including sites we will never see. The other half is not, and cannot
be: Permissions-Policy is the host document's decision by design and no
script can override it. So the customer-facing docs now say plainly that
the mic needs `microphone=(self)`, what the symptom looks like, and that
everything else in the widget works regardless.

Pinned by four assertions in scripts/test/widget-voice.ts covering denied,
allowed, API-absent and API-throwing. Proven by mutation: making the check
always return true turns exactly the "denies the microphone" assertion red.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 17:20:06 -07:00
d97fd69db1 refactor(deps): ai-kit comes from npm — @bitbaum/ai-kit ^0.6.2 (#473)
The package is now published to the npm registry as @bitbaum/ai-kit
(npm's typosquat guard blocked the bare name "ai-kit", hence the scope;
ai-kit PR #25 documents the rename — content is identical to the
github:bitbaum/ai-kit#v0.6.2 tag). The git pin is retired: the lockfile
no longer records the writer's ssh transport and npm-major-specific
resolution for this dependency, so the whole lockfile-writer trap class
dies with it. All imports move from 'ai-kit' / 'ai-kit/grounding' to
'@bitbaum/ai-kit' / '@bitbaum/ai-kit/grounding'.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-04 00:11:06 +00:00
GandMao Nakamoto 46c21c22d4 feat(feedback): FleetCrown users can finally report bugs in FleetCrown (#472)
Asked directly: where is the feedback widget on FleetCrown itself, and how
does a user give feedback about the site they are using? Measured on the
live app — feedbackWidgetPresent: false, no widget script loaded at all.
The only thing in the corner is the Loki assistant button.

The widget was scoped to eleven public marketing routes by an allowlist
whose comment gave two reasons. Both were checked:

  "the FAB would collide with the app shell's mobile nav"
    True when written, and fixed earlier today. The widget now measures its
    corner and steps aside — rectangle matching for the desktop Loki FAB
    (56px at bottom:28, which the feedback FAB overlapped exactly), and an
    interactive hit-test below 480px for the mobile nav, which is inset-x-3
    and therefore too wide for the rectangle scan to treat as an obstacle.

  "in-app feedback already has Loki"
    Not true. insertSiteFeedback has exactly one caller — the widget's
    ingest route — and the word "feedback" does not appear in loki-core.ts.
    Telling the assistant "this button is broken" produces no site_feedback
    row, nothing in the triage inbox, nothing dispatchable. A signed-in
    user's only option was to tell the operator out of band.

So the rule is inverted: render everywhere EXCEPT a short list, each entry
carrying its reason — /terminal (a FAB over live PTY output covers what you
are reading), the auth routes (you are not in the product yet), and
/docs/feedback-widget (a launcher on the page documenting launchers is an
unanswerable "is this yours or the demo's?").

An allowlist meant every new page shipped with no way to report a bug on
it, and nobody noticed, because a missing feedback channel is invisible
exactly the way the problems it would have caught are.

PublicFeedbackWidget is now DogfoodFeedbackWidget: it is no longer public-
only, and a name that says otherwise is the kind of stale label this page
already had too much of.

Pinned by scripts/test/feedback-widget-reach.ts (42 assertions): every app
surface reachable, public ones still reachable, exclusions excluded
including nested paths, near-misses like /terminals and /settings NOT
swallowed by prefix matching, the widget mounted from the root layout so
new pages inherit it, and loki-core still unable to file feedback — the
premise that justified the old scoping.

Proven by mutation: restoring a public-only allowlist turns 20 assertions
red, including every app surface.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 13:11:59 +00:00
GandMao Nakamoto e654e8baed fix(projects): one element per anchor — tab panels own the hash (#471)
Left over from the tab conversion. The sections had ids from when they were
scroll anchors (`id="feedback"`, `id="settings"`, ...), and the new panels
took ids of their own — so both existed for the same concept: a panel
`panel-feedback` wrapping a section still called `feedback`.

That is not cosmetic. Every panel stays mounted, because they hold unsaved
drafts and poll while work is in flight. So loading /projects/<id>#feedback
handed the browser a real element to scroll to that was inside a HIDDEN
panel — native anchor behaviour racing the tab logic over the same name.
ControlInbox and FeedbackItemRow both link exactly that way, so it is the
common path, not an edge case.

The panel is the anchor now: `id={tab.id}`, `aria-controls={tab.id}`,
`scroll-mt-28` to clear the sticky tab bar. The six nested ids are gone.
What the browser scrolls to is what becomes visible.

Pinned by scripts/test/project-tab-anchors.ts rather than left to review:
it reads the tab ids out of ProjectWorkspaceView, asserts the panel uses
them, asserts no component under components/projects re-declares one as an
element id, and asserts ControlInbox still deep-links to #feedback — the
link that makes the invariant matter in the first place.

Proven by mutation: reintroducing id="feedback" on the section turns
exactly that one assertion red.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 12:44:39 +00:00
GandMao Nakamoto 1260cab156 fix(widget): auto-avoid did nothing in production — DOMRect does not spread (#467)
Shipped in #466, verified green by 38 assertions, and completely inert on
a real page. Found by probing the deployed bundle rather than trusting
the suite.

avoidOffsetY cloned its input with `{...own}`. At runtime `own` is a
DOMRect from getBoundingClientRect(), and DOMRect exposes left/top/right/
bottom as GETTERS ON THE PROTOTYPE, not own enumerable properties. So the
spread produced `{}`; every comparison became `undefined < number`, which
is false; and the function concluded, silently and without error, that
nothing was ever in the way. The launcher stayed at bottom:16 on top of
whatever it was covering.

Every existing assertion passed because their fixtures are object
literals, and those spread perfectly. The suite could not have caught
this — it was testing a shape the browser never produces.

Fixed by reading the four fields explicitly (toRect) at every boundary
rather than relying on the source object's shape: in avoidOffsetY, in the
loop's box arithmetic, and in probeCorner.

The regression test builds its fixture with Object.create over prototype
getters and NO own properties — the actual DOMRect shape. A class with
fields would not have reproduced it, since TypeScript compiles those to
own properties and the spread survives. Proven by mutation: restoring the
spread turns exactly that one assertion red.

Diagnosis path, since it was not obvious: reposition() WAS running (it
reset a vandalised inline style), probeCorner's filters all passed when
replicated by hand in the page, no exception was thrown, and boot served
autoAvoid:true. The only remaining suspect was the data crossing between
them.

Also: w-25 on the position preview was the only use of that utility in
the repo; w-24 is on the conventional scale.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 10:25:24 +00:00
GandMao Nakamoto 7449bb7093 feat(widget): stop the launcher covering other people's buttons (#466)
Every mainstream chat/support widget — Intercom, Crisp, Tawk, Drift, and
most in-house AI assistants — defaults to the bottom-right corner. So did
ours, with a z-index near the 32-bit maximum, so on any site running both
we won and hid THEIR control. Reported on kivvi; it is structural, not
specific to that site.

The only escape was `data-fc-bottom` on the script tag, which means
editing the customer's HTML: not one click, and impossible on a site we
do not deploy.

Three layers now, because none is sufficient alone:

1. AUTO-AVOID, any viewport. The launcher measures its corner and steps
   up past foreign fixed/sticky elements, re-checking on resize and at
   800ms/2.5s to catch chat scripts that boot late. Matching is by
   rectangle, so it works against a vendor we have never heard of.
   Replaces a dodge() that only ran at ≤480px and RESET to the base
   offset above it — which is exactly why desktop collisions survived.
   Full-width bars are skipped (stepping over a cookie banner just lands
   on the next one) and a shift larger than MAX_AVOID_SHIFT is abandoned
   rather than chasing the launcher off-screen.

2. REMOTE PLACEMENT. Corner + nudge + an auto-avoid switch live on the
   token and are served by /api/widget-boot, so moving a launcher on a
   live customer site is a dashboard action that lands within the boot
   cache window. The snippet stays a pointer — the same design idea as
   the pause switch. Placement rides along with the render verdict, so
   there is no window where the launcher paints in one corner and jumps.

3. VISITOR ESCAPE HATCH. Long-press (touch) or right-click (pointer) on
   the launcher offers move / hide / reset, kept in localStorage per
   token. For the case the other two missed, decided by the one person it
   is actually blocking. The operator's kill switch still outranks it.

Also fixes a real bug found while reading the ingest path: PAUSE DID NOT
PAUSE. The boot call stopped the widget rendering, but the token is
public and sits in the customer's page source, so a paused project kept
accepting POSTs from anyone holding a copy — and the operator, seeing no
widget on the site, had no reason to suspect it. Ingest now rejects a
non-active token.

Operator surface, per the two places it is actually needed:
  • project page: a position picker with a live preview box, because
    "bottom-left, 16, 16" is not something anyone can picture
  • Control inbox: Pause/Resume directly on the widget row, so the list
    that told you it was off is where you turn it back on

38 assertions cover the geometry, including that the widget's normalizer
and the server's agree — the logic exists twice because widget/ cannot
import from src/, and drift there would make the dashboard preview lie
about where the launcher lands. One of those assertions caught a real
defect: after clearing one obstacle the launcher landed exactly flush
against the next, so the avoid test now runs against a gap-inflated box.

Migration 0062 adds a nullable placement column; NULL means the default.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 02:50:15 -07:00
G 9beb11a78b chore: remove georgy.butaev@revamp-it.ch from scaffold git identity 2026-09-03 09:34:43 +00:00
34669faf19 fix(apps.conf): hirnli has its own database, and is a product not a client site (#464)
The deploy of hirnli's identity migration ran against evig's `revampit`
database and aborted:

  NOTICE: relation "users" already exists, skipping     <- evig's next-auth users
  ERROR:  column "user_id" referenced in foreign key constraint does not exist

because evig's `sessions` uses `userId`, not `user_id`. It rolled back and
shipped nothing, so no damage — but the schema step had pointed one app's
migrations at another app's production database, which is the failure this
file's own header warns about for the supabase apps.

Corrects four fields on the revamp-info row:

  db          revampit -> hirnli    Hirnli was split into its own database on
                                    2026-09-02. It is a platform holding many
                                    customers' fundraising research and has no
                                    business inside one customer's app DB —
                                    and it could not create `users` there
                                    anyway, that name is evig's.
  domains     + hirnli.orangecat.ch The platform host, live since 2026-09-02.
  repo_path   revamp-info -> hirnli The repo was renamed; this pointed nowhere.
  owner/kind  RevampIT/client-site -> bitbaum/product
                                    Hirnli is George's platform. Revamp-IT and
                                    evig are CUSTOMERS of it, the first two of
                                    many. Billing a platform to one of its own
                                    tenants is exactly the confusion the owner
                                    column exists to prevent.

`name` deliberately unchanged: it keys /opt/revamp-info and the
revamp-info-app systemd unit, so renaming it is a box-side cutover of its own
(as the evig rename was), not a config edit.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 08:53:43 +00:00
GandMao Nakamoto f487cc3862 chore: delete 1,190 lines of dead code, two dependencies, and two lying snapshots (#463)
* chore: delete dead code, and two dependencies with it

Each deletion verified by grep in both directions before removal, and
`npm run verify` passes with all of it gone.

src/components/ui/button.tsx — zero importers. It was also the ONLY
consumer of @base-ui/react and class-variance-authority, so both come out
of package.json with it. A shadcn-style Button was always going to sit
unused in a repo whose buttons are ui-btn-* classes in globals.css; what
it actually cost was two dependencies in every install and audit.

The Atlas cluster. /atlas redirects to /projects and the NAV entry points
there too, so the only link to /atlas/[projectId] lived inside AtlasCard —
which nothing rendered. Removed:
  • AtlasCard.tsx, LinkSuggestions.tsx — zero importers
  • lib/atlas/suggest.ts, graph.ts — reachable only from LinkSuggestions
    and their own test, which is the shape of code kept alive by the thing
    that proves it works rather than by anything that uses it
  • scripts/test/atlas.ts — that test
  • GET /api/atlas and POST /api/atlas/refresh — zero callers
  • scripts/atlas-probe-once.ts, whose own first line calls it a
    "TEMPORARY ops runner (deleted after use)"

DELIBERATELY KEPT, because they are live: /api/atlas/site (HealthScore and
LiveUrlField both PATCH it), /api/atlas/guides, lib/atlas/probe.ts,
SitePages, SiteGuides, getAtlasRow, and the /atlas/[projectId] page they
render — it is reachable by URL even though nothing links to it, and that
is a different question from being dead. The /api/atlas demo-sandbox deny
prefix also stays: it still covers the site and guides routes.

* docs: date the two snapshots that are read as if they were current

HANDOFF.md and AUDIT_REPORT.md are point-in-time reports with no staleness
marker, so both keep being read as the present tense. Neither is rewritten
here — the reasoning in them is still worth having — but each now opens
with what was re-verified today and what it got wrong.

HANDOFF.md matters most because it literally opens "Read this first", so
a wrong number in it travels further than one in a reference doc. Verified:
desktop is v0.8.15 not v0.7.5, Electron ^43.4.1 not 33, ~57 schema modules
not 39 tables, the deploy uses the forward-only applier not drizzle-kit
migrate, its "next up" list is fully ticked, and the manual mirror step it
describes is automated.

AUDIT_REPORT.md has drifted in BOTH directions, which is the more
interesting failure: item 3 (bare box IPs) largely closed once
scripts/hetzner/_box-env.sh landed, while item 8 (god files) got worse —
1254→1297, 963→1044, 789→948. An unticked "LOW" item is not a stable one.

It also carried the private-zone PIN twice in its own text, including in
the line telling the operator to rotate it "because it is in git". Having
scrubbed that value from three scripts, the report had become the only
file in HEAD still publishing it. Both occurrences redacted. The item
stays OPEN: redaction is not rotation, and the history leak is unchanged.

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 01:27:19 -07:00
GandMao Nakamoto c41c1809e2 feat(widget): speak your feedback — plus the signals, escaping and docs that were lying (#462)
* fix(email): escape visitor text before it reaches an email body

feedbackShippedTemplate interpolated `excerpt` and `page` raw. Both are
visitor-authored — excerpt is the free-prose suggestion typed into the
widget on a customer's site, page is location.pathname read off that
site — and the resulting HTML is mailed from our own domain to an
address the same visitor supplied.

operatorMailTemplate, four lines below, escaped correctly with an inline
replace-chain. That is the tell: escaping was something each template had
to remember separately, and this one forgot. rss.xml had a third copy of
the same chain.

So the escape is now a named helper both callers share, covering the five
XML predefined entities (the two extra quote forms make it safe in an
attribute as well as a text node, so no caller has to pick a variant).

Also makes the templates importable without a database. logSend's
debug-logs import opened a DB client at module load, which every pure
template in the file inherited — the reason none of them had tests. It is
deferred into the function now; sending logs exactly as before.

Proven by mutation: reverting the escape turns exactly the three
injection assertions red, not the whole file.

* fix(feedback): stop a failed request from answering "nothing needs you"

Three surfaces read an empty array as an empty queue. An empty array is
also what a failed fetch leaves behind, so a 500 or a timeout rendered as
the confident answer "there is nothing here" — on the exact screens an
operator checks to be sure nothing is waiting.

- ControlInbox returned null when total === 0, so both fetches failing
  produced total silence. It now stays quiet while requests are still in
  flight (a failure that resolves fast should not flash), and once they
  settle with nothing, says which of the two happened. When one list
  loads and the other does not, the count renders with a note that it
  may be low rather than presenting a partial total as complete.

- FeedbackInbox dropped `error` from useFetch entirely and fell through
  to "No feedback yet". The load error is now aliased `loadError` —
  `error` was already the mutation error from useFeedbackActions, and
  that collision is how the load error came to be dropped.

- ProjectFeedbackSection treated a failed token GET as "no token", which
  offered "Enable & install" for a widget that may already be live on the
  customer's site. Not knowing is now its own state.

Every new branch is reachable only when a request actually failed; the
genuine empty states are untouched.

* feat(widget): let visitors speak their feedback instead of typing it

Typing a bug report on a phone, on someone else's site, is where most
reports die. The widget now offers a mic: record, the clip is transcribed,
and the text lands in the same textarea appended to whatever was already
typed. The visitor still presses Send — speech-to-text mishears things,
and a mic that auto-sent would file those mistakes under their name.

FleetCrown already had working transcription (terminal, Loki composer,
command palette) but the widget never got it. Two things were missing:

- CORS. /api/beacon/transcribe is public but answers no preflight and
  sets no ACAO, so a cross-origin caller can never read the response.
- Authorization. That route takes no token — it is guarded only by a
  per-IP limiter. Opening it cross-origin would have made it an
  anonymous endpoint that spends our Groq quota for anyone with the URL.

So this adds /api/widget/transcribe rather than widening the beacon
route: same fcw_* token that already authorizes ingest, same per-token
origin allowlist, per-IP and per-token rate limits, and Groq only — the
local-Whisper fallback spawns ffmpeg + python3 on the host, which is not
something to expose to anonymous traffic. The Groq step itself moved to
lib/transcribe.ts so both routes share one implementation instead of
growing two copies of the error mapping.

Also in the widget, from the same audit:
- Recording stops and the mic is released when the panel closes, so the
  browser's recording indicator never outlives the panel on a host site.
- Sub-44px touch targets (the 18px remove-image dot, attach button) get
  a coarse-pointer hit area without changing how they look.
- The pulsing record dot honours prefers-reduced-motion.

Progressive enhancement throughout: no MediaRecorder, or an insecure
origin where getUserMedia is undefined, renders no button at all rather
than a control that cannot work. Bundle 16.3KB -> 20.8KB.

/api/widget is classified "spend" in the demo sandbox — the repo's own
gate caught that omission before this commit existed.

* docs(claude): correct the claims that were sending agents the wrong way

CLAUDE.md is loaded into every agent session, so a false line in it is not
a stale doc — it is an instruction. Each of these was verified against the
code in both directions before editing.

- Session helpers. It named `getCurrentUserId()` and `DEFAULT_USER_ID`;
  neither has existed since 98e88b65. Zero hits in src/. The real API is
  `getApiUserId()` (routes) and `requirePageUserId()` (pages), 64 files.

- The executor model. It said home/ runs on the user's machine "not the
  hosted box", and that Fleet Runner desktop is the "sole" local executor.
  scripts/box-runner.ts is a systemd service ON the box that imports the
  same startWatcher, added in b62e3aeb to delete the laptop dependency,
  and is the DEFAULT per this repo's own SSOT. A third executor,
  scripts/hosted-runner.ts, also exists. Neither was mentioned. An agent
  reading the old text would reason about the wrong machine.

- Husky hooks. Documented as pre-commit tsc+eslint / pre-push test:home.
  Actually pre-commit is eslint on staged files with no tsc, and pre-push
  runs the whole `npm run verify` bundle plus smoke and prod dogfood. The
  practical consequence — pre-push takes minutes — is now stated.

- Dark mode. "always dark mode (.dark on html)" is not true: ThemeProvider
  sets defaultTheme="dark" and a ThemeToggle ships in 8 places. Light is a
  real state, so the old advice to lean on text-white/* would break it.

- Six named components do not exist (ProjectTile, AutopilotCard, PromptRow,
  FeaturedCard, CategoryBar) or survive only as type names
  (ProjectGrid/ProjectDetail). Replaced with what is actually on disk.

- /feedback had no row in the Views table and widget/ had no entry at all,
  despite being a top-level nav surface and the only code strangers on
  other people's sites execute.

Also closes the gap that let widget/ drift unnoticed: `npm run lint` now
covers it alongside src/ and home/. It passes clean today, so this costs
nothing and stops the next regression rather than documenting it.

* docs: delete the agent CLI registry spec

Three independent reasons, any one sufficient:

1. It contains a slur — "A new engineer (or the 'retard' user)" — in a
   public repo. That alone is not something to leave sitting in docs/.

2. Every script it analyses is gone: scripts/cockpit-daemon.sh,
   agent-hook-lib.sh, agent-hook-bridge.sh, and the _agent_definitions.sh
   it proposes creating. Its "high duplication areas" list describes a
   codebase that no longer exists.

3. Its central decision is now false. It names src/lib/agent-registry.ts
   the "Primary SSOT"; that file's own header says it is a compatibility
   shim over src/lib/agents/, kept only for back-compat, and that new code
   should import from @/lib/agents directly. An agent following this spec
   would extend the shim it is supposed to be migrating off.

The refactor this document proposed did happen — differently and better
(per-agent adapter modules, ~300 lines removed). The plan that lost is
not worth keeping as a description of the system that won.

README's link to it goes too, so the docs index has no dead entry.

* docs(widget): stop the architecture note describing a system that moved on

Corrections, each verified against code:

- It said "No rate limiter exists in FleetCrown yet — port revampit's".
  src/lib/rate-limit.ts exists, is owned by the shared limitkit package,
  and is already imported by the ingest route the same document describes.
  Left alone, that bullet is an instruction to write a second one — the
  precise mechanism by which this fleet accumulated 14 rate limiters.

- The API table listed 5 routes and omitted GET /api/widget-boot, which is
  the render gate, the remote kill switch, and the heartbeat behind the
  "Live" badge — i.e. most of what the surrounding prose sells. Added,
  along with the new /api/widget/transcribe pair.

- It claimed /widget.js is "immutable-cached with a version query". There
  is no version query and no cache rule for it; next.config.ts sets those
  for /sw.js only. The "upgrades ship centrally" story rested on caching
  behaviour nobody configured.

- Screenshot capture, the submitter email loop and auto-triage drafts were
  all listed under "Later (not now, YAGNI)" and "not in v1" while being
  shipped and documented elsewhere in the same file.

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-02 09:27:19 -07:00
GandMao Nakamoto e0cc0b52d4 feat(ai): wire an AI chain health tracker into every completion path (#460)
The chat/tool/vision chains (groq.ts, agent/llm.ts, vision.ts) already walk
Groq -> OpenRouter on failure and are correctness-complete, but nothing
recorded whether that walk was still succeeding. A chain that always has
somewhere else to try also always returns success-shaped output to its
caller, right up until every link is dead — at which point the failure looks
like any other and only a user complaint would surface it. A full AI outage
would have been invisible with zero observability anywhere.

- src/lib/ai/health.ts: shared ai-kit createHealthTracker({downAfter: 3})
  instance, matching the convention already adopted fleet-wide (aoz-housing,
  surf-your-life, truthseeker).
- src/lib/groq.ts callTextDetailed, src/lib/agent/llm.ts callModelWithTools,
  src/lib/vision.ts analyzeImages: each hand-rolled chain walker now records
  one success/failure per top-level call at its real success/exhaustion
  points (not per link — a later link answering is the fallback working, not
  a health problem).
- src/app/api/health/route.ts: exposes the tracker's getHealth() as a new
  informational-only `ai` field. It is deliberately NOT folded into the
  200/503 status code — a dead vendor key can't be fixed by a restart, so
  gating the restart decision on it would bounce a healthy app for someone
  else's outage.
- scripts/test/ai-health.ts, scripts/test/health-route.ts: new coverage —
  the tracker's status transitions, and that the health route's status code
  is unaffected by AI health regardless of state.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-02 08:47:20 +00:00
GandClaude Opus 5 caa0e41c3b chore: add a formatter (#449)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

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

* style: format with prettier (1062 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

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

* chore: teach git blame to skip the reformat

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

* fix(lint): reattach two guards the reformat detached

Both effects were one-liners, so a trailing eslint-disable-line covered the
setState call:

  useEffect(() => { setSelected(new Set()); }, [q.length]); // eslint-disable-line ...

prettier expanded the block. The comment stayed on the closing line while the
call moved above it, so the guard protected nothing and the rule its author had
deliberately silenced failed the build.

This is the second shape of the same defect — hirnli had the eslint-disable-NEXT-line
variant. Both come from the same fact: an eslint directive binds to a line
number, so reformatting can silently unbind it, which makes 'mechanical, no
behaviour change' false for any bulk reformat.

* chore(desktop): bump the runner version the reformat requires

desktop-release-drift enforces that anything built into Fleet Runner which
differs from the last released tag must carry a version ahead of that tag —
main read 0.8.15 and fleet-runner-v0.8.15 already shipped.

A whole-repo reformat changes bytes under desktop/, so the gate fires. The
alternative was adding desktop/ to .prettierignore, which would buy a quiet PR
by carving a permanent hole in the formatter's coverage — the precise shape of
silent drift this test was written to catch. Bumping is what the rule asks for
and costs one patch release whose only content is whitespace.

* chore: merge main and re-format

A whole-repo reformat conflicts with any concurrent commit, and a conflicting PR
runs no checks at all while reporting nothing. Conflicts resolved to main,
which is correct because this branch changes formatting and nothing else.

* chore: leave desktop/ out of this reformat

desktop-release-drift is right to refuse this. Everything under desktop/ is
built into Fleet Runner, so changing it means shipping: bump the version AND add
a FLEET_RUNNER_RELEASES entry, whose stated audience is 'person who installed
Fleet Runner and wants to know what changed'. For a whitespace-only build the
honest answer is 'nothing', so that release should not exist — and I should not
write release notes claiming otherwise.

I had bumped to 0.8.16 to get the gate green. That was the wrong direction:
publishing a build to three OS runners to keep a formatting PR quiet. Reverted.

desktop/ is excluded in .prettierignore with the reasoning recorded there, to be
formatted alongside the next real runner change, where the bump and the notes are
true anyway.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 09:23:30 +00:00
bc0493f68f refactor(agent): the grounding harness is imported, not mirrored (#448)
FleetCrown half of the mirror retirement (fleet AI-engine plan, Phase 2).
src/lib/agent/core was the CANONICAL copy of the harness, mirrored
byte-for-byte into OrangeCat and policed by scripts/test/agent-core-drift.ts
plus scripts/sync-agent-core.ts. Its own README called the duplication
"deliberate and temporary" and named extraction to a package as the exit.
ai-kit v0.6.2 is that exit; OrangeCat's twin PR (#846, merged) deletes the
other side.

Fourteen imports across nine files collapse from three deep paths to one
subpath import. The sync script, the drift check and the npm script that ran
it are deleted rather than kept green: with a single copy there is nothing
left to drift, and a gate with no possible failure mode is noise wearing a
uniform. ai-kit also moves v0.2.1 -> v0.6.2 (still the ai-ration name in the
old lock entry); the three root imports this repo uses (chain, fair-share,
limits) are unchanged surfaces across that jump, which typecheck confirms.

The packaged copy differs from the deleted canonical by two mechanical
deltas, both made where the code now lives: .js extensions on relative
imports (pure ESM) and two null-guards under ai-kit's
noUncheckedIndexedAccess.

tsc clean; 124/124 unit test files pass (one fewer than before: the drift
check no longer exists to run).


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 09:45:07 +02:00
091edc0bf2 fix(nav): the desktop sidebar styled the active item and never said so (#447)
SidebarNavItem applied `ui-nav-item-active` from `current` and set no
aria-current, so the active state existed only for people who can see it.
MobileNav, MobileNavSheet and FleetSurfaceGuide all announce it correctly —
four surfaces right, one wrong, which is what applying a rule by hand looks
like at the margin.

So the rule stops being applied by hand. check-design-system.sh gains a
`check_paired` helper — the inverse of `check_none`, for rules about what MUST
be present — and one rule using it: a file that styles `ui-nav-item-active`
must also contain `aria-current`. The existing gate could only ever look for
forbidden strings, so this entire class of defect was invisible to it.

`check_paired` warns loudly when its trigger matches nothing, for the same
reason the ripgrep guard at the top of this file exists: a rule that scans
nothing must not read like a rule that passed.

Mutation-proven: with the fix reverted the gate exits 1 and names
SidebarNavItem.tsx; with it in place, exit 0 and 9 checks run. Typecheck clean.

Found by a fleet-wide navigation audit across 20 repos, which found the same
one-straggler shape in aoz-housing, vitareba and evig.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 07:41:58 +00:00
7c12ddb023 feat(ops): SSOT registry for everything that reaches the operator's Telegram (#445)
George: 'telegram should still update me on things. and we should have ssot
for things telegram does/updates me on. i do like when it tells me when there
is feedback sent through the feedback form.'

docs/telegram-notifications.md is now that SSOT: every notification class —
requested updates (visitor feedback, run outcomes, Loki briefings), incidents
(with the fix-agent dispatch), platform self-checks, and off-repo senders
(Loki cron, orangecat uptime) — one row each: what arrives, when, from where.

Enforced, not aspirational: scripts/ci/check-telegram-registry.sh (wired into
npm run verify) finds every sender surface in the repo — direct
api.telegram.org calls, importers of telegram-send.ts, box scripts sourcing
lib-alert.sh — and fails when a path is missing from the registry. Adding a
notification without registering it turns CI red in the same PR.

Mutation-proven: a planted unregistered sender fails the gate naming the
file; removing it goes green (22 sender files registered).


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 10:58:08 +00:00
1a342fa6d6 refactor(ops): one voice on the phone — grace, digests, backoff, subjects (#444)
George, 2026-08-29, pasting his Telegram: 'refactor whatever is sending this
abomination.' The morning read as: identical FAILED triples at 08:01, 08:31,
09:01, 09:32, 10:02, 10:33; a six-pack of FAILED+RECOVERED for a 5-minute
deploy blip; closures naming state keys ('RECOVERED:
rtc_revampit_configured_host_does_not_resolve__typing_static_nvi',
'agentwork_reparaturbonus-zh'); UNIT DOWN bodies that repeat the unit name
four times in systemd boilerplate while burying the app's actual error; and
two URL monitors speaking two dialects.

One rule set, all in lib-alert.sh and its callers:

- Reminders BACK OFF: the claim stamp holds 'ts count'; each claim quadruples
  the next wait (30m, 2h, 8h, capped at a day). alert_clear resets the
  ladder. claim_once is the decision without the delivery, so callers can
  digest.
- The sweep gets ONE-TICK GRACE: first sighting watches, never pages — the
  OnFailure notifier owns the instant page and already declines deploy blips.
  A blip inside the grace produces zero messages, failure or closure.
- DIGESTS: N failures on one tick are one 'STILL FAILING: a; b' message; same
  for recoveries.
- Recovery names the SUBJECT, never the key: alert_transition remembers the
  human subject at bad-time (explicit arg, else text-to-first-colon, else
  key) — fixes every alert_transition caller fleet-wide at one seam.
- The notifier page shows the APP's error: systemd liturgy filtered from the
  journal tail; '🔴 DOWN: appcron-kivvi-dunning — curl: (22) … HTTP 500'.
- fleet-uptime.yml speaks the same dialect ('🔴 DOWN: app (…)',
  '✅ RECOVERED: app', no ISO timestamp — Telegram stamps messages).

92 tests green; mutation-verified per area: no-grace → 8 red, key-recovery →
3 red, flat-backoff → 1 red.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 10:29:22 +00:00
beb1ee1699 feat(ops): a page queues its own fix — incident dispatch into FleetCrown (#443)
The alerting stack got very good at saying 'X is broken' exactly once — and
then a human still had to do the fixing. 2026-08-29 morning: four appcron
units re-paged every 30 minutes, every one fixable by an agent, none fixed by
one, while the FleetCrown box-runner polled an empty queue on the same box.

New /opt/monitoring/incident-dispatch.sh: every unit failure worth paging also
queues a remediation run (POST /api/inject, the same call Loki's fc.sh makes;
journal tail embedded in the prompt; notifyOnClose so the run's close summary
— root cause, action, what remains — is what reaches the phone). One incident
is one dispatch: a dispatch:<unit> stamp shared by both detectors (OnFailure
notifier + host-check sweep), cleared on recovery. Failure modes never cost
the page: missing token, API refusal, unknown project (retried as fleetcrown)
all degrade to journal lines. ALERT_DRY_RUN queues nothing.

The page itself now says '🤖 fix agent dispatched (<project>)' — the clause
that turns it from 'act now' into 'read the outcome when it arrives'.

18 new test cases in test-host-alerts.sh (78 total); mutation-verified: with
the notifier's dispatch call removed, 12 go red.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 09:50:13 +00:00
GandClaude Opus 5 20ff75ef33 fix(ops): only flag units that are meant to be running (#440)
The unit check asked "is it active?" and flagged aoz-demo, which is stopped AND
disabled with nothing routed to its port — deliberately retired. A check that
reports a decision as a fault is one people learn to ignore, and an ignored
check is worse than none.

"Is it supposed to be running?" is a different question from "is it running?".
Enabled-but-inactive is the fault; disabled-and-inactive is a choice.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 10:00:57 +02:00
GandClaude Opus 5 63c9f2e943 feat(ops): audit what is DEPLOYED, not what is committed (#439)
bitbaum/fleet already has hosted-supabase-audit.sh, whose stated job is "does
any repo still point at a Supabase we retired?". It ran on 2026-08-28 and
reported SUCCESS while printcraft returned 500 in production, pointing at a
hosted project whose DNS no longer resolved.

It missed because it runs `git grep` over repo checkouts, and the reference
lived in /opt/printcraft/shared/.env — not in git, deliberately, because the
box is the environment SSOT. The gate was scoped to the wrong substrate: it
checked the artifact while the configuration lived in the running system. A
check that looks in the wrong place is worse than no check, because it answers.

The rule this implements: SOURCE audits run in CI against git, RUNTIME audits
run on the box against what is actually deployed. The fleet had a good
collection of the first kind and none of the second.

Five checks, each a shape that has already bitten:
  - an env still naming a retired managed host (supabase.co, neon, planetscale)
  - a configured host that no longer resolves
  - a process running with keys its .env can no longer provide — config broken
    on disk for hours while the process holds the old values, which is exactly
    how 25 vitareba cron jobs died at the next restart
  - a declared node engine the box cannot satisfy
  - an app unit that is not active

Found on its first run, before it was committed:
  revamp-info  declares node >=22, box runs 20.20.2 — and it IS deployed
  revampit     points at a dead trycloudflare.com quick-tunnel host
  aoz-demo     unit inactive

Alerts per finding, never one aggregate: host-check spent six weeks unable to
fire because one permanently-failed unit pinned a single boolean at `bad`.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:13:04 +02:00
a78e8daa2a fix(security): bind fleetcrown to localhost only, not every interface (#437)
launch.sh's own comment claimed `unset HOSTNAME` makes the standalone Next
server "reachable at 127.0.0.1 / localhost" — it does the opposite. Next's
standalone server reads HOSTNAME as the bind address; unsetting it does not
default to localhost, it falls back to Next's own default of 0.0.0.0 (every
interface). Found 2026-08-29 while auditing why two unrelated services
(revampit, aoz-demo) were listening on all interfaces — fleetcrown itself
turned out to be one too.

Not an active incident: ufw's default-deny only allows 22/80/443, so port
4002 was never actually internet-reachable. But relying on the firewall to
cover a bind-address mistake is exactly the kind of thing that breaks
quietly the day the firewall config changes for an unrelated reason.

Every other app in the fleet already gets this right — sync-infra.sh sets
`HOSTNAME=127.0.0.1` for every site it provisions. fleetcrown launches
itself outside that shared script and never picked up the same convention.
Fixed to match: export HOSTNAME=127.0.0.1 instead of unsetting it.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 05:18:25 +00:00
GandClaude Opus 5 ae562996a3 feat(ops): answer "what datastore does this app actually use?" (#436)
Asked whether anything still used the self-hosted Supabase stack, I grepped
DATABASE_URL across every app env. Every hit pointed at localhost:5432, so the
answer looked like "nothing" — and stopping the stack was one command from
taking orangecat and botsmann down, with 114 auth users, 114 profiles and 927
messages behind it, written to as recently as the previous evening.

A Supabase app never sets DATABASE_URL. It talks HTTPS to PostgREST/Kong via
SUPABASE_URL. Absence of a Postgres connection string is not absence of a
dependency; it is the signature of a different one.

This reads BOTH bindings per app and reports whether a Postgres target actually
contains tables, so an empty database cannot masquerade as the live one.

What it found on first run:
  orangecat, botsmann -> self-hosted Supabase (supabase.orangecat.ch)
  printcraft          -> HOSTED supabase.co, never migrated off the cloud
  12 apps             -> native postgres
  native db orangecat -> exists with ZERO tables, referenced by nothing

Read-only. The question "is X safe to stop?" now has a factual answer instead
of a confident wrong one.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 07:12:05 +02:00
f313df1a16 fix(ops): one incident is one message ACROSS detectors, not just within one (#435)
06:45 `⚙️ FAILED UNIT: orangecat-cat-outcomes.service` from the host-check
sweep. 06:46 `🔴 UNIT DOWN: orangecat-cat-outcomes.service` from the OnFailure
notifier once its grace expired. One incident, two messages — and each detector
was individually correct and correctly deduplicated against itself, which is
exactly why this survived yesterday's fix. Keying the cooldown per detector
still lets N detectors send N messages about one fact.

- The cooldown key is now the SUBJECT (the unit), shared between the sweep and
  the notifier. Whichever notices first speaks; the other finds the claim taken
  and goes to the journal. Neither has to know the other exists.

- Closure is only sent for a failure that was actually announced. `✅
  RECOVERED: unit____` reached George yesterday — closure on a message nobody
  received, naming a state key instead of a unit. Recoveries now name the unit,
  and say nothing when nothing was said.

- The nightly disk GC no longer pages when it succeeds. "freed 2296MB (81% →
  78%)" at 00:02 is the box looking after itself and asking nothing of anyone;
  the disk check already pages above 85%. It still pages when the outcome is
  NOT routine — space reclaimed but still above the mark, or nothing left to
  reclaim. Its test suite gained a delivery capture, because with only a logger
  stub, moving a message from alert() to logger() is indistinguishable from
  leaving it alone.

test:ops 60 passed in the host-alert suite (was 52) and 22 in disk-gc (was 20).
Three mutations — sweep keyed on itself, closure for an unannounced failure,
routine GC paging again — each turn their suite red.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 05:04:20 +00:00
644de633b0 fix(ops): a message is worth sending only if a human must act on it (#433)
* fix(ops): a message is worth sending only if a human must act on it

Thirteen Telegrams reached George on the evening of 2026-08-28. Two of them
were real, and one of those two was an outage nobody had told him about in a
way he could act on. This makes every category of the other eleven impossible.

- lib-alert: one delivery point. alert_once/alert_clear give every sender a
  per-subject cooldown; an identical-text floor sits under the UNKEYED path so
  a caller with no state (the register check, which sent the same failure twice
  in 60s) still cannot repeat itself. Keyed senders bypass the floor — two
  mechanisms arguing about one message means the quieter one silently wins.
  ALERT_DRY_RUN=1 journals without delivering, because at 22:14 a test of a new
  check rang a real phone with a message saying it was a test. Suppressed is
  never invisible: the journal gets every alert, including the suppressed ones.

- notify-failure: a oneshot that a retry has already fixed is not an incident.
  restic-check failed at 18:41:42 on a 25-day-old stale lock, was re-run at
  18:42:28, finished clean at 18:44:46 — and paged, because OnFailure fires on
  the failing run and nothing looked again. It looks again. The unit template
  gains TimeoutStartSec: DefaultTimeoutStartSec is 90s, so the notifier would
  otherwise be killed inside its own grace window and the page never sent.

- host-check: an app whose .env its own unit User= cannot read is REPAIRED and
  reported, not asked about. This took two apps down today (vitareba 18:38,
  botsmann 20:16, both root-owned .env, both crash-looping) and both times the
  remedy was one deterministic command — the owner is not a guess, it is the
  unit's User=. deploy.sh asserts the same invariant where the file is written.

- cloud-init-hotplugd is masked. Failed since 2026-07-22 with nothing to do, it
  was the member that pinned the old aggregate latch at `bad` for six weeks;
  per-unit keying turned that silence into a recurring page. A unit that can
  only produce noise should not be in the failed set at all, so that
  `systemctl --failed` keeps meaning "something is wrong".

- fleet-register-check moves into the repo (it was untracked, which is why
  neither of its bugs was ever reviewed) and now judges the register as
  COMMITTED. It read a working tree that ~15 agent sessions share and paged
  twice about a duplicate port that had never been committed. CI still judges
  the tree, which is right there — in CI the tree IS the commit under review.

Six mutations, each reintroducing one of the above, each turning the suite red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqzRcMP1uJzd7Tav5fNxQz

* fix(ops): the watchdog had its own copy of the send path

watch.sh carried a byte-identical alert(), so every property added to the
shared one — the duplicate floor, ALERT_DRY_RUN, the journal-always guarantee
— silently did not apply to the watchdog's DOWN/RECOVERED messages. A second
copy of a send path is exactly how the fleet register check ended up able to
page twice in sixty seconds with no state at all: nothing is wrong with the
copy on the day it is made, and nothing updates it afterwards.

Falls back to journal-only if lib-alert.sh is somehow absent, rather than
going silent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqzRcMP1uJzd7Tav5fNxQz

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 20:48:02 +00:00
GandMao Nakamoto 80fca6cf94 fix(ops): one incident is one page — per-unit cooldown on the OnFailure notifier (#432)
vitareba-app could not read its .env on 2026-08-28 (root-owned after a
`chown --reference`). Restart=on-failure + RestartSec=3 restarted it 18 times
in 60 seconds, every restart fired OnFailure, and every OnFailure sent its own
Telegram: six identical "UNIT DOWN" messages for ONE incident, none of which
made the fix arrive any sooner.

The existing guard could not help. It silences a unit that comes BACK within
8s (deploy restarts, transient blips); a unit that cannot start at all never
comes back, so the guard fell through and paged on every loop iteration.

Page once per unit, hold for NOTIFY_COOLDOWN_SEC (30m), then re-page as a
reminder while it is still down. Recovery clears the stamp, so the next
genuine outage pages immediately instead of inheriting the last one's silence.
Suppressed restarts still go to the journal — quiet in Telegram must not mean
invisible in the logs.

Also: the summary block added in #431 sat in the MIDDLE of the test file, so
`[ "$fail" -eq 0 ]` under `set -e` aborted the run on the first failure and
the cases below it never executed — a suite that reports on itself partially.
One summary, at the end, after every case has run.

Covered by scripts/hetzner/test-host-alerts.sh, which drives the shipped
heredoc payload (no second copy to drift). Proven by mutation on a throwaway
copy: dropping the cooldown, dropping the recovery clear, and freezing the
cooldown each turn the suite red.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-08-28 19:29:45 +00:00