Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,15 @@ KRAKATOA_NUTRITIONIX_KEY=
# KRAKATOA_ASK_MODEL=claude-sonnet-5
# KRAKATOA_ASK_EFFORT=medium

# --- Totem bridge: habit push and WHOOP burn (optional, off by default) ----------
# Krakatoa holds no WHOOP credentials; it reads them through a Totem bridge.
# --- WHOOP burn, read from Bushido (optional, off by default) --------------------
# Krakatoa holds no WHOOP credentials; Bushido holds the grant and Krakatoa asks
# it (POST /api/whoop/owner). Off unless both are set, here or in Settings.
# BUSHIDO_API_URL=http://127.0.0.1:8099
# BUSHIDO_API_TOKEN=
# KRAKATOA_WHOOP_STALE_MS=1200000
# KRAKATOA_WHOOP_DAYS=30

# --- Totem bridge: habit push (optional, off by default) -------------------------
# Off unless KRAKATOA_TOTEM=1, KRAKATOA_TOTEM_URL is set, or Settings turns it on.
# KRAKATOA_TOTEM=0
# KRAKATOA_TOTEM_URL=http://127.0.0.1:8787
Expand All @@ -66,8 +73,6 @@ BRIDGE_SECRET=
# No default. (An install upgraded from before Settings records where it read it.)
# KRAKATOA_TOTEM_ENV=
# KRAKATOA_TOTEM_HABIT=krakatoa
# KRAKATOA_WHOOP_STALE_MS=1200000
# KRAKATOA_WHOOP_DAYS=30

# --- Digest file (optional, off by default) --------------------------------------
# Write data/digest.json, a small summary of the last two weeks, after every
Expand Down
57 changes: 38 additions & 19 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ disk. Default port **8101**.
| The generic foods | `content/basics.json` + `app/src/lib/basics.js` |
| …and the script that generates them | `scripts/basics.build.mjs` |
| Optional Totem bridge: habit push | `server/totem.js` |
| Optional Totem bridge: WHOOP's daily burn, and the deficit | `server/whoop.js` + `app/src/lib/whoop.js` |
| Optional WHOOP daily burn, read from Bushido, and the deficit | `server/whoop.js` + `app/src/lib/whoop.js` |
| Chain menus (OPTIONAL file: every reader must cope with it absent) | `scripts/restaurants.build.mjs` → `content/restaurants.json` |
| …one reader per way a chain publishes | `scripts/restaurants/*.mjs` |
| …and the bowl or order built from one | `app/src/lib/restaurants.js` + `app/src/bowl.jsx` |
Expand Down Expand Up @@ -120,7 +120,8 @@ shows which build is being served.
backslashes. Do not go back to a regex.
- **Machine callers** (MCP clients, scripts) use `Authorization: Bearer <token>`:
the API token from Settings (`KRAKATOA_API_TOKEN`), or the Totem bridge
secret. A bearer opens `/api/*` and `/mcp`, never the pages.
secret. (The Bushido token goes the other way: Krakatoa sends it to Bushido,
and it opens nothing here.) A bearer opens `/api/*` and `/mcp`, never the pages.
- **The iPhone app** (`mobile/`) signs in with the owner's password like a
browser, but sends `X-Krakatoa-Client: native` and gets the session in the
JSON reply instead of a cookie (also on a password change). It sends it back
Expand All @@ -142,7 +143,9 @@ shows which build is being served.
(`settingsWriteRefused`). Proxy mode on a non-loopback bind logs a warning.
- **A changed bridge URL** sets `totem.ownSecretOnly` (`guardTotemUrl`), so
neither `BRIDGE_SECRET` nor Totem's .env is sent to the new host; only a
secret entered for it.
secret entered for it. A changed Bushido URL does the same for
`BUSHIDO_API_TOKEN` (`bushido.ownTokenOnly`, `guardBushidoUrl`); the PUT
runs both through `guardUrls`.

### Settings (`server/settings.js`, `app/src/settings.jsx`)

Expand All @@ -168,9 +171,13 @@ reaches outside the app off**:

- **AI.** Without a CLI, `/api/label` and `/api/ask` answer 503 with
`setup: 'ai'`, and the screens show "Set up AI in Settings" instead of an error.
- **The Totem bridge** (WHOOP burn and the habit push). While off, nothing
contacts it, `/api/whoop` answers `configured: false`, and the day has no
energy panel. `totemConfig()` returning null is the off switch everywhere.
- **The Totem bridge** (the habit push). While off, nothing contacts it.
`totemConfig()` returning null is the off switch everywhere.
- **Bushido** (WHOOP burn). On only with a URL and a token
(`BUSHIDO_API_URL`, `BUSHIDO_API_TOKEN`, or Settings); there is no default
URL and no on switch. While off, nothing contacts it, `/api/whoop` answers
`configured: false`, `features.whoop` is false, and the day has no energy
panel. `bushidoConfig()` returning null is the off switch.
- **The digest file** (`data/digest.json`). `/api/digest` still answers live.

`settings.migrate()` runs once per data dir (when `settings.json` is absent).
Expand All @@ -179,12 +186,14 @@ bridge and the digest on. With no `owner.json` it predates sign-in and gets
`auth.mode: proxy`; **with an `owner.json` it never gets proxy**. The legacy
Totem `.env` path is recorded only if that file exists; it has no default.
Nobody upgrading should find their setup switched off. The "off" defaults are
for fresh installs only. `server/install.test.js` boots real servers for all
for fresh installs only. (One deliberate exception: WHOOP moved from the bridge
to Bushido, and an upgraded install needs the Bushido URL and token set to keep
the energy panel. Nothing is migrated for it.) `server/install.test.js` boots real servers for all
three paths (fresh, proxy, existing). Keep it passing.

There is no `examples/` directory and nothing is seeded: `content/` is generic
(USDA foods and chain menus), and there are no timers, jobs or scheduled tasks.
The only background work is a WHOOP refresh on read when the bridge is on, and
The only background work is a WHOOP refresh on read when Bushido is set up, and
resuming Ask AI threads that were mid-run at restart.

## 3. A barcode carries no nutrition, and that is the whole design
Expand Down Expand Up @@ -370,10 +379,17 @@ Two traps:

### WHOOP: under or over (optional)

`GET /api/whoop` mirrors the Totem bridge into `data/whoop.json`, and only when
the bridge is on. **One token holder**: WHOOP rotates its refresh token and
invalidates the old pair, so the bridge holds it and Krakatoa never does. The
cache is **disposable**, and **nothing blocks on it**.
`GET /api/whoop` mirrors Bushido's WHOOP figures into `data/whoop.json`, and
only when Bushido is set up. **One token holder**: WHOOP rotates its refresh
token and invalidates the old pair, so Bushido holds it and Krakatoa never
does. Krakatoa asks with `POST <BUSHIDO_API_URL>/api/whoop/owner`,
`Authorization: Bearer <BUSHIDO_API_TOKEN>` and
`{ "method": "training", "args": [{ "days": N }] }`; Bushido answers
`200 { result }` (the training payload; only `recovery[].calories`, `strain`
and `body.weightLb` are kept) or a non-2xx `{ error, needsReauth?, rateLimited? }`
(409 no WHOOP set up, 403 wrong token, 429 rate limited, 502 WHOOP failed),
whose `error` is shown verbatim. The cache is **disposable**, and **nothing
blocks on it**. Pinned in `server/whoop.test.js`.

The design problem is honesty. `balanceFor` handles it, and the flags are the
feature:
Expand All @@ -385,9 +401,9 @@ feature:
- **`untracked`**: a day with nothing logged is not a 2,800 deficit, it is a day
the app was not opened.

**The refresh button** is the only synchronous path to the bridge. It shows how
stale the number is; **a failed pull keeps the previous numbers** with the
bridge's own error text beside them; with no balance at all, an error still
**The refresh button** is the only synchronous path to Bushido. It shows how
stale the number is; **a failed pull keeps the previous numbers** with
Bushido's own error text beside them; with no balance at all, an error still
renders the panel and the button.

**The panel is a tug of war on one track**: eaten from the left, burned from the
Expand Down Expand Up @@ -580,7 +596,7 @@ the model in 30 KB chunks, three at a time, every item verified. Use the
regional variants, normalise categories, and do not count identical numbers
under another label as a second size.

## 12. Other programs: MCP, and the optional Totem bridge
## 12. Other programs: MCP, the optional Totem bridge, and Bushido

**MCP.** `server/mcp.js` serves MCP Streamable HTTP (JSON replies) at `POST /mcp`,
with a bearer token unless sign-in is left to a proxy. 16 tools: `get_day`,
Expand All @@ -599,16 +615,19 @@ prefix because gateways namespace them (`krakatoa__log_food`).
- **Every tool states all four hints**; deletes are `destructiveHint` and the
descriptions say to ask first. Tested in `server/mcp.test.js`.

**The Totem bridge** (off by default; Settings or `KRAKATOA_TOTEM=1`). Two wires:
**The Totem bridge** (off by default; Settings or `KRAKATOA_TOTEM=1`). One wire:

- **A habit push.** `server/totem.js` posts one record per DAY: calories as
`value`, the macro split as `parts`, the foods as the note, `count` = foods
logged. **One day, one record**, rebuilt from the whole day (per-food syncs made
the last write win). **Fire and forget**: the bridge being down never fails a
log. **The streak is whether the day was TRACKED**, not whether it was a good
day, so bad days still get logged. `node server/totem.js --ensure` creates the
habit once; it is deliberately never called from the request path.
- **WHOOP burn**, read from the bridge (§8).
habit once; it is deliberately never called from the request path. The
Settings Test only reads (`findHabit`).

**Bushido** (off until a URL and token are set): WHOOP burn, read from Bushido,
which holds the WHOOP grant (§8). It used to come through the bridge.

**The digest file** (off by default): every write regenerates
`data/digest.json`: today's foods, a fortnight of totals, targets, the average
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ Formerly called **Fuel** (renamed 2026-10-02).
that it is one tap. Favourites ("stars") pin foods you buy.
- **One screen per food.** It shows the food, a way to fix the entry you tapped,
and every time you have logged it.
- **WHOOP energy balance.** Shows eaten vs. burned on one track. It won't give a
- **WHOOP energy balance** (optional, read from Bushido, which holds the WHOOP
connection). Shows eaten vs. burned on one track. It won't give a
verdict on a day that is still being counted or was never logged, and compares
a partial day against your typical complete day.
- **Water**, with quick-add buttons for common container sizes and a 64 oz
Expand Down Expand Up @@ -83,7 +84,8 @@ server/ Node HTTP server with zero npm dependencies (Node built-ins only)
nutrition.js normalises both databases into one food shape
label.js, ai.js, aithreads.js, learned.js label reader and Ask AI (headless `claude`)
mcp.js MCP Streamable HTTP endpoint
whoop.js, totem.js optional bridge integration (WHOOP burn, habit push)
whoop.js optional WHOOP burn, read from Bushido (which holds the grant)
totem.js optional Totem bridge: the habit push
digest.js compact day rollup written to data/digest.json for other tools
content/ generated data: basics.json (USDA); restaurants.json (chains, optional)
scripts/ generators for content/, with one reader per way a chain publishes
Expand Down
6 changes: 3 additions & 3 deletions app/balance.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ test('a failed pull keeps the numbers AND says why they did not move', () => {

test('with NO balance at all, an error still renders a panel with a way out', () => {
// This is the state someone presses refresh to escape. Rendering nothing would
// leave a bridge that is down looking exactly like a feature that is off.
const html = render(null, { onRefresh: () => {}, whoop: { error: 'no BRIDGE_SECRET found' } })
assert.ok(html.includes('no BRIDGE_SECRET found'))
// leave a Bushido that is down looking exactly like a feature that is off.
const html = render(null, { onRefresh: () => {}, whoop: { error: 'Bushido has no WHOOP connection' } })
assert.ok(html.includes('Bushido has no WHOOP connection'))
assert.ok(html.includes('Refresh from WHOOP'))
// …but no error and no balance is still nothing, as before.
assert.equal(render(null, { onRefresh: () => {}, whoop: { burn: {} } }), '')
Expand Down
2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"test:digest": "node ../server/digest.test.js",
"lint": "eslint src",
"test:combos": "node combos.test.js",
"test:whoop": "node whoop.test.js",
"test:whoop": "node whoop.test.js && node ../server/whoop.test.js",
"test:balance": "esbuild balance.test.jsx --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.balance.mjs --log-level=error && node .balance.mjs",
"test:macros": "node macros.test.js",
"test:restaurants": "node restaurants.test.js",
Expand Down
2 changes: 1 addition & 1 deletion app/src/lib/whoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* background, so a reload is as current as anything needs to be.
*
* `refresh` is the exception, and it is a BUTTON. It is the one synchronous path
* to the bridge — everything else serves the cache and refetches behind itself —
* to Bushido — everything else serves the cache and refetches behind itself —
* because the case it exists for is standing there having just finished a
* workout, wanting the number to catch up now rather than within twenty minutes.
*/
Expand Down
46 changes: 42 additions & 4 deletions app/src/settings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* Krakatoa — Settings.
*
* Everything a new install needs, set up in the browser: the account, the AI,
* the food-database keys, and the optional connection to a Totem bridge. Each
* the food-database keys, and the optional connections to Bushido (WHOOP) and a
* Totem bridge (the habit push). Each
* section saves on its own. A field set by the server's environment is shown
* locked with the variable's name, because the environment always wins and an
* editable box that changes nothing is a lie. Stored secrets never come back
Expand Down Expand Up @@ -300,6 +301,43 @@ function Databases({ s, d, save, test }) {

/* ------------------------------------------------------------- connections */

/* WHOOP's burn, read from Bushido, which holds the WHOOP grant. On when it has
a URL and a token; there is no switch, because there is no default URL. */
function BushidoLink({ s, d, save, test }) {
const [result, setResult] = useState(null)
const b = s.bushido
if (!b) return null
const onSave = async (doTest) => {
setResult({ busy: doTest ? 'Connecting…' : 'Saving…' })
try {
if (d.draft.bushido) await save('bushido')
setResult(doTest ? await test('bushido') : { ok: true, detail: 'Saved.' })
Comment on lines +313 to +314

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh WHOOP state after saving Bushido

When Bushido is configured from this screen after the app has loaded, save() refreshes only /api/me; useWhoop() has already fetched the prior { configured: false, burn: {}, error: null } document and never fetches again. The feature flag therefore enables the energy area, but Balance renders nothing and provides no refresh button; even “Save and connect” refreshes only the server cache. The native screen mirrors this behavior, so both clients require a reload before WHOOP appears. Invalidate or refresh the client WHOOP state after saving/testing Bushido.

AGENTS.md reference: AGENTS.md:L404-L407

Useful? React with 👍 / 👎.

} catch (e) { setResult({ ok: false, detail: e.message }) }
}
return (
<section className="set-section">
<h3 className="list-head"><Plug size={16} /> WHOOP, through Bushido (optional)</h3>
<p className="muted">
For people who also run Bushido, the training app that holds the WHOOP connection. With a Bushido URL and token, the day
shows WHOOP's calorie burn beside what you ate. Without them, Krakatoa never contacts it and the energy panel is hidden.
</p>
<p className="set-pill-row">
<span className={`set-pill ${b.connected ? 'ok' : ''}`}>{b.connected ? 'Connected' : 'Not connected'}</span>
</p>
<Field id="bushido-url" label="Bushido URL" f={b.url} value={d.get('bushido', 'url', b.url.from === 'settings' ? b.url.value : '')}
onChange={d.set('bushido', 'url')} placeholder={b.url.value || 'http://127.0.0.1:8099'}
hint={d.draft.bushido?.url !== undefined ? 'A new URL needs its own token: enter it below. The old one is not sent to a new address.' : null} />
<Field id="bushido-token" label="Bushido API token" f={b.token} value={d.get('bushido', 'token')} onChange={d.set('bushido', 'token')}
placeholder="Bushido's API token" />
<div className="row-btns">
<button className="btn" disabled={!b.connected && !d.draft.bushido} onClick={() => onSave(true)}>{d.draft.bushido ? 'Save and connect' : 'Test'}</button>
<button className="btn btn-primary" disabled={!d.draft.bushido} onClick={() => onSave(false)}>Save</button>
</div>
<Result r={result} />
</section>
)
}

function Connections({ s, d, save, test, saveNow }) {
const [result, setResult] = useState(null)
const t = s.totem
Expand All @@ -315,9 +353,8 @@ function Connections({ s, d, save, test, saveNow }) {
<section className="set-section">
<h3 className="list-head"><Plug size={16} /> Totem bridge (optional)</h3>
<p className="muted">
For people who also run Totem, a personal assistant that holds the WHOOP connection. With the bridge on, the day shows
WHOOP's calorie burn beside what you ate, and each logged day is written to a Totem habit. Off, Krakatoa never contacts it
and the energy panel is hidden.
For people who also run Totem, a personal assistant. With the bridge on, each logged day is written to a Totem habit.
Off, Krakatoa never contacts it.
</p>
<p className="set-pill-row">
<span className={`set-pill ${t.connected ? 'ok' : ''}`}>{t.connected ? 'Connected' : 'Not connected'}</span>
Expand Down Expand Up @@ -445,6 +482,7 @@ export default function SettingsPane({ section = null, onClose }) {
<Account s={s} />
<AISection s={s} d={d} save={save} test={test} />
<Databases s={s} d={d} save={save} test={test} />
<BushidoLink s={s} d={d} save={save} test={test} />
<Connections s={s} d={d} save={save} test={test} saveNow={saveNow} />
<Access s={s} d={d} save={save} saveNow={saveNow} />
</>
Expand Down
4 changes: 2 additions & 2 deletions app/src/today.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ function ago(iso) {
export function Balance({ balance, whoop, onRefresh, refreshing }) {
/*
* The panel renders for the ERROR case even with no balance, because that is
* the state someone presses refresh to get out of: a bridge that is down or a
* the state someone presses refresh to get out of: a Bushido that is down or a
* grant that needs reconnecting says so here, with WHOOP's own wording, rather
* than the card silently not existing.
*/
Expand Down Expand Up @@ -257,7 +257,7 @@ export function Balance({ balance, whoop, onRefresh, refreshing }) {

{/* A failed pull leaves the previous cache in place and carries its reason
alongside — so the numbers above are still real and this says why they
did not move. The bridge's wording travels verbatim because it names
did not move. Bushido's wording (WHOOP's, passed on) travels verbatim because it names
the fix ("reconnect WHOOP", "authorized without read:workout"). */}
{err && (
<p className="balance-verdict muted">
Expand Down
Loading
Loading