Merge main (v0.6.7: row 68 damage reward, adapter pokered-unique8-v8) into port/shadow-01

This commit is contained in:
acamilo 2026-09-30 03:16:36 +00:00
commit 5a7747210f
72 changed files with 5097 additions and 291 deletions

View file

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View file

@ -698,6 +698,24 @@ export function App() {
ingest.commit(hot.lastSnapshotMs, true); ingest.commit(hot.lastSnapshotMs, true);
return useStage.getState().chat.length; return useStage.getState().chat.length;
}, },
/**
* Feed reward events into the ticker by hand, `stepMs` of feed time apart, for the ticker
* mockups (a battle's hits, a KO), and settle the dwell gate five seconds after the last.
* The events go through the same `TickerQueue.push` a snapshot's do.
*/
ticker: (events, stepMs = 7000) => {
let at = hot.lastSnapshotMs;
for (const [index, item] of events.entries()) {
at = hot.lastSnapshotMs + index * stepMs;
ingest.queue().push(
{ id: 900_000 + index, wallMs: 0, brainMs: 0, kind: 'reward', label: item.label, value: item.value },
at,
);
}
at += 5000;
ingest.commit(at, true);
return useStage.getState().ticker.map((row) => `${row.label} ${String(row.amount ?? '')}`);
},
/** /**
* Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the * 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 * splash mockups and e2e assertions. The raw object goes through the same validation as a
@ -790,6 +808,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;
/** Push reward events into the ticker by hand; returns the rows shown. */
ticker: (events: readonly { label: string; value: number }[], stepMs?: number) => string[];
/** Show a recovery notice by hand (validated like a polled one); null clears it. */ /** Show a recovery notice by hand (validated like a polled one); null clears it. */
recovery: (notice: unknown, nowS?: number) => RecoveryView | null; recovery: (notice: unknown, nowS?: number) => RecoveryView | null;
fly: () => { fly: () => {

View file

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

View file

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

View file

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

View file

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

View file

@ -93,6 +93,31 @@ const CHAT_WRAP: { by: string; text: string; bot?: boolean }[] = [
}, },
]; ];
/**
* The ticker in a battle (row 68): the fly's hits arrive as `HIT #<species> FOR <n> HP` rewards and
* fold into one "damage dealt" row. Injected by hand through `window.__stage.ticker`, seven feed
* seconds apart, because no fixture holds a battle recorded on adapter v8.
*/
const TICKER_SHOTS: { name: string; events: { label: string; value: number }[] }[] = [
{
name: 'row68-ticker-hits',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
],
},
{
name: 'row68-ticker-ko',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 12 HP KO', value: 0.13 },
],
},
];
const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [ const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [
{ name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' }, { name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' },
{ name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' }, { name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' },
@ -294,6 +319,18 @@ async function main(): Promise<void> {
console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`); console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`);
} }
for (const shot of TICKER_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const rows = await page.evaluate((events) => window.__stage?.ticker(events) ?? [], shot.events);
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${rows.join(' | ')})`);
}
for (const shot of RECOVERY_SHOTS) { for (const shot of RECOVERY_SHOTS) {
if (!wanted(shot.name)) continue; if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' })); await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));

View file

@ -89,8 +89,9 @@ decoder preset to use.
disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already
achieved flags on the first sample so a restore never replays them, and pays only positive achieved flags on the first sample so a restore never replays them, and pays only positive
rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors and items flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors, items
picked up (`docs/rewards-learning.md`). Version `pokered-unique8-v7`; a deploy that names the picked up and the HP the fly's own attacks remove in battle (`docs/rewards-learning.md`).
Version `pokered-unique8-v8`; a deploy that names the
previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them. previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them.
- Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel, - Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel,
Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a

View file

@ -398,6 +398,19 @@ on-screen ticker cannot disagree with what the sim did.
slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed"). slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed").
`STATE_VERSION` stays 4. `STATE_VERSION` stays 4.
**`v7` -> `v8`** (2026-09-29, the damage reward). `pokered-unique8-v8`'s `migrates_from()` is
`["pokered-unique8-v7", "pokered-unique8-v6"]`: the live run is `v7`, and `v6` still composes,
because `v7`'s own step (the item seed on the first sample without `items:seeded`) is still in
this build and the damage state starts empty either way. The deploy that ships it sets
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`; naming `v7` does not admit a `v6` checkpoint, which
needs its own id. One optional field is added, `damageCounts` (the wild keys that have paid
damage), and one optional object inside a battle in flight, `battle.damage` (the per-battle
marks and what the battle has paid). A `v7` state has neither and restores with no wild key paid
and, if the checkpoint was taken mid-battle, every enemy Pokémon marked at the HP it has when
first read, so nothing it lost before the restore is paid. `STATE_VERSION` stays 4. The
compatibility string moves in segment 1 only: `.../pokered-unique8-v7/...` becomes
`.../pokered-unique8-v8/...`, every other segment byte-identical.
- **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away; - **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away;
`infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a `infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a
dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and

View file

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

View file

@ -155,6 +155,21 @@ which neither `gen_symbols.py` nor `resolve_wram.py` resolves, and a hand-writte
thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame
before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM. before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM.
### The damage reward's reads (2026-09-29)
**New 2026-09-29** (`damage`, `docs/rewards-learning.md`, "Damage rewards"). The two WRAM names were
resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit and
are bracketed by addresses `symbols.rs` already carried. The HRAM byte is the second hand-counted
HRAM address in the crate, after row 63's `hJoyLast`, and is held to the same standard: counted
from that pinned anchor and checked against the section's end, then pinned on the cartridge.
| what | symbol | address | notes | verified |
| --- | --- | --- | --- | --- |
| whose side is acting | `hWhoseTurn` | `$FFF3` | "0 on player's turn, 1 on enemy's turn" (`ram/hram.asm`). Counted from `hJoyLast` (`$FFB1`) with each `UNION` at its largest member; the nine bytes after it end at `$FFFE`, the end of HRAM. `ExecutePlayerMove` writes 0 before the fly's move and `MainInBattleLoop` 1 before the enemy's; `HandlePoisonBurnLeechSeed` picks whose HP to cut by it. MEM-01's memory image captures HRAM, so the session runtime reads the same byte. | survey (`tests/rom_damage.rs`, the row 67 state: every enemy HP drop with 0, every own HP drop with 1) |
| the move executing | `wPlayerMoveNum` | `$cfd2` | the first of the six move bytes `ExecutePlayerMove` loads; `STRUGGLE` (`$a5`) for a Pokémon with no PP. Bracketed by `wWalkCounter` and `wEnemyMonSpecies`. | survey (BUBBLE `$91` and TACKLE `$21` read on the frames their hits landed) |
| which enemy slot is out | `wEnemyMonPartyPos` | `$cfe8` | `battle_struct`'s third field (`macros/ram.asm`: Species, HP, PartyPos, aliasing BoxLevel); `$ff` until a trainer's first send-out, then the 0-based party slot. Bracketed by `wEnemyMonHP` and `wEnemyMonStatus`. | trace (`pokemon_red/tests.rs`), survey |
| (stale) the enemy | `wEnemyMonSpecies` ... `wEnemyMonMaxHP` | as above | **not cleared between battles**: `InitBattleVariables` leaves `wEnemyMon` alone, and a trainer battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData`. The first samples of a battle can hold the last battle's Pokémon at the HP it finished on; the damage rule marks a target only once it reads full. | disassembly, trace |
### Battle menu and cursor, own turn against forced switch ### Battle menu and cursor, own turn against forced switch
`HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it `HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it
@ -1024,3 +1039,22 @@ the latch keeps that A until the next list first asks. Measured on the Potion's
list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120 list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120
rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and
HRAM whose values never overlap between lost and answered frames. HRAM whose values never overlap between lost and answered frames.
## 15. The naming screen (2026-09-29, `docs/design/macros.md` 12.32)
Row 69. Two bytes of a `UNION` in `ram/wram.asm` that the reviewed list does not carry, pinned the
way `hJoyLast` is and read back from the code that stores them by
`row69_the_naming_bytes_are_where_the_cartridge_stores_them` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `wNamingScreenNameLength` | `$CEE9` | the letters typed; the operand of `PrintNicknameAndUnderscores`'s `ld [wNamingScreenNameLength], a` before `hlcoord 10, 2` |
| `wNamingScreenSubmitName` | `$CEEA` | non-zero once START or ED is taken; the operand of `.pressedStart`'s `ld [wNamingScreenSubmitName], a` |
**`state::naming_screen`** is the keyboard only when the menu bytes `DisplayNamingScreen` writes
(`wTopMenuItemY` 3, `wMaxMenuItem` 7, `wMenuWatchedKeys` `$ff`) **and** its figure are on screen:
the whole `TextBoxBorder` at (0, 4)-(19, 14) and a run of seven or ten underscores (`$76`, the raised
one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH - 1` or
`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for
`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before
`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first.

View file

@ -1913,6 +1913,172 @@ a door is taken the way the cartridge takes it, and the map graph says what the
decoder, the reward catalog, the adapter version, the roles and the compatibility string are decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched. untouched.
### 12.30 A counter walked away from is not walked back to, a ball is bought with one button, and a closed bag is not the pad (2026-09-29, row 66)
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) to watch the fly shop,
buy Poké Balls and catch. On v0.6.5, 35 minutes in: `GO SHOP` done 33 times, `TALK` 5, `BUY BALL`
never dealt, `THROW BALL` 0, no catch. Three findings, two of them the pad.
**`GO SHOP` and the way out were a ring.** Row 62 (12.26) deals a service walk whenever the
cartridge says the service is needed, whatever the ledgers say. When the fly stands at the counter
and does not use it, that is a ring by construction: `GO SHOP` from the street to the Viridian
clerk, `GO OUT` or `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again,
because the bag still holds no ball. Reproduced with the connectome from a post-parcel checkpoint
of the Viridian mart (`survey-rank8-row66-viridian-mart`, saved by the offers survey): three laps in
eighteen brain seconds. A `GO SHOP` or `GO HEAL` that finishes facing the counter person now
records the building's counter (`TargetKey::Counter`, keyed by the building's map, because the
question is asked from the street, where none of the building's sprite slots means anything). For
the reached window the service walk toward that building is not dealt, from the street or inside.
That is 12.1's ledger doing for the service walk what it does for every other walk: a target
arrived at and faced is not walked to again at once. `TALK` at the counter, `HEAL` in a centre and
`BUY BALL` in a mart are unchanged by it. When the window closes the counter is a service again.
**A ball is one button (the operator's decision).** Even without the ring the fly did not buy.
A purchase took four choices in a row at the counter: `TALK`, a press at the greeting, `CONFIRM`
on BUY, and `BUY BALL` on the list. With the connectome the fly walked to the clerk every time and
never once chose `TALK` there. So `BUY BALL` is now also the mart's `HEAL`. On the overworld pad
inside a mart, one press walks to the clerk, talks, advances the greeting until BUY / SELL / QUIT
is drawn, buys the first row, answers the price box as 12.26's purchase does, and is `done` when
the wallet drops. It is offered only while it can work:
- in a mart whose first stock row is a Poké Ball (`geography::BALL_FIRST_MARTS`: Viridian, Pewter,
Cerulean, `data/items/marts.asm`). The script reads the stock once the counter is open and
refuses if the first row is anything else;
- while `service_needed` holds for the mart: no ball in the bag, 200 in the wallet, no Oak's parcel
(while it is carried the Viridian clerk's text table is the parcel's and he sells nothing). In
Viridian it is also not offered before Oak has the parcel (`EVENT_OAK_GOT_PARCEL`);
- with the clerk not in the blocked window. The talked and reached ledgers do not retire him, as
for the nurse.
The fly still chooses it, as it chooses `HEAL`. The open-counter `BUY BALL` is unchanged.
**After a catch the pad read the bag.** `wListMenuID` is written when a list opens and never
cleared. After a ball was thrown, every frame to the end of the battle read as an open battle bag:
"All right! WEEDLE was caught!", the Pokédex page, the nickname offer and the naming screen. The pad
was `BACK` and `THROW BALL`, a `THROW BALL` that threw nothing. Its A presses said YES to the
nickname and typed it, 6,900 frames from the catch to the battle's end on a stub survey. The bag
is now the bag only while its box, a `TextBoxBorder` at (4, 2)-(19, 12), is on screen: row 50's rule
for the move list. After the catch the pad is `NEXT`. `NEXT` answers the nickname offer with YES
and names the Pokémon with A's. Offering the offer's two answers inside a battle is a pad change
not made here.
ROM tests: `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` and
`row66_buy_ball_from_the_marts_floor_rings_up_a_ball` (`FLY_ROW66_MART_CHECKPOINT`),
`row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 66.
Nothing ranks a button or presses for the fly. The walk back is withheld for a window, a purchase
is one offer, and the bag is read off the screen. The decoder, the reward catalog, the adapter
### 12.31 A battle lost on repeat is the readout's choice when the pad offers the move that wins (2026-09-29, row 67)
Live on v0.6.5, rung 10, an hour and a half in the Pewter Gym (map 54): per 3,000 events `NEXT`
1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17, no battle won. The feed
read `battle` most of the time, but the fly was not in one battle. It was in a ring. It lost
29 battles in a row to the gym's Jr. Trainer (Diglett L11, Sandshrew L11), whited out to Pewter
(`wLastBlackoutMap` `$02`, money 0) and walked straight back in. Reproduced from the live
checkpoint (`FLY_ROW67_CHECKPOINT`).
- **The pad was right.** Squirtle L11 has TACKLE 35/35, TAIL WHIP 30/30 and BUBBLE 30/30, and
the trainer's Pokémon are Ground type. In a trainer battle with a party of one and no Potion,
the menu's pad is `MOVE 1`, `MOVE 2`, `MOVE 3`, which is every move with PP and an effect.
RUN, ITEM, SWITCH and THROW BALL each have nothing behind them there. Every turn advances.
In 932 own-turn frames, no move with PP and an effect was missing from the pad.
- **The choice was the readout's.** Per live battle, TAIL WHIP was 155 of 178 moves and BUBBLE
23. TAIL WHIP has an effect until the stage reaches -6, and 12.23 withholds it from there. Squirtle
faints at about the sixth turn, so the rule arrives as the battle ends (live: `22222233`).
A readout with no favourite wins with the same pad: uniform over it, the trainer is beaten on
all three seeds, and on the committed seed in the third battle. The live readout's favourite,
replayed, loses 17 of 17 battles.
- **PP never runs out.** Each loss spends about six TAIL WHIPs of 30, and the whiteout heals the party and
restores PP. The out-of-PP path is sound anyway: from the no-PP checkpoint, a trainer battle
with a party of one and every move at 0, the pad is `MOVE 1` alone (FIGHT's backstop, 12.8),
and "has no moves left!" and Struggle end the battle in 1,487 frames.
- **Nothing in the macros changes.** Moving the fly off TAIL WHIP would be ranking a move. The
one pad rule measured that would work, withholding a stat-lowering move once the target's
stage has moved, wins the first battle on both seeds (two stages: the second). It is a rule
about which move is good rather than one about what the cartridge refuses, so it waits for
the operator, like the reward options (`infra/docs/macros-traps.md` row 67).
- **What ships is detection.** The watchdog's check 10 gains `unwon-battles`: 24 or more `MOVE
n` decisions and no battle-won reward (`wildwin`, `trainer`, `badge`) in the ten-brain-minute
window, on two probes, with no new ground. Replayed on the live log, it flags from 14:01. The
existing rules first flag at 14:46, because a stray tile reward on a walk back reset
`unrewarded`. The recovery ladder acts on the flag as on any other, and a restart alone
does not change the readout.
Nothing is ranked, weighted or pressed for the fly. The decoder, the reward catalog, the adapter
version, the roles and the compatibility string are untouched.
### 12.32 A ball at low HP is the only attack, and the fly spells its catch's name (2026-09-29, row 69)
(12.31 is row 67.) Two operator decisions of 2026-09-29, after row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag, and every catch named
`AAAAAAAAAA` by `NEXT`'s A presses on the keyboard.
**"Throw on low HP only."** In a wild battle, when `THROW BALL` is on the pad and the wild
Pokémon's HP is low, the ball is the only attack-side button: `MOVE 1` to `MOVE 4` are withheld on
the top-level menu, and so are `SWITCH` and `RUN`, and `BACK` in the bag.
- **Low is the cartridge's number.** `ItemUseBall` (`engine/items/item_effects.asm`) computes
`W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, floored at each step, with a `BallFactor`
of 8 for a Great Ball and 12 for every other. The ball holds on HP when a random byte is at most
`W`, so at `W >= 255` HP stops mattering. For a Poké Ball that is HP at about a third of its
maximum (7 of a Weedle's 20), for a Great Ball about a half. Lower HP buys nothing more; what is
left is the catch rate and the status, which no press changes. So low is where the throw stops
getting better (`palette::ball_holds_on_hp`, `palette::throw_only`), for the ball
`THROW BALL` would throw.
- **What stays beside the ball.** `ITEM`, because it is dealt only for a Pokémon that is out,
under half its HP, with a Potion the cartridge would take: the one non-attack need that keeps
the thrower standing. `SWITCH` is about a healthier fighter; `RUN` forfeits the catch the pad
exists for, with the enemy at its weakest; `BACK` in the bag leads to a menu whose pad is the
same ball. `palette::WITHHELD_FOR_THE_THROW` is the list.
- **It cannot loop.** It applies only while `THROW BALL` itself is dealt, so every precondition
of that button still holds it: a wild battle, a ball, room in the party, a species the party does
not hold. A missed throw is an ordinary turn (`NEXT` between turns, the ball again on the next
own turn while one is left). With no ball left the button is off the pad and so is the rule, and
the moves are back. An enemy that faints ends the battle as always. A catch goes to the nickname
offer, which `NEXT` answers YES as before.
**"Let the fly name it."** The keyboard (`DisplayNamingScreen`) is a screen of its own. It reads
`Unknown` in or out of a battle (the detector checks it before `wIsInBattle`), and its pad is the
fly's **own buttons**: the D-pad moves over the letters, A types one (or ED, which hands the name
back, or the case switch), B deletes, START hands the name back. SELECT is not on the operator's
list and is masked. No macro is dealt while the fly spells.
- **Why raw buttons and not a macro per key.** A macro per key is new types, and a new type
re-deals every macro population (`docs/readout.md`). The fly's raw buttons are already decoded
every frame in macros mode, and the title already passes them through (section 2). The player's
and rival's names at the start of a game are the same screen before the game timer starts, so
they read `Title` and the fly has always typed them with these buttons; the nickname is now
consistent with them. `Observed::raw` carries the scene's mask and the layer presses
`raw_mask & raw` while nothing is bound and nothing runs.
- **The bound.** Once the name is full (`wNamingScreenNameLength` at the capacity the underscores
show, ten or seven; the cartridge moves the cursor onto ED itself then), or sixty brain seconds
after the keyboard opened (`palette::NAMING_BOUND_MS`), the raw buttons are shut and `CONFIRM`
is the only button. On the keyboard `CONFIRM` pulses START until the screen is gone
(`Step::Submit`), `blocked` after 160 frames. `CONFIRM` is not offered earlier: a macro group of
one always has a winner at its next decision, so a lone `CONFIRM` would hand back an empty name
within a second.
- **What the name is.** Whatever the fly typed stays. An empty name is the species' own name,
which is the cartridge (`AskName.declinedNickname`).
- **The reading.** Red has no "keyboard open" byte, so `state::naming_screen` is the construction
`yes_no_prompt` makes: the menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3,
`wMaxMenuItem` 7, every key watched), the keyboard's whole box at (0, 4)-(19, 14), and the
underscores at (10, 3). `wNamingScreenNameLength` (`$CEE9`) and `wNamingScreenSubmitName`
(`$CEEA`) are read from the operands of the cartridge's own instructions, like `hJoyLast`, and
pinned by the ROM tests.
- `game.scene` is `unknown` on the keyboard, `game.palette` is `[]` while the fly spells, and
`game.padEmptyMs` stays 0: the fly's own buttons are a pad.
ROM tests (`tests/rom_catch.rs`): `row69_at_low_hp_a_wild_battles_pad_is_the_ball`
(`FLY_ROW69_CHECKPOINT`), `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`
and `row69_a_fly_that_types_nothing_is_ended_by_the_bound` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 69.
Nothing presses for the fly on the keyboard but the bound's one button, dealt as a button and
chosen by the fly's own macro group. The decoder, the reward catalog, the adapter version, the
roles and the compatibility string are untouched.
## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a
## priority to visit the shop at least once per area; make shop macros item purchases. same ## priority to visit the shop at least once per area; make shop macros item purchases. same
## for the Pokécenter. heal should be a macro.") ## for the Pokécenter. heal should be a macro.")
@ -1993,7 +2159,9 @@ observe is not a precondition, it is a guess.
| Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad | | Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad |
| Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it | | Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it |
| Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged | | Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged |
| Unknown (the Pokédex, the trainer card, OPTION, a naming screen, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them | | Unknown (the Pokédex, the trainer card, OPTION, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them |
| Unknown, the naming screen (**12.32**) | the fly's own D-pad, A, B and START; **CONFIRM** alone once the name is full or after sixty brain seconds | new, row 69: read before the battle test, so a nickname typed in a battle is here too |
| Battle, own turn, main menu, a wild Pokémon at low HP with THROW BALL dealt (**12.32**) | THROW BALL, and ITEM for a hurt thrower | new, row 69: the moves, SWITCH and RUN withheld; the bag's BACK too |
| Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as | | Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as |
| Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands | | Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands |
| Battle, own turn, party list | SWITCH, BACK | unchanged | | Battle, own turn, party list | SWITCH, BACK | unchanged |
@ -2044,7 +2212,7 @@ measured where it cannot.
| a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one | | a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one |
| a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette | | a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette |
| the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt | | the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt |
| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`; a screen neither press leaves (the naming screen, row 14) is a genuine stall and still needs START, which is a contract change | | a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`. The naming screen (row 14), which neither press leaves, is read since **12.32** and its pad is the fly's own buttons, then `CONFIRM` (START) once the name is full or the bound runs |
| an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other | | an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other |
| the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read | | the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read |
| the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens | | the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens |

View file

@ -177,7 +177,7 @@ Node 22, TypeScript, `tsx` for dev, `node --test` for tests. Deps: `@twurple/aut
One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim. One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim.
Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/fly-pokemon-client-{id,secret}`, matching the stream-key posture already documented. Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/<app>-client-{id,secret}`, matching the stream-key posture already documented.
Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope: Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope:

View file

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

View file

@ -178,8 +178,9 @@ achievements.
| Badge | +3 | each newly set badge bit | | Badge | +3 | each newly set badge bit |
That is the prototype's catalog as it shipped, kept here as history. The live one is That is the prototype's catalog as it shipped, kept here as history. The live one is
`docs/rewards-learning.md`: `pokered-unique8-v7` adds `boundary` (v5), `catch` (v6), and `talk` and `docs/rewards-learning.md`: `pokered-unique8-v8` adds `boundary` (v5), `catch` (v6), `talk` and
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23). `item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23), and `damage`
(v8, the operator's decision of 2026-09-29).
Every value is positive; there were no loss or blackout penalties. Values in a frame summed into Every value is positive; there were no loss or blackout penalties. Values in a frame summed into
`R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with `R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with

View file

@ -1,6 +1,6 @@
# Rewards and learning # Rewards and learning
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v7`. The code of record is The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v8`. The code of record is
`services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the `services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the
gates and the rules); this page says what each rule pays for and why it is allowed to. The gates and the rules); this page says what each rule pays for and why it is allowed to. The
prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules
@ -27,6 +27,7 @@ change what the fly can do.
| `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger | | `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger |
| `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger | | `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger |
| `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger | | `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger |
| `damage` | -- | +0.20 per whole Pokémon, in proportion; +0.05 knockout | 80 ms | HP the fly's own attack removed from the enemy (since v8): its share of the target's max HP, below the lowest HP that target has shown this battle; +0.05 when the hit knocks out a trainer's Pokémon; at most 0.50 a battle; a wild battle at 1, 1/2, 1/3 for its first three per `(map, species, level)`, then nothing |
Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")` Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")`
is `None` by test. The values in one frame sum into `R`, and the network reinforces once with is `None` by test. The values in one frame sum into `R`, and the network reinforces once with
@ -34,7 +35,8 @@ is `None` by test. The values in one frame sum into `R`, and the network reinfor
The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`: The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`:
`docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its `docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its
own shares the nearest one. It still reaches the page as an event with its own label. own shares the nearest one. It still reaches the page as an event with its own label. `damage` is
the one Pokémon kind with no counter at all ("Damage rewards" below says why).
Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on
`wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on `wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on
@ -177,6 +179,87 @@ half, 0.10, once, keyed under the building's id as it always was; walking out pa
person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no
building can be farmed. building can be farmed.
## Damage rewards
The operator's decision of 2026-09-29, chosen over a pad rule that would have withheld a stat move
once it had been used: pay the fly for the HP its own attack removes from the Pokémon it is
fighting. It is a catalog change, an operator decision like the catch and engagement rewards, not a
loop-review fix. It answers row 67 (`infra/docs/macros-traps.md`): the live fly lost the Pewter
Gym's Jr. Trainer 29 times running, choosing TAIL WHIP 155 times, BUBBLE 23 and TACKLE 0, and
nothing in the catalog paid for anything that happened inside a battle it did not win. The pad
offered every move; the readout's favourite was the one move that cannot win. The code is
`pokemon_red/damage.rs`.
**What counts as the fly's attack.** A drop in `wEnemyMonHP` on a sample where `hWhoseTurn`
(`$FFF3`) reads 0 and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit
(`engine/battle/core.asm`), `ApplyDamageToEnemyPokemon` subtracts the damage inside
`ExecutePlayerMove`, with `hWhoseTurn` 0, once per hit of a multi-hit move. Everything else that
lowers the enemy's HP lands with it 1: the enemy's poison and burn ticks and a Leech Seed on the
enemy (`HandlePoisonBurnLeechSeed` picks whose HP to cut *by* `hWhoseTurn`), its recoil, its
confusion self-hit, its own Explosion or Self-Destruct, and the HP it pays for a Substitute. A
Leech Seed on the fly heals the enemy, and HP going up never pays. Damage into an enemy Substitute
never touches `wEnemyMonHP`. `STRUGGLE` is the move the cartridge executes for a Pokémon with no
PP; the fly chose FIGHT, not the move, so it pays nothing (winning still pays what winning pays).
`tests/rom_damage.rs` pins the address on the cartridge from the live row 67 state: every drop of
the enemy's HP lands with `hWhoseTurn` 0 and every drop of the fly's own with 1.
**How much.** 0.20 per whole enemy Pokémon's max HP, paid in proportion on the sample the HP
drops -- BUBBLE for 10 of Diglett's 24 is 0.083, TACKLE for 4 of Sandshrew's 33 is 0.024. The hit
that knocks out a trainer's Pokémon adds 0.05 on the same event. At most **0.50 a battle**, which is
the `trainer` rule's own value: a battle's worth of damage is worth what winning it is, and the
Jr. Trainer's two Pokémon reach it exactly (2 x (0.20 + 0.05)). A wild knockout adds nothing here
because the `battle` rule already pays it, on the way out of the battle. Next to the rest of the
catalog: a wild battle's damage (0.20) is twice its knockout (0.10) and equal to a new area (0.20);
a trainer battle's (0.50) is the trainer's flag; a gym's is a sixth of the badge (3.0).
**What cannot be farmed.**
- *Heal.* Each target keeps the lowest HP it has shown this battle, and only HP below that pays. A
Potion, Recover, Rest or a drain lifts the HP; the same HP is not paid twice.
- *Switch.* A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that goes out
and comes back keeps its mark, and two Weedles of one level are two targets.
- *A stale enemy.* `InitBattleVariables` does not clear `wEnemyMon`, and a trainer battle sets
`wIsInBattle` a whole transition before `LoadEnemyMonData` runs, so the first samples of a
battle can hold the last battle's Pokémon at the HP it finished on -- in the row 67 ring, the
same trainer's Diglett in the same slot. A target is marked the first time it reads full HP,
which is how every enemy Pokémon enters a battle in this game, so the stale one neither pays nor
hides the real one's first hit.
- *The battle.* 0.50 at most, whatever the party size.
- *Wild Pokémon.* A wild battle pays at the wild-KO rule's scale, 1, 1/2, 1/3, for its first three
battles per `(map, species, level)` that paid any damage (`damageCounts`), then nothing; attacking
a wild Pokémon and running from it counts. A rollback blocks every key that has paid, the way it
blocks a paid wild KO or catch.
- *Trainers* keep no lifetime ledger. A trainer is fought again only after the fly has lost to it
(or after a rollback), and each of those battles is bounded by the cap. In the row 67 ring that
is the point: every lost battle pays for the hits that landed, and the hits that land are the
moves that win.
**Feed.** `damage` publishes on no counter (`RewardKind::from_adapter` is `None`). Every other
Pokémon kind shares the nearest counter, and the nearest here is `wildwin`, but the stage folds
that row into "N wild wins": false of a trainer battle, and false of a battle the fly goes on to
lose. A hit reaches the page as a reward event with its own label, `HIT #<species> FOR <n> HP`
(`... KO` for a knockout; the species is the cartridge's internal index, as `CAUGHT #<species>` is),
and the event log, `/status` and the checkpoint carry it; it is only left out of
`game.rewardCounts` and the ticker's per-kind copy, the way the platformer's `started` and `clear`
are. No feed kind was added. The stage rolls the hits up itself (`apps/stage/src/lib/ticker.ts`,
`hitCopy` in the game config): a reward with no `rewardKind` and that label folds into one
"damage dealt x<n>" row with the summed value, ` KO` once a hit in it felled a Pokémon, joined by
each hit within 45 s of the last; a later battle starts a new row (`apps/stage/mockups/row68-ticker-*.png`).
**Learning.** A payout reinforces the recent spike history with `m = tanh(R)` over a 5 s
eligibility trace ([plasticity](plasticity.md)). Measured on the cartridge from the row 67 state
(`tests/rom_damage.rs`), the HP drops 176 frames (2.9 s) after the `MOVE n` press when the fly
moves first and about 420 frames (7 s) when the Jr. Trainer's Pokémon does -- its attack and text
come first. So the choice's trace is at a half to a quarter when its hit is paid, and the previous
turn's choice, one turn (about 7.5 s) earlier still, at a tenth to a twentieth. That ratio is the
whole mechanism: nothing tells the readout which move to press. A hit is small (0.02 to 0.10), so what it can move per battle is small too; whether
the brain learns the attacking move inside a few brain hours is a measurement, not a promise, and
the first one is `infra/docs/macros-traps.md`, row 68.
**Migration.** `v7` -> `v8` adds `damageCounts` and, inside a battle in flight, `battle.damage`;
both are optional and a `v7` state restores with no wild key paid and its battle's Pokémon marked
where they stand. See `docs/design/flysim.md`, "Restoring across an adapter version".
## Gates ## Gates
Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other
@ -276,6 +359,15 @@ body picks the macro; the descending neurons press the buttons.**
## Honesty ## Honesty
The catalog now includes damage (v8). It is the first rule that pays for something inside a battle
the fly may still lose, and the closest the catalog has come to grading a *choice*: the moves are
all on the pad, and the one that lands pays. It is still a reward read out of WRAM after the frame,
not a press: nothing in the adapter picks a move, removes one from the pad or tells the readout
which is good, and a move pays only if the cartridge says it took HP off the enemy. The pad rule
the operator declined (withholding a stat move once used) would have been the doctrine change; this
one leaves the pad exactly as the scene deals it. It is also bounded on purpose: at most what winning
pays, per battle, and a wild Pokémon only three times.
The catalog now includes conversations and items (v7). Paying for a conversation is the closest The catalog now includes conversations and items (v7). Paying for a conversation is the closest
the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a
press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is

View file

@ -916,3 +916,40 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and
redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63, redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63,
64, 65 APPROVE-WITH-NOTES. 64, 65 APPROVE-WITH-NOTES.
- 2026-09-29 (v0.6.6, loop review + port foundation): the fly shops, throws and names what it
catches. Row 66: a counter walked away from is not walked back to for the ledger window (the
GO SHOP/GO OUT re-entry ring: 31 to 0), BUY BALL is one walk-talk-buy button like HEAL (the
operator's call; offered in a mart that sells balls, with no ball and 200 in the wallet), and a
closed battle bag is not the pad (post-catch presses typed the nickname). Row 67: the live fly
lost the Pewter Gym's Jr. Trainer 29 times in a row choosing TAIL WHIP (the pad offered every
move); a report-only `unwon-battles` watchdog reason lets the recovery ladder act 45 minutes
sooner, and the no-PP ROM test is fixed (Struggle is the cartridge's answer). Row 69 (the
operator's calls): in a wild battle at the catch formula's low-HP threshold with a ball in the
bag, THROW BALL is the only attack-side button; the naming screen takes the fly's own buttons
("AAAAAAAAAA" before), bounded by CONFIRM after a full name or 60 brain seconds. Port
foundation merged, dormant on the stream: AGENT-01, MEM-01, ENV-01, STATE-02 (the checkpoint
store is now the shared `flysim-store` crate; FLYSIM01 gains an optional `reinforcements`
field, downgrade-safe both ways). A PII guard scans lint, tag-release and pushes. Reviews: all
APPROVE-WITH-NOTES.
- 2026-09-29 (unreleased, the operator's decision, row 68): the fly is paid for the HP its own
attack removes in battle, the catalog's answer to row 67 (the Pewter Gym's Jr. Trainer lost on
repeat with TAIL WHIP six turns in seven). New kind `damage`: 0.20 per whole enemy Pokémon, in
proportion, +0.05 when it knocks out a trainer's Pokémon, at most 0.50 a battle; a wild battle at
1, 1/2, 1/3 per map/species/level. Only a drop on the fly's own turn (`hWhoseTurn` 0) by a move it
chose (not Struggle); a heal is never paid twice; no feed counter (a hit is not a "wild win").
Adapter `pokered-unique8-v8`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 migrates the
run (v6 still migrates when named). Survey, 3 starts x 120 brain minutes from the row 67
checkpoint: v8 beat the trainer in 2 of 3 (one run also won the Boulder Badge), v7 in 0 of 3, but
the move choice did not shift more under v8 than v7 (BUBBLE ~15% -> ~20% in both): no learned
preference is shown inside two hours (`infra/docs/macros-traps.md` row 68).
- 2026-09-30 (v0.6.7, the operator's call, reward catalog): the fly is paid for damage its own
attacks deal. Row 67 found the live fly losing the Pewter Gym's Jr. Trainer on repeat with TAIL
WHIP while BUBBLE was on the pad; the operator chose a reward over a pad rule. HP removed on the
fly's own turn (hWhoseTurn 0, not Struggle; poison/burn/Leech Seed/recoil/enemy moves never pay;
healed HP not re-paid) pays 0.20 per whole enemy mon, +0.05 for knocking out a trainer's mon,
capped at 0.50 per battle (a trainer beaten); wild battles diminish 1, 1/2, 1/3 per
map/species/level. Adapter pokered-unique8-v8, migrating v7 (compat differs in the adapter
segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO").
Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift
within two hours. Review: APPROVE-WITH-NOTES.

View file

@ -322,8 +322,9 @@ if [ -n "$RELEASE_TARBALL" ]; then
# #
# FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps # FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps
# the run. It names adapter version strings whose checkpoints the new build # the run. It names adapter version strings whose checkpoints the new build
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 for the deploy # may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 for the deploy
# that adds the engagement rewards (v7; v5 -> v6 was the catch reward's). # that adds the damage reward (v8; v6 -> v7 was the engagement rewards', v5 -> v6
# the catch reward's).
# It only applies when the adapter segment is the # It only applies when the adapter segment is the
# ONLY difference between the two strings and the new build's adapter says it # ONLY difference between the two strings and the new build's adapter says it
# can read that one; a dataset, kernel, emulator or state-format change is # can read that one; a dataset, kernel, emulator or state-format change is
@ -377,7 +378,7 @@ The difference is usually an adapter/ladder or dataset version bump. Three ways
* deploy a build whose string matches (check out the commit the running release was built from), or * deploy a build whose string matches (check out the commit the running release was built from), or
* if the ADAPTER VERSION is the only segment that differs and the new build documents a * if the ADAPTER VERSION is the only segment that differs and the new build documents a
migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6). The run is kept; flysim applies the same string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7). The run is kept; flysim applies the same
rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or
* accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which * accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which
archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and

View file

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

View file

@ -72,6 +72,7 @@ log_info() {
: "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10) : "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10)
: "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57) : "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57)
: "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58) : "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58)
: "${WD_LOOP_FIGHT_MIN:=24}" # this many MOVE n decisions with no battle won and no new ground, two probes running, is battles lost on repeat (row 67)
: "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}" : "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}"
mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR" mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR"
@ -192,7 +193,7 @@ write_textfile_metrics() {
# convention as fly_watchdog_encoder_degraded), while the flag itself # convention as fly_watchdog_encoder_degraded), while the flag itself
# starts at 0, because a 0/1 flag carrying -1 reads as a loop to every # starts at 0, because a 0/1 flag carrying -1 reads as a loop to every
# alert expression that would ever use it. # alert expression that would ever use it.
echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked) or completing nothing, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this." echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked), completing nothing, earning nothing or winning no battle, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this."
echo "# TYPE fly_loop_suspected gauge" echo "# TYPE fly_loop_suspected gauge"
echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)." echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)."
@ -221,6 +222,12 @@ write_textfile_metrics() {
echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)." echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_rewards gauge" echo "# TYPE fly_loop_rewards gauge"
echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)" echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_fights MOVE n decisions (a move chosen in a battle) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_fights gauge"
echo "fly_loop_fights $(cat "${WD_RUN_DIR}/loop.fights" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_wins Battle-won reward events (rewardKind wildwin, trainer or badge) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_wins gauge"
echo "fly_loop_wins $(cat "${WD_RUN_DIR}/loop.wins" 2>/dev/null || echo -1)"
echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against." echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against."
echo "# TYPE fly_places_delta gauge" echo "# TYPE fly_places_delta gauge"
echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)" echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)"
@ -807,6 +814,22 @@ check_capture_freeze() {
# unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the # unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the
# window, on this probe AND the previous one. # window, on this probe AND the previous one.
# #
# Row 67: the Pewter Gym, one trainer lost ~30 times in a row. The readout
# chose TAIL WHIP six turns in seven, Squirtle fainted every time, the fly
# whited out to Pewter and walked straight back in: MOVE 2 / NEXT / GO
# OBJECTIVE / TALK / NO, seven names, every macro `done`. Two stray tile
# rewards (a new tile of the gym on a whiteout's walk back) reset the
# unrewarded rule for ~45 minutes. What the window never had was a battle WON.
# So the reward lines carry their rewardKind, and one more rule reads them,
# behind the same gate:
# unwon-battles — WD_LOOP_FIGHT_MIN+ `MOVE n` decisions and no reward of
# kind wildwin, trainer or badge in the window, on this
# probe AND the previous one.
# The feed has no HP (docs/feed-protocol.md), so "a battle that makes no
# progress" is read as moves chosen and nothing won. Measured on the live log:
# healthy windows had 13-46 MOVE starts and 1-4 wins (the one 22-move window
# with no win also had new ground); the trap had 30-39 and none.
#
# The tile rule is what separates a loop from a legitimately repeating # The tile rule is what separates a loop from a legitimately repeating
# explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer # explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer
# than the frame cap, not a trap), and the watchdog has no tile counter. The # than the frame cap, not a trap), and the watchdog has no tile counter. The
@ -857,7 +880,7 @@ loop_status_fields() {
loop_macro_stream() { loop_macro_stream() {
[ -f "$FLY_EVENT_LOG" ] || return 0 [ -f "$FLY_EVENT_LOG" ] || return 0
tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \ tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)"' -R 2>/dev/null \ | jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \
|| true || true
} }
@ -865,12 +888,13 @@ loop_macro_stream() {
# #
# total US distinct US topCount US period US repeats US windowFrom US # total US distinct US topCount US period US repeats US windowFrom US
# windowTo US topName US block US tail US decisions US refused US blocked US # windowTo US topName US block US tail US decisions US refused US blocked US
# timeout US done US rewards # timeout US done US rewards US fights US wins
# #
# `total` counts start events inside the window, `decisions` starts plus # `total` counts start events inside the window, `decisions` starts plus
# refusals (the sequence, `distinct` and `topCount` are over decisions), and # refusals (the sequence, `distinct` and `topCount` are over decisions), and
# the next four count each outcome in the window, and `rewards` the reward # the next four count each outcome in the window, and `rewards` the reward
# events in it (row 58). `period`/`repeats` describe # events in it (row 58), `fights` the `MOVE n` decisions and `wins` the
# rewards of kind wildwin/trainer/badge (row 67). `period`/`repeats` describe
# the shortest repeating block at the END of the sequence (0/0 when nothing # the shortest repeating block at the END of the sequence (0/0 when nothing
# repeats), `block` is that block comma-joined, and `tail` is the last 12 # repeats), `block` is that block comma-joined, and `tail` is the last 12
# names for context. The window ends at the newest macro event's own brain # names for context. The window ends at the newest macro event's own brain
@ -879,14 +903,18 @@ loop_analyze() {
awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" ' awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" '
# Reward lines are counted and nothing else: the window still ends at the # Reward lines are counted and nothing else: the window still ends at the
# newest macro event, as it always has. # newest macro event, as it always has.
$3 == "reward" { rms[++nr] = $1 + 0; next } $3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; next }
{ ms[++n] = $1 + 0; lbl[n] = $2 } { ms[++n] = $1 + 0; lbl[n] = $2 }
END { END {
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\n"; exit } if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\n"; exit }
to = ms[n]; from = to - win to = ms[n]; from = to - win
k = 0; distinct = 0; topn = 0; top = "" k = 0; distinct = 0; topn = 0; top = ""
starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0 starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) rewards++ fights = 0; wins = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) {
rewards++
if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++
}
for (i = 1; i <= n; i++) { for (i = 1; i <= n; i++) {
if (ms[i] < from) continue if (ms[i] < from) continue
if (lbl[i] ~ / blocked$/) { blocked++; continue } if (lbl[i] ~ / blocked$/) { blocked++; continue }
@ -897,6 +925,7 @@ loop_analyze() {
else continue else continue
name = lbl[i]; sub(/ (start|refused)$/, "", name) name = lbl[i]; sub(/ (start|refused)$/, "", name)
seq[++k] = name seq[++k] = name
if (name ~ /^MOVE [1-4]$/) fights++
if (!(name in cnt)) { cnt[name] = 0; distinct++ } if (!(name in cnt)) { cnt[name] = 0; distinct++ }
cnt[name]++ cnt[name]++
if (cnt[name] > topn) { topn = cnt[name]; top = name } if (cnt[name] > topn) { topn = cnt[name]; top = name }
@ -919,9 +948,9 @@ loop_analyze() {
tailstr = "" tailstr = ""
start = k - 11; if (start < 1) start = 1 start = k - 11; if (start < 1) start = 1
for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j] for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j]
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\n", \ printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\n", \
starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \ starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \
k, refused, blocked, timeout, done, rewards k, refused, blocked, timeout, done, rewards, fights, wins
}' }'
} }
@ -979,14 +1008,15 @@ check_loop() {
echo "$delta" > "${WD_RUN_DIR}/loop.places_delta" echo "$delta" > "${WD_RUN_DIR}/loop.places_delta"
local analysis total distinct topn period repeats win_from win_to top block tailstr local analysis total distinct topn period repeats win_from win_to top block tailstr
local decisions refused blocked timeouts completed rewards local decisions refused blocked timeouts completed rewards fights wins
analysis="$(loop_macro_stream | loop_analyze)" analysis="$(loop_macro_stream | loop_analyze)"
IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \ IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \
decisions refused blocked timeouts completed rewards <<< "$analysis" decisions refused blocked timeouts completed rewards fights wins <<< "$analysis"
total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}" total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}"
period="${period:-0}"; repeats="${repeats:-0}" period="${period:-0}"; repeats="${repeats:-0}"
decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}" decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}"
timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}" timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}"
fights="${fights:-0}"; wins="${wins:-0}"
echo "$distinct" > "${WD_RUN_DIR}/loop.distinct" echo "$distinct" > "${WD_RUN_DIR}/loop.distinct"
echo "$period" > "${WD_RUN_DIR}/loop.period" echo "$period" > "${WD_RUN_DIR}/loop.period"
echo "$repeats" > "${WD_RUN_DIR}/loop.repeats" echo "$repeats" > "${WD_RUN_DIR}/loop.repeats"
@ -994,6 +1024,8 @@ check_loop() {
echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked" echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked"
echo "$completed" > "${WD_RUN_DIR}/loop.done" echo "$completed" > "${WD_RUN_DIR}/loop.done"
echo "$rewards" > "${WD_RUN_DIR}/loop.rewards" echo "$rewards" > "${WD_RUN_DIR}/loop.rewards"
echo "$fights" > "${WD_RUN_DIR}/loop.fights"
echo "$wins" > "${WD_RUN_DIR}/loop.wins"
local prev_suspected=0 local prev_suspected=0
[ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" [ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
@ -1022,6 +1054,14 @@ check_loop() {
[ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1 [ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1
echo "$busy" > "$busy_file" echo "$busy" > "$busy_file"
# Battles lost on repeat (row 67), judged over two probes like the two
# above: moves chosen, no battle won, no new ground.
local unwon_file="${WD_RUN_DIR}/loop.prev_unwon" prev_unwon=0 unwon=0
[ -f "$unwon_file" ] && prev_unwon="$(cat "$unwon_file" 2>/dev/null || echo 0)"
case "${prev_unwon:-}" in ''|*[!0-9]*) prev_unwon=0 ;; esac
[ "$fights" -ge "$WD_LOOP_FIGHT_MIN" ] && [ "$wins" -eq 0 ] && [ "$grown" -eq 0 ] && unwon=1
echo "$unwon" > "$unwon_file"
local failed=$(( refused + blocked + timeouts )) local failed=$(( refused + blocked + timeouts ))
local suspected=0 reason="" local suspected=0 reason=""
if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then
@ -1051,6 +1091,11 @@ check_loop() {
# completes, none of them earns anything, and the ground stays put. # completes, none of them earns anything, and the ground stays put.
suspected=1 suspected=1
reason="unrewarded" reason="unrewarded"
elif [ "$unwon" -eq 1 ] && [ "$prev_unwon" -eq 1 ]; then
# Row 67: every macro completes and the odd tile reward keeps the
# window from reading unrewarded, but no battle is ever won.
suspected=1
reason="unwon-battles"
fi fi
fi fi
echo "$suspected" > "${WD_RUN_DIR}/loop.suspected" echo "$suspected" > "${WD_RUN_DIR}/loop.suspected"
@ -1083,6 +1128,8 @@ check_loop() {
--argjson timeouts "$timeouts" \ --argjson timeouts "$timeouts" \
--argjson completed "$completed" \ --argjson completed "$completed" \
--argjson rewards "$rewards" \ --argjson rewards "$rewards" \
--argjson fights "$fights" \
--argjson wins "$wins" \
--argjson windowFrom "${win_from:-0}" \ --argjson windowFrom "${win_from:-0}" \
--argjson windowTo "${win_to:-0}" \ --argjson windowTo "${win_to:-0}" \
--argjson windowMs "$WD_LOOP_WINDOW_MS" \ --argjson windowMs "$WD_LOOP_WINDOW_MS" \
@ -1112,6 +1159,8 @@ check_loop() {
decisions: $decisions, decisions: $decisions,
outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused }, outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused },
rewards: $rewards, rewards: $rewards,
fights: $fights,
wins: $wins,
tail: (if $tail == "" then [] else ($tail | split(", ")) end) tail: (if $tail == "" then [] else ($tail | split(", ")) end)
}, },
dominant: { name: (if $dominant == "" then null else $dominant end), dominant: { name: (if $dominant == "" then null else $dominant end),
@ -1137,6 +1186,8 @@ check_loop() {
if [ "$suspected" -eq 1 ]; then if [ "$suspected" -eq 1 ]; then
if [ "$reason" = "unrewarded" ]; then if [ "$reason" = "unrewarded" ]; then
log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "unwon-battles" ]; then
log_err "loop suspected (unwon-battles): ${fights} moves chosen in battle and no battle won in the last ${mins} brain minutes, two probes running — ${decisions} decisions, ${rewards} reward event(s), top [${top}] x${topn}, tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — battles lost on repeat are a readout choice or a pad that offers no winning move. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then
log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "sequence" ]; then elif [ "$reason" = "sequence" ]; then

View file

@ -38,6 +38,19 @@ branch="$(git rev-parse --abbrev-ref HEAD)"
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})" die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})"
fi fi
# A tag is published with its whole history, so the privacy scan runs first and fails
# closed: without the operator's private pattern list ($FLY_PII_PATTERNS) it cannot see
# host names, people's names, the channel or pass entry names, and a tag is not cut blind.
# It checks the tree being tagged and every line added since the previous tag.
log "running tools/pii-scan.sh (private pattern list required)"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --tree HEAD \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in the tree (or its private pattern list is missing) — see above"
prev_tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)"
pii_range="HEAD"
[ -z "$prev_tag" ] || pii_range="${prev_tag}..HEAD"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --range "$pii_range" \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in commits since ${prev_tag:-the root} (a tag publishes them even if a later commit removed them) — see above"
git fetch --tags >/dev/null 2>&1 \ git fetch --tags >/dev/null 2>&1 \
&& log "fetched tags from the remote" \ && log "fetched tags from the remote" \
|| log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state" || log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state"

View file

@ -3370,3 +3370,225 @@ gives these results:
- **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest - **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest
of the window (65e). of the window (65e).
- **branch**: all six leave with no empty pad, and three win the Cascade Badge. - **branch**: all six leave with no empty pad, and three win the Cascade Badge.
## 2026-09-29, row 66: shop, Poké Balls and catching from the rung-8 restart
### What was found
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) on v0.6.5 to watch
shopping and catching. In the first 35 minutes: `GO SHOP` done 33, `TALK` 5, `BUY BALL` never
dealt, `THROW BALL` 0, no catch. The sequences after `GO SHOP` were `GO SHOP`, `GO OUT`, `GO SHOP`,
`GO OUT` (`docs/design/macros.md` 12.30).
### Reproduction
- `survey-rank8-row66-viridian-mart.checkpoint` (`FLY_ROW66_MART_CHECKPOINT`, not committed) was
saved by the offers survey (`FLY_PROBE_SAVE_MART=2a`, `FLY_PROBE_SAVE_AFTER=3000`) from
`survey-rank7-row62` on the frame the fly walked into the Viridian mart after delivering the
parcel: 793 in the wallet, no ball.
- The connectome from it (`trap_hunt`, `FLY_TRAP_LOG_MACROS=1`): `GO SHOP` from the door to the
clerk, `GO OBJECTIVE` out of the door, `GO SHOP` from the street. Three laps in 18 brain seconds.
`TALK` was on the pad at the counter every time and was never chosen.
- A catch on the stub survey (`FLY_PROBE_SCREEN_*` dumps): from "All right! WEEDLE was caught!"
to the end of the battle, 6,900 frames under a pad of `BACK` and `THROW BALL`. `THROW BALL`'s A
said YES to the nickname and typed AAAAAAAAAA.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 66 | row 62's service walk is dealt again whenever the service is needed, with no window, so a fly that walks away from the counter is walked straight back | the Viridian mart after the parcel, no ball, money for one | `a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window`, `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` | **fixed**: a completed `GO SHOP` / `GO HEAL` facing the counter records `TargetKey::Counter` on the building's map. The service walk toward it is withheld for the reached window |
| 66b | a purchase took four choices in a row at the counter (`TALK`, the greeting, `CONFIRM`, `BUY BALL`). The connectome never chose `TALK` there | any mart | `buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought`, `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | **operator decision, built**: `BUY BALL` is also one button from the mart's floor, like `HEAL`. It walks to the clerk, talks, opens BUY, buys the first row and is done when paid. It is offered only in Viridian (after Oak has the parcel), Pewter and Cerulean, with no ball, 200 in the wallet, no parcel, and the clerk not blocked |
| 66c | `wListMenuID` outlives the battle bag, so every frame after a throw read as an open bag | a catch (the Pokédex page, the nickname, the naming screen) and the text after any throw or potion | `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends`, the state unit test | **fixed**: the bag is the bag only while its box (4, 2)-(19, 12) is drawn |
| 66d | after a catch, `NEXT` says YES to the nickname offer and names the Pokémon with A's | every catch | -- | **left, named**: offering the box's two answers in a battle is a pad change for the operator |
| 66e | the connectome did not choose `THROW BALL` in any wild battle with a ball (35 decisions over seven battles, three runs) | Viridian Forest with a ball bought by 66b | -- | **left, the fly's**: dealt as designed (12.9). Whether to make throwing likelier is the operator's |
| 66f | whiteouts halve the wallet: 3,175 to 793 to 396 to 0 on one stub run before Pewter | early fights lost | -- | **left**: the cartridge's rule. It is why the restart rung matters |
| 66g | `rom_catch`'s `BALL` is the button's tag (`MB·BALL`), not its channel, so the lean sets a rate nobody reads | the test's drive | -- | **left, documented**: that drive is the one that catches from `FLY_CATCH_CHECKPOINT`. Both tests now retry from idle offsets, because one ball misses about two throws in three |
### Before and after
ROM tests (rom-env sourced):
| test | v0.6.5 | branch |
| --- | --- | --- |
| `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` (10,000 frames, the drive declines the counter) | 31 street `GO SHOP`s, 31 walks back in. **Fails** | 0 and 0. Passes |
| `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | `BUY BALL` never dealt on the floor, no ball. **Fails** | dealt, started, done. One ball, 793 to 593, at f491. Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | `THROW BALL` dealt on 666 frames after the catch, pad `BACK`/`THROW BALL`. **Fails** | 0, pad `NEXT`, battle over 1,463 frames after the catch. Passes |
With the connectome (`trap_hunt`, one sweep thread). `FLY_TRAP_SEED` seeds only the palette, and
three seeds from one checkpoint were byte-identical. So the runs vary the starting state: three
post-parcel Viridian mart entrances saved from stub seeds 1, 3 and 5, and the Pewter gym
(`survey-rank11-row59`, 1,606 in the wallet). A decision is a macro start whose pad held the
button.
| run | brain min | counter `TALK` dealt / chosen | floor `BUY BALL` dealt / chosen / done | balls bought | `THROW BALL` dealt / chosen |
| --- | ---: | ---: | ---: | ---: | ---: |
| base, Viridian mart (s1 entrance) | 5 | 4 / 0 | -- | 0 | 0 / 0 |
| branch, Viridian mart (s1 entrance) | 5 | 1 / 0 | 2 / 0 / 0 | 0 | 0 / 0 |
| branch, Viridian mart (s3 entrance) | 5 | 3 / 0 | 3 / 1 / 1 | 1 (431 to 231) | 4 / 0 |
| branch, Viridian mart (s5 entrance) | 5 | 3 / 0 | 4 / 1 / 1 | 1 (1,587 to 1,387) | 16 / 0 |
| branch, Pewter gym, then the Pewter mart | 10 | 1 / 0 | 4 / 1 / 1 | 1 (1,606 to 1,406) | 15 / 0 |
`TALK` at a counter: 0 of 12 decisions on either arm. The floor `BUY BALL`: chosen 3 of 13, and
done (paid) all 3 times. The ring: 4 mart entries in 16 brain seconds on base, one visit on the
branch.
## 2026-09-29, row 67: the Pewter Gym trainer, lost on repeat
### What was live
v0.6.5, macros mode, reset to rung 8 at 12:16Z and back at PEWTER CITY by 13:40. The fly
entered the Pewter Gym (map 54) at 13:41, talked to the guide (#3) and to the Jr. Trainer
(#2). For the next hour and a half the pad read `battle` most of the time.
Per 3,000 events: `NEXT` 1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17,
`GO FRONTIER` 13, `TALK` 7. There was no battle-won reward, only two tile rewards on map 54. Check
10 stayed clear.
### Reproduction (the pulled checkpoint, hot generation 230739)
- The checkpoint is on the walk back, not in a battle: Pewter City (18, 13), `wIsInBattle` 0,
`wLastBlackoutMap` `$02`, money 0, no badge, `EVENT_BEAT_PEWTER_GYM_TRAINER_0` clear. The party
is one Squirtle L11, 34/34: TACKLE 35/35, TAIL WHIP 30/30, BUBBLE 30/30.
- The opponent is `wTrainerClass` `$05` (Jr. Trainer♂) #1, `wEnemyPartyCount` 2: Diglett L11 and
Sandshrew L11, both Ground (`wEnemyMonType1` `$04`).
- Driven with the real palette and the live readout's measured favourite (TAIL WHIP 87%, else
BUBBLE), the cycle is the live one. `GO OBJECTIVE` into the gym, then `TALK` and the guide's
YES/NO. Then the trainer's challenge starts the battle. The own-turn pad is `MOVE 1, MOVE 2, MOVE 3`
on every turn, and each turn resolves in about 530 frames. Squirtle falls 34 → 29 → 24 → 19
→ 11 → 6 → 0 while Diglett's DEFENSE falls to -6. Then `wIsInBattle` `$ff`, `wBattleResult` 1,
the whiteout to Pewter (13, 26) with PP back to 30, and the walk back. One battle takes about
4,500 frames.
- Live, per battle (29 battles, from the event log): TAIL WHIP 155, BUBBLE 23, TACKLE 0, and 5 to 8
moves each. Where TAIL WHIP ran out of effect before the faint, 12.23 withheld it and the fly
pressed BUBBLE (`22222233`).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 67 | a readout that favours TAIL WHIP loses every battle against a trainer it could beat; the whiteout heals the party, so PP never runs out and the ring never ends | the Pewter Gym's Jr. Trainer, Squirtle alone | `row67_the_gym_trainer_is_beaten_from_what_the_pad_deals` | **left, the fly's**: the pad offers every move with PP and an effect on every own-turn frame (0 missing in 932) and a uniform choice wins. Options for the operator below |
| 67b | check 10 did not flag: a stray tile reward (a new gym tile on a walk back) every ~20 minutes reset `unrewarded`, and battles are not a sequence of four names | a whiteout ring with a walk in it | `lint.sh` check 10 case 8 | **fixed**: `unwon-battles` (24+ `MOVE n`, no `wildwin`/`trainer`/`badge` reward, two probes, no new ground) |
| 67c | the no-PP ROM test asserted "more than one button" on a trainer battle whose only honest button is `MOVE 1` (12.8's backstop); it was red on main and skipped without `FLY_NOPP_CHECKPOINT` | the no-PP checkpoint | `macros_mode_ends_a_turn_with_no_move_left_on_the_cartridge` | **fixed (test)**: at least one button, and the battle ends (Struggle, 1,487 frames) |
### The options, measured
From the live checkpoint, 60,000 frames per arm (16.7 brain minutes), real palette. The driver
is harness choice, not the fly's:
| arm | trainer battles (L lost, W won) | trainer beaten | Brock beaten |
| --- | --- | --- | --- |
| live favourite (TAIL WHIP 87%), seed 1 | LLLLLLLLL | no | no |
| live favourite, seed 2 | LLLLLLLL | no | no |
| uniform over the pad, seeds 1 / 2 / 3 | LLW / LLLLW / LLLW | f32,940 / f46,293 / f41,030 | seed 1 |
| BUBBLE whenever dealt | W | f12,234 | yes |
| TACKLE whenever dealt | LLLLLW | f59,253 | no |
| live favourite, stat-down move withheld once the target's stage is -1 or lower, seeds 1 / 2 | W / W | f9,165 / f9,304 | yes / yes |
| the same at -2, seeds 1 / 2 | LW / LW | f17,053 / f19,033 | yes / yes |
| the same at -3, seed 1 | LLLLLW | f54,551 | no |
- **Withhold a move with no effect on this target** (12.23's rule): it already applies, and TAIL
WHIP has an effect until -6. The fly faints at about that turn, so the rule changes nothing here.
- **Withhold a stat-lowering move once it has done something**: the -1 arm wins the first battle
on both seeds and then beats Brock. It is a pad rule about which move is good, not about what
the cartridge refuses, so it is a doctrine change for the operator. It would also hide GROWL,
SAND-ATTACK and similar moves after one use in every battle.
- **Reward damage dealt**: this is a reward-catalog change, out of scope for loop review, and it
cannot be measured without the brain. Nothing in the current catalog separates BUBBLE from
TAIL WHIP until a battle is won, and none is.
- **Watchdog detection plus the recovery ladder**: shipped (67b). Replayed probe by probe on the
live log with uniqueLocations proxied from the tile rewards, base check 10 first flags at 14:46
(`unrewarded`). The branch flags `unwon-battles` at 14:01, 14:16, 14:21, 14:36 and 14:41; a
tile reward at 14:06 and 14:26 clears one probe each. The healthy windows before the gym
(13 to 46 `MOVE n`, 1 to 4 wins each) are not flagged. The ladder's restart does not change the
readout, and a reset to PEWTER CITY replays the same gym. Only the reset to the rung below adds
forest battles, and whether that is enough was not measured.
## 2026-09-29, row 69: throw on low HP only, and the fly names its catch
### What was asked
Two operator decisions after row 66 (`docs/design/macros.md` 12.32). Row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag (66e), and every catch named
`AAAAAAAAAA`: `NEXT` answered the nickname offer YES and its A presses typed on the keyboard (66d).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 69 | at low HP the ball sat beside four moves, `SWITCH` and `RUN`, and the fly never chose it (66e) | a wild battle with a ball, the enemy at a third of its HP | `row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack` and four more unit tests, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` (`FLY_ROW69_CHECKPOINT`) | **operator decision, built**: with `THROW BALL` dealt and `ItemUseBall`'s HP factor saturated (`W >= 255`), the moves, `SWITCH`, `RUN` and the bag's `BACK` are withheld; `ITEM` stays for a hurt thrower |
| 69b | the keyboard read as the battle's between-turns frame, so `NEXT` typed the name (66d) | every catch | `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`, `the_naming_screen_is_its_menu_and_its_box_and_its_underscores` | **operator decision, built**: the keyboard reads `Unknown` and its pad is the fly's own D-pad, A, B and START |
| 69c | a keyboard nobody ends is a stall: B never leaves it and A stops typing at ten letters | a fly that does not press ED or START | `row69_a_fly_that_types_nothing_is_ended_by_the_bound`, `row69_confirm_on_the_keyboard_presses_start_until_it_closes` | **fixed**: once the name is full or sixty brain seconds have run, `CONFIRM` alone, which presses START until the keyboard closes (`blocked` after 160 frames) |
| 69d | row 66's `unknown_pads_with_no_box` counted the bound's `CONFIRM` on the keyboard, which is drawn without the text font | the rung-10 Pewter gym drive, which buys a ball and catches | `the_fly_reaches_the_pewter_gym_from_the_rung_ten_checkpoint` | **fixed in the test**: the keyboard is a drawn screen |
| 69e | the catch checkpoint's lead one-shots every forest Pokémon, so no wild HP is ever low there | `FLY_CATCH_CHECKPOINT` | -- | **left, named**: the low-HP ROM test uses a rung-9 Route 2 checkpoint (rung-9 A below: a Bulbasaur at 5/30, one ball) as `FLY_ROW69_CHECKPOINT` |
### Before and after
ROM tests (rom-env sourced, the build box), a69a258 against the branch:
| test | a69a258 | branch |
| --- | --- | --- |
| `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | 664 low-HP frames with the ball dealt, pad `MOVE 1`, `MOVE 2`, `MOVE 3`, `THROW BALL`. **Fails** | 58 frames, pad `THROW BALL` alone, thrown. Passes |
| `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends` | keyboard 511 frames, 11 `NEXT` starts, 0 raw frames, name `AAAAAAAAAA`. **Fails** | keyboard 1,516 frames, no macro, 1,516 frames of the fly's buttons, 7 letters at most, name `RIJ?`, closed by the fly (ED). Passes |
| `row69_a_fly_that_types_nothing_is_ended_by_the_bound` | `NEXT` types ten A's and ED. **Fails** | nothing typed; `CONFIRM` dealt once at the bound, span 3,587 frames, name empty (the species' own). Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | passes | passes (battle over 2,468 frames after the catch) |
With the connectome (`trap_hunt`, one sweep thread, 15 brain minutes, macro log). The runs vary the
starting state, as row 66's did: four rung-9 checkpoints with one ball each.
| checkpoint (lead, balls) | arm | wild battles with a ball | `THROW BALL` dealt frames / chosen | the throw's pad (frames) | catches | keyboard | rung, tiles, windows flagged |
| --- | --- | ---: | ---: | ---: | ---: | --- | --- |
| rung-9 A, Route 2 (Bulbasaur 5/30, 1) | a69a258 | 5 | 414 / 0 | -- | 0 | -- | 10, 520, 40 |
| | branch | 2 | 96 / 1, at low HP from the pad `THROW BALL` alone | 32 | 1 | 16.8 brain s, A 32, B 30, longest 1, name empty (the species'), ended by the fly (ED) | 10, 482, 51 |
| rung-9 B, Route 2 (Wartortle 9/70, 1) | a69a258 | 1 | 32 / 1, at full HP on the first frame | 0 | 1 | `NEXT` | 9, 300, 46 |
| | branch | 1 | 32 / 1, the same throw | 0 | 1 | 28.1 brain s, A 55, B 52, longest 1, name empty, ended by the fly (ED) | 9, 236, 43 |
| rung-9 C, the forest (`FLY_CATCH_CHECKPOINT`, Wartortle 18/70, 1) | both, identical | 1 | 32 / 1, at full HP, missed | 0 | 0 | -- | 9, 278, 18 |
| rung-9 D, the forest (the no-PP state, Bulbasaur 6/34, 1) | both, identical | 2 | 282 / 0 | 0 (never low with the ball dealt) | 0 | -- | 9, 285, 21 |
- **Throws and catches.** Three balls thrown in four runs on the branch, two catches; on a69a258
two thrown and one catch. The one run where they differ is the one whose wild HP passed a third
with the ball dealt: the fly threw from the throw's pad at once and caught. Two of the throws
were the fly's own choice from the ordinary pad on a battle's first frame, on both arms.
- **Names.** Both keyboards were ended by the fly's own A on ED, in 17 and 28 brain seconds, well
inside the bound. The brain's A and B fire at nearly the same rate there, so each letter it typed
it deleted again and both names came out empty, which the cartridge turns into the species'
name. That is the fly's spelling, kept as it is.
- **Stalls.** None from this row. Every run ends its battles; no keyboard reached the bound. The
flagged windows are `NEXT` runs through battle text on both arms (and on the branch's rung-9 A run
five `GO ROUTE, GO HEAL` windows, row 62's tug, 65h). The branch's rung-9 B run covers fewer tiles
after the keyboard because its frames after the catch differ from a69a258's (the keyboard took
28 brain seconds instead of `NEXT`'s few), not because anything waited: 635 macros started, 633
done, one refusal and one timeout, against 803, 802, one and one.
## 2026-09-29, row 68: the damage reward, the catalog's answer to row 67
Row 67 (the Pewter Gym's Jr. Trainer lost on repeat, TAIL WHIP 155 / BUBBLE 23 / TACKLE 0) is a
readout choice, not a pad fault. The operator chose a catalog change over a pad rule: `damage`,
adapter `pokered-unique8-v8` (`docs/rewards-learning.md`, "Damage rewards"). It pays for the HP the
fly's own attack removes; it does not touch the pad.
### The survey
The real brain, macros mode, from the row 67 checkpoint, 120 brain minutes per arm, `v7` (main)
against `v8` (the rule), on the stream's own frame (`LegacyFrame`). The palette seed turned out not
to diversify a run (seeds 1, 2 and 3 were identical per arm), so the three pairs are three starts:
the checkpoint as it is, and the checkpoint with the game run 7 and 19 frames ahead of the brain.
Each pair is identical until the first damage payout.
| start | arm | trainer battles | won | BUBBLE share, first 40 / last 40 min | damage paid | rung |
| --- | --- | ---: | ---: | --- | ---: | --- |
| +0 | v7 | 68 | 0 | 14% / 17% | -- | 10 |
| +0 | v8 | 58 | 3 (Jr. Trainer at 101 min, Brock at 107, a Route 3 trainer at 112) | 15% / 20% | 6.01 | **11, BOULDER BADGE** |
| +7 | v7 | 65 | 0 | 16% / 21% | -- | 10 |
| +7 | v8 | 67 | 0 | 14% / 14% | 3.41 | 10 |
| +19 | v7 | 60 | 0 | 15% / 24% | -- | 10 |
| +19 | v8 | 59 | 1 (Jr. Trainer at 119.6 min) | 16% / 22% | 6.74 | 10 |
TACKLE stayed at 0 to 2 choices a run in every arm.
**What it shows.** The rule fires where it should: every `v8` arm was paid for BUBBLE's hits and
nothing for TAIL WHIP's, 3.4 to 6.7 over two hours, capped per battle. `v8` beat the trainer in 2
of 3 starts and `v7` in 0 of 3 (and the live run 0 of 29). **What it does not show** is the
mechanism the rule is for: the move choice did not move more under `v8` than under `v7`. BUBBLE
drifted from about 15% to about 20% in both arms, and TAIL WHIP stayed near 80% everywhere. So
inside two brain hours the wins are not explained by a learned preference; a paid hit also changes
the brain's activity (the PAM stimulation) and the trajectory, and three starts cannot tell a small
real effect from luck. Learning is too slow to show in this window, or not happening, and the
survey cannot say which.
**Status: shipped as the operator decided, not a fix.** The trap is still possible under it: one of
three `v8` starts never won. Row 67's watchdog check 10 (`unwon-battles`, on its branch) is the
detector, and the pad rule the operator declined is the lever that still exists.

View file

@ -282,7 +282,7 @@ pct exec $CTID -- /opt/fly/bin/fly-reset-to-milestone $N
# (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5. # (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5.
# (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's # (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's
# adapter so the gate and flysim both migrate instead of refusing: # adapter so the gate and flysim both migrate instead of refusing:
FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 infra/05-deploy.sh <release-env> <release-tarball> FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 infra/05-deploy.sh <release-env> <release-tarball>
# The gate logs "the adapter version is the only difference, and it is named; the run is KEPT # The gate logs "the adapter version is the only difference, and it is named; the run is KEPT
# and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the # and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the
# same rule at restore. Anything else about the string differing is still a refusal. # same rule at restore. Anything else about the string differing is still a refusal.
@ -695,13 +695,17 @@ pct exec <ctid> -- cat /run/fly/wd/loop.json | jq .
| `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window | | `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window |
| `fly_loop_done` | macros that ended `done` in the window | | `fly_loop_done` | macros that ended `done` in the window |
| `fly_loop_rewards` | reward events in the window | | `fly_loop_rewards` | reward events in the window |
| `fly_loop_fights` | `MOVE n` decisions (a move chosen in a battle) in the window |
| `fly_loop_wins` | battle-won reward events (`wildwin`, `trainer`, `badge`) in the window |
The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+ The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+
times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused, times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused,
blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row
(`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row (`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row
(`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other (`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other
names, every macro `done`) — **and** no growth in the exploration count. A decision is a `start` or a names, every macro `done`), or 24+ `MOVE n` decisions and no battle won on two probes in a row
(`unwon-battles`, row 67: one Pewter Gym trainer lost thirty times, whiteout and back, with a
stray tile reward now and then keeping `unrewarded` quiet) — **and** no growth in the exploration count. A decision is a `start` or a
`refused`: a refused press starts nothing, which is why counting starts alone read row 57's `refused`: a refused press starts nothing, which is why counting starts alone read row 57's
pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and
one name. A one name. A

View file

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

4
infra/env/README.md vendored
View file

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

15
infra/env/example.env vendored
View file

@ -216,6 +216,11 @@ TWITCH_CHANNEL=<twitch-channel>
# never is. 06-secrets.sh reads it on the operator box and installs it as a # never is. 06-secrets.sh reads it on the operator box and installs it as a
# systemd credential. # systemd credential.
PASS_KEY=twitch/<channel>-key PASS_KEY=twitch/<channel>-key
# The `pass` entries holding the Twitch app client id and secret (names only).
# 06-secrets.sh installs them together as the twitch-app credential; unset means
# it skips twitch-app with a warning.
BRIDGE_ID_KEY=twitch/<app>-client-id
BRIDGE_SECRET_KEY=twitch/<app>-client-secret
# --- flybridge (services/bridge/src/config.ts) ------------------------------ # --- flybridge (services/bridge/src/config.ts) ------------------------------
# 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads # 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads
@ -335,9 +340,13 @@ FLY_FEED_VIA=direct
# two strings AND the new build's adapter declares a migration from that one. A # two strings AND the new build's adapter declares a migration from that one. A
# dataset, kernel, plasticity, emulator or state-format difference is still a # dataset, kernel, plasticity, emulator or state-format difference is still a
# refusal. Set it for the one deploy that needs it and leave it out afterwards; # refusal. Set it for the one deploy that needs it and leave it out afterwards;
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The v0.6.0 # 05-deploy writes it into /etc/fly/fly.env only while it is set. The deploy
# deploy (pokered-unique8-v7, the engagement rewards) is the one that needs: # of pokered-unique8-v8 (the damage reward) over the live v7 run needs:
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 # FLY_ACCEPT_ADAPTERS=pokered-unique8-v7
# and, to keep the milestone archives written before v0.6.0 restorable as
# fallbacks and fly-reset-to-milestone targets, also names v6 (v8 reads both):
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7,pokered-unique8-v6
# (v0.6.0's, pokered-unique8-v7 over v6, needed pokered-unique8-v6.)
# --- push mode -------------------------------------------------------------- # --- push mode --------------------------------------------------------------
# local: flypush.service stays disabled, everything else identical to prod. # local: flypush.service stays disabled, everything else identical to prod.

View file

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

View file

@ -31,6 +31,9 @@ mapfile -t SHELL_SCRIPTS < <(
# nothing else ever exercises it before it runs as root, at boot, # nothing else ever exercises it before it runs as root, at boot,
# against /etc/pve. # against /etc/pve.
find "$INFRA_DIR/host" -name '*.sh' -type f find "$INFRA_DIR/host" -name '*.sh' -type f
# the privacy guard lives in tools/ because the pre-push hook and
# tag-release run it too.
find "$INFRA_DIR/../tools" -maxdepth 1 -name '*.sh' -type f
} | sort -u } | sort -u
) )
@ -1325,10 +1328,52 @@ LPCAT
fail "check 10: a rewarded busy window gave suspected=$(lp_metric fly_loop_suspected) rewards=$(lp_metric fly_loop_rewards)" fail "check 10: a rewarded busy window gave suspected=$(lp_metric fly_loop_suspected) rewards=$(lp_metric fly_loop_rewards)"
fi fi
# (8) Row 67: the Pewter Gym, one trainer lost on repeat. MOVE 2 six turns in
# seven, a whiteout, the walk back and the guide's YES/NO -- six names,
# every macro done, and one stray tile reward in the window, so neither the
# sequence, dominance nor unrewarded rule fires. No battle is won: two probes
# flag as unwon-battles; the same window with one wild win in it does not.
lp_reset
lp_cycle 25 "GO OBJECTIVE" "TALK" "NO" "NEXT" "NEXT" "NEXT" "MOVE 2" "NEXT" \
"MOVE 2" "NEXT" "MOVE 3" "NEXT" | lp_outcomes "$lp_fixture/events.jsonl" "done"
printf '{"id":999997,"wallMs":1758000999997,"brainMs":100000,"kind":"reward","label":"AREA 54: 24 UNIQUE LOCATIONS","value":0.05,"rewardKind":"explore"}\n' \
>> "$lp_fixture/events.jsonl"
lp_status "$lp_fixture/status.json" 2311
lp_pass
lp_pass
lp_first="$(lp_metric fly_loop_suspected)"
lp_pass
if [ "$lp_first" = "0" ] && [ "$(lp_metric fly_loop_suspected)" = "1" ] \
&& [ "$(lp_metric fly_loop_rewards)" = "1" ] \
&& [ "$(lp_metric fly_loop_fights)" = "75" ] \
&& [ "$(lp_metric fly_loop_wins)" = "0" ] \
&& grep -q 'loop suspected (unwon-battles): 75 moves chosen in battle and no battle won' "$lp_fixture/journal.log"; then
pass "check 10: battles lost on repeat, a stray tile reward in the window, no win over two probes flag as unwon-battles"
else
fail "check 10: the row-67 log gave first=${lp_first} then suspected=$(lp_metric fly_loop_suspected) rewards=$(lp_metric fly_loop_rewards) fights=$(lp_metric fly_loop_fights) wins=$(lp_metric fly_loop_wins), journal: $(cat "$lp_fixture/journal.log")"
fi
if lp_report="$(jq -e -r '[.reason, (.window.fights|tostring), (.window.wins|tostring), .action] | join(" ")' "$lp_fixture/run/loop.json" 2>/dev/null)" \
&& [ "$lp_report" = "unwon-battles 75 0 none" ]; then
pass "check 10: loop.json carries the moves chosen and the battles won in the window"
else
fail "check 10: loop.json read back as '${lp_report:-UNREADABLE}' — expected 'unwon-battles 75 0 none'"
fi
lp_reset
printf '{"id":999998,"wallMs":1758000999998,"brainMs":150000,"kind":"reward","label":"BEAT PEWTER GYM TRAINER 1","value":0.5,"rewardKind":"trainer"}\n' \
>> "$lp_fixture/events.jsonl"
lp_pass
lp_pass
lp_pass
if [ "$(lp_metric fly_loop_suspected)" = "0" ] && [ "$(lp_metric fly_loop_wins)" = "1" ]; then
pass "check 10: the same battles with one of them won do not flag"
else
fail "check 10: a won battle gave suspected=$(lp_metric fly_loop_suspected) wins=$(lp_metric fly_loop_wins)"
fi
# The ethos, asserted rather than reviewed: over every case above, check 10 # The ethos, asserted rather than reviewed: over every case above, check 10
# restarted nothing. It reports; a human or a review agent decides. # restarted nothing. It reports; a human or a review agent decides.
if [ ! -s "$lp_fixture/systemctl.log" ]; then if [ ! -s "$lp_fixture/systemctl.log" ]; then
pass "check 10: never acts — no unit was restarted across any of the eight cases" pass "check 10: never acts — no unit was restarted across any of the cases"
else else
fail "check 10 ACTED, which it must never do: $(cat "$lp_fixture/systemctl.log")" fail "check 10 ACTED, which it must never do: $(cat "$lp_fixture/systemctl.log")"
fi fi
@ -1471,16 +1516,13 @@ fi
# forge URLs. The rules, and the keep/move/redact verdict behind every file # forge URLs. The rules, and the keep/move/redact verdict behind every file
# that was touched, live in the operator's infra repo. # that was touched, live in the operator's infra repo.
# #
# Two things about the patterns below are deliberate: # The scan is tools/pii-scan.sh. It carries only GENERIC shapes (addresses,
# # container ids, host paths, e-mail, credential shapes); the proper nouns are
# * Each proper noun is spelled with ONE bracketed character — `sp[i]cy`, # loaded at run time from the operator's private pattern list
# `chonk[e]rs`, `Al[e]x`. The regex still matches the real string exactly, # ($FLY_PII_PATTERNS), so the guard is not itself a list of what it refuses.
# but the literal token does not appear in this file, so the guard does not # Here a missing private list is a NOTE (public CI has none, by design);
# itself become the last copy of what it refuses. Do not "tidy" the # infra/build/tag-release.sh and the pre-push hook (tools/install-hooks.sh)
# brackets away. # fail closed instead.
# * `operator-name` is the only case-SENSITIVE pattern. Capitalised `Al[e]x` in
# prose is the operator; lowercase quoted `"al[e]x"` is a chat-username
# fixture all through the tests, which the sprint explicitly leaves alone.
# #
# Legitimate mentions are listed in infra/tests/de-pii-allow.txt, one # Legitimate mentions are listed in infra/tests/de-pii-allow.txt, one
# `path pattern-name # reason` per line. Add to it only with a reason; the # `path pattern-name # reason` per line. Add to it only with a reason; the
@ -1491,81 +1533,29 @@ echo "--- de-PII guard ---"
REPO_ROOT="$(cd "$INFRA_DIR/.." && pwd)" REPO_ROOT="$(cd "$INFRA_DIR/.." && pwd)"
DEPII_ALLOW="$INFRA_DIR/tests/de-pii-allow.txt" DEPII_ALLOW="$INFRA_DIR/tests/de-pii-allow.txt"
DEPII_NAMES=(); DEPII_FLAGS=(); DEPII_RES=() DEPII_OUT="$("$REPO_ROOT/tools/pii-scan.sh" --allow "$DEPII_ALLOW" --tree 2>&1)" && DEPII_RC=0 || DEPII_RC=$?
depii() { DEPII_NAMES+=("$1"); DEPII_FLAGS+=("$2"); DEPII_RES+=("$3"); }
# name grep flags regex (one bracketed char per proper noun)
depii host-proxmox '-i' 'sp[i]cy'
depii host-backup '-i' 'chonk[e]rs'
depii host-llm '-i' '\bsl[o]th\b'
depii operator-name '' '\bAl[e]x\b|al[e]x_camilo|al[e]x\.camilo|al[e]x-(copy|ui)-taste'
depii lan-address '-i' '192\.168\.[0-9]{1,3}\.[0-9]{1,3}|\b2600:[0-9a-f]'
depii container-id '-i' '\b(ct|vm)[ _-]?[12][0-9][0-9]\b|\bpct +[a-z-]+ +[0-9]{2,4}\b|subvol-[12][0-9][0-9]-disk|/lxc/[12][0-9][0-9]\.conf'
depii host-root-path '' '/ro[o]t/'
depii home-path '' '/ho[m]e/[a-z]'
depii twitch-account '-i' '15412[6]9693|aflyplayspok[e]mon'
depii claim-log-name '' 'AGENTS[_]LOG'
depii forge-name '-i' 'forg[e]jo|git[e]a'
depii infra-repo-name '-i' 'trik[i]lli'
depii mac-address '' '\b([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b'
depii email-address '' '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,}'
depii pass-entry-path '' '\bpass +(show|insert) +[A-Za-z0-9._-]+/'
# depii_allowed PATH PATTERN_NAME — true when de-pii-allow.txt excuses this
# pair. A path entry may end in `/` (directory prefix) or `*` (glob).
depii_allowed() {
local path="$1" name="$2" a_path a_name rest
[ -f "$DEPII_ALLOW" ] || return 1
while read -r a_path a_name rest; do
case "$a_path" in ''|'#'*) continue ;; esac
[ "$a_name" = "$name" ] || [ "$a_name" = '*' ] || continue
case "$a_path" in
*/) case "$path" in "$a_path"*) return 0 ;; esac ;;
*\**) # shellcheck disable=SC2254
case "$path" in $a_path) return 0 ;; esac ;;
*) [ "$path" = "$a_path" ] && return 0 ;;
esac
done < "$DEPII_ALLOW"
return 1
}
# The tree, minus what the sprint deliberately excludes: the connectome data
# (neuron ids and column CSVs, no house strings), the npm lockfile, and
# .local/ (untracked anyway). Prefer `git grep` — it honours .gitignore and is
# an order of magnitude faster — and fall back to grep -r for a checkout that
# is not a git repo (a release tarball unpacked on the host).
depii_scan() {
local flags="$1" re="$2"
if git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1; then
# shellcheck disable=SC2086
git -C "$REPO_ROOT" grep -nI $flags -E -e "$re" -- \
. ':!data' ':!package-lock.json' 2>/dev/null || true
else
# shellcheck disable=SC2086
grep -rnI $flags -E -e "$re" "$REPO_ROOT" \
--exclude-dir=data --exclude-dir=.git --exclude-dir=node_modules \
--exclude-dir=.local --exclude-dir=target --exclude=package-lock.json \
2>/dev/null | sed "s|^${REPO_ROOT}/||" || true
fi
}
DEPII_HITS=0 DEPII_HITS=0
for i in "${!DEPII_NAMES[@]}"; do while IFS= read -r line; do
name="${DEPII_NAMES[$i]}" case "$line" in
while IFS= read -r line; do "pii-scan: NOTE:"*) echo "$line" ;;
[ -n "$line" ] || continue "pii-scan: clean"*|"pii-scan: "*" finding(s) "*|"") ;;
hit_path="${line%%:*}" "pii-scan: "*) fail "de-PII: ${line#pii-scan: }"; DEPII_HITS=$((DEPII_HITS + 1)) ;;
depii_allowed "$hit_path" "$name" && continue esac
fail "de-PII: ${name}: ${line}" done <<<"$DEPII_OUT"
DEPII_HITS=$((DEPII_HITS + 1))
done < <(depii_scan "${DEPII_FLAGS[$i]}" "${DEPII_RES[$i]}")
done
if [ "$DEPII_HITS" -eq 0 ]; then if [ "$DEPII_RC" -eq 0 ] && [ "$DEPII_HITS" -eq 0 ]; then
pass "de-PII guard: no identifying strings outside tests/de-pii-allow.txt (${#DEPII_NAMES[@]} patterns)" pass "de-PII guard: $(printf '%s\n' "$DEPII_OUT" | grep -o 'clean.*' | tail -1)"
else elif [ "$DEPII_HITS" -gt 0 ]; then
echo " ^ redact these (rules in the operator's infra repo), or, if the" >&2 echo " ^ redact these (rules in the operator's infra repo), or, if the" >&2
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
else
fail "de-PII guard: tools/pii-scan.sh exited ${DEPII_RC}: ${DEPII_OUT}"
fi
if "$INFRA_DIR/tests/pii-scan-test.sh" >/dev/null 2>&1; then
pass "pii-scan tests: tree, range, commit message, value needles, allowlist, fail-closed, pre-push hook"
else
fail "pii-scan tests failed; run infra/tests/pii-scan-test.sh"
fi fi
echo "--- loop recovery tests ---" echo "--- loop recovery tests ---"

180
infra/tests/pii-scan-test.sh Executable file
View file

@ -0,0 +1,180 @@
#!/usr/bin/env bash
# infra/tests/pii-scan-test.sh — tests for tools/pii-scan.sh and tools/install-hooks.sh.
#
# Everything runs in throwaway repos under a temp dir, against a throwaway private pattern
# list. The fake identifying values are assembled at run time from pieces, so no complete
# fake value (and no real one) appears in this file for the tree scan to trip over.
set -euo pipefail
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
T="$(mktemp -d)"
trap 'rm -rf "$T"' EXIT
FAILS=0
ok() { echo "ok - $*"; }
bad() { echo "FAIL - $*"; FAILS=$((FAILS + 1)); }
# expect RC DESC -- CMD...: run CMD, capture output in $OUT, check the exit code
# the tree scan covers TRACKED files (git grep), like the guard it replaced
track() { git -C "$W" add -A; }
expect() {
local want="$1" desc="$2"; shift 3
local rc=0
OUT="$("$@" 2>&1)" || rc=$?
if [ "$rc" -eq "$want" ]; then ok "$desc"; else bad "$desc (exit $rc, wanted $want)"; printf '%s\n' "$OUT" | sed 's/^/ /'; fi
}
contains() { case "$OUT" in *"$1"*) ok "$2" ;; *) bad "$2 (missing '$1')"; printf '%s\n' "$OUT" | sed 's/^/ /' ;; esac; }
not_contains() { case "$OUT" in *"$1"*) bad "$2 (output leaks '$1')" ;; *) ok "$2" ;; esac; }
# --- fake private values, built from pieces -------------------------------------------
HOST="zorb""lequin" # a "host name"
PERSON="Quen""tavius" # a "person"
SECRET="fk""Q7pL2xV9""mZ4rT8wY""1nB6" # a "router key"
LAN="192.168"".77.21"
MAIL="someone""@""example.org"
mkdir -p "$T/private"
printf 'FAKE_ROUTER_KEY=%s\nSHORT=abc\n' "$SECRET" > "$T/private/router.env"
cat > "$T/private/patterns.txt" <<EOF
# test list
house-host -i ${HOST}
operator-name - \\b${PERSON}\\b
@values $T/private/router.env
EOF
export FLY_PII_PATTERNS="$T/private/patterns.txt"
# --- a throwaway repo with the scanner in it ------------------------------------------
W="$T/work"
git init -q -b main "$W"
git -C "$W" config user.name lint
git -C "$W" config user.email lint@example.invalid
mkdir -p "$W/tools" "$W/infra/tests" "$W/src"
cp "$REPO/tools/pii-scan.sh" "$REPO/tools/install-hooks.sh" "$W/tools/"
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
echo "hello" > "$W/src/a.txt"
git -C "$W" add -A && git -C "$W" commit -qm "init"
SCAN="$W/tools/pii-scan.sh"
expect 0 "clean tree passes" -- "$SCAN" --tree
contains "private list loaded" "private list is reported loaded"
expect 0 "--list prints names" -- "$SCAN" --list
contains "house-host" "--list includes private names"
not_contains "$HOST" "--list never prints a private regex"
# generic pattern
echo "feed at ws://${LAN}:7400" > "$W/src/b.txt"
track
expect 1 "LAN address in the tree fails" -- "$SCAN" --tree
contains "lan-address: src/b.txt:1:" "finding names the pattern and the location"
not_contains "$LAN" "the address itself is not echoed"
git -C "$W" rm -qf src/b.txt
# private noun, case-insensitive
echo "ssh root@$(echo "$HOST" | tr a-z A-Z).example" > "$W/src/c.txt"
track
expect 1 "private host name fails" -- "$SCAN" --tree
contains "house-host: src/c.txt:1:" "private name reported by its pattern name"
not_contains "$HOST" "private host name is not echoed"
git -C "$W" rm -qf src/c.txt
# case-sensitive private pattern: lowercase fixture passes, capitalised fails
echo "user: $(echo "$PERSON" | tr A-Z a-z)" > "$W/src/d.txt"
track
expect 0 "case-sensitive pattern ignores the lowercase fixture" -- "$SCAN" --tree
echo "by ${PERSON}" > "$W/src/d.txt"
track
expect 1 "case-sensitive pattern catches the capitalised name" -- "$SCAN" --tree
git -C "$W" rm -qf src/d.txt
# literal secret value from @values
echo "KEY=${SECRET}" > "$W/src/e.env"
track
expect 1 "a literal secret value fails" -- "$SCAN" --tree
contains "secret-value:FAKE_ROUTER_KEY: src/e.env:1:" "value finding names the env KEY"
not_contains "${SECRET:0:6}" "secret value is fully redacted"
git -C "$W" rm -qf src/e.env
# credential shape
echo "export STREAM_KEY=\"live_123456""7_abcdefghijABCDEFGHIJ123\"" > "$W/src/f.sh"
track
expect 1 "stream-key shape fails" -- "$SCAN" --tree
contains "secret-twitch" "stream key reported as secret-twitch"
git -C "$W" rm -qf src/f.sh
# allowlist
echo "contact ${MAIL}" > "$W/src/g.txt"
track
expect 1 "e-mail address fails" -- "$SCAN" --tree
printf 'src/g.txt email-address # upstream licence contact\n' >> "$W/infra/tests/de-pii-allow.txt"
expect 0 "allowlisted path/name pair passes" -- "$SCAN" --tree
printf 'src/ house-host # a different name does not excuse\n' >> "$W/infra/tests/de-pii-allow.txt"
echo "${LAN}" > "$W/src/g2.txt"
track
expect 1 "an allow entry excuses only its own pattern name" -- "$SCAN" --tree
git -C "$W" rm -qf src/g.txt src/g2.txt
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
# fail closed / open
expect 2 "--require-private without the list exits 2" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --require-private --tree
contains "private pattern list not found" "missing list is named"
expect 0 "without --require-private a missing list is a NOTE" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --tree
contains "NOTE: no private pattern list" "NOTE printed"
printf 'broken-line\n' > "$T/private/broken.txt"
expect 2 "a malformed private list is an error, not a silent pass" -- env FLY_PII_PATTERNS="$T/private/broken.txt" "$SCAN" --tree
# range: added then removed is still published history
base="$(git -C "$W" rev-parse HEAD)"
echo "on ${HOST} today" > "$W/src/h.txt"; git -C "$W" add -A; git -C "$W" commit -qm "add h"
git -C "$W" rm -q src/h.txt; git -C "$W" commit -qm "remove h"
expect 0 "tree is clean after the removal" -- "$SCAN" --tree
expect 1 "range still finds the line a commit added" -- "$SCAN" --range "${base}..HEAD"
contains "house-host:" "range finding names the pattern"
contains "src/h.txt:1" "range finding names path and line"
git -C "$W" commit -q --allow-empty -m "deploy to ${HOST}"
expect 1 "range scans commit messages" -- "$SCAN" --range "HEAD~1..HEAD"
contains "<commit-message>:1" "message finding is marked"
git -C "$W" reset -q --hard "$base"
git -C "$W" status --porcelain | grep -q . && bad "work repo not clean before the hook tests" || true
# --- pre-push hook ---------------------------------------------------------------------
git init -q --bare "$T/pub.git"
git init -q --bare "$T/priv.git"
git -C "$W" remote add github "$T/pub.git"
git -C "$W" remote add origin "$T/priv.git"
expect 0 "install-hooks installs" -- "$W/tools/install-hooks.sh"
[ -x "$W/.git/hooks/pre-push" ] && ok "hook is executable" || bad "hook missing"
expect 0 "install-hooks is idempotent" -- "$W/tools/install-hooks.sh"
expect 0 "clean push to github is accepted" -- git -C "$W" push -q github main
echo "at ${LAN}" > "$W/src/i.txt"; git -C "$W" add -A; git -C "$W" commit -qm "i"
expect 1 "push with PII to github is refused" -- git -C "$W" push -q github main
contains "refusing to publish" "hook explains the refusal"
expect 0 "push to a private remote is not scanned" -- git -C "$W" push -q origin main
git -C "$W" rm -q src/i.txt; git -C "$W" commit -qm "rm i"
expect 1 "removing it in a later commit does not unblock the push" -- git -C "$W" push -q github main
git -C "$W" reset -q --hard github/main
git -C "$W" tag -a v9.9.9 -m "release for ${HOST}"
expect 1 "annotated tag message is scanned" -- git -C "$W" push -q github v9.9.9
contains "<tag-message>" "tag finding is marked"
git -C "$W" tag -d v9.9.9 >/dev/null
git -C "$W" tag -a v9.9.8 -m "release"
expect 0 "clean annotated tag is accepted" -- git -C "$W" push -q github v9.9.8
git -C "$W" commit -q --allow-empty -m "clean"
expect 1 "push is refused when the private list is missing" -- env FLY_PII_PATTERNS="$T/nope" git -C "$W" push -q github main
git -C "$W" checkout -q -b old "$base"
rm -f "$W/tools/pii-scan.sh"
echo "x ${HOST}" > "$W/src/j.txt"; git -C "$W" add -A; git -C "$W" commit -qm "j"
expect 1 "a branch without tools/pii-scan.sh is scanned by the hook's own copy" -- git -C "$W" push -q github old
printf 'exit 0\n' > "$T/other-hook"
git -C "$W" checkout -q main
cp "$T/other-hook" "$W/.git/hooks/pre-push"
expect 1 "install-hooks refuses to clobber a foreign hook" -- "$W/tools/install-hooks.sh"
# --- review-pii-guard N2/N3 (2026-09-29) ----------------------------------------------
printf 'broken - (unclosed\n' > "$T/private/bad-patterns.txt"
expect 2 "an invalid private regex refuses to scan (never 'clean')" -- env FLY_PII_PATTERNS="$T/private/bad-patterns.txt" "$SCAN" --tree
printf '++ %s\n' "$LAN" > "$W/src/plusplus.txt"
git -C "$W" add -A && git -C "$W" commit -qm "a line that starts with ++"
expect 1 "an added line starting '++ ' is still scanned" -- "$SCAN" --range HEAD~1..HEAD
git -C "$W" rm -qf src/plusplus.txt && git -C "$W" commit -qm "drop it"
echo "==="
if [ "$FAILS" -eq 0 ]; then echo "pii-scan-test: ALL PASSED"; else echo "pii-scan-test: ${FAILS} FAILED"; exit 1; fi

View file

@ -244,7 +244,7 @@ The unit itself lives in `infra/`, not here (W4 in `docs/stream-mvp-plan.md`). W
provide: provide:
- `LoadCredentialEncrypted=twitch-client-id:...` and `...twitch-client-secret:...`, sourced from - `LoadCredentialEncrypted=twitch-client-id:...` and `...twitch-client-secret:...`, sourced from
`pass` (`twitch/fly-pokemon-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files `pass` (`twitch/<app>-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files
`src/config.ts` reads. `src/config.ts` reads.
- A writable, persistent directory for `TOKENS_FILE`, `REDEMPTION_STATE_FILE` and - A writable, persistent directory for `TOKENS_FILE`, `REDEMPTION_STATE_FILE` and
`NOTICE_STATE_FILE` (default `/var/lib/flybridge/`), owned by the service user. `NOTICE_STATE_FILE` (default `/var/lib/flybridge/`), owned by the service user.

View file

@ -52,7 +52,7 @@ pub fn example_composition() -> LegacyComposition {
byte_length: 1_048_576, byte_length: 1_048_576,
format: "gb-rom".to_owned(), format: "gb-rom".to_owned(),
}, },
adapter: "pokered-unique8-v7".to_owned(), adapter: "pokered-unique8-v8".to_owned(),
symbol_provenance: pokered.to_owned(), symbol_provenance: pokered.to_owned(),
mode: "macros".to_owned(), mode: "macros".to_owned(),
macro_channels: decoder_vector("macros")["macroChannels"] macro_channels: decoder_vector("macros")["macroChannels"]
@ -71,7 +71,7 @@ pub fn example_composition() -> LegacyComposition {
audio_sample_rate: 48_000, audio_sample_rate: 48_000,
}, },
flysim_compatibility: format!( flysim_compatibility: format!(
"{}/pokered-unique8-v7/{}/{}/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:{pokered}/statefmt:199616-x86_64-unknown-linux-gnu", "{}/pokered-unique8-v8/{}/{}/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:{pokered}/statefmt:199616-x86_64-unknown-linux-gnu",
gameboy::KERNEL_VERSION, gameboy::KERNEL_VERSION,
gameboy::FAFB_V783_FINGERPRINT, gameboy::FAFB_V783_FINGERPRINT,
gameboy::PLASTICITY_VERSION, gameboy::PLASTICITY_VERSION,

View file

@ -492,7 +492,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -560,9 +560,9 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"digest": "44916db0a0846d3338f50d4f24d9d4e0214fa239af7d15e4174213cd93b07e28", "digest": "d37ccb40162ecb42172609623d53791804571fee1b66a1f4ab8183a9a68852ea",
"recipeLines": [ "recipeLines": [
"fly-session/composition-v1", "fly-session/composition-v1",
"session=<sessionId>", "session=<sessionId>",

View file

@ -5202,7 +5202,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5243,7 +5243,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "the profile AssetRef digest is the legacy profile's" "reason": "the profile AssetRef digest is the legacy profile's"
}, },
@ -5267,7 +5267,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "raw", "mode": "raw",
"macroChannels": [ "macroChannels": [
@ -5308,7 +5308,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "raw mode deals no macro channels" "reason": "raw mode deals no macro channels"
}, },
@ -5332,7 +5332,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [] "macroChannels": []
@ -5368,7 +5368,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "macros mode needs its channels" "reason": "macros mode needs its channels"
}, },
@ -5392,7 +5392,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5433,7 +5433,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "the executor extension is pokered-macros-v1" "reason": "the executor extension is pokered-macros-v1"
}, },
@ -5457,7 +5457,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5498,7 +5498,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "exact", "restore": "exact",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "the legacy composition declares legacy-transient-reset" "reason": "the legacy composition declares legacy-transient-reset"
}, },
@ -5522,7 +5522,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5563,7 +5563,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "the rollback policy needs gameboy-slots-v1" "reason": "the rollback policy needs gameboy-slots-v1"
}, },
@ -5587,7 +5587,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5628,7 +5628,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "one Game Boy frame is 8572265625/512 ns, not 1/60 s" "reason": "one Game Boy frame is 8572265625/512 ns, not 1/60 s"
}, },
@ -5652,7 +5652,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5693,7 +5693,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v6/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "the FLYSIM01 string and the declaration describe the same fly" "reason": "the FLYSIM01 string and the declaration describe the same fly"
}, },
@ -5717,7 +5717,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -5758,7 +5758,7 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSESS1", "checkpointFormatOfRecord": "FLYSESS1",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"reason": "FLYSIM01 stays until RETIRE-01" "reason": "FLYSIM01 stays until RETIRE-01"
}, },

View file

@ -3337,7 +3337,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "macros", "mode": "macros",
"macroChannels": [ "macroChannels": [
@ -3405,11 +3405,11 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"note": "placeholder ROM digest; real macros-mode decoder digest and channels", "note": "placeholder ROM digest; real macros-mode decoder digest and channels",
"canonical": "{\"checkpointFormatOfRecord\":\"FLYSIM01\",\"compositionId\":\"pokered-live\",\"decoderConfigDigest\":\"82b6601f0390b742a67eca44ef935b49e16a73315db70f5644f1cbd21f7c8a52\",\"environment\":{\"audio\":{\"channels\":2,\"sampleRate\":48000},\"controllerSchema\":{\"digest\":\"1bde5fa114b99824ad608fba4ea85706cb0cebc6123a778dc1e5f89791d2a05e\",\"id\":\"gameboy-joypad-v1\",\"version\":1},\"extensions\":[\"gameboy-slots-v1\"],\"inspectionSchema\":{\"digest\":\"d6cb62248bfdac2ffdf00290ffbebf9a101b1fe28f7be766d24db28ede8da3e6\",\"id\":\"gameboy-memory-inspection-v1\",\"version\":1},\"setupFrames\":1,\"slots\":[\"best\"],\"stepDuration\":{\"denominator\":\"512\",\"numerator\":\"8572265625\"}},\"episodePolicy\":\"legacy-ratchet-rollback-v1\",\"executor\":{\"adapter\":\"pokered-unique8-v7\",\"id\":\"pokered-macros-v1\",\"macroChannels\":[\"macro_go_objective\",\"macro_go_out\",\"macro_go_warp\",\"macro_go_route\",\"macro_go_item\",\"macro_go_npc\",\"macro_go_frontier\",\"macro_go_shop\",\"macro_go_heal\",\"macro_talk\",\"macro_menu\",\"macro_next\",\"macro_yes\",\"macro_no\",\"macro_close\",\"macro_confirm\",\"macro_back\",\"macro_move_1\",\"macro_move_2\",\"macro_move_3\",\"macro_move_4\",\"macro_switch\",\"macro_item\",\"macro_throw_ball\",\"macro_run\",\"macro_buy_potion\",\"macro_buy_ball\",\"macro_buy_antidote\",\"macro_buy_repel\",\"macro_heal\",\"macro_leave\"],\"mode\":\"macros\",\"rom\":{\"byteLength\":\"1048576\",\"digest\":\"c840ea493f9bf41505f26cf5b1db26815dd588e7ec91d5fd6f1ad4d363dc4f20\",\"format\":\"gb-rom\",\"id\":\"pokered-rom\"},\"symbolProvenance\":\"0cd19d3b877b7dc66d12c7050bed9a7f38154d4b\"},\"flysimCompatibility\":\"lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu\",\"profile\":{\"byteLength\":\"1137\",\"digest\":\"41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878\",\"format\":\"fly-profile-v1\",\"id\":\"gameboy-legacy-fafb-v783-v1\"},\"restore\":\"legacy-transient-reset\",\"scheduler\":\"lockstep-v1\"}", "canonical": "{\"checkpointFormatOfRecord\":\"FLYSIM01\",\"compositionId\":\"pokered-live\",\"decoderConfigDigest\":\"82b6601f0390b742a67eca44ef935b49e16a73315db70f5644f1cbd21f7c8a52\",\"environment\":{\"audio\":{\"channels\":2,\"sampleRate\":48000},\"controllerSchema\":{\"digest\":\"1bde5fa114b99824ad608fba4ea85706cb0cebc6123a778dc1e5f89791d2a05e\",\"id\":\"gameboy-joypad-v1\",\"version\":1},\"extensions\":[\"gameboy-slots-v1\"],\"inspectionSchema\":{\"digest\":\"d6cb62248bfdac2ffdf00290ffbebf9a101b1fe28f7be766d24db28ede8da3e6\",\"id\":\"gameboy-memory-inspection-v1\",\"version\":1},\"setupFrames\":1,\"slots\":[\"best\"],\"stepDuration\":{\"denominator\":\"512\",\"numerator\":\"8572265625\"}},\"episodePolicy\":\"legacy-ratchet-rollback-v1\",\"executor\":{\"adapter\":\"pokered-unique8-v8\",\"id\":\"pokered-macros-v1\",\"macroChannels\":[\"macro_go_objective\",\"macro_go_out\",\"macro_go_warp\",\"macro_go_route\",\"macro_go_item\",\"macro_go_npc\",\"macro_go_frontier\",\"macro_go_shop\",\"macro_go_heal\",\"macro_talk\",\"macro_menu\",\"macro_next\",\"macro_yes\",\"macro_no\",\"macro_close\",\"macro_confirm\",\"macro_back\",\"macro_move_1\",\"macro_move_2\",\"macro_move_3\",\"macro_move_4\",\"macro_switch\",\"macro_item\",\"macro_throw_ball\",\"macro_run\",\"macro_buy_potion\",\"macro_buy_ball\",\"macro_buy_antidote\",\"macro_buy_repel\",\"macro_heal\",\"macro_leave\"],\"mode\":\"macros\",\"rom\":{\"byteLength\":\"1048576\",\"digest\":\"c840ea493f9bf41505f26cf5b1db26815dd588e7ec91d5fd6f1ad4d363dc4f20\",\"format\":\"gb-rom\",\"id\":\"pokered-rom\"},\"symbolProvenance\":\"0cd19d3b877b7dc66d12c7050bed9a7f38154d4b\"},\"flysimCompatibility\":\"lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu\",\"profile\":{\"byteLength\":\"1137\",\"digest\":\"41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878\",\"format\":\"fly-profile-v1\",\"id\":\"gameboy-legacy-fafb-v783-v1\"},\"restore\":\"legacy-transient-reset\",\"scheduler\":\"lockstep-v1\"}",
"digest": "44916db0a0846d3338f50d4f24d9d4e0214fa239af7d15e4174213cd93b07e28" "digest": "d37ccb40162ecb42172609623d53791804571fee1b66a1f4ab8183a9a68852ea"
}, },
{ {
"name": "an example legacy composition in raw mode", "name": "an example legacy composition in raw mode",
@ -3431,7 +3431,7 @@
"byteLength": "1048576", "byteLength": "1048576",
"format": "gb-rom" "format": "gb-rom"
}, },
"adapter": "pokered-unique8-v7", "adapter": "pokered-unique8-v8",
"symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "symbolProvenance": "0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
"mode": "raw", "mode": "raw",
"macroChannels": [] "macroChannels": []
@ -3467,11 +3467,11 @@
"episodePolicy": "legacy-ratchet-rollback-v1", "episodePolicy": "legacy-ratchet-rollback-v1",
"restore": "legacy-transient-reset", "restore": "legacy-transient-reset",
"checkpointFormatOfRecord": "FLYSIM01", "checkpointFormatOfRecord": "FLYSIM01",
"flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu" "flysimCompatibility": "lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu"
}, },
"note": "", "note": "",
"canonical": "{\"checkpointFormatOfRecord\":\"FLYSIM01\",\"compositionId\":\"pokered-live\",\"decoderConfigDigest\":\"6234e4a0363cfe82b8d515943c4f645a3960eda8fa5bf9465009061f80d50812\",\"environment\":{\"audio\":{\"channels\":2,\"sampleRate\":48000},\"controllerSchema\":{\"digest\":\"1bde5fa114b99824ad608fba4ea85706cb0cebc6123a778dc1e5f89791d2a05e\",\"id\":\"gameboy-joypad-v1\",\"version\":1},\"extensions\":[\"gameboy-slots-v1\"],\"inspectionSchema\":{\"digest\":\"d6cb62248bfdac2ffdf00290ffbebf9a101b1fe28f7be766d24db28ede8da3e6\",\"id\":\"gameboy-memory-inspection-v1\",\"version\":1},\"setupFrames\":1,\"slots\":[\"best\"],\"stepDuration\":{\"denominator\":\"512\",\"numerator\":\"8572265625\"}},\"episodePolicy\":\"legacy-ratchet-rollback-v1\",\"executor\":{\"adapter\":\"pokered-unique8-v7\",\"id\":\"pokered-macros-v1\",\"macroChannels\":[],\"mode\":\"raw\",\"rom\":{\"byteLength\":\"1048576\",\"digest\":\"c840ea493f9bf41505f26cf5b1db26815dd588e7ec91d5fd6f1ad4d363dc4f20\",\"format\":\"gb-rom\",\"id\":\"pokered-rom\"},\"symbolProvenance\":\"0cd19d3b877b7dc66d12c7050bed9a7f38154d4b\"},\"flysimCompatibility\":\"lif-1ms-f64-v2/pokered-unique8-v7/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu\",\"profile\":{\"byteLength\":\"1137\",\"digest\":\"41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878\",\"format\":\"fly-profile-v1\",\"id\":\"gameboy-legacy-fafb-v783-v1\"},\"restore\":\"legacy-transient-reset\",\"scheduler\":\"lockstep-v1\"}", "canonical": "{\"checkpointFormatOfRecord\":\"FLYSIM01\",\"compositionId\":\"pokered-live\",\"decoderConfigDigest\":\"6234e4a0363cfe82b8d515943c4f645a3960eda8fa5bf9465009061f80d50812\",\"environment\":{\"audio\":{\"channels\":2,\"sampleRate\":48000},\"controllerSchema\":{\"digest\":\"1bde5fa114b99824ad608fba4ea85706cb0cebc6123a778dc1e5f89791d2a05e\",\"id\":\"gameboy-joypad-v1\",\"version\":1},\"extensions\":[\"gameboy-slots-v1\"],\"inspectionSchema\":{\"digest\":\"d6cb62248bfdac2ffdf00290ffbebf9a101b1fe28f7be766d24db28ede8da3e6\",\"id\":\"gameboy-memory-inspection-v1\",\"version\":1},\"setupFrames\":1,\"slots\":[\"best\"],\"stepDuration\":{\"denominator\":\"512\",\"numerator\":\"8572265625\"}},\"episodePolicy\":\"legacy-ratchet-rollback-v1\",\"executor\":{\"adapter\":\"pokered-unique8-v8\",\"id\":\"pokered-macros-v1\",\"macroChannels\":[],\"mode\":\"raw\",\"rom\":{\"byteLength\":\"1048576\",\"digest\":\"c840ea493f9bf41505f26cf5b1db26815dd588e7ec91d5fd6f1ad4d363dc4f20\",\"format\":\"gb-rom\",\"id\":\"pokered-rom\"},\"symbolProvenance\":\"0cd19d3b877b7dc66d12c7050bed9a7f38154d4b\"},\"flysimCompatibility\":\"lif-1ms-f64-v2/pokered-unique8-v8/75ba5d3536a2862fdb9f4ef1a76b96fe099a7201ac737f0cf53fe4c5ad4183f3:1657ba7716494c9db95a13b1527bc129226363f99b395774de1f76ff28571f0e:63b1acb26272edccdcfacf3c2ff58069e0cefaa84451429c989258bafaeae1d5:f567d7f07227e71c0df2ab4e6510f3a3f79e51b675095792e16d216d74b7b5b7:ece0b5e76d1884dd2f3ff6e0362bc284febe205ac1ce07fdab5009942ddffb62:b8c33144d4cec31c3ac4b6091ef1f4207f567c4f710f7c13fd2dc47c44c2b634:dbbafc044cd50aad7b792615988ff6d9991c846cc3d8b2eafc86b7c357b5eefc/fly-kc-mbon-rstdp-v2/binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b/statefmt:199616-x86_64-unknown-linux-gnu\",\"profile\":{\"byteLength\":\"1137\",\"digest\":\"41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878\",\"format\":\"fly-profile-v1\",\"id\":\"gameboy-legacy-fafb-v783-v1\"},\"restore\":\"legacy-transient-reset\",\"scheduler\":\"lockstep-v1\"}",
"digest": "568eceeb052ebf4fbd0c10661e227783cecc8ac7fee75ae6ba84335c684bfb7c" "digest": "0e62f2d6ee98226262f0d212762a9a69f1901a97f08dbe7790a502fe308e56a5"
}, },
{ {
"name": "a rank climb: slot saved, then the milestone capture", "name": "a rank climb: slot saved, then the milestone capture",

View file

@ -17,7 +17,7 @@ ROM bytes -> Emulator::run_frame -> RGBA frame + PCM + WRAM
| `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash | | `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash |
| `image` | The boundary memory image (`read_memory_image`), the `Cartridge` and `ImageReader`, which runs the macros and adapters over an image instead of a live emulator (MEM-01) | | `image` | The boundary memory image (`read_memory_image`), the `Cartridge` and `ImageReader`, which runs the macros and adapters over an image instead of a live emulator (MEM-01) |
| `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` | | `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` |
| `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table | | `pokemon_red` | The `pokered-unique8-v8` reward adapter, its catalog and its generated symbol table |
| `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map | | `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map |
| `ratchet` | The progress ratchet, generic over the adapter's rank and its `RecoveryPolicy` | | `ratchet` | The progress ratchet, generic over the adapter's rank and its `RecoveryPolicy` |
| `recovery` | Rolling the game back to the ratchet's best safe snapshot | | `recovery` | Rolling the game back to the ratchet's best safe snapshot |

View file

@ -57,7 +57,7 @@ impl MemoryReader for &mut dyn MemoryReader {
/// ///
/// `kind` is an adapter-owned interned name (Pokémon: `milestone`, /// `kind` is an adapter-owned interned name (Pokémon: `milestone`,
/// `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`, `catch`, /// `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`, `catch`,
/// `talk`, `item`); it is the key the statistics counters and the on-screen ticker group /// `talk`, `item`, `damage`); it is the key the statistics counters and the on-screen ticker group
/// by. Field names serialize exactly as the prototype's `RewardEvent` did, so a /// by. Field names serialize exactly as the prototype's `RewardEvent` did, so a
/// checkpoint written by either implementation reads in the other. /// checkpoint written by either implementation reads in the other.
#[derive(Debug, Clone, PartialEq, Serialize)] #[derive(Debug, Clone, PartialEq, Serialize)]
@ -241,7 +241,7 @@ impl std::error::Error for AdapterError {}
/// A game, as the sim loop sees it. /// A game, as the sim loop sees it.
pub trait GameAdapter: Send { pub trait GameAdapter: Send {
/// Adapter version string, pinned into the checkpoint compatibility string. /// Adapter version string, pinned into the checkpoint compatibility string.
/// Pokémon: `pokered-unique8-v7`. /// Pokémon: `pokered-unique8-v8`.
fn id(&self) -> &'static str; fn id(&self) -> &'static str;
/// Earlier [`GameAdapter::id`]s whose checkpoints this build can read, by a migration /// Earlier [`GameAdapter::id`]s whose checkpoints this build can read, by a migration

View file

@ -30,7 +30,7 @@ pub const PROTOTYPE_PLASTICITY_VERSION: &str = "fly-kc-mbon-rstdp-v2";
pub struct Compatibility<'a> { pub struct Compatibility<'a> {
/// `kernelVersion(config)` from the neural library. /// `kernelVersion(config)` from the neural library.
pub neural_kernel_version: &'a str, pub neural_kernel_version: &'a str,
/// The adapter's version string, e.g. `pokered-unique8-v7`. /// The adapter's version string, e.g. `pokered-unique8-v8`.
pub adapter: &'a str, pub adapter: &'a str,
/// The dataset's seven SHA-256 digests joined with `:`. /// The dataset's seven SHA-256 digests joined with `:`.
pub dataset_fingerprint: &'a str, pub dataset_fingerprint: &'a str,
@ -78,7 +78,7 @@ const ADAPTER_SEGMENT: usize = 1;
/// The environment variable that opts a deploy into the adapter migration. /// The environment variable that opts a deploy into the adapter migration.
/// ///
/// Read by flysim at restore and by `infra/05-deploy.sh`'s compatibility gate. Comma- or /// Read by flysim at restore and by `infra/05-deploy.sh`'s compatibility gate. Comma- or
/// whitespace-separated adapter ids, e.g. `FLY_ACCEPT_ADAPTERS=pokered-unique8-v6`. /// whitespace-separated adapter ids, e.g. `FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`.
pub const ACCEPT_ADAPTERS_ENV: &str = "FLY_ACCEPT_ADAPTERS"; pub const ACCEPT_ADAPTERS_ENV: &str = "FLY_ACCEPT_ADAPTERS";
/// What a build may do with a checkpoint whose compatibility string is not its own. /// What a build may do with a checkpoint whose compatibility string is not its own.
@ -180,7 +180,7 @@ mod tests {
assert_eq!( assert_eq!(
fixture().prototype_string(), fixture().prototype_string(),
concat!( concat!(
"lif-1ms-f64-v2/pokered-unique8-v7/aa:bb:cc:dd:ee:ff:00/", "lif-1ms-f64-v2/pokered-unique8-v8/aa:bb:cc:dd:ee:ff:00/",
"fly-kc-mbon-rstdp-v2/", "fly-kc-mbon-rstdp-v2/",
"binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/", "binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/",
"pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", "pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b",
@ -194,10 +194,43 @@ mod tests {
#[test] #[test]
fn an_identical_string_restores_without_any_opt_in() { fn an_identical_string_restores_without_any_opt_in() {
let current = with_adapter("pokered-unique8-v7"); let current = with_adapter("pokered-unique8-v8");
assert_eq!(decide(&current, &current, &[], &[]), RestoreDecision::Exact); assert_eq!(decide(&current, &current, &[], &[]), RestoreDecision::Exact);
} }
#[test]
fn a_v7_checkpoint_restores_under_v8_only_with_the_opt_in_and_v6_still_does() {
let new = with_adapter("pokered-unique8-v8");
let migrates = crate::pokemon_red::MIGRATES_FROM;
for from in ["pokered-unique8-v7", "pokered-unique8-v6"] {
let old = with_adapter(from);
assert!(matches!(decide(&old, &new, migrates, &[]), RestoreDecision::Refuse(_)));
assert_eq!(
decide(&old, &new, migrates, &accepted_adapters(Some(from))),
RestoreDecision::MigrateAdapter { from: from.to_string() }
);
}
// Naming v7 does not wave a v6 checkpoint through, nor v5 at all.
assert!(matches!(
decide(
&with_adapter("pokered-unique8-v6"),
&new,
migrates,
&accepted_adapters(Some("pokered-unique8-v7"))
),
RestoreDecision::Refuse(_)
));
assert!(matches!(
decide(
&with_adapter("pokered-unique8-v5"),
&new,
migrates,
&accepted_adapters(Some("pokered-unique8-v5"))
),
RestoreDecision::Refuse(_)
));
}
#[test] #[test]
fn a_v6_checkpoint_restores_under_v7_only_with_the_opt_in() { fn a_v6_checkpoint_restores_under_v7_only_with_the_opt_in() {
let old = with_adapter("pokered-unique8-v6"); let old = with_adapter("pokered-unique8-v6");

View file

@ -188,6 +188,13 @@ pub struct SlotBinding {
pub struct Observed { pub struct Observed {
pub scene: SceneId, pub scene: SceneId,
pub bindings: Vec<SlotBinding>, pub bindings: Vec<SlotBinding>,
/// The fly's own buttons this scene lets through to the cartridge while no macro is running
/// and nothing is bound, as a joypad mask; 0 for every scene but the one that is typed on.
///
/// Row 69 (`docs/design/macros.md` 12.32): the naming screen is spelled with the D-pad, A, B
/// and START, and its pad is those buttons rather than a macro per key. The title's raw
/// buttons are not this field -- a scene that is not playable passes all of them, by section 2.
pub raw: u8,
} }
/// How a macro ended: `docs/design/macros.md` section 5's `outcome` field. /// How a macro ended: `docs/design/macros.md` section 5's `outcome` field.

View file

@ -1,4 +1,4 @@
//! The `pokered-unique8-v7` reward catalog. //! The `pokered-unique8-v8` reward catalog.
//! //!
//! A direct port of the prototype's `src/reward/catalog.ts`, including the //! A direct port of the prototype's `src/reward/catalog.ts`, including the
//! declaration order, which is the order `counts` and `last` serialize in. //! declaration order, which is the order `counts` and `last` serialize in.
@ -23,6 +23,7 @@ pub mod kind {
pub const CATCH: &str = "catch"; pub const CATCH: &str = "catch";
pub const TALK: &str = "talk"; pub const TALK: &str = "talk";
pub const ITEM: &str = "item"; pub const ITEM: &str = "item";
pub const DAMAGE: &str = "damage";
} }
/// What a `catch` of a species this run has already caught pays. /// What a `catch` of a species this run has already caught pays.
@ -46,7 +47,7 @@ pub struct RewardRule {
pub stimulation_ms: u32, pub stimulation_ms: u32,
} }
pub const REWARDS: [RewardRule; 11] = [ pub const REWARDS: [RewardRule; 12] = [
RewardRule { RewardRule {
kind: kind::MILESTONE, kind: kind::MILESTONE,
label: "Story", label: "Story",
@ -151,6 +152,22 @@ pub const REWARDS: [RewardRule; 11] = [
value: 0.15, value: 0.15,
stimulation_ms: 120, stimulation_ms: 120,
}, },
// The operator's decision of 2026-09-29: pay the fly for the HP its own attack removes from
// the Pokémon it is fighting, so the move that deals damage is worth more than the one that
// does not (row 67: TAIL WHIP 155, BUBBLE 23, TACKLE 0, 29 battles lost). Appended for the
// same reason as every rule since `boundary`.
//
// The value is what one whole enemy Pokémon's max HP pays, paid in proportion as it goes;
// `damage::KO_BONUS` adds 0.05 when the fly's hit knocks out a trainer's Pokémon, and
// `damage::BATTLE_CAP` holds a battle to the 0.50 the `trainer` rule pays for winning one.
// A wild battle is scaled 1, 1/2, 1/3 per (map, species, level) like the wild-KO rule.
RewardRule {
kind: kind::DAMAGE,
label: "Damage",
trigger: "HP the fly's own attack removed in battle, 0.20 per whole Pokémon; +0.05 a trainer's Pokémon knocked out; max 0.50 a battle; wild 1, 1/2, 1/3 per map/species/level",
value: 0.20,
stimulation_ms: 80,
},
]; ];
/// Position of `kind` in [`REWARDS`], or `None` for an unknown kind. This is /// Position of `kind` in [`REWARDS`], or `None` for an unknown kind. This is
@ -260,6 +277,9 @@ mod tests {
assert_eq!(rule(kind::TALK).unwrap().stimulation_ms, 100); assert_eq!(rule(kind::TALK).unwrap().stimulation_ms, 100);
assert_eq!(rule(kind::ITEM).unwrap().value, 0.15); assert_eq!(rule(kind::ITEM).unwrap().value, 0.15);
assert_eq!(rule(kind::ITEM).unwrap().stimulation_ms, 120); assert_eq!(rule(kind::ITEM).unwrap().stimulation_ms, 120);
// Nor this: the operator's damage rule, `pokered-unique8-v8`.
assert_eq!(rule(kind::DAMAGE).unwrap().value, 0.20);
assert_eq!(rule(kind::DAMAGE).unwrap().stimulation_ms, 80);
assert!(rule("blackout").is_none(), "the catalog has no penalties"); assert!(rule("blackout").is_none(), "the catalog has no penalties");
assert!(REWARDS.iter().all(|rule| rule.value > 0.0)); assert!(REWARDS.iter().all(|rule| rule.value > 0.0));
} }
@ -281,9 +301,10 @@ mod tests {
kind::CATCH, kind::CATCH,
kind::TALK, kind::TALK,
kind::ITEM, kind::ITEM,
kind::DAMAGE,
] ]
); );
assert_eq!(index(kind::ITEM), Some(REWARDS.len() - 1)); assert_eq!(index(kind::DAMAGE), Some(REWARDS.len() - 1));
} }
#[test] #[test]

View file

@ -0,0 +1,447 @@
//! What the damage rule of `pokered-unique8-v8` reads: HP the fly's own attack removed from the
//! Pokémon it is fighting.
//!
//! The operator's decision of 2026-09-29 (`docs/rewards-learning.md`, "Damage rewards"), chosen
//! over a pad rule that would have withheld a stat move once it had been used. Row 67
//! (`infra/docs/macros-traps.md`) is the reason: the live fly lost the Pewter Gym's Jr. Trainer 29
//! times running with TAIL WHIP 155, BUBBLE 23, TACKLE 0, and nothing in the catalog paid for
//! anything that happened inside a battle it did not win. This rule pays for the attack that lands,
//! so the move that deals damage is worth more than the one that does not, in the battle where the
//! choice is made.
//!
//! Everything here is a read of game memory after a frame. Nothing chooses, biases or presses a
//! button: which moves are on the pad is still the scene's (`docs/design/macros.md`), and which one
//! is pressed is still the fly's.
//!
//! ## What counts as the fly's attack
//!
//! A drop in `wEnemyMonHP` on a sample where `hWhoseTurn` reads 0 (the player's side is acting)
//! and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit (`engine/battle/core.asm`):
//!
//! - `ApplyDamageToEnemyPokemon` subtracts `wDamage` from `wEnemyMonHP` inside
//! `ExecutePlayerMove`, with `hWhoseTurn` 0. Multi-hit moves subtract once per hit.
//! - the enemy's poison and burn ticks and a Leech Seed on the enemy are
//! `HandlePoisonBurnLeechSeed`, which picks the enemy's HP *because* `hWhoseTurn` is 1;
//! the enemy's recoil, its confusion self-hit, its own Explosion and a Substitute it makes
//! all happen in `ExecuteEnemyMove`, with `hWhoseTurn` 1. None of them pays.
//! - a Leech Seed on the *player* heals the enemy on the player's turn: HP goes up, which never
//! pays (below). Damage into an enemy Substitute is `AttackSubstitute`, which never touches
//! `wEnemyMonHP`.
//! - `STRUGGLE` is the move the cartridge executes for a Pokémon with no PP. The fly chose FIGHT,
//! not the move, so it is not paid for; winning still pays what winning pays.
//!
//! ## What cannot be farmed
//!
//! - **Heal.** Each target keeps its lowest HP this battle; only HP below that pays. A Potion,
//! Recover, Rest or a drain lifts the HP and the same HP is not paid twice.
//! - **Switch.** A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that
//! goes out and comes back keeps its mark, and two Weedles of one level are two targets. A
//! target is marked the first time it reads full HP, which is how every enemy Pokémon enters a
//! battle in this game, so a stale `wEnemyMon` left over from the last battle neither pays nor
//! hides the real Pokémon's first hit.
//! - **The battle.** At most [`BATTLE_CAP`] a battle, whatever the party size.
//! - **Wild Pokémon.** A wild battle pays at the scale the wild-KO rule uses -- 1, 1/2, 1/3 --
//! for its first three battles per `(map, species, level)` that paid any damage, and nothing
//! after, and a rollback blocks every key that has paid. Trainer battles have no such ledger:
//! a trainer is only fought again after losing to it (or a rollback), and the per-battle cap
//! bounds each of those.
use serde_json::{Value, json};
use crate::adapter::MemoryReader;
use super::state::poke;
use super::symbols::ram;
/// What a trainer's Pokémon knocked out by the fly's own hit adds to that hit.
///
/// The damage share of the knockout hit is already paid; this is the step "one of the trainer's
/// Pokémon is down", on the frame it happens. Trainer battles only: a wild knockout is the
/// `battle` rule's, paid on the way out of the battle.
pub const KO_BONUS: f64 = 0.05;
/// The most damage pays in one battle: the `trainer` rule's own 0.50, so that a battle's worth
/// of damage is worth what winning it is. The Pewter Gym's Jr. Trainer (two Pokémon) reaches it
/// exactly: 2 x (0.20 + 0.05).
pub const BATTLE_CAP: f64 = 0.50;
/// Wild battles per `(map, species, level)` that may pay damage, for the lifetime of the ledger:
/// the wild-KO rule's three, for the same reason.
pub const MAX_WILD_BATTLES: u64 = 3;
/// The sanity bound the adapter already applies to an enemy's max HP (`sample`'s wild-KO read):
/// the largest in the game is under 1000, so anything else is a byte read out of a battle that
/// is not set up yet.
const MAX_HP_BOUND: u16 = 1000;
/// One enemy Pokémon, as far as a battle can tell them apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Target {
/// `wEnemyMonPartyPos`: the enemy party slot (`$ff` before a trainer's first send-out).
pub slot: u8,
pub species: u8,
pub level: u8,
}
/// The bytes one sample reads for the rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Reading {
pub target: Target,
pub hp: u16,
pub max_hp: u16,
/// `hWhoseTurn` reads 0.
pub fly_turn: bool,
/// `wPlayerMoveNum`.
pub move_id: u8,
}
impl Reading {
/// Read one sample, or `None` when the enemy's HP is not a readable HP: a max of 0 or past
/// [`MAX_HP_BOUND`], or a current HP above the max -- which is also what the one torn read
/// possible here looks like, `ApplyDamageToEnemyPokemon`'s `sbc` having wrapped below zero
/// before it clamps.
pub fn read(memory: &mut impl MemoryReader) -> Option<Self> {
let hp = word(memory, ram::wEnemyMonHP);
let max_hp = word(memory, ram::wEnemyMonMaxHP);
if max_hp == 0 || max_hp >= MAX_HP_BOUND || hp > max_hp {
return None;
}
Some(Self {
target: Target {
slot: memory.read8(ram::wEnemyMonPartyPos),
species: memory.read8(ram::wEnemyMonSpecies),
level: memory.read8(ram::wEnemyMonLevel),
},
hp,
max_hp,
fly_turn: memory.read8(poke::H_WHOSE_TURN) == 0,
move_id: memory.read8(ram::wPlayerMoveNum),
})
}
}
fn word(memory: &mut impl MemoryReader, address: u16) -> u16 {
u16::from(memory.read8(address)) << 8 | u16::from(memory.read8(address + 1))
}
/// HP the fly's own attack removed on one sample.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hit {
pub target: Target,
pub removed: u16,
pub max_hp: u16,
pub knocked_out: bool,
}
/// One target's mark: its max HP when first seen and the lowest HP it has shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Mark {
target: Target,
max_hp: u16,
low: u16,
}
/// The rule's state for one battle. Carried in the adapter's `battle` (and so in a checkpoint
/// taken mid-battle); a new battle starts with a new one.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BattleDamage {
marks: Vec<Mark>,
/// Paid so far this battle, after the wild scale.
paid: f64,
/// The wild scale, decided at the battle's first hit; always 1 in a trainer battle.
scale: Option<f64>,
/// A battle restored from a state written before this rule: a target first seen is marked
/// at the HP it has *now*, since what it had lost before the restore is unknown.
restored: bool,
}
impl BattleDamage {
/// The state for a battle a `v7` checkpoint was taken in.
pub fn restored() -> Self {
Self { restored: true, ..Self::default() }
}
pub fn paid(&self) -> f64 {
self.paid
}
pub fn scale(&self) -> Option<f64> {
self.scale
}
/// Update the marks with one sample and say what the fly is owed for, if anything.
///
/// Every drop moves the mark, whoever caused it, so a poison tick is never paid later as
/// part of the fly's next hit. Only a drop on the fly's own turn, by a move it chose, is a
/// [`Hit`].
pub fn observe(&mut self, reading: Reading) -> Option<Hit> {
let index = match self.marks.iter().position(|mark| mark.target == reading.target) {
Some(index) if self.marks[index].max_hp == reading.max_hp => index,
found => {
// Every enemy Pokémon enters a battle at its max HP -- a wild one is generated
// full, a trainer's party is built full -- so a target not yet marked is only
// real once it reads full. Anything else is `wEnemyMon` still holding the last
// battle's Pokémon: `InitBattleVariables` does not clear it, and a trainer
// battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData` runs.
// In the row 67 ring that stale Pokémon is the same trainer's, in the same
// slot, at the HP it beat the fly with. A battle restored from a state without
// this rule cannot know, and marks what it reads.
if !self.restored && reading.hp != reading.max_hp {
return None;
}
let mark =
Mark { target: reading.target, max_hp: reading.max_hp, low: reading.hp };
match found {
// The same slot, species and level with another max HP is another Pokémon
// (a wild one with other DVs): its mark starts again.
Some(index) => {
self.marks[index] = mark;
index
}
None => {
self.marks.push(mark);
self.marks.len() - 1
}
}
}
};
let mark = &mut self.marks[index];
if reading.hp >= mark.low {
return None;
}
let removed = mark.low - reading.hp;
mark.low = reading.hp;
if !reading.fly_turn || reading.move_id == poke::moves::STRUGGLE {
return None;
}
Some(Hit {
target: reading.target,
removed,
max_hp: reading.max_hp,
knocked_out: reading.hp == 0,
})
}
/// Decide the wild scale once per battle. `ledger` is `(battles already paid for this key,
/// whether a rollback blocked it)`; the caller counts the battle when this returns a
/// non-zero scale for the first time.
pub fn decide_scale(&mut self, trainer: bool, ledger: (u64, bool)) -> (f64, bool) {
if let Some(scale) = self.scale {
return (scale, false);
}
let (count, blocked) = ledger;
let scale = if trainer {
1.0
} else if blocked || count >= MAX_WILD_BATTLES {
0.0
} else {
1.0 / (count as f64 + 1.0)
};
self.scale = Some(scale);
(scale, !trainer && scale > 0.0)
}
/// What `hit` pays: `value` per whole Pokémon's max HP, plus [`KO_BONUS`] for a trainer's
/// Pokémon knocked out, at the battle's scale, within what is left of [`BATTLE_CAP`].
pub fn pay(&mut self, hit: Hit, value: f64, trainer: bool) -> f64 {
let scale = self.scale.unwrap_or(0.0);
let mut amount = value * f64::from(hit.removed) / f64::from(hit.max_hp);
if trainer && hit.knocked_out {
amount += KO_BONUS;
}
let amount = (amount * scale).min((BATTLE_CAP - self.paid).max(0.0));
self.paid += amount;
amount
}
pub fn to_json(&self) -> Value {
json!({
"paid": self.paid,
"scale": self.scale,
"restored": self.restored,
"marks": self.marks.iter().map(|mark| json!([
mark.target.slot, mark.target.species, mark.target.level, mark.max_hp, mark.low,
])).collect::<Vec<_>>(),
})
}
/// The inverse of [`BattleDamage::to_json`]; `None` for anything malformed.
pub fn from_json(value: &Value) -> Option<Self> {
let paid = value.get("paid")?.as_f64().filter(|paid| paid.is_finite() && *paid >= 0.0)?;
let scale = match value.get("scale") {
None | Some(Value::Null) => None,
Some(scale) => Some(scale.as_f64().filter(|scale| (0.0..=1.0).contains(scale))?),
};
let restored = value.get("restored")?.as_bool()?;
let byte = |value: &Value| value.as_u64().and_then(|v| u8::try_from(v).ok());
let hp = |value: &Value| value.as_u64().and_then(|v| u16::try_from(v).ok());
let marks = value
.get("marks")?
.as_array()?
.iter()
.map(|mark| {
let mark = mark.as_array().filter(|mark| mark.len() == 5)?;
Some(Mark {
target: Target {
slot: byte(&mark[0])?,
species: byte(&mark[1])?,
level: byte(&mark[2])?,
},
max_hp: hp(&mark[3])?,
low: hp(&mark[4])?,
})
})
.collect::<Option<Vec<_>>>()?;
Some(Self { marks, paid, scale, restored })
}
}
#[cfg(test)]
mod tests {
use super::*;
const DIGLETT: Target = Target { slot: 0, species: 0x3b, level: 11 };
const SANDSHREW: Target = Target { slot: 1, species: 0x60, level: 11 };
const BUBBLE: u8 = 145;
const TACKLE: u8 = 33;
fn fly(target: Target, hp: u16, max_hp: u16, move_id: u8) -> Reading {
Reading { target, hp, max_hp, fly_turn: true, move_id }
}
fn enemy(target: Target, hp: u16, max_hp: u16) -> Reading {
Reading { target, hp, max_hp, fly_turn: false, move_id: BUBBLE }
}
#[test]
fn a_drop_on_the_flys_turn_is_a_hit_and_one_on_the_enemys_is_not() {
let mut battle = BattleDamage::default();
assert_eq!(battle.observe(fly(DIGLETT, 31, 31, BUBBLE)), None, "full HP is the mark");
let hit = battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap();
assert_eq!((hit.removed, hit.knocked_out), (11, false));
// The enemy's own poison tick: the mark moves, nothing is owed.
assert_eq!(battle.observe(enemy(DIGLETT, 18, 31)), None);
// ... so the next hit is paid from 18, not from 20.
assert_eq!(battle.observe(fly(DIGLETT, 12, 31, TACKLE)).unwrap().removed, 6);
// The same HP on the next sample is not a second hit.
assert_eq!(battle.observe(fly(DIGLETT, 12, 31, TACKLE)), None);
}
#[test]
fn struggle_is_not_the_flys_choice_and_pays_nothing() {
let mut battle = BattleDamage::default();
battle.observe(fly(DIGLETT, 31, 31, BUBBLE));
assert_eq!(battle.observe(fly(DIGLETT, 25, 31, poke::moves::STRUGGLE)), None);
assert_eq!(battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap().removed, 5);
}
#[test]
fn healed_hp_is_not_paid_twice() {
let mut battle = BattleDamage::default();
battle.observe(fly(DIGLETT, 31, 31, BUBBLE));
assert_eq!(battle.observe(fly(DIGLETT, 10, 31, BUBBLE)).unwrap().removed, 21);
// A Super Potion on the trainer's turn, or a drain on the fly's: up is never paid.
assert_eq!(battle.observe(enemy(DIGLETT, 31, 31)), None);
assert_eq!(battle.observe(fly(DIGLETT, 31, 31, BUBBLE)), None);
// Down to 15 again is ground already paid for; 15 to 4 is new.
assert_eq!(battle.observe(fly(DIGLETT, 15, 31, BUBBLE)), None);
let hit = battle.observe(fly(DIGLETT, 0, 31, BUBBLE)).unwrap();
assert_eq!((hit.removed, hit.knocked_out), (10, true));
}
#[test]
fn a_switch_keeps_each_targets_mark() {
let mut battle = BattleDamage::default();
battle.observe(fly(DIGLETT, 31, 31, BUBBLE));
battle.observe(fly(DIGLETT, 16, 31, BUBBLE));
// Sandshrew comes out: a new target, marked at its max.
assert_eq!(battle.observe(enemy(SANDSHREW, 33, 33)), None);
assert_eq!(battle.observe(fly(SANDSHREW, 30, 33, TACKLE)).unwrap().removed, 3);
// Diglett comes back at the 16 it left with: nothing new until it goes below.
assert_eq!(battle.observe(enemy(DIGLETT, 16, 31)), None);
assert_eq!(battle.observe(fly(DIGLETT, 10, 31, BUBBLE)).unwrap().removed, 6);
// Two Pokémon of one species and level in different slots are two targets.
let twin = Target { slot: 2, ..DIGLETT };
assert_eq!(battle.observe(enemy(twin, 31, 31)), None);
assert_eq!(battle.observe(fly(twin, 21, 31, BUBBLE)).unwrap().removed, 10);
}
#[test]
fn a_stale_enemy_from_the_last_battle_cannot_pay_or_hide_the_real_one() {
// The first in-battle samples can still hold the last battle's Pokémon at the HP it
// finished on -- in the row 67 ring, the same trainer's Diglett in the same slot. It is
// not marked until it reads full, so neither it nor the real Diglett's first hit is lost.
let mut battle = BattleDamage::default();
assert_eq!(battle.observe(enemy(DIGLETT, 7, 31)), None);
assert_eq!(battle.observe(fly(DIGLETT, 3, 31, BUBBLE)), None, "not marked: not paid");
assert_eq!(battle.observe(enemy(DIGLETT, 31, 31)), None, "the real one loads full");
assert_eq!(battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap().removed, 11);
// The same identity with another max HP is another Pokémon: its mark starts again.
assert_eq!(battle.observe(fly(DIGLETT, 29, 29, BUBBLE)), None);
assert_eq!(battle.observe(fly(DIGLETT, 19, 29, BUBBLE)).unwrap().removed, 10);
}
#[test]
fn a_battle_restored_without_the_rule_marks_targets_where_they_stand() {
let mut battle = BattleDamage::restored();
assert_eq!(battle.observe(fly(DIGLETT, 12, 31, BUBBLE)), None, "12/31 is the mark");
assert_eq!(battle.observe(fly(DIGLETT, 5, 31, BUBBLE)).unwrap().removed, 7);
}
#[test]
fn a_trainer_battle_pays_the_share_plus_the_knockout_and_stops_at_the_cap() {
let mut battle = BattleDamage::default();
assert_eq!(battle.decide_scale(true, (99, true)), (1.0, false), "no ledger for trainers");
let value = 0.20;
battle.observe(fly(DIGLETT, 31, 31, BUBBLE));
let hit = battle.observe(fly(DIGLETT, 0, 31, BUBBLE)).unwrap();
assert!((battle.pay(hit, value, true) - 0.25).abs() < 1e-12, "0.20 + the 0.05 knockout");
battle.observe(fly(SANDSHREW, 33, 33, BUBBLE));
let hit = battle.observe(fly(SANDSHREW, 0, 33, BUBBLE)).unwrap();
assert!((battle.pay(hit, value, true) - 0.25).abs() < 1e-12);
assert!((battle.paid() - BATTLE_CAP).abs() < 1e-12, "two Pokémon reach the cap");
let third = Target { slot: 2, ..SANDSHREW };
battle.observe(fly(third, 33, 33, BUBBLE));
let hit = battle.observe(fly(third, 0, 33, BUBBLE)).unwrap();
assert_eq!(battle.pay(hit, value, true), 0.0, "a third pays nothing");
}
#[test]
fn a_wild_battle_pays_one_half_one_third_then_nothing() {
let value = 0.20;
let mut paid = Vec::new();
for count in 0..4 {
let mut battle = BattleDamage::default();
let (scale, counted) = battle.decide_scale(false, (count, false));
assert_eq!(counted, count < MAX_WILD_BATTLES);
battle.observe(fly(DIGLETT, 31, 31, TACKLE));
let hit = battle.observe(fly(DIGLETT, 0, 31, TACKLE)).unwrap();
paid.push(battle.pay(hit, value, false));
assert_eq!(battle.decide_scale(false, (0, false)).0, scale, "decided once a battle");
}
assert!((paid[0] - 0.20).abs() < 1e-12, "no knockout bonus in the wild: {paid:?}");
assert!((paid[1] - 0.10).abs() < 1e-12);
assert!((paid[2] - 0.20 / 3.0).abs() < 1e-12);
assert_eq!(paid[3], 0.0);
let mut blocked = BattleDamage::default();
assert_eq!(blocked.decide_scale(false, (0, true)), (0.0, false), "a rollback blocks it");
}
#[test]
fn the_battle_state_round_trips() {
let mut battle = BattleDamage::default();
battle.decide_scale(false, (1, false));
battle.observe(fly(DIGLETT, 31, 31, BUBBLE));
let hit = battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap();
battle.pay(hit, 0.2, false);
let back = BattleDamage::from_json(&battle.to_json()).unwrap();
assert_eq!(back, battle);
assert!(BattleDamage::from_json(&json!({ "paid": -1.0 })).is_none());
assert!(
BattleDamage::from_json(&json!({
"paid": 0.0, "scale": null, "restored": false, "marks": [[0, 1, 2, 3]]
}))
.is_none()
);
}
}

View file

@ -238,6 +238,23 @@ impl Wram {
self.set(ram::wFontLoaded, poke::BIT_FONT_LOADED).draw_box(0, 12, 19, 17) self.set(ram::wFontLoaded, poke::BIT_FONT_LOADED).draw_box(0, 12, 19, 17)
} }
/// The naming screen as `DisplayNamingScreen` leaves it (row 69): the keyboard's box at
/// (0, 4)-(19, 14), `capacity` underscores from (10, 3) with the raised one under the next
/// letter, the keyboard's menu bytes, and `length` letters typed.
pub fn naming_screen(&mut self, length: u8, capacity: u8) -> &mut Self {
let (left, top, right, bottom) = poke::NAMING_BOX;
self.draw_box(left, top, right, bottom);
let (x, y) = poke::NAMING_UNDERSCORES;
for place in 0..u16::from(capacity) {
let raised = place == u16::from(length.min(capacity - 1));
let tile =
if raised { poke::NAMING_UNDERSCORE_RAISED } else { poke::NAMING_UNDERSCORE };
self.screen_tile(x + place, y, tile);
}
self.cursor(poke::NAMING_TOP_Y, 1, 1, poke::NAMING_MAX_ITEM, 0xff)
.set(poke::NAMING_LENGTH, length)
}
/// The two-option YES/NO box where a Pokémon Center's script draws it (row 41): the box at /// The two-option YES/NO box where a Pokémon Center's script draws it (row 41): the box at
/// (11, 6)-(19, 11) over the dialogue box, with the cursor parked in its first interior column. /// (11, 6)-(19, 11) over the dialogue box, with the cursor parked in its first interior column.
pub fn yes_no_prompt(&mut self) -> &mut Self { pub fn yes_no_prompt(&mut self) -> &mut Self {

View file

@ -312,6 +312,11 @@ pub enum TargetKey {
/// the box belongs to is whatever the fly is standing in front of, and the box is the only /// the box belongs to is whatever the fly is standing in front of, and the box is the only
/// thing on screen while it is open. /// thing on screen while it is open.
Answer { at: Tile, yes: bool }, Answer { at: Tile, yes: bool },
/// A mart's or a Pokémon Center's counter, walked to by `GO SHOP` or `GO HEAL` and faced
/// (row 66). Keyed by the building's map and nothing else, because the question it answers is
/// asked from *outside* the building, where no sprite slot of it means anything: has the fly
/// just stood at this counter and walked away from it ([`MacroState::counter_walked_to`]).
Counter,
} }
/// Which list the shared cursor belongs to right now. /// Which list the shared cursor belongs to right now.
@ -617,6 +622,27 @@ pub trait MacroState: GameState {
false false
} }
/// Whether a `GO SHOP` or `GO HEAL` has walked the fly to the counter of the building on
/// `map` and faced it, inside the reached window (row 66). Asked of any map, not only the
/// loaded one: it is what the service walk from the street outside reads.
fn counter_walked_to(&mut self, _map: u8) -> bool {
false
}
/// Whether Oak has been given his parcel (`EVENT_OAK_GOT_PARCEL`). Until then the Viridian
/// clerk's text table is the parcel's and his counter sells nothing (row 66: `BUY BALL` from
/// the floor is not offered there before it). Defaulted to true, so a state that cannot read
/// the event flags withholds nothing on its account.
fn parcel_delivered(&mut self) -> bool {
true
}
/// The naming screen, when it is up (row 69). `None` for any other screen, and for a state
/// that cannot read it, so a reader without it deals no naming pad.
fn naming(&mut self) -> Option<super::state::Naming> {
None
}
/// Where the ladder's next unreached rung is, when the adapter's rung catalog knows. /// Where the ladder's next unreached rung is, when the adapter's rung catalog knows.
/// ///
/// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's /// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's

View file

@ -19,7 +19,8 @@ use crate::macros::{
use super::super::mapgrid::MapGrids; use super::super::mapgrid::MapGrids;
use super::super::state::PokeState; use super::super::state::PokeState;
use super::cartridge::{ use super::cartridge::{
Areas, Frontiers, LAST_MAP, MacroState, Pushed, Stood, Talked, Targets, Tile, outdoors, Areas, Frontiers, LAST_MAP, MacroState, Pushed, Stood, Talked, TargetKey, Targets, Tile,
outdoors,
}; };
use super::geography; use super::geography;
use super::executor::{MacroAbort, MacroMachine, Refusal}; use super::executor::{MacroAbort, MacroMachine, Refusal};
@ -119,6 +120,9 @@ pub struct PokemonPalette {
/// ledgers wrote what it had been aiming at against the new map's id. /// ledgers wrote what it had been aiming at against the new map's id.
settled: Option<u8>, settled: Option<u8>,
tear_frames: u16, tear_frames: u16,
/// The brain millisecond the naming screen was first read on, while it is up (row 69,
/// `palette::NAMING_BOUND_MS`). Session state, never checkpointed.
naming_since: Option<f64>,
/// The brain clock of the frame being decided, from [`MacroPalette::clock`]. /// The brain clock of the frame being decided, from [`MacroPalette::clock`].
/// ///
/// The blocked ledger is a *window*, so it needs the same clock the loop publishes rather /// The blocked ledger is a *window*, so it needs the same clock the loop publishes rather
@ -148,6 +152,7 @@ impl PokemonPalette {
nearer: false, nearer: false,
settled: None, settled: None,
tear_frames: 0, tear_frames: 0,
naming_since: None,
now_ms: 0.0, now_ms: 0.0,
} }
} }
@ -271,6 +276,9 @@ impl PokemonPalette {
if let Some((map, target)) = self.machine.take_reached() { if let Some((map, target)) = self.machine.take_reached() {
self.targets.record_reached(map, target); self.targets.record_reached(map, target);
} }
if let Some(map) = self.machine.take_counter() {
self.targets.record_reached(map, TargetKey::Counter);
}
// A tile the cartridge drove the fly off: no window, because the map is like that until // A tile the cartridge drove the fly off: no window, because the map is like that until
// the event that unlocks it, and nothing here knows which event that is (row 37). // the event that unlocks it, and nothing here knows which event that is (row 37).
while let Some((map, tile)) = self.machine.take_pushed() { while let Some((map, tile)) = self.machine.take_pushed() {
@ -299,11 +307,16 @@ impl MacroPalette for PokemonPalette {
} }
fn observe(&mut self, memory: &mut dyn MemoryReader, ledger: &dyn RunLedger) -> Observed { fn observe(&mut self, memory: &mut dyn MemoryReader, ledger: &dyn RunLedger) -> Observed {
let torn = { let (torn, naming) = {
let mut state = PokeState::new(memory); let mut state = PokeState::new(memory);
self.tear(&mut state) (self.tear(&mut state), state.naming())
}; };
let (scene, bindings, standing, stepping, approach) = { // Row 69: the naming screen's clock. Session state like the ledgers: it starts on the
// first frame the keyboard is read and is dropped on the first frame it is not, so each
// name gets the whole bound and a restore starts it again.
self.naming_since = naming.map(|_| self.naming_since.unwrap_or(self.now_ms));
let naming_elapsed = self.naming_since.map_or(0.0, |since| (self.now_ms - since).max(0.0));
let (scene, bindings, raw, standing, stepping, approach) = {
let Self { let Self {
machine, machine,
mode, mode,
@ -333,10 +346,15 @@ impl MacroPalette for PokemonPalette {
// the `TALK` gave the buttons back, so the machine is given every frame rather than // the `TALK` gave the buttons back, so the machine is given every frame rather than
// only the ones it owns (`docs/design/macros.md` section 12.4). // only the ones it owns (`docs/design/macros.md` section 12.4).
machine.observe_frame(&mut state); machine.observe_frame(&mut state);
let palette = match mode { let naming = naming.filter(|_| scene == Scene::Unknown);
PaletteMode::Palette => Palette::for_scene(scene, &mut state), let palette = match (naming, mode) {
PaletteMode::Plan => plan::plan_for(scene, &mut state), // Row 69: the keyboard's pad is the fly's own buttons until the name is full or
// the bound has run, then `CONFIRM` alone (`palette::naming_set`).
(Some(naming), _) => Palette::for_naming(scene, naming, naming_elapsed),
(None, PaletteMode::Palette) => Palette::for_scene(scene, &mut state),
(None, PaletteMode::Plan) => plan::plan_for(scene, &mut state),
}; };
let raw = if naming.is_some() { palette::naming_raw(&palette) } else { 0 };
let bindings = bindings(&palette); let bindings = bindings(&palette);
// Where the fly is standing, for the ledger below. Only on a frame the fly is its own // Where the fly is standing, for the ledger below. Only on a frame the fly is its own
// master: while the cartridge is walking it -- a warp in flight, a ledge hop, a script // master: while the cartridge is walking it -- a warp in flight, a ledge hop, a script
@ -355,7 +373,7 @@ impl MacroPalette for PokemonPalette {
Some((objective.map, hops)) Some((objective.map, hops))
}); });
*cached = Some(palette); *cached = Some(palette);
(scene, bindings, standing, stepping, approach) (scene, bindings, raw, standing, stepping, approach)
}; };
// Section 12.7: the macro layer's own answer to "has the run stood here", because the // Section 12.7: the macro layer's own answer to "has the run stood here", because the
// adapter's reward ledger cannot record a doormat. // adapter's reward ledger cannot record a doormat.
@ -407,7 +425,7 @@ impl MacroPalette for PokemonPalette {
// The talked entry `observe_frame` may just have earned, into the ledger the next frame // The talked entry `observe_frame` may just have earned, into the ledger the next frame
// reads. // reads.
self.record_talk(); self.record_talk();
Observed { scene: scene_id(scene), bindings } Observed { scene: scene_id(scene), bindings, raw }
} }
fn start( fn start(

View file

@ -30,7 +30,8 @@ use super::cartridge::{
}; };
use super::geography::Amenity; use super::geography::Amenity;
use super::palette::{ use super::palette::{
MacroId, MacroKind, Palette, amenity_goals, frontier_aims, heal_goals, healthiest_other, MacroId, MacroKind, Palette, amenity_goals, floor_ball_goals, frontier_aims, heal_goals,
healthiest_other,
facing_target, listing, move_index, move_list, nurse_prompt, objective_goals, party_rested, facing_target, listing, move_index, move_list, nurse_prompt, objective_goals, party_rested,
potion_slot, potion_slot,
precondition, precondition,
@ -130,6 +131,10 @@ const PROMPT_WAIT: u32 = 360;
/// [`PRESS_HOLD`] of A, then released, so the press is a new one each time. /// [`PRESS_HOLD`] of A, then released, so the press is a new one each time.
const PROMPT_PULSE: u32 = 40; const PROMPT_PULSE: u32 = 40;
/// Frames `CONFIRM` on the naming screen waits for the keyboard to close ([`Step::Submit`]).
/// The cartridge whites the screen out over three frames and clears it; four pulses of START fit.
const SUBMIT_WAIT: u32 = 160;
/// Extra presses a cursor navigation may spend beyond twice the length of its list, to cover a /// Extra presses a cursor navigation may spend beyond twice the length of its list, to cover a
/// press the game swallows while a menu is still drawing. /// press the game swallows while a menu is still drawing.
const CURSOR_SLACK: u8 = 6; const CURSOR_SLACK: u8 = 6;
@ -370,6 +375,17 @@ enum Step {
/// `Blocked` if it never does. The cartridge adds the item and takes the money a few frames /// `Blocked` if it never does. The cartridge adds the item and takes the money a few frames
/// after the YES, so a purchase is `done` when the wallet says so and not when the press is. /// after the YES, so a purchase is `done` when the wallet says so and not when the press is.
Paid { waited: u32, before: u32 }, Paid { waited: u32, before: u32 },
/// Advance the clerk's greeting until the counter's BUY / SELL / QUIT menu is drawn, then
/// move on; `Blocked` if it never comes, or if the counter's first stock row is not a Poké
/// Ball once its list can be read (row 66, `BUY BALL` from the floor). Pulses A the way
/// [`Step::Prompt`] does and reads the screen every frame, so the menu is caught before the
/// next pulse could choose BUY on it.
Counter { waited: u32 },
/// Pulse START until the naming screen is gone, which is the name handed back (row 69);
/// `Blocked` if it is still up after [`SUBMIT_WAIT`] frames. START is `.pressedStart` in
/// `DisplayNamingScreen`, taken on its edge, so each pulse is a new press like
/// [`Step::Prompt`]'s.
Submit { waited: u32 },
} }
/// Progress through one A* walk. /// Progress through one A* walk.
@ -648,6 +664,9 @@ pub struct MacroMachine {
/// that finds no route to *any* of its goals has failed at all of them, and each is a key. /// that finds no route to *any* of its goals has failed at all of them, and each is a key.
blocked: Vec<(u8, TargetKey)>, blocked: Vec<(u8, TargetKey)>,
reached: Option<(u8, TargetKey)>, reached: Option<(u8, TargetKey)>,
/// The building whose counter a completed `GO SHOP` or `GO HEAL` has just faced, for the
/// reached ledger under [`TargetKey::Counter`] (row 66).
counter: Option<u8>,
/// A map whose frontier a `GO FRONTIER` has just proved unreachable, waiting to be taken /// A map whose frontier a `GO FRONTIER` has just proved unreachable, waiting to be taken
/// into the session's ledger ([`super::cartridge::Frontiers`], section 12.14). /// into the session's ledger ([`super::cartridge::Frontiers`], section 12.14).
/// ///
@ -754,6 +773,7 @@ impl MacroMachine {
outcome: None, outcome: None,
blocked: Vec::new(), blocked: Vec::new(),
reached: None, reached: None,
counter: None,
exhausted: None, exhausted: None,
pushed_tile: Vec::new(), pushed_tile: Vec::new(),
refused_at: None, refused_at: None,
@ -842,6 +862,9 @@ impl MacroMachine {
} }
// A walk's cap is its own; every other script keeps section 4's flat ten seconds. // A walk's cap is its own; every other script keeps section 4's flat ten seconds.
let cap = match plan.front() { let cap = match plan.front() {
// `BUY BALL` from the floor is a walk and then a whole purchase (row 66): the walk's
// budget, and a script's ten seconds for the counter after it.
Some(Step::Walk(walk)) if spec.kind == MacroKind::BuyBall => walk.budget + FRAME_CAP,
Some(Step::Walk(walk)) => walk.budget, Some(Step::Walk(walk)) => walk.budget,
_ => FRAME_CAP, _ => FRAME_CAP,
}; };
@ -1000,6 +1023,11 @@ impl MacroMachine {
self.reached.take() self.reached.take()
} }
/// The building whose counter a completed `GO SHOP` or `GO HEAL` faced, taken (row 66).
pub fn take_counter(&mut self) -> Option<u8> {
self.counter.take()
}
/// The map a `no route` from `GO FRONTIER` earned, taken rather than read (section 12.14). /// The map a `no route` from `GO FRONTIER` earned, taken rather than read (section 12.14).
pub fn take_exhausted(&mut self) -> Option<u8> { pub fn take_exhausted(&mut self) -> Option<u8> {
self.exhausted.take() self.exhausted.take()
@ -1040,6 +1068,7 @@ impl MacroMachine {
// that so a cancelled queue cannot leak into the next macro's finish. // that so a cancelled queue cannot leak into the next macro's finish.
self.blocked.clear(); self.blocked.clear();
self.reached = None; self.reached = None;
self.counter = None;
// A rollback is not the map pushing the fly anywhere, and it is not the frontier being // A rollback is not the map pushing the fly anywhere, and it is not the frontier being
// out of reach either: the fly is about to be somewhere else entirely. // out of reach either: the fly is about to be somewhere else entirely.
self.pushed_tile.clear(); self.pushed_tile.clear();
@ -1411,6 +1440,16 @@ impl MacroMachine {
&& let Some(entry) = active.target && let Some(entry) = active.target
{ {
self.reached = Some(entry); self.reached = Some(entry);
// **The counter itself, by the building's map** (row 66): a service walk
// that ended facing the clerk or the nurse. From the street the question
// is "has the fly just stood at this counter", and outside the building
// no sprite slot of it can be named.
if matches!(active.kind, MacroKind::GoShop | MacroKind::GoHeal)
&& let (map, TargetKey::Thing(_)) = entry
&& super::geography::amenity_at(map).is_some()
{
self.counter = Some(map);
}
// And a completed `HEAL` has *had* the conversation: the box was opened, // And a completed `HEAL` has *had* the conversation: the box was opened,
// answered and closed by this macro's own presses, so the nurse is talked // answered and closed by this macro's own presses, so the nurse is talked
// to and `TALK` has nothing left to open (section 12.12). Without it the // to and `TALK` has nothing left to open (section 12.12). Without it the
@ -1577,6 +1616,38 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress {
Progress::Hold(buttons::NONE) Progress::Hold(buttons::NONE)
} }
} }
Step::Submit { waited } => {
if state.naming().is_none() {
Progress::Finished
} else if *waited >= SUBMIT_WAIT {
Progress::Blocked
} else {
*waited += 1;
if *waited % PROMPT_PULSE < PRESS_HOLD {
Progress::Hold(buttons::START)
} else {
Progress::Hold(buttons::NONE)
}
}
}
Step::Counter { waited } => {
if shop_screen(state) == Some(ShopScreen::BuySellQuit) {
if stock_index(state, item::POKE_BALL) == Some(0) {
Progress::Next
} else {
Progress::Blocked
}
} else if *waited >= PROMPT_WAIT {
Progress::Blocked
} else {
*waited += 1;
if *waited % PROMPT_PULSE < PRESS_HOLD {
Progress::Hold(buttons::A)
} else {
Progress::Hold(buttons::NONE)
}
}
}
Step::Prompt { waited, before } => { Step::Prompt { waited, before } => {
if state.money() < *before { if state.money() < *before {
Progress::Finished Progress::Finished
@ -1808,6 +1879,8 @@ fn beside(state: &mut dyn MacroState, here: Tile) -> Vec<Tile> {
const fn spanned(kind: MacroKind) -> &'static [Class] { const fn spanned(kind: MacroKind) -> &'static [Class] {
match kind { match kind {
MacroKind::Heal => &[Class::Overworld, Class::Talking], MacroKind::Heal => &[Class::Overworld, Class::Talking],
// Row 66: from the floor, `BUY BALL` walks, opens the counter (text) and buys (the shop).
MacroKind::BuyBall => &[Class::Overworld, Class::Talking, Class::Shop],
_ => &[], _ => &[],
} }
} }
@ -2072,6 +2145,9 @@ fn script(
// A is YES and B is NO in every yes/no box Red draws. Agent A's seam reports no cursor // A is YES and B is NO in every yes/no box Red draws. Agent A's seam reports no cursor
// for one, so there is none to read and nothing to navigate: these are the two presses // for one, so there is none to read and nothing to navigate: these are the two presses
// the table names and no more. // the table names and no more.
// On the naming screen `CONFIRM` is the bound's one button (row 69): it hands the name
// back with START, whatever the fly has spelled, and is done when the keyboard is gone.
MacroKind::Confirm if state.naming().is_some() => vec![Step::Submit { waited: 0 }],
MacroKind::Yes | MacroKind::Confirm => vec![press(buttons::A)], MacroKind::Yes | MacroKind::Confirm => vec![press(buttons::A)],
MacroKind::No | MacroKind::Back => vec![press(buttons::B)], MacroKind::No | MacroKind::Back => vec![press(buttons::B)],
MacroKind::Close | MacroKind::Leave => { MacroKind::Close | MacroKind::Leave => {
@ -2119,7 +2195,8 @@ fn script(
// Section 14's addition: the ball comes out of the bag, so the script is `ITEM`'s with a // Section 14's addition: the ball comes out of the bag, so the script is `ITEM`'s with a
// ball's index instead of a potion's -- and it stops at the confirmation. The throw // ball's index instead of a potion's -- and it stops at the confirmation. The throw
// animation, the shake count, the "Gotcha!" and the nickname prompt are all text the fly // animation, the shake count, the "Gotcha!" and the nickname prompt are all text the fly
// answers with the between-turns `NEXT` and the dialog's `NO` (section 12). // answers with the between-turns `NEXT` (a YES at the prompt), and the keyboard after it
// is the fly's own buttons (row 69, section 12.32).
MacroKind::ThrowBall => { MacroKind::ThrowBall => {
let bag_slot = throw_slot(state)?; let bag_slot = throw_slot(state)?;
let mut steps = Vec::new(); let mut steps = Vec::new();
@ -2167,7 +2244,33 @@ fn script(
vec![cursor_on(battle_entry::RUN, true, Some(ListKind::BattleMain))] vec![cursor_on(battle_entry::RUN, true, Some(ListKind::BattleMain))]
} }
MacroKind::BuyPotion => shop_plan(state, item::POTION)?, MacroKind::BuyPotion => shop_plan(state, item::POTION)?,
MacroKind::BuyBall => shop_plan(state, item::POKE_BALL)?, // At the open counter, the purchase; from the mart's floor (row 66), `HEAL`'s shape for a
// mart: walk to the clerk, the A that talks to him, the greeting advanced until BUY / SELL
// / QUIT is drawn, and the same purchase from there -- BUY, the first row (a Poké Ball in
// every mart this is offered in, checked once the list is readable), quantity one, the
// price box's YES, done when the wallet drops.
MacroKind::BuyBall if state.shop().is_some() => shop_plan(state, item::POKE_BALL)?,
MacroKind::BuyBall => {
let goals = aim_goals(floor_ball_goals(state));
unreachable.extend(goal_keys(&goals));
let (walk, target) = walk_then(state, goals, true)?;
aimed = target;
let before = state.money();
vec![
Step::Walk(walk),
press(buttons::A),
settle(),
Step::Counter { waited: 0 },
cursor(0, true),
settle(),
cursor(0, true),
settle(),
press(buttons::A),
Step::Prompt { waited: 0, before },
press(buttons::A),
Step::Paid { waited: 0, before },
]
}
MacroKind::BuyAntidote => shop_plan(state, item::ANTIDOTE)?, MacroKind::BuyAntidote => shop_plan(state, item::ANTIDOTE)?,
MacroKind::BuyRepel => shop_plan(state, item::REPEL)?, MacroKind::BuyRepel => shop_plan(state, item::REPEL)?,
// Section 13's two errands: the same walk `GO OBJECTIVE` makes, aimed at the area's mart // Section 13's two errands: the same walk `GO OBJECTIVE` makes, aimed at the area's mart

View file

@ -761,6 +761,12 @@ pub fn route_within(from: Region, to: u8, area: u8) -> bool {
false false
} }
/// The marts on [`AMENITIES`] whose counter stocks `POKE_BALL` as its first row
/// (`data/items/marts.asm` at the pinned commit): Viridian, Pewter and Cerulean all open their buy
/// list on it. `BUY BALL` from the floor (row 66) is offered only in these, and its script still
/// reads the stock once the counter is open and refuses if the first row is anything else.
pub const BALL_FIRST_MARTS: [u8; 3] = [maps::VIRIDIAN_MART, maps::PEWTER_MART, maps::CERULEAN_MART];
/// Which kind of amenity `map` *is*, when it is one. /// Which kind of amenity `map` *is*, when it is one.
/// ///
/// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the /// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the

View file

@ -17,7 +17,8 @@ use crate::adapter::PlaceKind;
use super::geography::{self, Amenity}; use super::geography::{self, Amenity};
use super::path::{self, Exit, Way}; use super::path::{self, Exit, Way};
use super::state::{BattleMenu, Facing, Mon, Move, Scene, ShopScreen, Status}; use super::state::{BattleKind, BattleMenu, Facing, Mon, Move, Naming, Scene, ShopScreen, Status};
use crate::emulator::buttons;
/// Slots in one palette: **one per macro type**, so a cell never moves. /// Slots in one palette: **one per macro type**, so a cell never moves.
/// ///
@ -447,6 +448,24 @@ impl Palette {
slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind)); slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind));
} }
} }
// Row 69, the operator's "throw on low HP only": with `THROW BALL` on this pad and the
// wild Pokémon's HP where a ball's HP factor is already at its best, the ball is the only
// answer on the attack side ([`throw_only`], [`WITHHELD_FOR_THE_THROW`]).
if slots[usize::from(MacroKind::ThrowBall.slot())].is_some() && throw_only(state) {
for kind in WITHHELD_FOR_THE_THROW {
slots[usize::from(kind.slot())] = None;
}
}
Self { scene, slots }
}
/// The naming screen's pad (row 69, `docs/design/macros.md` 12.32): [`naming_set`] with the
/// session's clock, which [`Palette::for_scene`] does not have.
pub fn for_naming(scene: Scene, naming: Naming, elapsed_ms: f64) -> Self {
let mut slots: [Option<MacroSpec>; SLOTS] = [None; SLOTS];
for kind in naming_set(naming, elapsed_ms) {
slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind));
}
Self { scene, slots } Self { scene, slots }
} }
@ -492,8 +511,14 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
// 47 minutes, 189 of them on map `0x02` with no box on screen at all. So the pad is // 47 minutes, 189 of them on map `0x02` with no box on screen at all. So the pad is
// empty there and the fly waits, which is the doctrine's own answer for a scene with // empty there and the fly waits, which is the doctrine's own answer for a scene with
// nothing sensible to press -- and the cartridge gives the buttons back by itself. // nothing sensible to press -- and the cartridge gives the buttons back by itself.
// The naming screen (row 69) is an `Unknown` with a pad of its own: the fly's raw
// buttons, and `CONFIRM` alone once the name is full or the bound has run
// ([`naming_set`]). Asked here with no clock, so only the full name ends it;
// [`Palette::for_naming`] is the same rule with the session's clock.
Scene::Unknown => { Scene::Unknown => {
if state.text_open() { if let Some(naming) = state.naming() {
naming_set(naming, 0.0)
} else if state.text_open() {
vec![Next, Back] vec![Next, Back]
} else { } else {
Vec::new() Vec::new()
@ -529,6 +554,11 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
if inside_center(state) { if inside_center(state) {
set.push(Heal); set.push(Heal);
} }
// Row 66: the mart's `HEAL`. One button from the floor that walks to the clerk,
// opens the counter and buys one ball ([`floor_ball_goals`]).
if inside_mart(state) {
set.push(BuyBall);
}
set.extend([GoShop, GoHeal, GoItem, GoNpc, GoFrontier, Talk]); set.extend([GoShop, GoHeal, GoItem, GoNpc, GoFrontier, Talk]);
set set
} }
@ -606,6 +636,113 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
} }
} }
/// How long the fly spells a name before `CONFIRM` is the only button, in brain milliseconds
/// (row 69).
///
/// The operator's bound: "the stream can't sit on the keyboard forever". A minute is room for the
/// ten letters a Pokémon's name holds at the readout's own pace -- `a` fires at most every 480 ms
/// and a direction is held 800 ms -- several times over, and short enough to be one beat of the
/// stream rather than a stall.
pub const NAMING_BOUND_MS: f64 = 60_000.0;
/// The fly's own buttons on the naming screen (row 69): the D-pad moves over the keyboard, `A`
/// types the letter under the cursor (or ED, which hands the name back, or the case switch), `B`
/// deletes the last letter, `START` hands the name back. `SELECT` (the case switch as a button)
/// is not the operator's list and is left off.
pub const NAMING_RAW: u8 = buttons::UP
| buttons::DOWN
| buttons::LEFT
| buttons::RIGHT
| buttons::A
| buttons::B
| buttons::START;
/// The naming screen's macro buttons (row 69): **none** while the fly is spelling, so the pad is
/// its raw buttons ([`NAMING_RAW`]); `CONFIRM` alone once the name is full or [`NAMING_BOUND_MS`]
/// has run since the screen opened, and then the raw buttons are off.
///
/// Why not `CONFIRM` beside the raw buttons from the start: the macro group decides every 800 ms
/// among the bound buttons and a group of one always has a winner, so a lone `CONFIRM` would hand
/// back an empty name within a second of the keyboard appearing. The fly can end the name itself
/// all along -- ED is a key on the keyboard and `START` is one of its buttons -- and the bound is
/// the only thing that ends it for it. A name handed back empty is the species' own name: that is
/// the cartridge (`AskName.declinedNickname`), not this.
pub fn naming_set(naming: Naming, elapsed_ms: f64) -> Vec<MacroKind> {
if naming.full() || elapsed_ms >= NAMING_BOUND_MS {
vec![MacroKind::Confirm]
} else {
Vec::new()
}
}
/// The raw buttons the naming screen lets through for this pad (row 69): [`NAMING_RAW`] while the
/// pad has no macro button on it, nothing once it has.
pub fn naming_raw(palette: &Palette) -> u8 {
if palette.bound() == 0 { NAMING_RAW } else { 0 }
}
/// What `THROW BALL` takes off the pad beside it when it is the throw's turn (row 69): every move,
/// `SWITCH`, `RUN`, and the bag's `BACK`.
///
/// The operator's decision is that the ball is the only *attack-side* answer, and the moves are
/// that side. Of the rest, what stays is `ITEM`: it is only ever dealt for a Pokémon that is out,
/// under half its HP, with a Potion the cartridge would take (section 13.1, row 63), so it is the
/// one non-attack need that keeps the thrower standing while it throws. What goes:
///
/// - `SWITCH`'s reason is a healthier *fighter*, and there is nothing left to fight for;
/// - `RUN` is bound on the fly's own Pokémon losing, and the enemy is at the weakest it will be:
/// fleeing forfeits the catch the pad exists for, and a whiteout is the cartridge's own end;
/// - `BACK` in the bag leads to the top-level menu, whose pad is the same ball.
pub const WITHHELD_FOR_THE_THROW: [MacroKind; 7] = [
MacroKind::Move1,
MacroKind::Move2,
MacroKind::Move3,
MacroKind::Move4,
MacroKind::Switch,
MacroKind::Run,
MacroKind::Back,
];
/// Whether it is the throw's turn (row 69): a wild battle whose Pokémon has HP left, at or under
/// the HP where the ball the fly would throw has its best odds.
///
/// **"Low" is the cartridge's own number** (`ItemUseBall`, `engine/items/item_effects.asm`). The
/// HP half of Red's catch test is `W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, floored at
/// each step, with a `BallFactor` of 8 for a Great Ball and 12 for every other; the ball holds
/// when a second random byte is at most `W`, so at `W >= 255` it always holds and HP no longer
/// matters. For a Poké Ball that is HP at about a third of its maximum -- 7 of a Weedle's 20 --
/// and for a Great Ball about a half. Lower HP buys nothing more; what is left is the catch rate
/// and the status, which the fly's own presses cannot change. So "low" is exactly where the
/// throw stops getting better. The ball is the one [`throw_slot`] would throw; a Master Ball skips
/// the test in the cartridge and is read with a factor of 12 here, which only waits a little.
///
/// Everything else `THROW BALL` needs is its own precondition ([`throw_slot`]): a wild battle, a
/// ball, room in the party, a species the party does not hold. With no ball left, or a species
/// already caught, the button is off the pad and so is this, and the ordinary pad is back.
pub fn throw_only(state: &mut dyn MacroState) -> bool {
let Some(battle) = state.battle() else { return false };
if battle.kind != BattleKind::Wild {
return false;
}
let Some(enemy) = battle.enemy else { return false };
let Some(index) = throw_slot(state) else { return false };
let Some(ball) = state.bag().get(usize::from(index)).map(|stack| stack.id) else {
return false;
};
ball_holds_on_hp(enemy.hp, enemy.max_hp, ball)
}
/// `ItemUseBall`'s HP test, whole: whether `W` reaches 255 for `ball` at this HP (row 69).
pub fn ball_holds_on_hp(hp: u16, max_hp: u16, ball: u8) -> bool {
if hp == 0 || max_hp == 0 || hp > max_hp {
return false;
}
let factor: u32 = if ball == item::GREAT_BALL { 8 } else { 12 };
// `srl b / rr a` twice and only `a` kept: the low byte of HP / 4, and 1 for a quotient of 0.
let quarter = u32::from((hp >> 2) as u8).max(1);
(u32::from(max_hp) * 255 / factor) / quarter >= 255
}
/// Section 3's preconditions, one arm each. /// Section 3's preconditions, one arm each.
pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
match kind { match kind {
@ -670,8 +807,8 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
move_slot_bound(state, kind) move_slot_bound(state, kind)
} }
// Section 14's addition (the operator: "throw pokeball should be a macro"). A wild battle, a ball // Section 14's addition (the operator: "throw pokeball should be a macro"). A wild battle, a ball
// in the bag, and room in the party. No catch-rate and no HP knowledge: when to throw is // in the bag, and room in the party. No catch-rate and no HP knowledge here: the enemy's
// the fly's. // HP decides only what else is on the pad beside it (row 69, [`throw_only`]).
MacroKind::ThrowBall => throw_slot(state).is_some(), MacroKind::ThrowBall => throw_slot(state).is_some(),
MacroKind::Switch => healthiest_other(state).is_some(), MacroKind::Switch => healthiest_other(state).is_some(),
// ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't // ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't
@ -692,7 +829,12 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
| MacroKind::BuyBall | MacroKind::BuyBall
| MacroKind::BuyAntidote | MacroKind::BuyAntidote
| MacroKind::BuyRepel => match kind.purchase() { | MacroKind::BuyRepel => match kind.purchase() {
Some((id, cost)) => affordable(state, id, cost), Some((id, cost)) => {
affordable(state, id, cost)
|| (kind == MacroKind::BuyBall
&& state.scene() == Scene::Overworld
&& !floor_ball_goals(state).is_empty())
}
// Unreachable while [`MacroKind::purchase`] covers the four arms above, and a `false` // Unreachable while [`MacroKind::purchase`] covers the four arms above, and a `false`
// rather than a panic if it ever stops: an unpriced purchase is a button off the pad. // rather than a panic if it ever stops: an unpriced purchase is a button off the pad.
None => false, None => false,
@ -999,7 +1141,9 @@ pub fn amenity_goals(state: &mut dyn MacroState, kind: Amenity) -> Vec<Aim> {
// reached and talked ledgers answer "is this job done", and for a service the answer is // reached and talked ledgers answer "is this job done", and for a service the answer is
// the party or the bag, not the ledger: a nurse reached an hour ago with a party that has // the party or the bag, not the ledger: a nurse reached an hour ago with a party that has
// since been beaten is a job to do again. // since been beaten is a job to do again.
if service_needed(state, kind) { // ...unless this counter is the one the fly has just walked to and walked away from
// ([`counter_walked_away`], row 66): then the ledgers answer, as they do for any person.
if service_needed(state, kind) && !state.counter_walked_to(here) {
return service_aims(state, kind); return service_aims(state, kind);
} }
return counter_aims(state, counter_sprite(kind)); return counter_aims(state, counter_sprite(kind));
@ -1041,6 +1185,36 @@ pub fn heal_goals(state: &mut dyn MacroState) -> Vec<Aim> {
person_aims(state, poke_sprite::NURSE, Ledgers::BlockedOnly, true) person_aims(state, poke_sprite::NURSE, Ledgers::BlockedOnly, true)
} }
/// `BUY BALL`'s walk from the floor of a mart: the tiles the clerk can be talked to from (row 66).
///
/// The operator's decision on row 66: buying a ball is one macro, modelled on `HEAL` -- walk to
/// the clerk, talk, open BUY, take the first row, answer the price box, done when the wallet says
/// it is paid. Measured with the connectome before it: `GO SHOP` walked the fly to the Viridian
/// clerk again and again and the fly never once chose `TALK` there, so the four choices in a row
/// that a purchase took (`TALK`, the greeting, `CONFIRM`, `BUY BALL`) never happened. The fly
/// still has to choose this button; it is only on the pad while it can work:
///
/// - in a mart whose first stock row is a Poké Ball ([`geography::BALL_FIRST_MARTS`]);
/// - while [`service_needed`] holds for the mart: no ball in the bag, the money for one, and no
/// Oak's parcel (the Viridian clerk's text table while it is carried sells nothing) -- and in
/// Viridian not before Oak has the parcel at all ([`MacroState::parcel_delivered`]);
/// - with the clerk reachable: the blocked window is kept, the talked and reached ledgers are not
/// (a counter is a service), and the tile already facing him is a goal (no walk at all).
///
/// Empty anywhere else, which is the other half of the precondition.
pub fn floor_ball_goals(state: &mut dyn MacroState) -> Vec<Aim> {
let Some(here) = state.player().map(|player| player.map) else { return Vec::new() };
if !geography::BALL_FIRST_MARTS.contains(&here) || !service_needed(state, Amenity::Mart) {
return Vec::new();
}
// Before the parcel is even in the bag the Viridian counter is the parcel's too: the clerk's
// script hands it over on the fly's first visit, and sells nothing until Oak has it.
if here == super::super::maps::VIRIDIAN_MART && !state.parcel_delivered() {
return Vec::new();
}
person_aims(state, poke_sprite::CLERK, Ledgers::BlockedOnly, true)
}
/// Whether the building of `kind` has something to do for the fly right now: the party needs the /// Whether the building of `kind` has something to do for the fly right now: the party needs the
/// nurse, or the bag has no ball the wallet could buy one of (row 62). /// nurse, or the bag has no ball the wallet could buy one of (row 62).
/// ///
@ -1095,7 +1269,32 @@ pub fn amenity_wanted(state: &mut dyn MacroState, kind: Amenity) -> Option<u8> {
return None; return None;
} }
let area = area_here(state)?; let area = area_here(state)?;
amenity_in_reach(state, area, kind) let map = amenity_in_reach(state, area, kind)?;
if counter_walked_away(state, map) {
return None;
}
Some(map)
}
/// Whether the fly has just stood at the counter of the building on `map`, facing it, and is now
/// outside that building: what takes the service walk toward it off the pad for the reached window
/// (row 66).
///
/// **A counter the fly walked away from is not walked back to at once.** Row 62 made a service
/// dealt again whenever the cartridge says it is needed, whatever the ledgers say, and that is a
/// ring by construction when the fly does not use the counter: live on v0.6.5 from the rung-8
/// archive, `GO SHOP` 33 times in 35 minutes, each one a walk in from the street and up to the
/// Viridian clerk, then `GO OUT` or `GO OBJECTIVE` back out of the door without a `TALK`, and
/// outside `GO SHOP` on the pad again because the bag still had no ball. Reproduced from a
/// post-parcel checkpoint of the Viridian mart with the connectome: three laps in eighteen brain
/// seconds. It is section 12.1's ledger doing what it does for every other walk -- a target
/// arrived at and faced is not re-walked for the window -- applied to the one walk row 62 took it
/// away from. The fly standing at the counter still has `TALK` (its precondition reads the
/// service, not this), the nurse's `HEAL` still walks from anywhere in the centre, and when the
/// window closes the counter is a service again.
fn counter_walked_away(state: &mut dyn MacroState, map: u8) -> bool {
let here = state.player().map(|player| player.map);
here != Some(map) && state.counter_walked_to(map)
} }
/// `area`'s building of `kind`, when the route to it from the piece of ground the fly stands on /// `area`'s building of `kind`, when the route to it from the piece of ground the fly stands on

View file

@ -269,6 +269,31 @@ pub struct TextBox {
pub waiting: bool, pub waiting: bool,
} }
/// The naming screen, while it is up (`DisplayNamingScreen`, `engine/menus/naming_screen.asm`;
/// row 69, `docs/design/macros.md` 12.32).
///
/// The keyboard the cartridge draws for a Pokémon's nickname, the Name Rater, and the player's and
/// rival's names at the start of a game. The last two are before the game timer starts and read
/// as the title (section 2), so this is only ever asked of the first two in practice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Naming {
/// Letters typed so far (`wNamingScreenNameLength`).
pub length: u8,
/// How many letters the name can hold: ten for a Pokémon, seven for the player or the rival
/// (`NAME_LENGTH - 1`, `PLAYER_NAME_LENGTH - 1`), counted from the underscores on screen.
pub capacity: u8,
/// START or ED has been taken and the name is being handed back (`wNamingScreenSubmitName`).
pub submitted: bool,
}
impl Naming {
/// Whether no further letter fits. The cartridge moves the cursor onto ED itself then
/// (`PrintNicknameAndUnderscores`), and an A press on a letter adds nothing.
pub fn full(self) -> bool {
self.length >= self.capacity
}
}
/// A menu cursor, as `HandleMenuInput` keeps it. Shared by every menu in the game. /// A menu cursor, as `HandleMenuInput` keeps it. Shared by every menu in the game.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cursor { pub struct Cursor {

View file

@ -28,16 +28,19 @@ use super::executor::{
}; };
use super::palette::{ use super::palette::{
MacroId, MacroKind, Palette, SLOTS, amenity_goals, amenity_wanted, answer_key, errand, facing_nurse, MacroId, MacroKind, Palette, SLOTS, amenity_goals, amenity_wanted, answer_key, errand, facing_nurse,
floor_ball_goals,
healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed, healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed,
listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested, listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested,
poke_sprite, precondition, throw_slot, untalked_objects, untalked_people, ways, poke_sprite, precondition, throw_slot, untalked_objects, untalked_people, ways,
NAMING_BOUND_MS, NAMING_RAW, WITHHELD_FOR_THE_THROW, ball_holds_on_hp, naming_raw, naming_set,
throw_only,
}; };
use super::path::{self, Exit, Way}; use super::path::{self, Exit, Way};
use super::super::maps; use super::super::maps;
use super::plan; use super::plan;
use super::state::{ use super::state::{
Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize,
Mon, Move, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox,
Walkable, Warp, Walkable, Warp,
}; };
@ -181,6 +184,13 @@ struct World {
/// A frame at which the cartridge heals the party, which is what a Pokémon Center does while /// A frame at which the cartridge heals the party, which is what a Pokémon Center does while
/// its text box is open (`docs/design/macros.md` section 13). /// its text box is open (`docs/design/macros.md` section 13).
heal_at: Option<u32>, heal_at: Option<u32>,
/// Oak has not been given the parcel yet (row 66); false in every fixture unless set.
parcel_undelivered: bool,
/// The naming screen, while it is up (row 69). A START press on it hands the name back and
/// closes it, as `DisplayNamingScreen.pressedStart` does.
naming: Option<Naming>,
/// A keyboard that never closes, for the bound on `CONFIRM`'s own wait.
glue_naming: bool,
/// Whether a text box is drawn on a scene that is not [`Scene::Dialog`] /// Whether a text box is drawn on a scene that is not [`Scene::Dialog`]
/// ([`MacroState::text_open`]). /// ([`MacroState::text_open`]).
/// ///
@ -302,6 +312,9 @@ impl World {
refused_items: BTreeSet::new(), refused_items: BTreeSet::new(),
switch: None, switch: None,
heal_at: None, heal_at: None,
parcel_undelivered: false,
naming: None,
glue_naming: false,
box_open: false, box_open: false,
prompt: false, prompt: false,
price_after: None, price_after: None,
@ -529,6 +542,10 @@ impl World {
} }
fn on_pulse(&mut self, mask: u8) { fn on_pulse(&mut self, mask: u8) {
// The keyboard hands the name back on START and closes (row 69), unless glued.
if mask == buttons::START && self.naming.is_some() && !self.glue_naming {
self.naming = None;
}
if self.scene == Scene::Overworld { if self.scene == Scene::Overworld {
if mask == buttons::START { if mask == buttons::START {
self.start_to_open = self.start_to_open.saturating_sub(1); self.start_to_open = self.start_to_open.saturating_sub(1);
@ -875,6 +892,18 @@ impl MacroState for World {
self.targets.reached(self.map, target) self.targets.reached(self.map, target)
} }
fn counter_walked_to(&mut self, map: u8) -> bool {
self.targets.reached(map, TargetKey::Counter)
}
fn parcel_delivered(&mut self) -> bool {
!self.parcel_undelivered
}
fn naming(&mut self) -> Option<Naming> {
self.naming
}
fn refused_here(&mut self, slot: u8) -> bool { fn refused_here(&mut self, slot: u8) -> bool {
self.targets.refused(self.map, slot, self.player) self.targets.refused(self.map, slot, self.player)
} }
@ -4879,8 +4908,8 @@ fn the_last_resort_prefers_the_exit_toward_the_objective() {
/// Section 14's `THROW BALL` (the operator: "throw pokeball should be a macro"). /// Section 14's `THROW BALL` (the operator: "throw pokeball should be a macro").
/// ///
/// The precondition is three facts and no judgement: a wild battle, a ball in the bag, and room in /// The precondition is three facts and no judgement: a wild battle, a ball in the bag, and room in
/// the party. When to throw is the fly's -- there is no catch-rate and no enemy-HP knowledge here, /// the party. There is no catch-rate and no enemy-HP knowledge in this precondition; since row 69
/// and there is none anywhere in this crate. /// the enemy's HP decides only what else is dealt beside the ball (`palette::throw_only`).
#[test] #[test]
fn throw_ball_needs_a_wild_battle_a_ball_and_room_in_the_party() { fn throw_ball_needs_a_wild_battle_a_ball_and_room_in_the_party() {
let mut world = World::battle(); let mut world = World::battle();
@ -5805,6 +5834,108 @@ fn go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one() {
assert!(!on_the_pad(&mut world, MacroKind::GoShop), "the parcel's text table, no counter"); assert!(!on_the_pad(&mut world, MacroKind::GoShop), "the parcel's text table, no counter");
} }
#[test]
fn a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window() {
// Row 66. Live on v0.6.5 from the rung-8 archive: `GO SHOP` 33 times in 35 minutes, in from
// the street to the Viridian clerk and back out of the door without a `TALK`, and `GO SHOP` on
// the street's pad again because the bag still had no ball -- row 62's "dealt again while
// needed", with no window at all.
let mut world = viridian();
world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY));
world.seen_maps.insert(maps::VIRIDIAN_MART);
assert!(on_the_pad(&mut world, MacroKind::GoShop), "no ball, and the money for one");
// A `GO SHOP` has just stood the fly at that counter; it walked back out.
world.targets.record_reached(maps::VIRIDIAN_MART, TargetKey::Counter);
assert!(!on_the_pad(&mut world, MacroKind::GoShop), "not straight back in: {:?}", pad_of(&mut world));
assert_eq!(amenity_wanted(&mut world, Amenity::Mart), None);
// The window closes and the counter is a service again.
world.targets.clock(BLOCKED_MINUTES_DEFAULT * 60_000.0 + 1.0);
assert!(on_the_pad(&mut world, MacroKind::GoShop), "after the window");
// Inside, inside the window: no walk back to the counter, and at the counter its press.
let mut mart = World::mart();
mart.targets.record_reached(mart.map, TargetKey::Counter);
mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1)));
assert!(service_needed(&mut mart, Amenity::Mart));
assert!(!on_the_pad(&mut mart, MacroKind::GoShop), "{:?}", pad_of(&mut mart));
mart.player = Tile::new(2, 5);
mart.facing = Facing::Left;
assert!(on_the_pad(&mut mart, MacroKind::Talk), "the counter still opens where the fly stands");
// Only the counter: another person reached in the building is not the counter.
let mut mart = World::mart();
mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1)));
assert!(on_the_pad(&mut mart, MacroKind::GoShop), "row 62's rule stands without a counter visit");
}
#[test]
fn buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought() {
// Row 66, the operator's decision: buying a ball is one button, modelled on `HEAL`.
let mut mart = World::mart();
assert_eq!(mart.scene, Scene::Overworld);
assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "no ball, 3000, the clerk: {:?}", pad_of(&mut mart));
assert!(!floor_ball_goals(&mut mart).is_empty());
// Facing the clerk already: still offered, with no walk (the tile he is faced from is a goal).
mart.player = Tile::new(2, 5);
mart.facing = Facing::Left;
assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "at the counter");
mart.player = Tile::new(3, 6);
// A ball in the bag: nothing to buy it for.
mart.bag = vec![(item::POKE_BALL, 1)];
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "a ball already");
mart.bag = vec![(item::GREAT_BALL, 1)];
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "any ball counts");
mart.bag = Vec::new();
// Under a ball's price.
mart.money = price::POKE_BALL - 1;
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "199");
mart.money = price::POKE_BALL;
assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "200");
// Oak's parcel: the Viridian clerk's text table is the parcel's and he sells nothing.
mart.bag = vec![(item::OAKS_PARCEL, 1)];
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "carrying the parcel");
mart.bag = Vec::new();
// ...or before the clerk has even handed it over: nothing to buy until Oak has it.
mart.parcel_undelivered = true;
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "before the parcel");
mart.parcel_undelivered = false;
// The talked and reached ledgers do not retire a counter; the blocked window does.
mart.talked.insert(TalkTarget::Sprite(1));
mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1)));
mart.targets.record_reached(mart.map, TargetKey::Counter);
assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "talked, reached, walked away: still a service");
mart.targets.record_blocked(mart.map, TargetKey::Thing(TalkTarget::Sprite(1)));
assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "a clerk no walk reaches");
// Only in a mart whose first row is a ball, and never outside one.
let mut pewter = World::mart();
pewter.map = maps::PEWTER_MART;
assert!(on_the_pad(&mut pewter, MacroKind::BuyBall), "Pewter's first row is a ball");
let mut street = viridian();
street.money = 3_000;
assert!(!on_the_pad(&mut street, MacroKind::BuyBall), "not from the street");
let mut elsewhere = World::mart();
elsewhere.map = maps::OAKS_LAB;
assert!(floor_ball_goals(&mut elsewhere).is_empty(), "not a mart");
// The open counter keeps its own rule: the greeting is no screen a purchase starts from.
let mut counter = World::mart();
counter.scene = Scene::Shop;
counter.list = List::Shop(ShopScreen::Talking);
counter.stock = vec![item::POKE_BALL];
assert!(!precondition(MacroKind::BuyBall, &mut counter), "the clerk is still talking");
counter.list = List::Shop(ShopScreen::BuySellQuit);
counter.cursor_max = 2;
assert!(precondition(MacroKind::BuyBall, &mut counter), "BUY / SELL / QUIT");
}
#[test] #[test]
fn heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her() { fn heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her() {
// Row 62. `HEAL`'s goals were `counter_aims`, which drops the tile the fly already faces her // Row 62. `HEAL`'s goals were `counter_aims`, which drops the tile the fly already faces her
@ -6274,3 +6405,213 @@ fn a_same_map_teleport_is_somewhere_the_way_out_took_the_fly() {
dead.duds = world.duds.clone(); dead.duds = world.duds.clone();
assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked));
} }
// ---------------------------------------------------------------------------------------------
// Row 69 (the operator, 2026-09-29): "throw on low HP only" and "let the fly name it".
// ---------------------------------------------------------------------------------------------
fn pad_kinds(world: &mut World) -> Vec<MacroKind> {
let scene = world.scene();
plan::plan_for(scene, world).slots.iter().flatten().map(|spec| spec.kind).collect()
}
/// `ItemUseBall`'s HP half, number for number (`engine/items/item_effects.asm`):
/// `W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, the ball holds on HP when `W >= 255`.
#[test]
fn row69_low_is_where_the_balls_hp_factor_is_at_its_best() {
// A Weedle's 20: 20 * 255 / 12 = 425; HP 7 -> 425 / 1 = 425, HP 8 -> 425 / 2 = 212.
assert!(ball_holds_on_hp(7, 20, item::POKE_BALL));
assert!(!ball_holds_on_hp(8, 20, item::POKE_BALL));
assert!(ball_holds_on_hp(1, 20, item::POKE_BALL));
// A Great Ball's factor is 8: 20 * 255 / 8 = 637; HP 11 -> 637 / 2 = 318, HP 12 -> 212.
assert!(ball_holds_on_hp(11, 20, item::GREAT_BALL));
assert!(!ball_holds_on_hp(12, 20, item::GREAT_BALL));
// Every other ball reads with 12, as the cartridge's does.
assert!(!ball_holds_on_hp(8, 20, item::ULTRA_BALL));
// A third, near enough, at any size: 120 * 255 / 12 = 2550; HP 40 -> 2550 / 10 = 255.
assert!(ball_holds_on_hp(40, 120, item::POKE_BALL));
assert!(!ball_holds_on_hp(44, 120, item::POKE_BALL));
// Fainted, full, or nothing read: never.
assert!(!ball_holds_on_hp(0, 20, item::POKE_BALL));
assert!(!ball_holds_on_hp(20, 20, item::POKE_BALL));
assert!(!ball_holds_on_hp(5, 0, item::POKE_BALL));
}
/// The throw's turn: a wild battle, a ball `THROW BALL` would throw, an enemy at low HP. Then the
/// ball is the only attack-side button; above it the pad is the ordinary one.
#[test]
fn row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack() {
let mut world = World::battle();
world.mons.truncate(1);
world.mons[0].hp = 20;
world.bag = vec![(item::POKE_BALL, 2)];
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 });
// Full HP: the ordinary pad, moves and the ball side by side.
assert!(!throw_only(&mut world));
let pad = pad_kinds(&mut world);
assert!(pad.contains(&MacroKind::Move1) && pad.contains(&MacroKind::ThrowBall), "{pad:?}");
// Low HP: the ball alone.
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 7, max_hp: 20 });
assert!(throw_only(&mut world));
assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]);
for kind in WITHHELD_FOR_THE_THROW {
assert!(!on_the_pad(&mut world, kind), "{} withheld", kind.name());
}
}
/// `ITEM` stays beside the ball: a hurt Pokémon out with a Potion the cartridge would take is the
/// one non-attack need kept. `SWITCH` and `RUN` go.
#[test]
fn row69_the_throws_pad_keeps_a_potion_for_a_hurt_thrower_and_nothing_else() {
let mut world = World::battle();
// The Pokémon out is at 4 of 20 with a healthy reserve: SWITCH, RUN (losing) and ITEM are all
// dealt on the ordinary pad.
world.bag = vec![(item::POTION, 1), (item::POKE_BALL, 1)];
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 });
let ordinary = pad_kinds(&mut world);
assert!(ordinary.contains(&MacroKind::Switch), "{ordinary:?}");
assert!(ordinary.contains(&MacroKind::Item), "{ordinary:?}");
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 3, max_hp: 20 });
let pad = pad_kinds(&mut world);
assert_eq!(pad, vec![MacroKind::Item, MacroKind::ThrowBall]);
}
/// Every way out of the rule returns the ordinary pad: a trainer's Pokémon, no ball left, a
/// species the party holds, a full party, a fainted enemy, nothing read.
#[test]
fn row69_the_ordinary_pad_comes_back_whenever_the_ball_cannot_be_thrown() {
let low = Some(EnemyMon { species: 0x70, level: 6, hp: 2, max_hp: 20 });
let base = || {
let mut world = World::battle();
world.mons.truncate(1);
world.mons[0].hp = 20;
world.bag = vec![(item::POKE_BALL, 1)];
world.enemy = low;
world
};
let mut world = base();
assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]);
let mut trainer = base();
trainer.battle = Some((BattleKind::Trainer, true, false));
assert!(!throw_only(&mut trainer));
assert!(on_the_pad(&mut trainer, MacroKind::Move1), "a trainer's battle is never the throw's");
let mut spent = base();
spent.bag = vec![(item::POKE_BALL, 0)];
assert!(!throw_only(&mut spent));
assert!(on_the_pad(&mut spent, MacroKind::Move1), "no ball, the moves are back");
let mut owned = base();
owned.mons[0].species = 0x70;
assert!(!throw_only(&mut owned));
assert!(on_the_pad(&mut owned, MacroKind::Move1), "a species already caught");
let mut full = base();
full.mons = (0..6).map(|slot| mon(slot, 20, 20, &[(33, 30)])).collect();
full.active = Some(0);
assert!(!throw_only(&mut full));
let mut fainted = base();
fainted.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 0, max_hp: 20 });
assert!(!throw_only(&mut fainted));
let mut unread = base();
unread.enemy = None;
assert!(!throw_only(&mut unread), "HP the seam cannot read is not low");
assert!(on_the_pad(&mut unread, MacroKind::Move1));
}
/// In the bag, the throw's pad is the ball (and a Potion for a hurt thrower); `BACK` would lead to
/// the menu whose pad is the same ball.
#[test]
fn row69_in_the_bag_at_low_hp_back_is_withheld() {
let mut world = World::battle();
world.mons.truncate(1);
world.mons[0].hp = 20;
world.bag = vec![(item::POKE_BALL, 1)];
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 });
world.list = List::BattleBag;
world.cursor_max = 1;
world.grid = false;
assert!(on_the_pad(&mut world, MacroKind::Back));
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 5, max_hp: 20 });
assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]);
}
/// A failed throw is an ordinary turn: the pad between turns is `NEXT` and the next own turn is
/// the throw's again while a ball is left. Nothing here keeps a count.
#[test]
fn row69_between_turns_the_pad_is_next_whatever_the_hp() {
let mut world = World::battle();
world.bag = vec![(item::POKE_BALL, 1)];
world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 2, max_hp: 20 });
world.scene = Scene::Battle { own_turn: false, forced_switch: false };
world.list = List::None;
assert_eq!(pad_kinds(&mut world), vec![MacroKind::Next]);
}
fn keyboard(length: u8, capacity: u8) -> Naming {
Naming { length, capacity, submitted: false }
}
/// The naming screen's pad: nothing bound while the fly spells (its raw buttons are the pad),
/// `CONFIRM` alone once the name is full or the bound has run.
#[test]
fn row69_the_keyboard_is_the_flys_own_buttons_until_the_name_is_full_or_the_bound_runs() {
assert!(naming_set(keyboard(0, 10), 0.0).is_empty());
assert!(naming_set(keyboard(9, 10), NAMING_BOUND_MS - 1.0).is_empty());
assert_eq!(naming_set(keyboard(10, 10), 0.0), vec![MacroKind::Confirm], "full");
assert_eq!(naming_set(keyboard(7, 7), 0.0), vec![MacroKind::Confirm], "a player's seven");
assert_eq!(naming_set(keyboard(3, 10), NAMING_BOUND_MS), vec![MacroKind::Confirm], "bound");
let spelling = Palette::for_naming(Scene::Unknown, keyboard(2, 10), 1_000.0);
assert_eq!(spelling.bound(), 0);
assert_eq!(naming_raw(&spelling), NAMING_RAW);
assert_eq!(
NAMING_RAW,
buttons::UP | buttons::DOWN | buttons::LEFT | buttons::RIGHT | buttons::A | buttons::B
| buttons::START,
"the D-pad, A, B and START; not SELECT"
);
let ending = Palette::for_naming(Scene::Unknown, keyboard(2, 10), NAMING_BOUND_MS);
assert_eq!(ending.bound(), 1);
assert_eq!(naming_raw(&ending), 0, "once CONFIRM is dealt the raw buttons are off");
// The dealer without a clock: the same screen reads as the fly's own buttons, and the plain
// `Unknown` pad (`NEXT`, `BACK`) is not dealt on it.
let mut world = World::room();
world.scene = Scene::Unknown;
world.box_open = true;
assert_eq!(pad_kinds(&mut world), vec![MacroKind::Next, MacroKind::Back]);
world.naming = Some(keyboard(1, 10));
assert!(pad_kinds(&mut world).is_empty());
world.naming = Some(keyboard(10, 10));
assert_eq!(pad_kinds(&mut world), vec![MacroKind::Confirm]);
}
/// `CONFIRM` on the keyboard hands the name back with START and is done when the screen is gone.
#[test]
fn row69_confirm_on_the_keyboard_presses_start_until_it_closes() {
let mut world = World::room();
world.scene = Scene::Unknown;
world.naming = Some(keyboard(10, 10));
assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Done);
assert!(world.naming.is_none());
assert!(world.pulses.contains(&buttons::START), "{:?}", world.pulses);
assert!(!world.pulses.contains(&buttons::A), "not the A that types a letter");
}
/// And a keyboard that never closes is `blocked`, not a macro that holds the pad for ever.
#[test]
fn row69_confirm_on_a_keyboard_that_does_not_close_is_blocked() {
let mut world = World::room();
world.scene = Scene::Unknown;
world.naming = Some(keyboard(10, 10));
world.glue_naming = true;
assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Blocked);
}

View file

@ -1,4 +1,4 @@
//! The Pokémon Red reward adapter, `pokered-unique8-v7`. //! The Pokémon Red reward adapter, `pokered-unique8-v8`.
//! //!
//! A port of the prototype's `src/reward/pokemon-red.ts`. The gates and budgets //! A port of the prototype's `src/reward/pokemon-red.ts`. The gates and budgets
//! are unchanged; `docs/rewards-learning.md` holds the live rule table and the //! are unchanged; `docs/rewards-learning.md` holds the live rule table and the
@ -8,9 +8,11 @@
//! next to and the first step onto each of a map's exits; v6 adds `catch`, the //! next to and the first step onto each of a map's exits; v6 adds `catch`, the
//! operator's decision of 2026-09-22, which pays for keeping a wild Pokémon; v7 adds //! operator's decision of 2026-09-22, which pays for keeping a wild Pokémon; v7 adds
//! `talk` and `item` and stops `boundary` paying indoors, the operator's decision of //! `talk` and `item` and stops `boundary` paying indoors, the operator's decision of
//! 2026-09-23 to pay for engaging with a building rather than for leaving it. //! 2026-09-23 to pay for engaging with a building rather than for leaving it; v8 adds `damage`,
//! the operator's decision of 2026-09-29 to pay for the HP the fly's own attack removes.
pub mod catalog; pub mod catalog;
pub mod damage;
pub mod engage; pub mod engage;
#[cfg(test)] #[cfg(test)]
pub(crate) mod fake_wram; pub(crate) mod fake_wram;
@ -36,7 +38,15 @@ use symbols::ram;
/// Adapter version, pinned into the checkpoint compatibility string. /// Adapter version, pinned into the checkpoint compatibility string.
/// ///
/// `v7` is the engagement rules: `talk` and `item` pay, and `boundary` stops paying on an /// `v8` is the damage rule (the operator, 2026-09-29): HP the fly's own attack removes from the
/// Pokémon it is fighting pays, in proportion, within a per-battle cap ([`damage`]). A `v7`
/// checkpoint is refused by default and resumed only when the operator names it in
/// `FLY_ACCEPT_ADAPTERS`, like every migration before it. `v7`'s state is a `v8` state with no
/// `damageCounts` (no wild key has paid damage) and, for a battle in flight, no per-battle damage
/// state: that battle marks each enemy Pokémon at the HP it has when first read, so nothing lost
/// before the restore is paid ([`damage::BattleDamage::restored`]).
///
/// `v7` was the engagement rules: `talk` and `item` pay, and `boundary` stops paying on an
/// indoor map (the operator, 2026-09-23). Bumping it is what makes a `v6` checkpoint a /// indoor map (the operator, 2026-09-23). Bumping it is what makes a `v6` checkpoint a
/// decision rather than an accident: the compatibility string is compared whole before a /// decision rather than an accident: the compatibility string is compared whole before a
/// restore is attempted, so a `v6` run is refused by default and resumed only when the /// restore is attempted, so a `v6` run is refused by default and resumed only when the
@ -53,11 +63,17 @@ use symbols::ram;
/// that meant "4 badges" on the old ladder is not a rung on the new one. Neither of /// that meant "4 badges" on the old ladder is not a rung on the new one. Neither of
/// those is a migration; the last two are, because nothing an older ledger holds means /// those is a migration; the last two are, because nothing an older ledger holds means
/// something different under the newer rules.) /// something different under the newer rules.)
pub const REWARD_ADAPTER: &str = "pokered-unique8-v7"; pub const REWARD_ADAPTER: &str = "pokered-unique8-v8";
/// Adapter ids whose checkpoints `v7` can read. /// Adapter ids whose checkpoints `v8` can read.
/// ///
/// Exactly one, and it is one because the engagement rules add ledger keys and change nothing /// `v7`, the live run's, by the migration [`REWARD_ADAPTER`] describes. And still `v6`: the
/// chain composes, because nothing in `v8` reads a key `v7` wrote that a `v6` state lacks other
/// than the ones `v7`'s own migration already handles in this build -- the item seed runs on the
/// first sample that finds `items:seeded` absent, and the damage state starts empty either way.
/// `compat_migration.rs` restores a `v6` envelope and a `v7` envelope under this build.
///
/// (For `v7` the list was `v6` alone, and the reason it was one:) the engagement rules add ledger keys and change nothing
/// else a `v6` state holds: every field keeps its name, shape and meaning, the `talk:` keys start /// else a `v6` state holds: every field keeps its name, shape and meaning, the `talk:` keys start
/// empty (no conversation was ever paid), and the `item:`/`hidden:` keys are seeded from the /// empty (no conversation was ever paid), and the `item:`/`hidden:` keys are seeded from the
/// game's own flags on the first sample, so no pickup made under `v6` pays when a rollback /// game's own flags on the first sample, so no pickup made under `v6` pays when a rollback
@ -68,7 +84,7 @@ pub const REWARD_ADAPTER: &str = "pokered-unique8-v7";
/// ///
/// Listing an id here is necessary but not sufficient: `FLY_ACCEPT_ADAPTERS` must name it too /// Listing an id here is necessary but not sufficient: `FLY_ACCEPT_ADAPTERS` must name it too
/// (`crate::compatibility::decide`, `docs/design/flysim.md`). /// (`crate::compatibility::decide`, `docs/design/flysim.md`).
pub const MIGRATES_FROM: &[&str] = &["pokered-unique8-v6"]; pub const MIGRATES_FROM: &[&str] = &["pokered-unique8-v7", "pokered-unique8-v6"];
/// The only cartridge semantic rewards are enabled for. Even the canonical /// The only cartridge semantic rewards are enabled for. Even the canonical
/// pret build stays disabled until reviewed; see `docs/rewards-learning.md`. /// pret build stays disabled until reviewed; see `docs/rewards-learning.md`.
@ -102,6 +118,11 @@ pub const SUPPORTED_ROM: &str =
/// *Not* bumped for the engagement rules either. `talk` and `item` key their payouts into the /// *Not* bumped for the engagement rules either. `talk` and `item` key their payouts into the
/// existing `seen` array, the way `boundary` did, and the item seed is marked there too /// existing `seen` array, the way `boundary` did, and the item seed is marked there too
/// ([`ITEMS_SEEDED`]); a `v6` state is structurally a `v7` state with none of those keys. /// ([`ITEMS_SEEDED`]); a `v6` state is structurally a `v7` state with none of those keys.
///
/// *Not* bumped for the damage rule. It adds one optional counter, `damageCounts`, and one
/// optional object inside a battle in flight, `battle.damage`; a `v7` state without them restores
/// with the counter empty and the battle marked where it stands, which is the truth about a run
/// that was never paid for damage.
pub const STATE_VERSION: u64 = 4; pub const STATE_VERSION: u64 = 4;
/// The `seen` key that says the item keys have been seeded from the cartridge's flags. /// The `seen` key that says the item keys have been seeded from the cartridge's flags.
@ -374,7 +395,7 @@ fn rung_place(seen: &OrderedSet, rung: usize) -> Option<MapPlace> {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq)]
struct Battle { struct Battle {
key: String, key: String,
wild: bool, wild: bool,
@ -400,6 +421,8 @@ struct Battle {
/// Whether that catch was a species this run had never owned, decided on the frame /// Whether that catch was a species this run had never owned, decided on the frame
/// the capture was observed. /// the capture was observed.
captured_new: bool, captured_new: bool,
/// The damage rule's marks and what this battle has paid ([`damage::BattleDamage`]).
damage: damage::BattleDamage,
} }
/// Immutable per-sample byte cache. Each address requested during one sample /// Immutable per-sample byte cache. Each address requested during one sample
@ -449,6 +472,9 @@ pub struct PokemonRedReward {
/// string. The one field `v6` adds to the checkpoint; absent in a `v5` state, which /// string. The one field `v6` adds to the checkpoint; absent in a `v5` state, which
/// reads as every species at zero. /// reads as every species at zero.
catch_counts: BTreeMap<String, u64>, catch_counts: BTreeMap<String, u64>,
/// Wild battles that paid damage, per wild key (`map:species:level`, the wild-KO rule's). The
/// one field `v8` adds to the checkpoint; absent in a `v7` state, which reads as none.
damage_counts: BTreeMap<String, u64>,
replay_blocked: OrderedSet, replay_blocked: OrderedSet,
counts: Counts, counts: Counts,
total: f64, total: f64,
@ -507,6 +533,7 @@ impl PokemonRedReward {
tile_counts: BTreeMap::new(), tile_counts: BTreeMap::new(),
wild_wins: BTreeMap::new(), wild_wins: BTreeMap::new(),
catch_counts: BTreeMap::new(), catch_counts: BTreeMap::new(),
damage_counts: BTreeMap::new(),
replay_blocked: OrderedSet::new(), replay_blocked: OrderedSet::new(),
counts: Counts::default(), counts: Counts::default(),
total: 0.0, total: 0.0,
@ -676,6 +703,10 @@ impl PokemonRedReward {
for species in caught { for species in caught {
self.replay_blocked.insert(&format!("catch:{species}")); self.replay_blocked.insert(&format!("catch:{species}"));
} }
let damaged: Vec<String> = self.damage_counts.keys().cloned().collect();
for key in damaged {
self.replay_blocked.insert(&format!("damage:{key}"));
}
} }
/// Sample WRAM after one completed frame and return this frame's payouts. /// Sample WRAM after one completed frame and return this frame's payouts.
@ -800,6 +831,7 @@ impl PokemonRedReward {
species_at_start: Some(species_paid), species_at_start: Some(species_paid),
captured: None, captured: None,
captured_new: false, captured_new: false,
damage: damage::BattleDamage::default(),
}); });
} }
// The cartridge's own answer to "was one caught": `ram/wram.asm`'s comment on // The cartridge's own answer to "was one caught": `ram/wram.asm`'s comment on
@ -831,6 +863,9 @@ impl PokemonRedReward {
battle.species_at_start.is_some_and(|before| species_paid > before); battle.species_at_start.is_some_and(|before| species_paid > before);
} }
} }
if in_battle != 255 {
self.damage(&mut emitted, memory, in_battle == 2, brain_ms);
}
} else if in_battle == 0 { } else if in_battle == 0 {
self.mode = "OVERWORLD".to_string(); self.mode = "OVERWORLD".to_string();
if let Some(battle) = self.battle.take() { if let Some(battle) = self.battle.take() {
@ -985,6 +1020,39 @@ impl PokemonRedReward {
emitted emitted
} }
/// The damage rule (`docs/rewards-learning.md`, the operator 2026-09-29): pay for the HP the
/// fly's own attack removed from the enemy on this sample. [`damage`] says what counts.
fn damage(
&mut self,
emitted: &mut Vec<RewardEvent>,
memory: &mut impl MemoryReader,
trainer: bool,
brain_ms: f64,
) {
let Some(reading) = damage::Reading::read(memory) else { return };
let Some(battle) = self.battle.as_mut() else { return };
let Some(hit) = battle.damage.observe(reading) else { return };
let key = battle.key.clone();
let count = self.damage_counts.get(&key).copied().unwrap_or(0);
let blocked = self.replay_blocked.contains(&format!("damage:{key}"));
let (_, counted) = battle.damage.decide_scale(trainer, (count, blocked));
let value = catalog::rule(kind::DAMAGE).expect("the damage rule is in the catalog").value;
let amount = battle.damage.pay(hit, value, trainer);
if counted {
self.damage_counts.insert(key, (count + 1).min(damage::MAX_WILD_BATTLES));
}
if amount > 0.0 {
let knocked_out = if hit.knocked_out { " KO" } else { "" };
self.emit_amount(
emitted,
kind::DAMAGE,
format!("HIT #{} FOR {} HP{knocked_out}", hit.target.species, hit.removed),
amount,
brain_ms,
);
}
}
fn emit( fn emit(
&mut self, &mut self,
emitted: &mut Vec<RewardEvent>, emitted: &mut Vec<RewardEvent>,
@ -1220,6 +1288,8 @@ impl PokemonRedReward {
// empty, which is the documented v5 -> v6 migration and the truth about a run // empty, which is the documented v5 -> v6 migration and the truth about a run
// that was never paid for a catch. // that was never paid for a catch.
"catchCounts": self.catch_counts, "catchCounts": self.catch_counts,
// The one field v8 adds, absent in a v7 state for the same reason.
"damageCounts": self.damage_counts,
"replayBlocked": self.replay_blocked.as_slice(), "replayBlocked": self.replay_blocked.as_slice(),
"counts": self.counts, "counts": self.counts,
"total": self.total, "total": self.total,
@ -1243,6 +1313,7 @@ impl PokemonRedReward {
"speciesAtStart": battle.species_at_start, "speciesAtStart": battle.species_at_start,
"captured": battle.captured, "captured": battle.captured,
"capturedNew": battle.captured_new, "capturedNew": battle.captured_new,
"damage": battle.damage.to_json(),
})), })),
"mode": self.mode, "mode": self.mode,
}) })
@ -1295,6 +1366,11 @@ impl PokemonRedReward {
None | Some(Value::Null) => BTreeMap::new(), None | Some(Value::Null) => BTreeMap::new(),
Some(value) => counted_record(Some(value)).ok_or(BAD_CHECKPOINT)?, Some(value) => counted_record(Some(value)).ok_or(BAD_CHECKPOINT)?,
}; };
// Absent in every v7 state: no wild key has paid damage, because the rule did not exist.
let damage_counts = match input.get("damageCounts") {
None | Some(Value::Null) => BTreeMap::new(),
Some(value) => counted_record(Some(value)).ok_or(BAD_CHECKPOINT)?,
};
let recent = recent_raw let recent = recent_raw
.iter() .iter()
@ -1330,6 +1406,12 @@ impl PokemonRedReward {
.get("capturedNew") .get("capturedNew")
.and_then(Value::as_bool) .and_then(Value::as_bool)
.unwrap_or(false), .unwrap_or(false),
// v8's. A v7 battle has none, and marks each enemy Pokémon at the HP it reads
// next rather than paying for HP lost before the restore.
damage: match value.get("damage") {
None | Some(Value::Null) => damage::BattleDamage::restored(),
Some(state) => damage::BattleDamage::from_json(state).ok_or(BAD_HISTORY)?,
},
}), }),
}; };
let replay_blocked = match input.get("replayBlocked") { let replay_blocked = match input.get("replayBlocked") {
@ -1356,6 +1438,7 @@ impl PokemonRedReward {
self.tile_counts = tile_counts; self.tile_counts = tile_counts;
self.wild_wins = wild_wins_raw; self.wild_wins = wild_wins_raw;
self.catch_counts = catch_counts; self.catch_counts = catch_counts;
self.damage_counts = damage_counts;
self.replay_blocked = replay_blocked.iter().map(String::as_str).collect(); self.replay_blocked = replay_blocked.iter().map(String::as_str).collect();
self.counts = Counts::default(); self.counts = Counts::default();
for (key, count) in &counts_raw { for (key, count) in &counts_raw {

View file

@ -30,7 +30,9 @@ use super::symbols::ram;
/// The order of the tests is the contract: /// The order of the tests is the contract:
/// ///
/// 1. **Not started** — `wStatusFlags6`'s game-timer bit is clear, so the cartridge is on the /// 1. **Not started** — `wStatusFlags6`'s game-timer bit is clear, so the cartridge is on the
/// title, in the intro or on a naming screen: [`Scene::Title`]. /// title, in the intro or on a naming screen: [`Scene::Title`]. After it, **the naming
/// screen** once the game has started -- the keyboard, in or out of a battle -- is
/// [`Scene::Unknown`], whose pad the palette deals from [`state::naming_screen`] (row 69).
/// 2. **Not readable** — the map header or the party count is outside its range, which is what a /// 2. **Not readable** — the map header or the party count is outside its range, which is what a
/// frame in the middle of a load or a warp looks like: [`Scene::Unknown`]. /// frame in the middle of a load or a warp looks like: [`Scene::Unknown`].
/// 3. **Battle** — `wIsInBattle` says a wild or trainer battle is running: /// 3. **Battle** — `wIsInBattle` says a wild or trainer battle is running:
@ -47,6 +49,13 @@ pub fn detect(memory: &mut dyn MemoryReader) -> Scene {
if !state::started(memory) { if !state::started(memory) {
return Scene::Title; return Scene::Title;
} }
// The naming screen (row 69) before the battle test: a nickname is typed with `wIsInBattle`
// still set, and the keyboard is no battle menu. It has no scene of its own on the feed's
// closed set; it is the `Unknown` that 13.1 already listed it under, and its pad is the fly's
// own buttons (`docs/design/macros.md` 12.32).
if state::naming_screen(memory).is_some() {
return Scene::Unknown;
}
if state::map_size(memory).is_none() || memory.read8(ram::wPartyCount) > 6 { if state::map_size(memory).is_none() || memory.read8(ram::wPartyCount) > 6 {
return Scene::Unknown; return Scene::Unknown;
} }

View file

@ -33,7 +33,7 @@ use super::macros::geography::Amenity;
use super::mapgrid::{self, MapGrids}; use super::mapgrid::{self, MapGrids};
use super::macros::state::{ use super::macros::state::{
BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState,
MapGrid, MapSize, Mon, Move, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu,
Status, TextBox, Walkable, Warp, Status, TextBox, Walkable, Warp,
}; };
use super::symbols::ram; use super::symbols::ram;
@ -50,6 +50,17 @@ pub mod poke {
/// reads it back from there (row 63, `docs/design/macros.md` 12.27). /// reads it back from there (row 63, `docs/design/macros.md` 12.27).
pub const H_JOY_LAST: u16 = 0xffb1; pub const H_JOY_LAST: u16 = 0xffb1;
/// `ram/hram.asm`: `hWhoseTurn`, "0 on player's turn, 1 on enemy's turn". Counted from the
/// `hJoyLast` anchor above through the declarations that follow it (each `UNION` at its
/// largest member) to `$FFF3`; the section's remaining nine bytes then end at `$FFFE`, the
/// last byte of HRAM, which is the check that the count is right. It is the classic
/// `H_WHOSETURN`. The battle engine writes it before each side acts (`MainInBattleLoop`,
/// `ExecutePlayerMove`), and `HandlePoisonBurnLeechSeed` reads it to pick whose HP to cut, so
/// the enemy's poison, burn and Leech Seed ticks all land while it reads 1. Read by the damage
/// reward (`docs/rewards-learning.md`) and pinned on the cartridge by
/// `tests/rom_damage.rs`, which reads 0 on the frame BUBBLE lands.
pub const H_WHOSE_TURN: u16 = 0xfff3;
pub mod pad { pub mod pad {
pub const A: u8 = 1 << 0; pub const A: u8 = 1 << 0;
pub const B: u8 = 1 << 1; pub const B: u8 = 1 << 1;
@ -119,11 +130,39 @@ pub mod poke {
/// four tall, then writes a horizontal run over its top-left corner and a `┘` over (10, 12). /// four tall, then writes a horizontal run over its top-left corner and a `┘` over (10, 12).
/// Values rather than symbols, like `YES_NO_BOX`: this is a figure on screen, not a byte. /// Values rather than symbols, like `YES_NO_BOX`: this is a figure on screen, not a byte.
pub const MOVE_LIST_BOX: (u16, u16, u16, u16) = (4, 12, 19, 17); pub const MOVE_LIST_BOX: (u16, u16, u16, u16) = (4, 12, 19, 17);
/// The bag's own box in a battle (row 66): `DisplayListMenuID` draws a `TextBoxBorder` at
/// (4, 2), nine rows by fourteen, so its corners are (4, 2) and (19, 12). Surveyed on the
/// cartridge: whole on every frame the list is up, gone on the frame it closes.
pub const ITEM_LIST_BOX: (u16, u16, u16, u16) = (4, 2, 19, 12);
pub const MOVE_LIST_JOIN: u16 = 10; pub const MOVE_LIST_JOIN: u16 = 10;
/// Where `MoveSelectionMenu` parks the shared cursor: row 12, column 5. /// Where `MoveSelectionMenu` parks the shared cursor: row 12, column 5.
pub const MOVE_LIST_CURSOR_Y: u8 = 12; pub const MOVE_LIST_CURSOR_Y: u8 = 12;
pub const MOVE_LIST_CURSOR_X: u8 = 5; pub const MOVE_LIST_CURSOR_X: u8 = 5;
/// The naming screen (row 69, `engine/menus/naming_screen.asm`).
///
/// `wNamingScreenNameLength` and `wNamingScreenSubmitName` are two consecutive bytes in a
/// `UNION` of `ram/wram.asm` and are not in the reviewed address list, so they are pinned the
/// way `H_JOY_LAST` is: read from the operands of the cartridge's own instructions and checked
/// by the ROM-gated test. `PrintNicknameAndUnderscores` opens `call CalcStringLength / ld a, c
/// / ld [wNamingScreenNameLength], a / hlcoord 10, 2`, whose store is `$CEE9`, and
/// `DisplayNamingScreen.pressedStart` is `ld a, 1 / ld [wNamingScreenSubmitName], a / ret`,
/// whose store is `$CEEA`, the next byte.
pub const NAMING_LENGTH: u16 = 0xcee9;
pub const NAMING_SUBMIT: u16 = 0xceea;
/// `DisplayNamingScreen`'s box: `TextBoxBorder` at (0, 4), nine rows by eighteen, so its
/// corners are (0, 4) and (19, 14). The keyboard is inside it.
pub const NAMING_BOX: (u16, u16, u16, u16) = (0, 4, 19, 14);
/// Where the underscores under the name start (`hlcoord 10, 3`), and their two tiles: `$76`
/// for an empty place and `$77` for the raised one under the next letter.
pub const NAMING_UNDERSCORES: (u16, u16) = (10, 3);
pub const NAMING_UNDERSCORE: u8 = 0x76;
pub const NAMING_UNDERSCORE_RAISED: u8 = 0x77;
/// The keyboard's menu: `wTopMenuItemY` 3, `wMaxMenuItem` 7 and every key watched (`$ff`),
/// written once by `DisplayNamingScreen` and by nothing else in the game in that combination.
pub const NAMING_TOP_Y: u8 = 3;
pub const NAMING_MAX_ITEM: u8 = 7;
/// `constants/ram_constants.asm`: `wMiscFlags` bit 3. /// `constants/ram_constants.asm`: `wMiscFlags` bit 3.
pub const BIT_USING_GENERIC_PC: u8 = 1 << 3; pub const BIT_USING_GENERIC_PC: u8 = 1 << 3;
/// `wFontLoaded` bit 0. /// `wFontLoaded` bit 0.
@ -257,6 +296,10 @@ pub mod poke {
pub const ROW_BYTES: u16 = 6; pub const ROW_BYTES: u16 = 6;
/// `constants/move_constants.asm`: `NUM_ATTACKS`, `STRUGGLE` (`$a5`) the last. /// `constants/move_constants.asm`: `NUM_ATTACKS`, `STRUGGLE` (`$a5`) the last.
pub const LAST_MOVE: u8 = 0xa5; pub const LAST_MOVE: u8 = 0xa5;
/// The same constant under its own name: the move the cartridge executes for a
/// Pokémon whose moves have no PP left (`ExecutePlayerMove`'s caller, `MoveSelectionMenu`'s
/// "has no moves left!"). The damage reward does not pay for it: the fly did not choose it.
pub const STRUGGLE: u8 = 0xa5;
/// `constants/move_effect_constants.asm`: the stat-stage effects, each run in stage /// `constants/move_effect_constants.asm`: the stat-stage effects, each run in stage
/// order ATTACK, DEFENSE, SPEED, SPECIAL, ACCURACY, EVASION. /// order ATTACK, DEFENSE, SPEED, SPECIAL, ACCURACY, EVASION.
@ -631,12 +674,19 @@ pub fn battle(memory: &mut dyn MemoryReader) -> Option<Battle> {
BattleMenu::Moves { cursor: slot, count } BattleMenu::Moves { cursor: slot, count }
} else if party_list(memory) { } else if party_list(memory) {
BattleMenu::Party { cursor: cursor.current } BattleMenu::Party { cursor: cursor.current }
} else if read(memory, ram::wListMenuID) == poke::ITEM_LIST_MENU { } else if read(memory, ram::wListMenuID) == poke::ITEM_LIST_MENU && item_list_drawn(memory) {
// The bag, opened from the battle menu's ITEM entry. `DisplayListMenuID` keeps its // The bag, opened from the battle menu's ITEM entry. `DisplayListMenuID` keeps its
// position in the same shared cursor every other menu uses, and the entry count is the // position in the same shared cursor every other menu uses, and the entry count is the
// bag's own, so the scripts that reach into it (`ITEM`, `THROW BALL`) navigate by reading // bag's own, so the scripts that reach into it (`ITEM`, `THROW BALL`) navigate by reading
// rather than by counting presses -- which is what section 4 requires of them and what // rather than by counting presses -- which is what section 4 requires of them and what
// they could not do while this read as no list at all. // they could not do while this read as no list at all.
//
// **And only while its box is on screen** (row 66), row 50's rule for the move list:
// `wListMenuID` is written when the list opens and never cleared, so after a ball was
// thrown every frame to the end of the battle -- "All right! WEEDLE was caught!", the
// Pokédex page, the nickname offer and the naming screen -- read as an open bag, the pad
// was `BACK` and `THROW BALL`, and the ball's A presses typed the nickname: 6,900 frames
// from the catch to the end of the battle, under a `THROW BALL` that threw nothing.
let count = bag(memory).len().min(usize::from(poke::BAG_CAPACITY)); let count = bag(memory).len().min(usize::from(poke::BAG_CAPACITY));
BattleMenu::Bag { cursor: cursor.current, count: u8::try_from(count).unwrap_or(0) } BattleMenu::Bag { cursor: cursor.current, count: u8::try_from(count).unwrap_or(0) }
} else { } else {
@ -1033,6 +1083,49 @@ pub fn yes_no_prompt(memory: &mut dyn MemoryReader) -> bool {
two_option_box_drawn(memory, cursor.top_x, cursor.top_y) two_option_box_drawn(memory, cursor.top_x, cursor.top_y)
} }
/// The naming screen, when it is up (row 69, `docs/design/macros.md` 12.32).
///
/// Red has no "the keyboard is open" byte, so this is the construction `yes_no_prompt` makes: the
/// menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3, `wMaxMenuItem` 7, every key
/// watched), **and** the figure it draws -- the keyboard's whole `TextBoxBorder` at (0, 4)-(19, 14)
/// and the underscores under the name at (10, 3). Both halves, because the menu bytes are not
/// cleared when the screen closes.
///
/// The capacity is the underscores counted on screen (seven or ten), and the length is
/// `wNamingScreenNameLength`, which `PrintNicknameAndUnderscores` writes after every key that
/// changes the name.
pub fn naming_screen(memory: &mut dyn MemoryReader) -> Option<Naming> {
let cursor = cursor(memory);
if cursor.top_y != poke::NAMING_TOP_Y
|| cursor.max != poke::NAMING_MAX_ITEM
|| cursor.watched_keys != 0xff
{
return None;
}
let (left, top, right, bottom) = poke::NAMING_BOX;
if !border_drawn(memory, left, top, right, bottom) {
return None;
}
let (x, y) = poke::NAMING_UNDERSCORES;
let capacity = (x..poke::SCREEN_WIDTH)
.take_while(|column| {
matches!(
screen_tile(memory, *column, y),
poke::NAMING_UNDERSCORE | poke::NAMING_UNDERSCORE_RAISED
)
})
.count();
// `PLAYER_NAME_LENGTH - 1` or `NAME_LENGTH - 1`: nothing else is the keyboard.
if capacity != 7 && capacity != 10 {
return None;
}
Some(Naming {
length: read(memory, poke::NAMING_LENGTH),
capacity: capacity as u8,
submitted: read(memory, poke::NAMING_SUBMIT) != 0,
})
}
/// Whether `DisplayTwoOptionMenu`'s own box is drawn around the cursor the game parked in it. /// Whether `DisplayTwoOptionMenu`'s own box is drawn around the cursor the game parked in it.
/// ///
/// One fact about the routine rather than about any one script (row 56): the cursor goes in the /// One fact about the routine rather than about any one script (row 56): the cursor goes in the
@ -1065,6 +1158,12 @@ fn two_option_box_drawn(memory: &mut dyn MemoryReader, cursor_x: u8, cursor_y: u
}) })
} }
/// Whether the battle bag's list box is whole on screen ([`poke::ITEM_LIST_BOX`], row 66).
fn item_list_drawn(memory: &mut dyn MemoryReader) -> bool {
let (left, top, right, bottom) = poke::ITEM_LIST_BOX;
border_drawn(memory, left, top, right, bottom)
}
/// Whether `MoveSelectionMenu`'s own box is the figure on screen (`infra/docs/macros-traps.md`, /// Whether `MoveSelectionMenu`'s own box is the figure on screen (`infra/docs/macros-traps.md`,
/// row 50). /// row 50).
/// ///
@ -2317,6 +2416,22 @@ impl MacroState for PokeState<'_> {
self.targets.reached(map, target) self.targets.reached(map, target)
} }
/// Whether the counter of the building on `map` was walked to inside the window (row 66).
fn counter_walked_to(&mut self, map: u8) -> bool {
self.targets.reached(map, TargetKey::Counter)
}
/// `EVENT_OAK_GOT_PARCEL`, bit 56 of `wEventFlags`.
fn parcel_delivered(&mut self) -> bool {
let bit = super::symbols::events::EVENT_OAK_GOT_PARCEL;
read(self.memory, ram::wEventFlags + (bit >> 3)) & (1 << (bit & 7)) != 0
}
/// The naming screen (row 69), [`naming_screen`].
fn naming(&mut self) -> Option<super::macros::state::Naming> {
naming_screen(self.memory)
}
/// Where the ladder's next unreached rung is (`GO OBJECTIVE`). /// Where the ladder's next unreached rung is (`GO OBJECTIVE`).
/// ///
/// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only /// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only

View file

@ -382,6 +382,13 @@ fn a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn() {
let mut wram = Wram::overworld(); let mut wram = Wram::overworld();
battler(&mut wram); battler(&mut wram);
wram.bag(&[(crate::pokemon_red::macros::cartridge::item::POTION, 2)]).set(ram::wListMenuID, poke::ITEM_LIST_MENU); wram.bag(&[(crate::pokemon_red::macros::cartridge::item::POTION, 2)]).set(ram::wListMenuID, poke::ITEM_LIST_MENU);
// Row 66: the list byte alone is not the bag. It is never cleared, so it outlives the list
// into the rest of the battle -- after a ball, the catch, the Pokédex page, the nickname.
let fight = battle(&mut wram).unwrap();
assert_eq!(fight.menu, BattleMenu::None, "the list byte without the list's box on screen");
assert!(!fight.own_turn, "text after the bag closed is nobody's turn");
let (left, top, right, bottom) = poke::ITEM_LIST_BOX;
wram.draw_box(left, top, right, bottom);
let fight = battle(&mut wram).unwrap(); let fight = battle(&mut wram).unwrap();
assert_eq!(fight.menu, BattleMenu::Bag { cursor: 0, count: 1 }); assert_eq!(fight.menu, BattleMenu::Bag { cursor: 0, count: 1 });
assert!(fight.own_turn, "the battle bag is a cursor accepting input"); assert!(fight.own_turn, "the battle bag is a cursor accepting input");
@ -1365,3 +1372,43 @@ fn the_joypad_latch_is_hjoylast_bit_zero() {
wram.set(poke::H_JOY_LAST, poke::pad::DOWN); wram.set(poke::H_JOY_LAST, poke::pad::DOWN);
assert!(!a_latched(&mut wram), "a direction down is not an A down"); assert!(!a_latched(&mut wram), "a direction down is not an A down");
} }
/// Row 69: the naming screen is the keyboard's menu bytes **and** its figure on screen.
#[test]
fn the_naming_screen_is_its_menu_and_its_box_and_its_underscores() {
let mut wram = Wram::new();
wram.started().naming_screen(3, 10);
let naming = naming_screen(&mut wram).expect("the keyboard");
assert_eq!((naming.length, naming.capacity, naming.submitted), (3, 10, false));
assert!(!naming.full());
let mut wram = Wram::new();
wram.started().naming_screen(7, 7);
assert!(naming_screen(&mut wram).expect("a player's keyboard").full());
let mut wram = Wram::new();
wram.started().naming_screen(0, 10).set(poke::NAMING_SUBMIT, 1);
assert!(naming_screen(&mut wram).unwrap().submitted);
// The menu bytes outlive the screen: with the box cleared it is not the keyboard.
let mut wram = Wram::new();
wram.started().naming_screen(3, 10).fill_screen(0x7f);
assert_eq!(naming_screen(&mut wram), None);
// And another menu with every key watched is not it either.
let mut wram = Wram::new();
wram.started().naming_screen(3, 10).cursor(3, 1, 1, 6, 0xff);
assert_eq!(naming_screen(&mut wram), None);
}
/// Row 69: the keyboard is `Unknown` even inside a battle, where a nickname is typed.
#[test]
fn the_naming_screen_reads_unknown_in_a_battle_and_title_before_the_game() {
let mut wram = Wram::new();
wram.started().battle(1).naming_screen(0, 10);
assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Unknown);
// The player's name at the start of the game is before the game timer: the title's raw pad.
let mut wram = Wram::new();
wram.naming_screen(0, 7);
assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Title);
}

View file

@ -35,8 +35,10 @@ pub mod ram {
pub const wListMenuID: u16 = 0xcf94; // 53140 pub const wListMenuID: u16 = 0xcf94; // 53140
pub const wFontLoaded: u16 = 0xcfc4; // 53188 pub const wFontLoaded: u16 = 0xcfc4; // 53188
pub const wWalkCounter: u16 = 0xcfc5; // 53189 pub const wWalkCounter: u16 = 0xcfc5; // 53189
pub const wPlayerMoveNum: u16 = 0xcfd2; // 53202
pub const wEnemyMonSpecies: u16 = 0xcfe5; // 53221 pub const wEnemyMonSpecies: u16 = 0xcfe5; // 53221
pub const wEnemyMonHP: u16 = 0xcfe6; // 53222 pub const wEnemyMonHP: u16 = 0xcfe6; // 53222
pub const wEnemyMonPartyPos: u16 = 0xcfe8; // 53224
pub const wEnemyMonStatus: u16 = 0xcfe9; // 53225 pub const wEnemyMonStatus: u16 = 0xcfe9; // 53225
pub const wEnemyMonType1: u16 = 0xcfea; // 53226 pub const wEnemyMonType1: u16 = 0xcfea; // 53226
pub const wEnemyMonLevel: u16 = 0xcff3; // 53235 pub const wEnemyMonLevel: u16 = 0xcff3; // 53235

View file

@ -865,8 +865,8 @@ fn the_recent_ticker_keeps_the_newest_eight_events_newest_first() {
#[test] #[test]
fn the_adapter_reports_its_identity_and_pinned_rom() { fn the_adapter_reports_its_identity_and_pinned_rom() {
let reward = PokemonRedReward::new(); let reward = PokemonRedReward::new();
assert_eq!(reward.id(), "pokered-unique8-v7"); assert_eq!(reward.id(), "pokered-unique8-v8");
assert_eq!(reward.migrates_from(), ["pokered-unique8-v6"]); assert_eq!(reward.migrates_from(), ["pokered-unique8-v7", "pokered-unique8-v6"]);
assert!(reward.rom_allowed(SUPPORTED_ROM)); assert!(reward.rom_allowed(SUPPORTED_ROM));
assert!(!reward.rom_allowed( assert!(!reward.rom_allowed(
"5ca7ba01642a3b27b0cc0b5349b52792795b62d3ed977e98a09390659af96b7b" "5ca7ba01642a3b27b0cc0b5349b52792795b62d3ed977e98a09390659af96b7b"
@ -1894,3 +1894,272 @@ fn a_warp_is_classified_by_the_header_still_loaded_while_the_map_id_has_moved_on
f.memory.set(ram::wCurMap, maps::PEWTER_CITY); f.memory.set(ram::wCurMap, maps::PEWTER_CITY);
assert!(boundary_values(&f.visit(10, 7)).is_empty()); assert!(boundary_values(&f.visit(10, 7)).is_empty());
} }
// -- the damage rule (`pokered-unique8-v8`, the operator 2026-09-29) --------------------------
/// Move ids from `constants/move_constants.asm`, the three row 67's Squirtle knows.
const TACKLE: u8 = 0x21;
const TAIL_WHIP: u8 = 0x27;
const BUBBLE: u8 = 0x91;
/// `wTrainerClass`-independent: `wIsInBattle` is 2 in a trainer battle, 1 in a wild one.
const TRAINER_BATTLE: u8 = 2;
const WILD_BATTLE: u8 = 1;
impl Fixture {
/// The enemy battle struct as `LoadEnemyMonData` leaves it: party slot, species, level, HP
/// and max HP (both big-endian words).
fn enemy(&mut self, slot: u8, species: u8, level: u8, hp: u16, max_hp: u16) {
self.memory.set(ram::wEnemyMonPartyPos, slot);
self.memory.set(ram::wEnemyMonSpecies, species);
self.memory.set(ram::wEnemyMonLevel, level);
self.enemy_hp(hp, max_hp);
}
fn enemy_hp(&mut self, hp: u16, max_hp: u16) {
self.memory.set(ram::wEnemyMonHP, (hp >> 8) as u8);
self.memory.set(ram::wEnemyMonHP + 1, hp as u8);
self.memory.set(ram::wEnemyMonMaxHP, (max_hp >> 8) as u8);
self.memory.set(ram::wEnemyMonMaxHP + 1, max_hp as u8);
}
/// `hWhoseTurn` and `wPlayerMoveNum` for the side acting, as `ExecutePlayerMove` and
/// `MainInBattleLoop` write them.
fn turn(&mut self, fly: bool, move_id: u8) {
self.memory.set(state::poke::H_WHOSE_TURN, u8::from(!fly));
self.memory.set(ram::wPlayerMoveNum, move_id);
}
fn damage_events(&mut self) -> Vec<RewardEvent> {
self.sample().into_iter().filter(|event| event.kind == kind::DAMAGE).collect()
}
}
fn values(events: &[RewardEvent]) -> Vec<f64> {
events.iter().map(|event| event.value).collect()
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-12
}
/// Row 67's battle: the Jr. Trainer's Diglett (slot 0, $3b, L11, 31 HP) and Sandshrew (slot 1,
/// $60, L11, 33 HP), entered with the *last* battle's Diglett still in `wEnemyMon` at 7 HP.
fn row67_battle() -> Fixture {
let mut f = Fixture::booted();
f.enemy(0, 0x3b, 11, 7, 31);
f.turn(true, BUBBLE);
f.memory.set(ram::wIsInBattle, TRAINER_BATTLE);
assert!(f.damage_events().is_empty(), "the stale Diglett is not the battle's");
f.enemy_hp(3, 31);
assert!(f.damage_events().is_empty(), "and nothing it does pays");
f.enemy(0, 0x3b, 11, 31, 31);
assert!(f.damage_events().is_empty(), "the real Diglett loads full");
f
}
#[test]
fn the_flys_own_attack_pays_in_proportion_and_tail_whip_pays_nothing() {
let mut f = row67_battle();
// TAIL WHIP: no HP moves, whatever the turn.
f.turn(true, TAIL_WHIP);
assert!(f.damage_events().is_empty());
// BUBBLE lands for 12 of 31.
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
let hit = f.damage_events();
assert_eq!(labels(&hit), ["HIT #59 FOR 12 HP"]);
assert!(close(hit[0].value, 0.20 * 12.0 / 31.0));
assert_eq!(hit[0].stimulation_ms, 80);
// The HP bar animates for a while; the same HP is not paid again.
assert!(f.damage_events().is_empty());
// TACKLE for 5.
f.turn(true, TACKLE);
f.enemy_hp(14, 31);
assert_eq!(values(&f.damage_events()).len(), 1);
assert_eq!(f.reward.statistics().counts[kind::DAMAGE], 2);
}
#[test]
fn hp_the_enemy_loses_on_its_own_turn_and_struggle_pay_nothing() {
let mut f = row67_battle();
// Poison, burn, Leech Seed, recoil, a confusion self-hit, its own Explosion: all with
// `hWhoseTurn` 1.
f.turn(false, BUBBLE);
f.enemy_hp(27, 31);
assert!(f.damage_events().is_empty());
// Struggle is the cartridge's move, not the fly's.
f.turn(true, state::poke::moves::STRUGGLE);
f.enemy_hp(24, 31);
assert!(f.damage_events().is_empty());
// The fly's next hit is paid from 24, not from 31.
f.turn(true, BUBBLE);
f.enemy_hp(20, 31);
let hit = f.damage_events();
assert_eq!(labels(&hit), ["HIT #59 FOR 4 HP"]);
}
#[test]
fn a_healed_enemy_is_not_paid_for_twice_and_a_switch_keeps_the_marks() {
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(11, 31);
assert_eq!(f.damage_events().len(), 1);
// A Potion on the trainer's turn.
f.turn(false, BUBBLE);
f.enemy_hp(31, 31);
assert!(f.damage_events().is_empty());
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
assert!(f.damage_events().is_empty(), "31 to 19 was paid before the Potion");
// The trainer switches to Sandshrew, which is hit, and back.
f.turn(false, BUBBLE);
f.enemy(1, 0x60, 11, 33, 33);
assert!(f.damage_events().is_empty());
f.turn(true, TACKLE);
f.enemy_hp(28, 33);
assert_eq!(labels(&f.damage_events()), ["HIT #96 FOR 5 HP"]);
f.turn(false, BUBBLE);
f.enemy(0, 0x3b, 11, 19, 31);
assert!(f.damage_events().is_empty());
f.turn(true, BUBBLE);
f.enemy_hp(8, 31);
assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 3 HP"], "only below its low of 11");
}
#[test]
fn a_trainer_battle_pays_the_knockouts_and_stops_at_the_cap() {
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(0, 31);
let ko = f.damage_events();
assert_eq!(labels(&ko), ["HIT #59 FOR 31 HP KO"]);
assert!(close(ko[0].value, 0.25));
f.enemy(1, 0x60, 11, 33, 33);
f.sample();
f.enemy_hp(0, 33);
assert!(close(values(&f.damage_events())[0], 0.25));
// A third Pokémon: the cap is spent.
f.enemy(2, 0x60, 11, 33, 33);
f.sample();
f.enemy_hp(0, 33);
assert!(f.damage_events().is_empty());
f.memory.set(ram::wIsInBattle, 0);
f.sample();
assert!(close(f.reward.statistics().total, 0.50), "the battle's damage is the trainer's 0.50");
}
#[test]
fn a_new_trainer_battle_starts_a_new_budget() {
// Row 67's ring: lose, black out, walk back, fight again. Each battle pays its own damage.
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
assert_eq!(f.damage_events().len(), 1);
f.memory.set(ram::wIsInBattle, 0xff);
f.sample();
f.memory.set(ram::wIsInBattle, 0);
f.sample();
f.memory.set(ram::wIsInBattle, TRAINER_BATTLE);
f.sample();
f.enemy(0, 0x3b, 11, 31, 31);
f.sample();
f.enemy_hp(19, 31);
assert_eq!(f.damage_events().len(), 1, "the second battle's first hit pays");
}
#[test]
fn a_wild_battle_pays_damage_on_the_wild_ko_scale_and_a_rollback_blocks_the_key() {
let mut f = Fixture::booted();
let mut paid = Vec::new();
for _ in 0..4 {
f.enemy(0, 0xa5, 3, 12, 12);
f.turn(true, TACKLE);
f.memory.set(ram::wIsInBattle, WILD_BATTLE);
f.sample();
f.enemy_hp(6, 12);
paid.extend(values(&f.damage_events()));
f.memory.set(ram::wIsInBattle, 0);
f.memory.set(ram::wBattleResult, 1);
f.sample();
}
assert_eq!(paid.len(), 3, "three wild battles per map/species/level: {paid:?}");
assert!(close(paid[0], 0.10) && close(paid[1], 0.05) && close(paid[2], 0.10 / 3.0));
assert_eq!(f.reward.export_state()["damageCounts"], json!({ "38:165:3": 3 }));
// Another species on the same map is another key, and a rollback blocks it once paid.
f.enemy(0, 0x24, 3, 12, 12);
f.memory.set(ram::wIsInBattle, WILD_BATTLE);
f.sample();
f.enemy_hp(0, 12);
let events = f.damage_events();
assert_eq!(labels(&events), ["HIT #36 FOR 12 HP KO"]);
assert!(close(events[0].value, 0.20), "no knockout bonus in the wild");
f.memory.set(ram::wIsInBattle, 0);
f.memory.set(ram::wBattleResult, 0);
assert_eq!(kinds(&f.sample()), ["battle"], "the wild KO still pays as it did");
f.reward.clear_transient();
f.enemy(0, 0x24, 3, 12, 12);
f.memory.set(ram::wIsInBattle, WILD_BATTLE);
f.sample();
f.enemy_hp(0, 12);
assert!(f.damage_events().is_empty(), "a rollback cannot replay the damage");
}
#[test]
fn a_battle_sample_still_reads_each_address_once() {
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
f.damage_events();
assert!(
f.memory.reads.values().all(|count| *count == 1),
"{:?}",
f.memory.reads.iter().filter(|(_, count)| **count != 1).collect::<Vec<_>>()
);
}
#[test]
fn a_battle_in_flight_round_trips_through_a_checkpoint() {
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
f.damage_events();
let state = f.reward.export_state();
let mut restored = PokemonRedReward::new();
restored.import_state(&state).unwrap();
assert_eq!(restored.export_state(), state);
f.reward = restored;
f.enemy_hp(15, 31);
assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 4 HP"], "the mark came back with it");
}
#[test]
fn a_v7_state_restores_under_v8_with_no_damage_ledger_and_its_battle_marked_where_it_stands() {
// A v7 export mid-battle: v8's export without `damageCounts`, `counts.damage` or
// `battle.damage`.
let mut f = row67_battle();
f.turn(true, BUBBLE);
f.enemy_hp(19, 31);
f.damage_events();
let mut v7 = f.reward.export_state();
v7.as_object_mut().unwrap().remove("damageCounts");
v7["counts"].as_object_mut().unwrap().remove("damage");
v7["battle"].as_object_mut().unwrap().remove("damage");
assert_eq!(v7["version"], json!(STATE_VERSION), "v7 and v8 share a schema version");
let mut restored = PokemonRedReward::new();
restored.import_state(&v7).unwrap();
assert_eq!(restored.statistics().counts[kind::DAMAGE], 0);
assert_eq!(restored.export_state()["damageCounts"], json!({}));
f.reward = restored;
// Diglett stands at 19 of 31: that is its mark, and the 12 lost before the restore is not
// paid. The next hit is.
assert!(f.damage_events().is_empty());
f.enemy_hp(10, 31);
assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 9 HP"]);
// Sandshrew, which the restore never saw, is marked where it first reads too.
f.enemy(1, 0x60, 11, 33, 33);
f.sample();
f.enemy_hp(30, 33);
assert_eq!(labels(&f.damage_events()), ["HIT #96 FOR 3 HP"]);
}

View file

@ -1743,6 +1743,7 @@ fn offers_survey(
layer: &mut flysim::macros::MacroLayer, layer: &mut flysim::macros::MacroLayer,
decoder: &mut PopulationDecoder, decoder: &mut PopulationDecoder,
hold_ms: f64, hold_ms: f64,
checkpoint: &flysim::store::Checkpoint,
) { ) {
use flybrain_gb::pokemon_red::macros::cartridge::MacroState; use flybrain_gb::pokemon_red::macros::cartridge::MacroState;
use flybrain_gb::pokemon_red::macros::geography::{self, Amenity}; use flybrain_gb::pokemon_red::macros::geography::{self, Amenity};
@ -1764,6 +1765,9 @@ fn offers_survey(
let hp: Vec<String> = let hp: Vec<String> =
party.mons.iter().map(|mon| format!("{}/{} {:?}", mon.hp, mon.max_hp, mon.status)).collect(); party.mons.iter().map(|mon| format!("{}/{} {:?}", mon.hp, mon.max_hp, mon.status)).collect();
let bag: Vec<(u8, u8)> = state::bag(gb).iter().map(|item| (item.id, item.count)).collect(); let bag: Vec<(u8, u8)> = state::bag(gb).iter().map(|item| (item.id, item.count)).collect();
let owned: u32 = (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum();
let species: Vec<u8> = party.mons.iter().map(|mon| mon.species).collect();
let row66 = format!("- row66: party count {} species {species:?}, box count {}, pokedex owned {owned}", gb.read8(ram::wPartyCount), gb.read8(0xda80));
let money = state::money(gb); let money = state::money(gb);
let last = blackout(gb); let last = blackout(gb);
let player = state::player(gb); let player = state::player(gb);
@ -1775,6 +1779,7 @@ fn offers_survey(
println!("- party {hp:?}; needs rest {}", palette::party_needs_rest(st)); println!("- party {hp:?}; needs rest {}", palette::party_needs_rest(st));
println!("- money {money}, bag {bag:?}"); println!("- money {money}, bag {bag:?}");
println!("- wLastBlackoutMap ($d719) = {last:#04x}"); println!("- wLastBlackoutMap ($d719) = {last:#04x}");
println!("{row66}");
let centers: Vec<(String, bool)> = let centers: Vec<(String, bool)> =
CENTERS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect(); CENTERS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect();
let marts: Vec<(String, bool)> = let marts: Vec<(String, bool)> =
@ -1820,6 +1825,10 @@ fn offers_survey(
let mut was_full = true; let mut was_full = true;
let mut counts: BTreeMap<&str, u64> = BTreeMap::new(); let mut counts: BTreeMap<&str, u64> = BTreeMap::new();
let mut maps_seen: BTreeMap<u8, u64> = BTreeMap::new(); let mut maps_seen: BTreeMap<u8, u64> = BTreeMap::new();
let owned_now = |gb: &mut Emulator| -> u32 { (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum() };
let mut last_owned = owned_now(gb);
let mut last_mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80));
let mut was_wild = false;
for frame in 0..budget { for frame in 0..budget {
let bound = layer.bound_channels(); let bound = layer.bound_channels();
if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() { if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() {
@ -1882,6 +1891,15 @@ fn offers_survey(
} }
} }
let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter); let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter);
if let (Some(from), Some(to)) = (std::env::var("FLY_PROBE_SCREEN_FROM").ok().and_then(|v| v.parse::<usize>().ok()), std::env::var("FLY_PROBE_SCREEN_TO").ok().and_then(|v| v.parse::<usize>().ok()))
&& frame >= from && frame <= to && (frame - from) % env_usize("FLY_PROBE_SCREEN_EVERY", 100) == 0
{
let battle = state::battle(gb).map(|battle| format!("{:?}", battle.menu));
println!(" screen f{frame} mask {:#04x} scene {} pad {names:?} running {:?} battle-menu {battle:?} text {:?} prompt {} wIsInBattle {} boxes {:?} listid {:#04x} itemlist {:02x?} shop {:?} stock {:?}", executed.mask, layer.scene_name(), layer.running(), state::text_box(gb), state::yes_no_prompt(gb), gb.read8(ram::wIsInBattle), state::drawn_boxes(gb), gb.read8(ram::wListMenuID), (0..6u16).map(|i| gb.read8(ram::wItemList + i)).collect::<Vec<u8>>(), state::shop(gb).map(|s| s.screen), state::shop_stock(gb));
for line in screen_text(gb) {
println!(" | {line}");
}
}
// `FLY_PROBE_TRACE_MACRO=BUY BALL` prints every frame of that macro's first three runs: // `FLY_PROBE_TRACE_MACRO=BUY BALL` prints every frame of that macro's first three runs:
// the mask, the scene, the counter's screen, the cursor and the wallet. // the mask, the scene, the counter's screen, the cursor and the wallet.
if let Some(want) = trace_macro.as_deref() if let Some(want) = trace_macro.as_deref()
@ -1953,6 +1971,23 @@ fn offers_survey(
} }
was_wiped = wiped; was_wiped = wiped;
was_full = full; was_full = full;
let owned = owned_now(gb);
if owned > last_owned {
*counts.entry("row66 pokedex owned +").or_default() += u64::from(owned - last_owned);
log.push(format!("f{frame} pokedex owned {last_owned} -> {owned}"));
}
last_owned = owned;
let mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80));
if mons > last_mons && mons <= 26 {
*counts.entry("row66 mons gained (party+box)").or_default() += u64::from(mons - last_mons);
log.push(format!("f{frame} party+box {last_mons} -> {mons}"));
}
if mons <= 26 { last_mons = mons; }
let wild = gb.read8(ram::wIsInBattle) == 1;
if wild && !was_wild {
*counts.entry(if balls(gb) > 0 { "row66 wild battles with a ball" } else { "row66 wild battles, no ball" }).or_default() += 1;
}
was_wild = wild;
let now_balls = balls(gb); let now_balls = balls(gb);
if now_balls > last_balls { if now_balls > last_balls {
*counts.entry("balls bought").or_default() += u64::from(now_balls - last_balls); *counts.entry("balls bought").or_default() += u64::from(now_balls - last_balls);
@ -1974,8 +2009,22 @@ fn offers_survey(
last_blackout = now_blackout; last_blackout = now_blackout;
} }
if map != last_map { if map != last_map {
// Row 66: `FLY_PROBE_SAVE_MART=<map>` with `FLY_PROBE_SAVE` writes the first frame the fly
// walks into that mart with the money for a ball, no ball and no parcel.
if let (Some(want), Some(path)) = (std::env::var("FLY_PROBE_SAVE_MART").ok().and_then(|v| u8::from_str_radix(v.trim_start_matches("0x"), 16).ok()), std::env::var_os("FLY_PROBE_SAVE"))
&& map == Some(want)
&& money >= 200
&& frame >= env_usize("FLY_PROBE_SAVE_AFTER", 0)
&& balls(gb) == 0
&& !state::bag(gb).iter().any(|item| item.id == 0x46)
&& !std::path::Path::new(&path).exists()
{
let bytes = save_state(checkpoint, gb, adapter, frame, &path);
log.push(format!("f{frame} saved {bytes} bytes to {}", std::path::Path::new(&path).display()));
}
if map.is_some_and(|map| CENTERS.contains(&map) || MARTS.contains(&map)) { if map.is_some_and(|map| CENTERS.contains(&map) || MARTS.contains(&map)) {
log.push(format!("f{frame} entered {map:?} (party full {full}, money {money})")); let parcel = state::bag(gb).iter().any(|item| item.id == 0x46);
log.push(format!("f{frame} entered {map:?} (party full {full}, money {money}, balls {}, parcel {parcel})", balls(gb)));
} }
last_map = map; last_map = map;
} }
@ -2152,7 +2201,7 @@ fn main() {
// Row 62's offer survey: which shop, centre and ball buttons are dealt, frame by frame. // Row 62's offer survey: which shop, centre and ball buttons are dealt, frame by frame.
if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "offers") { if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "offers") {
offers_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms); offers_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms, &checkpoint);
return; return;
} }

View file

@ -235,6 +235,70 @@ struct Trace {
payouts_by_kind: BTreeMap<&'static str, (u64, f64)>, payouts_by_kind: BTreeMap<&'static str, (u64, f64)>,
move_starts: (u64, u64), move_starts: (u64, u64),
wall_seconds: f64, wall_seconds: f64,
row66: Row66,
row69: Row69,
}
/// Row 69's tally: frames the throw's pad was up, and every naming screen -- how long, the fly's
/// own presses on it, the name, and what ended it.
#[derive(Default)]
struct Row69 {
throw_pad_frames: u64,
keyboard_frames: u64,
keyboard_presses: u64,
/// The keyboard up now: brain ms it opened, frames, presses, longest, name, CONFIRM started.
open: Option<(f64, u64, u64, u8, String, bool)>,
keyboards: Vec<String>,
previous_mask: u32,
/// A, B and START going down on the keyboard, over the run.
keys: BTreeMap<&'static str, u64>,
}
/// `wStringBuffer` (`CalcStringLength`'s operand on the cartridge), in Red's charmap.
fn row69_name(gb: &mut flybrain_gb::Emulator) -> String {
use flybrain_gb::MemoryReader;
(0..11u16)
.map(|index| gb.read8(0xcf4b + index))
.take_while(|byte| *byte != 0x50)
.map(|byte| match byte {
0x80..=0x99 => char::from(b'A' + (byte - 0x80)),
0xa0..=0xb9 => char::from(b'a' + (byte - 0xa0)),
0x7f => ' ',
_ => '?',
})
.collect()
}
/// Row 66's shop/ball/catch tally: pad frames, starts and outcomes of the watched buttons, and
/// the cartridge beside them.
#[derive(Default)]
struct Row66 {
/// channel -> [free frames on the pad, starts, done, other outcomes]
tally: BTreeMap<&'static str, [u64; 4]>,
free_frames: u64,
counts: BTreeMap<&'static str, u64>,
log: Vec<String>,
last: Option<(u32, u32, u32, u32, u8)>,
was_wild: bool,
}
const ROW66_WATCH: [&str; 8] = [
"GO SHOP", "TALK", "CONFIRM", "BUY BALL", "BUY POTION", "LEAVE", "THROW BALL", "GO HEAL",
];
fn row66_read(gb: &mut flybrain_gb::Emulator) -> (u32, u32, u32, u32, u8) {
use flybrain_gb::MemoryReader;
use flybrain_gb::pokemon_red::symbols::ram;
let balls: u32 = flybrain_gb::pokemon_red::state::bag(gb)
.iter()
.filter(|item| (0x01..=0x04).contains(&item.id))
.map(|item| u32::from(item.count))
.sum();
let money = flybrain_gb::pokemon_red::state::money(gb);
let mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80));
let owned: u32 = (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum();
let map = flybrain_gb::pokemon_red::state::player(gb).map_or(0xff, |player| player.map);
(balls, money, mons, owned, map)
} }
/// Which sub-state of a battle this frame is, or `None` when no battle is running. /// Which sub-state of a battle this frame is, or `None` when no battle is running.
@ -330,6 +394,23 @@ impl FrameObserver for Hunt {
.then(|| flybrain_gb::pokemon_red::state::player(parts.emulator).map(|p| p.map)) .then(|| flybrain_gb::pokemon_red::state::player(parts.emulator).map(|p| p.map))
.flatten(); .flatten();
self.battle_sub = battle_sub_state(parts.emulator); self.battle_sub = battle_sub_state(parts.emulator);
if let Some(layer) = parts.macros.as_deref()
&& layer.running().is_none()
{
let names: Vec<String> = layer.feed_palette().into_iter().map(|slot| slot.name).collect();
if names == ["THROW BALL"] || names == ["ITEM", "THROW BALL"] {
self.trace.row69.throw_pad_frames += 1;
}
if !names.is_empty() {
let row = &mut self.trace.row66;
row.free_frames += 1;
for watch in ROW66_WATCH {
if names.iter().any(|name| name == watch) {
row.tally.entry(watch).or_default()[0] += 1;
}
}
}
}
if let Some(sub) = self.battle_sub { if let Some(sub) = self.battle_sub {
*self.trace.battle_frames.entry(sub).or_insert(0) += 1; *self.trace.battle_frames.entry(sub).or_insert(0) += 1;
let pad = self.trace.battle_pads.entry(sub).or_default(); let pad = self.trace.battle_pads.entry(sub).or_default();
@ -343,7 +424,66 @@ impl FrameObserver for Hunt {
let ms = parts.agent.network.ms; let ms = parts.agent.network.ms;
let location = frame.location; let location = frame.location;
let trace = &mut self.trace; let trace = &mut self.trace;
{
let naming = flybrain_gb::pokemon_red::state::naming_screen(parts.emulator);
let row = &mut trace.row69;
match (naming, row.open.take()) {
(Some(naming), open) => {
let (since, frames, presses, longest, _, confirm) =
open.unwrap_or((ms, 0, 0, 0, String::new(), false));
// A press is a button going down while no macro runs: each of the eight bits
// on its own edge, since the D-pad group is almost always holding one.
let press = if executed.events.is_empty() {
(executed.mask & !row.previous_mask).count_ones()
} else {
0
};
let letters = executed.mask & !row.previous_mask;
for (bit, name) in [(0x10u32, "A"), (0x20, "B"), (0x40, "START")] {
if executed.events.is_empty() && letters & bit != 0 {
*row.keys.entry(name).or_default() += 1;
}
}
let confirm = confirm || executed.events.iter().any(|event| event.name == "CONFIRM");
row.keyboard_frames += 1;
row.keyboard_presses += u64::from(press);
row.open = Some((
since,
frames + 1,
presses + u64::from(press),
longest.max(naming.length),
row69_name(parts.emulator),
confirm,
));
}
(None, Some((since, frames, presses, longest, name, confirm))) => {
row.keyboards.push(format!(
"{:.2} min: {frames} frames ({:.1} brain s), {presses} presses, longest {longest}, \
name {name:?}, ended by {}",
(since - trace.began_ms) / MINUTE_MS,
(ms - since) / 1000.0,
if confirm { "CONFIRM (the bound)" } else { "the fly (ED or START)" }
));
}
(None, None) => {}
}
row.previous_mask = executed.mask;
}
for event in &executed.events { for event in &executed.events {
if std::env::var("FLY_TRAP_LOG_MACROS").is_ok_and(|value| value == "1") {
let pad: Vec<String> = parts.macros.as_deref().map(|layer| layer.feed_palette().into_iter().map(|slot| slot.name).collect()).unwrap_or_default();
println!(
"macro {:8.2}s {:?} {} {} pad {pad:?}",
(ms - trace.began_ms) / 1000.0,
location,
event.name,
event.outcome.map_or("start", |outcome| outcome.as_str())
);
}
if let Some(watch) = ROW66_WATCH.iter().find(|watch| **watch == event.name) {
let key = match event.outcome { None => 1, Some(o) if o.as_str() == "done" => 2, Some(_) => 3 };
trace.row66.tally.entry(watch).or_default()[key] += 1;
}
match event.outcome { match event.outcome {
None => { None => {
trace.starts.push((ms, event.name)); trace.starts.push((ms, event.name));
@ -564,6 +704,8 @@ fn run(
payouts_by_kind: BTreeMap::new(), payouts_by_kind: BTreeMap::new(),
move_starts: (0, 0), move_starts: (0, 0),
wall_seconds: 0.0, wall_seconds: 0.0,
row66: Row66::default(),
row69: Row69::default(),
seeded: seeded_note, seeded: seeded_note,
refusals: BTreeMap::new(), refusals: BTreeMap::new(),
refusal_run: (None, 0), refusal_run: (None, 0),
@ -640,6 +782,32 @@ fn run(
); );
} }
{
use flybrain_gb::MemoryReader;
let minute = (ms - began_ms) / MINUTE_MS;
let now = row66_read(parts.emulator);
let wild = parts.emulator.read8(flybrain_gb::pokemon_red::symbols::ram::wIsInBattle) == 1;
let row = &mut hunt.trace.row66;
if wild && !row.was_wild {
*row.counts.entry(if now.0 > 0 { "wild battles with a ball" } else { "wild battles, no ball" }).or_default() += 1;
}
row.was_wild = wild;
if let Some(last) = row.last {
if now.0 > last.0 { *row.counts.entry("balls gained").or_default() += u64::from(now.0 - last.0); row.log.push(format!("{minute:.2} min balls {} -> {} (map {:#04x})", last.0, now.0, now.4)); }
if now.0 < last.0 { *row.counts.entry("balls spent").or_default() += u64::from(last.0 - now.0); row.log.push(format!("{minute:.2} min balls {} -> {} (map {:#04x})", last.0, now.0, now.4)); }
if now.1 < last.1 && [0x2a, 0x38].contains(&now.4) { row.log.push(format!("{minute:.2} min money {} -> {} in mart {:#04x}", last.1, now.1, now.4)); }
if now.2 > last.2 && now.2 <= 26 { *row.counts.entry("mons gained (party+box)").or_default() += u64::from(now.2 - last.2); row.log.push(format!("{minute:.2} min party+box {} -> {}", last.2, now.2)); }
if now.3 > last.3 { *row.counts.entry("pokedex owned +").or_default() += u64::from(now.3 - last.3); row.log.push(format!("{minute:.2} min pokedex owned {} -> {}", last.3, now.3)); }
if now.4 != last.4 && [0x2a, 0x38, 0x43].contains(&now.4) {
*row.counts.entry("mart entries").or_default() += 1;
let parcel = flybrain_gb::pokemon_red::state::bag(parts.emulator).iter().any(|item| item.id == 0x46);
row.log.push(format!("{minute:.2} min entered mart {:#04x} (money {}, balls {}, parcel {parcel})", now.4, now.1, now.0));
}
} else {
row.log.push(format!("start: balls {} money {} party+box {} owned {} map {:#04x}", now.0, now.1, now.2, now.3, now.4));
}
row.last = Some(now);
}
let location = frame.location; let location = frame.location;
if let Some((map, x, y)) = location { if let Some((map, x, y)) = location {
hunt.trace.steps.push((ms, map, x, y)); hunt.trace.steps.push((ms, map, x, y));
@ -1000,6 +1168,37 @@ fn main() {
trace.ended_in.0, trace.ended_in.1, trace.ended_why trace.ended_in.0, trace.ended_in.1, trace.ended_why
); );
walk_report(&trace); walk_report(&trace);
{
let row = &trace.row66;
println!("\n## Row 66: shop, balls, catches\n\n{} free frames with a pad\n", row.free_frames);
println!("| button | frames on the pad | starts | done | other |\n| --- | ---: | ---: | ---: | ---: |");
for watch in ROW66_WATCH {
let [a, b, c, d] = row.tally.get(watch).copied().unwrap_or_default();
println!("| {watch} | {a} | {b} | {c} | {d} |");
}
println!("\n- counts: {:?}", row.counts);
if let Some(last) = row.last { println!("- end: balls {} money {} party+box {} owned {} map {:#04x}", last.0, last.1, last.2, last.3, last.4); }
for line in row.log.iter().take(150) { println!("- {line}"); }
}
{
let row = &trace.row69;
println!(
"\n## Row 69: the throw's pad and the keyboard\n\n- free frames with the throw's pad \
(THROW BALL alone, or with ITEM): {}\n- keyboard frames {}, the fly's own button presses \
on it {} (of them {:?})",
row.throw_pad_frames, row.keyboard_frames, row.keyboard_presses, row.keys
);
for line in &row.keyboards {
println!("- keyboard at {line}");
}
if let Some((since, frames, presses, longest, name, _)) = &row.open {
println!(
"- keyboard still up at the end: opened {:.2} min, {frames} frames, {presses} presses, \
longest {longest}, name {name:?}",
(since - trace.began_ms) / MINUTE_MS
);
}
}
for (rank, label, ms) in &trace.rungs { for (rank, label, ms) in &trace.rungs {
println!("- rung {rank} {label} at {:.2} brain minutes", ms / MINUTE_MS); println!("- rung {rank} {label} at {:.2} brain minutes", ms / MINUTE_MS);
} }

View file

@ -184,6 +184,8 @@ pub struct MacroLayer {
last_decision_ms: Option<f64>, last_decision_ms: Option<f64>,
scene: SceneId, scene: SceneId,
bindings: Vec<SlotBinding>, bindings: Vec<SlotBinding>,
/// The raw buttons the last observation lets through ([`flybrain_gb::Observed::raw`]).
raw: u8,
running: Option<Running>, running: Option<Running>,
finished: Option<Finished>, finished: Option<Finished>,
/// The brain millisecond the pad became empty in a playable scene, or `None` while it has /// The brain millisecond the pad became empty in a playable scene, or `None` while it has
@ -241,6 +243,7 @@ impl MacroLayer {
// `observe` has not happened and guessing the intro would be a guess. // `observe` has not happened and guessing the intro would be a guess.
scene: SceneId::Unknown, scene: SceneId::Unknown,
bindings: Vec::new(), bindings: Vec::new(),
raw: 0,
running: None, running: None,
finished: None, finished: None,
pad_empty_since_ms: None, pad_empty_since_ms: None,
@ -285,6 +288,18 @@ impl MacroLayer {
}; };
} }
// Row 69: a scene typed on with the fly's own buttons (the naming screen). With nothing
// bound and nothing running, the readout's buttons reach the cartridge through the
// scene's mask, exactly as the title's do; the macro group has nothing to choose from.
if self.raw != 0 && self.bindings.is_empty() && self.running.is_none() {
let mask = raw_mask & u32::from(self.raw);
return Decision {
mask,
events: Vec::new(),
silence: (mask == 0).then_some(Silence::Channels),
};
}
// Rule one: a running macro owns the buttons, whatever the channels are doing. Its own // Rule one: a running macro owns the buttons, whatever the channels are doing. Its own
// `step` ends it on a scene change or at the frame cap. // `step` ends it on a scene change or at the frame cap.
if let Some(running) = self.running { if let Some(running) = self.running {
@ -377,6 +392,7 @@ impl MacroLayer {
let observed = self.palette.observe(memory, ledger); let observed = self.palette.observe(memory, ledger);
self.scene = observed.scene; self.scene = observed.scene;
self.bindings = observed.bindings; self.bindings = observed.bindings;
self.raw = observed.raw;
self.watch_pad(ms); self.watch_pad(ms);
let mut decision = Decision::default(); let mut decision = Decision::default();
if !self.scene.playable() if !self.scene.playable()
@ -415,7 +431,11 @@ impl MacroLayer {
/// Only a *playable* scene counts: the title screen deals no palette by contract (section 2), /// Only a *playable* scene counts: the title screen deals no palette by contract (section 2),
/// and raw mode has no palette at all, so neither is an empty pad in the sense that matters. /// and raw mode has no palette at all, so neither is an empty pad in the sense that matters.
fn watch_pad(&mut self, ms: f64) { fn watch_pad(&mut self, ms: f64) {
let empty = self.scene.playable() && self.bindings.is_empty() && self.running.is_none(); // A scene whose pad is the fly's own buttons (row 69) is not empty.
let empty = self.scene.playable()
&& self.bindings.is_empty()
&& self.raw == 0
&& self.running.is_none();
match (empty, self.pad_empty_since_ms) { match (empty, self.pad_empty_since_ms) {
(false, _) => self.pad_empty_since_ms = None, (false, _) => self.pad_empty_since_ms = None,
(true, None) => self.pad_empty_since_ms = Some(ms), (true, None) => self.pad_empty_since_ms = Some(ms),
@ -436,6 +456,12 @@ impl MacroLayer {
} }
} }
/// The fly's own buttons the last observation lets through while nothing is bound (row 69's
/// naming screen), as a joypad mask; 0 in every other scene. For a survey line and the tests.
pub fn raw_buttons(&self) -> u8 {
self.raw
}
/// The scene the last [`MacroLayer::observe`] found. /// The scene the last [`MacroLayer::observe`] found.
pub fn scene(&self) -> FeedScene { pub fn scene(&self) -> FeedScene {
FeedScene::from_adapter(self.scene) FeedScene::from_adapter(self.scene)
@ -612,6 +638,8 @@ mod tests {
/// Name sets the next `observe`s use instead, oldest first: a plan whose head changes. /// Name sets the next `observe`s use instead, oldest first: a plan whose head changes.
rename: Vec<Vec<&'static str>>, rename: Vec<Vec<&'static str>>,
bound: Vec<u8>, bound: Vec<u8>,
/// The raw buttons the scene lets through (row 69).
raw: u8,
/// Masks `step` returns, in order; a `None` ends the macro. /// Masks `step` returns, in order; a `None` ends the macro.
plan: Vec<Option<u8>>, plan: Vec<Option<u8>>,
running: Option<&'static str>, running: Option<&'static str>,
@ -629,6 +657,7 @@ mod tests {
names: Vec::new(), names: Vec::new(),
rename: Vec::new(), rename: Vec::new(),
bound: Vec::new(), bound: Vec::new(),
raw: 0,
plan: Vec::new(), plan: Vec::new(),
running: None, running: None,
finished: None, finished: None,
@ -652,6 +681,7 @@ mod tests {
} }
Observed { Observed {
scene: self.scene, scene: self.scene,
raw: self.raw,
bindings: self bindings: self
.bound .bound
.iter() .iter()
@ -924,6 +954,36 @@ mod tests {
assert_eq!(layer.counts().done, 1); assert_eq!(layer.counts().done, 1);
} }
/// Row 69: the naming screen's pad is the fly's own buttons, through the scene's mask, while
/// nothing is bound; it is not an empty pad; and once a button is bound the raw path is shut.
#[test]
fn a_scene_typed_on_passes_the_raw_buttons_through_its_mask_while_nothing_is_bound() {
let naming = 0b0111_1111;
let mut layer = layer(Fake { scene: SceneId::Unknown, raw: naming, ..Fake::default() });
// Up and A, pressed by the readout: through. Select: not in the mask.
let decision = decide(&mut layer, &channels(&["up", "a"]), 0b0001_0001, 0.0);
assert_eq!(decision.mask, 0b0001_0001);
assert!(decision.events.is_empty());
let decision = decide(&mut layer, &channels(&["select"]), 0b1000_0000, 16.0);
assert_eq!(decision.mask, 0, "SELECT is not one of the keyboard's buttons");
assert_eq!(decision.silence, Some(Silence::Channels));
layer.observe(&mut Zeroes, &NoLedger, 1_000.0);
assert_eq!(layer.pad_empty_ms(9_000.0), 0.0, "the fly's own buttons are a pad");
// A bound button (the bound's `CONFIRM`) shuts the raw path: only the macro can press.
let mut ending = super::tests::layer(Fake {
scene: SceneId::Unknown,
raw: 0,
bound: vec![0],
plan: vec![Some(0b0100_0000), None],
..Fake::default()
});
let decision = decide(&mut ending, &channels(&["up"]), 0b0000_0001, 0.0);
assert_eq!(decision.mask, 0, "raw UP does not reach the cartridge beside a bound button");
let decision = decide(&mut ending, &holding(0), 0b0000_0001, 16.0);
assert_eq!(decision.mask, 0b0100_0000, "the macro's START");
}
#[test] #[test]
fn the_title_screen_presses_the_raw_mask_and_runs_no_macro() { fn the_title_screen_presses_the_raw_mask_and_runs_no_macro() {
let mut layer = layer(Fake { scene: SceneId::Title, ..Fake::default() }); let mut layer = layer(Fake { scene: SceneId::Title, ..Fake::default() });

View file

@ -165,10 +165,16 @@ pub fn reset_to_milestone(
memory-only and are reset by stopping flysim)" memory-only and are reset by stopping flysim)"
)); ));
// 6. The sugar journal, copied aside in step 1. // 6. The sugar journal, copied aside in step 1. The reset itself is complete by now, so a
let journals = crate::journal::clear(hot_dir) // journal that cannot be cleared is reported, not an error: an error here made
.with_context(|| format!("clearing the sugar journal in {}", hot_dir.display()))?; // fly-loop-reset call a finished reset a failure (review-state-02 N3).
report.push(format!("cleared the sugar journal: {journals} files removed")); match crate::journal::clear(hot_dir) {
Ok(journals) => report.push(format!("cleared the sugar journal: {journals} files removed")),
Err(error) => report.push(format!(
"WARNING: the reset is complete but the sugar journal in {} was not cleared: {error:#}",
hot_dir.display()
)),
}
Ok(report) Ok(report)
} }
@ -331,7 +337,7 @@ mod tests {
wall_ms: 1_700_000_000_000, wall_ms: 1_700_000_000_000,
rom_sha256: "ab".repeat(32), rom_sha256: "ab".repeat(32),
emulator_frame: 12_345, emulator_frame: 12_345,
compatibility: "kernel/pokered-unique8-v7/fingerprint".to_string(), compatibility: "kernel/pokered-unique8-v8/fingerprint".to_string(),
speed: 1.0, speed: 1.0,
buttons: 0, buttons: 0,
rank_since_ms: 4_242.0, rank_since_ms: 4_242.0,

View file

@ -242,7 +242,7 @@ pub struct FeedMacroOutcome {
/// Reward categories the feed reports counts for. The adapter's own interned kinds /// Reward categories the feed reports counts for. The adapter's own interned kinds
/// (`milestone`, `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`, /// (`milestone`, `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`,
/// `catch`, `talk`, `item`) map onto these. /// `catch`, `talk`, `item`) map onto these; `damage` has no counter (`from_adapter`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum RewardKind { pub enum RewardKind {
@ -300,6 +300,15 @@ impl RewardKind {
// "new place" for all four, the operator's call (`apps/stage/src/games/pokemon-red.ts`). // "new place" for all four, the operator's call (`apps/stage/src/games/pokemon-red.ts`).
"talk" => Self::Explore, "talk" => Self::Explore,
"item" => Self::Explore, "item" => Self::Explore,
// `damage` (the operator, 2026-09-29) has no counter, deliberately. It pays for a hit,
// several times a battle, in trainer battles as well as wild ones: on `wildwin` the
// stage would fold every hit into "N wild wins", which is false of a trainer battle
// and of a battle the fly goes on to lose, and on any other counter it would be as
// wrong. Unmapped, a hit still reaches the page as a reward event with its own label
// (`HIT #<species> FOR <n> HP`), the event log, `/status` and the checkpoint; it is
// only left out of `game.rewardCounts` and the ticker's per-kind copy, the way the
// platformer's `started` and `clear` are. The feed's closed kind set does not move.
"damage" => return None,
// The platformer. // The platformer.
"band" => Self::Explore, "band" => Self::Explore,
"coin" => Self::Wildwin, "coin" => Self::Wildwin,
@ -753,13 +762,16 @@ mod tests {
GameMode::Unknown GameMode::Unknown
); );
for rule in flybrain_gb::pokemon_red::catalog::REWARDS { for rule in flybrain_gb::pokemon_red::catalog::REWARDS {
assert!(RewardKind::from_adapter(rule.kind).is_some(), "{}", rule.kind); // Every Pokémon kind shares a counter but `damage`, which has none on purpose.
let mapped = RewardKind::from_adapter(rule.kind).is_some();
assert_eq!(mapped, rule.kind != "damage", "{}", rule.kind);
} }
assert_eq!(RewardKind::from_adapter("nonsense"), None); assert_eq!(RewardKind::from_adapter("nonsense"), None);
assert_eq!(RewardKind::from_adapter("boundary"), Some(RewardKind::Explore)); assert_eq!(RewardKind::from_adapter("boundary"), Some(RewardKind::Explore));
assert_eq!(RewardKind::from_adapter("catch"), Some(RewardKind::Wildwin)); assert_eq!(RewardKind::from_adapter("catch"), Some(RewardKind::Wildwin));
assert_eq!(RewardKind::from_adapter("talk"), Some(RewardKind::Explore)); assert_eq!(RewardKind::from_adapter("talk"), Some(RewardKind::Explore));
assert_eq!(RewardKind::from_adapter("item"), Some(RewardKind::Explore)); assert_eq!(RewardKind::from_adapter("item"), Some(RewardKind::Explore));
assert_eq!(RewardKind::from_adapter("damage"), None, "a hit is not a wild win");
} }
#[test] #[test]

View file

@ -1,17 +1,19 @@
//! A `v6` checkpoint restored under `v7`: accepted with the opt-in, refused without it. //! A `v7` (and a `v6`) checkpoint restored under `v8`: accepted with the opt-in, refused without
//! it.
//! //!
//! The unit tests in `flybrain-gb` cover the decision function and the adapter's own state //! The unit tests in `flybrain-gb` cover the decision function and the adapter's own state
//! migration separately. This is the two of them against one artefact: a real `FLYSIM01` //! migration separately. This is the two of them against one artefact: a real `FLYSIM01`
//! envelope carrying a `pokered-unique8-v6` compatibility string and a `v6` reward ledger — //! envelope carrying a `pokered-unique8-v7` (or `-v6`) compatibility string and that version's
//! written, encoded, decoded, and then put through exactly what `Sim::try_restore` puts a //! reward ledger — written, encoded, decoded, and then put through exactly what
//! candidate through, and then one sample of a game in which items were already taken. //! `Sim::try_restore` puts a candidate through, and then samples of a game: one in which items
//! were already taken (`v6`), one in the middle of the row 67 battle (`v7`).
//! //!
//! No ROM and no dataset, deliberately. Building a `Sim` would need both, and neither is part of //! No ROM and no dataset, deliberately. Building a `Sim` would need both, and neither is part of
//! the question: what decides a restore is the compatibility string and `import_state`, and what //! the question: what decides a restore is the compatibility string and `import_state`, and what
//! decides the seed is the first sample's read of the cartridge's own item bits. //! decides the seed is the first sample's read of the cartridge's own item bits.
//! //!
//! (`v5` -> `v6`, the catch rule's migration, was this same file; `v6` no longer migrates from //! (`v5` -> `v6`, the catch rule's migration, was this same file, and `v6` -> `v7` the engagement
//! anything, so that pair is refused now like any other.) //! rules'. `v8` reads both `v7` and `v6`: the chain composes, and `v5` stays refused.)
use flybrain_gb::GameAdapter; use flybrain_gb::GameAdapter;
use flybrain_gb::MemoryReader; use flybrain_gb::MemoryReader;
@ -67,7 +69,34 @@ fn v6_reward() -> serde_json::Value {
}) })
} }
/// A `v7` reward ledger: the `v6` one after the engagement rules' first sample (the item seed and
/// a conversation), with a battle in flight -- the row 67 Jr. Trainer's Diglett at 19 of 31 --
/// and **no** `damageCounts`, `counts.damage` or `battle.damage`.
fn v7_reward() -> serde_json::Value {
let mut reward = v6_reward();
let seen = reward["seen"].as_array_mut().unwrap();
for key in ["items:seeded", "item:42", "talk:54:sprite:1"] {
seen.push(serde_json::json!(key));
}
reward["counts"]["talk"] = serde_json::json!(1);
reward["counts"]["item"] = serde_json::json!(0);
reward["mode"] = serde_json::json!("BATTLE");
reward["battle"] = serde_json::json!({
"key": "54:59:11", "wild": false, "sawLiving": true, "ko": false,
"speciesAtStart": 1, "captured": null, "capturedNew": false
});
reward
}
fn v6_checkpoint() -> Vec<u8> { fn v6_checkpoint() -> Vec<u8> {
checkpoint_of("pokered-unique8-v6", v6_reward())
}
fn v7_checkpoint() -> Vec<u8> {
checkpoint_of("pokered-unique8-v7", v7_reward())
}
fn checkpoint_of(adapter: &str, reward: serde_json::Value) -> Vec<u8> {
use flybrain_core::decoder::DecoderState; use flybrain_core::decoder::DecoderState;
use flybrain_core::lif::LifState; use flybrain_core::lif::LifState;
use flybrain_core::ordered::NumberMap; use flybrain_core::ordered::NumberMap;
@ -118,12 +147,12 @@ fn v6_checkpoint() -> Vec<u8> {
wall_ms: 1_790_000_000_000, wall_ms: 1_790_000_000_000,
rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(),
emulator_frame: 1_000_000, emulator_frame: 1_000_000,
compatibility: compatibility("pokered-unique8-v6"), compatibility: compatibility(adapter),
speed: 1.0, speed: 1.0,
buttons: 0, buttons: 0,
rank_since_ms: 1_000.0, rank_since_ms: 1_000.0,
last_event_id: 4_242, last_event_id: 4_242,
reward: v6_reward(), reward,
ratchet: flybrain_gb::RatchetState { best: 3, attempts: 1, recoveries: 4, ..Default::default() }, ratchet: flybrain_gb::RatchetState { best: 3, attempts: 1, recoveries: 4, ..Default::default() },
emulator: vec![3; 64], emulator: vec![3; 64],
framebuffer: vec![0; 32], framebuffer: vec![0; 32],
@ -134,25 +163,31 @@ fn v6_checkpoint() -> Vec<u8> {
} }
#[test] #[test]
fn a_v6_checkpoint_is_refused_under_v7_without_the_opt_in() { fn a_v7_or_v6_checkpoint_is_refused_under_v8_without_its_own_opt_in() {
let checkpoint = store::decode(&v6_checkpoint()).expect("the fixture decodes");
let adapter = PokemonRedReward::new(); let adapter = PokemonRedReward::new();
let current = compatibility(adapter.id()); let current = compatibility(adapter.id());
assert_ne!(checkpoint.runtime.compatibility, current, "v7 is not v6"); for (bytes, own) in
[(v7_checkpoint(), "pokered-unique8-v7"), (v6_checkpoint(), "pokered-unique8-v6")]
for opt_in in [None, Some(""), Some("pokered-unique8-v5"), Some("some-other-adapter")] { {
assert!( let checkpoint = store::decode(&bytes).expect("the fixture decodes");
matches!( assert_ne!(checkpoint.runtime.compatibility, current, "v8 is not {own}");
decide( let other = if own.ends_with("v7") { "pokered-unique8-v6" } else { "pokered-unique8-v7" };
&checkpoint.runtime.compatibility, for opt_in in
&current, [None, Some(""), Some("pokered-unique8-v5"), Some("some-other-adapter"), Some(other)]
adapter.migrates_from(), {
&accepted_adapters(opt_in), assert!(
matches!(
decide(
&checkpoint.runtime.compatibility,
&current,
adapter.migrates_from(),
&accepted_adapters(opt_in),
),
RestoreDecision::Refuse(_)
), ),
RestoreDecision::Refuse(_) "{own} with FLY_ACCEPT_ADAPTERS={opt_in:?} must not migrate"
), );
"FLY_ACCEPT_ADAPTERS={opt_in:?} must not migrate anything" }
);
} }
} }
@ -166,7 +201,7 @@ impl MemoryReader for Wram {
} }
#[test] #[test]
fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_seeded() { fn a_v6_checkpoint_restores_under_v8_with_the_new_ledgers_empty_and_the_items_seeded() {
let checkpoint = store::decode(&v6_checkpoint()).expect("the fixture decodes"); let checkpoint = store::decode(&v6_checkpoint()).expect("the fixture decodes");
let mut adapter = PokemonRedReward::new(); let mut adapter = PokemonRedReward::new();
let current = compatibility(adapter.id()); let current = compatibility(adapter.id());
@ -182,18 +217,20 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se
); );
// The migration itself: `import_state`, exactly as `Sim::try_restore` calls it. // The migration itself: `import_state`, exactly as `Sim::try_restore` calls it.
adapter.import_state(&checkpoint.runtime.reward).expect("a v6 ledger is a valid v7 ledger"); adapter.import_state(&checkpoint.runtime.reward).expect("a v6 ledger is a valid v8 ledger");
let after = adapter.export_state(); let after = adapter.export_state();
assert_eq!(after["counts"]["talk"], serde_json::json!(0), "no conversation was ever paid"); assert_eq!(after["counts"]["talk"], serde_json::json!(0), "no conversation was ever paid");
assert_eq!(after["counts"]["item"], serde_json::json!(0), "nor any item"); assert_eq!(after["counts"]["item"], serde_json::json!(0), "nor any item");
assert_eq!(after["counts"]["damage"], serde_json::json!(0), "nor any damage");
assert_eq!(after["damageCounts"], serde_json::json!({}));
// And nothing else moved: every field the v6 state carried round-trips to the same value, // And nothing else moved: every field the v6 state carried round-trips to the same value;
// and v7 adds no field at all -- its ledgers are keys in `seen`. // v7 added no field (its ledgers are keys in `seen`) and v8 adds one, `damageCounts`.
// //
// `counts` is the one field that is not byte-identical, and it is not a change of meaning: // `counts` is the one field that is not byte-identical, and it is not a change of meaning:
// it serializes every kind in the catalog, so a v7 state lists `talk` and `item` where a v6 // it serializes every kind in the catalog, so a v8 state lists `talk`, `item` and `damage`
// state had nothing to list. Every kind the v6 state did carry keeps its number. // where a v6 state had nothing to list. Every kind the v6 state did carry keeps its number.
let before = v6_reward(); let before = v6_reward();
for (key, value) in before.as_object().unwrap() { for (key, value) in before.as_object().unwrap() {
if key == "counts" { if key == "counts" {
@ -206,7 +243,7 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se
.keys() .keys()
.filter(|kind| !value.as_object().unwrap().contains_key(*kind)) .filter(|kind| !value.as_object().unwrap().contains_key(*kind))
.collect(); .collect();
assert_eq!(added, vec!["talk", "item"], "v7 counts two more kinds and no others"); assert_eq!(added, vec!["talk", "item", "damage"], "three more kinds and no others");
continue; continue;
} }
assert_eq!(&after[key], value, "{key} must survive the migration byte for byte"); assert_eq!(&after[key], value, "{key} must survive the migration byte for byte");
@ -217,7 +254,7 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se
.keys() .keys()
.filter(|key| !before.as_object().unwrap().contains_key(*key)) .filter(|key| !before.as_object().unwrap().contains_key(*key))
.collect(); .collect();
assert!(added.is_empty(), "v7 adds no field: {added:?}"); assert_eq!(added, vec!["damageCounts"], "v8 adds one field");
// The first sample of the restored game. Under v6 the fly took an item ball (global // The first sample of the restored game. Under v6 the fly took an item ball (global
// toggleable index 0x2a) and a hidden item (index 9); v6 paid for neither. The sample seeds // toggleable index 0x2a) and a hidden item (index 9); v6 paid for neither. The sample seeds
@ -250,11 +287,11 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se
#[test] #[test]
fn nothing_but_the_adapter_segment_may_differ_for_the_migration_to_apply() { fn nothing_but_the_adapter_segment_may_differ_for_the_migration_to_apply() {
let adapter = PokemonRedReward::new(); let adapter = PokemonRedReward::new();
let accepted = accepted_adapters(Some("pokered-unique8-v6")); let accepted = accepted_adapters(Some("pokered-unique8-v7"));
let current = compatibility(adapter.id()); let current = compatibility(adapter.id());
// A v6 string whose state format also moved: a different build, not a rule change. // A v7 string whose state format also moved: a different build, not a rule change.
let other_abi = compatibility("pokered-unique8-v6").replace("199616", "199617"); let other_abi = compatibility("pokered-unique8-v7").replace("199616", "199617");
assert!(matches!( assert!(matches!(
decide(&other_abi, &current, adapter.migrates_from(), &accepted), decide(&other_abi, &current, adapter.migrates_from(), &accepted),
RestoreDecision::Refuse(_) RestoreDecision::Refuse(_)
@ -266,14 +303,85 @@ fn nothing_but_the_adapter_segment_may_differ_for_the_migration_to_apply() {
RestoreDecision::Exact RestoreDecision::Exact
); );
// And v5 -> v7 is not a migration this adapter wrote, whatever the operator names. // And v5 -> v8 is not a migration this adapter wrote, whatever the operator names.
assert!(matches!( assert!(matches!(
decide( decide(
&compatibility("pokered-unique8-v5"), &compatibility("pokered-unique8-v5"),
&current, &current,
adapter.migrates_from(), adapter.migrates_from(),
&accepted_adapters(Some("pokered-unique8-v5,pokered-unique8-v6")), &accepted_adapters(Some("pokered-unique8-v5,pokered-unique8-v6,pokered-unique8-v7")),
), ),
RestoreDecision::Refuse(_) RestoreDecision::Refuse(_)
)); ));
} }
/// The enemy battle struct and the turn, as `LoadEnemyMonData` and `ExecutePlayerMove` leave them.
fn battle_wram(hp: u8, fly_turn: bool) -> Wram {
let mut wram = Wram(vec![0; 0x10000]);
wram.0[ram::wStatusFlags6 as usize] = 1;
wram.0[ram::wPartyCount as usize] = 1;
wram.0[ram::wCurMap as usize] = 54;
wram.0[ram::wCurMapWidth as usize] = 5;
wram.0[ram::wCurMapHeight as usize] = 7;
wram.0[ram::wXCoord as usize] = 4;
wram.0[ram::wYCoord as usize] = 10;
wram.0[ram::wIsInBattle as usize] = 2;
wram.0[ram::wEnemyMonPartyPos as usize] = 0;
wram.0[ram::wEnemyMonSpecies as usize] = 59;
wram.0[ram::wEnemyMonLevel as usize] = 11;
wram.0[(ram::wEnemyMonHP + 1) as usize] = hp;
wram.0[(ram::wEnemyMonMaxHP + 1) as usize] = 31;
wram.0[flybrain_gb::pokemon_red::state::poke::H_WHOSE_TURN as usize] = u8::from(!fly_turn);
wram.0[ram::wPlayerMoveNum as usize] = 0x91;
wram
}
#[test]
fn a_v7_checkpoint_taken_mid_battle_restores_under_v8_and_pays_only_what_follows() {
let checkpoint = store::decode(&v7_checkpoint()).expect("the fixture decodes");
let mut adapter = PokemonRedReward::new();
let current = compatibility(adapter.id());
assert_eq!(
decide(
&checkpoint.runtime.compatibility,
&current,
adapter.migrates_from(),
&accepted_adapters(Some("pokered-unique8-v7")),
),
RestoreDecision::MigrateAdapter { from: "pokered-unique8-v7".to_string() }
);
adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a valid v8 ledger");
// Every field v7 carried survives, and v8 adds `damageCounts` and the battle's `damage`.
let before = v7_reward();
let after = adapter.export_state();
for (key, value) in before.as_object().unwrap() {
match key.as_str() {
"counts" => {
for (kind, count) in value.as_object().unwrap() {
assert_eq!(&after["counts"][kind], count, "counts.{kind}");
}
assert_eq!(after["counts"]["damage"], serde_json::json!(0));
}
"battle" => {
for (field, v) in value.as_object().unwrap() {
assert_eq!(&after["battle"][field], v, "battle.{field}");
}
assert_eq!(after["battle"]["damage"]["restored"], serde_json::json!(true));
}
_ => assert_eq!(&after[key], value, "{key} must survive the migration byte for byte"),
}
}
assert_eq!(after["damageCounts"], serde_json::json!({}));
// The restored battle: Diglett stands at 19 of 31. The 12 HP it lost under v7 are not paid;
// its own turn's poison tick is not paid; BUBBLE's next hit is.
assert!(adapter.sample(&mut battle_wram(19, true), 2_000.0).is_empty(), "no back pay");
assert!(adapter.sample(&mut battle_wram(17, false), 2_017.0).is_empty(), "not its turn");
let hit = adapter.sample(&mut battle_wram(8, true), 2_034.0);
assert_eq!(hit.len(), 1);
assert_eq!(hit[0].kind, "damage");
assert_eq!(hit[0].label, "HIT #59 FOR 9 HP");
assert!((hit[0].value - 0.20 * 9.0 / 31.0).abs() < 1e-12);
assert_eq!(adapter.progress().rank, 3, "the rank is untouched");
}

View file

@ -264,10 +264,21 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil
let boot = boot_started.elapsed(); let boot = boot_started.elapsed();
eprintln!("[timing] boot to first healthy /healthz: {:.1} s", boot.as_secs_f64()); eprintln!("[timing] boot to first healthy /healthz: {:.1} s", boot.as_secs_f64());
let (status, versions) = service.get("/status"); // `/healthz` goes green before the first snapshot is published, and until then `/status`
// carries the placeholder header (rank BOOT, a one-rung ladder). On a loaded box that
// window is long enough to be read, so wait (bounded) for the first real snapshot; every
// assertion below is unchanged.
let first_snapshot_by = Instant::now() + Duration::from_secs(30);
let (status, versions) = loop {
let (status, versions) = service.get("/status");
if versions["milestone"]["total"] != json!(1) || Instant::now() >= first_snapshot_by {
break (status, versions);
}
std::thread::sleep(Duration::from_millis(100));
};
assert_eq!(status, 200); assert_eq!(status, 200);
assert_eq!(versions["version"]["kernel"], json!("lif-1ms-f64-v2")); assert_eq!(versions["version"]["kernel"], json!("lif-1ms-f64-v2"));
assert_eq!(versions["version"]["adapter"], json!("pokered-unique8-v7")); assert_eq!(versions["version"]["adapter"], json!("pokered-unique8-v8"));
assert!( assert!(
versions["version"]["dataset"].as_str().unwrap_or_default().len() > 32, versions["version"]["dataset"].as_str().unwrap_or_default().len() > 32,
"the dataset fingerprint is in /status: {}", "the dataset fingerprint is in /status: {}",

View file

@ -33,6 +33,7 @@
//! different test's question; this one says out loud that it skipped. //! different test's question; this one says out loud that it skipped.
use flybrain_core::decoder::PopulationDecoder; use flybrain_core::decoder::PopulationDecoder;
use flybrain_core::decoder::gameboy::to_button_mask;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::ordered::NumberMap; use flybrain_core::ordered::NumberMap;
use flybrain_gb::adapter::RewardEvent; use flybrain_gb::adapter::RewardEvent;
@ -54,7 +55,15 @@ const SEED: u32 = 20_260_922;
const HOT: f64 = 16.0; const HOT: f64 = 16.0;
const REST: f64 = 10.0; const REST: f64 = 10.0;
/// `THROW BALL`'s channel (`pokemon_red::macros::palette`). /// `THROW BALL`'s channel (`pokemon_red::macros::palette`).
///
/// Row 66's note: this is the button's *tag*; its channel is `macro_throw_ball`
/// ([`THROW_BALL_CHANNEL`]), so the lean below sets a rate the decoder does not read and the drive
/// in a wild battle is the calibrated tie. It is kept as it is because that drive is the one that
/// catches from the forest checkpoint (with the real channel hot the checkpoint's one ball misses
/// on this frame timing), and the row 66 test reuses it up to the catch.
const BALL: &str = "MB·BALL"; const BALL: &str = "MB·BALL";
/// `THROW BALL`'s channel as the macro layer binds it.
const THROW_BALL_CHANNEL: &str = "macro_throw_ball";
/// Frames the stub leans on one channel before the rotation moves on, the shape of the real /// Frames the stub leans on one channel before the rotation moves on, the shape of the real
/// group's hysteresis-then-fatigue rotation. /// group's hysteresis-then-fatigue rotation.
const BURST_FRAMES: u32 = 24; const BURST_FRAMES: u32 = 24;
@ -190,9 +199,9 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab
eprintln!("skipped: no FLY_CATCH_CHECKPOINT"); eprintln!("skipped: no FLY_CATCH_CHECKPOINT");
return; return;
}; };
let mut run = Run::resume(&rom, &checkpoint); let balls = Run::resume(&rom, &checkpoint).balls();
let balls = run.balls();
if balls == 0 { if balls == 0 {
let run = Run::resume(&rom, &checkpoint);
eprintln!( eprintln!(
"skipped: the checkpoint's bag holds no ball (map {:#04x}). `BUY BALL` can buy one \ "skipped: the checkpoint's bag holds no ball (map {:#04x}). `BUY BALL` can buy one \
inside a mart; point FLY_CATCH_CHECKPOINT at a state that already has one.", inside a mart; point FLY_CATCH_CHECKPOINT at a state that already has one.",
@ -200,24 +209,47 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab
); );
return; return;
} }
eprintln!("bag holds {balls} balls; map {:#04x}", run.adapter.map_id().unwrap_or(u32::MAX)); eprintln!("bag holds {balls} balls");
// Twenty brain minutes is generous for a forest checkpoint: the live run threw 28 balls in // Five brain minutes per attempt is generous for a forest checkpoint: the live run threw 28
// its first Viridian Forest session (`pokemon_red::macros::palette`). // balls in its first Viridian Forest session (`pokemon_red::macros::palette`). An attempt
let budget = 20 * 60 * 60; // starts after `5 * attempt` frames with nothing pressed, so each one meets the wild battle,
let mut battles = 0u32; // and the ball meets the random number, on a different frame (row 66): one ball misses about
let mut was_in_battle = false; // two throws in three, and which throw a checkpoint's one ball is depends on frame timing
for _ in 0..budget { // that any change to the pad moves.
run.step(); let budget = 5 * 60 * 60;
let now = run.in_wild_battle(); let mut battles;
if now && !was_in_battle { let mut attempt = 0u32;
battles += 1; let mut run = loop {
let mut run = Run::resume(&rom, &checkpoint);
for _ in 0..attempt * 5 {
run.ms += MS_PER_FRAME;
run.frame += 1;
let evaluated = run
.legacy
.stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms)
.expect("a frame should complete");
run.payouts.extend(evaluated.rewards);
} }
was_in_battle = now; battles = 0;
if !run.catches().is_empty() { let mut was_in_battle = false;
break; for _ in 0..budget {
run.step();
let now = run.in_wild_battle();
if now && !was_in_battle {
battles += 1;
}
was_in_battle = now;
if !run.catches().is_empty() {
break;
}
} }
} if !run.catches().is_empty() || attempt == 23 {
break run;
}
eprintln!("attempt {attempt}: no catch ({battles} wild battles, {} balls left)", run.balls());
attempt += 1;
};
let catches = run.catches(); let catches = run.catches();
assert!( assert!(
@ -255,3 +287,523 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab
// sets the bit the `species` rule reads, whether or not it was new to this run. // sets the bit the `species` rule reads, whether or not it was new to this run.
assert!(run.balls() < balls, "a ball was spent"); assert!(run.balls() < balls, "a ball was spent");
} }
/// What one drive from the checkpoint saw after its catch.
struct AfterCatch {
caught_at: u32,
ended_at: u32,
/// Frames between the catch and the battle's end on which `THROW BALL` was on the pad.
ball_dealt: u32,
/// Every pad the fly could decide on in that stretch.
pads: std::collections::BTreeSet<Vec<String>>,
/// Row 69: the naming screen, as this test reads it off the cartridge ([`keyboard`]).
keyboard: Keyboard,
}
/// Row 69: what the naming screen saw, read by this test itself rather than by the palette.
#[derive(Debug, Default)]
struct Keyboard {
/// Frames the keyboard was up.
frames: u32,
/// Frames on it with no macro running on which the cartridge was given a button: the fly's
/// own presses.
raw_frames: u32,
/// Macros started while it was up, by name.
starts: Vec<&'static str>,
/// Pads dealt on it, while nothing ran.
pads: std::collections::BTreeSet<Vec<String>>,
/// The longest the name got, and the name on its last frame (`wStringBuffer`, decoded).
longest: u8,
name: String,
/// Frames from its first frame to its last.
span: u32,
closed: bool,
}
/// `wStringBuffer`, from `CalcStringLength`'s `ld hl, wStringBuffer` on the cartridge (row 69).
const STRING_BUFFER: u16 = 0xcf4b;
/// `wNamingScreenNameLength` (row 69, `pokemon_red::state::poke::NAMING_LENGTH`).
const NAMING_LENGTH: u16 = 0xcee9;
/// The naming screen, as this test reads it: the keyboard's menu bytes, its box's corner at
/// (0, 4), and an underscore under the name at (10, 3). The letters typed, or `None`.
fn keyboard(run: &mut Run) -> Option<u8> {
let tile = |run: &mut Run, x: u16, y: u16| run.byte(ram::wTileMap + y * 20 + x);
let menu = run.byte(ram::wTopMenuItemY) == 3
&& run.byte(ram::wMaxMenuItem) == 7
&& run.byte(ram::wMenuWatchedKeys) == 0xff;
(menu && tile(run, 0, 4) == 0x79 && tile(run, 19, 14) == 0x7e
&& matches!(tile(run, 10, 3), 0x76 | 0x77))
.then(|| run.byte(NAMING_LENGTH))
}
/// The name in `wStringBuffer`, in Red's charmap: capitals from `$80`, small letters from `$a0`.
fn typed(run: &mut Run) -> String {
(0..11u16)
.map(|index| run.byte(STRING_BUFFER + index))
.take_while(|byte| *byte != 0x50)
.map(|byte| match byte {
0x80..=0x99 => char::from(b'A' + (byte - 0x80)),
0xa0..=0xb9 => char::from(b'a' + (byte - 0xa0)),
0x7f => ' ',
_ => '?',
})
.collect()
}
/// One drive: `idle` frames with nothing pressed first (so each attempt reaches the wild battle
/// on a different frame, and the ball meets a different random number), then the first test's
/// drive up to the catch, then the pad's own buttons in turn. `None` when no ball kept anything
/// within the budget: one ball in the bag misses about two throws in three.
fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: u32) -> Option<AfterCatch> {
drive_past_a_catch_typing(rom, checkpoint, idle, true)
}
/// [`drive_past_a_catch`], and on the keyboard lean on A and B (`type_keys`) or on nothing, so
/// only the D-pad group's own rotation reaches it and the row 69 bound is what ends it.
fn drive_past_a_catch_typing(
rom: &[u8],
checkpoint: &flysim::store::Checkpoint,
idle: u32,
type_keys: bool,
) -> Option<AfterCatch> {
let mut run = Run::resume(rom, checkpoint);
for _ in 0..idle {
run.ms += MS_PER_FRAME;
run.frame += 1;
let evaluated = run
.legacy
.stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms)
.expect("a frame should complete");
run.payouts.extend(evaluated.rewards);
}
let budget = 5 * 60 * 60;
let mut caught_at: Option<u32> = None;
let mut ball_dealt = 0u32;
let mut pads = std::collections::BTreeSet::new();
let mut hold = 0usize;
let mut board = Keyboard::default();
let mut board_from: Option<u32> = None;
for frame in 0..budget {
let bound = run.layer.bound_channels();
let on_keyboard = keyboard(&mut run);
let hot = if caught_at.is_some() && on_keyboard.is_some() && bound.is_empty() && !type_keys {
None
} else if caught_at.is_some() && on_keyboard.is_some() && bound.is_empty() {
// Row 69: the keyboard's pad is the fly's own buttons. The stub leans on A (a letter)
// mostly and on B (a deletion) now and then; the D-pad is the direction group's own
// rotation. What the name comes out as is the stub's, as it will be the brain's.
if frame % BURST_FRAMES == 0 {
hold += 1;
}
Some(if hold % 4 == 3 { "command_5".to_string() } else { "command_4".to_string() })
} else if caught_at.is_none() {
if run.in_wild_battle() {
Some(BALL.to_string())
} else {
let slot = (run.frame / BURST_FRAMES) as usize % run.channels.len();
Some(run.channels[slot].to_string())
}
} else if bound.is_empty() {
None
} else {
if frame % BURST_FRAMES == 0 {
hold += 1;
}
Some(bound[hold % bound.len()].clone())
};
if caught_at.is_some() {
if bound.iter().any(|channel| channel == THROW_BALL_CHANNEL) {
ball_dealt += 1;
}
if run.layer.running().is_none() && !bound.is_empty() {
pads.insert(bound.clone());
}
}
let active = run.decoder.decode_bound(&rates(hot.as_deref()), run.ms, false, None, Some(&bound));
// The readout's own buttons as raw mode would press them: the layer passes them to the
// cartridge only where a scene says so (the title, and since row 69 the keyboard).
let raw = to_button_mask(&active);
let idle = run.layer.running().is_none();
let executed =
run.legacy.execute(Some(&mut run.layer), &active, raw, run.ms, &mut run.gb, &run.adapter);
if let Some(length) = on_keyboard {
board.frames += 1;
board_from.get_or_insert(frame);
board.span = frame - board_from.unwrap_or(frame);
board.longest = board.longest.max(length);
board.name = typed(&mut run);
if idle {
if !bound.is_empty() {
board.pads.insert(bound.clone());
}
if executed.mask != 0 && executed.events.is_empty() {
board.raw_frames += 1;
}
}
for event in &executed.events {
if event.outcome.is_none() {
board.starts.push(event.name);
}
}
} else if board.frames > 0 {
board.closed = true;
}
run.ms += MS_PER_FRAME;
run.frame += 1;
let evaluated = run
.legacy
.stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms)
.expect("a frame should complete");
run.payouts.extend(evaluated.rewards);
if caught_at.is_none() && run.byte(ram::wCapturedMonSpecies) != 0 {
caught_at = Some(frame);
}
if let Some(caught_at) = caught_at
&& run.byte(ram::wIsInBattle) == 0
{
assert!(!run.catches().is_empty(), "the catch pays at the battle's end");
return Some(AfterCatch { caught_at, ended_at: frame, ball_dealt, pads, keyboard: board });
}
}
assert!(caught_at.is_none(), "a battle still running {budget} frames after its catch");
None
}
/// Row 66: once a ball has kept a Pokémon, nothing to the end of the battle is the bag.
///
/// After the throw `wListMenuID` still says `ITEMLISTMENU` -- it is written when a list opens and
/// never cleared -- so on v0.6.5 every frame from "All right! … was caught!" through the Pokédex
/// page, the nickname offer and the naming screen read as an open battle bag. The pad was `BACK`
/// and `THROW BALL`, a `THROW BALL` that threw nothing and whose A presses typed the nickname;
/// driven from the rung-8 survey checkpoint the battle took 6,900 frames to end after the catch.
///
/// The drive after the catch leans on the pad's own buttons in turn (not the whole channel
/// list), so what it measures is what the pad offers, not how often a rotation over every channel
/// lands on it.
#[test]
fn row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let Some(checkpoint) = checkpoint() else {
eprintln!("skipped: no FLY_CATCH_CHECKPOINT");
return;
};
if Run::resume(&rom, &checkpoint).balls() == 0 {
eprintln!("skipped: the checkpoint's bag holds no ball");
return;
}
let after = (0..24)
.find_map(|attempt| {
let after = drive_past_a_catch(&rom, &checkpoint, attempt * 5);
if after.is_none() {
eprintln!("attempt {attempt}: the ball missed");
}
after
})
.expect("one of 24 attempts should keep a Pokémon");
eprintln!(
"caught at f{}, battle over at f{} ({} frames); THROW BALL dealt on {} of them; pads {:?}",
after.caught_at,
after.ended_at,
after.ended_at - after.caught_at,
after.ball_dealt,
after.pads
);
assert_eq!(after.ball_dealt, 0, "THROW BALL on the pad after the catch: {:?}", after.pads);
assert!(
after.pads.iter().all(|pad| !pad.iter().any(|channel| channel == "macro_back")),
"BACK on the pad after the catch, with no list up: {:?}",
after.pads
);
assert!(
after.ended_at - after.caught_at < 3_000,
"the battle took {} frames to end after the catch",
after.ended_at - after.caught_at
);
}
/// Row 69 ("let the fly name it"): after a catch the nickname offer is answered YES as before,
/// and the keyboard's pad is the fly's own buttons -- the D-pad, A, B, START -- with no macro on
/// it, until the name is full (or the bound runs), when `CONFIRM` alone hands the name back. The
/// keyboard closes and the battle ends.
///
/// On a69a258 (row 66) the keyboard read as the battle's between-turns frame and its pad was
/// `NEXT`, whose A presses typed the name.
#[test]
fn row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let Some(checkpoint) = checkpoint() else {
eprintln!("skipped: no FLY_CATCH_CHECKPOINT");
return;
};
if Run::resume(&rom, &checkpoint).balls() == 0 {
eprintln!("skipped: the checkpoint's bag holds no ball");
return;
}
let after = (0..24)
.find_map(|attempt| drive_past_a_catch(&rom, &checkpoint, attempt * 5))
.expect("one of 24 attempts should keep a Pokémon");
let board = &after.keyboard;
eprintln!(
"caught at f{}, battle over at f{}; keyboard {} frames over {} (raw {}), longest {}, \
name {:?}, starts {:?}, pads {:?}, closed {}",
after.caught_at,
after.ended_at,
board.frames,
board.span,
board.raw_frames,
board.longest,
board.name,
board.starts,
board.pads,
board.closed
);
assert!(board.frames > 0, "a catch goes to the keyboard (the nickname offer answered YES)");
assert!(board.raw_frames > 0, "the fly's own buttons reached the keyboard");
assert!(board.longest > 0, "the fly typed a letter");
assert!(
board.starts.iter().all(|name| *name == "CONFIRM"),
"no macro types on the keyboard: {:?}",
board.starts
);
assert!(
board.pads.iter().all(|pad| pad == &vec!["macro_confirm".to_string()]),
"the keyboard deals CONFIRM alone or nothing: {:?}",
board.pads
);
assert_ne!(board.name, "AAAAAAAAAA", "not the name NEXT's A presses typed on a69a258");
assert!(board.closed, "the keyboard closed");
// The bound is sixty brain seconds, about 3,600 frames; the stub fills the name long before.
assert!(board.span < 3_700, "the keyboard was up for {} frames", board.span);
assert!(after.ended_at - after.caught_at < 6_000, "the battle ended");
}
/// `ItemUseBall`'s HP test, this file's own reading of it (`engine/items/item_effects.asm`): for
/// the first ball in the bag, `(MaxHP * 255 / BallFactor) / max(HP / 4, 1) >= 255`, a factor of 8
/// for a Great Ball and 12 for the rest.
fn enemy_low(run: &mut Run) -> bool {
let word = |run: &mut Run, address: u16| {
u16::from(run.byte(address)) * 256 + u16::from(run.byte(address + 1))
};
let hp = word(run, ram::wEnemyMonHP);
let max = word(run, ram::wEnemyMonMaxHP);
let Some(ball) = state::bag(&mut run.gb)
.iter()
.find(|item| (0x01..=0x04).contains(&item.id) && item.count > 0)
.map(|item| item.id)
else {
return false;
};
if hp == 0 || max == 0 || hp > max {
return false;
}
let factor: u32 = if ball == 0x03 { 8 } else { 12 };
let quarter = u32::from((hp >> 2) as u8).max(1);
(u32::from(max) * 255 / factor) / quarter >= 255
}
/// Row 69's checkpoint for the low-HP drive, or the catch checkpoint when it is not set.
///
/// The catch checkpoint's lead is a level-twenty Wartortle that takes every forest Pokémon from
/// full HP to nothing in one hit, so no wild Pokémon is ever *low* there. `FLY_ROW69_CHECKPOINT`
/// names a rung-9 state whose lead is weak enough for a wild Pokémon's HP to pass through a third
/// on its way down, with a ball in the bag.
fn row69_checkpoint() -> Option<flysim::store::Checkpoint> {
let path = std::env::var_os("FLY_ROW69_CHECKPOINT")?;
Some(
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope"),
)
}
/// Row 69 ("throw on low HP only"): in a wild battle, with a ball in the bag and the wild
/// Pokémon's HP where the ball's HP factor is at its best, `THROW BALL` is the only attack-side
/// button on the pad -- no `MOVE n`, no `SWITCH`, no `RUN` -- and the throw happens.
///
/// The stub leans on the pad's own buttons in turn, leaving `THROW BALL` alone while HP is high
/// so the checkpoint's one ball is not spent before the HP is low. On a69a258 the low-HP pads
/// hold the moves beside the ball.
#[test]
fn row69_at_low_hp_a_wild_battles_pad_is_the_ball() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let Some(checkpoint) = row69_checkpoint() else {
eprintln!("skipped: no FLY_ROW69_CHECKPOINT");
return;
};
if Run::resume(&rom, &checkpoint).balls() == 0 {
eprintln!("skipped: the checkpoint's bag holds no ball");
return;
}
let mut low_pads: std::collections::BTreeSet<Vec<String>> = Default::default();
let mut high_ball_pads: std::collections::BTreeSet<Vec<String>> = Default::default();
let mut low_frames = 0u32;
let mut thrown_low = 0u32;
let mut battles = 0u32;
let mut hp_log: Vec<(u8, u16, u16, u16)> = Vec::new();
for attempt in 0..16u32 {
let mut run = Run::resume(&rom, &checkpoint);
for _ in 0..attempt * 7 {
run.ms += MS_PER_FRAME;
run.frame += 1;
let _ = run
.legacy
.stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms)
.expect("a frame should complete");
}
let mut hold = 0usize;
let mut was_wild = false;
for frame in 0..3 * 60 * 60u32 {
let bound = run.layer.bound_channels();
let wild = run.in_wild_battle();
if wild && !was_wild {
battles += 1;
}
was_wild = wild;
let low = wild && enemy_low(&mut run);
if wild {
let hp = u16::from(run.byte(ram::wEnemyMonHP)) * 256
+ u16::from(run.byte(ram::wEnemyMonHP + 1));
let max = u16::from(run.byte(ram::wEnemyMonMaxHP)) * 256
+ u16::from(run.byte(ram::wEnemyMonMaxHP + 1));
let own = u16::from(run.byte(ram::wBattleMonHP)) * 256
+ u16::from(run.byte(ram::wBattleMonHP + 1));
let seen = (run.byte(ram::wEnemyMonSpecies), hp, max, own);
if hp_log.last() != Some(&seen) {
hp_log.push(seen);
}
}
let idle = run.layer.running().is_none();
if idle && wild && bound.iter().any(|channel| channel == THROW_BALL_CHANNEL) {
if low {
low_frames += 1;
low_pads.insert(bound.clone());
} else {
high_ball_pads.insert(bound.clone());
}
}
let hot = if wild && !bound.is_empty() {
if frame % BURST_FRAMES == 0 {
hold += 1;
}
// Not `RUN` either: a fled battle never reaches low HP.
let choices: Vec<&String> = bound
.iter()
.filter(|channel| low || *channel != THROW_BALL_CHANNEL)
.filter(|channel| *channel != "macro_run")
.collect();
choices.get(hold % choices.len().max(1)).map(|channel| channel.to_string())
} else {
let slot = (run.frame / BURST_FRAMES) as usize % run.channels.len();
Some(run.channels[slot].to_string())
};
let balls = run.balls();
let active =
run.decoder.decode_bound(&rates(hot.as_deref()), run.ms, false, None, Some(&bound));
run.legacy.execute(Some(&mut run.layer), &active, 0, run.ms, &mut run.gb, &run.adapter);
run.ms += MS_PER_FRAME;
run.frame += 1;
let evaluated = run
.legacy
.stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms)
.expect("a frame should complete");
run.payouts.extend(evaluated.rewards);
if run.balls() < balls {
if low {
thrown_low += 1;
}
break;
}
}
if thrown_low > 0 && low_frames > 0 {
break;
}
}
eprintln!(
"{battles} wild battles; {low_frames} low-HP frames with the ball dealt; thrown at low HP \
{thrown_low}; low pads {low_pads:?}; high pads with the ball {high_ball_pads:?}"
);
eprintln!("(species, enemy hp, max, own hp) as it changed: {:?}", &hp_log[..hp_log.len().min(120)]);
assert!(low_frames > 0, "no wild battle reached low HP with a ball dealt");
let allowed = [THROW_BALL_CHANNEL, "macro_item"];
for pad in &low_pads {
assert!(
pad.iter().all(|channel| allowed.contains(&channel.as_str())),
"a low-HP pad with more than the ball on its attack side: {pad:?}"
);
}
assert!(thrown_low > 0, "the ball was thrown at low HP");
}
/// Row 69's bound: a fly that types nothing is not left on the keyboard. After sixty brain seconds
/// (`palette::NAMING_BOUND_MS`) `CONFIRM` alone is dealt, hands the name back empty, and the
/// cartridge keeps the species' own name. The stub presses no letter: only the D-pad group's own
/// rotation reaches the keyboard.
#[test]
fn row69_a_fly_that_types_nothing_is_ended_by_the_bound() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let Some(checkpoint) = checkpoint() else {
eprintln!("skipped: no FLY_CATCH_CHECKPOINT");
return;
};
if Run::resume(&rom, &checkpoint).balls() == 0 {
eprintln!("skipped: the checkpoint's bag holds no ball");
return;
}
let after = (0..24)
.find_map(|attempt| drive_past_a_catch_typing(&rom, &checkpoint, attempt * 5, false))
.expect("one of 24 attempts should keep a Pokémon");
let board = &after.keyboard;
eprintln!(
"keyboard {} frames over {} (raw {}), longest {}, name {:?}, starts {:?}, pads {:?}, \
closed {}",
board.frames,
board.span,
board.raw_frames,
board.longest,
board.name,
board.starts,
board.pads,
board.closed
);
assert_eq!(board.longest, 0, "nothing typed");
assert_eq!(board.starts, vec!["CONFIRM"], "the bound's one button, once");
assert_eq!(
board.pads.iter().cloned().collect::<Vec<_>>(),
vec![vec!["macro_confirm".to_string()]]
);
// Sixty brain seconds at 59.7275 frames a second is 3,584 frames, and a little for the press.
assert!((3_500..3_800).contains(&board.span), "the bound ran: {} frames", board.span);
assert!(board.closed);
}
/// Row 69: the two naming-screen bytes the palette reads are where the cartridge's own
/// instructions store them. `PrintNicknameAndUnderscores`: `ld a, c / ld [wNamingScreenNameLength],
/// a / hlcoord 10, 2` (`$79 $EA lo hi $21 $D2 $C3`); `DisplayNamingScreen.pressedStart`:
/// `ld a, 1 / ld [wNamingScreenSubmitName], a / ret` (`$3E $01 $EA lo hi $C9`).
#[test]
fn row69_the_naming_bytes_are_where_the_cartridge_stores_them() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
use flybrain_gb::pokemon_red::state::poke;
let [lo, hi] = poke::NAMING_LENGTH.to_le_bytes();
let length = [0x79, 0xea, lo, hi, 0x21, 0xd2, 0xc3];
assert!(rom.windows(length.len()).any(|window| window == length), "wNamingScreenNameLength");
let [lo, hi] = poke::NAMING_SUBMIT.to_le_bytes();
let submit = [0x3e, 0x01, 0xea, lo, hi, 0xc9];
assert!(rom.windows(submit.len()).any(|window| window == submit), "wNamingScreenSubmitName");
assert_eq!(poke::NAMING_SUBMIT, poke::NAMING_LENGTH + 1, "consecutive in the UNION");
}

View file

@ -0,0 +1,278 @@
//! The damage reward against the real cartridge, from the live row 67 checkpoint.
//!
//! Gated on `FLY_ROM` *and* on the checkpoint, the way every ROM test in this workspace is, and
//! skips cleanly without either:
//!
//! ```sh
//! FLY_ROM="$HOME/roms/pokemon-red.gb" \
//! FLY_ROW67_CHECKPOINT=.local/checkpoints/<the row 67 Pewter checkpoint> \
//! cargo test --release -p flysim --test rom_damage -- --nocapture
//! ```
//!
//! ## What only the cartridge can answer
//!
//! The synthetic traces in `pokemon_red/tests.rs` and `pokemon_red/damage.rs` write
//! `wEnemyMonHP`, `hWhoseTurn` and `wPlayerMoveNum` from the disassembly. They cannot say that
//! `hWhoseTurn` is at `$FFF3` on this cartridge, that it reads 0 on the frame the fly's BUBBLE
//! lands and 1 on the frame the enemy's attack does, or that the enemy's HP drops on a frame the
//! adapter samples with the move that did it still in `wPlayerMoveNum`. This test does, with the
//! shipping adapter sampling once a frame -- and it restores the checkpoint's own `v7` reward
//! ledger, so it is also the `v7` -> `v8` migration on the live run's state.
//!
//! ## How the fly is moved
//!
//! Not by a brain: the shipping palette (`PokemonPalette`) deals the pad, and a harness picks. Out
//! of battle the pick is uniform over what the pad deals, which is what `row67_the_gym_trainer_is_
//! beaten_from_what_the_pad_deals` (`rom_macros_mode.rs`) showed reaches the gym's Jr. Trainer.
//! In battle it rotates the three moves -- TAIL WHIP, BUBBLE, TACKLE -- so each is used, and the
//! test asserts what each one was paid.
use std::collections::BTreeMap;
use flybrain_gb::adapter::RewardEvent;
use flybrain_gb::compatibility::{RestoreDecision, accepted_adapters, decide};
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::pokemon_red::symbols::ram;
use flybrain_gb::pokemon_red::{MIGRATES_FROM, PokemonRedReward, REWARD_ADAPTER, state};
use flybrain_gb::{
AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, GameAdapter,
MacroPalette, MemoryReader, Started,
};
const MS_PER_FRAME: f64 = 1000.0 / 59.7275;
const SEED: u32 = 20_260_929;
/// `constants/move_constants.asm`.
const TACKLE: u8 = 0x21;
const TAIL_WHIP: u8 = 0x27;
const BUBBLE: u8 = 0x91;
fn rom() -> Option<Vec<u8>> {
let path = std::env::var_os("FLY_ROM")?;
match std::fs::read(&path) {
Ok(bytes) => Some(bytes),
Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"),
}
}
fn checkpoint() -> Option<flysim::store::Checkpoint> {
let path = std::env::var_os("FLY_ROW67_CHECKPOINT")?;
Some(
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope"),
)
}
fn hp(gb: &mut Emulator, address: u16) -> u16 {
u16::from(gb.read8(address)) << 8 | u16::from(gb.read8(address + 1))
}
/// The live `v7` checkpoint is refused by this build without the opt-in and restored with it, by
/// the same decision `Sim::try_restore` makes, and its reward ledger imports.
#[test]
fn the_live_v7_checkpoint_migrates_to_v8() {
let Some(checkpoint) = checkpoint() else {
eprintln!("skipped: no FLY_ROW67_CHECKPOINT");
return;
};
let live = checkpoint.runtime.compatibility.clone();
let segments: Vec<&str> = live.split('/').collect();
assert_eq!(segments[1], "pokered-unique8-v7", "the live run is v7: {live}");
// This build's string is the live one with the adapter segment moved and nothing else: the
// dataset, kernel, plasticity, emulator, symbols and state format are the same build inputs.
let mut ours = segments.clone();
ours[1] = REWARD_ADAPTER;
let current = ours.join("/");
assert!(matches!(decide(&live, &current, MIGRATES_FROM, &[]), RestoreDecision::Refuse(_)));
assert_eq!(
decide(&live, &current, MIGRATES_FROM, &accepted_adapters(Some("pokered-unique8-v7"))),
RestoreDecision::MigrateAdapter { from: "pokered-unique8-v7".to_string() }
);
let mut adapter = PokemonRedReward::new();
adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a v8 ledger");
let state = adapter.export_state();
assert_eq!(state["damageCounts"], serde_json::json!({}));
assert_eq!(state["counts"]["damage"], serde_json::json!(0));
for kind in ["milestone", "map", "trainer", "battle", "talk", "item", "catch"] {
assert_eq!(
state["counts"][kind], checkpoint.runtime.reward["counts"][kind],
"counts.{kind} survives"
);
}
assert_eq!(state["seen"], checkpoint.runtime.reward["seen"], "the ledger survives");
assert_eq!(adapter.progress().rank, 10, "PEWTER CITY");
}
/// BUBBLE and TACKLE are paid when they land, TAIL WHIP never is, and the enemy's own hits land
/// while `hWhoseTurn` reads 1.
#[test]
fn damage_pays_on_bubble_and_tackle_and_not_on_tail_whip() {
let (Some(rom), Some(checkpoint)) = (rom(), checkpoint()) else {
eprintln!("skipped: needs FLY_ROM and FLY_ROW67_CHECKPOINT");
return;
};
let mut gb = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.expect("binjgb should accept the cartridge");
gb.import_state(&checkpoint.runtime.emulator).expect("the checkpoint's emulator state");
let mut adapter = PokemonRedReward::new();
adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a v8 ledger");
let mut palette = PokemonPalette::new(SEED);
let rotation = ["MOVE 2", "MOVE 3", "MOVE 1"];
let mut next_move = 0usize;
let hold_frames = 48u32;
let mut since_decision = hold_frames;
let mut running = false;
let mut rng = 7u32;
let mut ms = 0.0;
// Per move id: moves started, enemy HP drops seen, damage events paid, HP paid for.
let mut chosen: BTreeMap<u8, u32> = BTreeMap::new();
let mut drops: BTreeMap<u8, u32> = BTreeMap::new();
let mut paid: BTreeMap<u8, Vec<RewardEvent>> = BTreeMap::new();
let mut enemy_drop_turns: BTreeMap<u8, u32> = BTreeMap::new();
let mut own_drop_turns: BTreeMap<u8, u32> = BTreeMap::new();
let mut last_enemy: Option<(u8, u8, u16)> = None;
let mut last_own: Option<u16> = None;
let mut trainer_battles = 0u32;
let mut fighting = gb.read8(ram::wIsInBattle);
// Frames from the `MOVE n` start to the payout it earned: how old the choice's trace is.
let mut chose_at: Option<u32> = None;
let mut delays: Vec<u32> = Vec::new();
for frame in 0..90_000u32 {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&adapter);
palette.observe(&mut gb, &ledger)
};
let mut mask = 0u8;
{
let ledger = AdapterLedger(&adapter);
if running {
match palette.step(&mut gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
let moves: Vec<_> =
observed.bindings.iter().filter(|b| b.name.starts_with("MOVE ")).collect();
let binding = if moves.is_empty() {
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
&observed.bindings[(rng >> 8) as usize % observed.bindings.len()]
} else {
let want = rotation[next_move % rotation.len()];
let pick = moves.iter().find(|b| b.name == want).unwrap_or(&moves[0]);
next_move += 1;
pick
};
if let Some(n) = binding.name.strip_prefix("MOVE ").and_then(|n| n.parse::<u16>().ok())
{
let id = gb.read8(ram::wBattleMonMoves + n - 1);
*chosen.entry(id).or_default() += 1;
chose_at = Some(frame);
}
if let Started::Running(_) = palette.start(binding.slot, &mut gb, &ledger) {
running = true;
match palette.step(&mut gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
}
}
}
since_decision += 1;
gb.set_buttons(mask);
gb.run_frame().expect("a frame should complete");
ms += MS_PER_FRAME;
let events = adapter.sample(&mut gb, ms);
let in_battle = gb.read8(ram::wIsInBattle);
if fighting == 0 && in_battle == 2 {
trainer_battles += 1;
}
fighting = in_battle;
let whose = gb.read8(state::poke::H_WHOSE_TURN);
let move_id = gb.read8(ram::wPlayerMoveNum);
if in_battle == 2 {
let enemy = (
gb.read8(ram::wEnemyMonPartyPos),
gb.read8(ram::wEnemyMonSpecies),
hp(&mut gb, ram::wEnemyMonHP),
);
if let Some(before) = last_enemy
&& (before.0, before.1) == (enemy.0, enemy.1)
&& enemy.2 < before.2
{
*enemy_drop_turns.entry(whose).or_default() += 1;
if whose == 0 {
*drops.entry(move_id).or_default() += 1;
}
}
last_enemy = Some(enemy);
let own = hp(&mut gb, ram::wBattleMonHP);
if let Some(before) = last_own
&& own < before
{
*own_drop_turns.entry(whose).or_default() += 1;
}
last_own = Some(own);
} else {
last_enemy = None;
last_own = None;
}
for event in events.into_iter().filter(|event| event.kind == "damage") {
assert_eq!(whose, 0, "a damage payout on the enemy's turn: {event:?}");
assert_eq!(in_battle, 2, "the walk to the gym has no grass: {event:?}");
paid.entry(move_id).or_default().push(event);
delays.extend(chose_at.map(|at| frame - at));
}
let hits = |id: u8| paid.get(&id).map_or(0, Vec::len);
if hits(BUBBLE) >= 2
&& hits(TACKLE) >= 2
&& chosen.get(&TAIL_WHIP).copied().unwrap_or(0) >= 3
&& own_drop_turns.values().sum::<u32>() >= 2
{
break;
}
}
let summary: BTreeMap<u8, Vec<(String, f64)>> = paid
.iter()
.map(|(id, events)| {
(*id, events.iter().map(|event| (event.label.clone(), event.value)).collect())
})
.collect();
eprintln!(
"{:.1} brain minutes, {trainer_battles} trainer battle(s). moves chosen {chosen:?}; \
enemy HP drops on the fly's turn by move {drops:?}; enemy drops by hWhoseTurn \
{enemy_drop_turns:?}; own drops by hWhoseTurn {own_drop_turns:?}; damage paid by move \
{summary:?}; frames from the MOVE press to its payout {delays:?}",
ms / 60_000.0
);
assert!(trainer_battles > 0, "the run never reached the trainer's battle");
assert!(chosen.get(&TAIL_WHIP).copied().unwrap_or(0) >= 3, "TAIL WHIP was not used");
assert!(!paid.contains_key(&TAIL_WHIP), "TAIL WHIP was paid: {summary:?}");
for id in [BUBBLE, TACKLE] {
let events = paid.get(&id).map(Vec::as_slice).unwrap_or_default();
assert!(events.len() >= 2, "move {id:#04x} was not paid twice: {summary:?}");
for event in events {
assert!(event.value > 0.0 && event.value <= 0.25 + 1e-12, "{event:?}");
assert_eq!(event.stimulation_ms, 80);
}
}
// The address, pinned on the cartridge: the fly's hits land on 0, the enemy's on 1.
assert_eq!(enemy_drop_turns.get(&1), None, "the enemy lost HP on its own turn");
assert!(own_drop_turns.get(&1).copied().unwrap_or(0) >= 2, "{own_drop_turns:?}");
assert_eq!(own_drop_turns.get(&0), None, "the fly lost HP on its own turn: {own_drop_turns:?}");
// Every drop on the fly's turn was paid, and only those.
for (id, count) in &drops {
assert_eq!(
paid.get(id).map_or(0, Vec::len) as u32,
*count,
"move {id:#04x}: every drop it caused is one payout"
);
}
}

View file

@ -1011,8 +1011,11 @@ impl Run {
} }
} }
// Section 12.13's claim, per frame: an `Unknown` with nothing drawn deals nothing. // Section 12.13's claim, per frame: an `Unknown` with nothing drawn deals nothing.
// The keyboard (row 69) is drawn -- its own box, not the text font -- and its bound's
// `CONFIRM` is a pad on something drawn, so it is not counted.
if self.layer.scene_name() == "unknown" if self.layer.scene_name() == "unknown"
&& !flybrain_gb::pokemon_red::state::text_box(&mut self.gb).open && !flybrain_gb::pokemon_red::state::text_box(&mut self.gb).open
&& flybrain_gb::pokemon_red::state::naming_screen(&mut self.gb).is_none()
&& !self.layer.bound_channels().is_empty() && !self.layer.bound_channels().is_empty()
{ {
self.unknown_pads_with_no_box += 1; self.unknown_pads_with_no_box += 1;
@ -1976,11 +1979,20 @@ fn gate_checkpoint() -> Option<flysim::store::Checkpoint> {
/// is `BACK`. 600,000 frames of it. /// is `BACK`. 600,000 frames of it.
/// ///
/// What is asserted: `ATTACK` is on the pad of the fly's own turn, the macro behind it **starts /// What is asserted: `ATTACK` is on the pad of the fly's own turn, the macro behind it **starts
/// and runs on the cartridge** from this state, that turn never deals one button, and the battle /// and runs on the cartridge** from this state, that turn never deals an empty pad, and the battle
/// ends — which is the whole claim, because a turn that can be ended is a battle that finishes one /// ends — which is the whole claim, because a turn that can be ended is a battle that finishes one
/// way or the other. Which way is not asserted: with 6 of 34 HP against a trainer the measured run /// way or the other. Which way is not asserted: with 6 of 34 HP against a trainer the measured run
/// faints and blacks out, and that is the game rather than the macro layer. /// faints and blacks out, and that is the game rather than the macro layer.
/// ///
/// **The checkpoint is a trainer battle** (a Bug Catcher, `wIsInBattle` 2) with one Poké Ball and
/// no Potion in the bag, not the wild battle of the live stall. Its own turn is `MOVE 1` alone,
/// and that is the pad the rules deal (row 67, 2026-09-29, measured): `RUN` is a wild battle's,
/// `THROW BALL` too, `ITEM` needs a Potion, `SWITCH` a reserve, and a spent move beside `MOVE 1`
/// is off the pad since 12.23 and 12.27. `MOVE 1` is FIGHT's backstop (12.8): FIGHT opens,
/// "has no moves left!", Struggle, and the battle ends in 1,487 frames. The assertion used to be
/// "more than one button", which only a button that does nothing could satisfy here; it had been
/// red on main since before row 63 and skipped wherever `FLY_NOPP_CHECKPOINT` was unset.
///
/// Gated on `FLY_ROM` and on a checkpoint in that state, which /// Gated on `FLY_ROM` and on a checkpoint in that state, which
/// `examples/scene_probe.rs` writes with `FLY_PROBE_CATCH=noattack FLY_PROBE_SAVE=…` — 99 brain /// `examples/scene_probe.rs` writes with `FLY_PROBE_CATCH=noattack FLY_PROBE_SAVE=…` — 99 brain
/// minutes of the stub from the gate-house checkpoint, the release box's own run carried forward. /// minutes of the stub from the gate-house checkpoint, the release box's own run carried forward.
@ -2026,7 +2038,7 @@ fn macros_mode_ends_a_turn_with_no_move_left_on_the_cartridge() {
run.started run.started
); );
assert!( assert!(
run.battle_pad.is_some_and(|dealt| dealt > 1), run.battle_pad.is_some_and(|dealt| dealt >= 1),
"the fly's own turn dealt a pad of {:?} buttons: by name {:?}", "the fly's own turn dealt a pad of {:?} buttons: by name {:?}",
run.battle_pad, run.battle_pad,
run.started run.started
@ -4554,3 +4566,370 @@ fn row65_the_fly_leaves_the_cerulean_badge_houses_back_yard() {
assert!(worst_empty < 600, "an empty pad in the yard for {worst_empty} frames: {:?}", run.started); assert!(worst_empty < 600, "an empty pad in the yard for {worst_empty} frames: {:?}", run.started);
assert!(left.is_some(), "the fly never left the yard: {:?} {:?}", run.route, run.started); assert!(left.is_some(), "the fly never left the yard: {:?} {:?}", run.route, run.started);
} }
fn row66_mart_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW66_MART_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 66: a fly that walks up to the Viridian clerk and away again without a `TALK` is not
/// walked straight back in by `GO SHOP`.
///
/// **What was live** (v0.6.5, restored from the rung-8 archive): `GO SHOP` done 33 times in 35
/// minutes, `TALK` 5, `BUY BALL` never dealt -- in from the street to the counter, `GO OUT` or
/// `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again because the bag
/// still held no ball (row 62's "dealt again while the service is needed", with no window).
/// Reproduced with the connectome from this checkpoint: three laps in eighteen brain seconds.
///
/// The drive declines the counter on purpose: `GO SHOP` whenever it is dealt, then the ways out,
/// never `TALK`. It says nothing about which button the fly would press; the claim is that the pad
/// does not deal the walk back to a counter the fly has just walked away from (section 12.1's
/// reached window, applied to the service walk).
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW66_MART_CHECKPOINT=.local/checkpoints/survey-rank8-row66-viridian-mart.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row66
/// ```
#[test]
fn row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop() {
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::{MacroPalette, Outcome, Started};
let rom = skip_without_rom!();
let Some(checkpoint) = row66_mart_checkpoint() else {
eprintln!("skipped: no FLY_ROW66_MART_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.bag_count(POKE_BALL), 0, "no ball at the checkpoint");
assert!(run.money() >= 200, "and the money for one: {}", run.money());
let order = ["GO SHOP", "GO OUT", "GO OBJECTIVE"];
let hold_frames = 48u32;
let mut palette = PokemonPalette::new(SEED);
let mut running: Option<&'static str> = None;
let mut since_decision = hold_frames;
let mut ms = run.ms;
// `GO SHOP` walks that finished facing the counter, `TALK` dealt there, and `GO SHOP` walks
// started from the street outside after the first of those.
let mut at_the_counter = 0u32;
let mut talk_dealt_at_the_counter = false;
let mut from_the_street_after = 0u32;
let mut laps = 0u32;
let mut last_map = run.map();
for _ in 0..10_000u32 {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
let mut mask = 0u8;
{
let ledger = AdapterLedger(&run.adapter);
if running.is_some() {
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
if at_the_counter > 0
&& run.map() == VIRIDIAN_MART
&& observed.bindings.iter().any(|binding| binding.name == "TALK")
{
talk_dealt_at_the_counter = true;
}
let binding = order
.iter()
.find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want))
.or_else(|| observed.bindings.iter().find(|binding| binding.name != "TALK"))
.unwrap_or(&observed.bindings[0]);
if binding.name == "GO SHOP" && run.map() != VIRIDIAN_MART && at_the_counter > 0 {
from_the_street_after += 1;
}
if let Started::Running(name) = palette.start(binding.slot, &mut run.gb, &ledger) {
running = Some(name);
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
}
}
}
if let Some((name, outcome)) = palette.take_finished()
&& name == "GO SHOP"
&& outcome == Outcome::Done
&& run.map() == VIRIDIAN_MART
{
at_the_counter += 1;
}
since_decision += 1;
run.gb.set_buttons(mask);
run.gb.run_frame().expect("a frame should complete");
ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, ms);
let map = run.map();
if map == VIRIDIAN_MART && last_map == VIRIDIAN_CITY {
laps += 1;
}
last_map = map;
}
eprintln!(
"GO SHOP done in the mart {at_the_counter}, TALK dealt at the counter \
{talk_dealt_at_the_counter}, GO SHOP from the street after that {from_the_street_after}, \
walks back into the mart {laps}, balls {}",
run.bag_count(POKE_BALL)
);
assert!(at_the_counter >= 1, "the first GO SHOP walks the fly to the clerk");
assert!(talk_dealt_at_the_counter, "and the press that opens the counter is on the pad there");
assert_eq!(
from_the_street_after, 0,
"GO SHOP dealt on the street again after the fly walked away from the counter"
);
}
/// Row 66, the operator's decision: `BUY BALL` is one button from a mart's floor, modelled on
/// `HEAL`, and pressed it rings up a ball.
///
/// From the post-parcel Viridian mart (793 in the wallet, no ball): `BUY BALL` whenever it is
/// dealt, otherwise a uniform pick among the buttons on the pad. The claim is about the pad and the
/// script, not the fly's choice: on the floor of the mart the button is dealt, and one press of it
/// walks to the clerk, opens the counter and rings up one ball. On v0.6.5 it was dealt only at an
/// open counter, which took `TALK`, the greeting and `CONFIRM` first, and the connectome never
/// chose `TALK` there (three laps of `GO SHOP` and out in eighteen brain seconds).
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW66_MART_CHECKPOINT=.local/checkpoints/survey-rank8-row66-viridian-mart.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row66
/// ```
#[test]
fn row66_buy_ball_from_the_marts_floor_rings_up_a_ball() {
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::{MacroPalette, Outcome, Started};
let rom = skip_without_rom!();
let Some(checkpoint) = row66_mart_checkpoint() else {
eprintln!("skipped: no FLY_ROW66_MART_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.bag_count(POKE_BALL), 0, "no ball at the checkpoint");
let money = run.money();
let hold_frames = 48u32;
let mut palette = PokemonPalette::new(SEED);
let mut running: Option<&'static str> = None;
let mut since_decision = hold_frames;
let mut ms = run.ms;
let mut rng = 0x2026_0929u32;
let mut dealt_on_the_floor = 0u32;
let mut started = 0u32;
let mut done = 0u32;
let mut bought_at = None;
for frame in 0..20_000u32 {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
let mut mask = 0u8;
{
let ledger = AdapterLedger(&run.adapter);
if running.is_some() {
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
if run.map() == VIRIDIAN_MART
&& observed.bindings.iter().any(|binding| binding.name == "BUY BALL")
&& !observed.bindings.iter().any(|binding| binding.name == "LEAVE")
{
dealt_on_the_floor += 1;
}
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
let binding = observed
.bindings
.iter()
.find(|binding| binding.name == "BUY BALL")
.unwrap_or(&observed.bindings[rng as usize % observed.bindings.len()]);
if binding.name == "BUY BALL"
&& flybrain_gb::pokemon_red::scene::detect(&mut run.gb)
== flybrain_gb::pokemon_red::macros::state::Scene::Overworld
{
started += 1;
}
if let Started::Running(name) = palette.start(binding.slot, &mut run.gb, &ledger) {
running = Some(name);
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
}
}
}
if let Some((name, outcome)) = palette.take_finished()
&& name == "BUY BALL"
&& outcome == Outcome::Done
{
done += 1;
}
since_decision += 1;
run.gb.set_buttons(mask);
run.gb.run_frame().expect("a frame should complete");
ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, ms);
if run.bag_count(POKE_BALL) > 0 && bought_at.is_none() {
bought_at = Some(frame);
}
if bought_at.is_some() && running.is_none() {
break;
}
}
eprintln!(
"BUY BALL dealt on the floor on {dealt_on_the_floor} holds, started {started}, done {done}; \
a ball at {bought_at:?}; balls {}, money {money} -> {}",
run.bag_count(POKE_BALL),
run.money()
);
assert!(dealt_on_the_floor > 0, "BUY BALL is on the mart floor's pad");
assert!(started > 0, "and started from the floor");
assert_eq!(run.bag_count(POKE_BALL), 1, "one ball rung up");
assert_eq!(run.money(), money - 200, "and paid for");
assert!(done >= 1, "the macro reports done when paid");
}
/// The live row-67 checkpoint, or `None` to skip.
///
/// v0.6.5, rung 10, hot generation 230739, pulled while the fly walked back to the Pewter Gym
/// from its last whiteout: Pewter City (18, 13), Squirtle L11 (TACKLE, TAIL WHIP, BUBBLE, all
/// full), money 0, the gym's Jr. Trainer (Diglett L11, Sandshrew L11) not yet beaten.
fn row67_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW67_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 67: the Pewter Gym trainer lost thirty times in a row is the readout's, not the pad's.
///
/// **What was live** (2026-09-29, v0.6.5): an hour and a half in the gym, `NEXT` 1,332, `MOVE 2`
/// 83, `MOVE 3` 13, `MOVE 1` 0 in 3,000 events, no battle won. Per battle the readout chose TAIL
/// WHIP six turns in seven, Squirtle fainted, the fly whited out to Pewter and walked straight
/// back in (`infra/docs/macros-traps.md` row 67, `docs/design/macros.md` 12.31).
///
/// The claims, from the live checkpoint with the real palette and a uniform choice per hold (a
/// harness choice, not the fly's):
///
/// - **on every frame of the fly's own turn the pad deals a `MOVE n` for every move that has PP
/// and that the cartridge would not answer with nothing** -- BUBBLE is always there to be
/// pressed, so the pad is not the trap;
/// - **the trainer is beaten** inside the budget: a readout with no favourite wins this battle
/// with what the pad offers. The live readout's measured favourite (TAIL WHIP 87%) lost 17 of
/// 17 over the same budget, two seeds (`infra/docs/macros-traps.md` row 67).
#[test]
fn row67_the_gym_trainer_is_beaten_from_what_the_pad_deals() {
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::pokemon_red::state;
use flybrain_gb::pokemon_red::symbols::{events, ram};
use flybrain_gb::{MacroPalette, MemoryReader, Started};
let rom = skip_without_rom!();
let Some(checkpoint) = row67_checkpoint() else {
eprintln!("skipped: no FLY_ROW67_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), PEWTER_CITY, "the checkpoint is in Pewter City, on the way back");
assert!(!run.event(events::EVENT_BEAT_PEWTER_GYM_TRAINER_0), "the trainer is not yet beaten");
let budget = 60_000u32;
let hold_frames = 48u32;
let mut palette = PokemonPalette::new(SEED);
let mut rng = 1u32;
let mut running = false;
let mut since_decision = hold_frames;
let mut ms = run.ms;
let mut own_turn_frames = 0u32;
let mut useful_move_missing = 0u32;
let mut starts = std::collections::BTreeMap::<&'static str, u32>::new();
let mut battles: Vec<(u32, bool)> = Vec::new();
let mut fighting = run.gb.read8(ram::wIsInBattle);
let mut beaten_at = None;
for frame in 0..budget {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
let names: Vec<&str> = observed.bindings.iter().map(|binding| binding.name).collect();
if let Some(battle) = state::battle(&mut run.gb)
&& battle.own_turn
&& matches!(battle.menu, flybrain_gb::pokemon_red::macros::state::BattleMenu::Main { .. })
&& !state::a_latched(&mut run.gb)
&& let Some(own) = battle.own
{
own_turn_frames += 1;
for (slot, name) in ["MOVE 1", "MOVE 2", "MOVE 3", "MOVE 4"].iter().enumerate() {
if let Some(entry) = own.moves[slot].filter(|entry| entry.id != 0 && entry.pp > 0)
&& state::move_without_effect(&mut run.gb, entry.id) != Some(true)
&& !names.contains(name)
{
useful_move_missing += 1;
}
}
}
let mut mask = 0u8;
{
let ledger = AdapterLedger(&run.adapter);
if running {
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
let binding = &observed.bindings[(rng >> 8) as usize % observed.bindings.len()];
if let Started::Running(_) = palette.start(binding.slot, &mut run.gb, &ledger) {
*starts.entry(binding.name).or_default() += 1;
running = true;
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
}
}
}
since_decision += 1;
run.gb.set_buttons(mask);
run.gb.run_frame().expect("a frame should complete");
ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, ms);
let now = run.gb.read8(ram::wIsInBattle);
if fighting == 2 && now != 2 {
// `$ff` is the frame a battle is lost; anything else after a trainer battle is a win.
battles.push((frame, now != 0xff));
}
fighting = now;
if run.event(events::EVENT_BEAT_PEWTER_GYM_TRAINER_0) {
beaten_at = Some(frame);
break;
}
}
eprintln!(
"{:.1} brain minutes: trainer beaten at {beaten_at:?}; trainer battles (frame, won) \
{battles:?}; own-turn frames {own_turn_frames}, a useful move missing from the pad on \
{useful_move_missing}; starts {starts:?}",
(ms - run.ms) / 60_000.0,
);
assert!(own_turn_frames > 0, "the run never reached the trainer's battle");
assert_eq!(useful_move_missing, 0, "a move with PP and an effect was not on the pad");
assert!(beaten_at.is_some(), "the trainer was not beaten in {budget} frames: {battles:?}");
}

View file

@ -202,6 +202,11 @@ fn every_status_mode_reward_kind_and_attachment_the_service_can_emit_is_in_the_s
assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap()); assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap());
} }
for rule in flybrain_gb::pokemon_red::catalog::REWARDS { for rule in flybrain_gb::pokemon_red::catalog::REWARDS {
// `damage` publishes no counter (`RewardKind::from_adapter`): its events carry their own
// label and no `rewardKind`, which the schema already allows.
if rule.kind == flybrain_gb::pokemon_red::catalog::kind::DAMAGE {
continue;
}
let kind = flysim::snapshot::RewardKind::from_adapter(rule.kind).expect(rule.kind); let kind = flysim::snapshot::RewardKind::from_adapter(rule.kind).expect(rule.kind);
snapshot.header.events[0].reward_kind = Some(kind); snapshot.header.events[0].reward_kind = Some(kind);
assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap()); assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap());

View file

@ -225,6 +225,14 @@ EXTRA_RAM = (
'wToggleableObjectFlags', 'wToggleableObjectFlags',
'wToggleableObjectList', 'wToggleableObjectList',
'wObtainedHiddenItemsFlags', 'wObtainedHiddenItemsFlags',
# The damage reward (`docs/rewards-learning.md`, the operator 2026-09-29).
# ExecutePlayerMove loads the executing move into wPlayerMoveNum (STRUGGLE, $a5,
# when the cartridge chose it for a Pokemon with no PP), and battle_struct's third
# field, wEnemyMonPartyPos, names which enemy party slot is out -- so two Pokemon of
# one species and level in a trainer's party are two targets, not one.
# services/flysim/tools/resolve_wram.py is the second reading of both.
'wPlayerMoveNum',
'wEnemyMonPartyPos',
) )

View file

@ -89,6 +89,15 @@ WANTED = {
# poisoning one, and a target that must recharge is put to sleep whatever # poisoning one, and a target that must recharge is put to sleep whatever
# its status (MoveHitTest, CheckTargetSubstitute, SleepEffect). # its status (MoveHitTest, CheckTargetSubstitute, SleepEffect).
'wEnemyBattleStatus2': "the enemy's Mist, substitute and recharge bits", 'wEnemyBattleStatus2': "the enemy's Mist, substitute and recharge bits",
# The damage reward (`docs/rewards-learning.md`, the operator 2026-09-29).
# ExecutePlayerMove loads the executing move's six bytes here; the move id is
# STRUGGLE ($a5) when the cartridge picked Struggle for a Pokemon with no PP,
# which is the one attack the fly did not choose, and pays nothing.
'wPlayerMoveNum': 'the move the player is executing this turn',
# battle_struct's third field (macros/ram.asm: Species db, HP dw, PartyPos):
# which enemy party slot is out, $ff until a trainer's first send-out. It is
# what tells a trainer's two Weedles of one level apart.
'wEnemyMonPartyPos': "the enemy's party slot",
} }

View file

@ -104,3 +104,17 @@ files, so `packages/brain/tests/dataset.test.ts` is the end-to-end check that th
during extraction from the `fly-plays-pokemon` prototype. The circuit roles are now accumulated during extraction from the `fly-plays-pokemon` prototype. The circuit roles are now accumulated
in the same pass over the sorted `root_id` list that builds `meta.json`, which is what made the in the same pass over the sorted `root_id` list that builds `meta.json`, which is what made the
two scripts agree on neuron indices in the first place. two scripts agree on neuron indices in the first place.
# Privacy guard
`pii-scan.sh` refuses identifying strings and credentials in what this public repo publishes:
the tree (`--tree [REV]`), the lines and messages of a commit range (`--range`), or everything a
push would publish (`--push REMOTE`, the pre-push hook's mode). The generic shapes live in the
script; the proper nouns are loaded from the operator's private pattern list
(`$FLY_PII_PATTERNS`, default `~/.config/flybrain/pii-patterns.txt`), so the guard never spells
out what it refuses. `infra/tests/lint.sh` runs it and treats a missing list as a note;
`infra/build/tag-release.sh` and the pre-push hook fail closed without it.
`install-hooks.sh` installs the pre-push hook for this clone and all its worktrees; it scans
pushes to the `github` remote (and any github.com URL, or names in `$FLY_PII_PUBLIC_REMOTES`).
Tests: `infra/tests/pii-scan-test.sh`.

51
tools/install-hooks.sh Executable file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env bash
# tools/install-hooks.sh [--force]
#
# Installs the flybrain pre-push hook into this clone's hooks directory (shared by every
# worktree). On a push to a PUBLIC remote — the remote named `github`, any name listed in
# $FLY_PII_PUBLIC_REMOTES, or any github.com URL — the hook runs tools/pii-scan.sh --push
# over every commit the push would publish (added lines and messages), annotated tag
# messages, and each pushed tip's tree. It fails closed: without the operator's private
# pattern list ($FLY_PII_PATTERNS, default ~/.config/flybrain/pii-patterns.txt) the push is
# refused. Pushes to other remotes are not scanned.
#
# A copy of the scanner is installed next to the hook so branches that predate
# tools/pii-scan.sh are still scanned; re-run this script after the scanner changes.
# `git push --no-verify` skips the hook, as for any git hook; do not.
set -euo pipefail
FORCE=0
[ "${1:-}" != --force ] || FORCE=1
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
hooks_dir="$(git -C "$SELF_DIR" rev-parse --path-format=absolute --git-path hooks)"
mkdir -p "$hooks_dir"
hook="$hooks_dir/pre-push"
marker="# flybrain pii-guard pre-push hook"
if [ -e "$hook" ] && ! grep -qF "$marker" "$hook" && [ "$FORCE" -ne 1 ]; then
echo "install-hooks: $hook exists and is not ours; merge it by hand or re-run with --force" >&2
exit 1
fi
install -m 0755 "$SELF_DIR/pii-scan.sh" "$hooks_dir/flybrain-pii-scan.sh"
cat > "$hook" <<'HOOK'
#!/usr/bin/env bash
# flybrain pii-guard pre-push hook (installed by tools/install-hooks.sh; re-run it to update)
set -euo pipefail
remote="$1" url="${2:-}"
public=0
for r in github ${FLY_PII_PUBLIC_REMOTES:-}; do [ "$remote" = "$r" ] && public=1; done
case "$url" in *github.com[:/]*) public=1 ;; esac
[ "$public" -eq 1 ] || exit 0
top="$(git rev-parse --show-toplevel)"
scan="$top/tools/pii-scan.sh"
[ -x "$scan" ] || scan="$(dirname "${BASH_SOURCE[0]}")/flybrain-pii-scan.sh"
allow="$top/infra/tests/de-pii-allow.txt"
if ! FLY_PII_REPO="$top" "$scan" --require-private --allow "$allow" --push "$remote"; then
echo "pre-push: refusing to publish to '${remote}': fix the findings above (or restore the private pattern list)." >&2
exit 1
fi
HOOK
chmod 0755 "$hook"
echo "install-hooks: installed $hook (public remotes: github ${FLY_PII_PUBLIC_REMOTES:-}, and github.com URLs)"

306
tools/pii-scan.sh Executable file
View file

@ -0,0 +1,306 @@
#!/usr/bin/env bash
# tools/pii-scan.sh — refuse identifying strings and secrets in what this public repo publishes.
#
# tools/pii-scan.sh [options] --tree [REV] tracked files at REV (default: the checkout)
# tools/pii-scan.sh [options] --range REVS... lines ADDED by those commits, plus their
# messages (git rev-list syntax: A..B, X --not Y)
# tools/pii-scan.sh [options] --push REMOTE pre-push mode: reads git's pre-push stdin
# ("<lref> <lsha> <rref> <rsha>" lines) and scans
# every commit the push would publish, their
# messages, annotated tag messages, and each tip
# tools/pii-scan.sh --list pattern names in force (never the regexes)
#
# Options:
# --patterns FILE the PRIVATE pattern list (default $FLY_PII_PATTERNS, else
# ${XDG_CONFIG_HOME:-~/.config}/flybrain/pii-patterns.txt)
# --require-private exit 2 when that file is missing (tag-release and pre-push use this:
# fail closed). Without it a missing file is a NOTE and only the generic
# patterns below run (public CI has no private list, by design).
# --allow FILE allowlist (default infra/tests/de-pii-allow.txt)
#
# Exit: 0 clean, 1 findings, 2 usage or configuration error.
#
# Why two pattern sets. The generic shapes below (LAN addresses, container ids, host paths,
# e-mail addresses, credential shapes) contain no proper noun, so they can live here. The
# proper nouns — host names, the operator's names and handles, the channel, account ids,
# `pass` entry names, the forge — are exactly what must not be published, so they live in a
# file outside this repo and are loaded at run time. A guard that spelled them out (even with
# one character bracketed) would itself be the leak.
#
# Private file format, one per line (`#` comments):
# <name> <flags> <extended regex> flags: -i (ignore case) or - (case-sensitive)
# @values <env-file> each KEY=VALUE value of 8+ chars in that file becomes a
# literal needle, reported as secret-value:<KEY>, with
# the matched text never printed
#
# Findings print as `pii-scan: <name>: <where>: <redacted match>`; the match is cut to its
# first three characters so a log of the scan does not republish what it found.
set -euo pipefail
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# FLY_PII_REPO: the checkout to scan. The pre-push hook sets it, because its fallback copy of
# this script lives in .git/hooks, outside any work tree.
REPO_ROOT="${FLY_PII_REPO:-$(git -C "$SELF_DIR" rev-parse --show-toplevel 2>/dev/null || (cd "$SELF_DIR/.." && pwd))}"
usage() { sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' >&2; exit 2; }
die() { echo "pii-scan: $*" >&2; exit 2; }
PATTERNS_FILE="${FLY_PII_PATTERNS:-${XDG_CONFIG_HOME:-$HOME/.config}/flybrain/pii-patterns.txt}"
ALLOW_FILE="$REPO_ROOT/infra/tests/de-pii-allow.txt"
REQUIRE_PRIVATE=0
MODE=""
MODE_ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
--patterns) PATTERNS_FILE="${2:?}"; shift 2 ;;
--allow) ALLOW_FILE="${2:?}"; shift 2 ;;
--require-private) REQUIRE_PRIVATE=1; shift ;;
--tree|--range|--push|--list) MODE="$1"; shift; MODE_ARGS=("$@"); break ;;
-h|--help) usage ;;
*) die "unknown argument: $1 (see --help)" ;;
esac
done
[ -n "$MODE" ] || usage
TMP="$(mktemp -d)"
chmod 700 "$TMP"
trap 'rm -rf "$TMP"' EXIT
# --------------------------------------------------------------------------------------
# Patterns. NAMES/FLAGS/RES are parallel arrays; KIND is `re` or `values` (a -F -f file).
# The two path patterns keep one bracketed character only so this file does not match
# itself; they are not proper nouns.
# --------------------------------------------------------------------------------------
NAMES=(); FLAGS=(); RES=(); KIND=()
# Every pattern is compiled once up front: grep exits 2 on a bad regex, and a scan that
# silently skipped a broken private pattern would report "clean" (fail open).
pat() {
local rc=0 f=-E
[ "$2" = -i ] && f=-iE
grep $f -e "$3" </dev/null >/dev/null 2>&1 || rc=$?
[ "$rc" -le 1 ] || die "pattern '$1' is not a valid extended regex; refusing to scan"
NAMES+=("$1"); FLAGS+=("$2"); RES+=("$3"); KIND+=(re)
}
# name flags extended regex
pat lan-address -i '\b192\.168\.[0-9]{1,3}\.[0-9]{1,3}\b|\b2600:[0-9a-f]'
pat private-address - '\b10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b|\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.[0-9]{1,3}\b'
pat tailnet-address - '\b100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.[0-9]{1,3}\.[0-9]{1,3}\b'
pat private-dns -i '(@|://)[a-z0-9.-]+\.(internal|lan|home\.arpa|ts\.net)\b|\b[a-z0-9-]+\.ts\.net\b|\bheadscale\b'
pat container-id -i '\b(ct|vm)[ _-]?[12][0-9][0-9]\b|\bpct +[a-z-]+ +[0-9]{2,4}\b|\bqm +[a-z-]+ +[0-9]{2,4}\b|subvol-[12][0-9][0-9]-disk|/lxc/[12][0-9][0-9]\.conf'
pat host-root-path - '/ro[o]t/'
pat home-path - '/ho[m]e/[a-z]'
pat claim-log-name - 'AGENTS[_]LOG'
pat mac-address - '\b([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b'
pat email-address - '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}'
pat pass-entry-path - '\bpass +(show|insert|edit|generate) +[A-Za-z0-9._-]+/'
pat secret-private-key - '-----BEGIN [A-Z ]*PRIVATE KEY-----'
pat secret-token-prefix - '\bsk-(or-v1-|proj-|ant-)?[A-Za-z0-9_-]{20,}|\bgh[pousr]_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{30,}|\bAKIA[0-9A-Z]{16}\b|\bxox[baprs]-[A-Za-z0-9-]{10,}|\bglpat-[A-Za-z0-9_-]{20,}'
pat secret-twitch - 'oauth:[a-z0-9]{20,}|\blive_[0-9]{6,}_[A-Za-z0-9]{20,}'
pat secret-client-id -i '(client[_-]?id|clientid)["'"'"' ]*[:=][ "'"'"']*[a-z0-9]{30}\b'
pat secret-bearer - '\b(Bearer|Basic) [A-Za-z0-9._~+/=-]{24,}'
pat secret-assignment - '(KEY|SECRET|TOKEN|PASSWORD|PASSWD)["'"'"']?[ ]*[:=][ ]*["'"'"']?[A-Za-z0-9][A-Za-z0-9_+/=-]{19,}'
PRIVATE_LOADED=0
if [ -r "$PATTERNS_FILE" ]; then
PRIVATE_LOADED=1
lineno=0
while IFS= read -r raw || [ -n "$raw" ]; do
lineno=$((lineno + 1))
line="${raw#"${raw%%[![:space:]]*}"}"
case "$line" in ''|'#'*) continue ;; esac
if [ "${line%% *}" = "@values" ]; then
vfile="${line#@values}"; vfile="${vfile#"${vfile%%[![:space:]]*}"}"
vfile="${vfile/#\~/$HOME}"
[ -r "$vfile" ] || die "$PATTERNS_FILE:$lineno: @values file is not readable: $vfile"
while IFS= read -r kv || [ -n "$kv" ]; do
case "$kv" in ''|'#'*) continue ;; esac
kv="${kv#export }"
case "$kv" in *=*) ;; *) continue ;; esac
key="${kv%%=*}"; val="${kv#*=}"
val="${val%\"}"; val="${val#\"}"; val="${val%\'}"; val="${val#\'}"
[ "${#val}" -ge 8 ] || continue
n=${#NAMES[@]}
printf '%s\n' "$val" > "$TMP/needle.$n"
NAMES+=("secret-value:${key}"); FLAGS+=(-); RES+=("$TMP/needle.$n"); KIND+=(values)
done < "$vfile"
continue
fi
read -r pname pflags pre <<<"$line"
[ -n "${pre:-}" ] || die "$PATTERNS_FILE:$lineno: expected '<name> <flags> <regex>'"
case "$pflags" in -i|-) ;; *) die "$PATTERNS_FILE:$lineno: flags must be -i or -, got '$pflags'" ;; esac
pat "$pname" "$pflags" "$pre"
done < "$PATTERNS_FILE"
elif [ "$REQUIRE_PRIVATE" -eq 1 ]; then
die "private pattern list not found: ${PATTERNS_FILE} (set FLY_PII_PATTERNS). Refusing: without it the scan cannot see host names, people's names, the channel or pass entry names."
else
echo "pii-scan: NOTE: no private pattern list (${PATTERNS_FILE}); generic patterns only" >&2
fi
if [ "$MODE" = "--list" ]; then
printf '%s\n' "${NAMES[@]}"
exit 0
fi
# --------------------------------------------------------------------------------------
# Allowlist: `<path> <pattern-name> # reason`; path may end in / (prefix) or hold a glob.
# --------------------------------------------------------------------------------------
ALLOW_PATHS=(); ALLOW_NAMES=()
if [ -r "$ALLOW_FILE" ]; then
while read -r a_path a_name _; do
case "$a_path" in ''|'#'*) continue ;; esac
ALLOW_PATHS+=("$a_path"); ALLOW_NAMES+=("$a_name")
done < "$ALLOW_FILE"
fi
allowed() {
local path="$1" name="$2" i a
for i in "${!ALLOW_PATHS[@]}"; do
a="${ALLOW_NAMES[$i]}"
[ "$a" = "$name" ] || [ "$a" = '*' ] || continue
a="${ALLOW_PATHS[$i]}"
case "$a" in
*/) case "$path" in "$a"*) return 0 ;; esac ;;
*\**) # shellcheck disable=SC2254
case "$path" in $a) return 0 ;; esac ;;
*) [ "$path" = "$a" ] && return 0 ;;
esac
done
return 1
}
HITS=0
# report NAME PATH WHERE MATCH
report() {
local name="$1" path="$2" where="$3" match="$4" shown
allowed "$path" "$name" && return 0
case "$name" in
secret-*) shown="<redacted ${#match} chars>" ;;
*) shown="${match:0:3}… (${#match} chars)" ;;
esac
echo "pii-scan: ${name}: ${where}: ${shown}"
HITS=$((HITS + 1))
}
grep_flags() { # INDEX -> grep flags for regex pattern i (value needles use -F -f)
local i="$1"
# printf, not echo: `echo -E` is echo's own option and prints nothing.
if [ "${FLAGS[$i]}" = -i ]; then printf '%s\n' "-i -E"; else printf '%s\n' "-E"; fi
}
# --------------------------------------------------------------------------------------
# --tree [REV]
# --------------------------------------------------------------------------------------
scan_tree() {
local rev="${1:-}" i flags line path rest lno match is_git=0
git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1 && is_git=1
[ -z "$rev" ] || [ "$is_git" -eq 1 ] || die "--tree $rev needs a git checkout"
for i in "${!NAMES[@]}"; do
flags="$(grep_flags "$i")"
while IFS= read -r line; do
[ -n "$line" ] || continue
[ -z "$rev" ] || line="${line#"$rev":}"
path="${line%%:*}"; rest="${line#*:}"; lno="${rest%%:*}"; match="${rest#*:}"
report "${NAMES[$i]}" "$path" "$path:$lno" "$match"
done < <(
if [ "${KIND[$i]}" = values ]; then set -- -F -f "${RES[$i]}"; else set -- $flags -e "${RES[$i]}"; fi
if [ "$is_git" -eq 1 ]; then
# shellcheck disable=SC2086
git -C "$REPO_ROOT" grep -noI "$@" ${rev:+"$rev"} -- . ':!data' ':!package-lock.json' 2>/dev/null || true
else
grep -rnoI "$@" "$REPO_ROOT" --exclude-dir=data --exclude-dir=.git \
--exclude-dir=node_modules --exclude-dir=.local --exclude-dir=target \
--exclude=package-lock.json 2>/dev/null | sed "s|^${REPO_ROOT}/||" || true
fi
)
done
}
# --------------------------------------------------------------------------------------
# --range REVS...: added lines (corpus + index "commit path line") and commit messages.
# --------------------------------------------------------------------------------------
scan_corpus() { # CORPUS INDEX
local corpus="$1" index="$2" i flags
[ -s "$corpus" ] || return 0
for i in "${!NAMES[@]}"; do
flags="$(grep_flags "$i")"
while IFS=$'\t' read -r commit path lno match; do
report "${NAMES[$i]}" "$path" "${commit:0:10} $path:$lno" "$match"
done < <(
# shellcheck disable=SC2086
if [ "${KIND[$i]}" = values ]; then grep -noa -F -f "${RES[$i]}" "$corpus" || true
else grep -noa $flags -e "${RES[$i]}" "$corpus" || true; fi \
| awk -F'\t' 'NR==FNR { idx[NR] = $0; next }
{ n = index($0, ":"); k = substr($0, 1, n - 1) + 0;
print idx[k] "\t" substr($0, n + 1) }' "$index" -
)
done
}
scan_range() {
local corpus="$TMP/added" index="$TMP/added.idx"
git -C "$REPO_ROOT" log -p --no-color --no-ext-diff --no-renames --unified=0 \
--format='PIISCAN-COMMIT %H' "$@" -- . ':!data' ':!package-lock.json' \
| awk -v corpus="$corpus" -v index_f="$index" '
/^PIISCAN-COMMIT / { commit = $2; path = ""; hdr = 0; next }
/^--- / { hdr = 1; next }
/^\+\+\+ / && hdr { path = substr($0, 5); sub(/^b\//, "", path); if (path == "/dev/null") path = ""; hdr = 0; next }
/^@@ / { hdr = 0; if (match($0, /\+[0-9]+/)) ln = substr($0, RSTART + 1, RLENGTH - 1) + 0; next }
/^\+/ { if (path != "") { print substr($0, 2) > corpus; print commit "\t" path "\t" ln > index_f }; ln++; next }
'
touch "$corpus" "$index"
scan_corpus "$corpus" "$index"
local mcorpus="$TMP/msgs" mindex="$TMP/msgs.idx"
git -C "$REPO_ROOT" log --no-color --format='PIISCAN-COMMIT %H%n%B' "$@" \
| awk -v corpus="$mcorpus" -v index_f="$mindex" '
/^PIISCAN-COMMIT / { commit = $2; ln = 0; next }
{ ln++; print $0 > corpus; print commit "\t<commit-message>\t" ln > index_f }
'
touch "$mcorpus" "$mindex"
scan_corpus "$mcorpus" "$mindex"
}
scan_tag_message() { # TAG-OBJECT-SHA
local corpus="$TMP/tagmsg" index="$TMP/tagmsg.idx"
git -C "$REPO_ROOT" cat-file tag "$1" | sed '1,/^$/d' > "$corpus"
awk -v t="$1" '{ print t "\t<tag-message>\t" NR }' "$corpus" > "$index"
scan_corpus "$corpus" "$index"
}
# --------------------------------------------------------------------------------------
# --push REMOTE: git's pre-push protocol on stdin.
# --------------------------------------------------------------------------------------
ZERO=0000000000000000000000000000000000000000
scan_push() {
local remote="$1" lref lsha rref rsha
while read -r lref lsha rref rsha; do
[ -n "${lsha:-}" ] || continue
case "$lsha" in *[!0]*) ;; *) continue ;; esac # branch/tag deletion publishes nothing
echo "pii-scan: checking ${lref} -> ${remote} ${rref}" >&2
if [ "$(git -C "$REPO_ROOT" cat-file -t "$lsha")" = tag ]; then
scan_tag_message "$lsha"
fi
if [ "$rsha" != "$ZERO" ] && git -C "$REPO_ROOT" cat-file -e "${rsha}^{commit}" 2>/dev/null; then
scan_range "${rsha}..${lsha}"
else
scan_range "$lsha" --not --remotes="$remote"
fi
scan_tree "$(git -C "$REPO_ROOT" rev-parse "${lsha}^{commit}")"
done
}
case "$MODE" in
--tree) [ ${#MODE_ARGS[@]} -le 1 ] || die "--tree takes at most one REV"
scan_tree "${MODE_ARGS[0]:-}" ;;
--range) [ ${#MODE_ARGS[@]} -ge 1 ] || die "--range needs revisions"
scan_range "${MODE_ARGS[@]}" ;;
--push) [ ${#MODE_ARGS[@]} -eq 1 ] || die "--push takes the remote name"
scan_push "${MODE_ARGS[0]}" ;;
esac
if [ "$HITS" -gt 0 ]; then
echo "pii-scan: ${HITS} finding(s) (private list: $([ "$PRIVATE_LOADED" -eq 1 ] && echo loaded || echo absent)). Redact them — real values belong in the operator's infra repo — or, if a mention is genuinely not identifying, add '<path> <name> # reason' to infra/tests/de-pii-allow.txt." >&2
exit 1
fi
echo "pii-scan: clean (${#NAMES[@]} patterns, private list $([ "$PRIVATE_LOADED" -eq 1 ] && echo loaded || echo absent))" >&2