diff --git a/.agents/skills/sourceorigin-cleanup/SKILL.md b/.agents/skills/sourceorigin-cleanup/SKILL.md new file mode 100644 index 000000000..231a3cd72 --- /dev/null +++ b/.agents/skills/sourceorigin-cleanup/SKILL.md @@ -0,0 +1,213 @@ +--- +name: sourceorigin-cleanup +description: > + Run a repository-wide cleanup of SourceOrigin: an audit that measures the + code and suggests fixes, then a cleanup pass where one agent per area opens + focused, reviewed refactor PRs, a boundary lane cleans up between the crates + and surfaces, and every bug found gets a GitHub issue and a fix PR. Use when + asked for a cleanup or refactor pass, codebase stats or an audit, or to + deduplicate or simplify SourceOrigin as a whole. Not for cleaning up a single + PR or file. +--- + +# SourceOrigin cleanup + +You orchestrate a cleanup of the whole repository in two parts: an audit, then +a cleanup pass. Run both unless the owner asks for one. Delegates write the +code. You split the work, brief them, route reviews and report. + +Work from a checkout of `origin/main` that contains this skill, since the +delegates read their briefs from it. Keep a ledger in your scratchpad: each +agent, branch, PR, review state and finding, and the files each task holds. +Files are free once the task holding them has reported and its PRs touching them +have merged. Start no task on files that aren't free. A forced edit outside an +area (a renamed item's callers, a docs reference) is the exception: the agent +holding those files rebases over it. After compaction, a usage limit or a T3 +restart, check the ledger and restart only what didn't finish. + +Issues are GitHub issues in `sourceorigin-dev/sourceorigin`, titled like a +Conventional Commit and labelled with their kind (`bug`, `refactor`) and the +other labels that fit (`gh label list`). + +## Audit + +1. Measure: `python3 -I .agents/skills/sourceorigin-cleanup/scripts/stats.py . + --json /stats.json`. It needs `cloc`. Chart the result with + `html_preview` and `html_render`, including growth over time from the + JSON. +2. Read the output, then check what the script can't count: + - coverage, from the `rust-coverage` artifact of `main`'s latest CI run (or + `just coverage`) and `just web test` + - unused code and dependencies, with `just unused` + - generated files missing from `.gitattributes` + - which `expect` calls can really panic + - duplication built up since the last pass, including between the Rust and + TypeScript SDKs +3. Send the owner the charts and a ranked list of suggestions, each with the + numbers and paths behind it. Open nothing yet. +4. For each suggestion the owner picks, start a thread with + `t3_thread_launch`. Use Claude Opus 5.5 in a worktree off `origin/main`. + Its message stands alone: the goal, the numbers, the scope and what to + report. A thread that checks many sites reports a table of each site, its + verdict and why. + +Changes that move code in many areas, such as file splits, merge before the +cleanup pass starts or go into the area agents' tasks. + +## Cleanup pass + +### Split + +Start from this split and adjust it to the code. Split an area over about +30,000 lines of source and tests along a module boundary (`stats.py` lists the +modules of large areas), and merge small areas. Every file has exactly one +owner. + +| Area | Paths | Scope | +| --- | --- | --- | +| Sign-in and OIDC | `apps/auth-service/src/{oidc,passkey,federation,security,keys,sessions,grants}` | `auth` | +| Accounts | the rest of `apps/auth-service`: `src/{account,clients,deletion,recovery,emails,notifications,pictures,history,handles}`, the root modules and `tests` | `auth` | +| Operations | `apps/auth-service/src/{cli,config,jobs,deliveries,audit,alerts}` | `cli` or `auth` | +| Admin | `apps/auth-service/src/{admin,web/admin}`, `crates/ui/src/admin` | `admin` | +| Pages | the rest of `apps/auth-service/src/web` and `crates/ui`, `apps/auth-service/assets`, `apps/web`, `tests/browser` | `ui`, `web` or `browser` | +| Database | `crates/database` | `database` | +| SDKs | `crates/{auth-sdk,common,crypto}`, `packages/auth`, `tests/sdk-vectors` | `sdk`, `common` or `crypto` | +| Tooling | every other hand-written file: `crates/telemetry`, `tools/xtask`, `infra`, `just`, `.github`, root files | `telemetry`, `infra`, or none: `refactor: …` | + +Nobody edits `crates/database/migrations`, `snapshots/` or generated files by +hand. `docs/` and Markdown belong to the docs lane. + +Before you start the agents, run `rustup update stable`, `just install-tools`, +`just install`, `just validate` and `just db test` on `origin/main`. If one +fails, as it can under a new stable Clippy, have one Opus delegate fix it in a +PR, review and ship it as in Review, and ask the owner to merge it first. + +Open one GitHub issue for the pass, labelled `refactor`, and note its number +``. Each PR says `Part of #`. Each area agent opens several focused PRs, +on branches named `refactor/--`. Tell the owner the split in +one message and start without waiting. + +Every worktree compiles the workspace in its own target directory, on a +machine with no swap. Pick one `CARGO_BUILD_JOBS` value for every agent that +compiles, and pass it to each. 4 suits 8 implementers and their reviewers on +16 cores and 58 GB as a start. Run at most 8 reviews at a time. + +### Start the agents + +Call `orchestrator_capabilities` once. For each area, start a `delegate_task` +on Claude Opus 5.5 with `isolation: "worktree"` and `role: "implementation"`. +The task says to follow `.agents/skills/sourceorigin-cleanup/references/agent-brief.md`. +It names the area, paths, packages, branch prefix, title scope, tracking +issue, what the other areas own, and `CARGO_BUILD_JOBS`. + +Start a docs lane the same way, on `docs/-cleanup`. It follows the +`sourceorigin-docs` skill, fixes drift between the docs and the code, runs +`just docs` and opens a draft PR. It reports stale `///` comments and clap +help instead of editing them. Those comments sit in the area agents' files and +feed the generated reference pages. + +### Review + +Review each focused PR on its own as its agent reports it. Call +`link_pull_request` and start a review: a `delegate_task` on GPT 6.1 Sol with +`role: "review"`, `isolation: "worktree"` and +`target.options: { reasoningEffort: "high" }`. It follows +`.agents/skills/sourceorigin-cleanup/references/review-brief.md`. Give it the +PR number, the head SHA, the base branch (the parent PR's branch for a stacked +PR), `CARGO_BUILD_JOBS`, and a focus list: every "unchanged" claim in the PR +description, and every merged helper or test that could have changed +behavior. + +- Check each finding against the code before acting on it. +- Send real findings to the implementer's thread with `t3_thread_send`. +- After a fix that rewrites code, run a new, narrower review. +- Judgment calls go to the owner, with your recommendation. +- If Sol is over its limit, review with Opus instead and say so. + +When a PR's review is clean and it is rebased, mark it ready. Follow its CI +with `babysit-pr`, and update its `[!NOTE]` line to name who reviewed it. The +owner merges, through the merge queue. + +When something lands on `main`, have each agent rebase and apply its cleanup +to the new code, and start the boundary themes and fixes whose files are now +free. Review any logic the rebase merged. Suggest merging the SDKs and the +database first, because the apps depend on them. + +### Boundary lane + +The area agents each see one area. Alongside them, start one more Opus +delegate, `role: "research"`, to look at how the areas fit together, against +`docs/dev/architecture/overview.md` and `docs/dev/rust-conventions.md`: + +- the dependency direction between the crates, and logic in the wrong crate, + such as SQL outside `crates/database` or decisions in `crates/ui` templates +- public items no other crate needs, and the published crates' (`auth-sdk`, + `common`, `crypto`) public API +- types, conversions and helpers duplicated across crates, and between the + Rust and TypeScript SDKs and `common`'s wire types +- what the CLI, the settings, the developer console and the admin dashboard + each reimplement instead of sharing a service +- errors that lose their context at a crate boundary + +It edits nothing. It reports themes, each with the files involved and the +change it proposes. Add the cross-area issues the area agents report to that +list. Themes that need a design decision, or change a published crate's API, +go to the owner first. + +Once a theme's files are free, start one Opus implementation delegate per +theme. Merge themes that share files, or run them one after another. Each +follows the agent brief, with the theme's files as its area, and opens focused +PRs on `refactor/-boundary-`. Review them like the others. + +### Bugs + +Every bug an agent or reviewer reports gets an issue and a fix PR: + +1. Check it against current `main`, with a Sol delegate when there are many. + Merge duplicate reports, and ask the owner about anything that might be + intended. A vulnerability, anything an attacker could exploit, stops here: + tell the owner only, and open no issue or PR (`SECURITY.md`). +2. Open a GitHub issue labelled `bug`, or reuse the one that exists + (`gh issue list --search`). Include the `file:line`, what goes wrong and how + to reproduce it. If the existing issue is assigned or has a linked PR, note + it in the ledger and start no fix. +3. Once its files are free, start an Opus implementation delegate in a worktree, + on `fix/-` from a freshly fetched `origin/main`, with the + issue and `CARGO_BUILD_JOBS`. It writes a test that fails without the fix, + makes the smallest fix, updates the docs it affects, runs the agent brief's + checks, regenerating what the fix changes on purpose, such as a screenshot, + and opens a draft PR with `file-pr` that says `Closes #`. +4. Review and ship it as in Review, but without the review brief, which treats + any behavior change as a finding. The reviewer's task says to work at the + head SHA without pushing or commenting, revert the fix locally to check the + test then fails, and check the fix is correct and minimal and nothing else + changed. It reports findings with severity and `file:line`. + +Run at most 3 fixes at a time. + +### Report + +When every area and docs PR is reviewed and green, send the owner one +report: + +1. The PRs by area: link, lines added and removed, merge order, and the PRs + that are stacked. +2. Decisions only the owner can make, with your recommendation. +3. The bugs: each one's issue, fix PR and state. +4. The boundary themes, and which ones wait for the area PRs. +5. Other design issues. +6. Features missing from a surface (`AGENTS.md`), checked against current + `main`, and admin operations left CLI-only without a documented reason. + +Number the items `NEW-1`, `NEW-2` and so on, never `#1`, which GitHub links to +an issue or PR. + +### After the merge + +Rerun the stats and compare them with the audit. Report again when the boundary +and fix PRs are reviewed and green. Then offer these follow-ups, and start each +one only when the owner asks: + +1. A doc-comment PR for what the docs lane reported. It changes the generated + reference pages on purpose (`just docs reference`). +2. GitHub issues for the surface gaps. diff --git a/.agents/skills/sourceorigin-cleanup/references/agent-brief.md b/.agents/skills/sourceorigin-cleanup/references/agent-brief.md new file mode 100644 index 000000000..77bb6dc07 --- /dev/null +++ b/.agents/skills/sourceorigin-cleanup/references/agent-brief.md @@ -0,0 +1,105 @@ +# Cleanup pass: area agent + +You own one area of SourceOrigin in a parallel cleanup pass. Your task names +the area, paths, packages, branch prefix, title scope, tracking issue and +`CARGO_BUILD_JOBS`, and lists what the other agents own. + +Read every file in your area, and `docs/dev/rust-conventions.md`. Make real +simplifications, not cosmetic churn, and report bigger issues. Never add an +`#[allow]`. Use `#[expect(..., reason = "...")]` on the smallest item that +needs it. + +## Rules + +- **Change no behavior.** That includes HTTP responses (and which error a + request with several faults gets), OIDC and OAuth wire formats, rendered + pages and emails, CLI flags, help, output and exit codes, configuration + variables, domain events and their audit records, log and span fields, + metrics, timeouts, lock order, query plans, and the public API of the + published crates (`auth-sdk`, `common`, `crypto`) and `@sourceorigin/auth`. + `git diff ` shows no change to a migration, a `snapshots/` file or a + generated file, except the `.sqlx` entry of a query you rewrote. Don't + use blanket search and replace. +- **Report bugs instead of fixing them.** The orchestrator opens an issue and a + fix PR for each. If a cleanup can't be done without changing behavior, report + it too. Report a vulnerability only in your final message, never in a PR, + commit or code comment. +- **Stay in your area.** Edit another area only when a rename forces it: + keep it minimal and list those files in the PR description. Report what + crosses areas: another lane cleans up between them. +- **Keep the docs references right.** If you rename something a page in + `docs/` names, update that page (`sourceorigin-docs` skill) and run + `just docs`. Don't reword `///` comments or clap help that feed the + generated reference pages. +- Stop and report anything that needs a design decision. + +## Checks + +Export `CARGO_BUILD_JOBS` for every cargo command. For your packages, run: + +- `just install`, then `just fmt` +- `cargo clippy --locked -p --all-targets --all-features -- -D warnings`, + and again without `--all-features` +- `RUSTDOCFLAGS='-D warnings' cargo doc --locked --no-deps --all-features -p `, + and `cargo test --locked --doc --all-features -p ` for a library +- `just db prepare`, if you changed a query +- `just test -p --all-features`; for `auth-service` and + `sourceorigin-repository`, `just db test` instead. Both fail on a stale + generated file. +- `just rust unused` +- `cargo semver-checks -p --baseline-rev origin/main`, for a published + crate +- `just web check`, `just web lint`, `just web unused` and `just web test`, if + you touched TypeScript or JavaScript +- `just docs screenshots`, if you touched a page's markup, styles or script. + It must rewrite no image in `docs/images`. It deploys a preview, so run it + once per PR, last. + +Despite `AGENTS.md`, don't run `just validate`, `just lint` or `just test` +without `-p`: they build the whole workspace. CI runs on drafts every job a +PR's paths select, including the browser suite, the images, packaging and the +MSRV build, so leave those to it and read their results before you report. + +Prove each "unchanged" claim against the PR's base: `--help` output, the +rendered pages, emails and HTTP responses, the TypeScript SDK's built type +declarations, query plans (`EXPLAIN` in `just db scratch -- psql`). Before you +call a failing check unrelated, check that it fails on `main` too. Never change +a test just to make it pass. + +## Delivery + +- Split your work into focused PRs: one kind of cleanup in one part of your + area each, small enough to review in one sitting. Branch each from a + freshly fetched `origin/main` as ``, and keep your PRs from + sharing files. If one needs another, stack it: branch from the other PR's + branch, open it with that branch as its base, and say so in its + description. +- Make small, logical commits with conventional messages and no + `Co-Authored-By` line. +- Rebase on `origin/main` (a stacked PR on its base branch), and clean up any + new code the rebase brings in. PRs merge by squash, so when a stacked PR's + base merges, move only its own commits with + `git rebase --onto origin/main `, and check it targets + `main`. +- Open each PR as a **draft** with `file-pr`, despite its default, titled + `refactor(): ` (or `refactor: …` without a scope) + and labelled `refactor` and the other labels that fit (`gh label list`). Its + description says: + - `Part of #` + - what was hard to read and how you fixed it + - every test you merged or removed + - files edited outside your area, and why + - what you compared to prove the rest unchanged +- Don't mark a PR ready. + +Your final message gives: + +1. The PR links, in merge order, with what each one cleans up. +2. The checks you ran for each, with their results. +3. Bugs: `file:line`, what goes wrong and how to reproduce it. +4. Issues that cross areas, and other design issues: `file:line`, what's + wrong, why it matters and a fix. + +Check every item against the source before you report it. When you get review +findings, fix them on that PR's branch, rerun the affected checks, push, and +report what changed. diff --git a/.agents/skills/sourceorigin-cleanup/references/review-brief.md b/.agents/skills/sourceorigin-cleanup/references/review-brief.md new file mode 100644 index 000000000..a7e0bc523 --- /dev/null +++ b/.agents/skills/sourceorigin-cleanup/references/review-brief.md @@ -0,0 +1,27 @@ +# Cleanup pass: reviewer + +Review one PR from a SourceOrigin cleanup pass. It claims to be a pure +refactor: no behavior, output, schema, format or test coverage changes. Bug +fixes go in their own PRs, so any behavior change here is a finding. + +Review read-only. Don't push, comment or edit. Read the PR, and check out the +head SHA your task gives (`git fetch origin pull//head`). Export the +`CARGO_BUILD_JOBS` your task gives. + +Check every claim in your focus list yourself, against the base branch your +task gives (`origin/main` unless the PR is stacked). Then look for, most +important first: + +1. Hidden behavior changes: error codes, messages, statuses and precedence, + defaults, serialization (tokens, domain events, audit records, wire + types), rendered pages and emails, log and span fields, timeouts, lock + order and transaction boundaries, query plans (compare `EXPLAIN` in + `just db scratch -- psql`), and the published crates' public API. +2. Lost coverage: dropped assertions or cases, and expected values built by + the code under test. Compare test names and counts per file with the base. +3. Abstractions that make the code harder to read. +4. Missed cleanup and stale doc comments in the touched files, briefly. + +Report each finding with its severity (blocker, should-fix or nit), +`file:line`, the problem and a fix. Say which claims you verified and how. If +the PR is clean, say so. diff --git a/.agents/skills/sourceorigin-cleanup/scripts/stats.py b/.agents/skills/sourceorigin-cleanup/scripts/stats.py new file mode 100644 index 000000000..6c2fcd52c --- /dev/null +++ b/.agents/skills/sourceorigin-cleanup/scripts/stats.py @@ -0,0 +1,311 @@ +"""Line statistics for a sourceorigin checkout, for the audit step of a cleanup pass. + +Usage: python3 -I stats.py [REPO] [--json OUT] + +Prints a summary and, with --json, writes every per-file record and the +history to OUT for charts. Generated files are the ones .gitattributes marks +linguist-generated, and lockfiles are Cargo.lock and pnpm-lock.yaml. Rust lines +are classified by a small lexer: a line is code, a doc comment (/// or //!), a +plain comment or blank, and a line with code and a trailing comment counts as +code. Rust test code is whole files under tests/, tests.rs files, modules +declared behind #[cfg(test)], and inline #[cfg(test)] items. TypeScript and +JavaScript test code is packages/auth/test and tests/browser. Other languages +are counted by cloc. +""" +import bisect, csv, io, json, os, re, subprocess, sys +from collections import defaultdict + +args = sys.argv[1:] +out = None +if "--json" in args: + i = args.index("--json") + out = os.path.abspath(args[i + 1]) + del args[i:i + 2] +os.chdir(args[0] if args else ".") + + +def git(*a): + return subprocess.run(["git", *a], capture_output=True, text=True, check=True).stdout + + +if git("rev-parse", "--is-shallow-repository").strip() == "true": + print("warning: shallow clone, so the growth history starts at its boundary", file=sys.stderr) +files = git("ls-files", "-z").split("\0")[:-1] +attrs = git("check-attr", "-z", "linguist-generated", "--", *files).split("\0") +marked = {attrs[i] for i in range(0, len(attrs) - 2, 3) if attrs[i + 2] in ("set", "true")} +LOCKFILE = re.compile(r"(^|/)(Cargo\.lock|pnpm-lock\.yaml)$") +LOCKFILES = {p for p in files if LOCKFILE.search(p)} +GENERATED = marked - LOCKFILES +TS_TESTS = ("packages/auth/test/", "tests/browser/") + + +def area(p): + parts = p.split("/") + if parts[0] in ("apps", "crates", "packages", "tools", "tests") and len(parts) > 2: + return f"{parts[0]}/{parts[1]}" + if parts[0] in ("docs", "infra"): + return parts[0] + return "root & CI" + + +def module(p): + """The top-level module or directory of an area holding p: apps/x/src/oidc, apps/x/tests.""" + a = area(p) + parts = p[len(a) + 1:].split("/") + head = parts[:2] if parts[0] == "src" and len(parts) > 2 else parts[:1] + return a + "/" + "/".join(head) + + +RAW = re.compile(r'b?r(#*)"') + + +def lex_rust(src): + """Per-line flags (code, doc, comment) and the offsets of braces in code.""" + n, lines = len(src), src.count("\n") + 1 + code, doc, com = [False] * lines, [False] * lines, [False] * lines + braces, i, line = [], 0, 0 + while i < n: + c = src[i] + if c == "\n": + line += 1; i += 1; continue + if c in " \t\r": + i += 1; continue + if src.startswith("//", i): + is_doc = (src.startswith("///", i) and not src.startswith("////", i)) or src.startswith("//!", i) + (doc if is_doc else com)[line] = True + j = src.find("\n", i) + i = n if j < 0 else j + continue + if src.startswith("/*", i): + is_doc = (src.startswith("/**", i) and not src.startswith("/**/", i)) or src.startswith("/*!", i) + kind = doc if is_doc else com + kind[line] = True + depth, i = 1, i + 2 + while i < n and depth: + if src.startswith("/*", i): depth += 1; i += 2 + elif src.startswith("*/", i): depth -= 1; i += 2 + else: + if src[i] == "\n": + line += 1; kind[line] = True + i += 1 + continue + code[line] = True + m = RAW.match(src, i) + if m and (i == 0 or not (src[i - 1].isalnum() or src[i - 1] == "_")): + end = '"' + m.group(1) + j = src.find(end, m.end()) + j = n if j < 0 else j + len(end) + for k in range(i, j): + if src[k] == "\n": line += 1; code[line] = True + i = j; continue + if c == '"' or src.startswith('b"', i): + i += 1 if c == '"' else 2 + while i < n and src[i] != '"': + if src[i] == "\\": i += 1 + if i < n and src[i] == "\n": line += 1; code[line] = True + i += 1 + i += 1; continue + if c == "'": + if i + 1 < n and src[i + 1] == "\\": + i = src.find("'", i + 2) + 1; continue + i += 3 if i + 2 < n and src[i + 2] == "'" else 1 + continue + if c in "{}": + braces.append((i, c)) + i += 1 + return code, doc, com, braces + + +def inline_test_lines(src, braces): + """Line numbers of #[cfg(test)] items inside a file that isn't all test code.""" + test, offsets = set(), [b[0] for b in braces] + for m in re.finditer(r"#\[cfg\(test\)\]", src): + semi = src.find(";", m.end()) + k = bisect.bisect_left(offsets, m.end()) + if k >= len(braces) or (semi >= 0 and semi < braces[k][0]): + end = semi + else: + depth, end = 0, len(src) + for off, ch in braces[k:]: + depth += 1 if ch == "{" else -1 + if depth == 0: + end = off; break + test.update(range(src.count("\n", 0, m.start()), src.count("\n", 0, end) + 1)) + return test + + +def test_files(rs, sources): + """Rust files that are test code as a whole.""" + tf = {p for p in rs if "/tests/" in "/" + p or p.endswith("/tests.rs")} + for p in rs: + for m in re.finditer(r"#\[cfg\(test\)\]\s*(?:pub(?:\([a-z]+\))?\s+)?mod\s+(\w+)\s*;", sources[p]): + d, base = os.path.split(p) + stem = base[:-3] + root = os.path.join(d if stem in ("mod", "lib", "main") else os.path.join(d, stem), m.group(1)) + tf.update(q for q in rs if q == root + ".rs" or q.startswith(root + "/")) + return tf + + +others = [p for p in files if not p.endswith(".rs") and os.path.isfile(p)] +cloc = {} +report = subprocess.run(["cloc", "--by-file", "--csv", "--quiet", "--skip-uniqueness", "--list-file=-"], + input="\n".join(others), capture_output=True, text=True, check=True).stdout +for row in csv.reader(io.StringIO(report)): + if len(row) >= 5 and row[0] not in ("language", "SUM"): + cloc[row[1].removeprefix("./")] = (row[0], int(row[2]), int(row[3]), int(row[4])) + +rs = [p for p in files if p.endswith(".rs")] +sources = {p: open(p, encoding="utf-8").read() for p in rs} +whole_tests = test_files(rs, sources) +FACTS = { + "unsafe": r"\bunsafe\s*(\{|fn\b|impl\b|trait\b)", "#[allow": r"#!?\[allow\(", + "#[expect": r"#!?\[expect\(", ".unwrap()": r"\.unwrap\(\)", ".expect(": r"\.expect\(", + "TODO/FIXME": r"\b(TODO|FIXME|XXX)\b", +} +facts = defaultdict(int) +tests = defaultdict(int) +pg_tests = 0 # Rust tests ignored unless TEST_DATABASE_URL is set +records = [] +for p in files: + kind = "generated" if p in GENERATED else "lockfile" if p in LOCKFILES else "handwritten" + rec = dict(path=p, area=area(p), kind=kind, lang="Other", blank=0, code=0, doc=0, comment=0, + test_code=0, test_comment=0) + if p.endswith(".rs"): + src = sources[p] + code, doc, com, braces = lex_rust(src) + lines = src.split("\n") + if lines and lines[-1] == "": + lines.pop() + tl = set(range(len(lines))) if p in whole_tests else inline_test_lines(src, braces) + for ln in range(len(lines)): + t = ln in tl + if code[ln]: + rec["test_code" if t else "code"] += 1 + elif doc[ln] or com[ln]: + rec["test_comment" if t else "doc" if doc[ln] else "comment"] += 1 + else: + rec["blank"] += 1 + rec["lang"] = "Rust" + if kind == "handwritten": + prod = "\n".join(l for i, l in enumerate(lines) if i not in tl) + for k, rx in FACTS.items(): + facts[k] += len(re.findall(rx, prod, re.M)) + n = len(re.findall(r"#\[(tokio::)?test\b", src)) + tests["rust integration" if "/tests/" in "/" + p and "/src/" not in p else "rust unit"] += n + pg_tests += len(re.findall(r'#\[ignore = "requires (a disposable )?TEST_DATABASE_URL"\]', src)) + elif p in cloc: + lang, b, c, k = cloc[p] + rec.update(lang=lang, blank=b, comment=c, code=k) + if p.startswith(TS_TESTS) and p.endswith((".ts", ".js")): + rec["test_code"], rec["code"], rec["test_comment"], rec["comment"] = k, 0, c, 0 + if p.endswith((".spec.ts", ".test.ts")) and not p.startswith("tests/browser/screenshots/"): + kind = "browser" if p.startswith("tests/browser/") else "typescript unit" + tests[kind] += len(re.findall(r"^\s*test(\.only)?\(", open(p).read(), re.M)) + elif os.path.isfile(p): + try: + text = open(p, encoding="utf-8").read() + except UnicodeDecodeError: + continue + ls = text.split("\n") + if ls and ls[-1] == "": + ls.pop() + rec["blank"] = sum(1 for l in ls if not l.strip()) + rec["code"] = len(ls) - rec["blank"] + if kind == "lockfile": + rec["lang"] = "Lockfile" + records.append(rec) + + +def total(r): + return sum(r[k] for k in ("blank", "code", "doc", "comment", "test_code", "test_comment")) + + +def hist_cat(p): + if p in GENERATED: return "generated" + if p in LOCKFILES: return "lockfile" + if p.endswith(".md"): return "docs" + if (p.endswith(".rs") and ("/tests/" in "/" + p or p.endswith("tests.rs"))) or \ + (p.startswith(TS_TESTS) and p.endswith((".ts", ".js"))): + return "test" + return "source" + + +# Growth by category, one point per first-parent commit. Inline test modules +# count as source here, so "test" is lower than in the summary. +history, cur, running = [], None, defaultdict(int) +for l in git("log", "--reverse", "--first-parent", "--no-renames", "--numstat", + "--format=@@%h %aI %s", "HEAD").split("\n"): + if l.startswith("@@"): + if cur: history.append(cur) + sha, date, *subject = l[2:].split(" ") + cur = {"sha": sha, "date": date, "subject": " ".join(subject)} + elif l.strip(): + added, deleted, path = l.split("\t", 2) + if added != "-": + running[hist_cat(path)] += int(added) - int(deleted) + cur.update(running) +if cur: history.append(cur) + +# Summary. +hand = [r for r in records if r["kind"] == "handwritten"] +all_lines = sum(map(total, records)) +print(f"HEAD {git('rev-parse', '--short', 'HEAD').strip()}: {len(files)} files, {all_lines:,} lines") +for kind in ("handwritten", "generated", "lockfile"): + n = sum(total(r) for r in records if r["kind"] == kind) + print(f" {kind:<12} {n:>9,} {n / all_lines:5.1%}") + +print("\nHand-written by language (code / comments / blank):") +langs = defaultdict(lambda: [0, 0, 0]) +for r in hand: + l = langs[r["lang"]] + l[0] += r["code"] + r["test_code"]; l[1] += r["doc"] + r["comment"] + r["test_comment"]; l[2] += r["blank"] +for lang, (c, m, b) in sorted(langs.items(), key=lambda kv: -kv[1][0])[:10]: + print(f" {lang:<16} {c:>8,} {m:>8,} {b:>8,}") + +rust = [r for r in hand if r["lang"] == "Rust"] +src, tst = sum(r["code"] for r in rust), sum(r["test_code"] for r in rust) +doc, com = sum(r["doc"] for r in rust), sum(r["comment"] for r in rust) +print(f"\nRust: {src:,} source, {tst:,} test ({tst / (src + tst):.0%}), " + f"{doc:,} doc comment and {com:,} plain comment lines outside tests") + +print("\nBy area (source / test / test share):") +areas = defaultdict(lambda: [0, 0]) +for r in hand: + if r["lang"] not in ("Markdown", "Other"): + areas[r["area"]][0] += r["code"]; areas[r["area"]][1] += r["test_code"] +for a, (s, t) in sorted(areas.items(), key=lambda kv: -sum(kv[1])): + print(f" {a:<24} {s:>8,} {t:>8,} {t / (s + t) if s + t else 0:5.0%}") + +modules = defaultdict(lambda: [0, 0]) +for r in hand: + if r["lang"] not in ("Markdown", "Other", "TOML") and sum(areas[r["area"]]) > 30000: + modules[module(r["path"])][0] += r["code"]; modules[module(r["path"])][1] += r["test_code"] +if modules: + print("\nModules of areas over 30,000 lines (source / test):") + for m, (s, t) in sorted(modules.items(), key=lambda kv: -sum(kv[1])): + print(f" {m:<40} {s:>8,} {t:>8,}") + +print("\nHand-written files over 1,500 lines:") +for r in sorted((r for r in hand if r["lang"] not in ("Markdown", "Other") and total(r) > 1500), + key=total, reverse=True): + print(f" {total(r):>6,} {r['path']}") + +print("\nTests:", ", ".join(f"{v} {k}" for k, v in tests.items()), f"({pg_tests} of the Rust ones need PostgreSQL)") +print("Outside tests:", ", ".join(f"{v} {k}" for k, v in facts.items())) +print("(regex counts: close, not exact)") + +# `foo.rs` next to `foo/` is caught by clippy::self_named_module_files. The +# other half of the layout rule is that a `mod.rs` needs children, a tests.rs +# at least (docs/dev/rust-conventions.md). +lonely = [p for p in rs if p.endswith("/mod.rs") + and not any(q != p and q.startswith(os.path.dirname(p) + "/") for q in rs)] +if lonely: + print("\nmod.rs files with no child modules (should be a plain foo.rs):") + for p in lonely: + print(f" {p}") + +if out: + with open(out, "w") as f: + json.dump({"files": records, "facts": facts, "tests": tests, "postgres_tests": pg_tests, "history": history, + "generated": sorted(GENERATED), "lockfiles": sorted(LOCKFILES)}, f, indent=1) + print(f"\nWrote {out}")