diff --git a/.agents/skills/boot-triage/LICENSE b/.agents/skills/boot-triage/LICENSE new file mode 100644 index 000000000..ac31f09ab --- /dev/null +++ b/.agents/skills/boot-triage/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jake Schincariol + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/boot-triage/SKILL.md b/.agents/skills/boot-triage/SKILL.md new file mode 100644 index 000000000..ae746251d --- /dev/null +++ b/.agents/skills/boot-triage/SKILL.md @@ -0,0 +1,142 @@ +--- +name: boot-triage +description: >- + Run the title under a hard timeout, keep its log outside the checkout, call the run PASS, HANG, CRASH or + EXIT, and turn the log and crashes.log into a ranked list of what stopped it: the crash report, the + unimplemented import that trapped, D3D12.X methods that are not implemented, and GPU failures. Compares a + run with the one before it. Use when the user says "run it", "does it boot", "why did it crash", "what do + I fix next", "did that break anything", or after a change to the loader, leonida-hle or leonida-gpu. +--- + +# Boot triage + +Every fix ends the same way: build, run, read the log, decide. This skill keeps that loop short and the +same every time. The method comes from the tester skill of +[Jakeschincariol/console-skill](https://github.com/Jakeschincariol/console-skill) (MIT, see +[LICENSE](LICENSE)), rewritten for this repository. Read [CLAUDE.md](../../../CLAUDE.md) first. + +Its partner skills: [missing-imports](../missing-imports/SKILL.md) fixes what this one ranks, +[trace-import](../trace-import/SKILL.md) works out what the title expects when the log doesn't say, and +[renderdoc-gpu-debug](../renderdoc-gpu-debug/SKILL.md) takes over when it runs but the picture is wrong. + +## Logs stay local + +The run's log and `crashes.log` keep the title's last debug output, and crash reports name its code. They +stay on your PC, outside the checkout (the "Derived data stays outside the repository" rule), and never go +into a commit, issue or pull request. Share import names, `module+offset` addresses and counts, never the +logs. + +## The state file + +`%LOCALAPPDATA%\leonida\agent-state.md` is the memory between sessions, outside the checkout for the same +reason. Read it first and write back one line per run. It holds: + +- the run command and the switches it was run with, copied and never rebuilt from memory; +- which build (`target\release` or `target\diag`); +- one line per run: date, what changed, verdict, run folder; +- the open stops, each with how many fixes were tried on it; +- the regression runs: the exact command and expected verdict of each milestone reached. + +If it does not exist, create it. The game folder comes from `leonida.toml` (`leonida config` prints it; +`run-gta6.ps1` asks for it once). + +## Without the game + +The loader and HLE tests build their input with our own code, and are the first thing to run after a change +there: + +```powershell +cargo test -p leonida-loader --locked +cargo test -p leonida-hle --locked +``` + +## One run + +1. **Build.** `cargo build --profile diag -p leonida --features diagnostics` for the debugging aids + (`LEONIDA_STACKS`, `LEONIDA_WATCH`, `LEONIDA_KEYS`, debug output), or `cargo build --release -p leonida` + to check what players get. Never `cargo clean` to make sure. +2. **Bind first, without running.** `target\diag\leonida.exe run` stops after binding and prints + `bound : N hle, N host, N title, N missing` with a `missing dll!symbol` line for each. A new + missing import here is cheaper to find than in a run. +3. **Run short, log to a new folder:** + + ```powershell + $run = Join-Path $env:LOCALAPPDATA "leonida\runs\$(Get-Date -Format yyyyMMdd-HHmmss)" + New-Item -ItemType Directory -Force $run | Out-Null + $env:LEONIDA_LOG = 'info' + $p = Start-Process target\diag\leonida.exe -PassThru -NoNewWindow -ArgumentList 'run', '--execute' ` + -RedirectStandardError "$run\stderr.log" -RedirectStandardOutput "$run\stdout.log" + $null = $p.Handle + if ($p.WaitForExit(120000)) { "exit $($p.ExitCode)" } else { taskkill /pid $p.Id /t /f | Out-Null; 'timeout' } + ``` + + Two minutes covers the loader, the intro and the menus; raise it only when chasing a later milestone, + and set `LEONIDA_KEYS` (diag build) to get through the menus unattended. `$p.Handle` is read so + PowerShell keeps the exit code. `taskkill /t` ends the whole process tree, so no game window is left. +4. **Give the verdict** (table below). +5. **Read only what matters**, not the whole log: + + ```powershell + Get-Content "$run\stdout.log" -Tail 20 + Select-String -Path "$run\stderr.log" -Pattern 'ERROR|unimplemented import|not implemented|panicked' | + Select-Object -First 40 + Get-Content (Join-Path $env:LOCALAPPDATA 'leonida\data\*\crashes.log') -Tail 80 + ``` + + `crashes.log` is appended to by every build, in the title's folder under `%LOCALAPPDATA%\leonida\data`; + take the entries with this run's time. +6. **Rank** (next section) and work the top item. +7. **Record** the line in the state file. + +## Verdicts + +| Verdict | When | +|---|---| +| PASS | the milestone being chased was reached (a log line, a picture, play) and nothing crashed before the timeout | +| HANG | the timeout came first and the milestone did not. `LEONIDA_STACKS=60,90` (diag) shows what every thread was waiting on | +| CRASH | a crash report in `crashes.log` for this run, an unimplemented import that trapped, a host GPU failure, or a negative exit code | +| EXIT | `title exited with ` before the milestone | + +## Ranking + +The first thing that went wrong usually caused the rest. In this order: + +1. **An unimplemented import that trapped.** With the default `--unimplemented trap` the run logs it, + writes `Leonida Legacy: unimplemented import dll!symbol called` to `crashes.log`, and aborts. That + import is the stop: [missing-imports](../missing-imports/SKILL.md). +2. **The crash report.** The faulting address as `module+offset`, the frames and the title's last lines of + debug output, which often say what it checked (`crates/leonida-loader/src/crash.rs`). A breakpoint is + usually the title's own assertion. Inside our code: a bug of ours. Inside the title's code with nothing + missing before it: [trace-import](../trace-import/SKILL.md), starting from that address. +3. **Host GPU failures** in `crashes.log` (device removed, a pipeline the driver refused). + `LEONIDA_D3D12_DRED=1` names the allocation and the commands in flight; `docs/fork-notes.md` lists the + other GPU switches. +4. **`method not implemented`** warnings (`crates/leonida-gpu/src/object.rs`): the object, the slot and the + caller. The method answered `E_NOTIMPL`, and the title may have gone on without it. +5. **Imports that returned 0** under `--unimplemented zero`: each is logged once. Use `zero` only to see how + far the title gets past a trap, never as the fix. + +## Comparing two runs + +After a fix, set this run's ranked list next to the one before: + +- The stop is gone: progress. Update the state file. +- A new stop after the old one: usually progress too, the title got further. +- A new stop earlier than the old one: the change broke something. Look at it before the next fix. + +After any change to the loader, `leonida-hle` or `leonida-gpu`, run every regression run in the state +file. A milestone that passed before and fails now is the first thing to fix. + +## Three strikes + +Three fixes on the same stop that did not move it: stop guessing. Reread the state file and +`docs/fork-notes.md`, trace the address with [trace-import](../trace-import/SKILL.md), and if it is still +unclear, ask the user one specific question. + +## Do not + +- leave a process running: one run at a time, ended at the timeout; +- make a stop pass silently to get further: an approximation gets a `shortcut:` marker, a risky behaviour a + `LEONIDA_*` switch that is off by default; +- clean the build or change a test to make a run pass; +- post a log, `crashes.log`, a `LEONIDA_CRASH_SAVE` file or a screenshot of the title anywhere. diff --git a/.agents/skills/missing-imports/LICENSE b/.agents/skills/missing-imports/LICENSE new file mode 100644 index 000000000..ac31f09ab --- /dev/null +++ b/.agents/skills/missing-imports/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jake Schincariol + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/missing-imports/SKILL.md b/.agents/skills/missing-imports/SKILL.md new file mode 100644 index 000000000..9387b0fd8 --- /dev/null +++ b/.agents/skills/missing-imports/SKILL.md @@ -0,0 +1,88 @@ +--- +name: missing-imports +description: >- + Turn the imports and D3D12.X methods the title needs but Leonida Legacy does not implement into a ranked + list of fixes, each with the file it belongs in: an hle_export! in a leonida-hle module, a new module, a + method of a leonida-gpu object, or a console path. Reads leonida census, the bind report of leonida run and + the run's log. Use when the user says "unimplemented import", "missing import", "what does the game still + need", "method not implemented", "E_NOTIMPL", or after boot-triage ranks a missing import as the stop. +--- + +# Missing imports + +The title's code runs unchanged; everything it expects from the console (the system DLLs, the GDK runtime, +the D3D12.X device) has to come from us. Every missing piece shows up as an import with no implementation, +a method that answers `E_NOTIMPL`, or a call that fails. This skill ranks them and says where each fix goes. +The method comes from the backend skill of +[Jakeschincariol/console-skill](https://github.com/Jakeschincariol/console-skill) (MIT, see +[LICENSE](LICENSE)), rewritten for this repository. Read [CLAUDE.md](../../../CLAUDE.md) first. + +It reads; it does not write the code for you. Some fixes are one line in a table, others a whole area. + +## What the title needs, before running it + +None of these run title code. + +```powershell +target\release\leonida.exe census --missing # every missing dll!function, most used first +target\release\leonida.exe census --strict --missing # the same, host pass-through not counted as covered +target\release\leonida.exe run # bind only: "bound ...: N hle, N host, N title, N missing" +target\release\leonida.exe inspect --imports # one image's imports +``` + +`census` with no paths reads the configured game folder. Its table has one row per DLL: functions +imported, served by us (`hle`), passed to the host, missing. + +Rank by: + +1. the import that trapped in the last run (`--unimplemented trap`, the default, aborts at the first call; + [boot-triage](../boot-triage/SKILL.md) finds it in `crashes.log`); +2. imports that returned 0 during a run with `--unimplemented zero` (each is logged once), in the order + they were called; +3. `method not implemented` warnings from `crates/leonida-gpu/src/object.rs`: object, slot, caller; +4. the rest of `census --missing`, by number of images using them. + +## Where each fix goes + +| What is missing | Where the fix goes | +|---|---| +| an export of a DLL a module already serves | an `extern "system"` function named exactly like the import, listed with `hle_export!` in that module's `module()`, as `crates/leonida-hle/src/modules/xmem.rs` does | +| a DLL no module serves | a new file in `crates/leonida-hle/src/modules/`, declared in `mod.rs` and pushed in `all()`; its `dlls` list may end a name with `*` to cover versioned API sets (`crates/leonida-hle/src/registry.rs`) | +| a D3D12.X method that answers `E_NOTIMPL` | the object's table in `crates/leonida-gpu/src/` (`object.rs` names the kind and the slot); device methods and pipeline creation are in `device.rs` | +| a file the title cannot open | `crates/leonida-hle/src/modules/files.rs`: the package is mounted as `G:` and temporary files as `T:` (`apps/leonida/src/run.rs`) | +| an import that should go to the PC's own DLL | the host pass-through; `leonida run --strict` turns it off to check what still depends on it | + +A new function comes with a test that needs no game, in the module's own `#[cfg(test)]` block as +`xmem.rs` has, or under `crates/leonida-hle/tests/`. + +## The method + +1. **Read the state file** (`%LOCALAPPDATA%\leonida\agent-state.md`, see + [boot-triage](../boot-triage/SKILL.md)): the run command, the open stops, the fixes already tried. +2. **Rank** with the commands above and the latest run's log. +3. **Find out what the function has to do before writing it.** Its public reference page gives the + signature; the title's call sites give the arguments it passes and what it does with the result + ([trace-import](../trace-import/SKILL.md)). Read `docs/fork-notes.md` too: much is measured there. + Quote where each fact comes from, or call it a guess. +4. **Write the smallest real implementation.** Returning success with the outputs unset is the bug the + `trap` default exists to catch; return a documented failure the title handles rather than a success it + cannot use. Code that approximates the console gets a `shortcut:` comment; a behaviour that might break + a picture or lose the device goes behind a `LEONIDA_*` switch, off by default, noted in + `docs/fork-notes.md`. Every new `unsafe` block gets a `// SAFETY:` comment. +5. **Test without the game:** `cargo test -p leonida-hle --locked` (or the crate you changed), then + `cargo clippy --workspace --all-targets --locked -- -D warnings` and compare with `main`: no new warning. +6. **Run again with [boot-triage](../boot-triage/SKILL.md)** and compare with the run before. Fixed: + update the state file. Same stop after the fix: count a strike; at three, stop guessing. +7. **Write it down** in `docs/fork-notes.md` when something was measured, with how. + +Before writing code, say in one paragraph what will change, why it fixes the cause, what it could break, +and whether that comes from reading the code or from memory. + +## Do not + +- make an import succeed silently to get past it, or switch a run to `--unimplemented zero` and call that + a fix; +- add a network call: the title must not reach the network (`crates/leonida-hle/src/modules/net.rs`); +- touch keys, licensing or protection: if a call turns out to need one, write that down and stop; +- quote the title's bytes, strings or disassembly in code, comments, tests or pull requests. Import names + and `module+offset` addresses are fine. diff --git a/.agents/skills/renderdoc-gpu-debug/LICENSE b/.agents/skills/renderdoc-gpu-debug/LICENSE new file mode 100644 index 000000000..673a52b12 --- /dev/null +++ b/.agents/skills/renderdoc-gpu-debug/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Alexey Medvedev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/renderdoc-gpu-debug/SKILL.md b/.agents/skills/renderdoc-gpu-debug/SKILL.md new file mode 100644 index 000000000..9a146fc56 --- /dev/null +++ b/.agents/skills/renderdoc-gpu-debug/SKILL.md @@ -0,0 +1,138 @@ +--- +name: renderdoc-gpu-debug +description: >- + Read GPU frames of a Leonida Legacy run: a frame shot (LEONIDA_SHOT) first, a RenderDoc capture + (LEONIDA_RENDERDOC) read through rdc-cli when a shot is not enough. Pipeline state at a draw, bound + resources, shaders, pixel history, render targets exported as PNG, and the difference between two + captures. Use when a picture is wrong (black, missing, washed out, garbage), or when the user mentions + RenderDoc, an .rdc file, a frame shot, a draw, a render target or pixel history. Not for frame timings. +--- + +# GPU frame debugging + +The RenderDoc part reads captures with [rdc-cli](https://github.com/BANANASJIM/rdc-cli), a command line +over RenderDoc's Python API. It is adapted from +[rudybear/renderdoc-skill](https://github.com/rudybear/renderdoc-skill) (MIT, see [LICENSE](LICENSE)), +rewritten for this repository. Read [CLAUDE.md](../../../CLAUDE.md) first: its hard rules apply to +everything here. + +## Captures and shots are game data + +A RenderDoc capture holds the title's shaders, textures and buffers; a frame shot's `snap-*.png` and an +exported render target show its pictures, and `events.txt` names its shaders. None of it goes into a +commit, an issue, a pull request or a test fixture, and none of it is written inside the checkout. The +defaults already keep them out: shots under `%LOCALAPPDATA%\leonida\shots`, captures under the +temporary folder. In a pull request, describe what was seen in words and numbers: the draw, the state +that was wrong, the value read back. + +## First: a frame shot + +The layer can take a frame apart itself, with no outside tool on the device (`crates/leonida-gpu/src/shot.rs`). +RenderDoc wraps the host device and hooks the process: the notes in that file record a run that ended +ten seconds in under a wrapped device, and while RenderDoc is loaded the driver's pipeline library is +neither read nor written, so the run is not the one players get. Try a shot before a capture. + +```powershell +powershell -ExecutionPolicy Bypass -File .\shot-run.ps1 -Keys '30:Enter,35:Enter' -ShotAt '300,600' +``` + +`-Keys` (`LEONIDA_KEYS`) presses keys at those seconds to get from the menus into play, `-ShotAt` +(`LEONIDA_SHOT_AT`) names the frames, counted from the first frame of 500 draws or more. Each +`shot-` folder has: + +- `events.txt`: every draw, dispatch, copy and submission in order, with its shaders, targets and states; +- `stamps.txt`: the card's clock before each of those commands; +- `snap-*.png` and `snaps.txt`: what a texture held when it left a written state, the picture each pass + left; +- `info.txt`, and `done` when everything is written. + +Open a `snap-*.png` with the Read tool to see it. Walk the snaps in order to find the first pass whose +picture is wrong; its line in `events.txt` names the draw, the shaders and the targets. + +## Then, if needed: a RenderDoc capture + +### Set up once + +1. Install RenderDoc from [renderdoc.org](https://renderdoc.org), and Python 3 of the version its + `renderdoc.pyd` was built for. +2. `pip install rdc-cli`. It is a tool on your PC, not part of this repository (which holds no Python). +3. Set `RENDERDOC_PYTHON_PATH` to the folder with `renderdoc.pyd` and `renderdoc.dll` (for the + installer, `C:\Program Files\RenderDoc`). +4. Run `rdc doctor`. Every check must pass. + +### Capture from a run + +The run loads RenderDoc itself and asks it for one frame (`crates/leonida-gpu/src/renderdoc.rs`), so +`rdc capture` is not needed: + +| Variable | Means | +|---|---| +| `LEONIDA_RENDERDOC` | the full path of `renderdoc.dll`. A bare name is refused, so neither the current folder nor the title's is searched | +| `LEONIDA_RENDERDOC_AT` | the frame to capture, counted in presents after the first frame of 500 draws or more (150 by default) | +| `LEONIDA_RENDERDOC_OUT` | the capture file names (by default `leonida_rdc\frame` under the temporary folder) | + +```powershell +$env:LEONIDA_RENDERDOC = 'C:\Program Files\RenderDoc\renderdoc.dll' +$env:LEONIDA_RENDERDOC_AT = '300' +$env:LEONIDA_KEYS = '30:Enter,35:Enter' +target\release\leonida.exe run --execute +``` + +The API captured is host D3D12: the title's D3D12.X calls go through `leonida-gpu` to the PC driver, +and its shaders are DXIL from `leonida-shader`. Close overlays that hook D3D12 (RivaTuner, OBS game +capture, FPS counters) before a capture; they hook the same device RenderDoc wraps. + +### Read it + +Every session is open, work, close. A daemon left open keeps GPU memory. + +```bash +rdc open "$TEMP/leonida_rdc/frame_capture.rdc" +rdc info --json # API, GPU, driver, resolution +rdc stats --json # passes, the largest draws and resources +rdc passes +rdc draws --limit 20 +rdc close +``` + +Then, at the draw that matters (its event id, EID): + +| Question | Command | +|---|---| +| What state is the pipeline in? | `rdc pipeline EID rs --json` (also `vs`, `ps`, `om`, `ia`, `ds`) | +| What is bound? | `rdc bindings EID --json` | +| Which shader runs, and what does it read? | `rdc shader EID ps --reflect --json`, `rdc shader EID ps --constants --json` | +| What does the shader say? | `rdc shader EID ps --targets`, then `rdc shader EID ps --target ` | +| What did the target hold after it? | `rdc rt EID -o "$TEMP/leonida_rdc/rt.png"`, then open the PNG with the Read tool | +| Which draws wrote this pixel? | `rdc pixel X Y EID --json` | +| How did the shader compute it? | `rdc debug pixel EID X Y --trace` | +| What changed between two runs? | `rdc diff a.rdc b.rdc --draws --json`, `rdc diff a.rdc b.rdc --framebuffer --json` | + +`rdc --help` and `rdc --help` list every command. Keep output small: `--limit` on lists, one +pipeline section at a time, `-q` for lists of ids. A full `rdc pipeline EID --json` is hundreds of lines +and a pixel trace can be a thousand. + +## What a wrong picture usually is here + +Check these in order before suspecting the driver: + +1. **The translated shader.** A program that does not translate drops its draws (TODO R-7): + `leonida translate --list` names them. A value that goes wrong inside a shader that did translate is + a rule of `leonida-shader`; a debugged pixel shows where. +2. **The descriptors and root signature.** An empty or wrong binding points at + `crates/leonida-gpu/src/descriptor.rs`, `root.rs` or `signature.rs`. +3. **Formats and layouts.** Scrambled with the right colours is tiling or detiling + (`crates/leonida-formats`, `crates/leonida-gpu/src/tiles.rs`); the right shape with wrong colours is a + format or an sRGB view. +4. **The state.** Culling, depth, blend and viewport from `rdc pipeline EID rs` and `om`. +5. **Something missing.** A `method not implemented` warning in the run's log (`object.rs`), or a + pipeline creation method that is not implemented (`device.rs`), means the title went without it. + +Write the finding with how it was seen: the shot and its line, or the EID and the state or value read, +and whether it was observed or inferred. + +## Not for timings + +A RenderDoc replay runs each draw alone on a wrapped device; its durations are not the game's. For time, +use `stamps.txt` of a shot, the card meter, or a measured run (`measure-gta6.ps1`), as "Measuring" in +CLAUDE.md says. diff --git a/.agents/skills/systematic-debugging/SKILL.md b/.agents/skills/systematic-debugging/SKILL.md new file mode 100644 index 000000000..62fc752aa --- /dev/null +++ b/.agents/skills/systematic-debugging/SKILL.md @@ -0,0 +1,283 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Overview + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +## The Iron Law + +``` +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST +``` + +If you haven't completed Phase 1, you cannot propose fixes. + +## When to Use + +Use for ANY technical issue: +- Test failures +- Bugs in production +- Unexpected behavior +- Performance problems +- Build failures +- Integration issues + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- Previous fix didn't work +- You don't fully understand the issue + +**Don't skip when:** +- Issue seems simple (simple bugs have root causes too) +- You're in a hurry (rushing guarantees rework) +- Manager wants it fixed NOW (systematic is faster than thrashing) + +## The Four Phases + +You MUST complete each phase before proceeding to the next. + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read Error Messages Carefully** + - Don't skip past errors or warnings + - They often contain the exact solution + - Read stack traces completely + - Note line numbers, file paths, error codes + +2. **Reproduce Consistently** + - Can you trigger it reliably? + - What are the exact steps? + - Does it happen every time? + - If not reproducible → gather more data, don't guess + +3. **Check Recent Changes** + - What changed that could cause this? + - Git diff, recent commits + - New dependencies, config changes + - Environmental differences + +4. **Gather Evidence in Multi-Component Systems** + + **WHEN system has multiple components (CI → build → signing, API → service → database):** + + **BEFORE proposing fixes, add diagnostic instrumentation:** + ``` + For EACH component boundary: + - Log what data enters component + - Log what data exits component + - Verify environment/config propagation + - Check state at each layer + + Run once to gather evidence showing WHERE it breaks + THEN analyze evidence to identify failing component + THEN investigate that specific component + ``` + + **Example (multi-layer system):** + ```bash + # Layer 1: Workflow + echo "=== Secrets available in workflow: ===" + echo "IDENTITY: $([ -n "${IDENTITY:-}" ] && echo SET || echo UNSET)" + + # Layer 2: Build script + echo "=== Env vars in build script: ===" + printenv IDENTITY >/dev/null 2>&1 && echo "IDENTITY in environment" || echo "IDENTITY not in environment" + + # Layer 3: Signing script + echo "=== Keychain state: ===" + security list-keychains + security find-identity -v + + # Layer 4: Actual signing + codesign --sign "$IDENTITY" --verbose=4 "$APP" + ``` + + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗) + +5. **Trace Data Flow** + + **WHEN error is deep in call stack:** + + See `root-cause-tracing.md` in this directory for the complete backward tracing technique. + + **Quick version:** + - Where does bad value originate? + - What called this with bad value? + - Keep tracing up until you find the source + - Fix at source, not at symptom + +### Phase 2: Pattern Analysis + +**Find the pattern before fixing:** + +1. **Find Working Examples** + - Locate similar working code in same codebase + - What works that's similar to what's broken? + +2. **Compare Against References** + - If implementing pattern, read reference implementation COMPLETELY + - Don't skim - read every line + - Understand the pattern fully before applying + +3. **Identify Differences** + - What's different between working and broken? + - List every difference, however small + - Don't assume "that can't matter" + +4. **Understand Dependencies** + - What other components does this need? + - What settings, config, environment? + - What assumptions does it make? + +### Phase 3: Hypothesis and Testing + +**Scientific method:** + +1. **Form Single Hypothesis** + - State clearly: "I think X is the root cause because Y" + - Write it down + - Be specific, not vague + +2. **Test Minimally** + - Make the SMALLEST possible change to test hypothesis + - One variable at a time + - Don't fix multiple things at once + +3. **Verify Before Continuing** + - Did it work? Yes → Phase 4 + - Didn't work? Form NEW hypothesis + - DON'T add more fixes on top + +4. **When You Don't Know** + - Say "I don't understand X" + - Don't pretend to know + - Ask for help + - Research more + +### Phase 4: Implementation + +**Fix the root cause, not the symptom:** + +1. **Create Failing Test Case** + - Simplest possible reproduction + - Automated test if possible + - One-off test script if no framework + - MUST have before fixing + - Use the `superpowers:test-driven-development` skill for writing proper failing tests + +2. **Implement Single Fix** + - Address the root cause identified + - ONE change at a time + - No "while I'm here" improvements + - No bundled refactoring + +3. **Verify Fix** + - Test passes now? + - No other tests broken? + - Issue actually resolved? + - Use the `superpowers:verification-before-completion` skill before claiming success + +4. **If Fix Doesn't Work** + - STOP + - Count: How many fixes have you tried? + - If < 3: Return to Phase 1, re-analyze with new information + - **If ≥ 3: STOP and question the architecture (step 5 below)** + - DON'T attempt Fix #4 without architectural discussion + +5. **If 3+ Fixes Failed: Question Architecture** + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + **STOP and question fundamentals:** + - Is this pattern fundamentally sound? + - Are we "sticking with it through sheer inertia"? + - Should we refactor architecture vs. continue fixing symptoms? + + **Discuss with your human partner before attempting more fixes** + + This is NOT a failed hypothesis - this is a wrong architecture. + +## Red Flags - STOP and Follow Process + +If you catch yourself thinking: +- "Quick fix for now, investigate later" +- "Just try changing X and see if it works" +- "Add multiple changes, run tests" +- "Skip the test, I'll manually verify" +- "It's probably X, let me fix that" +- "I don't fully understand but this might work" +- "Pattern says X but I'll adapt it differently" +- "Here are the main problems: [lists fixes without investigation]" +- Proposing solutions before tracing data flow +- **"One more fix attempt" (when already tried 2+)** +- **Each fix reveals new problem in different place** + +**ALL of these mean: STOP. Return to Phase 1.** + +**If 3+ fixes failed:** Question the architecture (see Phase 4.5) + +## your human partner's Signals You're Doing It Wrong + +**Watch for these redirections:** +- "Is that not happening?" - You assumed without verifying +- "Will it show us...?" - You should have added evidence gathering +- "Stop guessing" - You're proposing fixes without understanding +- "Ultra-think this" - Question fundamentals, not just symptoms +- "We're stuck?" (frustrated) - Your approach isn't working + +**When you see these:** STOP. Return to Phase 1. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. | +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. | +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. | +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. | +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. | +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. | +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. | +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. | + +## Quick Reference + +| Phase | Key Activities | Success Criteria | +|-------|---------------|------------------| +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY | +| **2. Pattern** | Find working examples, compare | Identify differences | +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis | +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass | + +## When Process Reveals "No Root Cause" + +If systematic investigation reveals issue is truly environmental, timing-dependent, or external: + +1. You've completed the process +2. Document what you investigated +3. Implement appropriate handling (retry, timeout, error message) +4. Add monitoring/logging for future investigation + +**But:** 95% of "no root cause" cases are incomplete investigation. + +## Supporting Techniques + +These techniques are part of systematic debugging and available in this directory: + +- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger +- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause +- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling diff --git a/.agents/skills/systematic-debugging/condition-based-waiting.md b/.agents/skills/systematic-debugging/condition-based-waiting.md new file mode 100644 index 000000000..70994f777 --- /dev/null +++ b/.agents/skills/systematic-debugging/condition-based-waiting.md @@ -0,0 +1,115 @@ +# Condition-Based Waiting + +## Overview + +Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI. + +**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes. + +## When to Use + +```dot +digraph when_to_use { + "Test uses setTimeout/sleep?" [shape=diamond]; + "Testing timing behavior?" [shape=diamond]; + "Document WHY timeout needed" [shape=box]; + "Use condition-based waiting" [shape=box]; + + "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"]; + "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"]; + "Testing timing behavior?" -> "Use condition-based waiting" [label="no"]; +} +``` + +**Use when:** +- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`) +- Tests are flaky (pass sometimes, fail under load) +- Tests timeout when run in parallel +- Waiting for async operations to complete + +**Don't use when:** +- Testing actual timing behavior (debounce, throttle intervals) +- Always document WHY if using arbitrary timeout + +## Core Pattern + +```typescript +// ❌ BEFORE: Guessing at timing +await new Promise(r => setTimeout(r, 50)); +const result = getResult(); +expect(result).toBeDefined(); + +// ✅ AFTER: Waiting for condition +await waitFor(() => getResult() !== undefined); +const result = getResult(); +expect(result).toBeDefined(); +``` + +## Quick Patterns + +| Scenario | Pattern | +|----------|---------| +| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` | +| Wait for state | `waitFor(() => machine.state === 'ready')` | +| Wait for count | `waitFor(() => items.length >= 5)` | +| Wait for file | `waitFor(() => fs.existsSync(path))` | +| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` | + +## Implementation + +Generic polling function: +```typescript +async function waitFor( + condition: () => T | undefined | null | false, + description: string, + timeoutMs = 5000 +): Promise { + const startTime = Date.now(); + + while (true) { + const result = condition(); + if (result) return result; + + if (Date.now() - startTime > timeoutMs) { + throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`); + } + + await new Promise(r => setTimeout(r, 10)); // Poll every 10ms + } +} +``` + +See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session. + +## Common Mistakes + +**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU +**✅ Fix:** Poll every 10ms + +**❌ No timeout:** Loop forever if condition never met +**✅ Fix:** Always include timeout with clear error + +**❌ Stale data:** Cache state before loop +**✅ Fix:** Call getter inside loop for fresh data + +## When Arbitrary Timeout IS Correct + +```typescript +// Tool ticks every 100ms - need 2 ticks to verify partial output +await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition +await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior +// 200ms = 2 ticks at 100ms intervals - documented and justified +``` + +**Requirements:** +1. First wait for triggering condition +2. Based on known timing (not guessing) +3. Comment explaining WHY + +## Real-World Impact + +From debugging session (2025-10-03): +- Fixed 15 flaky tests across 3 files +- Pass rate: 60% → 100% +- Execution time: 40% faster +- No more race conditions diff --git a/.agents/skills/systematic-debugging/defense-in-depth.md b/.agents/skills/systematic-debugging/defense-in-depth.md new file mode 100644 index 000000000..e2483354d --- /dev/null +++ b/.agents/skills/systematic-debugging/defense-in-depth.md @@ -0,0 +1,122 @@ +# Defense-in-Depth Validation + +## Overview + +When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks. + +**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible. + +## Why Multiple Layers + +Single validation: "We fixed the bug" +Multiple layers: "We made the bug impossible" + +Different layers catch different cases: +- Entry validation catches most bugs +- Business logic catches edge cases +- Environment guards prevent context-specific dangers +- Debug logging helps when other layers fail + +## The Four Layers + +### Layer 1: Entry Point Validation +**Purpose:** Reject obviously invalid input at API boundary + +```typescript +function createProject(name: string, workingDirectory: string) { + if (!workingDirectory || workingDirectory.trim() === '') { + throw new Error('workingDirectory cannot be empty'); + } + if (!existsSync(workingDirectory)) { + throw new Error(`workingDirectory does not exist: ${workingDirectory}`); + } + if (!statSync(workingDirectory).isDirectory()) { + throw new Error(`workingDirectory is not a directory: ${workingDirectory}`); + } + // ... proceed +} +``` + +### Layer 2: Business Logic Validation +**Purpose:** Ensure data makes sense for this operation + +```typescript +function initializeWorkspace(projectDir: string, sessionId: string) { + if (!projectDir) { + throw new Error('projectDir required for workspace initialization'); + } + // ... proceed +} +``` + +### Layer 3: Environment Guards +**Purpose:** Prevent dangerous operations in specific contexts + +```typescript +async function gitInit(directory: string) { + // In tests, refuse git init outside temp directories + if (process.env.NODE_ENV === 'test') { + const normalized = normalize(resolve(directory)); + const tmpDir = normalize(resolve(tmpdir())); + + if (!normalized.startsWith(tmpDir)) { + throw new Error( + `Refusing git init outside temp dir during tests: ${directory}` + ); + } + } + // ... proceed +} +``` + +### Layer 4: Debug Instrumentation +**Purpose:** Capture context for forensics + +```typescript +async function gitInit(directory: string) { + const stack = new Error().stack; + logger.debug('About to git init', { + directory, + cwd: process.cwd(), + stack, + }); + // ... proceed +} +``` + +## Applying the Pattern + +When you find a bug: + +1. **Trace the data flow** - Where does bad value originate? Where used? +2. **Map all checkpoints** - List every point data passes through +3. **Add validation at each layer** - Entry, business, environment, debug +4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it + +## Example from Session + +Bug: Empty `projectDir` caused `git init` in source code + +**Data flow:** +1. Test setup → empty string +2. `Project.create(name, '')` +3. `WorkspaceManager.createWorkspace('')` +4. `git init` runs in `process.cwd()` + +**Four layers added:** +- Layer 1: `Project.create()` validates not empty/exists/writable +- Layer 2: `WorkspaceManager` validates projectDir not empty +- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests +- Layer 4: Stack trace logging before git init + +**Result:** All 1847 tests passed, bug impossible to reproduce + +## Key Insight + +All four layers were necessary. During testing, each layer caught bugs the others missed: +- Different code paths bypassed entry validation +- Mocks bypassed business logic checks +- Edge cases on different platforms needed environment guards +- Debug logging identified structural misuse + +**Don't stop at one validation point.** Add checks at every layer. diff --git a/.agents/skills/systematic-debugging/find-polluter.sh b/.agents/skills/systematic-debugging/find-polluter.sh new file mode 100644 index 000000000..985f5d08c --- /dev/null +++ b/.agents/skills/systematic-debugging/find-polluter.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Bisection script to find which test creates unwanted files/state +# Usage: ./find-polluter.sh +# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts' + +set -e + +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 '.git' 'src/**/*.test.ts'" + exit 1 +fi + +POLLUTION_CHECK="$1" +TEST_PATTERN="$2" + +echo "🔍 Searching for test that creates: $POLLUTION_CHECK" +echo "Test pattern: $TEST_PATTERN" +echo "" + +# Get list of test files (find . emits ./-prefixed paths, so accept the +# pattern written with or without a leading ./) +TEST_PATTERN="${TEST_PATTERN#./}" +# find -path can't match '**/' against zero directory levels, so a pattern +# like src/**/*.test.ts would skip src/top.test.ts; also try the pattern +# with '**/' collapsed to cover files directly under the base directory. +TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u) +if [ -z "$TEST_FILES" ]; then + TOTAL=0 +else + TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ') +fi + +echo "Found $TOTAL test files" +echo "" + +COUNT=0 +for TEST_FILE in $TEST_FILES; do + COUNT=$((COUNT + 1)) + + # Skip if pollution already exists + if [ -e "$POLLUTION_CHECK" ]; then + echo "⚠️ Pollution already exists before test $COUNT/$TOTAL" + echo " Skipping: $TEST_FILE" + continue + fi + + echo "[$COUNT/$TOTAL] Testing: $TEST_FILE" + + # Run the test + npm test "$TEST_FILE" > /dev/null 2>&1 || true + + # Check if pollution appeared + if [ -e "$POLLUTION_CHECK" ]; then + echo "" + echo "🎯 FOUND POLLUTER!" + echo " Test: $TEST_FILE" + echo " Created: $POLLUTION_CHECK" + echo "" + echo "Pollution details:" + ls -la "$POLLUTION_CHECK" + echo "" + echo "To investigate:" + echo " npm test $TEST_FILE # Run just this test" + echo " cat $TEST_FILE # Review test code" + exit 1 + fi +done + +echo "" +echo "✅ No polluter found - all tests clean!" +exit 0 diff --git a/.agents/skills/systematic-debugging/root-cause-tracing.md b/.agents/skills/systematic-debugging/root-cause-tracing.md new file mode 100644 index 000000000..0e72e8f95 --- /dev/null +++ b/.agents/skills/systematic-debugging/root-cause-tracing.md @@ -0,0 +1,169 @@ +# Root Cause Tracing + +## Overview + +Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom. + +**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source. + +## When to Use + +```dot +digraph when_to_use { + "Bug appears deep in stack?" [shape=diamond]; + "Can trace backwards?" [shape=diamond]; + "Fix at symptom point" [shape=box]; + "Trace to original trigger" [shape=box]; + "BETTER: Also add defense-in-depth" [shape=box]; + + "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"]; + "Can trace backwards?" -> "Trace to original trigger" [label="yes"]; + "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"]; + "Trace to original trigger" -> "BETTER: Also add defense-in-depth"; +} +``` + +**Use when:** +- Error happens deep in execution (not at entry point) +- Stack trace shows long call chain +- Unclear where invalid data originated +- Need to find which test/code triggers the problem + +## The Tracing Process + +### 1. Observe the Symptom +``` +Error: git init failed in ~/project/packages/core +``` + +### 2. Find Immediate Cause +**What code directly causes this?** +```typescript +await execFileAsync('git', ['init'], { cwd: projectDir }); +``` + +### 3. Ask: What Called This? +```typescript +WorktreeManager.createSessionWorktree(projectDir, sessionId) + → called by Session.initializeWorkspace() + → called by Session.create() + → called by test at Project.create() +``` + +### 4. Keep Tracing Up +**What value was passed?** +- `projectDir = ''` (empty string!) +- Empty string as `cwd` resolves to `process.cwd()` +- That's the source code directory! + +### 5. Find Original Trigger +**Where did empty string come from?** +```typescript +const context = setupCoreTest(); // Returns { tempDir: '' } +Project.create('name', context.tempDir); // Accessed before beforeEach! +``` + +## Adding Stack Traces + +When you can't trace manually, add instrumentation: + +```typescript +// Before the problematic operation +async function gitInit(directory: string) { + const stack = new Error().stack; + console.error('DEBUG git init:', { + directory, + cwd: process.cwd(), + nodeEnv: process.env.NODE_ENV, + stack, + }); + + await execFileAsync('git', ['init'], { cwd: directory }); +} +``` + +**Critical:** Use `console.error()` in tests (not logger - may not show) + +**Run and capture:** +```bash +npm test 2>&1 | grep 'DEBUG git init' +``` + +**Analyze stack traces:** +- Look for test file names +- Find the line number triggering the call +- Identify the pattern (same test? same parameter?) + +## Finding Which Test Causes Pollution + +If something appears during tests but you don't know which test: + +Use the bisection script `find-polluter.sh` in this directory: + +```bash +bash ./find-polluter.sh '.git' 'src/**/*.test.ts' +``` + +Runs tests one-by-one, stops at first polluter. See script for usage. + +## Real Example: Empty projectDir + +**Symptom:** `.git` created in `packages/core/` (source code) + +**Trace chain:** +1. `git init` runs in `process.cwd()` ← empty cwd parameter +2. WorktreeManager called with empty projectDir +3. Session.create() passed empty string +4. Test accessed `context.tempDir` before beforeEach +5. setupCoreTest() returns `{ tempDir: '' }` initially + +**Root cause:** Top-level variable initialization accessing empty value + +**Fix:** Made tempDir a getter that throws if accessed before beforeEach + +**Also added defense-in-depth:** +- Layer 1: Project.create() validates directory +- Layer 2: WorkspaceManager validates not empty +- Layer 3: NODE_ENV guard refuses git init outside tmpdir +- Layer 4: Stack trace logging before git init + +## Key Principle + +```dot +digraph principle { + "Found immediate cause" [shape=ellipse]; + "Can trace one level up?" [shape=diamond]; + "Trace backwards" [shape=box]; + "Is this the source?" [shape=diamond]; + "Fix at source" [shape=box]; + "Add validation at each layer" [shape=box]; + "Bug impossible" [shape=doublecircle]; + "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white]; + + "Found immediate cause" -> "Can trace one level up?"; + "Can trace one level up?" -> "Trace backwards" [label="yes"]; + "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"]; + "Trace backwards" -> "Is this the source?"; + "Is this the source?" -> "Trace backwards" [label="no - keeps going"]; + "Is this the source?" -> "Fix at source" [label="yes"]; + "Fix at source" -> "Add validation at each layer"; + "Add validation at each layer" -> "Bug impossible"; +} +``` + +**NEVER fix just where the error appears.** Trace back to find the original trigger. + +## Stack Trace Tips + +**In tests:** Use `console.error()` not logger - logger may be suppressed +**Before operation:** Log before the dangerous operation, not after it fails +**Include context:** Directory, cwd, environment variables, timestamps +**Capture stack:** `new Error().stack` shows complete call chain + +## Real-World Impact + +From debugging session (2025-10-03): +- Found root cause through 5-level trace +- Fixed at source (getter validation) +- Added 4 layers of defense +- 1847 tests passed, zero pollution diff --git a/.agents/skills/tdd/SKILL.md b/.agents/skills/tdd/SKILL.md new file mode 100644 index 000000000..01eadaa34 --- /dev/null +++ b/.agents/skills/tdd/SKILL.md @@ -0,0 +1,38 @@ +--- +name: tdd +description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests. +--- + +# Test-Driven Development + +TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after. + +When exploring the codebase, read `GLOSSARY.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching. + +## What a good test is + +Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Seams: where tests go + +A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals. + +**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. + +Ask: "What's the public interface, and which seams should we test?" Give each proposed seam a one-line note on what it catches and what it misses. + +When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run. + +## Anti-patterns + +- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed. +- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec. +- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you. + +## Rules of the loop + +- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. +- **One slice at a time.** One seam, one test, one minimal implementation per cycle. +- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle. diff --git a/.agents/skills/tdd/agents/openai.yaml b/.agents/skills/tdd/agents/openai.yaml new file mode 100644 index 000000000..651b838a7 --- /dev/null +++ b/.agents/skills/tdd/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "TDD" + short_description: "Test-driven red-green-refactor" diff --git a/.agents/skills/tdd/mocking.md b/.agents/skills/tdd/mocking.md new file mode 100644 index 000000000..71cbfee67 --- /dev/null +++ b/.agents/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/.agents/skills/tdd/tests.md b/.agents/skills/tdd/tests.md new file mode 100644 index 000000000..7ab86479f --- /dev/null +++ b/.agents/skills/tdd/tests.md @@ -0,0 +1,77 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` + +**Tautological tests**: Expected value restates the implementation, so the test passes by construction. + +```typescript +// BAD: Expected value is recomputed the way the code computes it +test("calculateTotal sums line items", () => { + const items = [{ price: 10 }, { price: 5 }]; + const expected = items.reduce((sum, i) => sum + i.price, 0); + expect(calculateTotal(items)).toBe(expected); +}); + +// GOOD: Expected value is an independent, known literal +test("calculateTotal sums line items", () => { + expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15); +}); +``` diff --git a/.agents/skills/trace-import/SKILL.md b/.agents/skills/trace-import/SKILL.md new file mode 100644 index 000000000..455270f99 --- /dev/null +++ b/.agents/skills/trace-import/SKILL.md @@ -0,0 +1,93 @@ +--- +name: trace-import +description: >- + Work out what the title expects from an import, a D3D12.X method or a crash address: its callers, the + arguments it passes, what it does with the result, and write the finding down with a label for how it is + known (observed, measured, inferred, unknown). Use when the user asks "what does the game do with X", + "what does this import have to return", "who calls this", "what is at module+0x...", or before writing an + implementation whose behaviour is not documented. +--- + +# Trace an import + +Tracing means following the title from something concrete (an import, a method slot, a crash address) to +the code that uses it, and leaving a written trail. The method and the labels come from the `re-trace` and +`re-start` skills of [tanepiper/game-frame](https://github.com/tanepiper/game-frame) (CC0), rewritten for +this repository. Read [CLAUDE.md](../../../CLAUDE.md) first: nothing of the title goes into the +repository, and that includes disassembly, decompiled pseudocode and memory dumps. + +## Label every claim + +Write each finding with its evidence and one label: + +| Label | Means | +|---|---| +| observed | read in the executable, a crash report or a log line: name where, as `module+offset` | +| measured | produced by running: a run of the title, a test, a count over every shader, with the inputs | +| inferred | follows from observed or measured facts, with the reasoning written next to it | +| unknown | not settled; say what would settle it | + +A claim with no label is a guess, and CLAUDE.md asks for it to be called one. In code, behaviour built on +an inferred fact that approximates the console gets a `shortcut:` comment. + +## 0. Has it been done? + +The import, method or address may already be measured. Search before opening the executable: + +```bash +grep -rn "XUserAddAsync" docs/ crates/ | head +``` + +`docs/fork-notes.md` is the measurement log; `docs/architecture.md` says which crate owns what. The +implementations in `crates/leonida-hle/src/modules/` often carry what was learned in their comments. + +## 1. Find the way in + +Work outward from something concrete. None of these write inside the checkout. + +| Starting from | Where to look | +|---|---| +| an import | `leonida inspect --imports` (is it imported, from which DLL); `leonida census --missing` (how many images use it) | +| an import that trapped | `crashes.log`: `Leonida Legacy: unimplemented import dll!symbol called`. Run under a debugger and the trap breaks at the call, with the title's arguments in rcx, rdx, r8 and r9 | +| a D3D12.X method | the `method not implemented` warning (`crates/leonida-gpu/src/object.rs`): object kind, slot offset and the caller as `+offset` | +| a crash | the crash report (`crates/leonida-loader/src/crash.rs`): the faulting `module+offset`, the frames and the title's last debug output | +| a value that changes | `LEONIDA_WATCH=,...` (diag build) logs a title u32 each time it changes | +| where threads wait | `LEONIDA_STACKS=20,60` (diag build) prints every thread's stack at those seconds | + +## 2. Read the call site + +Open the address in a disassembler (Ghidra, x64dbg or IDA, your own install) and note: + +- the arguments: Win64 passes the first four in rcx, rdx, r8 and r9 (xmm0 to xmm3 for floats), the rest + on the stack; which are constants, which point at the caller's locals; +- what happens to the result: tested against what, and where each branch goes. A branch to `int3` is the + title treating that result as impossible, and a wrong answer there ends the run with a breakpoint; +- the out parameters it reads afterwards: those are what the implementation must fill in; +- the callers above, up to a loop, a vtable slot or a thread entry. A code path is not proof that it runs; + a trap, a crash report or a `LEONIDA_WATCH` line shows that it does. + +A function's name does not tell you its argument order or meaning: read the public reference page and the +call site, and say which one each fact comes from. + +## 3. Measure when it matters + +When the exact value matters (a size, a flag word, a slot), confirm it by running: a breakpoint at the +call under a debugger, `LEONIDA_WATCH`, or a test in the crate that builds the same input with our own +code. That turns observed into measured. `LEONIDA_CRASH_SAVE` writes title memory to the cache folder on a +crash; that file is game data and stays there. + +## 4. Write it down + +Add what was measured to `docs/fork-notes.md`, or extend the comment on the implementation: what the +title calls, from where (`module+offset`, with the build), with which arguments, what it does with the +result, and what is still open. Describe the code in prose and tables; never paste disassembly or +pseudocode. Every claim carries its label. + +## Pitfalls + +- A small function may be inlined into each caller, so a "missing" function is often inside its caller. +- A call through a register after loading the import's address does not show as a direct call; count + call sites as a lower bound. +- Two subsystems may share a helper with different meanings for its arguments. Name it by what it does, + not by the first place it was seen. +- Never round a constant: write it as the file has it. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..e485a1183 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,22 @@ +# Guide for coding agents + +The rules for this repository are in [CLAUDE.md](CLAUDE.md). Read it before changing anything: its hard rules +(no game data, derived data outside the repository, text files only, offline by design) apply to every agent, +whatever it is called. + +## Skills + +Step-by-step guides for common work, in the Agent Skills format. Each `SKILL.md` reads on its own, so an agent +that does not load skill folders can open the one it needs. + +The same files are in `.claude/skills/` (where Claude Code looks) and `.agents/skills/` (where other agents +look). Edit both copies in the same commit. + +| Skill | Use it to | +|---|---| +| [boot-triage](.claude/skills/boot-triage/SKILL.md) | run the title under a timeout, call the run PASS, HANG, CRASH or EXIT, and rank what stopped it | +| [missing-imports](.claude/skills/missing-imports/SKILL.md) | find which imports and D3D12.X methods are missing, and where each fix goes | +| [trace-import](.claude/skills/trace-import/SKILL.md) | work out what the title expects from an import or a crash address, with every claim labelled observed, measured, inferred or unknown | +| [renderdoc-gpu-debug](.claude/skills/renderdoc-gpu-debug/SKILL.md) | read a wrong picture: a frame shot first, a RenderDoc capture when that is not enough | +| [systematic-debugging](.claude/skills/systematic-debugging/SKILL.md) | find the root cause of a bug before fixing it | +| [tdd](.claude/skills/tdd/SKILL.md) | write the test first, then the code | diff --git a/CLAUDE.md b/CLAUDE.md index 3076d9bfc..4ce269b5c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,7 @@ It is a fork of [fxceless/victory-gta6](https://github.com/fxceless/victory-gta6 | `scripts/rename-from-upstream.ps1` | renames code taken from upstream (`victory` to `leonida`) | | `run-gta6.ps1` | builds and starts the game with the measured frame-rate switches | | `docs/` | architecture, asset policy, ray tracing, the fork's measurement log | -| `.claude/skills/` | agent skills: `boot-triage`, `missing-imports`, `trace-import`, `renderdoc-gpu-debug` (each `SKILL.md` reads on its own) | +| `.claude/skills/` | agent skills, copied in `.agents/skills/` for other agents; [AGENTS.md](AGENTS.md) lists them. Edit both copies | ## Commands diff --git a/docs/asset-policy.md b/docs/asset-policy.md index fe71a5a15..366e832dc 100644 --- a/docs/asset-policy.md +++ b/docs/asset-policy.md @@ -47,7 +47,9 @@ user's dump), `test_titles`, and `cache_dir` for everything derived `cargo xtask install-hooks`) is an allowlist: files must have an allowed type, be under 512 KiB, contain no binary data or known binary signatures, and hold no long hex/base64 runs. Exceptions need an entry - with a reason in `xtask/src/policy.rs`. + with a reason in `xtask/src/policy.rs`. A symbolic link passes when it + points inside the repository by a relative path; what it points at is + checked as a file of its own. 3. At runtime, everything that writes derived data calls `leonida_core::ensure_outside_repo`. 4. Tests that need real files take their paths from environment variables diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index ddde4a75d..48af176e9 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -3,8 +3,10 @@ //! //! This is an allowlist, not a blocklist: a file passes only if its name is //! on the list, it is not too big, it is text, and it does not smuggle data -//! inside text (long hex/base64 runs). +//! inside text (long hex/base64 runs). A symbolic link carries no data of +//! its own: it passes when it points inside the repository. +use std::collections::HashSet; use std::path::Path; use std::process::Command; @@ -50,12 +52,16 @@ const FORBIDDEN_MAGIC: &[(&[u8], &str)] = &[ pub fn run(root: &Path, staged: bool) -> Result<()> { let files = list_files(root, staged)?; + let links = symlinks(root)?; let mut violations = Vec::new(); for path in &files { if EXCEPTIONS.iter().any(|(p, _)| p == path) { continue; } - let content = if staged { + let link = links.contains(path); + // A link's blob in the index is its target, whether or not this + // clone made a real link of it. + let content = if staged || link { let out = Command::new("git") .args(["show", &format!(":{path}")]) .current_dir(root) @@ -70,7 +76,12 @@ pub fn run(root: &Path, staged: bool) -> Result<()> { Err(_) => continue, } }; - for problem in check(path, &content) { + let problems = if link { + check_link(path, &content) + } else { + check(path, &content) + }; + for problem in problems { violations.push(format!("{path}: {problem}")); } } @@ -142,6 +153,59 @@ fn list_files(root: &Path, staged: bool) -> Result> { .collect()) } +/// The paths the index holds as symbolic links (mode 120000). +fn symlinks(root: &Path) -> Result> { + let out = Command::new("git") + .args(["ls-files", "-s", "-z"]) + .current_dir(root) + .output() + .context("running git")?; + if !out.status.success() { + return Ok(HashSet::new()); + } + Ok(out + .stdout + .split(|&b| b == 0) + .filter_map(|entry| { + let entry = String::from_utf8_lossy(entry); + let (meta, path) = entry.split_once('\t')?; + meta.starts_with("120000 ").then(|| path.replace('\\', "/")) + }) + .collect()) +} + +/// All problems with a symbolic link at `path` whose target is `target`. +/// Only a relative path to a place inside the repository passes; what it +/// points at is checked as a file of its own. Pure, for testing. +pub fn check_link(path: &str, target: &[u8]) -> Vec { + let Ok(target) = std::str::from_utf8(target) else { + return vec!["symbolic link target is not text".to_owned()]; + }; + if target.is_empty() || target.len() > 1024 || target.chars().any(char::is_control) { + return vec!["symbolic link target is not a plain path".to_owned()]; + } + if target.starts_with(['/', '\\']) || target.contains(':') { + return vec![format!("symbolic link to an absolute path ({target})")]; + } + let mut place: Vec<&str> = path.split('/').collect(); + place.pop(); // the link's own name + for part in target.split(['/', '\\']) { + match part { + "" | "." => {} + ".." => { + if place.pop().is_none() { + return vec![format!("symbolic link leaves the repository ({target})")]; + } + } + name => place.push(name), + } + } + if place.is_empty() { + return vec![format!("symbolic link to the repository root ({target})")]; + } + Vec::new() +} + /// All problems with one file. Pure, for testing. pub fn check(path: &str, content: &[u8]) -> Vec { let mut problems = Vec::new(); @@ -183,7 +247,7 @@ fn longest_encoded_run(content: &[u8]) -> Option { #[cfg(test)] mod tests { - use super::check; + use super::{check, check_link}; /// Enforces the policy wherever tests run, even in clones without the hook. #[test] @@ -215,6 +279,21 @@ mod tests { ); } + #[test] + fn accepts_links_inside_the_repository() { + assert!(check_link(".agents/skills", b"../.claude/skills").is_empty()); + assert!(check_link("a/b/link.md", b"../c/./d.md").is_empty()); + } + + #[test] + fn rejects_links_that_leave_the_repository() { + assert!(!check_link(".agents/skills", b"../../outside").is_empty()); + assert!(!check_link("link", b"/etc/passwd").is_empty()); + assert!(!check_link("link", b"C:\\Windows").is_empty()); + assert!(!check_link("link", b".").is_empty(), "the root itself"); + assert!(!check_link("link", b"a\0b").is_empty()); + } + #[test] fn rejects_data_smuggled_into_text() { let blob = format!("const DATA: &str = \"{}\";", "A1".repeat(400));