Compare commits

..

No commits in common. "main" and "docs/session-framework" have entirely different histories.

456 changed files with 3018 additions and 169786 deletions

View file

@ -32,8 +32,6 @@ Read `docs/architecture-tour.md` first. Then `docs/stream-mvp-plan.md` for decis
LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass` LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass`
entry names or forge URLs. Say "the host", "the release container", "the dev container", "the entry names or forge URLs. Say "the host", "the release container", "the dev container", "the
channel", "the operator"; put the real values in the operator's infra repo. Real values belong channel", "the operator"; put the real values in the operator's infra repo. Real values belong
in an env file outside the checkout — see `infra/env/README.md`. `tools/pii-scan.sh` refuses in an env file outside the checkout — see `infra/env/README.md`. `infra/tests/lint.sh` refuses
the patterns (run by `infra/tests/lint.sh`, `infra/build/tag-release.sh` and the pre-push hook the patterns; the rules live in the operator's infra repo and
from `tools/install-hooks.sh`); the proper nouns it looks for live in the operator's private `infra/tests/de-pii-allow.txt` the few legitimate mentions.
pattern list (`$FLY_PII_PATTERNS`), never here, and `infra/tests/de-pii-allow.txt` lists the few
legitimate mentions. Run `tools/install-hooks.sh` once per clone.

View file

@ -47,15 +47,12 @@ are a `chromium --kiosk` line in a systemd unit and a Playwright test.
| `feed` | ws URL | Feed override for `mode=live`. Default `ws://127.0.0.1:7400/feed`. | | `feed` | ws URL | Feed override for `mode=live`. Default `ws://127.0.0.1:7400/feed`. |
| `gain`, `gamegain`, `sfxgain` | 0..1 | Master / game / SFX gain. Defaults 0.9 / 0.8 / 0.5. | | `gain`, `gamegain`, `sfxgain` | 0..1 | Master / game / SFX gain. Defaults 0.9 / 0.8 / 0.5. |
| `audio` | `0` | Do not create an AudioContext at all. | | `audio` | `0` | Do not create an AudioContext at all. |
| `recovery` | `1`, `0` | Poll `/recovery-notice.json` for the auto-recovery splash. Defaults to on in `live` mode and off in `player` mode, so a fixture screenshot never picks up a stray notice file. |
`window.__stage` exposes the operator surface: `metrics()` (per-stage paint timings), `audio()` `window.__stage` exposes the operator surface: `metrics()` (per-stage paint timings), `audio()`
(context state, ring fill, underruns, drops), `health()` (accepted snapshots, feed gaps, decode (context state, ring fill, underruns, drops), `health()` (accepted snapshots, feed gaps, decode
errors), `manifest()`, `seek(seconds)`, `stopFeed()`, `gameScale()`, `fly()` (renderer mode, gait errors), `manifest()`, `seek(seconds)`, `stopFeed()`, `gameScale()`, `fly()` (renderer mode, gait
phase, leg tips, proboscis extension), `motion()` (which tab and why, the moment on stage and its phase, leg tips, proboscis extension), `motion()` (which tab and why, the moment on stage and its
phase, the queue depth, live particles), `pam()` (the PAM centroid the flare spreads from), and phase, the queue depth, live particles), `pam()` (the PAM centroid the flare spreads from), and
`recovery(notice, nowS?)` (put a recovery notice on the splash by hand, validated like a polled
one, with its clock optionally pinned; `null` clears it), and
`fire(type, label, detail)` — the one deliberate way to drive the moment catalogue by hand, which `fire(type, label, detail)` — the one deliberate way to drive the moment catalogue by hand, which
is what the moment mockups and the moment assertions use instead of waiting for a fixture to is what the moment mockups and the moment assertions use instead of waiting for a fixture to
contain one of each. contain one of each.
@ -98,8 +95,7 @@ Builds, serves, and writes sixteen PNGs to `mockups/`, at 1920x1080 and DPR 1:
`steady-t1-{senses,connectome,ladder}` and `describe` for the four tabs, `big-moment-t1` 2.5 s into that `steady-t1-{senses,connectome,ladder}` and `describe` for the four tabs, `big-moment-t1` 2.5 s into that
fixture's milestone, `moment-{milestone,badge,sugar,rollback}` shot 300 ms after the trigger (the fixture's milestone, `moment-{milestone,badge,sugar,rollback}` shot 300 ms after the trigger (the
middle of every arrival in the catalogue), `macros-{overworld,running,outcome,battle,indoors}` for middle of every arrival in the catalogue), `macros-{overworld,running,outcome,battle,indoors}` for
the macro strip's five states, `recovery-<phase>-<action>` for the auto-recovery splash, and the the macro strip's five states, and the two `fly-*` review crops at 2x. `--only <substring>` shoots
two `fly-*` review crops at 2x. `--only <substring>` shoots
just the ones whose name contains it, which is how one panel gets re-reviewed without rewriting just the ones whose name contains it, which is how one panel gets re-reviewed without rewriting
every committed PNG. every committed PNG.
@ -198,7 +194,6 @@ Four rail panels instead of layout v1's five, on a 12 px gutter; the left column
| CHAT | 1012x244 | The last seven chat lines, or nothing at all | `panels/ChatPanel.tsx` | | CHAT | 1012x244 | The last seven chat lines, or nothing at all | `panels/ChatPanel.tsx` |
| Moment layer | — | Caption band, rail flash, particles, day slide | `panels/MomentLayer.tsx` | | Moment layer | — | Caption band, rail flash, particles, day slide | `panels/MomentLayer.tsx` |
| Stale feed banner | 1824x40 | Over the title strip after 2 s of silence | `panels/StaleBanner.tsx` | | Stale feed banner | 1824x40 | Over the title strip after 2 s of silence | `panels/StaleBanner.tsx` |
| Recovery splash | over the game | The auto-recovery notice: a text box, or the whole game while flysim restarts | `panels/RecoverySplash.tsx` |
### The progress cluster ### The progress cluster
@ -269,52 +264,6 @@ Bot lines green, names amber, text ink: a viewer has to be able to tell the brid
replies from a person at a glance, because the bridge is the only thing on this stream that can be replies from a person at a glance, because the bridge is the only thing on this stream that can be
made to say something by accident. made to say something by accident.
### Recovery splash
`infra/bin/fly-loop-recover` (`infra/docs/loop-recovery.md`) unsticks a confirmed macro loop by
restarting flysim or resetting the run to an earlier rung. Without a word on screen, viewers see
the game freeze and jump. The splash says what is happening, in the Game Boy's own four greens so
it reads as the cartridge's text box, not as a rail panel or an alarm:
| Phase | Layout | Reset copy | Restart copy |
|---|---|---|---|
| `countdown` | Text box over the bottom ~40% of the game, big `M:SS` to `executeAt`, the loop and how long it was stuck. The stuck loop stays visible above it | The fly is stuck in a loop! / Rewinding to the BOULDER BADGE milestone in 0:42 | … / Shaking it off in 0:42 |
| `acting` | Covers the whole 800x720 game panel, which is frozen or blank while flysim is down; a stepped progress bar | Rewinding… / Back to the BOULDER BADGE milestone | Shaking it off… / Same place, fresh start |
| `done` | Text box, 8 s after the helper's `updatedAt` | Back at the BOULDER BADGE milestone! | All shaken off! |
| `failed` | Text box, 20 s | That didn't work / Trying something else next | same |
A reset names its target by the ladder label: a place as is (`PEWTER CITY`), any other rung as
`the BOULDER BADGE milestone`, and the rung the fly is already on as `the start of MT. MOON` (the
ladder's first reset goes back to where it first reached that rung).
**Where the notice comes from.** Not the feed: flysim is the thing being restarted. The helper
writes `/run/fly/wd/recovery-notice.json` atomically (tmp + rename); `flystage-web`
(`infra/config/serve.mjs`, the page's own static server, User=fly, same container, independent of
flysim) serves it at `/recovery-notice.json` — 200 with the bytes, or 204 when there is no file
— and the page polls that once a second (`src/lib/recovery-poll.ts`). `FLY_RECOVERY_NOTICE`
overrides the path, for `serve.mjs` and for the Vite dev and preview servers alike, which serve
the same route.
**It can never break the stream.** `src/lib/recovery.ts` is pure and stateless: a missing,
malformed, oversized (> 16 KiB) or wrong-version file is no splash; a notice whose `updatedAt` is
more than 15 minutes old is ignored; `acting` stops covering the game 10 minutes after its last
write even if the helper never follows up, so a dead helper cannot hide the game; and every
string the helper wrote is clipped to letters, digits, spaces and `.,'&:#/-` at a fixed length
before it can reach the screen. Because the view is a function of the file and the wall clock
alone, a page that reloads mid-recovery shows exactly what one that watched it all would.
To look at it by hand:
```sh
export FLY_RECOVERY_NOTICE=$PWD/.recovery-notice.json # any writable path
npm run dev -w @flybrain/stage # http://127.0.0.1:5273/?recovery=1
npm run recovery-notice -w @flybrain/stage -- --phase countdown --action reset --in 45
npm run recovery-notice -w @flybrain/stage -- --demo restart # 20 s countdown, 15 s acting, done
npm run recovery-notice -w @flybrain/stage -- --clear
```
`npm run mockups -- --only recovery` writes the eight `mockups/recovery-<phase>-<action>.png`.
### Moments ### Moments
`docs/design/animation.md`'s catalogue, wired. The engine (`src/motion/`, landed separately) owns `docs/design/animation.md`'s catalogue, wired. The engine (`src/motion/`, landed separately) owns

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

View file

@ -14,8 +14,7 @@
"test:e2e": "playwright test", "test:e2e": "playwright test",
"mockups": "tsx tools/mockup.mts", "mockups": "tsx tools/mockup.mts",
"fonts": "tsx tools/font-compare.mts", "fonts": "tsx tools/font-compare.mts",
"record": "tsx tools/record-fixture.mts", "record": "tsx tools/record-fixture.mts"
"recovery-notice": "tsx tools/recovery-notice.mts"
}, },
"dependencies": { "dependencies": {
"@flybrain/brain": "*", "@flybrain/brain": "*",

View file

@ -50,8 +50,6 @@ import {
boxStyle, boxStyle,
} from '@/lib/geometry'; } from '@/lib/geometry';
import { stageOptions } from '@/lib/query'; import { stageOptions } from '@/lib/query';
import { parseRecoveryNotice, recoveryView, type RecoveryView } from '@/lib/recovery';
import { RecoveryPoller } from '@/lib/recovery-poll';
import { Director, FLY_HEAD_ANCHOR } from '@/motion/director'; import { Director, FLY_HEAD_ANCHOR } from '@/motion/director';
import { MotionEngine } from '@/motion/engine'; import { MotionEngine } from '@/motion/engine';
import type { MomentType } from '@/motion/moments'; import type { MomentType } from '@/motion/moments';
@ -70,7 +68,6 @@ import { FlyStrip } from '@/panels/FlyStrip';
import { GamePanel } from '@/panels/GamePanel'; import { GamePanel } from '@/panels/GamePanel';
import { MomentLayer } from '@/panels/MomentLayer'; import { MomentLayer } from '@/panels/MomentLayer';
import { ProgressCluster } from '@/panels/ProgressCluster'; import { ProgressCluster } from '@/panels/ProgressCluster';
import { RecoverySplash, nowSeconds, useRecovery } from '@/panels/RecoverySplash';
import { StaleBanner } from '@/panels/StaleBanner'; import { StaleBanner } from '@/panels/StaleBanner';
import { TabSlot } from '@/panels/TabSlot'; import { TabSlot } from '@/panels/TabSlot';
import { TitleStrip } from '@/panels/TitleStrip'; import { TitleStrip } from '@/panels/TitleStrip';
@ -635,14 +632,6 @@ export function App() {
loop.start(); loop.start();
// -- The auto-recovery splash's notice ----------------------------------------------------
// Polled from `flystage-web`, not the feed: flysim is what the helper restarts
// (`src/lib/recovery-poll.ts`). Off in player mode unless `?recovery=1`.
const recoveryPoller = options.recovery
? new RecoveryPoller({ onChange: (notice) => useRecovery.setState({ notice }) })
: null;
recoveryPoller?.start();
// -- Test and operator surface ------------------------------------------------------------ // -- Test and operator surface ------------------------------------------------------------
window.__stage = { window.__stage = {
options, options,
@ -698,37 +687,6 @@ export function App() {
ingest.commit(hot.lastSnapshotMs, true); ingest.commit(hot.lastSnapshotMs, true);
return useStage.getState().chat.length; return useStage.getState().chat.length;
}, },
/**
* Feed reward events into the ticker by hand, `stepMs` of feed time apart, for the ticker
* mockups (a battle's hits, a KO), and settle the dwell gate five seconds after the last.
* The events go through the same `TickerQueue.push` a snapshot's do.
*/
ticker: (events, stepMs = 7000) => {
let at = hot.lastSnapshotMs;
for (const [index, item] of events.entries()) {
at = hot.lastSnapshotMs + index * stepMs;
ingest.queue().push(
{ id: 900_000 + index, wallMs: 0, brainMs: 0, kind: 'reward', label: item.label, value: item.value },
at,
);
}
at += 5000;
ingest.commit(at, true);
return useStage.getState().ticker.map((row) => `${row.label} ${String(row.amount ?? '')}`);
},
/**
* Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the
* splash mockups and e2e assertions. The raw object goes through the same validation as a
* polled file, the poller stops so it cannot overwrite it, and `nowS` pins the splash's clock
* so a countdown screenshot is reproducible. `null` clears it. Returns what the splash shows.
*/
recovery: (raw, nowS) => {
recoveryPoller?.stop();
const notice = raw === null ? null : parseRecoveryNotice(raw);
const pinnedNowS = nowS ?? null;
useRecovery.setState({ notice, pinnedNowS });
return recoveryView(notice, nowSeconds(pinnedNowS));
},
fly: () => ({ fly: () => ({
// The renderer that is actually drawing, which is not always the one that was asked for: // The renderer that is actually drawing, which is not always the one that was asked for:
// `webgl` falls back to `paper` on a host with no usable GL context (`src/fly/index.ts`). // `webgl` falls back to `paper` on a host with no usable GL context (`src/fly/index.ts`).
@ -756,7 +714,6 @@ export function App() {
if (readyTimer !== null) clearTimeout(readyTimer); if (readyTimer !== null) clearTimeout(readyTimer);
loop.stop(); loop.stop();
source?.stop(); source?.stop();
recoveryPoller?.stop();
fly?.dispose(); fly?.dispose();
worker.terminate(); worker.terminate();
void engine?.stop(); void engine?.stop();
@ -782,7 +739,6 @@ export function App() {
<ChatPanel source={options.chat} /> <ChatPanel source={options.chat} />
<MomentLayer particleRef={particleCanvas} /> <MomentLayer particleRef={particleCanvas} />
<RecoverySplash />
<StaleBanner /> <StaleBanner />
</div> </div>
); );
@ -808,10 +764,6 @@ declare global {
fire: (type: MomentType, label?: string, detail?: string) => number | null; fire: (type: MomentType, label?: string, detail?: string) => number | null;
/** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */ /** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */
chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number; chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number;
/** Push reward events into the ticker by hand; returns the rows shown. */
ticker: (events: readonly { label: string; value: number }[], stepMs?: number) => string[];
/** Show a recovery notice by hand (validated like a polled one); null clears it. */
recovery: (notice: unknown, nowS?: number) => RecoveryView | null;
fly: () => { fly: () => {
mode: string; mode: string;
requested: string; requested: string;

View file

@ -89,11 +89,6 @@ export const pokemonRed: GameConfig = {
badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 }, badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 },
}, },
// The fly's own hits (adapter `damage`): several a battle, no protocol kind, so one row per
// battle that counts up. 45 s covers the slowest turn seen (about 7 s from press to payout)
// several times over and is far shorter than the gap between two battles.
hitCopy: { label: 'damage dealt', gapMs: 45_000, tier: 'quiet', koTier: 'notable' },
counters: [ counters: [
{ field: 'badges', label: 'badges', outOf: 8 }, { field: 'badges', label: 'badges', outOf: 8 },
{ field: 'uniqueLocations', label: 'places' }, { field: 'uniqueLocations', label: 'places' },

View file

@ -29,21 +29,6 @@ export interface RewardCopy {
collapsedNoun?: string; collapsedNoun?: string;
} }
/**
* Copy and window for the adapter's per-hit reward, which the protocol has no `rewardKind` for
* (Pokémon Red's `damage`, `HIT #<species> FOR <n> HP[ KO]`). Hits are folded stage-side into one
* row per battle instead of one row per hit.
*/
export interface HitCopy {
/** Row text. Constant; the feed's label is only read for the KO suffix. */
label: string;
/** A row is joined by a hit up to this long after the previous hit folded into it. */
gapMs: number;
/** Tier of the row; a KO raises it to `koTier`. */
tier: RewardTier;
koTier: RewardTier;
}
/** A counter shown in the progress row beside the milestone ladder. */ /** A counter shown in the progress row beside the milestone ladder. */
export interface GameCounter { export interface GameCounter {
/** Which `FeedGame` field to read. */ /** Which `FeedGame` field to read. */
@ -79,8 +64,6 @@ export interface GameConfig {
modeLabels: Record<GameMode, string>; modeLabels: Record<GameMode, string>;
/** Human copy and presentation tier for each reward kind. */ /** Human copy and presentation tier for each reward kind. */
rewardCopy: Record<RewardKind, RewardCopy>; rewardCopy: Record<RewardKind, RewardCopy>;
/** How a reward event with no `rewardKind` that reads as a hit is rolled up. Absent: never. */
hitCopy?: HitCopy;
/** /**
* Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g. * Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g.
* "3/8 badges · 214 places". Per-game *data*, not copy: the values come * "3/8 badges · 214 places". Per-game *data*, not copy: the values come

View file

@ -3,7 +3,6 @@
@import './theme/panels.css'; @import './theme/panels.css';
@import './theme/rail.css'; @import './theme/rail.css';
@import './theme/motion.css'; @import './theme/motion.css';
@import './theme/recovery.css';
/** /**
* Self-hosted OFL faces. `font-display: block` with the default 3 s block period is deliberate: * Self-hosted OFL faces. `font-display: block` with the default 3 s block period is deliberate:

View file

@ -57,12 +57,6 @@ export interface StageOptions {
audio: boolean; audio: boolean;
/** `?metrics=1` keeps the paint-stage histogram and prints it on demand. */ /** `?metrics=1` keeps the paint-stage histogram and prints it on demand. */
metrics: boolean; metrics: boolean;
/**
* Poll `flystage-web` for the auto-recovery notice (`src/lib/recovery.ts`). On by default in
* `live` mode and off in `player` mode, so a fixture screenshot can never pick up a notice file
* that happens to exist on the machine; `?recovery=1` / `?recovery=0` force it either way.
*/
recovery: boolean;
} }
const THEMES: readonly StageTheme[] = ['t1', 't2', 't3']; const THEMES: readonly StageTheme[] = ['t1', 't2', 't3'];
@ -120,7 +114,6 @@ export function parseStageOptions(search: string, defaultFeedUrl = 'ws://127.0.0
}, },
audio: flag(params, 'audio', true), audio: flag(params, 'audio', true),
metrics: flag(params, 'metrics', false), metrics: flag(params, 'metrics', false),
recovery: flag(params, 'recovery', mode === 'live'),
}; };
} }

View file

@ -1,88 +0,0 @@
/**
* Polls `flystage-web` for the recovery notice (`src/lib/recovery.ts`).
*
* Deliberately not the feed: flysim is the thing being restarted, so during `acting` there is no
* feed and no control API to ask. `flystage-web` is the page's own static server, in the same
* container and independent of flysim, and serves the helper's file at
* {@link RECOVERY_NOTICE_ROUTE} (`infra/config/serve.mjs`).
*
* Once a second, with a short timeout, and every failure — no server, a 404 from an older
* `serve.mjs`, a 204 for "no file", a half-written body, a hung request — is "no notice". The
* poller never throws into the page and never retries faster than its interval.
*/
import { RECOVERY_NOTICE_ROUTE, parseRecoveryBody, type RecoveryNotice } from './recovery';
export const RECOVERY_POLL_MS = 1000;
const TIMEOUT_MS = 2500;
type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
export interface RecoveryPollerOptions {
url?: string;
intervalMs?: number;
fetch?: Fetch;
onChange: (notice: RecoveryNotice | null) => void;
}
export class RecoveryPoller {
private readonly url: string;
private readonly intervalMs: number;
private readonly fetchFn: Fetch;
private readonly onChange: (notice: RecoveryNotice | null) => void;
private timer: ReturnType<typeof setTimeout> | null = null;
private stopped = true;
/** The last body seen, so an unchanged file does not re-render the panel. */
private lastKey = '\u0000';
constructor(options: RecoveryPollerOptions) {
this.url = options.url ?? RECOVERY_NOTICE_ROUTE;
this.intervalMs = options.intervalMs ?? RECOVERY_POLL_MS;
this.fetchFn = options.fetch ?? ((input, init) => fetch(input, init));
this.onChange = options.onChange;
}
start(): void {
if (!this.stopped) return;
this.stopped = false;
void this.tick();
}
stop(): void {
this.stopped = true;
if (this.timer !== null) clearTimeout(this.timer);
this.timer = null;
}
/** One poll. Public so the unit tests can drive it without timers. */
async poll(): Promise<RecoveryNotice | null> {
let body = '';
const abort = new AbortController();
const timeout = setTimeout(() => abort.abort(), TIMEOUT_MS);
try {
const response = await this.fetchFn(this.url, { cache: 'no-store', signal: abort.signal });
if (response.status === 200) body = await response.text();
} catch {
body = '';
} finally {
clearTimeout(timeout);
}
const notice = parseRecoveryBody(body);
const key = notice === null ? '' : JSON.stringify(notice);
if (key !== this.lastKey) {
this.lastKey = key;
try {
this.onChange(notice);
} catch (error) {
console.warn(`recovery splash: ${(error as Error).message}`);
}
}
return notice;
}
private async tick(): Promise<void> {
if (this.stopped) return;
await this.poll();
if (this.stopped) return;
this.timer = setTimeout(() => void this.tick(), this.intervalMs);
}
}

View file

@ -1,309 +0,0 @@
/**
* The recovery splash's model: the notice file's contract, its validation, and what the splash
* shows at a given wall-clock second.
*
* `infra/bin/fly-loop-recover` (the auto-unstick helper) writes one small JSON file while it acts
* on a confirmed macro loop — restarting flysim, or resetting the run to an earlier rung — and
* `flystage-web` serves it to this page at {@link RECOVERY_NOTICE_ROUTE}. Viewers otherwise see
* the game freeze or jump for no reason; the splash says what is happening.
*
* Everything here is pure: the poller (`src/lib/recovery-poll.ts`) fetches, the panel
* (`src/panels/RecoverySplash.tsx`) renders, and this file decides. The one rule it exists to
* keep is that **the notice can never break the stream**: a missing, malformed, oversized, future
* or stale file is no notice at all, and every string the helper wrote is clipped to a closed
* character set before it can reach the screen.
*/
/** Where `flystage-web` (and the Vite dev/preview servers) serve the notice file. */
export const RECOVERY_NOTICE_ROUTE = '/recovery-notice.json';
/** Ignore a notice whose `updatedAt` is older than this (the contract: 15 minutes). */
export const RECOVERY_STALE_S = 15 * 60;
/** How long `done` stays up after the helper wrote it. */
export const RECOVERY_DONE_S = 8;
/** How long `failed` stays up after the helper wrote it. */
export const RECOVERY_FAILED_S = 20;
/**
* Stop covering the game this long after an `acting` write, even if the helper never follows up.
* A helper that died mid-recovery must not leave the game hidden behind a splash; with the game
* uncovered again the page's own STALE FEED banner is the honest state.
*/
export const RECOVERY_ACTING_MAX_S = 10 * 60;
/** Tolerated clock skew between the helper's `updatedAt` and the page's clock. */
const FUTURE_SKEW_S = 120;
export type RecoveryPhase = 'countdown' | 'acting' | 'done' | 'failed';
export type RecoveryAction = 'restart' | 'reset';
/** A validated notice. Field names are the file's own; see `infra/docs/loop-recovery.md`. */
export interface RecoveryNotice {
id: string;
phase: RecoveryPhase;
action: RecoveryAction;
fromRung: number | null;
fromLabel: string;
/** Only for `reset`; null otherwise. */
toRung: number | null;
toLabel: string;
reason: string;
loop: string[];
stuckSeconds: number | null;
announcedAt: number;
executeAt: number;
updatedAt: number;
}
const PHASES: readonly RecoveryPhase[] = ['countdown', 'acting', 'done', 'failed'];
const ACTIONS: readonly RecoveryAction[] = ['restart', 'reset'];
/** Longest place name kept (the ladder's longest is 15 characters). */
const LABEL_MAX = 24;
/** Longest macro name kept (the pad's are at most 12, e.g. `GO OBJECTIVE`). */
const MACRO_MAX = 16;
/** At most this many macros of the loop are shown. */
const LOOP_MAX = 4;
/**
* Clip a helper-written string to what the splash may draw: printable ASCII letters, digits,
* spaces and a little punctuation (place names like `MT. MOON` or `S.S. ANNE`, `ROUTE 22`), with
* runs of whitespace collapsed, capped at `max` characters. Anything else is dropped, so a notice
* cannot put markup, control characters or an unbounded line on air.
*/
export function cleanText(value: unknown, max: number): string {
if (typeof value !== 'string') return '';
return value
.replace(/\s+/g, ' ')
.replace(/[^A-Za-z0-9 .,'&:#/-]/g, '')
.replace(/ {2,}/g, ' ')
.trim()
.slice(0, max)
.trim();
}
function finite(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null;
}
function rung(value: unknown): number | null {
const n = finite(value);
return n !== null && Number.isInteger(n) && n >= 0 && n < 1000 ? n : null;
}
/**
* Validate a parsed JSON value as a v1 notice, or return null.
*
* Required: `v === 1`, `id`, a known `phase` and `action`, and finite `announcedAt`, `executeAt`,
* `updatedAt`. Everything else is optional and degrades the copy rather than the notice: a reset
* without a `toLabel` still says it is rewinding, just not to where.
*/
export function parseRecoveryNotice(raw: unknown): RecoveryNotice | null {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null;
const o = raw as Record<string, unknown>;
if (o.v !== 1) return null;
const id = typeof o.id === 'string' ? o.id.slice(0, 64) : '';
if (id === '') return null;
if (!PHASES.includes(o.phase as RecoveryPhase)) return null;
if (!ACTIONS.includes(o.action as RecoveryAction)) return null;
const announcedAt = finite(o.announcedAt);
const executeAt = finite(o.executeAt);
const updatedAt = finite(o.updatedAt);
if (announcedAt === null || executeAt === null || updatedAt === null) return null;
const action = o.action as RecoveryAction;
const loop = Array.isArray(o.loop)
? o.loop
.map((step) => cleanText(step, MACRO_MAX).toUpperCase())
.filter((step) => step !== '')
.slice(0, LOOP_MAX)
: [];
const stuck = finite(o.stuckSeconds);
return {
id,
phase: o.phase as RecoveryPhase,
action,
fromRung: rung(o.fromRung),
fromLabel: cleanText(o.fromLabel, LABEL_MAX).toUpperCase(),
toRung: action === 'reset' ? rung(o.toRung) : null,
toLabel: action === 'reset' ? cleanText(o.toLabel, LABEL_MAX).toUpperCase() : '',
reason: cleanText(o.reason, 32),
loop,
stuckSeconds: stuck !== null && stuck >= 0 ? stuck : null,
announcedAt,
executeAt,
updatedAt,
};
}
/** Parse the body the server returned. Never throws. */
export function parseRecoveryBody(body: string): RecoveryNotice | null {
if (body.length === 0 || body.length > 16_384) return null;
try {
return parseRecoveryNotice(JSON.parse(body));
} catch {
return null;
}
}
/**
* How the splash sits on the stage: `box` is the Pokémon-style text box along the bottom of the
* game, leaving the stuck loop visible above it; `cover` fills the game panel, which is frozen or
* blank while flysim restarts.
*/
export type RecoveryLayout = 'box' | 'cover';
/** What the splash draws. Every string is already final copy. */
export interface RecoveryView {
id: string;
phase: RecoveryPhase;
action: RecoveryAction;
layout: RecoveryLayout;
/** The small chip in the frame's top edge. */
chip: string;
/** The first line, Pokémon-dialogue style. */
headline: string;
/** The second line. */
body: string;
/** `M:SS` during the countdown, otherwise empty. */
countdown: string;
/** `GO OBJECTIVE > GO WARP`, or empty. */
loop: string;
/** `STUCK 30 MIN`, or empty. */
stuck: string;
/** Whether to animate the trailing dots / blinking arrow. */
busy: boolean;
}
/** `0:42`, `1:00`, `12:05`. Negative clamps to `0:00`. */
export function formatCountdown(seconds: number): string {
const s = Math.max(0, Math.ceil(seconds));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
/** `STUCK 30 MIN`, `STUCK 2 H`, `STUCK 1 H 5 MIN`; empty under a minute or when unknown. */
export function formatStuck(seconds: number | null): string {
if (seconds === null || seconds < 60) return '';
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `STUCK ${minutes} MIN`;
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return m === 0 ? `STUCK ${h} H` : `STUCK ${h} H ${m} MIN`;
}
/**
* Whether the notice is showing at `nowS` (epoch seconds), per the contract's lifetimes.
*
* Stateless on purpose: a page that reloads mid-recovery, or a Chromium the watchdog restarted,
* draws exactly what a page that watched the whole thing would, from the file alone.
*/
export function recoveryVisible(notice: RecoveryNotice, nowS: number): boolean {
const age = nowS - notice.updatedAt;
if (age > RECOVERY_STALE_S) return false;
if (age < -FUTURE_SKEW_S) return false;
switch (notice.phase) {
case 'countdown':
return true;
case 'acting':
return age <= RECOVERY_ACTING_MAX_S;
case 'done':
return age <= RECOVERY_DONE_S;
case 'failed':
return age <= RECOVERY_FAILED_S;
}
}
/**
* Ladder rungs (`docs/design/ladder.md`) whose label is a place the fly can be "back at". The rest
* are events (BOULDER BADGE, GOT A STARTER, HM CUT) and read as "the BOULDER BADGE milestone".
*/
const PLACE_RUNGS: ReadonlySet<string> = new Set([
'PALLET TOWN', "OAK'S LAB", 'VIRIDIAN CITY', 'VIRIDIAN FOREST', 'PEWTER CITY', 'MT. MOON',
'CERULEAN CITY', 'NUGGET BRIDGE', 'VERMILION CITY', 'ROCK TUNNEL', 'LAVENDER TOWN',
'CELADON CITY', 'FUCHSIA CITY', 'CINNABAR ISLAND', 'INDIGO PLATEAU',
]);
/**
* Where a reset goes, in words: `PEWTER CITY`, `the BOULDER BADGE milestone`, and `the start of
* MT. MOON` when the target is the rung the fly is already on (the ladder's first reset: it goes
* back to where it first reached that rung). Empty without a label.
*/
export function resetTarget(notice: RecoveryNotice): string {
const label = notice.toLabel;
if (label === '') return '';
const named = PLACE_RUNGS.has(label) ? label : `the ${label} milestone`;
const same = notice.toRung !== null && notice.toRung === notice.fromRung;
return same ? `the start of ${named}` : named;
}
/** The splash at `nowS`, or null when nothing should be on screen. */
export function recoveryView(notice: RecoveryNotice | null, nowS: number): RecoveryView | null {
if (notice === null || !recoveryVisible(notice, nowS)) return null;
const reset = notice.action === 'reset';
const to = resetTarget(notice);
const base = {
id: notice.id,
phase: notice.phase,
action: notice.action,
loop: notice.loop.join(' > '),
stuck: formatStuck(notice.stuckSeconds),
};
switch (notice.phase) {
case 'countdown': {
const remaining = notice.executeAt - nowS;
const now = remaining <= 0;
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: 'The fly is stuck in a loop!',
body: reset
? now
? to !== '' ? `Rewinding to ${to} now` : 'Rewinding now'
: to !== '' ? `Rewinding to ${to} in` : 'Rewinding to the last milestone in'
: now
? 'Shaking it off now'
: 'Shaking it off in',
countdown: formatCountdown(remaining),
busy: now,
};
}
case 'acting':
return {
...base,
layout: 'cover',
chip: 'AUTO RECOVERY',
headline: reset ? 'Rewinding' : 'Shaking it off',
body: reset
? to !== '' ? `Back to ${to}` : 'Back to the last milestone'
: 'Same place, fresh start',
countdown: '',
busy: true,
};
case 'done':
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: reset ? (to !== '' ? `Back at ${to}!` : 'Rewound!') : 'All shaken off!',
body: "Go get 'em, little fly",
countdown: '',
loop: '',
stuck: '',
busy: false,
};
case 'failed':
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: "That didn't work",
body: 'Trying something else next',
countdown: '',
loop: '',
stuck: '',
busy: false,
};
}
}

View file

@ -68,9 +68,6 @@ export const DEFAULT_TICKER_OPTIONS = {
*/ */
const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']); const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']);
/** The adapter's hit label: `HIT #<species> FOR <n> HP` with ` KO` when the hit felled a trainer's Pokémon. */
const HIT_LABEL = /^HIT #\d+ FOR \d+ HP( KO)?$/;
export class TickerQueue { export class TickerQueue {
private readonly visibleRows: number; private readonly visibleRows: number;
private readonly minDwellMs: number; private readonly minDwellMs: number;
@ -80,8 +77,6 @@ export class TickerQueue {
private visible: TickerItem[] = []; private visible: TickerItem[] = [];
private pending: TickerItem[] = []; private pending: TickerItem[] = [];
private lastPromotionMs = Number.NEGATIVE_INFINITY; private lastPromotionMs = Number.NEGATIVE_INFINITY;
/** Feed time of the last hit folded into each hit row, by the row. */
private readonly lastHitMs = new WeakMap<TickerItem, number>();
/** Bumped whenever the visible list changes, so the store can push to React on change only. */ /** Bumped whenever the visible list changes, so the store can push to React on change only. */
private revision = 0; private revision = 0;
@ -111,11 +106,10 @@ export class TickerQueue {
push(event: FeedEvent, nowMs: number): boolean { push(event: FeedEvent, nowMs: number): boolean {
if (HIDDEN_KINDS.has(event.kind)) return false; if (HIDDEN_KINDS.has(event.kind)) return false;
const hit = this.hitOf(event); const tier = this.tierOf(event);
const tier = hit ? this.hitTier(hit.ko) : this.tierOf(event); const label = this.labelOf(event);
const label = hit ? `${this.game.hitCopy?.label ?? event.label}${hit.ko ? ' KO' : ''}` : this.labelOf(event);
const folded = hit ? this.foldHit(event, hit.ko, nowMs) : this.fold(event, nowMs); const folded = this.fold(event, nowMs);
if (folded) return true; if (folded) return true;
const item: TickerItem = { const item: TickerItem = {
@ -131,8 +125,6 @@ export class TickerQueue {
...(event.by === undefined ? {} : { by: event.by }), ...(event.by === undefined ? {} : { by: event.by }),
}; };
if (hit) this.lastHitMs.set(item, nowMs);
if (tier === 'moment') { if (tier === 'moment') {
// Jump the gate: the badge is the reason anyone is watching. // Jump the gate: the badge is the reason anyone is watching.
this.promote(item, nowMs); this.promote(item, nowMs);
@ -184,42 +176,6 @@ export class TickerQueue {
return false; return false;
} }
/** Is this a hit the game rolls up? Only a reward with no `rewardKind` and the adapter's own label. */
private hitOf(event: FeedEvent): { ko: boolean } | null {
if (!this.game.hitCopy || event.kind !== 'reward' || event.rewardKind) return null;
const match = HIT_LABEL.exec(event.label);
return match ? { ko: match[1] !== undefined } : null;
}
private hitTier(ko: boolean): TickerTier {
const copy = this.game.hitCopy;
return copy ? (ko ? copy.koTier : copy.tier) : 'quiet';
}
/**
* Fold a hit into the battle's row: the newest hit row whose last hit is within `gapMs`. The
* window slides with each hit (unlike `fold`'s, which is from creation) because a battle has
* no fixed length; a row that has left the panel is not resurrected, the next hit starts one.
* The row shows the summed reward, a `x<n>` count and a KO once any hit in it felled a Pokémon.
*/
private foldHit(event: FeedEvent, ko: boolean, nowMs: number): boolean {
const copy = this.game.hitCopy;
if (!copy) return false;
for (const item of [...this.visible, ...this.pending]) {
const last = this.lastHitMs.get(item);
if (last === undefined || nowMs - last > copy.gapMs) continue;
item.count += 1;
if (event.value !== undefined) item.amount = (item.amount ?? 0) + event.value;
const knocked = ko || item.label.endsWith(' KO');
item.label = `${copy.label} x${item.count}${knocked ? ' KO' : ''}`;
if (knocked) item.tier = copy.koTier;
this.lastHitMs.set(item, nowMs);
this.revision += 1;
return true;
}
return false;
}
private tierOf(event: FeedEvent): TickerTier { private tierOf(event: FeedEvent): TickerTier {
if (event.kind === 'reward' && event.rewardKind) { if (event.kind === 'reward' && event.rewardKind) {
return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet'; return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet';

View file

@ -1,129 +0,0 @@
import { useEffect, useState } from 'react';
import { create } from 'zustand';
import { LAYOUT, boxStyle } from '@/lib/geometry';
import { recoveryView, type RecoveryNotice, type RecoveryView } from '@/lib/recovery';
/**
* The auto-recovery splash, over the game panel.
*
* `infra/bin/fly-loop-recover` announces a recovery a minute before it acts, then restarts flysim
* or resets the run to an earlier rung; without this, viewers see the game freeze and jump for no
* reason. The model is `src/lib/recovery.ts`, the data path `src/lib/recovery-poll.ts`.
*
* Two layouts, both in the Game Boy's own four greens, so it reads as the cartridge's text box
* rather than as one more rail panel:
*
* - **box** (countdown, done, failed): a Pokémon-style text box across the bottom of the game,
* with the countdown beside it. The top two thirds of the game stay visible, because the stuck
* loop is the thing the countdown is about.
* - **cover** (acting): the whole game panel, because the picture there is frozen or blank while
* flysim restarts.
*
* It re-renders at 4 Hz while a notice is held — the stage's own React cadence — and not at all
* otherwise. The countdown is wall-clock arithmetic against the helper's `executeAt`, which is why
* the page needs nothing but the file: it is right after a reload, and while the feed is down.
*/
export const useRecovery = create<{ notice: RecoveryNotice | null; pinnedNowS: number | null }>(() => ({
notice: null,
pinnedNowS: null,
}));
const TICK_MS = 250;
export function nowSeconds(pinned: number | null): number {
return pinned ?? Date.now() / 1000;
}
export function RecoverySplash() {
const notice = useRecovery((state) => state.notice);
const pinned = useRecovery((state) => state.pinnedNowS);
const [nowS, setNowS] = useState(() => nowSeconds(pinned));
useEffect(() => {
setNowS(nowSeconds(pinned));
if (notice === null || pinned !== null) return;
const timer = setInterval(() => setNowS(nowSeconds(null)), TICK_MS);
return () => clearInterval(timer);
}, [notice, pinned]);
let view: RecoveryView | null = null;
try {
view = recoveryView(notice, nowS);
} catch {
view = null;
}
if (view === null) return null;
return (
<div
className="recovery"
data-testid="recovery-splash"
data-phase={view.phase}
data-action={view.action}
data-layout={view.layout}
style={{ ...boxStyle(LAYOUT.game), zIndex: 50 }}
>
{view.layout === 'cover' ? <Cover view={view} /> : <Box view={view} />}
</div>
);
}
function LoopLine({ view }: { view: RecoveryView }) {
if (view.loop === '' && view.stuck === '') return null;
return (
<div className="recovery__loop" data-testid="recovery-loop">
{view.loop !== '' ? <span className="recovery__loop-macros">{view.loop}</span> : null}
{view.loop !== '' && view.stuck !== '' ? <span className="recovery__sep" aria-hidden /> : null}
{view.stuck !== '' ? <span>{view.stuck}</span> : null}
</div>
);
}
function Box({ view }: { view: RecoveryView }) {
return (
<div className="recovery__box">
<span className="recovery__chip">{view.chip}</span>
<div className="recovery__row">
<div className="recovery__text">
<p className="recovery__headline" data-testid="recovery-headline">
{view.headline}
</p>
<p className="recovery__body" data-testid="recovery-body">
{view.body}
{view.busy ? <span className="recovery__dots" aria-hidden /> : null}
</p>
</div>
{view.countdown !== '' ? (
<div className="recovery__countdown" data-testid="recovery-countdown">
{view.countdown}
</div>
) : null}
</div>
<LoopLine view={view} />
<span className="recovery__arrow" aria-hidden />
</div>
);
}
function Cover({ view }: { view: RecoveryView }) {
return (
<div className="recovery__cover">
<span className="recovery__chip recovery__chip--cover">{view.chip}</span>
<p className="recovery__big" data-testid="recovery-headline">
{view.headline}
<span className="recovery__dots" aria-hidden />
</p>
<p className="recovery__body recovery__body--cover" data-testid="recovery-body">
{view.body}
</p>
<div className={`recovery__bar recovery__bar--${view.action}`} aria-hidden>
{Array.from({ length: 8 }, (_, index) => (
<span key={index} style={{ animationDelay: `${index * 150}ms` }} />
))}
</div>
<div className="recovery__was">{view.loop !== '' ? 'IT WAS LOOPING ON' : null}</div>
<LoopLine view={view} />
</div>
);
}

View file

@ -1,230 +0,0 @@
/**
* The auto-recovery splash (`src/panels/RecoverySplash.tsx`), over the 800x720 game panel.
*
* Its own palette on purpose: the Game Boy's four greens, so the splash reads as the cartridge's
* own text box / screen and never as a rail panel or an alarm. Square corners, a 4 px outer frame
* and a 2 px inner line, like every other box on the page (`tokens.css`). Type sits on the page's
* floors: Press Start 2P for the dialogue line and the countdown, VT323 for the rest.
*/
.recovery {
--gb-0: #e0f0c8; /* lightest: the paper */
--gb-1: #8bac0f;
--gb-2: #306230;
--gb-3: #0f380f; /* darkest: the ink */
pointer-events: none;
}
/* -- Box: countdown, done, failed ---------------------------------------------------------- */
.recovery__box {
position: absolute;
left: 16px;
right: 16px;
bottom: 16px;
padding: 30px 28px 20px;
background: var(--gb-0);
color: var(--gb-3);
border: var(--border-w) solid var(--gb-3);
outline: var(--border-inner-w) solid var(--gb-0);
outline-offset: calc(-1 * var(--border-w) - 6px);
box-shadow: inset 0 0 0 10px var(--gb-0), inset 0 0 0 12px var(--gb-2);
animation: recovery-rise 320ms var(--ease-pixel, steps(8, end)) both;
}
.recovery__chip {
position: absolute;
top: -18px;
left: 24px;
padding: 2px 12px;
font-family: var(--font-label);
font-size: var(--fs-body);
line-height: 28px;
background: var(--gb-3);
color: var(--gb-0);
letter-spacing: 0.04em;
}
.recovery__row {
display: flex;
align-items: center;
gap: 24px;
}
.recovery__text {
flex: 1 1 auto;
min-width: 0;
}
.recovery__headline {
margin: 0 0 14px;
font-family: var(--font-pixel);
font-size: 24px;
line-height: 1.45;
}
.recovery__body {
margin: 0;
font-family: var(--font-text);
font-size: 40px;
line-height: 1.05;
color: var(--gb-2);
}
.recovery__countdown {
flex: 0 0 auto;
font-family: var(--font-pixel);
font-size: 52px;
line-height: 1;
padding: 16px 14px 12px;
background: var(--gb-3);
color: var(--gb-0);
font-variant-numeric: tabular-nums;
}
.recovery__loop {
margin-top: 14px;
font-family: var(--font-text);
font-size: 30px;
line-height: 1;
color: var(--gb-2);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.recovery__loop-macros {
color: var(--gb-3);
}
.recovery__sep {
display: inline-block;
width: 8px;
height: 8px;
margin: 0 14px;
vertical-align: middle;
background: var(--gb-1);
}
/* The Pokémon "more text" arrow, blinking in the corner. Drawn, not typed: no glyph to miss. */
.recovery__arrow {
position: absolute;
right: 22px;
bottom: 16px;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 12px solid var(--gb-3);
animation: recovery-blink 1s steps(1, end) infinite;
}
/* Three dots that count up, for "working on it". Steps, not a fade. */
.recovery__dots::after {
content: '...';
display: inline-block;
width: 3ch;
overflow: hidden;
vertical-align: bottom;
text-align: left;
animation: recovery-dots 1.2s steps(4, jump-none) infinite;
}
/* -- Cover: acting --------------------------------------------------------------------------- */
.recovery__cover {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 28px;
padding: 40px;
background: var(--gb-0);
color: var(--gb-3);
border: var(--border-w) solid var(--gb-3);
box-shadow: inset 0 0 0 12px var(--gb-0), inset 0 0 0 16px var(--gb-2);
text-align: center;
}
.recovery__chip--cover {
position: static;
}
.recovery__big {
margin: 0;
font-family: var(--font-pixel);
font-size: 44px;
line-height: 1.3;
}
.recovery__body--cover {
font-size: 48px;
}
.recovery__was {
margin-top: 8px;
font-family: var(--font-label);
font-size: var(--fs-body);
color: var(--gb-2);
min-height: 1px;
}
.recovery__cover .recovery__loop {
margin-top: 0;
max-width: 100%;
}
/* Eight cells lighting in turn: right-to-left for a rewind, left-to-right for a restart. */
.recovery__bar {
display: flex;
gap: 8px;
}
.recovery__bar--reset {
flex-direction: row-reverse;
}
.recovery__bar span {
width: 40px;
height: 24px;
background: var(--gb-1);
animation: recovery-cell 1.2s steps(1, end) infinite;
}
@keyframes recovery-rise {
from {
transform: translateY(24px);
opacity: 0;
}
to {
transform: none;
opacity: 1;
}
}
@keyframes recovery-blink {
50% {
visibility: hidden;
}
}
@keyframes recovery-dots {
from {
width: 0;
}
to {
width: 3ch;
}
}
@keyframes recovery-cell {
0%,
12% {
background: var(--gb-3);
}
13%,
100% {
background: var(--gb-1);
}
}

View file

@ -1,138 +0,0 @@
/**
* The auto-recovery splash, against the real build.
*
* The first two tests go through the page's real data path — the poller fetching
* `/recovery-notice.json` — with Playwright answering the route, which is exactly what
* `flystage-web` does with the helper's file. The rest drive the splash through
* `window.__stage.recovery` with a pinned clock, for the geometry and the text floor.
*/
import { expect, test, type Page } from '@playwright/test';
import { stageUrl } from './stage';
const now = (): number => Math.floor(Date.now() / 1000);
function notice(overrides: Record<string, unknown> = {}): Record<string, unknown> {
const t = now();
return {
v: 1,
id: `${t}-reset`,
phase: 'countdown',
action: 'reset',
fromRung: 12,
fromLabel: 'MT. MOON',
toRung: 11,
toLabel: 'PEWTER CITY',
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: t,
executeAt: t + 45,
updatedAt: t,
...overrides,
};
}
async function open(page: Page): Promise<void> {
await page.goto(`${stageUrl({ t: 95, tab: 'senses', audio: false })}&recovery=1`);
await page.waitForSelector('html[data-ready="1"]', { timeout: 60_000 });
}
test('a polled notice shows the countdown, follows the phases and clears', async ({ page }) => {
let body: string | null = JSON.stringify(notice());
await page.route('**/recovery-notice.json', (route) =>
body === null
? route.fulfill({ status: 204 })
: route.fulfill({ status: 200, contentType: 'application/json', body }),
);
await open(page);
const splash = page.getByTestId('recovery-splash');
await expect(splash).toBeVisible({ timeout: 10_000 });
await expect(splash).toHaveAttribute('data-phase', 'countdown');
await expect(splash).toHaveAttribute('data-layout', 'box');
await expect(page.getByTestId('recovery-countdown')).toHaveText(/^0:4\d$/);
await expect(page.getByTestId('recovery-body')).toContainText('Rewinding to PEWTER CITY');
await expect(page.getByTestId('recovery-loop')).toContainText('GO OBJECTIVE > GO WARP');
body = JSON.stringify(notice({ phase: 'acting' }));
await expect(splash).toHaveAttribute('data-layout', 'cover', { timeout: 5_000 });
body = JSON.stringify(notice({ phase: 'done' }));
await expect(splash).toHaveAttribute('data-phase', 'done', { timeout: 5_000 });
// The file going away is also an end: the page never holds a notice the server no longer has.
body = null;
await expect(splash).toHaveCount(0, { timeout: 5_000 });
});
test('stale, malformed and missing notices never show', async ({ page }) => {
const bodies = [
JSON.stringify(notice({ updatedAt: now() - 16 * 60 })),
'{"v":1,"phase":"countdown"',
JSON.stringify(notice({ v: 2 })),
JSON.stringify(notice({ phase: 'done', updatedAt: now() - 60 })),
];
let index = 0;
await page.route('**/recovery-notice.json', (route) => {
const body = bodies[Math.min(index, bodies.length - 1)] as string;
index += 1;
return route.fulfill({ status: 200, contentType: 'application/json', body });
});
await open(page);
await expect.poll(() => index, { timeout: 10_000 }).toBeGreaterThan(bodies.length);
await expect(page.getByTestId('recovery-splash')).toHaveCount(0);
});
test('player mode does not poll unless asked', async ({ page }) => {
let hits = 0;
await page.route('**/recovery-notice.json', (route) => {
hits += 1;
return route.fulfill({ status: 204 });
});
await page.goto(stageUrl({ t: 95, tab: 'senses', audio: false }));
await page.waitForSelector('html[data-ready="1"]', { timeout: 60_000 });
await page.waitForTimeout(2500);
expect(hits).toBe(0);
});
test('the box leaves the top of the game clear; the cover stays inside the game', async ({ page }) => {
await open(page);
const game = await page.getByTestId('game').boundingBox();
if (!game) throw new Error('no game box');
const t = 1_790_629_095;
const base = notice({ announcedAt: t, executeAt: t + 60, updatedAt: t });
await page.evaluate(([raw, nowS]) => window.__stage?.recovery(raw, nowS as number), [base, t + 18] as const);
// Measure after the 320 ms rise, not during it.
await page.locator('.recovery__box').evaluate((element) =>
Promise.all(element.getAnimations().map((animation) => animation.finished)).then(() => undefined),
);
const box = await page.locator('.recovery__box').boundingBox();
if (!box) throw new Error('no text box');
expect(box.y).toBeGreaterThan(game.y + game.height / 2);
expect(box.x).toBeGreaterThanOrEqual(game.x);
expect(box.x + box.width).toBeLessThanOrEqual(game.x + game.width);
expect(box.y + box.height).toBeLessThanOrEqual(game.y + game.height);
await expect(page.getByTestId('recovery-countdown')).toHaveText('0:42');
await page.evaluate(
([raw, nowS]) => window.__stage?.recovery(raw, nowS as number),
[{ ...base, phase: 'acting', updatedAt: t + 60 }, t + 70] as const,
);
const cover = await page.locator('.recovery__cover').boundingBox();
if (!cover) throw new Error('no cover');
expect(cover).toEqual(game);
// Every run of text on the splash sits on the page's body floor.
const sizes = await page.evaluate(() =>
[...document.querySelectorAll('[data-testid="recovery-splash"] *')]
.filter((element) => [...element.childNodes].some((node) => node.nodeType === 3 && node.textContent?.trim()))
.map((element) => Number.parseFloat(getComputedStyle(element).fontSize)),
);
expect(sizes.length).toBeGreaterThan(3);
for (const size of sizes) expect(size).toBeGreaterThanOrEqual(24);
await page.evaluate(() => window.__stage?.recovery(null));
await expect(page.getByTestId('recovery-splash')).toHaveCount(0);
});

View file

@ -1,274 +0,0 @@
/**
* The recovery splash's model, poller and server route.
*
* The one property every test here protects: the notice file can never break the stream. A
* missing, malformed, stale or hostile file is no splash, and a good one shows exactly the
* contract's lifetimes (countdown until acting, acting while flysim is down, done ~8 s, failed
* briefly) from the file alone.
*/
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { parseStageOptions } from '../../src/lib/query';
import {
RECOVERY_ACTING_MAX_S,
RECOVERY_DONE_S,
RECOVERY_FAILED_S,
RECOVERY_STALE_S,
cleanText,
formatCountdown,
formatStuck,
parseRecoveryBody,
parseRecoveryNotice,
recoveryView,
} from '../../src/lib/recovery';
import { RecoveryPoller } from '../../src/lib/recovery-poll';
const T = 1_790_629_095;
function notice(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
v: 1,
id: `${T}-reset`,
phase: 'countdown',
action: 'reset',
fromRung: 12,
fromLabel: 'MT. MOON',
toRung: 11,
toLabel: 'PEWTER CITY',
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: T,
executeAt: T + 60,
updatedAt: T,
...overrides,
};
}
const view = (raw: Record<string, unknown>, now: number) => recoveryView(parseRecoveryNotice(raw), now);
test('the contract example parses', () => {
const parsed = parseRecoveryNotice(notice());
assert.ok(parsed);
assert.equal(parsed.phase, 'countdown');
assert.equal(parsed.action, 'reset');
assert.equal(parsed.toLabel, 'PEWTER CITY');
assert.equal(parsed.fromLabel, 'MT. MOON');
assert.deepEqual(parsed.loop, ['GO OBJECTIVE', 'GO WARP']);
});
test('anything malformed is no notice at all', () => {
const bad: unknown[] = [
null,
42,
'x',
[],
notice({ v: 2 }),
notice({ v: '1' }),
notice({ id: '' }),
notice({ id: 7 }),
notice({ phase: 'panic' }),
notice({ action: 'reboot' }),
notice({ executeAt: 'soon' }),
notice({ updatedAt: Number.NaN }),
notice({ announcedAt: undefined }),
];
for (const raw of bad) assert.equal(parseRecoveryNotice(raw), null, JSON.stringify(raw));
for (const body of ['', '{', 'null', '{"v":1}', 'x'.repeat(20_000)]) assert.equal(parseRecoveryBody(body), null);
assert.ok(parseRecoveryBody(JSON.stringify(notice())));
});
test('optional fields degrade the copy, not the notice', () => {
const bare = view({ v: 1, id: 'a', phase: 'countdown', action: 'reset', announcedAt: T, executeAt: T + 30, updatedAt: T }, T);
assert.ok(bare);
assert.equal(bare.body, 'Rewinding to the last milestone in');
assert.equal(bare.loop, '');
assert.equal(bare.stuck, '');
});
test('helper strings are clipped to a closed character set', () => {
assert.equal(cleanText('<img src=x onerror=alert(1)>', 24), 'img srcx onerroralert1');
assert.equal(cleanText('S.S. ANNE', 24), 'S.S. ANNE');
assert.equal(cleanText(' ROUTE\n\t22 ', 24), 'ROUTE 22');
assert.equal(cleanText('A'.repeat(100), 24).length, 24);
assert.equal(cleanText(12, 24), '');
const parsed = parseRecoveryNotice(notice({ loop: ['go objective', 5, '', 'A', 'B', 'C', 'D'], toLabel: 'pewter\u0000city' }));
assert.ok(parsed);
assert.deepEqual(parsed.loop, ['GO OBJECTIVE', 'A', 'B', 'C']);
assert.equal(parsed.toLabel, 'PEWTERCITY');
// A restart has no destination, whatever the file says.
assert.equal(parseRecoveryNotice(notice({ action: 'restart' }))?.toLabel, '');
});
test('countdown: the text box with M:SS to executeAt, reset and restart copy differ', () => {
const reset = view(notice(), T + 18);
assert.ok(reset);
assert.equal(reset.layout, 'box');
assert.equal(reset.countdown, '0:42');
assert.equal(reset.headline, 'The fly is stuck in a loop!');
assert.equal(reset.body, 'Rewinding to PEWTER CITY in');
assert.equal(reset.loop, 'GO OBJECTIVE > GO WARP');
assert.equal(reset.stuck, 'STUCK 30 MIN');
const restart = view(notice({ action: 'restart' }), T);
assert.ok(restart);
assert.equal(restart.body, 'Shaking it off in');
assert.equal(restart.countdown, '1:00');
// Past executeAt but not yet acting: say "now", never a negative clock.
const late = view(notice(), T + 75);
assert.ok(late);
assert.equal(late.countdown, '0:00');
assert.equal(late.body, 'Rewinding to PEWTER CITY now');
assert.equal(late.busy, true);
});
test('acting: covers the game while flysim is down, and gives up after a cap', () => {
const acting = notice({ phase: 'acting', updatedAt: T + 60 });
const reset = view(acting, T + 90);
assert.ok(reset);
assert.equal(reset.layout, 'cover');
assert.equal(reset.headline, 'Rewinding');
assert.equal(reset.body, 'Back to PEWTER CITY');
const restart = view({ ...acting, action: 'restart' }, T + 90);
assert.equal(restart?.headline, 'Shaking it off');
assert.equal(view(acting, T + 60 + RECOVERY_ACTING_MAX_S + 1), null);
});
test('a rung that is not a place reads as a milestone, and the current rung as its start', () => {
const badge = notice({ toRung: 11, toLabel: 'BOULDER BADGE' });
assert.equal(view(badge, T + 18)?.body, 'Rewinding to the BOULDER BADGE milestone in');
assert.equal(view({ ...badge, phase: 'acting' }, T + 63)?.body, 'Back to the BOULDER BADGE milestone');
assert.equal(view({ ...badge, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the BOULDER BADGE milestone!');
const same = notice({ toRung: 12, toLabel: 'MT. MOON' });
assert.equal(view(same, T + 18)?.body, 'Rewinding to the start of MT. MOON in');
assert.equal(view({ ...same, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the start of MT. MOON!');
assert.equal(view({ ...same, toLabel: 'BOULDER BADGE', toRung: 12, fromRung: 12 }, T + 18)?.body,
'Rewinding to the start of the BOULDER BADGE milestone in');
});
test('done shows about 8 s, failed a little longer, then both clear', () => {
const done = notice({ phase: 'done', updatedAt: T + 120 });
assert.equal(view(done, T + 120)?.headline, 'Back at PEWTER CITY!');
assert.equal(view({ ...done, action: 'restart' }, T + 121)?.headline, 'All shaken off!');
assert.ok(view(done, T + 120 + RECOVERY_DONE_S));
assert.equal(view(done, T + 120 + RECOVERY_DONE_S + 1), null);
const failed = notice({ phase: 'failed', updatedAt: T + 120 });
assert.equal(view(failed, T + 125)?.body, 'Trying something else next');
assert.equal(view(failed, T + 120 + RECOVERY_FAILED_S + 1), null);
});
test('a notice older than 15 minutes, or from the far future, is ignored', () => {
assert.ok(view(notice(), T + RECOVERY_STALE_S));
assert.equal(view(notice(), T + RECOVERY_STALE_S + 1), null);
assert.equal(view(notice(), T - 3600), null);
});
test('formatting', () => {
assert.equal(formatCountdown(59.2), '1:00');
assert.equal(formatCountdown(5), '0:05');
assert.equal(formatCountdown(725), '12:05');
assert.equal(formatCountdown(-3), '0:00');
assert.equal(formatStuck(null), '');
assert.equal(formatStuck(30), '');
assert.equal(formatStuck(1800), 'STUCK 30 MIN');
assert.equal(formatStuck(7200), 'STUCK 2 H');
assert.equal(formatStuck(3900), 'STUCK 1 H 5 MIN');
});
test('the page polls in live mode, not in player mode, unless told', () => {
assert.equal(parseStageOptions('?mode=live').recovery, true);
assert.equal(parseStageOptions('').recovery, false);
assert.equal(parseStageOptions('?recovery=1').recovery, true);
assert.equal(parseStageOptions('?mode=live&recovery=0').recovery, false);
});
test('the poller turns every failure into "no notice" and reports changes once', async () => {
const seen: (string | null)[] = [];
let reply: () => Promise<Response> = () => Promise.resolve(new Response(JSON.stringify(notice()), { status: 200 }));
const poller = new RecoveryPoller({
fetch: () => reply(),
onChange: (n) => seen.push(n === null ? null : n.phase),
});
assert.equal((await poller.poll())?.phase, 'countdown');
await poller.poll(); // unchanged: no second callback
reply = () => Promise.resolve(new Response(null, { status: 204 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response('{"v":1,', { status: 200 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response('not found', { status: 404 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.reject(new Error('ECONNREFUSED'));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response(JSON.stringify(notice({ phase: 'acting' })), { status: 200 }));
assert.equal((await poller.poll())?.phase, 'acting');
assert.deepEqual(seen, ['countdown', null, 'acting']);
});
test('the poller survives a throwing listener', async () => {
const poller = new RecoveryPoller({
fetch: () => Promise.resolve(new Response(JSON.stringify(notice()), { status: 200 })),
onChange: () => {
throw new Error('boom');
},
});
const warn = console.warn;
console.warn = () => {};
try {
assert.equal((await poller.poll())?.phase, 'countdown');
} finally {
console.warn = warn;
}
});
test('flystage-web serves the notice file at /recovery-notice.json, 204 without one', async () => {
const here = dirname(fileURLToPath(import.meta.url));
const serve = resolve(here, '../../../../infra/config/serve.mjs');
const dir = await mkdtemp(join(tmpdir(), 'recovery-notice-'));
const file = join(dir, 'recovery-notice.json');
const child = spawn(process.execPath, [serve, dir, '127.0.0.1', '0'], {
env: { ...process.env, FLY_RECOVERY_NOTICE: file },
stdio: ['ignore', 'pipe', 'inherit'],
});
try {
const base = await new Promise<string>((done, fail) => {
let out = '';
child.stdout.on('data', (chunk: Buffer) => {
out += chunk.toString();
const match = /(http:\/\/127\.0\.0\.1:\d+)\//.exec(out);
if (match?.[1]) done(match[1]);
});
child.on('exit', () => fail(new Error(`serve.mjs exited: ${out}`)));
});
const missing = await fetch(`${base}/recovery-notice.json`);
assert.equal(missing.status, 204);
assert.equal(missing.headers.get('cache-control'), 'no-store');
const body = JSON.stringify(notice());
await writeFile(file, body);
const present = await fetch(`${base}/recovery-notice.json?t=1`);
assert.equal(present.status, 200);
assert.equal(await present.text(), body);
await writeFile(file, 'x'.repeat(20_000));
assert.equal((await fetch(`${base}/recovery-notice.json`)).status, 204, 'oversized files are not served');
// The static half still works, and the notice is not reachable any other way.
await writeFile(join(dir, 'index.html'), '<p>stage</p>');
assert.equal(await (await fetch(`${base}/`)).text(), '<p>stage</p>');
} finally {
child.kill('SIGTERM');
await rm(dir, { recursive: true, force: true });
}
});

View file

@ -147,41 +147,3 @@ test('the platformer config paces the same way with different copy', async () =>
queue.push(reward('explore'), 100); queue.push(reward('explore'), 100);
assert.equal(queue.items()[0]?.label, '2 new ground'); assert.equal(queue.items()[0]?.label, '2 new ground');
}); });
function hit(hp: number, value: number, ko = false): FeedEvent {
return event('reward', `HIT #59 FOR ${hp} HP${ko ? ' KO' : ''}`, { value });
}
test('a battle\'s hits fold into one damage row that sums and counts', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(9, 0.05), 7_000);
queue.push(hit(4, 0.03), 15_000);
assert.equal(queue.items().length, 1);
const row = queue.items()[0];
assert.equal(row?.label, 'damage dealt x3');
assert.equal(row?.count, 3);
assert.ok(Math.abs((row?.amount ?? 0) - 0.14) < 1e-9);
assert.equal(row?.tier, 'quiet');
});
test('a KO marks the row and raises its tier; the window slides, then a new battle is a new row', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(5, 0.08, true), 30_000);
assert.equal(queue.items()[0]?.label, 'damage dealt x2 KO');
assert.equal(queue.items()[0]?.tier, 'notable');
queue.push(hit(3, 0.02), 70_000);
assert.equal(queue.items().length, 1, 'still inside 45 s of the last hit');
queue.push(hit(3, 0.02), 200_000);
assert.equal(queue.items().length, 2, 'a later battle gets its own row');
assert.equal(queue.items()[0]?.label, 'damage dealt');
});
test('a hit is not confused with other rewards, and a lone KO says so', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(31, 0.25, true), 0);
assert.equal(queue.items()[0]?.label, 'damage dealt KO');
queue.push(event('reward', 'NEW MAP', { value: 0.1 }), 10);
assert.equal(queue.items().length, 2, 'an unrelated no-kind reward keeps its own row');
});

View file

@ -24,8 +24,6 @@
* macros-center.png wide pad with both of its columns filled * macros-center.png wide pad with both of its columns filled
* macros-tab.png * macros-tab.png
* pad-strip.png * pad-strip.png
* recovery-{countdown,acting,done,failed}-{reset,restart}.png
* the auto-recovery splash, each phase and both actions
* *
* T1 Instrument is the chosen theme (`docs/stream-mvp-plan.md`, decisions 2026-09-15 evening), so * T1 Instrument is the chosen theme (`docs/stream-mvp-plan.md`, decisions 2026-09-15 evening), so
* the theme sweep the first gate needed is gone: what these images are for now is the *layout* and * the theme sweep the first gate needed is gone: what these images are for now is the *layout* and
@ -93,31 +91,6 @@ const CHAT_WRAP: { by: string; text: string; bot?: boolean }[] = [
}, },
]; ];
/**
* The ticker in a battle (row 68): the fly's hits arrive as `HIT #<species> FOR <n> HP` rewards and
* fold into one "damage dealt" row. Injected by hand through `window.__stage.ticker`, seven feed
* seconds apart, because no fixture holds a battle recorded on adapter v8.
*/
const TICKER_SHOTS: { name: string; events: { label: string; value: number }[] }[] = [
{
name: 'row68-ticker-hits',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
],
},
{
name: 'row68-ticker-ko',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 12 HP KO', value: 0.13 },
],
},
];
const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [ const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [
{ name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' }, { name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' },
{ name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' }, { name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' },
@ -169,34 +142,6 @@ const MOMENTS: { name: string; type: string; label: string; detail: string; tab?
{ name: 'moment-rollback', type: 'rollback', label: 'Rolled back to the archived frame', detail: 'try 3' }, { name: 'moment-rollback', type: 'rollback', label: 'Rolled back to the archived frame', detail: 'try 3' },
]; ];
/**
* The recovery splash shots (`src/panels/RecoverySplash.tsx`): every phase for both actions,
* driven through `window.__stage.recovery` with the splash's clock pinned 18 s into the countdown,
* so the clock reads 0:42 on every machine. The notice is the contract's own example.
*/
const RECOVERY_T = 1_790_629_095;
const RECOVERY_SHOTS = (['countdown', 'acting', 'done', 'failed'] as const).flatMap((phase) =>
(['reset', 'restart'] as const).map((action) => ({
name: `recovery-${phase}-${action}`,
nowS: phase === 'countdown' ? RECOVERY_T + 18 : RECOVERY_T + 63,
notice: {
v: 1,
id: `${RECOVERY_T}-${action}`,
phase,
action,
fromRung: 12,
fromLabel: 'MT. MOON',
...(action === 'reset' ? { toRung: 11, toLabel: 'BOULDER BADGE' } : {}),
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: RECOVERY_T,
executeAt: RECOVERY_T + 60,
updatedAt: phase === 'countdown' ? RECOVERY_T : RECOVERY_T + 60,
},
})),
);
function run(command: string, args: string[]): Promise<void> { function run(command: string, args: string[]): Promise<void> {
return new Promise((done, fail) => { return new Promise((done, fail) => {
const child = spawn(command, args, { cwd: appDir, stdio: 'inherit' }); const child = spawn(command, args, { cwd: appDir, stdio: 'inherit' });
@ -319,35 +264,6 @@ async function main(): Promise<void> {
console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`); console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`);
} }
for (const shot of TICKER_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const rows = await page.evaluate((events) => window.__stage?.ticker(events) ?? [], shot.events);
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${rows.join(' | ')})`);
}
for (const shot of RECOVERY_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const shown = await page.evaluate(([notice, nowS]) => window.__stage?.recovery(notice, nowS as number) ?? null, [
shot.notice,
shot.nowS,
] as const);
if (shown === null) throw new Error(`${shot.name}: the splash refused its notice`);
// The text box rises in over 320 ms (`src/theme/recovery.css`).
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${shown.layout}: ${shown.headline} / ${shown.body} ${shown.countdown})`);
}
// Two extra review shots: the fly strip alone, at 2x, once per renderer. The strip is 800x220 // Two extra review shots: the fly strip alone, at 2x, once per renderer. The strip is 800x220
// in a 1920x1080 frame, which is too small to judge an animal in; these are what a human looks // in a 1920x1080 frame, which is too small to judge an animal in; these are what a human looks
// at to decide whether it reads. // at to decide whether it reads.

View file

@ -1,92 +0,0 @@
/**
* Write a fake auto-recovery notice, for looking at the recovery splash by hand.
*
* The file is the one `infra/bin/fly-loop-recover` writes (contract: `infra/docs/loop-recovery.md`,
* "Stream notice"), written the same way — a temporary file renamed over the target, mode 0644 —
* to `--out`, else `$FLY_RECOVERY_NOTICE`. Point the page's server at the same path:
*
* ```sh
* export FLY_RECOVERY_NOTICE=$PWD/.recovery-notice.json # any writable path
* npm run dev -w @flybrain/stage # serves it at /recovery-notice.json
* # http://127.0.0.1:5273/?mode=player&recovery=1
*
* npm run recovery-notice -w @flybrain/stage -- --phase countdown --action reset --in 45
* npm run recovery-notice -w @flybrain/stage -- --phase acting --action restart
* npm run recovery-notice -w @flybrain/stage -- --demo reset # countdown 20 s, acting 15 s, done
* npm run recovery-notice -w @flybrain/stage -- --clear
* ```
*
* On the release container the deployed `serve.mjs` reads `/run/fly/wd/recovery-notice.json`
* unless its unit sets `FLY_RECOVERY_NOTICE`; this tool is for a dev machine, not for faking a
* recovery on air.
*/
import { chmod, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
type Phase = 'countdown' | 'acting' | 'done' | 'failed';
type Action = 'restart' | 'reset';
function arg(name: string): string | null {
const at = process.argv.indexOf(`--${name}`);
return at === -1 ? null : (process.argv[at + 1] ?? null);
}
const out = arg('out') ?? process.env.FLY_RECOVERY_NOTICE ?? '';
if (out === '') {
console.error('recovery-notice: pass --out <path> or set FLY_RECOVERY_NOTICE');
process.exit(2);
}
async function write(phase: Phase, action: Action, id: string, announcedAt: number, executeAt: number): Promise<void> {
const notice = {
v: 1,
id,
phase,
action,
fromRung: Number(arg('from-rung') ?? 12),
fromLabel: arg('from-label') ?? 'MT. MOON',
...(action === 'reset' ? { toRung: Number(arg('to-rung') ?? 11), toLabel: arg('to-label') ?? 'PEWTER CITY' } : {}),
reason: arg('reason') ?? 'unrewarded',
loop: (arg('loop') ?? 'GO OBJECTIVE,GO WARP').split(',').map((step) => step.trim()),
stuckSeconds: Number(arg('stuck') ?? 1800),
announcedAt,
executeAt,
updatedAt: Math.floor(Date.now() / 1000),
};
const tmp = join(dirname(out), `.recovery-notice.${process.pid}.tmp`);
await writeFile(tmp, `${JSON.stringify(notice, null, 2)}\n`);
await chmod(tmp, 0o644);
await rename(tmp, out);
console.log(`${phase} ${action} -> ${out}`);
}
const sleep = (s: number): Promise<void> => new Promise((done) => setTimeout(done, s * 1000));
async function main(): Promise<void> {
if (process.argv.includes('--clear')) {
await rm(out, { force: true });
console.log(`removed ${out}`);
return;
}
const now = Math.floor(Date.now() / 1000);
const demo = arg('demo');
if (demo !== null) {
const action = (demo === 'restart' ? 'restart' : 'reset') as Action;
const id = `${now}-${action}`;
await write('countdown', action, id, now, now + 20);
await sleep(20);
await write('acting', action, id, now, now + 20);
await sleep(15);
await write(process.argv.includes('--fail') ? 'failed' : 'done', action, id, now, now + 20);
return;
}
const phase = (arg('phase') ?? 'countdown') as Phase;
const action = (arg('action') ?? 'reset') as Action;
const lead = Number(arg('in') ?? 60);
await write(phase, action, `${now}-${action}`, now, now + lead);
}
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});

View file

@ -16,8 +16,7 @@
*/ */
import { execFileSync } from 'node:child_process'; import { execFileSync } from 'node:child_process';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
import { cp, readFile, stat } from 'node:fs/promises'; import { cp, stat } from 'node:fs/promises';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { dirname, join, normalize, resolve } from 'node:path'; import { dirname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import tailwindcss from '@tailwindcss/vite'; import tailwindcss from '@tailwindcss/vite';
@ -88,41 +87,8 @@ function datasetArtifacts(): Plugin {
}; };
} }
/**
* `GET /recovery-notice.json` in dev and preview, the same route `infra/config/serve.mjs` gives
* the deployed page: the auto-recovery helper's notice file (`FLY_RECOVERY_NOTICE`, default
* `/run/fly/wd/recovery-notice.json`), or 204 when there is none. What makes
* `npm run recovery-notice` (`tools/recovery-notice.mts`) work against a local page.
*/
function recoveryNotice(): Plugin {
const serve = async (req: IncomingMessage, res: ServerResponse, next: () => void): Promise<void> => {
if ((req.url ?? '').split('?')[0] !== '/recovery-notice.json') return next();
const path = process.env.FLY_RECOVERY_NOTICE || '/run/fly/wd/recovery-notice.json';
res.setHeader('cache-control', 'no-store');
try {
const info = await stat(path);
if (!info.isFile() || info.size === 0 || info.size > 16_384) throw new Error('no notice');
const body = await readFile(path);
res.setHeader('content-type', 'application/json; charset=utf-8');
res.end(body);
} catch {
res.statusCode = 204;
res.end();
}
};
return {
name: 'flystage-recovery-notice',
configureServer(server) {
server.middlewares.use((req, res, next) => void serve(req, res, next));
},
configurePreviewServer(server) {
server.middlewares.use((req, res, next) => void serve(req, res, next));
},
};
}
export default defineConfig(({ command }) => ({ export default defineConfig(({ command }) => ({
plugins: [react(), tailwindcss(), datasetArtifacts(), recoveryNotice()], plugins: [react(), tailwindcss(), datasetArtifacts()],
define: { define: {
__STAGE_VERSION__: JSON.stringify(stageVersion(command)), __STAGE_VERSION__: JSON.stringify(stageVersion(command)),
}, },

View file

@ -89,10 +89,7 @@ decoder preset to use.
disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already
achieved flags on the first sample so a restore never replays them, and pays only positive achieved flags on the first sample so a restore never replays them, and pays only positive
rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors, items flags, decaying wild wins, badges. Version `pokered-unique8-v5`.
picked up and the HP the fly's own attacks remove in battle (`docs/rewards-learning.md`).
Version `pokered-unique8-v8`; a deploy that names the
previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them.
- Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel, - Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel,
Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a
safe state it archives the emulator snapshot; on a stall (120 s without new exploration) or a game safe state it archives the emulator snapshot; on a stall (120 s without new exploration) or a game
@ -134,10 +131,6 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame
snapshot at 30 Hz: a JSON header (status, rates, learning stats, game mode, milestone rank and snapshot at 30 Hz: a JSON header (status, rates, learning stats, game mode, milestone rank and
total, sugar state, events, chat ring) followed by attachments: RGBA frame, f32 stereo 48 kHz total, sugar state, events, chat ring) followed by attachments: RGBA frame, f32 stereo 48 kHz
audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset. audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset.
flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an
embedded flybus router and the `fly-edge` process serves the same bytes
(`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
"Feed over the bus").
- Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM - Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM
pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat` pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat`
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`, (sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,
@ -166,8 +159,8 @@ sequenceDiagram
S->>S: every 5 s hot copy, every 300 s durable checkpoint S->>S: every 5 s hot copy, every 300 s durable checkpoint
``` ```
Where: `services/flysim/crates/flysim/src/{main,config,simloop,pacing,snapshot,feed,feedbus,api,chat,store,eventlog,metrics}.rs`, Where: `services/flysim/crates/flysim/src/{main,config,simloop,pacing,snapshot,feed,api,chat,store,eventlog,metrics}.rs`,
`services/flysim/crates/fly-edge`, `docs/design/flysim.md`. `docs/design/flysim.md`.
## 4. Stage page ## 4. Stage page

View file

@ -6,12 +6,6 @@ nothing outside the container can reach it, and the bridge is the only intended
There is deliberately **no endpoint that presses buttons, edits game memory, or changes the There is deliberately **no endpoint that presses buttons, edits game memory, or changes the
reward catalog**. That is a structural guarantee, not a configuration. reward catalog**. That is a structural guarantee, not a configuration.
Who serves it (2026-10-01): flysim itself (`FLY_CONTROL_VIA=direct`, the default), or
`fly-control-edge` from flysim's control services on the bus (`FLY_CONTROL_VIA=bus`,
`docs/design/flybus.md`, "Control over the bus"). Both are the same HTTP code over the same
request handling, so nothing in this document depends on the switch. On the bus, the
guarantee above is also a grant table.
| Method and path | Body | Effect | | Method and path | Body | Effect |
|---|---|---| |---|---|---|
| `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). | | `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). |
@ -106,22 +100,6 @@ mode = "raw" # "raw" or "macros"; FLY_MACRO_MODE overr
- Refusals are counted as `fly_chat_rejected_total{reason}`, one series per rule: `control`, - Refusals are counted as `fly_chat_rejected_total{reason}`, one series per rule: `control`,
`charset`, `empty`, `too_long`, `url`, `name`, `deny_list`, `rate_limited`, `malformed`. `charset`, `empty`, `too_long`, `url`, `name`, `deny_list`, `rate_limited`, `malformed`.
Acceptances are `fly_chat_accepted_total`, and the ring depth is `fly_chat_ring_lines`. Acceptances are `fly_chat_accepted_total`, and the ring depth is `fly_chat_ring_lines`.
- **The ring survives a restart (2026-09-22).** Every accepted line rewrites a sidecar,
`<hot_dir>/chat-ring.json` (`[paths] hot_dir`, the tmpfs the hot checkpoints use), by the same
atomic sequence a checkpoint commit uses: tmp file, fsync, rename over. At startup, before the
first publish, the file is read back; lines older than 24 hours are dropped, only the newest
`ring` of them are kept, and a missing file is silence. An unreadable, unparseable or
unknown-version file is ignored with a logged warning and an empty panel — which is what a
restart gave before this existed — never a startup failure. Writing it is best-effort too: a
failure is a warning, and the line is still accepted and still on screen.
The sidecar is **not** part of the checkpoint: it is session state, it adds no chunk to the
`FLYSIM01` envelope and nothing about it enters the compatibility string, so `--print-compatibility`
is unchanged and a build that refuses every checkpoint in a directory still restores the panel.
It lives beside the hot checkpoints because it has their lifetime — a reboot clears the tmpfs —
and `FLY_RESET_STATE=1` clears it along with them (`infra/05-deploy.sh`). The bridge resends
nothing on reconnect: the lines the page shows after a restart are the ones the service already
accepted, with their original event ids and timestamps.
`POST /chat` status codes: `202 { eventId }` accepted, `400` malformed body, `403` chat disabled, `POST /chat` status codes: `202 { eventId }` accepted, `400` malformed body, `403` chat disabled,
`422 { error }` a rule refused the line (the error names the rule), `429 { retryAfterMs }` a rate `422 { error }` a rule refused the line (the error names the rule), `429 { retryAfterMs }` a rate

View file

@ -1,441 +0,0 @@
# flybus: the communications bus
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
`FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
authority for the API and the wire format is the crate's own
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
the draft is the [conformance report](session-framework/bus-conformance.md).
## What it is
`flybus` is a local RPC and pub/sub bus for Tokio processes on one host, with immutable
file-backed artifacts for large payloads. One library, one router, one wire protocol:
messages are small strict-JSON envelopes carrying metadata and artifact references, while
bulk bytes (frames, audio, spike bitsets) live in a store directory the router owns.
Ownership follows deliveries and explicit holds; the router moves messages and tracks
ownership and does not interpret them. It implements the Flybus v1 draft (`bus-v1`, draft 1
of 2026-09-18) over the `ipc-v1` scalar encodings.
Transports are an in-memory pair, an accepted `AsyncRead + AsyncWrite` stream, or a Unix
socket. Identity is bound by the launcher before Hello and checked against a `Policy` of
per-client grants; open/unbound mode is for trusted tests only and is not authentication.
Nothing in the crate is specific to a game, a brain or a stream.
## What it is meant to replace
Today the three processes talk over two ad-hoc loopback surfaces:
| Today | Under the bus |
| --- | --- |
| Feed: WebSocket `127.0.0.1:7400/feed`, one binary message per snapshot at 30 Hz, header plus RGBA frame, audio and spike attachments, re-serialized per consumer | One `latest`-mode topic per stream, with the frame as a sealed artifact shared by fan-out instead of copied per subscriber |
| Control: loopback HTTP `127.0.0.1:7401` (`/stimulate`, `/chat`, `/checkpoint`, `/pause`, `/status`, ...) | RPC services with per-client grants, FIFO dispatch, explicit cancel states and backpressure |
| Per-surface limits, rate limits and timeouts written twice | `Limits` and `Policy` in one place, negotiated at Hello |
The feed and control contracts in [feed-protocol.md](../feed-protocol.md) and
[control-api.md](../control-api.md) stay binding until a migration replaces them. The bus
does not change any published contract by existing.
## Crate layout
`services/flysim/crates/flybus`, a workspace member of the flysim workspace. `flysim` depends
on it for the feed publisher (`src/feedbus.rs`) and `fly-edge` for the subscriber.
| Module | Contents |
| --- | --- |
| `wire` | Scalars, strict JSON, `Envelope`, `ArtifactRef`, `Attachment`, `Location`, framing, `CONTRACT` and `contract_digest()` |
| `error` | `ErrorCode`, `Dispatch`, `BusError` |
| `limits` | `Limits` and its hello encoding |
| `policy` | `Policy`, `Grants`, `Pattern` |
| `router` | `Router`, `RouterConfig`, `RouterStats`, `UnixListenerHandle`; the state machine in `router/state.rs` |
| `client` | `Client` and the handle types |
| `store` | The router-side file store and client-side location resolution |
| `transport` | `Transport` and the `Stream` trait |
Dependencies are already in the workspace lockfile: `tokio`, `serde`, `serde_json`, `sha2`,
`libc`. Tests run every integration case twice, once in memory and once over a Unix socket:
wire negotiation, RPC authority and cancellation, pub/sub credits and retention, artifact
allocate/seal/read with quotas and router restarts, plus the conformance suites and an
`--ignored` perf measurement.
## Wiring still pending
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
- ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
over the bus". The "no button endpoint" guarantee is a grant table there.
- **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either
a binding or a thin translating edge process is required before they leave the WebSocket
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
contracts byte for byte.
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below.
- ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below.
- **Migration order.** The feed is the cheaper first move; control should follow only once
the bus carries the feed in production for a full session.
## Feed over the bus (2026-09-23, EDGE-01)
`feed.via` (`FLY_FEED_VIA`) picks who serves `ws://127.0.0.1:7400/feed`. `direct` is the
default and is the behaviour that predates the bus. With `bus`:
```text
sim thread --watch<Snapshot>--> publisher task --flybus (in memory)--> Router
(unchanged) (flysim-bus runtime) | <bus_dir>/edge.sock
v (bound to "fly-edge")
fly-edge: Subscription -> watch -> flysim::feed :7400
```
- flysim does not bind `feed.bind`. It starts a `Router` on a runtime of its own (two
threads, `flysim-bus`), store root `<bus_dir>/store`, closed policy: `flysim` may declare
and publish `fly.feed.snapshots`, `fly-edge` may only subscribe to it, and the Unix socket
`<bus_dir>/edge.sock` is launcher-bound to `fly-edge`.
- The topic is `retained: latest`. Each publication is one snapshot: the attachments the
header lists as sealed artifacts named `frame` (`image/x-rgba`), `audio`
(`audio/x-f32le`), `spikes` (`application/x-spike-bitset`), and the header as the payload
`{"header": {...}}`. A header over 48 KiB of JSON goes as a `header` artifact instead, so
the 65,536-byte envelope limit can never make a snapshot unpublishable.
- The sim thread is untouched. The publisher reads the same `watch` slot the direct server
reads, so a slow bus skips snapshots the way a slow WebSocket client does, and nothing on
the bus can hold the loop's publish. `fly_bus_published_total` and
`fly_bus_publish_failures_total` count it.
- `fly-edge` subscribes `latest`, one in flight, with replay, rebuilds each `Snapshot` with
`feedbus::receive` and serves it with flysim's own `feed::router`. `hello`, `wants`,
drop-oldest, the idle header and the framing are therefore the same code, and the bytes are
the same bytes: `crates/fly-edge/tests/parity.rs` replays the committed stage fixtures
through both paths at once and requires byte-equal messages per client flavour.
- `fly_frames_sent_total` and `fly_feed_clients` move to the edge with the clients; it exports
them under the same names on `FLY_EDGE_METRICS_ADDR` (`127.0.0.1:9102` in
`infra/units/flyedge.service`), and watchdog check 2 follows `FLY_FEED_VIA` in `fly.env` to
them. flysim's own copies read 0 in bus mode; `/status` is otherwise unchanged. The edge also
exports `fly_edge_bus_connected`, `fly_edge_bus_lost_total`, `fly_edge_bind_failures_total`
(the bus answered but :7400 was taken, most likely by a flysim still in direct mode) and
`fly_edge_decode_failures_total`.
- Nothing about the fly changes: the readout, the reward catalog, the adapter version and the
compatibility string are byte-identical in both modes (`--print-compatibility`).
### Amendment 2026-09-23: feed sizing
Measured on the live fly (release build, the real cartridge): a running snapshot is a
**92,160-byte** frame (160x144 RGBA; not the 640x480 "1.2 MB" the pending list assumed), a
**17,407-byte** spike bitset (139,255 neurons), about **12,800 bytes** of audio at realtime
(1,600 stereo f32 frames per 30 Hz snapshot at 48 kHz) and a 2 to 3 KB header: **122,367
bytes** of artifacts, about 3.7 MB/s at 30 Hz. `flysim::feedbus::limits()`:
| Limit | Value | Why |
| --- | --- | --- |
| `max_clients` | 8 | connections, pending handshakes included: the in-process publisher and the edge's one socket seat |
| `max_subscriptions_per_client` | 4 | the edge needs 1; this is what bounds the worst case |
| `max_latest_in_flight` | 2 | the default; the edge asks for 1 |
| `max_artifact_bytes` | 4 MiB | ten seconds of audio that piled up behind a late publish |
| `max_store_bytes` | 32 MiB | tmpfs, so RAM; ten times the worst case below |
| `max_retained_bytes` | 8 MiB | one retained snapshot, plus a large header artifact |
| `max_owners_per_client` / reserved | 64 / 8 | three artifacts per delivery, a few deliveries |
| others | small counts | one topic, no services |
A `latest` subscriber that never consumes pins at most its queued slot plus its in-flight
credits (3 snapshots); the topic pins one retained value; the publisher holds one snapshot of
staging plus the sealed copy while sealing. Only one client can subscribe at all: the publisher
is in process, and `edge.sock` is launcher-bound to `fly-edge`, which the router admits once at
a time (a second connection is refused as already connected). The worst case is therefore that
one client holding all 4 subscriptions it may open, none consuming: 4 x 3 + 1 + 2 = **15
snapshots, about 1.8 MB**, and publication never waits on any of them (a latest subscriber is
never a reason to refuse a publication, bus-v1 section 9). `crates/fly-edge/tests/stall.rs`
measures exactly that seat: four hoarding subscriptions, a fifth refused, a second connection
refused, pacer lag 0, no publication refused. The 15 is an upper bound; the measured store
was 472,061 bytes (under 4 snapshots), because fan-out adds roots and never copies, so four
subscriptions stuck on the same publications pin the same artifacts.
### Amendment 2026-09-23: feed store lifecycle
- **Location.** `feed.bus_dir` (`FLY_BUS_DIR`), `/run/fly/bus` on the containers: tmpfs,
0700, owned by `fly`, created by tmpfiles and again by flysim. The store root is
`<bus_dir>/store`, the socket `<bus_dir>/edge.sock`. A reboot empties it.
- **Owner.** The router lives in flysim; its lifetime is flysim's. flysim removes a stale
socket file at start, and `Router::new` removes any store directory whose `flock` is free,
i.e. one a crashed flysim left behind. A clean stop removes its own directory. The edge owns
nothing on disk.
- **Order.** flysim first, the edge after it: `flyedge.service` is `After=` and
`Requires=flysim.service`, so an explicit stop or restart of flysim (the unstick rule's
restart included) takes the edge with it. A crash-restart of flysim needs nothing: the edge
sees the connection close, drops every WebSocket client, unbinds :7400 and reconnects every
500 ms, binding :7400 again only when the first snapshot of the new router arrives. To the
stage that is exactly a flysim restart in direct mode: refused, then back.
- **Default.** `flyedge.service` is in no target and `07-enable.sh` does not enable it;
`05-deploy.sh` writes `FLY_FEED_VIA=direct` unless the env file says otherwise, and refuses
anything but `direct` or `bus` (any case, written lowercased). The switch and the way back
are in the unit's header. The edge gets a cpuset drop-in on the page's CPUs with the other
units, so once enabled it never runs on flysim's.
- **Paths.** `feed.bus_dir` must be absolute and non-empty (checked in both modes), since
flysim and the edge each resolve it.
- **Migration order** is unchanged: the feed first; control only after the bus has carried
the feed in production for a full session.
### Known limits (review round 1, 2026-09-23)
Accepted for now and written down rather than fixed:
- **Feed counters off the container.** In bus mode flysim's `:9101` reports
`fly_feed_clients` and `fly_frames_sent_total` as 0, and the edge's copies are on loopback
`:9102` only. The watchdog follows `FLY_FEED_VIA`; anything that scrapes `:9101` from off
the container (the metrics dashboard) goes blind to the feed until it also scrapes the edge.
- **Store quota is per router, not per client.** Any client on `edge.sock` may allocate
artifacts up to the store cap; a hostile process running as the same user could fill the
store and make flysim's publications fail. The loop is unaffected (a refusal is counted, never
waited on), but the feed would stall. Same-user processes are inside the trust boundary
(crate README, "Limitations").
- **Rollback while in bus mode.** Rolling back to a release without `fly-edge` while `fly.env`
still says `bus` leaves no one on :7400, and check 2 then reads the edge's absent `:9102` and
escalates. Switch back to `direct` first (the unit header's way back), then roll back.
- **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a
Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`.
### Amendment 2026-10-01: the feed in production (EDGE-02)
- **The session runtime needed nothing.** `flysim-session` serves its listeners through
`flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was
written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs`
runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of
one store, direct and bus, records both feeds over a WebSocket and requires every frame in
common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then
stops the binary and starts a new one under the same edge, which must unbind, reconnect and
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review
N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the
sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts
one page CPU into `flysim.slice` for it).
- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an
`ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`;
`flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and
start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus
mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim
all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct`
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes.
- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off
the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle
header, so silence means a wedged subscription, which `Subscription::next` alone would never
report.
- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote
fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while
flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth
switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots.
Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to
connect to.
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the
env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no
binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and
the edge both follow fly.env at their next start, so a disagreement never leaves the stage with
no feed.
- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens
on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
## Control over the bus (2026-10-01, CTRL-01)
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the
default and the behaviour that predates the bus. With `bus`:
```text
api router (flysim::api) BusBackend flybus (Unix socket) control host (in flysim)
:7401 in fly-control-edge --> encode_request --> <bus_dir>/control-edge.sock --> fly.control.s.main.* services
same routes, extractors, (controlbus) bound to "fly-control-edge" -> flysim::control::handle
404s, headers, bodies -> the same Command queue
```
- `docs/control-api.md` is unchanged and still binding: every endpoint, status code and body.
flysim's control code is split in two. `flysim::control` holds the semantics: one
`ControlRequest` per endpoint, and `handle`, the only code that validates a request, talks to
the loop and picks a status. `flysim::api` is the HTTP layer over any `ControlBackend`. Direct
mode is `api` over `control` in one process. Bus mode is the same `api` in `fly-control-edge`
over a `BusBackend`, which carries the request to the `control` services in flysim. Neither
process has an HTTP table or a validation rule of its own, so the bytes on `:7401` are the
same in both modes. `crates/fly-control-edge/tests/parity.rs` sends every endpoint, each
validation case and each refusal to both paths and requires equal status, headers and
body. Over real sockets, it also requires the whole HTTP/1.1 response to be equal apart from
`date`. `fly-legacy-session/tests/service_parity.rs` runs the session runtime once more with
its control on the bus and compares it with the legacy loop. The comparison covers 120
frames, 19 control responses, the event log, the journal and the final checkpoint.
- Both runtimes get it: `flysim` and `flysim-session` both run `flysim::serve`, which in bus mode
does not bind `control.bind`. Instead it registers the services on the embedded router. That
is the feed's router when the feed is on the bus too: one router, one store, one closed policy
(`flysim::bus`). The read-only `control.metrics_bind` listener (`:9101`) stays in flysim in
both modes.
- Nothing about the fly changes. The command queue, its bound and its timeouts are the same.
The compatibility string is byte-identical in both modes.
### Services and methods
flybus grants name services, not methods. The surface is therefore split into six service
*families*, and a grant names families. Every family is scoped either to a session or to one
agent (fly) of it. Each method's payload and outcome:
| Service (live names) | Method | Endpoint | Payload |
| --- | --- | --- | --- |
| `fly.control.s.main.read` | `Control.Status` | `GET /status`, `/status.json` | `{}` |
| | `Control.Healthz` | `GET /healthz` | `{}` |
| | `Control.Metrics` | `GET /metrics` | `{}` |
| | `Control.Events` | `GET /events` | `{since?: string, limit?: string}`, the raw query values |
| `fly.control.s.main.a.fly.status` | `Control.Status` | (none: the fly's own status, for native clients) | `{}` |
| `fly.control.s.main.a.fly.sugar` | `Control.Stimulate` | `POST /stimulate` | `{request?: <body JSON>}` |
| `fly.control.s.main.a.fly.reward` | `Control.Reward` | `POST /reward` | `{request?: <body JSON>}` |
| `fly.control.s.main.chat` | `Control.Chat` | `POST /chat` | `{request?: <body JSON>}` |
| `fly.control.s.main.ops` | `Control.Checkpoint`, `Control.Pause`, `Control.Resume` | `POST /checkpoint`, `/pause`, `/resume` | `{}` |
- **Outcome.** `{"status": <the control-api.md code>, "body": <the JSON body>}`, or `{"status",
"text"}` for `/metrics`. Above 48 KiB (a full `/events` page can be 4,096 events) the body
travels as a sealed `body` artifact instead, with `bodyArtifact` naming its type. The status
code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an
HTTP caller does, so the edge needs no table of its own.
- **Requests** carry the body as the caller sent it (`request` is absent when it was empty or
not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as
a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets
the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A
method the service does not have is a 404. Neither reaches the loop.
- **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`).
The router dispatches FIFO per service. The host answers each request in a task of its own, so
a pause waiting on a durable write does not hold up a resume. Families are separate services,
so a stuck `ops` never delays `/status`.
- **Backpressure.** The bound is on the queue at the moment of admission. A burst can
therefore be refused before the router has dispatched its first calls into the in-flight
slots. That is measured, not assumed (`tests/backpressure.rs`). A full service refuses at
once with `BACKPRESSURE`, and the edge answers it
with direct mode's `503 {"error": "the simulation command queue is full"}`. Bus failures use
direct mode's words for the same failure (`control::unavailable`). `NO_SERVICE` before
dispatch is "has stopped"; `NO_SERVICE` after dispatch, `CALL_GONE` and `ROUTER_LOST` are
"dropped the request". `NOT_AUTHORIZED` is a 403.
- **Deadlines and cancel.** The host keeps direct mode's own timeouts: 2 s for a command,
none for `/checkpoint` and `/pause`, which wait for a durable write. The edge adds a guard of
that plus 2 s for timed requests only. At the guard it cancels the call and answers direct
mode's timeout 503. A call cancelled before dispatch never reaches the loop. A dispatched call
may still act, as a direct request whose caller timed out may. An HTTP client that goes away
drops its handler, and with it the pending call. The router discards the late result, and
the call record goes once the host answers (`tests/backpressure.rs`).
### Grants: the structural guarantee as a table
| Participant (socket) | read | status | sugar | reward | chat | ops | register |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `flysim-control`, the host (in-process, no socket) | | | | | | | every control service, exact names |
| `fly-stage` (`control/stage.sock`) | yes | yes | | | | | |
| `fly-bridge` (`control/bridge.sock`) | yes | yes | yes | | yes | | |
| `fly-watchdog` (`control/watchdog.sock`): watchdog, loop-recover ladder, `fly-runtime`, probation, shadow guard, stream check | yes | yes | | | | | |
| `fly-operator` (`control/operator.sock`) | yes | yes | yes | yes | yes | yes | |
| `fly-control-edge` (`control-edge.sock`): everything on `:7401` | yes | yes | yes | yes | yes | yes | |
| a player backing one fly (`player_grants`, not wired yet) | yes | that fly | that fly | | | | |
The status, sugar and reward columns are per agent: a role gets them for every fly of the
session (`grants`), or for one fly by id or by controller port (`grants_for`, `player_grants`
with `Agents::Id` or `Agents::Port`). The table is `controlbus::Role` and `controlbus::grants`. It reflects what each client calls
today: the stage only waits on `/healthz`; the bridge calls `/status`, `/stimulate`, `/chat`,
`/events` and `/healthz`; the infra scripts only read; the operator uses `curl`. Each socket is
launcher-bound to its participant. The watchdog and the ladder restart through systemd, never
through a control call.
"Nothing can press buttons" is structurally true because of four properties. Each is tested:
1. **No method takes input.** `ControlRequest` and the loop's `Command` have no variant that
presses a button, edits game memory or changes the reward catalog, so no method can be added
without a contract change. Service and method names are scanned for the same words `api.rs`
scans routes for (`controlbus` unit tests).
2. **Grants are exact calls and nothing else.** No role is granted `Any`, a prefix, `register`,
`publish`, `subscribe` or topic management (`every_grant_is_an_exact_call_...`). On a router
that also carries an environment's input service, no control participant can call that
service, the operator and the edge included. The router refuses before dispatch
(`tests/grants.rs`, `on_a_shared_router_no_control_participant_can_reach_an_input_service`).
3. **Only the host registers.** The one register grant belongs to an in-process participant
with no socket, so nothing outside flysim can stand in for a control service. A socket admits
only its own participant; claiming another id at hello is refused.
4. **The policy is closed.** An id that is not in the table cannot connect.
What this does not change: loopback HTTP has no caller identity, so `fly-control-edge` carries
the whole surface. That is exactly the trust `:7401` has today. A client is narrowed by moving
it off HTTP onto its own role socket. That needs a native client for the TypeScript processes
(a later slice; the operator chose edges over a Node binding for now). The bus's own limit still
applies: processes running as the same OS user are inside the trust boundary (crate README,
"Limitations").
### N flies, M environments, controller ports, players
Operator direction (2026-10-01): first the existing Game Boy fly goes fully onto the framework
and the bus. A later project puts several flies on multi-controller consoles, one fly per
controller port. This slice does not build that, but the services and grants are scoped per
session, per agent and per port from the start, so multi-fly is configuration, not a redesign.
A single-fly deployment is the same design with one agent.
- **Scope** (`controlbus::Scope`): a session id and its agents, each an id and, where the
environment has controller ports, the port it plays on (`AgentScope { id, port }`). The live
fly is session `main`, agent `fly` on port 0, the Game Boy's one pad (`Scope::live`). A scope
refuses two agents with one id or on one port.
- **Session-scoped** families (read, chat, ops) are `fly.control.s.<session>.<family>`. Pause and
checkpoint act on a whole session: one coordinator steps every agent, and one save is one
generation. The chat ring is the session's stage. `read` holds the session's status, health,
metrics and event log.
- **Agent-scoped** families (status, sugar, reward) are
`fly.control.s.<session>.a.<agent>.<family>`, one service per fly. A sugar or reward pulse goes
into one brain. Each fly's own view is its `status` service. Adding a fly adds its three
services, and nothing else changes.
- **Ports.** A port is a property of an agent's binding, not part of a name, because a pulse
goes into a brain, not into a controller. A grant limited to a port
(`Agents::Port(n)`) is resolved to the agent bound to that port when the policy is built. The
policy is fixed for a router's lifetime, so rebinding ports is a session restart. A port nobody
plays on grants no agent service.
- **M sessions** on one router (several games, or one multiplayer game) have disjoint names, so
a grant on one session never names another's. `:7401` addresses the live scope only. A second
session gets native bus clients, or an edge of its own on another port with its own scope.
- **Environments.** Environment-scoped status is reserved as
`fly.control.s.<session>.e.<env>.read`. Environment *input* services (`Environment.Step` and
the like) are never in a control scope. An agent's decision reaches its environment through
the coordinator, never through control, and on a multi-controller console each fly's decoder
writes only its own port. Property 2 holds however many environments and ports share the
router.
- **Players.** A viewer who backs one fly gets `player_grants(scope, Agents::Port(n))` or
`Agents::Id(..)`: read the session, see and sugar that fly, nothing else
(`a_player_sugars_their_own_fly_and_no_other`). In a multiplayer game the players on the pads
are flies, and their presses come from their decoders. A human input path would be a new
contract, never a control grant.
### What in `docs/control-api.md` is single-fly
The contract is unchanged by this slice. These parts of it assume one fly per session. Each
would need a contract amendment before a second fly could be served over HTTP. The bus services
above are already addressed per agent, so the amendments are to the HTTP shapes, not the bus.
| Endpoint or rule | Why it is single-fly | Multi-fly direction |
| --- | --- | --- |
| `GET /status` | The feed header reshaped: one `buttons`, `rates`, `decoder`, `learning`, `game`, `milestone`, `sugar`, `version` | Per agent: each fly's `status` service. The session's `Control.Status` becomes a session shape listing its agents and ports |
| `POST /stimulate` | No agent field; addresses "the fly" | The agent's `sugar` service; over HTTP an `agent` (or `port`) field, absent meaning the only fly |
| sugar limits ("6 per minute globally, no overlap with an active pulse") | The overlap rule is per brain; the budget is per deployment | Overlap per agent; whether the budget is per fly or per session is a policy decision |
| `POST /reward` | No agent field | The agent's `reward` service; same field as `/stimulate` |
| `GET /events`, `events.jsonl` | `FeedEvent` has no agent: reward, sugar and macro events cannot say whose they are | An `agent` field on agent events, absent for session events |
| `POST /checkpoint` | One generation of one FLYSIM01 envelope, which is single-fly by format | A session checkpoint holding every agent. FLYSIM01 stays the format of record until RETIRE-01 |
| `GET /metrics` | Series carry no agent label (`fly_reward_*`, the rates) | An `agent` label on per-fly series |
| `[macros]`, `loop.game` | One mode and one game per deployment | Per environment |
| `POST /chat`, `/pause`, `/resume`, `/healthz` | Session-level already | None |
### Lifecycle and operations
- `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and
`control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With
control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8.
- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its
`ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for
`flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings
`:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own
counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`,
`_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`).
- The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and
reconnects every 500 ms. To a client that looks exactly like flysim restarting
(`tests/backpressure.rs`, `tests/serve.rs`).
- Watchdog. Check 1 reads flysim's own `/healthz` on `:9101` when `FLY_CONTROL_VIA=bus`, so an
edge outage never restarts the fly. Check 1b restarts the edge alone when `:7401` fails while
flysim is healthy. Every other `:7401` reader (`fly-runtime`, probation, shadow guard,
loop-recover, the stream check) goes through the edge unchanged.
- Switch and rollback: `infra/docs/runbook.md`, "Control over the bus".
- **Migration order.** This document's rule stands: the control API moves after the feed has
been on the bus in production for a full session. The switch exists independently of the
feed's, and when to throw it is the coordinator's call.

View file

@ -355,74 +355,6 @@ on-screen ticker cannot disagree with what the sim did.
against the prototype's WASM size and diffs a known save. If they match, prototype checkpoints against the prototype's WASM size and diffs a known save. If they match, prototype checkpoints
import and the segment records the shared tag; if not, milestone saves must be re-earned and that import and the segment records the shared tag; if not, milestone saves must be re-earned and that
is a stated M3 finding. is a stated M3 finding.
- **Restoring across an adapter version** (2026-09-22). The compatibility string is compared
whole, so bumping the reward adapter refuses every checkpoint the previous one wrote -- which is
the right default and was, until now, the only behaviour. It is the wrong default for a change
that only *adds* a rule: `pokered-unique8-v6` adds the catch reward and one counter,
`catchCounts`, and means the same thing as `v5` for every other field, so a `v5` run is
resumable and throwing it away would be a choice nobody made deliberately.
So there is one narrow, opt-in migration, `flybrain_gb::compatibility::decide`, and it requires
**all three** of:
1. the two compatibility strings differ in the adapter segment (segment 1) and **nowhere else**.
A dataset, kernel, plasticity, emulator-revision, symbol-provenance or state-format
difference is still a refusal: none of those has a migration, and a fly restored across one
is a different fly;
2. the running adapter's `migrates_from()` lists the checkpoint's adapter, so the code that will
read that state says out loud that it can. Pokémon Red's list is `["pokered-unique8-v5"]` and
nothing else -- `v4` is excluded because its ledger holds no `boundary:` keys and resuming it
would pay a second time for every exit already found, and `v3` because its stored rank is a
rung on a different ladder;
3. the deploy names the same adapter id in **`FLY_ACCEPT_ADAPTERS`** (comma- or
space-separated). Unset or empty migrates nothing, which is what every deploy before this one
did.
Condition 2 without 3 would make the migration silent; condition 3 without 2 would let an
operator wave through a pair nobody wrote a migration for. `infra/05-deploy.sh`'s compatibility
gate applies the same rule before it flips the `current` symlink, and writes the variable into
`/etc/fly/fly.env` so flysim applies it at restore -- the two must agree, or a deploy would pass
a gate that flysim then fails, which is the black stream the gate exists to prevent. The
migration itself is `PokemonRedReward::import_state` doing what it already did: `catchCounts` is
absent from a `v5` state and restores empty, which is the truth about a run that was never paid
for a catch. `STATE_VERSION` does not move, because the schema did not.
**`v6` -> `v7`** (2026-09-23, the engagement rewards) is the same migration for the next pair,
and `pokered-unique8-v7`'s `migrates_from()` is `["pokered-unique8-v6"]` and nothing else -- `v5`
is no longer migrated, because the live run is `v6`. The deploy that ships it sets
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v6`. No field is added this time: `talk` and `item` key
their ledgers into the existing `seen` array, as `boundary` did, so a `v6` state restores
unchanged with no `talk:` keys. The one step is at the first sample after the restore, not in
`import_state`: a ledger without the `items:seeded` key writes an `item:`/`hidden:` key for every
item the cartridge already shows as taken, pays for none, and marks the seed, so a rollback to a
slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed").
`STATE_VERSION` stays 4.
**`v7` -> `v8`** (2026-09-29, the damage reward). `pokered-unique8-v8`'s `migrates_from()` is
`["pokered-unique8-v7", "pokered-unique8-v6"]`: the live run is `v7`, and `v6` still composes,
because `v7`'s own step (the item seed on the first sample without `items:seeded`) is still in
this build and the damage state starts empty either way. The deploy that ships it sets
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`; naming `v7` does not admit a `v6` checkpoint, which
needs its own id. One optional field is added, `damageCounts` (the wild keys that have paid
damage), and one optional object inside a battle in flight, `battle.damage` (the per-battle
marks and what the battle has paid). A `v7` state has neither and restores with no wild key paid
and, if the checkpoint was taken mid-battle, every enemy Pokémon marked at the HP it has when
first read, so nothing it lost before the restore is paid. `STATE_VERSION` stays 4. The
compatibility string moves in segment 1 only: `.../pokered-unique8-v7/...` becomes
`.../pokered-unique8-v8/...`, every other segment byte-identical.
- **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away;
`infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a
dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and
`recoveries` at zero (so the restarted run does not begin with its recovery budget already
spent), installs it as the newest generation of the hot and durable stores, removes the
milestone archives above N, and clears the event log -- whose id sequence the restored
checkpoint's `lastEventId` rewinds. `best` is not touched: the archive's own `best` is the rung
it was taken at, and the rank the stream shows is recomputed by the adapter from the restored
game state. The implementation is `flysim::reset` (`flysim --reset-to-milestone N`) rather than
the shell script, because two of those steps are inside the envelope. The sequence around it is
in `infra/docs/runbook.md`.
- **A running macro is not checkpointed** (2026-09-16, `docs/design/macros.md`). Palette mode's - **A running macro is not checkpointed** (2026-09-16, `docs/design/macros.md`). Palette mode's
state — the scene, the palette, the running macro, its plan and its frame count — is transient, state — the scene, the palette, the running macro, its plan and its frame count — is transient,
like the readout's blocked-direction cooldown and for the same reason: a restore that resumed a like the readout's blocked-direction cooldown and for the same reason: a restore that resumed a

View file

@ -555,7 +555,7 @@ into this project.
| What | Where | Mode | | What | Where | Mode |
|---|---|---| |---|---|---|
| source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/<app>-client-id`, `twitch/<app>-client-secret`, `twitch/<bot>-token` | WSL box only | | source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/helix-client-id`, `twitch/helix-client-secret`, `twitch/fly-pokemon-bot-token` | WSL box only |
| stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` | | stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` |
| bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` | | bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` |
| bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` | | bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` |

View file

@ -125,18 +125,7 @@ condition the plan wanted, at the cost of no new state.
## Recovery budgets ## Recovery budgets
Attempts per rung stay 3; lifetime budget scales with the ladder (36 instead of 12). Stall window Attempts per rung stay 3; lifetime budget scales with the ladder (36 instead of 12). Stall window
unchanged (120 s without new exploration, 180 s since last recovery). unchanged (120 s without new exploration, 180 s since last recovery). The ratchet's rank bound is
**Amended 2026-09-22 (rung 10).** "New exploration" is the adapter's lifetime tile ledger, so a map
entered for the first time resets the window -- a new map is a map's worth of tiles nobody has stood
on -- and a map *re-entered* does not. Two "Stuck" rollbacks fired inside half an hour on a fly that
was walking a town it had already covered toward the rung's own door, and both were this rule
working. The window now takes a second signal beside the tile count: **the fly being nearer its
objective, in map hops, than this run has ever been** (`docs/design/macros.md` section 12.15). The
ratchet treats it exactly as it treats new exploration -- it restarts the window and does nothing
else -- it can fire at most once per step of the road, and the ratchet itself knows no more about
what it means than it knows what a tile is. Nothing else about the budgets, the triggers or the
checkpointed state changes. The ratchet's rank bound is
now the running adapter's ladder length, passed in rather than a constant, because the bound belongs now the running adapter's ladder length, passed in rather than a constant, because the bound belongs
to the adapter: Pokémon's ladder is 38 rungs and the platformer's is 16 to the adapter: Pokémon's ladder is 38 rungs and the platformer's is 16
(`docs/design/platformer.md` §3). Only the *budgets* are per-game, from the adapter's (`docs/design/platformer.md` §3). Only the *budgets* are per-game, from the adapter's

View file

@ -118,57 +118,6 @@ Addresses are at the pinned commit. "Verified" is one of:
| which slot is out | `wPlayerMonNumber` | `$cc2f` | 0-based party slot | ROM, trace | | which slot is out | `wPlayerMonNumber` | `$cc2f` | 0-based party slot | ROM, trace |
| the enemy | `wEnemyMonSpecies`, `wEnemyMonHP`, `wEnemyMonLevel`, `wEnemyMonMaxHP` | `$cfe5`, `$cfe6`, `$cff3`, `$cff4` | HP big-endian. Not written on the frame a battle starts — the reward adapter's own comment says the same — so the enemy is `None` for the first few hundred frames of a battle. | ROM (the rival's Squirtle, level 5, 20/20, and `None` on the first frame), trace | | the enemy | `wEnemyMonSpecies`, `wEnemyMonHP`, `wEnemyMonLevel`, `wEnemyMonMaxHP` | `$cfe5`, `$cfe6`, `$cff3`, `$cff4` | HP big-endian. Not written on the frame a battle starts — the reward adapter's own comment says the same — so the enemy is `None` for the first few hundred frames of a battle. | ROM (the rival's Squirtle, level 5, 20/20, and `None` on the first frame), trace |
| how many moves | `wNumMovesMinusOne` | `$cd6c` | the move count minus one, valid in a battle | trace | | how many moves | `wNumMovesMinusOne` | `$cd6c` | the move count minus one, valid in a battle | trace |
| **a ball kept this one** | `wCapturedMonSpecies` | `$d11c` | **new 2026-09-22** (the catch reward, `docs/rewards-learning.md`). `ram/wram.asm`'s own comment is "0 if no mon was captured". `ItemUseBall` zeroes it before every throw (`.canUseBall`) and writes `wEnemyMonSpecies` into it only on the branch that keeps the Pokémon; `UseBagItem`'s `.returnAfterCapturingMon` zeroes it again and sets `wBattleResult` to 2 on the way out of the battle. It is therefore non-zero for the hundreds of frames the catch's text and Pokédex screen take, and zero everywhere else. The value is the **internal** species index, like `wEnemyMonSpecies` and unlike `wPokedexOwned`'s bit index. Address resolved by `services/flysim/tools/resolve_wram.py`, bracketed by `wFontLoaded` and `wForcePlayerToChooseMon`. | survey (`tests/rom_catch.rs`: a real wild battle from a rung-9 checkpoint, balls thrown by the `THROW BALL` macro, the byte read out of the running game), trace (`pokemon_red/tests.rs`) |
`wBattleResult` (`$cf0b`) is the second half of that row and is worth its own sentence: it is 0
for a win, 1 for a loss, and 2 on exactly two paths in the whole game -- `.returnAfterCapturingMon`
and a *link* battle whose opponent ran (`engine/battle/core.asm`), which this cartridge never has.
So "the captured-species byte was non-zero during the battle **and** the result is 2" is a catch
and nothing else. `InitBattleVariables`, `ResetStatusAndHalveMoneyOnBlackout` and
`HandleFlyWarpOrDungeonWarp` all clear it, so a stale 2 cannot survive into the next battle.
Not used for the catch, and why: `wPartyCount` (`$d163`) rises on a catch **only** when the party
has room -- a full party sends the Pokémon to `wBoxCount` instead -- and it also rises for a gift,
a trade and a Pokémon withdrawn from the PC. Reading a catch off it would need a second rule to
tell those apart. The cartridge's own flag needs none, which is why the row above is the one the
adapter reads.
### The engagement rewards' reads (2026-09-23)
**New 2026-09-23** (`talk` and `item`, `docs/rewards-learning.md`, "Engagement rewards"). All six
were resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit
and are bracketed by addresses `symbols.rs` already carried; two of the brackets needed the tool
to count `NUM_STATS` and `NUM_CITY_MAPS`, which the decomp defines as `const_value` over an
enumeration.
| what | symbol | address | notes | verified |
| --- | --- | --- | --- | --- |
| the text's subject | `wSpriteIndex` | `$cf13` | `DisplayTextID` copies its argument here: a sprite slot up to `wNumSprites`, else a text id. It arrives **about twenty frames after** `wFontLoaded` bit 0 rises, because `DisplayTextIDInit` loads the font's tiles first; until then it still holds the previous text's subject. | survey (`tests/rom_engage.rs`: the Viridian Forest north gate, the old man at slot 2, font bit on frame 820 and the argument on frame 840) |
| mid-step | `wWalkCounter` | `$cfc5` | non-zero for the frames of a step; the overworld only reads A at zero. Right after `wFontLoaded` in `ram/wram.asm`. | ROM, trace |
| an item ball's item | `wMapSpriteExtraData` | `$d504` | two bytes per sprite slot (slot 1 first): `(item id, 0)` for an `ITEM` `object_event`, `(trainer class, trainer number)` for a `TRAINER` one, zeroes otherwise -- `LoadMapHeader`'s `.itemBallSprite` / `.trainerSprite` / `.regularSprite` | survey (the forest's Antidote ball read `(11, 0)`) |
| taken or hidden, per object | `wToggleableObjectFlags` | `$d5a6` | `flag_array $100`, one bit per global toggleable index (`constants/toggle_constants.asm`); `PickUpItem`'s `HideObject` sets an item ball's bit after `GiveItem` succeeded | survey (the forest's Antidote ball's bit rose on the pickup frame) |
| this map's toggleables | `wToggleableObjectList` | `$d5ce` | up to sixteen `(sprite slot, global index)` pairs, `$ff`-terminated, written by `MarkTownVisitedAndLoadToggleableObjects` | survey |
| hidden items found | `wObtainedHiddenItemsFlags` | `$d6f0` | `flag_array MAX_HIDDEN_ITEMS` (112); `FoundHiddenItemText` sets the bit after `GiveItem` succeeded, and nothing else writes it | ROM (disassembly), trace |
Not used, and why: `hJoyPressed`/`hJoyHeld` would say "A was pressed" directly, but they are HRAM,
which neither `gen_symbols.py` nor `resolve_wram.py` resolves, and a hand-written address is the one
thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame
before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM.
### The damage reward's reads (2026-09-29)
**New 2026-09-29** (`damage`, `docs/rewards-learning.md`, "Damage rewards"). The two WRAM names were
resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit and
are bracketed by addresses `symbols.rs` already carried. The HRAM byte is the second hand-counted
HRAM address in the crate, after row 63's `hJoyLast`, and is held to the same standard: counted
from that pinned anchor and checked against the section's end, then pinned on the cartridge.
| what | symbol | address | notes | verified |
| --- | --- | --- | --- | --- |
| whose side is acting | `hWhoseTurn` | `$FFF3` | "0 on player's turn, 1 on enemy's turn" (`ram/hram.asm`). Counted from `hJoyLast` (`$FFB1`) with each `UNION` at its largest member; the nine bytes after it end at `$FFFE`, the end of HRAM. `ExecutePlayerMove` writes 0 before the fly's move and `MainInBattleLoop` 1 before the enemy's; `HandlePoisonBurnLeechSeed` picks whose HP to cut by it. MEM-01's memory image captures HRAM, so the session runtime reads the same byte. | survey (`tests/rom_damage.rs`, the row 67 state: every enemy HP drop with 0, every own HP drop with 1) |
| the move executing | `wPlayerMoveNum` | `$cfd2` | the first of the six move bytes `ExecutePlayerMove` loads; `STRUGGLE` (`$a5`) for a Pokémon with no PP. Bracketed by `wWalkCounter` and `wEnemyMonSpecies`. | survey (BUBBLE `$91` and TACKLE `$21` read on the frames their hits landed) |
| which enemy slot is out | `wEnemyMonPartyPos` | `$cfe8` | `battle_struct`'s third field (`macros/ram.asm`: Species, HP, PartyPos, aliasing BoxLevel); `$ff` until a trainer's first send-out, then the 0-based party slot. Bracketed by `wEnemyMonHP` and `wEnemyMonStatus`. | trace (`pokemon_red/tests.rs`), survey |
| (stale) the enemy | `wEnemyMonSpecies` ... `wEnemyMonMaxHP` | as above | **not cleared between battles**: `InitBattleVariables` leaves `wEnemyMon` alone, and a trainer battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData`. The first samples of a battle can hold the last battle's Pokémon at the HP it finished on; the damage rule marks a target only once it reads full. | disassembly, trace |
### Battle menu and cursor, own turn against forced switch ### Battle menu and cursor, own turn against forced switch
@ -179,7 +128,7 @@ parked its cursor. All five bytes are contiguous: `wTopMenuItemY` `$cc24`, `wTop
| menu | signature | cursor | verified | | menu | signature | cursor | verified |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| the top-level battle menu | `wTextBoxID` = `$0b`, `wTopMenuItemY` = 14, `wTopMenuItemX` = 9 with watched keys `PAD_RIGHT\|PAD_A` (left column) or 15 with `PAD_LEFT\|PAD_A` (right), `wMaxMenuItem` = 1 (`DisplayBattleMenu`, `engine/battle/core.asm:2081` and `:2114`) | reported 0 FIGHT, 1 PKMN, 2 ITEM, 3 RUN: the game keeps the index *within* the column and `.rightColumn` adds two on selection | ROM (a fresh menu is FIGHT; RIGHT is ITEM; DOWN from there is RUN), trace | | the top-level battle menu | `wTextBoxID` = `$0b`, `wTopMenuItemY` = 14, `wTopMenuItemX` = 9 with watched keys `PAD_RIGHT\|PAD_A` (left column) or 15 with `PAD_LEFT\|PAD_A` (right), `wMaxMenuItem` = 1 (`DisplayBattleMenu`, `engine/battle/core.asm:2081` and `:2114`) | reported 0 FIGHT, 1 PKMN, 2 ITEM, 3 RUN: the game keeps the index *within* the column and `.rightColumn` adds two on selection | ROM (a fresh menu is FIGHT; RIGHT is ITEM; DOWN from there is RUN), trace |
| the move list | `wTopMenuItemY` = 12, `wTopMenuItemX` = 5 (`MoveSelectionMenu`'s regular menu, `:2492`) **and the box it draws** — section 10, because nothing clears the cursor bytes and `SelectMenuItem` decrements `wCurrentMenuItem` back into range on its way out | the game's list is **one-based** — `wCurrentMenuItem` is `wPlayerMoveListIndex + 1` and `wMaxMenuItem` is the move count plus one — so the accessor reports the 0-based slot, and `None` for an index that names no move | trace, and the press survey of section 10 | | the move list | `wTopMenuItemY` = 12, `wTopMenuItemX` = 5 (`MoveSelectionMenu`'s regular menu, `:2492`) | the game's list is **one-based** — `wCurrentMenuItem` is `wPlayerMoveListIndex + 1` and `wMaxMenuItem` is the move count plus one — so the accessor reports the 0-based slot, and `None` for an index that names no move | trace |
| the party list | `wTopMenuItemY` = 1, `wTopMenuItemX` = 0, `wMaxMenuItem` = `wPartyCount - 1`, watched keys `PAD_A\|PAD_B` or `PAD_A` alone (`PartyMenuInit`, `home/pokemon.asm:201`) | 0-based party slot | trace | | the party list | `wTopMenuItemY` = 1, `wTopMenuItemX` = 0, `wMaxMenuItem` = `wPartyCount - 1`, watched keys `PAD_A\|PAD_B` or `PAD_A` alone (`PartyMenuInit`, `home/pokemon.asm:201`) | 0-based party slot | trace |
| **a forced switch** | the party list, in a battle, with `wPartyMenuTypeOrMessageID` = `BATTLE_PARTY_MENU` (`$02`) at `$d07d`. `ChooseNextMon` is the battle path that sets it (`engine/battle/core.asm:1088`, and `:1389` for the "use next mon?" branch); choosing PKMN from the menu sets `NORMAL_PARTY_MENU` (`$00`, `:2316`), which is why the two are distinguishable. `wForcePlayerToChooseMon` (`$d11f`) is the byte `PartyMenuInit` turns into "A only, no way out". | — | trace | | **a forced switch** | the party list, in a battle, with `wPartyMenuTypeOrMessageID` = `BATTLE_PARTY_MENU` (`$02`) at `$d07d`. `ChooseNextMon` is the battle path that sets it (`engine/battle/core.asm:1088`, and `:1389` for the "use next mon?" branch); choosing PKMN from the menu sets `NORMAL_PARTY_MENU` (`$00`, `:2316`), which is why the two are distinguishable. `wForcePlayerToChooseMon` (`$d11f`) is the byte `PartyMenuInit` turns into "A only, no way out". | — | trace |
@ -196,7 +145,6 @@ forces. A battle that is neither — text, an animation, the turn resolving —
| a submenu | the weakest rule here, and the reason `Unknown` exists: `wListMenuID` is the bag or an elevator list, or the party list geometry outside a battle. A submenu none of those catch reads as `Unknown`, never as `Overworld`. | trace | | a submenu | the weakest rule here, and the reason `Unknown` exists: `wListMenuID` is the bag or an elevator list, or the party list geometry outside a battle. A submenu none of those catch reads as `Unknown`, never as `Overworld`. | trace |
| mart | `wTextBoxID` = `BUY_SELL_QUIT_MENU` (`$15`) for the BUY / SELL / QUIT choice, and `engine/events/pokemart.asm:17` is its only user in the game; the buy list is `wListMenuID` = `$02` and the sell list is the bag's own `$03`, recognised only while the mart's template is still the last one drawn. | trace | | mart | `wTextBoxID` = `BUY_SELL_QUIT_MENU` (`$15`) for the BUY / SELL / QUIT choice, and `engine/events/pokemart.asm:17` is its only user in the game; the buy list is `wListMenuID` = `$02` and the sell list is the bag's own `$03`, recognised only while the mart's template is still the last one drawn. | trace |
| PC | `wMiscFlags` bit 3, above. | trace | | PC | `wMiscFlags` bit 3, above. | trace |
| a two-option YES/NO box | **new 2026-09-22, generalised 2026-09-23** (`docs/design/macros.md` sections 12.12 and 12.20). `wFontLoaded` bit 0, plus a two-option cursor (`wMaxMenuItem` 1, `wMenuWatchedKeys` = A\|B), plus the border `DisplayTwoOptionMenu` drew **around the cursor it parked** -- see section 11. **Both halves are load-bearing**: the cursor bytes survive the box closing, so all forty-six frames of a nurse's conversation and all fifty-two of a gym guide's carry that geometry while the box is drawn on a handful of them. The border is no longer pinned to one rectangle, because Red places the menu where the script asking for it says and two of those places are surveyed. | ROM (the rung-10 Pokemon Center and the rung-10 Pewter Gym checkpoints, each surveyed one raw pulse at a time: `examples/scene_probe.rs`, `FLY_PROBE_CATCH=nurse` and `=dialog`) |
### Money and bag ### Money and bag
@ -526,13 +474,6 @@ Two facts about the emulator came out of building these and are worth keeping:
which is two battles away from anything a fixed-seed walk reaches quickly. The trace is built which is two battles away from anything a fixed-seed walk reaches quickly. The trace is built
from `ChooseNextMon` and `PartyMenuInit`, and the distinguishing byte from `ChooseNextMon` and `PartyMenuInit`, and the distinguishing byte
(`wPartyMenuTypeOrMessageID` = `BATTLE_PARTY_MENU`) is asserted both ways. (`wPartyMenuTypeOrMessageID` = `BATTLE_PARTY_MENU`) is asserted both ways.
- **`yes_no_prompt` is "*this* two-option box is drawn", not "a choice is open".** The claim in
earlier revisions of this file — that pokered has no observable for a choice — stands for the
general question and is now narrowed rather than withdrawn: the box the Pokémon Center nurse's
offer is drawn in has been surveyed on the cartridge and is readable, and every other
two-option menu in the game is not, because `DisplayTwoOptionMenu` takes its coordinates from
the script that calls it. A prompt this reading misses is a plain dialog, which is the pad it
had before the reading existed.
- **`text_box().waiting` is "the dialogue box is drawn", not "the game wants a button".** Pokered - **`text_box().waiting` is "the dialogue box is drawn", not "the game wants a button".** Pokered
has no flag for the second thing; A is the right press either way, so the distinction has no has no flag for the second thing; A is the right press either way, so the distinction has no
consequence for the palette, but it is not what the field's name might suggest. consequence for the palette, but it is not what the field's name might suggest.
@ -565,46 +506,9 @@ change, 648 bytes, checked on the WSL box.
| state | symbol | address | encoding | verified | | state | symbol | address | encoding | verified |
| --- | --- | ---: | --- | --- | | --- | --- | ---: | --- | --- |
| the open mart's stock | `wItemList` | `$cf7b` | `ds 16`. `LoadItemList` (`home/text_script.asm:156`) copies the clerk's `script_mart` list out of its text script the moment the counter opens: **a count byte** (the macro's `_NARG`), then the item ids, then `$ff`. `DisplayPokemartDialogue_` points the buy list's `wListPointer` at the same buffer for `PRICEDITEMLISTMENU`, so an item's position in this list is its cursor index in the buy menu **for the first three entries only** — see the correction below. | ROM (Viridian's counter reads POKE BALL, ANTIDOTE, PARLYZ HEAL, BURN HEAL, in that order, and no Potion), trace | | the open mart's stock | `wItemList` | `$cf7b` | `ds 16`. `LoadItemList` (`home/text_script.asm:156`) copies the clerk's `script_mart` list out of its text script the moment the counter opens: **a count byte** (the macro's `_NARG`), then the item ids, then `$ff`. `DisplayPokemartDialogue_` points the buy list's `wListPointer` at the same buffer for `PRICEDITEMLISTMENU`, so **an item's position in this list is its cursor index** in the buy menu — which is what lets a purchase be navigated by reading the cursor rather than by counting presses. The terminator wins over the count, as it does for the bag, and the sixteen-byte buffer bounds both. | ROM (Viridian's counter reads POKE BALL, ANTIDOTE, PARLYZ HEAL, BURN HEAL, in that order, and no Potion), trace |
| the tileset's counter tiles | `wTilesetTalkingOverTiles` | `$d532` | three tile ids from the tileset header (`data/tilesets/tileset_headers.asm`), `$ff` for a tileset with fewer. Mart and Pokecenter are both `$18 $19 $1e`; the overworld and an ordinary house have none. `IsSpriteOrSignInFrontOfPlayer`'s `.extendRangeOverCounter` branch (`home/overworld.asm:1115`) walks exactly this list and doubles the talking range from `$10` to `$20` pixels — one tile to two — when the tile in front of the player is one of them. | ROM (the Viridian mart's column 1 and the centre's (3, 2) read as counters and the floor either side does not), trace | | the tileset's counter tiles | `wTilesetTalkingOverTiles` | `$d532` | three tile ids from the tileset header (`data/tilesets/tileset_headers.asm`), `$ff` for a tileset with fewer. Mart and Pokecenter are both `$18 $19 $1e`; the overworld and an ordinary house have none. `IsSpriteOrSignInFrontOfPlayer`'s `.extendRangeOverCounter` branch (`home/overworld.asm:1115`) walks exactly this list and doubles the talking range from `$10` to `$20` pixels — one tile to two — when the tile in front of the player is one of them. | ROM (the Viridian mart's column 1 and the centre's (3, 2) read as counters and the floor either side does not), trace |
### 7.1 Correction, 2026-09-22 (row 55): the list byte and the cursor index both say less than this
Two claims in the table above were surveyed again from the live checkpoint the stream looped in
(`examples/scene_probe.rs`, `FLY_PROBE_CATCH=shop`, in the Pewter mart), and both are narrower
than they were written.
**`wListMenuID` says the counter is open, not which of its screens is up.** Section 2's row for it
says it is "zeroed by `DisplayTextIDInit` at the start of every text display, so a stale value
cannot outlive one". That holds for text the overworld displays and not for the mart's own: the
clerk's "Here you are! Thank you!" is printed from inside `DisplayPokemartDialogue_`, which never
calls the routine that clears it. Measured: **every frame of a mart visit read `PRICEDITEMLISTMENU`
`$02`** — the counter menu and each of the clerk's text boxes included — and on the counter menu
`wTextBoxID` reads `MONEY_BOX` `$0d` rather than `BUY_SELL_QUIT_MENU` `$15`, because the money box
is the last template drawn. So `ShopScreen::BuySellQuit` and `Selling` were unreachable in a mart
that had ever drawn a buy list, and the frame the stream sat on — a dialogue box waiting for a
press, with a two-option box's leftover cursor bytes (`wTopMenuItemY` 8, `wTopMenuItemX` 15,
`wMaxMenuItem` 1, `wMenuWatchedKeys` `$03`) — read as "the priced buy list is open".
The screen is now read from the figure the game draws, the construction [`text_box`]'s `waiting`
test and [`yes_no_prompt`] already use: the full-width box drawn and waiting is the clerk
(`ShopScreen::Talking`, new), the item window drawn is the buy list, and the item window blank is
the counter menu. The item window's own figure is its first name cell, screen (6, 4), which held
`$7f` on the counter menu and `P` of `POKE BALL` on every frame the list was drawn.
**The buy list scrolls, so a position in `wItemList` is a cursor index only for the first three
entries.** Walked one DOWN pulse at a time on the live list: the cursor went `0, 1, 2` and then
**stopped moving while the window scrolled under it** — the fourth drawn row is a look-ahead the
cursor never occupies. The absolute position of the item under the cursor is that index plus
`wListScrollOffset`, which is **not** in the reviewed address list and cannot be pinned without the
disassembly `gen_symbols.py` reads (the same refusal `$cfc5` met in section 9). Viridian's
four-item counter hid it: POKE BALL is 0 and ANTIDOTE is 1, both in reach. Pewter's seven-item
counter did not: its ANTIDOTE is **3**.
So the macros carry `MART_CURSOR_ROWS = 3` and a purchase past it is not on the pad
(`infra/docs/macros-traps.md` row 55). Pinning `wListScrollOffset` would widen that, and it is a
residual rather than a guess.
**Why the second one is load-bearing.** A mart clerk is `object_event 0, 5, SPRITE_CLERK` behind a **Why the second one is load-bearing.** A mart clerk is `object_event 0, 5, SPRITE_CLERK` behind a
counter running down column 1; a Pokémon Center nurse is `object_event 3, 1, SPRITE_NURSE` behind counter running down column 1; a Pokémon Center nurse is `object_event 3, 1, SPRITE_NURSE` behind
the counter tile at (3, 2). **None of the four tiles around either of them is standable** — they are the counter tile at (3, 2). **None of the four tiles around either of them is standable** — they are
@ -737,47 +641,6 @@ is exactly the shape of mistake the cross-check below exists for.
both are the old map — so only the *id* is wrong, and the check that catches it is one byte: does both are the old map — so only the *id* is wrong, and the check that catches it is one byte: does
the cached grid still agree with the screen about the tile the fly is standing on. the cached grid still agree with the screen about the tile the fly is standing on.
### The frame mid-step, which the check refused (2026-09-22, row 54)
The cross-check above refused on **every frame the fly was moving**, and the reason is a fact about
when the cartridge writes the coordinates. `FLY_PROBE_CATCH=step` in
`services/flysim/crates/flysim/examples/scene_probe.rs` holds one direction from a checkpoint and
prints, per frame, the coordinates, the grid's verdict, the tiles the two readings disagree on, and
every plausible candidate for "a step is in progress". Holding UP out of the Pewter museum:
| frame | `wYCoord` | the grid | the disagreement |
| ---: | ---: | --- | --- |
| 0 | 7 | ok | -- |
| 1 | 7 | ok | -- |
| 2 .. 15 | **7** | screen disagrees | (10, 7) decoded `$20`, screen `$01`; (11, 7) `$20` against `$01` |
| 16 | **6** | ok | -- |
| 19 .. 32 | 6 | screen disagrees | (10, 7) `$20`/`$01`; (11, 6) `$01`/`$50` |
| 33 | 5 | ok | -- |
Three readings come out of it, and the first is the one everything else follows from:
1. **The coordinates change at the *end* of a step.** A step is sixteen frames; `wYCoord` reads the
tile it began on for all of them but the last. The background scrolls throughout, so from the
second frame the screen buffer is already centred one tile ahead.
2. **`map_tile_id(x, y)` therefore answers for `(x + dx, y + dy)` mid-step**, where `(dx, dy)` is
the step. Verified on both arms of the trace: at frame 19 the screen's reading for (10, 7) is
the decode of (10, 6) and its reading for (11, 6) is the decode of (11, 5), exactly.
3. **No pinned address says a step is in flight.** The player sprite's Y and X step deltas
(`wSpriteStateData1 + 3` and `+ 5`) keep their last value after the step ends -- `$ff, $00` on
every frame of the trace after the first -- so they cannot tell a step from the one before it.
`wStatusFlags5` stayed `$00`, `wMovementFlags` tracked the warp tile the fly was standing on and
not the step, and `rSCY` lags the coordinates by a frame of its own. The one byte that does
track it exactly -- counting `$07 $07 $06 $06 … $01 $01` down to `$00` on the frame the
coordinates catch up -- is **`$cfc5`**, and `gen_symbols.py` refuses a hand-written address while
the checkout `resolve_wram.py` reads is not on this box. So it is recorded here and **not used**.
What the reader does instead is measure the anchor: the screen is centred on the fly's own tile or
on one of its four neighbours, and the anchor it is centred on is the one whose **whole**
neighbourhood agrees with the decode. `(0, 0)` is tried first, so a standing frame costs exactly
what it did before. The refusals the check exists for all survive, because a wrong stride, a wrong
quadrant, a half-loaded map and the mid-warp tear each disagree under every one of the five: the
neighbourhood has to agree as a unit rather than tile by tile.
### The survey, on two maps ### The survey, on two maps
`services/flysim/crates/flysim/tests/rom_map_grid.rs`, the method of `services/flysim/crates/flysim/tests/rom_map_grid.rs`, the method of
@ -802,304 +665,3 @@ answers that, and the executor's per-step moved check covers the rest), a warp t
step onto it, and a script that pushes the fly off a tile (a session ledger answers that). The step onto it, and a script that pushes the fly off a tile (a session ledger answers that). The
water half of the tile-pair lists is deliberately absent: it is the list water half of the tile-pair lists is deliberately absent: it is the list
`CheckForJumpingAndTilePairCollisions` uses while surfing, and the palette cannot surf. `CheckForJumpingAndTilePairCollisions` uses while surfing, and the palette cannot surf.
## 10. A menu that is accepting input, against one that is only remembered (2026-09-22, row 50)
`HandleMenuInput` is shared by every menu in the game (section 2) and so are the five bytes it
parks a cursor in. Section 2's table reads those bytes to say *which* menu is up; it does not say
whether anybody is reading them. The difference is the whole of row 50: `MOVE n` reported `blocked`
**890 times in 1,431 macros** on the cartridge, every one of them on a frame the seam called an
open move list with a placeable cursor.
**Nothing in the game clears the cursor bytes.** `MoveSelectionMenu` writes `wTopMenuItemY` 12 and
`wTopMenuItemX` 5 once, and the whole of the turn that follows — the text, the animation, the
damage, the enemy's reply — reads them back unchanged. It is the same fact section 7's YES/NO box
rests on ("the cursor bytes survive the box closing"), and the reason the battle's *top-level* menu
never had this problem is that it carries `wTextBoxID` = `$0b` beside its geometry.
`SelectMenuItem` makes it worse rather than better: on its way out of `HandleMenuInput` it does
`ld a, [wCurrentMenuItem] / dec a / ld [wCurrentMenuItem], a`, turning the menu's one-based index
back into a 0-based move slot. That lands straight back inside the range the accessor reads as a
valid one-based slot, so a turn spent on move 2, 3 or 4 leaves a *placeable* cursor behind it.
### The accessor
| state | how | verified |
| --- | --- | --- |
| the move list is **accepting input** | the cursor at `wTopMenuItemY` 12 / `wTopMenuItemX` 5 **and** the figure `MoveSelectionMenu` draws: a `TextBoxBorder` at (4, 12) fourteen wide and four tall, with a horizontal run written over its top-left corner and the `┘` junction written over (10, 12) (`engine/battle/core.asm`, `.regularmenu`). Read whole — both verticals, both horizontal runs, all four corners — because a single frame tile id is an ordinary character. The mimic and relearn menus draw at row 7 and never reach a battle's own turn. | survey (below) |
`Scene::Battle { own_turn }` follows it: a frame whose move list is not on screen reads
`BattleMenu::None`, which is nobody's turn, which is the between-turns row and its one `NEXT`
(`docs/design/macros.md` 12.10). Nothing else moves — the top-level menu, the party list and the
bag keep the readings they had.
### The survey
`examples/scene_probe.rs`, `FLY_PROBE_CATCH=accept`, from the rung-9 forest checkpoint. The
question "is this menu accepting input" is answered by **pressing at it**, not by nominating a
flag: on every battle frame the emulator exports its state, one directional pulse is issued,
`wCurrentMenuItem` is read, and the state goes straight back — `HandleMenuInput` moves the cursor
on UP and DOWN before it even looks at `wMenuWatchedKeys`, so a cursor that moves is a menu running
its input loop. The pulse *releases* the buttons first, because `JoypadLowSensitivity` acts on a
key's edge and a direction the fly is already holding would read as refused for the measurement's
reason rather than the cartridge's.
| the reading | press refused | press honoured |
| --- | ---: | ---: |
| the cursor bytes alone (what the seam read before row 50) | 2,838 | 264 |
| the cursor bytes **and** the box on screen | **0** | **231** |
| the cursor bytes with no box drawn | 2,838 | 33 |
So 91.5% of the frames the old reading called an open move list were frames no press reached, and
the reading that survives is exact on the 231 it keeps. (The 33 are frames where the pulse's own
thirty frames were long enough for the cartridge to open something by itself; the pulse is a
measurement and not a claim about one frame.)
Beside the press, the probe asks **every byte of WRAM and HRAM** whether its values on accepting
frames are disjoint from its values on refusing ones, so a reading is found rather than guessed.
Over the move list, once the box is in the reading, no byte separates the two classes at all —
there is nothing left to separate. Over the whole class before the fix, the only separators were
the HRAM joypad bytes, which is the measurement seeing its own held button.
### What the same survey found and this section did not fix
- **The top-level battle menu is already exact**: 413 frames, 0 refused. `wTextBoxID` is why.
- **The bag is the same trap, unfixed and named.** `wListMenuID` = `ITEMLISTMENU` outlives the bag
exactly as the cursor bytes outlive the move list: 449 refused against 36 honoured over the
frames the seam calls an open battle bag. The bag list is drawn in the top half of the screen and
the survey has not yet found the figure that tells it from the frame after it closes, so it is
reported rather than guessed — `docs/design/ladder.md`'s rule. `ITEM` and `THROW BALL` are the
two macros it costs.
- **The party list, likewise**: `PartyMenuInit`'s geometry outlives its list.
## 11. A two-option box is the one the cartridge drew (2026-09-23, `docs/design/macros.md` 12.20)
Section 10 read one menu by the figure it draws; row 41 read the YES/NO box the same way but at a
**pinned** rectangle, (11, 6)-(19, 11), and named the limit in its own residual: Red places a
two-option menu where the script asking for it says, so a prompt drawn elsewhere read `false`.
Row 56 is that residual, live: the Pewter Gym guide's "Let me take you to the top!" draws the same
menu at **(14, 7)-(19, 11)** with the shared cursor at row 8, column **15**. Over 260 surveyed
presses of his conversation the box was drawn on **10** frames and `yes_no_prompt` answered `false`
on **all 260** -- so the dialog pad was `NEXT, YES, NO` on a box that was a choice, and the whole of
12.12 (no `NEXT` on a prompt, the nurse's one bound answer, the reopened-prompt exclusion) was
inert wherever the box was not the centre's.
### The accessor
Nothing in the reviewed symbol list says "a choice is open" and nothing can be added by hand
(`gen_symbols.py` refuses a hand-written address, and the disassembly is not built on this box), so
the reading is the construction `text_box`'s `waiting` already makes -- a WRAM flag plus the figure
-- with the figure **found** rather than pinned:
1. `wFontLoaded` bit 0, as for every text display;
2. the cursor is a two-option menu's: `wMaxMenuItem` 1 and `wMenuWatchedKeys` = A\|B;
3. the border's **left edge is one column to the left of `wTopMenuItemX`**, because
`DisplayTwoOptionMenu` writes the cursor into the box's first interior column. This holds in
both surveyed boxes -- left 11 with the cursor at 12, left 14 with the cursor at 15 -- and it is
the only geometric relation that does;
4. the **top** is looked up from the cursor's row for the border's own top-left corner, at most
three rows, because the nurse's box begins two rows above the first item and the guide's one:
one menu carries a caption line and the other does not;
5. and the rest of the figure is then read **whole** by `border_drawn` -- both verticals, both
horizontal runs and all four corners -- because a single frame tile id is an ordinary character.
### The survey
`examples/scene_probe.rs`, `FLY_PROBE_CATCH=dialog`, which walks a conversation one raw pulse at a
time and prints, per frame, the seam's reading beside **every complete `TextBoxBorder` on screen**
(`state::drawn_boxes`, a diagnostic that tries every rectangle rather than one). Two checkpoints,
400 frames:
| checkpoint | a box drawn above the dialogue box | `wTextBoxID` = `TWO_OPTION_MENU` (`$14`) | the new reading | frames |
| --- | --- | --- | --- | ---: |
| rung-10 Pewter Gym | false | false | false | 250 |
| rung-10 Pewter Gym | **true** | **true** | **true** | 10 |
| rung-10 Pokémon Center | false | false | false | 136 |
| rung-10 Pokémon Center | **true** | **true** | **true** | 4 |
The three agree exactly on all 400 frames. **`wTextBoxID` is recorded and not used**: it would be a
tighter reading still, and row 41's own note says the nurse's *plain* boxes read `$01` — which is
confirmed here — but no survey on this branch covers Red's other two-option menus, and a reading
this crate has not verified does not go in (`docs/design/ladder.md`). It is the named strengthening.
### What it does not claim
A frame whose two-option cursor bytes have outlived their box reads `false`, which is the whole
point of reading the figure; a border drawn somewhere the cursor is not parked is not the cursor's
box; and a menu of more than two options is not this menu. What the pad makes of a readable prompt
is `pokemon_red::macros::palette`'s business (`docs/design/macros.md` 12.12 and 12.20), not this
accessor's.
## 12. The people off the screen, and a battle decided (2026-09-23, `docs/design/macros.md` 12.22)
Two readings row 58 added, both out of bytes the seam already had or a byte bracketed by two it had.
### `state::offscreen_npcs`
`CheckSpriteAvailability` (`engine/overworld/movement.asm`) writes `$ff` into
`SPRITESTATEDATA1_IMAGEINDEX` (offset 2) for a sprite that is a toggleable object switched off, that
is outside its window, or that stands on a text box's tiles. The window, for a sprite whose
`SPRITESTATEDATA2_MOVEMENTBYTE1` (offset 6) is `WALK` (`$fe`) or `STAY` (`$ff`), compares the
sprite's biased `MAPY` / `MAPX` (offsets 4 and 5) with `wYCoord` / `wXCoord`: drawn when equal, or
when the sprite's is greater by at most `SCREEN_HEIGHT / 2 - 1` (8) rows and
`SCREEN_WIDTH / 2 - 1` (9) columns. A scripted mover (movement byte below `WALK`) skips the test.
So a `$ff` sprite of the loaded map whose coordinates fall **outside** the window, and whose
movement byte is `WALK` or above, is reported with those coordinates: the cartridge would hide it
for being off the screen whatever else were true, and a sprite it is not updating does not move.
Everything else `$ff` is not reported. Measured from the row-58 checkpoint at the Pewter Gym's
doormat: BROCK at (4, 1) and the Jr. Trainer at (3, 6) reported, the guide at (7, 10) drawn.
What it cannot tell is a toggleable object switched off from one out of sight, because both are
`$ff` outside the window. Its one reader is the rung's own list of people; the ladder's person
places are Oak's lab and the gyms, and only the lab and Viridian Gym carry toggleable people
(`data/maps/toggleable_objects.asm`).
### `poke::CUR_OPPONENT`, `wCurOpponent`
Written when a battle is decided (`home/trainers.asm` for a trainer, the encounter check for a wild
one), cleared by `EndOfBattle` in the same block that clears `wIsInBattle`. Not in the generated
table: `ram/wram.asm` at the pinned commit declares `wIsInBattle:: db`,
`wPartyGainExpFlags:: flag_array PARTY_LENGTH` (one byte), `wCurOpponent:: db`,
`wBattleType:: db`, `wDamageMultipliers:: db`, `wGymLeaderNo:: db`, `wTrainerNo:: db`, and the
table's `wIsInBattle` (`$d057`), `wBattleType` (`$d05a`) and `wTrainerNo` (`$d05d`) are exactly
where that layout puts them, so the byte is `wBattleType - 1` = `$d059`, asserted against both
neighbours in `scene/tests.rs`. Measured on the cartridge in the Pewter Gym: `$00` in the
overworld, `$cd` (`OPP_JR_TRAINER_M`) from the last box of the trainer's challenge through the
219-frame transition and the battle. `controllable` reads it as zero.
## 13. What a move will do: the move table and the bytes its effect reads (2026-09-23, `docs/design/macros.md` 12.23)
Row 60. Seven addresses, resolved by `tools/resolve_wram.py` and emitted into `symbols.rs`; the
tool now follows the decomp's `const` and `_RS` counters and a struct macro's field labels, which
is what reaches the `battle_struct` fields, and it re-derives 77 of 81 pinned addresses with no
disagreement.
| symbol | address | what reads it |
| --- | --- | --- |
| `wPlayerMonStatMods` | `$cd1a` | six stages, ATTACK DEFENSE SPEED SPECIAL ACCURACY EVASION; 1 is -6, 7 normal, 13 is +6 |
| `wEnemyMonStatMods` | `$cd2e` | the same for the enemy |
| `wEnemyMonStatus` | `$cfe9` | the enemy's status byte (`battle_struct` +4) |
| `wEnemyMonType1` | `$cfea` | and `Type2` after it |
| `wEnemyMonAttack` | `$cff6` | the enemy's modified ATTACK DEFENSE SPEED SPECIAL, big-endian words |
| `wBattleMonAttack` | `$d025` | the same for the fly's Pokémon |
| `wEnemyBattleStatus2` | `$d068` | bit 1 Mist, 4 substitute, 5 must recharge |
**The move table is ROM.** `Moves` opens `SECTION "Battle Engine 7"`, which `layout.link` places
first in bank `$0E`, so it is `$0E:$4000`, six bytes a row in move-id order from `POUND`:
animation (the move id itself), effect, power, type, accuracy, PP. `state::move_data` reads a row
through `MemoryReader::read_rom`, the cartridge image, and refuses a row whose first byte is not the
id asked for. Measured from the row-60 checkpoint: TACKLE (`$21`) effect `$00` power 35, TAIL
WHIP (`$27`) effect `$13` (`DEFENSE_DOWN1_EFFECT`) power 0.
**`state::move_without_effect`** answers only refusals decided before the roll, for a move with no
power, from `engine/battle/effects.asm` and `MoveHitTest`:
- `*_UP1` / `*_UP2`: the user's stage is 13, or (ATTACK..SPECIAL) the stat is 999;
- `*_DOWN1` / `*_DOWN2`: the target has Mist or a substitute, its stage is 1, or (ATTACK..SPECIAL)
the stat is 1 -- `StatModifierDownEffect` restores the stage and prints "Nothing happened!"
then, so a low-level target reaches it before -6;
- `SLEEP_EFFECT`: any status, unless the target must recharge;
- `POISON_EFFECT`: a substitute, any status, or a Poison type;
- `PARALYZE_EFFECT`: any status, or an Electric move against a Ground type.
`None` outside a battle, without a cartridge, or with a stage byte outside 1..13.
**Not covered** (the reading would be the same kind, and nothing early in the game reaches it):
Confuse Ray and Supersonic on a confused target, Leech Seed on a seeded or Grass target, Focus
Energy, Mist, Reflect and Light Screen already up, Disable on a disabled target, and a damaging
move the type chart makes "doesn't affect" (the chart is another ROM table).
## 14. What an item will do, and the joypad the cartridge last read (2026-09-24, `docs/design/macros.md` 12.27)
Row 63. Two addresses, both pinned and read back from the code that uses them by
`row63_the_joypad_latch_and_the_item_table_are_where_the_cartridge_says` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `ItemUsePtrTable` | `$03:$55E1` | one little-endian routine pointer per item id, `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`); the operand of `UseItem_`'s `ld hl` |
| `hJoyLast` | `$FFB1` (HRAM) | the buttons `_Joypad` saw down last time the game asked; the operand of `_Joypad`'s `ldh a, [hJoyLast]` at `$03:$4000` |
**`state::item_routine`** reads an item's pointer and refuses a table where the five balls or the
potions and status heals do not share one routine. **`state::battle_item_use`** classes an item by
its routine, never by its id: the routine of `POKE_BALL`, `POTION`, `POKE_DOLL`, `ETHER`, or one of
`X_ACCURACY`, `GUARD_SPEC`, `DIRE_HIT`, `X_ATTACK`, `POKE_FLUTE`, and answers each one's check before
it acts (`engine/items/item_effects.asm`): a ball in a wild battle (a full party is `None`, the box
count unread; a trainer is `false`); medicine with somebody it would change, `ItemUseMedicine`'s
own id order (Revive: fainted; Full Heal and the status heals: that status; Full Restore: hurt or
statused; the HP items: neither fainted nor full), the Pokémon that is out read from the battle's
copy; a Poké Doll in a wild battle; the X items and the flute in any battle; a PP restore with a
move below its PP (PP Ups counted). Every other routine refuses in a battle. A TM or an HM goes to
`ItemUseTMHM` before the table and is `None`.
**`state::a_latched`** is `hJoyLast` bit 0 (`PAD_A`). `hJoyPressed` is `hJoyInput & ~hJoyLast`,
and the game only calls `_Joypad` while something reads input, so after the A that confirms a list
the latch keeps that A until the next list first asks. Measured on the Potion's party list: the
list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120
rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and
HRAM whose values never overlap between lost and answered frames.
## 15. The naming screen (2026-09-29, `docs/design/macros.md` 12.32)
Row 69. Two bytes of a `UNION` in `ram/wram.asm` that the reviewed list does not carry, pinned the
way `hJoyLast` is and read back from the code that stores them by
`row69_the_naming_bytes_are_where_the_cartridge_stores_them` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `wNamingScreenNameLength` | `$CEE9` | the letters typed; the operand of `PrintNicknameAndUnderscores`'s `ld [wNamingScreenNameLength], a` before `hlcoord 10, 2` |
| `wNamingScreenSubmitName` | `$CEEA` | non-zero once START or ED is taken; the operand of `.pressedStart`'s `ld [wNamingScreenSubmitName], a` |
**`state::naming_screen`** is the keyboard only when the menu bytes `DisplayNamingScreen` writes
(`wTopMenuItemY` 3, `wMaxMenuItem` 7, `wMenuWatchedKeys` `$ff`) **and** its figure are on screen:
the whole `TextBoxBorder` at (0, 4)-(19, 14) and a run of seven or ten underscores (`$76`, the raised
one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH - 1` or
`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for
`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before
`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first.
## 16. The list's scroll offset (2026-10-01, `docs/design/macros.md` 12.34)
Row 71. One byte the reviewed list does not carry. It is pinned the way `hJoyLast` is, and
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM) reads it back from the
code that uses it. Section 7's "cannot be pinned" applied to the symbol table. The pin comes from
the cartridge instead.
| name | where | what reads it |
| --- | --- | --- |
| `wListScrollOffset` | `$CC36` | entries scrolled off the top of a `DisplayListMenuID` window; the operand of `DisplayListMenuIDLoop.buttonAPressed`'s `ld a, [wCurrentMenuItem] / ld c, a / ld a, [wListScrollOffset] / add c / ld c, a`, found once in the cartridge |
**`BattleMenu::Bag`'s `cursor`** is now `wCurrentMenuItem + wListScrollOffset`, the bag entry
under the arrow, which is the sum the cartridge makes on A. In the live trap the arrow was on row 1
with an offset of 3, so it was on entry 4, the Poké Ball. `state::shop`'s buy and sell lists
report their cursor (and its `max`) as the entry the same way. The offset is added only while a
list is on screen, because the byte outlives every list. Purchases still use only the first three
rows (`MART_CURSOR_ROWS`, section 7).
## 17. The hidden-event tables (2026-10-02, `docs/design/macros.md` 12.35)
Row 73. Two ROM tables, read through `MemoryReader::read_rom` from the cartridge image the process
already holds, never through the bus and never by switching banks. Pinned the way
`ItemUsePtrTable` is, and read back from the code that uses them by
`row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `HiddenEventMaps` | `$11:$6A40` | one map id per byte to a `$ff` (85 maps at the pinned commit); the operand of `CheckForHiddenEvent`'s `ld hl, HiddenEventMaps`, followed by `ld a, [hli] / ld b, a / cp $ff` |
| `HiddenEventPointers` | `$11:$6A96` | one little-endian pointer per map of the list above, into the same bank; the operand of the routine's `ld hl, HiddenEventPointers`, followed by `add hl, de` |
Both are in `SECTION "Hidden Events Core"`, which `layout.link` places in bank `$11`. Each map's
list is six bytes an entry to a `$ff` (`hidden_event`): y, x, the routine's argument, and the
routine as `dba` (bank, then a little-endian address). The coordinates are in the same tile space as
`wXCoord`/`wYCoord`, like a sign's.
**`state::hidden_events`** answers the current map's entries as `HiddenEvent { x, y, index,
facing }`: `index` is the entry's position in the map's list, which is how `wHiddenEventIndex`
counts and the talked ledger's key (`TalkTarget::Hidden`); `facing` is the argument when it is a
`SPRITE_FACING_*` value (`$00`, `$04`, `$08`, `$0C`), the side a routine such as `BillsHousePC`
checks. It answers nothing for a map list with no end within 128 entries or an id above `$f7`, a
pointer outside `$4000..$8000`, a list longer than 64 entries (the Game Corner's 48 are the longest), a tile off the loaded map or a
routine address at `$8000` or above. Bill's house (`$58`) has one entry: (1, 4), argument `$04`,
`BillsHousePC` at `$07:$6B6E`.

File diff suppressed because it is too large Load diff

View file

@ -68,15 +68,6 @@ already created. Builders use separate worktrees; the coordinator reviews contra
- **Done:** empty required populations, malformed CSR and incorrect profile restores fail; - **Done:** empty required populations, malformed CSR and incorrect profile restores fail;
legacy FAFB artifacts and default numerical version strings remain unchanged. legacy FAFB artifacts and default numerical version strings remain unchanged.
**2026-09-23: split by operator decision.** PROF-02a, the legacy profile, is done as a contract:
[legacy Game Boy composition v1](session-framework/legacy-gameboy-v1.md) defines
`gameboy-legacy-fafb-v783-v1` (today's schema-1 fingerprint embedded, `lif-1ms-f64-v2` and
`fly-kc-mbon-rstdp-v2` unchanged, the macro-role exception declared), the readout context
`gameboy-readout-context-v1`, the decision `gameboy-channels-v1`, and a composition declaration
whose digest carries the decoder and macro-channel configuration instead of the legacy
compatibility string. PROF-02b -- the bundle manifests, role mapping, strict graph validation and
profile-mismatch fixtures above -- is later and gates DATA-01, not the session port.
### DATA-01 — Acquire and normalize MaleCNS ### DATA-01 — Acquire and normalize MaleCNS
- **Branch:** `feat/malecns-import` - **Branch:** `feat/malecns-import`
@ -117,16 +108,6 @@ profile-mismatch fixtures above -- is later and gates DATA-01, not the session p
- **Done:** existing single-agent action/reward traces match and a fake environment can be - **Done:** existing single-agent action/reward traces match and a fake environment can be
driven through the same boundary without importing binjgb or task-specific addresses. driven through the same boundary without importing binjgb or task-specific addresses.
**2026-09-23: contract written (RT-01a), implementation pending.** The operator decided the
boundary: macros run in the coordinator's action executor over a per-boundary 64-KiB memory
image carried as an inspection artifact plus the ROM as an `AssetRef`; the emulator shim gains
one read-only bulk read and the joypad stays its only write; the Pokémon task and executor are
one object (`pokered-macros-v1`); the ratchet is the `legacy-ratchet-rollback-v1` episode policy
over the environment extension `gameboy-slots-v1`. The dated amendments are in
[workers-v1](session-framework/workers-v1.md), [step-v1](session-framework/step-v1.md) and
[state-media-v1](session-framework/state-media-v1.md); the session implementation guide's
ENV-01 carries the build.
### RUNTIME-02 — Extract the single-agent session ### RUNTIME-02 — Extract the single-agent session
- **Branch:** `refactor/session-runtime` - **Branch:** `refactor/session-runtime`

View file

@ -548,14 +548,6 @@ clock may lead environment time by warm-up; persist that offset instead of prete
clocks start at zero. Rendering, physics and decision cadence may differ, but the backend clocks start at zero. Rendering, physics and decision cadence may differ, but the backend
must define their relationship. must define their relationship.
**Amendment, 2026-09-23 (operator decision of 2026-09-23).** "Preserve the detailed legacy
ordering inside the legacy single-agent composition" now means inside a legacy composition that
runs on the session framework's `lockstep-v1`, not beside it: the operator decided on a full port.
The detailed ordering is preserved because it is already the lockstep transaction order with one
agent ([legacy-gameboy-v1](session-framework/legacy-gameboy-v1.md) section 4), and "keep the
legacy floating remainder arithmetic" costs nothing, because the legacy `f64` frame constant is
exactly the rational Game Boy frame and the two accumulators are identical (section 3 there).
Start with sequential agent evaluation for reproducibility. Then compare parallel agent Start with sequential agent evaluation for reproducibility. Then compare parallel agent
evaluation against the same action trace. Cap total worker budget: `agents × brain_threads` evaluation against the same action trace. Cap total worker budget: `agents × brain_threads`
can otherwise oversubscribe the machine. Use private pools for concurrent agents or serialize can otherwise oversubscribe the machine. Use private pools for concurrent agents or serialize
@ -613,9 +605,7 @@ jobs so repeated copies cannot exhaust memory under slow storage.
Exact replay requires action-executor and admission state, not just the neural envelope. Exact replay requires action-executor and admission state, not just the neural envelope.
Legacy macros intentionally discard transient execution on restart; preserve that behavior Legacy macros intentionally discard transient execution on restart; preserve that behavior
for v1 and label it as legacy continuation semantics, not exact session replay. for v1 and label it as legacy continuation semantics, not exact session replay. New sessions
(*2026-09-23:* the label is `restore: legacy-transient-reset`, declared by the legacy
composition, [legacy-gameboy-v1](session-framework/legacy-gameboy-v1.md) section 14.) New sessions
persist all behavior-affecting state or explicitly restart an episode under a documented rule. persist all behavior-affecting state or explicitly restart an episode under a documented rule.
Keep `FLYSIM01` readable through a legacy adapter. Never silently rewrite a checkpoint on Keep `FLYSIM01` readable through a legacy adapter. Never silently rewrite a checkpoint on

View file

@ -33,27 +33,6 @@ retroactively to existing [public feed](../../feed-protocol.md),
5. [Session media/state](state-media-v1.md) — observation timing and coherent recovery. 5. [Session media/state](state-media-v1.md) — observation timing and coherent recovery.
6. [Application/presentation boundary](publishing-v1.md) — snapshots, flexible data and effects. 6. [Application/presentation boundary](publishing-v1.md) — snapshots, flexible data and effects.
7. [Implementation guide](implementation.md) — sequenced build tasks and acceptance tests. 7. [Implementation guide](implementation.md) — sequenced build tasks and acceptance tests.
8. [Flybus conformance report](bus-conformance.md) — the `flybus` crate audited sentence by
sentence against bus-v1, with the test that proves each row, the measurements and the
draft's own contradictions. A review artifact, not a contract.
Two derived specifications, written by CONTRACT-01 because the slices that need them cannot
be built without them:
- [Seed derivation v1](seed-derivation-v1.md) — independent per-agent seeds from one recorded
master seed and stable agent ids, with test vectors in both languages.
- [Checkpoint envelope v1](checkpoint-envelope-v1.md) — the exact bytes of the new `FLYSESS1`
envelope and the durable commit sequence. `FLYSIM01` is unchanged and stays separately
readable.
One contract added by the 2026-09-23 amendments (PROF-02a, RT-01a), after the operator decided
to port the live fly onto this framework:
- [Legacy Game Boy composition v1](legacy-gameboy-v1.md) — the legacy profile
`gameboy-legacy-fafb-v783-v1`, its readout context and decision schemas, the memory-image
inspection, the `pokered-macros-v1` executor, the `gameboy-slots-v1` environment extension,
the `legacy-ratchet-rollback-v1` episode policy, `legacy-transient-reset` restore semantics and
the composition digest. MaleCNS bundles (PROF-02b) come later.
For context: [modular-session analysis](../malecns-modular-sessions.md) and For context: [modular-session analysis](../malecns-modular-sessions.md) and
[Melee audit](../melee-framework-audit.md). Each contract owns its named subject; step ordering [Melee audit](../melee-framework-audit.md). Each contract owns its named subject; step ordering
@ -78,10 +57,7 @@ Application / supervisor Application presentation
This diagram is connectivity, not execution order. The step contract defines causal order. This diagram is connectivity, not execution order. The step contract defines causal order.
One router can host several independent sessions and application consumers; a deployment may One router can host several independent sessions and application consumers; a deployment may
choose one router per application for fault isolation. A router crash affects all its clients, choose one router per application for fault isolation. A router crash affects all its clients,
so choose that boundary deliberately. In-process mode still exercises routing and ownership, so choose that boundary deliberately. In-process mode still exercises routing and ownership.
unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1,
amendment 2026-09-30), as the legacy composition's in-process release configuration is; process
mode always goes through the router.
Defaults: coordinator per session, worker per fly, environment worker per world. Task and Defaults: coordinator per session, worker per fly, environment worker per world. Task and
per-agent executors begin as coordinator-local libraries. An environment helper may own a per-agent executors begin as coordinator-local libraries. An environment helper may own a
@ -138,19 +114,6 @@ versions, historical arithmetic/fingerprints and FLYSIM01 reader. New identities
readout/executor/task/scheduler semantics. New public feed v2 is an application/presentation readout/executor/task/scheduler semantics. New public feed v2 is an application/presentation
gateway contract built on the same internal bus; it does not replace the bus or expose it raw. gateway contract built on the same internal bus; it does not replace the bus or expose it raw.
**Amendment, 2026-09-23 (operator decision of 2026-09-23).** "Keep legacy-gameboy-v1 distinct
from lockstep-v1" is superseded for scheduling. The operator decided on a **full port** of the
live fly onto the session framework: the legacy composition runs under `lockstep-v1` with one
agent, one port and one world, declared as [legacy-gameboy-v1](legacy-gameboy-v1.md). What the
sentence protected is kept, and now written down rather than implied: the legacy frame order is
this framework's transaction order (legacy-gameboy-v1 section 4); the historical fingerprint,
the default version strings and the compatibility string are unchanged and embedded, not
recomputed; the legacy clock is proven identical to the rational one (section 3); `FLYSIM01`
stays the format of record and its reader untouched until RETIRE-01; and the legacy restore and
rollback semantics are declared (`legacy-transient-reset`, `legacy-ratchet-rollback-v1`) rather
than approximated. The new identity covers what the old string never did: readout context,
decision, decoder configuration and macro channels, executor, slots and restore semantics.
## 5. Reuse criterion ## 5. Reuse criterion
Adding a third environment/application requires a backend, task/profile, composition and Adding a third environment/application requires a backend, task/profile, composition and

View file

@ -1,519 +0,0 @@
# Flybus v1 conformance report: the `flybus` crate against `bus-v1`
Status: **audit, 2026-09-22**. Subject: `services/flysim/crates/flybus`, the replayed
implementation of [Flybus v1](bus-v1.md) (draft 1, 2026-09-18), with no consumers yet. Scalar
encodings come from [ipc-v1](ipc-v1.md) sections 1 to 3. Acceptance lists come from the
[implementation guide](implementation.md) slices BUS-01, BUS-02 and BUS-03.
Every normative sentence of bus-v1 sections 2 to 11 gets a row. Four statuses:
| Status | Meaning |
| --- | --- |
| conforms | The implementation does what the sentence requires, and a test proves it. |
| deviates-allowed | It differs, and a quoted sentence of the draft permits the difference. |
| deviates-must-fix | It differs and the draft requires otherwise. |
| not-implemented | Not built yet; the row names who owns it. |
Counts over 195 rows: **conforms 178, deviates-allowed 9, deviates-must-fix 1 (fixed),
not-implemented 7**. The audit found the one deviates-must-fix — connection teardown could be
starved for the length of a whole frame by the writer it was waiting for — and it is fixed on
this branch, so the row for it now reads conforms and records the fix (section 9, "cannot be
starved"). Two contradictions inside the draft are recorded at the end and left alone.
Test names below are the functions in `services/flysim/crates/flybus/tests`, 239 of them in
this branch (`cargo test -p flybus`), plus the ignored measurement. Everything marked
"(both)" is generated twice by the `both_transports!` macro, once over the in-memory transport
and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
`in_memory::request_reply_roundtrip` and `unix_socket::request_reply_roundtrip`.
## 2. Client API
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| One client/connection serves RPC, pub/sub and artifacts | conforms | `client/mod.rs::Client` | `tests/integration.rs::session_over_one_router` (both) |
| The illustrative surface (`connect`, `register`, `call`, `subscribe`, `publish`, `artifacts().allocate`, `seal`, `message.artifact`) | deviates-allowed: "Illustrative Rust surface (not yet implemented)"; `connect` takes the transport, `call` takes no `budget`, `next()` yields `Option` | `client/mod.rs`, `client/handles.rs` | `tests/rpc.rs`, `tests/pubsub.rs`, `tests/artifacts.rs` |
| The artifact store is a storage backend of the bus, not another messaging service | conforms | `store.rs`, reached only through `Artifacts`/`Artifact` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Bulk data does not pass through router socket payloads; no separate data-transfer API | conforms: attachments carry `ArtifactRef` only; envelopes are capped at 64 KiB | `wire.rs::ArtifactRef`, `wire.rs::MAX_ENVELOPE_BYTES` | `tests/wire.rs::envelope_size_limits` (both), `tests/perf.rs` |
| `Artifact` is a read-only, cloneable handle | conforms | `client/handles.rs::Artifact` (no write API, `#[derive(Clone)]`) | `tests/conformance_artifacts.rs::extracted_artifact_outlives_the_message_it_came_from` (both) |
| `ArtifactWriter` is unique, not cloneable; sealing consumes its writable lifetime | conforms | `client/handles.rs::ArtifactWriter::seal_with_digest(mut self)` | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both) |
| Mapped slices cannot outlive their handle | conforms by construction: there is no mapping API; `ArtifactFile` owns its `Artifact` | `client/handles.rs::ArtifactFile` | `tests/bus_acceptance.rs::disconnect_releases_logical_ownership_without_mutating_open_bytes` (both) |
| Rust RAII automates releases | conforms | `client/handles.rs::OwnerGuard::drop` | `tests/artifacts.rs::fan_out_shares_one_object_and_the_last_consumer_collects` (both) |
| Other language bindings provide equivalent explicit close/context-manager behaviour | not-implemented (Rust only; section 1 says a binding "may" exist). Owner: a future binding | — | — |
| Garbage collection means reclaiming an unowned artifact, not inspecting game state | conforms | `router/state.rs::drop_roots` | `tests/conformance_artifacts.rs::collection_waits_for_every_retained_owner` (both) |
## 3. Addressing and identities
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Every identity of the table exists: `routerId`, `clientId`/`clientIncarnation`, `connectionId`, `service`/`serviceIncarnation`, `callId`, `topic`/`topicIncarnation`/`topicSequence`, `deliveryId`, `artifactId`/`generation`, `ownerId` | conforms | `router/mod.rs::fresh_tag`, `router/state.rs` (`serial_id` for `conn`/`svc`/`top`/`sub`/`dlv`/`own`/`a`) | `tests/conformance_wire.rs::hello_reports_the_contract_digest_and_valid_limits` (both), `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
| A fresh `routerId`/`storeId` per incarnation; old handles fail after restart | conforms | `router/mod.rs::Router::new` | `tests/artifacts.rs::router_restart_invalidates_old_handles` (both) |
| Reconnect creates a new `clientIncarnation`; v1 does not resume a connection's queues or delivery owners | conforms | `router/state.rs::hello` refuses a reused incarnation; `disconnect` releases everything | `tests/sol_review_races.rs::caller_disconnect_cleanup_works_before_and_after_consumption` |
| Identifiers are bounded ASCII; `Id` and `U64` match ipc-v1 | conforms: `^[a-z0-9][a-z0-9._-]{0,63}$`, `"0"\|[1-9][0-9]*` | `wire.rs::is_id`, `wire.rs::parse_u64` | `wire.rs::tests::scalars`, `tests/conformance_wire.rs::malformed_envelope_scalars_are_rejected` (both) |
| Service/topic names are 1..192 of `[a-z0-9._-]` with no empty dot-separated segment | conforms | `wire.rs::is_name` | `wire.rs::tests::scalars` |
| Exact names only; wildcard routing and queue groups deferred | conforms: routing is `HashMap` lookup by exact name. `Pattern::Prefix` is a launcher grant, never a route | `router/state.rs::services`/`topics`, `policy.rs::Pattern` | `tests/pubsub.rs::subscription_and_topic_validation` (both), `tests/rpc.rs::authority_is_enforced` (both) |
| One live registration owns a service name; duplicate registration fails; no implicit round-robin or replacement | conforms (`CONFLICT`) | `router/state.rs::op_register` | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both), `tests/conformance_routing.rs::duplicate_registration_by_owner_itself_is_rejected` (both) |
| Registration returns the incarnation; callers pin it; a change fails with `TARGET_CHANGED` | conforms | `router/state.rs::op_call` | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both), `tests/bus_acceptance.rs::no_automatic_retry_or_failover_onto_a_replacement_registration` (both) |
| An unpinned call reaches whoever holds the name now | conforms | `router/state.rs::op_call` (`expectedIncarnation: null`) | `tests/conformance_routing.rs::unpinned_call_after_incarnation_replacement_reaches_the_new_holder` (both) |
| `Worker.Hello` stays a domain RPC, distinct from transport negotiation | conforms by absence: `bus.hello` carries no role, capability or session field | `router/state.rs::hello` | `tests/wire.rs::hello_negotiation` (both) |
| Service/topic access is configured per participant by the launcher; naming a target is not authority | conforms | `policy.rs::{Policy, Grants}`, checked in every `op_*` | `tests/rpc.rs::authority_is_enforced` (both), `tests/pubsub.rs::subscription_and_topic_validation` (both) |
| Presentation subscribes without gaining authority to invoke Advance | conforms: `subscribe` and `call` are separate grants | `policy.rs::Grants` | `tests/rpc.rs::authority_is_enforced` (both) |
| One live connection per client id, and a client id's last incarnation may not be reused | deviates-allowed (narrowing): section 3 makes `callId` "unique ... for this client incarnation" and section 6 keeps serials "per connected client", which two live connections for one id would make ambiguous. Cost: one small record per client id ever seen | `router/state.rs::{ClientRecord, hello}` | `tests/sol_review_races.rs::pending_connections_are_bounded_and_hello_expires` |
## 4. Wire envelope and framing
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Framing is `u32` little-endian JSON length, then UTF-8 JSON | conforms | `wire.rs::{read_frame, write_frame}` | `tests/conformance_wire.rs::length_prefix_is_little_endian` (both) |
| Envelope fields exactly `protocol`/`major`/`minor`/`id`/`replyTo`/`kind`/`op`/`body`/`attachments` | conforms | `wire.rs::Envelope::{decode, to_value}` | `tests/conformance_wire.rs::unknown_top_level_field_closes_the_connection` (both) |
| `ArtifactRef` fields `storeId`/`artifactId`/`generation`/`byteLength`/`contentType`/`digest` | conforms (`generation`/`byteLength` as U64 strings) | `wire.rs::ArtifactRef` | `tests/conformance_artifacts.rs::stale_store_incarnation_and_generation_are_rejected` (both) |
| `Attachment` is `{name, ref, ownerId}` | conforms | `wire.rs::Attachment` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| Maximum total JSON envelope 65,536 bytes | conforms | `wire.rs::MAX_ENVELOPE_BYTES`, checked on decode and encode | `tests/conformance_wire.rs::frame_at_the_size_ceiling_is_accepted_one_byte_over_is_not` (both) |
| A delivery the router would build over the limit is refused at admission | conforms, and required by "Message length includes this wrapper" (section 5): admission sizes the delivery with the longest ids | `router/state.rs::frame_len` in `op_call`/`op_reply`/`op_publish` | `tests/sol_review_races.rs::unsent_oversized_call_rolls_back_its_local_slot`, `tests/wire.rs::envelope_size_limits` (both) |
| Up to 32 attachments, unique names; `contentType` nonempty ASCII <=127 | conforms | `wire.rs::{MAX_ATTACHMENTS, is_content_type}`, `Envelope::decode` | `tests/conformance_wire.rs::malformed_envelope_scalars_are_rejected` (both), `tests/artifacts.rs::quotas_are_enforced` (both) |
| No pixel/base64/checkpoint bytes in JSON; artifact sizes are independent of envelope size | conforms: bulk bytes only reach the store; `byteLength` is a string in the reference | `store.rs`, `wire.rs::ArtifactRef` | `tests/perf.rs` (1.2 MB frames, envelopes under 1 KiB) |
| Domain schemas enumerate every referenced artifact; generated bindings enforce it | not-implemented for domain schemas (the bus enforces its own attachment list). Owner: CONTRACT-01 / `fly-session-types` | `router/state.rs::check_attachments` enforces the bus half | `tests/conformance_artifacts.rs::forward_requires_the_source_owner_still_live` (both) |
| The router validates attachment declarations/ownership, not domain payload contents | conforms | `router/state.rs::{check_owned, check_attachments}`; `payload`/`outcome` stay opaque | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
| Commands have unique monotonically issued `msg-<U64>` ids per connection | conforms (strictly increasing) | `router/state.rs::handle` | `tests/conformance_wire.rs::{non_canonical_command_ids_are_rejected, non_increasing_command_ids_are_rejected}` (both) |
| Replies correlate with `replyTo`; notices and deliveries carry router-generated ids | conforms | `router/state.rs::{reply, outbound}` | `tests/conformance_wire.rs::non_null_reply_to_on_a_command_is_rejected` (both) |
| The router supplies authenticated sender/target metadata; senders cannot forge it in `body` | conforms on launcher-bound transports; the sender's `body` never supplies identity | `router/state.rs::{identity, Call::request_body}` | `tests/rpc.rs::raw_call_ids_and_forged_replies` (both), `tests/sol_review_races.rs::responder_survives_cancel_then_request_drop` |
| Identity is bound out of band before Hello; a mismatching Hello is refused before registration | conforms | `router/mod.rs::{serve_as, listen_unix_as}`, `state.rs::hello` | `tests/wire.rs::hello_refusals` (both) |
| Open/unbound transports are self-asserted, not authentication | deviates-allowed (explicit narrowing): section 1's "one trusted local deployment" and section 4's "The launcher provides expected client/registration privileges". `Policy::open()` is documented as test/trusted-only | `policy.rs::permits_unbound_transport`, `router/state.rs::add_conn` | `tests/sol_review_races.rs::pending_connections_are_bounded_and_hello_expires` |
| Reject duplicate JSON keys, invalid UTF-8, NaN/Infinity, unknown envelope fields, zero/oversize frames, invalid ranges | conforms | `wire.rs::{parse_json_strict, StrictVisitor, Fields::finish}`, `read_frame` | `tests/conformance_wire.rs::{duplicate_json_keys_are_rejected_at_every_depth, invalid_utf8_is_rejected, zero_length_frame_closes_the_connection, oversize_length_prefix_is_rejected_before_reading_body}` (both) |
| Read length before allocating | conforms | `wire.rs::read_frame` checks the prefix before `vec![0u8; len]` | `tests/conformance_wire.rs::oversize_length_prefix_is_rejected_before_reading_body` (both) |
| Handle partial reads/writes; serialise one writer per connection | conforms | `wire.rs::read_frame`, `router/mod.rs::{write_selected, write_loop}` (one writer task) | `tests/conformance_wire.rs::{a_frame_written_one_byte_at_a_time_still_decodes, a_reply_read_one_byte_at_a_time_still_decodes, truncated_frame_disconnects_cleanly}` (both) |
| No ancillary-FD tricks in the first file-backed implementation | conforms | `transport.rs` carries bytes only | — |
| A future memory backend keeps the same client/ownership API | not-implemented (future). Owner: a later storage backend | — | — |
| `bus.hello` body `{clientId, clientIncarnation, supportedMajors}`, no attachments; reply `{routerId, connectionId, selectedMajor, selectedMinor, contractDigest, limits}` | conforms | `router/state.rs::hello`, `limits.rs::Limits::to_json` | `tests/wire.rs::hello_negotiation` (both), `tests/conformance_wire.rs::{hello_refuses_attachments, hello_reports_the_contract_digest_and_valid_limits}` (both) |
| Refuse incompatible majors or identity mismatch before registration | conforms (`VERSION_MISMATCH`, `NOT_AUTHORIZED`) | `router/state.rs::hello` | `tests/conformance_wire.rs::hello_refuses_an_unsupported_major` (both), `tests/wire.rs::hello_refusals` (both) |
| Schema changes change `contractDigest` | conforms: the digest is the SHA-256 of `wire::CONTRACT`, which lists every operation, delivery and notice; the client refuses a router whose digest differs | `wire.rs::{CONTRACT, contract_digest}`, `client/mod.rs::connect` | `tests/conformance_wire.rs::memory_and_unix_negotiate_the_identical_contract` |
| Bodies reject unknown fields and `minor` must be 0 after hello | deviates-allowed (stricter than "unknown envelope fields", forbidden nowhere; section 4's envelope fixes `minor: 0`) | `wire.rs::Fields::finish`, `router/state.rs::handle` | `tests/wire.rs::body_errors_keep_the_connection` (both), `tests/sol_review_races.rs::client_rejects_unknown_reply_fields_and_invalid_direction_rules` |
| The connection reader dispatches replies and requests without blocking on user handlers | conforms: the reader hands `Request`/`Message` to unbounded per-handle channels and returns | `client/reactor.rs::{read_loop, on_delivery}` | `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both) |
| Artifact I/O and hashing run outside the routing critical section; no routing lock across slow I/O | conforms: `Outcome::Allocate`/`Seal` leave the lock, run on the blocking pool and re-enter; unlinks happen after the guard drops | `router/mod.rs::{read_loop, Inner::with_state}`, `store.rs::seal` | `tests/artifacts.rs::quotas_are_enforced` (both), `tests/perf.rs` (seal p50 1.3 ms, publish admission p50 0.4 ms) |
## 5. Operation registry
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Replies are `{ok:true, value}` or `{ok:false, error:{code, message, dispatch}}` | conforms | `router/state.rs::reply_body`, `client/reactor.rs::parse_reply` | `tests/wire.rs::body_errors_keep_the_connection` (both) |
| All 19 commands of the table exist with the listed bodies and reply values | conforms | `router/state.rs::handle` dispatch table; `wire.rs::CONTRACT` | `tests/conformance_wire.rs` + `tests/{rpc,pubsub,artifacts}.rs` (both) |
| `rpc.responder.release {callId, requestDeliveryId} -> {released}` is added to the registry | deviates-allowed: section 4's "Changes to these draft schemas change contractDigest" (this is a draft), and it is what keeps section 6's "bounded call correlation metadata" bounded when a handler keeps a responder after dropping the request. Recorded as an amendment in bus-v1 section 12 | `router/state.rs::op_responder_release`, `client/handles.rs::ReplyGuard` | `tests/sol_rereview_regressions.rs::{dropping_last_attached_responder_settles_the_call, dropping_last_responder_clone_settles_the_call}` |
| Release batches carry 1..64 ids | conforms | `wire.rs::MAX_BATCH`, `Fields::array` | `tests/artifacts.rs::release_ids_are_watermarked` (both) |
| No attachments on management commands except `rpc.call`, `rpc.reply`, `publish` | conforms | `router/state.rs::handle` | `tests/wire.rs::body_errors_keep_the_connection` (both) |
| `accepted`/`routed`/`removed`/`declared`/`cleared`/`deleted`/`replayLatest` are booleans; `subscribers`/`replaced`/`released` are U64 counts | conforms | `router/state.rs` (`.into()` for bools, `to_string()` for counts) | `tests/pubsub.rs::bounded_fifo_and_atomic_backpressure` (both), `client/reactor.rs::validate_reply_value` |
| Released counts count newly released roots, so an idempotent repeat may report zero | conforms | `router/state.rs::{op_consumed, op_release}` | `tests/artifacts.rs::release_ids_are_watermarked` (both) |
| Queue/credit requests are integers 1..65535 and cannot exceed configured limits | conforms | `wire.rs::MAX_CREDIT`, `op_register`/`op_subscribe` quota checks | `tests/pubsub.rs::subscription_and_topic_validation` (both), `tests/rpc.rs::service_queue_backpressure` (both) |
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
| `topicSequence` and counters are U64 strings; the router assigns the ids; the SDK exposes typed payloads plus handles | conforms | `router/state.rs::TopicMsg::body`, `client/handles.rs::Message` | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| Required bounded notices: route removal, subscription closure, call failure | conforms | `router/state.rs::{remove_service, shutdown, op_responder_release}` | `tests/pubsub.rs::router_shutdown_closes_subscriptions_with_notices` (both), `tests/rpc.rs::service_disconnect_fails_calls` (both) |
| Who gets those notices, and when | deviates-allowed: the draft names the notices but not their audience. `route.removed` goes to callers with open calls on the removed registration, `subscription.closed` only at router shutdown (nothing else ends a subscription without the client's own act), and `connection.closing` is an added notice before every router-initiated close | `router/state.rs::{remove_service, shutdown, violation}` | `tests/wire.rs::malformed_frames_close_the_connection` (both) |
| If notice capacity is exhausted, close the connection rather than lose control-plane correctness | conforms | `router/state.rs::push_control` | `tests/wire.rs::control_lane_exhaustion_closes` (both) |
## 6. RPC behaviour
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| `call-<U64>` with increasing serials per connected client; reused or retired ids are rejected, never executed again | conforms: a syntactically valid id advances the watermark even when admission is refused | `router/state.rs::op_call` (`call_watermark`) | `tests/sol_review_races.rs::rejected_call_id_still_advances_monotonic_watermark`, `tests/rpc.rs::raw_call_ids_and_forged_replies` (both) |
| Reconnecting creates a new incarnation rather than reviving old calls | conforms | `router/state.rs::{hello, disconnect}` | `tests/conformance_routing.rs::unpinned_call_after_incarnation_replacement_reaches_the_new_holder` (both), `tests/sol_review_races.rs::caller_disconnect_cleanup_works_before_and_after_consumption` for the old calls half (its synchronisation was fixed on 2026-09-22; see "A flaky test and what it was measuring") |
| An RPC targets one registered service, not a broadcast subject | conforms | `router/state.rs::op_call` | `tests/rpc.rs::request_reply_roundtrip` (both) |
| First-dispatch FIFO per caller and service; responses may complete out of order and correlate by callId | conforms | `router/state.rs::{Svc::queue, dispatch_rpc}` | `tests/rpc.rs::fifo_dispatch_and_out_of_order_completion` (both), `tests/conformance_routing.rs::out_of_order_replies_correlate_across_concurrent_callers` (both) |
| A service dispatcher can answer status concurrently with a long mutation | conforms | `router/state.rs::dispatch_rpc` (in-flight credits, not one-at-a-time) | `tests/bus_acceptance.rs::a_status_rpc_responds_while_another_handler_is_delayed` (both) |
| The router implements no frame barriers or numerical ordering | conforms by absence | `router/state.rs` (no domain fields) | `tests/integration.rs::session_over_one_router` (both) |
| Admission validates route, pinned incarnation, size, quotas and every source artifact owner, and establishes request-delivery roots atomically before accepting | conforms: every check precedes the first mutation, then roots, queue entry and reply | `router/state.rs::op_call` | `tests/conformance_artifacts.rs::rejected_call_creates_no_roots` (both), `tests/artifacts.rs::failed_admission_is_atomic` (both) |
| Rejection establishes no delivery and drops provisional roots | conforms | `router/state.rs::op_call` (validate-then-mutate) | `tests/conformance_artifacts.rs::rejected_call_creates_no_roots` (both) |
| An accepted call is not proof that its handler ran | conforms: `accepted` is admission only; the terminal outcome arrives as `rpc.result` or `call.failed` | `client/mod.rs::call`, `client/handles.rs::PendingCall` | `tests/rpc.rs::service_disconnect_fails_calls` (both) |
| Mark dispatched before any request bytes can reach the target; later transport loss is an unknown outcome | conforms: `Phase::Dispatched` and the delivery id are set when the frame is selected, before a byte is written | `router/state.rs::{next_frame, dispatch_rpc}` | `tests/sol_rereview_regressions.rs::shutdown_cancels_partial_rpc_request_before_reclaiming_attachment` |
| The service replies with its own owned handles; the router establishes caller-result ownership before accepting the reply | conforms | `router/state.rs::op_reply` (`check_attachments`, then `add_roots`, then the phase change) | `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| Only bounded call correlation metadata is kept until the result is consumed or the caller detaches; not an indefinite result cache | conforms: the record dies with consumption, detachment, disconnect or the last responder release; reply capabilities share the per-client owner bound | `router/state.rs::{remove_call, dispatch_rpc, op_responder_release}` | `tests/sol_review_races.rs::{cancel_after_request_consumption_retires_correlation, dropping_service_with_buffered_requests_retires_every_call}` |
| A second `rpc.reply` for the same call is rejected, not routed twice | conforms (`CALL_GONE`) | `router/state.rs::op_reply` | `tests/rpc.rs::replies_are_single_and_independent_of_the_request_guard` (both) |
| Responding does not release the request's delivery guard | conforms | `client/handles.rs::{Request, Responder}` (separate guards) | `tests/rpc.rs::replies_are_single_and_independent_of_the_request_guard` (both) |
| No automatic retry or failover; never route a retry automatically to a restarted worker | conforms | `router/state.rs::{remove_service, disconnect}` fail calls instead of re-queueing | `tests/bus_acceptance.rs::no_automatic_retry_or_failover_onto_a_replacement_registration` (both) |
| A deadline belongs to the calling client; on timeout it may cancel | conforms: no budget on the wire; `result()` is cancel-safe under `tokio::time::timeout` | `client/handles.rs::PendingCall::{result, cancel}` | `tests/rpc.rs::cancellation_states` (both) |
| Domain retries use a fresh callId with the same domain requestId/body, pinned to the same incarnation; endpoint dedup supplies safe replay; the router does not infer it from method names | conforms | `client/mod.rs::call`; the router carries `payload` opaquely | `tests/bus_acceptance.rs::a_retransmission_repeats_the_domain_request_under_a_fresh_call_id` (both), `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| Queued cancellation releases its queued artifact roots and returns `cancelled-before-dispatch` | conforms | `router/state.rs::op_cancel` -> `remove_call` -> `drop_roots` | `tests/conformance_routing.rs::cancel_before_dispatch_releases_queued_artifact_roots` (both) |
| After dispatch, return `execution-unknown` and keep the recipient's delivery alive until consumed or disconnected | conforms | `router/state.rs::op_cancel` (`detached = true`, delivery untouched) | `tests/rpc.rs::cancellation_states` (both), `tests/conformance_routing.rs::caller_disconnect_detaches_dispatched_call_but_service_keeps_serving` (both) |
| A later reply to a detached call returns `routed:false` with no caller-result roots; the service still owns any retained result | conforms | `router/state.rs::op_reply` (`call.detached` branch, before `add_roots`) | `tests/conformance_routing.rs::cancel_after_dispatch_then_late_reply_with_artifact_is_not_routed` (both) |
| A terminal result already admitted makes cancellation report `completed`; the client drains and consumes it | conforms | `router/state.rs::op_cancel` (`Phase::Replied`), `client/reactor.rs::on_delivery` consumes an abandoned result | `tests/rpc.rs::{cancellation_states, dropped_call_is_cancelled_and_late_result_consumed}` (both) |
| A retired or unknown correlation reports `call-gone`; those four strings are the complete enum | conforms | `router/state.rs::op_cancel`, `client/handles.rs::CancelState` | `tests/rpc.rs::cancellation_states` (both), `client/reactor.rs::validate_reply_value` |
| No cancel state authorises re-execution; cancelling a future does not abandon incoming delivery ownership | conforms | `client/handles.rs::CallGuard::drop` (best-effort cancel, result still consumed) | `tests/rpc.rs::dropped_call_is_cancelled_and_late_result_consumed` (both), `tests/sol_review_races.rs::reply_racing_cancel_has_only_the_two_contract_outcomes` |
| Endpoint replay caches Artifact handles plus payload, not bare references, and owns holds until eviction | conforms (SDK support; the discipline is the endpoint's) | `client/handles.rs::Artifact::retain`, `ArtifactWriter::seal` returns a hold | `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both), `tests/bus_acceptance.rs::a_lost_result_leaks_no_roots_and_the_endpoint_cache_still_replays` (both) |
| Re-delivery gets new delivery ids pointing to the same immutable bytes | conforms | `router/state.rs::dispatch_rpc` (fresh `dlv-<n>` per delivery) | `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| An expired domain cache returns `RESULT_EXPIRED` | not-implemented: a domain code, not a transport code. Owner: `fly-session-rpc` (ipc-v1) | — | — |
## 7. Pub/sub semantics
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Topic declaration teaches the router nothing about meaning; no hardcoded frame/brain topics | conforms | `router/state.rs::{Topic, op_declare}` | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| `latest`: one queued value, replacing only an undelivered one; replacement releases that entry's roots; delivered or in-use messages are never reclaimed early; maxQueued is exactly 1 | conforms | `router/state.rs::{op_publish (latest branch), op_subscribe}` | `tests/pubsub.rs::latest_coalesces_only_undelivered_values` (both), `tests/conformance_artifacts.rs::latest_mode_holds_at_most_two_roots_delivered_plus_queued` (both) |
| `bounded`: FIFO, no coalescing or silent loss; when capacity is unavailable, reject with `BACKPRESSURE` before admitting any delivery | conforms | `router/state.rs::op_publish` (pre-checks every subscriber) | `tests/pubsub.rs::bounded_fifo_and_atomic_backpressure` (both), `tests/conformance_routing.rs::bounded_overflow_rolls_back_all_artifact_roots` (both) |
| maxInFlight credits return only on `delivery.consumed`, not on socket write completion | conforms | `router/state.rs::release_owner` (credit returned when the owner is released) | `tests/pubsub.rs::credits_return_only_on_consume` (both), `tests/conformance_routing.rs::bounded_credit_waits_for_every_extracted_artifact` (both) |
| A latest subscriber with all credits in use still has one replaceable queued value | conforms | `router/state.rs::{Sub::queue, dispatch_topic}` (queue and credits are separate) | `tests/bus_acceptance.rs::both_transports_produce_equivalent_behaviour_traces` (events 21 and 24: `publish replaced=1`, then `latest seq=3 replaced=1`), `tests/integration.rs::session_over_one_router` (both: a renderer held for the whole run keeps one delivery in flight and one replaceable value, and receives snapshots 1 and 20 of 20) |
| Atomic subscriber/retention snapshot at admission; validate and reserve every queue entry and owner budget before accepting | conforms: one mutex, validate-then-mutate | `router/state.rs::op_publish` | `tests/artifacts.rs::failed_admission_is_atomic` (both) |
| A bounded overflow rejects the whole publish: no partial fan-out, no retained-latest update | conforms | `router/state.rs::op_publish` | `tests/conformance_routing.rs::bounded_overflow_rolls_back_all_artifact_roots` (both) |
| On acceptance, one `topicSequence` and roots for every delivery and the optional retained value | conforms; a refused publication spends no sequence number | `router/state.rs::op_publish` (`t.sequence += 1` after the checks) | `tests/pubsub.rs::bounded_fifo_and_atomic_backpressure` (both) |
| Different topics have no total ordering; multiple publishers follow router acceptance order | conforms: per-topic sequence only | `router/state.rs::Topic::sequence` | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| The publication reply counts accepted subscriptions and replaced queue entries, not consumers that processed data | conforms | `router/state.rs::op_publish` reply | `tests/pubsub.rs::latest_coalesces_only_undelivered_values` (both) |
| `replaced` on a delivery reports how many undelivered messages were coalesced since that subscription's preceding delivery | conforms | `router/state.rs::{Sub::replaced, dispatch_topic}` (taken at dispatch) | `tests/pubsub.rs::latest_coalesces_only_undelivered_values` (both), `tests/integration.rs::session_over_one_router` (both: the 18 replacements the publisher was told about at admission are the same 18 the renderer is told about on delivery, and are exactly the snapshots it did not receive) |
| Optional `retained:latest` holds one last message and its artifacts independent of subscribers | conforms | `router/state.rs::op_publish` (retain branch) | `tests/conformance_artifacts.rs::retained_topic_value_holds_a_root_independent_of_subscribers` (both) |
| `replayLatest` enqueues the retained value before subsequent accepted publications; bounded preserves the order, latest may coalesce it | conforms | `router/state.rs::op_subscribe` (replay is enqueued under the subscribe lock) | `tests/conformance_routing.rs::latest_replay_is_ordered_ahead_of_a_racing_publish` (both: one racing publication to a bounded and a latest subscription at once; bounded must deliver replay then publication, and the latest branch is chosen by that publication's own `replaced` count, never by which side of the race the dispatcher won), `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| Replay uses the original topicSequence, a fresh deliveryId and explicit roots | conforms | `router/state.rs::op_subscribe` (`add_roots`, the same `Arc<TopicMsg>`) | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| Without retention, a zero-subscriber publication retains no ownership after admission | conforms | `router/state.rs::op_publish` | `tests/pubsub.rs::zero_subscriber_publish_retains_nothing` (both) |
| Clearing a topic releases only its retained root, not active consumers | conforms | `router/state.rs::op_clear` | `tests/conformance_routing.rs::cleared_topic_gives_no_replay_until_a_fresh_publish` (both) |
| Topic count and retained bytes are capped | conforms; `max_retained_bytes` is added to the draft's table because this sentence requires it | `limits.rs::{max_topics, max_retained_bytes}`, `router/state.rs::{op_declare, op_publish}` | `tests/pubsub.rs::topic_and_retention_quotas` (both) |
| No durable replay, automatic redelivery or exactly-once claim | conforms by absence | `router/state.rs` (queues are in memory and die with the connection) | `tests/artifacts.rs::router_restart_invalidates_old_handles` (both) |
| Deleting or redeclaring a topic creates a fresh topicIncarnation; a reset sequence cannot be read as continuation | conforms | `router/state.rs::{op_delete, op_declare}` | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both) |
| Old subscription deliveries keep their original incarnation and ownership until consumed | conforms | `router/state.rs::drop_subscription` (matches on the incarnation), delivery bodies carry it | `tests/pubsub.rs::unsubscribe_discards_queue_but_not_deliveries` (both) |
| `topic.delete` only with no subscribers | conforms (`CONFLICT`) | `router/state.rs::op_delete` | `tests/pubsub.rs::subscription_and_topic_validation` (both) |
| Bus admission, message consumption and durable storage acknowledgment are three different events | conforms: `publish` returns admission counts, `delivery.consumed` is separate, and there is no storage ack in the bus | `router/state.rs::{op_publish, op_consumed}` | `tests/pubsub.rs::credits_return_only_on_consume` (both) |
| A topic must be declared before publish or subscribe | deviates-allowed: the draft is silent on undeclared topics, while "Topic count and retained bytes are capped" and `topic.declare`'s "conflicting settings fail" both imply a registry a publication cannot create by accident. `NO_TOPIC` names the refusal (amendment, section 12); `topic.delete` of an unknown topic still answers `deleted:false` | `router/state.rs::{op_publish, op_subscribe, op_clear}` | `tests/pubsub.rs::subscription_and_topic_validation` (both) |
## 8. Artifact lifecycle and garbage collection
### 8.1 Immutable object lifecycle
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| `ALLOCATED/WRITING -> SEALED -> owned -> COLLECTED`, and an abandoned or disconnected writer goes straight to COLLECTED | conforms | `router/state.rs::{ArtState, abandon_writer, finish_seal}` | `tests/artifacts.rs::{writer_drop_releases_staging, disconnect_releases_all_but_retained}` (both), `tests/conformance_artifacts.rs::disconnect_abandons_an_unsealed_writer` (both) |
| `ArtifactRef` is an identity, not an address or authority; opening needs a current root on that connection | conforms | `router/state.rs::{check_owned, op_open}` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
| storeId is the store incarnation; old handles fail after restart | conforms (`ARTIFACT_GONE`) | `router/state.rs::check_owned` | `tests/artifacts.rs::router_restart_invalidates_old_handles` (both) |
| No artifact id or inode reuse; `generation` is 1 | conforms | `wire.rs::GENERATION`, `router/state.rs::next_artifact` (monotonic) | `tests/conformance_artifacts.rs::stale_store_incarnation_and_generation_are_rejected` (both) |
| Content hashes optional for live frames, mandatory where a domain contract says so | conforms: both paths exist and the router verifies what it is given | `client/handles.rs::ArtifactWriter::seal_with_digest`, `store.rs::copy_exact` | `tests/artifacts.rs::seal_checks_length_and_digest` (both) |
| The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
| The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
| Sealing on send (amendment 2026-10-02, BUS-02): an `rpc.call`/`rpc.reply`/`publish` attachment naming the sender's own writer is sealed (its declared prefix, copied outside the state lock) before the command is admitted, the writer becomes the sender's hold, `recycle` reissues the staging file as a new writer, and a refused sealing send releases every writer it named | conforms | `router/state.rs::{sealing_attachments, finish_sealing_send}`, `router/mod.rs::read_loop` (`SealThenAdmit`), `store.rs::{seal_prefix, rename}`, `client/handles.rs::{ArtifactWriter::into_unsealed, Responder::reply_sealing}` | `tests/sealing.rs::{a_reply_seals_and_recycles_its_writers, a_refused_sealing_send_releases_its_writers}` (both), `tests/artifacts.rs::unsealed_artifacts_cannot_be_used` (both) |
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |
### 8.2 What owns an artifact
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Roots: producer hold/active writer, accepted queued delivery, in-flight delivery, retained latest, explicit hold | conforms, all five | `router/state.rs::{Owner, add_roots, drop_roots}` | `tests/conformance_artifacts.rs::{queued_deliveries_hold_roots_before_dispatch, collection_waits_for_every_retained_owner, retained_topic_value_holds_a_root_independent_of_subscribers}` (both) |
| Seal transfers the unique writer into a hold | conforms; the seal reply reuses the writer's own ownerId to express exactly that transfer | `router/state.rs::finish_seal` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Admission creates destination roots before the sender may relinquish source roots | conforms: the SDK holds every source `OwnerGuard` until the router has answered | `client/reactor.rs::OutCommand::keep`, `router/state.rs::{op_call, op_reply, op_publish}` | `tests/conformance_artifacts.rs::forward_requires_the_source_owner_still_live` (both) |
| A timeout must not drop a source guard while an unsent operation might still be admitted; the client keeps the guard until the transport outcome is known | conforms: an unsent command's guards travel with it and are released only when it fails or is answered | `client/reactor.rs::{next_outgoing, fail_all}` | `tests/sol_review_races.rs::unsent_oversized_call_rolls_back_its_local_slot`, `tests/artifacts.rs::abandoned_futures_do_not_leak_owners` (both) |
| Every envelope lists its complete artifact set; duplicates in one delivery count once | conforms | `router/state.rs::{check_attachments, dedup}` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| A retained topic and several consumers can reference the same bytes; the router updates metadata only and never copies bytes for fan-out | conforms | `router/state.rs::op_publish` (`Arc<TopicMsg>` plus root counts) | `tests/artifacts.rs::fan_out_shares_one_object_and_the_last_consumer_collects` (both), `tests/perf.rs` (store peak 3.7 MB for three consumers) |
### 8.3 Consumed means no remaining use
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| The incoming message owns a shared DeliveryGuard; extracting an Artifact clones it; dropping the message alone does not consume the delivery | conforms | `client/handles.rs::{OwnerGuard, Message::artifact}` | `tests/artifacts.rs::extracted_artifacts_outlive_their_message` (both), `tests/conformance_artifacts.rs::extracted_artifact_outlives_the_message_it_came_from` (both) |
| Local handle clones need no bus round trip; dropping the last guard queues `delivery.consumed` on a bounded control lane | conforms | `client/handles.rs::OwnerGuard::drop`, `client/reactor.rs::push_control` | `tests/pubsub.rs::credits_return_only_on_consume` (both) |
| Ownership is at delivery granularity; independent retention needs `artifact.retain` before the guard is dropped | conforms | `client/handles.rs::Artifact::retain` | `tests/conformance_artifacts.rs::explicit_retain_outlives_the_original_hold` (both) |
| A domain acknowledgment implicitly drops nothing | conforms by absence: only a guard drop or an explicit release ends ownership | `client/handles.rs::OwnerGuard` | `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| An allocation or seal grant that arrives after its caller abandoned the future is still processed and released; no owner the application never saw is leaked | conforms: the reactor builds the handle, so an undelivered reply drops it | `client/reactor.rs::{complete, Hook::Owner}` | `tests/artifacts.rs::abandoned_futures_do_not_leak_owners` (both) |
| An in-progress seal has a bounded I/O hold; on producer disconnect it cleans up and never publishes an ownerless object | conforms | `router/state.rs::finish_seal` (`owner_live` check), `router/mod.rs::read_loop` seal task | `tests/conformance_artifacts.rs::disconnect_abandons_an_unsealed_writer` (both) |
| Dropping a response future is not consumption: the client owns queued results until surfaced, discarded or disconnected | conforms | `client/reactor.rs::{CallSlot, on_delivery}` | `tests/rpc.rs::dropped_call_is_cancelled_and_late_result_consumed` (both) |
| Receivers await asynchronous CPU/GPU use before releasing the guard | conforms as far as the API can enforce: the guard lives as long as any `Artifact`/`ArtifactFile` clone | `client/handles.rs::{Artifact, ArtifactFile}` | `tests/conformance_routing.rs::bounded_credit_waits_for_every_extracted_artifact` (both) |
| A pointer from a mapping cannot outlive its Artifact; FFI wrappers enforce it | not-implemented: no mapping and no FFI surface exists. Owner: a future mmap or binding | — | — |
| Release commands are batched, idempotent and scoped to the owning connection | conforms | `router/state.rs::{op_release, op_consumed}`, `client/reactor.rs::take_batch` | `tests/artifacts.rs::owners_are_scoped_to_their_connection` (both) |
| Delivery and hold ids use monotonic per-connection serials with separate watermarks; a retired id is a no-op, a never-issued one an error; no tombstone per frame | conforms | `router/state.rs::{Conn::delivery_issued, Conn::hold_issued, op_consumed, op_release}` | `tests/artifacts.rs::release_ids_are_watermarked` (both) |
| Control-lane exhaustion closes the connection instead of losing releases | conforms on both sides | `router/state.rs::push_control`, `client/reactor.rs::push_control` | `tests/wire.rs::control_lane_exhaustion_closes` (both) |
### 8.4 Crash, disconnect and safe physical reclamation
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| On disconnect: unregister services and subscriptions, cancel queued deliveries, release that connection's writers, holds and delivery roots | conforms | `router/state.rs::disconnect` | `tests/artifacts.rs::disconnect_releases_all_but_retained` (both), `tests/conformance_artifacts.rs::{disconnect_releases_an_explicit_hold, disconnect_releases_queued_and_dispatched_deliveries}` (both) |
| Retained topic roots stay router-owned | conforms | `router/state.rs::disconnect` (topics untouched) | `tests/conformance_routing.rs::subscriber_disconnect_releases_queued_and_delivered_artifacts_but_not_retention` (both) |
| Late replies and releases cannot attach to a new connection or service incarnation | conforms: owners are per connection and calls remember their service incarnation | `router/state.rs::{check_owned, op_reply, remove_service}` | `tests/artifacts.rs::owners_are_scoped_to_their_connection` (both), `tests/rpc.rs::raw_call_ids_and_forged_replies` (both) |
| Teardown reclaims a connection's roots without racing the frame it is writing: either a complete frame precedes the reclamation or a partial one is cut and nothing more is appended | conforms, **fixed on this branch** (see the section 9 row on starvation). Teardown now marks the stream closing once, before waiting for the poll already in progress, so only that one poll can still write and every later one is refused | `router/state.rs::WriteGate`, `router/mod.rs::write_selected`, `router/state.rs::close_conn` | `tests/sol_rereview_regressions.rs::{teardown_waits_for_an_active_transport_poll_before_reclaiming, shutdown_does_not_deliver_a_frame_after_releasing_its_owner, protocol_close_cancels_partial_topic_frame_before_reclaiming_attachment, shutdown_cancels_partial_rpc_request_before_reclaiming_attachment, shutdown_cancels_partial_rpc_result_before_reclaiming_attachment}` |
| GC removes the registry entry and unlinks the sealed object after its final root is gone | conforms; the unlink happens after the routing lock is released | `router/state.rs::drop_roots`, `router/mod.rs::Inner::with_state` | `tests/artifacts.rs::fan_out_shares_one_object_and_the_last_consumer_collects` (both) |
| Existing mappings stay valid until the OS closes them; never overwrite the inode or reuse its bytes | conforms: sealed files are 0444, written once and only unlinked | `store.rs::{seal, remove}` | `tests/bus_acceptance.rs::disconnect_releases_logical_ownership_without_mutating_open_bytes` (both) |
| Logical reclamation is not proof of physical release; measurements include OS mappings and client memory | conforms: `RouterStats` is documented as logical, and the measurement reports process RSS | `router/state.rs::RouterStats`, `tests/perf.rs` | `tests/perf.rs` (RSS 11 to 16 MB) |
| No TTL may reclaim a live owned artifact | conforms by absence: nothing in the router expires an owned root | `router/state.rs` | `tests/conformance_artifacts.rs::collection_waits_for_every_retained_owner` (both) |
| Limits may disconnect a consumer but cannot overwrite memory under a renderer | conforms: exhaustion closes the connection, which releases roots; bytes are never rewritten | `router/state.rs::push_control`, `store.rs` | `tests/wire.rs::control_lane_exhaustion_closes` (both) |
| Future pooled shared memory must prove equivalent lifetime/generation safety | not-implemented (deferred by the draft). Owner: a later storage backend | — | — |
| Router restart makes a new routerId/storeId, loses routes, queues and retention, and invalidates old handles | conforms | `router/mod.rs::Router::new`, `store.rs::Store::create` | `tests/artifacts.rs::router_restart_invalidates_old_handles` (both) |
| Orphan files from a stopped router are cleaned without being treated as durable checkpoints | conforms, at the next router start on the same root (a `flock`-free marked directory) | `store.rs::clean_orphans` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
| Live sessions fail their epoch and use coherent recovery | not-implemented: a session responsibility. Owner: STATE-01 / step-v1 | — | — |
## 9. Bounds, scheduling and failure reporting
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| Every default of the table, exactly: clients/services/topics 64/256/512; subscriptions 128 per client and 1024 total; control envelope 64 KiB; active calls 64; service queued/in-flight 16/16; latest 1/2; bounded 64/16; active owners 256; store 512 MiB and 128 MiB per object; per-client queued envelope bytes 1 MiB; reserved lane 128 frames and 1 MiB | conforms | `limits.rs::Limits::default`, `wire.rs::MAX_ENVELOPE_BYTES` | `tests/conformance_wire.rs::hello_reports_the_contract_digest_and_valid_limits` (both), `tests/pubsub.rs::topic_and_retention_quotas` (both) |
| Limits are configured explicitly and a configuration the router could not honour is refused | conforms | `limits.rs::Limits::validate`, `router/mod.rs::Router::new` | `tests/rpc.rs::active_call_limit` (both), `tests/artifacts.rs::quotas_are_enforced` (both) |
| The per-client queued envelope byte budget counts `bounded` subscriptions only, and latest slots are bounded at subscriptions x 64 KiB instead | conforms to the amended table. The draft's single row was the audit's contradiction 1: this section also forbids a latest spectator from being the reason a publication is refused, so its slot cannot sit in a budget whose overflow rejects one. The coordinator amended the row and gave latest slots their own (bus-v1 section 12, 2026-09-22) | `limits.rs::max_queued_bytes_per_client`, `router/state.rs::op_publish` | `tests/bus_acceptance.rs::a_latest_subscriber_never_refuses_a_publication` (both), `tests/sol_review_races.rs::{retained_replay_obeys_bounded_queue_byte_quota, latest_replay_remains_bounded_outside_the_bounded_byte_pool}` |
| Reserve an owner allowance for lifecycle and results separately from ordinary telemetry | conforms | `limits.rs::reserved_owners_per_client`, `router/state.rs::{ordinary_budget_left, dispatch_rpc}` | `tests/conformance_artifacts.rs::artifact_bounds_and_owner_budget_are_enforced` (both) |
| Memory quotas account for staging, seal copies, queued deliveries and caches | conforms | `router/state.rs::{op_allocate, op_seal, Conn::queued_bytes}` | `tests/artifacts.rs::quotas_are_enforced` (both) |
| Ownership metadata is bounded even when many roots share one artifact | conforms: a root is a counter, and owners are bounded per client | `router/state.rs::{Art::roots, ordinary_budget_left}` | `tests/conformance_artifacts.rs::artifact_bounds_and_owner_budget_are_enforced` (both) |
| Disk-full, allocation failure or hash mismatch returns a typed artifact error and cleans provisional storage and roots | conforms (`QUOTA_EXCEEDED`, `STORE_FAILURE`, `ARTIFACT_MISMATCH`) | `router/state.rs::{op_allocate, finish_allocate, op_seal, finish_seal}`, `store.rs::seal` | `tests/artifacts.rs::seal_checks_length_and_digest` (both), `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| The router fairly services clients | deviates-allowed: fairness is Tokio's scheduling plus a yield every 32 commands from one connection, and round robin between a connection's services and subscriptions. The draft sets no fairness metric; the crate's Limitations section calls this modest | `router/mod.rs::read_loop`, `router/state.rs::{dispatch_rpc, dispatch_topic}` | `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both) |
| Replies, release, cancellation and route-health control cannot be starved by telemetry | conforms: control first, then RPC, then topic data, with topic data given a turn after 16 higher-priority frames | `router/state.rs::{next_frame, TOPIC_STARVATION_LIMIT}` | `tests/sol_rereview_regressions.rs::{fair_topic_insertion_preserves_router_envelope_order, sdk_accepts_fair_topic_insertion_through_saturated_control_backlog}`, `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both) |
| ... and neither can connection teardown be starved by the frame it is waiting for | **was deviates-must-fix, fixed on this branch**. The write gate was a plain mutex held across each synchronous transport poll, so a writer sending a frame one byte per poll re-acquired it hundreds of times while teardown waited for it, and could finish a whole delivery before teardown got in: `teardown_waits_for_an_active_transport_poll_before_reclaiming` failed 6 runs out of 6 in release and about 1 in 5 in debug. The gate now separates "teardown has begun" (a flag set once, without waiting) from "a poll is in progress" (a condvar teardown waits on), so teardown's window is one poll instead of a whole frame, and no byte can follow it. No public signature changed | `router/state.rs::WriteGate`, `router/mod.rs::write_selected` | `tests/sol_rereview_regressions.rs::teardown_waits_for_an_active_transport_poll_before_reclaiming` (rewritten: a 50 KB delivery the resumed writer cannot finish, and a channel instead of a sleep) |
| Preserve FIFO for calls to a target despite lane scheduling | conforms: the service queue is FIFO and lane choice never reorders it | `router/state.rs::dispatch_rpc` | `tests/rpc.rs::fifo_dispatch_and_out_of_order_completion` (both) |
| Classification is an explicit generic envelope operation or policy, not a topic-name heuristic | conforms by construction: `next_frame` chooses a lane from the queue an item sits in (control, then RPC, then topic), and neither it nor `pop_control`/`dispatch_rpc`/`dispatch_topic` reads a service or topic name. A name reaches the scheduler only as opaque bytes inside an already-classified frame | `router/state.rs::{next_frame, pop_control, dispatch_rpc, dispatch_topic}` | `tests/bus_acceptance.rs::a_topic_named_like_a_notice_is_still_classified_as_topic_data` (both), and `tests/sol_rereview_regressions.rs::fair_topic_insertion_preserves_router_envelope_order` for the lane order itself |
| No indefinite wait inside the router on subscriber readiness or artifact I/O | conforms: a slow reader stalls only its own writer task; I/O leaves the lock | `router/mod.rs::{write_loop, read_loop}` | `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both) |
| Admission is bounded; rejected callers choose their own policy | conforms | `router/state.rs::{op_call, op_publish}` | `tests/rpc.rs::service_queue_backpressure` (both) |
| The thirteen transport error codes exist with those names | conforms | `error.rs::ErrorCode` | `tests/wire.rs::body_errors_keep_the_connection` (both) |
| Three more codes: `CONFLICT`, `NO_TOPIC`, `ARTIFACT_MISMATCH` | deviates-allowed: "Transport errors **include** ..." is not an exhaustive list, and each names a refusal the draft requires but leaves unnamed. Recorded as an amendment in bus-v1 section 12 | `error.rs::ErrorCode` | `tests/pubsub.rs::subscription_and_topic_validation` (both), `tests/artifacts.rs::seal_checks_length_and_digest` (both) |
| Before admission report `not-dispatched`; once dispatch might have occurred report `dispatched` or `unknown` conservatively | conforms | `error.rs::BusError::new` (not-dispatched by default), `router/state.rs` dispatched notices, `client/reactor.rs::fail_all` (unknown) | `tests/rpc.rs::{cancellation_states, service_disconnect_fails_calls}` (both), `tests/sol_review_races.rs::writer_failure_terminates_reader_and_pending_work` |
| Bounded subscriptions can reject a publication; latest spectators cannot hold a session transaction indefinitely | conforms: a latest subscriber never causes `BACKPRESSURE` | `router/state.rs::op_publish` (the latest branch skips every capacity check) | `tests/bus_acceptance.rs::a_latest_subscriber_never_refuses_a_publication` (both: 100 publications of 60 KB into one unconsumed slot, six times the bounded pool, none refused, 98 coalesced), with `tests/pubsub.rs::{bounded_fifo_and_atomic_backpressure, saturated_subscriber_does_not_block_control}` (both) for the bounded half, and `tests/integration.rs::session_over_one_router` (both: 20 snapshot publications accepted by both subscriptions while the presentation consumer reads nothing) |
| Sustained pinned-artifact quota exhaustion is surfaced as pressure, not solved by freeing live data | conforms: `QUOTA_EXCEEDED`, never eviction | `router/state.rs::{op_allocate, op_seal}` | `tests/artifacts.rs::quotas_are_enforced` (both) |
| Session and application policies choose disconnect, pause or fail; the router does not know which | conforms by absence | `router/state.rs` | `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both) |
## 10. Native-frame bandwidth check
| Requirement | Status | Code | Test |
| --- | --- | --- | --- |
| 640x480 RGBA is 1,228,800 bytes; 73.728 MB/s at 60 fps is the planning dimension | conforms as measured, not as a claim | `tests/perf.rs::{W, H, HZ}` | `tests/perf.rs` (120 frames in 2.00 s, 0 late) |
| Two agent workers plus one presentation consumer read the same immutable frame object | conforms | `router/state.rs::op_publish` (roots, not copies) | `tests/perf.rs` (three consumers, store peak 3.7 MB = three 1.2 MB objects in flight, not nine) |
| Bus messages contain only references; no 3x byte fan-out through the router | conforms | `wire.rs::Attachment` | `tests/artifacts.rs::fan_out_shares_one_object_and_the_last_consumer_collects` (both), `tests/perf.rs` |
| Readers still incur memory traffic; renderer readback and seal copying remain real costs | conforms, and both are now measured separately | `tests/perf.rs` (`producer copy into staging`, `seal`, `consumer readback`) | `tests/perf.rs` |
| No claim of zero-copy capture or measured host capacity | conforms: the measurement section below says so in those words | `tests/perf.rs` header | — |
| Nothing game-specific, no rendering, publishing or sampling logic in Flybus | conforms: no crate in the workspace depends on flybus yet, and the crate names no game, brain or stream concept | `crates/flybus/**` | `tests/integration.rs::session_over_one_router` (both; the domain lives in the test) |
## 11. Acceptance tests and implementation sequence
| bus-v1 item | Status | Test |
| --- | --- | --- |
| 1. Wire/router: schema, framing, Hello, exclusive routes, pinned incarnations, request/reply, disconnect, bounds; in-memory passes the same tests as Unix sockets | conforms | `tests/conformance_wire.rs` (45), `tests/wire.rs` (12), `tests/rpc.rs` (26), all `both_transports!`; `tests/bus_acceptance.rs::both_transports_produce_equivalent_behaviour_traces` |
| 2. Pub/sub: exact topics, FIFO/bounded rejection, latest coalescing, retained replay and clear, atomic fan-out, fair control/reply delivery under a saturated subscriber | conforms | `tests/pubsub.rs` (20), `tests/conformance_routing.rs` (24) |
| 3. Artifacts: allocate/seal/read; publication before seal fails; fan-out owns one object; the last consumer releases; a retained extracted frame survives a message drop | conforms | `tests/artifacts.rs` (28), `tests/conformance_artifacts.rs` (36) |
| 4. Faults: sender drops after admission, consumer dies mid-read, reply lost, queued frame replaced, subscription closes with in-use deliveries, router restarts, old release arrives; no double-free, use-after-reuse, unbounded tombstones or hidden replay | conforms | `tests/conformance_routing.rs::{caller_disconnect_detaches_dispatched_call_but_service_keeps_serving, subscriber_disconnect_releases_queued_and_delivered_artifacts_but_not_retention}`, `tests/artifacts.rs::{release_ids_are_watermarked, router_restart_invalidates_old_handles}`, `tests/bus_acceptance.rs::{a_lost_result_leaks_no_roots_and_the_endpoint_cache_still_replays, disconnect_releases_logical_ownership_without_mutating_open_bytes}`, `tests/sol_rereview_regressions.rs` (11) |
| 5. RPC cache: an endpoint retains an artifact-bearing result, the original caller consumes it, a domain retry still returns valid bytes, eviction drops the last hold | conforms | `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both), `tests/bus_acceptance.rs::a_retransmission_repeats_the_domain_request_under_a_fresh_call_id` (both) |
| 6. Integration: two parallel fake agents, a complete-batch environment RPC, committed snapshot publication and a deliberately slow presentation consumer on one router | conforms; the consumer is slow by construction, held until the publisher's completion is observed, so its coalescing is forced rather than raced for | `tests/integration.rs::session_over_one_router` (both) |
| 7. Performance: 640x480x60 with three consumers, one delayed; p50/p95/p99 RPC latency, router CPU, copy and readback cost separately, RSS, store live and peak bytes, outstanding roots, collection lag, queue lengths, for one, two and four agents | conforms | `tests/perf.rs::frames_at_60hz_with_three_consumers` (`--ignored`); numbers below |
| The first executable example: a counter RPC, a pub/sub observer and a frame artifact held past message consumption, in one small Rust program, no game or browser | conforms | `examples/demo.rs` (`cargo run -p flybus --example demo`), asserted by `tests/example_demo.rs::the_example_shows_a_counter_rpc_an_observer_and_a_held_frame` |
## The implementation guide's acceptance bullets
Every bullet of BUS-01, BUS-02 and BUS-03, with the named test that proves it. A bullet a
pre-existing suite already covered is cited here rather than duplicated; the rest are the
tests in `tests/bus_acceptance.rs`, named after their bullet.
### BUS-01 — router and RPC, in-memory and Unix socket parity
| Bullet | Test |
| --- | --- |
| Partial frames and writes | `tests/conformance_wire.rs::{a_frame_written_one_byte_at_a_time_still_decodes, a_reply_read_one_byte_at_a_time_still_decodes, truncated_frame_disconnects_cleanly, length_prefix_is_little_endian}` (both), `tests/sol_rereview_regressions.rs::{shutdown_cancels_partial_rpc_request_before_reclaiming_attachment, protocol_close_cancels_partial_topic_frame_before_reclaiming_attachment}` |
| Disconnect after request | `tests/rpc.rs::service_disconnect_fails_calls` (both), `tests/conformance_routing.rs::caller_disconnect_detaches_dispatched_call_but_service_keeps_serving` (both), `tests/sol_review_races.rs::caller_disconnect_cleanup_works_before_and_after_consumption` |
| Lost result | **new** `tests/bus_acceptance.rs::a_lost_result_leaks_no_roots_and_the_endpoint_cache_still_replays` (both) |
| Retransmission fixtures | **new** `tests/bus_acceptance.rs::a_retransmission_repeats_the_domain_request_under_a_fresh_call_id` (both), with `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| No automatic retry | **new** `tests/bus_acceptance.rs::no_automatic_retry_or_failover_onto_a_replacement_registration` (both) |
| Cancel after dispatch reports execution-unknown | `tests/rpc.rs::cancellation_states` (both), `tests/sol_review_races.rs::reply_racing_cancel_has_only_the_two_contract_outcomes` |
| Incarnation replacement is visible | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both), `tests/conformance_routing.rs::{duplicate_registration_by_owner_itself_is_rejected, unpinned_call_after_incarnation_replacement_reaches_the_new_holder}` (both) |
| Out-of-order replies | `tests/rpc.rs::fifo_dispatch_and_out_of_order_completion` (both), `tests/conformance_routing.rs::out_of_order_replies_correlate_across_concurrent_callers` (both) |
| Status RPC responds while another handler is delayed | **new** `tests/bus_acceptance.rs::a_status_rpc_responds_while_another_handler_is_delayed` (both) |
| Saturation is bounded | `tests/rpc.rs::{service_queue_backpressure, active_call_limit}` (both), `tests/wire.rs::control_lane_exhaustion_closes` (both), `tests/sol_review_races.rs::pending_connections_are_bounded_and_hello_expires` |
| Both transports produce equivalent behaviour traces | **new** `tests/bus_acceptance.rs::both_transports_produce_equivalent_behaviour_traces`, over the trace recorder in `tests/common/mod.rs::Trace` |
The recorder keeps behaviour and refuses operational identity: `Trace::record` panics on any
router-issued id, so a trace holds methods, payload fields, counts, sequences, credits, cancel
states and error codes only. The two scenarios (an RPC one and a pub/sub-plus-artifact one)
produce 29 events, identical over both transports; `FLYBUS_TRACE=1` prints them.
### BUS-02 — pub/sub, retention and backpressure
| Bullet | Test |
| --- | --- |
| Overflow rejects a bounded publication before partial fan-out | `tests/pubsub.rs::bounded_fifo_and_atomic_backpressure` (both), `tests/conformance_routing.rs::bounded_overflow_rolls_back_all_artifact_roots` (both) |
| Latest replaces only queued messages | `tests/pubsub.rs::latest_coalesces_only_undelivered_values` (both), `tests/conformance_artifacts.rs::latest_mode_holds_at_most_two_roots_delivered_plus_queued` (both) |
| Delivery consumption returns credits | `tests/pubsub.rs::credits_return_only_on_consume` (both), `tests/conformance_routing.rs::bounded_credit_waits_for_every_extracted_artifact` (both) |
| Unsubscribe preserves already-delivered ownership | `tests/pubsub.rs::unsubscribe_discards_queue_but_not_deliveries` (both), `tests/conformance_routing.rs::unsubscribe_cannot_reach_another_connections_subscription_id` (both) |
| Retained replay is ordered | `tests/pubsub.rs::retained_replay_clear_delete_and_incarnations` (both), `tests/conformance_routing.rs::{latest_replay_is_ordered_ahead_of_a_racing_publish, cleared_topic_gives_no_replay_until_a_fresh_publish}` (both), `tests/sol_review_races.rs::{retained_replay_obeys_bounded_queue_byte_quota, latest_replay_remains_bounded_outside_the_bounded_byte_pool}` |
| Stalled observers cannot starve RPC replies | `tests/pubsub.rs::saturated_subscriber_does_not_block_control` (both), `tests/sol_rereview_regressions.rs::{fair_topic_insertion_preserves_router_envelope_order, sdk_accepts_fair_topic_insertion_through_saturated_control_backlog}` |
All six were already covered, so BUS-02 added no test of its own. The equivalence trace above
carries a pub/sub and artifact scenario, so BUS-02's behaviour is in the transport comparison
too, and `a_latest_subscriber_never_refuses_a_publication` (both) proves the rule that sits
behind "latest replaces only queued messages": the replacement never turns into a refusal.
### BUS-03 — artifact-backed messages and automatic lifetimes
| Bullet | Test |
| --- | --- |
| Last owner collects | `tests/artifacts.rs::fan_out_shares_one_object_and_the_last_consumer_collects` (both), `tests/conformance_artifacts.rs::collection_waits_for_every_retained_owner` (both) |
| Extracted handle survives message drop | `tests/artifacts.rs::extracted_artifacts_outlive_their_message` (both), `tests/conformance_artifacts.rs::{extracted_artifact_outlives_the_message_it_came_from, explicit_retain_outlives_the_original_hold}` (both) |
| Forward before release is safe | `tests/conformance_artifacts.rs::forward_requires_the_source_owner_still_live` (both), `tests/sol_review_races.rs::unsent_oversized_call_rolls_back_its_local_slot`, `tests/integration.rs::session_over_one_router` (both; the coordinator forwards a frame to two agents) |
| Lost replies and cache replay remain valid | **new** `tests/bus_acceptance.rs::a_lost_result_leaks_no_roots_and_the_endpoint_cache_still_replays` (both), with `tests/rpc.rs::endpoint_cache_replays_artifact_results` (both) |
| Disconnect releases logical ownership without mutating still-mapped bytes | **new** `tests/bus_acceptance.rs::disconnect_releases_logical_ownership_without_mutating_open_bytes` (both), with `tests/artifacts.rs::{disconnect_releases_all_but_retained, seal_is_immune_to_live_writable_handles}` (both) |
| Retained latest and queue replacement release the correct roots | `tests/conformance_artifacts.rs::{latest_mode_holds_at_most_two_roots_delivered_plus_queued, retained_topic_value_holds_a_root_independent_of_subscribers, queued_deliveries_hold_roots_before_dispatch}` (both), `tests/conformance_routing.rs::subscriber_disconnect_releases_queued_and_delivered_artifacts_but_not_retention` (both) |
| Measure 640x480 RGBA x 60 with three readers: one stored image, no raw pixels in router messages, bounded CPU/RSS/owners/queues, reader and copy costs recorded | `tests/perf.rs::frames_at_60hz_with_three_consumers`; see the measurement below |
## The crate README's differences from the draft
Each of the differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict |
| --- | --- |
| 1. Extra error codes `CONFLICT`, `NO_TOPIC`, `ARTIFACT_MISMATCH` | Kept. Allowed by section 9: "Transport errors **include** `INVALID_ENVELOPE`, ..." — an inclusive list. Each names a refusal the draft requires without naming its code, so all three are now in the bus-v1 amendment (section 12) |
| 2. Topics must be declared; `topic.clear` of an unknown topic is `NO_TOPIC` while `topic.delete` answers `deleted:false` | Kept. The draft is silent; section 7's "Topic count and retained bytes are capped" and `topic.declare`'s "conflicting settings fail" both presuppose a registry. See the section 7 row |
| 3. When notices are sent | Kept. Section 5 requires the three notices but says nothing about audience or timing: "Required bounded notices are route removal, subscription closure and call failure" |
| 4. Byte budgets: `max_queued_bytes_per_client` counts bounded subscriptions only; `max_retained_bytes` added | Kept, and no longer a difference: the section 9 table now names the bounded pool and bounds latest slots separately (amendment, contradiction 1), and section 7's "Topic count and retained bytes are capped" requires the retained cap |
| 5. Admission sizes a delivery with the router-added ids at their longest, so an inbound envelope near 65,536 bytes can be refused although it fits | Kept, and required: section 5's "Message length includes this wrapper" plus section 4's fixed maximum mean the delivery the router would build must also fit. ipc-v1 section 2's "must not silently truncate a payload" forbids the alternative |
| 6. One live connection per client id; a client id's last incarnation may not be reused; only `*_as` endpoints authenticate the Hello id | Kept. See the section 3 and 4 rows: section 3's per-incarnation callId uniqueness and section 4's launcher-provided privileges |
| 7. The seal reply's ownerId is the writer's own id, now a hold | Kept. Section 8.2: "seal transfers its unique writer" — one owner token, transferred |
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
| 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` |
| 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) |
| 11. Read locations in deliveries | Kept. The bus-v1 amendment of 2026-10-01 (BUS-01) |
| 12. Sealing sends, `recycle`, and no `rpc.responder.release` after an admitted reply | Kept. The bus-v1 amendment of 2026-10-02 (BUS-02); section 8.1's immutability holds because the sealed bytes are still a copy, and a reply the router admitted already ended the reply authority the release would give up |
## Measured on the dev VM
Two complete release runs of `cargo test --release -p flybus --test perf -- --ignored
--nocapture` on the development VM (4 CPUs), 640x480 RGBA at 60 Hz for 2 s per schedule, three
latest-mode consumers with the third delayed 40 ms per frame, and one, two and four agent
services called every frame. The router runs on its own two-thread Tokio runtime whose threads
carry a distinct name, so its CPU (routing plus the seal copies on its blocking pool) is
measured apart from the clients' four threads in the same process. Each cell is the range over
the two runs.
| Metric | 1 agent | 2 agents | 4 agents |
| --- | --- | --- | --- |
| Frames produced (late) | 120 (0) | 120 (0) | 120 (0 and 3) |
| RPC round trip ms p50/p95/p99 | 0.51-0.60 / 0.84-1.47 / 1.12-2.05 | 0.76-0.78 / 1.34-2.21 / 2.14-6.18 | 1.04-1.08 / 1.67-5.01 / 2.06-10.02 |
| allocate (quota + staging file) ms | 0.96-1.01 / 1.13-1.28 / 1.34-1.49 | 0.98-1.02 / 1.22-3.50 / 1.82-5.61 | 0.80-0.94 / 1.15-5.32 / 1.31-6.60 |
| producer copy into staging ms | 0.37-0.38 / 0.45-0.49 / 0.67-0.75 | 0.37 / 0.45 / 0.51-0.55 | 0.36-0.39 / 0.41-0.49 / 0.48-0.77 |
| seal, router copy to a sealed inode, ms | 1.31-1.35 / 1.65-1.73 / 1.89-1.90 | 1.27-1.42 / 1.69-4.97 / 1.87-7.41 | 1.14-1.30 / 1.64-5.33 / 1.72-7.00 |
| publish admission ms | 0.41-0.42 / 0.61-0.85 / 0.68-1.11 | 0.41-0.43 / 0.83-1.07 / 1.17-3.10 | 0.42-0.49 / 0.73-2.75 / 1.52-4.54 |
| consumer readback of 1.2 MB ms | 0.65-0.75 / 1.19-1.53 / 1.45-1.92 | 0.76-0.91 / 1.45-2.20 / 1.76-6.02 | 0.89-0.99 / 1.67-4.85 / 2.04-6.38 |
| Router CPU (cores, of 2 threads) | 0.175-0.185 | 0.200 | 0.175-0.215 |
| Whole process CPU (cores, of 6 threads) | 0.325-0.335 | 0.410-0.425 | 0.370-0.460 |
| VmRSS / VmHWM | 11.2-13.6 / 13.6-14.4 MB | 11.8-14.1 / 15.0 MB | 15.7-15.8 / 16.4-16.6 MB |
| Store bytes peak / live after drain | 3.7 MB / 0 | 3.7 MB / 0 | 3.7 MB / 0 |
| Outstanding roots peak / live | 5-6 / 0 | 6 / 0 | 5-6 / 0 |
| Queue length peak / live | 1 / 0 | 1 / 0 | 1 / 0 |
| Collection lag after the last frame | 63.5-74.7 ms | 73.6-83.0 ms | 44.1-68.2 ms |
| Frames seen by the three consumers (coalesced) | 120, 120, 49 (0, 0, 70-71) | 120, 120, 49 (0, 0, 71) | 120, 120, 47-49 (0, 0, 70-71) |
What the numbers do and do not say:
- **These are not capacity claims.** Two runs of a synthetic two-second schedule, in one
process, on one shared virtual machine with fewer CPUs than the process has threads, over
temporary local storage, with no capture device, encoder or renderer in the path. They are a
floor on cost, not a ceiling on throughput, and nothing here licenses a sizing decision.
- The second run's tails are three to five times the first run's (RPC p99 10.02 ms against
2.06 ms at four agents, three late frames against none) because other work shared the VM's
four CPUs during it. The p50s barely moved. That spread is the honest width of a measurement
on a shared host, not a property of the bus.
- No byte fan-out: three consumers of a 1.2 MB frame kept the store's peak at 3.7 MB, which is
one sealed object plus the staging and sealing copies of the next frame, not one object per
consumer. Outstanding roots peaked at six.
- Copy costs are real and dominate routing: the producer's copy into staging (p50 0.4 ms), the
router's seal copy into a fresh inode (p50 1.1 to 1.4 ms) and a consumer's readback (p50 0.7
to 1.0 ms) each cost as much as or more than publish admission (p50 0.4 ms).
- The delayed consumer coalesced 70 or 71 of 120 frames and never caused a rejected
publication, which is section 9's rule about latest spectators in one number.
- Every schedule drained completely: live store bytes, roots and queue lengths are zero
afterwards, 44 to 83 ms behind the last frame.
- Router CPU grows with agent count much more slowly than the whole process (0.18 to 0.22
cores against 0.33 to 0.46), because the clients own the copies. A thread that exits between
two samples takes its CPU with it, so the router figure is a floor.
## A flaky test and what it was measuring, 2026-09-22 (MEDIA-01)
`tests/sol_review_races.rs::caller_disconnect_cleanup_works_before_and_after_consumption`
failed intermittently on `main` after the bus slice merged. Reproduced here at
**37 failures in 240 runs** (four parallel loops of 60, debug, on the loaded dev VM), always
on the same line and always the same way: `responder.reply(...)` returned `routed:true` where
the test asserted `false`.
The mechanism is a synchronisation gap in the test, not a routing defect.
`router/state.rs::op_reply` returns `routed:false` only when `call.detached` is set, and for a
disconnected caller that flag is set by `router/state.rs::disconnect`, which the router runs
when **its** connection task reads EOF. `Client::close` documents what it waits for — "flushes
queued releases, closes the connection and waits until the reader has stopped ... the router
releases what they owned" — which is the client side only. So after `close()` returns, the
router may not have torn the caller's connection down yet, and a reply that reaches it first is
routed to a connection that is already closing. Nothing escapes: `disconnect` then releases
that connection's roots along with the queued result, which is why the test's own later
`settle` calls always passed. Only the `routed` flag, read one step too early, was wrong.
The fix is in the test: it now waits for the teardown it is talking about
(`e.settle("caller-a disconnected", |s| s.connections == 1)`) before asserting the
reply-to-a-detached-call sentence of section 6. That is the same bounded
poll-until-the-router-settles the rest of the file already uses for router-side consequences;
no sleep, no timing constant, and the assertion now has the precondition its contract sentence
names. **360 runs after the fix, 0 failures** (240 debug, 120 release).
Two other intermittent failures were seen in the same sweep. They belonged to the bus slice
rather than to this one and were fixed there, in the same way and for the same reason:
- `tests/example_demo.rs::the_example_shows_a_counter_rpc_an_observer_and_a_held_frame`,
2 failures in 40 standalone runs plus 1 in 12 full-suite runs. It printed
"while the frame is held: 1 artifact(s), 2 root(s)" instead of 1 root: the producer's hold
release is queued on the control lane and had not been applied when the example read the
counts. `examples/demo.rs` now waits for that release before reading the counts, the same
bounded poll it already used for collection eight lines below, so the line the guide quotes
is an observation rather than a race. The printed output is unchanged.
- `tests/integration.rs::session_over_one_router`, 1 failure in 12 full-suite runs and 0 in 40
standalone runs, at the assertion that the deliberately slow consumer skipped snapshots.
Under load it kept up, so the assertion was a timing claim about the machine: section 7
permits a latest subscriber to miss values, it does not oblige it to. The renderer is now
held until the publisher's twentieth receipt has returned -- the publisher's completion
observed, not timed -- so the coalescing is forced by construction, and the test asserts the
guarantees that do hold: each delivery carries the frame of the snapshot it announces,
deliveries arrive in publication order, the last value received is the latest published, the
renderer receives snapshots 1 and 20 of 20, both subscriptions accept all twenty publications
while the spectator reads nothing, and the eighteen replacements reported to the publisher at
admission are the same eighteen reported to the renderer on delivery and are exactly the
snapshots it did not receive. 16 failures in 40 runs beside four busy loops before, 0 in 40
after; the whole crate went from 10 failed runs in 20 to 0, and the workspace suite from 2
in 5 to 0.
## Contradictions
Two, both inside bus-v1, both minor, neither resolved by changing code. Both were referred to
the coordinator rather than guessed at, and both now carry a dated amendment in bus-v1
section 12; the rows above cite the amended wording. The original reading is kept here because
it is the reason for the amendment.
1. **The per-client queued envelope byte budget versus the latest-mode guarantee.** Section 9's
table has "Per-client ordinary queued envelope bytes | 1 MiB". Section 7 requires that a
latest subscriber always has one replaceable queued value, and section 9 itself says "latest
spectator subscriptions cannot hold a required session transaction indefinitely" — that is, a
latest subscriber must never be the reason a publication is rejected. A byte budget that
covered latest slots and rejected on overflow would violate the second statement; a budget
that excludes them is not the sentence in the table. The crate excludes them, which keeps the
normative sentence and loosens the table row: the worst case becomes subscriptions x 64 KiB
(8 MiB at the default 128 subscriptions per client) instead of 1 MiB. **Resolved in the
spec, not the code** (2026-09-22): the table row now names the bounded pool and latest slots
have their own row, so the implementation conforms as written. No behaviour changed, and
`a_latest_subscriber_never_refuses_a_publication` now proves the guarantee directly.
2. **A call `budget` versus a client-owned deadline.** Section 2's illustrative surface passes a
`budget` into `bus.call(...)`, while section 6 states "A deadline belongs to the calling
client" and gives the router no timeout behaviour, and section 5's `rpc.call` body has no
budget field. The crate follows sections 5 and 6 and has no budget argument, which is safe
because section 2 is labelled illustrative. **Resolved in the spec, not the code**
(2026-09-22): the sketch drops `budget` and shows the deadline at the caller, so the
illustrative surface and the wire contract now agree.
Ambiguities resolved without treating them as contradictions, for the record:
- Section 5's "Reply only by the registered recipient" is read as "by the connection the request
was delivered to", so that section 6's "dispatched calls can still be answered" after
`service.unregister` remains possible. The crate correlates replies by request delivery id on
that connection, not by the live registration.
- Section 9's "Active calls per client 64" is read as calls the caller still awaits: a call
detached by a post-dispatch cancel frees its caller slot while the router keeps the bounded
correlation record until the service consumes or answers it.
## Not implemented, and who owns it
- A standalone router executable (section 1 calls it optional): embed `Router`.
- Bindings in other languages (section 1: a binding "may" exist), and the mapping/FFI pointer
lifetime rules that section 8.3 writes for them.
- A memory storage backend (section 4) and pooled shared memory with generation reuse
(section 8.4), both deferred by the draft.
- Domain-schema enforcement that every referenced artifact is listed in attachments (section 4),
and the domain `RESULT_EXPIRED` outcome (section 6): CONTRACT-01 and `fly-session-rpc`.
- Epoch failure and coherent recovery after a router restart (section 8.4): the session
contract, STATE-01.
- Any consumer at all: no other crate depends on flybus yet, so the feed and control surfaces of
[feed-protocol](../../feed-protocol.md) and [control-api](../../control-api.md) are untouched
and the crate's "Wiring still pending" list still stands.

View file

@ -43,7 +43,7 @@ Illustrative Rust surface (not yet implemented):
```rust ```rust
let bus = Client::connect(config).await?; let bus = Client::connect(config).await?;
let service = bus.register("agent.fly-a", service_config).await?; let service = bus.register("agent.fly-a", service_config).await?;
let reply = timeout(deadline, bus.call(target, "Agent.Prepare", payload, attachments)).await?; let reply = bus.call(target, "Agent.Prepare", payload, attachments, budget).await?;
let subscription = bus.subscribe("session.demo.snapshots", subscription_config).await?; let subscription = bus.subscribe("session.demo.snapshots", subscription_config).await?;
bus.publish("session.demo.snapshots", payload, attachments).await?; bus.publish("session.demo.snapshots", payload, attachments).await?;
@ -207,11 +207,7 @@ roots, so an idempotent repeat may report zero. Queue/credit requests are intege
and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters. and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters.
call target is a service name; expectedIncarnation is its registration ID, not worker process ID. call target is a service name; expectedIncarnation is its registration ID, not worker process ID.
Location grants are `{storeId, relativePath}` resolved by the client beneath the configured Location grants are `{storeId, relativePath}` resolved by the client beneath the configured
local store root; absolute paths, parent traversal and symlink escapes are rejected (the local store root; absolute paths, parent traversal and symlink escapes are rejected. They
reference SDK caches a store's canonical directories per connection, BUS-02, and still checks
each file with an lstat and an `O_NOFOLLOW` open; a store directory replaced by a symlink after a
connection first used it is not re-checked by that connection, which the store's 0700 owner-only
directory makes a same-user act). They
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
committed into application schemas or source configuration. committed into application schemas or source configuration.
@ -426,8 +422,7 @@ Configure limits explicitly; these defaults are a prototype starting point, not
| Bounded subscription queued / in-flight deliveries | 64 / 16 | | Bounded subscription queued / in-flight deliveries | 64 / 16 |
| Active owners per client | 256 | | Active owners per client | 256 |
| Total artifact storage / per object | 512 MiB / 128 MiB | | Total artifact storage / per object | 512 MiB / 128 MiB |
| Per-client ordinary bounded queued envelope bytes | 1 MiB | | Per-client ordinary queued envelope bytes | 1 MiB |
| Latest subscription slots | subscriptions × 64 KiB |
| Reserved management/reply lane | 128 frames and 1 MiB per client | | Reserved management/reply lane | 128 frames and 1 MiB per client |
Reserve an owner allowance for lifecycle/results separately from ordinary telemetry; memory Reserve an owner allowance for lifecycle/results separately from ordinary telemetry; memory
@ -443,8 +438,7 @@ bounded; rejected callers choose their own retry/fail/pause policy.
Transport errors include `INVALID_ENVELOPE`, `VERSION_MISMATCH`, `NOT_AUTHORIZED`, Transport errors include `INVALID_ENVELOPE`, `VERSION_MISMATCH`, `NOT_AUTHORIZED`,
`NO_SERVICE`, `TARGET_CHANGED`, `BACKPRESSURE`, `CALL_GONE`, `ARTIFACT_UNSEALED`, `NO_SERVICE`, `TARGET_CHANGED`, `BACKPRESSURE`, `CALL_GONE`, `ARTIFACT_UNSEALED`,
`ARTIFACT_GONE`, `OWNER_INVALID`, `QUOTA_EXCEEDED`, `STORE_FAILURE`, `ROUTER_LOST`, and the `ARTIFACT_GONE`, `OWNER_INVALID`, `QUOTA_EXCEEDED`, `STORE_FAILURE`, `ROUTER_LOST`.
three of section 12.
Before admission use dispatch:not-dispatched. Once dispatch might have occurred, report Before admission use dispatch:not-dispatched. Once dispatch might have occurred, report
unknown/dispatched conservatively; a caller-side timeout must not imply no mutation. unknown/dispatched conservatively; a caller-side timeout must not imply no mutation.
@ -490,120 +484,3 @@ pipeline may itself exchange large artifacts through this same bus if useful.
The first executable example should show a counter RPC, a pub/sub observer, and a frame The first executable example should show a counter RPC, a pub/sub observer, and a frame
artifact held past message consumption in one small Rust program. No game or browser required. artifact held past message consumption in one small Rust program. No game or browser required.
Distributed simulation ordering remains the [session contract's](step-v1.md) responsibility. Distributed simulation ordering remains the [session contract's](step-v1.md) responsibility.
## 12. Amendments
Draft 1 stands as written above. Each amendment below names something the draft requires but
left unnamed, and is dated. The implementation and the sentence-by-sentence audit behind these
entries are in the [conformance report](bus-conformance.md).
**2026-09-22, from the flybus conformance audit.** Three error codes, because section 9's list
is inclusive and these three refusals had no name:
| Code | Reason |
| --- | --- |
| `CONFLICT` | Section 3's duplicate registration, section 5's conflicting topic redeclaration and section 5's `topic.delete` with subscribers are refusals of a live claim, not a missing route, a quota or a bad envelope. |
| `NO_TOPIC` | Publishing to or subscribing to a name nobody declared is a missing topic, and `NO_SERVICE` names the service case only. |
| `ARTIFACT_MISMATCH` | Section 9's "hash mismatch returns a typed artifact error", plus a sealed length that disagrees with the allocation and a reference that disagrees with the artifact it names; `STORE_FAILURE` would blame the store for the caller's claim. |
**2026-09-22, same audit.** One added operation, because section 6 requires bounded call
correlation and gives no way to end it when a handler keeps reply authority after releasing the
request delivery:
| Command | Body / reply value | Semantics |
| --- | --- | --- |
| `rpc.responder.release` | `{callId, requestDeliveryId}` -> `{released}` | The recipient gives up reply authority for a dispatched call. The final release for an attached call retires the correlation and emits `call.failed` with dispatch `dispatched`: `CALL_GONE` while the route is live, `NO_SERVICE` after route loss. Request consumption (section 8.3) stays independent of it. |
Both amendments change `contractDigest`, which section 4 already provides for.
**2026-09-22, coordinator decision on the audit's contradiction 1.** Section 9's table row
"Per-client ordinary queued envelope bytes | 1 MiB" now reads "Per-client ordinary **bounded**
queued envelope bytes", and latest slots get their own row, "subscriptions × 64 KiB", because
section 7's unconditional one-slot guarantee and the structural 1/2 cap outweigh one imprecise
table row: a budget whose overflow rejects a publication cannot contain a subscription that
this same section forbids to reject one.
**2026-09-22, coordinator decision on the audit's contradiction 2.** Section 2's sketch no
longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because
section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled
illustrative.
**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client
gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in
the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no
router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into
one under the same reference. They read, clone and retain without a router, and no router ever
learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish`
before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
the same date); section 8's ownership rules apply to every artifact a router stores, which these
never are.
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
a frame for an answer the router already knows when it delivers.
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
`artifact.open` would return for that artifact under that delivery's ownership. It is still
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
symlink checks, and never placed in an application body.
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
field, and the connection closes as for any malformed envelope.
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
client that prefers to ask.
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
that needs the bytes kept alive can keep a clone instead of taking a second hold.
**2026-10-02, BUS-02 (wire change; `contractDigest` changes).** A sending command may seal the
artifacts it attaches. Section 8.1 makes a producer seal (`artifact.seal`, one router round trip)
before any message may name the artifact, and section 5 allocates every artifact afresh
(`artifact.allocate`, another). A participant that replies with media every transition -- the
legacy world a frame, a memory image and an audio chunk, the agent a spike bitset and its feed
status -- paid both for every artifact of every transition, two of them on the transition's
critical path, for answers the router could give as it admits the reply.
- **Sealing attachments.** In `rpc.call`, `rpc.reply` and `publish`, an attachment's `ownerId` may
be the sender's own writer of `ref.artifactId`, still unsealed. Its `ref` is the reference the
sealed artifact will have: this store, generation 1, the allocation's content type, a null
digest, and a `byteLength` of at most the allocation -- the sealed artifact is the first
`byteLength` staging bytes. As part of admitting the command the router seals each such writer
exactly as `artifact.seal` would (section 8.1: the copy into a fresh sealed inode happens outside
the routing state lock, before anything is admitted, and the connection's later commands wait
for it), the writer becomes the sender's explicit hold on the sealed artifact (as after
`artifact.seal`), and only then is the command admitted as if its sender had sealed first. If a
seal fails, or the command is then refused, nothing is admitted and every writer the command
named is released (with whatever it sealed): the reply carries the refusal, `not-dispatched`.
- **Recycling.** Such a command's body may carry `recycle: true` (a body member of `rpc.call`,
`rpc.reply` and `publish` with at least one sealing attachment, refused otherwise). The router
then keeps each sealed writer's staging file and reissues it as a new writer -- a new
`artifactId`, a new hold `ownerId`, the same allocation and content type -- and the command's
reply value carries `writers: [{name, artifactId, generation, ownerId, writeLocation}]`, one per
attachment it sealed, named by attachment. A writer it cannot reissue (owner budget) is simply
left out. Section 8.1's immutability is unchanged: the sealed bytes are a copy, so a producer
writing into the recycled staging file reaches only the staging inode. A reissued writer is a
fresh allocation in content as well: the router overwrites the staging file with zeros before
the reply, so it reads as zeros and no artifact sealed from it -- a prefix, or the whole
allocation through `artifact.seal` -- can carry bytes of the artifact it was before (review N3,
2026-10-02). `recycle` in a body with no sealing attachment is refused, `false` included, and
one writer named by two attachments of the same command is refused (`INVALID_ENVELOPE`).
- Nothing else changes: deliveries, ownership roots, credits and quotas are those of the command
with pre-sealed attachments; a sealing attachment counts its sealed copy against the store quota
at admission, as `artifact.seal` counts it at the seal.
SDK changes of the same slice, no wire change: `ArtifactWriter::into_unsealed` and
`Responder::reply_sealing` (the client side of the above); a reply the router admitted spends the
call's reply authority, so the SDK no longer sends `rpc.responder.release` after one (it was a
no-op command on every call); the router encodes each frame once and forwards an admitted
payload as the bytes it re-encoded once at admission instead of deep-copying it per delivery.

View file

@ -1,216 +0,0 @@
# Checkpoint envelope v1: `FLYSESS1`
Status: **draft 1**, 2026-09-22. Specified by CONTRACT-01 of the
[implementation guide](implementation.md); required by
[session artifacts, native media and recovery](state-media-v1.md) section 4, which says to
"use a new envelope version; specify exact byte layout before production files". Reference
implementations of the layout: `services/flysim/crates/fly-session-types/src/checkpoint.rs`
and `packages/session-types/src/checkpoint.ts`; fixture:
`.../fly-session-types/fixtures/checkpoint-envelope.json`.
This is the byte layout and the durable commit sequence. The store itself, generations,
rotation, the writer thread and the capture RPC flow are the STATE-01 slice.
## 1. Why a new format
The historical envelope (`FLYSIM01`, `crates/flybrain-core/src/envelope.rs`) is a magic, a
`u32` manifest length, a JSON manifest, `u32`-prefixed chunks in manifest order and a CRC32
footer, with chunk names restricted to ASCII letters so the TypeScript reader can never name a
prototype key. It stays exactly as it is, and its reader stays separately readable: nothing in
this document changes a byte of it, and a `FLYSIM01` file is refused by a `FLYSESS1` reader at
the magic.
A coherent all-participant session checkpoint needs what that format does not have:
- payload names that are `Id`s (`agent-fly-a`, `executor-fly-a`), so the letters-only
constraint is widened **deliberately, in a new version**, rather than quietly;
- a per-payload content digest, because state-media-v1 section 1 makes digests mandatory on
checkpoint payloads and a group install must be able to fail one participant's bytes;
- a payload table with explicit offsets and lengths, so a reader can map one participant's
payload without walking every preceding chunk;
- SHA-256 over the whole prefix instead of CRC32, matching the `Digest` type these contracts
already use everywhere else.
## 2. Byte layout
All integers are unsigned little-endian. All digests are raw 32-byte SHA-256 (the manifest
records the same digests as lowercase hex `Digest` strings).
### Header, 32 bytes
| Offset | Size | Field |
| ---: | ---: | --- |
| 0 | 8 | Magic, ASCII `FLYSESS1` |
| 8 | 4 | `envelopeVersion`, `1` |
| 12 | 4 | `headerBytes`, `32` |
| 16 | 4 | `manifestBytes` |
| 20 | 4 | `payloadCount`, at most 64 |
| 24 | 4 | `tableOffset` |
| 28 | 4 | Reserved, must be zero |
### Manifest
`manifestBytes` bytes of canonical JSON (RFC 8785) at offset 32, no trailing newline. It is
canonical so the envelope's own digest is stable under reserialization, and a reader rejects a
manifest that is not already canonical rather than silently accepting a second spelling.
### Payload table
At `tableOffset`, which is `32 + manifestBytes` rounded up to a multiple of 8.
`payloadCount` entries of 112 bytes each, in write order:
| Offset in entry | Size | Field |
| ---: | ---: | --- |
| 0 | 64 | Name: an `Id` in ASCII, NUL-padded, no bytes after the terminator |
| 64 | 8 | `offset` |
| 72 | 8 | `byteLength` |
| 80 | 32 | SHA-256 of exactly `byteLength` bytes at `offset` |
### Payloads
Each payload starts at its declared offset. The first starts at the end of the table rounded
up to a multiple of 8; each subsequent one starts at the previous payload's end rounded up the
same way. Padding bytes are zero. Offsets are ascending and non-overlapping, which a reader
checks rather than assumes.
### Footer, 48 bytes
| Offset from end | Size | Field |
| ---: | ---: | --- |
| 48 | 8 | `fileBytes`, the total length including the footer |
| 40 | 32 | SHA-256 of every byte before the footer |
| 8 | 8 | Magic, ASCII `FLYSESSF` |
A truncated file therefore fails at the footer magic or the recorded length, not at an
arbitrary payload.
## 3. Manifest fields
State-media-v1 section 4 lists what the manifest records. The names below are the JSON field
names; a manifest missing any of them is not a complete checkpoint.
| Field | Contents |
| --- | --- |
| `envelopeVersion` | `1` |
| `checkpointId` | `Id`, the identity every participant's capture shares |
| `sourceScope` | `Scope`: session, epoch and the committed step |
| `episodeId` | `Id` |
| `worldTime` | `RationalNs`, the environment's logical time at that boundary |
| `schedulerId` | The coordinator's scheduler identity, `lockstep-v1` in v1 |
| `compositionDigest` | Coordinator scheduler and configuration identity |
| `portMap` | The exact port-to-agent map, `[{portId, agentId}]` |
| `compatibility` | Backend, content, patch, controller, parser and state-format identities |
| `agents` | Per agent: profile, dataset, **index** and model identities, resolved seed, tick count, remainder and the payload name holding its state |
| `coordinator` | Task ledger, prior world inspection, per-agent executor state, admission state and event watermarks, each as a payload name or an inline value |
| `helperState` | External-helper state required for exact resume, as payload names |
| `payloads` | `[{name, byteLength, digest}]`, mirroring the payload table |
**Amendment, 2026-09-22 (PUBLISH-01).** The `agents` row gains `indexDigest`, the index the
agent attested to at `Agent.Initialize`, and it joins that agent's compatibility identity.
Without it a replacement fly that built another graph -- the same dataset, the same neuron
count, another index -- passed the group check and was then published under its predecessor's
`indexDigest`, which is a graph identity crossing a recovery and exactly what section 5's rules
exist to prevent. It is recorded from the worker's attestation rather than recomputed from the
dataset, because the point is that the two can disagree. `envelopeVersion` stays `1`, which the
required-manifest-field rule below allows only while no production `FLYSESS1` file exists; once
one does, adding a required manifest field must bump it.
**Amendment, 2026-09-22 (STATE-01).** The table above names a holder for every payload except
the environment's own, although section 6's fixture has one (`world`) and a group install has
to map it by name like any other participant's. The manifest therefore also records:
| Field | Contents |
| --- | --- |
| `environment` | `{workerId, payload}`: which worker the world belonged to and the payload name holding its state |
The reference implementations' required-field set was also missing `helperState`, which this
section has listed from the start. Both are now in `REQUIRED_MANIFEST_FIELDS` in Rust and in
TypeScript, and the fixture was regenerated by the existing example. The schema set is
untouched, so `contractDigest` is unchanged.
`coordinator.eventWatermarks` is `{lastSourceStep, issued}`. The fixture illustrated
`{lastEventId, lastOrdinal}`, and it is the illustration that changed: an event id is derived
from the epoch, so a watermark spelled as one cannot be compared across the restore that
gives the session a new epoch, while a source step and an issued count can.
**A required-manifest-field change is compatibility-relevant and `contractDigest` does not
cover it.** The digest is taken over the schema set, and this manifest is not in it, so
`envelopeVersion` is the only thing that can carry such a change. It stays `1` here only
because no production `FLYSESS1` file exists yet: once one does, adding or removing a required
manifest field **must** bump `envelopeVersion`, because a reader of the older version would
otherwise accept a file it cannot completely read, or refuse one it could.
`payloads` is redundant with the table on purpose: the table is what a reader needs to map
bytes, and the manifest is what a store lists, compares and reports without opening the
payload area. A reader checks that the two agree.
What the manifest must **not** contain (state-media-v1 section 4): a transient bus `storeId`,
artifact ID, owner token, mapping or pointer. Payload bytes and durable content identity are
the only things that survive; on restore the durable store imports fresh bus artifacts, and
`sourceScope` is provenance, not a claim on the current router.
## 4. What a reader enforces
In this order, so a corrupt file fails on its own terms rather than on a derived value:
1. Length at least header plus footer; magic; version; `headerBytes`; reserved word zero.
2. Footer magic, `fileBytes` equal to the actual length, and the prefix digest.
3. Manifest inside the payload area, valid strict JSON (duplicate keys, invalid UTF-8 and
non-finite numbers refused) and already canonical.
4. `tableOffset` exactly at the laid-out position; the table inside the payload area.
5. Per entry: an `Id` name with no bytes after its terminator, names unique, the declared
offset exactly at the aligned end of the previous payload, the payload inside the payload
area, and its digest matching its bytes.
6. No padding between the last payload and the footer.
7. The required manifest field set, `envelopeVersion` of 1, and a `payloads` list that matches
the table name for name, length for length and digest for digest.
Failing any of these is a corrupt or foreign file. The group install rule of state-media-v1
section 5 then applies: corrupt any participant and installation fails as a group.
## 5. Durable commit
State-media-v1 section 6, in the order the writer performs it:
1. Write the envelope to a temporary generation file in the store directory.
2. `fsync` the file.
3. `rename` it to its final generation name.
4. `fsync` the store directory.
5. Write the store manifest to its own temporary file, `fsync`, `rename`, `fsync` the
directory.
**The store manifest rename is the durable commit point.** Before it, the generation file is
an unreferenced temporary that is never a restore candidate. After it, and only after it, the
writer reports a saved acknowledgment and moves the high-water mark.
Consequences the writer must respect rather than reinterpret:
- Bus publications for `captured`, `queued`, `committed`, `failed` and `superseded` are
distinct events; only durable completion produces the saved acknowledgment.
- A lost save reply never advances durable metadata: the coordinator resolves the same
operation or fails the epoch, and an unreferenced generation stays unreferenced.
- A failed write releases its owned ephemeral captures under the configured retry policy and
reports the failure. It never reports false durability.
- The writer owns the bus artifact handles until the bytes are committed or the job fails, and
drops them afterwards; durable files are outside the bus's ephemeral collection.
- No per-payload `fsync` inside one envelope: the single file `fsync` in step 2 covers it.
## 6. Fixture
`fixtures/checkpoint-envelope.json` holds one complete envelope: the manifest, five payloads
(one agent, one executor, the task ledger, the prior inspection and a world payload), the
envelope's base64 bytes, its exact layout (header size, manifest offset and length, table
offset, every entry's offset, length and digest, footer offset, total length) and six
corruptions a reader must refuse, each naming the byte to flip.
The two implementations are held to it from both directions: each parses the fixture and
checks every recorded offset, and the TypeScript side re-encodes the same manifest and
payloads and requires the bytes to be identical to the fixture. A layout change that only one
language makes therefore fails on the next test run.
## 7. Out of scope
Generations, rotation, hot versus durable copies, the capture queue and its bounds, the
`State.Capture` / `State.StageRestore` / `State.ActivateRestore` flow, compatibility
comparison rules and group fencing. Those are STATE-01, over this layout. `FLYSIM01` and the
legacy composition keep their own format and their own reader, unchanged.

View file

@ -160,51 +160,6 @@ delayed rendering retains its handle. Distinguish AssetRef from transient Artifa
**Depends on:** SESSION-02, MEDIA-01 and the profile/identity foundation in the broader backlog. **Depends on:** SESSION-02, MEDIA-01 and the profile/identity foundation in the broader backlog.
**2026-09-22:** blocked. The profile/identity foundation is FOUNDATION-02
(`feat/brain-profile-contract`) in the [MaleCNS backlog](../malecns-modular-implementation.md),
which has not been built. Not started.
**2026-09-23:** unblocked. The operator split FOUNDATION-02 (decision of 2026-09-23): its legacy
half, PROF-02a, is the [legacy Game Boy composition](legacy-gameboy-v1.md) contract with
machine-readable profile, readout-context and decision schemas in `fly-session-types` and
`@flybrain/session-types`; the MaleCNS half (PROF-02b) is later and does not gate this slice.
AGENT-01 builds the legacy profile `gameboy-legacy-fafb-v783-v1` first. It must: report
`brainTicks` equal to the legacy `network.ms` (legacy-gameboy-v1 section 3); consume
`gameboy-readout-context-v1` and return `gameboy-channels-v1`; keep the held channel, blocked
window and last location as private readout state; report `stimulusRemainingMs`; answer
`Agent.Rollback` under capability `legacy-ratchet-rollback-v1`; and choose the mapping from the
legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`,
which that contract leaves open.
**2026-09-23 (AGENT-01 built, `feat/agent-legacy-worker`).** `LegacyAgentWorker`
(`fly-session/src/legacy_agent.rs`) serves the legacy profile under the launcher in all three
execution modes (`legacy-agent` subcommand). Its parity harness (`legacy_parity.rs`) drives
`NeuralAgent` directly in `Sim::step_frame` order from recorded inputs. On the committed toy
connectome, the worker's records match that reference exactly in every mode, including a
rollback and a restore, and are pinned as goldens. A gated FAFB run
(`FLY_AGENT01_FAFB=1`) shows the same on `gameboy-legacy-fafb-v783-v1`. The rate-role mapping
turned out to be the identity: the legacy names are already `Id`s. It is recorded in
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The
harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`.
**2026-09-29 (AGENT-01 rebased onto v0.6.5 and checked against FND-01's trace).** The rebase onto
main had no conflicts. Main changed nothing the worker reads except the adapter id in the
fixtures (v7). The toy goldens and the FAFB reference digest are unchanged. `FLY_TRACE` carries
the frames only as digests and not the `{boot, bound, location}` context, so it checks a worker
and cannot drive one. `legacy_parity::read_frame_trace` and `check_against_trace` hold a run's
records to it: ticks, clock, exact remainder, rates digest, spike-set digest and decision. The
script is checked too: the same sugar, frames, reward events and rollback.
`flysim/tests/agent_trace_parity.rs` is the host. It runs `LegacyFrame` on the ROM with the trace
on, records the missing inputs and checks the worker (in-process, thread and process) and the
direct reference against the trace:
- the toy connectome in raw mode from power-on, for every ROM run;
- `gameboy-legacy-fafb-v783-v1` in macros mode from stream checkpoints (`FLY_AGENT01_FAFB=1`),
with sugar and a ratchet rollback, the worker seeded from the checkpoint's agent state.
Both are identical. Found on the way: a `FLYSIM01` import must start `learning.updates` at the
legacy `plasticity.updates` (legacy-gameboy-v1 section 13, amendment of 2026-09-29).
**Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives;
reference-first composition/goldens; independently seeded agent state and shared immutable data. reference-first composition/goldens; independently seeded agent state and shared immutable data.
Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering.
@ -217,89 +172,6 @@ dispatch order and varying worker count preserves results. Keep 64-role limits e
**Depends on:** AGENT-01 and environment/task extraction in the broader backlog. **Depends on:** AGENT-01 and environment/task extraction in the broader backlog.
**2026-09-22:** blocked. AGENT-01 is blocked, and environment/task extraction is
RUNTIME-01 (`refactor/environment-task-boundary`) in the same backlog, which has not been
built. Not started.
**2026-09-23:** unblocked. RUNTIME-01's contract is the RT-01a amendments of 2026-09-23 to
[workers-v1](workers-v1.md) (sections 1, 3, 4, 5 and the new section 7),
[step-v1](step-v1.md) (sections 2, 3, 5 and 6) and [state-media-v1](state-media-v1.md)
(sections 2, 3, 4, 5 and 7), with the Game Boy specifics in
[legacy-gameboy-v1](legacy-gameboy-v1.md), all implementing the operator's decisions of
2026-09-23. ENV-01 and AGENT-01 may proceed in parallel against the schemas and fixtures; ENV-01
needs FND-01's trace harness for its "legacy fixtures unchanged" acceptance. ENV-01 must also:
add the one read-only bulk memory read to the shim and prove it mutates nothing; publish the
memory image per boundary; declare the one-frame setup scaffold; convert audio to f32 and leave
the DC blocker to the edge; implement `gameboy-slots-v1`; and make the coordinator refuse
`episodeRequest.kind = "rollback"` in any composition that declares no rollback policy (the
synthetic coordinator today pauses on every episode request, which is safe but not the rule).
**Amendment, 2026-09-23 (operator decision of 2026-09-23).** The "Implement" paragraph below said
to keep `legacy-gameboy-v1` separately routed. The operator decided on a full port instead: the
legacy composition runs on `lockstep-v1` as declared in legacy-gameboy-v1, and "exact old
ordering/hash semantics" is kept by construction and by test rather than by a separate route --
the frame order maps one to one (section 4), the legacy clock equals the rational one
(section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2
and 12). The acceptance criteria below stand.
**2026-09-29: built on `port/env-01` (off main `9f2345d`).** `fly-session::legacy_env` is the
environment worker (`LegacyGameboyEnvironment`), launched by `Launcher::launch_legacy_environment`
and the `legacy-environment` subcommand in all three execution modes. It makes exactly the emulator
calls flysim's `LegacyFrame` makes, in the same order: `Environment.Initialize` runs the one-frame
setup scaffold with no button down (O[0] has `engineFrame` "1", no audio chunk);
`Environment.Advance` takes one complete `gameboy-joypad-v1` batch for the one port, runs one frame
and returns the `lcd` view, the `apu` chunk as `f32le` (`sample / 255`, unfiltered) and the
`gameboy-memory-inspection-v1` image; `Environment.SaveSlot` / `RestoreSlot` are
`gameboy-slots-v1` (a restore imports, releases the pad, shows the slot's frame, runs no frame and
moves to the new epoch at the same boundary); `State.Capture` / `StageRestore` / `ActivateRestore`
carry every slot and stage on a stopped replacement emulator. The joypad is the only write into a
running game. The coordinator now refuses `episodeRequest.kind = "rollback"` (task failure, epoch
fenced) unless the composition declares `legacy-ratchet-rollback-v1`
(`Coordinator::declare_rollback_policy`); with the policy declared it still pauses at the boundary,
because the rollback sequence is TASK-01's. Parity (`tests/legacy_env.rs`, harness
`legacy_env_parity`): records equal to the emulator driven directly, frame by frame (view, 64 KiB
image, WRAM, audio chunk, slot and capture state digests), in-process, thread and process, on a
toy cartridge the harness assembles (committed golden `fixtures/legacy-env/toy-cart.golden.json`)
and, with rom-env, on the real cartridge from the row-58 checkpoint; and the service's own
`FLY_TRACE`s (FND-01's harness; `FLY_ENV01_TRACE_DIR`) replayed through the worker reproduce every
recorded frame, WRAM and slot-state digest, including a ratchet slot save and a rollback. Not in
this slice: the shim's bulk read (MEM-01, behind the one seam `legacy_env::memory_image`), the
coordinator's save/rollback/`Agent.Rollback` sequence and the executor (TASK-01), and assembling
the FLYSIM01 export from the three halves (STATE-02; the world's half is
`Flysim01World::{manifest_entries, chunks}`).
**Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice:
- ~~*The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM,
`FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and
`export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The
legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image
would make every slot and capture differ from the service's bytes. The worker reads the image
between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as
the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare")
therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read
must keep that guard (or equivalent).~~
*Struck 2026-09-29 (ENV-01 review, R1):* superseded by MEM-01 (legacy-gameboy-v1 section 8
amendment). The register windows are not captured, so `legacy_env::memory_image` is MEM-01's
`Emulator::read_memory_image` with no guard, neutral by construction; the service traces still
match, and the toy golden's image digests were regenerated.
- *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no
boundary, world clock or audio position. The frame counter advances once per transition and
never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is
`k x stepDuration` and the audio position is that time's sample at the configured rate, rounded
down. The first chunk after the restore marks the discontinuity. The ratchet's one slot is the
composition's first declared slot (`best`).
- *Names.* The image travels as the attachment `inspection.memory`; the audio stream is `apu`;
the port is `p1`. `backendConfig` is the canonical JSON of `gameboy-backend-config-v1`
`{form, romDigest, portId, slots, audio {sampleRate, channels, bufferFrames}, setupFrames, view,
controllerSchema, inspectionSchema}`; `Environment.Initialize` naming any other document, and a
cartridge on disk that is not `romDigest`, are refused `INCOMPATIBLE_STATE` with nothing mutated.
The capture payload is flybrain-core's envelope with magic `FLYENV01`, and its participant
compatibility uses the state format `fly-gb-env-v1`.
- *`legacy-transient-reset` for the world is empty.* Everything the environment holds is restored:
emulator, frame on screen, joypad, frame counter, slots, clock and audio position. The reset
applies to the executor, the agent's readout transient and the task's transient observations.
**Implement:** binjgb environment, task-local memory inspector and identity/existing action **Implement:** binjgb environment, task-local memory inspector and identity/existing action
adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics. adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics.
@ -307,553 +179,6 @@ adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash
its own identity and public adapter selection. No console-specific state enters generic its own identity and public adapter selection. No console-specific state enters generic
session types. ROM-backed checks are optional explicit jobs, not required downloads. session types. ROM-backed checks are optional explicit jobs, not required downloads.
### MEM-01 — The boundary memory image (port slice)
**2026-09-29: built** on `port/mem-01` off v0.6.5 and awaiting review. It changes no live
behaviour: nothing in `flysim` calls the new read, and the compatibility string is unchanged. It
delivers the piece of ENV-01 above that reads "add the one read-only bulk memory read to the shim
and prove it mutates nothing", together with the executor-side reader that TASK-01 and the
CUT-01 shadow need.
- **Shim.** `fly_gb_read_memory_image(gb, out, 65536)` fills the buffer in address order.
`Emulator::read_memory_image{,_into}` wraps it. There is no new write path.
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 8 carries a dated amendment (2026-09-29):
VRAM, OAM and I/O are not captured and read `$FF`. binjgb's read of those windows runs a
catch-up that moves the exported state. Every memory byte is captured exactly.
- **Executor reader.** `flybrain_gb::{MemoryImage, Cartridge, ImageReader}`. `ImageReader`
implements `MemoryReader`. The palette, `MacroLayer`, `PokeState` and `PokemonRedReward` run
over it unchanged; this is the same code, not a port. The emulator's own bank reads now go
through the same `Cartridge::read_bank`.
- **Proof.** flybrain-gb `tests/rom_memory_image.rs` (ROM) checks three things. The exported
state is byte-identical before and after each bulk read over 4,200 boot frames. The image
equals the single and cached reads. Reading every frame leaves framebuffers, audio and state
frame-for-frame equal to a run that is never read. flysim `tests/rom_memory_image.rs` runs a
live arm and an image-only shadow arm (task and executor) from nine rom-env checkpoints for
3,000 frames each: 27,000 frames with about 5.5 M `MacroState` answers, deals, pads,
decisions, rewards, ledgers and rollbacks. It finds 0 mismatches and 0 reads outside the
captured ranges.
- **Cost.** A bulk read has a median of 0.31 ms per boundary, 1.9 % of a 16.74 ms frame or
about 209 MB/s of reading. This is the same cost as the 57,120 single reads it replaces. The
image is 3.91 MB/s at 59.7275 fps. A 64 KiB copy has a median of 5 µs, and the optional
SHA-256 digest a median of 0.36 ms. Means and p99 values are dominated by preemption: the
measurement ran on the shared 4-core build box at load 16.
**For ENV-01:** after `run_frame` and after a slot import, publish
`read_memory_image` as the `gameboy-memory-inspection-v1` artifact (`MEMORY_IMAGE_CONTENT_TYPE`,
65,536 bytes, digest optional, `romDigest` = `Cartridge::sha256_hex`). **For TASK-01:** build
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
### TASK-01 — The `pokered-macros-v1` task and executor (port slice)
**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 +
ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of
the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it
the live fly's whole composition -- agent, world, task and executor -- runs on the session
framework, from a fresh start or from a FLYSIM01 checkpoint.
- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one
object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds
any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide`
over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs
`PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's
decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe`
over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order;
there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is
retained until Phase C has read it.
- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the
coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the
agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A
declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with
`RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters
cover the backend and task config, the media, the decision schema, the world's state format and
per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's
`preStepStimulations` and reports every admission applied or aborted. `Coordinator::import`
installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are
kept for a parity run.
- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's
`legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves
go into each participant's own capture format, and the ordinary group restore installs them:
stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first,
because ENV-01 stages only on a replacement. The context the agent resumes with is computed
from the checkpoint's own memory image, and the coordinator holds the task to it after the
install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`.
- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's
`LegacyCheckpointer`).
- `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy
candidate order, holding each candidate to the legacy gate. Any refusal falls to the next
candidate; each attempt runs on a session of its own, because a refused install fences its
session. It is a fresh start when the stores are empty. After either, the startup durable
save is written and the intervals start.
- `advance` keeps the declared boundary order: the slot save (inside the step), the milestone
archive on a rank climb, the rollback (deferred by the coordinator until the host has
captured), a durable save after a rollback, then the interval saves.
- `shutdown_save` is the legacy shutdown's durable save.
- The session runtime writes no sugar journal yet: its admission is the coordinator's, and the
journal's boot header needs the edge.
- `lastEventId` carries the restored file's watermark; the runtime has no feed event log
before EDGE-01.
- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged,
against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the
next cut.
- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment.
**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session
writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built
from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the
executor's batch, the view, the image and the boundary actions. It is compared field by field with
the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list
order. Where the legacy side runs in the test, the ledgers are compared after every boundary as
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
counts and "nearer". Results: see the TASK-01 run report and the amendment below.
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
B1, N1 and N3.
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
past the 32 KiB `TypedValue` bound.
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
- The coordinator files those attachments as `task-ledger-<name>` payloads in captures and
imports.
- A bad ledger is an error, never a panic, so a boot falls to the next candidate.
- Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB).
- **N1: a sugar admitted before the next commit is an active pulse.**
- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the
seed is never read.
- **N4: saves are queued to the writer thread.**
- **N5: speed.** The profile is below. Changes:
- The world seals its three artifacts concurrently.
- Cache and caller holds are taken concurrently.
- In-process participants use the in-memory transport.
- A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded
history.
- `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside
the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state
under the lock, then encodes, digests and seals it off the lock. The coordinator's
`begin_capture` / `finish_capture` let the session step on while the payload is written.
- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`):
- The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a
few percent.
- What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a
quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit,
plus the world's and the agent's artifact seals and reads.
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
- The report `claude-task-01` has the per-phase table and what would close the rest.
### PERF-01 — The session runtime's per-frame cost (port slice)
**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and
awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the
in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy
loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame,
in-process and process, and the compatibility string is unchanged.
- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30).
An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`,
`launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method.
The request still goes through the shell's admission, deduplication, arrival order and
endpoint, and the reply is the same outcome. Handler media over the lane are in-memory
artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy,
no retain or open round trip. A bus call or a publication carries a sealed copy
(`rpc::promote`), begun while the task and the commits run. Process mode is untouched.
`FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also
runs over the lane.
- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare
ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits,
proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs.
- **The session topic** gets a committed snapshot every 60th boundary in a service session (and
at every boundary with events or boundary actions), not every other one. Nothing in the
release subscribes; the stream is the legacy feed.
- Small ones: a single dispatch job is called in place, the shell moves the reply result
instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling
spans for the shell, the lane, each handler and the brain's own phase clock.
- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any
other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and
work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate
(an AGENT-01 amendment) was not needed once the bitset cost nothing.
- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`;
the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the
release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms
to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
### PERF-02 — The session's ticks on the release cpuset (port slice)
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. Pinning is only safe in a cpuset that is the sim's alone (a pinned worker cannot leave a CPU that something else hogs: 0.14x real time): the deploy makes it so with `flysim.slice` and `fly-cpu-confine` and writes `FLY_SESSION_PIN=0` when it cannot (`infra/docs/runbook.md`). The legacy loop and process mode are
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
workers against the sequential kernel on the real connectome. The service's periodic profile
line also prints the measurement spans (and the brain's phase split) when
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
### BUS-01 (port slice) — The live session's participants on the router
Not the framework guide's BUS-01 above (the router itself); the port plan reuses the name.
**2026-10-01: built** on `port/bus-01` off `main` (v0.7.5), awaiting review. Operator direction:
run the live session over the flybus router on Unix sockets, one emulator and one fly, because
multiplayer and more flies follow. The topology, its rules and the shadow procedure are
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 12 (amendment 2026-10-01) and section 18
(amendment of the same date); the wire change is [bus-v1](bus-v1.md) section 12 (2026-10-01).
- **Selecting it.** `FLY_SESSION_TRANSPORT=bus` / `flysim-session --transport bus` (process mode
by default; `FLY_SESSION_MODE=thread` and `in-process` too), `fly-runtime session --bus`
(`session-bus`) on the container, `fly-shadow --mode bus/process` and
`fly-shadow-run start --bus` / `check --bus` for its shadow. The local lane stays the default.
`SessionArm` names the four arms; `FLY_PARITY_ARMS` picks them for the parity suites (default
`local,bus/thread,bus/process`).
- **What it took.** Per-process CPU placement (`Launcher::place_process`,
`--host-cpus`/`--sweep-cpus`, `flybrain_core::pool::apply_placement`), the launcher's own clients
in memory in thread and process modes, `block_in_place` for a bus request's handler (without it a
slow `Agent.Initialize` could not be resolved and a process-mode session failed to boot on a
loaded box: "never resolved"), delivered read locations (bus-v1 amendment), writers allocated
ahead (`WriterPool`), no second hold on a worker's own seals, small store I/O in place, the
envelope encoded without copying its body, and the agent's feed status attached to a bus Commit
(the host's 30 Hz `Legacy.FeedStatus` call was a round trip of its own).
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`, as v0.7.5) are the same in every arm: the toy and FAFB parity suites
(`session_trace`, `service_parity`, `rollback_sequence`, `save_handoff`) ran `local`,
`bus/thread` and `bus/process`.
- **Measured, and not fast enough to go live.** The report `claude-bus-01` has the tables. On a
build box with the release CPU model and the release cpuset's shape (four CPUs, four sweep
threads), same frames, interleaved, unpaced: legacy 16.1 ms a frame, the lane 17.4,
`bus/thread` 25.1, `bus/process` 25.7 (`main`'s process mode: 30.4, so this slice took about a
third off the bus's cost). Paced at real time the lane holds 1.00 and the bus 0.69 to 0.71, with a
neighbour CPU busy or not. Every round trip through the router is 0.5 to 1 ms there (the
synthetic `fly-session measure` puts a bare `Worker.Status` at 0.5 ms whether the processes
share one CPU or four), and a transition needs at least five in sequence: Prepare; Advance and
its seals; Commit and its seals. That is a realtime factor of roughly 0.7 on the release
container, so the lane stays live and nothing is switched. Moving the router, the coordinator
and the world to a fifth CPU (`FLY_SESSION_AUX_CPUS`) made it 1.5 to 2 ms slower. What would close
it is a cheaper round trip, not more CPUs: the router's own per-message work (strict JSON parsed
and re-encoded per hop, the state lock, about three task hops a direction), and sealing a reply's
media in the reply itself (one round trip fewer for Advance and for Commit).
- **`fly_frame_work_*`** on `/metrics` (both runtimes): the loop's compute time per frame without
its pacing sleep, mean, p99 and max over the last 3,600 frames. It agrees with the unpaced
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
hides.
### BUS-02 (port slice) — A cheaper bus transition
**2026-10-02: built** on `port/bus-02` off `port/bus-01`, awaiting review. Goal: make the
session-over-flybus transport cheap enough to carry the live fly (operator: run on the bus with
real sockets, because more consoles and more flies follow). The wire change is [bus-v1](bus-v1.md)
section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched.
- **Where a bus transition's time went** (a build box with the release CPU model and the release
cpuset's shape, router traffic counted per frame, cross-process timestamps per hop). About 35
commands a transition went through the router -- three calls and their replies, but also five
`artifact.seal`, six `artifact.allocate`, five `artifact.retain`, four `artifact.release`, six
`delivery.consumed` and three no-op `rpc.responder.release` -- and the router encoded every frame
twice and deep-copied every payload three or four times. The session's host CPU (the dispatcher's
CPU, which the router, the coordinator and the world share) was about 96% busy in every arm, so
bus cost was frame time almost one for one.
- **What changed.** Sealing sends (bus-v1 amendment: a reply seals the writers it attaches and
recycles their staging files as new writers, so a reply's media cost no seal or allocate round
trip); result attachments kept as delivered instead of retained; no responder release after an
admitted reply; the router encodes each frame once and forwards an admitted payload as bytes;
seal copies with `copy_file_range`; client location resolution cached; the session's writer pool
keyed by capacity (4 KiB buckets) so the variable-length feed status no longer misses it. About
14 commands a transition remain (three calls, three replies, consumes, cache releases).
- **Measured.** Before/after tables in the run report `claude-bus-02`. Unpaced, same rounds:
`bus/process` 17.1-17.2 ms a frame before, 14.9-15.8 after; paced at 1.0, the frame-work metric
17.4 before, 15.0 after (the lane 12.5, legacy 10.7). The bus still costs 2.5 to 3.5 ms a frame
more than the lane on that box, short of the 1.5 ms target, so the lane stays live. Also found:
BUS-01's numbers had the bus store on a disk-backed directory; on tmpfs (as the release, under
`/run`) its own binaries were 2.5 ms a frame faster.
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`) in `local`, `bus/thread` and `bus/process` (the FAFB parity suites, all arms).
- **Review notes (2026-10-02).** The review approved with notes; since the feed and the control
API already run over flybus in production, the router and SDK changes carry live traffic, so
every note was treated as live-path correctness. A recycled writer's staging file is zero-filled
when the router reissues it (about 10 us a 92,160-byte reply on tmpfs), so no artifact sealed from it -- by prefix or
whole -- carries the previous artifact's bytes (N3). A sealing reply is sent with the worker's
result cache held, so a duplicate replays the sealed artifacts rather than racing the reply
with an unsealed writer (N2). A refused sealing reply is answered as the handler's own seal
failure was before this slice (`BACKEND_FAILURE`, mutation applied), cached the same way, and
logged (N1). A failed staging rename leaves no file (N5). `recycle` without a sealing
attachment is refused even when false, a writer named by two attachments is refused, and the
SDK checks `writers` on every sealing send's reply (N4). The store-directory cache is per
connection (N6). Two test races are closed: the fly-edge stall test waits for the feed topic,
and SERVE-01's parity accepts a refused `/stimulate` drained one frame late (N7). The review's
adversarial lifecycle tests are in `flybus/tests/sealing_lifecycle.rs`.
### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
live behaviour. flysim gains trace switches that are off unless set, and the compatibility string
is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs,
the architecture, what is compared, the declared differences, the window and the verdict CUT-01
reads.
- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only:
- `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE`
path.
- `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB.
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions.
- `frame::ledgers_string` is now the one definition of the ledger string. The session task's
`ledgers_of` calls it.
- **`fly-legacy-session::shadow`** and the binary `fly-shadow`:
- `follow` reads the per-process files. It hands out complete lines only, and a file ends when
a newer one exists.
- `spool` copies every new store generation as it appears. It keeps a floor and a byte bound,
and never writes to a live store.
- `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the
live file byte for byte, after `host-fields` and `archive-order`.
- `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`,
`fly-shadow check`).
- The runner boots each segment from the live process's startup save (TASK-01's import). It
replays the admissions, runs the transition, and takes the live captures in the live order
around a deferred rollback. It compares with `trace::compare_line`, which is now shared with
`trace::compare`. It stops on the first divergence and writes `divergence.json` with 30
transitions of context.
- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to
flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the
commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the
unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship
`fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a
"Shadow run (SHADOW-01)" section.
- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real
`fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service
restarts. It runs on a build box, never on a host.
**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real
service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every
run. It totalled **4,090 brain seconds (68 brain minutes), 244,327 transitions, 13 processes and
zero divergence**:
| Run | Start | Brain s | Transitions | What it covered |
| --- | --- | --- | --- | --- |
| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary |
| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves |
| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward |
| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` |
| smoke | row 67, unthrottled | 122 | 7,305 | the first run |
| final | row 67, real time, the final binary, the lag guard on | 601 | 35,917 | the box was contended by other runs, so the live loop fell behind real time 5 times; each time the guard paused the shadow (667 s in all), and all 143 saves were still compared |
The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and
finished 12 minutes behind. Every save was still compared, from the spool.
`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart
under a shadow, then plants four differences on copies of that run's trace and spool. Each one
stops a fresh shadow with the right kind, field and step:
- a work-RAM digest;
- a ledger digest;
- a sugar removed, which diverges on the brain at that transition;
- a live save's `rankSinceMs`.
**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other
agents' runs made paired measurements vary by up to 2x.
- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The
live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a
frame, so the session runtime costs about what the legacy loop does (x1.05).
- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the
main trace unthrottled gave these means:
- in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms;
- thread mode with 2 threads: 18.5 ms;
- process mode with 2 threads: 18.5 ms.
Every replay was identical again: five more comparisons of 20,000 transitions each.
- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB.
- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best
paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has
1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is
160 MB per live hour.
The resource plan for the release container is in the SHADOW-01 run report and in
`units/flyshadow.service`:
- `SCHED_IDLE` on the page and encoder CPUs, never flysim's;
- 2 sweep threads;
- a back-off whenever the live `fly_lag_seconds` grows;
- a 3 GB memory ceiling;
- a ledger digest every 60 transitions.
To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace
is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later.
**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An
emulator imported from a state therefore drifts from a powered-on one in its channel accumulators.
The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores
through an import in both runtimes, so the two agree. A fresh start does not import, and the
shadow follows one by powering on as well.
**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast`
had three failures, each accounted for:
- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes
alone.
- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main.
- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load
22.
`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures,
typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is
648 B `8ce67b97...` in raw and macros mode, unchanged.
**Review fix round, 2026-09-29** (APPROVE-WITH-NOTES). The branch was rebased onto port/task-01's
fix round, `2fc9fd7`: an artifact-backed task ledger, the palette seed, queued saves and bounded
history. The shadow now bounds its coordinator's history per segment. The fixes:
- *R1.* The verdict hashes `flysim-session`, SERVE-01's service, with the other release binaries.
`check` defaults to `--binary flysim-session --current /opt/fly/current`. It requires the
verdict's release to be the directory the link resolves to, with every shadowed binary
unchanged there.
- *R2.* Every session-side failure is a divergence:
- a session that does not start;
- a restore-gate refusal (`tests/shadow.rs` now plants one);
- a capture with no agent;
- an unrecorded transition;
- an unbuildable trace line.
Skips carry a kind, and only the live side's own kinds allow a cutover.
- *N1.* The live trace needs the shadow's heartbeat to start and to keep going, and flysim keeps
the trace directory under 8 GiB. The runbook's claim is corrected.
- *N2.* `fly-shadow-run` records a baseline and runs `flyshadow-guard.timer`. The guard stops
everything and restarts flysim without the trace on 1 s of lag growth, or when the realtime
factor drops below min(0.97, baseline - 0.03). `lint.sh` drives the rule on six cases.
- *N3.* Both `pass` and the cutover require one live save compared per 600 brain seconds, with at
most 10 % unavailable. The cutover also requires a shadow at most 3,600 transitions behind.
**Cost re-measured on the rebased tip.** This was a 12-brain-minute rehearsal on the same box,
at real time, with a restart and the guard on. It had 43,104 transitions, 197 saves byte-identical
and zero divergence. The box was contended by other runs again; the guard paused the shadow for
911 s and it still passed. Unthrottled replays of its trace, all identical, gave these mean
milliseconds per frame:
| Mode | ms per frame (mean) |
| --- | --- |
| in-process, 2 threads | 15.1 |
| in-process, 3 threads | 13.3 |
| thread mode, 3 threads | 14.9 |
| process mode, 2 threads | 15.4 |
Earlier the same 2-thread and 3-thread in-process arms took 19.7 and 17.0 ms. With 3 threads the
shadow keeps real time with about 20 % to spare.
**Review round 2, 2026-09-30** (APPROVE-WITH-NOTES; R3 and G1 were required before `start`).
The branch was rebased onto port/task-01 `eaf588d`, and main v0.6.7 was merged in: row 68 and
adapter `pokered-unique8-v8`. The live shadow will therefore carry the v8 compatibility string.
The fixtures were already v8 on main.
- *R3.* `allows_cutover` floors the window at `REQUIRED_BRAIN_SECONDS` (10,800). A verdict run with
a shorter `--required-brain-seconds` passes as a rehearsal but never passes `check`. There is a
test case for this.
- *G1, the host guard.*
- `start` measures a 10-minute baseline of 60 samples before the shadow exists: the median RTF,
its spread as 1.4826 x MAD, and the lag growth rate over the most recent half.
- The guard trips only on a sustained degradation *against that baseline*: 3 checks in a row in
which the last 5 samples of the same process fall below it, in RTF or in lag rate, by more
than max(0.05, 4 x spread / sqrt 5).
- It stops itself when the shadow is not running. `check` refuses after a trip or with the
shadow down.
- Tested over two kinds of trace:
- *Synthetic*, shaped on the release container: a flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per
second and per sample, and real time with hiccups. There was no false trip in 800 3-hour
runs, and every one of 400 degradations tripped (to 0.55-0.75, and 0.66 to 0.58).
- *Recorded* from a real flysim, now fixtures: alone (at about 1.0, and at 0.4-1.0 under box
load) no trip; with a real idle shadow on other cpus no trip; with a real shadow on the fly's
own cpu (0.66 to 0.44-0.60) a trip at check 7.
- One recording had a load step inside its baseline, which widened a mean/sd baseline to a
0.25 margin. That is why the baseline is robust.
- *G1, the in-shadow back-off* (`LagJudge`). It pauses the shadow while the live lag grows faster
than the baseline rate plus the margin (re-read from `baseline.json`). It lifts itself for
10 minutes when a pause did not help, because then the shadow is not the cause. Tests show:
- a flat 0.66 fly is never paused;
- with no baseline, at most 1 minute in 11 is paused;
- a shadow that costs the fly time stays paused about half the time.
- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file
and every newer one, including while the shadow is backed off.
**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not
a timing, load or segment-handling bug.
- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test.
`cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx
target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so
it wrote no trace at all. The failure was reproduced by running such a test binary against its
own stale `flysim`.
- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`,
with the same target directory and profile, which does nothing when the binary is current.
This was proved on a target that another tree's `flysim` had populated.
- *What production could miss, and now cannot.* A live process that runs without a trace is now
a `coverage` divergence (above). That covers a process whose consumer check failed, and one
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
### SHADOW-02 — The shadow on a build box (port slice)
**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
back to 0.999-1.0 the moment the shadow was stopped.
- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
pins; no path, no secret).
- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
byte that was on disk a minute ago). The box's verdict is written back only when it is this
run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
box): the release directory and binary hashes must equal its own; a new run id resets the mirror
and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
finished is never written again (`done`, and the relay then deletes the container's copy);
reports liveness (heartbeat fresh, verdict this run's and running or passed).
- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
stop while following is a `coverage` divergence; coverage reads the journal before listing the
traces. `shadow::release` holds the release hashing the binary and `check` share.
- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
`flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
`Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
`flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
`02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
section has the set-up.
**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
and `resync`, the run reset, the env allowlist.
**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
build box standing in for the release container, the remote shadow on another behind a real sshd
with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
the trace is on, so the trace's cost counts against it.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
@ -867,244 +192,6 @@ for new epoch metadata; corrupt any participant and installation fails as a grou
reply doesn't advance durable metadata; failure during activation cannot resume half a world. reply doesn't advance durable metadata; failure during activation cannot resume half a world.
Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery. Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery.
### STATE-02 — The legacy composition's checkpoints in `FLYSIM01` (port slice)
**2026-09-29: built** on `port/state-02` off `port/integration` and awaiting review. The operator's
decision of 2026-09-23 makes `FLYSIM01` the format of record until RETIRE-01, and the session
runtime exports it on every durable save ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16).
This slice is that export, the import back, the store policy and the restore selection. It adds
no `FLYSESS1` production file. Nothing in `flysim`'s frame, checkpoint bytes or compatibility
string changes.
- **One store, two runtimes.** `flysim`'s `store.rs` and `journal.rs` move unchanged into the new
crate `flysim-store`, which `flysim` re-exports (`flysim::store`, `flysim::journal`) and
`fly-session` links. Both runtimes write through the one `store::encode` and commit through the
one `Store`, so they share the envelope bytes, the generations, `manifest.json`, the
`milestone-<N>` archives, `keep_generations` rotation and the restore order by construction.
- **Export** (`fly-session::legacy_checkpoint`). A `FLYSIM01` file is assembled from its owners'
halves: the agent's `FLYAGT01` capture payload (the seven agent chunks, the remainder already the
accumulator's), the world's `FLYENV01` payload (emulator, frame on screen, joypad, frame
counter, cartridge digest, and slot `best` as `ratchetGame`/`ratchetFrame`), the task's
`{reward, ratchet}` and the host's `{generation, wallMs, compatibility, speed, rankSinceMs,
lastEventId}`. `runtime_state` builds the legacy `RuntimeState` field for field as
`Sim::snapshot_state` does.
- **Import.** `split`/`halves` read a `FLYSIM01` file back into those halves. `agent_payload` is
the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01`
payload a replacement agent stages, using the same encoder the worker's own capture uses
(`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms,
warmupOffset = 2500}`. `learning.updates` is the file's `reinforcements`. A file from before
that member starts at `plasticity.updates` once (`legacy_reinforcements`, section 13
amendment). The checkpoint id is the file's generation (`flysim01-g<N>`). No template worker
is involved. This fixes the four points the AGENT-01 review raised against the prototype:
template dependence, borrowed ids, no compatibility gate (the gate is `restore_from_store`'s,
below), and the count falling back on every round trip. The payload also carries the file's
`framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input.
`LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive,
and the two differ on the row 65 yard survey checkpoint (found here; see the section 13
amendment). `world_payload` is ENV-01's `FLYENV01` from
the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`.
`legacy_parity` now seeds its workers through this import.
- **`reinforcements`, an optional `FLYSIM01` manifest member.** `LegacyFrame` now counts
reinforcement calls the way the agent worker does: one per commit while the rule is enabled,
zero sums included. `Sim` writes the count, and `LegacyFrame::restore` reads it (falling back
to `plasticity.updates`), so the count survives every round trip in either runtime. Readers
that predate it ignore it. The member changes no behaviour and not the compatibility string,
but it does change legacy checkpoint bytes: a file written from now on is the old layout plus
this member.
- **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site:
- one generation counter over both stores, starting above the highest either has allocated;
- a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also
restarts the hot interval;
- a durable save for a climb, archived as `milestone-<rank>` when the rank is above every rank
this process has archived (`best_archived_rank`, per process as in the legacy loop);
- rank tracking as in `track_rank`;
- encoding and fsyncs on a writer thread.
- **Restore selection.** `restore_from_store` walks `store::restore_order`: hot latest, hot
previous, durable latest, durable previous, then the archives by descending rank, each as its
generation and then as its `milestone-<N>` file. It checks the legacy gate: the cartridge, and
`flybrain_gb::compatibility::decide` with `FLY_ACCEPT_ADAPTERS`. It moves to the next candidate
on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no
candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit
as `Sim::restore_or_warm_up` does.
- **The agent worker** now refuses a conflicting stage (a restore already staged, or a token
already activated) before it builds a replacement network (AGENT-01 review).
- **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header
records the runtime, start frame, brain ms, restore origin, generation and compatibility. The
journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a
`continues` line. `journal::clear` removes the journal. `flysim` writes the header at boot, and
`flysim --reset-to-milestone` clears the journal after it has copied both stores aside.
`read_segments` cuts the journal into per-process segments. `read` still returns input lines
only.
**Boundary order the session host must keep** (section 16, and section 11 step 6). At `Ready(k+1)`
the order is:
1. `Environment.SaveSlot`, if one is due.
2. The milestone capture, if the rank climbed.
3. The rollback, if one was requested.
4. The durable capture after the rollback, then the hot and durable interval saves.
The capture itself uses `State.Capture` on the world and the agent at the same committed
boundary, plus the task's ledger, `{reward, ratchet, slotFilled}` (`TaskHalf::to_ledger`). Wiring
it into the coordinator and the boot-time restore path is left to the legacy composition's
coordinator (TASK-01); this slice ships the pieces and proves them on the workers.
**Proof** (flysim `tests/state_02.rs`, `tests/state_02_store.rs`; `fly-session`
`legacy_checkpoint` unit tests):
- *legacy -> session -> legacy on 18 real checkpoints* (every distinct rom-env checkpoint, which
includes the row 64, row 65 and row 67 ones). Each file is split and the world is restored
into the real environment worker and captured again. The agent goes through the imported
`FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is
byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once.
Against the files themselves, every export differs only in named fields. All 18 gain
`reinforcements`, because the files predate it. Twelve written by adapters v5 or v6 also
differ in `reward`, which the adapter's import migrates. One survey checkpoint also differs in
a joypad byte of its emulator state that its own `buttons` field does not match; both runtimes
apply `buttons` on restore. Before the counter was added, six of the 18 were byte-identical to
the file.
- *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a
checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy
loop and the session runtime then each run 600 frames from it. World: 1,800 values identical
to `FLY_TRACE` (frame, WRAM). Agent: 600 transitions identical (ticks, clock, exact remainder,
rates, spikes, decision). The session runtime's export at the last boundary is byte-identical
to the legacy loop's checkpoint of that boundary. That export also survives session -> legacy
-> session unchanged: a fresh legacy loop restores it and checkpoints the same bytes, and a
fresh world and agent import it and export the same bytes.
- *The same with `gameboy-legacy-fafb-v783-v1` in macros mode* from the row 67 checkpoint, with
sugar and a ratchet rollback (`FLY_STATE02_FAFB=1`). Four checkpoints were run for 1,800 frames
each: rows 58, 64 and 67, and the row 65 yard survey. Each run has 5,400 world values and 1,800
agent transitions identical to the trace, with 2 sugar and 1 rollback. Each export is
byte-identical to the legacy checkpoint and survives session -> legacy -> session.
- *The tools, both ways* (`tests/state_02_store.rs`, the real `infra/bin` scripts and the real
binary). `fly-loop-reset --list` and `--print-state-compatibility` read a store the session
runtime wrote. `fly-reset-to-milestone` promotes its rung with the recovery budget back and
clears the journal. The legacy order and the session runtime then choose the same candidate,
and the session runtime carries on above every generation and archives its next climb. The
other way round, the session runtime restores a store the legacy writer wrote and the tool
reset, and it would save it as the same bytes.
**Not in this slice, and why:**
- *The coordinator hook and the boot-time restore.* Both need the legacy composition's
bootstrap, which is TASK-01's. The restore order is Initialize-free: stage and activate the
world, have the task install `{reward, ratchet}` and observe O[k] for the first context
(`{boot, bound, location: null}`), then build the agent's payload with that context
(`agent_payload`) and stage and activate it.
- *The task's per-frame half in the proofs.* The executor and the task's evaluation are TASK-01's.
The proofs take the joypad masks from the trace and the task's end-of-run `{reward, ratchet}`
from the legacy loop.
- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive
holds the post-capture ratchet and slot. It is excluded from the shadow comparison.
### SERVE-01 — The session runtime as the live service (port slice)
**2026-09-29: built** on `port/serve-01` off `port/task-01` and awaiting review. It makes the
session runtime a drop-in for the live `flysim` service, so CUT-01 can switch the stream over
with one command and roll back with one. It changes no live behaviour: the legacy loop's frame,
feed, checkpoint bytes and compatibility string are unchanged, and nothing runs the new binary
until `fly-runtime session` is run on a container.
- **One service shell, two runtimes** (`flysim::serve`). `flysim::run` is split: `serve(config,
sim)` binds the feed (`:7400`, or the feed bus that `fly-edge` serves), the control API
(`:7401`) and the metrics listener (`:9101`), handles SIGTERM/SIGINT/SIGHUP, and runs `sim` on
the calling thread with the `Shared` state, the snapshot slot and the command queue. The
legacy loop is `serve(config, Sim::boot + Sim::run)`. The pieces of a feed header that come
from the fly (`feed_rates`, `feed_learning`, `feed_game`, `feed_milestone`, `feed_sugar`) and
the chat admission (`admit_chat`) move out of `Sim` into free functions both runtimes call.
The feed codec, the bus publisher, the router, `/status`, `/events`, `/metrics` and the
WebSocket framing are therefore one copy of the code whichever runtime is behind them.
- **The service host** (`fly-legacy-session::service`, binary `flysim-session`). It reads
`flysim`'s own `Config` (so `/etc/fly/fly.env`, `FLY_ACCEPT_ADAPTERS` through STATE-02's
`RestoreGate`, the macro mode, speed, threads, chat, the store paths) and keeps `Sim`'s order
call site for call site: boot by TASK-01's `boot_unsaved` (the legacy candidate order and gate),
the boot event, the chat sidecar, the journal's boot header (`runtime: fly-session`), the
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,
the same filter on the environment's `v / 255`); the spike bitset is the OR of the commits'
`telemetry.spikes` since the last publish, which equals the legacy window exactly; `buttons`
is the executor's mask (the checkpoint's after an import, 0 after a rollback, as
`LegacyFrame` has it); the game, milestone and macro fields are the task's own adapter,
ratchet and macro layer (`PokeredTask::inspect`, `take_feed`). The numbers from inside the
network that no session message carries -- the plasticity statistics (`learning.changed`,
`learning.synapses`), the decoder's baselines and scores for `/status`, and the rates and pulse
at the boundary -- come from one declared extension of the legacy agent,
`Legacy.FeedStatus` (capability `legacy-feed-status-v1`): read-only, answered at a committed
`Ready(k)`, once per published snapshot, never in a trace. `Coordinator::read_agent_extension`
calls it without fencing the epoch; `Coordinator::media_bytes` reads the committed view and
audio chunk.
- **Sugar.** flysim's `RateLimiter` and clamp, over the pulse the network holds: the last commit's
`stimulusRemainingMs`, raised by each sugar admitted since (`network.stimulate` is a maximum),
so a second request in one drain is refused with the legacy `retryAfterMs`. The admission lands
in the next Prepare, which is the frame the legacy drain applies it before, and the journal
stamps it with that frame.
- **Long-running hygiene.** The coordinator kept every transition's trace, every phase change,
an audit line per step and every timing sample: about 120 KB/s of heap on the live fly
(the first soak's RSS). `Coordinator::trim_records` bounds them at each boundary; the timings
are logged once a minute as a `session profile` line and cleared.
- **Declared differences** (the rest is byte-equal, below): `POST /reward` is always 403
(`control.allow_reward` is forced off; the operator pulse has no session-framework
counterpart, `legacy-gameboy-v1` section 15); a fresh start publishes no audio for its setup
frame (the environment discards O[0]'s); `FLY_TRACE` and `FLY_PROFILE_SECONDS` are the legacy
loop's tools; only the Pokémon composition exists (another `FLY_GAME` is refused at start); the
toy connectome cannot run macros mode (AGENT-01 refuses a macro channel the dataset does not
track, and the toy tracks none).
- **Infra.** `flysim.service` stays the fly's one unit. `infra/bin/fly-runtime session|legacy|status`
switches the binary it runs with one drop-in (`flysim.service.d/10-runtime.conf`), so every
consumer that names `flysim.service` -- `fly.target`, `flyedge.service`'s `Requires=`, the
watchdog, `fly-loop-recover`'s sudoers-granted restart, `fly-loop-reset`,
`fly-reset-to-milestone`, the unstick rule -- works unchanged and the choice survives reboots and
deploys. It refuses a release without `flysim-session` or with a different compatibility
string, waits for `/healthz` and an advancing frame, and falls back to legacy by itself if the
session runtime does not come up. `flysim-session.service` is the standalone unit (flysim's
limits and cpuset, `Conflicts=flysim.service`, no `[Install]`) for rehearsals.
`build-flysim.sh`/`package-release.sh` ship `flysim-session` and `fly-session`; `05-deploy.sh`
installs `fly-runtime`, writes the standalone unit's cpuset drop-in and refuses a release
without `flysim-session` while the drop-in is present; tmpfiles creates `/run/fly/session`.
The runbook's "Switch the runtime" is the operator's page.
**Proof** (`fly-legacy-session/tests/service_parity.rs`, `journal_replay.rs`, rom-env; the SERVE-01
run report has the numbers). Both runtimes are started from the same seeded store behind
flysim's own control router and driven by one script of control requests, each landing before
the same frame: every running feed header is equal field by field (wall-clock fields excepted)
and every frame, audio and spike attachment byte for byte; every control response is equal
(`/stimulate` 202/429 with the same `retryAfterMs`, `/reward` 403, `/chat` 202/422,
`/checkpoint` the same generation, `/pause`, `/resume`, `/events`, 404s); the event log, the
journal and the final checkpoint are equal. Toy connectome raw mode, and the real connectome in
macros mode through a ratchet rollback, each in-process and as processes. A soak of both
runtimes side by side with the stage's decoder and the bridge's `HttpSimClient`
(`tools/runtime-soak.ts`), the hot/durable cadence sampled from the stores, and a `SIGKILL`
whose journal is replayed from the seed in the legacy loop onto the killed process's last hot
checkpoint.
Results (2026-09-29, the build boxes; the run report has the logs):
| Proof | Result |
| --- | --- |
| Toy raw, 120 frames, 19 scripted requests incl. two sugars in one drain | identical, in-process and process |
| Real connectome, macros, `rollback` checkpoint (ratchet rollback on frame 1), 120 frames | identical, both modes, before and after the TASK-01 fixes |
| Real connectome, macros, engage checkpoint (ledger thinned), 2400 frames, 46 macro and 2 reward events | identical, both modes |
| Real connectome, macros, row 64 (a 42 KB adapter ledger, TASK-01 B1), 1200 frames | identical, both modes |
| Soak, 35 min, both runtimes from the row 67 checkpoint, production configuration | 0 decode or schema errors, no 2 s stall, `/healthz` 100 %, event ids gapless, hot every 5 s and durable at 300 s on both (same intervals) |
| Soak, 36 min, the session killed -9 at +6 min | back in about 1 s from the hot checkpoint 3.5 s old, 1 `/healthz` 503, the feed client reconnected (533 ms gap), two journal segments |
| The killed process's journal, 17 sugars, replayed from the seed in the legacy loop | 18,838 frames onto its last hot checkpoint: agent, emulator, frame, adapter, ratchet equal |
| Feed over the bus (`FLY_FEED_VIA=bus`) with `fly-edge` | 3,050 snapshots through the edge, 0 errors |
Open for CUT-01: **speed.** Unpaced on a shared box the session ran 54-61 fps where the legacy
loop ran 68-118 (per frame p50: `Agent.Prepare` 7.8 ms, `Environment.Advance` 2.6,
`Agent.Commit` 1.6, publication 0.4; `Legacy.FeedStatus` 0.9 ms at 30 Hz). The live container
must be measured (SHADOW-01's cost run) before cutover. **Memory.** After `trim_records` the
session's RSS still grows about 5-8 MB an hour, tied to the saves (an unpaced run without saves
is flat); at `MemoryMax=4G` that is weeks, and a restart clears it, but it is not explained yet.
**Number form.** A checkpoint the session writes carries the adapter ledger's integral numbers
as `7580031` where the legacy loop writes `7580031.0` (the ledger crossed canonical JSON); equal
values, and both runtimes read both.
### PUBLISH-01 — Committed snapshots and observer isolation ### PUBLISH-01 — Committed snapshots and observer isolation
**Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to

View file

@ -17,37 +17,6 @@ ownership. This document owns Scope, model-related scalar types, worker capabili
domain operation deduplication and errors. Domain request identity is independent of the bus domain operation deduplication and errors. Domain request identity is independent of the bus
callId: a safe retry has a new transport callId but the original domain requestId/body. callId: a safe retry has a new transport callId but the original domain requestId/body.
**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker
RPC is a Flybus call", for participants that share the coordinator's process. The release
container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a
frame above the brain (three round trips through the router and four or five sealed store files
a frame), against 0.7 ms for everything the legacy loop does outside its ticks.
- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator
directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods --
step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to
that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks.
- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through
the same shell code as a bus request: section 5's classification, canonical body digest,
result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the
endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker,
incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and
resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped
before answering is a lost connection (mutation unknown).
- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1
section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef`
(`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3
holds as written: every `ArtifactRef` in a payload is backed by a live handle the message
carries. An in-memory artifact never crosses a router: a bus call or a publication that needs
one carries a sealed copy (the coordinator makes it), and the snapshot names the copy.
A sealed handle a handler returns over the lane reaches the caller in memory under the same
reference.
- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached
over the bus, so process mode keeps exercising routing and ownership, and the bus path stays
the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic
transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy
parity runs in-process (lane) and process (bus).
## 2. Common domain types ## 2. Common domain types
```ts ```ts
@ -125,14 +94,10 @@ interface HelloResult {
workerId: Id; incarnationId: Id; role: "agent" | "environment" | "coordinator"; workerId: Id; incarnationId: Id; role: "agent" | "environment" | "coordinator";
buildDigest: Digest; contractDigest: Digest; buildDigest: Digest; contractDigest: Digest;
capabilities: Id[]; capabilities: Id[];
limits: { maxAgents: number; maxPorts: number; workerThreads: number }; limits: { maxAgents: number; maxPorts: number };
} }
``` ```
`limits.workerThreads` is the thread allocation the worker's launcher started it within; it
is an integer >=1 and its rule belongs to [worker interfaces](workers-v1.md) section 2, whose
2026-09-22 amendment added it.
The bus supplies caller identity; do not accept a forged caller in params. Bind a worker's The bus supplies caller identity; do not accept a forged caller in params. Bind a worker's
session authority to the expected coordinator identity/incarnation during negotiation and session authority to the expected coordinator identity/incarnation during negotiation and
initialization. Wrong worker/role, no common major or missing required capability refuses initialization. Wrong worker/role, no common major or missing required capability refuses
@ -189,11 +154,6 @@ Lifecycle/capture replies are retained until Worker.Acknowledge:
not another consumer's bus delivery. Already released/unknown IDs are ignored. Serial not another consumer's bus delivery. Already released/unknown IDs are ignored. Serial
watermarks reject reuse after acknowledgment without an unbounded tombstone list. watermarks reject reuse after acknowledgment without an unbounded tombstone list.
**Amendment, 2026-09-22 (CONTRACT-01):** those ids are domain request ids in the `req-<U64>`
serial form, not arbitrary `Id`s. The serial watermark rule in the sentence above cannot reject
reuse after acknowledgment unless the acknowledged id carries its serial, so a bus callId or a
bare `Id` is refused there.
Bound unacknowledged lifecycle replies at 16, then BUSY before application. Status and Bound unacknowledged lifecycle replies at 16, then BUSY before application. Status and
Acknowledge use a cache of their last 16 replies; current/previous step records have their Acknowledge use a cache of their last 16 replies; current/previous step records have their
separate finite retention. Caches containing big artifacts consume bus owner/byte budgets; separate finite retention. Caches containing big artifacts consume bus owner/byte budgets;

File diff suppressed because it is too large Load diff

View file

@ -42,20 +42,6 @@ Example addresses (chosen by composition, not recognized by router code):
| `app.pokemon.cues` | Pub/sub: application narrative/presentation events under declared delivery policy | | `app.pokemon.cues` | Pub/sub: application narrative/presentation events under declared delivery policy |
| `app.pokemon` | RPC: application queries/admission, e.g. restore UI state or request a supported effect | | `app.pokemon` | RPC: application queries/admission, e.g. restore UI state or request a supported effect |
**Amendment, 2026-09-22 (PUBLISH-01).** The repair path above needs exact methods, and
"exact methods require session API schemas" left the row unbuildable. The session registers
one **read-only** service, `session.<id>.query`, with exactly two methods, both ordinary
[session RPCs](ipc-v1.md) answering from what the session already published:
`Session.GetDescriptor` takes an optional `{revision: U64}` and returns that `SessionDescriptor`
or, with no revision, the newest; `Session.GetSnapshot` takes no parameters and returns the
latest `CommittedSnapshot`. A revision the session never published is `IDENTITY_MISMATCH`, not
an empty answer. Nothing on this service mutates, selects a participant or reaches a worker, so
it is not the controller API section 7 rules out; adding a third method that did would be.
These two names are **internal and provisional**: they are what the internal boundary needs in
order to be buildable now, and the later public v2 step is free to rename them, supersede them
or expose a different repair surface entirely. Nothing about them is browser-facing, and the
public step does not inherit them by default merely because they landed first.
Descriptor revisions and scope link observations to schemas. Cross-topic ordering is not Descriptor revisions and scope link observations to schemas. Cross-topic ordering is not
guaranteed; a subscriber receiving an unknown descriptor revision must fetch it through the guaranteed; a subscriber receiving an unknown descriptor revision must fetch it through the
application/session query contract or buffer a bounded number of snapshots, not infer shape. application/session query contract or buffer a bounded number of snapshots, not infer shape.
@ -91,16 +77,6 @@ interface CommittedSnapshot {
} }
``` ```
**Amendment, 2026-09-22 (PUBLISH-01).** "Null at initial boundary 0" is the rule for a
boundary this epoch *produced*. A group restore ([state/media](state-media-v1.md) section 5)
re-establishes a committed boundary `k > 0` that this epoch did not run a transition into, and
the abandoned epoch's decisions are not this session's to republish under a new epoch. So the
rule is: `selectedDecision` and `appliedControls` are null at boundary 0 and at a boundary
*installed* by a restore, present otherwise, and always **together** and for **every agent or
none**. A snapshot where one fly carries an action and another does not would be two different
boundaries in one value, and is refused. Without this, the section 6 requirement to publish the
recovery could not be met at all: the restored boundary's snapshot would be unrepresentable.
Publish only after all agent commits establish Ready(k). Decisions/controls describe the Publish only after all agent commits establish Ready(k). Decisions/controls describe the
transition ending at that boundary, null at initial boundary 0. Health updates are separate transition ending at that boundary, null at initial boundary 0. Health updates are separate
and never claim an uncommitted future boundary. Every transient media reference is a declared and never claim an uncommitted future boundary. Every transient media reference is a declared

View file

@ -1,101 +0,0 @@
# Seed derivation v1
Status: **draft 1**, 2026-09-22. Specified by CONTRACT-01 of the
[implementation guide](implementation.md), required by
[worker interfaces](workers-v1.md) section 2 before the real-agent slice. Reference
implementations: `services/flysim/crates/fly-session-types/src/seed.rs` and
`packages/session-types/src/seed.ts`; test vectors:
`services/flysim/crates/fly-session-types/fixtures/seed-vectors.json`.
## 1. What this is for
`Agent.Initialize` takes `seed`, a signed 32-bit integer, matching the current RNG input.
Workers-v1 section 2 requires that the coordinator derive independent per-agent seeds from
**its recorded master seed and stable agent IDs** under a versioned algorithm, and that the
algorithm be specified and tested before the real agent slice. This is that algorithm.
It is a reproducibility rule, not a secret: a run manifest records the master seed in the
clear, and anyone with the manifest can recompute every agent's seed. It is not a key
derivation function and must not be used as one.
`seed-derivation-v1` is part of composition identity. Changing any byte of it requires a new
identifier (`seed-derivation-v2`), because two runs that agree on every other identity but
disagree here are not the same experiment.
## 2. Inputs
| Input | Type | Source |
| --- | --- | --- |
| `masterSeed` | `U64` decimal string | Recorded once per run by the application/supervisor |
| `agentId` | `Id` | The configured agent identity, stable across restarts and epochs |
Both are the ipc-v1 section 2 scalars. An `agentId` that is not an `Id` is an error, not
something to normalize. The master seed is the whole 64-bit range: a 32-bit master seed would
be no wider than the seed it derives.
## 3. Derivation
```text
material = "flybrain/seed-derivation-v1" LF masterSeed LF agentId LF
digest = SHA-256(material)
lanes = digest read as eight big-endian uint32 values, in order
seed = the first nonzero lane, reinterpreted as a two's-complement int32
```
`LF` is one `0x0a` byte. `masterSeed` is its canonical decimal form: `"0"`, or no leading
zero. The prefix is a domain separator, so a digest from this algorithm can never collide with
one taken over some other pair of strings.
Zero lanes are skipped because the pinned kernel's RNG is an xorshift generator, whose state
must not be zero: a derivation that could hand out `0` would silently produce a stalled
generator. If every one of the eight lanes were zero, the material is rehashed with a counter
suffix (`material || "1" LF`, then `"2" LF`, then `"3" LF`) and the search repeats; no input
has ever needed it, and four rounds exhausted is an error rather than a fallback seed.
The seed is the *negative* number when the lane's high bit is set. That is deliberate: the
existing RNG input is a signed 32-bit integer, and half the range is negative.
## 4. Properties
- **Deterministic.** The seed is a function of the two recorded inputs and nothing else: not
of wall time, agent order, port assignment, worker process or thread count.
- **Independent per agent.** Distinct agent IDs give unrelated seeds; there is no arithmetic
relationship between `fly-a` and `fly-b` for a caller to exploit or accidentally rely on.
- **Stable across recovery.** Restore, episode reset and a new epoch do not re-derive a
different seed for the same agent ID under the same master seed. The seed is persisted as run
configuration and state, and the capture compatibility digest covers the resolved seed
(workers-v1 section 2), so a checkpoint cannot be installed into a differently seeded
instance.
- **Equal IDs give equal seeds.** That is the only way to get identical seeds, and workers-v1
allows identical seeds only when an experiment declares them. A composition therefore
refuses a repeated agent ID rather than quietly sharing a seed between two agents.
Non-properties, stated so nobody assumes them: this is not uniform over the int32 range beyond
what SHA-256 gives, it is not a stream (one seed per agent per run, not per step), and it says
nothing about how a model consumes its seed.
## 5. Test vectors
`fixtures/seed-vectors.json` carries the full table: five master seeds (`0`, `1`, `42`, `2^63`
and the `U64` maximum) across four agent IDs, each with the exact material string, its SHA-256
and the derived seed, plus one four-agent composition and the inputs that must be refused.
Both implementations reproduce every row, and each records the material as well as the seed so
a third implementation can find where it diverges.
The first two rows:
| masterSeed | agentId | material | seed |
| --- | --- | --- | ---: |
| `0` | `fly-a` | `flybrain/seed-derivation-v1\n0\nfly-a\n` | 1828176714 |
| `0` | `fly-b` | `flybrain/seed-derivation-v1\n0\nfly-b\n` | 1218785088 |
Refused: an agent ID that is not an `Id` (uppercase, empty, over 64 characters), a master seed
that is not a canonical `U64`, and a composition with a repeated agent ID.
## 6. Out of scope
Choosing the master seed, recording it in the run manifest, and the hand-selected explicit
seeds that workers-v1 allows for the first synthetic composition. This document defines only
the derivation. A profile that needs several independent streams inside one agent derives them
from the agent's own seed under its own documented rule; that is a profile concern, not a
session one.

View file

@ -65,38 +65,11 @@ the sample position relative to the episode's configured audio origin, with inte
firstSample/sampleRate. Crash restore preserves sample position under a new epoch; first firstSample/sampleRate. Crash restore preserves sample position under a new epoch; first
chunk marks discontinuity. Within an epoch, chunks cannot overlap or go backwards. chunk marks discontinuity. Within an epoch, chunks cannot overlap or go backwards.
**Amendment, 2026-09-22 (MEDIA-01).** Two readings of the paragraphs above, made explicit
because they are now enforced:
- The bootstrap window is exactly the boundaries where `max(0, boundary - observationDelaySteps)`
is zero, that is `boundary <= observationDelaySteps`. Inside it the repeated `O[0]` is the
**same artifact**, not a fresh render of the same scene; outside it the producing boundary
advances one per step, and a frame from any other boundary -- older or newer -- is a step
failure. A producer therefore keeps a queue of `observationDelaySteps + 1` frames and nothing
more, so there is no older frame available to substitute.
- Within an epoch, `discontinuity` marks a range the stream actually skipped. The first chunk
after a restore marks it, and a later chunk may mark it when it starts past where the previous
chunk ended; a chunk that continues the previous one exactly is continuous by construction and
its flag is refused. Without that reading the restore rule is advisory, because a stream could
set the flag on every chunk and satisfy it by accident. The requirement is one-directional: a
fresh epoch's first chunk **may** mark a discontinuity, because section 6's recovery
establishes a fresh timeline and publishes one.
The environment provides **native game output**. Sensor transformations belong to the agent The environment provides **native game output**. Sensor transformations belong to the agent
profile. Resizing for viewers, overlays, composition, audio mixing/resampling, encoding, profile. Resizing for viewers, overlays, composition, audio mixing/resampling, encoding,
browser delivery and streaming belong to the application/presentation layer. No bus or browser delivery and streaming belong to the application/presentation layer. No bus or
generic session configuration assumes a 1080p show or Twitch output. generic session configuration assumes a 1080p show or Twitch output.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** For the Game Boy
environment of the legacy composition ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 9):
the environment converts binjgb's unsigned 8-bit interleaved stereo to the declared
`f32le-interleaved` with binjgb's host rule `sample / 255` (unipolar, silence at 0.0), and does
not filter. The DC blocker the running service applies before publishing (pole 0.995, per
channel) moves to the **edge**, as presentation: its state is the edge's, never checkpointed,
reset only when the edge restarts, and never seen by an agent. The observations a slot restore
returns carry no audio chunk, like the ones `ActivateRestore` returns (section 5 amendment of
2026-09-22), and the next chunk marks the discontinuity.
640×480 RGBA at 60 fps produces 73.728 MB/s of raw image data. Artifact fan-out references 640×480 RGBA at 60 fps produces 73.728 MB/s of raw image data. Artifact fan-out references
one stored object; reads and any staging/seal copy still consume memory bandwidth. This is one stored object; reads and any staging/seal copy still consume memory bandwidth. This is
reasonable to measure before introducing codecs or pooled GPU buffers. Native dimensions reasonable to measure before introducing codecs or pooled GPU buffers. Native dimensions
@ -127,28 +100,6 @@ If it violates configured resource policy, disconnect/restart that observer inst
live data or silently skipping simulation input. Global store exhaustion is an explicit fault live data or silently skipping simulation input. Global store exhaustion is an explicit fault
or pause condition; the router cannot guess that a particular live object is disposable. or pause condition; the router cannot guess that a particular live object is disposable.
**Amendment, 2026-09-23 (RT-01a).** An artifact-backed inspection -- the legacy composition's
64-KiB memory image per boundary -- is required coordinator input, not spectator data: the
coordinator retains `O[k]`'s image through the executor's use in the next transition's Phase B
and the task's old/new evaluation in its Phase C, and drops it after. It is never coalesced and
never published to observers by the session; about 3.9 MB/s at the Game Boy's cadence, budgeted
with the cached step observations above.
**Amendment, 2026-09-22 (PUBLISH-01).** "Disconnect/restart that observer" names an action
no participant can take under [Flybus v1](bus-v1.md). Section 5 there makes publish admission
all or nothing -- "for a bounded subscriber overflow, reject the **whole** publish; no partial
fan-out or retained-latest update" -- and the router exposes no per-subscriber eviction, so a
session meeting a full bounded queue cannot drop that one subscriber and deliver to the rest.
The realisable reading, which the session now implements, is three-part: observation topics
are published `latest`, and a latest subscriber can never refuse a publication (it loses its
own queued value and is told how many by `replaced`); a bounded subscriber's refusal, which
`bus-v1` section 6 explicitly permits, is a named and counted publication outcome that takes
no world step, stalls nothing and fences no epoch, and the exact value stays recoverable
through the [publishing-v1](publishing-v1.md) section 2 query path; and disconnecting the
offender is an operator action against the topic the ledger names, not something the session
performs. A per-subscriber drop would need a router operation Flybus v1 does not have, and
inventing one here would be a transport change written into the wrong document.
No coordinator tracks per-reader socket acknowledgments or calls a producer's reclaim method. No coordinator tracks per-reader socket acknowledgments or calls a producer's reclaim method.
The SDK and bus perform that bookkeeping. File-backed immutable mappings are safe after The SDK and bus perform that bookkeeping. File-backed immutable mappings are safe after
unlink; physical pages disappear when all OS mappings close. Pooled reuse is deferred until unlink; physical pages disappear when all OS mappings close. Pooled reuse is deferred until
@ -169,19 +120,6 @@ The manifest records:
or reproducible reconstruction inputs, admission state and event watermarks. or reproducible reconstruction inputs, admission state and event watermarks.
- Payload names, lengths and hashes, including external-helper state required for exact resume. - Payload names, lengths and hashes, including external-helper state required for exact resume.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** A composition may declare
**restore semantics** other than exact. The legacy composition declares
`restore: legacy-transient-reset` ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 14): its
executor's ledgers and running macro, the agent's readout transient (held channel, blocked
window, last location) and the task's transient observations are **not** captured and start
cleared on every restore, exactly as the running service does on a restart. The
[modular analysis](../malecns-modular-sessions.md) section 5.4 already asked for this to be
labelled "legacy continuation semantics, not exact session replay"; the declaration is that
label, in the composition digest. The consequence is explicit: for this composition the
uninterrupted-versus-resumed trace equality of STATE-01 does not apply; its resume tests
compare against the legacy restore outcome. The operator's unstick procedure depends on the
reset. An environment's slots (`gameboy-slots-v1`) **are** world state and are captured.
Use a new envelope version; specify exact byte layout before production files. The historical Use a new envelope version; specify exact byte layout before production files. The historical
letter-only chunk-name constraint is not silently widened, and FLYSIM01 remains separately letter-only chunk-name constraint is not silently widened, and FLYSIM01 remains separately
readable. Persist payload **bytes and durable content identity**, not transient bus storeId, readable. Persist payload **bytes and durable content identity**, not transient bus storeId,
@ -235,40 +173,11 @@ restored time. It cannot advance gameplay to manufacture it. Capture/reconstruct
covers render/inspection state and any pending sensor pipeline. Agent state agrees with it; covers render/inspection state and any pending sensor pipeline. Agent state agrees with it;
do not replay reward or recalibrate merely to fill missing cached data. do not replay reward or recalibrate merely to fill missing cached data.
**Amendment, 2026-09-22 (STATE-01).** Three readings of this section, made explicit because
they are now enforced:
- `compatibilityDigest` on `CaptureResult` and `StageRestoreParams` is the **participant's**
capture compatibility digest of [worker interfaces](workers-v1.md) section 2 -- profile,
resolved seed, numerical model version and effective instance configuration for an agent;
backend, content, patch, controller and parser identity for an environment. It is not the
manifest's `compatibility` block of section 4, which is the composition's and which the
coordinator compares before anything is asked to stage. Both exist because they answer
different questions, and a restore that passed the second could still be handing an agent
another agent's brain.
- The observation `ActivateRestore` returns ran no transition, so it carries **no audio
chunk**, and one in it is refused. Section 2's chunk is the audio of an interval and this
observation covers none; MEDIA-01 implemented that rule as "boundary 0 carries no chunk",
which is true of the only such observation that slice could produce and false of this one.
The rule is about provenance, not about the boundary number.
- A participant that staged into a group install the coordinator then abandoned must be
**replaced** before another restore, exactly as one that activated must. It is holding a
validated replacement state that nothing installed, and [session RPC](ipc-v1.md) section 6
already refuses to silently reattach such a participant to an active epoch. Without this the
group's second attempt meets its own leftovers and calls them a conflict.
If emulator validation requires mutation, stage a stopped replacement emulator. If that cannot If emulator validation requires mutation, stage a stopped replacement emulator. If that cannot
provide externally atomic resume, advertise episode-restart, not exact-checkpoint. After all provide externally atomic resume, advertise episode-restart, not exact-checkpoint. After all
activation acknowledgments, install the coordinator's staged task/executor/admission state activation acknowledgments, install the coordinator's staged task/executor/admission state
and establish Paused(new epoch,k). Failure during activation never permits half a group to run. and establish Paused(new epoch,k). Failure during activation never permits half a group to run.
**Amendment, 2026-09-23 (operator decision of 2026-09-23).** `FLYSIM01` remains the **format of
record** for the legacy composition until RETIRE-01: every durable save exports a `FLYSIM01`
envelope the current service reads under its unchanged compatibility string, and restore
selects from those files through the legacy compatibility decision. A `FLYSESS1` checkpoint
may be written beside it; it is not a restore candidate for this composition until RETIRE-01
says so ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16).
## 6. Durable commit, router failure and recovery ## 6. Durable commit, router failure and recovery
Write payload/envelope temporary generation, fsync, rename, fsync directory, then atomically Write payload/envelope temporary generation, fsync, rename, fsync directory, then atomically
@ -301,14 +210,3 @@ state and retained/fresh brain components are explicit. Gain retention, eligibil
clearing, calibration and first sensory input are part of the policy, tested independently. clearing, calibration and first sensory input are part of the policy, tested independently.
Legacy Pokémon ratchet behavior remains in the legacy composition. Shared competitive worlds Legacy Pokémon ratchet behavior remains in the legacy composition. Shared competitive worlds
never restore one player's environment independently of the other players. never restore one player's environment independently of the other players.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** The sentence above kept the
ratchet outside the framework. The operator decided on a full port instead, so the ratchet's
game-only rollback is now a declared episode policy of the legacy composition,
`legacy-ratchet-rollback-v1`, with the environment capability `gameboy-slots-v1`
([workers-v1](workers-v1.md) section 7, [step-v1](step-v1.md) section 6 amendment,
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 11). It is a rollback, not a reset: a new
epoch at the same boundary, the episode and the brain continuing, the environment restoring a
slot, agents clearing holds and eligibility and installing the slot frame without a tick, the
executor cancelling then observing. What the original sentence protected still holds: the
policy is single-agent and a shared competitive world must not declare it.

View file

@ -5,21 +5,6 @@ arrows below are RPCs through the same [Flybus router](bus-v1.md); the router it
implements the barrier. Read [architecture](README.md) and [session RPC](ipc-v1.md) first. Method payloads are in implements the barrier. Read [architecture](README.md) and [session RPC](ipc-v1.md) first. Method payloads are in
[worker interfaces](workers-v1.md). [worker interfaces](workers-v1.md).
**Amendment, 2026-09-23 (operator decision of 2026-09-23).** The live Game Boy fly is ported
onto this protocol as the legacy composition of [legacy-gameboy-v1](legacy-gameboy-v1.md),
scheduled by `lockstep-v1` with one agent, one port and one world; it is no longer a separate
ordering. Its frame order is this document's transaction order (legacy-gameboy-v1 section 4
maps it step by step), so the amendments below add capabilities to the protocol and change
none of its ordering rules.
**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of
[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router:
the arrows below are then direct calls into the same worker shell, carrying the same requests and
replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that
overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the
coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the
world, the task and the commits run, and the snapshot is published before the next Prepare.
## 1. Committed boundary ## 1. Committed boundary
At `Ready(epoch, k)`: At `Ready(epoch, k)`:
@ -45,7 +30,6 @@ Starting → Ready(k) → Preparing(k) → Applying(k) → Observing(k+1)
Ready(k) → Paused(k) → Ready(k) Ready(k) → Paused(k) → Ready(k)
Ready(k) / Paused(k) → Capturing(k) → same boundary Ready(k) / Paused(k) → Capturing(k) → same boundary
pause requested mid-step → Committing(k) → Ready(k+1) → Paused(k+1)
any unresolved partial failure → Failed → Restoring(new epoch) → Paused(k) any unresolved partial failure → Failed → Restoring(new epoch) → Paused(k)
terminal episode → Paused(k) → Resetting(new epoch) → Ready(0) terminal episode → Paused(k) → Resetting(new epoch) → Ready(0)
``` ```
@ -54,38 +38,6 @@ terminal episode → Paused(k) → Resetting(new epoch) → Ready(0)
transition carry `scope.step=k`; result fields identify `nextStep=k+1` where applicable. transition carry `scope.step=k`; result fields identify `nextStep=k+1` where applicable.
Do not send Agent.Commit with step `k+1` merely because the observation is newer. Do not send Agent.Commit with step `k+1` merely because the observation is newer.
**Amendment, 2026-09-22.** The mid-step pause line above adds no new edge: a pause requested
during a transition is served by the ordinary `Committing(k) → Ready(k+1)` edge followed by
`Ready(k+1) → Paused(k+1)`. It is written into the machine because section 6 requires the
transition to finish first, so the only boundary such a pause can land on is the one the
transition just committed.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** One edge is added, for a
composition that declares a rollback policy:
```text
Ready(e, k) → RollingBack(e', k) → Ready(e', k)
```
It is taken only when the transition that reached `k` returned `episodeRequest.kind =
"rollback"`, after that transition fully committed and before the next Prepare (section 6
amendment). The boundary number does not change; the epoch does. A pause requested during it
lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
not allowed in `RollingBack`.
**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session`
`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and
the boundary stays the same. One edge is added for a checkpoint of another format installed as a
session's start (the legacy composition's FLYSIM01 import):
```text
Ready(0), no transition taken -> Restoring(k) -> Paused(k)
```
The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only
a session that has not advanced may take the edge; the coordinator enforces this, because the phase
alone cannot tell a fresh `Ready(0)` from a reset one.
## 3. Transaction sequence ## 3. Transaction sequence
### Phase A: prepare all agents concurrently ### Phase A: prepare all agents concurrently
@ -117,12 +69,6 @@ After every PreparedDecision arrives:
2. Run each task-local action executor once, in sorted agent-ID order, against coherent current 2. Run each task-local action executor once, in sorted agent-ID order, against coherent current
game state, task progress/objectives and clock from this boundary. game state, task progress/objectives and clock from this boundary.
Direct-control profiles use an identity executor. Macro profiles are explicit extensions. Direct-control profiles use an identity executor. Macro profiles are explicit extensions.
*Amendment, 2026-09-23 (RT-01a):* the legacy composition's extension is
`pokered-macros-v1`. "Coherent current game state" is the boundary's 64-KiB memory image
from `O[k].inspection` plus the ROM `AssetRef` -- never a live emulator read -- and "clock"
is the agent's brain time after its Prepare ([legacy-gameboy-v1](legacy-gameboy-v1.md)
sections 8 and 10).
3. Assemble all configured port controls in descriptor port order; reject duplicates/missing 3. Assemble all configured port controls in descriptor port order; reject duplicates/missing
ports. Uncontrolled ports are configured neutral before the epoch, not supplied ad hoc. ports. Uncontrolled ports are configured neutral before the epoch, not supplied ad hoc.
4. Send exactly one `Environment.Advance(scope=k, batchId, controls)`. 4. Send exactly one `Environment.Advance(scope=k, batchId, controls)`.
@ -132,12 +78,6 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai
the next request. Transport/control scaffolding may have a measured fixed latency; it must the next request. Transport/control scaffolding may have a measured fixed latency; it must
be declared in its descriptor and conformance tests. be declared in its descriptor and conformance tests.
*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is
`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the
legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches
the executor and the task as bytes: the coordinator holds each attachment the task declares
(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated.
### Phase C: observe and evaluate the task ### Phase C: observe and evaluate the task
The coordinator receives the environment result and verifies batch identity, boundary, The coordinator receives the environment result and verifies batch identity, boundary,
@ -149,17 +89,6 @@ controls. It returns scoped rewards/stimulation, next decision contexts, progres
an optional episode request. Commit its ledger update in memory and retain the result for an optional episode request. Commit its ledger update in memory and retain the result for
this transition. No task output directly writes controllers or neural state. this transition. No task output directly writes controllers or neural state.
**Amendment, 2026-09-23 (RT-01a).** The task may also ask for two things that happen at the
boundary this transition reaches, after Phase D, never inside it: a slot save
(`Environment.SaveSlot`, composition capability `gameboy-slots-v1`) and a rollback
(`episodeRequest.kind = "rollback"`). Both are recorded with the transition's result and
applied by the coordinator in the order *save, then rollback* (section 6 amendment). A slot
save due at a boundary completes before any `State.Capture` or FLYSIM01 export at that boundary
(amended 2026-09-23, review round 1; [legacy-gameboy-v1](legacy-gameboy-v1.md) section 16). The
retained old inspection is what makes "evaluate once against old/new inspection" possible when
the inspection is artifact-backed: the coordinator keeps `O[k]`'s image until this evaluation
finishes.
### Phase D: commit all agent outcomes concurrently ### Phase D: commit all agent outcomes concurrently
Send `Agent.Commit(scope=k)` with that agent's next sensory observation and routed outcomes. Send `Agent.Commit(scope=k)` with that agent's next sensory observation and routed outcomes.
@ -235,15 +164,6 @@ Example: a synthetic 60-Hz environment with a 1-ms model tick produces 16,17,17
over three steps, totaling 50. A real backend's measured/declared emulated cadence may over three steps, totaling 50. A real backend's measured/declared emulated cadence may
differ; never substitute this example's duration for Game Boy or Dolphin clocks. differ; never substitute this example's duration for Game Boy or Dolphin clocks.
**Amendment, 2026-09-23 (PROF-02a).** The Game Boy's declared cadence is one frame of 70224
cycles at 4194304 Hz, `stepDuration = 8572265625/512` ns. The legacy service accumulates the
`f64` constant `1000 / (4194304 / 70224)` ms, which is exactly `548625/32768` ms, and every
remainder it produces is a multiple of 2^-15 ms below 32 -- exact in `f64`. The legacy
"floating remainder arithmetic" and this section's rational accumulator therefore give identical
ticks and remainders for every frame; both implementations assert it and
`fixtures/gameboy-legacy.json` records the first twelve frames (16, 17, 17, 16, ...). No legacy
exception to this section is needed ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 3).
Wall time is only for pacing, health and presentation. The coordinator schedules absolute Wall time is only for pacing, health and presentation. The coordinator schedules absolute
deadlines after committed boundaries; when behind, it omits sleep and reports lag. It does deadlines after committed boundaries; when behind, it omits sleep and reports lag. It does
not skip world steps, drop neural ticks, or let one agent advance more slowly than another. not skip world steps, drop neural ticks, or let one agent advance more slowly than another.
@ -273,39 +193,6 @@ exactly what is retained, cleared, warmed or recalibrated. No worker independent
Changing port assignment, agent membership, model/profile, cadence or task schema requires Changing port assignment, agent membership, model/profile, cadence or task schema requires
a new composition/epoch. Hot-join and hot-swap during an active match are not v1 capabilities. a new composition/epoch. Hot-join and hot-swap during an active match are not v1 capabilities.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** A declared rollback policy
is an episode policy that does **not** pass through Paused and does **not** start a new episode.
For `legacy-ratchet-rollback-v1` ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 11), once
every Commit of the transition that reached `k` has succeeded:
1. If the same transition asked for a slot save, `Environment.SaveSlot(scope e,k)` first.
2. Choose a new epoch `e'`. `Environment.RestoreSlot(scope e',k; priorEpoch e)` returns the
restored `O'[k]`: same boundary, `worldTime` and `engineFrame` continue, no audio chunk.
3. Coordinator-local: the task clears its transient observations; the executor cancels any
running action and observes `O'[k]`, which yields the next decision contexts.
4. `Agent.Rollback(scope e',k; priorEpoch e)` on every agent concurrently: holds and
eligibility cleared, `O'[k]`'s view installed, no tick.
5. With every reply in hand: `Ready(e', k)`, then the usual durable save. Every capture at
this boundary, before or after the rollback, follows step 1.
A worker reports `capturing` during `SaveSlot` and `restoring` during `RestoreSlot` or
`Agent.Rollback`. A lost reply is resolved by [session RPC](ipc-v1.md) section 6 against the
same operation key before anything fails the epoch (legacy-gameboy-v1 section 11).
Exactly what is retained, cleared and installed is named by the policy, as this section already
requires; nothing is reset by a worker on its own initiative, and a failure at any step fails
the epoch and restores the group coherently. "Reset uses a new epoch/episode and step 0"
remains the rule for terminal episodes; a rollback keeps the episode and the step numbering
because the brain, the audience's history and the frame counter all continue across it, as they
do in the running service. The policy is single-agent: a shared competitive world must not
declare it, because it would rewind one world under every player on one player's stall, which
[state-media-v1](state-media-v1.md) section 7 forbids.
**Amendment, 2026-09-23 (RT-01a).** Sugar admission in the legacy composition reads the pulse
from the last completed commit's telemetry, so an admission decided while a transition is in
flight is at most one commit stale; the admitted stimulus still enters only at the next
admission cut of section 3, Phase A ([workers-v1](workers-v1.md) section 5 amendment).
## 7. Failure rules ## 7. Failure rules
| Failure point | Required response | | Failure point | Required response |
@ -333,19 +220,6 @@ The synthetic integration test must record, for every transition:
- Observation producing boundaries and task event/outcome IDs in order. - Observation producing boundaries and task event/outcome IDs in order.
- All Commit acknowledgments and published committed boundary. - All Commit acknowledgments and published committed boundary.
**Amendment, 2026-09-23 (RT-01a, review round 1).** For a composition with boundary actions the
record also carries, for the boundary the transition reached:
- in behaviour, `boundaryActions`: every `Environment.SaveSlot` (slot id and saved state
digest) and a rollback (slot id), in the order applied -- saves first, each slot once, at most
one rollback, last. FND-01's harness compares it like any other behaviour field;
- in operational metadata, `captures`: every checkpoint capture or FLYSIM01 export at that
boundary, in the order taken, each with the number of boundary actions already applied.
Captures are operational because their schedule is wall-clock policy.
A trace whose capture precedes one of the boundary's slot saves, or counts more actions than
were applied, is refused. The synthetic composition records both lists empty.
Evaluate agents sequentially, concurrently, and in reversed dispatch/completion order. All Evaluate agents sequentially, concurrently, and in reversed dispatch/completion order. All
committed state/action/reward results must match, excluding wall time, request IDs and other committed state/action/reward results must match, excluding wall time, request IDs and other
explicitly operational metadata. Delayed/lost/duplicate messages must not add a neural tick, explicitly operational metadata. Delayed/lost/duplicate messages must not add a neural tick,

View file

@ -22,9 +22,6 @@ rpc.result. Large inputs/outputs use owned bus attachments, never another worker
| `State.Capture` | Coordinator → agent/environment | Immutable snapshot of committed boundary | | `State.Capture` | Coordinator → agent/environment | Immutable snapshot of committed boundary |
| `State.StageRestore` | Coordinator → agent/environment | Validate replacement state under new epoch | | `State.StageRestore` | Coordinator → agent/environment | Validate replacement state under new epoch |
| `State.ActivateRestore` | Coordinator → agent/environment | Install staged state; remain quiescent | | `State.ActivateRestore` | Coordinator → agent/environment | Install staged state; remain quiescent |
| `Environment.SaveSlot` | Coordinator → environment | Capability `gameboy-slots-v1`; record a slot at the committed boundary (section 7) |
| `Environment.RestoreSlot` | Coordinator → environment | Capability `gameboy-slots-v1`; boundary k under a new epoch (section 7) |
| `Agent.Rollback` | Coordinator → agent | Capability `legacy-ratchet-rollback-v1`; Ready(e,k) → Ready(e',k), no tick (section 7) |
State methods have payloads in [state and media](state-media-v1.md). Artifact lifetime and State methods have payloads in [state and media](state-media-v1.md). Artifact lifetime and
message consumption are bus operations managed by the SDK, not Worker/Coordinator methods. message consumption are bus operations managed by the SDK, not Worker/Coordinator methods.
@ -54,8 +51,6 @@ interface AgentTelemetry {
rates: { roleId: Id; hz: number }[]; rates: { roleId: Id; hz: number }[];
learning: { enabled: boolean; updates: U64; changed: U64; signal: number }; learning: { enabled: boolean; updates: U64; changed: U64; signal: number };
} }
// Amendment 2026-09-23: AgentTelemetry also carries
// stimulusRemainingMs: number | null; // pulse still running after the operation; null = reports none
``` ```
`AssetRef` names persistent content in a preprovisioned local registry; it is not an arbitrary path or `AssetRef` names persistent content in a preprovisioned local registry; it is not an arbitrary path or
@ -80,15 +75,6 @@ finite; shipped positive-only task profiles reject negatives. Empty rewards do n
different numerical rule. `id`/`eventId` is unique within its outcome or command namespace; different numerical rule. `id`/`eventId` is unique within its outcome or command namespace;
the coordinator assigns stable IDs before sending a mutating request. the coordinator assigns stable IDs before sending a mutating request.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** `AgentTelemetry` gains
`stimulusRemainingMs: number | null`: the milliseconds of stimulation pulse still running when
the operation that reports the telemetry completed, or `null` for an agent that has no pulse to
report. The operator decided that sugar admission reads the legacy `reward_remaining` from the
last commit's telemetry (section 5 amendment), and no field carried it. It is finite and
nonnegative; it is a report, never an input. The field is required-and-nullable like every
optional field in these contracts, so every existing producer now writes `null`. It changes
`contractDigest`, which [session RPC](ipc-v1.md) section 4 already provides for.
## 2. Agent methods ## 2. Agent methods
### Agent.Initialize ### Agent.Initialize
@ -110,39 +96,9 @@ interface AgentInitializeResult {
warmupTicks: U64; committedStep: U64; // committedStep == "0" warmupTicks: U64; committedStep: U64; // committedStep == "0"
decisionContextDigest: Digest; decisionContextDigest: Digest;
telemetry: AgentTelemetry; telemetry: AgentTelemetry;
graph: AgentGraph;
}
interface AgentGraph {
datasetDigest: Digest; indexDigest: Digest; neuronCount: U64;
rateRoles: Id[]; // <=64, unique; AgentTelemetry.rates is in this order
supportedStimuli: Id[]; // <=64, unique; an undeclared kind is UNSUPPORTED
} }
``` ```
**Amendment, 2026-09-22 (PUBLISH-01).** `AgentInitializeResult` gains `graph`, because
[publishing-v1](publishing-v1.md) section 3 requires `datasetDigest`, `indexDigest`,
`neuronCount`, `rateRoles` and `supportedStimuli` in every published `AgentDescriptor` and no
worker method carried any of them. Without this the only available source is the composition
that asked for the agent, so a descriptor could only ever agree with itself and the section 3
rule that "geometry/spike mapping requires indexDigest, not merely the same number of neurons"
would have nothing to compare. Initialize is where the agent has just loaded its dataset and
built its index, so the attestation belongs there. `rateRoles` is the "profile-defined order"
section 1 already requires `AgentTelemetry.rates` to be in, and the result is refused when the
two disagree; `supportedStimuli` is the profile capability section 1 already requires a
stimulus kind to resolve through, and a kind outside it is refused with `UNSUPPORTED` before
the model is touched. It changes `contractDigest`, which [session RPC](ipc-v1.md) section 4
already provides for.
**Amendment, 2026-09-22 (SESSION-02).** `HelloResult.limits` gains `workerThreads`, an
integer >=1 reporting the allocation the launcher started that worker within, because
"within launcher allocation" above had no wire-level proof: the launcher passes the number to
the worker out of band, and a coordinator that is not also its own launcher had no contract
path to it. Hello is where a worker already proves its identity and reports its limits, so the
allocation belongs there. A caller asking for more than the worker reports is refused with
`BUSY` before the model is constructed, which this section already required; the amendment
only makes the number visible to whoever must respect it. It changes `contractDigest`, which
[session RPC](ipc-v1.md) section 4 already provides for.
The profile fixes warm-up/calibration behavior and supported schema versions. Validate inputs The profile fixes warm-up/calibration behavior and supported schema versions. Validate inputs
and required roles before model construction. Install the initial sensory input, warm the and required roles before model construction. Install the initial sensory input, warm the
brain with learning disabled, calibrate the fixed readout and establish Ready(0). Do not brain with learning disabled, calibrate the fixed readout and establish Ready(0). Do not
@ -297,25 +253,6 @@ The environment only needs backend-relevant portions of task setup, not reward r
neural policies. `taskConfig` resolves a declared setup configuration; the complete task neural policies. `taskConfig` resolves a declared setup configuration; the complete task
implementation and ledger stay in the coordinator. implementation and ledger stay in the coordinator.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** Three readings for the
Game Boy environment of the legacy composition ([legacy-gameboy-v1](legacy-gameboy-v1.md)
sections 8 and 9), stated here because they are about this method's shape:
- *Setup scaffold.* The backend configuration may declare setup frames the environment runs
with every control neutral before it returns O[0]. The legacy composition declares exactly
**one frame with no button down**, which is what its fresh start does; O[0] then has
`engineFrame` `"1"`, `worldTime` `0/1` and no audio chunk. These frames are declared
scaffold, attributed to no fly, and never a transition.
- *Inspection may be artifact-backed.* `inspection` is a `TypedValue` under the descriptor's
schema; the legacy schema `gameboy-memory-inspection-v1` carries a 64-KiB memory image as an
`ArtifactRef` (listed in the bus attachments) plus the ROM's digest. This is the "explicit
artifact-backed schema" section 1 requires for typed state over 32 KiB, and it is the one
bulk transfer per boundary the section 4 rule against per-byte remote reads asks for. The
environment's only write to a running game remains the controller batch.
- *Audio.* The environment publishes native samples in the declared f32 format; converting a
backend's integer samples to f32 is the environment's job (binjgb: `sample / 255`), and any
filtering for listening -- the legacy DC blocker -- is presentation, applied by the edge.
### Environment.Advance ### Environment.Advance
```ts ```ts
@ -382,18 +319,6 @@ but not a port assignment. The coordinator supplies the port. Per-agent executor
private; a running macro may emit controls according to its declared policy, but only after private; a running macro may emit controls according to its declared policy, but only after
neural selection. The first implementation supports the stateless identity executor only. neural selection. The first implementation supports the stateless identity executor only.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** The legacy composition
declares the extension **`executor: pokered-macros-v1`**: its task and its action executor are
**one object** implementing both interfaces above, serving one agent on one port
([legacy-gameboy-v1](legacy-gameboy-v1.md) section 10). They share state that neither could
reach through a declared channel if split: the executor's scene observation is the `bound` set
the task hands the decoder, the macros read the task's exploration ledgers, and the macro layer's
progress signal feeds the ratchet. The executor reads the boundary's memory image and the ROM
`AssetRef`, never the emulator. "Stateless identity executor only" remains true of the
synthetic composition; a stateful executor is permitted exactly where a composition declares
one by name, and its state is captured or declared transient by that composition's restore
semantics (state-media-v1 section 4 amendment).
The executor's currentGameState is a coherent read-only inspector view at this boundary; The executor's currentGameState is a coherent read-only inspector view at this boundary;
progressView supplies task history/objectives. It updates its selected action every step progressView supplies task history/objectives. It updates its selected action every step
(movement, path replanning, interaction, completion), not merely replaying a blind button (movement, path replanning, interaction, completion), not merely replaying a blind button
@ -417,31 +342,6 @@ not arbitrary raw inspector memory or incoming chat.
It requests a coordinator-owned policy transition after final reward commit; it cannot reset It requests a coordinator-owned policy transition after final reward commit; it cannot reset
the environment directly. Generic progress is a TypedValue, not mandatory Pokémon ladder data. the environment directly. Generic progress is a TypedValue, not mandatory Pokémon ladder data.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** `episodeRequest.kind` is
`"terminal"` or **`"rollback"`**. A rollback request asks for the composition's declared
rollback policy; its `outcome` is that policy's registered schema. The only policy defined is
`legacy-ratchet-rollback-v1` (outcome `{slotId, trigger}`), applied at the boundary the
transition just committed without a pause ([step-v1](step-v1.md) section 6 amendment). A
composition that declares no rollback policy treats the request as a task failure. It still
"cannot reset the environment directly": the coordinator applies the policy through the
section 7 methods.
**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`:
- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the
bytes of every attachment the task declares (`Task::inspection_attachments`, for example
`inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value
it always was.
- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary
it reached. They are applied after every Commit, saves first.
- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next
contexts.
- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task
whose executor state is transient re-observes the restored world here, and returns the contexts
the coordinator holds against the checkpoint's.
- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared
state.
## 5. Admission and audience boundary ## 5. Admission and audience boundary
The first synthetic implementation has no audience input. Later integration maps permitted The first synthetic implementation has no audience input. Later integration maps permitted
@ -456,26 +356,6 @@ v2 contract must specify accepted/applied/rolled-back/aborted states and reconci
paid interactions are enabled. Do not inherit a claim of durable exactly-once stimulation paid interactions are enabled. Do not inherit a claim of durable exactly-once stimulation
from these in-memory worker request caches. from these in-memory worker request caches.
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** Sugar in the legacy
composition is admitted by the coordinator with the legacy rules -- the rate limiter and "no
overlap with an active pulse" -- reading the pulse from `stimulusRemainingMs` of the **last
completed commit**. The operator accepted that this value can be one commit old; both
consequences are bounded to one frame and are listed in
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 15. Admitted sugar is a profile-supported
`reward-pulse` stimulus in the next Prepare's `preStepStimulations`. Because admission and
application are now separate, each admission record carries its interaction id and ends
`applied` or, if the epoch fails before that Prepare commits, `aborted`; the edge fulfils the
first and refunds the second, and the slice wiring the bridge tests both. This is the
accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
kind; paid interactions in general still need the public v2 contract.
**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the
admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it
ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The
legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted.
The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of
2026-09-29).
## 6. Health, shutdown and extensions ## 6. Health, shutdown and extensions
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore
@ -485,56 +365,3 @@ advertised. Unsupported methods return `UNSUPPORTED`, mutation none.
New task-specific fields belong in registered TypedValue schemas. New worker capabilities, New task-specific fields belong in registered TypedValue schemas. New worker capabilities,
variable-duration stepping, subscriptions or additional sensor modalities require a contract variable-duration stepping, subscriptions or additional sensor modalities require a contract
change and shared fixtures. An unconstrained plugin dictionary is not a substitute for that. change and shared fixtures. An unconstrained plugin dictionary is not a substitute for that.
## 7. Extension methods (amendment, 2026-09-23)
**Amendment, 2026-09-23 (RT-01a; operator decision of 2026-09-23).** The operator decided on a
full port of the live fly, whose ratchet rolls the *game* back to a saved state while the brain
continues. Neither half of that is expressible with sections 2 and 3: there is no method that
saves or restores world state outside a coherent group checkpoint, and none that installs a new
input in an agent without a transition. These three methods are that, generically shaped, each
behind a capability a worker advertises in `Worker.Hello`; a worker without it answers
`UNSUPPORTED`, mutation none. Payloads are in `fly-session-types` (`extensions`) and
`@flybrain/session-types`, in the session schema set.
```ts
// Environment.SaveSlot -- capability gameboy-slots-v1. Scope: the committed boundary (e, k).
interface SaveSlotParams { slotId: Id } // a slot the composition declares
interface SaveSlotResult { slotId: Id; boundary: U64; // == scope.step
stateDigest: Digest; byteLength: U64 }
// Environment.RestoreSlot -- capability gameboy-slots-v1. Scope: (e', k), a NEW epoch.
interface RestoreSlotParams { slotId: Id; priorEpoch: Id; // the environment is Ready(e, k)
policy: "legacy-ratchet-rollback-v1" }
interface RestoreSlotResult { slotId: Id; committedStep: U64; // == k: no transition ran
observation: WorldObservation } // boundary k, no audio chunk
// Agent.Rollback -- capability legacy-ratchet-rollback-v1. Scope: (e', k), the same new epoch.
interface AgentRollbackParams { agentId: Id; priorEpoch: Id; // the agent is Ready(e, k)
policy: "legacy-ratchet-rollback-v1";
input: SensoryInput; // boundary k: the restored world
decisionContext: TypedValue } // for the next Prepare
interface AgentRollbackResult { agentId: Id; committedStep: U64; // == k: no tick ran
decisionContextDigest: Digest; telemetry: AgentTelemetry }
```
- Both environment methods run only at a committed boundary with no Advance outstanding.
`SaveSlot` replaces the slot's contents with the world state and the frame on screen at that
boundary; slots are environment state and belong to its `State.Capture` payload. It is one
operation per boundary under the section-5 operation key of [session RPC](ipc-v1.md).
- `RestoreSlot` and `Agent.Rollback` move a participant from `(priorEpoch, k)` to
`(scope.epoch, k)`; `priorEpoch` must differ from the scoped epoch, and after the move every
request scoped to the prior epoch is `STALE_EPOCH`. The restored observation keeps the
boundary number, `worldTime` and `engineFrame`, and returns fresh artifacts; it carries no
audio chunk, and the next chunk marks a discontinuity (state-media-v1 section 2).
- `Agent.Rollback` applies the policy's agent half and nothing else: for
`legacy-ratchet-rollback-v1`, clear decoder holds and plastic eligibility, install `input`
without a tick, reset the readout's transient (held channel, blocked window, location from
the context), keep the brain clock, membrane, RNG, rates and gains. No reward, stimulation or
calibration. It is the only way to install an input outside a Commit.
- A failure of any of these methods mid-policy fails the epoch; recovery is the coherent group
restore of [state-media-v1](state-media-v1.md) section 6. There is no partial rollback.
- `maxSlots` is 4 (a crate-chosen bound, published in the schema set).
The sequence that uses them is [step-v1](step-v1.md) section 6's amendment and
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 11.

View file

@ -177,7 +177,7 @@ Node 22, TypeScript, `tsx` for dev, `node --test` for tests. Deps: `@twurple/aut
One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim. One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim.
Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/<app>-client-{id,secret}`, matching the stream-key posture already documented. Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/fly-pokemon-client-{id,secret}`, matching the stream-key posture already documented.
Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope: Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope:
@ -193,7 +193,7 @@ Two identities, both registered on the provider: the **bot account** (chat send)
| `channel:manage:broadcast` | broadcaster | stream markers | | `channel:manage:broadcast` | broadcaster | stream markers |
| `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) | | `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) |
Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. Before that assertion, each role's stored token is made usable (added 2026-09-28): an access token expired by `obtainmentTimestamp + expiresIn`, or one `validate` rejects with 401, is refreshed once through that role's `RefreshingAuthProvider`, and every refresh is persisted under the role whose provider made it (serialized atomic writes), so both roles survive a restart even when they are one account. Only a refresh Twitch refuses (4xx) is fatal, with one line naming the role and the runbook's re-authorize step; tokens, the client secret and request URLs never reach the log. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition. Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition.
## B2. Day one (pre-channel-setup) ## B2. Day one (pre-channel-setup)

View file

@ -187,8 +187,7 @@ before. The Rust producer always sends all five, in both modes.
- **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in - **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in
brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound, brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound,
on the naming screen, whose pad is the fly's own buttons (`docs/design/macros.md` 12.32), and and while a macro is running, because a running macro owns the pad. It is **report only**: no
while a macro is running, because a running macro owns the pad. It is **report only**: no
producer acts on it and no consumer should, and nothing in the loop reads it back. It exists producer acts on it and no consumer should, and nothing in the loop reads it back. It exists
because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no
button waits — and on screen that is indistinguishable from a hang button waits — and on screen that is indistinguishable from a hang

View file

@ -177,11 +177,6 @@ achievements.
| Wild win | +0.1, +0.05, +0.0333 | at most three observed wild KOs per `(map,species,level)` | | Wild win | +0.1, +0.05, +0.0333 | at most three observed wild KOs per `(map,species,level)` |
| Badge | +3 | each newly set badge bit | | Badge | +3 | each newly set badge bit |
That is the prototype's catalog as it shipped, kept here as history. The live one is
`docs/rewards-learning.md`: `pokered-unique8-v8` adds `boundary` (v5), `catch` (v6), `talk` and
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23), and `damage`
(v8, the operator's decision of 2026-09-29).
Every value is positive; there were no loss or blackout penalties. Values in a frame summed into Every value is positive; there were no loss or blackout penalties. Values in a frame summed into
`R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with `R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with
overlapping pulses taking their maximum. overlapping pulses taking their maximum.

View file

@ -8,9 +8,7 @@ the project."
1. The release watchdog (`infra/bin/fly-watchdog` check 10) flags a suspected loop: few distinct 1. The release watchdog (`infra/bin/fly-watchdog` check 10) flags a suspected loop: few distinct
macros, a short sequence repeating, no growth in places explored. It exports macros, a short sequence repeating, no growth in places explored. It exports
`fly_loop_suspected` and writes `/run/fly/wd/loop.json`. It never acts. The separate `fly_loop_suspected` and writes `/run/fly/wd/loop.json`. It never acts.
`fly-loop-recover.timer` unsticks a confirmed trap on its own: flysim restart, then milestone
resets (`infra/docs/loop-recovery.md`). That buys time; it does not replace checkpoint-based review.
2. The coordinator session (Fable) checks that marker on a schedule. On a flag it pulls the 2. The coordinator session (Fable) checks that marker on a schedule. On a flag it pulls the
live checkpoint read-only (`pct pull`, into `.local/checkpoints/`, never committed), and live checkpoint read-only (`pct pull`, into `.local/checkpoints/`, never committed), and
spawns a review agent with the trap brief: reproduce from the checkpoint with the real spawns a review agent with the trap brief: reproduce from the checkpoint with the real
@ -21,16 +19,6 @@ the project."
on the encoder output and `/status`, and records the release in `docs/stream-mvp-plan.md`. on the encoder output and `/status`, and records the release in `docs/stream-mvp-plan.md`.
No approval round trip with the operator; he sees the record. No approval round trip with the operator; he sees the record.
## Unstick while a fix cooks (the operator, 2026-09-23)
"lets unstick the fly so stream stays interesting. lets make that a rule. while a fix cooks,
revert." When the watcher confirms a trap and its review agent is dispatched, the coordinator
restarts flysim only (claimed in the host log): a restore starts with empty macro ledgers and
keeps the rung. A recurrence gets another restart; only a fly still trapped about ten brain
minutes after a restart is rolled back with `fly-reset-to-milestone`. This is an action outside
the fly: it presses no button and changes no ROM, readout, catalog or adapter, and it never
replaces the fix, which still ships through the loop above.
## The ethos check (every one must hold, or the fix is not shipped) ## The ethos check (every one must hold, or the fix is not shipped)
- The ROM is never modified. Game memory is read, never written. The only write into the - The ROM is never modified. Game memory is read, never written. The only write into the

View file

@ -99,17 +99,6 @@ argmax of the same normalized scores over the same rates. It is the same kind of
the retina already sees, arriving through a much narrower channel, and it is disclosed on the the retina already sees, arriving through a much narrower channel, and it is disclosed on the
honesty panel with the rest of the readout. honesty panel with the rest of the readout.
**Where the location comes from on the session framework (2026-09-23).** When the live fly runs
on the session framework (the operator's port decision of 2026-09-23), the sim loop that owned
the position is split: the task reads the location, the agent owns the decoder. The location
then reaches the decoder as a **declared** field of its decision context,
`gameboy-readout-context-v1 {boot, bound, location}`
([legacy Game Boy composition](design/session-framework/legacy-gameboy-v1.md) section 5). The rule is
unchanged: the location only restarts the blocked window, `null` is still no information, the
held channel and the window stay the readout's own state, and the blocked channel is still
computed here, never handed in. The profile allowlists the field, and the task cannot put
anything else in it.
## Macro group (2026-09-16) ## Macro group (2026-09-16)
`DecoderConfig.macros` is a second `ExclusiveGroup` with the same fields and the same decision rules `DecoderConfig.macros` is a second `ExclusiveGroup` with the same fields and the same decision rules

View file

@ -1,6 +1,6 @@
# Rewards and learning # Rewards and learning
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v8`. The code of record is The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v5`. The code of record is
`services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the `services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the
gates and the rules); this page says what each rule pays for and why it is allowed to. The gates and the rules); this page says what each rule pays for and why it is allowed to. The
prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules
@ -23,11 +23,7 @@ change what the fly can do.
| `trainer` | `trainer` | +0.5 | 200 ms | Each named `EVENT_BEAT_*` flag once, except the flags classified as story milestones | | `trainer` | `trainer` | +0.5 | 200 ms | Each named `EVENT_BEAT_*` flag once, except the flags classified as story milestones |
| `battle` | `wildwin` | +0.1, +0.05, +0.0333 | 100 ms | At most three observed wild KOs per `(map, species, level)` | | `battle` | `wildwin` | +0.1, +0.05, +0.0333 | 100 ms | At most three observed wild KOs per `(map, species, level)` |
| `badge` | `badge` | +3 | 400 ms | Each newly set badge bit | | `badge` | `badge` | +3 | 400 ms | Each newly set badge bit |
| `boundary` | `explore` | +0.05, +0.10 | 100 ms | First tile adjacent to one of the map's exits, and the exit tile itself; once per `(map, exit)` for the lifetime of the ledger. **Nothing on an indoor map** (since v7): the exit is still recorded, and pays 0 | | `boundary` | `explore` | +0.05, +0.10 | 100 ms | First tile adjacent to one of the map's exits, and the exit tile itself; once per `(map, exit)` for the lifetime of the ledger |
| `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger |
| `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger |
| `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger |
| `damage` | -- | +0.20 per whole Pokémon, in proportion; +0.05 knockout | 80 ms | HP the fly's own attack removed from the enemy (since v8): its share of the target's max HP, below the lowest HP that target has shown this battle; +0.05 when the hit knocks out a trainer's Pokémon; at most 0.50 a battle; a wild battle at 1, 1/2, 1/3 for its first three per `(map, species, level)`, then nothing |
Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")` Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")`
is `None` by test. The values in one frame sum into `R`, and the network reinforces once with is `None` by test. The values in one frame sum into `R`, and the network reinforces once with
@ -35,230 +31,7 @@ is `None` by test. The values in one frame sum into `R`, and the network reinfor
The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`: The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`:
`docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its `docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its
own shares the nearest one. It still reaches the page as an event with its own label. `damage` is own shares the nearest one. It still reaches the page as an event with its own label.
the one Pokémon kind with no counter at all ("Damage rewards" below says why).
Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on
`wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on
`pokedex` because the `species` rule already pays for the Pokédex bit the same catch sets --
counting it twice would be the dishonest option. And the stage's ticker copy is keyed on the feed
kind, not on the catalog kind (`apps/stage/src/games/pokemon-red.ts`), so the row for a catch
currently reads "wild win". The event's own label, `CAUGHT #<species>`, is what reaches the event
log, `/status` and the checkpoint. Changing the ticker copy means opening the feed's closed kind
set, which this rule deliberately did not do.
`talk` and `item` publish on `explore`, for the same reason `boundary` does: each is the fly
finding what is in a place -- new ground, a door, a person or sign it opened, an item it picked up
-- at the same quiet scale (0.05 to 0.15). Not `area`, which counts maps and is a notable row; not
`story`, which is the plot; not `wildwin`, which is a battle. No feed kind was added, so
`docs/feed-protocol.md` and the stage's switch statements did not move. The Pokémon Red ticker's
`explore` row still says "new place" ("3 new places" collapsed) for all four: "new find" was
proposed and the operator kept "new place" (2026-09-23), so a conversation or an item reads as a
new place on screen. The event labels -- `TALKED TO #<slot> IN AREA <map>`, `READ SIGN #<id> IN
AREA <map>`, `FOUND ITEM #<item>`, `FOUND A HIDDEN ITEM` -- reach the event log, `/status` and the
checkpoint. Both also reset the stage's stall meter, which counts `explore`: engaging with a
building is progress in the sense the operator asked for.
## Catch rewards
The operator's decision of 2026-09-22: the fly is paid for *keeping* a wild Pokémon, not only for
knocking one out. The rule is one kind with two payouts, the way `boundary` is.
**How a catch is read.** From `wCapturedMonSpecies` (`$d11c`), whose comment in `ram/wram.asm` at
the pinned commit is "0 if no mon was captured". `ItemUseBall` zeroes it before every throw
(`.canUseBall`) and writes `wEnemyMonSpecies` into it only on the branch that keeps the Pokémon;
`UseBagItem`'s `.returnAfterCapturingMon` zeroes it again and sets `wBattleResult` to 2 on the way
out of the battle. `wBattleResult` is 2 on exactly two paths in the whole game -- that one, and a
link battle whose opponent ran -- so requiring both the species and the result means a byte read
out of a half-initialised battle cannot pay. The adapter records the species during the battle and
pays on the way out, where the wild-KO payout already lives.
Not from `wPartyCount`. A catch with a full party raises `wBoxCount` instead, and `wPartyCount`
also rises for a gift, a trade and a Pokémon taken out of the PC, so it would need a second rule
to mean anything. The cartridge's own flag needs none.
**What counts as a new species.** The `species` payout inside the same battle. Nothing but a catch
can set a `wPokedexOwned` bit during a wild battle, so a `species` payout between the battle
starting and the ball keeping the Pokémon *is* that Pokémon being new to the run. It is read this
way rather than off `wCapturedMonSpecies` because that byte is the cartridge's **internal** species
index while the owned bitset is by **Pokédex number**, and nothing in WRAM converts between the two
(`docs/design/macros-wram.md` section 2, "species numbering"). A battle restored from a checkpoint
written before this rule existed carries no "species payouts when it started", which reads as
"cannot tell" and pays the repeat amount: the conservative half, and at most 0.20 once.
**The budget.** Three payouts per species for the lifetime of the ledger, the same cap and the
same reason as the wild-KO rule's three: a species the fly can find over and over is a farm, and
three is enough for the behaviour to be learned. A rollback blocks every species already paid,
exactly as it blocks every wild-KO key already paid, so the same catch cannot be replayed for
reward. A Safari Zone or old-man battle pays nothing, because the whole sample is dropped a step
earlier with a visible mode; a trainer battle pays nothing, because balls cannot be thrown in one.
**The scale.** 0.30 on its own is below a new Pokédex entry (0.50), below a story flag (1.0) and
well below a badge (3.0). A catch of a new species pays 0.80 across two kinds, which sits between
a story flag and a badge -- deliberately, because it is the one event that is both a discovery and
a thing the fly had to do on purpose.
## Engagement rewards
The operator's decision of 2026-09-23, recorded with the port decisions: reward the fly for
engaging *inside* buildings and stop paying it for leaving them. It was chosen over a pad rule and
over weighting the choice, and it is a catalog change -- an operator decision, like the catch
reward -- not a loop-review fix (`docs/loop-review.md`). It answers a shape the loop reviews kept
finding in Pewter: `GO OBJECTIVE` into a building and `GO OUT` straight back, paid for the door on
the way out and for nothing inside.
**Indoors** is two of the cartridge's own tables, and nothing hand-classified
(`pokemon_red/engage.rs`, `indoor`). `CheckIfInOutsideMap` (`home/overworld.asm`) is the game's
outdoor test -- tileset `OVERWORLD` or `PLATEAU` -- and `WarpFound2` labels its other branch
`.indoorMaps`; on its own that would call Viridian Forest and every cave indoors, and their exits
are how the fly gets anywhere. `BikeRidingTilesets` (`data/tilesets/bike_riding_tilesets.asm`) is
the list of places the bicycle may be ridden -- `OVERWORLD`, `FOREST`, `UNDERGROUND`, `SHIP_PORT`,
`CAVERN` -- and the bike is the one thing the cartridge refuses inside a building by rule. A map is
indoors when its `wCurMapTileset` is in neither: every house, mart, Pokémon Center, gym, gate, lab
and museum, the S.S. Anne, Silph Co., the Pokémon Tower, the Mansion, the Rocket Hideout and the
Indigo Plateau's rooms. Not the forest, a cave, the Underground Path or Vermilion's dock.
**`talk`, +0.10.** Paid on the sample the text box closes, for a conversation that
1. *the fly opened*: on the last sample before the font bit (`wFontLoaded` bit 0) rose, the fly had
the joypad -- no `wJoyIgnore`, no simulated input, no scripted movement -- was standing still
(`wWalkCounter` zero, the only state the overworld reads A in) and stood where it stands now. A
script's text usually opens with the joypad taken; one opened by a map script the frame after a
step ends can still look opened by the fly, and is then held to rule 2 (below);
2. *is with the thing in front of it*: `DisplayTextID` copies its argument into `wSpriteIndex` --
a sprite slot up to `wNumSprites`, or a text id -- and the sprite must stand on the tile the
player faces (or one further, across a counter, on a tileset that has counter tiles, which is
`IsSpriteOrSignInFrontOfPlayer`'s own long reach), or the text id must be the sign's on that
tile. The byte arrives about **twenty frames after** the font bit (measured on the cartridge:
`DisplayTextIDInit` loads the font's tiles first) and until then still names the previous
text's subject, so it is read once it has changed or 45 samples have passed, and only while the
bottom dialogue box is drawn -- the start menu draws its own box elsewhere. An item ball is a
sprite but not a person, and pays `item`;
3. *opened indoors*, on the map the box opened on;
4. *finished*: the box closed on the same map. A conversation that ends in a warp, a rollback or a
restore pays nothing.
The ledger is the adapter's lifetime `seen` set, keyed `talk:<map>:sprite:<slot>` or
`talk:<map>:sign:<text id>` -- the same "map and object index" the macros' `talked` ledger uses,
but **not** that ledger: the macros' ledger is session state and is thrown away on a restore; this
one is checkpointed and survives a rollback, so talking to the same person again, after a restore
or not, pays nothing. The trainer the fly speaks to before a battle is a person and pays once; the
nurse, a clerk and a sign each pay once per map.
**`item`, +0.15.** Read from the cartridge's own "this one has been taken" bits, on any map.
An item ball is one of the map's toggleable sprites (`wToggleableObjectList`, sprite slot and
global index) whose `wMapSpriteExtraData` is `(item id, 0)` -- the shape `LoadMapHeader` writes for
an `ITEM` `object_event` and for nothing else (a trainer's is `(class, number)` with numbers from
1, a person's two zeroes); `PickUpItem` sets its global bit in `wToggleableObjectFlags` through
`HideObject`, and only after `GiveItem` succeeded, so a full bag pays nothing. A hidden item is a
bit of `wObtainedHiddenItemsFlags`, set by `FoundHiddenItemText` after `GiveItem` and by nothing
else; hidden *coins* have their own bitset and are not items. Either pays when its bit rises
between two playable samples, keyed `item:<global index>` or `hidden:<index>`, once for the life
of the ledger. A gift item from a script (the Old Amber, a TM from a person) is not an item ball:
the conversation pays `talk`, and the item nothing.
**The seed.** The first playable sample that finds the key `items:seeded` absent -- a fresh
adapter, or a `v6` ledger restored under `v7` -- writes a key for every bit the game already shows
as taken and pays for none of them, so a rollback to a slot from before a `v6`-era pickup cannot
pay for taking it again. The two item balls a script *reveals* are left out of the seed, because
their bits are set from a new game until Giovanni's defeat clears them: the Rocket Hideout's Silph
Scope and Lift Key (`$87`, `$88`), the only `ITEM` entries `data/maps/toggleable_objects.asm` starts
`OFF`.
**`boundary` indoors.** Every exit on an indoor map is still written to the ledger, so
`exit_visited` answers exactly what it did and the macros see no change, but nothing is paid. A
town's doors, a route's edges, the forest's gates and a cave's ladders pay as before. One
consequence, measured on the cartridge (`tests/rom_engage.rs`): for the thirty-odd frames of
`PlayMapChangeSound` the cartridge has written the destination into `wCurMap` while the tileset and
the warp table are still the map being left, so the exit the fly is standing on is classified by
the map it belongs to. Walking into a building through a town door still pays that door's on-exit
half, 0.10, once, keyed under the building's id as it always was; walking out pays nothing.
**The scale.** A building's worth of engagement -- a few people, a sign, perhaps a ball -- is
0.3 to 0.6: more than the 0.15 its door paid for being left, less than a new Pokédex entry per
person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no
building can be farmed.
## Damage rewards
The operator's decision of 2026-09-29, chosen over a pad rule that would have withheld a stat move
once it had been used: pay the fly for the HP its own attack removes from the Pokémon it is
fighting. It is a catalog change, an operator decision like the catch and engagement rewards, not a
loop-review fix. It answers row 67 (`infra/docs/macros-traps.md`): the live fly lost the Pewter
Gym's Jr. Trainer 29 times running, choosing TAIL WHIP 155 times, BUBBLE 23 and TACKLE 0, and
nothing in the catalog paid for anything that happened inside a battle it did not win. The pad
offered every move; the readout's favourite was the one move that cannot win. The code is
`pokemon_red/damage.rs`.
**What counts as the fly's attack.** A drop in `wEnemyMonHP` on a sample where `hWhoseTurn`
(`$FFF3`) reads 0 and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit
(`engine/battle/core.asm`), `ApplyDamageToEnemyPokemon` subtracts the damage inside
`ExecutePlayerMove`, with `hWhoseTurn` 0, once per hit of a multi-hit move. Everything else that
lowers the enemy's HP lands with it 1: the enemy's poison and burn ticks and a Leech Seed on the
enemy (`HandlePoisonBurnLeechSeed` picks whose HP to cut *by* `hWhoseTurn`), its recoil, its
confusion self-hit, its own Explosion or Self-Destruct, and the HP it pays for a Substitute. A
Leech Seed on the fly heals the enemy, and HP going up never pays. Damage into an enemy Substitute
never touches `wEnemyMonHP`. `STRUGGLE` is the move the cartridge executes for a Pokémon with no
PP; the fly chose FIGHT, not the move, so it pays nothing (winning still pays what winning pays).
`tests/rom_damage.rs` pins the address on the cartridge from the live row 67 state: every drop of
the enemy's HP lands with `hWhoseTurn` 0 and every drop of the fly's own with 1.
**How much.** 0.20 per whole enemy Pokémon's max HP, paid in proportion on the sample the HP
drops -- BUBBLE for 10 of Diglett's 24 is 0.083, TACKLE for 4 of Sandshrew's 33 is 0.024. The hit
that knocks out a trainer's Pokémon adds 0.05 on the same event. At most **0.50 a battle**, which is
the `trainer` rule's own value: a battle's worth of damage is worth what winning it is, and the
Jr. Trainer's two Pokémon reach it exactly (2 x (0.20 + 0.05)). A wild knockout adds nothing here
because the `battle` rule already pays it, on the way out of the battle. Next to the rest of the
catalog: a wild battle's damage (0.20) is twice its knockout (0.10) and equal to a new area (0.20);
a trainer battle's (0.50) is the trainer's flag; a gym's is a sixth of the badge (3.0).
**What cannot be farmed.**
- *Heal.* Each target keeps the lowest HP it has shown this battle, and only HP below that pays. A
Potion, Recover, Rest or a drain lifts the HP; the same HP is not paid twice.
- *Switch.* A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that goes out
and comes back keeps its mark, and two Weedles of one level are two targets.
- *A stale enemy.* `InitBattleVariables` does not clear `wEnemyMon`, and a trainer battle sets
`wIsInBattle` a whole transition before `LoadEnemyMonData` runs, so the first samples of a
battle can hold the last battle's Pokémon at the HP it finished on -- in the row 67 ring, the
same trainer's Diglett in the same slot. A target is marked the first time it reads full HP,
which is how every enemy Pokémon enters a battle in this game, so the stale one neither pays nor
hides the real one's first hit.
- *The battle.* 0.50 at most, whatever the party size.
- *Wild Pokémon.* A wild battle pays at the wild-KO rule's scale, 1, 1/2, 1/3, for its first three
battles per `(map, species, level)` that paid any damage (`damageCounts`), then nothing; attacking
a wild Pokémon and running from it counts. A rollback blocks every key that has paid, the way it
blocks a paid wild KO or catch.
- *Trainers* keep no lifetime ledger. A trainer is fought again only after the fly has lost to it
(or after a rollback), and each of those battles is bounded by the cap. In the row 67 ring that
is the point: every lost battle pays for the hits that landed, and the hits that land are the
moves that win.
**Feed.** `damage` publishes on no counter (`RewardKind::from_adapter` is `None`). Every other
Pokémon kind shares the nearest counter, and the nearest here is `wildwin`, but the stage folds
that row into "N wild wins": false of a trainer battle, and false of a battle the fly goes on to
lose. A hit reaches the page as a reward event with its own label, `HIT #<species> FOR <n> HP`
(`... KO` for a knockout; the species is the cartridge's internal index, as `CAUGHT #<species>` is),
and the event log, `/status` and the checkpoint carry it; it is only left out of
`game.rewardCounts` and the ticker's per-kind copy, the way the platformer's `started` and `clear`
are. No feed kind was added. The stage rolls the hits up itself (`apps/stage/src/lib/ticker.ts`,
`hitCopy` in the game config): a reward with no `rewardKind` and that label folds into one
"damage dealt x<n>" row with the summed value, ` KO` once a hit in it felled a Pokémon, joined by
each hit within 45 s of the last; a later battle starts a new row (`apps/stage/mockups/row68-ticker-*.png`).
**Learning.** A payout reinforces the recent spike history with `m = tanh(R)` over a 5 s
eligibility trace ([plasticity](plasticity.md)). Measured on the cartridge from the row 67 state
(`tests/rom_damage.rs`), the HP drops 176 frames (2.9 s) after the `MOVE n` press when the fly
moves first and about 420 frames (7 s) when the Jr. Trainer's Pokémon does -- its attack and text
come first. So the choice's trace is at a half to a quarter when its hit is paid, and the previous
turn's choice, one turn (about 7.5 s) earlier still, at a tenth to a twentieth. That ratio is the
whole mechanism: nothing tells the readout which move to press. A hit is small (0.02 to 0.10), so what it can move per battle is small too; whether
the brain learns the attacking move inside a few brain hours is a measurement, not a promise, and
the first one is `infra/docs/macros-traps.md`, row 68.
**Migration.** `v7` -> `v8` adds `damageCounts` and, inside a battle in flight, `battle.damage`;
both are optional and a `v7` state restores with no wild key paid and its battle's Pokémon marked
where they stand. See `docs/design/flysim.md`, "Restoring across an adapter version".
## Gates ## Gates
@ -288,10 +61,6 @@ therefore replays none of it.
## Boundary rewards ## Boundary rewards
Since `pokered-unique8-v7` everything below holds **outdoors** -- towns, routes, the forest,
caves -- and on an indoor map the same keys are written and nothing is paid ("Engagement rewards"
above has the definition of indoors and the one transition frame worth knowing about).
`docs/design/room-escape.md` section 2. The rule pays 0.05 the first time the fly stands on a tile `docs/design/room-escape.md` section 2. The rule pays 0.05 the first time the fly stands on a tile
orthogonally adjacent to one of the current map's exits, and 0.10 the first time it stands on the orthogonally adjacent to one of the current map's exits, and 0.10 the first time it stands on the
exit tile itself. Both are keyed into the adapter's lifetime `seen` ledger as exit tile itself. Both are keyed into the adapter's lifetime `seen` ledger as
@ -359,41 +128,7 @@ body picks the macro; the descending neurons press the buttons.**
## Honesty ## Honesty
The catalog now includes damage (v8). It is the first rule that pays for something inside a battle The catalog now includes exits. That is worth saying plainly on the honesty panel, because paying
the fly may still lose, and the closest the catalog has come to grading a *choice*: the moves are
all on the pad, and the one that lands pays. It is still a reward read out of WRAM after the frame,
not a press: nothing in the adapter picks a move, removes one from the pad or tells the readout
which is good, and a move pays only if the cartridge says it took HP off the enemy. The pad rule
the operator declined (withholding a stat move once used) would have been the doctrine change; this
one leaves the pad exactly as the scene deals it. It is also bounded on purpose: at most what winning
pays, per battle, and a wild Pokémon only three times.
The catalog now includes conversations and items (v7). Paying for a conversation is the closest
the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a
press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is
read out of WRAM after a conversation the fly's own buttons -- or the macro the mushroom body chose
-- opened and finished, and it is once per person or sign for the life of the run, so the thing
that is learned is "the people in a building are worth a visit", not "press A". It is also why the
rule demands evidence that the fly opened the box. That evidence is not proof: a map script runs
one frame after a step ends and may open text while the fly is still, controllable and on the same
tile. Such text pays only if it names the person or sign the fly is facing, once per key; in the
early game none can (checked: the museum ticket man, the Route 22 and Route 5 guards, Viridian
Mart, Oak's Lab), and a few late ones can once each (the Fighting Dojo master, the Elite Four
after their battles). Review of 2026-09-23.
The catalog also includes catches. The honesty panel's copy is not data-driven from the catalog --
`apps/stage/src/lib/schedule.ts`'s rotating card is four written lines and lists no kinds -- so
there was nothing to regenerate and the copy is unchanged. The sentences below are where the
argument lives.
Paying for a catch does not move the fly: the ball is thrown by a macro the mushroom body chose
among the ones the battle scene put on the pad, and the payout is read out of WRAM after the
frame. What it does do is make one of the palette's existing macros worth choosing, which is the
same kind of pressure every other rule applies. The cap is what keeps it from becoming a farm: a
run that finds one patch of grass and throws balls at the same species all night earns 0.50 from
it and then nothing.
The catalog also includes exits. That is worth saying plainly on the honesty panel, because paying
for a door is closer to telling the fly where to go than paying for a badge is: for a door is closer to telling the fly where to go than paying for a badge is:
- **still no button path.** Nothing in the adapter chooses or biases a button. The reward is read - **still no button path.** Nothing in the adapter chooses or biases a button. The reward is read

View file

@ -1,176 +0,0 @@
# The behavioural scorecard
A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what
they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a
release plays *better or worse* than the one before it across the places the fly actually is. The
scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real
connectome with the macro layer, reduced to one JSON per release and compared release against
release by a test over the paired runs, never by a single run.
It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The
ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly.
```sh
export FLY_ROM=/path/to/the-cartridge # read, never copied
cargo build --release -p fly-scorecard # from services/flysim
fly-scorecard list # the set, resolved, each checkpoint's rung
fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes
fly-scorecard summary card.json # one screen of markdown
fly-scorecard compare old.json new.json # exit 1 when a metric regressed
fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE)
```
`--runtime session` (the default) runs the session composition the release cut over to
(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame
(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a
card from one runtime is comparable with a card from the other. From the same checkpoint and seed
the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard
run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer.
## The set
`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds
its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the
newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked).
`list` prints the rung each one stands on, from its reward ledger. The set has two or three
states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join
the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from
the environment is named on stderr and, with `--strict`, an error.
## Seeds
A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed
therefore chooses how many frames the brain's readout is ignored before the measurement starts
(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise
generator still advances, the game sees no button, and from the first measured frame the readout
is the brain's own: the run sits on a different point of its own trajectory. The idle frames are
not measured. The same seed twice is the same run.
## What a run reports
One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by
`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames.
| group | what |
| --- | --- |
| rungs | start, end, gained, the brain minute of each climb; reported per brain hour |
| places | the adapter's exploration count, start and end |
| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch |
| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) |
| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) |
| ratchet | rollbacks, split by game over and stall |
| macros | starts, done, blocked, timeout, refused, by macro |
| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got |
| heals | GO HEAL and the nurse's HEAL |
| whiteouts | the whole party fainted (a rising edge) |
| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other |
| rewards, scenes | counts and totals by adapter kind; frames by scene |
The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe
memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about
time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds,
first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or
the whole run when it is shorter; and the first probe compares the exploration count with the
run's starting count, which the live check lacks after a boot.
## Compare
`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`)
has a direction (more is better, less is better, or info), an absolute tolerance and a relative
one. For each metric the pairs give one difference, signed so that positive means B is worse. B
**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip
permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over
the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most
alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of
releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the
same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent,
and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a
fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The
comparison also names its caveats (different lengths, different runtimes, fewer than eight
pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint.
**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one
checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs
(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled
compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its
own, without statistics: it **fails**, named as `trap@<checkpoint>`, when B is trapped on at least
two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm
(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is
trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled,
zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with
three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center
on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap,
so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243.
Identical suites never fail.
The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per
hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and
lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's
flagged windows are reported, never judged: healing more can follow losing more, and a fly that
fights for most of a run presses NEXT through battle text more than ten times in two minutes,
which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so
the number has no room to move).
## Cost and size
A run's brain minute costs about 75 CPU seconds however it is split, and the result does not
depend on the thread count (the same seed gives an identical report at one thread and at four).
The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet
ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one
job of four threads ran five times slower per brain minute than one-thread jobs did. So the
default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by
three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten
quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let
rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001.
`--resume` keeps the runs an interrupted suite had finished (`<out>.runs.jsonl`).
## What it does not do
- It does not rebuild session ledgers a restore starts empty (the trap hunt's
`FLY_TRAP_SEED_*`); a trap that needs them is that tool's.
- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a
per-run prediction; a release that is faster by a rung every few hours shows only across the
suite.
- It judges play against the previous release, not against a notion of good. A regression is
"worse than last time"; the absolute numbers say how good last time was.
## Releases and nightly
`tools/scorecard/overlay.sh <ref> <tree>` puts the tool on the tree of an older release (the crate,
the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that
predates it can be scored and its numbers are its own. The operator's nightly runner builds the
latest release tag on a build box, runs the suite, writes the card and a one-screen summary and
compares with the previous release's card.
## The v0.7.5 baseline
`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8,
compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on
the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box.
| headline | v0.7.5 |
| --- | ---: |
| rungs per brain hour | 1.50 (9 of 36 runs climbed) |
| empty-pad time | 6.96% of frames |
| watchdog probes suspected | 2.8% |
| ladder-worthy traps | 1 (one run, `r09-forest-catch`) |
| blocked macro finishes | 0.5% |
| buy ball / throw / catch | 10 / 10 / 8 |
| heals / whiteouts | 9 / 46 |
| battles won / lost | 33 / 45 |
| ratchet rollbacks | 1 |
What the card shows about v0.7.5, worth reading before the next release is compared with it:
- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a
battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won;
46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on
`r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle.
- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three
seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT
alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The
watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery
step would act on it.
- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15.

View file

@ -640,413 +640,3 @@ then purge; then the stale-doc pass.
the party list and SWITCH the bag since v0.4.0; fixed, THROW BALL now 15/0 in the forest run. the party list and SWITCH the bag since v0.4.0; fixed, THROW BALL now 15/0 in the forest run.
ROM test fails on v0.4.3 and passes here. Ethos check held. Row 41 (a nurse box answered YES ROM test fails on v0.4.3 and passes here. Ethos check held. Row 41 (a nurse box answered YES
1,278 times) is next. 1,278 times) is next.
- 2026-09-22 (v0.4.5, loop review, auto): row 41. In the Pewter center the nurse's conversation is a
ring of 46 A presses with one YES/NO choice; the dialog pad dealt NEXT and YES unconditionally
(one press, two names) and TALK was bound over the counter but recorded one tile ahead, so the
nurse never entered the talked ledger: YES x2,142. Fixed: a readable prompt deals its answers with
NEXT off it, only the answer that changes something is bound, TALK is off at a rested nurse, the
nurse is talked after a heal or a decline, a prompt that reopens unchanged is excluded. ROM test:
leaves the center on frame 326. Hunt: 1 -> 437 tiles, YES 1,424 -> 4. Ethos check held.
- 2026-09-22 (session framework, wave 1): BUS slice merged. The flybus crate is audited section
by section against bus-v1 (195 rows: 178 conform, 9 allowed deviations each quoting the
sentence that permits it, 7 not implemented and owned), the teardown-versus-in-flight-poll
race is fixed (the write gate now separates "closing" from "a poll is in progress", so
teardown waits one poll instead of a frame), the BUS-01 to BUS-03 acceptance bullets are
named tests over both transports with a 29-event trace equivalence, and the guide's first
deliverable exists: one example with a counter RPC, a latest observer and a frame artifact
held past its message. Measured on the dev VM, not capacity claims: 640x480 RGBA at 60 Hz to
three consumers, one delayed, RPC p50 0.5-1.1 ms, seal p50 1.1-1.4 ms, router 0.18-0.22 cores,
RSS 11-17 MB. Two spec contradictions were resolved in bus-v1 rather than in the code (the
per-client byte budget now names bounded queues only, with latest slots capped separately;
the illustrative client sketch drops its budget argument for a caller-side deadline).
- 2026-09-22 (session framework, wave 1 complete): the CONTRACT and SESSION slices merged. There
is now one executable contract for the new architecture: a types crate and a matching
TypeScript package that read the same fixtures, RFC 8785 canonical JSON, a contract digest
generated from the schema set rather than from source formatting, the four identities typed so
they cannot be mistaken for one another, and two new specifications with test vectors for seed
derivation and the checkpoint envelope. On top of it a synthetic lockstep session runs over the
bus: fake agents, a counter world, identity executors and a deterministic task, stepping
prepare, advance, evaluate, commit in that order, with the rational clock proving 16, 17 and 17
ticks and a zero remainder, request deduplication that refuses a changed body and replays a
cached one, and the guide's failure injections as tests that compare an injected run against a
clean one on behaviour, mutation count and world counter. Reviews caught two defects worth
naming: a merge that stopped short of the TypeScript half, whose absence silently took its own
test gate with it, and an unchecked addition that would have wrapped in release. Both fixed
before merge.
- 2026-09-22 (v0.4.6, loop review, auto): two rollbacks on rung 10. The "BACK in a text box" was
a scripted overworld frame with no box (the cartridge holding the joypad) dealt NEXT/BACK; the
museum had no map-graph row so no hop reached the gym; a frontier behind the admission desk
never retired; the ratchet counted covered ground as no progress. Fixed: a scripted frame with
nothing drawn deals nothing; the museum rows are on the graph; an unreachable frontier is a
per-map mark; nearer the objective in map hops counts as progress. ROM test: museum to the gym
interior on 15 macros, TALK on the pad at the leader. The trap hunt did NOT improve on the
reviewer's criterion (tiles 193 -> 175, windows 59 -> 69) because the after arm reaches new
ground with a new trap (row 54: GO FRONTIER, GO HEAL, GO ROUTE cycling, GO HEAL x204 at net 0);
Fable shipped it anyway: the hunt criterion compares within ground both arms reach, and a trap on
newly opened ground is a new row, not a regression. Row 54 review started at once.
## 2026-09-22 - session framework wave 2
Per-fly processes and native observations landed on top of the wave-1 contract and
lockstep session.
- The session runs in three execution modes that share one coordinator, one worker and
one router: in process, one thread per participant, and one process per fly plus one
for the environment over Unix sockets. The worker is a subcommand of the existing
binary, not a new crate. A launcher owns the thread budget, proves each participant's
configured identity and allocation on the wire before the coordinator pins anything,
polls health on its own clock, and reaps its children.
- A caller deadline that expires no longer fails the epoch on its own. It runs the
contract's resolution procedure against the same request and the same incarnation, so
a merely slow participant completes its step, and the epoch fails only on a definite
refusal, a lost incarnation or an exhausted budget. Which of the two bounds ended a
resolution is recorded and named in the failure rather than inferred.
- Failures name the participant, and a failed session fences its epoch: the boundary
stops, handles are dropped, and no further transition or publication is possible.
Worker death, helper death, a router restart mid-advance and stale replies after a
restart all have bounded, diagnosed outcomes, each proved in every mode.
- The environment now emits native output: one shared RGBA frame per boundary reaching
both flies through owned attachments, and one audio chunk per transition on an exact
rational sample budget. Observation delay is a real queue, so nothing stale can be
substituted. Spectators watch a latest subscription with finite credits and cannot
perturb what the flies sense. Audio never enters sensory input.
- Every media rule is enforced rather than assumed: strides, dimensions, formats,
lengths, producing step, timeline continuity, and the distinction between a persistent
asset and a transient artifact. A missing or malformed frame or chunk fails its step.
- Three contract silences were closed by dated amendments rather than by convention: the
launcher's thread allocation is now on the wire in the worker's hello, the audio
discontinuity rule is one-directional, and a mid-step pause is defined.
Measured on the development box, not capacity claims: with two flies the critical path
per transition sat near 10 to 12 ms at the median across all three modes, so a process
boundary costs little at the median and shows in the tail. What the split costs is
memory, roughly 5.7 MiB per participant process, while the coordinator's own footprint
is flat and lowest once the workers leave it.
Two flaky bus tests predating this work assert timing rather than contract and are being
rewritten separately.
- 2026-09-22 (v0.4.7, loop review, auto): row 54 in Pewter and on Route 3. The player's coordinates
change at the END of a sixteen-frame step, so the whole-map grid refused every moving frame and
walks fell back to the window; a landing tile went unrecorded for fifteen frames and stayed a
frontier; an errand aimed at a door underfoot settled where it stood; the errand ledger was
session state and re-armed on restore. Fixed: the walk anchor is measured from the screen
neighbourhood, landing tiles retire, errands arrive inside facing the counter, the errand ledger
persists. Route 3's north edge is a survey item (table says west+east). From the Pewter checkpoint
the fly wins the Boulder Badge at 10.78 brain minutes. The hunt's flagged windows did not fall
(73/73) because 82% of the fixed run is battle time; Fable shipped it on the same judgement as
v0.4.6 and started row 50 (MOVE n blocked on an unresponsive move list). The on-screen chat ring
now survives a sim restart (sidecar in the hot dir, never in the checkpoint).
- 2026-09-22 (v0.5.0, the operator's decision): the fly is paid for keeping a wild Pokémon. New
catalog kind `catch` (0.30 for a species this run never caught, 0.10 for a repeat, three payouts
per species), read from the captured-species byte and the battle result together; the existing
species rule still pays on top. Adapter `pokered-unique8-v6`; the compatibility string differs
in the adapter segment only, and a deploy with `FLY_ACCEPT_ADAPTERS=pokered-unique8-v5` migrates
a v5 checkpoint instead of refusing it. `fly-reset-to-milestone <N>` restarts the run from a
ladder rung (archives both stores first). The live run restarts from rung 7 with this release, so
the ladder is climbed again with the catch reward and the row-54 walks in place.
- 2026-09-22 19:59 UTC (v0.5.0 deployed): rung 7 had no milestone archive (the ratchet passed it
inside one commit), so the run restarted from rung 8, VIRIDIAN CITY, with
`fly-reset-to-milestone 8`; the v5 checkpoint migrated to v6 as designed. The previous state is
archived beside the store.
## 2026-09-22 - session framework: what landed and what stopped
The session framework slices from docs/design/session-framework/implementation.md were built
in ordered waves, each on its own branch with an independent review before merge.
Landed on main: CONTRACT-01, BUS-01 through BUS-03, SESSION-01, SESSION-02, MEDIA-01,
STATE-01 and PUBLISH-01. Together they give the repo an executable session contract with a
TypeScript oracle, a conforming bus with a written conformance table, a lockstep session that
runs in process, on threads or as one process per fly, native frame and audio observations
with spectator isolation, a coherent all-participant checkpoint with group restore and a
liftable fence, and an internal publication boundary with committed snapshots over the same
bus. Every contract silence met on the way was closed by a dated amendment in the affected
document rather than by convention; none touched doctrine.
Also landed: the bus test suite asserts guarantees rather than the machine's timing, and a
coordinator defect found through one of those flakes is fixed, where a lifecycle
acknowledgement that legitimately releases nothing was treated as a fault.
Stopped: AGENT-01 and ENV-01 are blocked on FOUNDATION-02 and RUNTIME-01 from the MaleCNS
backlog, which do not exist yet. The profile contract and the environment boundary are
decisions for the operator, so the swarm stopped here. DOLPHIN-01 was never in scope.
Measured on the development box, not capacity claims: bus RPC near one millisecond at the
median; a two-fly transition near 10 to 12 ms at the median in every execution mode; about
5.7 MiB per participant process when split.
- 2026-09-22 (v0.5.1, loop review, auto): row 50. The cartridge never clears the move-list cursor
bytes after a turn, so every frame of a turn's text, animation and reply read as the fly's own
turn on an open list; the pad dealt MOVE 1-4 and BACK on all of them and the cursor step pressed
at a list nobody was reading. Surveyed by pressing: a press was honoured on 231 of 231 frames
where the menu box is drawn and on none where it is not. Fix: one gate on the drawn box in the
battle seam; a frame with no box is between turns, NEXT only. From the forest checkpoint MOVE n
blocked starts 838 -> 0, every battle entered is ended, worst battle 503 -> 283 macros; hunt
tiles up on both arms (296 -> 430 forest, 163 -> 184 Route 3), flagged windows again rise
because the fly is inside battles it is fighting (same judgement as v0.4.6). Next row: the
battle bag's list id outlives the bag the same way.
- 2026-09-22 (v0.5.2, loop review, auto): row 55, opened by the v0.4.7 errand change. A mart's
list id says the counter is open, not which screen is up, so the clerk's closing text box read
as an open buy list, and the buy list scrolls, so a stock position past the third row is never a
cursor index. BUY ANTIDOTE aimed at row 3 of a list reporting one row, blocked on frame 0 with
no button pressed, and was dealt again every hold. Fix: the shop screen is read from what the
game draws (a clerk's text box lists nothing, so a cursor step waits), and a purchase past the
three cursor rows is not on the pad. From the live checkpoint the fly leaves the mart in 0.19
brain minutes where it never left before; hunt tiles 1 -> 62, blocked starts 1,494 -> 82.
- 2026-09-23 (v0.5.3, loop review, auto): row 56, the Pewter Gym guide. His YES/NO box is drawn
at a different place from the one row 41 pinned, so the seam read no prompt on any of the
frames it was up, dealt NEXT beside YES and NO on a choice, and every NO un-armed the pending
TALK, so the guide never entered the talked ledger and his fifty-two-press ring ran for hours.
Fix: the two-option border is found around the cursor the game parks in it, read whole; which
kind a NO was is decided when the box closes. From the live checkpoint the fly leaves the gym
on frame 1,337 where it never left in twenty brain minutes; hunt tiles 83 -> 441, dialog frames
32,496 -> 2,849. Rung 11 is not reached on either hunt arm: GO OBJECTIVE is on the Pewter pad
and the fly picks the frontier instead, which is the fly's choice, not a trap. The watchdog's
distinct-macro rule cannot see a four-macro ring; the watcher's zero-progress check covers it.
- 2026-09-23 (v0.5.4, loop review, auto): row 57, Pewter City. The pad was GO ROUTE alone,
refused `no route` every 0.8 s for over two hours with no button pressed; the watchdog counted
starts only and saw one. Mechanism: the youngster's escort walls the tile each escorted walk
set out from, up to 26 tiles away, until the fly stands in a pocket no route leaves; every
refusal re-stamped the gym door's blocked window, so GO OBJECTIVE never came back. Fix: an
escort walls the tile where the script took over; a refusal that teaches the ledger nothing is
not dealt again from that tile for the window; a last resort that cannot reach the objective's
door takes a way out it can. ROM test: refusals in a row 746 -> 1, out of the pocket on frame
517 instead of 36,325; seeded hunt tiles 303 -> 439, flagged windows 70 -> 66 of 73 counting
refusals as decisions. Check 10 now counts outcomes (refused, blocked, done) and flags
`stalled` and `zero-progress`, still never acting. The GO OBJECTIVE / GO OUT ring at the gym
door is row 58. Ethos check held. While it cooked the operator's new unstick rule kept the
stream moving with flysim restarts (loop-review.md).
- 2026-09-23 (v0.5.5, loop review, auto): row 58, the Pewter Gym door. GO OBJECTIVE walked in,
GO OUT walked out, for hours, with no reward; restarts bought twenty to forty minutes each.
Mechanism: the objective's people were read from the sprites the cartridge draws, and from the
doormat Brock and the Jr. Trainer are off screen, so with the guide talked the rung had nobody
and the gym dealt its ways out. Three moments the game holds the joypad (a warp's first frames,
a trainer's challenge before the battle screen, a trainer walking up) wrote the fly's ledgers.
Fix: the objective reads off-screen people by the cartridge's own availability rule; facing any
of them is arrival; a warp's tear deals an empty pad (at most 90 frames); `controllable` reads
`wCurOpponent`; ledger writes wait for the joypad to come back and drop if a battle starts.
ROM test: base 40 arrivals, 38 straight back out; branch reaches Brock. Route survey from the
live checkpoint, 33 brain minutes: GO OUT 1,118 -> 0, rung 10 -> 11, BOULDER BADGE. The trap
hunt's stub readout never walks the ring on either arm (flagged 17 -> 23, all one-tile windows
in the gym's dialogs and battles; tiles 329 -> 437), so the proof is the ROM test and the
survey: the ethos check held in spirit, recorded as a deviation from the hunt's letter. Check
10 gains `unrewarded` (100+ decisions, no reward, no new ground, two probes), still never
acting. Also shipped: EDGE-01, the feed over flybus behind FLY_FEED_VIA, off (`direct`)
everywhere. Next: row 59, Route 3's neighbours and Mt. Moon's doors in the geography table.
- 2026-09-23 (the operator's reset): the live run restarted from milestone 1, the bedroom, with the
brain as it was then (65 brain seconds), to watch the macros in the early game. The v5 archive
migrated to v6. It reached rung 9, Viridian Forest, 31 minutes later.
- 2026-09-23 (v0.6.0, the operator's decision, plus loop review row 60): the fly is paid for
engaging inside buildings and not for leaving them. New catalog kinds `talk` (+0.10, the first
conversation the fly opens with each person or sign on an indoor map, once per key for the run)
and `item` (+0.15, each item ball or hidden item, once); `boundary` pays nothing for an indoor
exit. Indoor is the cartridge's own tables (not CheckIfInOutsideMap's outdoor tilesets and not a
bike tileset). Both publish on `explore`; the ticker still reads "new place" (the operator kept
the wording). Adapter `pokered-unique8-v7`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v6
migrates the run and seeds every item the game already shows taken without paying it. Row 60:
from the fresh run, TAIL WHIP (MOVE 2) was dealt beside TACKLE after the cartridge had begun
refusing it ("Nothing happened!": the stage at -6 or the stat at 1), and the brain's MOVE 2
preference drew battles out until Squirtle fainted. A move the cartridge would refuse -- read
from its move table and the target's stages, status, types, Mist and substitute -- is not dealt
beside one that works, as a move out of PP is not. ROM test: 2,657 of 2,657 own-turn frames dealt
the refused move before, 0 of 568 after; battles won 0 -> 3 of 12 -> 14. The real-brain hunt did
not finish at this load; recorded as a deviation. Ethos check held.
- 2026-09-23 (v0.6.1, loop review, auto): row 59, Mt. Moon. With the Boulder Badge the live fly
reached rung 12 and rang on Route 4 (GO ROUTE 233, GO OBJECTIVE 122, GO OUT 111 per ten minutes,
one new tile), and restarts did not hold: the map graph was wrong, not a ledger. The geography
table is now the cartridge's own headers and warps: Route 3 connects north to Route 4, Mt.
Moon's doors are on Route 4 (1F at (18,5), B1F's exit at (24,5)); Routes 14/15 and 24/25 were
in the wrong compass columns and Routes 22/23 were missing; a map can be several pieces (Route
4 two, Mt. Moon B1F four chambers, B2F three), the fly's piece read from the decoded grid and a
warp landing in the piece that holds its destination; sea and fence connections (Pallet/21,
Cinnabar/20, 20/19, 22/23) are no longer exits. A trainer's challenge leaves five frames of
plain overworld before the battle, and a push-back is now written only after thirty frames of
the fly's own. From the live Route 4 checkpoint: crossings of the west doors 56 -> 13, into Mt.
Moon at frame 278; from the badge checkpoint the fly reaches Mt. Moon and rung 12 where the base
rang at Pewter. The reviewer checked all 36 connection rows and every piece against the
disassembly. The trap hunt was not run at this load (recorded deviation). Also shipped: FND-01,
one LegacyFrame for the service and every harness (no live behaviour change), FLY_TRACE and the
sugar journal. Ethos check held.
- 2026-09-24 (v0.6.2, loop review, auto): row 61, the Viridian Forest corridor. In the fresh run the
fly rang between the forest, its south gate and Route 2 (GO OBJECTIVE / GO OUT / GO ROUTE) for
twenty minutes at rung 9. A Bug Catcher stands on the forest's only corridor north; when he saw
the fly, the frames of his "!" bubble and the five frames between his text and the battle read as
the fly's own overworld, and a held push-back walled (1,18) for good, so GO OBJECTIVE had no road
north. The macros now read the cartridge's BIT_TRAINER_BATTLE (wStatusFlags7 bit 3, set at the
"!", cleared after every battle, a lost one too) and treat those frames as the cartridge's: no
pad, no ground recorded, no push decided. Row 59's 30-frame debounce already closed the five-frame
gap; this is the cartridge-fact layer under it. ROM test: base walls (1,18) and stays at rung 9;
branch reaches Pewter on frame 23,755, and offers no button on any of the 67 challenge frames
(67 of 67 before). Survey seed 7: rung 9 -> BOULDER BADGE. The trap hunt's stub cannot see this
trap; the ROM test and survey are the proof (recorded deviation). Ethos check held.
- 2026-09-28 (v0.6.4, infra + stage, auto): automatic loop recovery that climbs. The v0.6.3 timer
only restarted flysim, once an hour; a trap that outlives a restore (Mt. Moon, rung 12, GO
OBJECTIVE / GO WARP) was restarted 48 times in two days. `fly-loop-recover` now climbs a ladder
per confirmed trap that outlives the last step: restart flysim, reset to the current rung's
milestone, reset to the rung below the best (never lower); two resets a day, restarts three
hours apart once they are spent; it starts over at a new best rung or after six quiet hours, and
its state survives a reboot. A router model list confirms each step and can delay it three
probes, never deny it. Resets go through one root wrapper (`fly-loop-reset`) that runs only a
root-owned flysim identical to the running one, uses only archives this build can restore,
and pauses the watchdog for the reset. Every step is announced 60 s ahead on stream: the
recovery splash counts down over the stuck loop, covers the game while it acts, and reports the
result (`apps/stage/mockups/`). Independent review: BLOCK, then fixed; round 2 approved with
the watchdog wait fixed.
- 2026-09-28 (bridge, unreleased): chat died for hours after an unrelated bridge outage outlived
both access tokens (~4 h) and the next start failed `validate` with 401 in a crash loop, with
both refresh tokens still good. Closes the v0.2.3 debt: on load, a stored token expired by its
timestamps or rejected with 401 is refreshed once through its role's provider before giving up,
and every refresh is persisted under its own role (serialized atomic 0600 writes), so both roles
survive when they are one account. Only a refresh Twitch refuses is fatal, one line pointing at
the runbook's re-authorize step; Twitch errors are logged without URLs, tokens or the secret.
- 2026-09-29 (v0.6.5, loop review, auto, plus infra/stage): the two-day Mt. Moon trap and what the
merge of its fixes surfaced. Row 64: the fly stood on B2F's exit ladder (5,7), the only road on;
GO OBJECTIVE and GO WARP both aimed at the tile underfoot and reported done without a step, and
the cartridge fires a ladder only at the end of a step onto it (1,500 of 1,500 macros from the
checkpoint, no ledger involved, so 48 restarts restored it). A walk standing on its warp now steps
off and back on; Route 4's ledges are one-way hops the route search takes (they read as walls,
so the road to Cerulean was "no route"); a way out that leaves the fly on its own map is not done
(the effect-based guarantee against in-place rings). The operator's GO WARP / GO FRONTIER
exhaustion lead was checked and refuted (GO WARP 25,554 starts; the frontier correctly spent).
Row 62 round 2 (shop, balls, nurse): no GO HEAL east of Mt. Moon, no service out of the rung's
room; Pewter buys a ball. Row 63: a confirming A waits for the cartridge's release (ITEM/BACK
with a usable Potion). Row 65: the merge of 62+63+64 failed row 59's ROM test (a Mt. Moon 1F
mouth door ring, 34 crossings) and review found a Cerulean badge-house yard stall; both fixed.
The release gate now refuses to run without FLY_ROM: the ROM suites had been passing vacuously
whenever it was unset, v0.6.4's gate included. Also: recovery timer every minute, the splash's
approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and
redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63,
64, 65 APPROVE-WITH-NOTES.
- 2026-09-29 (v0.6.6, loop review + port foundation): the fly shops, throws and names what it
catches. Row 66: a counter walked away from is not walked back to for the ledger window (the
GO SHOP/GO OUT re-entry ring: 31 to 0), BUY BALL is one walk-talk-buy button like HEAL (the
operator's call; offered in a mart that sells balls, with no ball and 200 in the wallet), and a
closed battle bag is not the pad (post-catch presses typed the nickname). Row 67: the live fly
lost the Pewter Gym's Jr. Trainer 29 times in a row choosing TAIL WHIP (the pad offered every
move); a report-only `unwon-battles` watchdog reason lets the recovery ladder act 45 minutes
sooner, and the no-PP ROM test is fixed (Struggle is the cartridge's answer). Row 69 (the
operator's calls): in a wild battle at the catch formula's low-HP threshold with a ball in the
bag, THROW BALL is the only attack-side button; the naming screen takes the fly's own buttons
("AAAAAAAAAA" before), bounded by CONFIRM after a full name or 60 brain seconds. Port
foundation merged, dormant on the stream: AGENT-01, MEM-01, ENV-01, STATE-02 (the checkpoint
store is now the shared `flysim-store` crate; FLYSIM01 gains an optional `reinforcements`
field, downgrade-safe both ways). A PII guard scans lint, tag-release and pushes. Reviews: all
APPROVE-WITH-NOTES.
- 2026-09-29 (unreleased, the operator's decision, row 68): the fly is paid for the HP its own
attack removes in battle, the catalog's answer to row 67 (the Pewter Gym's Jr. Trainer lost on
repeat with TAIL WHIP six turns in seven). New kind `damage`: 0.20 per whole enemy Pokémon, in
proportion, +0.05 when it knocks out a trainer's Pokémon, at most 0.50 a battle; a wild battle at
1, 1/2, 1/3 per map/species/level. Only a drop on the fly's own turn (`hWhoseTurn` 0) by a move it
chose (not Struggle); a heal is never paid twice; no feed counter (a hit is not a "wild win").
Adapter `pokered-unique8-v8`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 migrates the
run (v6 still migrates when named). Survey, 3 starts x 120 brain minutes from the row 67
checkpoint: v8 beat the trainer in 2 of 3 (one run also won the Boulder Badge), v7 in 0 of 3, but
the move choice did not shift more under v8 than v7 (BUBBLE ~15% -> ~20% in both): no learned
preference is shown inside two hours (`infra/docs/macros-traps.md` row 68).
- 2026-09-30 (v0.6.7, the operator's call, reward catalog): the fly is paid for damage its own
attacks deal. Row 67 found the live fly losing the Pewter Gym's Jr. Trainer on repeat with TAIL
WHIP while BUBBLE was on the pad; the operator chose a reward over a pad rule. HP removed on the
fly's own turn (hWhoseTurn 0, not Struggle; poison/burn/Leech Seed/recoil/enemy moves never pay;
healed HP not re-paid) pays 0.20 per whole enemy mon, +0.05 for knocking out a trainer's mon,
capped at 0.50 per battle (a trainer beaten); wild battles diminish 1, 1/2, 1/3 per
map/species/level. Adapter pokered-unique8-v8, migrating v7 (compat differs in the adapter
segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO").
Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift
within two hours. Review: APPROVE-WITH-NOTES.
- 2026-09-30 (v0.7.0, the port): the flybus session runtime ships beside the legacy loop, installed
and not selected. AGENT-01 (the brain as a worker), MEM-01 (the macros read a 64 KiB memory image
with the same engine), ENV-01 (the Game Boy as a worker), STATE-02 (one checkpoint store for
both runtimes, FLYSIM01 of record), TASK-01 (the macros in the coordinator), PERF-01 (an
in-process local lane: the session costs ~1.3x legacy per frame, down from 2.45x), SERVE-01
(`flysim-session` serves the same feed/control/metrics contracts; `fly-runtime session|legacy`
swaps the binary behind flysim.service; a crash loop falls back to legacy by itself), SHADOW-01
(`fly-shadow` replays the live fly's trace through the session runtime and compares every
transition, ledger and save byte; a baseline-relative guard stops it if the live fly suffers),
CUT-01 (the switch is a 30-minute speed probation: a median realtime factor under 0.97 falls back
with reason "speed"). Deploying changes nothing live: legacy's output is byte-identical to
v0.6.7. Cutover is `fly-shadow-run check && fly-runtime session` after three hours of zero
divergence; rollback is `fly-runtime legacy`. Every slice and the release candidate were
independently reviewed (APPROVE-WITH-NOTES).
- 2026-09-30 (v0.7.1, loop review hotfix): row 70. The fly's first live catch (a Zubat, Mt. Moon)
gave it a second party member, and in the next trainer battle the cartridge's SHIFT-style offer
"Will ZUBAT change POKéMON?" opened the battle party list with the same menu id as a forced
switch after a faint. Read as forced, the pad was SWITCH (no healthy target) and NEXT ("ZUBAT is
already out!", the list again) for 58 brain minutes; the recovery ladder's rung-11 reset erased
the catch and, restores being deterministic, replayed the path back into the trap. A forced
switch now also requires the active battler at 0 HP; the offer is the fly's own turn with SWITCH
and BACK. ROM test from the live checkpoint: NEXT on all 6,000 frames before, BACK and the battle
continues after; a real post-faint switch unchanged. The ladder change (protect recent catches
from resets) is held back for a review finding. Review: APPROVE.
- 2026-10-01 (v0.7.2, loop review): row 70's recovery ladder. A milestone reset within 2 hours of a
new species becomes a restart (operator decision: a catch is worth up to 2 h of a trap, not more);
a reset's deterministic replay re-earns rewards the restored archive already had, so progress and
catch protection now count only reward names the ladder has not seen; a held reset does not climb;
the last-archive marker expires. Escape from a trap only the lower rung clears: 2.08 h (as v0.7.0),
3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at
most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK,
r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES.
- 2026-10-01 (v0.7.3, port slice SHADOW-02): the shadow moves off the release container. On the
container a light relay forwards the live trace, new saves and the sugar journal over one outbound
ssh link whose key can only run the receiver; a build box mirrors them and runs the unchanged
shadow on its own cores; the verdict comes back. Release binding by binary hashes; the relay's
heartbeat is fresh only while the link, the box's shadow and the sync are; any trace stop (no
consumer, byte cap, outage) ends the verdict window, so a pass needs 3 h of compared brain time
after the last loss. The guard and `check` stay on the container. The on-box shadow (v0.7.0)
slowed the live fly; the relay costs about 0.5% of a core. Reviews: BLOCK, BLOCK,
APPROVE-WITH-NOTES, APPROVE.
- 2026-10-01 (v0.7.4, loop review hotfix): row 71. On Route 24 (rung 15) the fly met a wild
Oddish at low HP with two Poké Balls in a bag that had grown to five items (TMs, HELIX FOSSIL,
NUGGET), so the ball was the fifth entry and the list scrolled. The macro state read the bag
cursor as the window row only, so THROW BALL could never reach the ball and was blocked every
time; row 69's low-HP rule left it the only card. A restart restores the open bag, so the ladder
could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge
computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before,
Oddish caught after. Review: APPROVE.
- 2026-10-01 (v0.7.5, port slice PERF-02): the first cutover (v0.7.3, after a 3 h shadow with zero
divergence) failed its speed probation at a median 0.959x real time and fell back to legacy on
its own. Cause: with exactly as many CPUs as sweep threads, the session's other threads woke each
frame and the scheduler often stacked two sweep threads on one CPU. flysim-session now pins each
sweep worker to its own CPU and its other threads to the remaining one (16.2 to 13.0 ms a frame on
a build box of the release CPU; legacy 10.5), and the sim gets its own slice: every other unit,
user session and `pct exec` shell is confined off its CPUs (a hog there collapsed a pinned
session). Results, traces and the compatibility string are unchanged. Reviews: two rounds,
APPROVE-WITH-NOTES; notes addressed.
- 2026-10-01 20:07Z (CUT-01, milestone M4): the stream runs on the session runtime. v0.7.5's remote
shadow compared 3 h of live brain time (645,560 transitions, 2,161 identical checkpoints) with
zero divergence; `check` allowed the switch; the 30-minute speed probation passed at a median
1.000x real time with no lag growth. Legacy stays one command away (`fly-runtime legacy`);
RETIRE-01 after a clean week.
- 2026-10-02 (v0.7.6, flybus groundwork, nothing switched): the control API as flybus RPC with
per-agent grants (CTRL-01, `FLY_CONTROL_VIA`), the video feed over the bus in production form
(EDGE-02, `fly-feed bus|direct`), the session's agent and world as processes on the router's
Unix sockets (BUS-01, `fly-runtime session --bus`), an optional aux cpu for bus threads off the
sim's cores, and a per-frame work metric for both runtimes. All default off; the live stream
is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural
scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the
parity test's idle-header race.
- 2026-10-02 07:13Z: the stream's video feed runs over flybus (`fly-feed bus`, one aux cpu for the
bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about
14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime
factor unchanged at about 1.0. Rollback: `fly-feed direct`.
- 2026-10-02 07:41Z: the control API runs over flybus too (`FLY_CONTROL_VIA=bus`): `:7401` is
served by the control edge calling flysim's RPC services under per-client grants. First 15
minutes: bus connected, calls flowing, no failures, no restarts, realtime factor about 1.0.
Both switches are in the host env, so a deploy keeps them. The session's agent and world stay
on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the
release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there.
- 2026-10-02 (v0.7.7, loop review): row 73. The scout found rung 16 unreachable: its place was
"on Route 25", so inside Bill's house the walks just left again, and Bill's PC is a hidden
object no macro could press. Rung 16 is now Bill's errand inside the house (people first, then
things; exits off the pad while the errand waits), and hidden objects are read from the
cartridge's own table and become a target only as that errand's next step. Cerulean's north half
joins the map graph through the trashed house. Trap hunts: rung 16 in 0 of 6 seeds before, 6 of 6
after; Route 5 from the ticket 0 of 6 before, 5 of 6 after. Review: APPROVE-WITH-NOTES; notes
fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a
wall-clock rate.
- 2026-10-02 (v0.7.8, groundwork for the GPU and the bus): the GPU brain steps a whole frame per
call with its state resident on the card (about 230 KB a frame crosses PCIe instead of 24 MB),
bit-exact against the CPU through rollback, restore and checkpoints; a dead GPU makes the process
CPU-only and the replacement restores the last checkpoint on the CPU (cuda feature, off; operator
decision: the live brain moves to the release host's Quadro after a 3 h shadow). Cheaper flybus
round trips (seal on reply, recycled zero-filled staging writers, frames encoded once); the
session's own transport stays on the in-process lane. No behaviour change on the live stream.

View file

@ -18,10 +18,7 @@ need pct
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \ PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \
ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \ ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo \ fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo"
openssh-client"
# openssh-client (SHADOW-02): the remote shadow's relay dials OUT to a build box. The client only;
# the container still runs no sshd (below).
# Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage # Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl` # needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three # (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three

290
infra/05-deploy.sh Normal file → Executable file
View file

@ -46,13 +46,6 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[ $# -ge 1 ] || die "usage: $0 ENVFILE [RELEASE_TARBALL]" [ $# -ge 1 ] || die "usage: $0 ENVFILE [RELEASE_TARBALL]"
load_env "$1" load_env "$1"
# flybridge refuses to start on an empty GAME_TITLE, and the generated fly.env below writes the
# variable whether or not the env file sets it. It only reads the file at start, so a missing
# value surfaced as dead chat at the next reboot, a day and a deploy later (2026-09-28). A release
# with a channel therefore needs the title before anything is touched.
if [ "$ROLE" = release ] && [ -n "${TWITCH_CHANNEL:-}" ] && [ -z "${GAME_TITLE:-}" ]; then
die "TWITCH_CHANNEL is set but GAME_TITLE is empty in $1: flybridge would refuse to start. Set GAME_TITLE (infra/env/example.env)."
fi
RELEASE_TARBALL="${2:-}" RELEASE_TARBALL="${2:-}"
# The label this script writes into the files it GENERATES (/etc/fly/fly.env, # The label this script writes into the files it GENERATES (/etc/fly/fly.env,
@ -119,27 +112,6 @@ fi
require_pve_host require_pve_host
need pct need pct
# Who serves the feed (docs/design/flybus.md): refused here, before section 1 flips
# /opt/fly/current, rather than half way through the deploy or at flysim's boot.
FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
|| die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'"
# Who serves the control API (docs/design/flybus.md, "Control over the bus"): the same.
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
# container is not in the env file unless the operator put it there, and this deploy writes the env
# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at
# their next start, so the feed stays served either way) but the mode would change at the next
# restart of flysim, which is not what anyone meant. Said once, loudly, here.
FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \
| tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then
log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \
"this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \
"If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both."
fi
# CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a # CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a
# `vgl` on a container that never had VirtualGL installed would only show up as # `vgl` on a container that never had VirtualGL installed would only show up as
# flystage refusing to start, i.e. a black stream, minutes after the deploy # flystage refusing to start, i.e. a black stream, minutes after the deploy
@ -197,26 +169,13 @@ NEED_RELOAD=0
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}" RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}" ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the
# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing.
SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}"
case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac
SESSION_AUX_LIST=""
DEPLOY_CPUS="" DEPLOY_CPUS=""
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to
# flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
PARTITION_ACTIVE=0
if [ -n "${CPUSET:-}" ]; then if [ -n "${CPUSET:-}" ]; then
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \ deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)" "/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \ read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
PARTITION_ACTIVE=1
if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then
_aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1
read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split"
fi
log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim" log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim"
else else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \ log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -227,36 +186,6 @@ else
log "05-deploy: CPUSET unset — heavy in-container steps run unpinned (no partition configured)" log "05-deploy: CPUSET unset — heavy in-container steps run unpinned (no partition configured)"
fi fi
# Whether the only difference between two compatibility strings is the adapter
# segment, and FLY_ACCEPT_ADAPTERS names the adapter the live checkpoints carry.
#
# The bash half of flybrain_gb::compatibility::decide, which is what flysim
# itself applies at restore. Both have to agree: a gate that let a deploy
# through and a flysim that then refused every checkpoint would be the black
# stream this whole section exists to prevent. The string is
# {kernel}/{adapter}/{fingerprint}/{plasticity}/binjgb:{rev}/pokered:{commit}/statefmt:{id},
# so the adapter is segment 1 and nothing else may move.
adapter_migration_accepted() {
local live="$1" new="$2" accepted="$3"
local -a live_parts new_parts
IFS='/' read -r -a live_parts <<< "$live"
IFS='/' read -r -a new_parts <<< "$new"
[ "${#live_parts[@]}" -eq "${#new_parts[@]}" ] || return 1
local i differing=0 index=-1
for ((i = 0; i < ${#live_parts[@]}; i++)); do
if [ "${live_parts[$i]}" != "${new_parts[$i]}" ]; then
differing=$((differing + 1))
index=$i
fi
done
[ "$differing" -eq 1 ] && [ "$index" -eq 1 ] || return 1
local entry
for entry in ${accepted//,/ }; do
[ "$entry" = "${live_parts[1]}" ] && return 0
done
return 1
}
# cpu_pin CMD [ARGS...] — run CMD inside the container on the page cpus. # cpu_pin CMD [ARGS...] — run CMD inside the container on the page cpus.
# Falls through to a plain ct_exec when no partition is configured, so this is # Falls through to a plain ct_exec when no partition is configured, so this is
# a no-op on an unpartitioned container rather than a new failure mode (a # a no-op on an unpartitioned container rather than a new failure mode (a
@ -308,21 +237,6 @@ if [ -n "$RELEASE_TARBALL" ]; then
cpu_pin chown -R fly:fly "$release_path" cpu_pin chown -R fly:fly "$release_path"
fi fi
# A root-owned flysim for fly-loop-reset, which runs as root and so must never execute the
# fly-owned copy above (the fly account could replace it). Taken from the tarball on the host
# and checked against the tarball's own MANIFEST on every deploy, so a release installed by
# an earlier deploy is covered too.
log "05-deploy: installing a root-owned flysim at /opt/fly/sbin/flysim for fly-loop-reset"
root_flysim="$(mktemp)"
tar -xzOf "$RELEASE_TARBALL" ./flysim > "$root_flysim"
want_sha="$(tar -xzOf "$RELEASE_TARBALL" ./MANIFEST | awk '$2 == "flysim" || $2 == "./flysim" {print $1; exit}')"
[ -n "$want_sha" ] && [ "$(sha256sum "$root_flysim" | cut -d' ' -f1)" = "$want_sha" ] \
|| { rm -f "$root_flysim"; die "the tarball's flysim does not match its MANIFEST; not installing /opt/fly/sbin/flysim"; }
ct_exec "$CTID" -- install -d -o root -g root -m 0755 /opt/fly/sbin
ct_push_file "$CTID" "$root_flysim" /opt/fly/sbin/flysim.new 0755
ct_exec "$CTID" -- sh -c 'chown root:root /opt/fly/sbin/flysim.new && mv -f /opt/fly/sbin/flysim.new /opt/fly/sbin/flysim'
rm -f "$root_flysim"
log "05-deploy: overlaying infra-owned stage/serve.{mjs,sh} (docs/design/infra.md's 'own tiny static server' clarification)" log "05-deploy: overlaying infra-owned stage/serve.{mjs,sh} (docs/design/infra.md's 'own tiny static server' clarification)"
converge_file "$CTID" "$INFRA_DIR/config/serve.mjs" "${release_path}/stage/serve.mjs" 0644 fly:fly >/dev/null converge_file "$CTID" "$INFRA_DIR/config/serve.mjs" "${release_path}/stage/serve.mjs" 0644 fly:fly >/dev/null
converge_file "$CTID" "$INFRA_DIR/config/serve.sh" "${release_path}/stage/serve.sh" 0755 fly:fly >/dev/null converge_file "$CTID" "$INFRA_DIR/config/serve.sh" "${release_path}/stage/serve.sh" 0755 fly:fly >/dev/null
@ -344,22 +258,9 @@ if [ -n "$RELEASE_TARBALL" ]; then
# BEFORE the symlink moves. Cost: one dataset load, a second or two. # BEFORE the symlink moves. Cost: one dataset load, a second or two.
# #
# FLY_RESET_STATE=1 is the deliberate override: it archives the durable # FLY_RESET_STATE=1 is the deliberate override: it archives the durable
# checkpoints (kept, never deleted) and clears the tmpfs hot ring — the hot # checkpoints (kept, never deleted) and clears the tmpfs hot ring, so the
# checkpoints and the on-screen chat ring's sidecar — so the new build warms # new build warms up fresh. Everything learned so far is thrown away, which
# up fresh. Everything learned so far is thrown away, which is why it is not # is why it is not the default.
# the default.
#
# FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps
# the run. It names adapter version strings whose checkpoints the new build
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 for the deploy
# that adds the damage reward (v8; v6 -> v7 was the engagement rewards', v5 -> v6
# the catch reward's).
# It only applies when the adapter segment is the
# ONLY difference between the two strings and the new build's adapter says it
# can read that one; a dataset, kernel, emulator or state-format change is
# still a refusal, because none of those has a migration. The same variable is
# written into /etc/fly/fly.env below, so flysim applies the same rule at
# restore that this gate applied at deploy.
# ----------------------------------------------------------------------- # -----------------------------------------------------------------------
state_dir="${FLY_STATE_DIR:-/srv/fly/state}" state_dir="${FLY_STATE_DIR:-/srv/fly/state}"
hot_dir="${FLY_STATE_HOT_DIR:-/run/fly/state}" hot_dir="${FLY_STATE_HOT_DIR:-/run/fly/state}"
@ -385,11 +286,6 @@ if [ -n "$RELEASE_TARBALL" ]; then
log "05-deploy: no decodable checkpoint in ${state_dir} — nothing to compare, continuing" log "05-deploy: no decodable checkpoint in ${state_dir} — nothing to compare, continuing"
elif [ "$new_compat" = "$live_compat" ]; then elif [ "$new_compat" = "$live_compat" ]; then
log "05-deploy: checkpoint compatibility matches the live state, the new build will restore it" log "05-deploy: checkpoint compatibility matches the live state, the new build will restore it"
elif [ -n "${FLY_ACCEPT_ADAPTERS:-}" ] \
&& adapter_migration_accepted "$live_compat" "$new_compat" "$FLY_ACCEPT_ADAPTERS"; then
log "05-deploy: FLY_ACCEPT_ADAPTERS=${FLY_ACCEPT_ADAPTERS} — the adapter version is the only difference, and it is named; the run is KEPT and migrated"
log "05-deploy: live: $live_compat"
log "05-deploy: new: $new_compat"
elif [ "${FLY_RESET_STATE:-0}" = 1 ]; then elif [ "${FLY_RESET_STATE:-0}" = 1 ]; then
archive="${state_dir}.$(date -u +%Y%m%d%H%M%S)" archive="${state_dir}.$(date -u +%Y%m%d%H%M%S)"
log "05-deploy: FLY_RESET_STATE=1 — compatibility CHANGED, archiving the durable state to ${archive} and clearing the hot ring" log "05-deploy: FLY_RESET_STATE=1 — compatibility CHANGED, archiving the durable state to ${archive} and clearing the hot ring"
@ -398,17 +294,13 @@ if [ -n "$RELEASE_TARBALL" ]; then
# state_dir is its own mountpoint, so the directory itself cannot be # state_dir is its own mountpoint, so the directory itself cannot be
# renamed; its contents move instead. # renamed; its contents move instead.
ct_exec "$CTID" -- sh -c "mkdir -p '$archive' && mv '${state_dir}'/*.checkpoint '${state_dir}/manifest.json' '$archive'/ 2>/dev/null; chown -R fly:fly '$archive'" ct_exec "$CTID" -- sh -c "mkdir -p '$archive' && mv '${state_dir}'/*.checkpoint '${state_dir}/manifest.json' '$archive'/ 2>/dev/null; chown -R fly:fly '$archive'"
ct_exec "$CTID" -- sh -c "rm -f '${hot_dir}'/*.checkpoint '${hot_dir}/manifest.json' '${hot_dir}/chat-ring.json' 2>/dev/null; true" ct_exec "$CTID" -- sh -c "rm -f '${hot_dir}'/*.checkpoint '${hot_dir}/manifest.json' 2>/dev/null; true"
else else
die "05-deploy: REFUSING to deploy release ${version}: its checkpoint compatibility string does not match the live state in ${state_dir}, so flysim would refuse every checkpoint there and then refuse to start at all — a black stream. die "05-deploy: REFUSING to deploy release ${version}: its checkpoint compatibility string does not match the live state in ${state_dir}, so flysim would refuse every checkpoint there and then refuse to start at all — a black stream.
live state: ${live_compat} live state: ${live_compat}
new build: ${new_compat} new build: ${new_compat}
The difference is usually an adapter/ladder or dataset version bump. Three ways forward: The difference is usually an adapter/ladder or dataset version bump. Two ways forward:
* deploy a build whose string matches (check out the commit the running release was built from), or * deploy a build whose string matches (check out the commit the running release was built from), or
* if the ADAPTER VERSION is the only segment that differs and the new build documents a
migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7). The run is kept; flysim applies the same
rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or
* accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which * accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which
archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and
clears ${hot_dir} so the new build warms up fresh. clears ${hot_dir} so the new build warms up fresh.
@ -416,53 +308,6 @@ The 'current' symlink has NOT been moved; the running release is untouched."
fi fi
fi fi
# The session runtime (SERVE-01). While `fly-runtime session` has pointed flysim.service at
# flysim-session (the drop-in below), a release without that binary would leave the fly
# unable to start at all, and one whose session string differs from flysim's would write
# checkpoints the other runtime refuses. Refused here, before the symlink moves; to deploy
# such a release anyway, `fly-runtime legacy` first.
#
# Policy (C2 of the SERVE-01 review), operator decision 2026-09-29: "Session stays, trust gates".
# A deploy KEEPS the chosen runtime. It does not drop to legacy and does not re-run
# the shadow for the new flysim-session binary; the trust gates before the release (the
# parity and service tests, the compat check just below) are what vouch for it. A bad
# release is caught afterwards by the persistent fallback: while the drop-in exists,
# flysim.service carries OnFailure=fly-runtime-fallback.service and RestartMode=direct with a 3-starts-in-10-minutes
# limit, so a session binary that will not stay up puts the fly back on legacy by itself
# (`fly-runtime fallback`, /run/fly/runtime-fellback.json), whoever restarted it.
if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/flysim-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime (fly-runtime session) and this release has no flysim-session. Run \`fly-runtime legacy\` in the container first, or deploy a release that ships it. The 'current' symlink has NOT been moved."
# BUS-01: on the bus transport flysim-session starts its participants from fly-session.
if ct_exec "$CTID" -- grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/fly-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime on the bus (fly-runtime session --bus) and this release has no fly-session worker. Run \`fly-runtime session --local\` in the container first. The 'current' symlink has NOT been moved."
fi
session_compat="$(ct_exec "$CTID" -- env \
"FLY_GAME=${GAME}" \
"FLY_DATASET=${release_path}/data/fafb-v783" \
"FLY_ROM=/srv/fly/rom/${ROM_SHA256:-none}.gb" \
"${release_path}/flysim-session" --print-compatibility 2>/dev/null | tr -d '\r' || true)"
if [ -n "${new_compat:-}" ] && [ "$session_compat" != "$new_compat" ]; then
die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime and its compatibility string differs from flysim's.
flysim: ${new_compat}
flysim-session: ${session_compat}
The 'current' symlink has NOT been moved."
fi
log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string"
fi
# The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's
# ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed.
# Refused when the env file asks for bus, and when the container is in bus mode now (an edge
# that is running keeps running, but the first time it restarts there is nothing to start; and
# the way back is `fly-feed direct`, which needs no binary of this release).
if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then
ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \
|| die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved."
log "05-deploy: the feed is on the bus; this release ships fly-edge"
fi
log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically" log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically"
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current" ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
else else
@ -473,7 +318,7 @@ fi
# 2. systemd units # 2. systemd units
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging systemd units" log "05-deploy: converging systemd units"
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.slice "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
[ -f "$f" ] || continue [ -f "$f" ] || continue
name="$(basename "$f")" name="$(basename "$f")"
changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)" changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)"
@ -518,7 +363,6 @@ log "05-deploy: non-secret env files"
# never drift apart (see cpuset_partition's own header comment). They are # never drift apart (see cpuset_partition's own header comment). They are
# assigned in section 0b, which needs them earlier than this for the # assigned in section 0b, which needs them earlier than this for the
# deploy-time cpu pinning; nothing between here and there changes them. # deploy-time cpu pinning; nothing between here and there changes them.
tmp_fly_env="$(mktemp)" tmp_fly_env="$(mktemp)"
tmp_flypush_env="$(mktemp)" tmp_flypush_env="$(mktemp)"
trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
@ -589,10 +433,6 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# so FLY_ENCODER-style flipping between backends across restarts keeps the # so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move. # checkpoint: the compatibility string this script gates on does not move.
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}"
# Where the session worker writes fly_brain_backend (which hardware runs the
# LIF tick, and the GPU fallback count): the same textfile directory as
# fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA").
echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom"
# On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the
# kill switch: POST /chat answers 403 and the feed header omits `chat`, so # kill switch: POST /chat answers 403 and the feed header omits `chat`, so
# the CHAT panel blanks without touching flybridge or the page. flysim reads # the CHAT panel blanks without touching flybridge or the page. flysim reads
@ -608,40 +448,7 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# refuses anything but "raw" for a game with no macros, reads the retired # refuses anything but "raw" for a game with no macros, reads the retired
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised # "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
# value outright. # value outright.
# PERF-02: flysim-session pins its sweep workers one per cpu of the cpuset it finds. That is only
# safe when the cpuset is the sim's alone: with the partition in force (section 3b) it is, and
# bin/fly-cpu-confine keeps every other process off it. Without it (no CPUSET, or a conf that does
# not match) the unit sees the container's whole cpuset, where a pinned worker would sit on a cpu
# anything can hog (measured 0.14x real time), so pinning is turned off: the threads float. The
# runtime reads the exact value 0 as off.
if [ "$PARTITION_ACTIVE" -eq 1 ]; then
echo "FLY_SESSION_PIN=1"
else
echo "FLY_SESSION_PIN=0"
fi
# EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set.
if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then
echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}"
fi
echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}" echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as
# every release before this knob. "bus" makes flysim publish on its
# embedded feed bus and leave :7400 to flyedge.service, which this script
# never enables: see that unit's header for the switch. Written
# unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs.
# Watchdog check 2 reads this line to know whose /metrics carries the
# feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
# Validated and lowercased above (feed_via_normalize).
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
# the bus"). "direct" is the default: flysim binds it. "bus" makes flysim
# register the control services on its embedded router and leave :7401 to
# flycontrol-edge.service, which this script never enables (runbook,
# "Control over the bus"). Written unconditionally; the watchdog reads it
# to know whose /healthz is flysim's own (check 1) and whether to watch
# the edge (check 1b). Validated and lowercased above.
echo "FLY_CONTROL_VIA=${FLY_CONTROL_VIA_EFFECTIVE}"
# How long a macro leaves a target alone after a walk to it aborted # How long a macro leaves a target alone after a walk to it aborted
# (macros.md section 12.1, the Viridian stall). Only written when it is set, # (macros.md section 12.1, the Viridian stall). Only written when it is set,
# because the default lives in the crate and a box that has not tuned it # because the default lives in the crate and a box that has not tuned it
@ -649,16 +456,6 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
if [[ -n "${FLY_MACRO_BLOCKED_MINUTES:-}" ]]; then if [[ -n "${FLY_MACRO_BLOCKED_MINUTES:-}" ]]; then
echo "FLY_MACRO_BLOCKED_MINUTES=${FLY_MACRO_BLOCKED_MINUTES}" echo "FLY_MACRO_BLOCKED_MINUTES=${FLY_MACRO_BLOCKED_MINUTES}"
fi fi
# Adapter versions whose checkpoints this build may migrate
# (flybrain_gb::compatibility, docs/design/flysim.md "Restoring across an
# adapter version"). Only written when it is set, because the safe state is
# absent: an empty or missing variable migrates nothing, which is what every
# deploy before 2026-09-22 did. It stays in fly.env for as long as the
# operator leaves it on the deploy command line, so removing the opt-in is
# one deploy without it.
if [[ -n "${FLY_ACCEPT_ADAPTERS:-}" ]]; then
echo "FLY_ACCEPT_ADAPTERS=${FLY_ACCEPT_ADAPTERS}"
fi
# flybridge (services/bridge/src/config.ts). Nothing wrote these before, so # flybridge (services/bridge/src/config.ts). Nothing wrote these before, so
# flybridge.service had no EnvironmentFile= at all and the service refused to # flybridge.service had no EnvironmentFile= at all and the service refused to
# start with "CHANNEL is required / BOT_USER is required / GAME_TITLE is # start with "CHANNEL is required / BOT_USER is required / GAME_TITLE is
@ -775,52 +572,33 @@ if [ -n "${CPUSET:-}" ]; then
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \ "Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
"leaves cpuset.cpus.effective empty and the unit unstartable." "leaves cpuset.cpus.effective empty and the unit unstartable."
else else
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")" read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')" log "05-deploy: cpuset partition — flysim=$sim_cpus, xvfb/flystage/flystage-web/pulse/mediamtx=$page_cpus, flycast=$encoder_cpus"
tmp_dropin="$(mktemp)" tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day for u in flysim xvfb flystage flystage-web flycast pulse mediamtx; do
# it is enabled it serves the page from the page's CPUs, never from flysim's; likewise case "$u" in
# flycontrol-edge (CTRL-01). flysim) cpus="$sim_cpus" ;;
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores. flycast) cpus="$encoder_cpus" ;;
# (`fly-runtime session` runs it AS flysim.service, which already has them.) *) cpus="$page_cpus" ;;
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not esac
# flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
# leave idle and never a cycle of the live fly's.
# flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
# its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
# using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
# everything else. See that script's header for the cgroup semantics and the ordering rule.
# A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
mapfile -t plan_lines <<< "$plan"
for plan_line in "${plan_lines[@]}"; do
read -r u cpus <<< "$plan_line"
case "$u" in *=) continue ;; esac
cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then
NEED_RELOAD=1
log "05-deploy: ${u}.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
fi
done
{ {
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit." echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
echo "$plan" | awk '$1 ~ /=$/ {print $1 $2}' echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[Service]"
echo "AllowedCPUs=${cpus}"
} > "$tmp_dropin" } > "$tmp_dropin"
changed="$(converge_file "$CTID" "$tmp_dropin" /etc/fly/cpuset.env 0644 root:root)" ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.service.d"
[ "$changed" = changed ] && log "05-deploy: /etc/fly/cpuset.env changed — fly-cpu-confine applies it when flysim next (re)starts, by which time it runs in flysim.slice" changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.service.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then
NEED_RELOAD=1
log "05-deploy: ${u}.service.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
fi
done
rm -f "$tmp_dropin" rm -f "$tmp_dropin"
fi fi
else else
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)" log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
fi fi
# No partition in force: nothing may stay confined by an earlier one, and the session runtime must
# not pin (fly.env above says FLY_SESSION_PIN=0). A confinement already applied lasts until the next
# boot or `fly-cpu-confine release`.
if [ "$PARTITION_ACTIVE" -ne 1 ]; then
ct_exec "$CTID" -- rm -f /etc/fly/cpuset.env
log "05-deploy: no cpuset partition: /etc/fly/cpuset.env removed, FLY_SESSION_PIN=0 in fly.env (sweep workers float); run \`fly-cpu-confine release\` if an earlier partition is still applied"
fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not # 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not
@ -828,28 +606,10 @@ fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /opt/fly/bin" log "05-deploy: converging bin/ helpers to /opt/fly/bin"
ct_exec "$CTID" -- mkdir -p /opt/fly/bin ct_exec "$CTID" -- mkdir -p /opt/fly/bin
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-feed fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do for name in fly-watchdog fly-recap fly-retention flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
done done
# A container already on the session runtime keeps it (see the policy note at the compat check
# above), and its drop-in is rewritten in place from the current template (no restart) so that
# the OnFailure= fallback and MALLOC_ARENA_MAX reach containers switched before they existed.
if [ -n "${RELEASE_TARBALL:-}" ] && ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- /opt/fly/bin/fly-runtime session --no-restart \
|| log "05-deploy: WARNING: could not refresh the session drop-in; it keeps its old content (no OnFailure= fallback until \`fly-runtime session\` is re-run)"
fi
# The NOPASSWD surface those helpers use (config/fly-sudoers). 02-base installs it at
# provision time; converging it here too means a release that adds a helper's line
# (fly-loop-reset, v0.6.4) does not need a re-provision. Validated before install.
log "05-deploy: converging config/fly-sudoers, validated before install"
TMP_SUDOERS="/tmp/fly-sudoers.$$"
ct_push_file "$CTID" "$INFRA_DIR/config/fly-sudoers" "$TMP_SUDOERS" 0440
ct_exec "$CTID" -- visudo -c -f "$TMP_SUDOERS" || die "config/fly-sudoers failed visudo -c, refusing to install it"
ct_exec "$CTID" -- install -o root -g root -m 0440 "$TMP_SUDOERS" /etc/sudoers.d/fly-watchdog
ct_exec "$CTID" -- rm -f "$TMP_SUDOERS"
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 5. reload if anything unit-shaped changed # 5. reload if anything unit-shaped changed
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -26,7 +26,7 @@
# docs/design/stage-bridge.md section B1 has flybridge read # docs/design/stage-bridge.md section B1 has flybridge read
# TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate # TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate
# LoadCredentialEncrypted= values sourced from # LoadCredentialEncrypted= values sourced from
# twitch/<app>-client-{id,secret}. This script follows infra.md (the # twitch/fly-pokemon-client-{id,secret}. This script follows infra.md (the
# doc this task implements) and writes ONE twitch-app.cred containing both # doc this task implements) and writes ONE twitch-app.cred containing both
# values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own # values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own
# implementation (out of scope here, not yet written) will need to parse # implementation (out of scope here, not yet written) will need to parse
@ -118,14 +118,9 @@ fi
# docs/stream-mvp-plan.md's rollout order) — install only if both pass # docs/stream-mvp-plan.md's rollout order) — install only if both pass
# entries already exist, so running this before the Twitch app is # entries already exist, so running this before the Twitch app is
# registered is a clean no-op rather than a hard failure. # registered is a clean no-op rather than a hard failure.
# The two entry NAMES come from the env file (BRIDGE_ID_KEY, BRIDGE_SECRET_KEY): a BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-twitch/helix-client-id}"
# `pass` entry name identifies the operator's store, so it is not spelled here. BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-twitch/helix-client-secret}"
BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-}" if command -v pass >/dev/null 2>&1 \
BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-}"
if [ -z "$BRIDGE_ID_KEY" ] || [ -z "$BRIDGE_SECRET_KEY" ]; then
log "06-secrets: WARNING: BRIDGE_ID_KEY / BRIDGE_SECRET_KEY are not set in the env file, skipping twitch-app." \
"Set both to the pass entry names of the Twitch app id and secret (infra/env/example.env) to install it."
elif command -v pass >/dev/null 2>&1 \
&& pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \ && pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \
&& pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then && pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then
log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}" log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}"

View file

@ -27,7 +27,7 @@ require_pve_host
need pct need pct
ALWAYS_ON_UNITS="xvfb.service pulse.service mediamtx.service flysim.service flystage-web.service flystage.service flycast.service flybridge.service" ALWAYS_ON_UNITS="xvfb.service pulse.service mediamtx.service flysim.service flystage-web.service flystage.service flycast.service flybridge.service"
ALWAYS_ON_TIMERS="fly-recap.timer fly-retention.timer fly-watchdog.timer fly-loop-recover.timer" ALWAYS_ON_TIMERS="fly-recap.timer fly-retention.timer fly-watchdog.timer"
log "07-enable: enabling app units (not yet starting)" log "07-enable: enabling app units (not yet starting)"
for u in $ALWAYS_ON_UNITS; do for u in $ALWAYS_ON_UNITS; do

View file

@ -267,12 +267,6 @@ refuses to write the drop-ins until the conf actually carries
`CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves `CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves
`cpuset.cpus.effective` empty and the unit unstartable. `cpuset.cpus.effective` empty and the unit unstartable.
The sim's CPUs are also kept exclusive to it (PERF-02 review N1, `infra/docs/runbook.md` "The sim's
CPUs are exclusive to the sim"): the sim units run in `flysim.slice`, and `bin/fly-cpu-confine`
confines `system.slice`, `user.slice`, `init.scope` and `/.lxc` (`pct exec`) to the other CPUs when the sim starts.
Without a partition (`CPUSET` unset) none of this applies and the deploy turns the session
runtime's worker pinning off (`FLY_SESSION_PIN=0`).
`CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local `CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local
socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md` socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md`
section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three

View file

@ -1,188 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-cpu-confine — keep every process that is not the sim off the sim's CPUs.
#
# Usage (INSIDE the container, as root):
# fly-cpu-confine apply confine system.slice, user.slice, init.scope and /.lxc (where `pct exec`
# lands) to the non-sim CPUs
# fly-cpu-confine release undo `apply` (all of them go back to the container's whole cpuset)
# fly-cpu-confine status what each of them is confined to, and where the sim runs
# fly-cpu-confine check list every process that is not in flysim.slice but may run on a
# sim CPU (exit 1 if there is one); this command's own process and its
# parents (the shell it was started from) are noted, not failed
#
# Why. The session runtime pins its sweep workers one per CPU (PERF-02). A pinned worker cannot
# leave its CPU, so any sustained CPU-bound process that may run there stalls every barrier:
# measured 0.14x real time with a plain busy loop (0.68x at nice 19; SCHED_IDLE is harmless).
# Priorities do not fix that; keeping the sim's CPUs to the sim does.
#
# How (cgroup v2). flysim.service and flysim-session.service run in flysim.slice, which has
# AllowedCPUs= the sim's CPUs (a drop-in written by 05-deploy.sh). Its siblings under the root
# cgroup are system.slice (every other service, cron, apt, sshd), user.slice (every login
# session) and init.scope (PID 1 and what it forks). `apply` sets AllowedCPUs= the NON-sim CPUs
# on those three, so nothing that systemd places anywhere else can reach a sim CPU. A child's
# cpuset is bounded by its parent's, so the sim must never sit under a slice that excludes its
# CPUs: that is why it has a slice of its own and is not left in system.slice.
#
# The CPU lists come from ${CPUSET_ENV} (written by 05-deploy.sh, from the same cpuset_partition
# call as the AllowedCPUs= drop-ins). No file means no partition: nothing is confined.
#
# `apply` is runtime-only (systemctl set-property --runtime) and is run by flysim.service and
# flysim-session.service's ExecStartPre, so it is re-applied after every boot and every restart
# and can never run while the sim still sits in system.slice: shrinking system.slice under a
# sim that has not been restarted into flysim.slice would silently make it float over the page
# CPUs. `apply` refuses (exit 3, nothing changed) if a sim unit is outside flysim.slice.
#
# `pct exec` / `pct enter` (lxc-attach) put their processes in the cgroup `/.lxc` (or `/.lxc-N`),
# a sibling of system.slice that systemd does not manage. It is written directly
# (cpuset.cpus), only if it already exists (a cgroup lxc owns is never created here), and a
# failure is a warning, never an error: it must not stop the sim from starting. If it cannot be
# written, `check` lists what is running there; run long operator jobs with
# `systemd-run --scope --slice=system.slice -- <cmd>` (or `... -- bash`).
set -euo pipefail
: "${CPUSET_ENV:=/etc/fly/cpuset.env}"
: "${SYSTEMCTL:=systemctl}"
: "${PROC_ROOT:=/proc}"
: "${CGROUP_ROOT:=/sys/fs/cgroup}"
: "${SIM_SLICE:=flysim.slice}"
: "${SIM_UNITS:=flysim.service flysim-session.service}"
CONFINED_UNITS="system.slice user.slice init.scope"
# existing lxc attach cgroups (/.lxc, /.lxc-N) that have a cpuset
lxc_cgroups() {
local d
for d in "$CGROUP_ROOT"/.lxc "$CGROUP_ROOT"/.lxc-*; do
[ -d "$d" ] && [ -e "$d/cpuset.cpus" ] && echo "$d"
done
return 0
}
# set_lxc CPUS — write CPUS into every lxc attach cgroup; warn, never fail.
set_lxc() {
local d
for d in $(lxc_cgroups); do
if ! echo "$1" > "$d/cpuset.cpus" 2>/dev/null; then
log "WARNING: cannot write ${d}/cpuset.cpus; processes started with pct exec stay unconfined (run long jobs with systemd-run --scope --slice=system.slice)"
fi
done
return 0
}
log() { echo "fly-cpu-confine: $*" >&2; }
# read_env — set SIM_CPUS and OTHER_CPUS from ${CPUSET_ENV}, or return 1 when there is no partition.
# Parsed as KEY=VALUE lines, never sourced.
read_env() {
SIM_CPUS="" OTHER_CPUS=""
[ -r "$CPUSET_ENV" ] || return 1
local k v
while IFS='=' read -r k v; do
case "$k" in
FLY_SIM_CPUS) SIM_CPUS="$v" ;;
FLY_OTHER_CPUS) OTHER_CPUS="$v" ;;
esac
done < "$CPUSET_ENV"
[ -n "$SIM_CPUS" ] && [ -n "$OTHER_CPUS" ]
}
# expand LIST — one cpu number per line for a list such as 1,3,5-7.
expand() {
echo "$1" | tr ',' '\n' | awk -F- 'NF==1 && $1 != "" {print $1} NF==2 {for (i=$1;i<=$2;i++) print i}'
}
sim_outside_slice() {
local u cg
for u in $SIM_UNITS; do
cg="$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
[ -n "$cg" ] || continue
case "$cg" in
"/${SIM_SLICE}/"*) ;;
*) echo "$u ($cg)"; return 0 ;;
esac
done
return 1
}
cmd="${1:-}"
case "$cmd" in
apply)
if ! read_env; then
log "no partition configured (${CPUSET_ENV} missing or empty): nothing confined"
exit 0
fi
if out="$(sim_outside_slice)"; then
log "REFUSING to confine: $out runs outside ${SIM_SLICE}; restart it first (it would float over the page cpus otherwise)"
exit 3
fi
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${OTHER_CPUS}"
done
set_lxc "$OTHER_CPUS"
log "system.slice, user.slice, init.scope and /.lxc confined to ${OTHER_CPUS}; ${SIM_SLICE} keeps ${SIM_CPUS}"
;;
release)
# Not `AllowedCPUs=` (empty): systemd leaves the cgroup's cpuset.cpus at its last value while
# the cpuset controller stays enabled for some other unit (here flysim.slice), so the slices
# would stay confined. Set the container's whole cpuset explicitly.
all_cpus="$(cat "${CGROUP_ROOT}/cpuset.cpus.effective" 2>/dev/null || true)"
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${all_cpus}"
done
set_lxc "$all_cpus"
log "system.slice, user.slice, init.scope and /.lxc released to the container's whole cpuset (${all_cpus:-unknown})"
;;
status)
for u in $CONFINED_UNITS $SIM_SLICE; do
echo "$u AllowedCPUs=$("$SYSTEMCTL" show -p AllowedCPUs --value "$u" 2>/dev/null || true)"
done
for d in $(lxc_cgroups); do
echo "${d#"$CGROUP_ROOT"} cpuset.cpus=$(cat "$d/cpuset.cpus" 2>/dev/null || true)"
done
for u in $SIM_UNITS; do
echo "$u ControlGroup=$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
done
;;
check)
if ! read_env; then
log "no partition configured: nothing to check"
exit 0
fi
sim="$(expand "$SIM_CPUS" | sort -n | tr '\n' ' ')"
bad=0
# this process and its parents (the pct exec shell chain) are not a CPU hog
self=" "
p="${SELF_PID:-$$}"
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#self}" -lt 400 ]; do
self="$self$p "
p="$(sed -n 's/^PPid:[[:space:]]*//p' "$PROC_ROOT/$p/status" 2>/dev/null || true)"
done
for d in "$PROC_ROOT"/[0-9]*; do
pid="${d##*/}"
[ -r "$d/status" ] || continue
cg="$(sed -n 's/^0:://p' "$d/cgroup" 2>/dev/null || true)"
case "$cg" in "/${SIM_SLICE}/"* | "/${SIM_SLICE}") continue ;; esac
# kernel threads have no cgroup of their own in this sense and are not a CPU hog
if [ -z "$(readlink "$d/exe" 2>/dev/null || true)" ]; then continue; fi
allowed="$(sed -n 's/^Cpus_allowed_list:[[:space:]]*//p' "$d/status")"
[ -n "$allowed" ] || continue
hit=""
for c in $(expand "$allowed"); do
for s in $sim; do [ "$c" = "$s" ] && hit="$hit$c,"; done
done
if [ -n "$hit" ]; then
case "$self" in *" $pid "*)
log "note: ${pid} ($(cat "$d/comm" 2>/dev/null)) is this check's own process chain in ${cg:-?} and may run on sim cpu ${hit%,}; not counted"
continue ;;
esac
echo "process $pid ($(cat "$d/comm" 2>/dev/null)) in ${cg:-?} may run on sim cpu ${hit%,}"
bad=1
fi
done
[ "$bad" -eq 0 ] && log "ok: only ${SIM_SLICE} can run on ${SIM_CPUS}"
exit "$bad"
;;
*)
sed -n '2,11p' "$0" >&2
exit 2
;;
esac

View file

@ -1,332 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself
# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over
# the bus"; the runbook's "Feed over the bus".
#
# Usage (INSIDE the container, as root):
# fly-feed status configured, running, the edge and its counters (any user)
# fly-feed bus [--no-restart] [--no-rollback]
# fly-feed direct [--no-restart] [--no-wait]
#
# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's
# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings
# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever
# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or
# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes
# hands at the start, so the stream is down for the length of a flysim restart, exactly like the
# unstick rule's) and waits until the page is on the feed again.
#
# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s):
# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it);
# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving);
# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the
# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit
# (a box that only serves the feed) the wait ends at 2.
# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
# only reports. `direct` is the safe terminal state: once the line says direct nothing, an
# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted
# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus`
# rolls back the same way as a failed one.
# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts
# flysim without blocking and does not wait for health or roll anything back: it is what the
# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up.
#
# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and
# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the
# next deploy writes `direct` back (the next flysim start would then follow it) and says so.
#
# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is
# selected, `fly-runtime`): a switch and its rollback are two.
#
# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}.
set -euo pipefail
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_EDGE_SERVICE:=flyedge.service}"
: "${FLY_PAGE_SERVICE:=flystage.service}"
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
: "${FLY_PROC_DIR:=/proc}"
: "${FLY_FEED_HEALTH_TIMEOUT:=300}"
: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}"
: "${FLY_FEED_LOCK:=/run/fly/feed.lock}"
: "${FLY_FEED_SAMPLE_SECONDS:=3}"
FEED_LOG="$FLY_FEED_LOG"
log() { echo "fly-feed: $*" >&2; }
die() { log "$*"; exit 1; }
record() {
if command -v logger >/dev/null 2>&1; then
logger -t fly-feed -- "$*" || true
fi
mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG"
}
usage() {
echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2
exit 2
}
# direct | bus | invalid:<value>. flysim reads the value case-insensitively; a missing line is direct.
configured() {
local value=""
if [ -f "$FLY_ENV_FILE" ]; then
value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)"
fi
value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')"
case "$value" in
""|direct) echo direct ;;
bus) echo bus ;;
*) echo "invalid:${value}" ;;
esac
}
# What the running flysim process started with (its environment, not the file): direct | bus |
# stopped | unknown.
running() {
local pid value
pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi
if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi
value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
case "$value" in
bus) echo bus ;;
*) echo direct ;;
esac
}
# The counters of whoever serves the feed in `via` mode.
metrics_url() {
if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi
}
# metric URL NAME -> the value of the first sample of NAME, or empty.
metric() {
curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true
}
# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these).
whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; }
# The page is on the feed: at least one client, and the frames counter moves over a sample.
page_on_feed() {
local url first second clients
url="$(metrics_url "$1")"
clients="$(metric "$url" fly_feed_clients)"
[ "$(whole "$clients")" -ge 1 ] || return 1
first="$(metric "$url" fly_frames_sent_total)"
sleep "$FLY_FEED_SAMPLE_SECONDS"
second="$(metric "$url" fly_frames_sent_total)"
[ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ]
}
page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; }
old_invocation=""
# Print to stdout, exiting quietly once the reader has gone (`fly-feed status | head -1`).
# Under `pct exec` SIGPIPE is ignored, so a write to a closed pipe fails with EPIPE and bash's
# printf/echo print "write error: Broken pipe": silence that one write and stop printing.
say() {
printf '%s\n' "$*" 2>/dev/null || exit 0
}
# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode.
healthy() {
local via="$1" deadline
deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
sleep 1
continue
fi
if ! page_unit_active; then
log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for"
return 0
fi
if page_on_feed "$via"; then
log "healthy (${via}): the page is on the feed and frames are moving"
return 0
fi
fi
sleep 1
done
return 1
}
# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner.
set_via() {
local value="$1" tmp
[ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)"
tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")"
awk -v v="$value" '
/^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next }
{ print }
END { if (!done) print "FLY_FEED_VIA=" v }
' "$FLY_ENV_FILE" >"$tmp"
chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp"
chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true
mv -f "$tmp" "$FLY_ENV_FILE"
}
locked=0
take_lock() {
[ "$locked" -eq 0 ] || return 0
mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true
exec 8>>"$FLY_FEED_LOCK"
flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching"
locked=1
}
restart_flysim() {
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
log "restarting ${FLY_SERVICE}"
# --no-block: a start that never becomes READY must not hold this process (and the lock);
# `healthy` proves it is talking to the new invocation.
systemctl restart --no-block "$FLY_SERVICE"
}
status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
say "configured: ${conf}"
say "running: ${run}"
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
say " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
fi
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
say "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
url="$(metrics_url "$run")"
if [ "$run" = bus ]; then
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
say "edge healthz: ok"
else
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
fi
say "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
fi
say "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
if [ -f "$FEED_LOG" ]; then say "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
rollback=1
wait_for_health=1
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-rollback) rollback=0 ;;
--no-wait) wait_for_health=0 ;;
*) usage ;;
esac
done
case "$command" in
status) status_report; exit 0 ;;
bus|direct) ;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})"
before="$(configured)"
[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching"
if [ "$command" = bus ]; then
[ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)"
fi
take_lock
running_before="$(running)"
if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then
log "already ${command}: fly.env says it and the running flysim started that way; nothing to do"
status_report
exit 0
fi
# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When
# the line already said bus (a deploy wrote it, the running flysim never started that way), the
# way back is direct: the state that worked.
back="$before"
if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi
# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never
# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it).
if [ "$command" = direct ]; then back=direct; fi
switching=0
restarted=0
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
set_via "$back" || true
if [ "$command" = direct ]; then
record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)"
else
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)"
fi
if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi
fi
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
switching=1
set_via "$command"
record "${command} (was ${before}; flysim was running ${running_before})"
if [ "$restart" -ne 1 ]; then
switching=0
log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it"
exit 0
fi
restarted=1
restart_flysim
if [ "$wait_for_health" -ne 1 ]; then
switching=0
record "${command}: flysim restart queued (--no-wait); health not checked"
log "restart queued; fly-feed status shows the result"
exit 0
fi
if healthy "$command"; then
switching=0
if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then
log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it"
systemctl stop "$FLY_EDGE_SERVICE" || true
fi
record "${command}: healthy"
log "the feed is served ${command}"
exit 0
fi
log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s"
if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then
set_via "$back"
switching=0
record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)"
restart_flysim
if healthy "$back"; then
log "rolled back to ${back}; it is healthy"
else
log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}"
fi
else
switching=0
record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})"
fi
exit 1

View file

@ -1,382 +0,0 @@
#!/usr/bin/env python3
"""Out-of-process loop recovery with an escalation ladder; invoked after the watchdog probe.
Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's
milestone, then to the rung below. It climbs one step per confirmed trap that outlives
the previous step, and starts over once the fly reaches a new best rung, makes lasting
progress after the last step that it had not made before (a reset's replay re-earns its
archive's rewards, which is not progress), or has been quiet for QUIET seconds. A milestone reset
never erases a species first owned within PROTECT seconds, and never repeats the last
reset's archive (a restore replays it exactly); either is a restart instead. A router model can
delay a step, never deny it.
"""
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
from urllib.request import Request, urlopen
REPORT = Path(os.environ.get("FLY_LOOP_REPORT", "/run/fly/wd/loop.json"))
STATE = Path(os.environ.get("FLY_LOOP_RECOVERY_STATE", "/var/lib/fly-loop-recover/state.json"))
HISTORY = Path(os.environ.get("FLY_LOOP_RECOVERY_HISTORY", "/var/lib/fly-loop-recover/history.jsonl"))
NOTICE = Path(os.environ.get("FLY_RECOVERY_NOTICE", "/run/fly/wd/recovery-notice.json"))
MILESTONES = Path(os.environ.get("FLY_STATE_DIR", "/srv/fly/state"))
STATUS_URL = os.environ.get("FLY_STATUS_URL", "http://127.0.0.1:7401/status")
RESET_BIN = os.environ.get("FLY_LOOP_RESET_BIN", "/opt/fly/bin/fly-loop-reset")
INTERVAL = int(os.environ.get("WD_LOOP_INTERVAL", "300"))
COUNTDOWN = int(os.environ.get("FLY_LOOP_COUNTDOWN", "60"))
SETTLE = 1200 # a report inside this after an action may still hold the old window
QUIET = 6 * 3600 # this long without a suspected report starts the ladder over
HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent
DAY = 24 * 3600
MAX_RESETS = 2 # milestone resets per DAY
AGAIN = 12 * 3600 # after this long the last reset's archive may be restored again (row 70)
PROTECT = 2 * 3600 # a species owned this recently is not reset away (row 70)
SEEN = 2000 # lasting-progress names remembered, oldest dropped first (row 70 r3)
VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway
MODEL_BUDGET = 90 # seconds across all models in one decision
VERIFY_TIMEOUT = 240
LIST_TIMEOUT = 120
RESTART_TIMEOUT = 180
RESET_TIMEOUT = 480 # the wrapper waits up to 60 s for the watchdog, then stop, reset, start
# docs/design/ladder.md; mirrors RANK_LADDER in flybrain-gb's pokemon_red/mod.rs (a test pins it).
LADDER = [
"BOOT", "BEDROOM", "DOWNSTAIRS", "PALLET TOWN", "OAK'S LAB", "GOT A STARTER", "OAK'S PARCEL",
"POKEDEX", "VIRIDIAN CITY", "VIRIDIAN FOREST", "PEWTER CITY", "BOULDER BADGE", "MT. MOON",
"CERULEAN CITY", "CASCADE BADGE", "NUGGET BRIDGE", "MET BILL", "VERMILION CITY", "HM CUT",
"THUNDER BADGE", "ROCK TUNNEL", "LAVENDER TOWN", "CELADON CITY", "SILPH SCOPE", "RAINBOW BADGE",
"POKE FLUTE", "FUCHSIA CITY", "SOUL BADGE", "SILPH CO. FREED", "MARSH BADGE", "CINNABAR ISLAND",
"VOLCANO BADGE", "EARTH BADGE", "INDIGO PLATEAU", "BEAT LORELEI", "BEAT BRUNO", "BEAT AGATHA",
"CHAMPION",
]
PROMPT = (
"You check a Game Boy Pokemon Red run played by a simulated fly brain through macros "
"(GO OBJECTIVE, GO WARP, GO ROUTE, FIGHT, ...). A watchdog flagged a suspected loop over "
"a 10-minute brain window. Stuck means the same few macros repeat with no new places "
"(places.delta 0) and no rewards; healthy play finds new places, wins battles or earns "
"rewards. Answer with only the JSON object {\"stuck\": true} or {\"stuck\": false}. "
"No explanation, no reasoning, no other text."
)
def load(path, default):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(value) + "\n")
os.chmod(tmp, 0o644)
tmp.replace(path)
def log(event):
try:
HISTORY.parent.mkdir(parents=True, exist_ok=True)
with HISTORY.open("a") as out:
out.write(json.dumps(event) + "\n")
except OSError as error:
print("history not written:", error, file=sys.stderr)
def models():
names = os.environ.get("FLY_LOOP_MODELS") or os.environ.get("FLY_LOOP_MODEL") or ""
return [name.strip() for name in names.split(",") if name.strip()]
def parse_stuck(content):
"""The stuck flag from a free model's reply, which may wrap the JSON in prose or fences."""
for match in re.finditer(r"\{[^{}]*\}", content or ""):
try:
decision = json.loads(match.group(0))
except ValueError:
continue
if type(decision) is dict and type(decision.get("stuck")) is bool:
return decision["stuck"]
return None
def verdict(report):
"""True/False from the first model that answers, None when no router or none answered."""
url = os.environ.get("FLY_LOOP_ROUTER_URL")
names = models()
if not url or not names:
return None, None
brief = {key: report.get(key) for key in ("reason", "sequence", "window", "places", "milestone", "dominant", "map")}
headers = {"Content-Type": "application/json"}
key = os.environ.get("FLY_LOOP_ROUTER_KEY")
if key:
headers["Authorization"] = "Bearer " + key
deadline = time.monotonic() + MODEL_BUDGET
for name in names:
left = deadline - time.monotonic()
if left < 5:
break
payload = {"model": name, "temperature": 0, "max_tokens": 400, "messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": json.dumps(brief)},
]}
request = Request(url.rstrip("/") + "/chat/completions", json.dumps(payload).encode(), headers)
try:
with urlopen(request, timeout=min(30, left)) as response:
answer = json.load(response)
stuck = parse_stuck(answer["choices"][0]["message"]["content"])
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
print(f"model {name}: {type(error).__name__} {getattr(error, 'code', '')}".rstrip(), file=sys.stderr)
continue
if stuck is None:
print(f"model {name}: no stuck flag in reply", file=sys.stderr)
continue
return stuck, name
return None, None
def rungs():
found = []
for path in MILESTONES.glob("milestone-*.checkpoint"):
number = path.stem.removeprefix("milestone-")
if number.isdigit():
found.append(int(number))
return sorted(found)
def plan(level, rank, best, resets_left, last_reset=None):
"""(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart.
Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best,
and never lower, so repeated days of a trap cannot walk the run down the ladder. The archive
the last reset restored is not restored again (`last_reset`, cleared by a new best rung): a
restore is deterministic, so the same archive replays the same run into the same trap (row 70:
the second reset to rung 11 matched the first event for event).
"""
if level == 0 or not resets_left or rank is None:
return "restart", None
target = rank if level == 1 else max(best, rank) - 1
if target > rank or target == last_reset or target not in restorable_rungs():
return "restart", None
return "reset", target
def restorable_rungs():
"""The rungs the running build can restore (fly-loop-reset --list), empty on any failure."""
try:
done = subprocess.run(["sudo", "-n", RESET_BIN, "--list"], check=False, timeout=LIST_TIMEOUT,
capture_output=True, text=True)
except (OSError, subprocess.SubprocessError) as error:
print("restorable rungs unknown:", type(error).__name__, file=sys.stderr)
return set()
if done.returncode != 0:
return set()
return {int(line) for line in done.stdout.split() if line.isdigit()}
def status():
try:
with urlopen(STATUS_URL, timeout=5) as response:
return json.load(response)
except (OSError, ValueError):
return None
def verify(target, deadline):
while time.monotonic() < deadline:
now = status()
if now and now.get("status") == "running":
rank = (now.get("milestone") or {}).get("rank")
if target is None or rank == target:
return True
time.sleep(5)
return False
def act(action, target):
if action == "restart":
command, limit = ["sudo", "-n", "systemctl", "restart", "flysim.service"], RESTART_TIMEOUT
else:
command, limit = ["sudo", "-n", RESET_BIN, str(target)], RESET_TIMEOUT
try:
done = subprocess.run(command, check=False, timeout=limit)
except (OSError, subprocess.SubprocessError) as error:
print(f"{action} did not complete: {type(error).__name__}", file=sys.stderr)
return False
if done.returncode != 0:
return False
return verify(target, time.monotonic() + VERIFY_TIMEOUT)
def notice(base, phase, now):
try:
write_json(NOTICE, dict(base, phase=phase, updatedAt=int(now)))
except OSError as error:
print("notice not written:", error, file=sys.stderr)
def run(now=None, sleep=time.sleep, clock=None):
clock = clock or (time.time if now is None else (lambda: now))
now = int(clock())
report = load(REPORT, None)
if type(report) is not dict:
return "no watchdog report"
state = load(STATE, {})
if type(state) is not dict:
state = {}
rank = (report.get("milestone") or {}).get("rank")
level = state.get("level", 0)
if type(rank) is int and rank > state.get("bestRank", 0):
if level:
log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank})
state.update(bestRank=rank, level=0)
state.pop("lastReset", None)
level = 0
if "lastReset" in state and now - state.get("lastResetAt", 0) >= AGAIN:
state.pop("lastReset", None)
last = state.get("lastSuspectedAt")
if level and last and now - last > QUIET:
log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank})
state["level"] = level = 0
state["resets"] = [at for at in state.get("resets", []) if now - at < DAY]
at = report.get("at")
# Row 70: lasting progress in the probe's window (a new rung, a species owned, a map entered,
# a trainer or badge beaten; the watchdog's window.progress). The ladder climbs for a trap that
# OUTLIVES its last step; one that follows real progress after that step is a new trap and
# starts again from a restart. A species owned is also kept from a milestone reset for PROTECT.
# A new trap means the old one let go: a clear probe more than SETTLE after the step, so a catch
# made while the fly stays flagged does not start the ladder over.
#
# Progress is measured against everything the ladder has seen before, not against the
# restored archive (row 70 review r3): a milestone reset restores the reward ledger, so the
# replay pays the archive's areas, trainers, species and rungs again, and counting those
# started the ladder over after every reset (a rung-12 replay re-earning an area and a
# species cost two extra steps and a three-hour hold before the rung below). The watchdog
# names each lasting reward (`window.progress.keys`, `kind:label`); only a name not in
# `progressSeen` is progress, and only a species not in it is protected (the replayed catch
# was the fly's before the reset too, and was protected then). A watchdog without names falls
# back to the counts.
progress = (report.get("window") or {}).get("progress") or {}
fresh = type(at) is int and 0 <= now - at <= 600
if fresh and report.get("suspected") == 0:
state["clearAt"] = max(at, state.get("clearAt", 0))
if fresh and type(progress) is dict:
keys = progress.get("keys")
if type(keys) is list:
seen = state.get("progressSeen")
seen = [key for key in seen if type(key) is str] if type(seen) is list else []
known = set(seen)
new = [key for key in dict.fromkeys(key for key in keys if type(key) is str) if key not in known]
state["progressSeen"] = (seen + new)[-SEEN:]
lasting, species = len(new), sum(key.startswith("pokedex:") for key in new)
else:
lasting, species = (progress.get(name) if type(progress.get(name)) is int else 0
for name in ("lasting", "species"))
if lasting > 0:
state["progressAt"] = max(at, state.get("progressAt", 0))
if species > 0:
state["speciesAt"] = max(at, state.get("speciesAt", 0))
since = state.get("actedAt", 0) + SETTLE
if level and state.get("progressAt", 0) > since and state.get("clearAt", 0) > since:
log({"at": now, "event": "ladder-reset", "why": "progress since the last step", "rank": rank})
state["level"] = level = 0
# The last probe that saw progress (new places, or a higher rung than the last probe), kept across
# restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak.
delta = (report.get("places") or {}).get("delta")
if type(at) is int and 0 <= now - at <= 600 and (
(type(delta) is int and delta > 0)
or (type(rank) is int and type(state.get("rank")) is int and rank > state["rank"])):
state["lastProgressAt"] = at
if type(rank) is int:
state["rank"] = rank
if (report.get("suspected") != 1 or type(at) is not int
or not 0 <= now - at <= 600 or report.get("action") != "none"):
state.pop("observedAt", None)
state["vetoes"] = 0
write_json(STATE, state)
return "not a fresh suspected loop"
state["lastSuspectedAt"] = now
acted = state.get("actedAt", 0)
if at < acted + SETTLE:
write_json(STATE, state)
return f"settling after {state.get('lastAction')}"
observed = state.get("observedAt")
if not observed or observed < acted + SETTLE:
state["observedAt"] = at
write_json(STATE, state)
return "waiting for second probe"
if at - observed < INTERVAL - 30:
write_json(STATE, state)
return "waiting for next probe"
resets_left = MAX_RESETS - len(state["resets"])
action, target = plan(level, rank, state.get("bestRank", 0), resets_left, state.get("lastReset"))
protected = action == "reset" and now - state.get("speciesAt", -PROTECT) < PROTECT
# Only a catch-protected reset is held (the level keeps its slot, so it never drops a rung deeper
# while the window lasts, row 70). A step skipped because it would restore the archive just used
# does climb, so the ladder reaches the rung below promptly.
held_reset = protected
if protected:
action, target = "restart", None
# Restarts are at least HOLD apart, also when the ladder has started over since the last one.
if action == "restart" and (level or state.get("lastAction") == "restart") and now - acted < HOLD:
write_json(STATE, state)
if protected:
return "holding: a species owned within the protection window, next restart after the hold"
if not level:
return "holding: the last restart was under three hours ago"
return "holding: no reset to take, next restart after the hold"
if protected:
log({"at": now, "event": "protect", "why": "a species owned within the protection window",
"speciesAt": state["speciesAt"], "rank": rank})
stuck, model = verdict(report)
if stuck is False and state.get("vetoes", 0) < VETO_LIMIT:
state["vetoes"] = state.get("vetoes", 0) + 1
write_json(STATE, state)
log({"at": now, "event": "veto", "model": model, "vetoes": state["vetoes"], "rank": rank})
return f"model {model} says not stuck ({state['vetoes']}/{VETO_LIMIT})"
why = {True: f"confirmed by {model}", False: "veto limit reached", None: "no model answer, watchdog alone"}[stuck]
base = {"v": 1, "id": f"{now}-{action}", "action": action,
"fromRung": rank, "fromLabel": (report.get("milestone") or {}).get("label"),
"reason": report.get("reason"), "loop": (report.get("sequence") or [])[:4],
"stuckSeconds": now - state["lastProgressAt"] if state.get("lastProgressAt")
else max(0, now - observed) + 600,
"announcedAt": now, "executeAt": now + COUNTDOWN}
if action == "reset":
base.update(toRung=target, toLabel=LADDER[target] if 0 <= target < len(LADDER) else None)
notice(base, "countdown", now)
sleep(COUNTDOWN)
started = int(clock())
# Recorded before acting, so a helper killed mid-step has still climbed (unless held) and spent the reset.
state.update(level=level if held_reset else level + 1, actedAt=started, lastAction=action, vetoes=0)
state.pop("observedAt", None)
if action == "reset":
state["resets"].append(started)
state.update(lastReset=target, lastResetAt=started)
write_json(STATE, state)
notice(base, "acting", started)
ok = act(action, target)
finished = int(clock())
if action == "reset" and not ok:
state.pop("lastReset", None) # not known to have been restored, so it may be tried again
notice(base, "done" if ok else "failed", finished)
state["actedAt"] = finished
write_json(STATE, state)
log({"at": finished, "event": action, "target": target, "ok": ok, "why": why, "rank": rank,
"level": level, "sequence": report.get("sequence"), "map": report.get("map")})
outcome = "flysim restarted" if action == "restart" else f"reset to rung {target}"
return f"{outcome} ({why})" if ok else f"{action} FAILED ({why})"
if __name__ == "__main__":
print(run())

View file

@ -1,172 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-loop-reset — the milestone step of fly-loop-recover's ladder, as root.
#
# fly-loop-recover runs as User=fly and reaches this through one NOPASSWD sudoers line
# (config/fly-sudoers). It does what infra/docs/runbook.md "Restart the run from a rung"
# does by hand: stop flysim, promote milestone-<N>.checkpoint with fly-reset-to-milestone,
# start flysim.
#
# Root never executes anything the fly account can write. The release tree under
# /opt/fly/releases is fly-owned, so the flysim run here is the root-owned copy 05-deploy
# installs at /opt/fly/sbin/flysim straight from the release tarball; without it every rung is
# refused and the ladder falls back to restarts. Paths are fixed (test overrides are honoured
# only when not root), and /etc/fly/fly.env is read as KEY=VALUE data, never sourced.
#
# fly-reset-to-milestone does not check that the build can restore the archive, and a flysim
# that refuses every checkpoint refuses to start: a black stream. So a rung is only used when
# its archive's compatibility string equals this build's, or differs only in an adapter id that
# FLY_ACCEPT_ADAPTERS names (05-deploy.sh's adapter_migration_accepted).
#
# fly-watchdog restarts a flysim whose /healthz fails, which during a reset would start it on a
# half-rewritten store; its timer is stopped for the reset and started again on every exit path.
#
# Usage: fly-loop-reset <rung> reset to that rung
# fly-loop-reset --list print the rungs this build can restore, one per line
set -euo pipefail
STATE_DIR=/srv/fly/state
ENV_FILE=/etc/fly/fly.env
FLYSIM=/opt/fly/sbin/flysim
RESET_BIN=/opt/fly/bin/fly-reset-to-milestone
if [ "$(id -u)" -ne 0 ]; then
STATE_DIR="${FLY_LOOP_RESET_TEST_STATE_DIR:-$STATE_DIR}"
ENV_FILE="${FLY_LOOP_RESET_TEST_ENV_FILE:-$ENV_FILE}"
FLYSIM="${FLY_LOOP_RESET_TEST_FLYSIM:-$FLYSIM}"
RESET_BIN="${FLY_LOOP_RESET_TEST_RESET_BIN:-$RESET_BIN}"
fi
SERVICE=flysim.service
WATCHDOG_TIMER=fly-watchdog.timer
WATCHDOG_SERVICE=fly-watchdog.service
readonly STATE_DIR ENV_FILE FLYSIM RESET_BIN SERVICE WATCHDOG_TIMER WATCHDOG_SERVICE
log() { echo "fly-loop-reset: $*" >&2; }
usage() { log "usage: fly-loop-reset <rung> | --list"; exit 2; }
LIST=0
RANK=""
[ "$#" -eq 1 ] || usage
if [ "$1" = --list ]; then
LIST=1
elif [[ "$1" =~ ^[0-9]{1,2}$ ]]; then
RANK="$1"
else
usage
fi
# FLY_* lines of fly.env as `env` arguments. Values may be quoted the systemd way; nothing
# is evaluated.
env_args=()
accepted=""
if [ -r "$ENV_FILE" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^(FLY_[A-Z0-9_]*)=(.*)$ ]] || continue
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
if [[ "$value" =~ ^\"(.*)\"$ ]] || [[ "$value" =~ ^\'(.*)\'$ ]]; then
value="${BASH_REMATCH[1]}"
fi
env_args+=("$key=$value")
if [ "$key" = FLY_ACCEPT_ADAPTERS ]; then
accepted="$value"
fi
done < "$ENV_FILE"
fi
clean_env() { env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root "${env_args[@]}" "$@"; }
# The same rule as 05-deploy.sh: exactly one '/'-separated field differs, it is the adapter
# (index 1), and the archive's adapter id is listed.
migration_accepted() {
local old="$1" new="$2" i differing=0 index=-1 entry
local -a old_parts new_parts
IFS='/' read -r -a old_parts <<< "$old"
IFS='/' read -r -a new_parts <<< "$new"
[ "${#old_parts[@]}" -eq "${#new_parts[@]}" ] || return 1
for ((i = 0; i < ${#old_parts[@]}; i++)); do
if [ "${old_parts[$i]}" != "${new_parts[$i]}" ]; then
differing=$((differing + 1))
index=$i
fi
done
[ "$differing" -eq 1 ] && [ "$index" -eq 1 ] || return 1
for entry in ${accepted//,/ }; do
[ "$entry" = "${old_parts[1]}" ] && return 0
done
return 1
}
# The root copy must be the flysim that runs: a manual rollback of /opt/fly/current without a
# deploy would otherwise approve archives the running build refuses.
LIVE_FLYSIM=/opt/fly/current/flysim
[ "$(id -u)" -eq 0 ] || LIVE_FLYSIM="${FLY_LOOP_RESET_TEST_LIVE_FLYSIM:-$FLYSIM}"
same_build() {
[ -f "$LIVE_FLYSIM" ] \
&& [ "$(sha256sum < "$FLYSIM" | cut -d' ' -f1)" = "$(sha256sum < "$LIVE_FLYSIM" | cut -d' ' -f1)" ]
}
build_compat=""
if [ -x "$FLYSIM" ] && [ "$(stat -c %u "$FLYSIM")" = "$(id -u)" ] && same_build; then
build_compat="$(clean_env timeout 90 "$FLYSIM" --print-compatibility 2>/dev/null | tail -n1 || true)"
fi
if [ -z "$build_compat" ]; then
log "no compatibility string from $FLYSIM (missing, not owned by $(id -un), not the running build, or failed); no rung is restorable"
[ "$LIST" -eq 1 ] && exit 0
exit 3
fi
restorable() {
local archive="${STATE_DIR}/milestone-$1.checkpoint" compat
[ -f "$archive" ] || return 1
compat="$(head -c 262144 "$archive" 2>/dev/null | grep -a -o -m1 '"compatibility"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n1 | cut -d'"' -f4 || true)"
[ -n "$compat" ] || return 1
[ "$compat" = "$build_compat" ] || migration_accepted "$compat" "$build_compat"
}
if [ "$LIST" -eq 1 ]; then
for archive in "${STATE_DIR}"/milestone-*.checkpoint; do
[ -e "$archive" ] || continue
rung="${archive##*/milestone-}"
rung="${rung%.checkpoint}"
if [[ "$rung" =~ ^[0-9]{1,2}$ ]] && restorable "$rung"; then
echo "$rung"
fi
done | sort -n
exit 0
fi
if ! restorable "$RANK"; then
log "rung ${RANK}'s archive is missing or not restorable by this build (FLY_ACCEPT_ADAPTERS='${accepted}'); nothing touched"
exit 3
fi
# shellcheck disable=SC2317 # invoked by the EXIT trap
finish() {
local status=$?
systemctl start "$SERVICE" || log "starting ${SERVICE} failed"
systemctl start "$WATCHDOG_TIMER" || log "starting ${WATCHDOG_TIMER} failed"
exit "$status"
}
trap finish EXIT
trap 'exit 143' TERM INT HUP
log "pausing ${WATCHDOG_TIMER} and stopping ${SERVICE} to reset to rung ${RANK}"
systemctl stop "$WATCHDOG_TIMER"
# A oneshot probe mid-run is "activating", which `is-active` does not count; wait on ActiveState.
watchdog_idle() {
case "$(systemctl show -p ActiveState --value "$WATCHDOG_SERVICE")" in
inactive|failed) return 0 ;;
*) return 1 ;;
esac
}
for _ in $(seq 1 60); do
watchdog_idle && break
sleep 1
done
if ! watchdog_idle; then
log "${WATCHDOG_SERVICE} still running after 60 s; not resetting"
exit 4
fi
systemctl stop "$SERVICE"
status=0
clean_env FLY_BIN="$FLYSIM" "$RESET_BIN" "$RANK" || status=$?
[ "$status" -eq 0 ] || log "fly-reset-to-milestone ${RANK} failed (exit ${status}); starting ${SERVICE} on the state it left"
exit "$status"

View file

@ -1,77 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-reset-to-milestone — restart the run from an earlier ladder rung,
# instead of from scratch.
#
# The operator's decision of 2026-09-22: "restart the live run from an early
# checkpoint instead of from scratch". 05-deploy's FLY_RESET_STATE=1 cannot do
# that — it archives the durable state and the next start warms up a fresh fly,
# losing everything the brain has learned. This promotes one milestone archive
# (milestone-<N>.checkpoint, written at the first commit at a new best rank and
# never rotated away) to being what both stores restore.
#
# Usage: fly-reset-to-milestone <N>
# Run INSIDE the container, as root, with flysim STOPPED. It refuses
# otherwise, and it refuses a rung this run never reached.
#
# The whole sequence — stop, reset, deploy with the adapter opt-in, start,
# verify the rank — is in infra/docs/runbook.md, "Restart the run from a rung".
# Nothing here is destructive on its own: every file in both stores is copied to
# a dated directory next to the durable one before anything is rewritten.
set -euo pipefail
: "${FLY_STATE_DIR:=/srv/fly/state}"
: "${FLY_STATE_HOT_DIR:=/run/fly/state}"
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_USER:=fly}"
FLYSIM="${FLY_BIN:-${FLY_RELEASE_DIR}/flysim}"
log() { echo "fly-reset-to-milestone: $*" >&2; }
die() { log "$*"; exit 1; }
RANK="${1:-}"
if [ "$#" -ne 1 ] || ! [[ "$RANK" =~ ^[0-9]+$ ]]; then
die "usage: fly-reset-to-milestone <rung> (e.g. fly-reset-to-milestone 9)"
fi
# --- refusals ----------------------------------------------------------------
# A running flysim owns both stores: it commits a hot checkpoint every few
# seconds and a durable one every few minutes, so a reset underneath it would be
# overwritten within the minute and the tool would have lied.
if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet "$FLY_SERVICE"; then
die "$FLY_SERVICE is running. Stop it first: systemctl stop $FLY_SERVICE"
fi
[ -x "$FLYSIM" ] || die "no flysim binary at $FLYSIM (set FLY_BIN to point at one)"
milestone="${FLY_STATE_DIR}/milestone-${RANK}.checkpoint"
# The binary refuses this too, and refuses before it copies anything; checking
# here as well is what makes the message name the rungs that do exist.
if [ ! -f "$milestone" ]; then
log "no milestone archive for rung ${RANK}: $milestone does not exist."
log "rungs this run reached:"
ls -1 "${FLY_STATE_DIR}"/milestone-*.checkpoint 2>/dev/null \
| sed 's|.*/milestone-||; s|\.checkpoint$||' | sort -n | tr '\n' ' ' >&2 || true
echo >&2
exit 1
fi
# --- the reset ---------------------------------------------------------------
log "resetting to rung ${RANK} (durable ${FLY_STATE_DIR}, hot ${FLY_STATE_HOT_DIR})"
FLY_STATE="$FLY_STATE_DIR" FLY_STATE_HOT="$FLY_STATE_HOT_DIR" \
"$FLYSIM" --reset-to-milestone "$RANK"
# flysim runs unprivileged; this tool runs as root, so everything it wrote and
# everything it archived has to go back to the service account.
if command -v chown >/dev/null 2>&1 && id "$FLY_USER" >/dev/null 2>&1; then
chown -R "${FLY_USER}:${FLY_USER}" "$FLY_STATE_DIR" "$FLY_STATE_HOT_DIR" 2>/dev/null || true
for dir in "${FLY_STATE_DIR}".reset-*; do
[ -d "$dir" ] && chown -R "${FLY_USER}:${FLY_USER}" "$dir"
done
fi
log "done. Next, per infra/docs/runbook.md:"
log " 1. deploy the build whose adapter wrote that checkpoint, or deploy the new"
log " one with FLY_ACCEPT_ADAPTERS set to the checkpoint's adapter id"
log " 2. systemctl start $FLY_SERVICE"
log " 3. curl -s localhost:7401/status | grep -o '\"rank\":[0-9]*'"

View file

@ -1,501 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-runtime — which runtime the live fly runs: the legacy loop (`flysim`) or the
# session runtime (`flysim-session`, SERVE-01).
#
# Usage (INSIDE the container, as root):
# fly-runtime status print `legacy` or `session` (and the session's transport), and
# what flysim.service runs
# fly-runtime session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation]
# fly-runtime session-bus [...] the same as `session --bus`
# fly-runtime legacy [--no-restart]
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
#
# CUT-01 calls `fly-runtime session` after its zero-divergence shadow; `fly-runtime legacy` is
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
#
# The session's transport (BUS-01). `--local` (the default for a first switch) runs the session's
# participants in flysim-session's own process over the local lane. `--bus` runs them on the flybus
# router over Unix sockets: flysim-session (the router, the coordinator, the listeners) starts the
# agent and the world as child processes of the same unit (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release), in flysim.slice, on flysim's cpuset.
# The drop-in then carries `Environment=FLY_SESSION_TRANSPORT=bus`. Without either flag `session`
# keeps the transport the drop-in already has, so 05-deploy's `session --no-restart` refresh never
# changes it; `session --local` is the way back from the bus. Results, traces, checkpoints and the
# compatibility string are the same in both: only where the participants run changes. A switch onto
# the bus needs a shadow that ran the bus (`fly-shadow-run check --bus`), which the coordinator runs
# before this command, as for the first cutover. Everything below applies to both transports: one
# unit, OnFailure= falls back to LEGACY, the probation judges the session runtime either way.
#
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
# is chosen by one drop-in, ${DROPIN}:
#
# [Service]
# ExecStart=
# ExecStart=/opt/fly/current/flysim-session
# Environment=FLY_SESSION_DIR=/run/fly/session
#
# i.e. flysim-session.service's ExecStart and its one extra variable (the standalone unit and
# this drop-in are kept identical by infra/tests/lint.sh). Everything else that names
# flysim.service -- fly.target, flyedge.service's Requires=, fly-watchdog's checks and escalation,
# fly-loop-recover's `sudo systemctl restart flysim.service` and its sudoers line,
# fly-loop-reset, fly-reset-to-milestone, the unstick rule, `journalctl -u flysim`, the cpuset
# drop-in -- therefore keeps working unchanged, a reboot keeps the choice, and 05-deploy.sh (which
# converges unit files but never removes a drop-in) keeps it across deploys. 05-deploy.sh refuses
# a release without flysim-session while the drop-in is present.
#
# `session` refuses unless the release has flysim-session and its --print-compatibility equals
# flysim's (the store is shared, so the two must restore each other's checkpoints). After the
# restart it waits for /healthz (FLY_RUNTIME_HEALTH_TIMEOUT, default 300 s: the connectome load and
# the restore) and a snapshot that has advanced; if the session runtime does not come up healthy
# it switches back to legacy by itself and exits 1 (--no-fallback leaves it to the operator).
#
# The fallback survives the invocation (C1 of the SERVE-01 review). The drop-in also carries
#
# [Unit]
# OnFailure=fly-runtime-fallback.service
# StartLimitIntervalSec=600
# StartLimitBurst=3
# [Service]
# RestartMode=direct
#
# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default
# RestartMode=normal the unit passes through `failed` before every Restart=always restart and
# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit
# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes
# (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and
# fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd
# runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove
# the drop-in, daemon-reload, restart flysim.service (now the legacy binary) and log a line. That
# holds across reboots, watchdog and loop-recover restarts and deploys, none of which go through
# `fly-runtime session`. It is idempotent (a lock, and a no-op once the drop-in is gone) and it
# keeps the drop-in when there is no executable legacy binary, so it never swaps one runtime that
# cannot start for another. `fly-runtime session` deletes the reason file; `status` shows it.
#
# During a switch fly-runtime traps INT, TERM and HUP (and any failure): an interrupted `session`
# puts the previous state back (drop-in removed, or the earlier one restored) and restarts
# flysim.service on it, so a dropped ssh never leaves a drop-in that was not health-checked.
#
# The speed probation (CUT-01). Operator decision 2026-09-30: the session runtime stays only if it
# sustains >= 1.0x real time on the release container. A `session` that restarted flysim and saw
# it healthy therefore starts infra/bin/fly-runtime-probation (fly-runtime-probation.timer, every
# 60 s for 30 minutes): a sustained speed failure ends in `fly-runtime fallback "speed: ..."`, the
# same fallback as above under the same lock. `legacy` and every fallback cancel it. `--no-restart`
# (05-deploy's refresh of the drop-in) and `--no-probation` (rehearsals) start none. If the
# probation cannot be started, `session` falls back: an unguarded cutover is not allowed.
#
# `session` also stops a running shadow and its guard (fly-shadow-run stop, no flysim restart) once
# flysim is healthy on the session runtime, so the procedure cannot be done wrong (review N1).
#
# Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}.
set -euo pipefail
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_RUNTIME_HEALTH_TIMEOUT:=300}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_SYSTEMD_DIR:=/etc/systemd/system}"
: "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}"
: "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}"
: "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}"
: "${FLY_RUNTIME_LOCK_WAIT:=150}"
DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d"
DROPIN="${DROPIN_DIR}/10-runtime.conf"
RUNTIME_LOG="$FLY_RUNTIME_LOG"
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
FALLBACK_UNIT=fly-runtime-fallback.service
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
WORKER_BIN="${FLY_RELEASE_DIR}/fly-session"
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
SESSION_DIR=/run/fly/session
SHADOW_RUN_BIN="${FLY_SHADOW_RUN_BIN:-$(dirname "$(readlink -f "$0")")/fly-shadow-run}"
PROBATION_BIN="${FLY_PROBATION_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime-probation}"
log() { echo "fly-runtime: $*" >&2; }
# The speed probation's hooks (best effort except `start`, which the caller checks).
probation() {
[ -x "$PROBATION_BIN" ] || return 0
"$PROBATION_BIN" "$@" || log "fly-runtime-probation $1 failed"
}
die() { log "$*"; exit 1; }
# CUT-01 (review N1): once flysim runs the session runtime the shadow and its guard are over. The
# guard would judge the session against the legacy baseline and restart flysim on a trip; the
# session writes no trace. Stops both WITHOUT restarting flysim. Best effort, never fails the switch.
stop_shadow() {
if systemctl is-active --quiet flyshadow.service 2>/dev/null \
|| systemctl is-active --quiet flyshadow-guard.timer 2>/dev/null; then
if [ -x "$SHADOW_RUN_BIN" ] && "$SHADOW_RUN_BIN" stop; then
log "the shadow and its guard are stopped (flysim.service not restarted)"
else
log "WARNING: could not stop the shadow; run: fly-shadow-run stop (never with --restart-flysim)"
fi
fi
}
usage() {
echo "usage: fly-runtime status | session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
exit 2
}
current() {
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
}
# The session's transport the drop-in selects: `bus` or `local` (also with no drop-in).
current_transport() {
if [ -f "$DROPIN" ] && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$DROPIN"; then
echo bus
else
echo local
fi
}
# `legacy`, `session` or `session-bus`, for the runtime log.
current_label() {
if [ "$(current)" = session ] && [ "$(current_transport)" = bus ]; then echo session-bus; else current; fi
}
record() {
local line
line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
if command -v logger >/dev/null 2>&1; then
logger -t fly-runtime -- "$*" || true
fi
mkdir -p "$(dirname "$RUNTIME_LOG")" 2>/dev/null || true
echo "$line" >>"$RUNTIME_LOG" 2>/dev/null || log "could not append to $RUNTIME_LOG"
}
# The compatibility string a binary would write, with the service's own environment: fly.env is
# systemd's EnvironmentFile syntax, read as KEY=VALUE lines rather than sourced as shell.
compat_of() {
local -a vars=()
local line key value
if [ -f "$FLY_ENV_FILE" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
key="${line%%=*}"
value="${line#*=}"
value="${value%\"}"
value="${value#\"}"
vars+=("${key}=${value}")
done <"$FLY_ENV_FILE"
fi
env "${vars[@]}" "$1" --print-compatibility 2>/dev/null | tr -d '\r'
}
write_dropin() {
mkdir -p "$DROPIN_DIR"
local tmp="${DROPIN}.tmp.$$"
cat >"$tmp" <<EOF
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
# Keep [Service] in step with units/flysim-session.service.
[Unit]
OnFailure=${FALLBACK_UNIT}
StartLimitIntervalSec=600
StartLimitBurst=3
[Service]
RestartMode=direct
ExecStart=
ExecStart=${SESSION_BIN}
Environment=FLY_SESSION_DIR=${SESSION_DIR}
Environment=MALLOC_ARENA_MAX=2
EOF
if [ "$transport" = bus ]; then
cat >>"$tmp" <<EOF
# BUS-01: the participants are child processes on the session router's Unix sockets.
Environment=FLY_SESSION_TRANSPORT=bus
EOF
fi
chmod 0644 "$tmp"
mv -f "$tmp" "$DROPIN"
}
# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
healthy() {
local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
local first=""
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
local frame
frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
| sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$frame" ]; then
if [ -z "$first" ]; then
first="$frame"
elif [ "$frame" -gt "$first" ]; then
log "healthy: frame ${first} -> ${frame}"
return 0
fi
fi
fi
sleep 1
done
return 1
}
# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
locked=0
take_lock() {
if [ "$locked" -eq 1 ]; then return 0; fi
mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
exec 9>>"$FLY_RUNTIME_LOCK"
if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
return 1
}
drop_lock() {
exec 9>&-
locked=0
}
restarted=0
old_invocation=""
restart_and_check() {
systemctl daemon-reload
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
log "restarting ${FLY_SERVICE} on the $(current) runtime"
restarted=1
# --no-block: a blocking restart of a unit that never becomes READY holds this process (and
# the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
# that it is talking to the NEW invocation, not the old process that is still shutting down.
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
drop_lock
healthy
}
# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
do_fallback() {
local reason="$1" result nrestarts saved
take_lock || log "continuing without the lock"
if [ ! -f "$DROPIN" ]; then
log "fallback: the legacy runtime is already selected; nothing to do"
return 0
fi
if [ ! -x "$LEGACY_BIN" ]; then
record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
return 1
fi
result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
reason="${reason//[\"\\]/}"
reason="${reason//$'\n'/ }"
mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
>"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
cp -f "$DROPIN" "$saved"
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
probation cancel --quiet
record "legacy (automatic fallback: ${reason}; was session)"
systemctl daemon-reload || true
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
restarted=1
if systemctl restart --no-block "$FLY_SERVICE"; then
rm -f "$saved"
return 0
fi
# Could not even queue the restart: keep what was running, and say so.
mkdir -p "$DROPIN_DIR" && mv -f "$saved" "$DROPIN"
systemctl daemon-reload || true
rm -f "$FELLBACK_FILE"
record "fallback FAILED (${reason}): could not restart ${FLY_SERVICE}; the session drop-in is back"
return 1
}
# An interrupted or failed switch puts the previous state back. `switching` is 1 from just
# before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the
# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and
# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the
# switch deleted it under the lock, only a finished fallback writes it): restoring the older
# drop-in then would strand the stream on the session runtime after it was taken off.
switching=0
switch_target=""
prev_dropin=""
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
take_lock || true
if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then
record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)"
restarted=0
elif [ "$switch_target" = session ]; then
if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then
mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN"
else
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
fi
record "$(current) (switch to session interrupted or failed (exit ${rc}); rolled back)"
else
record "$(current) (switch to legacy interrupted (exit ${rc}))"
fi
systemctl daemon-reload || true
if [ "$restarted" -eq 1 ]; then
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
systemctl restart --no-block "$FLY_SERVICE" || true
fi
fi
[ -z "$prev_dropin" ] || rm -f "$prev_dropin"
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
fallback=1
probe=1
transport=""
fallback_reason=""
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
if [ "$command" = session-bus ]; then command=session; transport=bus; fi
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-fallback) fallback=0 ;;
--no-probation) probe=0 ;;
--bus) [ "$command" = session ] || usage; transport=bus ;;
--local) [ "$command" = session ] || usage; transport=local ;;
*) usage ;;
esac
done
# No flag: keep the drop-in's transport (05-deploy's refresh); local for a first switch.
[ -n "$transport" ] || transport="$(current_transport)"
case "$command" in
status)
current
if [ "$(current)" = session ]; then echo " transport: $(current_transport)"; fi
if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi
systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true
exit 0
;;
session|session-bus|legacy) ;;
fallback)
[ "$(id -u)" -eq 0 ] || die "run as root"
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
exit $?
;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${DROPIN} and restarts ${FLY_SERVICE})"
if [ "$command" = session ]; then
[ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
[ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
if [ "$transport" = bus ] && [ ! -x "$WORKER_BIN" ]; then
die "this release has no ${WORKER_BIN}: the bus transport starts its participants from it"
fi
legacy_compat="$(compat_of "$LEGACY_BIN")"
session_compat="$(compat_of "$SESSION_BIN")"
[ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
if [ "$legacy_compat" != "$session_compat" ]; then
die "the two runtimes would write different checkpoints; not switching.
flysim: ${legacy_compat}
flysim-session: ${session_compat}"
fi
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
if [ -f "$DROPIN" ]; then
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
cp -f "$DROPIN" "$prev_dropin"
fi
switch_target=session
switching=1
rm -f "$FELLBACK_FILE"
write_dropin
record "$(current_label) (was ${before}); compatibility ${session_compat}"
if [ "$restart" -ne 1 ]; then
systemctl daemon-reload
switching=0
log "drop-in written; restart ${FLY_SERVICE} to apply"
exit 0
fi
if restart_and_check; then
# OnFailure= may have fallen back while we waited (a healthy legacy would pass the
# check above too): only report success if the session drop-in is still what runs.
if [ -f "$DROPIN" ] && [ ! -f "$FELLBACK_FILE" ]; then
switching=0
stop_shadow
if [ "$probe" -eq 1 ]; then
if [ ! -x "$PROBATION_BIN" ] || ! "$PROBATION_BIN" start; then
log "the speed probation could not be started; an unguarded cutover is not allowed"
if [ "$fallback" -eq 1 ]; then
do_fallback "the speed probation could not be started" || true
fi
exit 1
fi
log "flysim.service runs the session runtime, on probation: fly-runtime-probation status"
else
log "flysim.service runs the session runtime (no probation)"
fi
exit 0
fi
switching=0
log "the session runtime failed and ${FALLBACK_UNIT} fell back to legacy: $(cat "$FELLBACK_FILE" 2>/dev/null)"
exit 1
fi
log "the session runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s"
if [ "$fallback" -eq 1 ]; then
do_fallback "the session runtime was not healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s of the switch" || true
switching=0
if healthy; then
log "fell back to the legacy runtime; it is healthy"
else
log "fell back to the legacy runtime, and it is NOT healthy either: check journalctl -u ${FLY_SERVICE}"
fi
else
switching=0
fi
exit 1
fi
# legacy
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
switch_target=legacy
switching=1
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
probation cancel
record "legacy (was ${before})"
[ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; }
if restart_and_check; then
switching=0
log "flysim.service runs the legacy runtime"
exit 0
fi
switching=0
die "the legacy runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s: check journalctl -u ${FLY_SERVICE}"

View file

@ -1,299 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-runtime-probation -- CUT-01's speed probation after `fly-runtime session`.
# Pushed to /opt/fly/bin by 05-deploy.sh. Root, inside the container. Normally nobody runs it by
# hand: `fly-runtime session` starts it, `fly-runtime legacy` and every fallback cancel it, and
# fly-runtime-probation.timer runs `tick` every 60 s.
#
# fly-runtime-probation start begin a probation (enables and starts the timer)
# fly-runtime-probation cancel end it without a verdict (disables the timer)
# fly-runtime-probation status state, latest samples, result
# fly-runtime-probation tick (timer) one sample and one decision
# fly-runtime-probation simulate CHECKS.jsonl the rule over recorded samples (lint)
#
# Operator decision 2026-09-30: cut over only if the session runtime sustains >= 1.0x real time on
# the release container. Only that box can measure it, so the switch is guarded. The rule:
# - A sample is one fly_realtime_factor mean over 10 one-second reads of flysim's /metrics (the
# same sampling as fly-shadow-run's guard), with fly_lag_seconds and fly_uptime_seconds.
# - Warm-up: a flysim process is not judged before it has been up FLY_PROBATION_WARMUP (300 s:
# the connectome load, the restore, the first minutes). A restart (uptime goes backwards)
# starts the window again; so does a paused or not running fly: it is not judged.
# - Window: the judged samples of the last FLY_PROBATION_WINDOW (600 s), at least
# FLY_PROBATION_MIN_SAMPLES (8). FAIL when the window's MEDIAN realtime factor is below
# FLY_PROBATION_MIN_RTF (0.97), or the lag grew by more than FLY_PROBATION_MAX_LAG_GROWTH
# (30 s) between the start and the end of the window (median of the first and of the last 3
# samples). The median is the same robust statistic fly-shadow-run's baseline uses: one
# stalled sample, or two, never fails it.
# - PASS when FLY_PROBATION_SECONDS (1800) have passed since `start` and the latest window is
# full and healthy. A probation that cannot fill a window within FLY_PROBATION_MAX_SECONDS
# (7200: a fly that never runs) fails as inconclusive: no proof of 1.0x, no cutover.
# FAIL runs `fly-runtime fallback "speed: ..."` (the ordinary fallback: lock, reason file
# /run/fly/runtime-fellback.json, journal line, flysim.service restarted on legacy). It is retried
# every minute until it succeeds. PASS writes ${RESULT} (passed: true) and disables the timer.
# Nothing judges the speed afterwards: the watchdog and the start-limit fallback are unchanged.
#
# State is ${DIR}/state.json (on disk, so a reboot resumes the probation: the timer is enabled,
# and OnBootSec= runs it after boot); ${DIR}/last.json keeps the last verdict.
set -euo pipefail
: "${FLY_PROBATION_DIR:=/var/lib/fly/probation}"
: "${FLY_PROBATION_RESULT:=/run/fly/runtime-probation.json}"
: "${FLY_PROBATION_TIMER:=fly-runtime-probation.timer}"
: "${FLY_PROBATION_READS:=10}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
RUNTIME_BIN="${FLY_RUNTIME_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime}"
STATE="$FLY_PROBATION_DIR/state.json"
LAST="$FLY_PROBATION_DIR/last.json"
log() { echo "fly-runtime-probation: $*" >&2; }
die() { log "$*"; exit 1; }
journal() {
if command -v logger >/dev/null 2>&1; then logger -t fly-runtime -- "probation: $*" || true; fi
log "$*"
}
need_root() { [ "$(id -u)" = 0 ] || die "run as root"; }
take_lock() {
mkdir -p "$FLY_PROBATION_DIR"
exec 8>>"$FLY_PROBATION_DIR/lock"
flock -w 60 8 || die "could not take $FLY_PROBATION_DIR/lock"
}
drop_lock() { exec 8>&-; }
# One sample of the live fly: {t, status, rtMean, lag, uptime} (fly-shadow-run's format).
sample() {
python3 - "$FLY_METRICS_URL" "$FLY_CONTROL_URL" "$FLY_PROBATION_READS" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url, reads = sys.argv[1], sys.argv[2], int(sys.argv[3])
def metrics():
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
out = {}
for line in text.splitlines():
if line.startswith("#"):
continue
parts = line.split()
if len(parts) == 2:
try:
out[parts[0]] = float(parts[1])
except ValueError:
pass
return out
factors = []
for i in range(reads):
factors.append(metrics().get("fly_realtime_factor", 0.0))
if i + 1 < reads:
time.sleep(1)
m = metrics()
try:
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
status = None
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}
PROBATION_PY='
import json, os, sys
def env(name, default):
return type(default)(os.environ.get(name, default))
WARMUP = env("FLY_PROBATION_WARMUP", 300.0)
WINDOW = env("FLY_PROBATION_WINDOW", 600.0)
MIN_SAMPLES = env("FLY_PROBATION_MIN_SAMPLES", 8)
MIN_RTF = env("FLY_PROBATION_MIN_RTF", 0.97)
MAX_LAG_GROWTH = env("FLY_PROBATION_MAX_LAG_GROWTH", 30.0)
DURATION = env("FLY_PROBATION_SECONDS", 1800.0)
MAX_SECONDS = env("FLY_PROBATION_MAX_SECONDS", 7200.0)
def running(s):
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
def median(xs):
xs = sorted(xs)
n = len(xs)
return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2
def step(state, s):
"""Returns (state, verdict, detail): verdict is wait, ok, pass or fail."""
started = state["startedAt"]
history = state.get("history", [])
elapsed = s["t"] - started
if not running(s):
return state, "wait", "flysim is %s: not judged" % s.get("status")
if history and s["uptime"] < history[-1]["uptime"]:
history = []
if s["uptime"] < WARMUP:
state["history"] = []
return state, "wait", "warming up (flysim up %.0f of %.0f s)" % (s["uptime"], WARMUP)
history = [h for h in history if h["t"] > s["t"] - WINDOW] + [s]
state["history"] = history
n = len(history)
if n < MIN_SAMPLES:
if elapsed >= MAX_SECONDS:
return state, "fail", "speed: probation inconclusive after %.0f s (%d judged samples in the window): no proof of 1.0x" % (elapsed, n)
return state, "wait", "collecting %d of %d samples" % (n, MIN_SAMPLES)
rtf = median([h["rtMean"] for h in history])
lag_growth = median([h["lag"] for h in history[-3:]]) - median([h["lag"] for h in history[:3]])
detail = "median realtime factor %.3f over %d samples, lag growth %+.1f s over %.0f s" % (
rtf, n, lag_growth, history[-1]["t"] - history[0]["t"])
state["last"] = {"medianRtf": rtf, "lagGrowth": lag_growth, "samples": n}
why = []
if rtf < MIN_RTF:
why.append("median realtime factor %.3f < %.2f" % (rtf, MIN_RTF))
if lag_growth > MAX_LAG_GROWTH:
why.append("lag grew %.1f s > %.0f s" % (lag_growth, MAX_LAG_GROWTH))
if why:
return state, "fail", "speed: " + ", ".join(why) + " over %d samples / %.0f s" % (
n, history[-1]["t"] - history[0]["t"])
if elapsed >= DURATION:
return state, "pass", detail
return state, "ok", detail + " (%.0f of %.0f s)" % (elapsed, DURATION)
mode = sys.argv[1]
if mode == "step":
state = json.load(open(sys.argv[2]))
state, verdict, detail = step(state, json.loads(sys.argv[3]))
json.dump(state, open(sys.argv[2], "w"))
print(verdict + " " + detail)
elif mode == "simulate":
samples = [json.loads(l) for l in open(sys.argv[2]) if l.strip()]
state = {"startedAt": samples[0]["t"] - 60, "history": []}
verdict, detail = "wait", ""
for n, s in enumerate(samples, 1):
state, verdict, detail = step(state, s)
if verdict in ("pass", "fail"):
print("%s at check %d: %s" % (verdict, n, detail))
sys.exit(0 if verdict == "pass" else 1)
print("undecided after %d checks: %s %s" % (len(samples), verdict, detail))
sys.exit(3)
'
now_iso() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
enabled_timer() { systemctl "$1" --now "$FLY_PROBATION_TIMER" >/dev/null 2>&1; }
start() {
need_root
take_lock
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
rm -f "$FLY_PROBATION_RESULT"
printf '{"startedAt":%s,"startedAtIso":"%s","history":[]}\n' "$(date +%s.%N)" "$(now_iso)" >"$STATE.tmp.$$"
mv -f "$STATE.tmp.$$" "$STATE"
if ! enabled_timer enable; then
rm -f "$STATE"
die "could not enable --now $FLY_PROBATION_TIMER (is the unit installed?)"
fi
journal "started: ${FLY_PROBATION_SECONDS:-1800} s, median realtime factor >= ${FLY_PROBATION_MIN_RTF:-0.97} over ${FLY_PROBATION_WINDOW:-600} s after ${FLY_PROBATION_WARMUP:-300} s warm-up, lag growth <= ${FLY_PROBATION_MAX_LAG_GROWTH:-30} s; else fallback to legacy"
}
cancel() {
local quiet=0
[ "${1:-}" = --quiet ] && quiet=1
need_root
take_lock
local had=0
if [ -f "$STATE" ]; then had=1; fi
rm -f "$STATE" "$FLY_PROBATION_RESULT"
enabled_timer disable || true
if [ "$had" -eq 1 ] || [ "$quiet" -eq 0 ]; then journal "cancelled"; fi
}
# The verdict, persisted in last.json (and in ${RESULT} on a pass).
finish() { # passed(true|false) detail state-file
local tmp="$LAST.tmp.$$"
python3 - "$1" "$2" "$3" >"$tmp" <<'PY'
import json, sys, datetime
passed, detail = sys.argv[1] == "true", sys.argv[2]
st = {}
try:
st = json.load(open(sys.argv[3]))
except Exception:
pass
out = {"passed": passed, "at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"startedAt": st.get("startedAtIso"), "detail": detail}
out.update(st.get("last", {}))
print(json.dumps(out))
PY
mv -f "$tmp" "$LAST"
if [ "$1" = true ]; then
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
cp -f "$LAST" "$FLY_PROBATION_RESULT"
fi
}
tick() {
need_root
local sample_json="" now out verdict detail rc
if [ "${1:-}" = --sample-json ]; then sample_json="$2"; fi # the test seam: a recorded sample
if [ ! -f "$STATE" ]; then
log "no probation: disabling $FLY_PROBATION_TIMER"
enabled_timer disable || true
exit 0
fi
# Only the session runtime is judged: a fallback, a legacy switch or a deploy that removed the
# drop-in ended it.
if [ "$("$RUNTIME_BIN" status 2>/dev/null | head -n1)" != session ]; then
journal "the session runtime is not selected; probation ends"
cancel --quiet
exit 0
fi
if [ -n "$sample_json" ]; then now="$sample_json"; else now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }; fi
take_lock
[ -f "$STATE" ] || { log "cancelled while sampling"; exit 0; }
rc=0
out="$(python3 -c "$PROBATION_PY" step "$STATE" "$now")" || rc=$?
[ "$rc" -eq 0 ] || die "probation rule failed: $out"
verdict="${out%% *}"
detail="${out#* }"
case "$verdict" in
wait|ok) drop_lock; log "$verdict: $detail" ;;
pass)
finish true "$detail" "$STATE"
rm -f "$STATE"
enabled_timer disable || true
journal "PASSED: $detail"
;;
fail)
cp -f "$STATE" "$STATE.failed.$$"
drop_lock
journal "FAILED: $detail; falling back to legacy"
if "$RUNTIME_BIN" fallback "$detail"; then
take_lock
finish false "$detail" "$STATE.failed.$$"
rm -f "$STATE" "$STATE.failed.$$"
enabled_timer disable || true
else
rm -f "$STATE.failed.$$"
log "fallback did not complete; probation stays and retries in a minute"
exit 1
fi
;;
*) die "unexpected verdict: $out" ;;
esac
}
status() {
if [ -f "$STATE" ]; then
python3 - "$STATE" <<'PY'
import json, sys
s = json.load(open(sys.argv[1]))
print("probation running since %s; %d judged samples in the window; last %s" % (
s.get("startedAtIso"), len(s.get("history", [])), json.dumps(s.get("last"))))
PY
else
echo "no probation running"
fi
if [ -f "$LAST" ]; then echo "last verdict: $(cat "$LAST")"; fi
if [ -f "$FLY_PROBATION_RESULT" ]; then echo "passed: $FLY_PROBATION_RESULT"; fi
}
cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
start) start ;;
cancel) cancel "$@" ;;
tick) tick "$@" ;;
status) status ;;
simulate) [ $# = 1 ] || die "simulate CHECKS.jsonl"; python3 -c "$PROBATION_PY" simulate "$1" ;;
*) echo "usage: fly-runtime-probation start|cancel|status|tick|simulate CHECKS.jsonl" >&2; exit 2 ;;
esac

View file

@ -1,630 +0,0 @@
#!/usr/bin/env bash
# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
# container, by the coordinator, with the container claimed in the host's agent claim log (one
# agent at a time).
#
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
# and the live-impact guard, restart flysim once. The shadow runs on a
# build box (SHADOW-02, below); --local runs it on this container
# instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
# restart; --restart-flysim restarts it now), remove trace and spool
# fly-shadow-run status the verdict in one screen
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
# into the release /opt/fly/current points to, onto flysim-session.
# --bus also requires that the shadow ran the bus topology (BUS-01)
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
# without the trace if the live fly pays for the shadow
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give
#
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
# only follow a process from that process's own startup save.
#
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
# it has compared.
#
# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run
# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset
# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed:
# - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means
# of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its
# spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent
# half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a
# step within the window neither sets the baseline nor widens the margin. It refuses to start
# on fewer than half the samples running.
# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim
# process (a restart starts the window again) it compares the mean RTF and the lag growth
# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it
# scales with how noisy this fly already was.
# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below
# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it.
# A paused, booting or recovering fly is not judged.
# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples;
# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/).
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow
# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own
# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
#
# THE BUS TOPOLOGY (BUS-01). `start --bus` runs the shadow's session the way `fly-runtime
# session --bus` runs the live one: the router, the coordinator and the task in the shadow's own
# process, the agent and the world as child processes (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release) on the router's Unix sockets. It sets
# FLY_SHADOW_MODE=bus/process in flyshadow.service's drop-in (mode.conf); a remote relay forwards it
# to the box (live.env), whose shadow reads it. The verdict records the topology
# (candidate.executionMode "process", candidate.transport "bus"), and `check --bus` refuses any
# verdict that did not run it. The live fly must run the LEGACY runtime while a shadow runs: only
# the legacy loop writes the trace (FLY_TRACE_DIR) the shadow follows, so `start` refuses while
# flysim.service runs the session runtime (fly-runtime status: session).
#
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
#
# Files (all owned by fly):
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
# /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB)
# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract)
# /srv/fly/shadow/divergence.json the first divergence with its context
# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl)
# /srv/fly/shadow/guard-state.json the guard's recent samples
# /srv/fly/shadow/relay.json remote mode: the relay's health
set -euo pipefail
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
DROPIN_DIR=/etc/systemd/system/flysim.service.d
DROPIN="$DROPIN_DIR/shadow-trace.conf"
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
MODE_DROPIN="$REMOTE_DROPIN_DIR/mode.conf"
RUNTIME_DROPIN="${FLY_RUNTIME_DROPIN:-$DROPIN_DIR/10-runtime.conf}"
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
# restarts for the new run and the ingest hashes the release first).
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
# The ledger digest period in transitions: about one a second. Every boundary is proved in the
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}"
die() { echo "fly-shadow-run: $*" >&2; exit 2; }
log() { echo "fly-shadow-run: $*"; }
need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }
# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged
# over 10 one-second reads.
sample() {
python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url = sys.argv[1], sys.argv[2]
def metrics():
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
out = {}
for line in text.splitlines():
if line.startswith("#"):
continue
parts = line.split()
if len(parts) == 2:
try:
out[parts[0]] = float(parts[1])
except ValueError:
pass
return out
factors = []
for _ in range(10):
factors.append(metrics().get("fly_realtime_factor", 0.0))
time.sleep(1)
m = metrics()
try:
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
status = None
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}
# The guard's rule, one definition for `baseline`, `decide` and `simulate`.
GUARD_PY='
import json, math, sys
WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05
def running(s):
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
def rate(samples):
"""Lag growth per wall second over the longest same-process run of samples."""
best, run = None, []
for s in samples:
if run and s["uptime"] < run[-1]["uptime"]:
run = []
run.append(s)
if len(run) >= 2 and (best is None or len(run) > len(best)):
best = list(run)
if not best or best[-1]["t"] <= best[0]["t"]:
return None
return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"]))
def baseline(samples):
"""Robust statistics of the running samples: a step in the live fly within the window (its own
warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long
as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the
median absolute deviation, which estimates the standard deviation without the step; the lag
growth rate is taken over the most recent half, after any early step."""
ok = [s for s in samples if running(s)]
if len(ok) < max(3, len(samples) // 2):
raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples)))
recent = ok[len(ok) // 2:]
rtf = sorted(s["rtMean"] for s in ok)
median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2
dev = sorted(abs(x - median) for x in rtf)
mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2
sd = 1.4826 * mad
lag_rate = rate(recent)
return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0,
"samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))}
def decide(base, state, s):
"""Returns (state, verdict); the verdict starts with ok or trip."""
history, run = state.get("history", []), state.get("degradedRun", 0)
if not running(s):
return state, "ok (flysim is %s: not judged)" % s.get("status")
if history and s["uptime"] < history[-1]["uptime"]:
history, run = [], 0
history = (history + [s])[-WINDOW:]
state = {"history": history, "degradedRun": run}
if len(history) < WINDOW:
state["degradedRun"] = 0
return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW)
rtf = sum(h["rtMean"] for h in history) / WINDOW
lag_rate = rate(history) or 0.0
m = base["margin"]
why = []
if rtf < base["rtfMean"] - m:
why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m))
if lag_rate > base["lagRate"] + m:
why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m))
state["degradedRun"] = run + 1 if why else 0
if state["degradedRun"] >= SUSTAIN:
return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"]
if why:
return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why))
return state, "ok"
def load_jsonl(path):
return [json.loads(line) for line in open(path) if line.strip()]
mode = sys.argv[1]
if mode == "baseline":
print(json.dumps(baseline(load_jsonl(sys.argv[2]))))
elif mode == "decide":
base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
state, verdict = decide(base, state, json.load(open(sys.argv[4])))
json.dump(state, open(sys.argv[3], "w"))
print(verdict)
sys.exit(1 if verdict.startswith("trip") else 0)
elif mode == "simulate":
base = baseline(load_jsonl(sys.argv[2]))
state, n = {}, 0
for n, s in enumerate(load_jsonl(sys.argv[3]), 1):
state, verdict = decide(base, state, s)
if verdict.startswith("trip"):
print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base)))
sys.exit(1)
print("no trip over %d checks (baseline %s)" % (n, json.dumps(base)))
'
# The shadow must never share a CPU with the live fly (review N2): refuse unless the unit's cpuset
# drop-in exists (05-deploy skips every cpuset drop-in when the CT conf and CPUSET disagree) and its
# AllowedCPUs is non-empty and disjoint from flysim.service's.
check_cpuset() {
local dropin="${FLY_SHADOW_CPUSET_DROPIN:-/etc/systemd/system/flyshadow.service.d/cpuset.conf}"
[ -f "$dropin" ] || die "$dropin is missing: flyshadow would run on every CPU, including flysim's. Run 05-deploy with CPUSET set; nothing started"
local shadow_cpus sim_cpus
shadow_cpus="$(systemctl show -p AllowedCPUs --value flyshadow.service 2>/dev/null || true)"
sim_cpus="$(systemctl show -p AllowedCPUs --value flysim.service 2>/dev/null || true)"
[ -n "$shadow_cpus" ] || die "flyshadow.service has an empty AllowedCPUs; nothing started"
[ -n "$sim_cpus" ] || die "flysim.service has an empty AllowedCPUs, so the shadow cannot be kept off it; nothing started"
local overlap rc=0
overlap="$(python3 -c '
import sys
def cpus(t):
out = set()
for part in t.replace(",", " ").split():
a, _, b = part.partition("-")
out.update(range(int(a), int(b or a) + 1))
return out
try:
both = cpus(sys.argv[1]) & cpus(sys.argv[2])
except ValueError:
sys.exit(2)
if both:
print(",".join(str(c) for c in sorted(both)))
sys.exit(1)
' "$shadow_cpus" "$sim_cpus" 2>/dev/null)" || rc=$?
case "$rc" in
0) ;;
1) die "flyshadow.service AllowedCPUs ($shadow_cpus) overlaps flysim.service's ($sim_cpus) on CPU $overlap; nothing started" ;;
*) die "cannot parse AllowedCPUs (flyshadow '$shadow_cpus', flysim '$sim_cpus'); nothing started" ;;
esac
}
# Remote mode's prerequisites, checked before anything changes.
check_remote() {
[ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
local target key known
target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
[ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
{ [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
{ [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
[ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
}
start() {
need_root
local mode=remote arm=""
for arg in "$@"; do
case "$arg" in
--local) mode=local ;;
--bus) arm=bus/process ;;
*) die "start: unknown option $arg" ;;
esac
done
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
# Only the legacy loop writes the trace the shadow follows (FLY_TRACE_DIR); the session runtime
# ignores it, and every process it ran would be a coverage divergence.
[ ! -f "$RUNTIME_DROPIN" ] || die "flysim.service runs the session runtime, which writes no trace for a shadow to follow. Switch the live fly to legacy for the shadow window first (fly-runtime legacy), then start the shadow"
if [ -n "$arm" ]; then
[ -x "$(dirname "$(readlink -f "$BIN")")/fly-session" ] || die "the bus topology needs fly-session beside $BIN"
fi
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
if [ "$mode" = remote ]; then
[ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
check_remote
fi
check_cpuset
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
# A previous run's verdict is kept beside, never read as this run's.
if [ -f "$SHADOW_DIR/verdict.json" ]; then
mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
fi
rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists"
local n samples base
n=$(( BASELINE_SECONDS / 10 ))
[ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30"
samples="$SHADOW_DIR/baseline-samples.jsonl"
: > "$samples"
for _ in $(seq 1 "$n"); do
sample >> "$samples" || die "could not read flysim's metrics for the baseline"
done
base="$(python3 -c "$GUARD_PY" baseline "$samples")" \
|| die "flysim did not run normally during the baseline; not starting the shadow"
printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
printf '{}\n' > "$SHADOW_DIR/guard-state.json"
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
log "baseline: $base"
mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
if [ -n "$arm" ]; then
cat > "$MODE_DROPIN" <<EOF
# written by fly-shadow-run start --bus (BUS-01); removed by fly-shadow-run stop and by its guard.
# The shadow's session runs the bus topology; a remote relay forwards this to the box.
[Service]
Environment=FLY_SHADOW_MODE=$arm
EOF
log "the shadow runs the bus topology ($arm)"
else
rm -f "$MODE_DROPIN"
fi
if [ "$mode" = remote ]; then
local run_id
run_id="$(date +%s%3N)"
[ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
cat > "$REMOTE_DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
[Service]
EnvironmentFile=$REMOTE_ENV
Environment=FLY_SHADOW_RUN_ID=$run_id
ExecStart=
ExecStart=$BIN relay
CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=1G
EOF
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
else
rm -f "$REMOTE_DROPIN"
log "LOCAL shadow on this container (--local)"
fi
cat > "$DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service]
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
EOF
systemctl daemon-reload
rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the
# relay writes it once the box's shadow of this run is alive and the sync is caught up).
for _ in $(seq 1 "$HEARTBEAT_WAIT"); do
[ -f "$SHADOW_DIR/trace/consumer" ] && break
sleep 1
done
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; }
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
systemctl restart flysim.service
systemctl start flyshadow-guard.timer
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
}
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
stop_all() {
systemctl stop flyshadow-guard.timer 2>/dev/null || true
systemctl stop flyshadow.service 2>/dev/null || true
rm -f "$DROPIN" "$REMOTE_DROPIN" "$MODE_DROPIN"
systemctl daemon-reload
log "stopped the shadow: $1"
}
stop() {
need_root
local restart_flysim=0 keep=0
for arg in "$@"; do
case "$arg" in
--restart-flysim) restart_flysim=1 ;;
--keep) keep=1 ;;
*) die "stop: unknown option $arg" ;;
esac
done
stop_all "fly-shadow-run stop"
if [ "$restart_flysim" = 1 ]; then
systemctl restart flysim.service
log "flysim.service restarted without the trace"
else
log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
fi
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
if [ "$keep" = 0 ]; then
rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
fi
log "the verdict stays in $SHADOW_DIR/verdict.json"
}
# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit
# waiting out its restart delay, activating/auto-restart, from a stopped one).
unit_state() {
local out active
out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true
active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')"
# An unreadable state is not "stopped": the guard keeps running and judges the fly.
case "$active" in
active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;;
*) printf 'unknown\n' ;;
esac
}
guard() {
need_root
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
log "no baseline: nothing to guard"
systemctl stop flyshadow-guard.timer 2>/dev/null || true
exit 0
fi
# The guard acts only against a shadow that is up or on its way up. One that diverged, passed
# and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and
# flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay
# (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must
# keep running, or the restarted shadow runs unguarded while `check` still allows a cutover
# (SHADOW-01 review round 3, G1-a).
local active_state
active_state="$(unit_state flyshadow.service)"
case "$active_state" in
inactive|failed)
log "flyshadow.service is $active_state: the guard stops itself and changes nothing"
systemctl stop flyshadow-guard.timer 2>/dev/null || true
exit 0
;;
esac
[ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json"
local now tmp verdict
now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
tmp="$(mktemp)"
printf '%s\n' "$now" > "$tmp"
if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then
rm -f "$tmp"
log "guard: $verdict ($now)"
exit 0
fi
rm -f "$tmp"
log "guard TRIPPED: $verdict ($now)"
stop_all "guard: $verdict"
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
"$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
systemctl restart flysim.service
log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
}
status() {
systemctl is-active flyshadow.service || true
systemctl is-active flyshadow-guard.timer || true
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
python3 - "$SHADOW_DIR/relay.json" <<'PY'
import json, sys
r = json.load(open(sys.argv[1]))
print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
PY
fi
[ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
python3 - "$SHADOW_DIR/verdict.json" <<'PY'
import json, sys
v = json.load(open(sys.argv[1]))
c = v["compared"]
print(f"verdict {v['status']}: {v['reason']}")
print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s "
f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
if v["firstDivergence"]:
print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
PY
}
check() {
# `--bus` (BUS-01): the cutover goes onto the bus topology, so the shadow must have run it.
local -a pass=()
local arg
for arg in "$@"; do
case "$arg" in
--bus) pass+=(--require-arm bus/process) ;;
*) pass+=("$arg") ;;
esac
done
set -- "${pass[@]}"
# Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session
# runtime during the window, the verdict no longer covers what would be cut over.
if [ -f "$RUNTIME_DROPIN" ]; then
echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)"
exit 1
fi
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
# present (G1-a).
if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then
echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))"
exit 1
fi
if ! systemctl is-active --quiet flyshadow.service; then
echo "cutover refused: flyshadow.service is not running"
exit 1
fi
if ! systemctl is-active --quiet flyshadow-guard.timer; then
echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)"
exit 1
fi
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
exit 1
fi
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
local why rc=0 run_id=""
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
import datetime, json, sys
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
def refuse(msg):
print(msg); sys.exit(1)
try:
v = json.load(open(verdict_path))
except Exception:
v = {}
if mode == "local":
if v.get("runId") is not None:
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
sys.exit(0)
if not run_id:
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
try:
r = json.load(open(relay_path))
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
refuse("no readable relay.json (%s)" % e)
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
refuse("relay.json is %.0f s old" % age)
if r.get("runId") != run_id:
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
if v.get("runId") != run_id:
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
if v.get("window") is None:
refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
if r.get("coverageLost"):
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
if not r.get("healthy"):
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
ta = r.get("traceAgeSeconds")
if ta is None:
refuse("no live trace file of this run")
if ta > 90:
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
PY
)" || rc=$?
if [ "$rc" != 0 ]; then
echo "cutover refused: remote shadow: $why"
exit 1
fi
[ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string. fly.env is systemd's
# EnvironmentFile syntax (GAME_TITLE=Pokemon Red is valid there), so it is read as KEY=VALUE
# lines, as fly-runtime does, never sourced as shell.
local line key value env_file="${FLY_ENV_FILE:-/etc/fly/fly.env}"
if [ -f "$env_file" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
key="${line%%=*}"
value="${line#*=}"
value="${value%\"}"
value="${value#\"}"
export "${key}=${value}"
done <"$env_file"
fi
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current "${FLY_CURRENT_DIR:-/opt/fly/current}" \
--binary flysim-session "$@"
}
cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
start) start "$@" ;;
stop) stop "$@" ;;
status) status ;;
check) check "$@" ;;
guard) guard ;;
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
*) echo "usage: fly-shadow-run start [--local]|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
esac

View file

@ -32,9 +32,6 @@ log_info() {
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}" : "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}" : "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
# flyedge's loopback /metrics (units/flyedge.service), read by check 2 when
# fly.env says FLY_FEED_VIA=bus.
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
: "${FLY_STATE_HOT:=/run/fly/state}" : "${FLY_STATE_HOT:=/run/fly/state}"
: "${FLY_MEDIA_DIR:=/srv/fly/media}" : "${FLY_MEDIA_DIR:=/srv/fly/media}"
: "${MEDIAMTX_API:=http://127.0.0.1:9997}" : "${MEDIAMTX_API:=http://127.0.0.1:9997}"
@ -48,9 +45,6 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5). # encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}"
# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick.
: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}"
: "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
: "${FFMPEG:=/usr/bin/ffmpeg}" : "${FFMPEG:=/usr/bin/ffmpeg}"
@ -73,9 +67,6 @@ log_info() {
: "${WD_LOOP_MIN_REPEATS:=20}" # ... repeating at least this many times : "${WD_LOOP_MIN_REPEATS:=20}" # ... repeating at least this many times
: "${WD_LOOP_DOMINANCE_PCT:=95}" # or one macro being this share of the window : "${WD_LOOP_DOMINANCE_PCT:=95}" # or one macro being this share of the window
: "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10) : "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10)
: "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57)
: "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58)
: "${WD_LOOP_FIGHT_MIN:=24}" # this many MOVE n decisions with no battle won and no new ground, two probes running, is battles lost on repeat (row 67)
: "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}" : "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}"
mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR" mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR"
@ -159,7 +150,7 @@ write_textfile_metrics() {
{ {
echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)." echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)."
echo "# TYPE fly_watchdog_restarts_total counter" echo "# TYPE fly_watchdog_restarts_total counter"
for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do for unit in flysim flystage flycast mediamtx flypush flystage-web; do
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")" echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
done done
# Check 7's own restart reason, kept as a separate labelset on the # Check 7's own restart reason, kept as a separate labelset on the
@ -177,9 +168,6 @@ write_textfile_metrics() {
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "# TYPE fly_watchdog_encoder_degraded gauge"
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)"
echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend."
echo "# TYPE fly_watchdog_backend_degraded gauge"
echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)"
# Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
# is -1 until the first probe completes, the same "unknown, not # is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or # broken" convention fly_watchdog_encoder_degraded uses; a value at or
@ -199,7 +187,7 @@ write_textfile_metrics() {
# convention as fly_watchdog_encoder_degraded), while the flag itself # convention as fly_watchdog_encoder_degraded), while the flag itself
# starts at 0, because a 0/1 flag carrying -1 reads as a loop to every # starts at 0, because a 0/1 flag carrying -1 reads as a loop to every
# alert expression that would ever use it. # alert expression that would ever use it.
echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked), completing nothing, earning nothing or winning no battle, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this." echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this."
echo "# TYPE fly_loop_suspected gauge" echo "# TYPE fly_loop_suspected gauge"
echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)." echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)."
@ -211,29 +199,6 @@ write_textfile_metrics() {
echo "# HELP fly_loop_distinct_macros Distinct macro names started in the window (-1 before the first probe)." echo "# HELP fly_loop_distinct_macros Distinct macro names started in the window (-1 before the first probe)."
echo "# TYPE fly_loop_distinct_macros gauge" echo "# TYPE fly_loop_distinct_macros gauge"
echo "fly_loop_distinct_macros $(cat "${WD_RUN_DIR}/loop.distinct" 2>/dev/null || echo -1)" echo "fly_loop_distinct_macros $(cat "${WD_RUN_DIR}/loop.distinct" 2>/dev/null || echo -1)"
# Row 57: outcomes, not only starts. A pad whose one button refuses
# every hold reads as one start and one name; these say what the
# decisions came to (-1 before the first probe).
echo "# HELP fly_loop_refused Macro presses refused (nothing pressed) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_refused gauge"
echo "fly_loop_refused $(cat "${WD_RUN_DIR}/loop.refused" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_blocked Macros that ended blocked or timed out in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_blocked gauge"
echo "fly_loop_blocked $(cat "${WD_RUN_DIR}/loop.blocked" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_done Macros that ended done in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_done gauge"
echo "fly_loop_done $(cat "${WD_RUN_DIR}/loop.done" 2>/dev/null || echo -1)"
# Row 58: an undo pair diluted by other macros completes everything and
# earns nothing; the reward events in the window are what say so.
echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_rewards gauge"
echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_fights MOVE n decisions (a move chosen in a battle) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_fights gauge"
echo "fly_loop_fights $(cat "${WD_RUN_DIR}/loop.fights" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_wins Battle-won reward events (rewardKind wildwin, trainer or badge) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_wins gauge"
echo "fly_loop_wins $(cat "${WD_RUN_DIR}/loop.wins" 2>/dev/null || echo -1)"
echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against." echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against."
echo "# TYPE fly_places_delta gauge" echo "# TYPE fly_places_delta gauge"
echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)" echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)"
@ -332,30 +297,9 @@ is_enabled() {
# ============================================================================ # ============================================================================
# Check 1: flysim — /healthz 200 and hot-state mtime age < 30s. # Check 1: flysim — /healthz 200 and hot-state mtime age < 30s.
# ============================================================================ # ============================================================================
# FLY_CONTROL_VIA from fly.env, lowercased ("direct" when absent).
control_via() {
local via=""
if [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_CONTROL_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
echo "${via:-direct}"
}
# flysim's own /healthz: :7401 when flysim serves it, and with FLY_CONTROL_VIA=bus
# (docs/design/flybus.md, "Control over the bus") flysim's read-only listener,
# which flysim serves itself in both modes -- so an edge that is down is check
# 1b's business and never restarts the fly.
flysim_health_url() {
if [ "$(control_via)" = "bus" ]; then
echo "${FLY_METRICS_URL}/healthz"
else
echo "${FLY_CONTROL_URL}/healthz"
fi
}
check_flysim() { check_flysim() {
local ok=1 local ok=1
if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
ok=0 ok=0
fi fi
if [ -e "$FLY_STATE_HOT" ]; then if [ -e "$FLY_STATE_HOT" ]; then
@ -373,116 +317,15 @@ check_flysim() {
fi fi
} }
# ============================================================================
# Check 1b: flycontrol-edge -- only with FLY_CONTROL_VIA=bus. :7401/healthz
# answered by the edge while flysim's own /healthz is fine; when the edge does
# not answer, restart the edge (never flysim, never a reboot: the fly is fine
# and the edge holds no state). With flysim itself down, check 1 owns it.
# ============================================================================
check_control_edge() {
[ "$(control_via)" = "bus" ] || return 0
curl -fsS -o /dev/null "${FLY_METRICS_URL}/healthz" || return 0
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
record_ok flycontrol-edge
else
record_fail flycontrol-edge
log_err "flycontrol-edge: :7401 does not answer while flysim is healthy; restarting the edge"
restart_unit flycontrol-edge
fi
}
# ============================================================================ # ============================================================================
# Check 2: flystage — flysim's frames_sent_total / feed_clients from the # Check 2: flystage — flysim's frames_sent_total / feed_clients from the
# read-only metrics listener (infra.md section 5; not superseded by the # read-only metrics listener (infra.md section 5; not superseded by the
# feed/control contracts). Flat frames counter across two passes, or zero # feed/control contracts). Flat frames counter across two passes, or zero
# clients, means the page is dead/frozen even though Chromium is alive. # clients, means the page is dead/frozen even though Chromium is alive.
#
# The two counters belong to whoever serves the feed: flysim itself, or with
# FLY_FEED_VIA=bus in fly.env, flyedge (docs/design/flybus.md, "Feed over the
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
# watchdog's own environment overrides both.
# ============================================================================ # ============================================================================
# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of
# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the
# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next
# restart, and judging the edge in that window would restart a flysim that is serving the feed
# itself. So: the running process when its environment can be read (flysim runs as the same user),
# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or
# no line, is direct.
feed_via() {
local via="" pid=""
pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)"
if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then
via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
elif [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then echo bus; else echo direct; fi
}
feed_metrics_url() {
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
echo "$FLY_FEED_METRICS_URL"
return
fi
if [ "$(feed_via)" = "bus" ]; then
echo "$FLY_EDGE_METRICS_URL"
else
echo "$FLY_METRICS_URL"
fi
}
# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200
# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down
# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go:
# a flysim that has only just answered may not have published yet. After that:
# 2nd consecutive failure restart flyedge (the escalation's restart)
# 3rd and the page and the encoder (escalate's chain)
# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed
# direct --no-wait` (a restart of flysim, one stream gap, then the page
# is served again by the process that always worked). It is logged as
# an escalation and leaves FLY_FEED_VIA=direct until an operator
# switches again; this check then does nothing.
check_flyedge() {
if [ "$(feed_via)" != "bus" ]; then
record_ok flyedge
return 0
fi
if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
return 0
fi
if is_active flyedge.service \
&& curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
record_ok flyedge
return 0
fi
record_fail flyedge
local n
n="$(fail_count flyedge)"
# From the 4th consecutive failure on, whatever the time the failures were spread over (passes
# are skipped while flysim is down, so a flapping flysim stretches the run past any window): the
# fallback to direct comes first and a reboot is never the answer to an edge fault. Only
# n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on
# the next pass instead of falling through to it.
if [ "$n" -ge 4 ]; then
log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)"
inc_counter "escalations_total"
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"
record_ok flyedge
elif [ "$n" -ge 2 ]; then
escalate flyedge flystage flycast
fi
}
check_flystage() { check_flystage() {
local metrics frames clients ok=1 chain=(flycast) local metrics frames clients ok=1
if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then metrics="$(curl -fsS "${FLY_METRICS_URL}/metrics" 2>/dev/null || true)"
# The edge serves the page. While it is down or silent that is check 2a's to fix, and a
# restarted page would only reconnect to nothing (and count towards a reboot).
curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0
chain=(flyedge flycast)
fi
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
if [ -z "$metrics" ]; then if [ -z "$metrics" ]; then
ok=0 ok=0
else else
@ -508,7 +351,7 @@ check_flystage() {
record_ok flystage record_ok flystage
else else
record_fail flystage record_fail flystage
escalate flystage "${chain[@]}" escalate flystage flycast
fi fi
} }
@ -716,39 +559,6 @@ check_encoder() {
"and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv"
} }
# ============================================================================
# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the
# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks
# for the card and the CPU is what runs, the GPU fell back (operator decision
# 2026-10-02: automatic, the stream keeps going, logged here, no paging).
#
# Like check 8 this takes NO remediation. A restart cannot repair a dead card
# and costs the run its in-memory state; the fallback is a CPU run from the
# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the
# card to a human. fly_brain_backend is not duplicated into this file's own
# .prom, for the reason check 8 gives.
# ============================================================================
check_backend() {
local wanted live fallbacks
if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then
# No session worker has written it (the legacy loop, a CPU deploy, or not started yet).
echo -1 > "${WD_RUN_DIR}/backend_degraded"
return 0
fi
wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
live="$(awk '/^fly_brain_backend\{/ && $NF == 1 {
if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \
"$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then
echo 1 > "${WD_RUN_DIR}/backend_degraded"
log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \
"Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'"
else
echo 0 > "${WD_RUN_DIR}/backend_degraded"
fi
}
# ============================================================================ # ============================================================================
# Check 9: capture freeze (infra/docs/capture-freeze.md). # Check 9: capture freeze (infra/docs/capture-freeze.md).
# #
@ -926,48 +736,10 @@ check_capture_freeze() {
# time, not wall time — a box running under 1.0x realtime would otherwise get # time, not wall time — a box running under 1.0x realtime would otherwise get
# a shorter window than the thresholds were measured over), the distinct macro # a shorter window than the thresholds were measured over), the distinct macro
# names in it, and the shortest block up to WD_LOOP_MAX_PERIOD that repeats at # names in it, and the shortest block up to WD_LOOP_MAX_PERIOD that repeats at
# the end of the sequence. The sequence is the fly's DECISIONS: a `start`, or a # the end of the sequence. Start events only: a start is one decision, and
# `refused` (a bound button that was pressed and did nothing, with no start # counting the `done` beside it would double every sequence and halve every
# beside it). Counting the `done` beside a start would double every sequence # period. They are the same names trap_hunt prints, so its numbers and these
# and halve every period. They are the same names trap_hunt prints, so its # are comparable.
# numbers and these are comparable.
#
# Row 57 (macros-traps.md): counting starts alone was blind to a pad whose
# one button refused. `GO ROUTE refused` ~740 times per 10 brain minutes for
# two hours read as 1 start, 1 distinct name, nothing flagged. So the window
# also counts every OUTCOME (done/blocked/timeout/refused), and two rules read
# them, both behind the same "no new ground" gate as the others:
# stalled — WD_LOOP_MIN_EVENTS+ decisions and WD_LOOP_STALL_PCT% of
# them ended refused, blocked or timed out;
# zero-progress — decisions in the window, not one `done` among them, on
# this probe AND the previous one (two probes, so a single
# unlucky window never flags).
#
# Row 58: `GO OBJECTIVE` into the Pewter Gym, `GO OUT` straight back out, for
# 25 minutes, with GO ITEM / GO FRONTIER / YES / NO mixed in — ten distinct
# names, every macro `done`, so neither the sequence rule (four names at
# most) nor zero-progress could fire, and the exploration count sat still.
# What the window did not have was a single reward event. So the stream also
# carries the `reward` events, and one more rule reads them, behind the same
# gate:
# unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the
# window, on this probe AND the previous one.
#
# Row 67: the Pewter Gym, one trainer lost ~30 times in a row. The readout
# chose TAIL WHIP six turns in seven, Squirtle fainted every time, the fly
# whited out to Pewter and walked straight back in: MOVE 2 / NEXT / GO
# OBJECTIVE / TALK / NO, seven names, every macro `done`. Two stray tile
# rewards (a new tile of the gym on a whiteout's walk back) reset the
# unrewarded rule for ~45 minutes. What the window never had was a battle WON.
# So the reward lines carry their rewardKind, and one more rule reads them,
# behind the same gate:
# unwon-battles — WD_LOOP_FIGHT_MIN+ `MOVE n` decisions and no reward of
# kind wildwin, trainer or badge in the window, on this
# probe AND the previous one.
# The feed has no HP (docs/feed-protocol.md), so "a battle that makes no
# progress" is read as moves chosen and nothing won. Measured on the live log:
# healthy windows had 13-46 MOVE starts and 1-4 wins (the one 22-move window
# with no win also had new ground); the trap had 30-39 and none.
# #
# The tile rule is what separates a loop from a legitimately repeating # The tile rule is what separates a loop from a legitimately repeating
# explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer # explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer
@ -1019,72 +791,32 @@ loop_status_fields() {
loop_macro_stream() { loop_macro_stream() {
[ -f "$FLY_EVENT_LOG" ] || return 0 [ -f "$FLY_EVENT_LOG" ] || return 0
tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \ tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward" or .kind == "milestone") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \ | jq -r 'fromjson? // empty | select(.kind == "macro") | "\(.brainMs)\t\(.label)"' -R 2>/dev/null \
|| true || true
} }
# loop_analyze — reads that stream on stdin and echoes one tab-separated line: # loop_analyze — reads that stream on stdin and echoes one tab-separated line:
# #
# total US distinct US topCount US period US repeats US windowFrom US # total US distinct US topCount US period US repeats US windowFrom US
# windowTo US topName US block US tail US decisions US refused US blocked US # windowTo US topName US block US tail
# timeout US done US rewards US fights US wins US progress US species US keys
# #
# `total` counts start events inside the window, `decisions` starts plus # `total` counts start events inside the window, `period`/`repeats` describe
# refusals (the sequence, `distinct` and `topCount` are over decisions), and
# the next four count each outcome in the window, and `rewards` the reward
# events in it (row 58), `fights` the `MOVE n` decisions and `wins` the
# rewards of kind wildwin/trainer/badge (row 67). `progress` counts the lasting
# progress in the window (row 70): a `milestone` event (a new rung), or a reward of kind
# pokedex (a species owned for the first time), area (a map entered for the first time),
# trainer or badge -- each paid once per run, so a ring cannot earn them twice -- and
# `species` the pokedex ones alone. `keys` names each of them once as `kind:label`
# (`pokedex:OWNED #8`, `milestone:Reached MT. MOON`), RS-joined, at most 64: a milestone
# reset restores the reward ledger, so its replay pays the same rewards again, and only
# the names tell a replayed reward from a new one. They are reported, never read by a
# rule here: the recovery ladder uses them to tell a trap that follows real progress from
# one that outlived its last step. `period`/`repeats` describe
# the shortest repeating block at the END of the sequence (0/0 when nothing # the shortest repeating block at the END of the sequence (0/0 when nothing
# repeats), `block` is that block comma-joined, and `tail` is the last 12 # repeats), `block` is that block comma-joined, and `tail` is the last 12
# names for context. The window ends at the newest macro event's own brain # names for context. The window ends at the newest macro event's own brain
# clock, not at `now`: brain time is the only clock the event log carries. # clock, not at `now`: brain time is the only clock the event log carries.
loop_analyze() { loop_analyze() {
awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" ' awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" '
# Reward lines are counted and nothing else: the window still ends at the { ms[NR] = $1 + 0; lbl[NR] = $2; n = NR }
# newest macro event, as it always has.
$3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; rlbl[nr] = $2; next }
$3 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; rlbl[nr] = $2; next }
{ ms[++n] = $1 + 0; lbl[n] = $2 }
END { END {
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\0370\0370\037\n"; exit } if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\n"; exit }
to = ms[n]; from = to - win to = ms[n]; from = to - win
k = 0; distinct = 0; topn = 0; top = "" k = 0; distinct = 0; topn = 0; top = ""
starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0
fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) {
lasting = rkind[q] == "milestone" || rkind[q] == "pokedex" || rkind[q] == "area" \
|| rkind[q] == "trainer" || rkind[q] == "badge"
if (lasting) {
progress++
key = rkind[q] ":" rlbl[q]
gsub(/[\036\037]/, " ", key)
if (!(key in seenkey) && nkeys < 64) { seenkey[key] = 1; keys = keys (nkeys++ ? "\036" : "") key }
}
if (rkind[q] == "milestone") continue
rewards++
if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++
if (rkind[q] == "pokedex") species++
}
for (i = 1; i <= n; i++) { for (i = 1; i <= n; i++) {
if (ms[i] < from) continue if (ms[i] < from) continue
if (lbl[i] ~ / blocked$/) { blocked++; continue } if (lbl[i] !~ / start$/) continue
if (lbl[i] ~ / timeout$/) { timeout++; continue } name = lbl[i]; sub(/ start$/, "", name)
if (lbl[i] ~ / done$/) { done++; continue }
if (lbl[i] ~ / refused$/) refused++
else if (lbl[i] ~ / start$/) starts++
else continue
name = lbl[i]; sub(/ (start|refused)$/, "", name)
seq[++k] = name seq[++k] = name
if (name ~ /^MOVE [1-4]$/) fights++
if (!(name in cnt)) { cnt[name] = 0; distinct++ } if (!(name in cnt)) { cnt[name] = 0; distinct++ }
cnt[name]++ cnt[name]++
if (cnt[name] > topn) { topn = cnt[name]; top = name } if (cnt[name] > topn) { topn = cnt[name]; top = name }
@ -1107,9 +839,8 @@ loop_analyze() {
tailstr = "" tailstr = ""
start = k - 11; if (start < 1) start = 1 start = k - 11; if (start < 1) start = 1
for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j] for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j]
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\n", \ printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\n", \
starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \ k, distinct, topn, period, repeats, from, to, top, block, tailstr
k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys
}' }'
} }
@ -1167,24 +898,13 @@ check_loop() {
echo "$delta" > "${WD_RUN_DIR}/loop.places_delta" echo "$delta" > "${WD_RUN_DIR}/loop.places_delta"
local analysis total distinct topn period repeats win_from win_to top block tailstr local analysis total distinct topn period repeats win_from win_to top block tailstr
local decisions refused blocked timeouts completed rewards fights wins progress species keys
analysis="$(loop_macro_stream | loop_analyze)" analysis="$(loop_macro_stream | loop_analyze)"
IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \ IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr <<< "$analysis"
decisions refused blocked timeouts completed rewards fights wins progress species keys <<< "$analysis"
total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}" total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}"
period="${period:-0}"; repeats="${repeats:-0}" period="${period:-0}"; repeats="${repeats:-0}"
decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}"
timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}"
fights="${fights:-0}"; wins="${wins:-0}"; progress="${progress:-0}"; species="${species:-0}"
echo "$distinct" > "${WD_RUN_DIR}/loop.distinct" echo "$distinct" > "${WD_RUN_DIR}/loop.distinct"
echo "$period" > "${WD_RUN_DIR}/loop.period" echo "$period" > "${WD_RUN_DIR}/loop.period"
echo "$repeats" > "${WD_RUN_DIR}/loop.repeats" echo "$repeats" > "${WD_RUN_DIR}/loop.repeats"
echo "$refused" > "${WD_RUN_DIR}/loop.refused"
echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked"
echo "$completed" > "${WD_RUN_DIR}/loop.done"
echo "$rewards" > "${WD_RUN_DIR}/loop.rewards"
echo "$fights" > "${WD_RUN_DIR}/loop.fights"
echo "$wins" > "${WD_RUN_DIR}/loop.wins"
local prev_suspected=0 local prev_suspected=0
[ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" [ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
@ -1197,70 +917,25 @@ check_loop() {
local grown=1 local grown=1
[ "$delta_known" -eq 1 ] && [ "$delta" -le 0 ] && grown=0 [ "$delta_known" -eq 1 ] && [ "$delta" -le 0 ] && grown=0
# Zero progress is judged over two probes: a window with decisions and no
# `done` among them is remembered, and only a second one in a row flags.
local idle_file="${WD_RUN_DIR}/loop.prev_idle" prev_idle=0 idle=0
[ -f "$idle_file" ] && prev_idle="$(cat "$idle_file" 2>/dev/null || echo 0)"
case "${prev_idle:-}" in ''|*[!0-9]*) prev_idle=0 ;; esac
[ "$decisions" -gt 0 ] && [ "$completed" -eq 0 ] && [ "$grown" -eq 0 ] && idle=1
echo "$idle" > "$idle_file"
# Busy going nowhere (row 58), judged over two probes like zero progress:
# many decisions, not one reward event, no new ground.
local busy_file="${WD_RUN_DIR}/loop.prev_unrewarded" prev_busy=0 busy=0
[ -f "$busy_file" ] && prev_busy="$(cat "$busy_file" 2>/dev/null || echo 0)"
case "${prev_busy:-}" in ''|*[!0-9]*) prev_busy=0 ;; esac
[ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1
echo "$busy" > "$busy_file"
# Battles lost on repeat (row 67), judged over two probes like the two
# above: moves chosen, no battle won, no new ground.
local unwon_file="${WD_RUN_DIR}/loop.prev_unwon" prev_unwon=0 unwon=0
[ -f "$unwon_file" ] && prev_unwon="$(cat "$unwon_file" 2>/dev/null || echo 0)"
case "${prev_unwon:-}" in ''|*[!0-9]*) prev_unwon=0 ;; esac
[ "$fights" -ge "$WD_LOOP_FIGHT_MIN" ] && [ "$wins" -eq 0 ] && [ "$grown" -eq 0 ] && unwon=1
echo "$unwon" > "$unwon_file"
local failed=$(( refused + blocked + timeouts ))
local suspected=0 reason="" local suspected=0 reason=""
if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then if [ "$total" -gt 0 ] && [ "$grown" -eq 0 ]; then
if [ "$decisions" -ge "$WD_LOOP_MIN_EVENTS" ] \ if [ "$distinct" -le "$WD_LOOP_MAX_DISTINCT" ] && [ "$repeats" -ge "$WD_LOOP_MIN_REPEATS" ]; then
&& [ $(( failed * 100 )) -ge $(( decisions * WD_LOOP_STALL_PCT )) ]; then
# Row 57: the fly keeps deciding and nothing it decides runs. A
# refused press is a decision with no start, which is why the
# rules below were blind to a pad of one button that refused.
suspected=1
reason="stalled"
elif [ "$idle" -eq 1 ] && [ "$prev_idle" -eq 1 ]; then
suspected=1
reason="zero-progress"
elif [ "$distinct" -le "$WD_LOOP_MAX_DISTINCT" ] && [ "$repeats" -ge "$WD_LOOP_MIN_REPEATS" ]; then
suspected=1 suspected=1
reason="sequence" reason="sequence"
elif [ "$decisions" -ge "$WD_LOOP_MIN_EVENTS" ] \ elif [ "$total" -ge "$WD_LOOP_MIN_EVENTS" ] \
&& [ $(( topn * 100 )) -ge $(( decisions * WD_LOOP_DOMINANCE_PCT )) ]; then && [ $(( topn * 100 )) -ge $(( total * WD_LOOP_DOMINANCE_PCT )) ]; then
# One macro and almost nothing else. The floor under it is not in # One macro and almost nothing else. The floor under it is not in
# the spec but is load-bearing: two starts in ten brain minutes are # the spec but is load-bearing: two starts in ten brain minutes are
# 100% of a window and mean the fly is barely deciding at all, # 100% of a window and mean the fly is barely deciding at all,
# which is silence (above), not a loop. # which is silence (above), not a loop.
suspected=1 suspected=1
reason="dominant" reason="dominant"
elif [ "$busy" -eq 1 ] && [ "$prev_busy" -eq 1 ]; then
# Row 58: an undo pair diluted by other macros. Every one of them
# completes, none of them earns anything, and the ground stays put.
suspected=1
reason="unrewarded"
elif [ "$unwon" -eq 1 ] && [ "$prev_unwon" -eq 1 ]; then
# Row 67: every macro completes and the odd tile reward keeps the
# window from reading unrewarded, but no battle is ever won.
suspected=1
reason="unwon-battles"
fi fi
fi fi
echo "$suspected" > "${WD_RUN_DIR}/loop.suspected" echo "$suspected" > "${WD_RUN_DIR}/loop.suspected"
local dom_pct=0 local dom_pct=0
[ "$decisions" -gt 0 ] && dom_pct=$(( topn * 100 / decisions )) [ "$total" -gt 0 ] && dom_pct=$(( topn * 100 / total ))
# The sequence a reader wants: the repeating block when there is one, the # The sequence a reader wants: the repeating block when there is one, the
# single dominant name when the dominance rule is what fired. # single dominant name when the dominance rule is what fired.
local shown="$block" local shown="$block"
@ -1281,17 +956,6 @@ check_loop() {
--argjson repeats "$repeats" \ --argjson repeats "$repeats" \
--argjson distinct "$distinct" \ --argjson distinct "$distinct" \
--argjson total "$total" \ --argjson total "$total" \
--argjson decisions "$decisions" \
--argjson refused "$refused" \
--argjson blocked "$blocked" \
--argjson timeouts "$timeouts" \
--argjson completed "$completed" \
--argjson rewards "$rewards" \
--argjson fights "$fights" \
--argjson wins "$wins" \
--argjson progress "$progress" \
--argjson species "$species" \
--arg keys "${keys:-}" \
--argjson windowFrom "${win_from:-0}" \ --argjson windowFrom "${win_from:-0}" \
--argjson windowTo "${win_to:-0}" \ --argjson windowTo "${win_to:-0}" \
--argjson windowMs "$WD_LOOP_WINDOW_MS" \ --argjson windowMs "$WD_LOOP_WINDOW_MS" \
@ -1318,13 +982,6 @@ check_loop() {
window: { window: {
brainMsFrom: $windowFrom, brainMsTo: $windowTo, brainMs: $windowMs, brainMsFrom: $windowFrom, brainMsTo: $windowTo, brainMs: $windowMs,
macroStarts: $total, macroStarts: $total,
decisions: $decisions,
outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused },
rewards: $rewards,
fights: $fights,
wins: $wins,
progress: { lasting: $progress, species: $species,
keys: (if $keys == "" then [] else ($keys | split("\u001e")) end) },
tail: (if $tail == "" then [] else ($tail | split(", ")) end) tail: (if $tail == "" then [] else ($tail | split(", ")) end)
}, },
dominant: { name: (if $dominant == "" then null else $dominant end), dominant: { name: (if $dominant == "" then null else $dominant end),
@ -1348,30 +1005,21 @@ check_loop() {
local mins=$(( WD_LOOP_WINDOW_MS / 60000 )) local mins=$(( WD_LOOP_WINDOW_MS / 60000 ))
if [ "$suspected" -eq 1 ]; then if [ "$suspected" -eq 1 ]; then
if [ "$reason" = "unrewarded" ]; then if [ "$reason" = "sequence" ]; then
log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "unwon-battles" ]; then
log_err "loop suspected (unwon-battles): ${fights} moves chosen in battle and no battle won in the last ${mins} brain minutes, two probes running — ${decisions} decisions, ${rewards} reward event(s), top [${top}] x${topn}, tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — battles lost on repeat are a readout choice or a pad that offers no winning move. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then
log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "sequence" ]; then
log_err "loop suspected: [${shown}] x${repeats} (period ${period}) in the last ${mins} brain minutes — ${total} macro starts, ${distinct} distinct name(s), exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a loop is a macro target-choice bug and a bounce would only restore the same loop. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected: [${shown}] x${repeats} (period ${period}) in the last ${mins} brain minutes — ${total} macro starts, ${distinct} distinct name(s), exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a loop is a macro target-choice bug and a bounce would only restore the same loop. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
else else
log_err "loop suspected: [${shown}] is ${dom_pct}% of ${total} macro starts in the last ${mins} brain minutes (${distinct} distinct name(s)), exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected: [${shown}] is ${dom_pct}% of ${total} macro starts in the last ${mins} brain minutes (${distinct} distinct name(s)), exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
fi fi
elif [ "$prev_suspected" -eq 1 ]; then elif [ "$prev_suspected" -eq 1 ]; then
log_info "loop cleared: ${total} macro starts (${decisions} decisions, ${completed} done, ${refused} refused) over ${distinct} distinct name(s) in the last ${mins} brain minutes, longest repeat x${repeats} (period ${period}), exploration count ${places:-?} delta ${delta}. Nothing was ever done about the loop; if a fix went in, this is it landing." log_info "loop cleared: ${total} macro starts over ${distinct} distinct name(s) in the last ${mins} brain minutes, longest repeat x${repeats} (period ${period}), exploration count ${places:-?} delta ${delta}. Nothing was ever done about the loop; if a fix went in, this is it landing."
fi fi
} }
main() { main() {
check_flysim check_flysim
check_flyedge
check_control_edge
check_flystage check_flystage
check_flycast check_flycast
check_encoder check_encoder
check_backend
check_mediamtx check_mediamtx
check_flypush check_flypush
check_disk check_disk

View file

@ -1,147 +0,0 @@
#!/usr/bin/env bash
# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
# Idempotent: re-run it for every release the container runs.
#
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
#
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
# root-owned, and /opt/fly/current points to it: the shadow's verdict names
# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
# refuses a relay whose release differs.
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
# live fly's NUMA node.
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
# clearly faster than real time: see the runbook's "Which box".
#
# What it sets up:
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# ignores what the client asks for; the ingest writes nothing outside the mirror;
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
# run id the relay brings).
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
set -euo pipefail
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
log() { echo "fly-shadow-remote-setup: $*"; }
[ "$(id -u)" = 0 ] || die "run as root on the build box"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
from=""; cpus=""; threads=4
while [ $# -gt 0 ]; do
case "$1" in
--from) from="$2"; shift 2 ;;
--cpus) cpus="$2"; shift 2 ;;
--threads) threads="$2"; shift 2 ;;
*) die "unknown option $1" ;;
esac
done
here="$(cd "$(dirname "$0")" && pwd)"
ROOT=/srv/fly-shadow-remote
HOME_DIR=/srv/fly-shadow-remote-home
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
[ -f "$tarball" ] || die "no tarball $tarball"
[ -f "$rom" ] || die "no ROM $rom"
[ -f "$pubkey" ] || die "no public key $pubkey"
base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
key="$(head -n 1 "$pubkey")"
[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
# The release, exactly as 05-deploy installs it on the container (but root-owned here).
release="/opt/fly/releases/${version}"
if [ -f "$release/MANIFEST" ]; then
log "release $version already at $release"
else
install -d -m 0755 "$release"
tar -xzf "$tarball" -C "$release"
chown -R root:root "$release"
fi
(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
# The bare subcommand exits 2 (usage); under pipefail a pipe into grep would fail on that, so capture.
probe="$("$release/fly-shadow" ingest 2>&1 || true)"
printf '%s' "$probe" | grep -q 'needs --root' \
|| die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
log "/opt/fly/current -> $release"
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
if id flyshadow >/dev/null 2>&1; then
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
else
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
fi
if [ -e "$ROOT" ]; then
[ -d "$ROOT" ] || die "$ROOT is not a directory"
else
mkdir -m 0750 "$ROOT"
chown -h flyshadow:flyshadow "$ROOT"
fi
for d in trace hot durable out; do
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
if [ -e "$ROOT/$d" ]; then
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
else
mkdir -m 0750 "$ROOT/$d"
chown -h flyshadow:flyshadow "$ROOT/$d"
fi
done
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
install -d -o root -g root -m 0755 "$HOME_DIR"
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
log "authorized_keys: the relay key may run only the ingest"
# The cartridge and this box's paths.
rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
install -d -m 0755 /srv/fly/rom
install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
install -d -m 0755 /etc/fly
cat > /etc/fly/fly-shadow-remote.env <<ENV
# written by infra/box/fly-shadow-remote-setup (SHADOW-02): this box's paths for the remote shadow.
FLY_ROM=/srv/fly/rom/${rom_sha}.gb
FLY_DATASET=/opt/fly/current/data/fafb-v783
ENV
log "ROM sha256 $rom_sha (must equal the container's ROM_SHA256)"
# The units.
install -m 0644 "$here/flyshadow-remote.service" /etc/systemd/system/flyshadow-remote.service
install -m 0644 "$here/flyshadow-remote.path" /etc/systemd/system/flyshadow-remote.path
install -d -m 0755 /etc/systemd/system/flyshadow-remote.service.d
{
printf '# written by fly-shadow-remote-setup\n[Service]\nEnvironment=FLY_SHADOW_THREADS=%s\n' "$threads"
[ -n "$cpus" ] && printf 'AllowedCPUs=%s\n' "$cpus"
} > /etc/systemd/system/flyshadow-remote.service.d/10-cores.conf
log "${threads} threads${cpus:+ on CPUs $cpus}"
systemctl daemon-reload
systemctl enable --now flyshadow-remote.path
systemctl enable flyshadow-remote.service
# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
systemctl try-restart flyshadow-remote.service || true
log "ready: the container's fly-shadow-run start brings the first run id"

View file

@ -1,13 +0,0 @@
# infra/box/flyshadow-remote.path — installed on a BUILD BOX with flyshadow-remote.service
# (SHADOW-02). A new run id (the container's `fly-shadow-run start`, written by the ingest) starts
# the shadow when it is down: the first run, or after a divergence (exit 3 is not restarted). A
# running shadow restarts itself on the change (exit 4, Restart=always).
[Unit]
Description=Start the remote shadow for a new run (SHADOW-02)
[Path]
PathChanged=/srv/fly-shadow-remote/run-id
Unit=flyshadow-remote.service
[Install]
WantedBy=multi-user.target

View file

@ -1,55 +0,0 @@
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
#
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the
# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
# the SAME release (installed from the same tarball at the same /opt/fly/releases/<version> path,
# so the verdict's release and binary hashes are the container's), on this box's own cores, at
# normal priority.
#
# Its input is the mirror /srv/fly-shadow-remote, written by `fly-shadow ingest`, the forced
# command of the one key the container's relay (`fly-shadow relay`, flyshadow.service there) holds;
# the relay writes this shadow's verdict back to the container, where `fly-shadow-run check`, its
# guard and CUT-01 read it as before. REPORT-ONLY: it reads the mirror, writes <root>/out and its
# runtime directory, and serves nothing.
#
# The run: `fly-shadow-run start` on the container gives each run an id; the ingest writes it to
# <root>/run-id (after resetting the mirror). A running shadow sees the change within 5 s and exits
# with status 4, and Restart=always starts the new run; a shadow that is down (it diverged: exit 3,
# which is not restarted, so the diverged verdict stays) is started by flyshadow-remote.path.
[Unit]
Description=flyshadow-remote: the session runtime shadowing the live fly from a build box (SHADOW-02, report only)
ConditionPathExists=/opt/fly/current/fly-shadow
ConditionPathExists=/srv/fly-shadow-remote/run-id
[Service]
Type=simple
User=flyshadow
# The live composition's settings, as the relay forwarded them (game, macro mode, accepted
# adapters, pins; never a path or a secret), then this box's own paths: FLY_ROM (the cartridge,
# with the container's ROM_SHA256) and FLY_DATASET (the release's connectome).
EnvironmentFile=-/srv/fly-shadow-remote/live.env
EnvironmentFile=/etc/fly/fly-shadow-remote.env
Environment=FLY_TRACE_DIR=/srv/fly-shadow-remote/trace
Environment=FLY_STATE_HOT=/srv/fly-shadow-remote/hot
Environment=FLY_STATE=/srv/fly-shadow-remote/durable
Environment=FLY_SHADOW_DIR=/srv/fly-shadow-remote/out
Environment=FLY_SHADOW_WORK=/run/flyshadow-remote
RuntimeDirectory=flyshadow-remote
# 3 sweep threads (the SHADOW-01 measurements: 13-15 ms a frame against 16.7 ms of real time).
Environment=FLY_SHADOW_THREADS=3
# No lag back-off: the live fly is on another machine. The spool holds a long catch-up.
ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0 --spool-max-mib 4096
Restart=always
RestartSec=2
RestartPreventExitStatus=3
# Dedicated cores (fly-shadow-remote-setup --cpus writes AllowedCPUs= in a drop-in) at a weight
# above anything else on the box: a build must not starve the shadow.
CPUWeight=1000
Nice=-5
MemoryMax=6G
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

View file

@ -79,22 +79,6 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
( (
cd "$crate_dir" cd "$crate_dir"
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim "${features_args[@]}" RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim "${features_args[@]}"
# fly-edge (FLY_FEED_VIA=bus, docs/design/flybus.md): the feed WebSocket
# served from flysim's feed bus. Small, and no cargo features of its own;
# built every time so a release can switch a container onto the bus
# without a rebuild. It lands next to OUT_PATH, where package-release.sh
# looks for it.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
# fly-control-edge (FLY_CONTROL_VIA=bus, CTRL-01): the control API served from
# flysim's control services on the bus. Same reasons, same place.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-control-edge
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
# that `fly-runtime session` points flysim.service at; fly-shadow (SHADOW-01,
# infra/units/flyshadow.service): the session runtime shadowing the live fly; and
# fly-session, their worker program (FLY_SESSION_MODE=process only). Same features as flysim,
# built every time so a release can switch runtimes without a rebuild. All land next to
# OUT_PATH, where package-release.sh looks for them.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-shadow --bin fly-session "${features_args[@]}"
) )
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim" built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
@ -122,24 +106,4 @@ fi
cp "$built" "$OUT_PATH" cp "$built" "$OUT_PATH"
chmod 0755 "$OUT_PATH" chmod 0755 "$OUT_PATH"
log "built $OUT_PATH ($(du -h "$OUT_PATH" | cut -f1))" log "built $OUT_PATH ($(du -h "$OUT_PATH" | cut -f1))"
edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-edge"
[ -x "$edge_built" ] || die "expected binary not found after build: $edge_built"
edge_out="$(dirname "$OUT_PATH")/fly-edge"
cp "$edge_built" "$edge_out"
chmod 0755 "$edge_out"
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
control_edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-control-edge"
[ -x "$control_edge_built" ] || die "expected binary not found after build: $control_edge_built"
control_edge_out="$(dirname "$OUT_PATH")/fly-control-edge"
cp "$control_edge_built" "$control_edge_out"
chmod 0755 "$control_edge_out"
log "built $control_edge_out ($(du -h "$control_edge_out" | cut -f1))"
for extra in flysim-session fly-shadow fly-session; do
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
extra_out="$(dirname "$OUT_PATH")/${extra}"
cp "$extra_built" "$extra_out"
chmod 0755 "$extra_out"
log "built $extra_out ($(du -h "$extra_out" | cut -f1))"
done
log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>" log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>"

View file

@ -11,17 +11,6 @@
# #
# Output: OUT_DIR/flybrain-<version>.tar.gz, laid out as # Output: OUT_DIR/flybrain-<version>.tar.gz, laid out as
# flysim (the binary, mode 0755) # flysim (the binary, mode 0755)
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
# left one beside FLYSIM_BIN; flyedge.service stays
# inactive on a release without it)
# fly-control-edge (the control-bus edge, CTRL-01, likewise;
# flycontrol-edge.service stays inactive without it)
# flysim-session (the session runtime, SERVE-01, and fly-session, its
# fly-shadow worker program; mode 0755, when build-flysim.sh left
# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses
# a release without flysim-session. fly-shadow is
# SHADOW-01's shadow; flyshadow.service stays inactive
# on a release without it)
# stage/... (apps/stage's build output) # stage/... (apps/stage's build output)
# bridge/... (services/bridge + node_modules) # bridge/... (services/bridge + node_modules)
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
@ -83,32 +72,6 @@ mkdir -p "$release_dir"
cp "$FLYSIM_BIN" "${release_dir}/flysim" cp "$FLYSIM_BIN" "${release_dir}/flysim"
chmod 0755 "${release_dir}/flysim" chmod 0755 "${release_dir}/flysim"
EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-edge"
if [ -x "$EDGE_BIN" ]; then
cp "$EDGE_BIN" "${release_dir}/fly-edge"
chmod 0755 "${release_dir}/fly-edge"
else
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
fi
CONTROL_EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-control-edge"
if [ -x "$CONTROL_EDGE_BIN" ]; then
cp "$CONTROL_EDGE_BIN" "${release_dir}/fly-control-edge"
chmod 0755 "${release_dir}/fly-control-edge"
else
log "no fly-control-edge beside $FLYSIM_BIN; packaging without it (FLY_CONTROL_VIA=bus unavailable in this release)"
fi
for extra in flysim-session fly-shadow fly-session; do
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
if [ -x "$EXTRA_BIN" ]; then
cp "$EXTRA_BIN" "${release_dir}/${extra}"
chmod 0755 "${release_dir}/${extra}"
else
case "$extra" in
fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;;
*) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;;
esac
fi
done
cp -a "$STAGE_DIR" "${release_dir}/stage" cp -a "$STAGE_DIR" "${release_dir}/stage"
cp -a "$BRIDGE_DIR" "${release_dir}/bridge" cp -a "$BRIDGE_DIR" "${release_dir}/bridge"

View file

@ -38,19 +38,6 @@ branch="$(git rev-parse --abbrev-ref HEAD)"
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})" die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})"
fi fi
# A tag is published with its whole history, so the privacy scan runs first and fails
# closed: without the operator's private pattern list ($FLY_PII_PATTERNS) it cannot see
# host names, people's names, the channel or pass entry names, and a tag is not cut blind.
# It checks the tree being tagged and every line added since the previous tag.
log "running tools/pii-scan.sh (private pattern list required)"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --tree HEAD \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in the tree (or its private pattern list is missing) — see above"
prev_tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)"
pii_range="HEAD"
[ -z "$prev_tag" ] || pii_range="${prev_tag}..HEAD"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --range "$pii_range" \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in commits since ${prev_tag:-the root} (a tag publishes them even if a later commit removed them) — see above"
git fetch --tags >/dev/null 2>&1 \ git fetch --tags >/dev/null 2>&1 \
&& log "fetched tags from the remote" \ && log "fetched tags from the remote" \
|| log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state" || log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state"
@ -69,19 +56,7 @@ if [ -d "$flysim_dir" ]; then
# --release, not debug (Makefile's `rust:` target and the reason it gives): the flysim # --release, not debug (Makefile's `rust:` target and the reason it gives): the flysim
# integration test that asserts the feed's 30 Hz contract only reaches ~9.5-10.4 Hz in a debug # integration test that asserts the feed's 30 Hz contract only reaches ~9.5-10.4 Hz in a debug
# build, so a debug run would fail or flake that gate. # build, so a debug run would fail or flake that gate.
# The ROM suites (tests/rom_*.rs) return early and count as PASSED when FLY_ROM or their log "running cargo test --workspace --release in services/flysim"
# checkpoint variable is unset, so a gate run without them proves nothing about the macros.
# v0.6.4's gate ran that way. Refuse without the ROM; name every checkpoint suite skipped.
if [ -z "${FLY_ROM:-}" ] || [ ! -r "${FLY_ROM}" ]; then
die "FLY_ROM is unset or unreadable: the ROM test suites would pass without running. Export FLY_ROM and the FLY_*_CHECKPOINT variables (the operator's rom env) first."
fi
skipped=""
while IFS= read -r var; do
[ -n "${!var:-}" ] || skipped="${skipped} ${var}"
done < <(grep -rhoE 'var_os\("FLY_[A-Z0-9_]*_CHECKPOINT"\)' "$flysim_dir"/crates/*/tests/rom_*.rs \
| sed -E 's/.*"(FLY_[A-Z0-9_]*)".*/\1/' | sort -u)
[ -z "$skipped" ] || log "WARNING: ROM checkpoint suites that will pass WITHOUT running (unset):${skipped}"
log "running cargo test --workspace --release in services/flysim (FLY_ROM set)"
(cd "$flysim_dir" && cargo test --workspace --release) (cd "$flysim_dir" && cargo test --workspace --release)
else else
log "WARNING: services/flysim does not exist in this checkout — skipping cargo test --workspace" log "WARNING: services/flysim does not exist in this checkout — skipping cargo test --workspace"

View file

@ -6,22 +6,13 @@
# <unit>` and, on the 5-consecutive-failure escalation, a container # <unit>` and, on the 5-consecutive-failure escalation, a container
# reboot. This is the minimum NOPASSWD surface for exactly what # reboot. This is the minimum NOPASSWD surface for exactly what
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast, # bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
# mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no # mediamtx, flypush), plus reboot. No `systemctl stop`, no
# `enable`/`disable`, no arbitrary unit name, and no units this script # `enable`/`disable`, no arbitrary unit name, and no units this script
# does not itself restart (xvfb, pulse, flystage-web are never touched by # does not itself restart (xvfb, pulse, flystage-web are never touched by
# fly-watchdog's checks, so they are not granted here). # fly-watchdog's checks, so they are not granted here).
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge.service
fly ALL=(root) NOPASSWD: /usr/sbin/reboot fly ALL=(root) NOPASSWD: /usr/sbin/reboot
# fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and
# resets to a milestone archive through this one root wrapper, which validates the rung,
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset
# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on
# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait

View file

@ -6,11 +6,6 @@ d /run/fly 0750 fly fly -
d /run/fly/pulse 0750 fly fly - d /run/fly/pulse 0750 fly fly -
d /run/fly/state 0750 fly fly - d /run/fly/state 0750 fly fly -
d /run/fly/wd 0750 fly fly - d /run/fly/wd 0750 fly fly -
# ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's
# router socket and artifact store. flysim also creates it, 0700, on start.
d /run/fly/bus 0700 fly fly -
# The session runtime's router store and worker sockets (SERVE-01, flysim-session).
d /run/fly/session 0700 fly fly -
d /var/lib/fly 0750 fly fly - d /var/lib/fly 0750 fly fly -
d /var/lib/fly/chrome 0700 fly fly - d /var/lib/fly/chrome 0700 fly fly -
d /srv/fly/state 0750 fly fly - d /srv/fly/state 0750 fly fly -

View file

@ -9,14 +9,6 @@
// on flystage-web.service). Deliberately not a general-purpose server: // on flystage-web.service). Deliberately not a general-purpose server:
// no directory listing, no symlink following outside root, no range // no directory listing, no symlink following outside root, no range
// requests (the page is a handful of static assets, not video). // requests (the page is a handful of static assets, not video).
//
// One route is not a file under root: GET /recovery-notice.json returns the
// auto-recovery helper's notice (infra/bin/fly-loop-recover writes it to
// /run/fly/wd/recovery-notice.json, FLY_RECOVERY_NOTICE overrides), which the
// page's recovery splash polls once a second. It is served from here and not
// from flysim because flysim is the thing being restarted. 200 with the file's
// bytes, or 204 when there is no (readable, small, regular) file; the page does
// all of the validation (apps/stage/src/lib/recovery.ts).
import { createServer } from 'node:http'; import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises'; import { readFile, stat } from 'node:fs/promises';
import { join, normalize, extname } from 'node:path'; import { join, normalize, extname } from 'node:path';
@ -25,27 +17,6 @@ const root = process.argv[2] ?? new URL('.', import.meta.url).pathname;
const host = process.argv[3] ?? '127.0.0.1'; const host = process.argv[3] ?? '127.0.0.1';
const port = Number(process.argv[4] ?? 7402); const port = Number(process.argv[4] ?? 7402);
const RECOVERY_ROUTE = '/recovery-notice.json';
const RECOVERY_PATH = process.env.FLY_RECOVERY_NOTICE || '/run/fly/wd/recovery-notice.json';
const RECOVERY_MAX_BYTES = 16384;
async function serveRecoveryNotice(res) {
const headers = { 'cache-control': 'no-store' };
const st = await stat(RECOVERY_PATH).catch(() => null);
if (!st?.isFile() || st.size === 0 || st.size > RECOVERY_MAX_BYTES) {
res.writeHead(204, headers).end();
return;
}
const body = await readFile(RECOVERY_PATH).catch(() => null);
if (!body) { res.writeHead(204, headers).end(); return; }
res.writeHead(200, {
...headers,
'content-type': 'application/json; charset=utf-8',
'content-length': body.length,
});
res.end(body);
}
const TYPES = { const TYPES = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
@ -56,7 +27,6 @@ const TYPES = {
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
try { try {
if (req.url.split('?')[0] === RECOVERY_ROUTE) { await serveRecoveryNotice(res); return; }
const urlPath = normalize(decodeURIComponent(req.url.split('?')[0])); const urlPath = normalize(decodeURIComponent(req.url.split('?')[0]));
if (urlPath.includes('..')) { res.writeHead(400).end('bad path'); return; } if (urlPath.includes('..')) { res.writeHead(400).end('bad path'); return; }
let path = join(root, urlPath === '/' ? 'index.html' : urlPath); let path = join(root, urlPath === '/' ? 'index.html' : urlPath);
@ -77,5 +47,5 @@ const server = createServer(async (req, res) => {
}); });
server.listen(port, host, () => { server.listen(port, host, () => {
console.log(`flystage-web: serving ${root} on http://${host}:${server.address().port}/`); console.log(`flystage-web: serving ${root} on http://${host}:${port}/`);
}); });

View file

@ -1,135 +0,0 @@
# Automated loop recovery
`fly-watchdog` remains report-only. The separate `fly-loop-recover.timer` reads its
`/run/fly/wd/loop.json` every minute and unsticks a confirmed trap on its own, climbing
a ladder one step per trap that outlives the previous step:
| level | step | cost |
|---|---|---|
| 0 | `systemctl restart flysim.service` | none: the restore keeps the rung and learned state, clears session macro ledgers |
| 1 | reset to the current rung's milestone archive | progress since the rung was first reached |
| 2+ | reset to the archive below the best rung (never lower) | one visible rung |
- **Confirmed** means two fresh suspected watchdog reports (at most 10 minutes old, `action: none`)
from separate probes about 5 minutes apart. A clear report in between starts the count again.
- **Outlives** means the reports that confirm it again are at least 20 minutes after the step, so
their 10-brain-minute window lies after it. The helper waits that long after every step.
- **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a
restart, at most every three hours, until a reset is free again. The same three-hour spacing applies
when a reset level finds no restorable rung and restarts instead, and between any two restarts in a
row, also when the ladder has started over in between.
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, after
six hours with no suspected report, or when the fly makes new lasting progress more than
20 minutes after the last step and a clear probe shows the old trap let go (row 70). Lasting
progress is the watchdog's `window.progress`: a rung reached, a species owned, a map entered, or
a trainer or badge beaten, each named in `window.progress.keys` as `kind:label` (`pokedex:OWNED
#41`). A ring cannot earn them twice, but a milestone reset restores the reward ledger, so its
replay pays the archive's rewards again. Progress is therefore measured against every name the
ladder has seen (`progressSeen` in the state file, the last 2,000), not against the restored
archive: a replay re-earning what the run had before the reset is not progress, and the ladder
climbs on to the rung below as it did before row 70. A trap that follows new progress is a new
trap, and it starts again from a restart. A catch made while the fly stays flagged is not a new
trap. With a watchdog that reports no names, the counts are used as before.
Names the ladder never saw (before this version was deployed, or while an older one ran) count
as new once.
- **Protected catches:** a milestone reset never erases a species first owned in the last two hours
(`PROTECT`, a `pokedex:` name not seen before). A species a reset's replay owns again was the fly's
before the reset and was protected then, so it does not open a second window. Within that window the step is a restart, spaced by
the hold like a spent budget, and `history.jsonl` records a `protect` event. A reset turned into a
restart this way does not climb the ladder: the level keeps its slot and the reset comes, at the
same rung, once the window ends. Evolution also counts as a species owned.
- **No archive twice in a row:** a reset never restores the same archive as the last reset,
until a new best rung is reached or twelve hours have passed (`AGAIN`; a trap no restart clears
is reset again in bounded time, no later than before this rule). Such a step does climb, so the rung below is reached promptly. A restore is deterministic, so the same archive replays the
same run into the same trap. Row 70's second reset to rung 11 matched the first one event for
event: the same Zubat caught, the same trap an hour later, and the catch erased. That step is
a restart instead. A reset that fails does not mark its archive: it is not known to have been
restored, so the next reset may try it again.
A milestone step only uses an archive the running build can restore. `fly-loop-reset --list`
compares each archive's compatibility string with `flysim --print-compatibility` and accepts an
adapter-only difference that `FLY_ACCEPT_ADAPTERS` in `/etc/fly/fly.env` names (the rule
`05-deploy.sh` applies). A flysim that refuses every checkpoint refuses to start, so a step whose
rung is not restorable is a restart instead, never a lower rung. Keep `FLY_ACCEPT_ADAPTERS` in the
release env file so a deploy does not drop it.
The step runs `/opt/fly/bin/fly-loop-reset <rung>` through sudo (the one line in
`config/fly-sudoers`). As root it:
- runs only the root-owned `/opt/fly/sbin/flysim`, and only while it is byte-identical to the
flysim `/opt/fly/current` points to, that `05-deploy.sh` installs from the release
tarball after checking it against the tarball's MANIFEST (never the fly-owned release tree).
Without that copy (an infra-only deploy, or a manual rollback) no rung is restorable and the
ladder only restarts; after a release deploy, check as `fly` that
`sudo -n /opt/fly/bin/fly-loop-reset --list` names the current rung;
- reads `fly.env` as `KEY=VALUE` data, never sources it, and ignores the caller's environment;
- stops `fly-watchdog.timer` and waits for a running probe to finish, so the watchdog cannot
start flysim on a half-rewritten store; stops flysim; runs `fly-reset-to-milestone`; and on every
exit path starts flysim and the watchdog timer again.
The reset copies both stores to `/srv/fly/state.reset-<UTC>` first, as in the runbook, and
clears milestone archives above the rung. After each step the helper waits up to four minutes for
`/status` to report `running` (and the target rank for a reset). Otherwise the step is recorded
as failed and the ladder still climbs. The step is recorded before it runs, so a helper killed
mid-step has still climbed and spent the reset. Do not stop `fly-loop-recover.service` during a
step: that kills the reset too, and the wrapper's exit trap starts flysim on whatever state is
left.
## On stream
Every step is announced 60 seconds ahead (`FLY_LOOP_COUNTDOWN`) in
`/run/fly/wd/recovery-notice.json` (`FLY_RECOVERY_NOTICE`), which the stage's recovery splash
reads. It holds the contract below, written atomically, mode 0644:
```json
{"v": 1, "id": "1790629095-reset", "phase": "countdown|acting|done|failed",
"action": "restart|reset", "fromRung": 12, "fromLabel": "MT. MOON",
"toRung": 11, "toLabel": "BOULDER BADGE", "reason": "unrewarded",
"loop": ["GO OBJECTIVE", "GO WARP"], "stuckSeconds": 900,
"announcedAt": 1790629095, "executeAt": 1790629155, "updatedAt": 1790629160}
```
`toRung`/`toLabel` are present for a reset only; every write refreshes `updatedAt`, and the
helper never deletes the file. `flystage-web` serves it at `/recovery-notice.json` (204 when
absent) and the page's recovery splash polls it once a second (`apps/stage/README.md`, "Recovery
splash"). The page ignores a notice more than 15 minutes old, shows `done` for 8 s and `failed`
for 20 s, and stops covering the game 10 minutes after an `acting` write that nothing followed.
A milestone step pauses the watchdog, so Chromium is not restarted under the splash; a plain
restart is short enough that a watchdog pass rarely lands in it.
## Model confirmation
An OpenAI-compatible router can be asked before each step. The model may only answer
`{"stuck": true|false}` (the reply may wrap it in prose; the first such object counts). It cannot
choose commands, rungs or buttons. `false` delays the step by one probe, at most three times in a
row; then the step goes ahead. If no model answers (unset, rate-limited, down, malformed), the
watchdog's confirmation stands alone. A model can delay recovery by about 15 minutes, never deny
it.
Provision a root-managed `/etc/fly/loop-recovery.env`, mode `0640 root:fly`, outside this public
checkout:
```
FLY_LOOP_ROUTER_URL=<base URL ending in /v1>
FLY_LOOP_ROUTER_KEY=<router key>
FLY_LOOP_MODELS=<model>,<fallback model>,...
```
Models are tried in order within a 90-second budget. Prefer fast free-tier chat models, and put
providers with generous free limits first: free OpenRouter models share a small daily quota and
the router's circuit breaker can close the whole provider for a while. Check each model against
a stuck and a healthy report before listing it. `FLY_LOOP_MODEL` (one model) is still read when
`FLY_LOOP_MODELS` is unset.
## Operating it
- Decisions: `journalctl -u fly-loop-recover.service`. Every step, veto and ladder restart is also
appended to `/var/lib/fly-loop-recover/history.jsonl`.
- Ladder state: `/var/lib/fly-loop-recover/state.json` (the unit's `StateDirectory`, so it
survives a reboot). Deleting it starts the ladder over.
- Stop automatic recovery: `systemctl disable --now fly-loop-recover.timer`.
- Record automatic steps you find in the journal in the host claim log when you next claim the
container; the unit has no access to that log.
This is an unstick mechanism, not a macro bug fix. A recurring trap still needs the
checkpoint-based loop review in `docs/loop-review.md`.

View file

@ -20,8 +20,7 @@ FLY_ROM=".../Pokemon Red (U) [S][BF].gb" FLY_MACRO_BRAIN=data/fafb-v783 \
cargo run --release -p flysim --example palette_bench cargo run --release -p flysim --example palette_bench
``` ```
Both arms are the sim loop's own frame order (`flysim::frame::LegacyFrame` since 2026-09-23; Both arms are the sim loop's own frame order over the real connectome (`data/fafb-v783`), the real
before that `NeuralAgent::tick`'s, one frame behind the stream) over the real connectome (`data/fafb-v783`), the real
Game Boy readout preset with nothing overridden, the real Pokémon adapter paying the real reward Game Boy readout preset with nothing overridden, the real Pokémon adapter paying the real reward
catalog, and the real ratchet on the adapter's own recovery policy. The only difference between catalog, and the real ratchet on the adapter's own recovery policy. The only difference between
them is `flysim::macros::MacroLayer`, built from the configuration the way `Sim::boot` builds it, them is `flysim::macros::MacroLayer`, built from the configuration the way `Sim::boot` builds it,

File diff suppressed because it is too large Load diff

View file

@ -193,8 +193,6 @@ ssh the host pct exec <release-ctid> -- curl -s 127.0.0.1:7410/metrics | grep fl
| Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. | | Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. |
| Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. | | Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. |
| Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. | | Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. |
| Repeating `FATAL: Twitch refused to refresh the <role> token ... (HTTP 400 "Invalid refresh token")` at startup | That role's refresh token is revoked or invalid (password change, app disconnected, re-authorized elsewhere) | Re-authorize that `--role` — "Rotate the bot token" below. Restarting cannot help; systemd keeps retrying every 15 s with one refresh request per role until the file is fixed. |
| `the stored <role> access token has expired; refreshing it` or `rejected the stored <role> access token (401); refreshing it once`, then a normal start | The bridge was down longer than an access token lives (~4 h), or Twitch invalidated it early | Nothing: it refreshed and persisted the new token itself. |
| One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. | | One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. |
| `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. | | `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. |
@ -205,30 +203,13 @@ unit, so chat can never take the fly down.
## Rotate the bot token (flybridge) ## Rotate the bot token (flybridge)
Access tokens live about 4 h; refresh tokens until revoked. The bridge refreshes on its own: Not yet applicable until flybridge exists and is wired up (P3, `docs/design/infra.md`
at runtime through `RefreshingAuthProvider`, and ON LOAD (`prepareStartupTokens` in section 7). Once it is: re-run `tools/authorize.mts` (`docs/design/stage-bridge.md`
`services/bridge/src/auth.ts`) — a stored access token that has expired, or that Twitch's section B1) on the operator box to get a fresh refresh token, which
validate endpoint rejects with 401, is refreshed with its refresh token before the bridge gives `RefreshingAuthProvider`'s `onRefresh` persists to `/var/lib/fly/bridge/tokens.json`
up, for both roles, and each refreshed token is written back to `/var/lib/flybridge/tokens.json` automatically from then on — a one-time manual step, not a recurring one. The
under its own role (tmp file + rename, mode 0600), also when the bot and the broadcaster are one `twitch-app` credential (client id/secret) only needs rotating if the app itself is
account. So an outage longer than an access token's life no longer needs a hand refresh compromised; follow the same `06-secrets.sh` pattern as the stream key.
(2026-09-28: it used to crash-loop on 401 at `validate`).
Re-authorizing is needed only when the journal says
`flybridge: FATAL: Twitch refused to refresh the <role> token for user <id> (HTTP 400 "Invalid refresh token")`,
or a scope is missing (the table in "Chat dead" above). Then, on the operator box:
1. `npx tsx tools/authorize.mts --role <role> --tokens-file <local copy of tokens.json>`
(`services/bridge`, `docs/design/stage-bridge.md` section B1). It rewrites only that role's
entry and keeps the other.
2. Push the file to the release container as `/var/lib/flybridge/tokens.json`, owned by the
service user, mode 0600 (it is a secret; never in a release artifact or in git).
3. `systemctl restart flybridge` and read the journal for the startup notice line.
Never paste a token or the client secret into a log, a ticket or chat: the bridge itself prints
neither (Twitch errors are logged by status and message only, URLs redacted). The `twitch-app`
credential (client id/secret) only needs rotating if the app itself is compromised; follow the
same `06-secrets.sh` pattern as the stream key.
## Restore a checkpoint locally ## Restore a checkpoint locally
@ -250,59 +231,6 @@ auto-reset (`docs/design/flysim.md` section 8: "no automatic fresh start, ever")
is deliberate — a silent reset would be indistinguishable from real progress on stream. is deliberate — a silent reset would be indistinguishable from real progress on stream.
A deliberate reset means moving `/srv/fly/state` aside by hand. A deliberate reset means moving `/srv/fly/state` aside by hand.
## Restart the run from a rung
When the run has to go back to an earlier milestone rather than start over — the operator's
decision of 2026-09-22 was "restart the live run from an early checkpoint instead of from
scratch". `FLY_RESET_STATE=1` is the wrong tool: it archives the durable state and the next start
warms up a fresh fly, losing everything the brain has learned.
`infra/bin/fly-reset-to-milestone <N>` promotes `milestone-<N>.checkpoint` to being what both
stores restore, with the ratchet's attempts and recoveries back at zero. It copies every file in
both stores to `/srv/fly/state.reset-<UTC>` first, so it is reversible by hand. It refuses while
flysim is running, and refuses a rung this run never reached.
The whole sequence, in order. Claim the container in the host's agent claim log first, like any
other work on it.
```
CTID=<release-ctid>
N=9 # the rung to restart from
# 1. what rungs exist at all
pct exec $CTID -- ls -1 /srv/fly/state/milestone-*.checkpoint
# 2. stop flysim (it owns both stores; a reset underneath it is overwritten within the minute)
pct exec $CTID -- systemctl stop flysim.service
# 3. the reset. Prints what it did, one line per step.
pct exec $CTID -- /opt/fly/bin/fly-reset-to-milestone $N
# 4. deploy. Two cases:
# (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5.
# (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's
# adapter so the gate and flysim both migrate instead of refusing:
FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 infra/05-deploy.sh <release-env> <release-tarball>
# The gate logs "the adapter version is the only difference, and it is named; the run is KEPT
# and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the
# same rule at restore. Anything else about the string differing is still a refusal.
# 5. start
pct exec $CTID -- systemctl start flysim.service
# 6. verify: the rank is the rung, and the restore came from the generation the tool wrote
pct exec $CTID -- curl -s http://127.0.0.1:7401/status | jq '.milestone.rank, .game.badges, .checkpoint'
pct exec $CTID -- journalctl -u flysim -n 40 --no-pager | grep -E 'restored|migration|compatibility'
```
Step 6 is the one that must be read rather than assumed. The rank is recomputed by the adapter
from the restored game state, not taken from the ratchet, so a rank that is *not* N means the
milestone archive was taken somewhere other than where its name says — stop and look before
starting a stream on it.
To undo: stop flysim, move the contents of `/srv/fly/state.reset-<UTC>/durable` back into
`/srv/fly/state`, delete the generation the tool wrote, and start again.
## Restore from the backup host ## Restore from the backup host
``` ```
@ -443,612 +371,6 @@ One `ln -sfn` plus a restart, per `docs/design/infra.md` section 2. Nothing else
touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`. touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`.
On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above. On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above.
## Switch the runtime (legacy loop or session runtime)
Two binaries in every release from SERVE-01 on run the same fly: `flysim`, the legacy loop, and
`flysim-session`, the same composition on the session framework (agent, Game Boy environment and
macro task as participants). They read the same `/etc/fly/fly.env`, write the same checkpoint
stores, event log, sugar journal and chat sidecar, and serve the same feed, control API and
metrics through the same listener code, so nothing else on the container can tell them apart.
`flysim.service` is the fly's one unit name either way; which binary it runs is one drop-in,
written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/opt/fly/bin`).
```
pct exec $CTID -- /opt/fly/bin/fly-runtime status # legacy | session
pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict (starts the speed probation)
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
```
- **What it does.** `session` writes `/etc/systemd/system/flysim.service.d/10-runtime.conf`
(`ExecStart=/opt/fly/current/flysim-session`, `FLY_SESSION_DIR=/run/fly/session`),
daemon-reloads and restarts `flysim.service`; `legacy` deletes the file and does the same. No
data moves: the store is shared, and each runtime restores the other's checkpoints.
- **What it checks.** `session` refuses a release without `flysim-session`, and refuses when
`flysim --print-compatibility` and `flysim-session --print-compatibility` differ. After the
restart both wait for `/healthz` and a `/status` frame that advances
(`FLY_RUNTIME_HEALTH_TIMEOUT`, 300 s). If the session runtime does not come up healthy, it
switches back to legacy by itself and exits 1 (`--no-fallback` leaves it to the operator).
Every switch is logged (`journalctl -t fly-runtime`, `/var/lib/fly/runtime.log`).
- **The fallback outlives the switch (C1).** While the session runtime is selected, the drop-in
also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3`,
`StartLimitIntervalSec=600` and `RestartMode=direct`, and `MALLOC_ARENA_MAX=2` (glibc arena
fragmentation was the whole of the 5-8 MB/h RSS growth). `RestartMode=direct` is what makes the
limit real: since systemd 254 the default (`normal`) sends the unit through the `failed` state
before every `Restart=always` restart, so `OnFailure=` would fire on the first crash, watchdog
kill or start timeout (seen on systemd 257, the container's). With `direct` the unit goes from
one start to the next and only hitting the start limit fails it. Three starts of `flysim.service` within ten minutes, from any
cause and any caller (a reboot, the watchdog or `fly-loop-recover` restarting it, a deploy, a
binary that crashes, hangs before READY or is killed by `WatchdogSec`) make systemd run
`fly-runtime fallback`: it writes `/run/fly/runtime-fellback.json` (time, reason, unit result),
deletes the drop-in, daemon-reloads and restarts `flysim.service` on the legacy binary, and logs
a `fly-runtime` journal line. It is idempotent, and it does nothing if the release has no
executable `flysim`. Look with `fly-runtime status` (it prints the reason) or
`cat /run/fly/runtime-fellback.json`; the container is then on legacy until an operator runs
`fly-runtime session` again, which clears the reason file. Restarts you make yourself count
too, and once the limit is reached systemd refuses the next start and runs the fallback. Three legitimate restarts in ten
minutes count the same as three crashes: after that many, prefer `fly-runtime legacy`, do the
work, then switch back.
- **Interrupted switches roll back.** `fly-runtime` traps INT, TERM and HUP (an ssh that drops
mid-switch): an unfinished `session` removes the drop-in again (or restores the one that was
there) and restarts `flysim.service` on that state, so a drop-in that never passed its health
check is never left behind. `session`, `legacy`, `fallback` and that rollback all take one lock
(`/run/fly/runtime.lock`); a switch holds it while it changes the drop-in and queues the restart
(`systemctl restart --no-block`, so a unit that never becomes READY cannot hold it) and releases
it for the health wait. The rollback does nothing when a fallback finished after the switch began (the
reason file exists), so it can never put back an older drop-in over a fallback.
- **What stays the same.** Everything that names `flysim.service` keeps working unchanged:
`fly.target`, `flyedge.service`'s `Requires=`, the watchdog, `fly-loop-recover`'s restart and
its sudoers line, `fly-loop-reset`, `fly-reset-to-milestone` (run with the service stopped, on
the shared store), the unstick rule's `systemctl restart flysim.service`, `journalctl -u
flysim`, the cpuset drop-in. The choice survives a reboot and a deploy: `05-deploy.sh`
converges unit files but never removes a drop-in (it rewrites it in place from the current
template, without a restart), and it refuses a release without `flysim-session` or with a
different compatibility string while the drop-in is present (`fly-runtime legacy` first to
deploy one). **Policy (C2, operator decision 2026-09-29, "Session stays, trust gates"):** a
deploy keeps the chosen runtime on the new release's `flysim-session`, without re-running the
shadow for it. The trust gates before the release vouch for the binary, and the persistent
fallback above protects a bad one.
- **What differs, by declaration.** `POST /reward` is always 403 on the session runtime (the
operator pulse has no session-framework counterpart, `legacy-gameboy-v1` section 15); a
fresh start publishes no audio for its one setup frame; `FLY_TRACE` and
`FLY_PROFILE_SECONDS` are legacy-loop tools (the session runtime logs a `session profile`
line of per-phase timings every minute instead). The sugar journal's boot header says
`runtime: fly-session`.
- **The standalone unit.** `flysim-session.service` is the same service as a unit of its own
(flysim's limits, cpuset and environment; `Conflicts=flysim.service`; no `[Install]`, so it
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
stopped, not for switching the stream.
- **The session on the bus (BUS-01).** `fly-runtime session --bus` (or `session-bus`) runs the
session's participants on the flybus router over Unix sockets: `flysim-session` (the router, the
coordinator, the listeners) starts `fly-session legacy-agent` and `fly-session legacy-environment`
as children of the same unit, in `flysim.slice`, on flysim's CPUs. The drop-in gains
`Environment=FLY_SESSION_TRANSPORT=bus`; `fly-runtime status` prints `session` and then
` transport: bus`. `fly-runtime session` without a flag (05-deploy's refresh) keeps the transport
the drop-in has; `fly-runtime session --local` goes back to the in-process lane, and
`fly-runtime legacy` to legacy. The fallback, the probation, the watchdog and the unstick rule's
restart are the same on either transport: one unit, restarted as a whole, children included
(`ps -o pid,args --ppid $(systemctl show -p MainPID --value flysim)` lists them). A deploy
refuses a release without `fly-session` while the drop-in says `bus`. **Before switching onto the
bus, run a shadow of it** (Shadow run below): with the live fly on legacy (`fly-runtime legacy`),
`fly-shadow-run start --bus`, three hours, then `fly-shadow-run check --bus && fly-runtime
session --bus`. Watch `fly_frame_work_mean_ms` and `fly_frame_work_p99_ms` on `/metrics` (the
loop's compute time per frame, without its pacing sleep, over the last 3,600 frames; the budget
at real time is 16.74 ms): they show the headroom that a realtime factor of 1.0 hides.
- **Per-frame compute time, both runtimes.** `/metrics` exports `fly_frame_work_mean_ms`,
`fly_frame_work_p99_ms`, `fly_frame_work_max_ms` and `fly_frame_work_frames` for the legacy loop
and the session runtime alike: everything one running iteration does except the pacing sleep.
Headroom is `1 - mean / 16.74` at real time.
## Feed over the bus (EDGE-02)
`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before
EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`,
`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way
(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes,
on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the
capture never see the difference.
**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the
env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it
says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not
failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the
edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s
stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by
hand, and flysim and the edge cannot disagree.
```
pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters
pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy)
pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back
```
### The live procedure
Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`),
`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is
claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`,
`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch
restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the
restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run
continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit
(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes
of two other restarts.
```
# 1. Before: the baseline to compare with (keep the output).
pct exec $CTID -- /opt/fly/bin/fly-feed status
pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "'
pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's
# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints
# "healthy (bus): the page is on the feed and frames are moving", exit 0.
pct exec $CTID -- /opt/fly/bin/fly-feed bus
# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this
# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the
# env file's value; flysim applies it at its next restart.)
# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day.
pct exec $CTID -- /opt/fly/bin/fly-feed status
```
What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes
`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner
kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`),
waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while
`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with
`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA`
back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback`
leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM
or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted
`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and
`/var/lib/fly/feed.log`.
### What to watch
| Where | Healthy in bus mode | Wrong looks like |
| --- | --- | --- |
| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` |
| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) |
| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` |
| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare |
| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy |
| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back |
| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` |
| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer |
The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that
changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed
counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers
`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then
the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the
fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly
those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator
switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather
than restarting a page that has nothing to connect to, and its chain ends with the edge and the
encoder.
### Rolling back
- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own
feed, stops a lingering edge. It needs nothing from the release (it works on one without
`fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so
count it against the start limit.
- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and
`fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both
runtimes.
- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while
the env file says `bus` or the container is in bus mode: `fly-feed direct` and set
`FLY_FEED_VIA=direct` in the env file first, then roll back or deploy.
- A reboot keeps whatever `fly.env` says.
### What the rehearsal measured
Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome,
macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real
stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed`
and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so
**real-time factor is not comparable between the two runs**; the numbers below are the ones load does
not move much. The live switch is the real A/B: take the step 1 baseline and compare.
| Measure | direct | bus |
| --- | --- | --- |
| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs |
| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) |
| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) |
| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs |
| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run |
| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both |
| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box |
| Page | 0 decode errors | 0 decode errors, gaps only under that load |
Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM
restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once)
each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and
sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of
flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores
from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the
feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after
the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge
back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to
direct with the page connected again. The live restart is longer than these 6 s by the real
restore and warm-up; use the unstick rule's usual time.
### Notes
- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and
`fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*`
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
counters.
- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and
the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking
pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the
operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as
`FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to
the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about
1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the
critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof
flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the
deploy, restart flysim, and only then `fly-feed bus`.
- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A
reboot empties it; a crashed flysim's directory is removed by the next one.
- **Control (`:7401`)** stays in flysim and is not part of this switch.
## Shadow run (SHADOW-01)
The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The
contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is
report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim
the release container in the host log first, as for any host work.
```
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, remote shadow + guard, one flysim restart
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (and a guard trip) in one screen
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
```
- **A shadow of the bus topology (BUS-01).** `start --bus` runs the box's shadow session with its
agent and world as child processes on its router's sockets (`FLY_SHADOW_MODE=bus/process`, which
the relay forwards); `check --bus` also requires that the verdict ran that topology
(`candidate.transport` `bus`, `executionMode` `process`). The live fly must be on the legacy
runtime for any shadow: only the legacy loop writes the trace, and `start` refuses otherwise.
- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
further behind every hour. `start` refuses without the remote configuration below; `start --local`
runs it on the container anyway. In remote mode `flyshadow.service` on the container is the
*relay* (`fly-shadow relay`, from a drop-in `start` writes): normal scheduling off flysim's CPUs,
a few file reads and one outbound ssh stream that carries the trace, the new saves and the sugar
journal to the box and brings the box shadow's verdict back to `/srv/fly/shadow/verdict.json`.
The guard, `check` and CUT-01 see the unit and the files they always did. Set-up below
("Remote shadow set-up").
- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty
10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth
rate. It refuses unless flysim ran normally for most of that time. Then it:
1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
`FLY_TRACE_LEDGERS=60`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this
run's id: the start's Unix ms);
2. starts `flyshadow.service` and waits for its heartbeat (remote: up to 5 minutes, while the
box resets its mirror, restarts its shadow for the new run and reports it alive);
3. restarts `flysim.service` once;
4. starts `flyshadow-guard.timer`.
`FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. The restart is the same one
the unstick rule uses: the rung is kept and the ledgers are cleared. A previous `verdict.json`
is kept beside the new one, renamed with its time.
- **The guard** runs every 60 s, automatically, and judges the live fly against its own baseline,
not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a
sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process
fall below the baseline, or grow lag faster than it, by more than the margin. The margin is
max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a
real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and
restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and
`status` shows it. A paused fly is not judged, and a restarted one starts its window again.
Once the shadow is down for good (`ActiveState` inactive or failed: diverged, stopped, given up),
the guard stops itself and changes nothing. While the shadow waits out its 10-s crash-restart delay
(`activating`) the guard keeps running. A trip is not a divergence: fix the resources, then `start` again.
- **While it runs**, every later flysim restart (the unstick rule, the watchdog,
`fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on
its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes.
Stopping or restarting `flyshadow.service` itself starts the window again.
- **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence:
- 10,800 brain seconds are compared;
- at least one live save per 10 brain minutes has been compared byte for byte.
The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01
runs `check` at the moment it cuts over. `check` also requires all of these:
- at least 10,800 brain seconds, whatever window the shadow was started with;
- the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and
`baseline.json` exists (a run no guard watched is never cut over);
- remote: `/srv/fly/shadow/relay.json` is less than a minute old and `healthy` (connected, the
box's shadow of this run alive, the sync caught up), and the verdict is this run's (`runId`);
its `lagTransitions` counts the live trace not yet on the box as well;
- the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
other shadowed binary unchanged;
- the shadow is caught up (at most about a minute behind);
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
a trace that is not being written while the shadow claims to follow refuses the check (a paused
flysim refuses too, until it runs);
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
refuse (safe, not silent). Run NTP on both;
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
(a clock stepped back must not keep an old pass fresh);
- no segment was skipped for a reason other than the live side's own.
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure
of the session runtime itself counts: it did not start, the restore gate refused the live save,
or a step failed. The shadow leaves `verdict.json` at `diverged` and
`/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it.
On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so
flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the
files for the review, and do not cut over.
- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
deletes every file it has compared (remote: the box deletes its copy, and the relay then deletes
the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that
stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
gap, never a skip. The shadow discards the brain time and saves compared before it
(`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
`coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
new window has compared the required time.
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
would have to restart while the stopped trace is still the newest file and reach its stop before
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
one.
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
and the run is lost (safe: start a new run as above); do not rely on the fast case.
`coverageLost` is synced to disk before the chunk with the stop is forwarded.
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
counts against it; if the guard trips on a remote run, the trace alone is too much for the live
fly's headroom. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the
unit's `AllowedCPUs` (`systemctl show`) is disjoint from flysim.service's (05-deploy skips every
cpuset drop-in when the CT conf and CPUSET disagree).
- **Stop** stops the unit and the guard, removes the drop-ins, and deletes the trace and the spool
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
within a minute, because its consumer is gone. Remote, the box's shadow keeps running idle until
the next `start`, which resets its mirror and restarts it for the new run.
- **Remote divergence**: the box's shadow stops (exit 3); the relay brings `divergence.json` and
both checkpoint files back to `/srv/fly/shadow/`, writes the diverged verdict and exits with
status 3 (the unit stays stopped, the guard stops itself). Pull the files from the container as
for a local divergence.
### Remote shadow set-up (SHADOW-02)
Once per build box, and again for every release the container runs. The real values (the box's
address, the key's path) go in the operator's private files, never in this repository. Nothing
on the build box can reach the release container: the container dials out.
1. **The relay's key**, on the release container (as root, claimed):
`install -d -o root -g fly -m 0750 /etc/fly/shadow-remote`, then
`ssh-keygen -t ed25519 -N '' -C fly-shadow-relay -f /etc/fly/shadow-remote/id_ed25519` and
`chown fly:fly /etc/fly/shadow-remote/id_ed25519*`. The private half never leaves the container.
The container needs an ssh client (`openssh-client`; `02-base.sh` installs it) and no sshd.
2. **The box** (as root on the box): copy the release tarball the container runs, the cartridge,
`infra/box/` and the public key there, then
`infra/box/fly-shadow-remote-setup flybrain-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
`/etc/fly/shadow-remote/known_hosts` on the container (`ssh-keyscan` from the host, checked by
hand).
3. **The container's remote file**, `/etc/fly/shadow-remote.env` (root, 0600):
`FLY_SHADOW_REMOTE=flyshadow@<box address>`,
`FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
it and runs in remote mode.
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
after an hour. The ingest refuses a relay whose release directory or binaries
differ from the box's (another release on the container: re-run step 2 with its tarball);
`journalctl -u flyshadow` on the container shows it.
Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
with `--cpus` and `--threads`; keep other heavy work (bx) off that box
for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
## Cutover to the session runtime (CUT-01)
Operator decision (2026-09-30): the stream moves to the session runtime only if that runtime
sustains at least 1.0x real time on the release container, otherwise it stays on legacy. Only the
release container can measure that, so the switch is guarded by a **probation**. Claim the
container in the host log first, as for any host work.
```
# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy.
# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy)
# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact; on a build box
# (Remote shadow set-up above, once per box and release):
pct exec $CTID -- /opt/fly/bin/fly-shadow-run start
pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass
# 3. Cutover: the shadow's gate, then the switch. One command line:
pct exec $CTID -- sh -c '/opt/fly/bin/fly-shadow-run check && /opt/fly/bin/fly-runtime session'
# 4. Watch the probation (30 minutes after the switch):
pct exec $CTID -- /opt/fly/bin/fly-runtime-probation status
pct exec $CTID -- /opt/fly/bin/fly-runtime status
# 5. Pass, or automatic fallback (below). Nothing to stop: step 3 already stopped the shadow.
# Manual rollback, any time (cancels the probation too):
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy
```
- **Step 3 in detail.** `check` refuses unless the verdict, the guard and the release all line
up (Shadow run above). `session` then does what "Switch the runtime" describes (compatibility
check, drop-in, restart, health wait) and, once flysim is healthy on the session runtime, starts
the probation. `session` returns 0 at that point: the probation is judged later, by the timer.
`session` also stops the shadow and its guard (`fly-shadow-run stop`, never
`--restart-flysim`) as soon as flysim is healthy on the session runtime, before the probation
starts. A guard left running would judge the session runtime against the legacy baseline and
restart flysim on a trip (a second start inside the 600 s start-limit window, and a reset
warm-up), and the session writes no trace, so the shadow has nothing to follow. If you stop the
shadow by hand at any time during the probation, do it without `--restart-flysim`.
- **The probation** (`infra/bin/fly-runtime-probation`, `fly-runtime-probation.timer` every 60 s,
root). Each tick takes one sample of flysim's `/metrics` (`fly_realtime_factor` averaged over 10
one-second reads, `fly_lag_seconds`, `fly_uptime_seconds`; the same sampling as the shadow
guard). It judges the session runtime only:
- *Warm-up.* A flysim process is not judged before it has been up 300 s (connectome load,
restore, first minutes). A restart, a pause or a fly that is not `running` starts the window
again; it is never counted as slow.
- *Failure*, sustained and not one sample: over the judged samples of the last 10 minutes (at
least 8 of them) the **median** realtime factor is below **0.97**, or the lag grew by more than
**30 s** from the window's start to its end (median of the first and of the last three
samples). The median is the robust statistic the shadow guard's baseline uses: one or two
stalled minutes do not fail it, a steady 0.85x does, at the earliest about 13 minutes after the
switch (5 min warm-up, 8 samples). A lag step of more than 30 s inside the window counts as
lag growth.
- *Pass*: 30 minutes since the switch, and the latest window is full and healthy. A probation
that cannot fill a window within 2 h (a fly that never runs) fails as inconclusive: no proof
of 1.0x, no cutover. `FLY_PROBATION_*` variables tune every number (tests and rehearsals only).
- **On failure** it runs `fly-runtime fallback "speed: ..."`, exactly the fallback of "Switch
the runtime": under the same lock, `/run/fly/runtime-fellback.json` with the reason
(`"speed: median realtime factor 0.850 < 0.97 ..."`), the drop-in removed, flysim restarted on
legacy, a `fly-runtime` journal line (`journalctl -t fly-runtime`,
`/var/lib/fly/runtime.log`), and the probation ended (`/var/lib/fly/probation/last.json`
says `passed: false`). If that fallback cannot complete (no executable `flysim`) it is retried
every minute. The container is then on legacy and the decision is "no cutover": do not retry
`session` without a fix (or a new measurement) for the cause.
- **On pass** it writes `/run/fly/runtime-probation.json` (`{"passed": true, "at", "startedAt",
"medianRtf", "lagGrowth", "samples", "detail"}`; also kept in
`/var/lib/fly/probation/last.json` because `/run` is cleared by a reboot) and disables its
timer. **Nothing judges the speed afterwards.** A continuous guard would make a passing
cutover fall back at 03:00 on one noisy hour, on a stream that has proven itself, and the
watchdog already covers a stuck or dead loop. The start-limit fallback also stays as it is.
- **Cancel and resume.** `fly-runtime legacy` cancels the probation, as does every fallback
(including the start-limit one), and a tick that finds the legacy runtime selected ends it
without a verdict. The state is `/var/lib/fly/probation/state.json` and the timer is enabled while
a probation runs (`[Install] WantedBy=timers.target`; nothing else enables it), so a reboot
during the probation resumes it: `OnBootSec=90s` runs the first tick, flysim's new process
starts a new warm-up and window, and the 30 minutes keep counting from the original switch.
`fly-runtime session --no-restart` (05-deploy's refresh of the drop-in) starts no probation;
`fly-runtime session --no-probation` is for rehearsals. A `session` that cannot start the
probation (helper or timer unit missing) falls back: an unguarded cutover is not allowed.
- **Reading the result honestly.** The probation is absolute, as decided: a container on which the
legacy loop itself runs below 0.97x (the release container has been measured at 0.66, and 0.77-0.99
after its cpuset rebalance) will fail it, and the session runtime was measured at 1.25-1.35x
legacy's time per frame on the dev box. A fallback with reason `speed` therefore means "this box
cannot hold real time on the session runtime", not necessarily "the session runtime is
broken"; compare with `fly-shadow-run`'s baseline (`/srv/fly/shadow/baseline.json`) before
anything else. The `check` before it measures the live fly against itself; this measures it
against the clock.
- **Rehearsal** without a host: `fly-runtime-probation simulate CHECKS.jsonl` runs the rule over
recorded samples (`{t, status, rtMean, lag, uptime}`, one a minute); `infra/tests/lint.sh` drives
the real `fly-runtime` and the probation over synthetic traces (healthy, 0.85x, a stall, lag
growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real
systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume).
## Control over the bus (CTRL-01)
`FLY_CONTROL_VIA` picks who serves `http://127.0.0.1:7401`: `direct` (the default; flysim binds
it) or `bus`. In bus mode flysim registers the control API as RPC services on its embedded flybus
router, and `flycontrol-edge.service` serves the same HTTP bytes on `:7401` by calling them
(`docs/design/flybus.md`, "Control over the bus"). Clients do not change: the bridge, the stage's
health wait, the watchdog, `fly-runtime`, the probation and shadow guards, `fly-loop-recover`,
the stream check and `curl` still talk to `:7401`. It works under either runtime, independently
of `FLY_FEED_VIA`. Claim the container in the host log first, as for any host work.
**Prerequisites.** The release ships `fly-control-edge` (`ls /opt/fly/current/fly-control-edge`).
The env file has `FLY_CONTROL_VIA=bus`, deployed with `05-deploy.sh`. The deploy only rewrites
`/etc/fly/fly.env` and pushes the unit; it neither enables the edge nor restarts flysim, so the
box keeps serving `:7401` directly until step 2.
```
# 1. Before: what the switch must preserve.
pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint'
pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from
# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of
# flysim.service, started with it because fly.env says bus) binds :7401 once they answer.
# Between the two, :7401 refuses connections, exactly as during any flysim restart.
# There is nothing to enable: the unit has no [Install] section.
pct exec $CTID -- systemctl restart flysim.service
# 3. Verify.
pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"...
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"}
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status' # the frame moves
pct exec $CTID -- curl -s 127.0.0.1:9103/metrics | grep -E '^fly_control_edge_(bus_connected|calls_total|call_failures_total)'
pct exec $CTID -- journalctl -u flysim -b --since -5min | grep -E 'control services registered|bus listening'
pct exec $CTID -- ls /run/fly/bus/control-edge.sock /run/fly/bus/control/
pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridge: sim reachable
```
- **Healthy looks like:** `fly_control_edge_bus_connected 1`, `calls_total` rising (the bridge and
the watchdog poll it), `call_failures_total` flat, no `fly-watchdog:` restart lines, and the next
real channel-points sugar fulfilled as before. Do not fire a test sugar or chat line on the live
stream to prove it; both are visible on screen.
- **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a
dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails
while flysim is healthy (the sudoers file grants exactly that restart).
- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=`
on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode
and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start`
(`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all
bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge
unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer.
**Rollback** (any time, no release change):
```
pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env
pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz
# then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back.
```
- **Rolling back to a release from before CTRL-01 while in bus mode** is safe. The older flysim
does not know `FLY_CONTROL_VIA`, so it binds `:7401` itself. The edge unit's
`ConditionPathExists=` keeps it inactive on a release without the binary, and the older
watchdog reads `:7401` as before. Switch to direct first anyway, so the env file says what
runs.
- **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port
cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim
was not restarted after the deploy. Restart flysim (step 2).
- **Upgrading a container that had the edge enabled** (before this wiring): an
old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but
run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true.
## CPU partition (cpuset) ## CPU partition (cpuset)
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
@ -1098,78 +420,6 @@ not a constant, and live in the operator's infra repo
ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh` ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh`
checks it against both the current shape and the earlier, narrower one. checks it against both the current shape and the earlier, narrower one.
### The sim's CPUs are exclusive to the sim (PERF-02 review N1)
The session runtime pins its sweep workers one per CPU. A pinned worker cannot leave its CPU, so
any sustained CPU-bound process that is allowed on a worker's CPU stalls every barrier: measured
**0.14x real time** with a plain busy loop (0.68x at nice 19; `SCHED_IDLE` was harmless; the
floating, unpinned runtimes held 0.86-0.94x under the same hog). Priorities cannot fix that, so
the partition above is completed by making the sim's CPUs exclusive:
- `flysim.service` and `flysim-session.service` run in **`flysim.slice`** (`units/flysim.slice`),
whose `AllowedCPUs=` is the sim's set (`flysim.slice.d/cpuset.conf`, written by `05-deploy.sh` from
`lib/common.sh`'s `cpuset_dropin_plan`, the same call that writes every other drop-in).
- `bin/fly-cpu-confine apply` sets `AllowedCPUs=` the **non-sim** CPUs on `system.slice` (every
other service, cron, apt, sshd), `user.slice` (every login session) and `init.scope`, and writes
the same list to `/sys/fs/cgroup/.lxc/cpuset.cpus` (where `pct exec` / `pct enter` processes land,
see below). It runs as
both sim units' `ExecStartPre` (root, failure never blocks the start), so it is re-applied after
every boot and every restart. The lists come from `/etc/fly/cpuset.env`, which the deploy writes.
- The slice is named without a dash on purpose: systemd nests `a-b.slice` under `a.slice`, and a
child's cpuset is bounded by its parent's (cgroup v2: effective cpus = own cpus intersected with
the parent's, and the parent's when that is empty). `flysim.slice` sits beside `system.slice`
under the root slice, so nothing above it excludes its CPUs.
- **Ordering rule.** Shrinking `system.slice` under a flysim that still sits in `system.slice` (a
unit started before this change, not yet restarted) would leave its own `AllowedCPUs=` outside the
parent's set and silently make it float over the page CPUs. So `apply` refuses (exit 3, nothing
changed) while a sim unit's cgroup is not under `/flysim.slice/`. A deploy therefore changes
nothing on a running sim; the confinement starts with the next `flysim` (re)start, which is the
first moment it is safe. `fly-cpu-confine status` shows the result.
- `fly-recap` and `fly-retention` also run at `CPUSchedulingPolicy=idle`, which the review measured
harmless beside the pinned workers (defence in depth for the batch jobs).
- **No partition, no pinning.** With `CPUSET` unset (or the container conf not matching it) there
is no confinement, so `05-deploy.sh` writes `FLY_SESSION_PIN=0` to `/etc/fly/fly.env` and the
session runtime's threads float, as before PERF-02. With the partition in force it writes
`FLY_SESSION_PIN=1`. (The runtime treats exactly `0` as off.)
- **`pct exec` / `pct enter`:** `lxc-attach` puts its processes in the cgroup `/.lxc` (or
`/.lxc-N`), a sibling of `system.slice` that systemd does not manage. `apply` writes the non-sim
list into the `cpuset.cpus` of every such cgroup that already exists (it never creates one; lxc
owns it). Where that file is not writable it logs a warning and carries on: `apply` never fails
the sim's start. In that case run long operator jobs through
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`. A `.lxc-N` created
after `apply` is not covered until the next sim start. `fly-cpu-confine check` lists every
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one); its own
process and the shell chain it was started from are printed as a note and not counted, so it
exits 0 on a healthy container when run through `pct exec`.
- **After the first deploy (once):** restart the sim so the confinement is applied, then read it.
`apply` is refused while flysim still runs outside `flysim.slice`, so nothing changes until then.
```
pct exec <ctid> -- systemctl restart flysim.service
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine status # system.slice, user.slice, init.scope and /.lxc = the non-sim cpus; flysim.slice = the sim's; flysim ControlGroup under /flysim.slice/
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine check # exit 0: "ok: only flysim.slice can reach ..."
pct exec <ctid> -- systemctl show -p AllowedCPUs flycast.service xvfb.service # still the drop-in values
```
Then watch the probation RTF. A `check` that names a process is a hog to move or stop.
- **If lag grows on the session runtime**: `fly-cpu-confine check`, then `top -H` for a stray hog on
the sim's CPUs. `FLY_SESSION_PIN=0` (a drop-in) restores floating.
- `fly-cpu-confine release` undoes the runtime confinement (until the next sim start); it sets
`system.slice`, `user.slice`, `init.scope` and `/.lxc` back to the container's whole cpuset
explicitly, because systemd keeps the old mask for an empty `AllowedCPUs=` while the cpuset
controller stays on for another unit. (Tested in `tests/lint.sh` against a fake cgroup tree.)
- **Rollback by re-running an older infra tree's `05-deploy.sh`** (rather than the symlink flip in
"Roll back a release", which is fine): an infra tree older than this change has no
`Slice=flysim.slice`, so flysim restarts into `system.slice`, which is still confined to the
non-sim CPUs. Its `AllowedCPUs=` then does not intersect that set and it floats over the page and
encoder CPUs while the sim's own CPUs sit idle (the slow shape again, not a black stream). After
such a rollback run `pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine release` (or reboot), then
restart flysim.
Verified on a real-systemd box (4 CPUs, the sim as a unit in `flysim.slice` on 3 of them, 3 sweep
threads, paced at 0.55x): confined or not, with no hog the session holds 0.55; five busy loops (three
as system services, two from a user shell) unconfined sit on the sim's CPUs and the session drops to
0.37; confined by the unit's own `ExecStartPre`, every loop samples on CPU 0 only, the sim's threads
keep their CPUs and the session holds 0.54-0.55.
### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition ### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition
`FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into `FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into
@ -1182,49 +432,13 @@ loud which backend is configured. Two separate switches, deliberately:
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed | | build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* | | run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file: backend from flysim's own log, not from the env file:
```sh ```sh
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend'
``` ```
The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables
(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without
the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with
`BACKEND_FAILURE`; a build with it logs `LIF backend cuda:<n> attached, device-owned state` when
the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the
card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual
drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the
feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too.
**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no
paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches
a dead card in a loop:
- A CUDA error on a frame whose host state was current (the first frame after a start or a
restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there.
- Any other CUDA error mid-run fails the agent (the device held the only current copy of the
membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on
the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact,
so the CPU run equals one that never had a GPU.
- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and
a CPU worker, not a failed `Agent.Initialize`.
- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still
dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU.
Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure,
with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs),
`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the
textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and
`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises
`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It
takes no remediation and pages no one (a restart cannot fix a dead card and would cost the
run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host,
and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2`
(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0`
and redeploy if the card is not coming back soon.
It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`. targets, `sm_75`.
@ -1332,24 +546,9 @@ pct exec <ctid> -- cat /run/fly/wd/loop.json | jq .
| `fly_loop_repeats` | how many times that block repeats at the end of the 10-brain-minute window | | `fly_loop_repeats` | how many times that block repeats at the end of the 10-brain-minute window |
| `fly_loop_distinct_macros` | distinct macro names started in the window | | `fly_loop_distinct_macros` | distinct macro names started in the window |
| `fly_places_delta` | growth in `game.uniqueLocations` since the previous probe (`-1` = no previous probe) | | `fly_places_delta` | growth in `game.uniqueLocations` since the previous probe (`-1` = no previous probe) |
| `fly_loop_refused` | macro presses refused in the window: a bound button pressed, nothing run |
| `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window |
| `fly_loop_done` | macros that ended `done` in the window |
| `fly_loop_rewards` | reward events in the window |
| `fly_loop_fights` | `MOVE n` decisions (a move chosen in a battle) in the window |
| `fly_loop_wins` | battle-won reward events (`wildwin`, `trainer`, `badge`) in the window |
The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+ The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+
times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused, times, or one macro at 95%+ of the window — **and** no growth in the exploration count. A
blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row
(`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row
(`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other
names, every macro `done`), or 24+ `MOVE n` decisions and no battle won on two probes in a row
(`unwon-battles`, row 67: one Pewter Gym trainer lost thirty times, whiteout and back, with a
stray tile reward now and then keeping `unrewarded` quiet) — **and** no growth in the exploration count. A decision is a `start` or a
`refused`: a refused press starts nothing, which is why counting starts alone read row 57's
pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and
one name. A
repeating macro over ground that keeps growing is a walk longer than the 600-frame cap, not a repeating macro over ground that keeps growing is a walk longer than the 600-frame cap, not a
trap (`macros-traps.md`: `GO FRONTIER` x19 across 93 tiles), and the watchdog is deliberately trap (`macros-traps.md`: `GO FRONTIER` x19 across 93 tiles), and the watchdog is deliberately
quiet about it. The thresholds are `WD_LOOP_*` in `infra/bin/fly-watchdog`; the 3-name ceiling quiet about it. The thresholds are `WD_LOOP_*` in `infra/bin/fly-watchdog`; the 3-name ceiling
@ -1463,50 +662,6 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
whichever container got there first lock the card out from under the other. whichever container got there first lock the card out from under the other.
## GPU on a build box (dev and benchmarks)
A build box is a container with the host's `/dev/nvidia*` device nodes passed through but no
userspace driver installed — used for the `cuda` feature tests and the GPU benchmarks. The
release container follows the lockstep runbook above; this path is only for build boxes,
no root, no system install, one userspace per test run.
**Get the host's module version** — the .run must match exactly:
```sh
ssh the host cat /proc/driver/nvidia/version # the "Kernel Module" line
# or: ssh the host cat /sys/module/nvidia/version
```
**Install under your home.** Download the matching `NVIDIA-Linux-x86_64-<ver>.run`, verify
its SHA256 against the checksum NVIDIA publishes, and `--extract-only`:
```sh
VER=580.76.05 # whatever the host module reports
mkdir -p ~/tmp/nvidia-$VER && cd ~/tmp/nvidia-$VER
U=https://download.nvidia.com/XFree86/Linux-x86_64/$VER/NVIDIA-Linux-x86_64-$VER.run
curl -fSLO $U && curl -fSLO $U.sha256sum
sha256sum -c NVIDIA-Linux-x86_64-$VER.run.sha256sum # must print OK
sh NVIDIA-Linux-x86_64-$VER.run --extract-only --target ~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
```
**Use it only for the test run.** Prepend the extracted directory to `LD_LIBRARY_PATH`
(`libcuda.so`, `libnvidia-ptxjitcompiler.so`) and `PATH` (`nvidia-smi`); the kernel
modules are the host's, so nothing else is needed:
```sh
NV=~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH FLY_CARGO_FEATURES=cuda \
cargo test --release -p flybrain-core --features cuda
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH \
cargo run --release -p flybrain-core --features cuda --example cuda_bench
```
**Shared card.** The build box shares the GPU with the LLM workload. Before and after each
timing run, `nvidia-smi` for other compute processes on the device; re-run flagged timings
(benchmarks yield to the other workload — a contended run is not a measurement).
**Never on the release container** — that path is the lockstep one above.
## The host reboot order ## The host reboot order
Fly containers have no special reboot ordering requirement relative to each other Fly containers have no special reboot ordering requirement relative to each other

View file

@ -49,7 +49,7 @@ a credential. Full list:
| # | shape matched | path | commits (first → last touching) | verdict | | # | shape matched | path | commits (first → last touching) | verdict |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/<channel>-key`), not a secret. | | 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/fly-pokemon-key`), not a secret. |
| 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. | | 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. |
| 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. | | 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. |
| 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. | | 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. |

4
infra/env/README.md vendored
View file

@ -53,8 +53,6 @@ requires `CTID`, `HOSTNAME`, `IP`, `GAME` and `PUSH_TARGET`; `ROLE` defaults to
Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app
id/secret arrive as the systemd credential `twitch-app`, installed by id/secret arrive as the systemd credential `twitch-app`, installed by
`infra/06-secrets.sh` from `pass` on the operator box, reading the two entry **names** from `infra/06-secrets.sh` from `pass` on the operator box; the OAuth tokens live in the
`BRIDGE_ID_KEY` and `BRIDGE_SECRET_KEY` in the real env file (it skips `twitch-app` with a
warning when they are unset); the OAuth tokens live in the
container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and
the ROM it describes is never committed, copied into the repo, or shown on stream. the ROM it describes is never committed, copied into the repo, or shown on stream.

49
infra/env/example.env vendored
View file

@ -138,12 +138,6 @@ RAYON_THREADS=3
# cpuset_partition (default 2 when unset). flycast gets its own group rather # cpuset_partition (default 2 when unset). flycast gets its own group rather
# than sharing the page group — see lib/common.sh's cpuset_partition header. # than sharing the page group — see lib/common.sh's cpuset_partition header.
ENCODER_CORES=2 ENCODER_CORES=2
# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in
# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when
# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the
# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs
# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`.
SESSION_AUX_CPUS=0
# --- CUDA LIF backend ------------------------------------------------------- # --- CUDA LIF backend -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what # 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
@ -222,11 +216,6 @@ TWITCH_CHANNEL=<twitch-channel>
# never is. 06-secrets.sh reads it on the operator box and installs it as a # never is. 06-secrets.sh reads it on the operator box and installs it as a
# systemd credential. # systemd credential.
PASS_KEY=twitch/<channel>-key PASS_KEY=twitch/<channel>-key
# The `pass` entries holding the Twitch app client id and secret (names only).
# 06-secrets.sh installs them together as the twitch-app credential; unset means
# it skips twitch-app with a warning.
BRIDGE_ID_KEY=twitch/<app>-client-id
BRIDGE_SECRET_KEY=twitch/<app>-client-secret
# --- flybridge (services/bridge/src/config.ts) ------------------------------ # --- flybridge (services/bridge/src/config.ts) ------------------------------
# 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads # 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads
@ -323,49 +312,11 @@ CHAT_DENY_LIST=/srv/fly/chat-deny.txt
# "palette" and "plan" are the two modes section 12 replaced; flysim still reads # "palette" and "plan" are the two modes section 12 replaced; flysim still reads
# either as "macros", with a warning, for one release. # either as "macros", with a warning, for one release.
FLY_MACRO_MODE=raw FLY_MACRO_MODE=raw
# --- feed path ----------------------------------------------------------------
# Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the
# bus"). direct: flysim binds it, as always. bus: flysim publishes every
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
# the same bytes. This line (written into fly.env by every deploy) is the only
# switch: flysim.service wants the edge, which starts only in bus mode.
# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts
# flysim, checks the page is back, rolls back by itself) and put the same value
# here afterwards, or the next deploy warns that it writes the old one back.
# Watchdog check 2 follows the running mode to the edge's counters by itself.
# Runbook: "Feed over the bus".
FLY_FEED_VIA=direct
# --- control path -------------------------------------------------------------
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,
# "Control over the bus"). direct: flysim binds it, as always. bus: flysim
# registers the control services on its embedded bus (/run/fly/bus) and
# flycontrol-edge.service serves the same bytes; enable that unit by hand
# (infra/docs/runbook.md, "Control over the bus"). Independent of FLY_FEED_VIA.
FLY_CONTROL_VIA=direct
# How long a macro leaves a target alone after a walk to it aborted "blocked" or # How long a macro leaves a target alone after a walk to it aborted "blocked" or
# "timeout" (macros.md section 12.1). Session state, so a restart offers every # "timeout" (macros.md section 12.1). Session state, so a restart offers every
# target once more. Unset means the default, 10. # target once more. Unset means the default, 10.
# FLY_MACRO_BLOCKED_MINUTES=10 # FLY_MACRO_BLOCKED_MINUTES=10
# --- restoring across an adapter version ------------------------------------
# Adapter version strings whose checkpoints this build may migrate, comma- or
# space-separated (docs/design/flysim.md, "Restoring across an adapter
# version"). Unset -- the default, and what every deploy before 2026-09-22 did
# -- migrates nothing: a build whose compatibility string differs from the live
# state's is refused by 05-deploy's gate and by flysim at restore.
#
# It applies only when the ADAPTER segment is the only difference between the
# two strings AND the new build's adapter declares a migration from that one. A
# dataset, kernel, plasticity, emulator or state-format difference is still a
# refusal. Set it for the one deploy that needs it and leave it out afterwards;
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The deploy
# of pokered-unique8-v8 (the damage reward) over the live v7 run needs:
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7
# and, to keep the milestone archives written before v0.6.0 restorable as
# fallbacks and fly-reset-to-milestone targets, also names v6 (v8 reads both):
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7,pokered-unique8-v6
# (v0.6.0's, pokered-unique8-v7 over v6, needed pokered-unique8-v6.)
# --- push mode -------------------------------------------------------------- # --- push mode --------------------------------------------------------------
# local: flypush.service stays disabled, everything else identical to prod. # local: flypush.service stays disabled, everything else identical to prod.
# twitch: flypush.service is enabled by 07-enable.sh. # twitch: flypush.service is enabled by 07-enable.sh.

View file

@ -154,33 +154,6 @@ require_release_tag() {
# (An earlier, eight-cpu version of this same live hotfix — CPUSET= # (An earlier, eight-cpu version of this same live hotfix — CPUSET=
# 1,3,5,7,9,11,13,15, ENCODER_CORES=2 (the default) — gave flysim=1,3,5,7, # 1,3,5,7,9,11,13,15, ENCODER_CORES=2 (the default) — gave flysim=1,3,5,7,
# page=9,11, flycast=13,15; infra/tests/lint.sh checks both shapes.) # page=9,11, flycast=13,15; infra/tests/lint.sh checks both shapes.)
# feed_via_normalize VALUE — print FLY_FEED_VIA lowercased (empty means "direct"), or
# return 1 for anything but direct|bus. flysim itself reads the value case-insensitively
# and refuses anything else at boot, which on a container is a restart loop; 05-deploy.sh
# refuses it at deploy instead and writes the lowercased word, so watchdog check 2 and
# flysim can never read the same line two ways (docs/design/flybus.md).
feed_via_normalize() {
local via
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
case "$via" in
direct|bus) printf '%s\n' "$via" ;;
*) return 1 ;;
esac
}
# control_via_normalize VALUE — FLY_CONTROL_VIA as feed_via_normalize does FLY_FEED_VIA:
# lowercased (empty means "direct"), or return 1 for anything but direct|bus. flysim refuses
# anything else at boot; 05-deploy.sh refuses it at deploy and writes the lowercased word, which
# the watchdog reads to know who serves :7401 (docs/design/flybus.md, "Control over the bus").
control_via_normalize() {
local via
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
case "$via" in
direct|bus) printf '%s\n' "$via" ;;
*) return 1 ;;
esac
}
cpuset_partition() { cpuset_partition() {
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}" local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
@ -202,69 +175,6 @@ cpuset_partition() {
echo "$sim_cpus $page_cpus $encoder_cpus" echo "$sim_cpus $page_cpus $encoder_cpus"
} }
# cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's
# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's
# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu.
cpuset_aux_split() {
local page="$1" count="$2" n
n="$(echo "$page" | awk -F, '{print NF}')"
if [ "$count" -ge "$n" ]; then
die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS."
fi
echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)"
}
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service,
# flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine:
#
# flysim.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the
# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it);
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
# slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
# flycast the encoder CPUs;
# flyshadow page + encoder (never the sim's);
# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS);
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
# of CPUSET that is not the sim's, in CPUSET order.
#
# One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
# cpuset_partition does.
cpuset_dropin_plan() {
local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
local out
out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
read -r sim page enc <<< "$out"
if [ "$aux_count" -gt 0 ]; then
# not `read <<< "$(...)"`: die inside the substitution would only end the subshell
out="$(cpuset_aux_split "$page" "$aux_count")" || return 1
read -r page aux <<< "$out"
fi
slice_cpus="$sim"
[ -n "$aux" ] && slice_cpus="${sim},${aux}"
echo "flysim.slice $slice_cpus"
for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $slice_cpus"
echo "FLY_OTHER_CPUS= ${page},${enc}"
[ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux"
return 0
}
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to
# /etc/systemd/system/UNIT-NAME.d/cpuset.conf ([Slice] for a .slice, [Service] otherwise).
cpuset_dropin_text() {
local unit="$1" cpus="$2" label="$3" section="Service"
case "$unit" in *.slice) section="Slice" ;; esac
echo "# generated by infra/05-deploy.sh from CPUSET in ${label} — do not hand-edit."
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[${section}]"
echo "AllowedCPUs=${cpus}"
}
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# operator-box guard # operator-box guard
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -1,32 +1,33 @@
# infra/tests/de-pii-allow.txt — the mentions tools/pii-scan.sh (run by # infra/tests/de-pii-allow.txt — the mentions infra/tests/lint.sh's de-PII
# infra/tests/lint.sh section 5, infra/build/tag-release.sh and the pre-push hook) # guard (section 5) is allowed to find.
# is allowed to find.
# #
# Format, whitespace-separated: # Format, whitespace-separated:
# #
# <path> <pattern-name> # reason # <path> <pattern-name> # reason
# #
# <path> is a repo-relative path, a directory prefix ending in `/`, or a glob. # <path> is a repo-relative path, a directory prefix ending in `/`, or a glob.
# <pattern-name> is a pattern name: a generic one from tools/pii-scan.sh # <pattern-name> is one of the guard's own names (host-proxmox, host-backup,
# (`tools/pii-scan.sh --list`), one from the operator's private pattern list # host-llm, operator-name, lan-address, container-id, host-root-path,
# (operator-name, forge-name, ...), or `*` for every pattern. # home-path, twitch-account, claim-log-name, forge-name, infra-repo-name,
# mac-address, email-address, pass-entry-path), or `*` for every pattern.
# #
# EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead — # EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead —
# the rules and the per-file verdicts live in the operator's infra repo. # the rules and the per-file verdicts live in the operator's infra repo.
# An entry here says "this string is not identifying", not "this is grandfathered". # An entry here says "this string is not identifying", not "this is grandfathered".
# #
# Comments below describe what a mention is, never the private string itself: an # The literals in the comments below are spelled with one bracketed character, for
# allowlist that carried the plaintext would be the leak it is meant to prevent. # the same reason lint.sh spells its patterns that way: an allowlist that carried the
# plaintext would be the leak it is meant to prevent.
# --- chat-username fixtures ------------------------------------------------- # --- chat-username fixtures -------------------------------------------------
# A lowercase first name is the chat-username fixture the sanitizer, deny-list, # Lowercase `"alex"` is the chat-username fixture the sanitizer, deny-list,
# rate-limiter, ticker and store tests are written against; the de-PII sprint # rate-limiter, ticker and store tests are written against; the de-PII sprint
# leaves test fixture names alone. The operator-name pattern is case-sensitive # leaves test fixture names alone. The guard's operator-name pattern is
# precisely so the capitalised name in prose still fails, and the real handle # case-sensitive precisely so capitalised `Al[e]x` in prose still fails, and
# was replaced with `fly_fan_42`. These entries exist only for the few places a # `al[e]x_camilo` (the real handle shape) was replaced with `fly_fan_42`. These
# fixture is lowercase-with-a-boundary that the pattern would still catch via # entries exist only for the few places a fixture is lowercase-with-a-boundary
# another alternative. # that the case-sensitive pattern would still catch via another alternative.
apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file
@ -34,12 +35,12 @@ services/flysim/crates/flysim/src/eventlog.rs operator-name # ticker fixture in
services/bridge/tests/ operator-name # lowercase chat-username fixtures services/bridge/tests/ operator-name # lowercase chat-username fixtures
# --- container-side paths --------------------------------------------------- # --- container-side paths ---------------------------------------------------
# `nvidia.run`, `virtualgl.deb` and `nv.run` under root's home are paths INSIDE # `/ro[o]t/nvidia.run`, `/ro[o]t/virtualgl.deb` and `/ro[o]t/nv.run` are paths INSIDE
# a container: root's home on a stock Debian guest, not an operator-chosen # a container: root's home on a stock Debian guest, not an operator-chosen
# location, and not specific to this network. Host-side staging paths are # location, and not specific to this network. Host-side staging paths are
# parameterised instead (HOST_STAGE_DIR / `<host-stage>`). # parameterised instead (HOST_STAGE_DIR / `<host-stage>`).
infra/02-base.sh host-root-path # the two installer paths under root's home are inside the guest infra/02-base.sh host-root-path # /ro[o]t/nvidia.run and /ro[o]t/virtualgl.deb are inside the guest
docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ root links, which are procfs docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ro[o]t/... which is procfs, not /root
# --- documentation examples ------------------------------------------------- # --- documentation examples -------------------------------------------------
# A made-up MAC in a worked example of the compatibility string. Real MACs are # A made-up MAC in a worked example of the compatibility string. Real MACs are
@ -50,16 +51,11 @@ services/flysim/crates/flybrain-gb/src/compatibility.rs mac-address # aa:bb:...
# Third-party addresses and handles: upstream projects, not this network. # Third-party addresses and handles: upstream projects, not this network.
# (None currently; keep the section so the next one lands in the right place.) # (None currently; keep the section so the next one lands in the right place.)
apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit
infra/tests/lint.sh email-address # the example.invalid git identity for the throwaway test repos infra/tests/lint.sh email-address # `lint@ex[a]mple.invalid`, the git identity for the throwaway test repos
infra/tests/pii-scan-test.sh email-address # same example.invalid identity for the scanner's throwaway repos
# --- publish pack ------------------------------------------------------------ # --- publish pack ------------------------------------------------------------
NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred
LICENSES.md operator-name # same copyright line, mirrored LICENSES.md operator-name # same copyright line, mirrored
.forgejo/workflows/ci.yml forge-name # the product name of the CI runner, not the operator's forge .forgejo/workflows/ci.yml forge-name # the product name of the CI runner (F[o]rgejo Actions), not the operator's forge
.github/workflows/ci.yml forge-name # a comment naming the sibling copy of this workflow .github/workflows/ci.yml forge-name # a comment naming the F[o]rgejo copy of this workflow
infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path
infra/tests/de-pii-allow.txt forge-name # this file names that workflow directory in the entry above infra/tests/de-pii-allow.txt forge-name # this file names the .f[o]rgejo/ workflow directory in the two entries above
# --- fixtures ----------------------------------------------------------------
apps/stage/tests/unit/query.test.ts private-address # made-up address in a feed-URL parsing fixture
services/bridge/tests/ secret-assignment # fake client id/secret fixtures ("test-client-secret-DO-NOT-LOG")

View file

@ -1,19 +0,0 @@
# Recorded live-fly samples for `fly-shadow-run`'s guard
These samples come from a real `flysim` (legacy, FAFB, macros mode, at real time) on a shared build
box on 2026-09-30. They are in `fly-shadow-run`'s own format and cadence:
- `baseline.jsonl` holds 60 samples 10 s apart;
- `checks.jsonl` holds 20 samples a minute apart, after the same flysim restart that `start` does.
`lint.sh` runs `fly-shadow-run simulate` over each case and holds it to `expect`:
| Case | Setup | Expect |
| --- | --- | --- |
| `slow-alone` | 1 cpu, 1 thread; no shadow | pass |
| `slow-shadow-same` | the same fly, with a real `fly-shadow` following it at normal priority on the same cpu. The live fly dropped from 0.66 to 0.44-0.60 | trip |
| `fast-shadow-idle` | 3 cpus, 3 threads; a real `fly-shadow` at `SCHED_IDLE` on other cpus. The box was already loaded, and the fly ran at 0.4-0.85 | pass |
| `fast-alone` | 3 cpus, 3 threads; no shadow | pass |
The box's own load moved the fly between 0.4 and 1.0 during some baselines. Those steps are why
the baseline is robust: the median, and the spread taken as the MAD.

View file

@ -1,60 +0,0 @@
{"t": 1790738128.362942, "status": "running", "rtMean": 0.7588339770286441, "lag": 33.479, "uptime": 71.223399881}
{"t": 1790738138.4285393, "status": "running", "rtMean": 1.0036906365382738, "lag": 33.479, "uptime": 81.293069051}
{"t": 1790738148.4962938, "status": "running", "rtMean": 0.9970303099114692, "lag": 33.479, "uptime": 91.408291997}
{"t": 1790738158.5748143, "status": "running", "rtMean": 0.9957513747669762, "lag": 33.479, "uptime": 101.483131764}
{"t": 1790738168.9591897, "status": "running", "rtMean": 0.819013893871745, "lag": 35.496, "uptime": 111.869185712}
{"t": 1790738179.0497794, "status": "running", "rtMean": 0.955720505211804, "lag": 35.496, "uptime": 121.957242118}
{"t": 1790738189.13739, "status": "running", "rtMean": 0.8799930137133124, "lag": 36.498, "uptime": 132.018380479}
{"t": 1790738199.2148638, "status": "running", "rtMean": 0.8902680060117365, "lag": 37.521, "uptime": 142.113434378}
{"t": 1790738209.3021023, "status": "running", "rtMean": 0.8803874146669992, "lag": 38.524, "uptime": 152.181022738}
{"t": 1790738219.3764796, "status": "running", "rtMean": 0.8658710279839296, "lag": 40.54, "uptime": 162.284831945}
{"t": 1790738229.4663715, "status": "running", "rtMean": 0.8894453486450183, "lag": 41.541, "uptime": 172.367967371}
{"t": 1790738239.553954, "status": "running", "rtMean": 0.9052554309116678, "lag": 42.543, "uptime": 182.460932044}
{"t": 1790738249.6388013, "status": "running", "rtMean": 0.9129316585556161, "lag": 43.544, "uptime": 192.526870399}
{"t": 1790738259.7050216, "status": "running", "rtMean": 0.9999965689074697, "lag": 43.544, "uptime": 202.609470103}
{"t": 1790738269.7767544, "status": "running", "rtMean": 0.9378600900744024, "lag": 43.544, "uptime": 212.690426315}
{"t": 1790738279.8516681, "status": "running", "rtMean": 0.7973579434723355, "lag": 45.556, "uptime": 222.761268128}
{"t": 1790738289.9210968, "status": "running", "rtMean": 0.9352522067409303, "lag": 46.571, "uptime": 232.836669514}
{"t": 1790738300.0552127, "status": "running", "rtMean": 0.7150556877963433, "lag": 49.584, "uptime": 242.963564523}
{"t": 1790738310.2007082, "status": "running", "rtMean": 1.0059437251512073, "lag": 49.584, "uptime": 253.109498917}
{"t": 1790738320.2790272, "status": "running", "rtMean": 1.00373183915971, "lag": 49.584, "uptime": 263.195154054}
{"t": 1790738330.3444412, "status": "running", "rtMean": 0.9972521469939926, "lag": 49.584, "uptime": 273.255265175}
{"t": 1790738340.4204133, "status": "running", "rtMean": 0.8495939168264007, "lag": 50.586, "uptime": 283.330032566}
{"t": 1790738350.5301325, "status": "running", "rtMean": 0.7839208383476353, "lag": 52.599, "uptime": 293.439062795}
{"t": 1790738360.6693776, "status": "running", "rtMean": 0.9653471893141468, "lag": 53.6, "uptime": 303.576346295}
{"t": 1790738370.8137631, "status": "running", "rtMean": 0.6241158180206947, "lag": 57.623, "uptime": 313.699656832}
{"t": 1790738380.9961703, "status": "running", "rtMean": 0.5687473149333804, "lag": 61.68, "uptime": 323.912074763}
{"t": 1790738391.089262, "status": "running", "rtMean": 0.5804323097526403, "lag": 65.706, "uptime": 333.967914558}
{"t": 1790738401.19394, "status": "running", "rtMean": 0.5362910197658861, "lag": 70.779, "uptime": 344.048343544}
{"t": 1790738411.3023837, "status": "running", "rtMean": 0.5510464052357773, "lag": 74.845, "uptime": 354.205680506}
{"t": 1790738421.4007213, "status": "running", "rtMean": 0.5652293538813947, "lag": 79.905, "uptime": 364.315364667}
{"t": 1790738431.503473, "status": "running", "rtMean": 0.57359026862898, "lag": 83.964, "uptime": 374.377908576}
{"t": 1790738441.6479023, "status": "running", "rtMean": 0.5540343187796515, "lag": 87.999, "uptime": 384.55919851}
{"t": 1790738451.7651033, "status": "running", "rtMean": 0.6037429716311573, "lag": 92.018, "uptime": 394.673360423}
{"t": 1790738461.8663146, "status": "running", "rtMean": 0.6985130182613225, "lag": 95.095, "uptime": 404.755070174}
{"t": 1790738471.9642298, "status": "running", "rtMean": 0.7594984860121092, "lag": 98.14, "uptime": 414.851205955}
{"t": 1790738482.0506132, "status": "running", "rtMean": 0.8166532570546075, "lag": 99.145, "uptime": 424.958463239}
{"t": 1790738492.1384304, "status": "running", "rtMean": 0.8807780226062987, "lag": 100.145, "uptime": 434.992925627}
{"t": 1790738502.2033277, "status": "running", "rtMean": 1.0802703218851182, "lag": 100.145, "uptime": 445.108112717}
{"t": 1790738512.273309, "status": "running", "rtMean": 0.9857221768324773, "lag": 100.145, "uptime": 455.179728346}
{"t": 1790738522.3412535, "status": "running", "rtMean": 1.0008941796078314, "lag": 100.145, "uptime": 465.243065017}
{"t": 1790738532.4065015, "status": "running", "rtMean": 1.0144037951650158, "lag": 100.145, "uptime": 475.316217749}
{"t": 1790738542.4878814, "status": "running", "rtMean": 0.995240358864496, "lag": 100.145, "uptime": 485.400446119}
{"t": 1790738552.5522985, "status": "running", "rtMean": 0.9958695819760208, "lag": 100.145, "uptime": 495.331048011}
{"t": 1790738562.6135433, "status": "running", "rtMean": 0.9990484834746928, "lag": 100.145, "uptime": 505.518260558}
{"t": 1790738572.6848962, "status": "running", "rtMean": 0.9999101070487516, "lag": 100.145, "uptime": 515.603359756}
{"t": 1790738582.7517495, "status": "running", "rtMean": 1.0067915374872096, "lag": 100.145, "uptime": 525.63843004}
{"t": 1790738592.8203006, "status": "running", "rtMean": 0.9933226593909843, "lag": 100.145, "uptime": 535.714625602}
{"t": 1790738602.8871908, "status": "running", "rtMean": 0.9997146956682066, "lag": 100.145, "uptime": 545.76592055}
{"t": 1790738612.9580173, "status": "running", "rtMean": 0.9995574815559497, "lag": 100.145, "uptime": 555.842376949}
{"t": 1790738623.0309892, "status": "running", "rtMean": 1.0009077839472587, "lag": 100.145, "uptime": 565.932440918}
{"t": 1790738633.1058488, "status": "running", "rtMean": 0.905700103566834, "lag": 101.148, "uptime": 576.014824329}
{"t": 1790738643.2241693, "status": "running", "rtMean": 0.9002632818253182, "lag": 102.159, "uptime": 586.12547679}
{"t": 1790738653.3037221, "status": "running", "rtMean": 1.001384402969126, "lag": 102.159, "uptime": 596.212798092}
{"t": 1790738663.377194, "status": "running", "rtMean": 1.0025847949946505, "lag": 102.159, "uptime": 606.291720522}
{"t": 1790738673.450081, "status": "running", "rtMean": 0.9982495351402143, "lag": 102.159, "uptime": 616.368169968}
{"t": 1790738683.5147092, "status": "running", "rtMean": 1.000470259093377, "lag": 102.159, "uptime": 626.427550974}
{"t": 1790738693.5863135, "status": "running", "rtMean": 0.9966639708181871, "lag": 102.159, "uptime": 636.458204371}
{"t": 1790738703.651422, "status": "running", "rtMean": 0.9994712074317433, "lag": 102.159, "uptime": 646.54138456}
{"t": 1790738713.7201247, "status": "running", "rtMean": 0.9965700494189607, "lag": 102.159, "uptime": 656.631814013}
{"t": 1790738723.7912498, "status": "running", "rtMean": 1.0007973265331749, "lag": 102.159, "uptime": 666.694264297}

View file

@ -1,20 +0,0 @@
{"t": 1790738735.0354905, "status": "running", "rtMean": 0.999484237762719, "lag": 0.0, "uptime": 11.07355663}
{"t": 1790738795.1101537, "status": "running", "rtMean": 0.998153021033785, "lag": 0.0, "uptime": 71.129215866}
{"t": 1790738855.1800184, "status": "running", "rtMean": 0.9926228160612285, "lag": 0.0, "uptime": 131.202241399}
{"t": 1790738915.249556, "status": "running", "rtMean": 0.9992177109183569, "lag": 0.0, "uptime": 191.273914994}
{"t": 1790738975.3090174, "status": "running", "rtMean": 1.0004807207169564, "lag": 0.0, "uptime": 251.312728385}
{"t": 1790739035.3770518, "status": "running", "rtMean": 0.99729025135176, "lag": 0.0, "uptime": 311.41256314}
{"t": 1790739095.4512274, "status": "running", "rtMean": 0.9963104110487839, "lag": 0.0, "uptime": 371.442377297}
{"t": 1790739155.5106263, "status": "running", "rtMean": 0.9986795197502222, "lag": 0.0, "uptime": 431.514951288}
{"t": 1790739215.5753255, "status": "running", "rtMean": 0.998777006263299, "lag": 0.0, "uptime": 491.615126509}
{"t": 1790739275.6377265, "status": "running", "rtMean": 0.9993828850549406, "lag": 0.0, "uptime": 551.643819315}
{"t": 1790739335.6982403, "status": "running", "rtMean": 0.9998689452246822, "lag": 0.0, "uptime": 611.710123532}
{"t": 1790739395.7690253, "status": "running", "rtMean": 1.0066090326463777, "lag": 0.0, "uptime": 671.806084883}
{"t": 1790739455.8361878, "status": "running", "rtMean": 0.9991477060779191, "lag": 0.0, "uptime": 731.837495033}
{"t": 1790739515.8999934, "status": "running", "rtMean": 0.9968497132252894, "lag": 0.0, "uptime": 791.918687829}
{"t": 1790739575.9599848, "status": "running", "rtMean": 0.9993416499626159, "lag": 0.0, "uptime": 851.966694729}
{"t": 1790739636.031231, "status": "running", "rtMean": 0.9997509681411471, "lag": 0.0, "uptime": 912.047324838}
{"t": 1790739696.1082256, "status": "running", "rtMean": 0.9993880587210896, "lag": 0.0, "uptime": 972.143571488}
{"t": 1790739756.1715124, "status": "running", "rtMean": 0.9978257533955007, "lag": 0.0, "uptime": 1032.192931507}
{"t": 1790739816.2371426, "status": "running", "rtMean": 1.0003866207887322, "lag": 0.0, "uptime": 1092.269950437}
{"t": 1790739876.297765, "status": "running", "rtMean": 0.9997339122145353, "lag": 0.0, "uptime": 1152.311864977}

View file

@ -1 +0,0 @@
pass

View file

@ -1,60 +0,0 @@
{"t": 1790736255.1832466, "status": "running", "rtMean": 0.44899475378270337, "lag": 40.531, "uptime": 71.111642723}
{"t": 1790736265.3486006, "status": "running", "rtMean": 0.40737226174421837, "lag": 46.58, "uptime": 81.296028671}
{"t": 1790736275.462523, "status": "running", "rtMean": 0.43926524622884744, "lag": 51.607, "uptime": 91.41614284}
{"t": 1790736285.5483737, "status": "running", "rtMean": 0.4992672422167786, "lag": 57.668, "uptime": 101.49334599}
{"t": 1790736295.691844, "status": "running", "rtMean": 0.4722833612045654, "lag": 62.729, "uptime": 111.631919513}
{"t": 1790736305.8359153, "status": "running", "rtMean": 0.49364414852989763, "lag": 67.756, "uptime": 121.766530366}
{"t": 1790736316.0044537, "status": "running", "rtMean": 0.4592358802945983, "lag": 72.814, "uptime": 131.934151579}
{"t": 1790736326.1091528, "status": "running", "rtMean": 0.4414601438247983, "lag": 78.84, "uptime": 142.0534588}
{"t": 1790736336.2525842, "status": "running", "rtMean": 0.4540765983005316, "lag": 83.88, "uptime": 152.198379259}
{"t": 1790736346.4600585, "status": "running", "rtMean": 0.4173426800525677, "lag": 89.957, "uptime": 162.413446602}
{"t": 1790736356.5611305, "status": "running", "rtMean": 0.4606621035712305, "lag": 96.016, "uptime": 172.491203687}
{"t": 1790736366.7702422, "status": "running", "rtMean": 0.46203321509514217, "lag": 101.071, "uptime": 182.696019242}
{"t": 1790736376.9394329, "status": "running", "rtMean": 0.4863329297033063, "lag": 106.126, "uptime": 192.889038592}
{"t": 1790736387.0649624, "status": "running", "rtMean": 0.4495199219435465, "lag": 112.232, "uptime": 203.013465866}
{"t": 1790736397.1682742, "status": "running", "rtMean": 0.42863654848005284, "lag": 118.286, "uptime": 213.12621802}
{"t": 1790736407.2758026, "status": "running", "rtMean": 0.4139101392220675, "lag": 123.367, "uptime": 223.208709667}
{"t": 1790736417.43286, "status": "running", "rtMean": 0.43302060621434524, "lag": 129.445, "uptime": 233.357393123}
{"t": 1790736427.5712192, "status": "running", "rtMean": 0.43801120859089393, "lag": 135.505, "uptime": 243.507406013}
{"t": 1790736437.7151752, "status": "running", "rtMean": 0.4402615997407782, "lag": 140.554, "uptime": 253.661724645}
{"t": 1790736447.85799, "status": "running", "rtMean": 0.48112727487436235, "lag": 146.635, "uptime": 263.813400946}
{"t": 1790736458.0452223, "status": "running", "rtMean": 0.4318712743090674, "lag": 151.707, "uptime": 273.954505321}
{"t": 1790736468.1886797, "status": "running", "rtMean": 0.42247469989908265, "lag": 157.751, "uptime": 284.121781118}
{"t": 1790736478.3070867, "status": "running", "rtMean": 0.414255858741203, "lag": 163.851, "uptime": 294.242313229}
{"t": 1790736488.4334955, "status": "running", "rtMean": 0.42798509497809467, "lag": 169.928, "uptime": 304.374179381}
{"t": 1790736498.598869, "status": "running", "rtMean": 0.6973435620918129, "lag": 171.95, "uptime": 314.520569518}
{"t": 1790736508.6862988, "status": "running", "rtMean": 0.8506385364177339, "lag": 173.964, "uptime": 324.645689838}
{"t": 1790736518.7639382, "status": "running", "rtMean": 0.6393757799420648, "lag": 176.98, "uptime": 334.702167477}
{"t": 1790736528.8444629, "status": "running", "rtMean": 0.7563780548037421, "lag": 179.995, "uptime": 344.767409573}
{"t": 1790736538.9335213, "status": "running", "rtMean": 0.7299449362518324, "lag": 183.099, "uptime": 354.892773648}
{"t": 1790736549.0587013, "status": "running", "rtMean": 0.7495898580324455, "lag": 185.1, "uptime": 365.018206452}
{"t": 1790736559.125795, "status": "running", "rtMean": 0.7466250548943967, "lag": 188.191, "uptime": 375.072270628}
{"t": 1790736569.2290745, "status": "running", "rtMean": 0.7135159366386999, "lag": 191.217, "uptime": 385.16395309}
{"t": 1790736579.3221574, "status": "running", "rtMean": 0.6444057032246826, "lag": 194.311, "uptime": 395.24551542}
{"t": 1790736589.387774, "status": "running", "rtMean": 0.7078500629057103, "lag": 197.356, "uptime": 405.328315223}
{"t": 1790736599.457208, "status": "running", "rtMean": 0.7724222621426244, "lag": 199.41, "uptime": 415.395630334}
{"t": 1790736609.5669358, "status": "running", "rtMean": 0.7238637707089501, "lag": 202.432, "uptime": 425.523861591}
{"t": 1790736619.667222, "status": "running", "rtMean": 0.636988015566429, "lag": 206.491, "uptime": 435.596000401}
{"t": 1790736629.7565455, "status": "running", "rtMean": 0.6846194839249449, "lag": 209.511, "uptime": 445.705233095}
{"t": 1790736639.9320571, "status": "running", "rtMean": 0.5775285955158141, "lag": 213.527, "uptime": 455.875805326}
{"t": 1790736650.1127295, "status": "running", "rtMean": 0.6874672985502784, "lag": 216.574, "uptime": 466.047794887}
{"t": 1790736660.23605, "status": "running", "rtMean": 0.7980788454806589, "lag": 218.599, "uptime": 476.191578571}
{"t": 1790736670.3181207, "status": "running", "rtMean": 0.8373465907575423, "lag": 220.629, "uptime": 486.259561672}
{"t": 1790736680.5240602, "status": "running", "rtMean": 0.5739965775984952, "lag": 224.72, "uptime": 496.479775337}
{"t": 1790736690.6629243, "status": "running", "rtMean": 0.5286072075517942, "lag": 229.778, "uptime": 506.594493598}
{"t": 1790736700.8302114, "status": "running", "rtMean": 0.6743407053708753, "lag": 232.792, "uptime": 516.784837195}
{"t": 1790736710.9810565, "status": "running", "rtMean": 0.4833175202797613, "lag": 237.843, "uptime": 526.927338551}
{"t": 1790736721.1076307, "status": "running", "rtMean": 0.5049205359243616, "lag": 242.912, "uptime": 537.054603691}
{"t": 1790736731.2034523, "status": "running", "rtMean": 0.4861911891792873, "lag": 248.95, "uptime": 547.101045326}
{"t": 1790736741.3109553, "status": "running", "rtMean": 0.4845765517462596, "lag": 254.061, "uptime": 557.246782973}
{"t": 1790736751.4774404, "status": "running", "rtMean": 0.5333230355802153, "lag": 258.103, "uptime": 567.418066384}
{"t": 1790736761.652144, "status": "running", "rtMean": 0.49627891829609305, "lag": 264.173, "uptime": 577.572329582}
{"t": 1790736771.8544915, "status": "running", "rtMean": 0.5215276573927089, "lag": 268.2, "uptime": 587.79709649}
{"t": 1790736781.9649491, "status": "running", "rtMean": 0.5216891717973449, "lag": 273.234, "uptime": 597.898939598}
{"t": 1790736792.0599647, "status": "running", "rtMean": 0.5310205891816586, "lag": 278.266, "uptime": 607.982986102}
{"t": 1790736802.1870968, "status": "running", "rtMean": 0.49618279364312484, "lag": 283.316, "uptime": 618.117053029}
{"t": 1790736812.290842, "status": "running", "rtMean": 0.49072671618430486, "lag": 288.404, "uptime": 628.23818419}
{"t": 1790736822.4333866, "status": "running", "rtMean": 0.5402747673446865, "lag": 292.418, "uptime": 638.367153256}
{"t": 1790736832.613669, "status": "running", "rtMean": 0.8329938906374317, "lag": 294.42, "uptime": 648.537882771}
{"t": 1790736842.6835933, "status": "running", "rtMean": 0.7430173560600793, "lag": 297.448, "uptime": 658.629022047}
{"t": 1790736852.755823, "status": "running", "rtMean": 0.8578215877131159, "lag": 298.448, "uptime": 668.694834509}

View file

@ -1,20 +0,0 @@
{"t": 1790736864.4256852, "status": "running", "rtMean": 0.6099898319965826, "lag": 3.091, "uptime": 11.07909019}
{"t": 1790736924.501681, "status": "running", "rtMean": 0.5411932741082821, "lag": 20.265, "uptime": 71.155545456}
{"t": 1790736984.5807962, "status": "running", "rtMean": 0.7295306018507262, "lag": 35.328, "uptime": 131.199399778}
{"t": 1790737044.6489198, "status": "running", "rtMean": 0.8067884564857175, "lag": 46.47, "uptime": 191.29805351}
{"t": 1790737104.7270966, "status": "running", "rtMean": 0.8192565712279218, "lag": 58.542, "uptime": 251.37716607}
{"t": 1790737164.7932363, "status": "running", "rtMean": 0.8487114702728498, "lag": 69.618, "uptime": 311.44889619}
{"t": 1790737224.91049, "status": "running", "rtMean": 0.42516908835738415, "lag": 101.107, "uptime": 371.522769005}
{"t": 1790737285.0996652, "status": "running", "rtMean": 0.41299332249218484, "lag": 136.493, "uptime": 431.719907398}
{"t": 1790737345.3437996, "status": "running", "rtMean": 0.4410892921905215, "lag": 171.04, "uptime": 491.980527036}
{"t": 1790737405.5281327, "status": "running", "rtMean": 0.4454430216668691, "lag": 204.353, "uptime": 552.14783058}
{"t": 1790737465.838257, "status": "running", "rtMean": 0.5991416565682315, "lag": 227.769, "uptime": 612.473422449}
{"t": 1790737525.9655414, "status": "running", "rtMean": 0.6857160494879407, "lag": 246.844, "uptime": 672.619024119}
{"t": 1790737586.045057, "status": "running", "rtMean": 0.6537634570200577, "lag": 265.963, "uptime": 732.678449214}
{"t": 1790737646.1301575, "status": "running", "rtMean": 0.6473194011694912, "lag": 290.309, "uptime": 792.775859726}
{"t": 1790737706.2470899, "status": "running", "rtMean": 0.474484017045933, "lag": 319.566, "uptime": 852.890865845}
{"t": 1790737766.4071772, "status": "running", "rtMean": 0.5316840402693012, "lag": 349.947, "uptime": 913.037081082}
{"t": 1790737826.488124, "status": "running", "rtMean": 0.7651768950839182, "lag": 371.253, "uptime": 973.141837869}
{"t": 1790737886.652113, "status": "running", "rtMean": 0.4461005912444415, "lag": 403.681, "uptime": 1033.302886448}
{"t": 1790737946.764796, "status": "running", "rtMean": 0.4610048048396617, "lag": 438.093, "uptime": 1093.383696514}
{"t": 1790738006.857649, "status": "running", "rtMean": 0.44882468186134916, "lag": 471.382, "uptime": 1153.477095415}

View file

@ -1 +0,0 @@
pass

View file

@ -1,60 +0,0 @@
{"t": 1790732513.9182734, "status": "running", "rtMean": 0.8924521636213212, "lag": 14.055, "uptime": 71.036299234}
{"t": 1790732524.0150237, "status": "running", "rtMean": 0.8353274823796196, "lag": 16.062, "uptime": 81.13323077}
{"t": 1790732534.1210978, "status": "running", "rtMean": 0.8500748093099013, "lag": 17.063, "uptime": 91.228242756}
{"t": 1790732544.215337, "status": "running", "rtMean": 0.8468167790642429, "lag": 19.065, "uptime": 101.324762382}
{"t": 1790732554.322073, "status": "running", "rtMean": 0.8195776032071418, "lag": 21.069, "uptime": 111.432768959}
{"t": 1790732564.4171112, "status": "running", "rtMean": 0.8132396801449534, "lag": 23.128, "uptime": 121.51184336}
{"t": 1790732574.6153316, "status": "running", "rtMean": 0.7620145427014579, "lag": 25.169, "uptime": 131.725135168}
{"t": 1790732584.921327, "status": "running", "rtMean": 0.8332397110903376, "lag": 27.171, "uptime": 142.033873438}
{"t": 1790732595.01128, "status": "running", "rtMean": 0.870312035539666, "lag": 28.172, "uptime": 152.095917692}
{"t": 1790732605.1342888, "status": "running", "rtMean": 0.8533222405905535, "lag": 29.174, "uptime": 162.233917268}
{"t": 1790732615.2172267, "status": "running", "rtMean": 0.8613640091999233, "lag": 31.183, "uptime": 172.332574842}
{"t": 1790732625.292268, "status": "running", "rtMean": 0.8522988744218247, "lag": 32.186, "uptime": 182.413805105}
{"t": 1790732635.3641157, "status": "running", "rtMean": 0.9357131448898743, "lag": 33.188, "uptime": 192.485818904}
{"t": 1790732645.4261112, "status": "running", "rtMean": 1.0206119648139633, "lag": 33.188, "uptime": 202.528181723}
{"t": 1790732655.4861393, "status": "running", "rtMean": 0.9996233335893017, "lag": 33.188, "uptime": 212.597230658}
{"t": 1790732665.5481722, "status": "running", "rtMean": 0.9988689561123472, "lag": 33.188, "uptime": 222.643138786}
{"t": 1790732675.6082208, "status": "running", "rtMean": 0.9720518244342236, "lag": 33.188, "uptime": 232.688977534}
{"t": 1790732685.6701753, "status": "running", "rtMean": 0.9535516201508779, "lag": 33.188, "uptime": 242.776975854}
{"t": 1790732695.7341325, "status": "running", "rtMean": 1.0629078918872632, "lag": 33.188, "uptime": 252.850174728}
{"t": 1790732705.8101525, "status": "running", "rtMean": 0.9727389888242601, "lag": 33.188, "uptime": 262.903659566}
{"t": 1790732715.8741817, "status": "running", "rtMean": 1.0273735099933976, "lag": 33.188, "uptime": 272.974337275}
{"t": 1790732725.938133, "status": "running", "rtMean": 1.0004052294537187, "lag": 33.188, "uptime": 283.049608446}
{"t": 1790732735.998134, "status": "running", "rtMean": 0.9949238477466771, "lag": 33.188, "uptime": 293.095921712}
{"t": 1790732746.058181, "status": "running", "rtMean": 1.001717860791771, "lag": 33.188, "uptime": 303.168958273}
{"t": 1790732756.1181643, "status": "running", "rtMean": 0.9904886517209306, "lag": 33.188, "uptime": 313.212038344}
{"t": 1790732766.1781104, "status": "running", "rtMean": 1.0019464588045806, "lag": 33.188, "uptime": 323.27335596}
{"t": 1790732776.2361557, "status": "running", "rtMean": 0.9964762908263903, "lag": 33.188, "uptime": 333.345377532}
{"t": 1790732786.2971303, "status": "running", "rtMean": 0.9919143606076284, "lag": 33.188, "uptime": 343.415231522}
{"t": 1790732796.356171, "status": "running", "rtMean": 0.9987406877370043, "lag": 33.188, "uptime": 353.453194803}
{"t": 1790732806.4211473, "status": "running", "rtMean": 0.9606955955830612, "lag": 33.188, "uptime": 363.51066889}
{"t": 1790732816.4811146, "status": "running", "rtMean": 1.0365607476649523, "lag": 33.188, "uptime": 373.577335699}
{"t": 1790732826.5412261, "status": "running", "rtMean": 0.9998410565989371, "lag": 33.188, "uptime": 383.641038325}
{"t": 1790732836.6022642, "status": "running", "rtMean": 1.0000077033831407, "lag": 33.188, "uptime": 393.71493795}
{"t": 1790732846.66412, "status": "running", "rtMean": 1.000194713414025, "lag": 33.188, "uptime": 403.778353067}
{"t": 1790732856.7631304, "status": "running", "rtMean": 0.9963137515722961, "lag": 33.188, "uptime": 413.843209009}
{"t": 1790732866.8251379, "status": "running", "rtMean": 1.0024279700647742, "lag": 33.188, "uptime": 423.939536235}
{"t": 1790732876.8881218, "status": "running", "rtMean": 0.9998292141625301, "lag": 33.188, "uptime": 434.00196051}
{"t": 1790732886.9481704, "status": "running", "rtMean": 1.000376047514638, "lag": 33.188, "uptime": 444.041568588}
{"t": 1790732897.0131807, "status": "running", "rtMean": 0.9650577242433412, "lag": 33.188, "uptime": 454.116318252}
{"t": 1790732907.0751567, "status": "running", "rtMean": 1.0144244685102852, "lag": 33.188, "uptime": 464.167010558}
{"t": 1790732917.135163, "status": "running", "rtMean": 1.0205380747863821, "lag": 33.188, "uptime": 474.251702386}
{"t": 1790732927.2051454, "status": "running", "rtMean": 1.0000612465292147, "lag": 33.188, "uptime": 484.315901269}
{"t": 1790732937.2681184, "status": "running", "rtMean": 0.9994207833538337, "lag": 33.188, "uptime": 494.376673004}
{"t": 1790732947.3331046, "status": "running", "rtMean": 1.000304521129079, "lag": 33.188, "uptime": 504.439961234}
{"t": 1790732957.3971682, "status": "running", "rtMean": 1.0002162260543621, "lag": 33.188, "uptime": 514.506681195}
{"t": 1790732967.4561813, "status": "running", "rtMean": 0.9940778699094166, "lag": 33.188, "uptime": 524.546264956}
{"t": 1790732977.5141263, "status": "running", "rtMean": 0.9996073475880696, "lag": 33.188, "uptime": 534.609522709}
{"t": 1790732987.574194, "status": "running", "rtMean": 1.0002335793712973, "lag": 33.188, "uptime": 544.681525736}
{"t": 1790732997.63819, "status": "running", "rtMean": 0.9719075938039292, "lag": 33.188, "uptime": 554.746296519}
{"t": 1790733007.6981711, "status": "running", "rtMean": 0.9642994644579728, "lag": 33.188, "uptime": 564.819180783}
{"t": 1790733017.758178, "status": "running", "rtMean": 1.018785781616432, "lag": 33.188, "uptime": 574.863920385}
{"t": 1790733027.8201568, "status": "running", "rtMean": 1.0126053016171566, "lag": 33.188, "uptime": 584.931657624}
{"t": 1790733037.8801777, "status": "running", "rtMean": 1.0288813388578921, "lag": 33.188, "uptime": 595.000913192}
{"t": 1790733047.9401584, "status": "running", "rtMean": 0.9993726786826045, "lag": 33.188, "uptime": 605.062362454}
{"t": 1790733058.0032334, "status": "running", "rtMean": 1.0003288362459641, "lag": 33.188, "uptime": 615.100685166}
{"t": 1790733068.0701303, "status": "running", "rtMean": 0.996323054395049, "lag": 33.188, "uptime": 625.182391179}
{"t": 1790733078.1311688, "status": "running", "rtMean": 0.9986121232113987, "lag": 33.188, "uptime": 635.237969741}
{"t": 1790733088.194169, "status": "running", "rtMean": 0.9998456257825143, "lag": 33.188, "uptime": 645.294446623}
{"t": 1790733098.254364, "status": "running", "rtMean": 0.9990527607429407, "lag": 33.188, "uptime": 655.371233565}
{"t": 1790733108.3171723, "status": "running", "rtMean": 0.9801059046785113, "lag": 33.188, "uptime": 665.424268239}

View file

@ -1,20 +0,0 @@
{"t": 1790733119.441622, "status": "running", "rtMean": 0.999626145847037, "lag": 0.0, "uptime": 11.03453719}
{"t": 1790733179.5021126, "status": "running", "rtMean": 0.996429238965645, "lag": 0.0, "uptime": 71.109465871}
{"t": 1790733239.563163, "status": "running", "rtMean": 1.0001344530283525, "lag": 0.0, "uptime": 131.161767319}
{"t": 1790733299.6230712, "status": "running", "rtMean": 1.0051819085367752, "lag": 0.0, "uptime": 191.213566544}
{"t": 1790733359.684059, "status": "running", "rtMean": 0.9994857841966536, "lag": 0.0, "uptime": 251.305985353}
{"t": 1790733419.744106, "status": "running", "rtMean": 0.9309339263307287, "lag": 1.016, "uptime": 311.343539702}
{"t": 1790733479.8072605, "status": "running", "rtMean": 0.9914113663325995, "lag": 1.016, "uptime": 371.420558771}
{"t": 1790733539.874109, "status": "running", "rtMean": 1.0150616406858766, "lag": 1.016, "uptime": 431.469758515}
{"t": 1790733599.934255, "status": "running", "rtMean": 0.9990854925925501, "lag": 1.016, "uptime": 491.554715659}
{"t": 1790733659.998115, "status": "running", "rtMean": 0.9992033155394792, "lag": 1.016, "uptime": 551.614612008}
{"t": 1790733720.0581028, "status": "running", "rtMean": 1.0002394824346315, "lag": 1.016, "uptime": 611.653389874}
{"t": 1790733780.121188, "status": "running", "rtMean": 1.002487894172868, "lag": 1.016, "uptime": 671.727773294}
{"t": 1790733840.1851053, "status": "running", "rtMean": 1.000530724113054, "lag": 1.016, "uptime": 731.80678409}
{"t": 1790733900.2461364, "status": "running", "rtMean": 1.000644782810976, "lag": 1.016, "uptime": 791.842628622}
{"t": 1790733960.3072183, "status": "running", "rtMean": 0.999652205983927, "lag": 1.016, "uptime": 851.922688196}
{"t": 1790734020.3681173, "status": "running", "rtMean": 0.9946548155046125, "lag": 1.016, "uptime": 911.968050417}
{"t": 1790734080.4291067, "status": "running", "rtMean": 1.0009058823044212, "lag": 1.016, "uptime": 972.041325345}
{"t": 1790734140.4912531, "status": "running", "rtMean": 0.9902809817215064, "lag": 1.016, "uptime": 1032.085088126}
{"t": 1790734200.550132, "status": "running", "rtMean": 1.0136589528338944, "lag": 1.016, "uptime": 1092.153292688}
{"t": 1790734260.6101415, "status": "running", "rtMean": 0.997751864835789, "lag": 1.016, "uptime": 1152.230885469}

Some files were not shown because too many files have changed in this diff Show more