Files
apk-reverse/check_routing.py
T
inliver233 2beade67f2 Reconstruction pass: make the gates tell the truth, make the package self-contained, keep the one-hop symptom index
An external audit of this repository landed on four structural findings, and this pass is the
response to them. Everything below was re-measured on this tree before being acted on; two of the
audit's claims needed a correction of my own, and both corrections are noted in place.

**The gates were optimistic, and one of them did not read content at all.**

  doctor.py    the capability table was hard-coded (`repack + sign = bool(java) and python`), so a
               machine with a JDK and no zipalign/apksigner was told it could re-sign; the script
               inventory was a hand-written list of 28 against 51 files on disk, omitting the nine
               most important scripts. It now scans the directory (`registered/checked = 52 / 52`,
               unjudgeable entries counted as `unknown`, never skipped) and resolves capability as a
               real requires-closure, reporting BLOCKED with the missing piece and an installable
               next step. Measured: the old doctor reports `[OK] repack + sign` on a JDK-only PATH
               where keytool, jarsigner, zipalign, apksigner and all eight smali jars are absent.
               The report is allowed to look bad; that is the point.
  check_commands.py (new)
               anchor checks prove a section exists, never that a command runs. This parses each
               script's argparse table with `ast` and checks every documented invocation against it.
               146 commands / 41 interfaces, 0 drift. It caught `sig_probe.py --live --pkg`, which
               does not exist -- the reference had been wrong since it was written.
  check_routing.py (new)
               the symptom index now has one home (`SKILL.md`, because symptom -> file must stay one
               hop) and the inventory has another (`references/routing.md`). This gate proves the
               mirror agrees, that every reference file is named, and that every script is named.

**so_constpatch.py was corrupting APKs it rebuilt.** The writer copied filename and timestamp onto a
fresh ZipInfo and recompressed the whole archive: 435-entry real package, `extra` lost on 205 entries,
`external_attr` rewritten on all 435, 132 untouched entries recompressed, and `resources.arsc` pushed
to an unaligned offset. Android's own `zipalign -c -v 4` fails the old output and passes the new one;
a 26-case fixture suite pins it, and `extractNativeLibs="false"` is now refused by default with a
pointer at `repack.py`. Fixing it exposed the same defect in `repack.py`, where `^lib/[^/]+\.so$`
cannot match `lib/arm64-v8a/*.so` -- so its alignment handling had never once fired on a real APK.

**The package was not self-contained.** 59 references pointed at the repository root, which `npx
skills add` does not install. They now converge on `references/evidence-summary.md` (capability,
conclusion, strength, evidence that ships) plus `evidence/` with the machine-readable companions: 8
references remain and each is explicitly labelled "repository root, not shipped". A drill in which
the new files were copied to an isolated directory and asked three questions answered all three.

**SKILL.md: 572 lines / 15,733 tokens -> 398 lines / ~10,900 tokens**, without losing the two things
that had to stay. The symptom index remains inline; the reference and script indexes moved to the
on-demand routing file. The freed budget went into making the rules *stronger*, not shorter: the
constraints section is now a table of thirteen non-negotiable constraints each paired with the check
that catches a violation, and the tooling obligations are instructions whose violation is a defect
(hedging language in SKILL.md: 1 line, down from a paragraph of hedged advice). Long references gained
a navigation head so a reader can decide from the top whether to load one.

**New: an executable test layer.** `tests/` (unit, CLI contract, no-device integration) plus
`pytest.ini`, `tests/run_tests.py`, a minimal CI job, and `evals/evals.json` written but never run --
stated as such in the file. 608 passed / 158 skipped / 25 xfailed. The 25 xfails are a work order, not
a pass: thirteen scripts report a missing input by exiting 1 instead of 2, seven let a traceback
escape, four treat `--help` as an error, and `preflight --json` lacks a `status` field. A regression
row for `dex_patch_bytes.py` reproduces a previous artifact byte-for-byte
(`67ae1e58e7a44777e5ac8f9f823ab21e…`) and additionally pins the four bytes that may move.

**Two real defects the new tests found in the tooling itself.** `check_repo.py` decoded subprocess
output with the locale encoding, so on a GBK console a script printing an em dash in its usage line
was reported as crashed; it now decodes UTF-8 explicitly. And a CLI contract test drove a *real
attached device* through `coldstart.py` -- logcat, screenshots, five orphan `adb logcat` processes --
which is fixed twice over: child processes run in a private temporary cwd, and the fifteen
device-bound scripts are never executed beyond `--help`/argument parsing.

**Quoting on the device side is now one implementation.** `devsh.su` escaped only double quotes, so
`;`, `$( )` and backticks in a caller-supplied value still reached the device shell while
`coldstart.Device.shell` quoted correctly. Both use `scripts/device_shell.py` now: POSIX single-quote
escaping, argv arrays by default, and identifier validation that refuses a malformed package, path or
component with exit 2 instead of a traceback. The integration test that used to pin the *defect* (it
asserted `su -c "…"` with `\"` escapes) now asserts the property, across five metacharacter payloads.

Gates: check_repo 0 problems (including the content-reading identity scan over git ls-files),
check_refs 0 dangling / 0 warning, check_routing coherent (53 symptom / 45 reference / 54 script rows),
check_budget 0 failure / 0 warning with the always-loaded body now measured in tokens rather than in
"narrative lines with the index excluded", check_commands 146 checked / 0 drift, pytest 608 passed.

Not done, and stated rather than implied: CI has never run on a runner; the evals have never been
executed; the 25 xfails are open; no device-side install/launch was performed in this pass.
2026-09-22 01:37:51 +08:00

177 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Keep `skills/apk-reverse/references/routing.md` coherent with `SKILL.md` and with the tree.
Why this exists: `SKILL.md` loads in full whenever this skill activates, so it carries only what has
to be one hop there -- the symptom index (recognising a failure must not become a two-hop lookup) and
the four gates with their pass criteria. The *inventory* lookups -- every reference file with when to
load it, every script with what it does -- live in `references/routing.md` and load on demand.
That split creates one risk: two tables that used to be one. This script removes it by **comparing**
the tables instead of generating one from the other:
* the **symptom index** has a single home, `SKILL.md`; `routing.md` keeps a mirror so a reader gets
all three tables in one load, and `--check` fails when the mirror and the live table differ;
* the **reference and script indexes** have a single home, `routing.md`;
* every file under `references/` must be named in the routing reference table, and every script in
`scripts/` must be named in the routing script table -- an inventory that has drifted from the
directory is worse than no inventory, because it reads as complete.
Usage:
python check_routing.py # report coherence; exit 1 on any problem
python check_routing.py --json
"""
import argparse
import glob
import json
import os
import re
import sys
ROOT = os.path.dirname(os.path.abspath(__file__))
SKILL_DIR = os.path.join(ROOT, 'skills', 'apk-reverse')
SKILL = os.path.join(SKILL_DIR, 'SKILL.md')
REFS = os.path.join(SKILL_DIR, 'references')
SCRIPTS = os.path.join(SKILL_DIR, 'scripts')
ROUTE = os.path.join(REFS, 'routing.md')
# A markdown table separator row: pipes, dashes, colons and spaces, and at least one dash. Tested on
# the row's *cells*, not the whole line -- every data row also starts and ends with `|`, so any
# whole-line pattern loose enough to accept a separator also accepts every data row, and the reverse
# mistake drops every data row and reports an intact inventory as broken.
def is_separator(row):
cells = [c for c in row.strip().strip('|').split('|')]
return bool(cells) and all(c.strip() and set(c.strip()) <= set('-:') for c in cells)
# Headings are matched by prefix: they contain an em dash, and comparing against an ASCII hyphen
# silently reports "table not found" instead of failing.
PREFIXES = {
'symptom': 'Symptom index',
'reference': 'Reference index',
'script': 'Script index',
}
def read(path):
with open(path, encoding='utf-8') as fh:
return fh.read()
def tables(text):
"""{heading: [data rows]} -- data rows exclude the header row.
The separator row is identified by its characters (`-`, `|`, `:`, spaces only). Do **not** use
`set(row) > set('|-: ')` to decide this: set comparison is not a character test, and every row
whose content happens to be a superset of those characters gets dropped -- which once classified
43 of 53 symptom rows as "not a table row" and made the checker report the inventory as broken
while it was intact. This file's own failure mode, found by a row count that did not add up.
"""
out = {}
cur = None
for ln in text.split('\n'):
if ln.startswith('## '):
cur = ln[3:].strip()
out.setdefault(cur, [])
elif cur is not None and ln.startswith('|'):
out[cur].append(ln)
result = {}
for key, rows in out.items():
data = [r for r in rows if not is_separator(r)]
result[key] = data[1:] if data else [] # drop the header row
return result
def pick(sections, prefix):
for key, rows in sections.items():
if key.startswith(prefix):
return rows
return None
def cell0(row):
return row.strip().strip('|').split('|')[0].strip().strip('`* ').lower()
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--json', action='store_true')
args = ap.parse_args()
problems = []
if not os.path.isfile(ROUTE):
print('FAIL references/routing.md is missing -- the inventory has no home')
print('RESULT=missing')
return 1
sk = tables(read(SKILL))
rt = tables(read(ROUTE))
live_sym = pick(sk, PREFIXES['symptom']) or []
mirror_sym = pick(rt, PREFIXES['symptom']) or []
ref_rows = pick(rt, PREFIXES['reference'])
scr_rows = pick(rt, PREFIXES['script'])
for name, rows in (('symptom (routing.md)', mirror_sym), ('reference', ref_rows),
('script', scr_rows)):
if rows is None:
problems.append('routing.md has no %s table' % name)
live_set = {cell0(r) for r in live_sym}
mirror_set = {cell0(r) for r in mirror_sym}
if live_set - mirror_set:
problems.append('routing.md symptom mirror is missing %d row(s) present in SKILL.md: %s'
% (len(live_set - mirror_set), '; '.join(sorted(live_set - mirror_set))[:180]))
if mirror_set - live_set:
problems.append('routing.md symptom mirror has %d row(s) SKILL.md does not: %s'
% (len(mirror_set - live_set), '; '.join(sorted(mirror_set - live_set))[:180]))
ref_text = ' '.join(r for r in (ref_rows or []))
ref_files = sorted(os.path.basename(p) for p in glob.glob(os.path.join(REFS, '*.md')))
unlisted = [f for f in ref_files if f not in ref_text]
if unlisted:
problems.append('routing.md reference table does not name %d reference file(s): %s'
% (len(unlisted), ', '.join(unlisted)))
scr_text = ' '.join(r for r in (scr_rows or []))
scr_files = sorted(f for f in os.listdir(SCRIPTS) if f.endswith(('.py', '.js')))
unlisted_s = [f for f in scr_files if f not in scr_text]
if unlisted_s:
problems.append('routing.md script table does not name %d script(s): %s'
% (len(unlisted_s), ', '.join(unlisted_s)))
report = {
'skill_symptom_rows': len(live_sym),
'routing_symptom_rows': len(mirror_sym),
'routing_reference_rows': len(ref_rows or []),
'routing_script_rows': len(scr_rows or []),
'reference_files_in_tree': len(ref_files),
'scripts_in_tree': len(scr_files),
'problems': problems,
'result': 'ok' if not problems else 'incoherent',
}
if args.json:
print(json.dumps(report, indent=2, ensure_ascii=False))
print('RESULT=%s' % report['result'])
return 1 if problems else 0
print('routing coherence')
print(' symptom index : SKILL.md %d rows / routing mirror %d rows'
% (len(live_sym), len(mirror_sym)))
print(' reference table: %d rows, covering %d reference files' % (len(ref_rows or []), len(ref_files)))
print(' script table : %d rows, covering %d scripts' % (len(scr_rows or []), len(scr_files)))
for p in problems:
print(' FAIL %s' % p)
print()
if problems:
print('== routing: %d problem(s) ==' % len(problems))
print('RESULT=incoherent')
return 1
print('== routing: coherent ==')
print('RESULT=ok')
return 0
if __name__ == '__main__':
sys.exit(main())