Compare commits
13 commits
862e343e1c
...
eecd5744e0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eecd5744e0 | ||
|
|
dc64ffb4ea | ||
|
|
3922b82762 | ||
|
|
26892d8530 | ||
|
|
865d6f6b55 | ||
|
|
c574e7b973 | ||
|
|
15f2e6dbae | ||
|
|
f205d95e5e | ||
|
|
9c9cec49a9 | ||
|
|
63ecc32b2f | ||
|
|
1bd2223431 | ||
|
|
dccc52ae1c | ||
|
|
432991cbc5 |
|
|
@ -47,12 +47,15 @@ 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.
|
||||||
|
|
@ -95,7 +98,8 @@ 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, and the two `fly-*` review crops at 2x. `--only <substring>` shoots
|
the macro strip's five states, `recovery-<phase>-<action>` for the auto-recovery splash, and the
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
@ -194,6 +198,7 @@ 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
|
||||||
|
|
||||||
|
|
@ -264,6 +269,48 @@ 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 PEWTER CITY 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 PEWTER CITY | Shaking it off… / Same place, fresh start |
|
||||||
|
| `done` | Text box, 8 s after the helper's `updatedAt` | Back at PEWTER CITY! | All shaken off! |
|
||||||
|
| `failed` | Text box, 20 s | That didn't work / A human will take a look | same |
|
||||||
|
|
||||||
|
**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
|
||||||
|
|
|
||||||
BIN
apps/stage/mockups/recovery-acting-reset.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
apps/stage/mockups/recovery-acting-restart.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
apps/stage/mockups/recovery-countdown-reset.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
apps/stage/mockups/recovery-countdown-restart.png
Normal file
|
After Width: | Height: | Size: 61 KiB |
BIN
apps/stage/mockups/recovery-done-reset.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
apps/stage/mockups/recovery-done-restart.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
apps/stage/mockups/recovery-failed-reset.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
apps/stage/mockups/recovery-failed-restart.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
|
|
@ -14,7 +14,8 @@
|
||||||
"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": "*",
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,8 @@ 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';
|
||||||
|
|
@ -68,6 +70,7 @@ 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';
|
||||||
|
|
@ -632,6 +635,14 @@ 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,
|
||||||
|
|
@ -687,6 +698,19 @@ export function App() {
|
||||||
ingest.commit(hot.lastSnapshotMs, true);
|
ingest.commit(hot.lastSnapshotMs, true);
|
||||||
return useStage.getState().chat.length;
|
return useStage.getState().chat.length;
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* 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`).
|
||||||
|
|
@ -714,6 +738,7 @@ 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();
|
||||||
|
|
@ -739,6 +764,7 @@ export function App() {
|
||||||
<ChatPanel source={options.chat} />
|
<ChatPanel source={options.chat} />
|
||||||
|
|
||||||
<MomentLayer particleRef={particleCanvas} />
|
<MomentLayer particleRef={particleCanvas} />
|
||||||
|
<RecoverySplash />
|
||||||
<StaleBanner />
|
<StaleBanner />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
@ -764,6 +790,8 @@ 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;
|
||||||
|
/** 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;
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
@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:
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,12 @@ 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'];
|
||||||
|
|
@ -114,6 +120,7 @@ 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'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
88
apps/stage/src/lib/recovery-poll.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
286
apps/stage/src/lib/recovery.ts
Normal file
|
|
@ -0,0 +1,286 @@
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 = notice.toLabel;
|
||||||
|
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: 'A human will take a look',
|
||||||
|
countdown: '',
|
||||||
|
loop: '',
|
||||||
|
stuck: '',
|
||||||
|
busy: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
129
apps/stage/src/panels/RecoverySplash.tsx
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
230
apps/stage/src/theme/recovery.css
Normal file
|
|
@ -0,0 +1,230 @@
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
138
apps/stage/tests/e2e/recovery.spec.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
});
|
||||||
261
apps/stage/tests/unit/recovery.test.ts
Normal file
|
|
@ -0,0 +1,261 @@
|
||||||
|
/**
|
||||||
|
* 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('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, 'A human will take a look');
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
@ -24,6 +24,8 @@
|
||||||
* 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
|
||||||
|
|
@ -142,6 +144,34 @@ 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: 'PEWTER CITY' } : {}),
|
||||||
|
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' });
|
||||||
|
|
@ -264,6 +294,23 @@ 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 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.
|
||||||
|
|
|
||||||
92
apps/stage/tools/recovery-notice.mts
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
});
|
||||||
|
|
@ -16,7 +16,8 @@
|
||||||
*/
|
*/
|
||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import { createReadStream } from 'node:fs';
|
import { createReadStream } from 'node:fs';
|
||||||
import { cp, stat } from 'node:fs/promises';
|
import { cp, readFile, 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';
|
||||||
|
|
@ -87,8 +88,41 @@ 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()],
|
plugins: [react(), tailwindcss(), datasetArtifacts(), recoveryNotice()],
|
||||||
define: {
|
define: {
|
||||||
__STAGE_VERSION__: JSON.stringify(stageVersion(command)),
|
__STAGE_VERSION__: JSON.stringify(stageVersion(command)),
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,9 @@ 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.
|
`fly_loop_suspected` and writes `/run/fly/wd/loop.json`. It never acts. The separate
|
||||||
|
`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
|
||||||
|
|
|
||||||
|
|
@ -878,3 +878,16 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
|
||||||
branch reaches Pewter on frame 23,755, and offers no button on any of the 67 challenge frames
|
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
|
(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.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -272,6 +272,21 @@ 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
|
||||||
|
|
@ -685,10 +700,20 @@ 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-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
|
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone 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
|
||||||
|
|
||||||
|
# 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
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
|
@ -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"
|
ALWAYS_ON_TIMERS="fly-recap.timer fly-retention.timer fly-watchdog.timer fly-loop-recover.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
|
||||||
|
|
|
||||||
301
infra/bin/fly-loop-recover
Executable file
|
|
@ -0,0 +1,301 @@
|
||||||
|
#!/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 or has been
|
||||||
|
quiet for QUIET seconds. 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
|
||||||
|
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):
|
||||||
|
"""(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.
|
||||||
|
"""
|
||||||
|
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 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)
|
||||||
|
level = 0
|
||||||
|
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")
|
||||||
|
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)
|
||||||
|
if action == "restart" and level and now - acted < HOLD:
|
||||||
|
write_json(STATE, state)
|
||||||
|
return "holding: reset budget spent, next restart after the hold"
|
||||||
|
|
||||||
|
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": 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 and spent the reset.
|
||||||
|
state.update(level=level + 1, actedAt=started, lastAction=action, vetoes=0)
|
||||||
|
state.pop("observedAt", None)
|
||||||
|
if action == "reset":
|
||||||
|
state["resets"].append(started)
|
||||||
|
write_json(STATE, state)
|
||||||
|
notice(base, "acting", started)
|
||||||
|
ok = act(action, target)
|
||||||
|
finished = int(clock())
|
||||||
|
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())
|
||||||
172
infra/bin/fly-loop-reset
Executable file
|
|
@ -0,0 +1,172 @@
|
||||||
|
#!/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"
|
||||||
|
|
@ -16,3 +16,7 @@ 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/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
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,14 @@
|
||||||
// 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';
|
||||||
|
|
@ -17,6 +25,27 @@ 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',
|
||||||
|
|
@ -27,6 +56,7 @@ 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);
|
||||||
|
|
@ -47,5 +77,5 @@ const server = createServer(async (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(port, host, () => {
|
server.listen(port, host, () => {
|
||||||
console.log(`flystage-web: serving ${root} on http://${host}:${port}/`);
|
console.log(`flystage-web: serving ${root} on http://${host}:${server.address().port}/`);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
109
infra/docs/loop-recovery.md
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
# Automated loop recovery
|
||||||
|
|
||||||
|
`fly-watchdog` remains report-only. The separate `fly-loop-recover.timer` reads its
|
||||||
|
`/run/fly/wd/loop.json` every five minutes 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.
|
||||||
|
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, or after
|
||||||
|
six hours with no suspected report.
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
@ -1483,6 +1483,13 @@ else
|
||||||
echo " mention is genuinely legitimate, add it to infra/tests/de-pii-allow.txt with a reason." >&2
|
echo " mention is genuinely legitimate, add it to infra/tests/de-pii-allow.txt with a reason." >&2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
echo "--- loop recovery tests ---"
|
||||||
|
if python3 -m unittest discover -s "$REPO_ROOT/infra/tests" -p 'test_loop_recover.py' >/dev/null 2>&1; then
|
||||||
|
pass "loop recovery: ladder, budget, reboot-safe state, model delay and fallback, splash notice"
|
||||||
|
else
|
||||||
|
fail "loop recovery tests failed; run python3 -m unittest discover -s infra/tests -p test_loop_recover.py -v"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "==="
|
echo "==="
|
||||||
if [ "$FAILED" -eq 0 ]; then
|
if [ "$FAILED" -eq 0 ]; then
|
||||||
echo "lint.sh: ALL CHECKS PASSED"
|
echo "lint.sh: ALL CHECKS PASSED"
|
||||||
|
|
|
||||||
356
infra/tests/test_loop_recover.py
Normal file
|
|
@ -0,0 +1,356 @@
|
||||||
|
import importlib.machinery
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
repo = Path(__file__).resolve().parents[2]
|
||||||
|
script = repo / "infra/bin/fly-loop-recover"
|
||||||
|
spec = importlib.util.spec_from_loader("recover", importlib.machinery.SourceFileLoader("recover", str(script)))
|
||||||
|
recover = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(recover)
|
||||||
|
RESTORABLE_RUNGS = recover.restorable_rungs
|
||||||
|
WRAPPER = repo / "infra/bin/fly-loop-reset"
|
||||||
|
|
||||||
|
T0 = 1_790_000_000
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
root = Path(self.temp.name)
|
||||||
|
self.root = root
|
||||||
|
for name, value in (("REPORT", "loop.json"), ("STATE", "var/state.json"),
|
||||||
|
("HISTORY", "var/history.jsonl"), ("NOTICE", "run/notice.json")):
|
||||||
|
patcher = patch.object(recover, name, root / value)
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
milestones = root / "state"
|
||||||
|
milestones.mkdir()
|
||||||
|
for rung in (1, 9, 10, 11, 12):
|
||||||
|
(milestones / f"milestone-{rung}.checkpoint").write_text("x")
|
||||||
|
patcher = patch.object(recover, "MILESTONES", milestones)
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
self.env = patch.dict("os.environ", {}, clear=False)
|
||||||
|
self.env.start()
|
||||||
|
self.addCleanup(self.env.stop)
|
||||||
|
for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"):
|
||||||
|
recover.os.environ.pop(key, None)
|
||||||
|
self.acts = []
|
||||||
|
self.unrestorable = set()
|
||||||
|
restorable = patch.object(recover, "restorable_rungs", side_effect=lambda: {1, 9, 10, 11, 12} - self.unrestorable)
|
||||||
|
restorable.start()
|
||||||
|
self.addCleanup(restorable.stop)
|
||||||
|
self.act = patch.object(recover, "act", side_effect=lambda action, target: self.acts.append((action, target)) or True)
|
||||||
|
self.act.start()
|
||||||
|
self.addCleanup(self.act.stop)
|
||||||
|
self.report(suspected=1, at=T0)
|
||||||
|
|
||||||
|
def report(self, **fields):
|
||||||
|
base = {"suspected": 1, "action": "none", "reason": "unrewarded", "sequence": ["GO WARP"],
|
||||||
|
"milestone": {"rank": 12, "label": "MT. MOON"}, "map": 61}
|
||||||
|
base.update(fields)
|
||||||
|
if "rank" in fields:
|
||||||
|
base["milestone"] = {"rank": base.pop("rank"), "label": "X"}
|
||||||
|
recover.REPORT.write_text(json.dumps(base))
|
||||||
|
|
||||||
|
def tick(self, at, **fields):
|
||||||
|
"""One watchdog probe at `at` and the timer running right after it."""
|
||||||
|
self.report(at=at, **fields)
|
||||||
|
return recover.run(at + 5, sleep=lambda seconds: None)
|
||||||
|
|
||||||
|
def confirm(self, start, **fields):
|
||||||
|
"""Two probes ~5 min apart after `start`; returns the second decision."""
|
||||||
|
self.assertIn("second probe", self.tick(start, **fields))
|
||||||
|
return self.tick(start + 300, **fields)
|
||||||
|
|
||||||
|
def test_ladder_restart_then_current_rung_then_rung_below(self):
|
||||||
|
self.assertIn("flysim restarted", self.confirm(T0))
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
self.assertIn("settling", self.tick(T0 + 600))
|
||||||
|
self.assertIn("reset to rung 12", self.confirm(T0 + 300 + recover.SETTLE + 10))
|
||||||
|
start = T0 + 2 * (300 + recover.SETTLE + 10)
|
||||||
|
self.assertIn("reset to rung 11", self.confirm(start, rank=12))
|
||||||
|
self.assertEqual([a for a in self.acts], [("restart", None), ("reset", 12), ("reset", 11)])
|
||||||
|
|
||||||
|
def test_spent_reset_budget_holds_to_restarts_three_hours_apart(self):
|
||||||
|
at = T0
|
||||||
|
for _ in range(3):
|
||||||
|
self.confirm(at)
|
||||||
|
at += 300 + recover.SETTLE + 10
|
||||||
|
self.assertEqual(len(self.acts), 3)
|
||||||
|
self.assertIn("holding", self.confirm(at))
|
||||||
|
# the trap never cleared while holding, so the first probe after the hold acts
|
||||||
|
self.assertIn("flysim restarted", self.tick(at + recover.HOLD))
|
||||||
|
self.assertEqual(self.acts[-1], ("restart", None))
|
||||||
|
|
||||||
|
def test_deeper_resets_never_go_below_the_rung_under_the_best(self):
|
||||||
|
state = {"level": 5, "bestRank": 12, "resets": [], "actedAt": 0}
|
||||||
|
recover.write_json(recover.STATE, state)
|
||||||
|
self.confirm(T0, rank=11)
|
||||||
|
self.assertEqual(self.acts, [("reset", 11)])
|
||||||
|
|
||||||
|
def test_an_unrestorable_rung_below_the_best_means_a_restart_never_a_lower_rung(self):
|
||||||
|
self.unrestorable = {11}
|
||||||
|
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||||
|
self.confirm(T0)
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_a_fly_already_below_the_rung_under_its_best_is_restarted_not_reset(self):
|
||||||
|
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||||
|
self.confirm(T0, rank=10)
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_no_restorable_archive_means_a_restart(self):
|
||||||
|
self.unrestorable = {1, 9, 10, 11, 12}
|
||||||
|
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||||
|
self.confirm(T0)
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_new_best_rung_starts_the_ladder_over(self):
|
||||||
|
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
|
||||||
|
self.confirm(T0, rank=13)
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_quiet_hours_start_the_ladder_over(self):
|
||||||
|
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0,
|
||||||
|
"lastSuspectedAt": T0 - recover.QUIET - 1})
|
||||||
|
self.confirm(T0)
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_stale_clear_or_acted_reports_never_act(self):
|
||||||
|
self.report(at=T0 - 700)
|
||||||
|
self.assertIn("not a fresh", recover.run(T0))
|
||||||
|
self.report(suspected=0, at=T0)
|
||||||
|
self.assertIn("not a fresh", recover.run(T0 + 1))
|
||||||
|
self.report(at=T0, action="restart")
|
||||||
|
self.assertIn("not a fresh", recover.run(T0 + 2))
|
||||||
|
self.assertEqual(self.acts, [])
|
||||||
|
|
||||||
|
def test_a_clear_probe_breaks_the_streak(self):
|
||||||
|
self.tick(T0)
|
||||||
|
self.tick(T0 + 300, suspected=0)
|
||||||
|
self.assertIn("second probe", self.tick(T0 + 600))
|
||||||
|
self.assertEqual(self.acts, [])
|
||||||
|
|
||||||
|
def test_state_survives_a_reboot_and_ignores_a_missing_or_corrupt_file(self):
|
||||||
|
self.confirm(T0)
|
||||||
|
self.assertTrue(recover.STATE.exists())
|
||||||
|
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
|
||||||
|
recover.STATE.write_text("{nope")
|
||||||
|
self.assertIn("second probe", self.tick(T0 + 5000))
|
||||||
|
|
||||||
|
def test_model_vetoes_delay_a_step_but_never_deny_it(self):
|
||||||
|
with patch.object(recover, "verdict", return_value=(False, "m")):
|
||||||
|
self.tick(T0)
|
||||||
|
for n in range(1, recover.VETO_LIMIT + 1):
|
||||||
|
self.assertIn(f"({n}/{recover.VETO_LIMIT})", self.tick(T0 + 300 * n))
|
||||||
|
self.assertIn("veto limit reached", self.tick(T0 + 300 * (recover.VETO_LIMIT + 1)))
|
||||||
|
self.assertEqual(self.acts, [("restart", None)])
|
||||||
|
|
||||||
|
def test_no_model_answer_falls_back_to_the_watchdog(self):
|
||||||
|
with patch.object(recover, "verdict", return_value=(None, None)):
|
||||||
|
self.assertIn("watchdog alone", self.confirm(T0))
|
||||||
|
|
||||||
|
def test_models_are_tried_in_order_until_one_answers(self):
|
||||||
|
recover.os.environ.update(FLY_LOOP_ROUTER_URL="http://router/v1", FLY_LOOP_MODELS="a, b ,c")
|
||||||
|
replies = iter([OSError("429"), {"choices": [{"message": {"content": "thinking...\n```json\n{\"stuck\": true}\n```"}}]}])
|
||||||
|
asked = []
|
||||||
|
|
||||||
|
class Reply:
|
||||||
|
def __init__(self, body):
|
||||||
|
self.body = body
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return json.dumps(self.body).encode()
|
||||||
|
|
||||||
|
def fake(request, timeout):
|
||||||
|
asked.append(json.loads(request.data)["model"])
|
||||||
|
reply = next(replies)
|
||||||
|
if isinstance(reply, Exception):
|
||||||
|
raise reply
|
||||||
|
return Reply(reply)
|
||||||
|
|
||||||
|
with patch.object(recover, "urlopen", side_effect=fake):
|
||||||
|
self.assertEqual(recover.verdict({"reason": "unrewarded"}), (True, "b"))
|
||||||
|
self.assertEqual(asked, ["a", "b"])
|
||||||
|
|
||||||
|
def test_parse_stuck_tolerates_prose_and_rejects_non_booleans(self):
|
||||||
|
self.assertIs(recover.parse_stuck('{"stuck":false}'), False)
|
||||||
|
self.assertIs(recover.parse_stuck('Answer: {"stuck": true} done'), True)
|
||||||
|
self.assertIsNone(recover.parse_stuck('{"stuck": "yes"}'))
|
||||||
|
self.assertIsNone(recover.parse_stuck(""))
|
||||||
|
self.assertIsNone(recover.parse_stuck(None))
|
||||||
|
|
||||||
|
def test_notice_goes_countdown_acting_done_for_the_splash(self):
|
||||||
|
phases = []
|
||||||
|
real = recover.notice
|
||||||
|
with patch.object(recover, "notice", side_effect=lambda base, phase, now: phases.append(phase) or real(base, phase, now)):
|
||||||
|
self.confirm(T0 + 300 + recover.SETTLE)
|
||||||
|
recover.write_json(recover.STATE, dict(json.loads(recover.STATE.read_text()), actedAt=0))
|
||||||
|
self.confirm(T0 + 2 * (300 + recover.SETTLE))
|
||||||
|
notice = json.loads(recover.NOTICE.read_text())
|
||||||
|
self.assertEqual(phases, ["countdown", "acting", "done"] * 2)
|
||||||
|
self.assertEqual((notice["v"], notice["action"], notice["toRung"], notice["toLabel"], notice["fromRung"]),
|
||||||
|
(1, "reset", 12, "MT. MOON", 12))
|
||||||
|
self.assertEqual(notice["executeAt"] - notice["announcedAt"], recover.COUNTDOWN)
|
||||||
|
|
||||||
|
def test_failed_action_is_reported_and_still_climbs(self):
|
||||||
|
self.act.stop()
|
||||||
|
with patch.object(recover, "act", return_value=False):
|
||||||
|
self.assertIn("FAILED", self.confirm(T0))
|
||||||
|
self.act.start()
|
||||||
|
self.assertEqual(json.loads(recover.NOTICE.read_text())["phase"], "failed")
|
||||||
|
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
|
||||||
|
|
||||||
|
def test_a_step_that_raises_or_times_out_is_a_failed_step_with_state_saved(self):
|
||||||
|
self.act.stop()
|
||||||
|
with patch.object(recover.subprocess, "run", side_effect=recover.subprocess.TimeoutExpired("sudo", 1)):
|
||||||
|
self.assertIn("FAILED", self.confirm(T0))
|
||||||
|
self.act.start()
|
||||||
|
self.assertEqual(json.loads(recover.NOTICE.read_text())["phase"], "failed")
|
||||||
|
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
|
||||||
|
|
||||||
|
def test_state_is_saved_before_the_step_runs(self):
|
||||||
|
seen = []
|
||||||
|
self.act.stop()
|
||||||
|
with patch.object(recover, "act", side_effect=lambda a, t: seen.append(json.loads(recover.STATE.read_text())) or True):
|
||||||
|
self.confirm(T0)
|
||||||
|
self.act.start()
|
||||||
|
self.assertEqual(seen[0]["level"], 1)
|
||||||
|
self.assertNotIn("observedAt", seen[0])
|
||||||
|
|
||||||
|
def test_restorable_rungs_parses_the_list_and_is_empty_on_any_failure(self):
|
||||||
|
ok = recover.subprocess.CompletedProcess([], 0, stdout="11\n12\n", stderr="")
|
||||||
|
with patch.object(recover.subprocess, "run", return_value=ok):
|
||||||
|
self.assertEqual(RESTORABLE_RUNGS(), {11, 12})
|
||||||
|
with patch.object(recover.subprocess, "run", side_effect=OSError("no sudo")):
|
||||||
|
self.assertEqual(RESTORABLE_RUNGS(), set())
|
||||||
|
with patch.object(recover.subprocess, "run", return_value=recover.subprocess.CompletedProcess([], 1, "12", "")):
|
||||||
|
self.assertEqual(RESTORABLE_RUNGS(), set())
|
||||||
|
|
||||||
|
def test_history_records_every_step(self):
|
||||||
|
self.confirm(T0)
|
||||||
|
lines = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
|
||||||
|
self.assertEqual(lines[-1]["event"], "restart")
|
||||||
|
self.assertTrue(lines[-1]["ok"])
|
||||||
|
|
||||||
|
def test_ladder_labels_match_the_rust_table(self):
|
||||||
|
source = (repo / "services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs").read_text()
|
||||||
|
table = re.search(r"RANK_LADDER: \[&str; \d+\] = \[(.*?)\];", source, re.S).group(1)
|
||||||
|
self.assertEqual(recover.LADDER, re.findall(r'"([^"]*)"', table))
|
||||||
|
|
||||||
|
|
||||||
|
BUILD = "lif-1ms-f64-v2/pokered-unique8-v7/abc/fly-kc-mbon-rstdp-v2"
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root")
|
||||||
|
class WrapperTests(unittest.TestCase):
|
||||||
|
"""infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
root = Path(self.temp.name)
|
||||||
|
self.root = root
|
||||||
|
self.calls = root / "calls.log"
|
||||||
|
(root / "state").mkdir()
|
||||||
|
(root / "bin").mkdir()
|
||||||
|
# The watchdog probe is mid-run ("activating") for the first two looks.
|
||||||
|
self.script(root / "bin/systemctl", f'''echo "systemctl $*" >> {self.calls}
|
||||||
|
if [ "$1" = show ]; then
|
||||||
|
n=$(grep -c "^systemctl show" {self.calls})
|
||||||
|
if [ "$n" -le 2 ]; then echo activating; else echo inactive; fi
|
||||||
|
fi''')
|
||||||
|
self.script(root / "flysim", f'[ "$1" = --print-compatibility ] && echo "{BUILD}"')
|
||||||
|
self.script(root / "reset", f'echo "reset $* FLY_BIN=$FLY_BIN" >> {self.calls}')
|
||||||
|
self.env_file = root / "fly.env"
|
||||||
|
self.env_file.write_text('FLY_MACRO_MODE=macros\nGAME_TITLE=Pokemon (Red) $(touch pwned)\n')
|
||||||
|
self.archive(12, BUILD)
|
||||||
|
self.archive(11, BUILD.replace("-v7", "-v6"))
|
||||||
|
self.archive(1, BUILD.replace("-v7", "-v5"))
|
||||||
|
|
||||||
|
def script(self, path, body):
|
||||||
|
path.write_text("#!/bin/sh\n" + body + "\n")
|
||||||
|
path.chmod(0o755)
|
||||||
|
|
||||||
|
def archive(self, rung, compat):
|
||||||
|
(self.root / f"state/milestone-{rung}.checkpoint").write_bytes(
|
||||||
|
b"FLYSIM01" + json.dumps({"generation": 1, "compatibility": compat}).encode() + b"\x00" * 64)
|
||||||
|
|
||||||
|
def run_wrapper(self, *args):
|
||||||
|
env = {"PATH": f"{self.root}/bin:/usr/bin:/bin", "FLY_LOOP_RESET_TEST_STATE_DIR": str(self.root / "state"),
|
||||||
|
"FLY_LOOP_RESET_TEST_ENV_FILE": str(self.env_file), "FLY_LOOP_RESET_TEST_FLYSIM": str(self.root / "flysim"),
|
||||||
|
"FLY_LOOP_RESET_TEST_RESET_BIN": str(self.root / "reset")}
|
||||||
|
env.update(getattr(self, "extra_env", {}))
|
||||||
|
return recover.subprocess.run([str(WRAPPER), *args], env=env, capture_output=True, text=True, timeout=60)
|
||||||
|
|
||||||
|
def log(self):
|
||||||
|
return self.calls.read_text() if self.calls.exists() else ""
|
||||||
|
|
||||||
|
def test_list_names_only_rungs_this_build_restores(self):
|
||||||
|
self.assertEqual(self.run_wrapper("--list").stdout.split(), ["12"])
|
||||||
|
self.env_file.write_text("FLY_ACCEPT_ADAPTERS=pokered-unique8-v6\n")
|
||||||
|
self.assertEqual(self.run_wrapper("--list").stdout.split(), ["11", "12"])
|
||||||
|
self.assertFalse((self.root / "pwned").exists())
|
||||||
|
|
||||||
|
def test_reset_pauses_the_watchdog_and_always_starts_flysim_again(self):
|
||||||
|
done = self.run_wrapper("12")
|
||||||
|
self.assertEqual(done.returncode, 0, done.stderr)
|
||||||
|
self.assertEqual([line.split()[:3] for line in self.log().splitlines() if not line.startswith("systemctl is-active")], [
|
||||||
|
["systemctl", "stop", "fly-watchdog.timer"],
|
||||||
|
["systemctl", "show", "-p"], ["systemctl", "show", "-p"], ["systemctl", "show", "-p"], ["systemctl", "show", "-p"],
|
||||||
|
["systemctl", "stop", "flysim.service"],
|
||||||
|
["reset", "12", f"FLY_BIN={self.root}/flysim"],
|
||||||
|
["systemctl", "start", "flysim.service"], ["systemctl", "start", "fly-watchdog.timer"]])
|
||||||
|
|
||||||
|
def test_a_failed_reset_still_starts_flysim_and_the_watchdog(self):
|
||||||
|
self.script(self.root / "reset", f'echo "reset $*" >> {self.calls}; exit 7')
|
||||||
|
self.assertEqual(self.run_wrapper("12").returncode, 7)
|
||||||
|
self.assertIn("systemctl start flysim.service", self.log())
|
||||||
|
self.assertIn("systemctl start fly-watchdog.timer", self.log())
|
||||||
|
|
||||||
|
def test_an_unrestorable_or_missing_rung_touches_nothing(self):
|
||||||
|
for rung in ("11", "5"):
|
||||||
|
self.assertEqual(self.run_wrapper(rung).returncode, 3)
|
||||||
|
self.assertEqual(self.log(), "")
|
||||||
|
|
||||||
|
def test_no_build_compatibility_means_nothing_is_restorable(self):
|
||||||
|
(self.root / "flysim").unlink()
|
||||||
|
self.assertEqual(self.run_wrapper("--list").stdout, "")
|
||||||
|
self.assertEqual(self.run_wrapper("12").returncode, 3)
|
||||||
|
self.assertEqual(self.log(), "")
|
||||||
|
|
||||||
|
def test_a_root_copy_that_is_not_the_running_build_restores_nothing(self):
|
||||||
|
other = self.root / "live-flysim"
|
||||||
|
self.script(other, "echo other build")
|
||||||
|
self.extra_env = {"FLY_LOOP_RESET_TEST_LIVE_FLYSIM": str(other)}
|
||||||
|
self.assertEqual(self.run_wrapper("--list").stdout, "")
|
||||||
|
self.assertEqual(self.run_wrapper("12").returncode, 3)
|
||||||
|
|
||||||
|
def test_a_watchdog_probe_that_never_finishes_blocks_the_reset(self):
|
||||||
|
self.script(self.root / "bin/systemctl", f'echo "systemctl $*" >> {self.calls}; [ "$1" != show ] || echo activating')
|
||||||
|
self.script(self.root / "bin/sleep", "exit 0")
|
||||||
|
self.assertEqual(self.run_wrapper("12").returncode, 4)
|
||||||
|
self.assertNotIn("systemctl stop flysim.service", self.log())
|
||||||
|
self.assertIn("systemctl start fly-watchdog.timer", self.log())
|
||||||
|
|
||||||
|
def test_bad_arguments_are_refused(self):
|
||||||
|
for args in ((), ("--check", "12"), ("12", "13"), ("../12",), ("123",), ("-1",)):
|
||||||
|
self.assertEqual(self.run_wrapper(*args).returncode, 2, args)
|
||||||
|
self.assertEqual(self.log(), "")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
13
infra/units/fly-loop-recover.service
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
[Unit]
|
||||||
|
Description=Recover confirmed macro loops: flysim restart, then milestone resets
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=fly
|
||||||
|
EnvironmentFile=-/etc/fly/loop-recovery.env
|
||||||
|
# The ladder's state and history outlive a reboot (/run does not).
|
||||||
|
StateDirectory=fly-loop-recover
|
||||||
|
# A step: the rung list (<=2 min), up to 90 s of model calls, a 60 s on-stream countdown,
|
||||||
|
# the reset (<=8 min) and 4 min to verify. systemd must never kill the wrapper mid-reset.
|
||||||
|
TimeoutStartSec=25min
|
||||||
|
ExecStart=/opt/fly/bin/fly-loop-recover
|
||||||
11
infra/units/fly-loop-recover.timer
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
[Unit]
|
||||||
|
Description=Check for repeated macro loops after watchdog probes
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnBootSec=7min
|
||||||
|
OnUnitActiveSec=5min
|
||||||
|
AccuracySec=10s
|
||||||
|
Unit=fly-loop-recover.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||