Role from Awesome ChatGPT Prompts (
prompts.csv, CC0-1.0). The prompt is the persona's instructions; ratings and installs below are from this marketplace.
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 fetchinto$W, read-onlygit(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(onlygh apiGETs), andgh repo listto 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.
Workflow
- Collect inputs — follow 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/reposand write$W/polyrepo-tax.config.json. - CI minutes (optional) — if the repos are on GitHub and
gh auth statussucceeds, runfetch-ci.mjsas described in inputs.md. Otherwise skip it: the analyzer usesciMinutesPerCommitand marks CI asassumed. - Analyze —
node "$S/scripts/analyze.mjs" --config "$W/polyrepo-tax.config.json" --out <report dir>. Signal definitions are in references/signals.md; the cost formulas are in references/cost-model.md. - 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 toexcludeCommitsin$W/overrides.jsonand rerun step 3 with"overrides": "overrides.json"in the config. Tell the user how many you excluded and why. - Migration plan — follow references/migration.md to turn the report's
migrationsection into a phased plan. Write it tomigration-plan.mdin the report dir, append it to the Markdown report, and runnode "$S/scripts/render-html.mjs" <report dir>/polyrepo-tax-report.jsonso the HTML report includes it. - Present — follow 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.
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.
{
"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:
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 (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
noonly 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):
- Target layout and tooling — the tool options table, then the pick:
migration.recommendedToolis the stack-based default. If the team chooses another fitting tool from the table, use that one. Proposeapps/${repo}for deployables andpackages/${name}for libraries. If one repo already uses Nx, Turborepo or Bazel, build on it rather than adding a second tool. - 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.
- Align each entry in
- 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 withgit 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.
- Nx:
- Phase 2+ — the next clusters in order of weight.
- Verify — run the
monorepo-doctorskill on the new monorepo for boundaries, cycles, caching, CI coverage and test leakage. Usemonorepo-boundaries-cleanupto pay down what it finds. - 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 withrender-html.mjsafter writingmigration-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.
- 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.
- One line: expected cost for the window and annualized range, split into developer and CI money.
- Bug counts by confidence, and the 3 strongest bugs, each with its commit evidence.
- The two cost drivers that dominate, and the assumption each depends on, so the user knows which number to challenge.
- 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 frommigration.toolOptionswith their ratings and the monorepo.tools source. The full table is in the report. - 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.jsonupwards. 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
versionfield of an internal package that another analysed repo consumes, or a tagvX.Y.Z/name@X.Y.Z. Tags only date releases; costed releases come from version commits. Packages listed inpublicPackages(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(/^\srevert\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}\n${c.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}\n${c.body}.toLowerCase();
const mentions = prior.find((b) => text.includes(b.pkg.toLowerCase()) || (b.pkg.split('/').pop().length >= 4 && new RegExp(\\b${b.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.to}${mentions ? ' and names that package' : COMPAT.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: M
Truncated - read the full file at https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv.
