歷史上,霍去病封狼居胥饮马瀚海的故事讓後人寫下著名的詞:千古江山,英雄無覓,孫仲謀處。舞榭歌臺,風流總被,雨打風吹去。斜陽草樹,尋常巷陌,人道寄奴曾住。想當年,金戈鐵馬,氣吞萬里如虎。 元嘉草草,封狼居胥,贏得倉皇北顧。四十三年,望中猶記,烽火揚州路。可堪回首,佛狸祠下,一片神鴉社鼓。憑誰問,廉頗老矣,尚能飯否?
• 孫仲謀與寄奴(劉裕): 上片緬懷東吳孫權與南朝宋武帝劉裕的英雄氣概,對比今日繁華消逝、尋常巷陌的蕭條。 • 元嘉草草: 借宋文帝劉義隆倉促北伐卻大敗的歷史,提醒當權者切忌輕敵冒進。 • 四十三年與佛狸祠: 回憶南歸至今的歲月與戰火記憶,感嘆敵軍曾駐紮之地如今祭祀喧囂、國勢堪憂。 • 廉頗自喻: 以年邁卻仍思效力的戰國名將廉頗自況,表達壯志未酬與渴望受重用的心境。
Clip C6 (v4) of the Hedgehog Dad mini-series, created with the prompts.chat prompt generator 'Cinematic Image-to-Video Motion Control Prompt Builder' (cmwwoa76w0001jq089obs442x): the hedgehog father drops the spine onto the rug, crosses his arms and stares down the crow, who stays still on the windowsill. Image-to-video from a sharp keyframe.
Locked tripod wide shot, no camera movement. The hedgehog slowly lowers his paw and drops the spine onto the rug, then crosses his arms and lifts his chin, lips pressed shut. The crow stays perfectly still on the sill, only blinking. Warm morning light holds steady; soft fireplace flicker and drifting dust motes. Preserve both characters' identities exactly: one hedgehog, one crow, no warping, no new characters. Smooth 24fps, 6 seconds.
Clip C6 (v3) of the Hedgehog Dad mini-series: the hedgehog father drops the spine onto the pile, crosses his arms and stares down the crow Seu Bento, firmly. Only the father moves; Bento stays still on the windowsill. Continuity rules so Veo does not mix the two animals. Locked camera, no dialogue.
Style: Pixar-style 3D animated family drama, warm soft morning light, soft shadows, 24 fps, STATIC LOCKED CAMERA for the whole clip, same framing as the start frame, smooth natural motion. 16:9, 8 seconds. Characters: - THE FATHER: adult hedgehog, brown fur, dark spines with cream tips, mustard-yellow knitted scarf, dark green vest, exactly two small round hedgehog ears. Stubborn, determined face, mouth always closed. - SEU BENTO: a crow (a bird, not a hedgehog), black feathers with grey tips, round golden glasses, red bow tie, brown tweed beret, dark grey beak, wings folded. Worried face. Same faces, outfits and colors in every shot. Exactly one hedgehog and one crow for the whole clip, nothing else. Location: A cozy hedgehog burrow carved inside tree roots: round window on screen-left, wooden shelves with jars, a stone fireplace with fire on screen-right, a colorful crocheted rug in the center with a pile of pulled spines on it. Bento is perched on the sill of the round window on screen-left; the father stands on the rug at screen-center facing Bento, holding one pulled spine. The pile of spines stays on the rug for the whole clip. Continuity rules: animate the attached start frame exactly as it is. The crow and the hedgehog are two different animals and stay separate at all times: the crow keeps feathers, wings and beak and never grows spines; the hedgehog keeps spines and never gets glasses, beret or wings. Nobody new appears in the room. The window light stays soft, the crow stays dark and sharp. SHOT SEQUENCE: * 0-3s: Wide shot. ONLY THE FATHER MOVES: he drops the spine from his paw onto the pile of spines on the rug. Stubborn, not smiling. Mouth closed. * 3-5.5s: Wide shot. ONLY THE FATHER MOVES: he looks at Bento, crosses his arms and lifts his chin, lips pressed together. Mouth closed. * 5.5-8s: Wide shot. ONLY THE FATHER MOVES: he glances down at the pile of spines, then back up at Bento, firm and determined. Mouth closed. Bento stays perfectly still on the sill for the whole clip, wings folded, only blinking; he never moves, never flies, never changes. Audio: No dialogue. A small tick when the spine lands on the pile at 1.5s, crackling fireplace, low emotional piano, a soft suspense note at the end. No narration. Negative: a second hedgehog, a hedgehog with glasses, Bento turning into a hedgehog, Bento splitting or duplicating, mixed animals, the father wearing glasses, open mouth, shouting, pain expression, distorted faces, melting features, extra ears, fox ears, the father turning to face the camera, the father turning his back, Bento flying, Bento leaving the sill, Bento entering the room, Bento losing his glasses, beret or bow tie, yellow or orange beak, the spines disappearing from the rug, extra characters, camera movement, zoom, camera rotation, cuts, scene jumps, teleportation, flickering, jittery motion, deformed hands or wings, subtitles, readable text, logos, watermark.
Keyframe of the Hedgehog Dad mini-series: the same scene and framing as the end of C5, with the crow Seu Bento sharp on the windowsill and the hedgehog father holding a spine. Made to serve as the opening frame of the C6 v3 video (so Veo does not mix the two animals).
Style: Pixar-style 3D animated family film still, warm soft morning light, gentle window glow without glare, soft shadows, crisp sharp details. 16:9. Characters: - THE FATHER: adult hedgehog, brown fur, dark spines with cream tips, mustard-yellow knitted scarf, dark green vest, exactly two small round hedgehog ears. Stubborn, determined face, mouth closed. - SEU BENTO: a crow (a bird, not a hedgehog), black feathers with grey tips, round golden glasses, red bow tie, brown tweed beret, dark grey beak, two black wings folded. Worried face. Same faces, outfits and colors as the reference images. Exactly one hedgehog and one crow, nothing else. Location: Same exact room, camera position and framing as the first reference image: a cozy hedgehog burrow carved inside tree roots, round window on screen-left, wooden shelves with jars, a stone fireplace with fire on screen-right, a colorful crocheted rug in the center with a pile of pulled spines on it. Composition: Wide shot. Bento is perched on the sill of the round window on screen-left, clearly visible, sharp and dark against the window, wings folded, facing the father. The father stands on the rug at screen-center in three-quarter profile facing Bento, holding one pulled spine in his paw. Negative: a second hedgehog, a hedgehog with glasses, a crow with spines, mixed animals, Bento inside the room, blown-out window glare, washed-out or blurry crow, extra characters, changed outfits or colors, yellow or orange beak, extra ears, fox ears, text, subtitles, logos, watermark.
Clip C6 (v2) of the Hedgehog Dad mini-series, opening Part 2 from the last frame of Part 1: the hedgehog father throws the spine onto the pile, crosses his arms and stares down the crow Seu Bento, who shakes his head and lowers his head, sad. One character moves at a time, locked camera, no dialogue.
Style: Pixar-style 3D animated family drama, warm cinematic morning light through a round window, soft shadows, 24 fps, STATIC LOCKED CAMERA for the whole clip, same framing as the start frame, smooth natural motion. 16:9, 8 seconds. Characters: - THE FATHER: adult hedgehog, brown fur, dark spines with cream tips, mustard-yellow knitted scarf, dark green vest, exactly two small round hedgehog ears. Stubborn, determined face, mouth always closed. - SEU BENTO: an old crow, dark grey feathers, round golden glasses, red bow tie, brown tweed beret, dark grey beak. Worried, sad face. Same faces, outfits and colors in every shot. Only these two characters. Location: A cozy hedgehog burrow carved inside tree roots: round window on screen-left, wooden shelves with jars, a stone fireplace with fire on screen-right, a colorful crocheted rug in the center with a pile of pulled spines lying on it. Bento is perched ON THE SILL of the round window on screen-left; the father stands on the rug at screen-center, facing Bento, holding one pulled spine in his paw. The pile of spines stays on the rug for the whole clip. SHOT SEQUENCE: * 0-3s: Wide shot. ONLY THE FATHER MOVES: he drops the spine from his paw onto the pile of spines on the rug. Stubborn, not smiling. Bento stays still on the sill. Mouths closed. * 3-5.5s: Wide shot. ONLY THE FATHER MOVES: he looks at Bento, crosses his arms and lifts his chin, firm and stubborn, lips pressed together. Bento stays still. Mouths closed. * 5.5-8s: Wide shot. ONLY BENTO MOVES: he slowly shakes his head and then lowers his head, sad. The father stays still with crossed arms, facing Bento. Mouths closed. Audio: No dialogue. A small tick when the spine lands on the pile at 1.5s, crackling fireplace, low emotional piano, a soft suspense note at the end. No narration. Negative: open mouth, shouting, screaming, pain expression, distorted faces, melting features, extra ears, fox or rabbit ears, the father turning into another animal, the father turning to face the camera, the father turning his back, Bento flying, Bento leaving the sill, Bento entering the room, Bento losing his glasses, beret or bow tie, yellow or orange beak, the spines disappearing from the rug, changing faces or outfits, extra characters, duplicated characters, camera movement, zoom, camera rotation, cuts, scene jumps, teleportation, flickering, jittery motion, deformed hands or wings, subtitles, readable text, logos, watermark.
Clip C6 of the Hedgehog Dad mini-series (opens Part 2, continuing from the last frame of Part 1): the hedgehog father ignores the warning from the crow Seu Bento, pulls out one more spine, and Bento flies away out the window. Image-to-video from the last frame of C5. No dialogue.
Style: Pixar-style 3D animated family drama, warm cinematic morning light through a round window, soft shadows, 24 fps, STATIC LOCKED CAMERA for the whole clip, same framing as the start frame, smooth natural motion. 16:9, 8 seconds. Characters: - THE FATHER: adult hedgehog, brown fur, dark spines with cream tips, mustard-yellow knitted scarf, dark green vest, exactly two small round hedgehog ears. Determined face. - SEU BENTO: an old crow, dark grey feathers, round golden glasses, red bow tie, brown tweed beret, dark grey beak. Worried face. Same faces, outfits and colors in every shot. Only these two characters. Location: A cozy hedgehog burrow carved inside tree roots: round window on screen-left, wooden shelves with jars, a stone fireplace with fire on screen-right, a colorful crocheted rug in the center with several pulled spines lying on it. Bento is perched ON THE SILL of the round window on screen-left; the father stands on the rug at screen-center, holding one pulled spine in his paw. SHOT SEQUENCE: * 0-2s: Wide shot. The father throws the spine down onto the pile of spines on the rug. Determined, not smiling. Mouths closed. * 2-4s: Wide shot. The father looks at Bento and lifts his chin, firm and stubborn. Bento looks back, worried. Mouths closed. * 4-6s: Wide shot. The father reaches to his own shoulder, pulls out one more spine and winces in pain. Mouths closed. * 6-8s: Wide shot. Bento slowly shakes his head, opens his wings and flies away out through the round window. The father, now alone, turns his head toward screen-right as if he heard a voice. Mouths closed. Audio: No dialogue. A small tick when the spine hits the rug at 1s, crackling fireplace, low emotional piano, a small "pop" at 4.5s, wing flaps at 6.5s, a suspense note at the end. No narration. Negative: distorted faces, melting features, extra ears, fox or rabbit ears, the father turning into another animal, Bento losing his glasses, beret or bow tie, yellow or orange beak, changing faces or outfits, extra characters, duplicated characters, Bento entering the room, deformed wings, camera movement, zoom, cuts, scene jumps, teleportation, flickering, jittery motion, deformed hands, subtitles, readable text, logos, watermark.
Read-only analysis of what a polyrepo setup costs: bugs from version drift and cross-repo changes, plus developer and CI time spent on internal dependency bumps, releases and duplicated fixes, converted to money. Works from the repositories' own git history and writes Markdown, JSON and HTML reports with a business case and a migration plan for the repos that would actually benefit from a monorepo.
---
name: polyrepo-tax
description: Use when a user wants to know what their polyrepo setup costs - bugs from version drift and cross-repo changes, developer and CI time spent on internal dependency bumps, releases and duplicated fixes - converted to money, or wants a business case and migration plan for moving several repositories into a monorepo. Read-only; analyzes git history and writes Markdown and JSON reports.
---
# Polyrepo Tax
Measure what splitting code across repositories costs an organization, from the
repositories' own git history: bugs attributable to repo boundaries, developer
hours and CI minutes spent moving code between repos, the equivalent money, and
a migration plan for the repos that would actually benefit.
Prerequisites: Node ≥ 22.5 and git. Optional: an authenticated `gh` CLI for real CI minutes.
`$S` is this skill's directory (the one holding this file). The work dir is `$W` = `$(node -p 'require("os").tmpdir()')/polyrepo-tax`.
## Rules
- **Read-only.** Never push, open PRs, edit files or run builds in the analysed repos. Allowed writes: clones and config under `$W`, and the reports (`polyrepo-tax-report.{md,json,html}`, `migration-plan.md`) (default `tmpdir/polyrepo-tax-reports`, or a user-given dir).
- Allowed commands: `git clone --bare` / `git fetch` into `$W`, read-only `git` (`log`, `show`, `ls-tree`, `for-each-ref`, `rev-parse`), `node $S/scripts/analyze.mjs`, `node $S/scripts/render-html.mjs`, `node $S/scripts/fetch-ci.mjs` (only `gh api` GETs), and `gh repo list` to discover repos.
- **Estimates, not invoices.** Every number must trace to commits or to a stated assumption. Never invent counts, rates, incidents or CI minutes. Use the user's numbers when given; otherwise use the defaults and label them as defaults.
- **Attribution, not blame.** Bugs are "attributable to repo boundaries" with a confidence level, never "caused by" a person. Do not name individual authors in the summary.
- **Honest recommendation.** If the measured tax is small, coupling is low or payback is longer than the user's horizon, say that a monorepo is not worth it (or only for one cluster). Never inflate assumptions to reach a target.
- Use only the bug categories defined in [references/signals.md](references/signals.md).
## Workflow
1. **Collect inputs** — follow [references/inputs.md](references/inputs.md): get the repo list, the window, internal package scopes, the loaded developer rate and the CI price. Clone the repos with full history into `$W/repos` and write `$W/polyrepo-tax.config.json`.
2. **CI minutes (optional)** — if the repos are on GitHub and `gh auth status` succeeds, run `fetch-ci.mjs` as described in inputs.md. Otherwise skip it: the analyzer uses `ciMinutesPerCommit` and marks CI as `assumed`.
3. **Analyze** — `node "$S/scripts/analyze.mjs" --config "$W/polyrepo-tax.config.json" --out <report dir>`. Signal definitions are in [references/signals.md](references/signals.md); the cost formulas are in [references/cost-model.md](references/cost-model.md).
4. **Review** — read the high- and medium-confidence bugs in the JSON report. For each one that the commit evidence does not support (for example `git show <sha>` shows an unrelated change), add the full SHA to `excludeCommits` in `$W/overrides.json` and rerun step 3 with `"overrides": "overrides.json"` in the config. Tell the user how many you excluded and why.
5. **Migration plan** — follow [references/migration.md](references/migration.md) to turn the report's `migration` section into a phased plan. Write it to `migration-plan.md` in the report dir, append it to the Markdown report, and run `node "$S/scripts/render-html.mjs" <report dir>/polyrepo-tax-report.json` so the HTML report includes it.
6. **Present** — follow [references/report-format.md](references/report-format.md): where the reports are, the headline numbers as a range, the top bugs with evidence, the assumptions that drive most of the cost, and the recommendation.
## Tracking
Create a todo per workflow step and mark each done when its output exists.
FILE:references/cost-model.md
# Cost model
`cost = developer hours × developerHourly + CI minutes × ciPerMinute`, computed per cost driver, then annualized as `cost × 365 / window days`.
## Assumptions
All are overridable through `assumptions` in the config. The report prints the values it used.
| Name | Default | Used for |
|---|---:|---|
| `bumpHumanHours` | 0.5 | Each internal bump by a person: open, review, merge, babysit CI. |
| `bumpBotHours` | 0.2 | Each internal bump by a bot: review and merge. |
| `releaseHours` | 0.5 | Each internal release consumed by a sibling repo, except `publicPackages`. |
| `coordinationHoursPerExtraRepo` | 2 | Each extra repo in a coordinated change: sequencing PRs, waiting on releases, cross-repo review. |
| `duplicateChangeHoursPerCopy` | 1 | Each extra copy of a repeated maintenance change or duplicated fix (`bumpBotHours` instead when every copy is by a bot). |
| `bugHours` | 8 | Each bug: triage, fix, review, release, bump. Duplicated fixes add `duplicateChangeHoursPerCopy` per extra repo. |
| `ciMinutesPerCommit` | 15 | CI minutes per landed commit when a repo has no CI data. With CI data: `totalMinutes ÷ commits in window`. |
| `bumpFixWindowDays` | 7 | `post-bump-fix` window. |
| `groupWindowDays` | 14 | Max spread of one cross-repo group. |
| `similarity` | 0.75 | Subject similarity threshold. |
| `migrationDaysPerRepo` | 3 | One-time import + CI + ownership work per migrated repo. |
| `migrationDaysPerConflict` | 0.5 | One-time alignment per external dependency with conflicting majors. |
| `monorepoToolingMonthly` | 0 | Ongoing monorepo cost (remote cache, larger runners), subtracted before payback. |
If the user has better numbers (for example "a production incident costs us 20 hours on average"), use them and say so.
## CI minutes per driver
Each driver's commits (bump commits, release commits, every commit in a bug, each extra-repo commit in a group) × that repo's CI minutes per commit. This treats an overhead commit as costing as much CI as an average landed change in that repo, including its PR runs.
## Scenarios
| Scenario | Bugs included |
|---|---|
| `low` | high confidence only |
| `expected` | high + medium |
| `high` | high + medium + low |
Non-bug drivers are identical across scenarios. Present `low`–`high` as the range, `expected` as the headline.
## Monorepo savings
Share of each driver a monorepo with workspace dependencies (`workspace:*`), affected-only CI and atomic commits removes:
| Driver | Removed | Reason |
|---|---:|---|
| Internal bumps, internal releases | 100% | Consumers build against source; no publish/bump cycle. |
| Repeated tooling changes, duplicated fixes, fix propagation | 100% | One config and one copy of the code. |
| Coordinated changes | 75% | One atomic PR; review across teams still costs time. |
| Dependency regressions, post-bump fixes | 90% | The producer PR runs consumer tests; some breaks still slip past tests. |
| Cross-repo fixes | 50% | Atomic fix, but the bug can still happen. |
Payback months = one-time migration cost ÷ (annual savings ÷ 12 − `monorepoToolingMonthly`). Both sides cover only the repos that would move (coupled clusters):
- Savings count an event only when its repos are all in scope: bumps and releases in migrated repos of packages produced by migrated repos, bugs whose repos all move, and the in-scope part of a cross-repo group with at least two in-scope repos. Cost per driver still covers every analysed repo.
- One-time cost = (`migrationDaysPerRepo` × migrated repos + `migrationDaysPerConflict` × external conflicts among migrated repos) × 8 × `developerHourly`.
Isolated repos are excluded from migration cost, savings and the recommendation.
The model does not count costs that are real but hard to measure from git: onboarding to N toolchains, context switching, slower discovery of shared code, and security patches applied N times (unless they show up as repeated changes). Mention them qualitatively, never as numbers.
FILE:references/inputs.md
# Step 1 — Inputs
Ask for anything below that the user has not given, in **one** message. Offer the default for each so they can just say "use defaults".
| Input | Default | Notes |
|---|---|---|
| Repositories | — (required) | Git URLs, `owner/repo` slugs, local paths, or "all repos in org X that team Y contributes to". Include the libraries the apps consume, not only the apps. |
| Window | last 12 months | Shorter windows are noisier; the report annualizes. |
| Internal package scopes | packages published by the listed repos | e.g. `@acme/`. Add a scope when apps consume internal packages from repos that are not in the list. |
| Loaded developer cost per hour | 100 USD | Salary + benefits + overhead ÷ working hours. Ask for their number; teams often use 75–150 USD. |
| CI price per minute | 0.008 USD | GitHub-hosted 2-core Linux list price at the time of writing. Ask for theirs: larger runners, macOS, self-hosted and plan discounts all differ. |
| Currency | USD | Set `rates.currency`; the report prints it. |
| Packages also used outside these repos | none | Packages published for other teams or open source keep releasing after a migration, so their releases are not costed. Put them in `publicPackages` (or `true` for all). |
To expand "all repos in org X": `gh repo list X --limit 1000 --no-archived --json nameWithOwner,pushedAt`. Show the list and ask which to include. Do not guess team membership.
## Clone
Use bare clones with full history. Shallow clones are reported as a data problem because they hide most history.
```bash
W="$(node -p 'require("os").tmpdir()')/polyrepo-tax"
mkdir -p "$W/repos"
# one per repo; for local paths, skip cloning and use the path directly
git clone --bare --quiet https://github.com/acme/web-app.git "$W/repos/web-app.git"
```
If a clone fails (no access, SSO), tell the user and continue with the others; list the missing repos in the final summary.
## Config
Write `$W/polyrepo-tax.config.json`. Paths are relative to the config file.
```json
{
"repos": [
{ "name": "ui-lib", "path": "repos/ui-lib.git", "github": "acme/ui-lib" },
{ "name": "web-app", "path": "repos/web-app.git", "github": "acme/web-app" }
],
"since": "2025-11-25",
"internalScopes": ["@acme/"],
"publicPackages": [],
"rates": { "developerHourly": 100, "ciPerMinute": 0.008, "currency": "USD" },
"assumptions": {},
"ci": "ci.json"
}
```
Put only overrides the user gave in `assumptions` (see cost-model.md for names). Leave out `"ci"` if step 2 is skipped.
## CI minutes (optional)
Only when `gh auth status` succeeds and repos have a `github` slug:
```bash
node "$S/scripts/fetch-ci.mjs" --config "$W/polyrepo-tax.config.json" --out "$W/ci.json"
```
It sums the wall-clock time of every completed GitHub Actions run in the window. The API caps a filtered query at 1000 runs, so it queries one month at a time and splits any range at the cap until each part is complete; if a single day still hits the cap, that repo fails and keeps the assumed CI minutes. It also samples job timings for up to 30 runs per repo (`--sample`) and scales the total by the measured job/wall ratio, which can be below 1 when queueing inflates wall-clock time. It makes only GET requests. A repo that fails keeps the assumed per-commit CI minutes; mention it.
Other CI systems: if the user can export total CI minutes per repo for the window, write `ci.json` by hand as `{ "repo_name": { "totalMinutes": 12345 } }`.
FILE:references/migration.md
# Step 5 — Migration plan
Write the plan from the report's `migration` section. Use only facts from the report and the repos; mark anything else as a suggestion.
## Decide scope first
- **Migrate:** the coupled clusters in `migration.clusters`, heaviest first.
- **Keep separate:** `migration.isolated`. Say why: no shared packages, no co-changes and no shared bugs in the window.
- **Don't migrate at all** when expected payback is longer than 24 months, or the user's horizon if they gave one, or every cluster has a weight below 5. Say so plainly, and suggest cheaper fixes for the top cost drivers instead: Renovate grouping and automerge for internal bumps, a shared CI template, contract tests between producer and consumer.
## Why migrate and tool options
The report carries two sections built from a dated snapshot of [monorepo.tools](https://monorepo.tools/) (`scripts/monorepo-tools.json`). Copy them into the plan as they are. Do not add tools, change ratings or give reasons the report does not list.
- **Why migrate** — `migration.whyMigrate`: the polyrepo costs monorepo.tools names (cumbersome code sharing, code duplication, costly cross-repo changes, hard-to-enforce conventions). Each appears only when this report measured evidence for it, with the counts. Present it as monorepo.tools' reasons, backed by this team's numbers.
- **Tool options** — `migration.toolOptions`: every tool monorepo.tools compares, not just one pick. Show all of them in a table with the rating, the per-category counts, the partial and unsupported counts, fit and whether the team already uses the tool.
- **monorepo.tools rating /10** = 10 × the features monorepo.tools marks "natively supported" ÷ the number of compared features. "Implement your own" and "community provided" are counted but not scored. Always call it the monorepo.tools rating, never just "the rating" or a neutral score.
- **Sources** — list every source under the table, monorepo.tools first, each with its publisher, retrieval date, role and coverage: monorepo.tools (published by Nx, scored), State of JS 2024 and 2025, and the Thoughtworks Radar (independent, not scored). The report renders this list; keep it when copying the table.
- **Fit** is `no` only when monorepo.tools marks polyglot support "not supported" and the repos contain more than JS/TS. Otherwise every tool fits; don't infer more.
- State `migration.toolSource`: the URLs, the snapshot date, and that monorepo.tools is made by Nx and accepts corrections by pull request. A feature count isn't a quality score: the team's stack, existing tools and skills matter too. Call those out as considerations, not as rating changes.
- **Independent signals (not scored)** — each option carries `independent`, from sources that aren't tool vendors: State of JS 2024 satisfaction (with its 2021 value), State of JS 2025 regular-use counts, and the Thoughtworks Technology Radar ring. They cover only some tools. Show "—" where none applies, never fill a gap, and never fold them into the rating: they measure sentiment, usage or expert opinion, not features. Say that every Radar blip shown is archived (none is on the current edition), and give its date.
- If the snapshot is older than about six months, or the user doubts a mark, tell them to check monorepo.tools/compare and update `scripts/monorepo-tools.json`. The same applies to new State of JS editions or Radar volumes. Never patch marks or signals from memory.
## Plan template
Write this to `migration-plan.md` in the report directory, filled in, append it to `polyrepo-tax-report.md`, then re-render the HTML report (`render-html.mjs` embeds `migration-plan.md` from the same directory):
1. **Target layout and tooling** — the tool options table, then the pick: `migration.recommendedTool` is the stack-based default. If the team chooses another fitting tool from the table, use that one. Propose `apps/repo` for deployables and `packages/name` for libraries. If one repo already uses Nx, Turborepo or Bazel, build on it rather than adding a second tool.
2. **Phase 0 — prepare (no repo moves).**
- Align each entry in `migration.externalConflicts`, starting with those in the most repos. Each is a normal PR in the existing repo.
- Agree on one package manager, Node version and lint/format config (from `repos[].packageManager`, `nodeVersion`).
- Freeze new internal packages outside the monorepo.
3. **Phase 1 — first cluster.** Import the producer libraries, then their consumers, keeping history:
- Nx: `nx import <repo-url> <dest-dir>`
- Otherwise: `git subtree add --prefix=<dest-dir> <repo-url> <branch>`, or rewrite with `git filter-repo --to-subdirectory-filter <dest-dir>` and merge with `--allow-unrelated-histories`.
- Replace internal version ranges with `workspace:*` and delete the publish step for packages no external consumer uses.
- Set up affected-only CI (`nx affected` / `turbo run --affected` / Bazel target selection) so a change runs only the tests it can break.
- Move each repo's CODEOWNERS entries under its new directory.
- Archive the old repo (read-only, README pointing to the new path) once its last open PRs are merged or moved.
4. **Phase 2+** — the next clusters in order of weight.
5. **Verify** — run the `monorepo-doctor` skill on the new monorepo for boundaries, cycles, caching, CI coverage and test leakage. Use `monorepo-boundaries-cleanup` to pay down what it finds.
6. **Measure** — rerun polyrepo-tax on the old repos for the pre-migration window, and track bumps, duplicated fixes and regressions after the move.
State the one-time effort (`migration.oneTime`) and payback range, and the risks: CI capacity during the transition, history-rewrite mistakes, ownership disputes, and teams that release independently.
FILE:references/report-format.md
# Step 6 — Report
The analyzer writes three files to the output directory (default `tmpdir/polyrepo-tax-reports`):
- `polyrepo-tax-report.html` — the shareable report: headline range, cost-by-driver chart, filterable bug list with commit evidence, churn, migration and assumptions. One self-contained file with no network requests, light and dark mode, printable. Re-render it with `render-html.mjs` after writing `migration-plan.md`.
- `polyrepo-tax-report.md` — the same content as Markdown; step 5 appends the migration plan.
- `polyrepo-tax-report.json` — the full data.
## JSON shape (version 1)
| Key | Contents |
|---|---|
| `window`, `rates`, `assumptions` | Inputs actually used. |
| `problems` | Data problems (missing repo, shallow clone). |
| `repos[]` | Name, commit count, packages, languages, package manager, build tools, CI files, and `ci` (`minutesPerCommit`, `source`: `measured` or `assumed`). |
| `internal` | `packages` (producer → consumers), `bumps`, `releases`, `medianBumpLagDays`, `drift`, `skew`. |
| `bugs[]` | `id`, `category`, `confidence`, `repos`, `title`, `why`, `commits[]` (`repo`, `sha`, `date`, `subject`). |
| `coordinated[]`, `duplicatedTooling[]` | Cross-repo groups with commits. |
| `cost.{low,expected,high}` | `lines[]` per driver (`count`, `hours`, `ciMinutes`, `cost`, `annualCost`, `savingsShare`, `annualSavings`) and `totals`. |
| `migration` | `recommendedTool`, `toolOptions[]` (every monorepo.tools tool: `rating` /10, `counts` per mark, `categories[]`, `gaps`, `fit`, `fitReason`, `alreadyUsed`, `independent`: State of JS and Thoughtworks Radar data where a source covers the tool, else `null`), `whyMigrate[]` (monorepo.tools reasons with measured `evidence`), `toolSource` (URLs, snapshot date, publisher, legend, `independent` sources with metric and coverage), `clusters`, `isolated`, `coupling`, `externalConflicts`, `oneTime`, `paybackMonths`. |
## What to tell the user
Keep the message short; the report has the detail.
1. Paths of the reports; suggest the HTML file for sharing with leadership. It contains repo names, commit subjects and SHAs, so it is as confidential as the repos.
2. One line: expected cost for the window and annualized range, split into developer and CI money.
3. Bug counts by confidence, and the 3 strongest bugs, each with its commit evidence.
4. The two cost drivers that dominate, and the assumption each depends on, so the user knows which number to challenge.
5. The recommendation: which cluster to migrate first and its payback, which repos to keep separate, or why not to migrate. When recommending a migration, give the measured reasons from `migration.whyMigrate`, and the top fitting tools from `migration.toolOptions` with their ratings and the monorepo.tools source. The full table is in the report.
6. Data gaps: repos that failed to clone, CI that was assumed, commits you excluded in review.
Never present the expected number without the range, or money without the rates that produced it.
FILE:references/signals.md
# Signals
The analyzer reads the history reachable from each repo's `HEAD` (`git log --no-merges`) between the window start and `now`, `package.json` diffs, tags, and the files at `HEAD`. In the bare clones from inputs.md, `HEAD` is the default branch. For a local working copy, check out the default branch first; a feature branch adds unmerged commits and misses ones it does not contain. Package ecosystems other than npm contribute to grouping signals (tickets, repeated fixes, tooling churn) but not to dependency bumps.
## Internal packages
A package is internal when an analysed repo publishes it (a `package.json` `name` at `HEAD`) or its name starts with a configured `internalScopes` prefix.
- **Bump** — a commit that changes an internal dependency's version range in a `package.json` upwards. Authors matching `[bot]`, Renovate, Dependabot or github-actions count as bots. One count per (commit, package). A repo bumping its own package (a playground or docs workspace) is not counted.
- **Downgrade** — the same, but to a lower minimum version.
- **Release** — a commit that changes the `version` field of an internal package that another analysed repo consumes, or a tag `vX.Y.Z` / `name@X.Y.Z`. Tags only date releases; costed releases come from version commits. Packages listed in `publicPackages` (also consumed outside the analysed repos) are excluded: they keep releasing in a monorepo.
- **Lag** — days from a release to the consumer's bump to that version.
- **Drift / skew** — at `HEAD`, consumers below the newest known version, and internal packages used at more than one major version across repos.
## Bug categories
Only these categories exist. Each bug carries commit evidence.
| Category | Confidence | Detected when | Why it is a repo-boundary bug |
|---|---|---|---|
| `dependency-regression` | high | A commit downgrades an internal dependency, or is `Revert "subject"` of a bump commit in the same repo. | An internal release broke a consumer after it shipped. In a monorepo, the producer change runs the consumer's tests before merge. |
| `duplicated-fix` | medium | Fix commits (see below) with near-identical subjects land in ≥2 repos within `groupWindowDays`, or share a ticket and a subject. | The same code or contract was copied into several repos and had to be fixed in each. |
| `cross-repo-fix` | medium | Fix commits in ≥2 repos share a ticket key (`ABC-123`, `owner/repo#12`) but have different subjects. | One bug needed coordinated changes across repos: the contract between them lives nowhere. |
| `fix-propagation` | medium | A fix commit that also bumps an internal dependency up. | The fix needed a producer release and a consumer bump to reach users. |
| `post-bump-fix` | medium / low | A fix commit within `bumpFixWindowDays` after an internal bump in the same repo. Medium if it names the bumped package or uses compatibility words (breaking, compat, migrate, mismatch…); low if it only lands within 2 days of a **major** internal bump. | The bump exposed an integration break after release. |
A **fix commit** has a `fix:`/`hotfix:`/`bugfix:` conventional prefix (but not the `deps` or `release` scopes), or has no conventional prefix and a subject containing fix/bug/hotfix/regression/broken/crash/incident (but not "typo"). Any other conventional type wins: `docs: fix anchors` and `chore: fix lint` are not fixes. Dependency-update subjects (`chore(deps)`, `fix(deps)`, `update dependency … to v2`) are bumps, not fixes.
Each commit is assigned to at most one bug, in the order of the table rows: regressions, then groups, then single-commit categories.
## Duplicated and coordinated work
Commits that are not bumps, releases or bugs are grouped across repos when they share a ticket key or a near-identical subject (token Jaccard ≥ `similarity` after removing conventional prefixes, ticket keys, PR numbers and SHAs, at least 3 tokens, within `groupWindowDays`). Groups spanning more than twice the window are dropped as long-lived tickets.
- **Repeated maintenance** — every commit in the group only touches CI, lint, format, TypeScript, test-runner, Docker, Renovate or editor config, or is a dependency update (`chore(deps): …`). Each extra repo is a duplicate copy. It is a cost but **not** coupling: every repo has tooling, so it never pulls repos into a migration cluster.
- **Coordinated change** — any other group: one feature or refactor split across repos. This is coupling.
## Known blind spots
State these when the user questions a number:
- Squash-merged PRs hide branch history; merge-commit workflows contribute every branch commit.
- Bugs fixed without a fix-like subject, or never fixed in git (worked around in config, data or ops), are missed. Counts are a floor for the categories above, not a total bug count.
- Bumps in lockfiles only, in non-npm manifests (Maven, Gradle, Go, Python) and Git submodule pointer updates are not counted.
- Similar subjects can coincide by chance; review step 4 in SKILL.md exists to exclude them.
FILE:scripts/analyze.mjs
#!/usr/bin/env node
// polyrepo-tax analyzer. Read-only: runs only `git log`, `git show`, `git ls-tree`
// and `git for-each-ref` against the given repositories (bare clones work).
// Usage:
// node analyze.mjs --config polyrepo-tax.config.json [--out DIR]
// node analyze.mjs ../repo-a ../repo-b [--since 2025-11-25] [--scope @acme/] [--rate 100]
// [--ci-rate 0.008] [--ci ci.json] [--overrides overrides.json] [--out DIR]
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { renderHtml, independentSignals, toolSources } from './render-html.mjs';
export const DEFAULT_ASSUMPTIONS = {
// Developer hours per event. Every value is user-overridable and printed in the report.
bumpHumanHours: 0.5, // open/review/merge a manual internal-dependency bump PR
bumpBotHours: 0.2, // review + merge a Renovate/Dependabot internal bump PR
releaseHours: 0.5, // cut and publish an internal release that sibling repos consume
coordinationHoursPerExtraRepo: 2, // sequencing PRs/releases for one change spread over N repos
duplicateChangeHoursPerCopy: 1, // re-applying the same tooling/config change in another repo
bugHours: 8, // triage + fix + release + bump for one polyrepo-attributable bug
ciMinutesPerCommit: 15, // used only when no CI data is supplied for a repo
bumpFixWindowDays: 7, // a fix this soon after an internal bump is checked for a link to it
groupWindowDays: 14, // max spread for "same change in several repos"
similarity: 0.75, // token Jaccard threshold for "same commit subject"
migrationDaysPerRepo: 3, // one-time cost to import one repo into the monorepo
migrationDaysPerConflict: 0.5, // one-time cost to align one external-dependency major-version conflict
monorepoToolingMonthly: 0, // ongoing $ for remote cache / tooling, if any
};
// Share of each cost a monorepo removes. Documented in references/cost-model.md.
export const SAVINGS = {
bumps: 1, releases: 1, coordination: 0.75, duplicatedTooling: 1,
'dependency-regression': 0.9, 'post-bump-fix': 0.9, 'fix-propagation': 1, 'duplicated-fix': 1, 'cross-repo-fix': 0.5,
};
const BOT = /\[bot\]|^renovate|^dependabot|greenkeeper|github-actions|^snyk-bot/i;
const FIX_PREFIX = /^(fix|hotfix|bugfix)(\(([^)]*)\))?!?:/i;
const FIX_WORD = /\b(fix(es|ed)?|bug(fix)?|hotfix|regression|broken|crash(es|ed)?|incident)\b/i;
const DEPS_CHORE = /^(chore|build|fix|ci)\((deps|deps-dev|dependencies)\)|^(update|bump|upgrade)\b.*\b(dependency|dependencies|deps|from .* to|to v?\d)/i;
const RELEASE = /^(chore|build)(\(release\))?:\s*(release|publish|version)|^(release|publish|version)\b|^v?\d+\.\d+\.\d+$/i;
const COMPAT = /\b(compat|compatib\w*|breaking|incompatib\w*|migrat\w*|mismatch|api change|new version|after (the )?(bump|upgrade|update))\b/i;
const TICKET = /\b([A-Z][A-Z0-9]{1,9})-(\d+)\b/g;
const GH_REF = /\b([\w.-]+\/[\w.-]+)#(\d+)\b/g;
const TICKET_STOP = new Set(['UTF', 'ISO', 'SHA', 'RFC', 'ECMA', 'HTTP', 'ES', 'TLS', 'SSL', 'X', 'UTC', 'GMT']);
const CONFIG_FILE = /(^|\/)(\.github\/(workflows|actions)\/|\.gitlab-ci\.yml$|\.circleci\/|Jenkinsfile$|azure-pipelines\.yml$|\.buildkite\/|\.eslintrc|eslint\.config\.|\.prettierrc|prettier\.config\.|tsconfig[\w.-]*\.json$|\.nvmrc$|\.node-version$|\.tool-versions$|renovate\.json5?$|\.github\/dependabot\.yml$|Dockerfile|\.dockerignore$|\.editorconfig$|jest\.config\.|vitest\.config\.|\.npmrc$|\.yarnrc|babel\.config\.|\.babelrc|\.husky\/|\.lintstagedrc|commitlint\.config\.|\.gitignore$|CODEOWNERS$)/;
const GENERIC = new Set(['update readme', 'initial commit', 'wip', 'update', 'fix', 'fix typo', 'typo', 'cleanup', 'merge', 'tests', 'lint', 'format', 'update changelog', 'docs', 'fix tests', 'fix build', 'fix lint']);
// Source languages by file extension. Anything but js/ts makes the workspace polyglot for tool fit.
const LANG = [
['js/ts', /\.(m?[jt]sx?|cjs|cts|vue|svelte)$/],
['jvm', /\.(java|kts?|groovy|gradle)$/], ['scala', /\.(scala|sc)$/], ['clojure', /\.(clj|cljs|cljc|edn)$/],
['dotnet', /\.(cs|csx|fs|fsi|fsx|vb)$/],
['c/c++', /\.(c|cc|cpp|cxx|c\+\+|h|hh|hpp|hxx|h\+\+|ipp|inl)$/], ['objective-c', /\.(m|mm)$/],
['go', /\.go$/], ['rust', /\.rs$/], ['zig', /\.zig$/], ['swift', /\.swift$/], ['dart', /\.dart$/],
['python', /\.(py|pyi|pyx)$/], ['ruby', /\.(rb|rake)$/], ['php', /\.php$/], ['perl', /\.(pl|pm)$/], ['lua', /\.lua$/],
['elixir/erlang', /\.(ex|exs|erl|hrl)$/], ['haskell', /\.(hs|lhs)$/], ['ocaml', /\.(ml|mli)$/],
];
const DAY = 86_400_000;
// Dated snapshot of the monorepo.tools/compare matrix. Ratings are computed from it alone.
export const MONOREPO_TOOLS = JSON.parse(fs.readFileSync(new URL('./monorepo-tools.json', import.meta.url), 'utf8'));
// Every tool on monorepo.tools, rated 0–10 by the share of compared features the page marks "natively supported".
// Partial marks ("implement your own", "community provided") are counted, not scored. A tool the page marks
// "not supported" for polyglot is not a fit when the repos contain more than JS/TS. Nothing else is inferred.
export function toolOptions(langNames, buildTools, data = MONOREPO_TOOLS) {
const polyglotIdx = data.features.findIndex((f) => f.key === 'polyglot');
const otherLangs = langNames.filter((l) => l !== 'js/ts');
const count = (marks) => Object.fromEntries(Object.keys(data.source.legend).map((k) => [k, marks.filter((m) => m === k).length]));
return data.tools.map((t) => {
const counts = count(t.marks);
const categories = data.categories.map((c) => {
const marks = t.marks.filter((_, i) => data.features[i].category === c);
return { category: c, native: marks.filter((m) => m === 'native').length, total: marks.length };
});
const fit = !(otherLangs.length && t.marks[polyglotIdx] === 'none');
return {
key: t.key, name: t.name, by: t.by, description: t.description, repo: t.repo,
rating: Math.round((counts.native / t.marks.length) * 100) / 10,
counts, total: t.marks.length, categories,
gaps: data.features.filter((_, i) => t.marks[i] === 'none').map((f) => f.label),
fit, fitReason: fit ? null : `monorepo.tools marks polyglot support "data.source.legend.none"; the repos also contain otherLangs.join(', ')`,
alreadyUsed: buildTools.has(t.detect),
independent: t.independent ?? null,
};
}).sort((x, y) => (y.fit - x.fit) || (y.rating - x.rating) || x.name.localeCompare(y.name));
}
// The polyrepo costs monorepo.tools lists, kept only where this report measured evidence for them.
export function whyMigrate(ev, data = MONOREPO_TOOLS) {
const evidence = {
'code-sharing': [[ev.bumps, 'internal dependency bumps'], [ev.releases, 'internal releases consumed by sibling repos']],
duplication: [[ev.duplicatedFixes, 'duplicated-fix bugs']],
'cross-repo-changes': [[ev.coordinated, 'coordinated cross-repo changes'], [ev.crossRepoFixes, 'cross-repo-fix bugs']],
conventions: [[ev.repeatedTooling, 'repeated tooling/dependency changes'], [ev.skew, 'internal packages with version skew today']],
};
return data.reasons.map((r) => ({ ...r, evidence: evidence[r.key].filter(([n]) => n > 0).map(([n, what]) => `what: n`) }))
.filter((r) => r.evidence.length);
}
const git = (repo, args) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
// For lookups that may legitimately miss (a file at a revision, a repo probe). History collection uses
// collect(), which records failures as data problems instead of returning empty history.
const tryGit = (repo, args) => { try { return git(repo, args); } catch { return ''; } };
function collect(repo, args, problems, label) {
try { return git(repo, args); } catch (err) {
problems.push(`label: git args[0] failed (String(err.stderr || err.message).trim().split('\n')[0]); this repo's results are incomplete`);
return '';
}
}
const tryJson = (s) => { try { return JSON.parse(s); } catch { return null; } };
const round = (n, d = 1) => Math.round(n * 10 ** d) / 10 ** d;
const days = (a, b) => (Date.parse(b) - Date.parse(a)) / DAY;
export function minVersion(range) {
if (typeof range !== 'string') return null;
const m = range.replace(/^workspace:/, '').match(/(\d+)\.(\d+|x|\*)(?:\.(\d+|x|\*))?/);
if (!m) return null;
const n = (v) => (v === undefined || v === 'x' || v === '*' ? 0 : Number(v));
return [Number(m[1]), n(m[2]), n(m[3])];
}
export function cmpVersion(a, b) {
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] - b[i];
return 0;
}
const vstr = (v) => (v ? v.join('.') : '?');
export function normalizeSubject(s) {
return s.replace(TICKET, ' ').toLowerCase()
.replace(/^\s*revert\s+"?/, '')
.replace(/^[a-z]+(\([^)]*\))?!?:\s*/, '')
.replace(/\(?#\d+\)?/g, ' ').replace(/\b[0-9a-f]{7,40}\b/g, ' ')
.replace(/[^a-z0-9@/.\s-]+/g, ' ').replace(/\s+/g, ' ').trim();
}
export function similarity(a, b) {
const ta = new Set(a.split(' ').filter(Boolean));
const tb = new Set(b.split(' ').filter(Boolean));
if (ta.size < 3 || tb.size < 3) return 0;
let inter = 0;
for (const t of ta) if (tb.has(t)) inter++;
return inter / (ta.size + tb.size - inter);
}
export function ticketsOf(text) {
const out = new Set();
for (const m of text.matchAll(TICKET)) if (!TICKET_STOP.has(m[1])) out.add(`m[1]-m[2]`);
for (const m of text.matchAll(GH_REF)) out.add(`m[1].toLowerCase()#m[2]`);
return [...out];
}
export const isBot = (c) => BOT.test(c.authorName) || BOT.test(c.authorEmail);
export const isFixSubject = (subject) => {
if (DEPS_CHORE.test(subject)) return false;
const pre = subject.match(FIX_PREFIX);
if (pre) return !/^(deps|deps-dev|dependencies|release)$/i.test(pre[3] ?? '');
// Another conventional type (docs:, chore:, test:, build:…) wins over the word "fix" in its description.
if (/^[a-z]+(\([^)]*\))?!?:/i.test(subject)) return false;
return FIX_WORD.test(subject) && !/\btypos?\b/i.test(subject);
};
// ---------- per-repo collection ----------
function inventory(repo) {
const files = tryGit(repo, ['ls-tree', '-r', '--name-only', 'HEAD']).split('\n').filter(Boolean);
const pkgFiles = files.filter((f) => /(^|\/)package\.json$/.test(f) && !/(^|\/)node_modules\//.test(f));
const packages = [];
for (const file of pkgFiles) {
const pkg = tryJson(tryGit(repo, ['show', `HEAD:file`]));
if (!pkg || typeof pkg !== 'object') continue;
const deps = { ...pkg.peerDependencies, ...pkg.optionalDependencies, ...pkg.devDependencies, ...pkg.dependencies };
packages.push({ file, name: pkg.name ?? null, version: pkg.version ?? null, private: pkg.private === true, deps });
}
const languages = {};
for (const f of files) {
if (/(^|\/)(node_modules|vendor|dist|build)\//.test(f)) continue;
const lang = LANG.find(([, re]) => re.test(f));
if (lang) languages[lang[0]] = (languages[lang[0]] ?? 0) + 1;
}
const has = (f) => files.includes(f);
const packageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : has('package-lock.json') ? 'npm' : null;
const buildTools = [
has('nx.json') && 'nx', has('turbo.json') && 'turbo', has('lerna.json') && 'lerna',
(has('MODULE.bazel') || has('WORKSPACE') || has('WORKSPACE.bazel')) && 'bazel',
(has('build.gradle') || has('build.gradle.kts') || has('settings.gradle') || has('settings.gradle.kts')) && 'gradle', has('pom.xml') && 'maven',
has('go.mod') && 'go', has('Cargo.toml') && 'cargo',
files.some((f) => /^lage\.config\.[cm]?js$/.test(f)) && 'lage', files.some((f) => /^\.moon\/workspace\.ya?ml$/.test(f)) && 'moon',
has('pants.toml') && 'pants', has('rush.json') && 'rush',
].filter(Boolean);
const ci = files.filter((f) => /^\.github\/workflows\/.+\.ya?ml$|^\.gitlab-ci\.yml$|^\.circleci\/config\.yml$|^Jenkinsfile$|^azure-pipelines\.yml$/.test(f));
const nodeVersion = has('.nvmrc') ? tryGit(repo, ['show', 'HEAD:.nvmrc']).trim() : null;
return { files: files.length, packages, languages, packageManager, buildTools, ci, nodeVersion };
}
function commits(repo, since, until, problems, label) {
const out = collect(repo, ['log', `--since=since`, `--until=until`, '--no-merges', '--format=%x1e%H%x1f%aI%x1f%an%x1f%ae%x1f%s%x1f%b%x1f', '--name-only'], problems, label);
const list = [];
for (const rec of out.split('\x1e')) {
if (!rec.trim()) continue;
const [sha, date, authorName, authorEmail, subject, body, rest = ''] = rec.split('\x1f');
list.push({ sha, date, authorName, authorEmail, subject, body: body.trim(), files: rest.split('\n').map((s) => s.trim()).filter(Boolean) });
}
return list;
}
// Parse package.json diffs (zero context) into per-commit dependency and version changes.
function manifestChanges(repo, since, until, problems, label) {
const out = collect(repo, ['log', `--since=since`, `--until=until`, '--no-merges', '--format=%x1e%H', '-p', '-U0', '--no-color', '--no-ext-diff', '--', ':(glob)**/package.json'], problems, label);
const bySha = new Map();
for (const rec of out.split('\x1e')) {
if (!rec.trim()) continue;
const lines = rec.split('\n');
const sha = lines[0].trim();
const files = new Map();
let file = null;
for (const line of lines.slice(1)) {
let m;
if ((m = line.match(/^\+\+\+ b\/(.+)$/))) { file = m[1]; continue; }
if ((m = line.match(/^--- a\/(.+)$/))) { file = m[1]; continue; }
if (line.startsWith('+++') || line.startsWith('---') || !file) continue;
if (!(m = line.match(/^([-+])\s*"([^"]+)"\s*:\s*"([^"]*)"/))) continue;
if (!files.has(file)) files.set(file, { removed: new Map(), added: new Map() });
files.get(file)[m[1] === '-' ? 'removed' : 'added'].set(m[2], m[3]);
}
bySha.set(sha, files);
}
return bySha;
}
function tags(repo, problems, label) {
return collect(repo, ['for-each-ref', 'refs/tags', '--format=%(refname:short)%09%(creatordate:iso-strict)'], problems, label)
.split('\n').filter(Boolean).map((l) => { const [name, date] = l.split('\t'); return { name, date }; });
}
// ---------- analysis ----------
export function analyze(config) {
const a = { ...DEFAULT_ASSUMPTIONS, ...config.assumptions };
const rates = { developerHourly: 100, ciPerMinute: 0.008, currency: 'USD', ...config.rates };
const now = config.now ?? new Date().toISOString();
const since = config.since ?? new Date(Date.parse(now) - 365 * DAY).toISOString().slice(0, 10);
const windowDays = Math.max(1, days(new Date(since).toISOString(), now));
const exclude = new Set(config.overrides?.excludeCommits ?? []);
const scopes = config.internalScopes ?? [];
const problems = [];
const repos = config.repos.map((r) => {
const p = typeof r === 'string' ? { path: r } : r;
const abs = path.resolve(config.baseDir ?? '.', p.path);
const name = p.name ?? path.basename(abs).replace(/\.git$/, '');
if (!tryGit(abs, ['rev-parse', '--git-dir'])) { problems.push(`name: not a git repository (abs)`); return null; }
if (tryGit(abs, ['rev-parse', '--is-shallow-repository']).trim() === 'true') problems.push(`name: shallow clone; history before the shallow boundary is missing`);
if (!tryGit(abs, ['rev-parse', '--verify', '--quiet', 'HEAD'])) { problems.push(`name: HEAD has no commits (abs)`); return null; }
// HEAD inventory is intentionally current state; history is bounded to [since, now].
const inv = inventory(abs);
const list = commits(abs, since, now, problems, name).filter((c) => !exclude.has(c.sha));
for (const c of list) c.repo = name;
return { name, path: abs, github: p.github ?? null, inv, commits: list, manifests: manifestChanges(abs, since, now, problems, name), tags: tags(abs, problems, name) };
}).filter(Boolean);
// Internal packages: published by an analysed repo, or matching a configured scope.
const producerOf = new Map();
for (const r of repos) for (const p of r.inv.packages) if (p.name) producerOf.set(p.name, r.name);
const isInternal = (name) => producerOf.has(name) || scopes.some((s) => name.startsWith(s));
// Releases of internal packages: version-field changes + tags.
const releases = new Map(); // pkg -> [{version:[..], date, repo, sha}]
const addRelease = (pkg, version, date, repo, sha) => {
const v = minVersion(version);
if (!v || !isInternal(pkg)) return;
if (!releases.has(pkg)) releases.set(pkg, []);
const list = releases.get(pkg);
const prev = list.find((x) => cmpVersion(x.version, v) === 0);
if (prev) { if (date < prev.date) Object.assign(prev, { date, sha, repo }); } else list.push({ version: v, date, repo, sha });
};
const commitBySha = new Map();
for (const r of repos) for (const c of r.commits) commitBySha.set(`r.name:c.sha`, c);
// Per-commit internal bumps.
const bumps = [];
const releaseCommits = [];
for (const r of repos) {
const fileToName = new Map(r.inv.packages.map((p) => [p.file, p.name]));
for (const [sha, files] of r.manifests) {
const c = commitBySha.get(`r.name:sha`);
if (!c) continue;
for (const [file, { removed, added }] of files) {
if (removed.has('version') && added.has('version')) {
let name = fileToName.get(file) ?? added.get('name');
if (!name) name = tryJson(tryGit(r.path, ['show', `sha:file`]))?.name;
if (name && isInternal(name)) {
addRelease(name, added.get('version'), c.date, r.name, sha);
releaseCommits.push({ repo: r.name, sha, date: c.date, pkg: name, version: added.get('version') });
}
}
for (const [dep, to] of added) {
// Skip self-references (a playground or docs package depending on its own repo's package).
if (dep === 'version' || dep === 'name' || !isInternal(dep) || !removed.has(dep) || producerOf.get(dep) === r.name) continue;
const from = removed.get(dep);
const vf = minVersion(from), vt = minVersion(to);
if (!vf || !vt || from === to) continue;
const direction = cmpVersion(vt, vf) > 0 ? 'up' : cmpVersion(vt, vf) < 0 ? 'down' : 'range';
if (direction === 'range') continue;
bumps.push({ repo: r.name, sha, date: c.date, file, pkg: dep, from, to, direction, bot: isBot(c), subject: c.subject });
}
}
}
for (const t of r.tags) {
const m = t.name.match(/^(?:(.+)@)?v?(\d+\.\d+\.\d+)$/);
if (!m) continue;
const publics = r.inv.packages.filter((p) => p.name && !p.private);
const pkg = m[1] ?? (publics.length === 1 ? publics[0].name : null);
if (pkg && t.date >= since && t.date <= now) addRelease(pkg, m[2], t.date, r.name, null);
}
}
// Collapse bumps: one per (repo, sha, pkg) — a commit touching several manifests counts once.
const bumpKey = new Map();
for (const b of bumps) { const k = `b.repo:b.sha:b.pkg`; if (!bumpKey.has(k)) bumpKey.set(k, b); }
const uniqueBumps = [...bumpKey.values()].sort((x, y) => x.date.localeCompare(y.date));
const bumpCommitKeys = new Set(uniqueBumps.map((b) => `b.repo:b.sha`));
const releaseDate = (pkg, v) => releases.get(pkg)?.find((x) => cmpVersion(x.version, v) === 0)?.date ?? null;
for (const b of uniqueBumps) {
const rd = b.direction === 'up' ? releaseDate(b.pkg, minVersion(b.to)) : null;
b.lagDays = rd && b.date >= rd ? round(days(rd, b.date)) : null;
}
// Consumers: which analysed repos depend (at HEAD) on which internal packages.
const consumers = [];
for (const r of repos) {
const seen = new Set();
for (const p of r.inv.packages) for (const [dep, range] of Object.entries(p.deps)) {
if (!isInternal(dep) || producerOf.get(dep) === r.name || seen.has(dep)) continue;
seen.add(dep);
consumers.push({ repo: r.name, pkg: dep, range, producer: producerOf.get(dep) ?? null, file: p.file });
}
}
const consumedPkgs = new Set(consumers.map((c) => c.pkg));
// Packages also consumed outside the analysed repos keep their releases in a monorepo, so those are not costed.
const isPublic = (pkg) => config.publicPackages === true || (Array.isArray(config.publicPackages) && config.publicPackages.includes(pkg));
const consumedReleases = releaseCommits.filter((x) => consumedPkgs.has(x.pkg) && !isPublic(x.pkg));
// Dedupe release commits per (repo, sha).
const relSeen = new Set();
const releaseEvents = consumedReleases.filter((x) => { const k = `x.repo:x.sha:x.pkg`; if (relSeen.has(k)) return false; relSeen.add(k); return true; });
// Drift at HEAD.
const latestVersion = (pkg) => {
const fromReleases = releases.get(pkg)?.map((x) => x.version) ?? [];
const head = repos.flatMap((r) => r.inv.packages).filter((p) => p.name === pkg).map((p) => minVersion(p.version)).filter(Boolean);
return [...fromReleases, ...head].sort(cmpVersion).at(-1) ?? null;
};
const drift = consumers.map((c) => {
const cur = minVersion(c.range), latest = latestVersion(c.pkg);
if (!cur || !latest || /^workspace:|^(file|link|portal):/.test(c.range)) return null;
return { ...c, current: vstr(cur), latest: vstr(latest), majorsBehind: latest[0] - cur[0], behind: cmpVersion(latest, cur) > 0 };
}).filter(Boolean);
const skew = [];
for (const pkg of consumedPkgs) {
const majors = new Map();
for (const d of drift.filter((x) => x.pkg === pkg)) {
const maj = d.current.split('.')[0];
if (!majors.has(maj)) majors.set(maj, []);
majors.get(maj).push(d.repo);
}
if (majors.size > 1) skew.push({ pkg, majors: Object.fromEntries(majors) });
}
// ---------- bugs and duplicated work ----------
const all = repos.flatMap((r) => r.commits).sort((x, y) => x.date.localeCompare(y.date));
const used = new Set();
const key = (c) => `c.repo:c.sha`;
const ev = (c) => ({ repo: c.repo, sha: c.sha.slice(0, 10), date: c.date.slice(0, 10), subject: c.subject });
const bugs = [];
// 1. dependency-regression (high): downgrade of an internal dependency, or revert of a bump commit.
for (const c of all) {
const downs = uniqueBumps.filter((b) => b.repo === c.repo && b.sha === c.sha && b.direction === 'down');
const rev = c.subject.match(/^Revert "(.+)"$/);
const revertsBump = rev && all.some((o) => o.repo === c.repo && o.subject === rev[1] && bumpCommitKeys.has(key(o)) && o.date <= c.date);
if (!downs.length && !revertsBump) continue;
used.add(key(c));
bugs.push({
category: 'dependency-regression', confidence: 'high', repos: [c.repo],
title: downs.length ? `c.repo rolled back downs.map((d) => `${d.pkg d.from → d.to`).join(', ')}` : `c.repo reverted an internal dependency bump`,
why: 'An internal release broke a consumer after it shipped. In a monorepo the producer change runs the consumer\'s tests before merge.',
commits: [ev(c)],
});
}
// 2. Groups: the same change in several repos (shared ticket, or near-identical subject).
const candidates = all.filter((c) => !used.has(key(c)) && !bumpCommitKeys.has(key(c)) && !RELEASE.test(c.subject));
const parent = new Map(candidates.map((c) => [key(c), key(c)]));
const find = (k) => { while (parent.get(k) !== k) { parent.set(k, parent.get(parent.get(k))); k = parent.get(k); } return k; };
const union = (x, y) => parent.set(find(x), find(y));
const linkedBy = new Map();
const byTicket = new Map();
for (const c of candidates) for (const t of ticketsOf(`c.subject\nc.body`)) {
if (!byTicket.has(t)) byTicket.set(t, []);
byTicket.get(t).push(c);
}
for (const [t, list] of byTicket) {
if (new Set(list.map((c) => c.repo)).size < 2) continue;
for (const c of list.slice(1)) union(key(c), key(list[0]));
for (const c of list) { linkedBy.set(key(c), 'ticket'); c.ticket ??= t; }
}
const norm = new Map(candidates.map((c) => [key(c), normalizeSubject(c.subject)]));
for (let i = 0; i < candidates.length; i++) {
const ci = candidates[i];
const ni = norm.get(key(ci));
if (GENERIC.has(ni)) continue;
for (let j = i + 1; j < candidates.length; j++) {
const cj = candidates[j];
if (days(ci.date, cj.date) > a.groupWindowDays) break;
if (cj.repo === ci.repo) continue;
if (similarity(ni, norm.get(key(cj))) >= a.similarity) {
union(key(ci), key(cj));
if (!linkedBy.has(key(ci))) linkedBy.set(key(ci), 'similar');
if (!linkedBy.has(key(cj))) linkedBy.set(key(cj), 'similar');
}
}
}
const groupsMap = new Map();
for (const c of candidates) {
if (!linkedBy.has(key(c))) continue;
const root = find(key(c));
if (!groupsMap.has(root)) groupsMap.set(root, []);
groupsMap.get(root).push(c);
}
const coordinated = [], duplicatedTooling = [];
for (const list of groupsMap.values()) {
const groupRepos = [...new Set(list.map((c) => c.repo))];
if (groupRepos.length < 2) continue;
// Groups spanning more than the window are usually unrelated commits sharing a long-lived ticket.
if (days(list[0].date, list.at(-1).date) > a.groupWindowDays * 2) continue;
for (const c of list) used.add(key(c));
const via = list.some((c) => linkedBy.get(key(c)) === 'ticket') ? 'ticket' : 'similar';
const ticket = list.find((c) => c.ticket)?.ticket ?? null;
const commitsEv = list.map(ev);
// A group is a bug only when fix commits land in at least two repos; one fix plus related work is coordination.
const fixes = list.filter((c) => isFixSubject(c.subject));
const isFix = new Set(fixes.map((c) => c.repo)).size >= 2;
const configOnly = list.every((c) => (c.files.length && c.files.every((f) => CONFIG_FILE.test(f))) || DEPS_CHORE.test(c.subject));
const title = ticket && !list[0].subject.includes(ticket) ? `ticket: list[0].subject` : list[0].subject;
if (isFix) {
const first = normalizeSubject(fixes[0].subject);
const similarRepos = new Set(fixes.filter((c) => similarity(normalizeSubject(c.subject), first) >= a.similarity).map((c) => c.repo));
const dup = similarRepos.size >= 2;
bugs.push(dup
? { category: 'duplicated-fix', confidence: 'medium', repos: groupRepos, title, why: `The same fix was applied in groupRepos.length repos: duplicated code, or a shared contract that has to be fixed everywhere.`, commits: commitsEv, copies: groupRepos.length }
: { category: 'cross-repo-fix', confidence: 'medium', repos: groupRepos, title, why: `One bug needed coordinated fixes in groupRepos.length repos (linked by ticket ?? 'subject'); the contract between them lives in no single repo.`, commits: commitsEv });
} else if (configOnly) {
duplicatedTooling.push({ repos: groupRepos, title, commits: commitsEv, copies: groupRepos.length, bot: list.every(isBot) });
} else {
coordinated.push({ repos: groupRepos, title, via, ticket, commits: commitsEv });
}
}
// 3. Single-commit fixes linked to an internal bump.
for (const c of all) {
if (used.has(key(c)) || !isFixSubject(c.subject) && !(FIX_WORD.test(c.body) && !DEPS_CHORE.test(c.subject))) continue;
const ownUps = uniqueBumps.filter((b) => b.repo === c.repo && b.sha === c.sha && b.direction === 'up');
if (ownUps.length) {
used.add(key(c));
bugs.push({
category: 'fix-propagation', confidence: 'medium', repos: [c.repo, ...new Set(ownUps.map((b) => producerOf.get(b.pkg)).filter(Boolean))],
title: `c.subject`, why: `The fix reached c.repo only after a release of ownUps.map((b) => b.pkg).join(', ') and a version bump.`,
commits: [ev(c)],
});
continue;
}
if (bumpCommitKeys.has(key(c))) continue;
const prior = uniqueBumps.filter((b) => b.repo === c.repo && b.direction === 'up' && b.date <= c.date && days(b.date, c.date) <= a.bumpFixWindowDays);
if (!prior.length) continue;
const text = `c.subject\nc.body`.toLowerCase();
const mentions = prior.find((b) => text.includes(b.pkg.toLowerCase()) || (b.pkg.split('/').pop().length >= 4 && new RegExp(`\\bb.pkg.split('/').pop().replace(/[.*+?^${()|[\]\\]/g, '\\$&')}\\b`, 'i').test(text)));
const lastMajor = prior.findLast((b) => minVersion(b.to)[0] > minVersion(b.from)[0]);
const confidence = mentions || COMPAT.test(text) ? 'medium' : lastMajor && days(lastMajor.date, c.date) <= 2 ? 'low' : null;
if (!confidence) continue;
used.add(key(c));
const b = mentions ?? (confidence === 'low' ? lastMajor : prior.at(-1));
bugs.push({
category: 'post-bump-fix', confidence, repos: [c.repo, producerOf.get(b.pkg)].filter(Boolean),
title: c.subject, why: `Fix landed round(days(b.date, c.date)) days after c.repo bumped b.pkg b.from → b.toCOMPAT.test(text) ? ' and describes a compatibility break' : ''.`,
commits: [{ ...ev(commitBySha.get(`b.repo:b.sha`)), evidenceOnly: true }, ev(c)],
});
}
// ---------- cost model ----------
const perRepoCi = {};
for (const r of repos) {
const ci = config.ci?.[r.name];
const landed = r.commits.length || 1;
perRepoCi[r.name] = ci && Number.isFinite(ci.totalMinutes) && ci.totalMinutes >= 0
? { minutesPerCommit: ci.totalMinutes / Math.max(ci.commits ?? landed, 1), source: 'measured', runs: ci.runs ?? null, totalMinutes: ci.totalMinutes }
: { minutesPerCommit: a.ciMinutesPerCommit, source: 'assumed' };
}
const ciMin = (repo, n = 1) => n * (perRepoCi[repo]?.minutesPerCommit ?? a.ciMinutesPerCommit);
const conf = { low: ['high'], expected: ['high', 'medium'], high: ['high', 'medium', 'low'] };
// scope: null = every analysed repo (the tax); a Set = only repos that would move (what a migration recovers).
const inScope = (scope, repo) => !scope || scope.has(repo);
const scopeGroup = (scope, g) => {
const commits = g.commits.filter((c) => inScope(scope, c.repo));
const repos = [...new Set(commits.map((c) => c.repo))];
return repos.length >= 2 ? { ...g, commits, repos, copies: repos.length } : null;
};
const lines = (scenario, scope = null) => {
const out = [];
const coordinatedS = coordinated.map((g) => scopeGroup(scope, g)).filter(Boolean);
const toolingS = duplicatedTooling.map((g) => scopeGroup(scope, g)).filter(Boolean);
// A bump that is itself counted as a fix-propagation bug is costed once, as the bug.
const ownBug = new Set(bugs.filter((b) => b.category === 'fix-propagation').flatMap((b) => b.commits.map((c) => `c.repo:c.sha`)));
const costedBumps = uniqueBumps.filter((b) => b.direction === 'up' && !ownBug.has(`b.repo:b.sha.slice(0, 10)`)
&& inScope(scope, b.repo) && (!scope || scope.has(producerOf.get(b.pkg))));
const humanBumps = costedBumps.filter((b) => !b.bot);
const botBumps = costedBumps.filter((b) => b.bot);
const bumpCommitSet = (list) => [...new Set(list.map((b) => `b.repo:b.sha`))].map((k) => k.split(':')[0]);
out.push({ key: 'bumps', label: 'Internal dependency bumps', count: humanBumps.length + botBumps.length,
hours: humanBumps.length * a.bumpHumanHours + botBumps.length * a.bumpBotHours,
ciMinutes: bumpCommitSet(costedBumps).reduce((s, repo) => s + ciMin(repo), 0) });
const rel = releaseEvents.filter((x) => inScope(scope, x.repo));
// One CI run per release commit, even when it versions several packages.
const relCommits = [...new Map(rel.map((x) => [`x.repo:x.sha`, x.repo])).values()];
out.push({ key: 'releases', label: 'Internal releases consumed by sibling repos', count: rel.length,
hours: rel.length * a.releaseHours, ciMinutes: relCommits.reduce((s, repo) => s + ciMin(repo), 0) });
out.push({ key: 'coordination', label: 'Changes coordinated across repos', count: coordinatedS.length,
hours: coordinatedS.reduce((s, g) => s + (g.repos.length - 1) * a.coordinationHoursPerExtraRepo, 0),
ciMinutes: coordinatedS.reduce((s, g) => s + g.commits.filter((c) => c.repo !== g.commits[0].repo).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
out.push({ key: 'duplicatedTooling', label: 'Same tooling/dependency maintenance repeated per repo', count: toolingS.length,
hours: toolingS.reduce((s, g) => s + (g.copies - 1) * (g.bot ? a.bumpBotHours : a.duplicateChangeHoursPerCopy), 0),
ciMinutes: toolingS.reduce((s, g) => s + g.commits.filter((c) => c.repo !== g.commits[0].repo).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
for (const cat of ['dependency-regression', 'post-bump-fix', 'fix-propagation', 'duplicated-fix', 'cross-repo-fix']) {
const list = bugs.filter((b) => b.category === cat && conf[scenario].includes(b.confidence) && (!scope || b.repos.every((x) => scope.has(x))));
out.push({ key: cat, label: `Bugs: cat`, count: list.length,
hours: list.reduce((s, b) => s + a.bugHours + (b.copies ? (b.copies - 1) * a.duplicateChangeHoursPerCopy : 0), 0),
ciMinutes: list.reduce((s, b) => s + b.commits.filter((c) => !c.evidenceOnly).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
}
const yearly = 365 / windowDays;
for (const l of out) {
l.cost = l.hours * rates.developerHourly + l.ciMinutes * rates.ciPerMinute;
l.savingsShare = SAVINGS[l.key];
l.annualCost = l.cost * yearly;
l.annualSavings = l.annualCost * l.savingsShare;
}
const sum = (f) => out.reduce((s, l) => s + l[f], 0);
return {
lines: out.map((l) => ({ ...l, hours: round(l.hours), ciMinutes: Math.round(l.ciMinutes), cost: Math.round(l.cost), annualCost: Math.round(l.annualCost), annualSavings: Math.round(l.annualSavings) })),
totals: { hours: round(sum('hours')), ciMinutes: Math.round(sum('ciMinutes')), cost: Math.round(sum('cost')), annualCost: Math.round(sum('annualCost')), annualSavings: Math.round(sum('annualSavings')),
devCost: Math.round(sum('hours') * rates.developerHourly), ciCost: Math.round(sum('ciMinutes') * rates.ciPerMinute) },
};
};
// ---------- migration facts ----------
const edges = new Map();
const edge = (x, y) => { const k = [x, y].sort().join(' ↔ '); if (!edges.has(k)) edges.set(k, { repos: [x, y].sort(), dependencies: 0, bumps: 0, sharedChanges: 0, sharedTooling: 0, bugs: 0 }); return edges.get(k); };
for (const c of consumers) if (c.producer) edge(c.repo, c.producer).dependencies++;
for (const b of uniqueBumps) { const p = producerOf.get(b.pkg); if (p && p !== b.repo) edge(b.repo, p).bumps++; }
const pairs = (rs) => rs.flatMap((x, i) => rs.slice(i + 1).map((y) => [x, y]));
for (const g of coordinated) for (const [x, y] of pairs(g.repos)) edge(x, y).sharedChanges++;
// Repeated tooling is a cost, but every repo has tooling: it is shown, not used for coupling.
for (const g of duplicatedTooling) for (const [x, y] of pairs(g.repos)) edge(x, y).sharedTooling++;
for (const b of bugs) for (const [x, y] of pairs([...new Set(b.repos)])) edge(x, y).bugs++;
const edgeList = [...edges.values()].filter((e) => e.dependencies + e.bumps + e.sharedChanges + e.bugs > 0).map((e) => ({ ...e, weight: e.dependencies * 2 + e.bumps + e.sharedChanges + e.bugs * 3 })).sort((x, y) => y.weight - x.weight);
// Clusters: tooling-only links do not justify a migration on their own.
const cp = new Map(repos.map((r) => [r.name, r.name]));
const cf = (k) => { while (cp.get(k) !== k) k = cp.get(k); return k; };
for (const e of edgeList) if (e.dependencies || e.bumps || e.bugs || e.sharedChanges >= 2) cp.set(cf(e.repos[0]), cf(e.repos[1]));
const clusterMap = new Map();
for (const r of repos) { const k = cf(r.name); if (!clusterMap.has(k)) clusterMap.set(k, []); clusterMap.get(k).push(r.name); }
const clusters = [...clusterMap.values()].map((members) => ({
repos: members.sort(), weight: edgeList.filter((e) => members.includes(e.repos[0]) && members.includes(e.repos[1])).reduce((s, e) => s + e.weight, 0),
})).sort((x, y) => y.weight - x.weight || y.repos.length - x.repos.length);
const isolated = clusters.filter((c) => c.repos.length === 1).map((c) => c.repos[0]);
const migrateRepos = repos.filter((r) => !isolated.includes(r.name) || repos.length === 1);
const migrateSet = new Set(migrateRepos.map((r) => r.name));
// Cost covers every analysed repo; savings and payback only the repos that would move.
const scenarios = {};
for (const k of ['low', 'expected', 'high']) {
const full = lines(k), scoped = lines(k, migrateSet);
full.lines.forEach((l, i) => { l.annualSavings = scoped.lines[i].annualSavings; });
full.totals.annualSavings = scoped.totals.annualSavings;
scenarios[k] = full;
}
// External dependency conflicts (different majors across the repos that would move) — alignment before one lockfile.
const ext = new Map();
for (const r of migrateRepos) for (const p of r.inv.packages) for (const [dep, range] of Object.entries(p.deps)) {
if (isInternal(dep)) continue;
const v = minVersion(range);
if (!v) continue;
if (!ext.has(dep)) ext.set(dep, new Map());
const m = ext.get(dep);
if (!m.has(v[0])) m.set(v[0], new Set());
m.get(v[0]).add(r.name);
}
const conflicts = [...ext].filter(([, m]) => m.size > 1)
.map(([dep, m]) => ({ dep, majors: Object.fromEntries([...m].map(([k, s]) => [k, [...s].sort()])), repos: new Set([...m.values()].flatMap((s) => [...s])).size }))
.sort((x, y) => y.repos - x.repos || x.dep.localeCompare(y.dep));
const langs = {};
for (const r of repos) for (const [l, n] of Object.entries(r.inv.languages)) langs[l] = (langs[l] ?? 0) + n;
const langNames = Object.keys(langs).sort((x, y) => langs[y] - langs[x]);
const tools = new Set(repos.flatMap((r) => r.inv.buildTools));
const recommendedTool = langNames.length === 0 ? 'unknown'
: langNames.every((l) => l === 'js/ts') ? (tools.has('nx') ? 'Nx (already used) on pnpm workspaces' : tools.has('turbo') ? 'Turborepo (already used) on pnpm workspaces' : 'pnpm workspaces + Nx or Turborepo')
: langNames.every((l) => l === 'jvm') ? 'Gradle composite build, or Bazel for very large graphs'
: tools.has('bazel') ? 'Bazel (already used)' : 'Nx (polyglot plugins) or Bazel';
const options = toolOptions(langNames, tools);
const reasons = whyMigrate({
bumps: uniqueBumps.length, releases: releaseEvents.length, coordinated: coordinated.length, repeatedTooling: duplicatedTooling.length,
skew: skew.length, duplicatedFixes: bugs.filter((b) => b.category === 'duplicated-fix').length,
crossRepoFixes: bugs.filter((b) => b.category === 'cross-repo-fix').length,
});
const migrationDays = migrateRepos.length * a.migrationDaysPerRepo + conflicts.length * a.migrationDaysPerConflict;
const migrationCost = Math.round(migrationDays * 8 * rates.developerHourly);
const payback = (s) => {
const monthly = s.totals.annualSavings / 12 - a.monorepoToolingMonthly;
return monthly > 0 ? round(migrationCost / monthly) : null;
};
return {
version: 1,
generatedAt: now,
window: { since, until: now.slice(0, 10), days: Math.round(windowDays) },
rates, assumptions: a, problems, publicPackages: config.publicPackages ?? [],
repos: repos.map((r) => ({
name: r.name, github: r.github, commits: r.commits.length,
packages: r.inv.packages.filter((p) => p.name).map((p) => ({ name: p.name, version: p.version, private: p.private })),
languages: r.inv.languages, packageManager: r.inv.packageManager, buildTools: r.inv.buildTools, ciFiles: r.inv.ci, nodeVersion: r.inv.nodeVersion, ci: perRepoCi[r.name],
})),
internal: {
packages: [...producerOf].filter(([n]) => consumedPkgs.has(n)).map(([pkg, repo]) => ({ pkg, repo, consumers: consumers.filter((c) => c.pkg === pkg).map((c) => c.repo) })),
bumps: uniqueBumps.map(({ subject, ...b }) => ({ ...b, sha: b.sha.slice(0, 10), date: b.date.slice(0, 10) })),
releases: releaseEvents.map((x) => ({ ...x, sha: x.sha.slice(0, 10), date: x.date.slice(0, 10) })),
medianBumpLagDays: median(uniqueBumps.map((b) => b.lagDays).filter((x) => x !== null)),
drift: drift.filter((d) => d.behind), skew,
},
bugs: bugs.map((b, i) => ({ id: `Bi + 1`, ...b })),
coordinated, duplicatedTooling,
cost: scenarios,
migration: {
recommendedTool, languages: langs,
toolOptions: options, whyMigrate: reasons,
toolSource: { urls: MONOREPO_TOOLS.source.urls, retrieved: MONOREPO_TOOLS.source.retrieved, publisher: MONOREPO_TOOLS.source.publisher, legend: MONOREPO_TOOLS.source.legend, independent: MONOREPO_TOOLS.independent },
clusters, isolated, coupling: edgeList.filter((e) => e.weight > 0), externalConflicts: conflicts,
oneTime: { days: round(migrationDays), cost: migrationCost, repos: migrateRepos.map((r) => r.name) },
paybackMonths: { low: payback(scenarios.low), expected: payback(scenarios.expected), high: payback(scenarios.high) },
},
};
}
export function toolOptionsMarkdown(m) {
const src = m.toolSource;
const cats = m.toolOptions[0].categories.map((c) => c.category);
const out = ['### Tool options', '',
`Every tool compared on [monorepo.tools/compare](src.urls[1]) (snapshot src.retrieved). The rating and every column up to "src.legend.none" come from monorepo.tools, which is published by Nx; the last column is from independent sources and is not scored.`, '',
`| Tool | monorepo.tools rating /10 | cats.join(' | ') | src.legend.implement | src.legend.community | src.legend.none | Fit | Already used | Independent signals (not scored) |`,
`|---|---:|').join('|')|---:|---:|---:|---|---|---|`];
for (const t of m.toolOptions) {
out.push(`| [t.name](t.repo) | t.rating.toFixed(1) | t.categories.map((c) => `${c.native/c.total`).join(' | ')} | t.counts.implement | t.counts.community | t.counts.none | `no: ${t.fitReason`} | '—' | independentSignals(t.independent) ?? '—' |`);
}
out.push('', '**Sources**', '');
for (const x of toolSources(src, m.toolOptions[0].total)) out.push(`- [x.name](x.url) (x.publisher, retrieved x.retrieved; **x.role**). x.metric. Covers: x.covers.`);
return out;
}
function median(xs) {
if (!xs.length) return null;
const s = [...xs].sort((x, y) => x - y);
const m = Math.floor(s.length / 2);
return round(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2);
}
// ---------- rendering ----------
export function renderMarkdown(r) {
const cur = r.rates.currency === 'USD' ? '$' : `r.rates.currency `;
const money = (n) => `curMath.round(n).toLocaleString('en-US')`;
const e = r.cost.expected;
const md = [];
md.push('# Polyrepo Tax Report', '');
md.push(`**Repos:** r.repos.length · **Window:** r.window.since → r.window.until (r.window.days days) · **Rates:** money(r.rates.developerHourly)/dev-hour, curr.rates.ciPerMinute/CI-minute`, '');
md.push(`**Polyrepo tax in this window (expected):** money(e.totals.cost) — e.totals.hours developer hours (money(e.totals.devCost)) + e.totals.ciMinutes.toLocaleString('en-US') CI minutes (money(e.totals.ciCost))`, '');
md.push(`**Annualized:** money(r.cost.low.totals.annualCost) – money(r.cost.high.totals.annualCost) (expected money(e.totals.annualCost)); a monorepo would recover about money(e.totals.annualSavings)/year.`, '');
const pb = r.migration.paybackMonths;
md.push(`**Migration:** ~r.migration.oneTime.days dev-days (money(r.migration.oneTime.cost)) for r.migration.oneTime.repos.length repos → payback `~${pb.expected months`} (range pb.high ?? '—'–pb.low ?? 'never').`, '');
const bugCount = (s) => r.bugs.filter((b) => s.includes(b.confidence)).length;
md.push(`**Polyrepo-attributable bugs:** bugCount(['high']) high-confidence · bugCount(['medium']) medium · bugCount(['low']) low`, '');
if (r.problems.length) md.push('> **Data problems:** ' + r.problems.join('; '), '');
md.push('These are estimates from git history, not invoices. Every count links to commits below; every rate and assumption is listed at the end and can be overridden.', '');
md.push('## Where the time goes (expected scenario)', '');
md.push('| Cost driver | Events | Dev hours | CI minutes | Cost (window) | Annualized | Monorepo removes |', '|---|---:|---:|---:|---:|---:|---:|');
for (const l of e.lines) md.push(`| l.label | l.count | l.hours | l.ciMinutes.toLocaleString('en-US') | money(l.cost) | money(l.annualCost) | Math.round(l.savingsShare * 100)% |`);
md.push(`| **Total** | | **e.totals.hours** | **e.totals.ciMinutes.toLocaleString('en-US')** | **money(e.totals.cost)** | **money(e.totals.annualCost)** | **money(e.totals.annualSavings)/yr** |`, '');
md.push('| Scenario | Counts | Window cost | Annualized | Annual savings | Payback |', '|---|---|---:|---:|---:|---:|');
for (const [k, label] of [['low', 'high-confidence bugs only'], ['expected', 'high + medium'], ['high', 'high + medium + low']]) {
const s = r.cost[k];
md.push(`| k | label | money(s.totals.cost) | money(s.totals.annualCost) | money(s.totals.annualSavings) | `${pb[k] mo`} |`);
}
md.push('');
md.push('## Bugs attributable to repo boundaries', '');
if (!r.bugs.length) md.push('None found in this window.', '');
for (const conf of ['high', 'medium', 'low']) {
const list = r.bugs.filter((b) => b.confidence === conf);
if (!list.length) continue;
md.push(`### conf[0].toUpperCase()conf.slice(1) confidence (list.length)`, '');
for (const b of list) {
md.push(`- **b.id · \`b.category\`** — b.title _([...new Set(b.repos)].join(', '))_`);
md.push(` - b.why`);
for (const c of b.commits) md.push(` - \`c.repo@c.sha\` c.date — c.subject`);
}
md.push('');
}
md.push('## Internal dependency churn', '');
const ib = r.internal;
const ups = ib.bumps.filter((b) => b.direction === 'up');
md.push(`- **ups.length** internal bump commits (ups.filter((b) => b.bot).length by bots, ups.filter((b) => !b.bot).length by people); **ib.bumps.filter((b) => b.direction === 'down').length** downgrade(s).`);
md.push(`- **ib.releases.length** internal releases existed to move code between repos''.`);
md.push(`- Median lag from release to consumer bump: **ib.medianBumpLagDays ?? 'n/a'** days.`);
if (ib.drift.length) md.push(`- **ib.drift.length** consumer(s) behind the latest internal version today; ib.drift.filter((d) => d.majorsBehind > 0).length at least a major version behind.`);
md.push('');
if (ib.packages.length) {
md.push('| Internal package | Producer | Consumers | Bumps | Releases |', '|---|---|---|---:|---:|');
for (const p of ib.packages) md.push(`| \`p.pkg\` | p.repo | p.consumers.join(', ') | ups.filter((b) => b.pkg === p.pkg).length | ib.releases.filter((x) => x.pkg === p.pkg).length |`);
md.push('');
}
if (ib.skew.length) {
md.push('**Version skew today** (the same internal package at different majors):', '');
for (const s of ib.skew) md.push(`- \`s.pkg\`: Object.entries(s.majors).map(([m, rs]) => `v${m in rs.join(', ')`).join(' · ')}`);
md.push('');
}
if (r.coordinated.length || r.duplicatedTooling.length) {
md.push('## Duplicated and coordinated work', '');
for (const g of r.coordinated.slice(0, 15)) md.push(`- **Coordinated change** (g.repos.join(', ')): g.title — g.commits.map((c) => `\`${c.repo@c.sha\``).join(', ')}`);
for (const g of r.duplicatedTooling.slice(0, 15)) md.push(`- **Repeated maintenance** ×g.copies'': g.title — g.commits.map((c) => `\`${c.repo@c.sha\``).join(', ')}`);
const more = Math.max(0, r.coordinated.length - 15) + Math.max(0, r.duplicatedTooling.length - 15);
if (more) md.push(`- …and more more in the JSON report.`);
md.push('');
}
const m = r.migration;
md.push('## Migration plan inputs', '');
md.push(`**Recommended tooling:** m.recommendedTool (languages by file count: Object.entries(m.languages).map(([l, n]) => `${l n`).join(', ') || 'none detected'})`, '');
if (m.whyMigrate?.length) {
md.push('### Why migrate', '', 'The polyrepo costs [monorepo.tools](https://monorepo.tools/) lists, shown only where this report measured them:', '');
for (const w of m.whyMigrate) md.push(`- **w.polyrepo** → w.monorepo. Measured: w.evidence.join(', ').`);
md.push('');
}
if (m.toolOptions?.length) md.push(...toolOptionsMarkdown(m), '');
md.push('**Clusters** (repos that change together; migrate the heaviest first):', '');
m.clusters.filter((c) => c.repos.length > 1).forEach((c, i) => md.push(`i + 1. c.repos.join(', ') — coupling weight c.weight`));
if (m.isolated.length) md.push('', `**No measured coupling — keep separate unless there is another reason:** m.isolated.join(', ')`);
md.push('');
if (m.coupling.length) {
md.push('| Repo pair | Internal deps | Bumps | Coordinated changes | Bugs | Weight | Repeated tooling (not weighted) |', '|---|---:|---:|---:|---:|---:|---:|');
for (const c of m.coupling.slice(0, 20)) md.push(`| c.repos.join(' ↔ ') | c.dependencies | c.bumps | c.sharedChanges | c.bugs | c.weight | c.sharedTooling |`);
md.push('');
}
if (m.externalConflicts.length) {
md.push(`**External dependencies to align before sharing one lockfile** (m.externalConflicts.length):`, '');
for (const c of m.externalConflicts.slice(0, 15)) md.push(`- \`c.dep\`: Object.entries(c.majors).map(([v, rs]) => `v${v (rs.join(', '))`).join(' · ')}`);
if (m.externalConflicts.length > 15) md.push(`- …and m.externalConflicts.length - 15 more in the JSON report.`);
md.push('');
}
md.push('## Assumptions', '');
md.push('| Assumption | Value |', '|---|---|');
for (const [k, v] of Object.entries(r.assumptions)) md.push(`| \`k\` | v |`);
md.push(`| \`developerHourly\` | money(r.rates.developerHourly) |`, `| \`ciPerMinute\` | curr.rates.ciPerMinute |`, '');
md.push('| Repo | Commits | CI minutes/commit | CI source |', '|---|---:|---:|---|');
for (const repo of r.repos) md.push(`| repo.name | repo.commits | round(repo.ci.minutesPerCommit) | repo.ci.source |`);
md.push('');
return md.join('\n');
}
// ---------- CLI ----------
function parseArgs(argv) {
const opts = { repos: [], internalScopes: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
const next = () => argv[++i];
if (a === '--config') opts.config = next();
else if (a === '--out') opts.out = next();
else if (a === '--since') opts.since = next();
else if (a === '--scope') opts.internalScopes.push(next());
else if (a === '--rate') opts.rate = Number(next());
else if (a === '--ci-rate') opts.ciRate = Number(next());
else if (a === '--ci') opts.ci = next();
else if (a === '--overrides') opts.overrides = next();
else if (a === '--now') opts.now = next();
else if (a === '--public') (opts.publicPackages ??= []).push(next());
else if (a.startsWith('--')) throw new Error(`unknown option a`);
else opts.repos.push(a);
}
return opts;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
const opts = parseArgs(process.argv.slice(2));
let config = { repos: [], internalScopes: [] };
if (opts.config) {
config = JSON.parse(fs.readFileSync(opts.config, 'utf8'));
config.baseDir = path.dirname(path.resolve(opts.config));
}
if (opts.repos.length) config.repos = [...(config.repos ?? []), ...opts.repos];
if (opts.internalScopes.length) config.internalScopes = [...(config.internalScopes ?? []), ...opts.internalScopes];
if (opts.since) config.since = opts.since;
if (opts.now) config.now = opts.now;
if (opts.publicPackages) config.publicPackages = opts.publicPackages.includes('*') ? true : [...(Array.isArray(config.publicPackages) ? config.publicPackages : []), ...opts.publicPackages];
config.rates = { ...config.rates };
if (opts.rate) config.rates.developerHourly = opts.rate;
if (opts.ciRate) config.rates.ciPerMinute = opts.ciRate;
const ciPath = opts.ci ?? (typeof config.ci === 'string' ? path.resolve(config.baseDir ?? '.', config.ci) : null);
if (ciPath) config.ci = JSON.parse(fs.readFileSync(ciPath, 'utf8'));
const ovPath = opts.overrides ?? (typeof config.overrides === 'string' ? path.resolve(config.baseDir ?? '.', config.overrides) : null);
if (ovPath) config.overrides = JSON.parse(fs.readFileSync(ovPath, 'utf8'));
if (!config.repos?.length) throw new Error('no repositories given (pass paths or --config)');
const report = analyze(config);
const out = path.resolve(opts.out ?? path.join(os.tmpdir(), 'polyrepo-tax-reports'));
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.json'), JSON.stringify(report, null, 2));
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.md'), renderMarkdown(report));
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.html'), renderHtml(report));
const e = report.cost.expected.totals;
console.log(`wrote path.join(out, 'polyrepo-tax-report').{md,json,html}`);
console.log(`expected: e.hours dev hours + e.ciMinutes CI minutes = report.rates.currency e.cost in report.window.days days; report.bugs.length candidate bugs`);
for (const p of report.problems) console.error(`WARN: p`);
} catch (err) {
console.error(`polyrepo-tax: err.message`);
process.exit(2);
}
}
FILE:scripts/fetch-ci.mjs
#!/usr/bin/env node
// Collects GitHub Actions minutes per repository for polyrepo-tax. Read-only: only `gh api` GET requests.
// Usage: node fetch-ci.mjs --config polyrepo-tax.config.json [--since 2025-11-25] [--sample 30] [--out ci.json]
// node fetch-ci.mjs --repo name=owner/repo [--repo ...] --since 2025-11-25 --out ci.json
// Total = wall-clock minutes of every completed run in the window. Runs fan out into parallel jobs that are
// billed separately, so job minutes are sampled for up to --sample runs per repo and the total is scaled
// by the sampled job/wall ratio.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const gh = (args) => execFileSync('gh', ['api', '-X', 'GET', ...args], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
const minutes = (a, b) => Math.max(0, (Date.parse(b) - Date.parse(a)) / 60000);
const LIMIT = 1000;
const DAY = 86_400_000;
const isoDay = (d) => d.toISOString().slice(0, 10);
// The runs API returns at most 1000 results per filtered query, so start with one month at a time.
export function monthRanges(since, until) {
const out = [];
let start = new Date(`sinceT00:00:00Z`);
const end = new Date(`untilT00:00:00Z`);
while (start < end) {
const next = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1));
const stop = next < end ? next : end;
out.push(`start.toISOString().slice(0, 10)..new Date(stop - 86_400_000).toISOString().slice(0, 10)`);
start = stop;
}
return out;
}
// Splits a range (YYYY-MM-DD..YYYY-MM-DD, inclusive) until each piece is under the API's result cap.
// Throws when a single day still reaches the cap, so a partial total is never reported as measured.
export function completeRanges(range, count) {
const total = count(range);
if (total < LIMIT) return total ? [range] : [];
const [from, to] = range.split('..').map((d) => new Date(`dT00:00:00Z`));
const spanDays = Math.round((to - from) / DAY);
if (spanDays < 1) throw new Error(`more than LIMIT - 1 runs on isoDay(from); cannot list them completely`);
const mid = new Date(from.getTime() + Math.floor(spanDays / 2) * DAY);
return [...completeRanges(`isoDay(from)..isoDay(mid)`, count), ...completeRanges(`isoDay(new Date(mid.getTime() + DAY))..isoDay(to)`, count)];
}
export function fetchRepo(slug, since, until, sample, api = gh) {
const runs = [];
const base = [`repos/slug/actions/runs`, '-f', 'status=completed'];
const count = (range) => Number(api([...base, '-f', `created=range`, '-f', 'per_page=1', '--jq', '.total_count']).trim());
for (const range of monthRanges(since, until).flatMap((r) => completeRanges(r, count))) {
const out = api([...base, '-f', `created=range`, '-f', 'per_page=100', '--paginate',
'--jq', '.workflow_runs[] | [.id, .run_started_at, .updated_at, .event, .name] | @tsv']);
for (const line of out.split('\n').filter(Boolean)) {
const [id, started, updated, event, name] = line.split('\t');
runs.push({ id, wall: minutes(started, updated), event, name });
}
}
const wall = runs.reduce((s, r) => s + r.wall, 0);
let ratio = 1, sampled = 0;
if (sample > 0 && runs.length) {
const step = Math.max(1, Math.floor(runs.length / sample));
let w = 0, j = 0;
for (let i = 0; i < runs.length && sampled < sample; i += step) {
try {
const jobs = api([`repos/slug/actions/runs/runs[i].id/jobs`, '-f', 'per_page=100', '--paginate', '--jq', '.jobs[] | [.started_at, .completed_at] | @tsv']);
const jm = jobs.split('\n').filter(Boolean).reduce((s, l) => { const [a, b] = l.split('\t'); return b && b !== 'null' ? s + Math.max(1, Math.ceil(minutes(a, b))) : s; }, 0);
if (runs[i].wall > 0) { w += runs[i].wall; j += jm; sampled++; }
} catch { /* skip runs whose jobs were deleted */ }
}
// Keep the measured ratio either way: below 1 when queue time inflates wall clock, above 1 for parallel jobs.
if (w > 0) ratio = j / w;
}
const byWorkflow = {};
for (const r of runs) byWorkflow[r.name] = Math.round((byWorkflow[r.name] ?? 0) + r.wall * ratio);
return { runs: runs.length, wallMinutes: Math.round(wall), jobWallRatio: Math.round(ratio * 100) / 100, sampledRuns: sampled, totalMinutes: Math.round(wall * ratio), byWorkflow, since, until };
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const argv = process.argv.slice(2);
const opt = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
const repos = [];
const config = opt('--config') ? JSON.parse(fs.readFileSync(opt('--config'), 'utf8')) : {};
for (const r of config.repos ?? []) {
if (typeof r === 'object' && r.github) repos.push({ name: r.name ?? path.basename(r.path).replace(/\.git$/, ''), slug: r.github });
}
argv.forEach((a, i) => { if (a === '--repo') { const [name, slug] = argv[i + 1].split('='); repos.push({ name, slug: slug ?? name }); } });
const until = opt('--until') ?? new Date().toISOString().slice(0, 10);
const since = opt('--since') ?? config.since ?? new Date(Date.now() - 365 * 86_400_000).toISOString().slice(0, 10);
const sample = Number(opt('--sample') ?? 30);
if (!repos.length) { console.error('fetch-ci: no repos with a "github" slug (use --config or --repo name=owner/repo)'); process.exit(2); }
const result = {};
for (const r of repos) {
try {
result[r.name] = fetchRepo(r.slug, since, until, sample);
console.error(`r.name: result[r.name].runs runs, result[r.name].totalMinutes minutes (job/wall ×result[r.name].jobWallRatio)`);
} catch (err) {
console.error(`WARN r.name: String(err.stderr || err.message).trim().split('\n')[0] — CI cost for this repo will be assumed`);
}
}
const out = opt('--out') ?? 'ci.json';
fs.writeFileSync(out, JSON.stringify(result, null, 2));
console.error(`wrote out`);
}
FILE:scripts/monorepo-tools.json
{
"source": {
"name": "monorepo.tools",
"urls": [
"https://monorepo.tools/",
"https://monorepo.tools/compare"
],
"retrieved": "2026-11-26",
"publisher": "Made by Nx; content \"© 2026 Nx and Contributors\". The page says it tries to represent each tool objectively and welcomes pull requests for corrections.",
"legend": {
"native": "natively supported",
"implement": "implement your own",
"community": "community provided",
"none": "not supported"
}
},
"reasons": [
{
"key": "code-sharing",
"polyrepo": "Cumbersome code sharing",
"monorepo": "Share code without the overhead of publishing versioned packages"
},
{
"key": "duplication",
"polyrepo": "Significant code duplication",
"monorepo": "A single source of truth: fix once and every consumer gets the fix"
},
{
"key": "cross-repo-changes",
"polyrepo": "Costly cross-repo changes",
"monorepo": "Atomic commits: a breaking change and its consumer fixes land in one PR"
},
{
"key": "conventions",
"polyrepo": "Hard to enforce conventions (drift is the default)",
"monorepo": "Conventions live in one place and are enforceable at scale"
}
],
"categories": [
"Fast",
"Understandable",
"Manageable",
"AI Support"
],
"features": [
{
"key": "local-caching",
"label": "Local computation caching",
"category": "Fast"
},
{
"key": "local-orchestration",
"label": "Local task orchestration",
"category": "Fast"
},
{
"key": "distributed-caching",
"label": "Distributed computation caching",
"category": "Fast"
},
{
"key": "distributed-execution",
"label": "Distributed task execution",
"category": "Fast"
},
{
"key": "remote-execution",
"label": "Transparent remote execution",
"category": "Fast"
},
{
"key": "affected",
"label": "Detecting affected projects/packages",
"category": "Fast"
},
{
"key": "task-splitting",
"label": "Task splitting",
"category": "Fast"
},
{
"key": "deflaking",
"label": "Deflaking",
"category": "Fast"
},
{
"key": "workspace-analysis",
"label": "Workspace analysis",
"category": "Understandable"
},
{
"key": "graph-visualization",
"label": "Project graph visualization",
"category": "Understandable"
},
{
"key": "code-sharing",
"label": "Source code sharing",
"category": "Manageable"
},
{
"key": "polyglot",
"label": "Polyglot support",
"category": "Manageable"
},
{
"key": "code-generation",
"label": "Code generation",
"category": "Manageable"
},
{
"key": "constraints",
"label": "Project constraints and visibility",
"category": "Manageable"
},
{
"key": "hermetic",
"label": "Hermetic builds",
"category": "Manageable"
},
{
"key": "mcp-server",
"label": "MCP Server",
"category": "AI Support"
},
{
"key": "ai-skills",
"label": "AI Skills",
"category": "AI Support"
},
{
"key": "ai-workspace-analysis",
"label": "Workspace Analysis (AI)",
"category": "AI Support"
},
{
"key": "ai-task-execution",
"label": "Task Execution via AI",
"category": "AI Support"
},
{
"key": "agentic-ci",
"label": "Agentic CI",
"category": "AI Support"
}
],
"tools": [
{
"key": "bazel",
"name": "Bazel",
"by": "Google",
"description": "A fast, scalable, multi-language and extensible build system.",
"repo": "https://github.com/bazelbuild/bazel",
"detect": "bazel",
"marks": [
"native",
"native",
"native",
"native",
"native",
"implement",
"implement",
"implement",
"implement",
"native",
"native",
"native",
"implement",
"native",
"native",
"community",
"none",
"community",
"community",
"none"
]
},
{
"key": "gradle",
"name": "Gradle",
"by": "Gradle, Inc",
"description": "A fast, flexible polyglot build system designed for multi-project builds.",
"repo": "https://github.com/gradle/gradle",
"detect": "gradle",
"marks": [
"native",
"native",
"native",
"implement",
"none",
"native",
"native",
"native",
"native",
"implement",
"native",
"native",
"implement",
"implement",
"none",
"native",
"none",
"community",
"community",
"implement"
],
"independent": {
"radar": {
"ring": "Adopt",
"edition": "2013-05",
"url": "https://www.thoughtworks.com/radar/tools/gradle"
}
}
},
{
"key": "lage",
"name": "Lage",
"by": "Microsoft",
"description": "Task runner in JS monorepos",
"repo": "https://github.com/microsoft/lage",
"detect": "lage",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"implement",
"native",
"none",
"implement",
"implement",
"none",
"none",
"none",
"none",
"none",
"none"
]
},
{
"key": "lerna",
"name": "Lerna",
"by": "maintained by the Nx team",
"description": "A tool for managing JavaScript projects with multiple packages.",
"repo": "https://github.com/lerna/lerna",
"detect": "lerna",
"marks": [
"native",
"native",
"native",
"native",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"none",
"implement",
"implement",
"none",
"none",
"none",
"none",
"none",
"native"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.59,
"2022": 0.47,
"2023": 0.36,
"2024": 0.33
},
"usage": 0.21
},
"stateOfJs2025": {
"regularUse": 794
}
}
},
{
"key": "moon",
"name": "moon",
"by": "moonrepo",
"description": "A task runner and monorepo management tool for the web ecosystem.",
"repo": "https://github.com/moonrepo/moon",
"detect": "moon",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"none",
"native",
"community",
"native",
"native",
"none"
],
"independent": {
"stateOfJs2025": {
"regularUse": 23,
"writeIn": true
}
}
},
{
"key": "nx",
"name": "Nx",
"by": "Nx",
"description": "Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.",
"repo": "https://github.com/nrwl/nx",
"detect": "nx",
"marks": [
"native",
"native",
"native",
"native",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.84,
"2022": 0.81,
"2023": 0.75,
"2024": 0.65
},
"usage": 0.23
},
"stateOfJs2025": {
"regularUse": 1682
},
"radar": {
"ring": "Trial",
"edition": "2021-10",
"url": "https://www.thoughtworks.com/radar/tools/nx"
}
}
},
{
"key": "pants",
"name": "Pants",
"by": "Pants Build",
"description": "A fast, scalable, user-friendly build system for codebases of all sizes.",
"repo": "https://github.com/pantsbuild/pants",
"detect": "pants",
"marks": [
"native",
"native",
"native",
"native",
"native",
"native",
"implement",
"implement",
"native",
"implement",
"native",
"native",
"native",
"implement",
"native",
"community",
"none",
"none",
"none",
"none"
]
},
{
"key": "rush",
"name": "Rush",
"by": "Microsoft",
"description": "Geared for large monorepos with lots of teams and projects. Part of the Rush Stack family of projects.",
"repo": "https://github.com/microsoft/rushstack",
"detect": "rush",
"marks": [
"native",
"native",
"native",
"implement",
"none",
"native",
"none",
"none",
"native",
"implement",
"native",
"none",
"implement",
"native",
"none",
"native",
"none",
"native",
"native",
"none"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.59,
"2022": 0.54,
"2023": 0.48,
"2024": 0.42
},
"usage": 0.01
},
"stateOfJs2025": {
"regularUse": 74
}
}
},
{
"key": "turborepo",
"name": "Turborepo",
"by": "Vercel",
"description": "The high-performance build system for JavaScript & TypeScript codebases.",
"repo": "https://github.com/vercel/turborepo",
"detect": "turbo",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"native",
"native",
"none",
"implement",
"implement",
"none",
"community",
"native",
"none",
"none",
"none"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.87,
"2022": 0.9,
"2023": 0.83,
"2024": 0.77
},
"usage": 0.16
},
"stateOfJs2025": {
"regularUse": 1718
},
"radar": {
"ring": "Trial",
"edition": "2025-04",
"previous": "Assess (2023-04)",
"url": "https://www.thoughtworks.com/radar/tools/turborepo"
}
}
}
],
"independent": {
"note": "Independent of the tool vendors. Shown next to the rating, never scored: they measure developer sentiment, usage or expert opinion, not features, and cover only some tools.",
"sources": [
{
"key": "stateOfJs2024",
"name": "State of JavaScript 2024",
"publisher": "Devographics",
"url": "https://2024.stateofjs.com/en-US/libraries/monorepo_tools/",
"retrieved": "2026-11-26",
"metric": "Satisfaction: proportion of positive sentiment among respondents having used an item and expressed a sentiment",
"covers": "Lerna, Nx, Rush, Turborepo (JS tools only)"
},
{
"key": "stateOfJs2025",
"name": "State of JavaScript 2025",
"publisher": "Devographics",
"url": "https://2025.stateofjs.com/en-US/other-tools/",
"retrieved": "2026-11-26",
"metric": "Respondents who answered \"Which of these monorepo tools do you regularly use?\" (multiple choice, 10,251 answered). This edition did not ask about satisfaction.",
"covers": "Lerna, Nx, Rush, Turborepo; moon only as a write-in answer"
},
{
"key": "radar",
"name": "Thoughtworks Technology Radar",
"publisher": "Thoughtworks",
"url": "https://www.thoughtworks.com/radar",
"retrieved": "2026-11-26",
"metric": "Ring (Adopt, Trial, Assess, Hold) on the latest edition that featured the tool",
"covers": "Gradle, Nx, Turborepo. None is on the current edition (Vol. 35, November 2026); Thoughtworks says older blips may no longer reflect its view."
}
]
}
}
FILE:scripts/render-html.mjs
#!/usr/bin/env node
// Renders a polyrepo-tax JSON report as one self-contained HTML file (no network requests).
// Usage: node render-html.mjs <polyrepo-tax-report.json> [--plan migration-plan.md] [--out report.html]
// Without --plan, a migration-plan.md next to the JSON is embedded when present.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
function moneyFormatter(currency) {
try {
const full = new Intl.NumberFormat('en-US', { style: 'currency', currency, maximumFractionDigits: 0 });
const compact = new Intl.NumberFormat('en-US', { style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 });
return { full: (n) => full.format(n), compact: (n) => (Math.abs(n) < 10_000 ? full.format(n) : compact.format(n)) };
} catch {
// Not an ISO 4217 code: keep only characters that are safe in HTML text and attributes.
const label = String(currency).replace(/[^A-Za-z0-9 ._-]/g, '').slice(0, 12) || 'USD';
const f = (n) => `label Math.round(n).toLocaleString('en-US')`;
return { full: f, compact: f };
}
}
const num = (n) => Math.round(n).toLocaleString('en-US');
// One line per tool from the independent sources; null when none covers it. Never feeds the rating.
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const month = (ym) => { const [y, m] = ym.split('-'); return `MONTHS[Number(m) - 1] y`; };
export function independentSignals(ind) {
if (!ind) return null;
const parts = [];
const s24 = ind.stateOfJs2024;
if (s24) {
const years = Object.keys(s24.satisfaction).sort();
const pct = (y) => `Math.round(s24.satisfaction[y] * 100)%`;
parts.push(`State of JS 2024 satisfaction pct(years.at(-1))years.length > 1 ? ` (${pct(years[0]) in years[0])` : ''}`);
}
if (ind.stateOfJs2025) parts.push(`State of JS 2025 regular use ind.stateOfJs2025.regularUse.toLocaleString('en-US')''`);
if (ind.radar) parts.push(`Thoughtworks Radar ind.radar.ring (month(ind.radar.edition), archived)`);
return parts.join(' · ');
}
// Every source behind the tool options table, monorepo.tools first: the one that is scored, and who publishes it.
export function toolSources(src, total) {
const list = [{
name: 'monorepo.tools', url: src.urls[1], publisher: 'published by Nx', retrieved: src.retrieved, role: 'scored',
metric: `Feature matrix. monorepo.tools rating = 10 × features marked "src.legend.native" ÷ total; "src.legend.implement" and "src.legend.community" are counted but not scored. The page says it aims to be objective and accepts corrections by pull request`,
covers: 'all tools in the table; the rating and the feature columns come from it',
}];
for (const x of src.independent?.sources ?? []) list.push({ ...x, role: 'independent, not scored' });
return list.map((x) => ({ ...x, metric: x.metric.replace(/\.$/, ''), covers: x.covers.replace(/\.$/, '') }));
}
// Minimal, escaped Markdown for the agent-written migration plan: headings, lists, code, tables, emphasis, links.
export function markdownToHtml(md) {
const inline = (s) => esc(s)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" rel="noopener">$1</a>');
const out = [];
const lines = md.replace(/\r\n/g, '\n').split('\n');
let list = null;
const closeList = () => { if (list) { out.push(`</list>`); list = null; } };
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^```/.test(line)) {
closeList();
const code = [];
while (++i < lines.length && !/^```/.test(lines[i])) code.push(lines[i]);
out.push(`<pre><code>esc(code.join('\n'))</code></pre>`);
continue;
}
if (/^\|.*\|\s*$/.test(line) && /^\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? '')) {
closeList();
const cells = (l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => inline(c.trim()));
const head = cells(line);
i++;
const rows = [];
while (i + 1 < lines.length && /^\|.*\|\s*$/.test(lines[i + 1])) rows.push(cells(lines[++i]));
out.push(`<div class="table-wrap"><table><thead><tr>head.map((c) => `<th>${c</th>`).join('')}</tr></thead><tbody>rows.map((r) => `<tr>${r.map((c) => `<td>${c</td>`).join('')}</tr>`).join('')}</tbody></table></div>`);
continue;
}
let m;
if ((m = line.match(/^(#{1,4})\s+(.*)$/))) { closeList(); const lvl = Math.min(m[1].length + 2, 5); out.push(`<hlvl>inline(m[2])</hlvl>`); continue; }
if ((m = line.match(/^\s*([-*]|\d+\.)\s+(.*)$/))) {
const type = /\d/.test(m[1]) ? 'ol' : 'ul';
if (list !== type) { closeList(); out.push(`<type>`); list = type; }
out.push(`<li>inline(m[2])</li>`);
continue;
}
if (!line.trim()) { closeList(); continue; }
closeList();
out.push(`<p>inline(line)</p>`);
}
closeList();
return out.join('\n');
}
export function renderHtml(r, { plan } = {}) {
const fmt = moneyFormatter(r.rates.currency ?? 'USD');
const e = r.cost.expected;
const pb = r.migration.paybackMonths;
const bugsBy = (c) => r.bugs.filter((b) => b.confidence === c);
const repoList = r.repos.map((x) => x.name).join(', ');
const ciMeasured = r.repos.filter((x) => x.ci?.source === 'measured').length;
const paybackText = pb.expected === null ? 'Not reached' : pb.expected > 120 ? '10+ years' : `pb.expected months`;
// Payback decides the message; weak coupling only qualifies a short payback, never contradicts it.
const strongCluster = r.migration.clusters.some((c) => c.repos.length > 1 && c.weight >= 5);
const verdict = pb.expected === null || pb.expected > 24
? { cls: 'verdict-no', text: 'The measured tax does not pay back a migration within two years. Fix the top cost drivers in place instead, or migrate only the most coupled cluster.' }
: strongCluster
? { cls: 'verdict-yes', text: `Migrating the coupled repos pays back in about pb.expected months at the expected estimate.` }
: { cls: 'verdict-no', text: `Payback is about pb.expected months, but no cluster has a coupling weight of 5 or more. Treat it as a small, uncertain gain: fixing the top cost drivers in place may be cheaper.` };
// Annualized cost by driver: one series, ranked, zero rows left to the table.
const drivers = e.lines.filter((l) => l.annualCost > 0).sort((a, b) => b.annualCost - a.annualCost);
const max = Math.max(1, ...drivers.map((l) => l.annualCost));
const bars = drivers.map((l) => {
const pct = (l.annualCost / max) * 100;
const tip = `l.label: fmt.full(l.annualCost)/yr · l.count event's' · l.hours dev h · num(l.ciMinutes) CI min in window · monorepo removes Math.round(l.savingsShare * 100)%`;
return `<div class="bar-row" tabindex="0" data-tip="esc(tip)"><div class="bar-label">/, 'Bugs · '))</div><div class="bar-track"><div class="bar" style="width:pct.toFixed(2)%"></div><span class="bar-value">esc(fmt.compact(l.annualCost))</span></div></div>`;
}).join('');
// Low / expected / high range on one axis.
const lo = r.cost.low.totals.annualCost, ex = e.totals.annualCost, hi = r.cost.high.totals.annualCost;
const span = Math.max(1, hi * 1.08);
const at = (v) => `((v / span) * 100).toFixed(2)%`;
const range = `<div class="range" role="img" aria-label="Annualized cost range esc(fmt.full(lo)) to esc(fmt.full(hi)), expected esc(fmt.full(ex))">
<div class="range-axis"></div>
<div class="range-span" style="left:at(lo);width:calc(at(hi) - at(lo))"></div>
<div class="range-dot" style="left:at(ex)" tabindex="0" data-tip="Expected (high + medium confidence bugs): esc(fmt.full(ex))/yr"></div>
<div class="range-tick" style="left:at(lo)" data-tip="Low (high-confidence bugs only): esc(fmt.full(lo))/yr" tabindex="0"><span>Low esc(fmt.compact(lo))</span></div>
<div class="range-tick" style="left:at(hi)" data-tip="High (all bugs incl. low confidence): esc(fmt.full(hi))/yr" tabindex="0"><span>High esc(fmt.compact(hi))</span></div>
</div>`;
const costTable = `<table><thead><tr><th>Cost driver</th><th class="n">Events</th><th class="n">Dev hours</th><th class="n">CI minutes</th><th class="n">Cost (window)</th><th class="n">Annualized</th><th class="n">Monorepo removes</th></tr></thead><tbody>
e.lines.map((l) => `<tr><td>${esc(l.label)</td><td class="n">l.count</td><td class="n">l.hours</td><td class="n">num(l.ciMinutes)</td><td class="n">fmt.full(l.cost)</td><td class="n">fmt.full(l.annualCost)</td><td class="n">Math.round(l.savingsShare * 100)%</td></tr>`).join('')}
</tbody><tfoot><tr><th>Total</th><th></th><th class="n">e.totals.hours</th><th class="n">num(e.totals.ciMinutes)</th><th class="n">fmt.full(e.totals.cost)</th><th class="n">fmt.full(e.totals.annualCost)</th><th class="n">fmt.full(e.totals.annualSavings)/yr</th></tr></tfoot></table>`;
const scenarioTable = `<table><thead><tr><th>Scenario</th><th>Bugs counted</th><th class="n">Window cost</th><th class="n">Annualized</th><th class="n">Annual savings</th><th class="n">Payback</th></tr></thead><tbody>
''><td>k</td><td>label</td><td class="n">fmt.full(s.cost)</td><td class="n">fmt.full(s.annualCost)</td><td class="n">fmt.full(s.annualSavings)</td><td class="n">`${pb[k] mo`}</td></tr>`;
}).join('')}</tbody></table>`;
// Drawn with CSS: the half-filled circle glyph renders inconsistently across fonts.
const confIcon = { high: '<span class="dot dot-high" aria-hidden="true"></span>', medium: '<span class="dot dot-medium" aria-hidden="true"></span>', low: '<span class="dot dot-low" aria-hidden="true"></span>' };
const bugCards = r.bugs.map((b) => `<details class="bug" data-conf="b.confidence">
<summary><span class="badge badge-b.confidence">confIcon[b.confidence] b.confidence</span><code class="cat">esc(b.category)</code><span class="bug-title">esc(b.title)</span><span class="bug-repos">esc([...new Set(b.repos)].join(', '))</span></summary>
<p>esc(b.why)</p>
<ul class="commits">b.commits.map((c) => `<li><code>${esc(c.repo)@esc(c.sha)</code> <span class="muted">esc(c.date)</span> esc(c.subject)''</li>`).join('')}</ul>
</details>`).join('');
const ib = r.internal;
const ups = ib.bumps.filter((b) => b.direction === 'up');
const pkgTable = ib.packages.length ? `<table><thead><tr><th>Internal package</th><th>Producer</th><th>Consumers</th><th class="n">Bumps</th><th class="n">Releases</th></tr></thead><tbody>
ib.packages.map((p) => `<tr><td><code>${esc(p.pkg)</code></td><td>esc(p.repo)</td><td>esc(p.consumers.join(', '))</td><td class="n">ups.filter((b) => b.pkg === p.pkg).length</td><td class="n">ib.releases.filter((x) => x.pkg === p.pkg).length</td></tr>`).join('')}</tbody></table>` : '<p class="muted">No internal package is consumed across the analysed repos.</p>';
const groups = [
...r.coordinated.map((g) => ({ kind: 'Coordinated change', ...g })),
...r.duplicatedTooling.map((g) => ({ kind: `Repeated maintenance ×g.copies''`, ...g })),
];
const groupList = groups.length ? `<ul class="groups">groups.map((g) => `<li><strong>${esc(g.kind)</strong> <span class="muted">esc(g.repos.join(', '))</span><br>esc(g.title)<br><span class="muted">g.commits.map((c) => `<code>${esc(c.repo)@esc(c.sha)</code>`).join(' ')}</span></li>`).join('')}</ul>` : '<p class="muted">None found.</p>';
const m = r.migration;
const clusters = m.clusters.filter((c) => c.repos.length > 1);
const clusterList = clusters.length ? `<ol class="clusters">clusters.map((c) => `<li><strong>${esc(c.repos.join(', '))</strong> <span class="muted">coupling weight c.weight</span></li>`).join('')}</ol>` : '<p class="muted">No coupled repos.</p>';
const whyHtml = m.whyMigrate?.length ? `<h3>Why migrate</h3><p class="muted">The polyrepo costs <a href="https://monorepo.tools/" rel="noopener">monorepo.tools</a> lists, shown only where this report measured them.</p>
<ul>m.whyMigrate.map((w) => `<li><strong>${esc(w.polyrepo)</strong> → esc(w.monorepo). <span class="muted">Measured: esc(w.evidence.join(', ')).</span></li>`).join('')}</ul>` : '';
const src = m.toolSource;
const cats = m.toolOptions?.[0]?.categories.map((c) => c.category) ?? [];
const optionsHtml = m.toolOptions?.length ? `<h3>Tool options</h3>
<p class="muted">Every tool compared on <a href="esc(src.urls[1])" rel="noopener">monorepo.tools/compare</a> (snapshot esc(src.retrieved)). The rating and every column up to “esc(src.legend.none)” come from monorepo.tools, which is published by Nx; the last column is from independent sources and is not scored.</p>
<div class="table-wrap"><table><thead><tr><th>Tool</th><th class="n">monorepo.tools rating /10</th>cats.map((c) => `<th class="n">${esc(c)</th>`).join('')}<th class="n">esc(src.legend.implement)</th><th class="n">esc(src.legend.community)</th><th class="n">esc(src.legend.none)</th><th>Fit</th><th>Already used</th><th>Independent signals <span class="muted">(not scored)</span></th></tr></thead><tbody>
m.toolOptions.map((t) => `<tr><td><a href="${esc(t.repo)" rel="noopener">esc(t.name)</a>t.by && t.by !== t.name ? ` <span class="muted">${esc(t.by)</span>` : ''}</td><td class="n"><strong>t.rating.toFixed(1)</strong></td>t.categories.map((c) => `<td class="n">${c.native/c.total</td>`).join('')}<td class="n">t.counts.implement</td><td class="n">t.counts.community</td><td class="n">t.counts.none</td><td>`no <span class="muted">(${esc(t.fitReason))</span>`}</td><td>'—'</td><td class="signals">(independentSignals(t.independent) ?? '—').split(' · ').map(esc).join('<br>')</td></tr>`).join('')}</tbody></table></div>
<h4>Sources</h4><ul class="muted">toolSources(src, m.toolOptions[0].total).map((x) => `<li><a href="${esc(x.url)" rel="noopener">esc(x.name)</a> (esc(x.publisher), retrieved esc(x.retrieved); <strong>esc(x.role)</strong>). esc(x.metric). Covers: esc(x.covers).</li>`).join('')}</ul>` : '';
const couplingTable = m.coupling.length ? `<table><thead><tr><th>Repo pair</th><th class="n">Internal deps</th><th class="n">Bumps</th><th class="n">Coordinated changes</th><th class="n">Bugs</th><th class="n">Weight</th><th class="n">Repeated tooling (not weighted)</th></tr></thead><tbody>
m.coupling.slice(0, 30).map((c) => `<tr><td>${esc(c.repos.join(' ↔ '))</td><td class="n">c.dependencies</td><td class="n">c.bumps</td><td class="n">c.sharedChanges</td><td class="n">c.bugs</td><td class="n">c.weight</td><td class="n">c.sharedTooling ?? 0</td></tr>`).join('')}</tbody></table>` : '';
const conflicts = m.externalConflicts.length ? `<table><thead><tr><th>External dependency</th><th>Majors in use</th></tr></thead><tbody>
m.externalConflicts.slice(0, 40).map((c) => `<tr><td><code>${esc(c.dep)</code></td><td>Object.entries(c.majors).map(([v, rs]) => `v${esc(v) <span class="muted">(esc(rs.join(', ')))</span>`).join(' · ')}</td></tr>`).join('')}</tbody></table>m.externalConflicts.length > 40 ? `<p class="muted">…and ${m.externalConflicts.length - 40 more in the JSON report.</p>` : ''}` : '<p class="muted">No conflicting major versions.</p>';
const assumptions = `<table><thead><tr><th>Assumption</th><th class="n">Value</th></tr></thead><tbody>
Object.entries(r.assumptions).map(([k, v]) => `<tr><td><code>${esc(k)</code></td><td class="n">esc(v)</td></tr>`).join('')}
<tr><td><code>developerHourly</code></td><td class="n">fmt.full(r.rates.developerHourly)</td></tr>
<tr><td><code>ciPerMinute</code></td><td class="n">esc(r.rates.currency) esc(r.rates.ciPerMinute)</td></tr></tbody></table>`;
const repoTable = `<table><thead><tr><th>Repo</th><th class="n">Commits</th><th>Stack</th><th class="n">CI min/commit</th><th>CI source</th></tr></thead><tbody>
r.repos.map((x) => `<tr><td>${esc(x.name)</td><td class="n">x.commits</td><td>esc([x.packageManager, ...x.buildTools].filter(Boolean).join(', ') || '—')</td><td class="n">Math.round(x.ci.minutesPerCommit * 10) / 10</td><td>esc(x.ci.source)</td></tr>`).join('')}</tbody></table>`;
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Polyrepo Tax Report</title>
<style>
:root {
color-scheme: light;
--surface: #ffffff; --surface-2: #f6f6f4; --line: #e4e4e0;
--text: #191919; --text-2: #5f5f5b; --accent: #257de0; --track: #eef3fb;
--yes: #0a7d22; --no: #a55a00;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
color-scheme: dark;
--surface: #161616; --surface-2: #1f1f1f; --line: #333333;
--text: #efefef; --text-2: #a3a3a3; --accent: #338ced; --track: #1c2735;
--yes: #4cc363; --no: #e8a34c;
}
}
:root[data-theme="dark"] {
color-scheme: dark;
--surface: #161616; --surface-2: #1f1f1f; --line: #333333;
--text: #efefef; --text-2: #a3a3a3; --accent: #338ced; --track: #1c2735;
--yes: #4cc363; --no: #e8a34c;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--surface); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { max-width: 1040px; margin: 0 auto; padding: 32px 16px 64px; }
h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; }
h2 { font-size: 20px; margin: 48px 0 12px; padding-top: 16px; border-top: 1px solid var(--line); }
h3 { font-size: 16px; margin: 24px 0 8px; }
h4, h5 { font-size: 15px; margin: 16px 0 6px; }
p { margin: 8px 0; }
code { font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
pre { background: var(--surface-2); padding: 12px; border-radius: 8px; overflow-x: auto; }
a { color: var(--accent); }
.muted { color: var(--text-2); }
.meta { color: var(--text-2); margin: 0 0 24px; }
.hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; align-items: stretch; }
.hero-main, .tile { background: var(--surface-2); border-radius: 12px; padding: 20px; }
.hero-label, .tile-label { color: var(--text-2); font-size: 13px; }
.hero-value { font-size: 44px; font-weight: 650; letter-spacing: -0.02em; line-height: 1.1; margin: 6px 0; font-variant-numeric: tabular-nums; }
.tiles { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.tile-value { font-size: 22px; font-weight: 600; margin-top: 4px; font-variant-numeric: tabular-nums; }
.tile-note { color: var(--text-2); font-size: 12px; }
.verdict { margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); border-left: 4px solid; }
.verdict-yes { border-color: var(--yes); } .verdict-no { border-color: var(--no); }
.range { position: relative; height: 56px; margin: 12px 8px 4px; }
.range-axis { position: absolute; left: 0; right: 0; top: 18px; height: 1px; background: var(--line); }
.range-span { position: absolute; top: 14px; height: 9px; border-radius: 5px; background: var(--track); }
.range-dot { position: absolute; top: 9px; width: 18px; height: 18px; margin-left: -9px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px var(--surface); cursor: default; }
.range-tick { position: absolute; top: 12px; width: 2px; height: 13px; margin-left: -1px; background: var(--text-2); }
.range-tick span { position: absolute; top: 18px; left: 50%; transform: translateX(-50%); white-space: nowrap; font-size: 12px; color: var(--text-2); }
.range-tick:first-of-type span { transform: none; left: 0; }
.chart { margin: 8px 0 4px; }
.bar-row { display: grid; grid-template-columns: minmax(140px, 34%) 1fr; gap: 12px; align-items: center; padding: 5px 0; border-radius: 6px; }
.bar-row:hover, .bar-row:focus-visible { background: var(--surface-2); outline: none; }
.bar-label { font-size: 13px; color: var(--text); text-align: right; }
.bar-track { display: flex; align-items: center; gap: 8px; min-width: 0; }
.bar { height: 20px; min-width: 2px; background: var(--accent); border-radius: 0 4px 4px 0; }
.bar-value { font-size: 13px; color: var(--text-2); white-space: nowrap; font-variant-numeric: tabular-nums; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; margin: 8px 0; }
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
thead th { color: var(--text-2); font-weight: 600; }
tfoot th { border-bottom: 0; }
.n { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.row-em td { font-weight: 600; }
.filters { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0 12px; }
.filters button { font: inherit; font-size: 13px; padding: 5px 12px; border-radius: 999px; border: 1px solid var(--line); background: var(--surface); color: var(--text); cursor: pointer; }
.filters button[aria-pressed="true"] { background: var(--text); color: var(--surface); border-color: var(--text); }
.bug { border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; margin: 8px 0; }
.bug summary { cursor: pointer; display: flex; flex-wrap: wrap; gap: 8px; align-items: baseline; }
.bug-title { font-weight: 600; flex: 1 1 260px; min-width: 0; overflow-wrap: anywhere; }
.bug-repos { color: var(--text-2); font-size: 13px; }
.cat { color: var(--text-2); }
.badge { font-size: 12px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--line); text-transform: capitalize; }
.badge-high { background: var(--text); color: var(--surface); border-color: var(--text); }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid currentColor; vertical-align: 0; margin-right: 2px; }
.dot-high { background: currentColor; }
.dot-medium { background: linear-gradient(90deg, currentColor 50%, transparent 50%); }
.commits { margin: 6px 0 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
.groups, .clusters { padding-left: 20px; }
.groups li, .clusters li { margin: 8px 0; overflow-wrap: anywhere; }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 8px 0; }
.signals { min-width: 240px; }
.plan { background: var(--surface-2); border-radius: 12px; padding: 4px 20px 12px; }
#tip { position: fixed; pointer-events: none; z-index: 10; max-width: 320px; padding: 8px 10px; border-radius: 8px; font-size: 12px; background: var(--text); color: var(--surface); box-shadow: 0 4px 16px rgb(0 0 0 / .25); opacity: 0; }
footer { margin-top: 48px; color: var(--text-2); font-size: 12px; }
@media (max-width: 720px) {
.hero { grid-template-columns: 1fr; }
.hero-value { font-size: 36px; }
.bar-row { grid-template-columns: 1fr; gap: 2px; }
.bar-label { text-align: left; }
}
@media print {
#tip, .filters { display: none; }
.bug { break-inside: avoid; }
details.bug:not([open]) > *:not(summary) { display: block; }
}
</style>
</head>
<body>
<main>
<h1>Polyrepo Tax Report</h1>
<p class="meta">r.repos.length repos (esc(repoList)) · esc(r.window.since) → esc(r.window.until) (r.window.days days) · fmt.full(r.rates.developerHourly)/dev-hour · esc(r.rates.currency) esc(r.rates.ciPerMinute)/CI-minute</p>
</strong> ${esc(r.problems.join('; '))</p>` : ''}
<section class="hero" aria-label="Headline numbers">
<div class="hero-main">
<div class="hero-label">Polyrepo tax per year, expected</div>
<div class="hero-value">fmt.full(ex)</div>
<div class="muted">fmt.full(lo) – fmt.full(hi) depending on which bugs you count</div>
range
</div>
<div class="tiles">
<div class="tile"><div class="tile-label">Developer time (window)</div><div class="tile-value">num(e.totals.hours) h</div><div class="tile-note">fmt.full(e.totals.devCost)</div></div>
<div class="tile"><div class="tile-label">CI time (window)</div><div class="tile-value">num(e.totals.ciMinutes) min</div><div class="tile-note">fmt.full(e.totals.ciCost) · ciMeasured ? `measured for ${ciMeasured of r.repos.length repos` : 'assumed'}</div></div>
<div class="tile"><div class="tile-label">Bugs attributable to repo boundaries</div><div class="tile-value">bugsBy('high').length + bugsBy('medium').length</div><div class="tile-note">bugsBy('high').length high · bugsBy('medium').length medium · bugsBy('low').length low confidence</div></div>
<div class="tile"><div class="tile-label">Migration payback</div><div class="tile-value">esc(paybackText)</div><div class="tile-note">fmt.full(m.oneTime.cost) one-time · saves fmt.full(e.totals.annualSavings)/yr</div></div>
</div>
</section>
<p class="verdict verdict.cls">esc(verdict.text)</p>
<p class="muted">Estimates from git history, not invoices. Every count links to commits below; every rate and assumption is listed at the end and can be overridden.</p>
<h2>Where the money goes</h2>
<p class="muted">Annualized cost per driver, expected scenario. Hover or focus a bar for hours and CI minutes.</p>
<div class="chart">bars || '<p class="muted">No measurable polyrepo cost in this window.</p>'</div>
<details><summary>Table view</summary><div class="table-wrap">costTable</div></details>
<h3>Scenarios</h3>
<div class="table-wrap">scenarioTable</div>
<h2>Bugs attributable to repo boundaries</h2>
r.bugs.length ? `<div class="filters" role="group" aria-label="Filter by confidence">
<button type="button" data-filter="all" aria-pressed="true">All ${r.bugs.length</button>
['high', 'medium', 'low'].map((c) => `<button type="button" data-filter="${c" aria-pressed="false">confIcon[c] c[0].toUpperCase()c.slice(1) bugsBy(c).length</button>`).join('')}
</div>
<div id="bugs">bugCards</div>` : '<p class="muted">None found in this window.</p>'}
<h2>Internal dependency churn</h2>
<div class="stats">
<div class="tile"><div class="tile-label">Internal bumps</div><div class="tile-value">ups.length</div><div class="tile-note">ups.filter((b) => b.bot).length by bots · ups.filter((b) => !b.bot).length by people</div></div>
<div class="tile"><div class="tile-label">Internal releases to move code</div><div class="tile-value">ib.releases.length</div><div class="tile-note">'packages consumed by sibling repos'</div></div>
<div class="tile"><div class="tile-label">Median release → bump lag</div><div class="tile-value">ib.medianBumpLagDays ?? 'n/a'' days'</div><div class="tile-note">time a consumer runs old code</div></div>
<div class="tile"><div class="tile-label">Consumers behind today</div><div class="tile-value">ib.drift.length</div><div class="tile-note">ib.drift.filter((d) => d.majorsBehind > 0).length a major version or more</div></div>
</div>
<div class="table-wrap">pkgTable</div>
ib.skew.length ? `<h3>Version skew today</h3><ul>${ib.skew.map((s) => `<li><code>${esc(s.pkg)</code>: Object.entries(s.majors).map(([v, rs]) => `v${esc(v) in esc(rs.join(', '))`).join(' · ')}</li>`).join('')}</ul>` : ''}
<h2>Duplicated and coordinated work</h2>
groupList
<h2>Migration</h2>
<p><strong>Recommended tooling:</strong> esc(m.recommendedTool) <span class="muted">(esc(Object.entries(m.languages).map(([l, n]) => `${l n files`).join(', ') || 'no languages detected')})</span></p>
whyHtml
optionsHtml
<h3>Clusters to migrate, heaviest first</h3>
clusterList
${esc(m.isolated.join(', '))</p>` : ''}
<p><strong>One-time effort:</strong> ~m.oneTime.days dev-days (fmt.full(m.oneTime.cost)) for m.oneTime.repos.length repos · <strong>payback</strong> `~${pb.expected months`} <span class="muted">(range pb.high ?? '—' – pb.low ?? 'never' months)</span></p>
couplingTable ? `<h3>Coupling between repos</h3><div class="table-wrap">${couplingTable</div>` : ''}
<h3>External dependencies to align first</h3>
<div class="table-wrap">conflicts</div>
plan ? `<h3>Migration plan</h3><div class="plan">${markdownToHtml(plan.replace(/^\s*#{1,6\s*Migration plan\s*\n/i, ''))}</div>` : ''}
<h2>Assumptions</h2>
<div class="table-wrap">assumptions</div>
<div class="table-wrap">repoTable</div>
<footer>Generated esc(r.generatedAt) by the polyrepo-tax skill. Full data: polyrepo-tax-report.json.</footer>
</main>
<div id="tip" role="tooltip"></div>
<script>
(() => {
const tip = document.getElementById('tip');
const show = (el, x, y) => {
tip.textContent = el.dataset.tip;
const w = tip.offsetWidth, h = tip.offsetHeight;
tip.style.left = Math.max(8, Math.min(x + 12, innerWidth - w - 8)) + 'px';
tip.style.top = Math.max(8, y - h - 12) + 'px';
tip.style.opacity = 1;
};
const hide = () => { tip.style.opacity = 0; };
for (const el of document.querySelectorAll('[data-tip]')) {
el.addEventListener('pointermove', (ev) => show(el, ev.clientX, ev.clientY));
el.addEventListener('pointerleave', hide);
el.addEventListener('focus', () => { const b = el.getBoundingClientRect(); show(el, b.left + 16, b.top); });
el.addEventListener('blur', hide);
}
const buttons = document.querySelectorAll('.filters button');
for (const btn of buttons) btn.addEventListener('click', () => {
for (const b of buttons) b.setAttribute('aria-pressed', String(b === btn));
for (const card of document.querySelectorAll('#bugs .bug')) card.hidden = btn.dataset.filter !== 'all' && card.dataset.conf !== btn.dataset.filter;
});
})();
</script>
</body>
</html>
`;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const argv = process.argv.slice(2);
const opt = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
const input = argv.find((a, i) => !a.startsWith('--') && !['--plan', '--out'].includes(argv[i - 1]));
if (!input) { console.error('usage: render-html.mjs <polyrepo-tax-report.json> [--plan migration-plan.md] [--out report.html]'); process.exit(2); }
const report = JSON.parse(fs.readFileSync(input, 'utf8'));
const planPath = opt('--plan') ?? path.join(path.dirname(input), 'migration-plan.md');
const plan = fs.existsSync(planPath) ? fs.readFileSync(planPath, 'utf8') : undefined;
const out = opt('--out') ?? path.join(path.dirname(input), 'polyrepo-tax-report.html');
fs.writeFileSync(out, renderHtml(report, { plan }));
console.log(`wrote outplan ? ` (with ${path.basename(planPath))` : ''}`);
}Create a premium 3D smartphone advertisement. A sleek purple smartphone floats in a dark purple studio. The phone smoothly separates into individual parts: screen, frame, camera lenses and internal components. Each piece floats elegantly in space, then seamlessly moves back into place, assembling into the complete phone. Smooth cinematic motion, realistic materials, soft purple lighting, elegant camera movement, luxury product commercial, vertical 9:16.
A premium purple smartphone floating in a purple studio. The phone smoothly separates into individual parts, including the screen, frame, camera lenses and internal components. The pieces float elegantly in space, then seamlessly assemble back into the complete phone. Smooth cinematic 3D animation, realistic materials, soft purple lighting, luxury product advertisement, vertical 9:16.

A fill-in-the-blanks image prompt for full-body surrealist haute couture fashion illustrations: pick a [theme] and three colors to get a sculptural, avant-garde gown, headpiece and handbag on a clean white background.
A full-body fashion illustration of one elegant model wearing a [theme]-inspired surrealist haute couture gown, avant-garde deconstructivist silhouette, sculptural tailoring, intricate 3D embroidery, layered velvet, translucent organza, pleated silk, elaborate [theme]-inspired headpiece, artistic handbag, flowing architectural forms, sophisticated [color1] and [color2] palette with [color3] accents, refined fashion illustration, dreamy editorial aesthetic, clean white background, 4K
A whimsical mixed-media video prompt: a miniature hand-drawn 2D delivery girl braves a gigantic photorealistic New York street, from gusts of traffic wind and a coffee-lid boat ride to a pizza-slice landing, with sound design and compositing notes.
Create a whimsical mixed-reality animation featuring a miniature hand-drawn 2D young woman with long black hair, a pink hoodie, denim shorts, white sneakers, and a tiny red delivery backpack exploring a gigantic photorealistic New York street. She encounters a massive pedestrian crossing where passing cars create powerful gusts of wind that nearly blow her away, climbs onto a giant sneaker left on the pavement, slides down a newspaper stand, discovers a giant hot-dog cart where she narrowly escapes a rolling pickle, sails across a huge puddle using a discarded coffee cup lid as a boat, and gets lifted into the air by a gust of wind using her delivery bag as an improvised parachute. Finally, she lands on top of a giant pizza slice and celebrates triumphantly until a human hand suddenly picks up the slice, leaving her dangling in disbelief. Combine expressive hand-drawn 2D animation with photorealistic urban environments, exaggerated scale, playful physics, cinematic macro close-ups, smooth camera movements, and seamless mixed-media compositing. Include realistic city ambience, traffic, footsteps, car horns, street vendor sounds, water splashes, wind, and playful comedic sound effects. No dialogue. Ultra-detailed visuals, consistent character design, cinematic depth of field, and high-end commercial animation quality.
A vertical, Japanese-style 3D animated family comedy prompt: a 3-year-old girl in an oversized chef hat surprises her father with a slightly burnt pancake, with dialogue beats, final shot, style, consistency and negative prompt included.
Create a heartwarming, hilarious, ultra-realistic Japanese-style 3D animated family comedy in vertical 9:16 format. A cute 3-year-old Japanese girl with short black bobbed hair, chubby cheeks, sparkling eyes, and pink pajamas decides to surprise her father with breakfast. Wearing an oversized chef hat, she struggles to prepare pancakes in the kitchen. She accidentally spills flour everywhere, gets chocolate on her face, and finally serves her father a funny-looking, slightly burnt pancake. 🎙️ Girl: "Papa! I made this for you!" Her father takes a bite, struggles to hide his reaction, and says, "Delicious!" The little girl notices his watery eyes and innocently asks, "Papa, are you crying because it's so yummy?" The mother walks in, tastes the pancake, and bursts into laughter. The father hugs his little daughter and kisses her forehead. Final Shot: The little girl proudly poses like a professional chef while her parents laugh. Style: High-end Japanese 3D animation, adorable characters, expressive faces, realistic movements, warm lighting, cinematic camera angles, funny sound effects, natural Japanese dialogue, and heartwarming family moments. Consistency: Maintain identical characters, clothing, facial features, and kitchen throughout. Negative: No distorted faces, extra fingers, flickering, scene jumps, subtitles, text, or watermark.
Opinionated conventions for keyboard-first terminal UI apps: TUI frameworks, responsive rendering, accessible colors and scriptable modes.
# Terminal UI App taste of a developer who builds fast, keyboard-first terminal interfaces - Pick a mature TUI framework (Bubble Tea, Ratatui, Textual, Ink) instead of writing raw escape codes. Confidence: 0.90 - Use an Elm-style model, update and view architecture so state changes are easy to test without a terminal. Confidence: 0.80 - Render in the alternate screen buffer and always restore the terminal on exit, panic or Ctrl+C. Confidence: 0.95 - Make every action reachable by keyboard and show the main shortcuts in a footer bar. Confidence: 0.90 - Offer a ? key that opens a full help overlay listing all key bindings for the current view. Confidence: 0.85 - Support both arrow keys and vim-style hjkl navigation, and never require a mouse, though mouse support is welcome. Confidence: 0.80 - Use q or Esc to go back or quit, and ask for confirmation only before destructive actions. Confidence: 0.85 - Never block the render loop on I/O; run network and disk work in the background and show a spinner or progress bar. Confidence: 0.90 - Redraw only on state changes or at a capped frame rate, not in a busy loop. Confidence: 0.80 - Handle terminal resize events and lay out with flexible constraints that still work at 80x24. Confidence: 0.90 - Respect NO_COLOR, detect color depth, and fall back gracefully from truecolor to 256 and 16 colors. Confidence: 0.85 - Never use color as the only signal; pair it with symbols, labels or bold text. Confidence: 0.85 - Use a small, consistent palette tied to the terminal theme instead of hard-coded bright colors. Confidence: 0.75 - Provide a non-interactive mode (flags, --json output) for every important action so the tool works in scripts and CI. Confidence: 0.90 - Detect when stdout is not a TTY and switch to plain output automatically. Confidence: 0.90 - Add fuzzy filtering with / to any list longer than one screen. Confidence: 0.80 - Write logs to a file (opt-in with --debug), never to the screen the UI is drawing on. Confidence: 0.85 - Store config in the XDG config directory as TOML or YAML, and let users remap key bindings there. Confidence: 0.75 - Test views with golden snapshot files of rendered output at fixed terminal sizes. Confidence: 0.75 - Test in the common terminals (iTerm2, Windows Terminal, GNOME Terminal, tmux) before a release, including Unicode width cases. Confidence: 0.70 - Keep startup under about 100 ms so opening the app feels instant. Confidence: 0.70 - Ship a single static binary or a pipx/npm install path, with a short animated demo GIF in the README. Confidence: 0.70
Opinionated conventions for building and releasing Swift packages: Package.swift setup, strict concurrency, Swift Testing, DocC and semver.
# Swift Package taste of a developer who ships small, well-tested Swift libraries - Use Swift Package Manager as the only distribution method for new libraries, and skip CocoaPods and Carthage specs unless users ask. Confidence: 0.85 - Set the swift-tools-version to the oldest toolchain you really test on, and raise it on purpose in a minor release. Confidence: 0.80 - Declare explicit platform minimums in Package.swift (.iOS, .macOS, .watchOS, .tvOS, .visionOS) instead of relying on defaults. Confidence: 0.85 - Keep one focused library product per package; split optional integrations into separate targets users can opt into. Confidence: 0.80 - Use the standard layout (Sources/<Target>, Tests/<Target>Tests) and avoid custom path settings. Confidence: 0.90 - Enable Swift 6 language mode and strict concurrency checking, and mark public types Sendable where it is true. Confidence: 0.80 - Keep the public API small: default to internal, and make each public symbol a deliberate decision. Confidence: 0.90 - Prefer value types and protocols with small requirements over class hierarchies in public APIs. Confidence: 0.80 - Offer async/await APIs first, and add completion-handler or Combine wrappers only when users need them. Confidence: 0.75 - Avoid third-party dependencies in a library; when one is needed, use a version range from: a major version, never a branch or exact revision. Confidence: 0.85 - Write tests with Swift Testing (@Test, #expect) for new code and keep XCTest only where it is already used. Confidence: 0.75 - Run CI on macOS and Linux with swift build and swift test, plus xcodebuild for each Apple platform you claim to support. Confidence: 0.85 - Write DocC documentation for every public symbol and include at least one article showing the main use case. Confidence: 0.80 - Host the docs on the Swift Package Index and keep a .spi.yml so builds and documentation stay green there. Confidence: 0.70 - Follow semantic versioning with plain tags like 1.4.0, without a v prefix, so SPM resolves them. Confidence: 0.90 - Use @available and deprecation messages with a renamed: hint one minor release before removing an API. Confidence: 0.85 - Keep resources in a Resources folder declared with .process and access them only through Bundle.module. Confidence: 0.75 - Format with swift-format or SwiftFormat and lint with SwiftLint in CI, using a config committed to the repo. Confidence: 0.70 - Avoid build plugins and macros unless they remove real boilerplate, because they slow builds and need extra trust prompts. Confidence: 0.65 - Ship a privacy manifest (PrivacyInfo.xcprivacy) when the library touches required-reason APIs. Confidence: 0.75 - Keep Package.resolved out of library repositories, but commit it in apps and example projects. Confidence: 0.80 - Include a runnable example app or snippet in the README that compiles in CI. Confidence: 0.70 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Fixed sections for every release. Confidence: 0.80
Opinionated habits for safe, incremental refactoring: characterization tests, small green steps, strangler fig and clean pull requests.
# Refactoring taste of an engineer who changes structure without changing behavior
- Never mix a refactor and a behavior change in the same commit; reviewers should be able to verify each one alone. Confidence: 0.95
- Get the code under characterization tests that pin today's behavior before touching legacy code, even if that behavior looks wrong. Confidence: 0.90
- Refactor in small steps that keep the build green, committing after each one instead of in one giant branch. Confidence: 0.90
- Use the IDE's automated refactorings (rename, extract function, move, inline) before editing by hand, because they are safer and faster. Confidence: 0.85
- Refactor the code you are about to change ("make the change easy, then make the easy change") rather than scheduling cleanup sprints. Confidence: 0.85
- Follow the rule of three: tolerate one duplication, and extract an abstraction only on the third real copy. Confidence: 0.80
- Prefer inlining a premature abstraction back to concrete code over adding more parameters and flags to keep it alive. Confidence: 0.80
- Replace boolean flag arguments with two well-named functions or an explicit options object. Confidence: 0.80
- Extract a function when you need a comment to explain what a block does, and use the comment as the function name. Confidence: 0.75
- Replace nested conditionals with guard clauses and early returns. Confidence: 0.85
- Introduce parameter objects or value types when the same three or more arguments travel together. Confidence: 0.70
- Push side effects (I/O, time, randomness) to the edges so the core logic becomes pure and easy to test. Confidence: 0.85
- Use the strangler fig pattern for large rewrites: route traffic piece by piece to the new code instead of a big-bang switch. Confidence: 0.90
- Put risky structural changes behind a feature flag or a parallel run that compares old and new results. Confidence: 0.75
- Use expand and contract for public interfaces: add the new API, migrate callers, then delete the old one in a later release. Confidence: 0.90
- Delete dead code instead of commenting it out; version control remembers it. Confidence: 0.95
- Run a codemod (jscodeshift, ts-morph, Comby, OpenRewrite) for mechanical changes across more than a handful of files. Confidence: 0.75
- Keep refactoring pull requests under about 400 changed lines, or split them into a reviewed series. Confidence: 0.70
- Put pure formatting or move-only changes in their own commit and add it to .git-blame-ignore-revs. Confidence: 0.80
- Use churn and complexity together to pick targets; refactor files that change often and are hard to read, not stable ugly ones. Confidence: 0.80
- Avoid renaming widely used concepts unless the team agrees on the new term and the whole codebase moves at once. Confidence: 0.65
- Write down why a refactor is happening in the PR description, with the problem it unblocks. Confidence: 0.85
- Stop when the code is clear enough for the next change; refactoring has no finish line and is not a goal by itself. Confidence: 0.80Estimates what employee turnover really costs per team: recruiting, interviews, vacancy, ramp-up, onboarding and offboarding from a simple CSV, flags hot spots, and tests whether a retention program pays for itself with savings and break-even scenarios. Stdlib Python.
---
name: employee-turnover-cost-calculator
description: Estimates what employee turnover really costs per team: recruiting, interviews, vacancy, ramp-up, onboarding and offboarding from a simple CSV, flags hot spots, and tests whether a retention program pays for itself with savings and break-even scenarios. Stdlib Python.
---
# Employee Turnover Cost Calculator
You help business managers, founders and HR leads put a credible number on employee turnover. "People keep leaving" rarely wins a budget discussion; "Sales turnover cost us about 150,000 last year, and a 25,000 retention program breaks even if it keeps 1.4 people" does. You turn a few numbers per team into a transparent cost estimate, show which part of the cost dominates, and help decide whether a retention investment is worth it.
The numbers are estimates built from stated assumptions, not accounting facts. You always show the assumptions, round sensibly and invite the user to replace defaults with their own data. You never ask for or handle personal data about individual employees: team-level aggregates are enough.
## Files in this skill
- `scripts/turnover_cost.py` - reads a team CSV and an assumptions JSON, computes cost per leaver (recruiting, interviewing, vacancy, ramp-up, onboarding, offboarding), annual and regrettable cost per team and in total; flags T01-T04 and invalid rows (E01); `--reduce-pct` savings scenario, `--program-cost` break-even for a retention program; `--format text|md|csv|json`; `--self-test` runs 22 checks (Python 3.8+ standard library only)
- `references/cost-model.md` - every cost component, the formulas, typical ranges and where to get the inputs
- `references/retention-levers.md` - what usually drives turnover per situation and which retention actions fit, with rough costs
- `templates/turnover-cost-brief.md` - a one-page brief for leadership
- `examples/teams.csv` + `examples/assumptions.json` - a fictional 93-person company with six teams
## Workflow
### 1. Gather inputs
Ask for, per team or role: average headcount over the last 12 months, number of leavers (voluntary and involuntary, or say which), how many were regrettable (people you wanted to keep), average salary, typical time to fill a role (calendar days), months until a new hire is fully productive, and the main hiring channel. Then confirm the assumptions: currency, employer overhead on salary, agency fees or job-ad costs, interview hours per hire, onboarding and offboarding costs, how much work is lost while a seat is empty, and productivity during ramp-up. Use the defaults in `examples/assumptions.json` only when the user has no better number, and say so.
### 2. Run the calculation
```
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --reduce-pct 20 --program-cost 25000
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --format md > turnover.md
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --format csv
python3 scripts/turnover_cost.py --self-test
```
Exit code 0 = no flags, 1 = flags or invalid rows, 2 = unreadable input or missing columns.
| Code | Meaning |
|---|---|
| T01 | turnover rate at or above `high_turnover_pct` (default 25%) |
| T02 | more than half of the team's leavers (2 or more) were regrettable |
| T03 | cost per leaver at or above 50% of annual salary |
| T04 | time to fill at or above `slow_fill_days` (default 60) |
| E01 | invalid row (non-numeric, regrettable > leavers, unknown hiring channel, implausible numbers) |
### 3. Interpret
- Look at both the total and the mix: high-volume, low-cost turnover (warehouse, support) and low-volume, high-cost turnover (engineering, sales) need different responses.
- Check which component dominates (`By part`): ramp-up and vacancy usually outweigh recruiting fees, which is why "cheaper recruiting" rarely fixes the problem.
- Regrettable cost is the number to act on; some turnover is healthy.
- Run a sensitivity check: re-run with ramp-up loss and vacancy cost 20-30% lower; if the conclusion still holds, it is robust.
### 4. Decide on retention actions
Use `references/retention-levers.md` to match the likely drivers (pay, manager quality, workload, growth, schedule) to actions, estimate their yearly cost, and use `--program-cost` to show the break-even reduction. Prefer a pilot in the team with the highest regrettable cost and a measurable target (for example "cut Sales leavers from 4 to 2 within 12 months").
### 5. Report
Fill `templates/turnover-cost-brief.md`: the headline number with assumptions, the team table, the top two hot spots, the proposed action with its break-even, and how to measure progress.
## Example
```
python3 scripts/turnover_cost.py examples/teams.csv --assumptions examples/assumptions.json --reduce-pct 20 --program-cost 25000
```
Result: about EUR 540k per year for 31 leavers (33.3% turnover, avg EUR 17.4k per leaver), EUR 298k of it regrettable. Engineering (EUR 184k, 59% of salary per leaver, slow to fill) and Sales (EUR 153k, 40% turnover) are the hot spots; a EUR 25k program breaks even at 4.6% less turnover, and a 20% reduction would save about EUR 108k.
## Limits
- Estimates only; hidden costs (lost customers, team morale, knowledge loss) are not included and usually make the real cost higher.
- Team averages hide individual differences; do not use the output to judge individual employees.
- Vacancy and ramp-up assumptions drive most of the result: agree them with finance before presenting.
FILE:references/cost-model.md
# Turnover cost model
All amounts per leaver unless stated. The script uses exactly these formulas.
| Component | Formula | Typical range | Where to get the input |
|---|---|---|---|
| Recruiting | agency fee % x salary, or fixed channel cost (job ads, referral bonus) | agency 15-30% of salary; job boards 300-2,000; referral bonus 500-3,000 | finance, recruiting invoices |
| Interviewing | interview hours per hire x loaded hourly cost of interviewers | 8-25 hours | hiring managers, ATS stages |
| Vacancy | working days empty (calendar days x 5/7) x daily loaded pay x vacancy cost % | 30-80% of daily pay, depending on how much work is covered by others or overtime | time-to-fill from ATS; ask managers how much work is really lost |
| Ramp-up | ramp months / 12 x loaded salary x productivity loss % | 1-2 months for hourly roles, 3-6 for skilled roles, 6-9 for senior or sales roles with long cycles; average loss 40-60% over the ramp | managers |
| Onboarding | fixed: equipment, licences, training, buddy time, admin | 500-4,000 | IT, HR |
| Offboarding | fixed: exit admin, access removal, handover time, final pay processing | 200-1,000 | HR, IT |
Loaded salary = salary x (1 + employer overhead %). Overhead covers employer taxes, benefits and pension contributions (often 15-35%).
Daily loaded pay = loaded salary / working days per year (around 220).
Turnover rate = leavers in 12 months / average headcount over the same months.
## Cross-check
Total cost per leaver usually lands between 20% and 60% of annual salary for most roles, and can exceed 100% for senior, specialist or quota-carrying roles once lost revenue is included. If the result is far outside that range, check the inputs (monthly vs annual salary, days vs months).
## What is not included
- Lost revenue or customers (sales roles, account managers): add separately if the business can estimate it.
- Overtime and burnout of remaining colleagues, and knock-on resignations.
- Knowledge loss and mistakes made by new hires.
- Severance and legal costs for involuntary exits.
Mention these as reasons the real cost is likely higher, without inventing numbers.
## Data hygiene
- Use team-level aggregates; never collect names or reasons for individual leavers in this calculation.
- Count interns, fixed-term contracts that ended as planned, and internal transfers separately or exclude them.
- Twelve months is the standard window; for small teams (under 10 people) one leaver swings the rate a lot, so look at two or three years.
FILE:references/retention-levers.md
# Retention levers
Match the likely driver to an action. Ask exit and stay interview themes (aggregated) before choosing.
| Likely driver | Signals | Actions | Rough yearly cost |
|---|---|---|---|
| Pay below market | offers from competitors, leavers get 15%+ raises | market pay review for the at-risk roles, clear salary bands, retention bonus for critical people | 3-8% of the affected payroll |
| Manager relationship | turnover concentrated under one or two managers | manager training, regular 1:1s, skip-level conversations, coaching | 1,000-3,000 per manager |
| Workload and burnout | overtime, sick leave rising, leavers mention stress | hire ahead of demand, cut low-value work, protect focus time, fair on-call rotas | varies; often cheaper than one leaver |
| No growth path | good people leave after 18-30 months | career ladders, internal mobility, learning budget, stretch projects | 500-2,000 per person |
| Schedule and flexibility | hourly roles, parents, long commutes | predictable shifts published early, shift swapping, hybrid days where possible | low |
| Bad hiring fit | many leavers in the first 90 days | clearer job previews, structured interviews, better onboarding and a buddy | 500-1,500 per hire |
| Recognition | leavers mention feeling invisible | regular, specific recognition; transparent promotion criteria | low |
## Running a pilot
1. Pick the team with the highest regrettable cost.
2. Choose one or two actions that fit its driver.
3. Set a target in leavers (not only percent) and a review date (6 and 12 months).
4. Compare with a similar team that did not get the action, if possible.
5. Re-run the calculator with the new numbers and report the saving against the program cost.
## Break-even reasoning
Program break-even (leavers avoided) = program cost / average cost per leaver. If keeping one or two people pays for the program, it is usually worth piloting even with uncertain assumptions.
FILE:templates/turnover-cost-brief.md
# Turnover cost brief: {company or department}, {period}
## Headline
Turnover cost us an estimated **{currency} {annual_cost}** in the last 12 months: {leavers} leavers, {turnover_pct}% turnover, about {currency} {avg_cost_per_leaver} per leaver. **{currency} {regrettable_cost}** of it came from people we wanted to keep.
## Where it hurts
| Team | Leavers | Turnover | Cost per leaver | Annual cost | Why |
|---|---|---|---|---|---|
| {team} | {n} | {pct}% | {cost} ({pct_salary}% of salary) | {annual} | {flags in plain words} |
Biggest cost component: {ramp-up / vacancy / recruiting} ({share}% of the total).
## Proposal
{Action, team, owner}. Cost: {currency} {program_cost} per year. It breaks even if it prevents **{break_even_leavers} leavers** ({break_even_pct}% less turnover). A {reduce_pct}% reduction would save about {currency} {annual_saving} ({net} net).
## How we will measure it
- Leavers and regrettable leavers per quarter in {team}
- Time to fill and 90-day attrition of new hires
- Review on {date}; stop or scale based on the result
## Assumptions
{overhead %, channel costs, interview hours, vacancy %, ramp months and loss %, onboarding/offboarding costs}. Not included: lost revenue, overtime, knowledge loss, severance, so the real cost is likely higher.
FILE:examples/teams.csv
team,role,avg_headcount,leavers_12m,regrettable_leavers,avg_salary,time_to_fill_days,ramp_months,hiring_channel
Customer Support,Support Agent,24,9,4,38000,35,2,job_board
Engineering,Software Engineer,18,4,3,78000,62,4,agency
Sales,Account Executive,10,4,2,62000,48,5,agency
Warehouse,Picker and Packer,30,13,3,31000,14,1,job_board
Finance,Accountant,5,1,1,58000,55,3,referral
Marketing,Content Marketer,6,0,0,52000,40,3,job_board
FILE:examples/assumptions.json
{
"currency": "EUR",
"working_days_per_year": 220,
"employer_overhead_pct": 22,
"hiring_channels": {
"agency": {"fee_pct_of_salary": 20, "fixed_cost": 0},
"job_board": {"fee_pct_of_salary": 0, "fixed_cost": 900},
"referral": {"fee_pct_of_salary": 0, "fixed_cost": 1500}
},
"interview_hours_per_hire": 14,
"interviewer_hourly_cost": 55,
"onboarding_cost_per_hire": 1800,
"offboarding_cost_per_leaver": 400,
"vacancy_cost_pct_of_daily_pay": 60,
"ramp_productivity_loss_pct": 50,
"high_turnover_pct": 25,
"slow_fill_days": 60
}
FILE:scripts/turnover_cost.py
#!/usr/bin/env python3
"""turnover_cost.py - estimate what employee turnover costs a business, per team and in total (standard library only).
Input: a CSV with one row per team or role (see examples/teams.csv) and an assumptions JSON (examples/assumptions.json).
Per leaver the cost is the sum of:
recruiting agency fee (% of salary) or fixed channel cost (job ads, referral bonus)
interviewing interview hours x interviewer hourly cost
vacancy days the seat is empty (time_to_fill_days converted to working days) x daily pay x vacancy_cost_pct
ramp-up ramp_months / 12 x loaded salary x ramp_productivity_loss_pct
onboarding fixed onboarding cost (equipment, training, admin)
offboarding fixed offboarding cost (exit admin, access removal, handover)
Loaded salary = avg_salary x (1 + employer_overhead_pct / 100).
Flags: T01 turnover rate >= high_turnover_pct, T02 more than half of 2+ leavers were regrettable,
T03 cost per leaver >= 50% of salary, T04 time to fill >= slow_fill_days, E01 invalid row.
Scenarios: --reduce-pct P shows the saving if turnover fell by P percent; --program-cost C (per year) shows
whether a retention program pays for itself and the break-even reduction.
Usage:
python3 turnover_cost.py teams.csv --assumptions assumptions.json [--format text|md|csv|json]
[--reduce-pct 20] [--program-cost 15000]
python3 turnover_cost.py --self-test
Exit code: 0 = no flags, 1 = flags present (T01-T04) or invalid rows, 2 = bad input file.
"""
import argparse, csv, io, json, sys
REQUIRED = ["team", "role", "avg_headcount", "leavers_12m", "regrettable_leavers", "avg_salary", "time_to_fill_days", "ramp_months", "hiring_channel"]
DEFAULTS = {"currency": "EUR", "working_days_per_year": 220, "employer_overhead_pct": 20, "hiring_channels": {},
"interview_hours_per_hire": 12, "interviewer_hourly_cost": 50, "onboarding_cost_per_hire": 1500,
"offboarding_cost_per_leaver": 300, "vacancy_cost_pct_of_daily_pay": 50, "ramp_productivity_loss_pct": 50,
"high_turnover_pct": 25, "slow_fill_days": 60}
def load_assumptions(path):
a = dict(DEFAULTS)
if path:
with open(path, encoding="utf-8") as fh:
a.update(json.load(fh))
return a
def parse_rows(text):
reader = csv.DictReader(io.StringIO(text))
missing = [c for c in REQUIRED if c not in (reader.fieldnames or [])]
if missing:
raise ValueError("missing columns: " + ", ".join(missing))
return list(reader)
def money(x):
return round(x + 0.0, 2)
def cost_row(row, a):
"""Return the cost breakdown and flags for one CSV row, or raise ValueError for invalid data."""
try:
hc = float(row["avg_headcount"]); leavers = int(row["leavers_12m"]); regret = int(row["regrettable_leavers"])
salary = float(row["avg_salary"]); fill = float(row["time_to_fill_days"]); ramp = float(row["ramp_months"])
except (TypeError, ValueError):
raise ValueError("non-numeric value")
if hc <= 0 or salary <= 0 or leavers < 0 or regret < 0 or fill < 0 or ramp < 0:
raise ValueError("values must be positive (headcount and salary > 0)")
if regret > leavers:
raise ValueError("regrettable_leavers > leavers_12m")
if leavers > hc * 3:
raise ValueError("leavers_12m more than 3x headcount - check the data")
channel = (row.get("hiring_channel") or "").strip()
ch = a["hiring_channels"].get(channel)
if ch is None:
raise ValueError("unknown hiring_channel %r" % channel)
loaded = salary * (1 + a["employer_overhead_pct"] / 100.0)
daily = loaded / a["working_days_per_year"]
working_days_vacant = fill * 5.0 / 7.0
parts = {
"recruiting": salary * ch.get("fee_pct_of_salary", 0) / 100.0 + ch.get("fixed_cost", 0),
"interviewing": a["interview_hours_per_hire"] * a["interviewer_hourly_cost"],
"vacancy": working_days_vacant * daily * a["vacancy_cost_pct_of_daily_pay"] / 100.0,
"ramp_up": ramp / 12.0 * loaded * a["ramp_productivity_loss_pct"] / 100.0,
"onboarding": float(a["onboarding_cost_per_hire"]),
"offboarding": float(a["offboarding_cost_per_leaver"]),
}
per_leaver = sum(parts.values())
rate = 100.0 * leavers / hc
flags = []
if rate >= a["high_turnover_pct"]:
flags.append("T01 turnover %.1f%% >= %s%%" % (rate, a["high_turnover_pct"]))
if leavers >= 2 and regret / leavers > 0.5:
flags.append("T02 %d of %d leavers regrettable" % (regret, leavers))
if per_leaver >= 0.5 * salary:
flags.append("T03 cost per leaver %.0f%% of salary" % (100 * per_leaver / salary))
if fill >= a["slow_fill_days"]:
flags.append("T04 time to fill %g days >= %s" % (fill, a["slow_fill_days"]))
return {"team": row["team"], "role": row["role"], "avg_headcount": hc, "leavers_12m": leavers, "regrettable_leavers": regret,
"turnover_pct": round(rate, 1), "avg_salary": salary, "cost_per_leaver": money(per_leaver),
"cost_per_leaver_pct_salary": round(100 * per_leaver / salary, 1),
"breakdown_per_leaver": {k: money(v) for k, v in parts.items()},
"annual_cost": money(per_leaver * leavers), "regrettable_cost": money(per_leaver * regret), "flags": flags}
def analyze(rows, a, reduce_pct=None, program_cost=None):
teams, errors = [], []
for i, row in enumerate(rows, start=2):
try:
teams.append(cost_row(row, a))
except ValueError as e:
errors.append({"line": i, "team": row.get("team", ""), "error": "E01 " + str(e)})
total = sum(t["annual_cost"] for t in teams)
leavers = sum(t["leavers_12m"] for t in teams)
hc = sum(t["avg_headcount"] for t in teams)
summary = {"currency": a["currency"], "teams": len(teams), "avg_headcount": hc, "leavers_12m": leavers,
"turnover_pct": round(100.0 * leavers / hc, 1) if hc else 0.0, "annual_cost": money(total),
"regrettable_cost": money(sum(t["regrettable_cost"] for t in teams)),
"avg_cost_per_leaver": money(total / leavers) if leavers else 0.0,
"cost_by_part": {k: money(sum(t["breakdown_per_leaver"][k] * t["leavers_12m"] for t in teams)) for k in ["recruiting", "interviewing", "vacancy", "ramp_up", "onboarding", "offboarding"]}}
if reduce_pct is not None:
summary["scenario"] = {"reduce_pct": reduce_pct, "leavers_avoided": round(leavers * reduce_pct / 100.0, 1), "annual_saving": money(total * reduce_pct / 100.0)}
if program_cost is not None:
be = 100.0 * program_cost / total if total else None
summary["program"] = {"program_cost": money(program_cost), "break_even_reduce_pct": round(be, 1) if be is not None else None,
"break_even_leavers_avoided": round(program_cost / summary["avg_cost_per_leaver"], 1) if leavers else None}
if reduce_pct is not None:
summary["program"]["net_saving_at_reduce_pct"] = money(total * reduce_pct / 100.0 - program_cost)
teams.sort(key=lambda t: -t["annual_cost"])
return {"summary": summary, "teams": teams, "errors": errors}
def fmt_money(x, cur):
return "%s %s" % (cur, "{:,.0f}".format(x))
def render(res, fmt):
s, cur = res["summary"], res["summary"]["currency"]
if fmt == "json":
return json.dumps(res, indent=2)
if fmt == "csv":
out = io.StringIO(); w = csv.writer(out, lineterminator="\n")
w.writerow(["team", "role", "avg_headcount", "leavers_12m", "turnover_pct", "cost_per_leaver", "cost_per_leaver_pct_salary", "annual_cost", "regrettable_cost", "flags"])
for t in res["teams"]:
w.writerow([t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], t["cost_per_leaver"], t["cost_per_leaver_pct_salary"], t["annual_cost"], t["regrettable_cost"], "; ".join(t["flags"])])
return out.getvalue().rstrip("\n")
L = []
md = fmt == "md"
L.append(("## " if md else "") + "Turnover cost: %s per year (%d leavers, %.1f%% turnover, avg %s per leaver)" % (fmt_money(s["annual_cost"], cur), s["leavers_12m"], s["turnover_pct"], fmt_money(s["avg_cost_per_leaver"], cur)))
L.append(("- " if md else " ") + "Regrettable leavers cost: %s" % fmt_money(s["regrettable_cost"], cur))
L.append(("- " if md else " ") + "By part: " + ", ".join("%s %s" % (k, fmt_money(v, cur)) for k, v in s["cost_by_part"].items()))
if "scenario" in s:
sc = s["scenario"]
L.append(("- " if md else " ") + "Scenario: %g%% less turnover avoids %.1f leavers and saves %s per year" % (sc["reduce_pct"], sc["leavers_avoided"], fmt_money(sc["annual_saving"], cur)))
if "program" in s:
p = s["program"]
line = "Retention program %s/year breaks even at %.1f%% less turnover (%.1f leavers avoided)" % (fmt_money(p["program_cost"], cur), p["break_even_reduce_pct"], p["break_even_leavers_avoided"])
if "net_saving_at_reduce_pct" in p:
line += "; net %s at the scenario" % fmt_money(p["net_saving_at_reduce_pct"], cur)
L.append(("- " if md else " ") + line)
L.append("")
if md:
L.append("| Team | Role | Headcount | Leavers | Turnover | Cost per leaver | % of salary | Annual cost | Flags |")
L.append("|---|---|---|---|---|---|---|---|---|")
for t in res["teams"]:
L.append("| %s | %s | %g | %d | %.1f%% | %s | %.1f%% | %s | %s |" % (t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], fmt_money(t["cost_per_leaver"], cur), t["cost_per_leaver_pct_salary"], fmt_money(t["annual_cost"], cur), "<br>".join(t["flags"]) or "-"))
else:
for t in res["teams"]:
L.append("%-18s %-20s hc %-5g leavers %-3d turnover %5.1f%% per leaver %-12s (%5.1f%% of salary) annual %s" % (t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], fmt_money(t["cost_per_leaver"], cur), t["cost_per_leaver_pct_salary"], fmt_money(t["annual_cost"], cur)))
for f in t["flags"]:
L.append(" " + f)
for e in res["errors"]:
L.append(("- " if md else "") + "line %d %s: %s" % (e["line"], e["team"], e["error"]))
return "\n".join(L)
def self_test():
T = []
def check(name, cond): T.append((name, bool(cond)))
a = dict(DEFAULTS); a.update({"employer_overhead_pct": 0, "working_days_per_year": 200, "hiring_channels": {"fixed": {"fixed_cost": 1000}, "agency": {"fee_pct_of_salary": 20}},
"interview_hours_per_hire": 10, "interviewer_hourly_cost": 50, "onboarding_cost_per_hire": 1000, "offboarding_cost_per_leaver": 500,
"vacancy_cost_pct_of_daily_pay": 100, "ramp_productivity_loss_pct": 50, "high_turnover_pct": 25, "slow_fill_days": 60})
base = {"team": "T", "role": "R", "avg_headcount": "10", "leavers_12m": "2", "regrettable_leavers": "1", "avg_salary": "40000", "time_to_fill_days": "28", "ramp_months": "3", "hiring_channel": "fixed"}
r = cost_row(base, a)
b = r["breakdown_per_leaver"]
check("fixed channel recruiting cost", b["recruiting"] == 1000)
check("interview cost hours x rate", b["interviewing"] == 500)
check("vacancy: 28 calendar days = 20 working days x 200/day", b["vacancy"] == 4000)
check("ramp: 3/12 x 40000 x 50%", b["ramp_up"] == 5000)
check("cost per leaver sums parts", r["cost_per_leaver"] == 12000)
check("annual cost = per leaver x leavers", r["annual_cost"] == 24000)
check("turnover rate 20%", r["turnover_pct"] == 20.0)
check("no flags for moderate row", r["flags"] == [])
r2 = cost_row(dict(base, hiring_channel="agency", ramp_months="4"), a)
check("agency fee 20% of salary", r2["breakdown_per_leaver"]["recruiting"] == 8000)
check("T03 when cost >= 50% of salary", any(f.startswith("T03") for f in r2["flags"]))
a2 = dict(a, employer_overhead_pct=25)
check("overhead loads ramp cost", cost_row(base, a2)["breakdown_per_leaver"]["ramp_up"] == 6250)
r3 = cost_row(dict(base, leavers_12m="3", regrettable_leavers="2", time_to_fill_days="70"), a)
check("T01 at 30% turnover", any(f.startswith("T01") for f in r3["flags"]))
check("T02 when most leavers regrettable", any(f.startswith("T02") for f in r3["flags"]))
check("no T02 for a single regrettable leaver", not any(f.startswith("T02") for f in cost_row(dict(base, leavers_12m="1"), a)["flags"]))
check("T04 slow fill", any(f.startswith("T04") for f in r3["flags"]))
res = analyze([base, dict(base, regrettable_leavers="5")], a)
check("invalid regrettable > leavers gives E01", res["errors"] and res["errors"][0]["line"] == 3)
res = analyze([dict(base, hiring_channel="magic")], a)
check("unknown channel gives E01", "unknown hiring_channel" in res["errors"][0]["error"])
res = analyze([base, dict(base, team="U", leavers_12m="0", regrettable_leavers="0")], a, reduce_pct=25, program_cost=6000)
check("total over teams", res["summary"]["annual_cost"] == 24000)
check("scenario saving 25%", res["summary"]["scenario"]["annual_saving"] == 6000)
check("program break-even 25% and 0.5 leavers", res["summary"]["program"]["break_even_reduce_pct"] == 25.0 and res["summary"]["program"]["break_even_leavers_avoided"] == 0.5)
check("net saving 0 at break-even", res["summary"]["program"]["net_saving_at_reduce_pct"] == 0)
try:
parse_rows("team,role\nA,B\n"); check("missing columns rejected", False)
except ValueError:
check("missing columns rejected", True)
for n, ok in T:
print(("PASS " if ok else "FAIL ") + n)
p = sum(ok for _, ok in T)
print("%d/%d checks passed" % (p, len(T)))
return 0 if p == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Employee turnover cost calculator (stdlib only).")
ap.add_argument("csv", nargs="?")
ap.add_argument("--assumptions")
ap.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
ap.add_argument("--reduce-pct", type=float)
ap.add_argument("--program-cost", type=float)
ap.add_argument("--self-test", action="store_true")
o = ap.parse_args(argv)
if o.self_test:
return self_test()
if not o.csv:
ap.error("give a CSV file or --self-test")
try:
a = load_assumptions(o.assumptions)
with open(o.csv, encoding="utf-8-sig") as fh:
rows = parse_rows(fh.read())
except (OSError, ValueError) as e:
print("input error: %s" % e, file=sys.stderr)
return 2
res = analyze(rows, a, o.reduce_pct, o.program_cost)
print(render(res, o.format))
return 1 if res["errors"] or any(t["flags"] for t in res["teams"]) else 0
if __name__ == "__main__":
sys.exit(main())
Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
name: python-docstring-coverage-checker
description: Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
# Python Docstring Coverage Checker
You help Python developers, library maintainers and tech leads make their code explain itself. Missing or outdated docstrings slow down every new teammate, break generated API docs and make AI coding assistants guess. A docstring that documents a parameter the function no longer has is worse than none. You measure how much of the public API is documented, find docstrings that drifted from the code, and propose a realistic plan to close the gap without turning it into busywork.
You read code locally with the `ast` module and never import, run or upload it. Coverage is a guide: a short one-line docstring on an obvious helper is fine, and the team decides what "public" means for its project.
## Files in this skill
- `scripts/docstring_coverage.py` - walks files or folders (skips .git, venvs, build dirs), checks the module, public classes, functions and methods (`__init__` included, other dunders and `_private` names skipped unless `--include-private`); findings D01-D06; `--format text|md|json`, `--min-severity`, `--fail-under PCT` for CI, `--min-params N`; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/docstring-styles.md` - Google, NumPy and reST/Sphinx styles side by side, how the script recognises each, and how to pick one
- `references/what-to-document.md` - what a good docstring contains, what to leave out, and how to prioritise
- `templates/docstring-report.md` - the review you hand back
- `examples/shipping_rates.py` - a fictional, under-documented shipping rate module (37.5% coverage, a stale `insured` parameter); `examples/shipping_rates_documented.py` - the same code fully documented (100%, no findings)
## Workflow
### 1. Scope
Ask which package is the public API (installed library, internal service, scripts), which docstring style the project uses or wants, whether docs are generated (Sphinx, MkDocs) and whether a CI gate is wanted. Exclude tests, migrations, generated and vendored code.
### 2. Run the check
```
python3 scripts/docstring_coverage.py src/
python3 scripts/docstring_coverage.py src/ --min-severity medium
python3 scripts/docstring_coverage.py src/ --format md > docstrings.md
python3 scripts/docstring_coverage.py src/ --format json
python3 scripts/docstring_coverage.py src/ --fail-under 80 --min-severity high
python3 scripts/docstring_coverage.py --self-test
```
Exit code 0 = coverage at or above `--fail-under` and nothing at or above `--min-severity`, 1 = below threshold or findings, 2 = bad path or nothing parsable. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| D01 | high | public module, class, function or method without a docstring |
| D02 | medium | parameters missing from the docstring (when it has a parameter section, or the function has `--min-params` (3) or more parameters) |
| D03 | medium | docstring documents a parameter that is not in the signature (stale) |
| D04 | low | returns or yields a value but has no Returns/Yields section |
| D05 | low | raises an exception the docstring does not mention |
| D06 | low | summary line missing, over 88 characters or without a final period |
Coverage = documented objects / checked objects (modules, classes, functions, methods), overall, per kind and per file.
### 3. Interpret
- Fix D03 first: stale docs actively mislead readers and tools. They usually come from a renamed or removed parameter.
- Then D01 on the most used public entry points (what other modules or users import), not alphabetically.
- D02 on functions with many parameters matters more than D04/D06 polish.
- Read the flagged code before writing docs; if a function is hard to describe in one sentence, say so: it may need splitting rather than a longer docstring.
- Check for docstrings that are present but useless ("Does the thing.", repeating the function name); the script cannot judge meaning, you can.
### 4. Plan the fix
Group work into small pull requests per module, starting with the public API. Propose the style from `references/docstring-styles.md` that matches the project (do not mix styles), write two or three example docstrings yourself from the real code, and suggest a CI gate that starts at today's coverage and rises over time (for example `--fail-under 60` now, 80 next quarter), so new code is documented without blocking everyone.
### 5. Report
Fill `templates/docstring-report.md`: coverage summary, stale docs, top undocumented entry points, example docstrings, the plan and the CI suggestion, and the limits.
## Example
```
python3 scripts/docstring_coverage.py examples/shipping_rates.py
python3 scripts/docstring_coverage.py examples/shipping_rates_documented.py --fail-under 90
```
The first run reports 37.5% coverage (3/8), five D01 findings, a stale `insured` parameter and missing `express` on `RateCalculator.quote` (D03, D02), plus missing Returns and an undocumented `ValueError`. The documented version passes with 100% and exit code 0.
## Limits
- Static analysis only: it cannot tell whether a docstring is correct or helpful, only whether it exists and matches the signature.
- Parameter sections are recognised in Google, NumPy and reST styles; unusual custom formats may produce false D02/D03 findings.
- Raises detection only sees direct `raise` statements in the function, not exceptions from called code.
- Properties, overloads and setters are skipped; dataclass fields are not checked individually.
FILE:references/docstring-styles.md
# Docstring styles
Pick one style per project and stick to it. All three are understood by Sphinx (Google and NumPy via the napoleon extension) and by most editors and documentation tools.
## Google style
Readable in plain text, compact, good default for applications and most libraries.
```python
def quote(parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
```
## NumPy style
More vertical, popular in scientific Python (numpy, pandas, scipy). Good when types and shapes need explaining.
```python
def resample(values, factor):
"""Resample a series by an integer factor.
Parameters
----------
values : list of float
Input samples.
factor : int
How many input samples make one output sample.
Returns
-------
list of float
The resampled series.
"""
```
## reST / Sphinx field style
Common in older projects and in Sphinx-first documentation.
```python
def connect(host, port=5432):
"""Open a database connection.
:param host: Server host name.
:param int port: Server port.
:returns: An open connection.
:raises ConnectionError: If the server cannot be reached.
"""
```
## How the script recognises them
- Parameter sections: `Args:`, `Arguments:`, `Parameters:`, `Keyword Args:`, `Other Parameters:` (Google), `Parameters` followed by a dashed line (NumPy), and `:param name:` / `:param type name:` (reST). `*args` and `**kwargs` may be written with or without stars.
- Returns: `Returns:`, `Return:`, `Yields:`, NumPy `Returns` / `Yields` headings, `:returns:`, `:rtype:`, `:yields:`.
- Raises: `Raises:` sections, `:raises X:` fields, or simply the exception name anywhere in the docstring.
## Choosing
| Situation | Suggested style |
|---|---|
| New application or internal library | Google |
| Scientific / data code with arrays and shapes | NumPy |
| Existing Sphinx docs already using fields | reST |
| Mixed project | the style most existing docstrings use; convert the rest gradually |
Type hints in the signature do not replace a docstring: they say what type a value is, the docstring says what it means, its units, defaults and edge cases. When hints exist, leave the types out of the docstring to avoid them drifting apart.
FILE:references/what-to-document.md
# What to document (and what not)
## A good docstring
1. **Summary line**: one sentence in the imperative or descriptive mood, under 88 characters, ending with a period. "Return the cheapest zone for a parcel." not "This function is used to get zone."
2. **Details (optional)**: a short paragraph on behavior the name does not reveal: units, side effects (writes a file, sends an email, hits the network), caching, thread safety, performance characteristics.
3. **Parameters**: what each one means, its unit and allowed values, and what the default does. Skip obvious type repetition when there are type hints.
4. **Returns / Yields**: what comes back, including special values (None when not found, empty list).
5. **Raises**: exceptions callers are expected to handle, and when.
6. **Example (optional)**: a two-line usage example for public entry points, ideally as a doctest.
## Leave out
- Restating the code line by line or the function name in other words.
- History ("changed in March to fix bug 123"): that belongs in git and the changelog.
- Implementation details that will change often; document the contract, not the internals.
- TODOs: track them as issues.
## Priorities when coverage is low
1. Stale docs (D03): wrong information is worse than none.
2. Public entry points used by other modules, services or users (what `__init__.py` exports, CLI commands, API handlers).
3. Functions with many parameters or surprising behavior (side effects, units, None returns).
4. Classes: one paragraph on what the object represents and its lifecycle.
5. Module docstrings: one or two sentences on what lives in the file.
6. Polish (summary periods, Returns sections on obvious getters) last, ideally fixed while touching the code anyway.
## Coverage targets
- Libraries published for others: 90-100% of the public API.
- Internal services: 70-85% of public functions and classes, 100% of anything other teams call.
- Scripts and glue code: module docstring plus the main entry point.
Ratchet the CI threshold up from today's number instead of jumping to a target that blocks every pull request.
## Writing with an AI assistant
Generated docstrings are a good first draft, but always check them against the code: assistants happily document parameters the function does not have, invent exceptions or describe what the name suggests instead of what the code does. Re-run the checker afterwards to catch stale parameters.
FILE:templates/docstring-report.md
# Docstring review: {project or package}
**Scanned:** {paths} on {date} - {files} files, {objects} public objects
**Style:** {Google | NumPy | reST | mixed}
**Command:** `python3 scripts/docstring_coverage.py {paths} {options}`
## Summary
- Coverage: **{pct}%** ({documented}/{objects}); modules {m}%, classes {c}%, functions {f}%, methods {me}%
- Stale docstrings (D03): {n}
- Undocumented public objects (D01): {n}, of which {k} are main entry points
- One-sentence verdict: {e.g. "Core API mostly documented; billing module has stale parameters after the March refactor."}
## Fix first: stale or wrong docs
| Location | Object | Problem | Fix |
|---|---|---|---|
| {file:line} | `{name}` | {documents `insured`, not in signature} | {remove or rename to `express`} |
## Top undocumented entry points
| Location | Object | Why it matters | Suggested summary line |
|---|---|---|---|
| {file:line} | `{name}` | {called from 6 modules / public API} | {Return the cheapest zone for a parcel.} |
## Example docstrings (from the real code)
```python
{2-3 complete docstrings in the chosen style}
```
## Plan
1. {PR 1: fix all D03 + document public API of module X}
2. {PR 2: ...}
3. {Agree on the style in CONTRIBUTING.md}
## CI gate
`python3 scripts/docstring_coverage.py {src} --fail-under {today's pct rounded down} --min-severity high`, raise by {5-10} points per {month/quarter}.
## Deliberately left alone
- {e.g. private helpers, tests, generated code, obvious one-line properties}
## Limits
Static check only: presence and signature match, not correctness. Exceptions raised by called functions are not detected. Custom docstring formats may need manual review.
FILE:examples/shipping_rates.py
# Fictional example module for the docstring coverage checker: deliberately under-documented.
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Volumetric weight in kilograms"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
insured: Whether insurance is added.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:examples/shipping_rates_documented.py
"""Shipping rate calculation for parcels (fictional example, fully documented version)."""
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
"""A parcel with its real weight and outer dimensions."""
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Return the volumetric weight in kilograms.
Args:
divisor: Carrier divisor in cubic centimeters per kilogram.
Returns:
The volumetric weight as a float.
"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
"""Create a calculator with one carrier's tariff.
Args:
base_rate: Fixed price per parcel.
per_kg: Price per billable kilogram.
fuel_surcharge_pct: Fuel surcharge in percent, added at the end.
"""
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery (+50 percent) is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
"""Return standard prices for several parcels to the same zone.
Args:
parcels: Iterable of parcels.
zone: One of the keys of ZONES.
Returns:
A list of prices in the same order as the parcels.
"""
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
"""Find the zone with the lowest standard price for a parcel.
Args:
parcel: The parcel to ship.
calculator: A RateCalculator.
Returns:
A (zone, price) tuple.
"""
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:scripts/docstring_coverage.py
#!/usr/bin/env python3
"""docstring_coverage.py - measure docstring coverage and quality for Python code (standard library only).
Walks files or folders, parses each file with the ast module (code is never imported or run) and checks
every module, public class, public function and public method:
D01 high public module, class, function or method has no docstring
D02 medium parameters missing from the docstring (only when the docstring documents parameters,
or when the function has --min-params or more parameters)
D03 medium docstring documents a parameter that is not in the signature (stale)
D04 low function returns a value but the docstring has no Returns/Yields section
D05 low function raises exceptions that the docstring does not mention
D06 low summary line missing, longer than 88 characters or not ending with a period
Docstring sections are recognised in Google (Args:), NumPy (Parameters / ----------) and
reST/Sphinx (:param x:) styles.
Usage:
python3 docstring_coverage.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--fail-under PCT] [--include-private] [--min-params N]
python3 docstring_coverage.py --self-test
Exit code: 0 = coverage >= --fail-under and no findings at or above --min-severity,
1 = below threshold or findings present, 2 = bad path / nothing parsable.
"""
import argparse, ast, json, os, re, sys
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "node_modules", "build", "dist", "__pycache__", ".tox", ".mypy_cache", "site-packages"}
SEV = {"low": 1, "medium": 2, "high": 3}
CODES = {"D01": "high", "D02": "medium", "D03": "medium", "D04": "low", "D05": "low", "D06": "low"}
SECTION_PARAMS = re.compile(r"^\s*(Args|Arguments|Parameters|Params|Keyword Args|Keyword Arguments|Other Parameters)\s*:?\s*$", re.M)
SECTION_RETURNS = re.compile(r"^\s*(Returns?|Yields?)\s*:?\s*$|:returns?:|:rtype:|:yields?:", re.M)
SECTION_RAISES = re.compile(r"^\s*(Raises|Exceptions)\s*:?\s*$|:raises?\s", re.M)
REST_PARAM = re.compile(r":param\s+(?:[\w\[\], .]+\s+)?\*{0,2}(\w+)\s*:")
def documented_params(doc):
"""Return the set of parameter names a docstring documents, in any of the three styles."""
names = set(REST_PARAM.findall(doc))
lines = doc.splitlines()
i = 0
while i < len(lines):
if SECTION_PARAMS.match(lines[i]):
numpy = i + 1 < len(lines) and set(lines[i + 1].strip()) == {"-"}
j = i + (2 if numpy else 1)
base = None
while j < len(lines):
line = lines[j]
if not line.strip():
j += 1
continue
indent = len(line) - len(line.lstrip())
if numpy:
if j + 1 < len(lines) and set(lines[j + 1].strip()) == {"-"} and lines[j + 1].strip():
break # next numpy section
if base is None:
base = indent
if indent == base:
if re.match(r"\s*\*{0,2}\w+", line):
for part in line.split(":")[0].split(","):
p = part.strip().lstrip("*")
if p.isidentifier():
names.add(p)
else:
if re.match(r"^\s*[A-Z][A-Za-z ]+:\s*$", line) and (base is None or indent < base):
break # next google section
if base is None:
base = indent
if indent < base:
break
if indent == base:
m = re.match(r"\s*\*{0,2}(\w+)\s*(\([^)]*\))?\s*:", line)
if m:
names.add(m.group(1))
j += 1
i = j
continue
i += 1
return names
def signature_params(fn, is_method):
a = fn.args
params = [x.arg for x in getattr(a, "posonlyargs", [])] + [x.arg for x in a.args] + [x.arg for x in a.kwonlyargs]
if a.vararg:
params.append(a.vararg.arg)
if a.kwarg:
params.append(a.kwarg.arg)
if is_method and params and params[0] in ("self", "cls"):
params = params[1:]
return [p for p in params if p != "_"]
def _own_nodes(fn):
"""Walk a function body without descending into nested functions or classes."""
stack = [n for n in fn.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
while stack:
node = stack.pop()
yield node
for child in ast.iter_child_nodes(node):
if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
stack.append(child)
def returns_value(fn):
for n in _own_nodes(fn):
if isinstance(n, ast.Return) and n.value is not None and not (isinstance(n.value, ast.Constant) and n.value.value is None):
return True
if isinstance(n, (ast.Yield, ast.YieldFrom)):
return True
return False
def raised_names(fn):
out = set()
for n in _own_nodes(fn):
if isinstance(n, ast.Raise) and n.exc is not None:
e = n.exc.func if isinstance(n.exc, ast.Call) else n.exc
if isinstance(e, ast.Name):
out.add(e.id)
elif isinstance(e, ast.Attribute):
out.add(e.attr)
return out
def is_public(name):
return not name.startswith("_") or (name.startswith("__") and name.endswith("__") and name == "__init__")
def check_summary(doc):
first = doc.strip().splitlines()[0].strip() if doc.strip() else ""
if not first:
return "empty summary line"
if len(first) > 88:
return "summary line is %d characters (max 88)" % len(first)
if not first.endswith((".", "!", "?", ":")):
return "summary line does not end with a period"
return None
def analyze_source(src, path="<string>", include_private=False, min_params=3):
tree = ast.parse(src, filename=path)
items, findings = [], []
def add(code, obj, line, msg):
findings.append({"code": code, "severity": CODES[code], "path": path, "line": line, "object": obj, "message": msg})
mod_doc = ast.get_docstring(tree)
items.append({"path": path, "object": "<module>", "kind": "module", "line": 1, "documented": bool(mod_doc)})
if not mod_doc:
add("D01", "<module>", 1, "module has no docstring")
elif check_summary(mod_doc):
add("D06", "<module>", 1, check_summary(mod_doc))
def visit(body, prefix, in_class, parent_public):
for node in body:
if isinstance(node, ast.ClassDef):
public = parent_public and (include_private or is_public(node.name))
name = prefix + node.name
if public:
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": "class", "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "class has no docstring")
elif check_summary(doc):
add("D06", name, node.lineno, check_summary(doc))
visit(node.body, name + ".", True, public)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
public = parent_public and (include_private or is_public(node.name))
if any(isinstance(d, ast.Name) and d.id == "overload" or isinstance(d, ast.Attribute) and d.attr in ("overload", "setter", "deleter") for d in node.decorator_list):
continue
name = prefix + node.name
if not public:
continue
kind = "method" if in_class else "function"
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": kind, "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "%s has no docstring" % kind)
continue
params = signature_params(node, in_class)
documented = documented_params(doc)
has_section = bool(documented) or bool(SECTION_PARAMS.search(doc))
if has_section or len(params) >= min_params:
missing = [p for p in params if p not in documented]
if missing:
add("D02", name, node.lineno, "parameters not documented: " + ", ".join(missing))
stale = sorted(documented - set(params) - {"self", "cls"})
if stale:
add("D03", name, node.lineno, "docstring documents parameters not in the signature: " + ", ".join(stale))
if returns_value(node) and not SECTION_RETURNS.search(doc) and node.name != "__init__":
add("D04", name, node.lineno, "returns a value but the docstring has no Returns/Yields section")
raised = raised_names(node)
undocumented = sorted(r for r in raised if r not in doc)
if undocumented:
add("D05", name, node.lineno, "raises without mention in the docstring: " + ", ".join(undocumented))
s = check_summary(doc)
if s:
add("D06", name, node.lineno, s)
visit(tree.body, "", False, True)
return items, findings
def iter_files(paths):
for p in paths:
if os.path.isfile(p):
yield p
elif os.path.isdir(p):
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
else:
raise FileNotFoundError(p)
def summarize(items):
by_kind = {}
for it in items:
k = by_kind.setdefault(it["kind"], [0, 0])
k[0] += 1
k[1] += it["documented"]
total = len(items)
doc = sum(it["documented"] for it in items)
return {"objects": total, "documented": doc, "coverage_pct": round(100.0 * doc / total, 1) if total else 100.0,
"by_kind": {k: {"objects": v[0], "documented": v[1], "coverage_pct": round(100.0 * v[1] / v[0], 1)} for k, v in sorted(by_kind.items())}}
def render(fmt, summary, findings, errors, per_file):
if fmt == "json":
return json.dumps({"summary": summary, "files": per_file, "findings": findings, "parse_errors": errors}, indent=2)
out = []
if fmt == "md":
out.append("## Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
out.append("")
out.append("| Kind | Documented | Coverage |")
out.append("|---|---|---|")
for k, v in summary["by_kind"].items():
out.append("| %s | %d/%d | %.1f%% |" % (k, v["documented"], v["objects"], v["coverage_pct"]))
out.append("")
if findings:
out.append("| Code | Severity | Location | Object | Finding |")
out.append("|---|---|---|---|---|")
for f in findings:
out.append("| %s | %s | %s:%d | `%s` | %s |" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
else:
out.append("No findings at the selected severity.")
else:
out.append("Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
for k, v in summary["by_kind"].items():
out.append(" %-8s %d/%d (%.1f%%)" % (k, v["documented"], v["objects"], v["coverage_pct"]))
for pf in per_file:
out.append(" file %s: %.1f%% (%d/%d)" % (pf["path"], pf["coverage_pct"], pf["documented"], pf["objects"]))
out.append("")
for f in findings:
out.append("%s %-6s %s:%d %s - %s" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
if not findings:
out.append("No findings at the selected severity.")
for e in errors:
out.append("PARSE ERROR %s: %s" % (e["path"], e["error"]))
return "\n".join(out)
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
src = '''"""Module summary."""
def a(x, y):
"""Add two numbers.
Args:
x: first.
y (int): second.
Returns:
The sum.
"""
return x + y
def b(x):
return x
'''
items, f = analyze_source(src)
codes = [x["code"] for x in f]
check("google style fully documented gives no finding for a", not [x for x in f if x["object"] == "a"])
check("missing docstring gives D01", ("D01", "b") in [(x["code"], x["object"]) for x in f])
check("coverage counts module and functions", summarize(items)["coverage_pct"] == 66.7)
items, f = analyze_source('"""M."""\ndef c(a, b):\n """Do it.\n\n Args:\n a: one.\n """\n pass\n')
check("missing param gives D02", [x["message"] for x in f if x["code"] == "D02"] == ["parameters not documented: b"])
items, f = analyze_source('"""M."""\ndef c(a):\n """Do it.\n\n Args:\n a: one.\n old: gone.\n """\n')
check("stale param gives D03", any(x["code"] == "D03" and "old" in x["message"] for x in f))
numpy = '"""M."""\ndef n(a, b):\n """Numpy style.\n\n Parameters\n ----------\n a : int\n One.\n b : str\n Two.\n\n Returns\n -------\n int\n """\n return 1\n'
items, f = analyze_source(numpy)
check("numpy style params and returns recognised", not f)
rest = '"""M."""\ndef r(a, b):\n """Rest style.\n\n :param a: one.\n :param int b: two.\n :returns: value.\n :raises ValueError: bad.\n """\n if a:\n raise ValueError("x")\n return a\n'
items, f = analyze_source(rest)
check("rest style params, returns and raises recognised", not f)
items, f = analyze_source('"""M."""\ndef s(a):\n """Short."""\n return a * 2\n')
check("return without Returns section gives D04", any(x["code"] == "D04" for x in f))
check("one short param below --min-params gives no D02", not any(x["code"] == "D02" for x in f))
items, f = analyze_source('"""M."""\ndef g(a):\n """Get."""\n raise KeyError(a)\n')
check("undocumented raise gives D05", any(x["code"] == "D05" and "KeyError" in x["message"] for x in f))
items, f = analyze_source('"""M."""\ndef h():\n """no period here"""\n')
check("summary without period gives D06", any(x["code"] == "D06" for x in f))
items, f = analyze_source('def _p():\n pass\nclass _Q:\n def m(self):\n pass\n')
check("private function and class skipped, module flagged", [x["object"] for x in f] == ["<module>"])
items, f = analyze_source('def _p():\n pass\n', include_private=True)
check("--include-private checks private names", any(x["object"] == "_p" for x in f))
cls = '"""M."""\nclass K:\n """A class."""\n def __init__(self, a, b, c):\n """Create it."""\n def run(self):\n """Run it."""\n def __repr__(self):\n return "K"\n'
items, f = analyze_source(cls)
check("__init__ with 3 params gives D02, self excluded", any(x["code"] == "D02" and x["object"] == "K.__init__" and "self" not in x["message"] for x in f))
check("dunder methods other than __init__ are skipped", not any(x["object"] == "K.__repr__" for x in f))
items, f = analyze_source('"""M."""\ndef outer():\n """Outer."""\n def inner():\n return 1\n return None\n')
check("nested return does not count for outer", not any(x["code"] == "D04" for x in f))
items, f = analyze_source('"""M."""\ndef gen(n):\n """Generate.\n\n Yields:\n Numbers.\n """\n yield n\n')
check("Yields section satisfies D04", not f)
items, f = analyze_source('"""M."""\ndef v(*args, **kwargs):\n """Var.\n\n Args:\n *args: values.\n **kwargs: options.\n """\n')
check("*args and **kwargs documented with stars", not f)
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
passed = sum(ok for _, ok in T)
print("%d/%d checks passed" % (passed, len(T)))
return 0 if passed == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Docstring coverage and quality checker (stdlib only).")
ap.add_argument("paths", nargs="*")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--min-severity", choices=list(SEV), default="low")
ap.add_argument("--fail-under", type=float, default=0.0, help="minimum coverage percent (default 0)")
ap.add_argument("--include-private", action="store_true")
ap.add_argument("--min-params", type=int, default=3, help="require a parameter section from this many parameters (default 3)")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.paths:
ap.error("give at least one path or --self-test")
try:
files = list(iter_files(a.paths))
except FileNotFoundError as e:
print("no such path: %s" % e, file=sys.stderr)
return 2
all_items, findings, errors, per_file = [], [], [], []
for p in files:
try:
with open(p, encoding="utf-8") as fh:
items, f = analyze_source(fh.read(), p, a.include_private, a.min_params)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append({"path": p, "error": str(e).splitlines()[0]})
continue
all_items += items
findings += f
s = summarize(items)
per_file.append({"path": p, "objects": s["objects"], "documented": s["documented"], "coverage_pct": s["coverage_pct"]})
if not all_items:
print(render(a.format, summarize([]), [], errors, []))
return 2
shown = [f for f in findings if SEV[f["severity"]] >= SEV[a.min_severity]]
shown.sort(key=lambda f: (-SEV[f["severity"]], f["path"], f["line"], f["code"]))
summary = summarize(all_items)
summary["fail_under"] = a.fail_under
print(render(a.format, summary, shown, errors, per_file))
return 1 if shown or summary["coverage_pct"] < a.fail_under else 0
if __name__ == "__main__":
sys.exit(main())

Photoreal cozy dusk inside a quiet café: a glass of amber tea with a thin ribbon of steam on a wooden window ledge beside a book, raindrops running down the pane and a blurred blue-hour street glowing with warm bokeh. Step 1 of the Rainy Café Window workflow.
A photorealistic close-up photograph taken inside a quiet café at dusk, looking out through a large rain-covered window. On the wooden window ledge in the foreground stands a clear glass cup of amber black tea on a small saucer, with a thin ribbon of steam rising from it, next to a closed hardcover book with a linen bookmark and a small ceramic jar of sugar cubes. The window glass is covered in raindrops of many sizes; several larger drops leave thin wavy trails as they run down the pane. Outside, softly out of focus, an empty evening street glows in blue-hour light, with warm round bokeh from street lamps, shop signs blurred beyond recognition and the faint red and white lights of distant traffic. Inside, warm tungsten light from a lamp to the right falls on the cup and the ledge, making the tea glow and the drops on the glass sparkle. 50 mm lens at table height, shallow depth of field: the cup, the steam and the nearest raindrops tack-sharp, the street a dreamy blur of warm and cool lights. A calm, cozy, reflective mood, contrast between the cold blue evening outside and the warm interior. No people, no animals, no readable text or logos. Widescreen 16:9.

A still-life photo of five hand-decorated Ukrainian pysanky eggs with fine wax-resist folk patterns (star rosette, wheat and pine, meanders, sun spiral, dotted grids) in a willow basket on linen, with a kistka stylus, beeswax, a candle and dye jars in soft window light.
A still-life photograph of five hand-decorated Ukrainian pysanky eggs made with the traditional wax-resist method, arranged in a shallow handwoven willow basket on an unbleached linen cloth. Each egg carries a different geometric folk pattern drawn in fine, crisp lines: an eight-pointed star rosette in white and yellow on deep red, wheat ears and pine branches in gold and green on black, a band of endless meanders and little triangles in orange and red, a sun motif with spiraling rays on rich blue, and dotted grids with tiny crosses and diamonds on burgundy. The lines are slightly uneven in places, showing the handwork, with small glossy and matte areas on the dyed shells. Beside the basket lie the tools of the craft: a traditional kistka stylus with a little brass funnel, a beeswax block, a thin beeswax candle with a soft flame, and three small glass jars of dye in red, yellow and blue. A dried sprig of wheat lies across the cloth. Soft window daylight from the left, gentle shadows, warm natural colors, close-up with shallow depth of field so the front egg's patterns are tack-sharp and the jars fall softly out of focus. No people, no hands, no text or letters on the eggs. Landscape 4:3.

A macro studio photo of a vintage snow globe: a tiny winter village with a lit white chapel, snowy timber cottages and frosted firs inside the glass, snowflakes swirling, a turned wooden base with a brass band, warm window glow and string-light bokeh on a dark winter night.
A close-up studio photograph of a vintage glass snow globe on a dark walnut shelf. Inside the clear water-filled dome sits a tiny handmade winter village: a small white chapel with a slim steeple and warm yellow light glowing from its arched windows, a pair of little timber cottages with snow-covered roofs and glowing windows, a few frosted fir trees and a narrow path winding up a snowy hill. Fine white snowflakes swirl gently through the water, a few settling on the roofs. The globe stands on a turned wooden base with a thin brass band, slightly worn at the edges. Soft curved reflections and a warm highlight bend across the glass; the glowing windows cast a faint golden light into the snow inside. Behind the globe, out of focus, a dark wintry window with blurred warm string-light bokeh. Warm low-key lighting from the side, deep blue and charcoal shadows, a cozy, nostalgic holiday mood. Macro lens, shallow depth of field with the chapel and cottages tack-sharp through the glass, slight refraction at the dome's edges, rich contrast between warm window light and cool snow. No people, no figures inside the globe, no readable text or logos. Portrait 3:4.
Plan an inclusive end-of-year office party as one JSON object: concept, date and run of show, venue checks, food for every diet, optional activities, remote colleagues, recognition and gifts, a budget that adds up, timeline, invitation texts, safety, risks and a day-of checklist.
1{2 "role": "You are an experienced office manager and people-operations lead who plans inclusive, well-run end-of-year team celebrations on a sensible budget.",3 "task": "Plan the company's end-of-year holiday party and return the full plan as one valid JSON object that follows output_format exactly.",4 "inputs": {5 "company": "${company:a 60-person software company with one office and 15 remote employees}",6 "headcount_expected": "${headcount:55 in person, 15 joining online}",7 "date_window": "${date_window:a weekday evening between December 10 and December 19}",8 "budget_total": "${budget:6000 EUR including venue, food, drinks and gifts}",9 "location": "${location:Berlin city center}",10 "format_preference": "${format:dinner and games at a rented venue, with a short online part for remote colleagues}",...+121 more lines
Get productive in an unfamiliar legacy codebase safely: orientation questions, a day-one safety checklist, a reading strategy from entry points and git churn, a one-page architecture sketch, a careful plan for your first task, a questions log and a two-week ramp-up plan.
Act as a Legacy Codebase Onboarding Guide. You are a patient senior engineer who has joined many unfamiliar, poorly documented codebases and knows how to become productive in one without breaking things. I have just joined a team (or inherited a project) and need to understand an existing codebase quickly and safely. My situation: - Codebase: a 9-year-old monolith web app with a REST API, background jobs and a relational database - Main languages and frameworks: Python, Django, Celery, PostgreSQL, some jQuery on the frontend - Size and age: about 250k lines, 40 contributors over the years, 5 still active - State of docs and tests: an outdated README, a few wiki pages, patchy unit tests, no architecture diagram - My role and experience: backend developer, 4 years of experience, new to this domain - My first assignment: fix a bug where invoice emails are sometimes sent twice - Time I have to ramp up: 2 weeks - People I can ask: one tech lead with little free time, a product manager, a retired original author reachable by email Guide me through the onboarding in this order: 1. Orientation questions. Before giving a plan, ask me up to 5 short questions whose answers would change your advice the most (for example how deployments happen, whether there is a staging environment, who is on call). If I say "skip", continue with sensible assumptions and list them. 2. Day 1 safety checklist. What to set up and verify before touching code: getting the app and tests running locally, read-only access to logs and the production database replica, where secrets live and what never to commit, how to run one test, how a change reaches production and how it is rolled back. 3. Build a mental map. Give me a step-by-step reading strategy that does not try to read everything: start from entry points (routes, CLI commands, job schedulers, message consumers), follow one real request end to end, find the core domain models and the 5-10 files that change most often (show git commands such as `git log --format=format: --name-only | sort | uniq -c | sort -rn | head -30`), identify the oldest and scariest areas, and note configuration and feature flags. Tell me what to write down while reading. 4. Architecture sketch. Show me how to draw a one-page map of the system as a text diagram: components, data stores, external services, queues and the direction of calls. Give a template I can fill in and tell me which questions to ask the tech lead to confirm it in 20 minutes. 5. First task plan. For my first assignment, explain how to find the relevant code (search terms, logs, tracing one example), how to reproduce the problem, how to write a characterization test that pins the current behavior before changing it, how to keep the change small, and what to check in review. Point out typical legacy traps: hidden side effects, global state, implicit ordering, timezone and encoding issues, code paths only used by one big customer, and dead code that is not actually dead. 6. Questions log. Give me a format for a running questions log (question, where I looked, answer, who answered, date) and explain how to batch questions so I respect busy colleagues' time. 7. Two-week ramp-up plan. A day-by-day plan for 2 weeks with concrete goals (for example "Day 3: trace the checkout request end to end and draw it"), each with a small output I can show my lead. 8. Leave it better. Suggest 3-5 small, low-risk improvements a newcomer is perfectly placed to make (README setup steps, a glossary of domain terms, a diagram, a missing test, removing a confusing warning) and how to propose them without sounding critical of the people who built the system. Rules: - Be practical and specific to my stack; show real commands and file patterns where useful, but never invent facts about my codebase: when something depends on code you have not seen, say what to look for instead. - Prefer safe, reversible steps; flag anything that could affect production data or customers. - Keep each section short and scannable, with checklists where they help. - End with the 3 things I should do first tomorrow morning.
I have received the marks from my lecturer on the research proposal. Out of 30 total marks, I obtained only 26.5 marks. Among the lowest compare to others. He does provide me the feedback as per attachment. You as best PhD lecturer should finetune the submitted research proposal version as per attachement so that I can score as high as full marks.
I have received the marks from my lecturer on the research proposal. Out of 30 total marks, I obtained only 26.5 marks. Among the lowest compare to others. He does provide me the feedback as per attachment. You as best PhD lecturer should finetune the submitted research proposal version as per attachement so that I can score as high as full marks.
Generate structured camera movement, subject motion, lighting continuity, and pacing instructions for short AI video generators. Designed for Motion Control AI workflows on https://goshortsai.com/motion-control-ai (works with Veo 3.1, Kling V3, Sora 2, and Wan 2.7).
Act as a senior cinematography and AI video motion director. Given a still reference image described as a studio product shot of a minimalist smartwatch on dark slate and a desired mood of sleek commercial luxury, generate a concise 4-to-6 second image-to-video motion prompt containing: 1. Camera movement (e.g., slow 15-degree orbital push-in, locked tripod macro pan, gentle dolly out) 2. Primary subject motion (natural physics, micro-movements, reflections) 3. Environmental motion (subtle dust motes, soft rim light sweep, fabric or foliage drift) 4. Continuity guardrails (preserve subject identity, no warping, smooth 24fps pacing) Output a single ready-to-paste prompt under 80 words optimized for Motion Control AI tools such as https://goshortsai.com/motion-control-ai.
Build your custom learning curriculum:
I want to self-educate on topics that help me solve the biggest problems I am currently facing. No shelf-help, no learning for the sake of learning. Use everything you know about me, then interview me to figure out where learning something new would have the biggest impact. Then do a deep research project to build me a list of resources to learn from. I believe in just-in-time learning, not just-in-case, only recommend things I can apply immediately. Don't give me the most popular resources. Give me the ones that fit my current struggles. Deliver it as a spreadsheet with: the resource, format (book, podcast, creator, course), the link, and why you picked it for me. If anything's unclear, ask before you start.