Files
psxrecomp/tools/gen_tcp_commands.py
T
Matthew Stanley e6ce5006b4 docs: move root and stale docs into docs/ and docs/internal/
The repository root carried seven markdown files that were not onboarding
material, plus two that had been superseded by the code they described. This
sorts them: reader-facing docs to docs/, working notes to docs/internal/, and
the two superseded ones merged into the docs that replaced them.

Moved to docs/:            WIDESCREEN.md, ENHANCEMENTS.md, TCP_COMMANDS.md
Moved to docs/internal/:   PRINCIPLES.md, ISSUES.md, DEBUG.md, GTE_LM_FIX.md,
                           and from docs/: bios-hardening.md, overlay-status.md,
                           overlay-plan.md, overlay-recompilation-design.md,
                           overlay-discovery.md, TOMBA2_EXC_CONSULT_RESPONSE.md,
                           CASE_A_AOT_GAP.md, audit_inventory.md
Moved to docs/internal/upstream/: UPSTREAM_2026-08-20.md

The root keeps only what belongs there: README.md, CONTRIBUTING.md, LICENSE,
CLAUDE.md, THIRD_PARTY_ATTRIBUTION.md, RELEASE_NOTES.md, the dotfiles and
psxrecomp_cli.py.

MERGES

SPLITGEN_MIGRATION.md folded into docs/BUILDING.md as "Split generated C". Its
migration instructions were stale in a way that mattered: it told every game
repo to hand-edit its CMakeLists and add a file(GLOB ...) over
<serial>_full*.c, but runtime/runtime.cmake now does that itself. GEN_FULL_GLOB
is a multi-value argument of psxrecomp_add_game_runtime(); the loop at
runtime.cmake:1985 makes each pattern absolute against CMAKE_CURRENT_SOURCE_DIR,
expands it with file(GLOB), and concatenates the hits into
GAME_GENERATED_FULL_C. So a title names the pattern and gets however many shards
a regeneration produced. The rewritten section describes that, the two-step
fallback when the globs match nothing (GEN_FULL_FALLBACK, else <serial>_full.c
derived from the dispatch marker by substituting _dispatch.c), and the one
caveat the code actually has: that file(GLOB) is plain, not CONFIGURE_DEPENDS,
so a regeneration which changes the shard COUNT needs a re-configure to be seen.

psxrecomp-toml-readme.md folded into docs/GAME_PROJECT_SETUP.md as "EXE-only
autofill (psxrecomp-toml)", placed after "Disc autofill (probe_disc.py)" and
before "Project Studio" so the two autofill paths sit together. Its documented
flags were checked against the usage text in recompiler/src/main_toml.cpp:28-42
and against the argument parser at :150-165 -- all seven options match with no
drift, so the flag list is reproduced as-is. Added a pointer that probe_disc.py
is preferable when a cue exists, since that tool does the same EXE-header work
plus disc identity and netplay gates.

FUNCTIONAL FIXES

tools/gen_tcp_commands.py wrote to REPO/"TCP_COMMANDS.md". After the move that
path does not exist, so the generator would have created a new stray root file
and --check would have failed against it forever. Retargeted to
REPO/"docs"/"TCP_COMMANDS.md", along with the seven docstring and message
strings that name the path.

Running it surfaced two further problems, both fixed here:

  * The doc was genuinely stale -- pre-existing drift, not introduced by this
    commit (the moved file is byte-identical to origin/master, and no
    debug-server command table is touched here). Four commands registered since
    the last regeneration were missing from the index -- cdrom_timing_dump,
    savestate_status, ws_ui_groups, xprobe_watch -- and scanline had gained a
    backend. Regenerated: 307 -> 311 commands, and the change is confined to the
    AUTOGEN block (the hand-written head and tail are byte-identical to master).
    tools/gen_tcp_commands.py --check now exits 0.
  * DOC.write_text() has no newline argument, so Python translated every newline
    to os.linesep. On Windows that rewrote all 585 lines of the file to CRLF and
    turned a four-line index update into a whole-file diff -- measured: 589 CRLF
    / 0 LF after a run, against 0 CRLF / 585 LF in the repo. Now written through
    an explicit newline="" handle, verified to leave the file at 0 CRLF.

runtime/include/debug_server.h:9 and runtime/src/debug_server.c:8 cited "TCP.md
and DEBUG.md". TCP.md has never existed in this repo under that name; both now
name docs/TCP_COMMANDS.md and docs/internal/DEBUG.md.

LINK AND REFERENCE FIXES

Every inbound reference to a moved file was located by grepping each basename
across the whole tracked tree, not just the markdown. Markdown hrefs in
README.md, CONTRIBUTING.md, docs/ARCHITECTURE.md, docs/COMPILING_OVERLAYS.md,
docs/AOT_OVERLAY_PLAN.md, docs/RELOCATION_MANIFEST_FORMAT.md,
docs/config_schema.md, docs/OVERLAY_XREF.md, docs/TCP_COMMANDS.md and several
docs/internal/ files now point at the new locations; where two files became
siblings under docs/internal/ the path was shortened rather than lengthened
(bios-hardening.md's reference to overlay-discovery.md, for instance).
docs/COMPILING_OVERLAYS.md's "in this folder" phrasing was wrong once two of the
three files it listed moved, so it now names internal/ explicitly.

24 source-comment mentions of ENHANCEMENTS.md sections G1.x across 19 files
(recompiler, runtime, cmake) were retargeted to docs/ENHANCEMENTS.md with the
section numbers untouched. docs/SHADOW_ENHANCEMENTS.md is a DIFFERENT file and
was deliberately excluded.

20 rationale strings citing docs/CASE_A_AOT_GAP.md across the four
recompiler/seeds/*.json files were updated. Done as a byte-level substring
replacement rather than a JSON round-trip: two of those files are stored with
CRLF endings and two with LF, and re-serializing them reformatted 5,700 lines.
The byte-level version changes exactly 20 lines and each file still parses.

References that look similar but point elsewhere were deliberately left alone,
and are worth naming so a future pass does not "fix" them:

  * "recomp-template PRINCIPLES.md" / "NES recomp template PRINCIPLES.md" in
    CLAUDE.md:43, docs/SHADOW_ENHANCEMENTS.md:28,
    docs/internal/HLE_SCHEDULER_CARVEOUT_PLAN.md:5,
    runtime/src/debug_server.c:4934 and tools/parity_diff.py:8 are a different
    repository's file. Only the five that mean this repo's PRINCIPLES.md were
    updated.
  * Every remaining bare ISSUES.md mention is a GAME repo's tracker
    (MegaManX6Recomp 2/7/8/9, TombaRecomp 6), not this repo's.
  * docs/disc-speed.md:4,54,56 and docs/internal/bios-hardening.md:5 name
    overlay-discovery as a BRANCH, not a file, so no path applies.

INDEXES

README.md's "New here?" table gains rows for docs/WIDESCREEN.md,
docs/ENHANCEMENTS.md and docs/TCP_COMMANDS.md. docs/internal/README.md gains
sections indexing all fourteen documents that moved in, plus an "Upstream
contributor reviews" section describing upstream/ and the new sweep file, plus a
"Removed" bullet for CYCLE_TIMING_ARCH.md (deleted in the previous commit)
pointing at FAITHFUL_TIMING_PLAN.md, CYCLE_MODEL_BEETLE.md and
PRECISE_IRQ_SLICE.md -- following the SLJIT_PERSIST_CACHE.md precedent already
in that file.

docs/ENHANCEMENTS.md:7 claimed framework bugs live in "game repos' ISSUES.md
until a framework tracker exists". A framework tracker does exist; it now says
so and names the Beads epic.

VERIFICATION

A link checker was written to scan every tracked *.md for relative links,
resolving each against the tree being scanned. Baseline at origin/master: 129
files, 137 relative links, 3 broken. After both commits: 127 files, 159 relative
links, 3 broken -- the SAME three, all pre-existing and untouched here:

    docs/DATA_SHARDS.md -> INSTANT_LOADS_PARKED.md   (never existed)
    docs/DATA_SHARDS.md -> INSTANT_LOADS_SPIKE2.md   (never existed)
    docs/NETPLAY.md     -> ../lib/recomp-net/README.md  (inside a submodule)

Zero new broken links. The checker's own coverage was checked against a raw grep
for markdown link openers: the 3-link difference is C++ lambdas inside code
blocks, correctly not treated as links.

Also verified: py_compile over all 113 tracked tools/*.py plus psxrecomp_cli.py;
all four seed JSONs still parse; the test-registration guard still reports 123
test files all registered; recompiler/tests/test_coverage_vault.py still passes;
and no file in this commit had its line endings flipped (checked mechanically
across all 50 modified files, after two files were caught and redone).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 07:39:07 -07:00

190 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Generate the complete TCP debug-command index in docs/TCP_COMMANDS.md.
WHY THIS EXISTS
---------------
docs/TCP_COMMANDS.md carried the instruction "update this file when you add a
handler". As of 2026-07-27 it described 47 commands while the two debug servers
registered 280 between them -- 17% coverage. A hand-maintained inventory of that
size does not stay correct, and a stale reference is worse than an absent one
because people trust it.
The curated table under "## Command inventory" is still hand-written and still
valuable: it carries parameters, prose, and the beetle/native split for the
commands people actually reach for. This script does NOT touch it. It regenerates
only the block between the AUTOGEN markers -- a complete index of every
registered command, flagging which ones the curated table already covers.
Usage:
python tools/gen_tcp_commands.py # rewrite the generated block
python tools/gen_tcp_commands.py --check # exit 1 if the block is stale
--check is what belongs in CI: it makes "the reference drifted" a build failure
instead of something discovered months later.
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
NATIVE_SRC = REPO / "runtime" / "src" / "debug_server.c"
BEETLE_SRC = REPO / "runtime" / "src" / "beetle_debug_server.c"
DOC = REPO / "docs" / "TCP_COMMANDS.md"
BEGIN = "<!-- BEGIN AUTOGENERATED COMMAND INDEX -- edit tools/gen_tcp_commands.py, not this block -->"
END = "<!-- END AUTOGENERATED COMMAND INDEX -->"
# `{ "name", handler },` inside the table. Tolerates arbitrary whitespace.
ENTRY_RE = re.compile(r'\{\s*"([A-Za-z0-9_]+)"\s*,\s*[A-Za-z0-9_]+\s*\}')
def extract_table(path: Path, table_decl: str) -> list[str]:
"""Pull command names out of a `static const CmdEntry <table_decl>` array.
Reads from the declaration to the closing `};` so unrelated brace-initialised
literals elsewhere in these very large files cannot leak in.
"""
if not path.exists():
raise SystemExit(f"gen_tcp_commands: missing source file {path}")
text = path.read_text(encoding="utf-8", errors="replace")
start = text.find(table_decl)
if start < 0:
raise SystemExit(
f"gen_tcp_commands: could not find '{table_decl}' in {path.name}. "
"The command table was renamed or restructured; update this script "
"rather than deleting the check."
)
end = text.find("};", start)
if end < 0:
raise SystemExit(f"gen_tcp_commands: unterminated table in {path.name}")
names = ENTRY_RE.findall(text[start:end])
if not names:
raise SystemExit(f"gen_tcp_commands: parsed 0 commands from {path.name}")
return names
def documented_in_curated_table(doc_text: str) -> set[str]:
"""Commands the hand-written parts of the doc already describe.
Picks up markdown table rows (`| `name` | ...`) and `## `name`` headings.
A row may name aliases -- "`ping` / `frame`", "`get_registers` (`regs`)" --
so every backticked token on a matching line counts.
"""
covered: set[str] = set()
for line in doc_text.splitlines():
stripped = line.strip()
if stripped.startswith("|") and "`" in stripped:
covered.update(re.findall(r"`([A-Za-z0-9_]+)`", stripped))
elif stripped.startswith("#") and "`" in stripped:
covered.update(re.findall(r"`([A-Za-z0-9_]+)`", stripped))
return covered
def build_block(native: list[str], beetle: list[str], covered: set[str]) -> str:
all_names = sorted(set(native) | set(beetle))
nset, bset = set(native), set(beetle)
documented = [n for n in all_names if n in covered]
undocumented = [n for n in all_names if n not in covered]
lines: list[str] = [BEGIN, ""]
lines.append("## Complete command index (generated)")
lines.append("")
lines.append(
f"**{len(all_names)} commands registered** — {len(native)} on the native "
f"server (`runtime/src/debug_server.c`), {len(beetle)} on the Beetle "
f"server (`runtime/src/beetle_debug_server.c`)."
)
lines.append("")
lines.append(
f"{len(documented)} of {len(all_names)} have prose above; "
f"**{len(undocumented)} are index-only**. An index-only command still "
"works — it just has no description here yet. Send it `{\"cmd\":\"<name>\"}` "
"and read the reply, or find its `handle_*` function in the server source."
)
lines.append("")
lines.append(
"Regenerate with `python tools/gen_tcp_commands.py`; "
"`--check` fails if this block has drifted from the code."
)
lines.append("")
lines.append("| Command | Native | Beetle | Described above |")
lines.append("|---|:--:|:--:|:--:|")
for name in all_names:
lines.append(
f"| `{name}` "
f"| {'✓' if name in nset else ''} "
f"| {'✓' if name in bset else ''} "
f"| {'✓' if name in covered else ''} |"
)
lines.append("")
lines.append(END)
return "\n".join(lines)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--check",
action="store_true",
help="exit 1 if the generated block is out of date (for CI)",
)
args = ap.parse_args()
native = extract_table(NATIVE_SRC, "s_commands[]")
beetle = extract_table(BEETLE_SRC, "CMDS[]")
doc_text = DOC.read_text(encoding="utf-8")
# Coverage is judged against the hand-written parts only, so a previously
# generated block can never count itself as documentation.
curated = doc_text
if BEGIN in curated:
head, _, rest = curated.partition(BEGIN)
_, _, tail = rest.partition(END)
curated = head + tail
block = build_block(native, beetle, documented_in_curated_table(curated))
if BEGIN in doc_text and END in doc_text:
head, _, rest = doc_text.partition(BEGIN)
_, _, tail = rest.partition(END)
updated = head + block + tail
else:
updated = doc_text.rstrip("\n") + "\n\n" + block + "\n"
if args.check:
if updated != doc_text:
print(
"docs/TCP_COMMANDS.md is out of date with the debug-server command "
"tables.\nRun: python tools/gen_tcp_commands.py",
file=sys.stderr,
)
return 1
print(f"docs/TCP_COMMANDS.md is current ({len(set(native) | set(beetle))} commands).")
return 0
if updated == doc_text:
print(f"docs/TCP_COMMANDS.md already current ({len(set(native) | set(beetle))} commands).")
return 0
# newline="" writes the LF endings assembled above verbatim. The default
# translates every newline to os.linesep, so on Windows a regeneration
# rewrote all 585 lines to CRLF and turned a few-line index update into a
# whole-file diff.
with open(DOC, "w", encoding="utf-8", newline="") as fh:
fh.write(updated)
print(f"docs/TCP_COMMANDS.md updated ({len(set(native) | set(beetle))} commands).")
return 0
if __name__ == "__main__":
raise SystemExit(main())