Commit Graph
486 Commits
Author SHA1 Message Date
CatoandClaude Opus 5.5 2dc485fa37 fix(feedback): /feedback 500ed whenever a run was queued behind another
findQueueBlockers reads a raw db.execute row, which is not run through the
schema: started_at comes back as a string, but was typed Date, and
applyRunContext called .toISOString() on it. Every inbox load with a
queued-behind run threw (479 times since 12:54 UTC). Coerce at the query,
and type the raw column honestly. The two other raw Date columns
(robots.updated_at, people.last_interaction) already coerce.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 18:10:45 +02:00
CatoandClaude Fable 5.1 8ca728a649 feat(studio): the private link comes back — mailed at intake, on a later address, and on request (#1091)
* feat(studio): the private link comes back — mailed at intake, on a later address, and on request

A studio request's only credential is its private link; a closed tab was a
lost request. Now the link is mailed to the address given at intake, or
added later through a `set_contact` guest action; and `/api/studio-recover`
hands the address fresh links to every open request under it (the old
links die), answering identically whether or not the address is known.
Keys are never stored or logged — email.ts records recipient and subject.

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

* fix(demo): classify /api/studio-recover for the demo sandbox; the rotation rejects a demo owner

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 08:18:35 -07:00
CatoandClaude 6bf6142b63 feat: live-fix messages open "Watch the fix"; late at night Control says go to sleep, autopilot has it (#1078)
Fix walkthroughs:
- New /feedback/<id>/watch-fix mints a fresh owner tour ticket on every
  open and lands on the live page's walkthrough (inbox when there is no
  live page or no access). A ticket lasts a day; a Telegram message lasts
  forever, so messages carry this address, not a ticket.
- notifyFixShipped: push, Telegram and the in-app alert for a live fix now
  link the walkthrough ("▶ Watch the fix") instead of the bare page.
- getFeedbackWithProject returns the project's liveUrl.

Late night:
- lib/late-night: 23:00–05:00 local, one "night" key per evening, copy.
- LateNightAutopilot on Control: autopilot off → "Hand it to autopilot and
  go to sleep" with one tap to turn it on; on → "Autopilot is on — go to
  sleep". "Not tonight" hides it until the next evening.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-07 11:40:54 -07:00
CatoandClaude Opus 5.5 1632405b27 feat(projects): a project started from a brief is named after its site — xhiva, not xhiva-art-refresh-<32 hex> (#1055)
The name becomes the repo and the <name>.orangecat.ch preview, and it used to carry
the request id because it doubled as the duplicate-submit guard. The operator, on the
xhiva preview: "why not just xhiva.orangecat.ch".

- siteName(): the registrable name (no www, no TLD, two-part suffixes like co.uk off,
  accents off); "inspired" projects say so; "Make it yours" stays my-<repo>.
- firstFreeName(): -2, -3 only when the name is taken anywhere in the fleet (repo and
  subdomain are global).
- The request id moves to the project's metadata (briefRequestId): a repeat finds its
  project by id; a per-request lock covers two tabs at once.
- briefKind is recorded too, because "this is a repo copy" was ALSO read from the
  name — and it is load-bearing (empty starter, the imported repo's Actions off).
  Projects started before keep being recognised by their old name.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 08:00:36 -07:00
CatoandClaude Opus 5.5 d5719be7f9 feat(terminal): screenshots reach the agent as images — the runner writes them, Claude opens them (#1045)
* feat(terminal): screenshots reach the agent as images — the runner writes them, Claude opens them

From the operator: a screenshot attached in the Terminal's composer should
actually reach the agent working in it. It never did — it was "described"
by a free vision model first, and when those were rate-limited the agent got
"Could not analyze attached image(s): all vision models failed — HTTP 429"
(2026-10-05). Even when they answered, the agent read a paraphrase.

Claude Code reads an image file when the prompt names its path. So:

- lib/agent-attachments: an image gets a placeholder line in the prompt and
  travels with the command (pending_commands payload `attachments`);
  parseAgentImages is the runner's boundary check (uuid ids, png/jpeg/gif/
  webp, size and count caps — refused whole).
- lib/agent-attachments-fs: where the agent runs (box runner, Fleet Runner,
  or a local Loki), write each image to ~/.loki/attachments/<id>.<ext>
  (0600, outside any checkout) and swap the placeholder for its absolute
  path; a file that cannot be written becomes a sentence, never a token.
- tab-inject (Terminal composer): stageAttachmentsForAgent instead of the
  vision fold; dispatch/inject carry the images.
- Runner (poller inject + dispatch, command-validator): accept and
  materialize them before typing.
- Chat view: a message with a screenshot goes through the new
  /api/control/chat-send (verbatim inject; the keystroke lane has no room for
  a picture), replacing /api/control/fold-attachments.

Other dispatch paths (Control's orchestration run, /api/inject, feedback)
still describe images; they are not typed into a live terminal.

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

* chore(desktop): Fleet Runner 0.8.39 — screenshots reach the agent as image files

The runner now materializes attached screenshots (poller inject/dispatch),
so this change must reach machines, not only the box.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:16:37 -07:00
CatoandClaude 9c52553581 fix(public): readable homepage quotes, one 'Free' on pricing, a demo panel that belongs (#1032)
Found by crawling every public page at 390px and 1440px in a real browser.

- Homepage 'Notes in, fixes out' quoted a featured note sliced at 140
  chars, measurements and all, ending mid-word ('permanently o…').
  publicFeedbackExcerpt drops bracketed asides and ends on a sentence or
  a word. Pinned by scripts/test/feedback-public-excerpt.ts.
- /pricing printed 'Free' as the plan name and again as its price. The
  price is now a number: CHF 0 / mo.
- /sign-in: the demo was a bare orange stripe above the page, louder than
  the sign-in itself, and the tall page pressed its heading against the
  header. The demo is now a panel in the card's own shape, and the auth
  page has top padding.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-03 17:30:42 -07:00
CatoandClaude Fable 5.1 85ca56c82d feat(loki): the chat the operator already uses — drafts, recordings, work trail, queue (#1022)
* fix(loki): the composer draft survives a discarded tab

On a phone, tapping the paperclip hands control to Android's file picker,
and the browser tab is fair game for the memory killer while it is away
("Zu wenig Speicher für vorherige Operation", 2026-10-03). The open thread
came back — it lives in ?c= — but every word in the composer was React
state and went with the tab.

The draft is now mirrored to localStorage on each change, keyed per
thread (the start page has its own key), and restored once on mount. A
prefill wins over a stale draft. The workspace clears the draft under the
key it was WRITTEN in at send time, because a first message creates the
thread and moves the composer to the new key before chatkit's own
clear-after-send runs — without that, the next /loki visit would offer an
already-sent message back.

Text only: staged images are base64 in memory and would exceed the storage
quota; the picker reopens them in one tap.

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

* feat(loki): attach a voice recording and it is transcribed into the composer

What the screenshots on 2026-10-03 were trying to do: tap the paperclip,
browse to Recordings, hand Loki a voice memo. The paperclip filtered audio
out, and a file that arrived anyway (Android hands over .m4a typeless) was
treated as text and refused as too large.

chatkit b30c843 (v0.3.0) teaches the shared composer that a recording picked
as a file is dictation that happened earlier: it goes to the same Whisper
server leg as the mic, under its own name, and the words land in the box.
This pins it.

The server leg had its own ceiling: 10 MB on the route and Groq's ~25 MB
request cap, against a phone recorder that writes ~1 MB a minute. The route
now takes 120 MB (chatkit's upload cap, the same number), and
lib/transcribe downmixes anything over Groq's cap to 16 kHz mono Opus
(~11 MB an hour; Whisper resamples to that itself) and, if still over,
segments it on twenty-minute cuts and transcribes them in order. Both steps
need ffmpeg, which the box has for the local-Whisper fallback, and only run
past the cap, so the widget's 3 MB clips never reach them. A segment that
fails loses the take rather than leaving a silent twenty minutes that reads
as if nothing was said.

The lockfile entry for chatkit was computed from the codeload tarball
(sha512 of the exact archive, version from its package.json) because pnpm
cannot resolve a second, private git dep from this sandbox; CI's frozen
install is the check.

Test: pure decisions, plus a real ffmpeg downmix of a synthetic 25.6 MB WAV
that reaches the Groq step.

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

* feat(loki): the thread shows what Loki said and ran, live and reopened

The operator reads one rhythm all day in the Claude Code app: a sentence,
a collapsed group of commands with a chevron, a sentence, the answer. Loki
threw that away twice. What the model SAID in a gathering round ("Found it
— checking who owns them") was discarded at the next round's `reset`, so
the operator watched a spinner where they should have read the thinking.
And the tools it ran lived only in the live spinner and a list of names in
provenance: a reopened thread showed an answer that had apparently cost
nothing.

lib/loki/work.ts is the shape, pure and client-safe: one list in turn
order of notes (what Loki said while gathering) and tools (what it ran,
with the outcome). The loop keeps a gathering round's prose as a note and
streams it as one before the reset; tool steps join the same list; the
whole `work` returns with the answer and is persisted in provenance. The
hook applies note and tool events to the identical list live, and
WorkTrail renders segments — notes as prose in the trail's voice,
consecutive tools folded into one collapsible group, the running group
open — for the live turn and the reopened one alike, so nothing changes
between watching a turn and coming back to it.

A note is never the answer: grounding verifies only `text`, Copy copies
only `text`, and the note is styled as the trail, not the bubble.

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

* feat(loki): queue the next message while a turn runs; show the command under each step

Two more places the thread differed from the chat the operator uses all
day, closed.

Queue. A send during a turn was refused — Send went dark until the spinner
stopped, the one place a chat makes the person wait on the machine. Now
the composer takes it (chatkit 5f9d737, `queue`: Send stays live beside
Stop, placeholder "Queue a message…"), the workspace holds it in order and
shows it as a pill with a way to take it back, and sends it through the
same `send` when the turn ends. Held, not dropped, when the turn failed:
the error and its Try again stand in front of it. The draft is cleared
under the key it was typed in, like any send.

Detail. Each tool step in the work trail now carries its arguments as one
short line (`query: "Elena"`) — the command under the step — in the code
face, cut to one line, streamed live and persisted with the rest of the
work. Empty arguments are no line rather than `{}`.

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

* feat(loki): elapsed time on the live turn, Listen under every answer, the rail shows where each thread stopped

Three more details from the chat the operator uses all day.

Elapsed. The live status line now reads "2m 3s · Working on it". Without
the number, forty seconds and four minutes are the same three dots, and
the operator cannot tell patience from a hang.

Listen. A play button under every answer reads it with the browser's own
voices — no upload, no key, offline. Markdown is flattened first
(lib/loki/speech-text.ts: headings, emphasis, citations, URLs and fenced
code are not prose), the voice language is guessed from the text so a
German answer is not read in an English voice, one utterance at a time,
stopped on unmount. Hidden where there is no speechSynthesis rather than
shown dead.

Rail. Each thread shows its last line under the title — a title says what
a thread is about, the last message says where it stopped, which is what
decides whether to reopen it — via one correlated subquery, and the thread
with a turn in flight shows a spinner.

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

* fix(loki): drain the send queue after a turn lands, not from an effect

CI lint on 09f77adc: LokiWorkspace crossed the 510-line cap, and the queue
flush set state synchronously inside an effect watching `sending` — a
cascade React may run twice, and one that could not tell whether the turn
that just ended had succeeded.

The queue is its own hook (use-send-queue: state mirrored in a ref so an
async send reads the current list) and its pills their own component. The
stream's `send` now resolves to whether a turn landed, and the workspace
drains the queue right there, as an event, through the same `send`. A
failed or stopped turn leaves the queue standing behind the error.

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

* refactor(loki): dispatch-outcome polling is its own hook

LokiWorkspace was still seven code lines over the 510 cap after the queue
moved out. The poll that re-reads a thread while its newest turn is a
dispatch is self-contained; it is now hooks/use-dispatch-outcome.ts,
unchanged in behaviour.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-03 00:51:37 -07:00
CatoandClaude Opus 5.5 b9483f3926 refactor(money, goals, habits): a renewed subscription is not overdue; goals fold; habits read at a glance (#1007)
* fix(money): a renewed subscription is not overdue — Money, Upcoming Bills and the Today watch read the next charge

Every active subscription read "Overdue <months ago>" in red: next_due is written once and
only moves on Mark paid, which nobody presses for a card that charges itself. The stored
date now rolls forward by whole periods (lib/subscription-due.ts). Today's imminent-bill
count also stops counting cancelled subscriptions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(goals, habits): milestones and sub-goals fold behind their count; the habit month reads at a glance

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 06:43:51 -07:00
CatoandClaude Fable 5.1 d856ce2b83 feat(studio): every request reaches a person; the chat stops narrating its rules (#1002)
* feat(studio): every request reaches a person; the chat stops narrating its rules

- A studio brief, a partner application and every guest action on one now
  announce themselves like feedback does (push, Telegram, an alert pointing
  at /feedback/studio). #995 persisted them and told nobody — the opposite of
  "a person will reply". Replays stay silent; a notify hiccup never fails the
  ingest.
- Widget chat: a fallback model answered a bitbaum visitor with "Stage used:
  beta. / No URLs written. / Loki first because building leads" under the
  real answer. stripMeta drops such lines before the reply is shown, and the
  prompt says the answer is only what the visitor reads. Tests pin the leak
  and the sentences that must survive.
- A paused widget token cannot transcribe voice either.

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

* docs(telegram): register the studio notifier

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

* refactor(studio): the routes announce; the query layer only says what happened

Announcing from inside createStudioRequest/mutateStudioPortal wrote an alert
row for the e2e's test tenant while the test was deleting it, and the FK
blocked the teardown (CI: studio-portal-e2e). The queries now return what
happened — the created row, or the applied action and its row — and the two
routes fire the notification, the way /api/feedback does.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-01 08:30:26 -07:00
CatoandClaude Opus 5.5 7076e0163f feat(site): the public site says what Loki is today — plain words first, depth on /how-it-works and /compare (#1000)
* feat(site): the public site says what Loki is today, in words a newcomer reads

Homepage rebuilt for a first-time, often non-technical visitor: "Describe it.
Agents build it.", one primary action, three plain steps (describe → built
and put online → say what to change on the site itself) with the phone check
as the safety line, three doors (an idea / a website to change / already
running agents), what is inside (Feedback, Watch, chat, Control — no retired
Beacon tier), and where the work runs, honest that the cloud builder is
invite-only during the beta.

New pages: /how-it-works (the short version, then the machinery under the
hood), /compare (Claude Code, Codex, Cursor, Copilot, Devin, Antigravity, Grok
Build, Muse Code, Lovable, Bolt, Replit, v0, Hermes, OpenClaw, OpenHands, Aider
— each row sourced and dated, no prices, and a section on where the others are
better), /why (mission + principles merged; /mission and /philosophy
redirect). /frontier retired (its producer was removed 2026-09-25) → /thoughts.

Also: nav rebuilt (Start / Learn, bitbaum added), footer names bitbaum, kicker
"Beta" not "Personal Systems", one description everywhere, no "Live" badge,
"pilots, concepts" not "client work" on /fleet, Heidi's blurb in its own
current words, dead Lightning address replaced (getalby 404 → coinos 200),
sitemap derived from the public nav (was 5 of ~25 pages), doubled /commission
title. public-copy-truth.ts pins all of it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(css): drop the ui-frontier-* rules the retired /frontier page used

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(audit): measure /why, /how-it-works, /compare; list the retired marketing pages as redirects

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(copy): assemble the retired name so the guard does not trip its own check

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 03:21:12 -07:00
CatoandClaude Opus 5.5 0c6e05508e fix(ops): a site that hangs is DOWN, not up; raw sql Date comparisons fixed (#996)
loki.orangecat.ch was down ~06:00-07:53 UTC on 2026-10-01 (next-server
alive, no listening socket; Caddy 502 after 20s) and nobody was paged. The
watchdog's curl times out at 15s, prints 000 itself, and the fallback
'|| echo 000' appended another: "000000" is neither "000" nor a number, so
check() kept the site UP. Any app that hangs rather than refuses was invisible.
check() now counts UP only on a proven 2xx/3xx; test-watchdog-check.sh runs the
shipped check() against a fake curl (old code fails timeout/refused/garbage).
The deploy verifiers had the same append (failing closed) and are normalised.

Also from the same journal: closeStaleAgentTurns threw ERR_INVALID_ARG_TYPE
every hour — postgres-js cannot serialise a Date in a raw sql fragment. Same
shape in the calendar overlap, the digest previous window and two more;
all now use lt/gt/gte, and no-raw-sql-comparisons.ts keeps it that way.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 01:23:15 -07:00
Cato b58f514ef6 Add scoped Bitbaum studio portal and keep Loki self-service free (#995)
* feat: start request-scoped Bitbaum portal and studio review

* test: prove scoped portal boundaries and restore studio record join

* fix: support canonical studio origin and readable partner review

* fix: support canonical studio origin and readable partner review
2026-09-30 14:49:38 -07:00
CatoandClaude Opus 5.5 a0e76b31f3 fix(projects): the roadmap is not behind the PIN; one card, one button; Plan leads with the roadmap (#962)
* fix(projects): the roadmap is not behind the PIN; the Now tab has one card and one button

- getProjectDetail loaded a project's goals only when the private-zone PIN
  was unlocked, so the project's own roadmap — the plan an operator most
  needs to see and watch progress against — was hidden from its owner
  (public shares already showed it for anyone without a PIN). Goals are the
  project's plan and always load now. Every "goalsLocked" branch that
  existed only because of the gate is gone: the kickoff tip, the Plan tab's
  unlock line, the dispatch prompt's "roadmap not visible", and
  kickoffBlockedReason.
- Now tab, before anything is built: the interview rendered as its own
  orange-buttoned card directly above Make it happen — two competing
  "start here"s. The questions are now an optional link inside the kickoff
  card (?interview=1 still opens them), the card names its first target
  (the next open milestone), and the Status quo / What happens next cards
  wait until there is work to report.
- The brief is shown once: a substantial description starts as a 3-line
  preview with Edit instead of a second full copy in a textarea; the
  repository option is one line with Change instead of a bordered box.
- Header: the description clamp was a fixed 6rem that sliced the fourth line
  through its letters on phones (ui-clamp-3-lines, 3 × 1.625em with a fade),
  and Share & publish joins the Live / Repository row.
- Tab bar (ui-tabbar): no visible scrollbar, a right-edge fade when tabs
  overflow on phones, and the chosen tab scrolls into view.

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

* fix(projects): Plan leads with the roadmap; the header link row fits a phone

Checked in a real browser at 390px against a local copy of the project:

- Plan: the roadmap was the last block on the tab, under an empty "Next
  action" and a "Completion contract". It is first now, numbered in build
  order (creation order, not progress order), with "1 of 3 done", the next
  milestone tagged, and finished ones collapsed to their title. "Completion
  contract" reads "When a run counts as done"; the tab title is "Plan".
- Header: "Repo" / "Share" labels below sm so Live · Repo · Share sit on one
  row (they took two), and the header's vertical gaps tighten on phones.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 08:38:43 -07:00
CatoandClaude Fable 5.1 14e8667896 feat(projects): builders can dispatch; client is a role; hand a project over (#958)
* feat(widget): Ask Loki for a second opinion; hiding is visible and reversible

Tested the embed in a real browser and found three install/hide defects:
- a `type="module"` tag rendered nothing (document.currentScript is null);
- two copies of the tag rendered two launchers;
- hiding lived only behind a long-press/right-click and was one-way: after a
  reload nothing, not even the host's own Loki.report(), brought it back.

Fixes: find the tag by its attribute when currentScript is null; a boot-in-
flight guard keeps one widget per page; "Hide this button on this site" sits
at the foot of the panel with an Undo toast, and #loki, Loki.show(),
report() and ask() all restore it.

New Ask Loki mode (on by default next to "Request a change"): the person the
site was built for asks whether an element, the page or the whole site should
change and why it is the way it is. The widget builds a text outline in the
visitor's browser (a few same-origin pages for "Whole site") and POSTs it to
/api/widget/advise — same token, origin allowlist, rate limits and owner AI
budget as widget chat. The answer may say "leave it"; each recommended change
has "Request this", which prefills Report so advice becomes ordinary
Implement work. data-fc-modes="report" opts a site out.

Tests: scripts/test/widget-embed-browser.ts (real Chromium; fails on the old
bundle) and scripts/test/widget-advise.ts.

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

* refactor(widget): move panel pieces out of main.ts to meet the function-length ratchet

CI lint failed: the main IIFE grew to 597 lines (max-lines-per-function 510).
The success views, scope chips, mode tabs and hide toast move to
widget/panel-views.ts; the counter/Send sync is one helper. No behaviour
change — widget-embed-browser (31) and widget-host-avoid-browser (17) pass.

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

* feat(projects): builders can dispatch; client is a role; hand a project over

- A collaborator with the builder role ("can run agents") was refused with
  "Project not found" the moment they dispatched, because dispatchStep looked
  the project up BY OWNER. It now asks getProjectAccess who may edit and
  refuses a non-editor with 403 and a sentence; the work still runs in the
  owner's tenant (project-capabilities.ts), so a builder receives the
  capability and never the owner's runner credentials.
- `client` joins PROJECT_ROLE_VALUES: the person the project is FOR. Same
  capabilities as a viewer, a different name, because a roster that cannot
  say who is paying is not a roster. ROLE_LABELS in project-capabilities.ts
  is the one table of role label / help / invitation sentence; the members
  panel and the invite email both read it (editors are shown as "Builder";
  the stored value stays `editor`).
- transferProjectOwnership: the owner hands the project to any member in one
  transaction — the user_projects row moves (the tenant the work runs in),
  the new owner's membership row goes, the old owner keeps a builder's seat.
  POST /api/projects/:id/transfer, and a "Hand over" button per member with
  a confirm that names what changes. The studio's hand-over to a client is
  this button.
- scripts/test/project-capabilities.ts covers the client role and that every
  role has a label and a help line.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 06:17:12 -07:00
CatoandClaude 836ca683bb feat(feedback): a run refused at its last step retries itself once (#955)
A feedback run the runner refused at the end of dispatch — the CLI answered
the prompt with a usage-limit wall, or opened and never started generating —
sat on the row as "Failed" until a person came back to Loki and pressed
Retry. The owner who left the note from a phone on 2026-09-28 (Petvity,
refused 66 seconds after dispatch) never saw the row, and the fix one click
away was never made.

Retry at dispatch time already routes around a spent provider
(implementFeedback → routeAroundSpent); the missing piece was the click.
Now the runner's failing ack, after closing the run as undelivered, hands the
run to feedback/auto-reimplement.ts, which re-implements the feedback item
once through the same path as the button. Loop safety: a stamp on the failed
run and priorRunId on the new one; a run that is itself a retry is never
retried. Never for failures that need a person: dead credentials, a workspace
that does not exist on the builder.

The row reads "Retried automatically — the first attempt failed because …"
while the second run is queued or working. Policy is pure
(auto-reimplement-policy.ts) so work-phase stays database-free.

Tests: scripts/test/feedback-auto-reimplement.ts.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 05:38:47 -07:00
CatoandClaude bd1c6de353 feat(feedback): "Watch the fix" walkthrough; failed runs say why (#951)
What the owner hit on 2026-09-28, testing the loop from a phone:

- A shipped Farmhouse fix showed a green "Live · confirm" chip that was
  itself a link to the site. It read as "watch it live" and landed on the
  homepage with no idea where to look.
- A failed Petvity run printed the bare word "Retry" above a Retry button,
  with the reason hidden.

Now:

- The badge is a status, never a link, and says "Shipped · confirm".
- "Check live" becomes "Watch the fix" (plus "What changed" -> the PR). It
  opens the live page with a signed, 24h tour token in the fragment. The
  widget, which already runs on every fleet site, reads an outline of the
  page and plays a walkthrough from /api/widget/tour: a cursor glides to each
  element, a caption says why, in-page controls are really clicked (anything
  that navigates or submits is only pointed at). The script comes from the
  model on the owner's AI budget, with a word-overlap fallback so it never
  depends on a vendor.
- A step the tour cannot show says so ("Oops — ... flagged, it will be
  investigated") and is filed as an AI-review item on the project, so a fix
  that is not really live comes back into the loop.
- Failed rows get one plain sentence from the run error (quota, repository
  access, timeout, no session, crash...) instead of "Retry".

Verified in headless Chromium at 390px against live farmhouse.orangecat.ch
with this bundle: scroll to the footer link, click it (page returns to top),
a missing step reports back, no horizontal overflow.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 02:01:44 -07:00
CatoandClaude Opus 5.5 63d8f84d33 feat(widget): Ask Loki for a second opinion; hiding is visible and reversible (#950)
* feat(widget): Ask Loki for a second opinion; hiding is visible and reversible

Tested the embed in a real browser and found three install/hide defects:
- a `type="module"` tag rendered nothing (document.currentScript is null);
- two copies of the tag rendered two launchers;
- hiding lived only behind a long-press/right-click and was one-way: after a
  reload nothing, not even the host's own Loki.report(), brought it back.

Fixes: find the tag by its attribute when currentScript is null; a boot-in-
flight guard keeps one widget per page; "Hide this button on this site" sits
at the foot of the panel with an Undo toast, and #loki, Loki.show(),
report() and ask() all restore it.

New Ask Loki mode (on by default next to "Request a change"): the person the
site was built for asks whether an element, the page or the whole site should
change and why it is the way it is. The widget builds a text outline in the
visitor's browser (a few same-origin pages for "Whole site") and POSTs it to
/api/widget/advise — same token, origin allowlist, rate limits and owner AI
budget as widget chat. The answer may say "leave it"; each recommended change
has "Request this", which prefills Report so advice becomes ordinary
Implement work. data-fc-modes="report" opts a site out.

Tests: scripts/test/widget-embed-browser.ts (real Chromium; fails on the old
bundle) and scripts/test/widget-advise.ts.

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

* refactor(widget): move panel pieces out of main.ts to meet the function-length ratchet

CI lint failed: the main IIFE grew to 597 lines (max-lines-per-function 510).
The success views, scope chips, mode tabs and hide toast move to
widget/panel-views.ts; the counter/Send sync is one helper. No behaviour
change — widget-embed-browser (31) and widget-host-avoid-browser (17) pass.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 00:11:04 -07:00
CatoandClaude Opus 5.5 989cd865b8 fix(status): registering a site keeps the owner's next step; Today's running agrees with Control (#924)
- Site registration wrote "Live site: <url>" / "Deployment queued…" into
  next_step, which Control shows as "Suggested next" and every dispatch
  briefs the agent with; Skif's agents were told their next step was a URL.
  Success no longer writes a status there, and clears a message registration
  itself left; failures (the owner must act) still say what to run.
  isRegistrationNextStep lives in the pure site-cd module.
- Today's "N running" counted prompts STARTED in a window, so dead agents
  kept counting ("2 running" beside Control's "1 working", zero open runs).
  It now counts projects with a live agent turn, Control's source.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 10:25:24 -07:00
Cato 20f4cebf65 feat(settings): power Loki with your own model — paste a key, get your best model (#921)
* wip: user_model_keys table + ai-kit 1.17.0

* wip: chat runs on the user's own model

* wip: settings API + screen for the user's own model

* wip: budget refusal offers your own model; tests

* fix: narrow userId for the own-model path; document BYOK_SEAL_SECRET

* fix(demo): the shared demo account may not store a model key

* fix(settings): deep links no longer cause a hydration mismatch
2026-09-25 09:55:40 -07:00
CatoandClaude Opus 5.5 8b48c1221e fix(runs): a reap correction is recorded as reclassified, not a second close (#920)
The reaper closes a stale run as timeout ("closed"); reap-evidence then
finds a PR it pushed and upgrades it to partial, and emitted a SECOND
"closed". Skif's history read "closed, closed" on two runs today. The
correction is now its own run_event kind, reclassified (text column, no
migration; nothing decides closedness from the latest kind).

Also: the partial note said "ran out of time", which is false for a run a
builder restart ended (#917 reaches the same copy). Now "ended before it
could report back".

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 09:32:16 -07:00
CatoandClaude Opus 5.5 10b1f3a082 fix(orchestration): a runner restart closes the runs its sessions were serving (#917)
The runner now reports bootedAt (process start, captured once) on every
runtime-state post. Runs on that runner's channel whose agent session was
live before the boot (claimed/launched/submitted/generating/progress event
older than bootedAt), with nothing heard since and no un-acked command, are
closed at once with the restart named, instead of reading 'waiting' until
the hourly reaper. Only-dispatched runs are left for the new runner.

Verdict matches the reaper's (partial on handoff, else timeout) so the same
repo-evidence correction upgrades runs that had already pushed work.
Fleet Runner 0.8.34.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 09:09:03 -07:00
CatoandClaude Opus 5.5 14cd5ae93c fix(terminal): a parallel run's tab reads as its project, and its rail finds its run (#911)
Since #900 an extra concurrent run gets the tab alias <project>~<runId8>.
The terminal context matched tabs to projects by raw name, so the alias
matched nothing: the strip, page header and composer showed
"skif~d0a14b69", and the Loki rail said "No run on skif~d0a14b69 yet"
beside an agent nine minutes into its work (2026-09-25).

- terminal context resolves tabs via baseProjectKey (the run-tab SSOT)
- getLatestRunForProjectKey understands a lane tab: base project AND the
  run its suffix names (runLaneOfTab), so parallel lanes don't swap runs;
  a malformed suffix is rejected, never a LIKE wildcard
- the strip labels a lane "Skif · parallel", with the alias in the tooltip

Tests: run-tab (lane parse, malformed suffixes, context uses the SSOT).

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 05:12:11 -07:00
Cato 05e9430646 feat(dispatch): Implement doesn't walk into an agent Loki just watched run out of quota (#909)
* wip: Implement routes around an agent Loki has seen run out

* test: routeAroundSpent, proved by mutation
2026-09-25 04:35:54 -07:00
Cato 1abc90de02 feat(dispatch): Implement starts in its own lane instead of waiting — and three bugs the old lane code carried (#900)
* wip: parallel lanes for Implement

* style: format
2026-09-25 02:13:47 -07:00
Cato 064cad655d fix(runs): one clock for the lane and the reaper — no second prompt into a live session (#896)
* wip: one clock for the lane and the reaper

* wip: database test for the lane and the reaper, wired into CI
2026-09-25 00:09:11 -07:00
CatoandClaude Opus 5.5 bec2a9d67c perf(runs): fetch the latest run per path, not every run ever made (#873)
getLatestRunsByProjectPaths selected every run for every path and kept
the first per path in JS. Measured on production today for the busiest
user: 699 rows at ~1.26 KB each (~880 KB, mostly `summary` JSON) fetched
and parsed to keep 32. Control paid that on every poll; since #863 the
/today front door pays it on every load, and it grows with every run.

Postgres time was ~2 ms either way, so the cost was transfer and parsing.
DISTINCT ON (project_path) returns only the 32 rows the caller keeps.
The repo already uses selectDistinctOn on this table (register/load-map).

Equivalence checked against production data before changing it: the old
and new selection pick the same run for all 36 (user, path) pairs, with
0 mismatches; there are 0 ties on the latest started_at and 0 NULL
started_at values, so neither tie-breaking nor NULL ordering can differ.
The drizzle-generated SQL (via .toSQL()) was run read-only on prod and
returned 32 rows.

Gate: latest-run-is-one-row-per-path.ts pins both halves. The ORDER BY
must lead with the DISTINCT ON column or Postgres rejects the query at
runtime, which tsc cannot see and both callers would swallow into an
empty map, so run health would silently stop reporting. Proven by
mutation both ways.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 02:34:52 -07:00
CatoandClaude Opus 5.5 ef96be9b91 feat(projects): invite anyone into a project by email, account or not (#872)
Inviting a collaborator required them to already have a Loki account.
The members route answered "No Loki account uses that email. Ask them to
register first." — a dead end with no way to ask. The only other invite
path creates a LOCAL-PASSWORD account and adds it to the inviter's whole
org: broader than one project, and a second identity path beside
OrangeCat, which fleet STACK.md says our own products must not grow.

Now any email works:

- Has an account: added at once, as before.
- No account: a one-time invite is created, emailed when mail is
  configured, and ALWAYS returned as a link to copy — an email that was
  sent is not an email that was received. They open it, sign in with
  OrangeCat (creating that account on the way), and join exactly this
  project with exactly the role chosen. No Loki password anywhere.

The link is bound to the invited email. A token is a bearer secret that
gets forwarded; on its own it would let whoever holds the link in. The
wrong account is told which address it was for, masked (ge•••@gmail.com)
because the link may be in the wrong hands.

Only a sha-256 of the token is stored, so a leaked backup cannot be
replayed as working links. Acceptance spends the invite and grants the
membership in one transaction guarded on accepted_at/revoked_at IS NULL,
so a double click or two tabs grants once. Re-inviting the same email
revokes the old link rather than leaving two live ones.

"emailed" is only reported when mail is configured AND the send
succeeded: sendEmail returns quietly when mail is off, so trusting the
call alone would have claimed an email nobody sent.

The panel moved from a collapsed "Editors" disclosure inside the
Feedback tab to the top of the project's Settings tab — where every other
product keeps "people with access", and where George looked for it. It
now offers Editor or Viewer, lists pending invites, and lets the owner
withdraw one. Editors do not see pending invitees' emails.

The accept API lives under /api/invitations/project/ so it inherits the
existing public-route exclusion instead of widening the proxy allow-list.

Migration 0080 is hand-written, like 0073-0079: drizzle/meta's snapshot
stops at 0072, so `drizzle-kit generate` diffs against a stale picture —
it believes beacon_sessions still exists and calendar_busy does not, and
would have emitted a DROP and a duplicate CREATE alongside this table.

Tests: 14 checks on the acceptance rule, proved by mutation — removing
the email binding turns the suite red. tsc clean, lint 0 errors,
check:design ok, format ok, test:unit 260/260, test:home 130/130.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 02:34:14 -07:00
CatoandClaude Opus 5 ce7ecd3e91 chore(account): deleting an account cannot silently stop working (#858)
`deleteUserAccount` hand-clears every table whose user FK is not
onDelete:"cascade", because the users row cannot go while such a row
points at it. That was seventeen `tx.delete(...)` calls in a fixed order
with a comment asking the next person to remember, and nothing checked it.

So adding a table with a plain `references(() => users.id)` broke account
deletion silently. tsc is happy — the new table is simply not mentioned.
Every test is happy — nothing exercised the path, in either direction:
`deleteUserAccount` had exactly two references in the repo, its route and
itself. The failure surfaces only when a real person opens Settings →
Danger zone, types their email to confirm, and gets a 500 on the one
action they cannot retry their way out of.

Measured against production first: seventeen tables need clearing and all
seventeen were already handled, so this goes in green. It is here to keep
that true, not to fix a present break. (The FK violation seen earlier in
this session came from a raw SQL DELETE that bypassed this function —
the app's own path was already correct.)

- the list moves to src/db/queries/user-purge-tables.ts and becomes data
  the function iterates, so the code and the declaration cannot disagree
- it lives apart from users.ts because users.ts imports `@/db`, which
  opens a client at module load; the gate has to run in CI, where there
  is no database (same reasoning as the deferred import in lib/email.ts)
- scripts/test/account-deletion-covers-every-table.ts derives the truth
  from drizzle's own table metadata, never by parsing source — a regex
  over `.references(` would be a second, weaker description of the same
  fact. It checks BOTH directions, so an entry left behind after a table
  gains onDelete:"cascade" is reported too, rather than sitting there as
  a no-op that reads like protection.

Proven by mutation, three ways: drop a table from the list → names
goals.user_id as blocking; give a listed table onDelete:"cascade" → names
it as a stale entry; add a new table with a plain user FK → names
gate_probe.user_id. scripts/test-unit.ts globs the directory, so the gate
is wired into `verify` by existing, and it ran green there.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 12:11:11 -07:00
CatoandClaude Opus 5 cc85390123 feat(projects): a flag can now be raised, edited and cleared (#847)
The third of the three "hard-coded demo" findings, and the worst of them.

A flag — security_vulnerability, broken_features, deployment_issue — is the
loudest signal in the product: it sorts a project to the top of /projects,
colours its row, and costs a health point. The complete set of ways to RAISE
one was: an agent writing the attr through the API.

There was NO UI. And the one surface that lets a person type an arbitrary attr,
"Additional context", excludes exactly these three keys on the grounds that "a
dedicated UI owns them" — a dedicated UI that did not exist. So the exclusion
only meant there was nowhere at all.

The result is what George saw: a red badge on evig, no way to tell what put it
there, no way to raise the same flag on a project that deserved one, and a
clear path buried inside a health disclosure. He called it "magic, or some
other non-scalable, stupid solution". It was the second one — three free-text
fields with no author and no door.

<ProjectFlags> is the door. All three signals always listed (a control that
appears only once the thing has happened cannot answer "how do I flag this?"),
each showing its note, when it was written and by what, with Raise / Edit /
Clear. On the Context tab, beside the other things a person writes about a
project.

NOTHING HERE DETECTS ANYTHING, and the copy says so in the first sentence: "A
flag is a note someone wrote — an agent or you. Nothing here scans the
project." Dressing three text fields up as monitoring would be the same lie in
better clothes. The panel also states the COST up front — top of the list, one
health point — so that is known before writing one rather than discovered
after.

getProjectDetail now loads attribute provenance (same single query), so the
project page can say "noted 6mo ago by loki-ui" instead of showing an
anonymous sentence.

Guarded by scripts/test/a-flag-can-be-raised-and-cleared.ts (9 checks), which
pins the HONESTY rule as hard as the mechanics: the copy must never contain
"detected", "monitoring" or "scans the project for", and must say what a flag
costs.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 09:19:53 -07:00
CatoandClaude Opus 5 0464358605 fix(orangecat): the wall went silent, and every link on it pointed at a login (#839)
* fix(orangecat): the wall went silent, and every link on it pointed at a login

Three failures on one seam, each invisible from inside Loki because the
symptom is on somebody else's page.

THE WALL STOPPED. OrangeCat rotated this account's refresh token at
2026-09-17 07:42:44 and issued a replacement that is still valid and was
never used; Loki kept presenting the one that rotation REVOKED at that
instant. Every refresh since answered 400, getOrangeCatLink returned null,
and every promote was skipped as "feature unavailable" — across every
project, for four days. The last entry to reach any OrangeCat wall was
posted eight minutes before that access token expired. The only trace was
66 console.warn lines on the box.

Verified by hashing the stored token and finding its row in OrangeCat's
oauth_refresh_tokens: revoked_at = 2026-09-17 07:42:44.

Three rules follow, none of them a repair: one refresh at a time per
account (the backfill cron fires up to 50 promotes at once, so a burst was
guaranteed to look like a broken link); a spent refresh token is never
written back (`?? account.refresh_token` reads as defensive and stores a
credential that can only ever fail); and a dead link raises an alert,
because re-linking needs a human click and nobody clicks what nobody sees.

EVERY LINK POINTED AT A LOGIN. Wall entries carried a hardcoded
`${LOKI_PUBLIC_ORIGIN}/projects` — the private dashboard. A stranger
following "via Loki" from Heidi's OrangeCat page got a sign-in form; the
owner got all 36 projects instead of the one the entry was about. Twelve
such links on that page alone. The right page has existed the whole time:
/fleet/<slug>, now derived exactly as the register derives it.

THAT PAGE WAS UNREADABLE ON A PHONE. Measured at 390px: 737px of roadmap
content in a 390px column, clipped by .ui-public-surface's own
overflow-x:hidden — 47% of every milestone line unreachable, no scrollbar,
no ellipsis. Cause: unbreakable GitHub URLs in prose. Fixed on the
ui-public-* prose tokens in globals.css, so it holds for every public page.
Also on that page: three of six "changelog" entries were internal dispatch
bookkeeping (two announcing a FAILED dispatch, stored truncated mid-word),
a `Source: <url>` provenance pointer rendered as an untickable milestone,
"0% recorded progress" under every item, and a raw ISO timestamp.

NO GATE COULD HAVE CAUGHT IT. audit-covers-every-page skipped every route
containing "[", so /fleet/[slug] — the template behind all 36 public
profiles — had never been measured at any width. Dynamic routes now take
the same decision as static ones: a concrete sample (/fleet/heidi,
/u/cato, one essay) or a line in NOT_MEASURED saying what it would take.
The overflow detector could not have seen it either — it reads
documentElement.scrollWidth, which the clip holds at the viewport width —
so there is a new one asking the reader's question: can I get to the rest
of this sentence? A listed route that 404s now fails, because a rotted
sample looks exactly like a covered route.

Two gates lied and are fixed with it: the audit's list parser ended an
array at the first "]" in a comment, and alert-registry read
`grant_type: "refresh_token"` as an unregistered alert type.

AND THE FEED IS NOW A CHOICE. Publishing did two things under one press:
it created the public page and enrolled the project in a live feed of
everything its agents did, with no switch — "stop telling everyone what my
agents are doing" cost you the funding page. user_projects.orangecat_autopost
separates them, three-state like auto_ship (null = nobody has chosen, and
an unanswered question is not consent). Reversible either way, without
touching the page. Already-published projects are backfilled to true:
introducing consent must not silently stop a feed someone relies on.

Left on, it is the strongest thing a public project page can carry —
dated evidence of work, which is the half of a transparency claim that
better copy cannot manufacture.

/fleet/[slug] also now reads CONSENT rather than ownership (it resolved any
slug in the owner's map, which the catalogue beside it has never done), and
a slug with no public profile gets an invitation instead of a dead end.

verify: tsc, lint (0 errors, 2 pre-existing warnings), test:unit 231/231.
The page itself is measured against prod after deploy — it cannot be
measured before.

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

* fix(smoke): the pre-push gate blocked a push over another app's dev server

`/api/health` answering with a `"commit"` field was the whole identity test,
and every app in the fleet serves that route from the same template. On
2026-09-22 a Heidi dev server held :3000 first; Loki's 48-route auth smoke ran
against it, reported 23 routes returning 404, and failed the push — a verdict
about somebody else's app, delivered as a verdict about this one.

A name cannot be mistaken for another name: health now says which app answered,
and the hook asks for "loki" instead of for a shape. Additive to the payload,
so the deploy assertion, the uptime sweep and check-deploy-ref are unaffected.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 07:04:07 -07:00
CatoandClaude Opus 5 cd67d92439 feat(projects): flags say how old they are, and an expiry finally means something (#833)
"Security risk", "4 broken features" and "Deploy issue" are the TEXT of project
attributes someone — a person or an agent — typed. They reached the list
undated and unattributed, so a note written this morning and one typed in June
looked identical, and both hoisted their project above everything else equally.

THE DATA WAS NEVER MISSING. fetchAttributesByEntityIds does `select()` — it
pulls updatedAt, source and valid_until on every row — and then dropped all
three in its grouping loop, keeping only key → value. Showing them costs no
extra query; the meta variant returns the value too, so getProjects makes the
same single call it always did.

Badges now read "Security risk · 23d", with the exact date and what wrote it in
the tooltip alongside the note itself. Terse where it is scanned, spelled out
where it is read.

VALID_UNTIL IS THE SHARPER ONE. That column has existed on the attributes table
the whole time and NOTHING read it — an author writing "this expires on the
14th" was writing into a field with no consumer. It is honoured now.

That is deliberately NOT auto-decay, which stays George's call: a flag with no
valid_until still stands forever, however old. Inventing a deadline for someone
else's security note would be worse than showing a stale one. And a malformed
valid_until never clears a flag — a typo must not silently resolve a security
issue.

One predicate, three surfaces: the badge, the attention sort and the "Site
issues" chip all call signalHasExpired. It lives in lib/, not beside the badge,
because two of those callers are not React — and because a flag hidden on the
row while still counted by the sort would hoist a project to the top of the
page with nothing on it explaining why.

Guarded by scripts/test/flags-carry-their-age.ts (8 checks), which pins the
policy line as hard as the behaviour: "no expiry means it stands forever" is a
test, so a future change cannot quietly introduce decay. Mutation-tested:
ignoring valid_until fails 2.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 03:27:33 -07:00
CatoandClaude Opus 5 689358197a feat(projects): fields the operator adds now reach the agent (#826)
AddAttrInline has always let anyone type any key/value onto a project, and
humanizeAttrKey renders it back under "Additional context" — inside an editor
headed **Agent context**. It reached no agent. renderProjectDossierForAgent
built its profile from hardcoded property reads, so a key nobody had
anticipated was stored, shown back to the human, and dropped silently on the
way to the model.

That is the worst shape of defect: the feature looks like it works. Someone
fills in "Suppliers" or "SWOT", sees it on the page, and reasonably concludes
their agents know about it.

Only UNREGISTERED keys qualify. A registered field already declares whether it
reaches agents, and two of those answers are deliberately "no" — the market
lens is for the human operator (it costs tokens on every dispatch), and
UI-owned attrs like `business_plan` have their own surface. Consulting the
registry is what stops this path from quietly undoing those decisions; the
tests exist mostly to keep it that way.

DEVIATION, stated plainly: the plan said custom fields would default to
human-only with a per-field "send to agents" toggle. They default to ON here,
with no toggle. A toggle needs new per-field storage and a migration, and adds
a step to reach a result the user already asked for by typing into a box
labelled Agent context. The boundary that actually carries risk — publishing —
is untouched and remains an explicit four-key allowlist. If the default turns
out wrong it is one predicate to change.

Capped at 12 fields per project so one profile cannot crowd out goals, runtime
and the last handoff. Values are never clipped: anything past the cap is
listed BY NAME, which is honest about what was withheld and lets the agent ask
for it.

Lives in lib/project-custom-context.ts rather than beside the dossier
renderer, which opens a database connection at import time — that is what had
put the text of every dispatch beyond the env-independent unit suite.

Mutation-tested: dropping the registry check trips three gates, including the
one that would have sent a 5,000-character business plan into every prompt.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 00:17:21 -07:00
CatoandClaude Opus 5 7d892ec91f refactor(projects): one registry describes a project field, not five lists (#825)
Five separate lists decided what a project field is and does: the context
editor's groups, the agent dossier's Profile block, the fallback
DRIVING_FIELDS, the AI profile-apply keys, and the public allowlist. Adding
one field meant editing five places, and nothing checked they agreed — so
they had already drifted:

  - the dossier carried `status`; DRIVING_FIELDS did not
  - the dossier said "Next owner step"; DRIVING_FIELDS said
    "Next step (owner's highest-priority action right now)"
  - the editor said "People served"; both agent paths said "Customers"

PROJECT_FIELDS in config/project-attrs.ts now describes each field once, and
the lists derive from it. The divergences above are carried as explicit
`inAgentDossier` / `inDrivingFields` flags rather than quietly reconciled:
changing what agents read is a product decision, not a refactor.

renderProjectDossierForAgent built its profile from hardcoded property reads
(`attrs.mission`, …), which is why a field added through the UI — AddAttrInline
has always allowed any key — reached no agent at all. It now iterates the
registry. Only the two rows the registry does not own stay bespoke: Health is
computed, and Operator notes live on user_projects.

One deliberate behaviour change: "Next step" moves later in the FALLBACK
dispatch prompt, because one registry cannot hold two orders and the dossier —
the path nearly every dispatch takes — is the one preserved exactly. The two
paths agreeing is the point of the change.

DRIVING_FIELDS moves to config and is re-exported under its old name: it is
pure config, and living in a queries module put it behind a database
connection, so the text every fallback prompt carries had no test.

The public allowlist stays an explicit four rather than becoming a per-field
boolean. Publishing is a security boundary, and four lines a reviewer can read
beat a flag scattered across 33 entries.

scripts/test/one-registry-describes-a-field.ts pins every derived value,
because they are prompt text — and fails if a PROJECT_ATTR key is added
without being registered.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 23:21:32 -07:00
CatoandClaude Opus 5 d71ddd446e fix(runs): the fleet stopped executing and nothing said so (#820)
`closeRunUndelivered` stamped `error`, emitted a run event and called
`notifyRunClosed` — but never `advanceEscalation`. It was the ONLY
failing-close path feeding the ladder nothing: the funnel
(updateOrchestrationRun) advances, the reaper advances, this did not. A
dispatch that died before an agent ever saw it therefore could not build
a streak no matter how often it repeated, so the `human` rung — the one
that raises the alert — was unreachable from this path.

Notification did not cover the gap and could not: formatRunCloseMessage
self-gates on payload.notifyOnClose, which only human-initiated
dispatches carry ("autopilot churn stays quiet"). For an autopilot or
cron dispatch the notify call returns null, so the close said nothing to
anyone at all.

Measured on prod today: six dispatches failed across FOUR projects
(loki, kivvi, solon, reparaturbonus-zh) within twelve hours on an
exhausted Claude quota — every one through this path — while the newest
row in `alerts` was six days old.

Derived, not assumed, via the same ladderEffectForClose predicate the
other two call sites use, so there is one rule for what a close does to a
ladder. The ladder's own `lastOutcome` keeps it honest downstream: it
already distinguishes a streak built from undelivered dispatches from one
built from an agent's failing work.

Attaches the missing signal only — it does not change the outcome, the
notification policy, or what a streak means.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 04:02:57 -07:00
CatoandClaude Opus 5 5386267149 fix(public): "46 agents running" was two agents and forty-four stale flags (#819)
/investors and the homepage hero read a raw boolean that nothing expires.
Measured against prod on 2026-09-20:

  rows flagged agent_running = true ....... 46
  updated in the last 30 minutes .......... 2
  oldest flagged row last touched ......... 2026-08-13 — 910 hours earlier

So the page showed "46 agents running" while Control, on the same database,
showed "0 working". Both numbers came from the same fleet; only one of them
was bounded.

It sits directly under this sentence, which is why it matters more than an
off-by-something: "the homepage hero and this page render the same live
snapshot of that fleet — real data, never fabricated numbers." The numbers
were not fabricated. They were stale, offered to an investor as proof of
activity. And this file's own header promises "honest by construction —
isLive is true only when an agent is really running, so the hero never claims
LIVE falsely". isLive is `totals.running > 0`, so it had been true for weeks
on the strength of flags nobody cleared.

The app already had the answer. Control bounds the same question by
OPEN_TURN_TTL_MS — thirty minutes, a constant whose comment records that
without it "a dead Codex tab showed working 61h", and which is deliberately
matched to STALE_PROMPT_S so two definitions cannot disagree on screen. The
public query simply never applied it. It does now, through one predicate used
by BOTH the headline count and the per-project dots: bounding only the count
would have left a project's dot lit for an agent that died in August.

Reused rather than re-picked on purpose. A second freshness number would
eventually disagree with Control's, and then a reader is right to trust
neither.

The other two figures were already honest and are untouched: "projects" counts
active rows, and "runs this week" was time-bounded from the start.

Proved by mutation: restoring the unbounded check fails 2 of the 6 cases.

verify: format:check, tsc, lint (0 errors, 2 pre-existing warnings),
check:design (11), check:desktop, test:home 130/130. test:unit 227/229 —
activity-time-zone-stable and telegram-allowlist need a live local server and
fail identically on pristine origin/main.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 15:08:45 -07:00
CatoandClaude Opus 5 1f7966ef4a fix(runs): a reaped "partial" recorded a verdict with nothing behind it (#816)
The reaper stamps `partial` on exactly one basis — `wroteAfterStart`, an
EXISTS over project_states proving the agent DID save a handoff inside the
run window. It then writes payload.note ("the agent had already saved a
handoff…") and stops. The handoff it just proved exists is never copied
onto the run, so `summary` stays NULL.

reapStaleRuns already names that state as the one to avoid — "reaped with
a partial verdict and a NULL summary, recording a failure whose reason
nobody could read". Aligning the freshness floor removed one CAUSE of it;
nothing ever filled the summary, so the ordinary path still reached it.

Measured on prod today: 8 of the last 12 closed runs on `loki` were reaped
partials with an entirely empty summary, every ~6 hours for three days.
That silence compounds, because the run summary is what briefs the NEXT
run — `done`/`next` are what the dossier re-serves under "Recent run
outcomes", so each dispatch was briefed with less than the previous run
actually knew.

A post-reap pass gives the handoff back, alongside the evidence corrector
it mirrors. Deliberately narrow: it attaches evidence, it does not
re-judge. Only rows whose summary is still NULL (never clobbers another
close path, re-running is a no-op); the run keeps its `partial` outcome,
because re-deriving the verdict would move the escalation ladders and the
failure brake that read it; and the same freshness floor the reaper used
is re-applied, so a handoff belonging to a different run can never be
pinned onto this one in the gap between the sweep and the pass.

The mapper is pure and lives beside the other two "summary from X"
builders, so it is testable with no database.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 13:13:57 -07:00
CatoandClaude Opus 5 af98b036a5 fix(ui): numbers that did not add up, and a gate with no way out (#811)
Two things found by reading the screens as a user rather than as their author.

SEVEN REPORTS WITH NO NAME

  The Feedback header read "68 reports · 29 still open" beside "32 shipped".
  29 + 32 is 61. A reader who checks the arithmetic concludes one of the three
  numbers is wrong; every one of them was right.

  The remainder is `archived` — filed away rather than fixed — a state no card
  admitted existed. Confirmed against the database: resolved 32, dispatched 25,
  archived 7, new 4 = 68, where "open" is new + dispatched. The metrics query
  never counted archived rows, so the page could not have named them.

  It does now, and `reportsSubLine` is pure and exported so the arithmetic is
  pinned without rendering — three numbers that fail to reconcile look exactly
  like three numbers that do. Mutation: dropping the archived clause fails 3 of
  the 5 cases.

A PIN SCREEN THAT BLOCKED ABSOLUTELY

  AGENTS.md and CLAUDE.md now state the rule: "A gate records; it never blocks.
  Anything that pauses a person shows the way forward on the same screen." The
  private-zone gate did the opposite.

  Forget the PIN and there is no route anywhere: changing it requires the
  current PIN, removing it requires the current PIN — both deliberately, so a
  hijacked session cannot swap it — and no reset flow exists. The screen
  offered an input, "Incorrect PIN", and nothing else, while the zone behind it
  holds 2,750 contacts and a 2,797-entity knowledge graph.

  The fix is NOT to weaken the gate. It is to stop implying a door that is not
  there: both surfaces — the /unlock page and the inline PrivatePinGate — now
  state the consequence and link to /support, whose address is on the apex
  domain and has a live MX (checked).

Not changed: the PIN recovery policy itself. Adding a reset path is a security
decision with a real trade-off, and it is George's.

verify: format:check, tsc, lint (0 errors, 2 pre-existing warnings),
check:design (11), check:desktop, test:home 130/130. test:unit 221/223 —
activity-time-zone-stable and telegram-allowlist need a live local server and
fail identically on pristine origin/main; this diff touches neither.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 10:41:20 -07:00
CatoandClaude Opus 5 4735397aa0 fix(feedback): the reporter page was the counter-example to its own top report (#806)
* fix(feedback): the reporter page was the counter-example to its own top report

/my-feedback rendered a report asking for a three-line clamp at full eight
lines, under a chip reading "Being implemented". The clamp WAS implemented —
FeedbackReportText, #783, written in answer to that very report — but only in
FeedbackItemRow, the operator's inbox. The reporter page kept its own row
markup, so the fix never reached the person who asked for it.

The missing import is the symptom. The defect is that a third feedback surface
existed with its own renderer and nobody knew, so this fixes the page and
closes the gap that let it drift.

The page now:

- renders bodies through the shared FeedbackReportText, so one dictated report
  stops owning the list;
- derives status instead of dictionary-mapping the DB word. `dispatched` meant
  queued, running, crashed days ago, or shipped-but-unconfirmed, and all four
  read "Being implemented"; work-phase.ts opens by saying DB status cannot
  answer that question, and this page was the last one still asking it;
- gives the reporter a next action — "Check the live page" once a fix is
  actually deployed, never while its pull request is open;
- colours the chip. Every state used .ui-badge, the same neutral pill as a
  duplicate count, so the one thing a reporter comes here to learn carried the
  weight of a footnote;
- formats dates in the READER's locale and time zone. toLocaleString() ran in
  a server component, so a Swiss reporter was shown a US date on the box's
  clock. The operator row never had this; it is already a client component;
- labels the project name, which sat unlabelled exactly where a person's name
  would and read as one.

What a reporter may see is decided in one place. reporter-view.ts writes every
reporter-facing sentence rather than forwarding FeedbackWorkView's, because
that view is written for whoever owns the machine: `detail` carries builder
asks, `diagnostic` the agent's raw error, `stepSummary` run-hop narration, plus
run and command ids. A pass-through would have been shorter and would have put
an engineer's note on a stranger's screen. attachReporterView is likewise a
narrow read, never attachFeedbackWork — that one refreshes GitHub ledgers,
sends the owner's notifications and scopes to the owner, none of which belongs
on a reporter's page load.

Reporter run lookup is deliberately not owner-scoped, and authorization comes
from the report instead: the caller has proved reporter_user_id, and passes
only the dispatched_run_id values off those rows.

Guards, so the next clamp-class fix cannot land on one surface only:

- feedback-reporter-view.ts pins that the page renders through the shared
  clamp, formats no date server-side, maps every phase, and leaks no
  operator-only string for any phase;
- CLAUDE.md names /my-feedback in Views — it listed /feedback and ControlInbox
  and not this one;
- /feedback and /my-feedback join audit:responsive, which would have caught an
  eight-line row at 390px.

Dropped the subtitle's "Tracking a report never grants permission to edit its
project." It answered a question no reporter asked and spent the line that now
says what the page is for; the boundary it described is enforced in code and
pinned by tests, not by that sentence.

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

* fix(feedback): read the reader's clock without setState in an effect

`react-hooks/set-state-in-effect` rejected the first cut, and correctly:
a useEffect that immediately setStates is a cascading render, and the rule
does not care that the second render is the point.

The constraint that produced it is real, though. Only the browser knows the
reader's time zone, so the localized string cannot exist during SSR — and
server and client must still emit identical markup or React throws the tree
away. useSyncExternalStore with a server snapshot answers both, and is the
shape this repo already reaches for: BrandVersion says "client-only, with a
null server snapshot so SSR/hydration match (no setState-in-effect)" in as
many words, and NotificationsPill uses the same mounted gate after a React
#418 on every authenticated page.

Also drops the now-redundant `title`: after hydration the visible text IS
the full localized string, and `dateTime` carries the exact instant for
machines at every stage.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-20 09:54:50 -07:00
CatoandClaude Opus 5 93a6e3e1f2 refactor(beacon): delete the popup, and gate the class of bug that hid it (#804)
The beacon popup was retired on 2026-06-11 (2391c6f7). That commit deleted the
page and five routes and left everything behind them standing, so for three
months the Settings page offered a "Popup mode" control that changed nothing,
and two live code paths called endpoints that returned 404 into a swallowed
catch.

Production had already said so plainly: beacon_sessions held ONE row, created
2026-06-08 23:39 UTC — three days BEFORE the retirement — and nothing in the
104 days since. All three of its indexes had idx_scan = 0.

DELETED
  scripts/beacon.py, scripts/_beacon_config.py — the launcher. Nothing invoked
    it; the Stop hook that once did has been `exit 0` since the same migration.
  POST /api/beacon — its only caller was that script.
  GET  /api/beacon/recent — zero references in the entire tracked tree.
  beacon_sessions (table, schema, queries) + the Fleet Doctor check that
    demanded it exist and the telemetry row that watched it.
  beacon_settings.popup_mode — stored, echoed, branched on by nothing. Its prod
    DEFAULT was still 'both', a PyQt-era value the app's own zod enum rejects.
  beacon_settings.min_idle_seconds — dropped from the query shape in September
    with the note that "the knob described behaviour that did not exist".
  POPUP_MODES / DEFAULT_POPUP_MODE and the Settings subgroup they fed.
  LEGACY_AUTO_INJECT_MODE_VALUES — its docstring claimed it served a migration
    UPDATE and tolerant parsing; no migration contains that UPDATE and
    normalizeAutoInjectMode never reads the array.
  The /beacon/ disallow in robots.ts, for a page tree that no longer exists.
  recentSwitchAgentStats — orphaned by the route deletion, caught by
    dead-exports-ratchet, which is exactly its job.

FIXED
  use-auto-continue.ts POSTed /api/beacon/cancel — deleted in 2391c6f7 — on
  every toggle-off, with `.catch(() => undefined)` hiding the 404.

KEPT, because they are live features wearing a dead feature's name:
  /api/beacon/queue/[tab] (the prompt queue, 4 call sites incl. desktop
  dispatch), /api/beacon-settings (autopilot + countdown), and
  /api/beacon/transcribe (voice input). Renaming those paths would break every
  shipped Fleet Runner, so the rename needs a deprecation window, not this PR.

Copy corrected along the way: the countdown said "how long the beacon waits"
when it drives the Control ready-banner; voice settings named
~/.cache/whisper/ when faster-whisper caches under ~/.cache/huggingface/, on
the SERVER, not the user's machine; a transcribe error pointed at
"Settings → Beacon", a tab that does not exist.

THE GATE — scripts/test/internal-paths-resolve.ts

Every internal path any file fetches or links must resolve to a route that
exists. Nothing checked this direction: dead-exports asks whether a symbol is
REFERENCED (these were — by each other), tsc cannot type a string, and smoke
could not see it because auth answers 401 before routing.

It resolves through [dynamic] and [...catch-all] segments, treats a template
hole as "any child", and accepts a path that is a prefix of a served route so
matcher lists (DEMO_DENIED_PREFIXES, robots, middleware) do not trip it. 508
references across 6 roots, 0 broken.

Proven by mutation, both directions: reintroduce the /api/beacon/cancel call
and it exits 1; delete src/app/api/orgs and it names all four callers. My first
attempt at that mutation silently failed to apply, and the gate "passed" — the
assert on the mutation itself is what caught it.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 09:48:52 -07:00
CatoandClaude Opus 5 451ac5ded7 fix(dispatch): a deadline four months gone is not a near-term commitment (#800)
Every dispatch this fleet sends opens with the operator's goals and
deadlines, under the instruction "align your priorities" — and on
2026-09-20 the two it listed were:

  The operator's near-term commitments/deadlines (be mindful of these):
  - Get a $50 signup bonus when you spend $100 within 30 days of getting
    a new Coinbase One Card — due 2026-05-03
  - You can unpause your project from the dashboard within 90 days. After
    this period, the project cannot be restore — due 2026-07-03

Four and a half months and eleven weeks gone, handed to every agent on
every project as something to aim at. Filed as #584 on 2026-09-10 after
the same block reached Heidi; it has shipped in every dispatch since,
including the one that produced this commit.

Two separate defects, and the interesting one is not the label.

listUpcomingCommitments takes everything active due before now+14d with
no floor, which is deliberate and documented — "overdue included, those
are the most urgent" — but it then ordered by due_date ASC and capped at
8. Ascending order over a set that reaches backwards means the OLDEST
rows sort first and take the whole cap, so the least recoverable items
crowd out the ones still worth doing. "Soonest first" and "most urgent
first" read as the same sentence and are opposites here. Distance from
today is what urgent actually means, so that is what the ORDER BY says
now; verified against the live table, where it flips the two rows into
the right order.

The label is the half that changes today's prompt. Overdue rows still
belong in this block — a commitment someone missed is exactly what an
agent should know — they just have to arrive marked as missed:

  - ... — was due 2026-07-03 (OVERDUE)
  - Reduce Monthly Burn (40%) — target 2026-06-30 (PAST, not met)

and the heading no longer calls the list "near-term" while carrying rows
that are not.

isOverdue lands in lib/dates.ts as the one definition, deliberately not
`isPast`: that is instant-granular and would call a 09:00 deadline missed
by lunchtime. It compares PRINTED dates — the same toLocalDateStr the
block renders with — so the word and the date beside it cannot disagree,
which an instant boundary computed in a different timezone from the
formatter can and does.

The same predicate goes into the daily brief, whose entire premise is
handing the model settled answers instead of rows to filter. It asked
"commitments due inside 3 days" and described its own SQL as
`due_date <= now()+3d`, both true of the code and neither true of the
rows: overdue ones were in the answer, unlabelled. Its dateLabel also
printed a UTC day next to a word now decided on the local one, so both
now go through toLocalDateStr.

The format test moves out of the source file into scripts/test/, where
test-unit.ts actually globs it — as an inline `--self-test` nothing ever
ran it. Extended to pin the boundaries, built from local calendar parts
rather than UTC instants (green under UTC, Zurich, Kolkata, New York,
Kiritimati and Midway).

Not touched: getGoalsDueSoon and getEventsDueSoon share the missing
floor, but /today's GoalsDueCard and EventsDueCard render them and are
meant to show overdue items to the human. Their `method` strings now
state that honestly instead of being made to lie less.

verify: 214/214 unit tests, tsc clean, lint 0 errors (2 pre-existing
warnings).

Refs #584

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 08:18:29 -07:00
CatoandClaude Opus 5 04cedba195 Loki's public face belongs to the tenants who agreed to be on it (#798)
* fix(setup): the documented local setup produced a broken app

Followed README.md and .env.example exactly on a clean checkout and got an
app that renders but cannot read a session. Three separate gaps, each on the
documented path:

- AUTH_TRUST_HOST was undocumented. src/auth.ts gates trustHost on it, and
  scripts/hetzner/gen-env.sh writes it on the box — but .env.example, the
  README's "minimum local .env.local", docker-compose.yml and loki-app.sh all
  omitted it. Unset, Auth.js answers EVERY /api/auth/session with 500
  UntrustedHost. Verified: 500 before, 200 after, nothing else changed.
  The auth.ts comment claimed the local production server set it; it did not.

- The compose db image has no pgvector. knowledge-embeddings.ts declares
  vector(384), so `drizzle-kit push` dies on the first table with
  `type "vector" does not exist` and leaves an EMPTY database — which reads
  like a broken checkout rather than a missing extension. Switched to
  pgvector/pgvector:pg17 and added an initdb script that creates it before
  the migrate service runs.

- drizzle.config.ts never loaded .env.local, though a dozen scripts under
  scripts/db and scripts/test do. `pnpm run db:push` therefore threw
  "DATABASE_URL is required" at someone who had just set DATABASE_URL where
  the README told them to. An exported variable still wins, so CI and the box
  are unaffected.

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

* fix(projects): the empty state named a button that does not exist

A new account with no projects is told to "Register your first project with
'New project' above". There is no "New project" control on the page — the
button reads "Add", and the dialog it opens is titled "Add Project". The
component file is called NewProjectButton.tsx, which is most likely where the
copy came from.

Found by signing up as a new user and following the onboarding instruction
literally: the first thing the product asks you to do names a control you
cannot find. Now says "Add", matching what is rendered.

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

* feat(fleet): a project reaches Loki's public catalogue only by consent

/fleet is unauthenticated and speaks for the PRODUCT, not for a user. It
resolved a single account — getSelfImprovementTarget(), "whoever owns the
oldest entity named loki" — and published every project that account had.
Two things were wrong with that in a multi-tenant product:

  1. No decision was ever recorded. A project was on a public page because it
     existed. Every other public surface here already goes through
     getPublicProjects (the landing hero, /u/[username]); /fleet was the only
     one reading the unfiltered query.
  2. WHICH account got published was a side effect of the self-improvement
     loop's notion of "which product am I improving". Reseed that entity and
     the next-oldest match's whole project list becomes Loki's front page.

So consent is now a stored property of the project:

- user_projects.listed_publicly, DEFAULT FALSE. The default is the point —
  signing up must never enrol a tenant in the product's shop window.
- getPubliclyListedProjects() reads consent instead of ownership, across all
  accounts, which is also what makes the page meaningful with more than one
  user. /fleet no longer selects by owner at all.
- A per-project toggle on the project workspace, beside the existing
  "Publish to OrangeCat" opt-in and reversible from the same control.
- 0075 backfills the account publishing the catalogue today, so the live page
  is unchanged for it while everyone else starts at false.

Also: FleetRegisterNote told EVERY account "19 sites are hosted on the box
with no project here" — apps.conf describes one box and is a file in this
repo, so a brand-new user was being told about sites they do not own. It now
renders only for the account that operates that box.

A user's own profile (/u/[username]) is deliberately untouched: that page is
the user speaking about themselves, and it was already scoped.

scripts/test/public-catalogue-consent.ts pins all of it — swapping the query
back is a one-word change, and a comment cannot hold that line.

Verified against a real database: consent false -> absent from /fleet,
true -> present, toggled both ways through the UI.

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

* feat(public): what a signed-out visitor sees is a decision, not an accident

Answers "whose projects does a stranger see on Loki?" — with three tiers
instead of three different hardcoded owner lookups.

THE PROBLEM. Loki is multi-tenant and the founder is tenant #1, but every
public surface resolved an owner and published whatever that account held:

  - the landing hero  → getHeroFleetSnapshot(getDefaultUser())
  - /fleet            → getSelfImprovementTarget()  (fixed in the last commit)
  - the /projects note→ nothing at all

Three answers to one question is three chances to be wrong, and the landing
was the worst of them: it never consulted consent at all. Verified locally —
a project with listed_publicly = false was rendering in the hero console.
It also ordered by a hardcoded FLAGSHIPS = ["loki", "orangecat"], the ad-hoc
version of "featured", which could only ever name the founder's own projects.
The same list sat in /u/[username], where it reordered EVERY tenant's profile
by two names they will never have.

THE MODEL. src/db/queries/public-visibility.ts is now the one place that says
what a signed-out visitor may see:

  1. AGGREGATE  — fleet-wide counts. Identify nobody, need no consent, and
                  grow honestly as Loki gains users.
  2. CATALOGUE  — /fleet: projects whose OWNER opted in (listed_publicly).
  3. SHOWCASE   — landing hero: the catalogue narrowed to what the OPERATOR
                  featured (featured_at). Curated space cannot be first-come.

Two gates because they answer to different people: consent is the tenant's
and may be withdrawn; featuring is the operator's editorial act. The showcase
predicate is BUILT ON the catalogue predicate, so revoking consent drops a
project off the homepage immediately even while it is still featured —
verified all three ways against a real database.

This is the doctrine site_feedback.featured_at already had ("raw visitor text
NEVER auto-publishes"). Projects now work the way feedback already did.

Featuring is authorized by isSiteOperator (users.is_default — the account made
at /setup, so it means "runs this instance" for self-hosters too) and lives on
its own query rather than riding patchProject, because it is the one project
field a tenant must not set for themselves. It also refuses to feature a
project whose owner has not consented.

UI: two separate controls on the project workspace, deliberately not merged —
"List publicly" (owner) and "Feature" (operator, shown only to them, and
explaining itself when consent is missing).

ALSO, from auditing the public pages at 320/390/768/1440:

- /fleet had 19 sub-44px tap targets — every one the site address that is the
  whole point of the row, and the only sub-44px targets left on any public
  route. .ui-public-fleet-site was missing from the touch floor AND was an
  inline box, where min-height does nothing. Both fixed; now zero.
- The responsive auditor EXCLUDED public routes, deferring to `smoke` "which
  already covers them" — smoke asserts HTTP status, which says nothing about a
  layout. So the pages a stranger sees first were the only ones with no
  responsive coverage. They are in the auditor now and need no session, so a
  session is required only when authenticated pages are requested.

No horizontal overflow at any width, before or after.

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

* fix(fleet): a phone spent a screenful on filters before the catalogue

Measured at 390x844: the first project row sat at y=1020px. Four facet rows
(Where / Kind / For / Missing) took 366px of that, so you scrolled past more
than a screen of controls before seeing any of the thing they control — on a
page whose entire job is to show a catalogue.

The rows now live in a <details> that is collapsed below md and forced open
from md up, so desktop is unchanged and the phone leads with content:
first row y=1020 -> 699. The summary carries a count of active facets,
because a filter you cannot see is one you forget you set — and then an empty
result reads as a broken page rather than a narrowed one.

<details> rather than state, because this page deliberately ships no
JavaScript ("the address bar is the state") and a filter panel that needed a
bundle to open would be the one thing on it that did.

One trap worth recording: hiding the closed panel has to be EXPLICIT. The UA
sheet hides a closed <details>'s children with display:none, but author styles
outrank the UA sheet and .ui-fleet-facet-row is `@apply flex` — so the first
version rendered a toggle that changed nothing, with the element correctly
reporting open=false while all four rows stayed visible. Verified both states
at both widths after the fix.

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

* feat(public): credit the builder, ask before publishing, stop renting the box

Four things, all following from the same rule: Loki is multi-tenant, so its
public face belongs to the tenants who agreed to be on it.

1. ATTRIBUTION. A showcased project now carries a byline — @handle linked to
   /u/[handle], display name when there is no handle, and NOTHING when there is
   neither, because a stand-in label is a name we would be inventing for
   somebody. Showing a tenant's work unattributed reads as "our projects",
   which is untrue and is the opposite of why a showcase exists; being credited
   and linked is also most of what a tenant gets back for consenting. Joined in
   the query rather than fetched per row.

2. LOKI ASKS. Consent was reachable only from a toggle nobody knew about, and a
   control nobody finds collects exactly one answer. The empty catalogue that
   follows is what gets "fixed" by widening the query again — the bug 0075
   removed. So the project workspace now invites the owner once, and
   listing_prompt_dismissed_at takes no for an answer: per project (declining
   for a client build says nothing about the open-source one beside it) and in
   the database (a refusal that resets on a new device is a product that nags).
   The rule lives in src/lib/listing-invitation.ts, pure and unit-tested. The
   bar is repo + active, deliberately NOT a live URL: /fleet's own facets list
   "Being built" beside "Live", so requiring a deployment would ask only the
   projects that least need the exposure.

3. THE BOX IS NOT THE FLEET. apps.conf describes ONE box and is a file in this
   repo, and unmatched entries MINTED rows — so a Loki with one consented
   project still published 19 sites belonging to someone the viewer has never
   heard of. buildFleetRegister now takes includeUnlinkedSites, true only for
   the operator, for whom those rows are the entire point (the register read
   sideways is a to-do list). A hosted app still ENRICHES a project that
   exists, so a consented project keeps its real address either way; only row
   creation is gated, because only row creation publishes something nobody
   asked to publish. Verified: operator sees 20 projects / 19 sites, the public
   sees 1 / 0.

4. THE COPY. "This is the studio's whole catalogue" was true when one account
   was the whole fleet. It now says what the page is: projects their owners
   chose to show.

Also, from re-auditing: .ui-public-fleet-name (the row's PRIMARY link) measured
21px tall on a phone. It had been invisible to every previous audit because
while the page listed hosted sites alone, nothing in a row was a link at all —
the fix in 3 is what made a real project row render and the gap appear. Same
cause as .ui-public-fleet-site last time: the coarse-pointer floor sets
min-height, which does nothing to an inline box.

Every public page: zero horizontal overflow and zero sub-44px targets at
320/390/768/1440.

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

* fix(home): the hero console had an empty third column

Making the hero tenant-agnostic dropped "runs this week", because the old one
counted getRecentOrchestrationRuns(userId) — one account's week, which is not a
number a visitor should be shown. But the console's metric row is grid-cols-3,
so removing it left a visibly empty third of the panel. Caught by looking at
the rendered page rather than the diff.

Restored fleet-wide, counted the same way as the other two: it is the metric
that answers "is anything actually happening here", and an aggregate across
every tenant identifies nobody, so it needs no consent and grows with the
product instead of describing one account.

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

* fix(footer): the studio's sites were labelled as Loki's fleet

Every public page's footer lists 14 sites generated from apps.conf under
"Part of the fleet — 14 more sites". apps.conf describes ONE box, the
studio's, and several of those sites belong to clients — so on a multi-tenant
Loki the label told every visitor that one account's client work was what Loki
is. Same error as the /fleet lede, and the same fix: say whose they are.

"Built by the studio" now, and the link beside it points at the tenants'
catalogue by its real name rather than calling it "the whole register".

Deliberately a COPY change and nothing more. The links themselves stay, all
14 of them: they are real work, several had no inbound link from anywhere
before this block existed, and the cross-linking is the entire reason it is
here. Removing them would trade a genuine asset to fix a sentence. Only the
claim was wrong.

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

* fix(home): the hero console looked broken with nothing featured

0076 deliberately does not backfill a feature stamp — featuring is an
editorial act nobody has performed yet — so the live hero will really render
with zero project rows until someone features something. I had asserted that
was fine without looking at it. It was not.

The bar carries mb-4 + border-b and the metrics carry mt-4 + border-t, so with
no rows between them the panel drew TWO horizontal lines with 32px of nothing
in between: the shape of content that failed to load, on the first screen of
the product.

The metrics now sit flush under the bar's own border in that state, which is a
panel with nothing to list rather than a panel that broke. Verified in both
states: with rows the divider is back and the flush class is absent.

Not fixed by falling back to showing consented-but-unfeatured projects, which
was the tempting option: the invitation asks permission for the public fleet
page specifically, so putting those projects in the hero would take more than
the owner agreed to.

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

* fix(fleet): an empty catalogue told visitors to clear filters they never set

With nothing listed, /fleet rendered "Nothing matches that. Clear the filters →"
— to a visitor who had set no filters, offering a link that changes nothing.
That is the FIRST thing a freshly self-hosted Loki ever says on that page, and
it reads as a fault rather than an empty shelf.

Two states now, told apart by `rows` (the whole catalogue, before the query)
rather than `result.rows` (after it):

  nothing listed at all → says so, and says why: owners choose which of their
                          projects appear, and nothing is published without
                          them saying so. Links to what Loki does.
  filtered away        → unchanged: "Nothing matches that" + clear the filters.

Found by putting the local database into the state a new install starts in,
rather than only the state mine happened to be in.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-20 06:30:17 -07:00
CatoandClaude Opus 5 ae92bde49e test(access): pin the project permission boundary, which nothing tested (#795)
Priority 5 of the 2026-09-17 review asks for the journey to be proved
with an editor and a reporter account. The live two-account walk still
needs two real sign-ins and is NOT what this does — see below. This is
the half that needs no accounts, and it turned out to be missing
entirely.

`getProjectAccess` is the one authorization decision every project
surface reads, and the rule inside it —

    canEdit: member.role === "editor",
    canManageMembers: false,

— lived in a function that cannot be imported without a DATABASE_URL. So
it had no test. The only way to find out that a viewer could edit, or
that an editor could add members, was to sign in as one and look. A
boundary whose only proof is a manual walk regains a hole the first time
someone adds a role.

The rule is now its own pure module and the query reads it. Behaviour is
unchanged — same two expressions, one place — and it is a Record over
ProjectRole, so adding a role without deciding its capabilities is a
type error rather than a silent `false` or, worse, a copy of another
role's answer.

Six checks, including two that hold for EVERY declared role rather than
the two that exist today: nobody but the owner can manage members, and
no collaborator role is silently as powerful as the owner. That is the
part a future role would break.

Proved by mutation: granting `viewer` canEdit fails with "a reporter
must not be able to dispatch work" — a viewer is the role a reporter
gets on the project they filed against, so that assertion is the
tenancy boundary itself.

WHAT THIS DOES NOT DO: it does not prove the end-to-end journey with two
real accounts. That needs credentials I do not have, and creating
accounts is not something to do unasked. Priority 5 stays open for the
live walk; this makes the rule it would be checking impossible to break
silently in the meantime.

tsc clean, lint 0 errors, test:unit 205/205.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 10:01:49 -07:00
CatoandClaude Opus 5 2d80b507ef fix(feedback): ask where a run ACTUALLY went, not where a new one would go (#792)
Risk 3 of the 2026-09-17 review: "Feedback attach-work falls back from
closed pending command to current project routing preference. A current
setting cannot prove where a historical attempt ran."

Exactly right. The channel resolution was:

  pending row (open) ?? pickDispatchChannel(project)

The open row is gone for most of a run's life — the runner stamps
executedAt on its inject-ack, within ~8s of injecting — so in practice
the second half decided almost every finished run. And that half is a
LIVE PREFERENCE. Flip a project from This computer to Cloud and every
finished local run starts claiming it ran on the box, with its offline
verdict computed against a machine it never touched.

The fix needed no new state, because the record already existed. The
executed pending_commands row carries the channel it was handed to, in
its payload, and getInjectAcksByRunIds was already reading exactly those
rows for the same runs — it just never selected the field. So the
immutable execution identity of the attempt was one property away the
whole time.

Now the order is an order of EVIDENCE:

  1. the open pending row  — this attempt, right now
  2. the executed command  — this attempt, recorded when it was handed
  3. the project's setting — where a NEW dispatch would go today

Only the first two are about the attempt being described. The third
stays as the last resort because a run that never reached a builder has
no recorded channel at all, and there the dispatcher's own rule is the
best available guess.

The channel lives in the jsonb payload rather than a column, so it is
validated the same way the open-row reader already validates it: an
unrecognised value is not a channel.

Tests: two cases — a project now set to Cloud whose attempt ran local
(the recorded fact wins, and the offline verdict follows it), and an
attempt with no recorded channel (falls back). Proved by mutation:
restoring the old expression fails "the recorded attempt outranks the
project's current preference". tsc clean, lint 0 errors, test:unit
204/204.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 09:34:52 -07:00
CatoandClaude Opus 5 c90638c311 fix(feedback): a dispatch waiting its turn is named, not blamed (#786)
Loki runs one agent per project: while a run is open, the queue deliberately
withholds the next command for that project (fifoEligibilitySql). Correct
behaviour. But nothing downstream knew that was the reason a command sat
unclaimed, so both surfaces guessed, and both guessed wrong — in opposite
directions, on the same row:

  row:   "Retry — or Open Terminal for why it never started"
  panel: "Waiting for This computer to claim. If this stays put, confirm
          Fleet Runner is polling"

Nothing had failed. The project had a healthy run in flight, both builders
were connected and claiming everything else, and Retry could only have
enqueued a second command the same gate would withhold for the same reason.
Found by pressing Implement on the live site and then reading the queue
(2026-09-17, command 98c6a42a: created 16:01, claimed 16:48 the moment the
run ahead of it closed).

The gate's rule is now one SQL fragment — olderOpenRunSql — composed by both
the claim query that enforces it and a new findQueueBlockers that answers
"what is ahead of this run". The decision the queue makes and the sentence a
person reads come from the same predicate, so they cannot drift.

The row now says which run holds the lane and that the wait ends by itself;
the panel says the same thing instead of sending the reader to inspect a
builder that is doing nothing wrong. Both keep their old copy when no blocker
exists, because "nobody is claiming this" is still a real and different fault.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 06:45:03 -07:00
CatoandClaude Opus 5 eadad2711f feat(calendar): warn on the card when a proposal clashes (#777)
* feat(approvals): standing approvals + one-tap decisions from Telegram

Asking Loki in Telegram to put an appointment in the calendar did not put an
appointment in the calendar. It sent you to a website.

Three separate causes, all fixed here:

1. THE CHAT HAD NO ROAD TO THE CALENDAR AT ALL. `gog calendar create` is
   blocked on the box by the safety shim, and the fleetcrown skill could only
   decide drafts that already existed — it had no way to create one. So the
   agent hit the shim, read "route it through the approval queue", and passed
   that on as advice. Adds `fc.sh book`, which proposes a structured event
   through /api/actions/propose, and rewrites the shim's refusal to name it.
   The shim still blocks every external Google write; unattended agents have
   gained nothing.

2. THE GATE WAS ON THE WRONG SIDE OF THE REVERSIBILITY LINE. The queue enforced
   "nothing runs that the operator did not TAP", which is stricter than the rule
   it stands for ("nothing runs that the operator did not APPROVE"). For an
   event in your own calendar — private, self-only, undone by deleting it — the
   difference was pure latency (2026-08-04: proposed 14:15, booked 21:02).
   Standing approvals let that yes be given once, in advance, with three rails
   in code rather than in a docblock: eligibility is hard-coded (calendar events
   and commitments only — never anything that reaches another person), the
   payload is re-checked at decision time (guests mean invitations, so those go
   back to the queue), and unknown is never yes (no resolvable time, or a slot
   already past, queues). Default on for calendar events; toggle at /approvals.

3. THE NOTIFICATION HANDED BACK A CHORE. "2 actions are waiting… <url>" states
   a problem and leaves the answer behind a login. Decisions now arrive as a
   card carrying what/when/where plus one-tap Approve / Reject / Edit buttons,
   backed by HMAC links scoped to one action and one verb — so a decision needs
   no session and works when the gateway is down. Still two messages and only
   two: one when a decision is owed, one when the effect really happened.

Also fixes a real data bug: propose_action had no event date fields, so the WHEN
of an appointment had nowhere to go and arrived as prose in `body`, which a Groq
pass then had to guess back — a model re-deriving a value the model one step
earlier knew exactly.

Behaviour that did NOT change: emails, messages, dispatches, and person-book
writes still require a per-item yes, and always will — they are ineligible in
code, and a preference row naming one authorises nothing. Every auto-approval is
audited with `via: standing-rule` and announced, so nothing is done in the
operator's name silently.

Tests pin the parts that must not be trusted: 37 cases on the standing-approval
rails (asserted from the side that hurts — a false `auto: true`), 21 on token
forgery and tampering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(chat-skill): the chat's whole Loki skill was dead, and unversioned

Found while testing the previous commit end-to-end, and it is the largest of
the reasons appointments never got added.

On 2026-09-14 the product was renamed to Loki and `calendar-drain.env`'s keys
were renamed with it. The chat agent's skill script, which reads that file, was
not — because it lived only on the box, where no gate in this repo could see
it. Since then every command it offers has aborted on its first line:

    line 14: <OLD>_AGENT_TOKEN: <OLD>_AGENT_TOKEN missing in calendar-drain.env

Verified live on bitbaum just now. So from Telegram the operator could not list
the approval queue, could not approve or reject anything, and could not
dispatch — silently, because a skill that errors just makes the agent talk
about something else instead. The only surviving route to a decision was the
website. That is the complaint, and it had a cause older than the UX.

Fixes:

- Renames the skill to `loki` (the retired product name is forbidden in this
  repo by scripts/hetzner/test-no-retired-name.sh — which caught this commit,
  correctly, when the box files were first imported verbatim) and reads the
  env keys the file actually has.
- The installer REMOVES the superseded skill directory rather than leaving it.
  Two skills claiming the same job, one of which cannot run, is how the agent
  kept choosing the broken one.
- The installer now runs `loki.sh pending` as the openclaw user and fails if it
  cannot authenticate. That is the check which would have caught the rename on
  the day it happened: run the thing, as the user who runs it, and require real
  output. Every other verification in that script only asserted that files
  exist, and files existing is exactly what was true throughout the outage.

Also closes a gap in the previous commit: an auto-approved COMMITMENT executed
without telling anyone, while the comments claimed every auto-approval is
announced. Calendar events are announced from where gog succeeds (asynchronous,
on the box); everything else finishes inside enqueueAction, so that is the only
place that knows it finished at all. A standing approval nobody is told about
is not a standing rule, it is a silent one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(install): keep the gog shim parseable, and prove the block still fires

The replacement text I substituted into the shim carried double quotes. It
lands inside `block(){ echo "…" >&2; }` — a double-quoted bash string — so a
quote in the middle of it closes that string early and leaves the shim a
syntax error. Every gog call on the box would then fail, reads included, and
the calendar drain's real bookings with them: an install step meant to improve
an error message would have taken out the calendar entirely.

Caught by tracing the sed against the shim's actual text rather than running
it. Two checks added so the next one is caught by the machine:

- `bash -n` on the shim after the edit — it is a shell script we just modified
  in place, so prove it still parses before trusting anything else about it.
- Actually attempt a calendar write as the openclaw user and require it to be
  REFUSED. The old check grepped for the rule's text, and a rule you can read
  in a file is not a rule you have seen refuse anything.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ui): use tokens this design system actually defines

The new approvals control and decision page reached for `text-brand`,
`accent-brand`, `bg-surface-hover` and `rounded-card`. None of those exist in
globals.css — the real names are `accent-text`, `surface-raised` and the
`radius-*` scale. Tailwind emits nothing for an unknown utility and reports no
error, so the checkbox would have rendered browser-default blue and the hover
state simply would not have happened, on a page whose entire job is to be
tapped once and trusted.

The design check passes either way: it forbids arbitrary values (`bg-[#fff]`),
which is a different failure from naming a token that was never defined. Caught
by grepping whether any other component uses these names — none did, which is
the tell.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(notify,install): two silent no-ops found by running the thing

Both found by exercising the deployed feature end to end rather than reading
it, and both are the same failure: a step that could not succeed, reporting
nothing.

1. A REFUSED TELEGRAM SEND WAS INVISIBLE. sendTelegramMessage reports a bad
   token, a blocked chat or an API error as `{ok:false}` — an ordinary return
   value, not an exception — so the try/catch around it caught the case that
   never happens and ignored the case that does. That matters more here than
   in a normal notification: the confirmation message IS the review mechanism
   for actions a standing rule took without asking. If it stops arriving, the
   operator does not notice Loki went quiet; they notice Loki apparently
   stopped doing things, which is the opposite of what is true. Both senders
   now log a refusal.

2. THE INSTALLER'S CLEANUP STEP CLEANED NOTHING. It globbed the skills
   directory as the ssh user, who cannot traverse the openclaw home: the glob
   matched nothing, the loop ran zero times, and the script printed its success
   banner. The superseded skill was still installed afterwards — the exact
   "two skills claiming one job, one of them broken" state the step exists to
   prevent, left in place by the step that prevents it.

   Fixed by running the loop under sudo, and then ASSERTING no other skill
   ships the old entrypoint. Trusting the loop's own silence is what let the
   first version pass; verified on the box that it now removes the directory
   and that the assertion sees an empty result afterwards.

Verified live on bitbaum after deploying the parent change: booking from the
chat skill returns auto-approved, the drain books it, the row reaches executed,
and the event is really in Google Calendar at the right time. Test event
deleted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): the one-tap approval link redirected to sign-in

The feature whose entire purpose is "decide from your phone without logging in"
sent you to a login page. Found by tapping it against production, not by
reading it:

    GET /a/<token>  →  302  /sign-in?callbackUrl=/a/<token>

Route auth here is one negative-lookahead regex in src/proxy.ts listing the
prefixes served without a session, and `a/` was not among them. Every unit test
on the token passed throughout — 21 of them — because they tested the TOKEN.
Nothing tested whether the route could be reached, which is the part that was
broken. A signature that verifies perfectly behind a login is worth nothing.

Adds `a/` with the same justification the file already records for `share/task/`:
the minted token IS the credential, the holder has no account by design, and the
link decides exactly one action with one verb (lib/actions/action-link.ts).

THE TRAILING SLASH IS LOAD-BEARING, and that is why this commit also adds a
gate. The list holds bare prefixes, so `a` instead of `a/` would have made
/approvals, /api/*, /agent — every path starting with that letter — publicly
readable, and nothing would have looked broken: the app would have worked
better, with nobody asked to log in. That is the one direction a reviewer will
not notice.

scripts/test/public-matcher.ts reads the real regex out of the real file and
asserts BOTH directions: what must be reachable without a session, and what must
not. Proven by mutation before committing — with `a` in place of `a/`, eight
assertions fail loudly (/approvals, /api/actions/pending, /api/me/preferences
among them). A test that only checked the public list would have passed just as
happily on a regex that made the whole app public.

Verified: pnpm verify green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(calendar): warn on the card when a proposal clashes

An approval card asks "shall I book Thursday 14:30?" and could not answer the
one question most likely to change the answer: is Thursday 14:30 already taken?
On 2026-09-17 a test booking for 14:30–15:30 was approved on top of an existing
15:00 meeting and the card said nothing at all.

It could not know. The calendar lives behind `gog`, authenticated on the
operator's machine only; the cloud control plane — where proposals are made and
cards are sent — gets `runtimeOnly: true` and an empty list.

So the box mirrors what is OCCUPIED, one way, and the card reads it:

  home/calendar-drain.ts  →  POST /api/calendar/busy  →  calendar_busy

The drain already held both halves this needs (gog, and the ck_* token), so it
gains a second, slower clock rather than a second process. Start, end and title
only — no attendees, no descriptions, no locations leave that machine. Google
stays authoritative; nothing here is ever written back.

FOUR DECISIONS WORTH THE REVIEW:

1. REPLACE THE WINDOW, DO NOT MERGE. An event cancelled in Google stops
   appearing in what the box sends; a merge would keep it forever and produce a
   phantom clash on a slot that is free. A warning that cries wolf is worse than
   no warning, because it is read exactly once.

2. BACK-TO-BACK IS NOT A CLASH. Overlap is half-open, so 14:00–15:00 against
   15:00–16:00 stays silent. Inclusive ends would flag every adjacent pair in a
   real diary and train the operator out of reading the line within a week.

3. STALE NEVER READS AS FREE. `conflictsFor` answers clear / conflict / UNKNOWN,
   and unknown speaks: "your calendar hasn't synced recently, so I couldn't
   check". An offline laptop leaves the mirror stale, and a stale empty window
   is indistinguishable from an empty afternoon — collapsing the two would have
   the card implying you are free on the app's behalf. Same failure this
   codebase keeps meeting: absence of evidence rendered as evidence of absence.

4. CLEAR SAYS NOTHING. A card that announces the absence of a problem every
   time is noise, and noise is what stops warnings being read.

Tests: 20 cases on the conflict rules, asserted from BOTH dangerous directions
(the false positive that kills trust, the false negative that hides a clash),
including the exact 2026-09-17 collision as a fixture; 10 new cases in the
drain's self-test on normalising gog events, where the null paths get as much
attention as the happy one — inventing a busy block is how you invent a clash.

The mirror is also the prerequisite for suggesting events that do not collide
with what is already booked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 11:03:18 -07:00
CatoandClaude Opus 5 dd8a877944 fix(ai): the capacity page said a busy vendor had never served (#770)
* fix(ai): the capacity page said a busy vendor had never served

Opened the page on production and read it. Three things were wrong, and the
first is the SAME false sentence that started this work.

THE GOOGLE ROW WAS THE ORIGINAL COMPLAINT, AGAIN

  google — not measured
  "configured, but it has not served an answer yet"
  "will be measured on the next answer it serves"

Gemini answers most of the traffic. It also publishes no rate-limit headers at
all, so it can never appear in provider_quota — which means BOTH lines were
false, and the second promised a measurement that would never arrive however
long anyone waited. The identical wording about Groq is what got this page
called made-up in the first place; I fixed it there and shipped it here.

Fixable now only because of the ledger added yesterday. Spend is a SECOND
WITNESS: headers answer "how much is left" and go silent for a vendor that
discloses nothing, while spend answers "did this actually run" and never goes
silent, because it is recorded on our side of the call. With two witnesses the
row can say the true and useful thing — "served 14 calls today (9,532 tokens) —
this vendor publishes no limits, so there is nothing left to measure", and a
consequence that admits the headroom is unknowable until it refuses.

Every false claim this page has made has been the same mistake: reporting
ABSENCE OF MEASUREMENT as ABSENCE OF ACTIVITY. Groq "hasn't served" while being
skipped. A minute window "spent" while holding 3,984 tokens. Now this.

TWO SMALLER LIES

  whisper-large-v3-turbo — "~1,999 answers". It serves TRANSCRIPTIONS. A wrong
  unit is how a reader starts distrusting the number beside it.

  Five OpenRouter models each printed "this is the last link — after it, answers
  wait for the reset". The fact is per-PROVIDER; repeating it per model does not
  make it truer, it just buries the rows that say something different. Said once
  per run now, and a consequence that returns after a different one speaks again
  — dedupeConsequences is pure and tested rather than inline in the route.

Quota-view checks 31 -> 37, both directions of each: a vendor nobody has called
still says exactly that, and a chat model keeps "answers".

Full gate green, run in pieces because the box is at 26/31 GB: tsc, lint,
format, design, unit 194/194, home 130, desktop, ops 7/7.

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

* chore: re-trigger CI

Both prior runs for this branch stalled seconds after starting, during a window
when the box was at 26/31 GB and local verify was being OOM-killed too. Branches
that started after the crunch are progressing normally, so this is a fresh run
against a healthier machine rather than a change to the code.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 07:51:39 -07:00
CatoandClaude Opus 5 28de8ac62e feat(newsletter): let the studio site join the list, and say so out loud (#762)
The studio site's /hire/ page stops publishing rates and offers a waitlist
instead. It is a static page on another origin, so a JSON POST to
/api/newsletter triggers a preflight this route did not answer, and a row
landed in a table with no sending pipeline — capture-only by design, which
is fine for a newsletter nobody has sent and wrong for a page that promises
a human writes back when capacity opens.

CORS, but an allowlist. The feedback widget can afford
`Access-Control-Allow-Origin: *` because its fcw_* token is the real gate.
This route has no token and writes a row per call, so it echoes one
allowlisted origin at a time (src/lib/api/public-cors.ts) and varies on
Origin, and an unknown origin gets no ACAO at all. The 429 carries the
headers too: a cross-origin refusal the browser cannot read is a refusal
the visitor cannot be told about.

A new row now announces itself on Telegram, through the channel's existing
contract — fire at the insert choke point, never throw, never slow the
response, and stay silent when the operator must not act. subscribeToNewsletter
returns whether it actually inserted, so a repeat signup is still a silent
no-op; the visitor is told the same thing either way. Registered in
docs/telegram-notifications.md, as the gate requires.

Proven by mutation, not by a green run: setting ACAO to "*" fails the new
test with "an allowlisted origin must be echoed back verbatim", and the
allowlist test also refuses a prefix match (bitbaum.orangecat.ch.evil.test),
a scheme downgrade, a null origin and a missing one. 191/191 unit files pass.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 05:00:18 -07:00
CatoandClaude Opus 5 e6b8a17970 feat(approvals): standing approvals + one-tap decisions from Telegram (#761)
* feat(approvals): standing approvals + one-tap decisions from Telegram

Asking Loki in Telegram to put an appointment in the calendar did not put an
appointment in the calendar. It sent you to a website.

Three separate causes, all fixed here:

1. THE CHAT HAD NO ROAD TO THE CALENDAR AT ALL. `gog calendar create` is
   blocked on the box by the safety shim, and the fleetcrown skill could only
   decide drafts that already existed — it had no way to create one. So the
   agent hit the shim, read "route it through the approval queue", and passed
   that on as advice. Adds `fc.sh book`, which proposes a structured event
   through /api/actions/propose, and rewrites the shim's refusal to name it.
   The shim still blocks every external Google write; unattended agents have
   gained nothing.

2. THE GATE WAS ON THE WRONG SIDE OF THE REVERSIBILITY LINE. The queue enforced
   "nothing runs that the operator did not TAP", which is stricter than the rule
   it stands for ("nothing runs that the operator did not APPROVE"). For an
   event in your own calendar — private, self-only, undone by deleting it — the
   difference was pure latency (2026-08-04: proposed 14:15, booked 21:02).
   Standing approvals let that yes be given once, in advance, with three rails
   in code rather than in a docblock: eligibility is hard-coded (calendar events
   and commitments only — never anything that reaches another person), the
   payload is re-checked at decision time (guests mean invitations, so those go
   back to the queue), and unknown is never yes (no resolvable time, or a slot
   already past, queues). Default on for calendar events; toggle at /approvals.

3. THE NOTIFICATION HANDED BACK A CHORE. "2 actions are waiting… <url>" states
   a problem and leaves the answer behind a login. Decisions now arrive as a
   card carrying what/when/where plus one-tap Approve / Reject / Edit buttons,
   backed by HMAC links scoped to one action and one verb — so a decision needs
   no session and works when the gateway is down. Still two messages and only
   two: one when a decision is owed, one when the effect really happened.

Also fixes a real data bug: propose_action had no event date fields, so the WHEN
of an appointment had nowhere to go and arrived as prose in `body`, which a Groq
pass then had to guess back — a model re-deriving a value the model one step
earlier knew exactly.

Behaviour that did NOT change: emails, messages, dispatches, and person-book
writes still require a per-item yes, and always will — they are ineligible in
code, and a preference row naming one authorises nothing. Every auto-approval is
audited with `via: standing-rule` and announced, so nothing is done in the
operator's name silently.

Tests pin the parts that must not be trusted: 37 cases on the standing-approval
rails (asserted from the side that hurts — a false `auto: true`), 21 on token
forgery and tampering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(chat-skill): the chat's whole Loki skill was dead, and unversioned

Found while testing the previous commit end-to-end, and it is the largest of
the reasons appointments never got added.

On 2026-09-14 the product was renamed to Loki and `calendar-drain.env`'s keys
were renamed with it. The chat agent's skill script, which reads that file, was
not — because it lived only on the box, where no gate in this repo could see
it. Since then every command it offers has aborted on its first line:

    line 14: <OLD>_AGENT_TOKEN: <OLD>_AGENT_TOKEN missing in calendar-drain.env

Verified live on bitbaum just now. So from Telegram the operator could not list
the approval queue, could not approve or reject anything, and could not
dispatch — silently, because a skill that errors just makes the agent talk
about something else instead. The only surviving route to a decision was the
website. That is the complaint, and it had a cause older than the UX.

Fixes:

- Renames the skill to `loki` (the retired product name is forbidden in this
  repo by scripts/hetzner/test-no-retired-name.sh — which caught this commit,
  correctly, when the box files were first imported verbatim) and reads the
  env keys the file actually has.
- The installer REMOVES the superseded skill directory rather than leaving it.
  Two skills claiming the same job, one of which cannot run, is how the agent
  kept choosing the broken one.
- The installer now runs `loki.sh pending` as the openclaw user and fails if it
  cannot authenticate. That is the check which would have caught the rename on
  the day it happened: run the thing, as the user who runs it, and require real
  output. Every other verification in that script only asserted that files
  exist, and files existing is exactly what was true throughout the outage.

Also closes a gap in the previous commit: an auto-approved COMMITMENT executed
without telling anyone, while the comments claimed every auto-approval is
announced. Calendar events are announced from where gog succeeds (asynchronous,
on the box); everything else finishes inside enqueueAction, so that is the only
place that knows it finished at all. A standing approval nobody is told about
is not a standing rule, it is a silent one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(install): keep the gog shim parseable, and prove the block still fires

The replacement text I substituted into the shim carried double quotes. It
lands inside `block(){ echo "…" >&2; }` — a double-quoted bash string — so a
quote in the middle of it closes that string early and leaves the shim a
syntax error. Every gog call on the box would then fail, reads included, and
the calendar drain's real bookings with them: an install step meant to improve
an error message would have taken out the calendar entirely.

Caught by tracing the sed against the shim's actual text rather than running
it. Two checks added so the next one is caught by the machine:

- `bash -n` on the shim after the edit — it is a shell script we just modified
  in place, so prove it still parses before trusting anything else about it.
- Actually attempt a calendar write as the openclaw user and require it to be
  REFUSED. The old check grepped for the rule's text, and a rule you can read
  in a file is not a rule you have seen refuse anything.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ui): use tokens this design system actually defines

The new approvals control and decision page reached for `text-brand`,
`accent-brand`, `bg-surface-hover` and `rounded-card`. None of those exist in
globals.css — the real names are `accent-text`, `surface-raised` and the
`radius-*` scale. Tailwind emits nothing for an unknown utility and reports no
error, so the checkbox would have rendered browser-default blue and the hover
state simply would not have happened, on a page whose entire job is to be
tapped once and trusted.

The design check passes either way: it forbids arbitrary values (`bg-[#fff]`),
which is a different failure from naming a token that was never defined. Caught
by grepping whether any other component uses these names — none did, which is
the tell.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 04:01:06 -07:00
CatoandClaude Opus 5 b71941be63 feat(providers): one-tap switch to a provider that still has quota (#757)
* feat(providers): one-tap switch to a provider that still has quota

When the agent building a project hits a rate limit, the way out already
existed — four other agent CLIs, most with untouched quota. Taking it was
the problem. The only chooser lived in the Terminal right rail, it offered
every agent in a fixed order whether or not the connected builder had it
installed, and taking it swapped the live PTY without recording the choice,
so the next dispatch went straight back to the agent that had just run out.

One ranking, three surfaces:

- src/lib/provider-switch.ts — the whole decision as pure functions. Ranks
  the operator's order, filters on two pieces of OBSERVED evidence (the
  builder's installed-agent report, and recent runs that died with capacity
  language), and holds the three-state rule provider_quota is built on: an
  agent nothing was reported about is unknown, and unknown reads as usable.
  Nothing is hidden — a provider that cannot answer still appears, disabled,
  saying why. 18 inline checks in scripts/test/provider-switch.ts.
- GET /api/providers — that ranking, once, for every surface. Accepts either
  the user_projects id or the entity id, because the Feedback row holds one
  and Control/Terminal hold the other.
- ProviderSwitch — "Try <next>" plus a menu of the rest, now the PRIMARY
  control on a Needs-you / Failed feedback row (Retry steps down beside it),
  in the Control inbox, and in the Terminal rail.

And it sticks: POST /api/feedback/<id>/dispatch takes an `agent`, records it
as the project's agentPref, then dispatches on it — no scavenger hunt through
project settings.

The order is the operator's, not the fleet's: user_preferences.agent_order
(migration 0072, nullable and additive) with a reorder list in Settings →
Agent. Null means "never stated", and the fleet default applies.

Two SSOT repairs the work ran into:
- AGENT_FALLBACK_ORDER was defined TWICE (agent-registry.ts and
  agent-resolution.ts) — the server reroute and the client reroute each read
  their own copy. agent-registry now re-exports the client-safe leaf.
- QUOTA_ALTERNATIVE_AGENTS is derived from that order instead of being a
  second hand-written list of the same five ids.
- TerminalRunView.alternatives is gone; quotaDeath stays as the flag that
  asks the shared chooser.

provider_quota is deliberately NOT an input: it meters the ai-kit inference
chain (groq, openrouter) behind Loki's own chat, not the agent CLIs. The
agent-CLI equivalent is the run evidence above — observed, never probed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(providers): never offer the agent the project would actually run on

Self-review caught a gap in the chooser's exclusion rule. It read "current"
straight off `user_projects.agent_pref`, so a project that has never had a
preference set reported no current agent at all — and dispatch does not work
that way. Such a project still runs, on DEFAULT_ADAPTER_ID, which means the
escape offered from a Claude Code rate limit could be Claude Code.

currentProviderFor() answers the question the exclusion is actually asking —
which agent just died — in the order the evidence deserves:

  1. what this project LAST RAN on (freshest run inside the window). A stored
     preference can be stale by one switch; a run is what happened.
  2. else its stored preference.
  3. else the fleet default, because that is what the next dispatch picks.

A run on an agent the chooser cannot offer (openclaw) is not "current" — it
falls through rather than excluding nothing.

Three more checks in scripts/test/provider-switch.ts, 21 total.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 00:59:08 -07:00
Cato 8034cb629b feat(feedback): add reporter tracking and project editors (#754) 2026-09-16 22:21:59 -07:00