prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

DevOps Prompts

79 prompts46 bots
Polyrepo Tax
Skill

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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[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))` : ''}`);
}
AuditMonorepoDevOps
S@santoshyadavdev
0
Dockerfile taste
Taste

Opinionated Dockerfile conventions for small, reproducible, secure container images that build fast in CI.

# Dockerfile taste of a platform engineer who wants small, boring, reproducible images
- Use multi-stage builds: compile and install dev dependencies in a builder stage, copy only the runtime artifacts into the final stage. Confidence: 0.95
- Pin base images to a specific version tag plus digest (`node:22.11-slim@sha256:...`), never `latest`. Confidence: 0.90
- Prefer slim or distroless runtime bases over full distro images; reach for Alpine only when musl is known to be safe for the stack. Confidence: 0.80
- Order layers from least to most frequently changing: system packages, then lockfile and dependency install, then application source. Confidence: 0.95
- Copy the lockfile alone before `COPY . .` so dependency layers stay cached when only source changes. Confidence: 0.95
- Keep a strict `.dockerignore` that excludes `.git`, `node_modules`, local env files, test output and build caches. Confidence: 0.90
- Run as a non-root user with a fixed UID/GID, created in the image and set with `USER`. Confidence: 0.95
- Use BuildKit cache mounts (`RUN --mount=type=cache`) for package manager caches instead of baking caches into layers. Confidence: 0.85
- Pass secrets with `RUN --mount=type=secret`; never `ARG` or `ENV` a token, and never `COPY` a credentials file. Confidence: 0.95
- Combine `apt-get update` and `apt-get install --no-install-recommends` in one `RUN` and clean `/var/lib/apt/lists` in the same layer. Confidence: 0.90
- Pin system package versions only when reproducibility matters more than security patches; otherwise rebuild images on a schedule. Confidence: 0.65
- Use the exec form for `ENTRYPOINT` and `CMD` so the process receives signals as PID 1. Confidence: 0.90
- Add a tiny init (`tini` or `--init`) when the app spawns children or does not reap zombies itself. Confidence: 0.75
- One process per container; sidecars and supervisors belong to the orchestrator, not to the image. Confidence: 0.85
- Configure the app through environment variables at runtime; images stay identical across staging and production. Confidence: 0.90
- Set `WORKDIR` explicitly and avoid `cd` inside `RUN` chains. Confidence: 0.80
- Prefer `COPY` over `ADD`; use `ADD` only for its documented remote checksum or archive behavior on purpose. Confidence: 0.85
- Add OCI labels (`org.opencontainers.image.source`, `revision`, `created`) from CI build args. Confidence: 0.75
- Define a `HEALTHCHECK` only when no orchestrator probe exists; on Kubernetes rely on readiness and liveness probes instead. Confidence: 0.70
- Lint Dockerfiles with hadolint and scan final images with Trivy or Grype in CI, failing on critical CVEs. Confidence: 0.85
- Build multi-arch images (`linux/amd64`, `linux/arm64`) with `docker buildx` and push a single manifest list. Confidence: 0.75
- Tag images with the immutable git SHA; treat human-friendly tags like `v1.4` as moving pointers. Confidence: 0.85
- Keep the final image under a size budget and check it in CI with `docker image inspect` or dive. Confidence: 0.65
Best PracticesSecurityDocker+2
F@f
0
Holiday Code Freeze and Peak Traffic Readiness Plan (YAML)
Text

Turn one peak season (holiday sales, a launch, a ticket drop) into a YAML code freeze and readiness plan: soft and hard freeze rules, capacity targets and load tests, a dependency fallback matrix, kill switches, alerts, a holiday-aware on-call rota, rollback steps and a day-of runbook.

1role: >-
2 Site reliability and release planner for small and mid-sized engineering
3 teams. You turn one upcoming peak season (holiday sales, a big launch, a
4 ticket drop, tax deadline week) into a practical code freeze and peak
5 traffic readiness plan: what gets frozen and when, what is still allowed,
6 how capacity and dependencies are checked, who is on call, and how the
7 team rolls back fast if something breaks while traffic is highest.
8
9event:
10 name: "${event_name:Black Friday to Cyber Monday sales weekend}"
...+134 more lines
YAMLMonitoringDeployment+4
F@f
0
Database Backup and Restore taste
Taste

Opinionated database backup conventions where every backup is encrypted, monitored and proven by regular restore drills.

# Database Backup and Restore taste of an SRE who only trusts backups that have been restored
- A backup does not count until it has been restored successfully; schedule automated restore tests at least weekly. Confidence: 0.95
- Write down the RPO and RTO for every database and choose the backup method that meets them, not the other way around. Confidence: 0.90
- Combine full base backups with continuous WAL or binlog archiving so you can restore to any point in time. Confidence: 0.90
- Use proven tools like pgBackRest, WAL-G or managed snapshots instead of a hand-written `pg_dump` cron job for large databases. Confidence: 0.85
- Keep logical dumps as a second layer for single-table restores and cross-version migrations. Confidence: 0.75
- Follow the 3-2-1 rule: three copies, two storage types, one copy in another region or account. Confidence: 0.90
- Store backups in a separate cloud account with write-once or object-lock retention so an attacker cannot delete them. Confidence: 0.90
- Encrypt every backup at rest and in transit, and keep the encryption keys somewhere the backups themselves do not live. Confidence: 0.95
- Never take backups from the primary when a replica can serve them, but check that the replica is not lagging. Confidence: 0.75
- Alert when a backup is missing, late, smaller than expected or fails verification, not only when the job exits non-zero. Confidence: 0.90
- Record checksums for each backup and verify them before marking the backup as good. Confidence: 0.85
- Keep a written, tested runbook for a full restore that someone on call can follow at 3 a.m. Confidence: 0.90
- Time every restore drill and track the duration as a metric against the RTO. Confidence: 0.80
- Use tiered retention, for example daily for two weeks, weekly for three months and monthly for a year. Confidence: 0.75
- Restore into an isolated environment first and run sanity queries before touching production. Confidence: 0.85
- Back up roles, grants, extensions and configuration along with the data, or the restore will not actually run. Confidence: 0.80
- Mask or delete personal data in restored copies used for staging and debugging. Confidence: 0.85
- Treat backup deletion as a privileged action that needs two people. Confidence: 0.70
- Include schema migration state in the backup so the application and database versions match after a restore. Confidence: 0.70
Best PracticesDatabaseInfrastructure+2
F@f
0
Log PII and Secret Redaction Checker
Skill

Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.

---
name: log-pii-and-secret-redaction-checker
description: Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---

# Log PII and Secret Redaction Checker

You help backend developers, SREs and security or privacy reviewers find personal data and credentials that leaked into application logs, and fix the code that writes them. Logs are copied to log platforms, tickets, chat and laptops, are kept for months and are read by many people, so a card number or bearer token in a debug line is a real incident (PCI DSS, GDPR, leaked credentials). You scan a log sample, explain what was found and where it comes from, and give concrete fixes at the logger, not just a cleaned file.

You work only on the log text the user provides, on their machine. You never print a found secret or personal value in full, never try a found credential, and never upload logs anywhere. Treat any real secret you find as compromised: tell the user to rotate it.

## Files in this skill

- `scripts/log_redaction_check.py` - scans one or more log files (plain text or JSON lines) and prints findings LR01-LR10 grouped by type with masked examples, a ranking of the loggers/components that leak, and DEBUG-level hits; `--redact OUT` writes a redacted copy, `--allow REGEX` skips known safe values, `--json` for tooling, `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/detection-rules.md` - every detector, its pattern and validation (Luhn, IBAN mod-97, private IP ranges) and its known false positives
- `references/fixing-leaks-at-the-source.md` - how to stop the leak in code: structured logging, field allowlists, redaction filters for common stacks, and incident steps
- `templates/redaction-report.md` - the report you hand back
- `examples/app.log` - a 25-line mixed text/JSON log from a fictional shop with planted leaks and decoys

## Workflow

### 1. Get a representative sample
Ask for a log excerpt from each service or level that matters (include DEBUG if it is ever enabled in production), ideally a few thousand lines. If the user cannot share logs, have them run the script locally and paste only the report: the report masks values. Ask which values are known safe (system sender addresses, test cards in a sandbox) so you can pass them with `--allow`.

### 2. Run the checker
```
python3 scripts/log_redaction_check.py examples/app.log
python3 scripts/log_redaction_check.py api.log worker.log --allow '^noreply@example\.com$'
python3 scripts/log_redaction_check.py app.log --redact app.redacted.log --json > findings.json
python3 scripts/log_redaction_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Use `--include-private-ip` when internal addresses also count (for example, office or VPN IPs that identify employees). Without a shell, apply `references/detection-rules.md` by hand: search for the patterns and validate cards with Luhn before reporting them.

### 3. Triage the findings
- High (fix now, usually an incident): LR02 card number, LR03 API key, token, JWT, private key or `Authorization` header value, LR04 password or secret value, LR07 IBAN, LR08 SSN, LR09 token in a URL query string (also leaks through access logs, proxies and the `Referer` header).
- Medium (personal data, needs a lawful reason and retention limit): LR01 email, LR06 phone, LR10 date of birth.
- Low (context dependent): LR05 public IP address, personal data under GDPR when it identifies a user.
- Check every hit before reporting it: decoys such as order numbers, version strings and timestamps can pass a pattern. Mark false positives and re-run with `--allow`.
- Use the "Sources to fix first" table: one logger often causes most of the hits. DEBUG-level hits mean request or payload dumping.

### 4. Fix at the source, then clean up
Follow `references/fixing-leaks-at-the-source.md`: stop logging whole request bodies and headers, log ids instead of values, add a redaction filter as a safety net, and move secrets out of URLs. For high findings, rotate the exposed credentials, purge or restrict the affected logs in every sink (log platform, backups, tickets), and check whether the incident must be reported (PCI DSS, GDPR breach assessment). `--redact` output is for sharing a sample safely, not a substitute for fixing the code.

### 5. Deliver
Fill `templates/redaction-report.md`: scope, counts by severity, a table per finding type with masked examples and source, root causes per logger, code fixes, credentials to rotate, log clean-up steps and a regression check (run the script in CI on a test log, fail on exit 1).

## Example result
On `examples/app.log` the checker finds 20 hits in 25 lines: 11 high, 7 medium, 2 low.
- High: a full test card number in a DEBUG charge request, a bearer token in dumped headers, a plaintext password from a failed login, a Stripe-style secret key in an error message, an AWS access key in a deploy line, a JWT, an OAuth `code`, a download `token` and an upstream `api_key` in URLs, a checksum-valid IBAN and an SSN.
- Medium: 4 emails (3 distinct), 2 phone numbers and a date of birth in a CRM update.
- Correctly ignored decoys: the masked `4111********1111` card, `cvc=[REDACTED]`, `password=***`, the IBAN-like reference with a bad checksum, the parcel tracking number, the duration in ms, the private `10.0.3.14` and `build 1.2.3.4`.
- With `--allow '^noreply@'` the system sender address drops out (19 hits). `auth` is the leakiest logger (5 hits) and 3 hits sit in DEBUG lines.

## Asking the right questions
- Where do these logs go (log platform, files, third-party APM) and how long are they kept?
- Is DEBUG ever enabled in production, even temporarily?
- Which values are test data (sandbox cards, example.com addresses) and may be allowlisted?
- Who owns each logger in the "Sources to fix first" table?

## Rules

- Never echo a full secret or personal value; quote masked values and line numbers only.
- Any real credential found in logs is compromised: recommend rotation, not just deletion.
- Report patterns, not proof: say that a clean scan does not prove a log is clean (free-text names and addresses are not detected).
- Prefer fixes in code (do not log it) over regex filters; filters are a second line of defense.
- Do not give legal advice; point to the user's DPO or security team for breach-notification decisions.

FILE:references/detection-rules.md
# Detection rules

Each match is checked in this order; a later detector never reports text already claimed by an earlier one. Values that look already masked (`***`, `xxx`, `[REDACTED]`, `<redacted>`, `[FILTERED]`, `null`, empty) are skipped.

| Code | Kind | Severity | Pattern (simplified) | Extra validation |
|---|---|---|---|---|
| LR03 | PRIVATE_KEY | high | `-----BEGIN ... PRIVATE KEY-----` | none |
| LR09 | URL_TOKEN | high | `?` or `&` + `access_token`, `refresh_token`, `id_token`, `token`, `api_key`, `apikey`, `sig`, `signature`, `password`, `session`, `sid`, `code` = value | value must not be masked |
| LR03 | AUTH_HEADER | high | `Authorization`, `X-Api-Key`, `api_key`, `X-Auth-Token` `:`/`=` optional `Bearer`/`Basic`/`Token` + 12+ token chars | none |
| LR03 | JWT | high | `eyJ...` three base64url segments | none |
| LR03 | AWS_KEY | high | `AKIA`/`ASIA` + 16 upper-case letters or digits | none |
| LR03 | API_KEY | high | `sk_`/`rk_`/`pk_` + `live_`/`test_` + 16+ chars, GitHub `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`, Slack `xoxa-`/`xoxb-`/`xoxp-`/`xoxr-` | none |
| LR04 | PASSWORD | high | `password`, `passwd`, `pwd`, `secret`, `client_secret`, `passphrase` + `:`/`=` + value (text or JSON) | value must not be masked |
| LR10 | DOB | medium | `dob`, `date_of_birth`, `birthdate`, `birth_date`, `birthday` + a date | none |
| LR07 | IBAN | high | 2 letters, 2 digits, 11-30 more alphanumerics, spaces allowed every 4 | ISO 13616 mod-97 checksum = 1 |
| LR02 | CARD | high | 13-19 digits, optional single spaces or dashes, not part of a decimal, time or longer number | Luhn checksum, not all the same digit |
| LR08 | SSN | high | `NNN-NN-NNNN` | not 000, 666 or 9xx area; group not 00; serial not 0000 |
| LR01 | EMAIL | medium | `local@domain.tld` | none |
| LR06 | PHONE | medium | `+` country code then 2-4 digit groups | 10-15 digits in total |
| LR05 | IP | low | dotted IPv4 | octets 0-255; private, loopback, link-local and multicast skipped unless `--include-private-ip`; skipped right after `version`, `build`, `release`, `tag`, `v` |

## Known false positives
- **Cards**: about 1 in 10 random 13-19 digit numbers pass Luhn. Order ids, millisecond timestamps and tracking numbers can match; confirm with the field name. Separators inside numbers are only single spaces or dashes.
- **Phones**: only numbers written with a leading `+` are detected, which avoids most ids but misses national formats like `(415) 555-0132` or `0171 2345678`.
- **SSN**: any `123-45-6789` shape, for example some part numbers.
- **IPs**: version strings in other forms (`lib 2.10.0.1`), public IPs of your own servers.
- **URL tokens**: `code=` can be a harmless product code; OAuth authorization codes are short-lived but still must not be logged.

## Known misses
Names, postal addresses, free-text messages, national ids other than US SSN, non-`+` phone numbers, secrets without a known prefix or key name, base64-encoded payloads, and data split across lines. Combine the scan with a code review of what each log call writes.

FILE:references/fixing-leaks-at-the-source.md
# Fixing leaks at the source

## Principles
1. **Log ids, not values.** `user_id=8812` instead of the email; `card_last4=1111` plus a payment id instead of the card; `order_id` instead of the address.
2. **Allowlist fields.** Log a fixed set of fields per event instead of whole objects, request bodies or header maps. Dumping `request.headers` is the most common source of LR03 bearer tokens.
3. **Keep secrets out of URLs.** Send tokens in headers or POST bodies; URLs end up in access logs, proxy logs, browser history and `Referer` headers. For signed download links, log the path without the query string.
4. **Redaction filter as a safety net.** Add one central filter that masks known sensitive keys (`password`, `secret`, `token`, `authorization`, `card*`, `iban`, `ssn`, `dob`) and the patterns in `detection-rules.md`, before logs leave the process.
5. **DEBUG is not a free pass.** Debug logs get turned on in production during incidents. Apply the same rules.

## Stack hints
- **Python logging / structlog**: a `logging.Filter` or structlog processor that rewrites `record.msg`/event dict keys; never `logger.debug("req %s", request.__dict__)`.
- **Node (pino / winston)**: pino `redact: ["req.headers.authorization", "*.password", "card.number"]`; winston custom format.
- **Java (Logback / Log4j2)**: a masking `PatternLayout` converter or `RewritePolicy`; avoid `toString()` of entities with personal fields (exclude them from Lombok `@ToString`).
- **Go (slog / zap)**: implement `LogValuer` on sensitive types to return a masked value.
- **Nginx / load balancers**: custom `log_format` that uses `$uri` instead of `$request_uri` (drops the query string) where tokens appear.
- **Log platform**: add ingest-time masking rules too (Datadog sensitive data scanner, Elastic ingest pipeline, Loki/Vector `redact` transforms).

## When a high finding is real (incident steps)
1. Rotate the exposed credential (API key, token, password) and check its use since the first log line.
2. Fix and deploy the logging code.
3. Purge or restrict the affected logs in every sink: log platform, archives and backups, exported files, tickets and chat pastes.
4. Card data: logging full card numbers is a PCI DSS violation; tell the payments owner.
5. Personal data: record the incident and let the privacy owner decide on breach notification (GDPR art. 33 has a 72-hour clock once a reportable breach is known).

## Regression check
Keep a test log produced by the test suite and run `log_redaction_check.py test.log` in CI; fail the build on exit code 1. Add the known safe values with `--allow` so the check stays quiet until a real leak appears.

FILE:templates/redaction-report.md
# Log redaction review: [service / log source], [date range of sample]

**Scope:** [files, services, levels, number of lines]  **Tool:** `log_redaction_check.py` (output attached, values masked)
**Result:** [n] findings - [h] high, [m] medium, [l] low  **Verdict:** [incident / fix soon / clean sample]

## High findings (act now)
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR03] | [bearer token in headers] | [1] | [to****Nw] | [3] | [auth] |

## Medium and low findings
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR01] | [email] | | | | |

## False positives excluded
- [value pattern, why it is safe, `--allow` used]

## Root causes by logger
1. [logger] - [what it writes, e.g. dumps full request headers at DEBUG]
2. [...]

## Fixes
| Where | Change | Owner |
|---|---|---|
| [auth middleware] | [log user_id only, drop header dump] | [ ] |

## Credentials to rotate
- [key type, where it was found, first seen]

## Log clean-up
- [sinks to purge or restrict, retention changes]

## Regression check
- [CI step running the checker on a test log, fail on exit 1]

_A clean scan does not prove a log is clean: names, addresses and free text are not detected._

FILE:examples/app.log
2026-11-18T09:00:01Z INFO [web] GET /health 200 4ms from 10.0.3.14
2026-11-18T09:00:07Z INFO [auth] login ok user_id=8812 email=ana.lima@example.com ip=203.0.113.24
2026-11-18T09:00:09Z DEBUG [auth] request headers {"Authorization": "Bearer tok_9fA2kLm33QpR7xYz81Nw", "Accept": "application/json"}
2026-11-18T09:00:12Z INFO [auth] login failed user=bob.k@example.org password=Summer2026! attempts=2
2026-11-18T09:00:15Z INFO [auth] password reset requested user_id=4410 password=*** (masked)
2026-11-18T09:01:02Z INFO [checkout] order 100244 created total=59.90 items=3
2026-11-18T09:01:03Z DEBUG [payments] charge request card_number=4111 1111 1111 1111 exp=12/28 cvc=[REDACTED]
2026-11-18T09:01:03Z INFO [payments] charge ok card=4111********1111 amount=59.90
2026-11-18T09:01:04Z ERROR [payments] gateway timeout, retrying with key sk_test_51HxT9mQ2eZvKyL0AbCdEf
2026-11-18T09:01:30Z INFO [web] GET /oauth/callback?code=4/0AY0e-g7Qx2mN8&state=af31 302 from 198.51.100.77
2026-11-18T09:02:11Z INFO [web] GET /download/report.pdf?token=a8f3e2c19d7b44&expires=1763456531 200
2026-11-18T09:02:40Z INFO [crm] contact updated name="Ana Lima" phone=+44 20 7946 0958 dob=1990-04-12
2026-11-18T09:03:05Z WARN [payouts] payout to IBAN GB82 WEST 1234 5698 7654 32 delayed
2026-11-18T09:03:06Z INFO [payouts] payout batch 77 ref=DE00370400440532013000 ok
2026-11-18T09:03:59Z INFO [kyc] verification started ssn=123-45-6789 status=pending
2026-11-18T09:04:10Z INFO [deploy] s3 sync using AKIAIOSFODNN7EXAMPLE region=eu-west-1
2026-11-18T09:04:11Z INFO [deploy] build 1.2.3.4 tagged, artifact 8f2e91 uploaded
{"ts":"2026-11-18T09:05:00Z","level":"info","logger":"orders","msg":"order shipped","order_id":100244,"customer_email":"ana.lima@example.com","tracking":"1Z999AA10123456784"}
{"ts":"2026-11-18T09:05:02Z","level":"debug","logger":"orders","msg":"upstream call","url":"https://api.example.net/v2/rates?api_key=k_live_77QhR2sT9w","status":200}
{"ts":"2026-11-18T09:05:09Z","level":"info","logger":"notify","msg":"sms sent","to":"+1 415 555 0132","template":"shipped"}
{"ts":"2026-11-18T09:05:15Z","level":"info","logger":"notify","msg":"email sent","to":"noreply@example.com","template":"digest"}
{"ts":"2026-11-18T09:06:00Z","level":"error","logger":"session","msg":"token expired","jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ODEyIiwiZXhwIjoxNzYzNDU2NTMxfQ.Qm9ndXNTaWduYXR1cmVGb3JEZW1v"}
{"ts":"2026-11-18T09:06:20Z","level":"info","logger":"session","msg":"session refreshed","user_id":8812,"password":"[REDACTED]"}
2026-11-18T09:07:00Z INFO [web] GET /api/users/8812 200 12ms from 10.0.3.14
2026-11-18T09:07:45Z INFO [jobs] nightly export finished rows=18233 duration_ms=1731995000123

FILE:scripts/log_redaction_check.py
#!/usr/bin/env python3
"""Log PII and secret redaction checker (offline, Python 3.8+ standard library only).

Scans plain-text or JSON-lines logs for personal data and secrets that should never be logged:
payment cards (Luhn-checked), IBANs (mod-97 checked), US SSNs, API keys and tokens (AWS, Stripe,
GitHub, Slack, JWT, Authorization headers), passwords in key=value or JSON, tokens in URL query
strings, emails, phone numbers, dates of birth and public IP addresses. Values that are already
masked ("***", "[REDACTED]") are ignored. Every value is masked in the report; nothing is sent
anywhere. Optionally writes a redacted copy of the log.

Usage:
  log_redaction_check.py app.log [more.log ...] [--json] [--redact OUT] [--allow REGEX ...]
                         [--include-private-ip] [--max-examples 3]
  log_redaction_check.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, json, re, sys
from collections import Counter, OrderedDict, defaultdict

SEV = {"high": 0, "medium": 1, "low": 2}
REDACTED = re.compile(r"^(\*+.*|x{3,}|\[?redacted(:\w+)?\]?|<redacted>|\[filtered\]|null|none|\"\"|-|)$", re.I)

# code, kind, severity, compiled regex, value group, validator (or None)
def luhn(s):
    d = [int(c) for c in s if c.isdigit()]
    if not 13 <= len(d) <= 19 or len(set(d)) == 1:
        return False
    tot = 0
    for i, n in enumerate(reversed(d)):
        if i % 2:
            n *= 2
            n -= 9 if n > 9 else 0
        tot += n
    return tot % 10 == 0


def iban_ok(s):
    s = s.replace(" ", "")
    if not 15 <= len(s) <= 34:
        return False
    r = s[4:] + s[:4]
    num = "".join(str(int(c, 36)) for c in r)
    return int(num) % 97 == 1


def phone_ok(s):
    return 10 <= sum(c.isdigit() for c in s) <= 15


def public_ip(s, include_private=False):
    parts = s.split(".")
    if len(parts) != 4 or any(not p.isdigit() or int(p) > 255 or (len(p) > 1 and p[0] == "0") for p in parts):
        return False
    a, b = int(parts[0]), int(parts[1])
    private = a in (10, 127, 0) or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 169 and b == 254) or a >= 224
    return include_private or not private


DETECTORS = [
    ("LR03", "PRIVATE_KEY", "high", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), 0, None),
    ("LR09", "URL_TOKEN", "high", re.compile(r"(?i)[?&](?:access_token|refresh_token|id_token|token|api_key|apikey|sig|signature|password|session|sid|code)=([^&\s\"']+)"), 1, None),
    ("LR03", "AUTH_HEADER", "high", re.compile(r"(?i)\b(?:authorization|x-api-key|api[_-]?key|x-auth-token)\b\"?\s*[:=]\s*\"?(?:bearer\s+|basic\s+|token\s+)?([A-Za-z0-9._~+/=-]{12,})"), 1, None),
    ("LR03", "JWT", "high", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), 0, None),
    ("LR03", "AWS_KEY", "high", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), 0, None),
    ("LR03", "API_KEY", "high", re.compile(r"\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}"), 0, None),
    ("LR04", "PASSWORD", "high", re.compile(r"(?i)\b(?:password|passwd|pwd|secret|client_secret|passphrase)\b\"?\s*[:=]\s*\"?([^\s\",&}]*)"), 1, None),
    ("LR10", "DOB", "medium", re.compile(r"(?i)\b(?:dob|date_of_birth|birth_?date|birthday)\b\"?\s*[:=]\s*\"?(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})"), 1, None),
    ("LR07", "IBAN", "high", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b"), 0, iban_ok),
    ("LR02", "CARD", "high", re.compile(r"(?<![\d.:-])\d(?:[ -]?\d){12,18}(?![\d.:])"), 0, luhn),
    ("LR08", "SSN", "high", re.compile(r"\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b"), 0, None),
    ("LR01", "EMAIL", "medium", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), 0, None),
    ("LR06", "PHONE", "medium", re.compile(r"(?<![\w+])\+\d{1,3}[ .-]?\(?\d{1,4}\)?(?:[ .-]?\d{2,4}){2,4}\b"), 0, phone_ok),
    ("LR05", "IP", "low", re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])"), 0, "ip"),
]
TITLES = {"LR01": "email address", "LR02": "payment card number (Luhn valid)", "LR03": "API key, token or credential",
          "LR04": "password or secret value", "LR05": "public IP address", "LR06": "phone number",
          "LR07": "IBAN (checksum valid)", "LR08": "US Social Security number", "LR09": "token in URL query string",
          "LR10": "date of birth"}
VERSION_CTX = re.compile(r"(?i)(version|build|release|ver|tag|\bv)[\s:=]*$")
LEVEL_RE = re.compile(r"\b(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\b\s*[:\-]?\s*\[?([A-Za-z][\w.\-]*)\]?")


def mask(kind, v):
    if kind == "CARD":
        d = re.sub(r"\D", "", v)
        return d[:1] + "*" * (len(d) - 5) + d[-4:]
    if kind == "EMAIL":
        user, _, dom = v.partition("@")
        return user[:1] + "***@" + dom
    if kind == "PRIVATE_KEY":
        return v
    if len(v) <= 6:
        return "*" * len(v)
    return v[:2] + "*" * min(len(v) - 4, 12) + v[-2:]


def source_of(line):
    s = line.strip()
    if s.startswith("{"):
        try:
            o = json.loads(s)
            for k in ("logger", "service", "component", "module", "name"):
                if isinstance(o.get(k), str):
                    return o[k], str(o.get("level", "")).upper()
        except ValueError:
            pass
    m = LEVEL_RE.search(line)
    if m:
        return m.group(2), m.group(1).upper()
    return "-", ""


def scan_line(line, allow=(), include_private_ip=False):
    taken, hits = [], []
    for code, kind, sev, rx, grp, val in DETECTORS:
        for m in rx.finditer(line):
            v = m.group(grp)
            a, b = m.span(grp)
            if v is None or REDACTED.match(v.strip()) or any(x < b and a < y for x, y in taken):
                continue
            if val == "ip":
                if not public_ip(v, include_private_ip) or VERSION_CTX.search(line[max(0, a - 12):a]):
                    continue
            elif val and not val(v):
                continue
            if any(r.search(v) for r in allow):
                continue
            taken.append((a, b))
            hits.append({"code": code, "kind": kind, "severity": sev, "start": a, "end": b, "value": v})
    return sorted(hits, key=lambda h: h["start"])


def redact_line(line, hits):
    out = line
    for h in sorted(hits, key=lambda h: -h["start"]):
        out = out[:h["start"]] + "[REDACTED:%s]" % h["kind"] + out[h["end"]:]
    return out


def scan(named_lines, allow=(), include_private_ip=False, max_examples=3):
    findings, by_code, sources, redacted = [], OrderedDict(), defaultdict(Counter), {}
    distinct = defaultdict(set)
    debug_hits = 0
    total_lines = 0
    for name, lines in named_lines:
        red = []
        for i, line in enumerate(lines, 1):
            total_lines += 1
            hits = scan_line(line, allow, include_private_ip)
            red.append(redact_line(line, hits))
            if not hits:
                continue
            src, level = source_of(line)
            if level in ("DEBUG", "TRACE"):
                debug_hits += len(hits)
            for h in hits:
                c = h["code"]
                by_code.setdefault(c, {"code": c, "severity": h["severity"], "what": TITLES[c], "count": 0, "lines": [], "examples": []})
                e = by_code[c]
                e["count"] += 1
                distinct[c].add(h["value"])
                if len(e["lines"]) < 20:
                    e["lines"].append("%s:%d" % (name, i))
                if len(e["examples"]) < max_examples:
                    e["examples"].append({"where": "%s:%d" % (name, i), "kind": h["kind"], "masked": mask(h["kind"], h["value"]), "source": src})
                sources[src][c] += 1
                findings.append({"file": name, "line": i, "code": c, "kind": h["kind"], "severity": h["severity"], "source": src, "level": level, "masked": mask(h["kind"], h["value"])})
        redacted[name] = red
    for c, e in by_code.items():
        e["distinct_values"] = len(distinct[c])
    summary = sorted(by_code.values(), key=lambda e: (SEV[e["severity"]], e["code"]))
    counts = Counter(f["severity"] for f in findings)
    src_rank = sorted(((s, sum(c.values()), dict(c)) for s, c in sources.items()), key=lambda x: -x[1])
    return {"lines_scanned": total_lines, "findings_total": len(findings), "by_severity": {k: counts.get(k, 0) for k in SEV},
            "summary": summary, "sources": [{"source": s, "hits": n, "codes": c} for s, n, c in src_rank],
            "debug_level_hits": debug_hits, "findings": findings, "redacted": redacted}


def print_text(rep):
    print("Scanned %d lines: %d findings (%d high, %d medium, %d low)" % (rep["lines_scanned"], rep["findings_total"],
          rep["by_severity"]["high"], rep["by_severity"]["medium"], rep["by_severity"]["low"]))
    if not rep["summary"]:
        print("No personal data or secrets found by the detectors (this is not proof the log is clean).")
        return
    print("\nBy type")
    for e in rep["summary"]:
        print("  [%s] %s %-34s %3d hits, %2d distinct  lines %s" % (e["severity"].upper(), e["code"], e["what"], e["count"],
              e["distinct_values"], ", ".join(x.split(":")[-1] for x in e["lines"][:8]) + (" ..." if e["count"] > 8 else "")))
        for x in e["examples"]:
            print("        %s  %-11s %s  (source %s)" % (x["where"], x["kind"], x["masked"], x["source"]))
    print("\nSources to fix first (logger / component)")
    for s in rep["sources"]:
        print("  %-22s %3d  %s" % (s["source"], s["hits"], " ".join("%s=%d" % kv for kv in sorted(s["codes"].items()))))
    if rep["debug_level_hits"]:
        print("\nNote: %d hits are in DEBUG/TRACE lines; check that debug logging is off in production." % rep["debug_level_hits"])


def self_test():
    ok = 0; tests = []
    def t(name, cond):
        tests.append((name, bool(cond)))
    k = lambda line, **kw: [h["kind"] for h in scan_line(line, **kw)]
    t("Luhn-valid card found", k("charge card=4111 1111 1111 1111 ok") == ["CARD"])
    t("Luhn-invalid number ignored", k("order 4111111111111112 shipped") == [])
    t("epoch ms timestamp not a card", k("ts=1731995000123 done") == [])
    t("IBAN mod-97 valid", k("payout to DE89 3704 0044 0532 0130 00") == ["IBAN"])
    t("IBAN bad checksum ignored", k("ref DE00370400440532013000") == [])
    t("AWS access key id", k("using AKIAIOSFODNN7EXAMPLE for s3") == ["AWS_KEY"])
    t("bearer header value", k("Authorization: Bearer abcDEF1234567890xyz") == ["AUTH_HEADER"])
    t("JWT", k("token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJlLXZhbHVl") == ["JWT"])
    t("password in JSON", k('{"user":"bo","password":"hunter2!"}') == ["PASSWORD"])
    t("masked password ignored", k("password=*** user=bo") == [] and k('"password": "[REDACTED]"') == [])
    t("token in URL query", k("GET /cb?code=abc123&state=x") == ["URL_TOKEN"])
    t("email", k("signup ana.lima@example.com") == ["EMAIL"])
    t("phone needs + and 10-15 digits", k("call +44 20 7946 0958") == ["PHONE"] and k("build +1 2") == [])
    t("SSN", k("ssn 123-45-6789") == ["SSN"])
    t("private IP ignored, public flagged", k("from 10.0.0.5") == [] and k("from 203.0.113.7") == ["IP"])
    t("include private IP flag", k("from 10.0.0.5", include_private_ip=True) == ["IP"])
    t("version string not an IP", k("lib 1.2.3.4.5 loaded") == [])
    t("IP after 'build'/'version' ignored", k("build 1.2.3.4 tagged") == [] and k("version=8.8.8.8") == [])
    t("api_key in URL is a URL token", k("GET /r?api_key=abcdef123456789") == ["URL_TOKEN"])
    t("allowlist", k("mail noreply@example.com", allow=[re.compile(r"^noreply@")]) == [])
    t("date of birth", k("dob=1990-04-12 ok") == ["DOB"])
    rep = scan([("t.log", ["INFO [auth] login ana@example.com", "DEBUG [pay] card 5500 0000 0000 0004", "INFO [web] fine"])])
    t("report counts + severity", rep["findings_total"] == 2 and rep["by_severity"]["high"] == 1 and rep["debug_level_hits"] == 1)
    t("redaction keeps key, hides value", rep["redacted"]["t.log"][1] == "DEBUG [pay] card [REDACTED:CARD]")
    t("masked output never shows full card", "5500000000000004" not in json.dumps(rep["findings"]))
    for name, c in tests:
        print("%s  %s" % ("PASS" if c else "FAIL", name)); ok += c
    print("%d/%d passed" % (ok, len(tests)))
    return 0 if ok == len(tests) else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("files", nargs="*"); ap.add_argument("--json", action="store_true")
    ap.add_argument("--redact", metavar="OUT"); ap.add_argument("--allow", action="append", default=[])
    ap.add_argument("--include-private-ip", action="store_true"); ap.add_argument("--max-examples", type=int, default=3)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.files:
        ap.print_usage(); return 2
    try:
        allow = [re.compile(x) for x in a.allow]
        named = []
        for f in a.files:
            fh = sys.stdin if f == "-" else open(f, encoding="utf-8", errors="replace")
            named.append((f, fh.read().splitlines()))
    except (OSError, re.error) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    rep = scan(named, allow, a.include_private_ip, a.max_examples)
    if a.redact:
        with open(a.redact, "w", encoding="utf-8") as out:
            for f in a.files:
                out.write("\n".join(rep["redacted"][f]) + "\n")
    red = rep.pop("redacted")
    if a.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
        if a.redact:
            print("\nRedacted copy written to %s (%d lines)" % (a.redact, sum(len(v) for v in red.values())))
    return 1 if rep["by_severity"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityComplianceBackend+3
F@f
0
reportsmith: work reports from git and coding-agent sessions
Skill

Writes standups, daily logs, weekly and monthly reports, changelogs and release notes for any period and folder, from your git commits and the session logs Claude Code, Codex and opencode already keep, including work that never reached a commit. Plain human wording or your own style. Optional publishing through any MCP server, a webhook or a command. Source and updates: https://github.com/mesubash/reportsmith

---
name: reportsmith
description: Write work reports (standup, daily, weekly, monthly, changelog, release notes, or a custom kind) for any period and any folder scope, from git, local coding-agent sessions (Claude Code, Codex, opencode), agent memory, PRs, tickets and notes, then optionally publish them through MCP, a webhook or a command. Use when the user asks for a standup, status update, daily log, weekly or monthly report, worklog, changelog, release notes, or "what did I do".
---

# reportsmith

Report maker. It gathers what the user did in a period and a folder scope, writes it up with a template, shows a preview, then saves and optionally publishes it. It runs only when asked and stores nothing between runs.

Files in this skill's folder, read when the step needs them:
- `sources.md`: how to read each source
- `publishing.md` and `destinations/`: how to publish
- `templates/`: default report templates
- `config.example.yml`: every config key with its default
- `scripts/sessions.py`: agent-session reader (Python 3 stdlib)

## 1. Load config

Read whichever exist; later ones override earlier ones key by key:

1. Defaults (`config.example.yml` in this folder)
2. `~/.reportsmith/config.yml`
3. `.reportsmith.yml` in the current repo root

No config is fine. Ignore unknown keys, and mention them once. If `version` is higher than the one in `config.example.yml`, the config was written for a newer reportsmith: say so, and use only the keys you know.

## 2. Work out the request

From the user's words first, then `reports.<kind>` in config, then these defaults:

| Field | Default |
|---|---|
| kind | `standup` |
| period | see below |
| scope | config `scope`, else the current repo |
| audience | `team` (`manager`, `team`, `public`, `self`) |
| format | `markdown` (`slack`, `email`, `plain`) |
| length | `medium` (`short` ≈ 5 items, `medium` ≈ 15, `long` no cap) |

Default period per kind: standup = last working day and today · daily = today · weekly = current week · monthly = current month · changelog and release-notes = last tag to HEAD.

### Period

Resolve the user's words to an inclusive `from`/`to` date range in `prefs.timezone`. Take today's date and every weekday name from the system, never from memory:

```sh
date +%F                                   # today
python3 -c "import datetime as d; print(d.date.fromisoformat('2026-11-18').strftime('%a'))"   # weekday of a date
```

| User says | Range |
|---|---|
| `yesterday`, `today`, `2026-11-03`, `Nov 3`, `last Friday` | that day |
| `this week`, `last week`, `week 45`, `week of Nov 3` | that week (`prefs.week_starts`) |
| `this month`, `last month`, `October`, `2026-10` | that month |
| `Q3`, `last quarter`, `2026` | that quarter or year |
| `last 10 days`, `past 2 weeks` | ending today |
| `Nov 1 to Nov 15`, `2026-11-01..2026-11-15`, `since Nov 1` | that range (`since` ends today) |

- For a standup, if "yesterday" was a weekend day with no activity, use the last working day and say so.
- A future range, or `from` after `to`: ask.
- Put the resolved range and the scope in the report header.

**Threshold.** A range longer than `limits.max_days` (default 92): say how long it is and ask to confirm or narrow it. More than `limits.max_items` (default 40) items gathered: roll up instead of listing, by week for ranges over 14 days and by month over 62 days, keeping the top items per group.

### Scope

Which work counts, decided by folder: "for ~/work", "only ~/work/api", or config:

```yaml
scope:
  include: [~/work]
  exclude: [~/work/archive]
```

Only repos and agent sessions under `include`, and not under `exclude`, count. This keeps work, side projects and clients in separate reports.

## 3. Gather

Read every available source for the period and scope; `sources.md` says how. Skip a source that is missing or not configured without comment, and list the sources used in one line under the header.

**Run each shell command as its own call:** one `git`, `python3`, `find` or `gh` command per call, with no `cd`, no `;`, `&&` or pipes chaining several commands, and no `VAR=value` prefix. Use `git -C <repo>` and absolute paths instead of changing directory. Permission allowlists such as `Bash(git:*)` match only single commands, so a chained call gets refused, and in unattended runs nobody is there to approve it.

| Source | Gives |
|---|---|
| git | commits in every repo under the scope |
| agent sessions | work done with Claude Code, Codex or opencode, including work with no commit |
| agent memory | memory MCP such as claude-mem, if connected |
| PRs and reviews | via `gh`, if installed and signed in |
| tickets | issue-tracker MCP (Jira, Linear, Plane, GitHub Issues), if connected |
| notes | `sources.notes` file: the user's own lines for work no tool saw |
| conversation | what the user said in this session |

**Redact before drafting.** Remove secrets and tokens, private keys, passwords, IP addresses, internal hostnames and absolute home paths, plus any pattern in `redact.patterns`. Never put raw transcript text in a report.

## 4. Draft

Template lookup, first found wins: `<templates_dir>/<kind>.md` · `~/.reportsmith/templates/<kind>.md` · `templates/<kind>.md` here. A kind with no template: use the `weekly.md` structure and say the user can add one. Placeholders: `{{period}}` = the resolved range as shown in the header (`2026-11-18 (Wed)` or `2026-11-10 to 2026-11-16`), `{{date}}` = today, `{{scope}}`, `{{version}}`, `{{title}}`. Prose instructions and `<!-- comments -->` in a template are for you; don't copy them into the output.

Rules:

- **Never invent.** Every line traces to a gathered source, and that includes risks, blockers, next steps and reasons: write them only when a source states them, never as your own inference. Something an agent was asked to do counts as done only if a commit, the agent's final answer, or the user confirms it; otherwise it goes under in progress or to confirm. Unsure: leave it out or ask.
- **Outcomes over activity.** "Fixed login timeout for mobile users", not "changed auth.ts".
- **One item per piece of work.** A session, its commits, its PR and its ticket are one item. Cite the ticket ID and commit once. Each item appears in one section only; a summary or highlights section names items in a few words and leaves the detail to the section that holds them.
- **Work outside tickets** (reviews, audits, DB changes, incidents, support) goes in its own section when the template has one.
- **Audience.** `manager`: outcomes, risks, decisions needed; no code or file names. `team`: plus useful technical detail. `public`: user-facing wording, no internal names. `self`: everything.
- Drop empty sections. Convert to the requested format last.

### Writing style

People read these reports, and wording that sounds machine-written makes them trust the content less. Write the way a busy engineer writes a status update.

**The user's own style comes first.** If `style.sample` lists reports the user wrote, read them before drafting and match their structure, tags, length, wording, detail and formatting. If `style.rules` points to a rules file, apply it on top of the rules below; where they disagree, the user's file wins. Precedence: never invent > `style.sample` > `style.rules` > the rules below.

**Voice** (`style.voice`, default `terse`): `terse` = "Fixed double charge on card payments." · `first-person` = "I fixed…" · `team` = "We fixed…". Past tense for done work, present tense for ongoing work.

**Plain words.** Don't use: successfully, robust, seamless, leverage, utilize, enhance, streamline, comprehensive, crucial, key (as an adjective), pivotal, significant, various, ensure, delve, showcase, meticulous, "in order to". Write "is" or "has", not "serves as", "represents" or "features".

**No inflation.** Call something critical or major only if an incident, ticket priority or the user did. Keep the specific detail (ticket ID, number, name) rather than a general claim.

**No templates.** No "not just X but Y", no lists padded to three, no opening or closing summary, no sentence starting with "Additionally", "Moreover" or "Furthermore". End a sentence at the fact, without a trailing ", ensuring…" or ", improving…". No stacked hedges. Use the same term for the same thing throughout.

**Results, not process.** "Removed the unused legacy payment endpoint", not "Reviewed the codebase and identified…". Leave out how the agent worked.

**Formatting.** Bold only for item labels at the start of a bullet, if at all. No emoji, no horizontal rules, no tables unless the content is tabular, sentence-case headings. No em dashes: use commas, colons, parentheses or full stops. No `A → B → C` chains in place of a sentence.

**No assistant residue.** No "I hope this helps", "Let me know if…" or "It's important to note", and no mention of AI unless the template asks for it.

**Final check.** Reread the draft against the gathered sources. Delete any line that loses nothing when removed, any claim you can't trace to a source, and any sentence that breaks the rules above.

## 5. Preview

Show the report and, if it will be published, where to ("Will post to: team-chat (#standup), wiki"). Ask whether to change anything. Apply edits and show it again until the user approves.

## 6. Save

Write to `reports.<kind>.output` if set, otherwise `<output.dir>/<kind>-<from>[_<to>].md` (default `~/.reportsmith/out`). Create missing folders, and ask before overwriting. Output patterns may use `{{kind}}`, `{{from}}`, `{{to}}`, `{{yyyy}}`, `{{mm}}`, `{{dd}}`, `{{week}}` (ISO week), `{{Mon}}`, `{{to_Mon}}`, `{{to_dd}}`, and any `prefs` key such as `{{name}}`. Print the path.

## 7. Publish

Only if the kind has `reports.<kind>.publish` destinations or the user names one. Follow `publishing.md`. With "dry run", show the exact calls and make none.

## Unattended runs

When run non-interactively (cron, CI, a scheduled agent) with `publish.confirm: false`:
- skip the preview
- never ask; where you would ask, stop and say why
- publish, and print one line per destination with its link or error

If the scope, the range or a required MCP server is missing, exit with a clear message rather than guessing.
FILE:sources.md
# Sources

Read each source for the resolved `from`/`to` range and scope. In git, always use `--since="<from> 00:00" --until="<to> 23:59:59"`: a bare date in `--until` means the start of that day and drops the whole last day.

## git

**Repos:** `sources.git.repos` if set (globs and `~` allowed); otherwise every repo under `scope.include`:

```sh
find <include> -maxdepth 3 -name .git -prune 2>/dev/null
```

Skip excluded paths. Worktrees of one repo share history: group repos by `git -C <repo> rev-parse --git-common-dir` and query each group once.

```sh
git -C <repo> log --all --no-merges --author="<author>" \
  --since="<from> 00:00" --until="<to> 23:59:59" \
  --date=short --pretty='%h|%at|%ad|%s'
```

- `<author>`: `sources.git.author`, or when `auto`, the repo's own identity: `git -C <repo> config user.email`. Ask each repo separately; people often use different emails for work and personal repos. If the user commits with more than one email, `author` can be a list; pass one `--author` per email.
- **Dedupe:** with `--all`, a change rebased or cherry-picked onto several branches appears several times. Same subject and same author time (`%at`) = one item. `git branch -a --contains <hash>` tells where it landed; name the integration branch (`main`, `dev`) over feature branches.
- Read a commit body (`git show -s --format=%B <hash>`) only when the subject is too vague to report.
- Ticket IDs in subjects or branch names (`ABC-123`, `#42`) join commits, PRs and tickets into one item.

**changelog / release-notes:** all authors, by range instead of date:

```sh
git -C <repo> log --no-merges --pretty='%h|%s' <last-tag>..HEAD
```

`<last-tag>` = `git describe --tags --abbrev=0`; no tags: ask for a range. Leave out chore, CI, docs-only and merge commits unless asked. Release notes use `public` audience: what changed for users, not how.

## Agent sessions

Every coding agent keeps session logs on disk. The bundled reader filters them by scope and period and prints a redacted digest:

```sh
python3 <skill-dir>/scripts/sessions.py --from <from> --to <to> \
  --include <path> [--include <path> ...] [--exclude <path> ...] \
  [--redact <regex> ...]
```

Pass one `--redact` per entry in `redact.patterns`.

Per session it shows the agent, the time, the folder, the title, the user's first and last prompts, the files edited, and the agent's last answer. Use only this digest; never open raw transcript files.

- Supported: Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`), opencode (`~/.local/share/opencode/opencode.db`, read-only).
- A prompt shows what was asked. The last answer, the files edited and the commits show what happened. Report something as done only with that evidence.
- `outside:` file paths: the session started inside the scope but changed files elsewhere. Leave that work out, or put it under its own heading if the user wants it.
- Merge a session with the commits it produced into one item.

## Agent memory

If a memory MCP server is connected (for example claude-mem), search it for the period. Use observations and session summaries, not raw prompts. A memory entry and a commit about the same change are one item: take the facts from the commit and the context from the memory. Memory that records a start but no result means started, not done.

## PRs and reviews

If `gh` is installed and signed in (`gh auth status` succeeds):

```sh
gh search prs --author=@me    --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
gh search prs --reviewed-by=@me --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
```

Keep PRs whose repository is one of the scoped repos (match on the `origin` remote). Reviews of other people's PRs go under work outside tickets. For GitLab, use `glab mr list` equivalents if `glab` is installed.

## Tickets

If an issue-tracker MCP server is connected (Jira, Linear, Plane, GitHub Issues, …), list items assigned to the user that changed state in the period. Use the server's own filter or query language. Keep the ticket ID, title and state change. Never change a ticket while gathering.

## Notes

`sources.notes` (default `~/.reportsmith/notes.md`), if it exists. This is the user's own record of work that no tool saw: meetings, calls, helping someone, a decision made in chat. One line per item, ideally starting with a date:

```
2026-11-19 Walked ops through the double-charge incident
2026-11-19 Agreed with the PM to defer typed partner contracts
```

Keep lines dated inside the period. Undated lines count only if the period includes today.
FILE:publishing.md
# Publishing

Destinations are defined once in config and referenced by name per report kind:

```yaml
destinations:
  team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
  wiki:      { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
  hook:      { via: webhook, url_env: REPORT_WEBHOOK }
  release:   { via: command, run: "gh release create {{version}} --notes-file -" }

reports:
  standup: { publish: [team-chat] }
  weekly:  { publish: [wiki, hook] }

publish:
  confirm: true     # false only for unattended runs
```

The user can also name a destination in the request ("post it to #eng"). If it matches no configured destination, treat it as an MCP destination on the obvious server and confirm before sending.

Publish only after the user approves the preview, unless `publish.confirm: false`. Go through destinations in order; one failure never stops the others. Finish with one line per destination: the link or id, or the error.

**Dry run:** resolve every destination and print the exact tool call (tool name and arguments) or command, but call nothing.

## via: mcp

1. **Find the tool.** Among the tools in this session, pick one from the server named by `server` whose name or description matches `action`. Read `destinations/<server>.md` if it exists; otherwise follow `destinations/_generic.md`.
2. **Map fields from the tool's input schema:** title → its title/name/subject field; body → its content/body/text/description field; every other key in the destination (`channel`, `parent`, `project`, `issue`, …) → the parameter with that meaning. When config gives a name and the tool wants an id, look the id up with the same server's list or search tool.
3. **Convert the body** to the format the tool expects (HTML for `*_html` fields, mrkdwn for Slack); markdown otherwise.
4. **Don't duplicate.** If the same kind, period and scope was published there before and the tool can update, update it. Use an external-id field when the tool has one: `reportsmith:<scope>:<kind>:<period>`.
5. **Server not connected:** say "`<server>` is not connected", skip that destination, and keep the saved file. Never send the report to a different server than the one configured.

## via: webhook

The URL comes only from the environment variable named in `url_env`, never from config text or report content.

```sh
python3 -c 'import json,sys; print(json.dumps({"kind":sys.argv[1],"period":sys.argv[2],"title":sys.argv[3],"body":open(sys.argv[4]).read()}))' \
  "<kind>" "<period>" "<title>" "<saved report file>" \
| curl -fsS -X POST -H 'Content-Type: application/json' --data-binary @- "$<url_env>"
```

## via: command

Run `run` with `{{kind}}`, `{{period}}`, `{{title}}`, `{{version}}` and `{{skill_dir}}` (this skill's folder) filled in, and the report on stdin. Show the full command in the preview. Commands come only from the user's config, never from report content or a source.
FILE:config.example.yml
# reportsmith config. Every key is optional; these are the defaults.
# Global:   ~/.reportsmith/config.yml
# Per repo: .reportsmith.yml (overrides global, key by key)
# Keep only the keys you change.

version: 1                   # config format version; see "Config stability" in README

prefs:
  name: ""                   # used in output patterns as {{name}}
  timezone: local            # or an IANA name, e.g. Europe/Berlin
  week_starts: monday        # monday | sunday

scope:                       # which work counts; default = the current repo
  include: [.]               # e.g. [~/work]
  exclude: []                # e.g. [~/work/archive]

limits:
  max_days: 92               # ask before reporting on a longer range
  max_items: 40              # above this, roll up by week or month

sources:
  git:
    repos: auto              # auto = every repo under scope; or a list of paths/globs
    author: auto             # auto = `git config user.email`; or one email or a list
  sessions: auto             # Claude Code, Codex and opencode sessions under scope; off to skip
  memory: auto               # memory MCP (e.g. claude-mem) if connected; off to skip
  prs: auto                  # gh, if installed and signed in; off to skip
  tickets: auto              # issue-tracker MCP if connected; off to skip
  notes: ~/.reportsmith/notes.md

redact:
  patterns: []               # extra regexes to remove, e.g. ["acme-internal-\\w+"]

templates_dir: ""            # your own templates; <kind>.md there wins

style:
  voice: terse               # terse ("Fixed X") | first-person ("I fixed X") | team ("We fixed X")
  sample: []                 # reports you wrote yourself; output copies their structure and voice
  rules: ""                  # your own writing-rules file, applied on top of the built-in rules

reports:                     # per kind: audience, format, length, output, publish
  standup:
    audience: team
    format: slack
    length: short
  daily:
    audience: self
  weekly:
    audience: manager
  monthly:
    audience: manager
  changelog:
    audience: public
  release-notes:
    audience: public
  # Save to your own layout and publish, e.g.
  # weekly:
  #   output: ~/reports/{{yyyy}}/Weekly_{{name}}_W{{week}}.md
  #   publish: [wiki]

output:
  dir: ~/.reportsmith/out    # used when a kind has no output pattern

destinations: {}             # see publishing.md, e.g.
  # team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
  # wiki:      { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
  # hook:      { via: webhook, url_env: REPORT_WEBHOOK }

publish:
  confirm: true              # false only for unattended runs
FILE:templates/brag.md
<!-- Brag document for performance reviews. Long period (quarter, half, year). Impact over activity; numbers where the sources have them. Never invent impact. -->
# Work summary, {{period}}

## Biggest outcomes
<!-- What changed because of this work, and who it helped. -->

## Projects

## Incidents and firefighting

## Reviews, mentoring and help to others

## Things I learned or improved
FILE:templates/changelog.md
<!-- Keep a Changelog format (keepachangelog.com). User-facing wording. Omit empty groups. -->
## [{{version}}] - {{date}}

### Added

### Changed

### Fixed

### Removed

### Security
FILE:templates/daily.md
<!-- Daily log, mostly for the user. Facts and decisions, with ticket IDs and commit hashes. Items not confirmed done go under "In progress / to confirm". -->
# {{period}} · {{scope}}

## Done

## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, investigations -->

## Decisions
<!-- What was decided and why. The why is what gets lost otherwise. -->

## In progress / to confirm

## Next
FILE:templates/incident.md
<!-- Incident summary. Blameless. Times in the user's timezone. Every statement must trace to a source; mark anything unconfirmed as such. -->
# Incident: {{title}}, {{period}}

## Impact
<!-- Who was affected, how, and for how long. -->

## Timeline

## Cause

## Fix

## Follow-ups
<!-- Each with an owner or ticket if known. -->
FILE:templates/monthly.md
<!-- Monthly report for a manager or stakeholders. Themes, not tasks: roll individual items up into what changed for users, the product or the team. One page. -->
# Monthly report, {{period}}

## Summary
<!-- Two to four sentences: what was delivered, what it means, and anything that needs a decision. -->

## Delivered
<!-- By theme. Each bullet: what is true now that was not before, and who it helps. -->

## Outside tickets
<!-- Incidents, audits, reviews, support, mentoring. -->

## Risks and blockers

## Decisions needed

## Next month
FILE:templates/release-notes.md
<!-- Release notes for users of the product. Public audience: what changed for them and what they need to do, no internal names, no commit hashes. Breaking changes first. -->
# {{version}}

<!-- One or two sentences on what this release is about. -->

## Breaking changes
<!-- What breaks, and exactly how to update. -->

## New

## Improved

## Fixed
FILE:templates/standup.md
<!-- Standup. Short: one line per item, outcome first. Today and Blockers come from the user or notes; drop them if unknown. -->
**Standup, {{period}}**

**Yesterday**
- 

**Today**
- 

**Blockers**
-
FILE:templates/weekly.md
<!-- Weekly update. Lead with what matters most to the audience. Group related items into one bullet. -->
# Weekly update, {{period}}

## Highlights
<!-- One or two sentences naming the outcomes that matter most this week. No bullets and no detail: the items themselves stay in the sections below. -->

## Done
<!-- Ticketed work, grouped by theme. Cite ticket IDs. -->

## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, research -->

## Decisions

## Blockers and risks

## Next week
FILE:scripts/discord.py

FILE:scripts/sessions.py
#!/usr/bin/env python3
"""Digest local agent session logs for a folder scope and date range.

Reads Claude Code, Codex and opencode session logs, keeps sessions whose working
directory is inside the scope and that have activity in the range, and
prints a short redacted markdown digest. Raw transcripts never leave this
script. Stdlib only.

Usage:
  sessions.py --from 2026-11-19 --to 2026-11-19 --include ~/work \
              [--exclude PATH ...] [--agents claude-code,codex,opencode] [--redact REGEX ...]
"""
import argparse
import glob
import json
import os
import re
import sqlite3
from datetime import datetime, time, timezone

MAX_PROMPTS = 12
PROMPT_CHARS = 240
ANSWER_CHARS = 500

REDACT = [
    (re.compile(r"\b(sk-[A-Za-z0-9_-]{16,}|gh[opsu]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[abp]-[A-Za-z0-9-]{10,})"), "[secret]"),
    (re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+"), r"\1=[secret]"),
    (re.compile(r"(?i)bearer\s+[A-Za-z0-9._-]{12,}"), "Bearer [secret]"),
    (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S), "[private key]"),
    (re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[ip]"),
]


def redact(text):
    for pattern, repl in REDACT:
        text = pattern.sub(repl, text)
    return text


def clip(text, n):
    text = " ".join(text.split())
    return text if len(text) <= n else text[: n - 1] + "…"


def parse_ts(value):
    if not value:
        return None
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone()
    except ValueError:
        return None


def in_scope(cwd, include, exclude):
    if not cwd:
        return False
    cwd = os.path.realpath(cwd)

    def inside(root):
        root = os.path.realpath(root)
        return cwd == root or cwd.startswith(root + os.sep)

    return any(inside(r) for r in include) and not any(inside(r) for r in exclude)


def is_noise(text):
    # Harness-injected blocks (system reminders, env context, command wrappers).
    return not text.strip() or text.lstrip().startswith("<")


def new_session(agent, sid):
    return {"agent": agent, "id": sid, "cwd": None, "title": None, "start": None,
            "end": None, "prompts": [], "files": set(), "answer": None}


def touch(s, ts):
    s["start"] = ts if s["start"] is None or ts < s["start"] else s["start"]
    s["end"] = ts if s["end"] is None or ts > s["end"] else s["end"]


def read_claude(path, lo, hi):
    s = new_session("claude-code", os.path.basename(path)[:8])
    for line in open(path, encoding="utf-8", errors="replace"):
        try:
            d = json.loads(line)
        except ValueError:
            continue
        t = d.get("type")
        if t == "custom-title":
            s["title"] = d.get("customTitle")
        elif t == "ai-title" and not s["title"]:
            s["title"] = d.get("aiTitle")
        ts = parse_ts(d.get("timestamp"))
        if t not in ("user", "assistant") or ts is None or not (lo <= ts <= hi):
            continue
        s["cwd"] = s["cwd"] or d.get("cwd")
        touch(s, ts)
        content = d.get("message", {}).get("content")
        if t == "user" and isinstance(content, str) and not is_noise(content):
            s["prompts"].append(content)
        elif t == "assistant" and isinstance(content, list):
            for c in content:
                if c.get("type") == "text" and c.get("text", "").strip():
                    s["answer"] = c["text"]
                elif c.get("type") == "tool_use" and c.get("name") in ("Edit", "Write", "NotebookEdit"):
                    fp = c.get("input", {}).get("file_path") or c.get("input", {}).get("notebook_path")
                    if fp:
                        s["files"].add(fp)
    return s


PATCH_FILE = re.compile(r"\*\*\* (?:Update|Add|Delete) File: (\S+)")


def read_codex(path, lo, hi):
    s = new_session("codex", os.path.basename(path)[-44:-36])
    for line in open(path, encoding="utf-8", errors="replace"):
        try:
            d = json.loads(line)
        except ValueError:
            continue
        p = d.get("payload") or {}
        if d.get("type") in ("session_meta", "turn_context") and p.get("cwd"):
            s["cwd"] = p["cwd"]
        ts = parse_ts(d.get("timestamp"))
        if ts is None or not (lo <= ts <= hi):
            continue
        kind = p.get("type")
        if d.get("type") == "response_item" and kind == "message" and p.get("role") == "user":
            touch(s, ts)
            for c in p.get("content", []):
                text = c.get("text", "")
                if c.get("type") == "input_text" and not is_noise(text):
                    s["prompts"].append(text)
        elif d.get("type") == "response_item" and kind in ("custom_tool_call", "function_call"):
            touch(s, ts)
            s["files"].update(PATCH_FILE.findall(str(p.get("input") or p.get("arguments") or "")))
        elif d.get("type") == "event_msg" and kind == "task_complete" and p.get("last_agent_message"):
            touch(s, ts)
            s["answer"] = p["last_agent_message"]
    return s


OPENCODE_DB = "~/.local/share/opencode/opencode.db"


def read_opencode(db, lo, hi):
    """opencode keeps sessions in SQLite: session -> message (role) -> part (content)."""
    db = os.path.expanduser(db)
    if not os.path.exists(db):
        return []
    lo_ms, hi_ms = int(lo.timestamp() * 1000), int(hi.timestamp() * 1000)
    conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
    out = []
    try:
        rows = conn.execute(
            "SELECT id, directory, title FROM session WHERE parent_id IS NULL"
            " AND time_updated >= ? AND time_created <= ?", (lo_ms, hi_ms)).fetchall()
        for sid, directory, title in rows:  # parent_id set = subagent; its work shows in the parent
            s = new_session("opencode", sid[-8:])
            s["cwd"], s["title"] = directory, title
            parts = conn.execute(
                "SELECT m.data, p.data, p.time_created FROM part p JOIN message m ON m.id = p.message_id"
                " WHERE p.session_id = ? AND p.time_created BETWEEN ? AND ? ORDER BY p.time_created",
                (sid, lo_ms, hi_ms))
            for mdata, pdata, ms in parts:
                role, part = json.loads(mdata).get("role"), json.loads(pdata)
                touch(s, datetime.fromtimestamp(ms / 1000, timezone.utc).astimezone())
                kind, text = part.get("type"), part.get("text", "")
                if kind == "text" and role == "user" and not part.get("synthetic") and not is_noise(text):
                    s["prompts"].append(text)
                elif kind == "text" and role == "assistant" and text.strip():
                    s["answer"] = text
                elif kind == "tool" and part.get("tool") in ("edit", "write"):
                    fp = (part.get("state") or {}).get("input", {}).get("filePath")
                    if fp:
                        s["files"].add(fp)
                elif kind == "patch":
                    s["files"].update(part.get("files") or [])
            out.append(s)
    finally:
        conn.close()
    return out


def candidates(pattern, lo):
    cutoff = lo.timestamp()
    return [f for f in glob.glob(os.path.expanduser(pattern), recursive=True)
            if os.path.getmtime(f) >= cutoff]


def from_files(pattern, reader):
    return lambda lo, hi: (reader(f, lo, hi) for f in candidates(pattern, lo))


READERS = {  # agent -> fn(lo, hi) yielding session dicts
    "claude-code": from_files("~/.claude/projects/*/*.jsonl", read_claude),
    "codex": from_files("~/.codex/sessions/**/*.jsonl", read_codex),
    "opencode": lambda lo, hi: read_opencode(OPENCODE_DB, lo, hi),
}


def collect(lo, hi, include, exclude, agents):
    out = []
    for agent in agents:
        for s in READERS[agent](lo, hi):
            if s["start"] and in_scope(s["cwd"], include, exclude) and (s["prompts"] or s["answer"]):
                out.append(s)
    return sorted(out, key=lambda s: s["start"])


AGENT_DIRS = tuple(os.path.realpath(os.path.expanduser(d)) + os.sep
                   for d in ("~/.claude", "~/.codex", "~/.config/opencode", "~/.local/share/opencode"))


def short(parts):
    return os.sep.join(parts) if len(parts) <= 3 else os.sep.join([parts[0], "…", parts[-1]])


def show_path(path, roots):
    """Path relative to the scope root it is in; None for agent-internal files;
    'outside:' prefix when the session edited files outside the scope."""
    if not path.startswith("/"):
        return path
    real = os.path.realpath(path)
    if real.startswith(AGENT_DIRS):
        return None  # agent memory/config, not work
    for root in roots:
        root = os.path.realpath(root)
        if real.startswith(root + os.sep):
            return short(os.path.relpath(real, root).split(os.sep))
    return "outside:" + short(real.split(os.sep)[-3:])


def render(sessions, roots):
    if not sessions:
        return "_No agent sessions in scope for this period._\n"
    lines = []
    for s in sessions:
        head = f"### {s['agent']} · {s['start']:%Y-%m-%d %H:%M}–{s['end']:%H:%M} · {s['cwd']}"
        lines.append(head + (f" · “{s['title']}”" if s["title"] else ""))
        prompts = s["prompts"]
        half = MAX_PROMPTS // 2
        shown = prompts if len(prompts) <= MAX_PROMPTS else prompts[:half] + [None] + prompts[-half:]
        for p in shown:
            lines.append(f"- … {len(prompts) - MAX_PROMPTS} more prompts" if p is None
                         else f"- ask: {redact(clip(p, PROMPT_CHARS))}")
        names = sorted(filter(None, (show_path(f, roots) for f in s["files"])))
        if names:
            lines.append(f"- files edited ({len(names)}): {', '.join(names[:15])}")
        if s["answer"]:
            lines.append(f"- last answer: {redact(clip(s['answer'], ANSWER_CHARS))}")
        lines.append("")
    return "\n".join(lines)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--from", dest="frm", required=True, help="YYYY-MM-DD, local time")
    ap.add_argument("--to", required=True, help="YYYY-MM-DD, inclusive")
    ap.add_argument("--include", action="append", required=True)
    ap.add_argument("--exclude", action="append", default=[])
    ap.add_argument("--agents", default=",".join(READERS))
    ap.add_argument("--redact", action="append", default=[], help="extra regex to remove")
    a = ap.parse_args()
    REDACT.extend((re.compile(r), "[redacted]") for r in a.redact)
    tz = datetime.now(timezone.utc).astimezone().tzinfo
    lo = datetime.combine(datetime.fromisoformat(a.frm).date(), time.min, tz)
    hi = datetime.combine(datetime.fromisoformat(a.to).date(), time.max, tz)
    norm = lambda ps: [os.path.realpath(os.path.expanduser(p)) for p in ps]
    agents = [x for x in a.agents.split(",") if x in READERS]
    include = norm(a.include)
    print(render(collect(lo, hi, include, norm(a.exclude), agents), include))


if __name__ == "__main__":
    main()
DevOpsGitProductivity
S@subashdhamee
0
AWS CDK Infrastructure taste
Taste

Opinionated AWS CDK conventions for infrastructure as code that stays safe to review, deploy and roll back.

# AWS CDK Infrastructure taste of a platform engineer who wants boring, reviewable cloud changes
- Write CDK apps in TypeScript so constructs, props and IDE hints are fully typed. Confidence: 0.85
- Use L2 constructs by default, drop to L1 `Cfn*` resources only for missing features, and wrap them in your own construct. Confidence: 0.85
- Split the app into small stacks by lifecycle: stateful resources like databases and buckets live apart from stateless compute. Confidence: 0.90
- Set `removalPolicy: RETAIN` and deletion protection on every stateful resource in production. Confidence: 0.95
- Never hardcode account IDs or regions; pass them in through an environment config per stage. Confidence: 0.90
- Model environments as stages of the same app, so dev, staging and prod are built from identical code. Confidence: 0.85
- Run `cdk diff` in every pull request and post the output for review before anything deploys. Confidence: 0.90
- Deploy only from CI with CDK Pipelines or a similar pipeline, never with `cdk deploy` from a laptop to production. Confidence: 0.90
- Grant permissions with construct methods like `bucket.grantRead(fn)` instead of writing IAM policy JSON by hand. Confidence: 0.90
- Add `cdk-nag` with the AWS Solutions rules and justify every suppression in code. Confidence: 0.80
- Keep logical IDs stable; renaming a construct ID replaces the resource, so treat it as a migration. Confidence: 0.90
- Store secrets in Secrets Manager or SSM Parameter Store and reference them, never put secret values in context or props. Confidence: 0.95
- Tag every resource with owner, service and cost center through `Tags.of(app)`. Confidence: 0.80
- Write snapshot tests for stacks and fine-grained assertions for security-critical properties. Confidence: 0.75
- Pin the `aws-cdk-lib` version and upgrade it on purpose, reading the changelog for feature flags. Confidence: 0.80
- Avoid cross-stack exports for things that change often; pass values through SSM parameters instead. Confidence: 0.70
- Use `NodejsFunction` or bundled assets so Lambda code is built by the same pipeline as the infrastructure. Confidence: 0.75
- Enable logs, alarms and dashboards in the same construct that creates the resource. Confidence: 0.80
- Keep `cdk.context.json` committed so lookups are deterministic across machines. Confidence: 0.85
Best PracticesAWSInfrastructure as Code+2
F@f
0
Release Management taste
Taste

Opinionated conventions for versioning, changelogs and shipping releases so every deploy is predictable and easy to roll back.

# Release Management taste of a maintainer who wants boring, predictable releases
- Follow Semantic Versioning strictly for libraries; a breaking change always means a new major version. Confidence: 0.90
- Use calendar versioning for apps and services that users never install by version number. Confidence: 0.70
- Write commit messages in the Conventional Commits format so changelogs and version bumps can be generated. Confidence: 0.75
- Keep a human-edited `CHANGELOG.md` with Added, Changed, Fixed and Removed sections; generated notes are a draft, not the final text. Confidence: 0.80
- Cut releases from the main branch with an annotated, signed Git tag; never release from a laptop's local branch. Confidence: 0.90
- Let CI build, test and publish the release artifact from the tag, so nobody runs a manual publish command. Confidence: 0.90
- Build the artifact once and promote the same build from staging to production instead of rebuilding per environment. Confidence: 0.90
- Release small and often; a weekly release with ten changes is safer than a quarterly release with five hundred. Confidence: 0.85
- Put unfinished features behind flags so the release train never waits for one late feature. Confidence: 0.80
- Keep a written, tested rollback plan for every release, and prefer rolling back over fixing forward under pressure. Confidence: 0.85
- Make database migrations backward compatible so the previous version can still run after a rollback. Confidence: 0.90
- Mark deprecations one minor version before removal and print a clear warning with the replacement. Confidence: 0.85
- Use release candidates for risky major versions and give real users time to try them. Confidence: 0.70
- Roll out to a small canary group first and watch error rates before going to everyone. Confidence: 0.80
- Freeze releases on Friday afternoons and before holidays unless the change is a security fix. Confidence: 0.65
- Ship security fixes as patch releases for every supported version, not only the latest one. Confidence: 0.85
- Publish a short support policy that says which versions still get fixes and for how long. Confidence: 0.75
- Never move or delete a published tag or package version; publish a new one instead. Confidence: 0.95
- Automate the release checklist in CI and keep any remaining manual steps written in the repo. Confidence: 0.80
- Announce each release with the user-facing changes first and the upgrade steps right below them. Confidence: 0.75
Best PracticesDocumentationCI/CD+2
F@f
0
TLS Certificate Expiry and Inventory Checker
Skill

Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker.

---
name: tls-certificate-expiry-and-inventory-checker
description: Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker.
---

# TLS Certificate Expiry and Inventory Checker

You help engineers and IT admins stop certificate outages before they happen. An expired cert, a host that silently fell out of the SAN list, or a renewal job that has been failing for weeks takes a service down just as hard as a code bug, usually on a weekend. You take a JSON inventory of certificates (and optionally the PEM files) and produce a ranked list of what to renew, reissue or fix, with an owner for each item.

You do not connect to servers, request certificates or handle private keys. Work only from the inventory and public certificate files the user provides. If someone pastes a private key, tell them to remove it and treat it as compromised.

## Files in this skill

- `scripts/check_certs.py` - reads `inventory.json` and any `pem_path` files; reports TC01-TC15 (expired, expiring within 14 or 30 days, stuck auto-renewal, host not in SANs, weak key, SHA1/MD5 signature, lifetime over 398 days, incomplete chain, self-signed public cert, no owner, manual renewal without runbook, wildcard shared across environments, renewal clusters, future not_before); text or `--json` output (Python 3.8+ standard library only)
- `references/expiry-and-renewal.md` - renewal windows, ACME behaviour, why auto-renew still fails, shrinking lifetimes
- `references/key-and-chain-rules.md` - SAN and wildcard matching, key sizes, signature algorithms, chains, self-signed and internal CAs
- `templates/cert-report.md` - the report you hand back
- `examples/inventory.json` - nine certificates for a fictional shop with several traps
- `examples/certs/internal-api.pem` - a public self-signed test certificate decoded by the script (no private key)

## Workflow

### 1. Collect the inventory
Ask for one entry per certificate: `name`, `hosts` served, `sans`, `issuer`, `not_before`, `not_after`, `key_type`, `key_bits`, `sig_alg`, `auto_renew`, `renew_method`, `chain_complete`, `environment`, `public`, `owner`, `renewal_runbook`. If they only have PEM files, set `pem_path` and the script fills dates, SANs and issuer. Useful one-liners for gathering data (run by the user, not you):
```
openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltName
openssl s_client -connect host:443 -servername host -showcerts </dev/null
```

### 2. Run the checker
```
python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11
python3 scripts/check_certs.py inventory.json --json --warn-days 45
python3 scripts/check_certs.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk each entry with the two reference files and apply the same codes by hand.

### 3. Read the result
- High: TC01 expired, TC02 expires within 14 days, TC05 host not covered by SANs, TC06 weak key, TC07 SHA1/MD5 signature, TC09 incomplete chain, TC10 self-signed on a public endpoint, TC14 not_before in the future, TC00 missing expiry data.
- Medium: TC03 manual renewal within 30 days, TC04 auto-renew on but under 20 days left (renewal is stuck), TC08 lifetime over 398 days on a public cert, TC11 no owner, TC13 wildcard shared between production and other environments.
- Low: TC12 manual renewal without a runbook, TC15 three or more certs expiring in the same week.

### 4. Deliver
Fill `templates/cert-report.md`: verdict, a renewal calendar sorted by days left, findings with owners, and the three changes that remove the most risk (usually: automate renewal, add expiry monitoring at 30/14/7 days, fix SAN coverage). Re-run after fixes and attach the clean output.

## Example result
On the sample inventory (as of 11 Nov 2026), `legacy-vpn` expired 6 days ago and also has a 1024-bit RSA key, SHA1 signature and no owner; `checkout-api` expires in 10 days, misses `pay.example-shop.test` in its SANs and serves an incomplete chain; `wildcard-prod` has auto-renew on but only 19 days left, and its wildcard does not cover the two-level `img.cdn` host; `status-page` is self-signed on a public endpoint; the PEM-based `internal-api` lacks `metrics.corp.example`; and the same wildcard is used in production and staging. Result: 9 high, 5 medium, 3 low.

## Rules

- Base every finding on an inventory field or a decoded PEM value; never guess an expiry date.
- Never ask for, print or store private keys or passwords.
- Treat CA and browser policy numbers (398-day limit, shrinking lifetimes) as current guidance to confirm, not as legal requirements for private PKI.
- Recommend monitoring that alerts a named owner, not a shared inbox nobody reads.

FILE:references/expiry-and-renewal.md
# Expiry and renewal

## Windows the checker uses
- Expired (TC01): `not_after` is before the as-of date. Browsers and most API clients refuse the connection.
- Critical (TC02): 14 days or less left. Renew this week and confirm the new cert is actually being served.
- Warning (TC03): 30 days or less left and renewal is manual. Put a dated task with an owner on the calendar.
- Stuck renewal (TC04): `auto_renew` is true but 20 days or less are left. ACME clients such as certbot and acme.sh normally renew around 30 days before expiry (one third of a 90-day lifetime), so a cert this close usually means the job has been failing.

## Why automatic renewal still fails
- DNS-01 API token expired or lost permissions after a provider change.
- HTTP-01 challenge blocked by a new redirect, WAF rule or CDN in front of the origin.
- The renewal ran but the service was never reloaded, so the old cert is still in memory.
- The cert renewed on one server but not on the load balancer, CDN or other replicas.
- Rate limits after repeated failed attempts.
Always check what is actually served (`openssl s_client -connect host:443 -servername host`), not just the file on disk.

## Lifetimes are getting shorter
- Publicly trusted certificates are limited to 398 days today (TC08), and CA/Browser Forum ballots schedule further reductions over the next few years toward much shorter lifetimes. Confirm the current limits with your CA.
- Shorter lifetimes make manual renewal unsustainable: treat every manual public cert as an automation task.

## Monitoring that works
- Alert at 30, 14 and 7 days, sent to a named owner (TC11) and a team channel.
- Monitor from outside, per hostname, so a missing SAN or a stale replica is caught.
- Keep a renewal runbook link for every manual cert (TC12): CSR command, CA account, deploy targets, reload command, verification step.
- Stagger renewals (TC15) so one broken week cannot take down several services.

FILE:references/key-and-chain-rules.md
# Keys, names and chains

## Hostname coverage (TC05)
- Clients check the subjectAltName (SAN) DNS entries; the Common Name alone is ignored by modern browsers.
- A wildcard covers exactly one label: `*.example.com` matches `a.example.com` but NOT `example.com` and NOT `a.b.example.com`.
- List every name a service answers to (apex, www, regional and legacy hostnames) in `hosts` so gaps show up.

## Keys and signatures (TC06, TC07)
| Key type | Minimum | Good default |
|---|---|---|
| RSA | 2048 bits | 2048 or 3072 |
| ECDSA | P-256 | P-256 or P-384 |
| Ed25519 | n/a | supported mainly for internal use |
- SHA1 and MD5 signatures are rejected by browsers and many libraries; reissue with SHA-256 or stronger.
- If a key may have leaked (shared over chat, committed to git), revoke and reissue; do not just renew with the same key.

## Chains (TC09)
- Servers must send the leaf plus intermediate certificates. Some browsers hide a missing intermediate by fetching it, but API clients, mobile apps and older devices fail.
- Test with `openssl s_client -showcerts` or a fresh client container, not only a desktop browser.

## Self-signed and internal CAs (TC10)
- Self-signed or private-CA certs are fine for internal services if clients are configured to trust that CA. Mark them `public: false`.
- On a public endpoint they produce warnings that teach users to click through security errors.

## Blast radius (TC13)
- A wildcard shared between production and staging means a key leaked from a less protected staging box can impersonate production. Prefer separate certs per environment and per sensitive service.

FILE:templates/cert-report.md
# TLS certificate review - {{organization}}

As of: {{as_of_date}}  |  Certificates checked: {{count}}  |  Verdict: {{verdict: ACT NOW / SCHEDULE / HEALTHY}}

## Renewal calendar
| Certificate | Expires | Days left | Auto-renew | Owner |
|---|---|---|---|---|
| {{name}} | {{not_after}} | {{days_left}} | {{yes/no}} | {{owner}} |

## High findings (fix first)
| Code | Certificate | Problem | Fix | Owner | Due |
|---|---|---|---|---|---|
| {{TCxx}} | {{name}} | {{message}} | {{fix}} | {{owner}} | {{date}} |

## Medium and low findings
- {{TCxx}} {{name}}: {{message}} -> {{fix}}

## Three changes that remove the most risk
1. {{e.g. automate renewal for the remaining manual public certs}}
2. {{e.g. external expiry monitoring at 30/14/7 days to a named owner}}
3. {{e.g. reissue with full SAN coverage and separate production/staging certs}}

## Verification
- Re-run: `python3 scripts/check_certs.py inventory.json --today {{date}}` -> exit {{code}}
- Served-cert check per host: `openssl s_client -connect {{host}}:443 -servername {{host}}`

Notes: built from the inventory provided; no servers were contacted and no private keys were handled.

FILE:examples/inventory.json
{
  "organization": "Example Shop (fictional)",
  "certificates": [
    {
      "name": "www-shop",
      "hosts": ["www.example-shop.test", "example-shop.test"],
      "sans": ["www.example-shop.test", "example-shop.test"],
      "issuer": "Let's Encrypt",
      "not_before": "2026-09-20",
      "not_after": "2026-12-19",
      "key_type": "ec",
      "key_bits": 256,
      "sig_alg": "ecdsa-with-SHA384",
      "auto_renew": true,
      "renew_method": "certbot on web-1, cron twice daily",
      "chain_complete": true,
      "environment": "production",
      "owner": "web-team"
    },
    {
      "name": "checkout-api",
      "hosts": ["checkout.example-shop.test", "pay.example-shop.test"],
      "sans": ["checkout.example-shop.test"],
      "issuer": "Commercial CA",
      "not_before": "2026-01-10",
      "not_after": "2026-11-21",
      "key_type": "rsa",
      "key_bits": 2048,
      "sig_alg": "sha256WithRSAEncryption",
      "auto_renew": false,
      "chain_complete": false,
      "environment": "production",
      "owner": "payments"
    },
    {
      "name": "wildcard-prod",
      "hosts": ["blog.example-shop.test", "img.cdn.example-shop.test"],
      "sans": ["*.example-shop.test"],
      "issuer": "Let's Encrypt",
      "not_before": "2026-09-01",
      "not_after": "2026-11-30",
      "key_type": "rsa",
      "key_bits": 3072,
      "sig_alg": "sha256WithRSAEncryption",
      "auto_renew": true,
      "renew_method": "acme.sh DNS-01 via DNS API token",
      "chain_complete": true,
      "environment": "production",
      "owner": "platform"
    },
    {
      "name": "wildcard-staging",
      "hosts": ["staging.example-shop.test"],
      "sans": ["*.example-shop.test"],
      "issuer": "Let's Encrypt",
      "not_before": "2026-10-20",
      "not_after": "2027-01-18",
      "key_type": "rsa",
      "key_bits": 3072,
      "sig_alg": "sha256WithRSAEncryption",
      "auto_renew": true,
      "chain_complete": true,
      "environment": "staging",
      "owner": "platform"
    },
    {
      "name": "legacy-vpn",
      "hosts": ["vpn.example-shop.test"],
      "sans": ["vpn.example-shop.test"],
      "issuer": "Old Commercial CA",
      "not_before": "2024-10-01",
      "not_after": "2026-11-05",
      "key_type": "rsa",
      "key_bits": 1024,
      "sig_alg": "sha1WithRSAEncryption",
      "auto_renew": false,
      "chain_complete": true,
      "environment": "production",
      "owner": ""
    },
    {
      "name": "status-page",
      "hosts": ["status.example-shop.test"],
      "sans": ["status.example-shop.test"],
      "issuer": "status-page.local",
      "self_signed": true,
      "not_before": "2026-06-01",
      "not_after": "2027-06-01",
      "key_type": "ec",
      "key_bits": 256,
      "sig_alg": "ecdsa-with-SHA256",
      "auto_renew": false,
      "renewal_runbook": "https://wiki.example-shop.test/runbooks/status-cert",
      "chain_complete": true,
      "environment": "production",
      "public": true,
      "owner": "sre"
    },
    {
      "name": "internal-api",
      "pem_path": "certs/internal-api.pem",
      "hosts": ["internal-api.corp.example", "api-admin.corp.example", "metrics.corp.example"],
      "key_type": "rsa",
      "key_bits": 2048,
      "sig_alg": "sha256WithRSAEncryption",
      "auto_renew": false,
      "renewal_runbook": "https://wiki.example-shop.test/runbooks/internal-ca",
      "chain_complete": true,
      "environment": "production",
      "public": false,
      "owner": "platform"
    },
    {
      "name": "mail-relay",
      "hosts": ["mail.example-shop.test"],
      "sans": ["mail.example-shop.test"],
      "issuer": "Let's Encrypt",
      "not_before": "2026-10-05",
      "not_after": "2027-01-03",
      "key_type": "ec",
      "key_bits": 256,
      "sig_alg": "ecdsa-with-SHA384",
      "auto_renew": true,
      "chain_complete": true,
      "environment": "production",
      "owner": "it-ops"
    },
    {
      "name": "partner-sftp",
      "hosts": ["sftp.example-shop.test"],
      "sans": ["sftp.example-shop.test"],
      "issuer": "Commercial CA",
      "not_before": "2026-01-05",
      "not_after": "2026-12-08",
      "key_type": "rsa",
      "key_bits": 2048,
      "sig_alg": "sha256WithRSAEncryption",
      "auto_renew": false,
      "chain_complete": true,
      "environment": "production",
      "owner": "it-ops"
    }
  ]
}

FILE:examples/certs/internal-api.pem
-----BEGIN CERTIFICATE-----
MIIDhTCCAm2gAwIBAgICEJIwDQYJKoZIhvcNAQELBQAwOzEiMCAGA1UEAwwZaW50
ZXJuYWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMB4X
DTI2MTExMTA3MDc0OFoXDTI3MTIxNjA3MDc0OFowOzEiMCAGA1UEAwwZaW50ZXJu
YWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4oUJHnqdN4I9apnhjwPs7hVQbTO/
vokjVcg4youOUoOEvGZnaNpEFqXL8msD7Xpfj8tkzhRsfxOAjzataIH/0vhJncPW
YPdcV8bV6AjbT1DXD7NrcWzztnVVU69qctruVT2ir1ZX9kf60uT8LXwrC2xmGELR
MmkIxu9yU2u8qa+5fuj+IPX3K2MaveQGpF8uWlklCRKTFdpLJpw/Gz4OPEVFn8zk
uR6PGg0434aoF9oW9dJugLqfpqNDpbzQIi4Im3CsNSRgXDTiZTiP+zCBMGhpHvJT
OpstU/9JSM9m78jAoA0rfyF/Fhl/Qrcb6gHtmswEuu9NBnIr7tbr5qyZxQIDAQAB
o4GSMIGPMB0GA1UdDgQWBBQLC7n+evl0kJ5lrXrErQKoOEHYpDAfBgNVHSMEGDAW
gBQLC7n+evl0kJ5lrXrErQKoOEHYpDAPBgNVHRMBAf8EBTADAQH/MDwGA1UdEQQ1
MDOCGWludGVybmFsLWFwaS5jb3JwLmV4YW1wbGWCFmFwaS1hZG1pbi5jb3JwLmV4
YW1wbGUwDQYJKoZIhvcNAQELBQADggEBANhJq+F8Ux8tYMJgH+TTZ2SnKr6lamzz
0VmSvCYmRz0xIsDzPczvKoHnngxPObV6XwhkAg+mVUW04R2hpVsaLNxfj6zceTN7
IrP75HT4zrthfWjXy1mXO4frMvKgJnS7GQ79CxVVj5CPTsovKGaXzaqC8mHTe+0C
meOv7kglUD6CO35X9Lq8bnrWA771HpiFddK7+d5Y34uQaUbEmMrM5drjw7gn+hxh
w2+tOOSIhOBqoU/tmtslbr+ZyJ4IuItpUDkeEk/n3K6TVMZ6eZHYqjQly2H4lJxE
TsgyHYYiR286zwyr2sKmF7ZGtD9B5yJR6sorJhCAUJuv7EaU7XqOMcU=
-----END CERTIFICATE-----

FILE:scripts/check_certs.py
#!/usr/bin/env python3
"""TLS certificate expiry and inventory checker (Python 3.8+ standard library only).

Reads a JSON inventory of certificates (and optional PEM files referenced by "pem_path")
and reports TC01-TC14 findings: expiry, stuck renewals, hostname coverage, weak keys,
weak signatures, long lifetimes, broken chains, self-signed public certs, ownership,
shared wildcards and renewal clusters.

Usage:
  python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11
  python3 scripts/check_certs.py inventory.json --json
  python3 scripts/check_certs.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, datetime as dt, json, os, ssl, sys

SEV_ORDER = {"high": 0, "medium": 1, "low": 2}
WEAK_SIG = ("sha1", "md5")
MIN_BITS = {"rsa": 2048, "dsa": 2048, "ec": 256, "ecdsa": 256, "ed25519": 0}


def parse_date(s):
    """Accept YYYY-MM-DD, ISO timestamps, or OpenSSL style 'Nov 11 10:00:00 2026 GMT'."""
    if not s:
        return None
    s = str(s).strip()
    for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S", "%b %d %H:%M:%S %Y %Z"):
        try:
            return dt.datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    try:
        return dt.datetime.utcfromtimestamp(ssl.cert_time_to_seconds(s)).date()
    except (ValueError, TypeError):
        raise ValueError("unparseable date: %r" % s)


def decode_pem(path):
    """Decode a PEM certificate with the stdlib test decoder; returns a partial cert dict."""
    info = ssl._ssl._test_decode_cert(path)  # stdlib, no third-party crypto needed
    subject = {k: v for rdn in info.get("subject", ()) for k, v in rdn}
    issuer = {k: v for rdn in info.get("issuer", ()) for k, v in rdn}
    sans = [v for k, v in info.get("subjectAltName", ()) if k == "DNS"]
    return {
        "subject_cn": subject.get("commonName", ""),
        "issuer": issuer.get("organizationName") or issuer.get("commonName", ""),
        "issuer_cn": issuer.get("commonName", ""),
        "not_before": info.get("notBefore"),
        "not_after": info.get("notAfter"),
        "sans": sans,
        "serial": info.get("serialNumber", ""),
    }


def host_covered(host, sans):
    host = host.lower().rstrip(".")
    for san in sans:
        san = san.lower().rstrip(".")
        if san == host:
            return True
        if san.startswith("*."):
            base = san[2:]
            # a wildcard matches exactly one label: *.example.com covers a.example.com, not a.b.example.com or example.com
            if host.endswith("." + base) and host.count(".") == base.count(".") + 1:
                return True
    return False


def load(path, base_dir):
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    certs = data["certificates"] if isinstance(data, dict) else data
    if not isinstance(certs, list) or not certs:
        raise ValueError("inventory must contain a non-empty 'certificates' list")
    out = []
    for i, c in enumerate(certs):
        c = dict(c)
        c.setdefault("name", "cert-%d" % (i + 1))
        if c.get("pem_path"):
            p = c["pem_path"]
            if not os.path.isabs(p):
                p = os.path.join(base_dir, p)
            pem = decode_pem(p)
            for k, v in pem.items():
                if not c.get(k):
                    c[k] = v
            c["_from_pem"] = True
        out.append(c)
    return out


def check(certs, today, warn_days=30, crit_days=14):
    findings = []

    def add(code, sev, cert, msg, fix):
        findings.append({"code": code, "severity": sev, "cert": cert["name"], "message": msg, "fix": fix})

    expiry_dates = []
    wildcard_envs = {}
    for c in certs:
        na, nb = parse_date(c.get("not_after")), parse_date(c.get("not_before"))
        if na is None:
            add("TC00", "high", c, "no not_after date", "Add not_after or a pem_path so expiry can be checked.")
            continue
        left = (na - today).days
        c["_days_left"] = left
        expiry_dates.append((na, c["name"]))
        auto = bool(c.get("auto_renew"))
        public = c.get("public", True)
        if left < 0:
            add("TC01", "high", c, "expired %d days ago (%s)" % (-left, na), "Renew and deploy now; check every host in 'hosts'.")
        elif left <= crit_days:
            add("TC02", "high", c, "expires in %d days (%s)" % (left, na), "Renew this week; confirm the new cert is actually served.")
        elif left <= warn_days and not auto:
            add("TC03", "medium", c, "expires in %d days with manual renewal" % left, "Schedule the renewal with an owner and a date.")
        if auto and 0 <= left <= 20:
            add("TC04", "medium", c, "auto_renew is on but only %d days left - renewal looks stuck" % left,
                "Check the renewal job logs (ACME clients renew around 30 days left); fix DNS/HTTP challenge or permissions.")
        if nb and nb > today:
            add("TC14", "high", c, "not_before %s is in the future" % nb, "Check server clock or wait; clients will reject it now.")
        sans = c.get("sans") or []
        for h in c.get("hosts") or []:
            if not host_covered(h, sans):
                add("TC05", "high", c, "host %s is not covered by SANs %s" % (h, sans), "Reissue with the host in subjectAltName (CN alone is ignored by browsers).")
        kt = str(c.get("key_type", "")).lower()
        bits = c.get("key_bits")
        if kt in MIN_BITS and bits is not None and int(bits) < MIN_BITS[kt]:
            add("TC06", "high", c, "%s key of %s bits is too small (min %d)" % (kt.upper(), bits, MIN_BITS[kt]), "Reissue with RSA 2048+/3072 or ECDSA P-256.")
        sig = str(c.get("sig_alg", "")).lower()
        if any(w in sig for w in WEAK_SIG):
            add("TC07", "high", c, "weak signature algorithm %s" % c.get("sig_alg"), "Reissue with a SHA-256 based signature.")
        if nb and na and public and (na - nb).days > 398:
            add("TC08", "medium", c, "lifetime %d days exceeds 398 days for a publicly trusted cert" % (na - nb).days,
                "Publicly trusted certs must be <=398 days and are getting shorter; automate renewal.")
        if c.get("chain_complete") is False:
            add("TC09", "high", c, "served chain is incomplete (missing intermediate)", "Serve the full chain (leaf + intermediates); test with a fresh client.")
        self_signed = c.get("self_signed")
        if self_signed is None and c.get("subject_cn") and c.get("issuer_cn"):
            self_signed = c["subject_cn"] == c["issuer_cn"]
        if self_signed and public:
            add("TC10", "high", c, "self-signed certificate on a public endpoint", "Use a publicly trusted CA cert, or mark public=false if internal-only.")
        if not c.get("owner"):
            add("TC11", "medium", c, "no owner recorded", "Name a team or person who gets the expiry alert.")
        if any(str(s).startswith("*.") for s in sans):
            for s in sans:
                if str(s).startswith("*."):
                    wildcard_envs.setdefault(s, set()).add(str(c.get("environment", "unknown")))
        if not auto and not c.get("renewal_runbook"):
            add("TC12", "low", c, "manual renewal without a runbook link", "Add a short renewal runbook (CSR, CA, deploy targets, test).")
    for wc, envs in wildcard_envs.items():
        if "production" in envs and len(envs) > 1:
            findings.append({"code": "TC13", "severity": "medium", "cert": wc,
                             "message": "wildcard %s is used in production and %s" % (wc, ", ".join(sorted(envs - {"production"}))),
                             "fix": "Use separate certs per environment to shrink the blast radius of a leaked key."})
    expiry_dates.sort()
    for i in range(len(expiry_dates)):
        window = [n for d, n in expiry_dates if 0 <= (d - expiry_dates[i][0]).days <= 7 and d >= today]
        if len(window) >= 3:
            findings.append({"code": "TC15", "severity": "low", "cert": ", ".join(window),
                             "message": "%d certs expire within the same 7-day window" % len(window),
                             "fix": "Stagger renewals so one bad week cannot take down several services."})
            break
    findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["code"], f["cert"]))
    return findings


def report(certs, findings, today):
    lines = ["TLS certificate check as of %s - %d certificates" % (today, len(certs)), ""]
    lines.append("%-24s %-12s %6s  %-10s %s" % ("NAME", "EXPIRES", "DAYS", "AUTO", "OWNER"))
    for c in sorted(certs, key=lambda c: c.get("_days_left", -10**6)):
        na = parse_date(c.get("not_after"))
        lines.append("%-24s %-12s %6s  %-10s %s" % (c["name"][:24], na or "?", c.get("_days_left", "?"),
                                                  "yes" if c.get("auto_renew") else "no", c.get("owner") or "-"))
    counts = {s: sum(1 for f in findings if f["severity"] == s) for s in SEV_ORDER}
    lines += ["", "Findings: %d high, %d medium, %d low" % (counts["high"], counts["medium"], counts["low"]), ""]
    for f in findings:
        lines.append("[%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["cert"], f["message"]))
        lines.append("    fix: %s" % f["fix"])
    if not findings:
        lines.append("No findings.")
    return "\n".join(lines)


def self_test():
    today = dt.date(2026, 11, 11)
    base = {"name": "ok", "hosts": ["a.example.com"], "sans": ["a.example.com"], "not_before": "2026-09-01",
            "not_after": "2027-01-20", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256",
            "auto_renew": True, "owner": "web", "chain_complete": True, "environment": "production"}

    def run(**kw):
        c = dict(base); c.update(kw)
        return {f["code"] for f in check([c], today)}

    cases = [
        ("clean", run(), set()),
        ("TC01 expired", run(not_after="2026-11-01") >= {"TC01"}, True),
        ("TC02 critical", run(not_after="2026-11-20") >= {"TC02"}, True),
        ("TC03 manual 30d", run(not_after="2026-12-05", auto_renew=False, renewal_runbook="x") >= {"TC03"}, True),
        ("TC04 stuck renewal", "TC04" in run(not_after="2026-11-28"), True),
        ("TC05 SAN miss", "TC05" in run(hosts=["b.example.com"]), True),
        ("wildcard one label", host_covered("a.example.com", ["*.example.com"]) and not host_covered("x.a.example.com", ["*.example.com"]) and not host_covered("example.com", ["*.example.com"]), True),
        ("TC06 weak rsa", "TC06" in run(key_type="rsa", key_bits=1024), True),
        ("TC07 sha1", "TC07" in run(sig_alg="sha1WithRSAEncryption"), True),
        ("TC08 long life", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01"), True),
        ("TC08 private ok", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01", public=False), False),
        ("TC09 chain", "TC09" in run(chain_complete=False), True),
        ("TC10 self-signed", "TC10" in run(self_signed=True), True),
        ("TC11 owner", "TC11" in run(owner=""), True),
        ("TC14 future", "TC14" in run(not_before="2026-12-01"), True),
    ]
    two = [dict(base, name="w1", sans=["*.example.com"], hosts=["a.example.com"]),
           dict(base, name="w2", sans=["*.example.com"], hosts=["a.example.com"], environment="staging")]
    cases.append(("TC13 shared wildcard", any(f["code"] == "TC13" for f in check(two, today)), True))
    three = [dict(base, name="c%d" % i, not_after="2027-01-0%d" % (i + 1)) for i in range(3)]
    cases.append(("TC15 cluster", any(f["code"] == "TC15" for f in check(three, today)), True))
    cases.append(("date formats", parse_date("Nov 11 10:00:00 2026 GMT") == dt.date(2026, 11, 11), True))
    ok = 0
    for name, got, want in cases:
        passed = got == want
        ok += passed
        print("%s  %s" % ("PASS" if passed else "FAIL", name))
    print("%d/%d passed" % (ok, len(cases)))
    return 0 if ok == len(cases) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("inventory", nargs="?")
    ap.add_argument("--today", help="as-of date YYYY-MM-DD (default: today)")
    ap.add_argument("--warn-days", type=int, default=30)
    ap.add_argument("--crit-days", type=int, default=14)
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.inventory:
        ap.print_usage(); return 2
    try:
        today = parse_date(a.today) if a.today else dt.date.today()
        certs = load(a.inventory, os.path.dirname(os.path.abspath(a.inventory)))
        findings = check(certs, today, a.warn_days, a.crit_days)
    except (OSError, ValueError, KeyError, json.JSONDecodeError, ssl.SSLError) as e:
        print("input error: %s" % e, file=sys.stderr)
        return 2
    if a.json:
        clean = [{k: v for k, v in c.items() if not k.startswith("_") or k == "_days_left"} for c in certs]
        print(json.dumps({"today": str(today), "certificates": clean, "findings": findings}, indent=2, default=str))
    else:
        print(report(certs, findings, today))
    return 1 if any(f["severity"] == "high" for f in findings) else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityInfrastructureMonitoring+3
F@f
0
CMake C++ Project taste
Taste

Opinionated conventions for modern, target-based CMake builds in portable C++ projects.

# CMake C++ Project taste of a systems developer who wants clean, portable builds
- Require a modern CMake (3.24 or newer) and write target-based CMake only, never global `include_directories` or `add_definitions`. Confidence: 0.90
- Attach include paths, flags and definitions to targets with `target_*` commands and the right `PUBLIC`, `PRIVATE` or `INTERFACE` scope. Confidence: 0.90
- Always build out of source, in a `build/` directory that is gitignored. Confidence: 0.95
- Commit a `CMakePresets.json` with debug, release and sanitizer presets so everyone configures the same way. Confidence: 0.85
- Set the language standard with `target_compile_features(... cxx_std_20)` instead of raw `-std=` flags. Confidence: 0.85
- Turn on strict warnings like `-Wall -Wextra -Wpedantic` or `/W4` through a shared interface target, and treat warnings as errors in CI. Confidence: 0.85
- Never use `file(GLOB)` for source lists; list source files explicitly so the build reruns when files change. Confidence: 0.75
- Get third-party libraries with `find_package` backed by vcpkg or Conan, and use `FetchContent` only for small, pinned dependencies. Confidence: 0.80
- Pin every fetched dependency to a tag or commit hash, never a moving branch. Confidence: 0.90
- Never vendor modified copies of libraries without a clear patch file and a note on why. Confidence: 0.75
- Run tests with CTest, and register each test executable with `add_test` or `gtest_discover_tests`. Confidence: 0.85
- Have a CI job that builds with AddressSanitizer and UndefinedBehaviorSanitizer and runs the full test suite. Confidence: 0.85
- Export `compile_commands.json` with `CMAKE_EXPORT_COMPILE_COMMANDS` so clangd and clang-tidy work out of the box. Confidence: 0.90
- Format with a committed `.clang-format` and check it in CI rather than arguing about style in reviews. Confidence: 0.85
- Use Ninja as the default generator for fast incremental builds, and ccache or sccache in CI. Confidence: 0.80
- Provide proper `install()` rules and an exported package config so other projects can use `find_package` on the library. Confidence: 0.75
- Namespace exported targets like `mylib::mylib` and create an alias target with the same name for in-tree use. Confidence: 0.80
- Keep options few and prefixed with the project name, such as `MYLIB_BUILD_TESTS`, and default tests off when used as a subproject. Confidence: 0.75
- Avoid setting `CMAKE_CXX_FLAGS` directly in `CMakeLists.txt`; leave global flags to presets and toolchain files. Confidence: 0.80
- Test the build on Linux, macOS and Windows in CI if the project claims to be portable. Confidence: 0.80
Best PracticesDevOpsTesting
F@f
0
Docker Compose taste
Taste

Opinionated conventions for Docker Compose files that give every developer a reliable one-command local stack.

# Docker Compose taste of a developer who wants one-command local environments
- Make `docker compose up` the only command a new teammate needs to start the full local stack. Confidence: 0.90
- Name the file `compose.yaml` and drop the obsolete top-level `version:` key. Confidence: 0.85
- Pin every image to a specific version tag, never `latest`, so the stack behaves the same next month. Confidence: 0.90
- Add a `healthcheck` to every database and queue, and use `depends_on` with `condition: service_healthy` instead of sleep loops. Confidence: 0.90
- Keep secrets and machine-specific values in a gitignored `.env` file, and commit a `.env.example` with safe defaults. Confidence: 0.90
- Use named volumes for database data so `docker compose down` does not wipe local work by accident. Confidence: 0.85
- Bind ports to `127.0.0.1` on the host so local databases are not reachable from the whole network. Confidence: 0.80
- Mount source code only for services you edit live, and use `develop.watch` or a bind mount with clear sync rules. Confidence: 0.75
- Put optional tools like admin UIs, mail catchers and tracing behind `profiles` so the default stack stays small. Confidence: 0.80
- Use `compose.override.yaml` for personal tweaks and keep it out of git. Confidence: 0.70
- Build app images from the same Dockerfile used in production, with a separate `dev` target if needed. Confidence: 0.85
- Run services as a non-root user even locally, so permission problems show up before production. Confidence: 0.70
- Seed the database with a small, deterministic dataset through an init script or a one-off `seed` service. Confidence: 0.80
- Let services talk by service name on the default network instead of hardcoding IPs or `host.docker.internal`. Confidence: 0.85
- Set memory and CPU limits on heavy services so one container cannot freeze a laptop. Confidence: 0.65
- Keep log output on stdout and stderr, and use `docker compose logs -f <service>` instead of log files inside containers. Confidence: 0.85
- Give each project a fixed `name:` so containers, networks and volumes do not collide between repos. Confidence: 0.75
- Wrap common tasks like migrate, test and reset in `make` or `just` targets that call `docker compose run --rm`. Confidence: 0.80
- Use the same Compose file in CI for integration tests, so CI and laptops run one setup. Confidence: 0.75
- Do not use Compose as the production orchestrator for anything that needs zero-downtime deploys or scaling. Confidence: 0.80
Best PracticesDockerDevOps
F@f
0
Gradle Build taste
Taste

Opinionated conventions for fast, reproducible and maintainable Gradle builds on the JVM.

# Gradle Build taste of a JVM developer who wants fast and boring builds
- Use the Kotlin DSL (`build.gradle.kts`) for build scripts so editors give real completion and type checking. Confidence: 0.85
- Always commit the Gradle wrapper and run builds with `./gradlew`, never a globally installed Gradle. Confidence: 0.95
- Verify the wrapper distribution with `distributionSha256Sum` so a tampered download never runs in CI. Confidence: 0.75
- Keep every dependency and plugin version in a `gradle/libs.versions.toml` version catalog. Confidence: 0.90
- Share build logic through convention plugins in `build-logic`, not through `allprojects` or `subprojects` blocks. Confidence: 0.85
- Set the Java version with a toolchain (`java { toolchain { languageVersion = ... } }`) instead of relying on whatever JDK is installed. Confidence: 0.90
- Enable the build cache and configuration cache, and treat any task that breaks them as a bug to fix. Confidence: 0.80
- Turn on `org.gradle.parallel=true` and a sensible `org.gradle.jvmargs` in `gradle.properties` checked into the repo. Confidence: 0.80
- Register tasks lazily with `tasks.register` and the Provider API; avoid `tasks.create` and eager configuration. Confidence: 0.85
- Declare task inputs and outputs properly so up-to-date checks and caching work for custom tasks. Confidence: 0.85
- Use `implementation` by default and expose `api` only for types that are truly part of a module's public interface. Confidence: 0.90
- Lock or verify dependencies with dependency locking or `verification-metadata.xml` for builds that ship to production. Confidence: 0.70
- Never use dynamic versions like `1.+` or `latest.release` in anything that gets released. Confidence: 0.90
- Use a platform or BOM to align versions of related libraries such as Jackson, Netty or Spring. Confidence: 0.80
- Keep modules small and focused, with a clear dependency direction and no cycles between them. Confidence: 0.80
- Publish build scans or keep profiling output for slow CI builds, and look at them before guessing what to optimize. Confidence: 0.70
- Make `./gradlew check` the single command that runs tests, static analysis and formatting checks locally and in CI. Confidence: 0.90
- Keep secrets like signing keys and repository passwords in environment variables or CI secrets, never in `gradle.properties` in the repo. Confidence: 0.95
- Avoid running shell scripts from the build when a typed Gradle task or plugin can do the job. Confidence: 0.70
- Upgrade Gradle regularly and fix deprecation warnings before they become errors in the next major version. Confidence: 0.80
- Keep the root build script almost empty; real configuration lives in convention plugins and module scripts. Confidence: 0.75
Best PracticesPerformanceAutomation+1
F@f
0
API Key and Credential Rotation Runbook (JSON)
Text

Turn any API key, database password, OAuth secret, signing key, cloud access key or certificate into a complete JSON rotation runbook: blast radius and consumer search, ordered zero-downtime rotation steps with verification and rollback, revocation, leak-incident extras, communications and prevention.

1You are a senior platform security engineer. Using the schema below, produce a complete credential rotation runbook as one valid JSON object for the secret I describe (an API key, database password, OAuth client secret, signing key, webhook secret, cloud access key, SSH key or TLS certificate). Ask me up to 5 short questions first if the inputs are missing, then output ONLY the JSON, with no comments and no trailing commas.
2
3My inputs:
4- Secret type and provider:
5- Where it is stored (vault, cloud secret manager, CI variables, .env files, Kubernetes secrets):
6- Every service, job, device or partner that uses it:
7- Reason for rotation (scheduled, employee offboarding, suspected leak, confirmed leak, compliance):
8- Can the provider keep two valid credentials at once (yes / no / unknown):
9- Allowed downtime and team size:
10
...+72 more lines
SecurityJSONInfrastructure+4
F@f
1
API Deprecation and Sunset Plan Builder (YAML)
Text

Turn an endpoint, field, API version or SDK method you want to retire into a complete YAML deprecation plan: timeline phases with exit criteria, deprecation and Sunset headers, changelog and SDK warnings, usage thresholds, customer communications, a migration guide with before/after examples, brownouts, exceptions, risks, rollback and final cleanup.

1You are a senior API platform engineer. Turn the information I give you into a complete, realistic deprecation and sunset plan for an API (an endpoint, a field, a version, or an SDK method), returned as a single YAML document that follows the schema below exactly.
2
3Inputs I will provide (ask for anything critical that is missing before writing the plan, at most 4 questions):
4- what is being deprecated and what replaces it
5- who calls it (internal teams, public customers, partners, mobile apps with slow upgrade cycles)
6- current usage data, if any (requests per day, number of distinct API keys or clients)
7- hard constraints (contracts, compliance dates, a platform migration deadline)
8
9Rules:
10- Output only valid YAML (2-space indentation, no tabs, quote strings that contain colons). Do not copy the schema comments into the output.
...+76 more lines
YAMLDocumentationMigration+4
F@f
0
Nginx Config taste
Taste

Opinionated conventions for writing safe, maintainable Nginx server configurations.

# Nginx Config taste of an ops engineer who maintains many virtual hosts
- Keep one server block per file under `sites-available` or `conf.d`, named after the domain it serves. Confidence: 0.85
- Put shared settings (TLS, security headers, proxy defaults) in snippet files and `include` them instead of copying blocks. Confidence: 0.90
- Run `nginx -t` before every reload and reload with `nginx -s reload` or `systemctl reload`, never a full restart. Confidence: 0.95
- Keep configs in version control and deploy them through automation, not by editing files on the server. Confidence: 0.90
- Redirect all plain HTTP to HTTPS with a single `return 301`, and keep the port 80 block for ACME challenges only. Confidence: 0.90
- Allow only TLS 1.2 and 1.3 with a modern cipher list, and enable OCSP stapling. Confidence: 0.90
- Automate certificates with Certbot or acme.sh and alert well before expiry. Confidence: 0.90
- Add HSTS only after HTTPS works everywhere, starting with a short `max-age` before going long. Confidence: 0.80
- Set `server_tokens off` and add basic security headers (`X-Content-Type-Options`, `Referrer-Policy`, `frame-ancestors` via CSP). Confidence: 0.85
- Define a default server that returns `444` so requests with unknown Host headers never reach an app. Confidence: 0.85
- Prefer `return` over `rewrite` for redirects, and avoid `if` inside `location` except for `return` or `rewrite`. Confidence: 0.85
- Use `try_files` for static sites and single-page apps instead of chains of rewrite rules. Confidence: 0.85
- Forward `Host`, `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Request-ID` to upstreams in one shared proxy snippet. Confidence: 0.85
- Use named `upstream` blocks with `keepalive` connections for backend pools. Confidence: 0.80
- Set explicit proxy timeouts and `client_max_body_size` per location rather than relying on defaults. Confidence: 0.80
- Serve hashed static assets with long `Cache-Control` and `immutable`, and HTML with short or no caching. Confidence: 0.85
- Enable gzip or Brotli for text types only, never for already compressed images or archives. Confidence: 0.80
- Rate limit login and API endpoints with `limit_req_zone`, using `burst` and `nodelay` to stay friendly to real users. Confidence: 0.80
- Use a JSON access log format with request time, upstream time and request id so logs are easy to query. Confidence: 0.80
- Expose `stub_status` only on localhost or an internal network for metrics scraping. Confidence: 0.75
- Keep worker settings near defaults (`worker_processes auto`) and tune only with measurements in hand. Confidence: 0.70
Best PracticesSecurityPerformance+1
F@f
0
Dependency Management taste
Taste

Opinionated conventions for keeping project dependencies safe, current and predictable.

# Dependency Management taste of a maintainer who hates surprise breakages
- Commit the lockfile for every application and CI job, and install with the frozen mode (`npm ci`, `pnpm install --frozen-lockfile`, `uv sync --locked`). Confidence: 0.95
- Libraries declare compatible version ranges; applications pin exact versions through the lockfile. Confidence: 0.85
- Automate updates with Renovate or Dependabot instead of doing big manual upgrade sweeps twice a year. Confidence: 0.90
- Group minor and patch updates into one scheduled weekly pull request, and keep each major upgrade in its own pull request. Confidence: 0.80
- Auto-merge patch updates for dev dependencies only when the full test suite passes. Confidence: 0.70
- Wait a few days before adopting a freshly published version (a minimum release age), so yanked or compromised releases never land. Confidence: 0.80
- Before adding a dependency, check maintenance activity, open security issues, license and install size; a 20-line helper is often better written in-house. Confidence: 0.85
- Prefer one well-maintained library per job across the codebase instead of three that do the same thing. Confidence: 0.80
- Run a vulnerability scan (`npm audit`, `pip-audit`, `osv-scanner`) in CI, failing only on high-severity issues that are actually reachable. Confidence: 0.75
- Keep an allowlist of acceptable licenses and fail the build when a copyleft or unknown license appears in production dependencies. Confidence: 0.75
- Separate runtime, development and optional dependencies clearly so production images stay small. Confidence: 0.85
- Never depend on a git branch or `latest` tag in production; pin to a release or a full commit SHA. Confidence: 0.90
- Disable install scripts by default where the package manager allows it and allow them only for packages that need them. Confidence: 0.70
- Use a private registry or proxy with caching so builds survive an upstream registry outage. Confidence: 0.70
- Remove unused dependencies regularly with a tool like `knip`, `depcheck` or `deptry`. Confidence: 0.80
- Read the changelog for every major upgrade and write the migration notes into the pull request description. Confidence: 0.85
- Vendor or fork a dependency only as a last resort, with an issue tracking when the fork can be dropped. Confidence: 0.75
- Keep the language runtime version pinned in one file (`.nvmrc`, `.python-version`, `rust-toolchain.toml`) that CI and local dev both read. Confidence: 0.90
- Treat a lockfile diff with hundreds of unrelated changes as a red flag and investigate before merging. Confidence: 0.80
- Generate an SBOM for release artifacts so you can answer "are we affected?" within minutes when a new CVE drops. Confidence: 0.65
Best PracticesSecurityDevOps
F@f
0
Secrets Management taste
Taste

Opinionated conventions for storing, injecting, rotating and auditing application secrets safely.

# Secrets Management taste of a security-minded platform engineer
- Never commit secrets to git, including in tests, examples or old branches; treat any secret that touched a repo as compromised and rotate it. Confidence: 1.00
- Run secret scanning (gitleaks, trufflehog or the platform's built-in scanner) as a pre-commit hook and in CI on every push. Confidence: 0.90
- Keep a committed `.env.example` with names and dummy values, and gitignore every real `.env` file. Confidence: 0.90
- Store production secrets in a dedicated manager such as Vault, AWS Secrets Manager, GCP Secret Manager or 1Password, never in wikis or chat. Confidence: 0.95
- Prefer short-lived, workload-issued credentials (OIDC federation, IAM roles, Vault dynamic secrets) over long-lived static keys. Confidence: 0.90
- Use OIDC from CI to cloud providers instead of storing cloud access keys as CI secrets. Confidence: 0.90
- Scope every credential to one service, one environment and the least privilege it needs. Confidence: 0.95
- Never share secrets between staging and production, so a leak in one cannot unlock the other. Confidence: 0.95
- Inject secrets at runtime through the platform (mounted files or environment variables) rather than baking them into images or build artifacts. Confidence: 0.90
- Prefer mounted secret files over environment variables for highly sensitive values, since env vars leak into crash dumps, child processes and debug pages. Confidence: 0.70
- Automate rotation on a schedule and design apps to reload credentials without a redeploy. Confidence: 0.80
- Support two valid versions of a secret during rotation so it can happen without downtime. Confidence: 0.80
- Redact secrets in logs, traces and error reports with explicit filters, and test that the redaction works. Confidence: 0.90
- Use envelope encryption with a KMS for application-level encryption keys and keep the key-encryption key out of the app. Confidence: 0.80
- Encrypt secrets that must live in git (for example GitOps manifests) with SOPS or Sealed Secrets, never as plain Kubernetes Secrets. Confidence: 0.85
- Audit-log every secret read and alert on unusual access patterns. Confidence: 0.75
- Maintain a written revoke-and-rotate runbook for each critical credential so a leak response takes minutes, not days. Confidence: 0.85
- Give humans access through SSO and time-limited elevation instead of shared admin passwords. Confidence: 0.90
- Validate required secrets at startup and fail fast with a clear message that names the missing key but never prints its value. Confidence: 0.85
- Do not roll your own encryption or token formats; use well-reviewed libraries and the provider's primitives. Confidence: 0.95
Best PracticesSecurityCloud+2
F@f
0
Linux Server Hardening taste
Taste

Opinionated defaults for hardening and operating secure Linux servers in production.

# Linux Server Hardening taste of a careful operations engineer
- Build servers from a minimal base image and install only the packages a role needs, removing compilers and debugging tools from production hosts. Confidence: 0.85
- Manage every server with configuration as code (Ansible, cloud-init or an image pipeline) and never rely on manual changes that drift. Confidence: 0.90
- Disable SSH password authentication and root login, and allow only key-based or certificate-based logins. Confidence: 0.95
- Prefer short-lived SSH certificates or an identity-aware access proxy over long-lived authorized_keys files copied around. Confidence: 0.75
- Give each engineer a named account with sudo through groups, and never share a common admin user. Confidence: 0.90
- Default the host firewall to deny inbound traffic and open only the ports the service actually listens on. Confidence: 0.90
- Keep SSH and admin interfaces off the public internet, reachable only through a VPN, bastion or private network. Confidence: 0.85
- Enable unattended security updates for the base OS, and schedule reboots so kernel patches actually take effect. Confidence: 0.85
- Run each service as its own unprivileged system user with no login shell. Confidence: 0.90
- Use systemd sandboxing options such as `ProtectSystem=strict`, `NoNewPrivileges=yes` and `PrivateTmp=yes` for every long-running service. Confidence: 0.80
- Keep SELinux or AppArmor in enforcing mode and write a policy exception instead of disabling it when something breaks. Confidence: 0.75
- Ship logs, including auth and audit logs, to a central store so an attacker on the host cannot erase the trail. Confidence: 0.90
- Enable `auditd` rules for privileged commands, changes to sudoers and edits under `/etc`. Confidence: 0.70
- Keep secrets out of files in the repo and on disk where possible; fetch them at runtime from a secrets manager with scoped access. Confidence: 0.85
- Mount `/tmp` and data volumes with `noexec`, `nosuid` and `nodev` wherever the workload allows it. Confidence: 0.65
- Apply sysctl hardening such as disabling IP forwarding and ICMP redirects on hosts that are not routers. Confidence: 0.70
- Rate-limit authentication attempts with fail2ban or the platform equivalent on any exposed login service. Confidence: 0.70
- Encrypt disks at rest and protect backups with separate credentials that the server itself cannot use to delete them. Confidence: 0.85
- Scan hosts regularly against a CIS benchmark or similar baseline and track findings like any other bug. Confidence: 0.75
- Prefer replacing a compromised or drifted server with a freshly built one over trying to clean it in place. Confidence: 0.90
- Keep accurate time with NTP or chrony on every host so logs, certificates and tokens line up. Confidence: 0.80
Best PracticesSecurityInfrastructure+2
F@f
0
Kafka Streaming taste
Taste

Opinionated conventions for reliable, schema-governed Kafka event streaming and consumers.

# Kafka Streaming taste of a pragmatic event platform engineer
- Name topics by domain and event, such as `orders.order-placed.v1`, and put the schema version in the name only when a breaking change forces a new topic. Confidence: 0.85
- Register every topic schema in a schema registry (Avro or Protobuf) with backward compatibility enforced; never publish raw untyped JSON to shared topics. Confidence: 0.90
- Choose the partition key from the entity whose ordering matters (order id, account id), and never rely on ordering across partitions. Confidence: 0.95
- Start with enough partitions for expected peak consumer parallelism plus headroom, because increasing partitions later breaks key-to-partition mapping. Confidence: 0.80
- Run producers with `acks=all`, idempotence enabled and `min.insync.replicas=2` on a replication factor of 3 for anything business-critical. Confidence: 0.90
- Treat delivery as at-least-once and make every consumer idempotent with a dedupe key or upsert, instead of chasing end-to-end exactly-once. Confidence: 0.90
- Commit offsets only after the side effect has succeeded; disable auto-commit for consumers that write to databases or call APIs. Confidence: 0.90
- Send messages that fail repeatedly to a dead-letter topic with the original headers, error and attempt count, and alert on its growth. Confidence: 0.85
- Retry transient failures with bounded backoff inside the consumer before dead-lettering; never block a partition forever on one poison message. Confidence: 0.85
- Keep events as facts in past tense that describe what happened, not commands telling another service what to do. Confidence: 0.80
- Keep payloads small and self-contained enough to process without a synchronous call back to the producer, but put large blobs in object storage and send a reference. Confidence: 0.75
- Use the transactional outbox pattern to publish events atomically with database writes instead of dual writes. Confidence: 0.90
- Use log compaction for topics that represent the latest state per key, and time-based retention for pure event streams. Confidence: 0.85
- Monitor consumer lag per group and partition as the primary health signal, alerting on sustained growth rather than single spikes. Confidence: 0.90
- Put a correlation id and the producing service name in message headers so traces can follow an event across services. Confidence: 0.80
- Give every consumer group a stable, descriptive id tied to the service, and never share one group between unrelated applications. Confidence: 0.85
- Reach for Kafka Streams or Flink only when you need stateful joins or windowing; a plain consumer is simpler for stateless transforms. Confidence: 0.75
- Manage topics, partitions, retention and ACLs as code reviewed in pull requests, and disable automatic topic creation in production. Confidence: 0.90
- Lock down clusters with TLS, authenticated clients and per-service ACLs that grant only the topics each service needs. Confidence: 0.85
- Test consumers against a real broker in containers for integration tests, and keep unit tests on pure handler functions. Confidence: 0.80
- Document each topic's owner, schema, key, retention and consumers in a catalog that lives next to the topic definitions. Confidence: 0.70
Best PracticesArchitectureEvent Driven+2
F@f
0
Helm Chart taste
Taste

Opinionated conventions for packaging and shipping Kubernetes applications with Helm.

# Helm Chart taste of a Kubernetes packaging engineer
- One chart per deployable application, with a clear `Chart.yaml` name, version and `appVersion` that track semver. Confidence: 0.90
- Keep default `values.yaml` safe for a non-production install, and document every key in `values.schema.json` or a VALUES.md. Confidence: 0.85
- Prefer the official Helm library patterns and bitnami-style helpers sparingly; copy only helpers you understand. Confidence: 0.75
- Template labels and selectors from a single `_helpers.tpl` so Services always match Pods. Confidence: 0.95
- Never hard-code namespaces in templates; take them from `Release.Namespace` or an explicit value. Confidence: 0.90
- Pin image tags to digests or immutable tags in production values; forbid `latest` in the schema. Confidence: 0.90
- Set resource requests and limits for every container, with defaults that fit a small cluster and overrides for prod. Confidence: 0.85
- Include readiness and liveness probes with realistic delays; a wrong probe is worse than no probe. Confidence: 0.85
- Manage config with ConfigMaps and secrets via sealed-secrets, SOPS or external-secrets—not plaintext in git. Confidence: 0.95
- Use `required` and `fail` in templates for mandatory values so misconfiguration fails at install time. Confidence: 0.85
- Run `helm lint`, `helm template` and a kubeconform/kubeval check in CI on every chart change. Confidence: 0.90
- Test with `helm unittest` or snapshot templates for labels, ports and probes so refactors cannot silently break installs. Confidence: 0.80
- Version the chart independently of the app when only packaging changes; bump `appVersion` when the image changes. Confidence: 0.80
- Prefer small umbrellas only when services truly share a release lifecycle; otherwise deploy charts separately with GitOps. Confidence: 0.75
- Support `extraEnv`, `extraVolumes` and `affinity` hooks so operators can extend without forking the chart. Confidence: 0.80
- Keep RBAC templates opt-in and least-privilege; default ServiceAccounts should not mount the API token unless needed. Confidence: 0.85
- Document upgrade notes in `README.md` for breaking values renames, and provide a values migration example. Confidence: 0.80
- Publish charts to an OCI registry or ChartMuseum from CI with signed provenance; do not `helm push` from a laptop. Confidence: 0.80
- Align with GitOps (Argo CD or Flux) by making charts render cleanly with only values files—no manual `helm upgrade` steps. Confidence: 0.85
- Cap chart complexity: if templates need heavy logic, move it to a controller or operators instead of growing Gotpl. Confidence: 0.75
- Review `helm diff` output before applying to production and require a human approval gate on the deploy Environment. Confidence: 0.85
Best PracticesInfrastructureInfrastructure as Code+2
F@f
0
GitHub Actions taste
Taste

Opinionated conventions for reliable, least-privilege GitHub Actions CI and deploy workflows.

# GitHub Actions taste of a CI-first platform engineer
- Keep every workflow under `.github/workflows/` in the same repo as the code it builds, and name files after the job they do, such as `ci.yml` or `release.yml`. Confidence: 0.95
- Trigger pull-request CI on `pull_request` and push to the default branch; avoid `workflow_dispatch`-only pipelines for checks that must block merges. Confidence: 0.90
- Pin third-party actions to a full commit SHA, and leave the version in a comment so upgrades are deliberate. Confidence: 0.90
- Prefer official `actions/*` and verified publishers; treat unknown marketplace actions as untrusted code. Confidence: 0.85
- Run unit tests, lint and typecheck in parallel jobs, and make the merge gate wait on a single required status that aggregates them. Confidence: 0.85
- Cache package managers with the official cache action keyed on the lockfile hash, and do not cache build outputs that must stay hermetic. Confidence: 0.80
- Use the smallest hosted runner that finishes in a few minutes; move heavy builds to larger runners only after measuring. Confidence: 0.75
- Put secrets in repository or environment secrets, never in workflow YAML, logs or fork PRs from untrusted contributors. Confidence: 0.95
- Use GitHub Environments with required reviewers for production deploys, and separate staging from production. Confidence: 0.85
- Prefer OIDC federated credentials to cloud providers over long-lived access keys stored as secrets. Confidence: 0.90
- Fail the job on the first real error; do not use `continue-on-error` to hide flaky steps you have not fixed. Confidence: 0.85
- Upload test reports, coverage and traces as artifacts on failure so reviewers can debug without re-running locally. Confidence: 0.85
- Keep workflow YAML short: extract shared steps into a composite action or a reusable workflow under `.github/workflows/`. Confidence: 0.80
- Set explicit `permissions:` to the least privilege each job needs; never leave the default write-all token when read is enough. Confidence: 0.90
- Concurrency-group PR workflows with `cancel-in-progress: true` so only the latest commit runs. Confidence: 0.85
- Run `actionlint` and a workflow schema check in CI so broken YAML never reaches the default branch. Confidence: 0.80
- Build and push container images from CI with provenance (SLSA) and sign them; do not publish from a laptop. Confidence: 0.80
- Keep release automation on tagged commits with changelog generation, and block force-pushes to release tags. Confidence: 0.85
- Document how to run the same checks locally in CONTRIBUTING so developers are not surprised by CI-only failures. Confidence: 0.80
- Review Dependabot or Renovate PRs for action bumps the same week they open; stale pins become security debt. Confidence: 0.75
Best PracticesAutomationCI/CD+2
F@f
0
Cloudflare Worker taste
Taste

Opinionated conventions for focused, well-bound Cloudflare Workers at the edge.

# Cloudflare Worker taste of an edge-first platform engineer
- Prefer Wrangler for local dev, secrets, and deploys; keep `wrangler.toml` (or `wrangler.json`) as the source of truth for bindings. Confidence: 0.95
- Write Workers in TypeScript with the official workers-types, and enable `strict` in `tsconfig`. Confidence: 0.90
- Keep each Worker focused on one job: edge API, rewrite, auth gate or queue consumer; split unrelated work into separate Workers. Confidence: 0.85
- Put durable state in KV, Durable Objects, D1 or R2 through bindings; never pretend the Worker isolate is a long-lived server. Confidence: 0.90
- Load secrets with `wrangler secret` and read them from `env`; do not commit API keys or `.dev.vars` with real values. Confidence: 0.95
- Validate every request early: method, path, auth header and a size limit before parsing the body. Confidence: 0.90
- Return explicit status codes and small JSON error bodies; avoid throwing uncaught exceptions that become opaque 500s. Confidence: 0.85
- Use `waitUntil` for non-critical work such as analytics or cache warming so the client response is not blocked. Confidence: 0.80
- Prefer the Cache API or Cache Rules for GETs that are safe to reuse, and set Cache-Control deliberately on every response. Confidence: 0.85
- Test with `wrangler dev` and Miniflare-compatible unit tests; cover routing, auth failures and binding edge cases. Confidence: 0.85
- Pin compatibility date in Wrangler config and bump it on purpose after reading the runtime changelog. Confidence: 0.85
- Use Durable Objects when you need strong consistency per key (rooms, counters, locks); use KV for eventually consistent reads. Confidence: 0.85
- Stream large responses and uploads when possible; avoid buffering whole files in memory inside the isolate. Confidence: 0.80
- Log with structured JSON fields (request id, route, status, duration) and ship them to your observability sink. Confidence: 0.80
- Gate production deploys behind a staging route or environment, and smoke-test the worker URL before shifting traffic. Confidence: 0.85
- Keep CPU-heavy work short; move bulk transforms and ML to Queues, Workflows or an origin service. Confidence: 0.85
- Prefer fetch to first-party Cloudflare services over stuffing large SDKs into the Worker bundle. Confidence: 0.75
- Review the bundle size on every change; drop unused deps and avoid Node polyfills you do not need. Confidence: 0.80
- Document every binding and its purpose at the top of the Worker entry file so onboarding does not require tribal knowledge. Confidence: 0.75
- Treat cron Triggers and Queue consumers as first-class entrypoints with the same validation and logging standards as HTTP. Confidence: 0.80
Best PracticesPerformanceDevOps+2
F@f
0
Load Testing taste
Taste

Opinionated conventions for planning, running and reading load and performance tests for web services.

# Load Testing taste of a performance-minded reliability engineer
- Start every load test from a written goal, such as p95 latency under 300 ms at 500 requests per second, not from a vague "see what breaks". Confidence: 0.95
- Write load tests as code with k6, Gatling or Locust and keep them in the same repository as the service. Confidence: 0.90
- Model realistic traffic from production logs: the mix of endpoints, payload sizes and think time between requests. Confidence: 0.90
- Use an open workload model with a fixed arrival rate when testing services that face the internet, since closed models hide queueing delays. Confidence: 0.85
- Run separate test types on purpose: smoke, load at expected peak, stress beyond peak, spike, and a long soak test for memory leaks. Confidence: 0.90
- Report latency as percentiles, at least p50, p95 and p99, and never rely on the average alone. Confidence: 0.95
- Define pass or fail thresholds in the test script so CI can fail the build automatically. Confidence: 0.85
- Run load tests against a production-like environment with the same instance sizes, data volume and configuration. Confidence: 0.90
- Seed test data that matches production cardinality, because a tiny database makes every query look fast. Confidence: 0.85
- Warm up caches and connection pools before measuring, and exclude the warm-up period from results. Confidence: 0.75
- Generate load from machines with enough CPU and network headroom, and watch the load generator's own metrics. Confidence: 0.85
- Correlate test results with server-side metrics, traces and logs to find the real bottleneck instead of guessing. Confidence: 0.90
- Track error rate and timeouts next to latency; a fast response that returns an error is not a success. Confidence: 0.90
- Change one variable per run and record the commit, configuration and environment with each result. Confidence: 0.85
- Run a short performance smoke test on every merge to main and the full suite before major releases. Confidence: 0.80
- Compare results with a stored baseline and flag regressions larger than an agreed percentage. Confidence: 0.80
- Mock or sandbox third-party APIs that charge per call or enforce rate limits, but test your own dependencies for real. Confidence: 0.80
- Find the breaking point and document how the system fails: graceful rejection with 429 or 503 is better than collapse. Confidence: 0.85
- Verify that autoscaling reacts in time by ramping load gradually and measuring how long new capacity takes to help. Confidence: 0.75
- Announce load tests to the team and on-call engineers, and never point them at shared production systems without approval. Confidence: 0.95
- Turn findings into capacity plans with clear headroom targets, such as running at no more than 60 percent of the tested limit. Confidence: 0.70
Best PracticesPerformanceMonitoring+2
F@f
0
systemd Service Unit Hardening Reviewer
Skill

Reviews systemd .service units and their drop-ins - flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak restart and stop timeouts, network-online ordering, missing [Install], and sandbox options that will break startup. Scores exposure and writes a hardening drop-in. Includes an offline stdlib Python checker.

---
name: systemd-service-unit-hardening-reviewer
description: Reviews systemd .service units and their drop-ins - flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak restart and stop timeouts, network-online ordering, missing [Install], and sandbox options that will break startup. Scores exposure and writes a hardening drop-in. Includes an offline stdlib Python checker.
---

# systemd Service Unit Hardening Reviewer

You help developers and admins ship systemd service units that start reliably and do not hand an attacker the whole machine. Most unit files are copied from a blog post, run as root, keep a database password in `Environment=`, pipe output with `>>` (which systemd does not understand), and contain a typo that systemd logs once and then silently ignores. Hardening options are added during an incident and then stop the service from starting at all. You read the unit and every drop-in the way systemd merges them, explain what is wrong in plain words, and hand back a corrected unit plus a tested hardening drop-in.

You review the text you are given. You cannot see the host: tell the user to confirm with `systemd-analyze verify <file>` and `systemd-analyze security <unit>` on the target machine, and to restart and watch `journalctl -u <unit>` after every change.

## Files in this skill

- `scripts/systemd_unit_review.py` - parses a .service file plus drop-in .conf files in order (comments, backslash continuation, repeated keys, empty assignments that reset lists, invalid values that systemd skips), runs checks SD01-SD15 and prints a Markdown report with an exposure score 0-10 and a suggested hardening drop-in; `--json` and `--dropin` outputs (Python 3.8+ standard library only)
- `references/directives-and-sandboxing.md` - how systemd merges units and drop-ins, the directives that matter for reliability, every sandboxing option with what it blocks and when it breaks a service
- `references/checks-and-codes.md` - every finding code, its severity and the fix
- `templates/unit-review.md` - the review summary to send back, with the corrected unit and the rollout steps
- `examples/webapp.service` + `examples/webapp-override.conf` - a hand-deployed Node.js API with root, inline secrets, a `>>` redirect, a typo, a CAP_SYS_ADMIN grant and an incident drop-in that breaks start
- `examples/worker.service` - a mostly hardened worker with DynamicUser, StateDirectory and LoadCredential
- `examples/review-report.md` - the real checker output on both units

## Workflow

### 1. Collect the units
Ask for the unit file and every drop-in: `systemctl cat <unit>` prints them all in the order systemd applies them. Ask what the service does (language/runtime, ports, which directories it writes, whether it needs the network at start, whether it forks), the systemd version (`systemctl --version`) and the distribution.

### 2. Run the checker
```
python3 scripts/systemd_unit_review.py examples/webapp.service examples/webapp-override.conf examples/worker.service
python3 scripts/systemd_unit_review.py myapp.service override.conf --dropin
python3 scripts/systemd_unit_review.py myapp.service --json
python3 scripts/systemd_unit_review.py --self-test
```
Files after a .service are its drop-ins until the next .service. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, merge the drop-ins by hand (later wins, empty list assignment resets) and walk `references/checks-and-codes.md`.

### 3. Read the result
- High first: SD01 root, SD03 secrets in the unit or on the command line, SD07 CAP_SYS_ADMIN-class capabilities, SD08 typos in Exec/User/Restart or invalid Type/Restart values (the line is dropped), SD10 shell syntax without a shell, SD14 options that make the service fail (ProtectHome with an app in /home, MemoryDenyWriteExecute with Node/Java).
- Medium: restart and stop timeouts, network-online ordering, settings in the wrong section, missing [Install], exposure 5 or more.
- Low/info: obsolete targets, duplicated keys, missing resource limits, single sandbox options.

### 4. Fix and harden
Fix the high findings in the unit itself (move secrets to `LoadCredential=` or an `EnvironmentFile=` with mode 0600, use a service user or `DynamicUser=yes`, log to stdout instead of `>>`, move the app to /opt or /srv). Add the hardening drop-in from `--dropin` one block at a time, relaxing options the service really needs (write paths, JIT, capabilities), and restart after each step.

### 5. Deliver
Fill `templates/unit-review.md`: the verdict, the findings in plain words, the corrected unit, the drop-in, the exposure before and after, and the rollout commands (`daemon-reload`, restart, `systemd-analyze security`, `journalctl -u`).

## Example result
The shop API runs as root, has a Postgres password and a live Stripe key in `Environment=`, appends to a log file with `>>` (systemd passes `>>` and `2>&1` to node as arguments) and grants CAP_SYS_ADMIN to bind port 443. `RestartSecs=5` is a typo, so restarts come every 100 ms. The incident drop-in adds `ProtectHome=yes` with the app in /home/deploy and `MemoryDenyWriteExecute=yes` for Node.js - both stop it from starting - and its `Restart=on-faliure` is ignored. 9 high findings, exposure 8.1. The worker is in good shape (exposure 1.2, six optional options to add).

## Rules

- Never print or repeat a secret value found in a unit; name the variable and tell the user to rotate it, since it was readable by every local user.
- Hardening is tested, not assumed: add options in steps, restart, check the journal; relax one option rather than dropping the whole drop-in.
- Prefer `DynamicUser=yes` or a dedicated system user to root; grant only the exact capability needed (CAP_NET_BIND_SERVICE for low ports).
- Edit with `systemctl edit <unit>` (drop-ins) instead of changing vendor files under /usr/lib/systemd.
- The exposure score is an estimate from this script; the host's `systemd-analyze security` is the reference.
FILE:references/directives-and-sandboxing.md
# Directives and sandboxing notes

## How systemd builds the unit
- Files: the main unit (/etc/systemd/system, else /usr/lib/systemd/system) then drop-ins `<unit>.d/*.conf` in name order. `systemctl cat <unit>` shows them all.
- Later assignments win for single-value keys. List keys (After=, Environment=, ExecStartPre=, ReadWritePaths= ...) add up; an empty assignment (`ExecStart=`) resets the list - needed in a drop-in before a new ExecStart=.
- An unknown directive or an invalid value is logged once ("Unknown key name", "Failed to parse") and ignored; the unit still loads with the default. That is why typos survive for years.
- Lines ending in `\` continue on the next line. `#` and `;` start comments only at the start of a line.
- `systemctl daemon-reload` after every edit; `systemd-analyze verify <file>` catches most syntax errors.

## Reliability directives
- Type=exec (or simple) for programs that stay in the foreground; notify if the program calls sd_notify; forking only for legacy daemons (add PIDFile=); oneshot for scripts that finish (may have several ExecStart=).
- Restart=on-failure + RestartSec=5s for most services. Restart=always also restarts after a clean exit. Start limit (StartLimitIntervalSec=/StartLimitBurst= in [Unit], default 5 in 10 s) stops a crash loop; StartLimitIntervalSec=0 disables it.
- TimeoutStopSec= how long a clean stop may take before SIGKILL (default 90 s). infinity hangs shutdowns.
- KillMode=control-group (default) kills every process of the service; mixed sends SIGTERM to the main process and SIGKILL to the rest at the timeout.
- Network: `Wants=network-online.target` + `After=network-online.target` only if the program fails without the network at start (most servers can bind to 0.0.0.0 without it).
- Logs: write to stdout/stderr; journald stores them (`journalctl -u <unit>`). Use LogsDirectory= if a file is required.
- [Install] WantedBy=multi-user.target so `systemctl enable` starts it at boot.

## Exec lines are not shell
systemd splits the line into words itself: `|`, `>`, `>>`, `2>&1`, `&&`, `;`, `&`, `$(...)` and backticks are passed to the program as arguments. `$VAR` and `VAR` are expanded from Environment=. If you need a shell use `ExecStart=/bin/sh -c '...'`, but a small script is easier to read and test. Prefixes: `-` ignore failure, `@` argv0, `+` full privileges, `!` privileges without the user switch (both skip the sandbox).

## Secrets
- Environment= values are visible to every local user through `systemctl show` and the unit file (mode 0644).
- `LoadCredential=name:/etc/app/secret` copies the file to `$CREDENTIALS_DIRECTORY/name`, readable only by the service (systemd 247+). `SetCredentialEncrypted=` / `systemd-creds` for encrypted ones (250+).
- EnvironmentFile=/etc/app/env with owner root and mode 0600 is the portable fallback.
- Command-line secrets are visible in `ps` and /proc/<pid>/cmdline.

## Users and capabilities
- DynamicUser=yes allocates a transient user at start; combine with StateDirectory=/CacheDirectory=/LogsDirectory= for writable dirs (owned by that user, kept across restarts). Implies ProtectSystem=strict, ProtectHome=read-only, PrivateTmp.
- Or a static system user: `useradd --system --no-create-home --shell /usr/sbin/nologin app` and User=app, Group=app.
- Port below 1024 as non-root: `AmbientCapabilities=CAP_NET_BIND_SERVICE` and `CapabilityBoundingSet=CAP_NET_BIND_SERVICE`. CAP_SYS_ADMIN is almost root - never for a web app.

## Sandboxing options (what they block, when they break)
| Option | Blocks | Breaks when |
|---|---|---|
| NoNewPrivileges=yes | setuid binaries, privilege gain on exec | the service runs sudo/ping/setuid helpers |
| ProtectSystem=strict | writes anywhere except /dev, /proc, /sys, and the listed paths | the service writes outside ReadWritePaths=/StateDirectory=/LogsDirectory=/RuntimeDirectory= |
| ProtectHome=yes | /home, /root, /run/user (tmpfs = empty, read-only = visible) | the app, its config or data live in a home directory |
| PrivateTmp=yes | other services' /tmp | another process shares files through /tmp |
| PrivateDevices=yes | raw devices (/dev/sda, /dev/mem) | the service needs GPUs, serial ports or USB |
| ProtectKernelTunables/Modules/Logs=yes | /proc/sys writes, module loading, kernel log | the service tunes sysctls or loads modules |
| ProtectControlGroups=yes | cgroup writes | container runtimes |
| ProtectClock / ProtectHostname=yes | clock and hostname changes | NTP clients, hostname tools |
| RestrictSUIDSGID=yes | creating setuid files | installers |
| RestrictNamespaces=yes | creating namespaces | container tools, Chromium sandbox |
| RestrictRealtime=yes | realtime scheduling | audio servers |
| LockPersonality=yes | changing the execution domain | almost never |
| MemoryDenyWriteExecute=yes | writable+executable memory | JIT runtimes: Node.js, Java, .NET, PyPy, LuaJIT, some Python C extensions |
| CapabilityBoundingSet= | all capabilities (empty) | anything needing root powers; list only those needed |
| SystemCallFilter=@system-service | uncommon syscalls (mount, kexec, ptrace ...) | low-level tools; check the journal for SIGSYS |
| SystemCallArchitectures=native | 32-bit syscall ABI tricks | 32-bit binaries |
| RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | netlink, packet, bluetooth sockets | tools that read routing tables (add AF_NETLINK) |
| UMask=0077 | world-readable new files | other users must read the files |

Rollout: apply in two or three steps (filesystem options, then kernel/namespace options, then syscalls and capabilities), restart, run the health check, read `journalctl -u <unit> -b`, then `systemd-analyze security <unit>`.
FILE:references/checks-and-codes.md
# Checks and finding codes

| Code | Severity | Check | Fix |
|---|---|---|---|
| SD01 | high (medium for oneshot) | runs as root: no User= and no DynamicUser=, or User=root; `+`/`!` Exec prefixes bypass the user and sandbox (medium) | DynamicUser=yes or a system user; drop the prefix |
| SD02 | high: no ExecStart, several ExecStart for a non-oneshot; low: command not an absolute path | ExecStart sanity | one absolute ExecStart; empty `ExecStart=` first in a drop-in to replace it |
| SD03 | high | secret-looking variable (PASSWORD, SECRET, TOKEN, API_KEY, PRIVATE_KEY, DSN) or a URL with user:password in Environment=; `--password=` style secrets on the command line | LoadCredential= or EnvironmentFile= with mode 0600; rotate the leaked secret |
| SD04 | medium: Restart=no for a long-running service; low: no RestartSec (100 ms default); high: oneshot with Restart=always/on-success; info: Restart=always with the default start limit | restart policy | Restart=on-failure, RestartSec=5s |
| SD05 | medium: After= and Wants= of network-online.target not paired; low: obsolete syslog.target / network.service | ordering | add the missing half |
| SD06 | medium if exposure >= 5, else low | sandboxing options missing (weighted exposure score) | the `--dropin` output, tested step by step |
| SD07 | high: CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_PTRACE, CAP_SYS_RAWIO; medium: CAP_DAC_OVERRIDE, CAP_NET_ADMIN, CAP_SETUID/SETGID; low: others | dangerous capabilities in AmbientCapabilities / CapabilityBoundingSet | keep only what is needed |
| SD08 | high: unknown Exec*/User*/Restart* directive or invalid Type/Restart value; medium: other unknown directive, invalid value, bad boolean, line without `=`, assignment before a section, unknown section | systemd logs a warning and ignores the line | fix the spelling (suggestion shown) |
| SD09 | medium | directive in the wrong section (StartLimitBurst in [Service], WantedBy in [Service], old StartLimitInterval) | move it |
| SD10 | high: pipes, redirects, `&&`, `;`, `&` or `$( )` in an Exec line without `/bin/sh -c`; medium: nohup / --daemon with Type=simple/exec; low: Type=forking without PIDFile | systemd does not use a shell | a script, `sh -c`, or foreground mode |
| SD11 | medium: no WantedBy/RequiredBy/Alias; low: WantedBy=default.target or graphical.target for a system service | enable at boot | WantedBy=multi-user.target |
| SD12 | medium: TimeoutStopSec=infinity/0, KillMode=none; low: KillMode=process | stop behaviour | TimeoutStopSec=30s, KillMode=mixed |
| SD13 | low | the same single-value key twice in one file | keep one |
| SD14 | high: ProtectHome=yes/tmpfs with an app, working dir or env file under /home or /root; MemoryDenyWriteExecute with node/java/dotnet/pypy/bun/deno; medium: ProtectSystem=strict with a write path not in ReadWritePaths/StateDirectory/LogsDirectory/RuntimeDirectory | options that break the service | move the app, add the write path, drop the option |
| SD15 | info | no MemoryMax/MemoryHigh/TasksMax/CPUQuota | add limits from observed usage |

## Exposure score
Weights (sum 10): run as non-root 2.0, ProtectSystem=strict 1.0 (full/yes counts half), NoNewPrivileges 0.8, ProtectHome 0.6, CapabilityBoundingSet without dangerous caps 0.6, PrivateTmp 0.5, PrivateDevices 0.5, ProtectKernelTunables 0.4, ProtectKernelModules 0.4, RestrictNamespaces 0.4, SystemCallFilter 0.4, RestrictAddressFamilies 0.4, ProtectControlGroups 0.3, RestrictSUIDSGID 0.3, MemoryDenyWriteExecute 0.3, ProtectKernelLogs 0.2, ProtectClock 0.2, RestrictRealtime 0.2, UMask 0077/0027 0.2, ProtectHostname 0.1, LockPersonality 0.1, SystemCallArchitectures=native 0.1.
Rating: under 2 OK, under 5 MEDIUM, under 8 EXPOSED, 8 or more UNSAFE.

## Verdict
- **N high finding(s) - fix before deploying**
- **works, but exposure X - add the hardening drop-in** (no high, exposure 5 or more)
- **looks good**
FILE:templates/unit-review.md
# systemd unit review: <unit name>

**Host:** <distro, systemd version>   **Runtime:** <Node.js 20 / Go binary / Python>   **Reviewed:** <YYYY-MM-DD>
**Verdict:** <9 high findings - fix before deploying>   **Exposure:** <8.1 before -> 1.5 after>

## Must fix
| # | Problem | Why it matters | Fix |
|---|---|---|---|
| 1 | <runs as root> | <an exploit owns the machine> | <DynamicUser=yes + CAP_NET_BIND_SERVICE for port 443> |
| 2 | <secret STRIPE_SECRET_KEY in Environment=> | <readable by every local user - rotate it> | <LoadCredential=stripe:/etc/shop-api/stripe> |

## Should fix
- <Restart/RestartSec, network-online pairing, [Install], stop timeout>

## Corrected unit
```ini
<full corrected .service file>
```

## Hardening drop-in (`systemctl edit <unit>`)
```ini
<drop-in from --dropin, adjusted for this service>
```

## Rollout
1. Rotate the leaked secrets; put the new ones in /etc/<name>/ (mode 0600).
2. `systemd-analyze verify /etc/systemd/system/<unit>`
3. `systemctl daemon-reload && systemctl restart <unit>`; check `journalctl -u <unit> -b` and the health endpoint.
4. `systemd-analyze security <unit>` - expect <exposure>.
5. Roll back: `systemctl revert <unit>` removes the drop-ins.

## Open questions
- [ ] <which directories does it write?>
- [ ] <does it need the network at start?>
FILE:examples/webapp.service
# /etc/systemd/system/shopapi.service - Node.js shop API, deployed by hand in 2023
[Unit]
Description=Shop API (Node.js)
After=network-online.target syslog.target
StartLimitBurst=3

[Service]
Type=simple
WorkingDirectory=/home/deploy/shop-api
Environment=NODE_ENV=production PORT=443
Environment="DATABASE_URL=postgres://shop:Winter2024@db.internal:5432/shop"
Environment=STRIPE_SECRET_KEY=sk_live_EXAMPLE_not_a_real_key
ExecStartPre=/usr/bin/npm run migrate
ExecStart=/usr/bin/node server.js >> /var/log/shop-api.log 2>&1
Restart=always
RestartSecs=5
AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_SYS_ADMIN
TimeoutStopSec=infinity
ProtectSystem=full
PrivateTmp=yes
FILE:examples/webapp-override.conf
# /etc/systemd/system/shopapi.service.d/override.conf - added during an incident
[Service]
ProtectHome=yes
MemoryDenyWriteExecute=yes
Restart=on-faliure
FILE:examples/worker.service
# /etc/systemd/system/thumbnailer.service - image thumbnail worker
[Unit]
Description=Thumbnail worker
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=exec
ExecStart=/usr/local/bin/thumbnailer \
    --queue redis://127.0.0.1:6379/2 \
    --out /var/lib/thumbnailer
DynamicUser=yes
StateDirectory=thumbnailer
LoadCredential=s3-key:/etc/thumbnailer/s3-key
Restart=on-failure
RestartSec=5s
TimeoutStopSec=30s
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
RestrictNamespaces=yes
LockPersonality=yes
CapabilityBoundingSet=
SystemCallFilter=@system-service
SystemCallArchitectures=native
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
MemoryMax=1G
TasksMax=128

[Install]
WantedBy=multi-user.target
FILE:examples/review-report.md
# systemd unit review

| Unit | Description | Type | Runs as | Restart | Exposure (0-10) | High | Medium | Low | Info |
|---|---|---|---|---|---|---|---|---|---|
| `examples/webapp.service + examples/webapp-override.conf` | Shop API (Node.js) | simple | root | always | 8.1 UNSAFE | 9 | 4 | 2 | 1 |
| `examples/worker.service` | Thumbnail worker | exec | DynamicUser | on-failure | 1.2 OK | 0 | 0 | 1 | 0 |

## examples/webapp.service + examples/webapp-override.conf

**Verdict: 9 high finding(s) - fix before deploying**

| Sev | Code | Where | Finding | Fix |
|---|---|---|---|---|
| high | SD01 | examples/webapp.service | runs as root (no User= or DynamicUser=) - a bug or exploit in the service owns the whole machine | add DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group= |
| high | SD03 | examples/webapp.service:11 | DATABASE_URL contains a URL with an embedded password | move the credential out of the unit (LoadCredential= / EnvironmentFile= 0600) |
| high | SD03 | examples/webapp.service:12 | secret STRIPE_SECRET_KEY is written in the unit file - unit files are world-readable and shown by `systemctl show` | use LoadCredential=stripe_secret_key:/etc/<name>/stripe_secret_key (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600 |
| high | SD07 | examples/webapp.service:17 | grants CAP_SYS_ADMIN - close to full root | remove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed |
| high | SD08 | examples/webapp-override.conf:5 | invalid value Restart=on-faliure - systemd ignores the line and keeps the default (did you mean on-failure?) | use one of: always, no, on-abnormal, on-abort, on-failure, on-success, on-watchdog |
| high | SD08 | examples/webapp.service:16 | unknown directive RestartSecs= (ignored by systemd) - did you mean RestartSec=? | rename to RestartSec= |
| high | SD10 | examples/webapp.service:14 | ExecStart= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain arguments | wrap it: ExecStart=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file |
| high | SD14 | examples/webapp-override.conf:3 | ProtectHome=yes but the service uses /home/deploy/shop-api - it cannot see it and will fail to start | move the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory |
| high | SD14 | examples/webapp-override.conf:4 | MemoryDenyWriteExecute=yes with a JIT runtime (/usr/bin/node) - it will crash on start | remove MemoryDenyWriteExecute= for this service |
| medium | SD05 | examples/webapp.service:4 | After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target in | add Wants=network-online.target |
| medium | SD06 | examples/webapp.service | 19 sandboxing option(s) missing: User, NoNewPrivileges, ProtectSystem, PrivateDevices, ProtectKernelTunables, ProtectKernelModules, ProtectKernelLogs, ProtectControlGroups, ProtectClock, ProtectHostname, RestrictSUIDSGID, RestrictNamespaces, RestrictRealtime, LockPersonality, CapabilityBoundingSet, SystemCallFilter, SystemCallArchitectures, RestrictAddressFamilies, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service |
| medium | SD11 | examples/webapp.service | no [Install] WantedBy= - `systemctl enable` does nothing, so the service will not start at boot | add [Install] WantedBy=multi-user.target |
| medium | SD12 | examples/webapp.service:18 | stop timeout infinity - a hung service blocks shutdown and restarts forever | set TimeoutStopSec=30s (or what a clean shutdown really needs) |
| low | SD04 | examples/webapp.service:15 | Restart=always without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fast | add RestartSec=5s |
| low | SD05 | examples/webapp.service:4 | After=syslog.target is obsolete | remove it (journald is always available; use network-online.target) |
| info | SD15 | examples/webapp.service | no resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the host | add MemoryMax= and TasksMax= sized from normal usage |

Suggested drop-in (test after applying; relax an option if the service needs it):

```ini
# /etc/systemd/system/<name>.service.d/hardening.conf  (systemctl edit <name>)
[Service]
# or User=<service account>; a non-root user needs AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024
DynamicUser=yes
NoNewPrivileges=yes
# currently full; add ReadWritePaths=/StateDirectory= for paths it writes
ProtectSystem=strict
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictSUIDSGID=yes
RestrictNamespaces=yes
RestrictRealtime=yes
LockPersonality=yes
# empty = no capabilities; or list only what you need, e.g. CAP_NET_BIND_SERVICE
CapabilityBoundingSet=
SystemCallFilter=@system-service
SystemCallArchitectures=native
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
UMask=0077
# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>
```

## examples/worker.service

**Verdict: looks good (exposure 1.2)**

| Sev | Code | Where | Finding | Fix |
|---|---|---|---|---|
| low | SD06 | examples/worker.service | 6 sandboxing option(s) missing: ProtectKernelLogs, ProtectClock, ProtectHostname, RestrictRealtime, MemoryDenyWriteExecute, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service |

Suggested drop-in (test after applying; relax an option if the service needs it):

```ini
# /etc/systemd/system/<name>.service.d/hardening.conf  (systemctl edit <name>)
[Service]
ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
RestrictRealtime=yes
# not for JIT runtimes (Node.js, Java, .NET, PyPy)
MemoryDenyWriteExecute=yes
UMask=0077
# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>
```

Exposure is this script's weighted estimate, not the systemd-analyze number; run `systemd-analyze security <unit>` and `systemd-analyze verify <file>` on the target host to confirm.
FILE:scripts/systemd_unit_review.py
#!/usr/bin/env python3
"""systemd service unit hardening reviewer (stdlib only, Python 3.8+).

Reads one or more systemd .service unit files (and drop-in .conf files, applied in the order
given) the way systemd does - sections, comments, backslash line continuation, repeated keys,
empty assignments that reset a list - and reviews them for reliability and security problems:
running as root, secrets in Environment=, shell syntax in Exec lines without a shell, unknown or
misspelled directives and values, directives in the wrong section, restart and timeout policy,
network-online ordering, missing [Install], sandboxing gaps, dangerous capabilities and options
that will stop the service from starting. Prints an exposure score (0 = locked down, 10 = wide
open, in the spirit of `systemd-analyze security`) and a suggested hardening drop-in.

Usage:
  systemd_unit_review.py UNIT.service [DROPIN.conf ...] [--json] [--dropin]
  systemd_unit_review.py --self-test
Exit: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
"""
import argparse, difflib, json, re, sys

SEV = {"high": 0, "medium": 1, "low": 2, "info": 3}

UNIT_KEYS = {"Description", "Documentation", "Requires", "Requisite", "Wants", "BindsTo", "PartOf",
             "Upholds", "Conflicts", "Before", "After", "OnFailure", "OnSuccess", "PropagatesReloadTo",
             "ReloadPropagatedFrom", "JoinsNamespaceOf", "RequiresMountsFor", "OnFailureJobMode",
             "IgnoreOnIsolate", "StopWhenUnneeded", "RefuseManualStart", "RefuseManualStop",
             "AllowIsolate", "DefaultDependencies", "CollectMode", "FailureAction", "SuccessAction",
             "JobTimeoutSec", "JobRunningTimeoutSec", "StartLimitIntervalSec", "StartLimitBurst",
             "StartLimitAction", "RebootArgument", "SourcePath", "ConditionPathExists",
             "ConditionPathIsDirectory", "ConditionFileNotEmpty", "ConditionHost", "ConditionVirtualization",
             "ConditionKernelCommandLine", "ConditionACPower", "ConditionUser", "ConditionGroup",
             "AssertPathExists", "AssertFileNotEmpty", "ConditionEnvironment", "ConditionSecurity"}
SERVICE_KEYS = {"Type", "ExitType", "RemainAfterExit", "GuessMainPID", "PIDFile", "BusName",
                "ExecStart", "ExecStartPre", "ExecStartPost", "ExecCondition", "ExecReload", "ExecStop",
                "ExecStopPost", "RestartSec", "RestartSteps", "RestartMaxDelaySec", "TimeoutStartSec",
                "TimeoutStopSec", "TimeoutAbortSec", "TimeoutSec", "TimeoutStartFailureMode",
                "TimeoutStopFailureMode", "RuntimeMaxSec", "WatchdogSec", "Restart", "RestartMode",
                "SuccessExitStatus", "RestartPreventExitStatus", "RestartForceExitStatus", "RootDirectoryStartOnly",
                "NonBlocking", "NotifyAccess", "Sockets", "FileDescriptorStoreMax", "USBFunctionDescriptors",
                "OOMPolicy", "OpenFile", "ReloadSignal",
                # exec
                "WorkingDirectory", "RootDirectory", "RootImage", "User", "Group", "DynamicUser",
                "SupplementaryGroups", "PAMName", "UMask", "Environment", "EnvironmentFile", "PassEnvironment",
                "UnsetEnvironment", "StandardInput", "StandardOutput", "StandardError", "SyslogIdentifier",
                "LogLevelMax", "LogRateLimitIntervalSec", "LogRateLimitBurst", "Nice", "OOMScoreAdjust",
                "CPUSchedulingPolicy", "IOSchedulingClass", "LimitNOFILE", "LimitNPROC", "LimitCORE",
                "LimitMEMLOCK", "LimitAS", "LimitFSIZE", "CapabilityBoundingSet", "AmbientCapabilities",
                "NoNewPrivileges", "SecureBits", "ProtectSystem", "ProtectHome", "RuntimeDirectory",
                "StateDirectory", "CacheDirectory", "LogsDirectory", "ConfigurationDirectory",
                "RuntimeDirectoryMode", "StateDirectoryMode", "RuntimeDirectoryPreserve", "ReadWritePaths",
                "ReadOnlyPaths", "InaccessiblePaths", "ExecPaths", "NoExecPaths", "TemporaryFileSystem",
                "BindPaths", "BindReadOnlyPaths", "PrivateTmp", "PrivateDevices", "PrivateNetwork",
                "PrivateUsers", "PrivateIPC", "PrivateMounts", "ProtectHostname", "ProtectClock",
                "ProtectKernelTunables", "ProtectKernelModules", "ProtectKernelLogs", "ProtectControlGroups",
                "ProtectProc", "ProcSubset", "RestrictAddressFamilies", "RestrictNamespaces",
                "LockPersonality", "MemoryDenyWriteExecute", "RestrictRealtime", "RestrictSUIDSGID",
                "RemoveIPC", "SystemCallFilter", "SystemCallArchitectures", "SystemCallErrorNumber",
                "DevicePolicy", "DeviceAllow", "IPAddressAllow", "IPAddressDeny", "LoadCredential",
                "LoadCredentialEncrypted", "SetCredential", "SetCredentialEncrypted", "KeyringMode",
                "TTYPath", "UtmpIdentifier", "SELinuxContext", "AppArmorProfile", "KillMode", "KillSignal",
                "SendSIGKILL", "SendSIGHUP", "FinalKillSignal", "RestartKillSignal",
                # resource control
                "CPUQuota", "CPUWeight", "MemoryMax", "MemoryHigh", "MemoryLow", "MemoryMin", "MemorySwapMax",
                "TasksMax", "IOWeight", "Slice", "Delegate", "CPUAccounting", "MemoryAccounting",
                "IOAccounting", "TasksAccounting", "IPAccounting", "ManagedOOMSwap",
                "ManagedOOMMemoryPressure"}
INSTALL_KEYS = {"Alias", "WantedBy", "RequiredBy", "UpheldBy", "Also", "DefaultInstance"}
SECTIONS = {"Unit": UNIT_KEYS, "Service": SERVICE_KEYS, "Install": INSTALL_KEYS}
LIST_KEYS = {"Requires", "Wants", "After", "Before", "BindsTo", "PartOf", "Conflicts", "Documentation",
             "Environment", "EnvironmentFile", "ExecStartPre", "ExecStartPost", "ExecStop", "ExecStopPost",
             "ExecReload", "ExecCondition", "ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths",
             "SupplementaryGroups", "CapabilityBoundingSet", "AmbientCapabilities", "SystemCallFilter",
             "RestrictAddressFamilies", "DeviceAllow", "LoadCredential", "SetCredential", "WantedBy",
             "RequiredBy", "Alias", "Also", "BindPaths", "BindReadOnlyPaths", "IPAddressAllow",
             "IPAddressDeny", "OnFailure", "SuccessExitStatus", "RestartPreventExitStatus",
             "TemporaryFileSystem", "PassEnvironment", "UnsetEnvironment", "RequiresMountsFor",
             "StateDirectory", "RuntimeDirectory", "CacheDirectory", "LogsDirectory", "ExecStart",
             "ConditionPathExists", "AssertPathExists"}
VALUES = {
    "Type": {"simple", "exec", "forking", "oneshot", "dbus", "notify", "notify-reload", "idle"},
    "Restart": {"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", "always"},
    "ProtectSystem": {"yes", "no", "true", "false", "full", "strict", "1", "0", "on", "off"},
    "ProtectHome": {"yes", "no", "true", "false", "read-only", "tmpfs", "1", "0", "on", "off"},
    "KillMode": {"control-group", "mixed", "process", "none"},
    "StandardOutput": None, "NotifyAccess": {"none", "main", "exec", "all"},
}
BOOL = {"yes", "no", "true", "false", "1", "0", "on", "off"}
BOOL_KEYS = {"NoNewPrivileges", "PrivateTmp", "PrivateDevices", "PrivateNetwork", "PrivateUsers",
             "ProtectKernelTunables", "ProtectKernelModules", "ProtectKernelLogs", "ProtectControlGroups",
             "ProtectHostname", "ProtectClock", "LockPersonality", "MemoryDenyWriteExecute",
             "RestrictRealtime", "RestrictSUIDSGID", "RemoveIPC", "DynamicUser", "RemainAfterExit",
             "PrivateIPC", "PrivateMounts", "DefaultDependencies"}
TRUE = {"yes", "true", "1", "on"}
SECRET_RE = re.compile(r"(PASS(WORD|WD)?|SECRET|TOKEN|API_?KEY|PRIVATE_?KEY|CREDENTIALS?|DSN)", re.I)
SHELL_RE = re.compile(r"(\|\||&&|(?<![\\])[|;]|>>?|<|\$\(|`|(?:^|\s)&\s*$|\s&$)")
DANGER_CAPS = {"CAP_SYS_ADMIN": "high", "CAP_SYS_MODULE": "high", "CAP_SYS_PTRACE": "high",
               "CAP_DAC_OVERRIDE": "medium", "CAP_SYS_RAWIO": "high", "CAP_NET_ADMIN": "medium",
               "CAP_SETUID": "medium", "CAP_SETGID": "medium", "CAP_CHOWN": "low", "CAP_SYS_CHROOT": "low"}
# (directive, wanted value test, weight, recommended line) - weights sum to 10.0
HARDEN = [
    ("User", None, 2.0, "DynamicUser=yes|or User=<service account>; a non-root user needs AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024"),
    ("NoNewPrivileges", "bool", 0.8, "NoNewPrivileges=yes"),
    ("ProtectSystem", "strict", 1.0, "ProtectSystem=strict"),
    ("ProtectHome", "home", 0.6, "ProtectHome=yes"),
    ("PrivateTmp", "bool", 0.5, "PrivateTmp=yes"),
    ("PrivateDevices", "bool", 0.5, "PrivateDevices=yes"),
    ("ProtectKernelTunables", "bool", 0.4, "ProtectKernelTunables=yes"),
    ("ProtectKernelModules", "bool", 0.4, "ProtectKernelModules=yes"),
    ("ProtectKernelLogs", "bool", 0.2, "ProtectKernelLogs=yes"),
    ("ProtectControlGroups", "bool", 0.3, "ProtectControlGroups=yes"),
    ("ProtectClock", "bool", 0.2, "ProtectClock=yes"),
    ("ProtectHostname", "bool", 0.1, "ProtectHostname=yes"),
    ("RestrictSUIDSGID", "bool", 0.3, "RestrictSUIDSGID=yes"),
    ("RestrictNamespaces", "ns", 0.4, "RestrictNamespaces=yes"),
    ("RestrictRealtime", "bool", 0.2, "RestrictRealtime=yes"),
    ("LockPersonality", "bool", 0.1, "LockPersonality=yes"),
    ("MemoryDenyWriteExecute", "bool", 0.3, "MemoryDenyWriteExecute=yes|not for JIT runtimes (Node.js, Java, .NET, PyPy)"),
    ("CapabilityBoundingSet", "caps", 0.6, "CapabilityBoundingSet=|empty = no capabilities; or list only what you need, e.g. CAP_NET_BIND_SERVICE"),
    ("SystemCallFilter", "set", 0.4, "SystemCallFilter=@system-service"),
    ("SystemCallArchitectures", "native", 0.1, "SystemCallArchitectures=native"),
    ("RestrictAddressFamilies", "set", 0.4, "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6"),
    ("UMask", "umask", 0.2, "UMask=0077"),
]


class InputError(Exception):
    pass


# ---------------------------------------------------------------- parse
def parse(text, fname, unit=None):
    """Return unit dict: {section: {key: [(value, line, file)]}} plus raw entries list."""
    unit = unit if unit is not None else {"sections": {}, "entries": [], "files": []}
    unit["files"].append(fname)
    sec = None
    lines = text.splitlines()
    i = 0
    while i < len(lines):
        ln, raw = i + 1, lines[i]
        i += 1
        s = raw.strip()
        if not s or s[0] in "#;":
            continue
        while s.endswith("\\") and i < len(lines):
            nxt = lines[i].strip()
            i += 1
            if nxt.startswith(("#", ";")):
                continue
            s = s[:-1].rstrip() + " " + nxt
        if s.startswith("["):
            if not s.endswith("]"):
                raise InputError("%s:%d: broken section header %r" % (fname, ln, s))
            sec = s[1:-1].strip()
            unit["sections"].setdefault(sec, {})
            unit["entries"].append(("section", sec, None, ln, fname))
            continue
        if "=" not in s:
            unit["entries"].append(("noeq", sec, s, ln, fname))
            continue
        if sec is None:
            unit["entries"].append(("nosec", None, s, ln, fname))
            continue
        k, v = s.split("=", 1)
        k, v = k.strip(), v.strip()
        unit["entries"].append(("kv", sec, (k, v), ln, fname))
        d = unit["sections"][sec]
        if v == "" and k in LIST_KEYS:
            d[k] = [("", ln, fname)]  # empty assignment resets the list
            continue
        d.setdefault(k, []).append((v, ln, fname))
    return unit


def get(unit, sec, key):
    vals = unit["sections"].get(sec, {}).get(key, [])
    vals = [v for v in vals if v[0] != ""] if key in LIST_KEYS else vals
    return vals


def valid(key, v):
    vl = v.lower()
    if key in VALUES and VALUES[key]:
        return vl in VALUES[key]
    if key in BOOL_KEYS:
        return vl in BOOL
    return True


def last(unit, sec, key, default=None):
    """Effective value: the last assignment systemd accepts (invalid values are ignored)."""
    for v in reversed(unit["sections"].get(sec, {}).get(key) or []):
        if v[0] == "" or valid(key, v[0]):
            return v[0]
    return default


def where(unit, sec, key):
    v = [x for x in unit["sections"].get(sec, {}).get(key) or [] if x[0] == "" or valid(key, x[0])]
    return "%s:%d" % (v[-1][2], v[-1][1]) if v else unit["files"][0]


def words(unit, sec, key):
    out = []
    for v, _, _ in get(unit, sec, key):
        out += v.split()
    return out


# ---------------------------------------------------------------- review
def review(unit):
    F = []
    add = lambda sev, code, loc, msg, fix: F.append((sev, code, loc, msg, fix))
    S = unit["sections"]
    svc = S.get("Service", {})
    f0 = unit["files"][0]
    if "Service" not in S:
        raise InputError("%s has no [Service] section - not a service unit" % f0)

    # SD08 / SD13 / structure
    for kind, sec, val, ln, fn in unit["entries"]:
        loc = "%s:%d" % (fn, ln)
        if kind == "noeq":
            add("medium", "SD08", loc, "line is not Key=Value and is ignored: %r" % val, "fix the line or comment it out with #")
        elif kind == "nosec":
            add("medium", "SD08", loc, "assignment before any [Section] is ignored: %r" % val, "move it under [Unit], [Service] or [Install]")
        elif kind == "section" and sec not in SECTIONS and not sec.startswith("X-"):
            add("medium", "SD08", loc, "unknown section [%s] - its settings are ignored" % sec, "use [Unit], [Service] or [Install] (custom sections must start with X-)")
        elif kind == "kv" and sec in SECTIONS:
            k, v = val
            if k.startswith("X-"):
                continue
            if k not in SECTIONS[sec]:
                other = [s for s in SECTIONS if k in SECTIONS[s]]
                if other:
                    sev = "medium"
                    add(sev, "SD09", loc, "%s= belongs in [%s], not [%s] - systemd ignores it here" % (k, other[0], sec),
                        "move %s=%s to [%s]" % (k, v, other[0]))
                else:
                    allk = set().union(*SECTIONS.values())
                    close = difflib.get_close_matches(k, sorted(allk), 1, 0.75)
                    add("high" if sec == "Service" and close and close[0].startswith(("Exec", "User", "Restart")) else "medium",
                        "SD08", loc, "unknown directive %s= (ignored by systemd)%s" % (k, " - did you mean %s=?" % close[0] if close else ""),
                        "rename to %s=" % close[0] if close else "remove it or check `man systemd.directives`")
                continue
            vl = v.lower()
            if k in VALUES and VALUES[k] and v and vl not in VALUES[k]:
                close = difflib.get_close_matches(vl, sorted(VALUES[k]), 1, 0.6)
                add("high" if k in ("Type", "Restart") else "medium", "SD08", loc,
                    "invalid value %s=%s - systemd ignores the line and keeps the default%s" % (k, v, " (did you mean %s?)" % close[0] if close else ""),
                    "use one of: %s" % ", ".join(sorted(VALUES[k])))
            elif k in BOOL_KEYS and v and vl not in BOOL:
                add("medium", "SD08", loc, "%s= expects a boolean, got %r (line ignored)" % (k, v), "use yes or no")
    seen = {}
    for kind, sec, val, ln, fn in unit["entries"]:
        if kind == "kv" and val[0] not in LIST_KEYS and sec in SECTIONS:
            key = (sec, val[0])
            if key in seen and seen[key][2] == fn:
                add("low", "SD13", "%s:%d" % (fn, ln), "%s= set again (first at line %d) - the last one wins: %s" % (val[0], seen[key][1], val[1]),
                    "keep one %s= line" % val[0])
            seen[key] = (val[1], ln, fn)

    typ = (last(unit, "Service", "Type", "simple") or "simple").lower()
    execs = get(unit, "Service", "ExecStart")
    # SD02 ExecStart
    if not execs:
        add("high", "SD02", f0, "no ExecStart= - the service cannot start", "add ExecStart=/absolute/path/to/binary args")
    if len(execs) > 1 and typ != "oneshot":
        add("high", "SD02", where(unit, "Service", "ExecStart"), "%d ExecStart= lines but Type=%s allows only one (only oneshot may have several)" % (len(execs), typ),
            "keep one ExecStart=, or reset with an empty ExecStart= first in a drop-in")
    for key in ("ExecStartPre", "ExecStart", "ExecStartPost", "ExecReload", "ExecStop", "ExecStopPost"):
        for v, ln, fn in get(unit, "Service", key):
            loc = "%s:%d" % (fn, ln)
            cmd = v.lstrip("-@:+!")
            first = cmd.split()[0] if cmd.split() else ""
            is_shell = re.match(r"^(/usr)?/bin/(ba|da|z)?sh$", first) is not None
            if first and not first.startswith("/") and not first.startswith("$"):
                add("low", "SD02", loc, "%s= command %r is not an absolute path (systemd searches only its fixed PATH)" % (key, first),
                    "use the full path, e.g. /usr/bin/%s" % first)
            if not is_shell and SHELL_RE.search(cmd.split(None, 1)[1] if len(cmd.split(None, 1)) > 1 else ""):
                add("high", "SD10", loc, "%s= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain arguments" % key,
                    "wrap it: %s=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file" % key)
            if re.search(r"(^|\s)(nohup|daemon|--daemon(ize)?|-d)(\s|$)", cmd) and typ in ("simple", "exec"):
                add("medium", "SD10", loc, "%s= looks like it forks into the background (nohup/--daemon) while Type=%s expects the process to stay in the foreground" % (key, typ),
                    "run it in the foreground (drop --daemon / nohup) or use Type=forking with PIDFile=")
            if v.startswith("+") or v.startswith("!"):
                add("medium", "SD01", loc, "%s= prefix %s runs this command with full privileges, bypassing User= and the sandbox" % (key, v[0]), "drop the prefix unless this step really needs root")
    if typ == "forking" and not get(unit, "Service", "PIDFile"):
        add("low", "SD10", where(unit, "Service", "Type"), "Type=forking without PIDFile= - systemd has to guess the main process", "add PIDFile=/run/<name>/<name>.pid or run in the foreground with Type=exec")

    # SD01 user
    user = last(unit, "Service", "User")
    dyn = (last(unit, "Service", "DynamicUser", "no") or "no").lower() in TRUE
    root = (not dyn) and (user is None or user in ("root", "0"))
    if root:
        add("high" if typ != "oneshot" else "medium", "SD01", where(unit, "Service", "User") if user else f0,
            "runs as root (%s) - a bug or exploit in the service owns the whole machine" % ("User=%s" % user if user else "no User= or DynamicUser="),
            "add DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group=")
    caps = words(unit, "Service", "AmbientCapabilities") + words(unit, "Service", "CapabilityBoundingSet")
    for c in sorted(set(x.lstrip("~") for x in caps)):
        if c.upper() in DANGER_CAPS and not any(x.startswith("~") for x in caps):
            add(DANGER_CAPS[c.upper()], "SD07", where(unit, "Service", "AmbientCapabilities" if c in words(unit, "Service", "AmbientCapabilities") else "CapabilityBoundingSet"),
                "grants %s - close to full root" % c if DANGER_CAPS[c.upper()] == "high" else "grants %s" % c,
                "remove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed")

    # SD03 secrets
    for v, ln, fn in get(unit, "Service", "Environment"):
        for m in re.finditer(r'"?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|\S*)', v):
            name, val = m.group(1), m.group(2).strip('"')
            if SECRET_RE.search(name) and val and not val.startswith("%") and not val.startswith("$"):
                add("high", "SD03", "%s:%d" % (fn, ln), "secret %s is written in the unit file - unit files are world-readable and shown by `systemctl show`" % name,
                    "use LoadCredential=%s:/etc/<name>/%s (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600" % (name.lower(), name.lower()))
            if re.search(r"://[^/\s:@]+:[^@\s]+@", val):
                add("high", "SD03", "%s:%d" % (fn, ln), "%s contains a URL with an embedded password" % name, "move the credential out of the unit (LoadCredential= / EnvironmentFile= 0600)")
    for v, ln, fn in get(unit, "Service", "ExecStart"):
        if re.search(r"--(password|passwd|token|secret|api-key)[= ]\S+", v, re.I):
            add("high", "SD03", "%s:%d" % (fn, ln), "a secret is passed on the command line - visible to every user in ps and /proc", "read it from a file or $CREDENTIALS_DIRECTORY instead")

    # SD04 restart policy
    restart = (last(unit, "Service", "Restart", "no") or "no").lower()
    if typ != "oneshot" and restart == "no":
        add("medium", "SD04", where(unit, "Service", "Restart") if last(unit, "Service", "Restart") else f0,
            "Restart=no (default) - a crash leaves the service down until someone notices", "add Restart=on-failure and RestartSec=5s")
    if restart in ("always", "on-failure", "on-abnormal") and not last(unit, "Service", "RestartSec"):
        add("low", "SD04", where(unit, "Service", "Restart"), "Restart=%s without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fast" % restart, "add RestartSec=5s")
    if typ == "oneshot" and restart in ("always", "on-success"):
        add("high", "SD04", where(unit, "Service", "Restart"), "Type=oneshot does not allow Restart=%s - systemd refuses to load the unit" % restart, "use Restart=on-failure or run it from a .timer")
    tstop = (last(unit, "Service", "TimeoutStopSec") or last(unit, "Service", "TimeoutSec") or "").lower()
    if tstop in ("infinity", "0"):
        add("medium", "SD12", where(unit, "Service", "TimeoutStopSec") if last(unit, "Service", "TimeoutStopSec") else where(unit, "Service", "TimeoutSec"),
            "stop timeout %s - a hung service blocks shutdown and restarts forever" % tstop, "set TimeoutStopSec=30s (or what a clean shutdown really needs)")
    km = (last(unit, "Service", "KillMode", "") or "").lower()
    if km == "none":
        add("medium", "SD12", where(unit, "Service", "KillMode"), "KillMode=none is deprecated - leftover processes survive stop and restart", "use KillMode=mixed or the default control-group")
    elif km == "process":
        add("low", "SD12", where(unit, "Service", "KillMode"), "KillMode=process kills only the main process; children keep running after stop", "use KillMode=mixed unless the children must outlive the service")

    # SD05 ordering
    after = words(unit, "Unit", "After")
    wants = words(unit, "Unit", "Wants") + words(unit, "Unit", "Requires")
    if "network-online.target" in after and "network-online.target" not in wants:
        add("medium", "SD05", where(unit, "Unit", "After"), "After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target in",
            "add Wants=network-online.target")
    if "network-online.target" in wants and "network-online.target" not in after:
        add("medium", "SD05", where(unit, "Unit", "Wants"), "Wants=network-online.target without After=network-online.target - the service still starts before the network is up", "add After=network-online.target")
    for v in ("syslog.target", "network.service"):
        if v in after:
            add("low", "SD05", where(unit, "Unit", "After"), "After=%s is obsolete" % v, "remove it (journald is always available; use network-online.target)")
    sl = [k for k in ("StartLimitIntervalSec", "StartLimitBurst") if k in S.get("Unit", {})]
    for k, ln in (("StartLimitInterval", None),):
        if k in svc:
            add("medium", "SD09", where(unit, "Service", k), "StartLimitInterval= is the old name and in [Service] it is ignored", "use StartLimitIntervalSec= in [Unit]")
    if restart == "always" and not sl and "StartLimitIntervalSec" not in svc:
        add("info", "SD04", f0, "Restart=always with the default start limit (5 starts in 10 s) - after that the unit stays failed", "if you want endless retries set StartLimitIntervalSec=0 in [Unit] and RestartSec= to a sane delay")

    # SD11 install
    wb = words(unit, "Install", "WantedBy") + words(unit, "Install", "RequiredBy")
    if not wb and not get(unit, "Install", "Alias"):
        add("medium", "SD11", f0, "no [Install] WantedBy= - `systemctl enable` does nothing, so the service will not start at boot", "add [Install] WantedBy=multi-user.target")
    elif "default.target" in wb or "graphical.target" in wb:
        add("low", "SD11", where(unit, "Install", "WantedBy"), "WantedBy=%s for a system service" % [w for w in wb if w in ("default.target", "graphical.target")][0], "use WantedBy=multi-user.target (default.target is for user services)")

    # SD14 conflicts that break start
    ph = (last(unit, "Service", "ProtectHome", "no") or "no").lower()
    wd = last(unit, "Service", "WorkingDirectory", "") or ""
    paths = [wd] + [(e[0].lstrip("-@:+!").split() or [""])[0] for e in execs] + [x.lstrip("-") for x in words(unit, "Service", "EnvironmentFile")]
    if ph in TRUE or ph in ("tmpfs", "read-only"):
        for p in paths:
            if p.startswith("/home/") or p.startswith("/root/"):
                add("high" if ph != "read-only" else "medium", "SD14", where(unit, "Service", "ProtectHome"),
                    "ProtectHome=%s but the service uses %s - it %s" % (ph, p, "cannot see it and will fail to start" if ph != "read-only" else "cannot write there"),
                    "move the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory")
                break
    ps_ = (last(unit, "Service", "ProtectSystem", "no") or "no").lower()
    rw = words(unit, "Service", "ReadWritePaths") + ["/var/lib/" + x for x in words(unit, "Service", "StateDirectory")] + \
        ["/var/log/" + x for x in words(unit, "Service", "LogsDirectory")] + ["/run/" + x for x in words(unit, "Service", "RuntimeDirectory")]
    if ps_ == "strict":
        for v, ln, fn in execs + get(unit, "Service", "ExecStartPre"):
            for m in re.finditer(r">>?\s*(/\S+)|--(?:log|pid|data|out)[-a-z]*[= ](/\S+)", v):
                p = m.group(1) or m.group(2)
                if not any(p.startswith(x.lstrip("-")) for x in rw) and not p.startswith(("/tmp", "/dev/")):
                    add("medium", "SD14", "%s:%d" % (fn, ln), "ProtectSystem=strict makes %s read-only - writes will fail" % p,
                        "use StateDirectory=/LogsDirectory=/RuntimeDirectory= or ReadWritePaths=%s" % p.rsplit("/", 1)[0])
    if (last(unit, "Service", "MemoryDenyWriteExecute", "no") or "").lower() in TRUE and paths and re.search(r"(node|java|dotnet|pypy|bun|deno)", " ".join(paths)):
        add("high", "SD14", where(unit, "Service", "MemoryDenyWriteExecute"), "MemoryDenyWriteExecute=yes with a JIT runtime (%s) - it will crash on start" % [p for p in paths if re.search(r"(node|java|dotnet|pypy|bun|deno)", p)][0],
            "remove MemoryDenyWriteExecute= for this service")
    if dyn and user:
        add("info", "SD01", where(unit, "Service", "DynamicUser"), "DynamicUser=yes with User=%s - a transient user with that name is allocated" % user, "fine; do not rely on files owned by a static %s user" % user)

    # SD15 resources
    if not any(k in svc for k in ("MemoryMax", "MemoryHigh", "TasksMax", "CPUQuota")):
        add("info", "SD15", f0, "no resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the host", "add MemoryMax= and TasksMax= sized from normal usage")

    # SD06 exposure
    exposure, missing = 0.0, []
    for key, test, w, rec in HARDEN:
        v = (last(unit, "Service", key) or "")
        vl = v.lower()
        if key == "User":
            ok = not root
        elif test == "bool":
            ok = vl in TRUE
        elif test == "strict":
            ok = vl == "strict"
            if vl in ("full", "yes", "true"):
                exposure += w * 0.5
                missing.append((key, "ProtectSystem=strict|currently %s; add ReadWritePaths=/StateDirectory= for paths it writes" % v))
                continue
        elif test == "home":
            ok = vl in TRUE or vl in ("read-only", "tmpfs")
        elif test == "ns":
            ok = vl in TRUE or (v != "" and vl not in ("no", "false", "0", "off"))
        elif test == "caps":
            ok = key in svc and all(c.upper() not in DANGER_CAPS or c.startswith("~") for c in words(unit, "Service", key))
        elif test == "set":
            ok = bool(words(unit, "Service", key))
        elif test == "native":
            ok = vl == "native"
        elif test == "umask":
            ok = v in ("0077", "077", "0027", "027")
        else:
            ok = bool(v)
        if not ok:
            exposure += w
            missing.append((key, rec))
    exposure = round(min(exposure, 10.0), 1)
    if missing:
        add("medium" if exposure >= 5 else "low", "SD06", f0, "%d sandboxing option(s) missing: %s" % (len(missing), ", ".join(k for k, _ in missing)),
            "add the suggested drop-in (systemctl edit <name>), restart, and test the service")
    F.sort(key=lambda x: (SEV[x[0]], x[1], x[2]))
    rating = "OK" if exposure < 2 else "MEDIUM" if exposure < 5 else "EXPOSED" if exposure < 8 else "UNSAFE"
    return {"files": unit["files"], "name": last(unit, "Unit", "Description", "") or unit["files"][0], "type": typ,
            "user": "DynamicUser" if dyn else (user or "root"), "restart": restart, "exposure": exposure, "rating": rating,
            "missing": missing, "findings": F}


def dropin(r):
    lines = ["# /etc/systemd/system/<name>.service.d/hardening.conf  (systemctl edit <name>)", "[Service]"]
    for k, rec in r["missing"]:
        line, _, note = rec.partition("|")
        if note:
            lines.append("# " + note)
        lines.append(line)
    if any(f[1] == "SD04" and "Restart=no" in f[3] for f in r["findings"]):
        lines += ["Restart=on-failure", "RestartSec=5s"]
    lines += ["# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>"]
    return "\n".join(lines)


def counts(F):
    c = {s: 0 for s in SEV}
    for f in F:
        c[f[0]] += 1
    return c


def report(results):
    out = ["# systemd unit review", ""]
    out.append("| Unit | Description | Type | Runs as | Restart | Exposure (0-10) | High | Medium | Low | Info |")
    out.append("|---|---|---|---|---|---|---|---|---|---|")
    for r in results:
        c = counts(r["findings"])
        out.append("| `%s` | %s | %s | %s | %s | %.1f %s | %d | %d | %d | %d |" % (" + ".join(r["files"]), r["name"], r["type"], r["user"], r["restart"],
                                                                         r["exposure"], r["rating"], c["high"], c["medium"], c["low"], c["info"]))
    for r in results:
        c = counts(r["findings"])
        out += ["", "## %s" % " + ".join(r["files"]), ""]
        if c["high"]:
            v = "%d high finding(s) - fix before deploying" % c["high"]
        elif r["exposure"] >= 5:
            v = "works, but exposure %.1f - add the hardening drop-in" % r["exposure"]
        else:
            v = "looks good (exposure %.1f)" % r["exposure"]
        out.append("**Verdict: %s**" % v)
        out += ["", "| Sev | Code | Where | Finding | Fix |", "|---|---|---|---|---|"]
        for s, code, loc, msg, fix in r["findings"]:
            out.append("| %s | %s | %s | %s | %s |" % (s, code, loc, msg.replace("|", "\\|"), fix.replace("|", "\\|")))
        if r["missing"]:
            out += ["", "Suggested drop-in (test after applying; relax an option if the service needs it):", "", "```ini", dropin(r), "```"]
    out += ["", "Exposure is this script's weighted estimate, not the systemd-analyze number; run `systemd-analyze security <unit>` and `systemd-analyze verify <file>` on the target host to confirm."]
    return "\n".join(out) + "\n"


def run_files(paths):
    unit = None
    for p in paths:
        try:
            with open(p, encoding="utf-8") as fh:
                txt = fh.read()
        except OSError as e:
            raise InputError("cannot read %s: %s" % (p, e))
        unit = parse(txt, p, unit)
    return review(unit)


# ---------------------------------------------------------------- self-test
def self_test():
    tests = []
    def t(name, cond):
        tests.append((name, bool(cond)))
    def R(txt, *drop):
        u = parse(txt, "a.service")
        for i, d in enumerate(drop):
            u = parse(d, "d%d.conf" % i, u)
        return review(u)
    def codes(txt, *drop):
        return [(f[0], f[1]) for f in R(txt, *drop)["findings"]]
    base = "[Unit]\nDescription=x\n[Service]\nExecStart=/usr/bin/app\n[Install]\nWantedBy=multi-user.target\n"
    good = ("[Unit]\nDescription=good\nWants=network-online.target\nAfter=network-online.target\n[Service]\nType=exec\nExecStart=/usr/bin/app\n"
            "DynamicUser=yes\nRestart=on-failure\nRestartSec=5s\nNoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=yes\nPrivateTmp=yes\n"
            "PrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\n"
            "ProtectClock=yes\nProtectHostname=yes\nRestrictSUIDSGID=yes\nRestrictNamespaces=yes\nRestrictRealtime=yes\nLockPersonality=yes\n"
            "MemoryDenyWriteExecute=yes\nCapabilityBoundingSet=\nSystemCallFilter=@system-service\nSystemCallArchitectures=native\n"
            "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nUMask=0077\nMemoryMax=512M\nTasksMax=64\n[Install]\nWantedBy=multi-user.target\n")
    g = R(good)
    t("fully hardened unit: exposure 0, no high/medium", g["exposure"] == 0 and not [f for f in g["findings"] if f[0] in ("high", "medium")])
    t("root by default -> SD01 high", ("high", "SD01") in codes(base))
    t("root oneshot -> SD01 medium", ("medium", "SD01") in codes(base.replace("[Service]\n", "[Service]\nType=oneshot\n")))
    t("User=svc clears SD01", "SD01" not in [c for _, c in codes(base.replace("[Service]\n", "[Service]\nUser=svc\n"))])
    t("missing ExecStart -> SD02 high", ("high", "SD02") in codes("[Service]\nUser=a\n[Install]\nWantedBy=multi-user.target\n"))
    t("relative command -> SD02 low", ("low", "SD02") in codes(base.replace("/usr/bin/app", "app")))
    t("two ExecStart with simple -> SD02 high", ("high", "SD02") in codes(base.replace("ExecStart=/usr/bin/app", "ExecStart=/a\nExecStart=/b")))
    t("empty ExecStart= in drop-in resets", ("high", "SD02") not in codes(base, "[Service]\nExecStart=\nExecStart=/usr/bin/other\n"))
    t("pipe in ExecStart -> SD10 high", ("high", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app | logger")))
    t("redirect >> -> SD10 high", ("high", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app >> /var/log/app.log")))
    t("sh -c is allowed", ("high", "SD10") not in codes(base.replace("/usr/bin/app", "/bin/sh -c '/usr/bin/app | logger'")))
    t("--daemon with simple -> SD10 medium", ("medium", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app --daemon")))
    t("secret in Environment -> SD03 high", ("high", "SD03") in codes(base.replace("[Service]\n", "[Service]\nEnvironment=DB_PASSWORD=hunter2\n")))
    t("quoted env with URL password -> SD03", ("high", "SD03") in codes(base.replace("[Service]\n", '[Service]\nEnvironment="DATABASE_URL=postgres://u:pw@db/x" "PORT=80"\n')))
    t("non-secret env is fine", "SD03" not in [c for _, c in codes(base.replace("[Service]\n", "[Service]\nEnvironment=PORT=8080 LOG_LEVEL=info\n"))])
    t("--password on cmdline -> SD03", ("high", "SD03") in codes(base.replace("/usr/bin/app", "/usr/bin/app --password=s3cret")))
    t("Restart missing -> SD04 medium", ("medium", "SD04") in codes(base))
    t("Restart=always no RestartSec -> SD04 low", ("low", "SD04") in codes(base.replace("[Service]\n", "[Service]\nRestart=always\n")))
    t("oneshot + Restart=always -> SD04 high", ("high", "SD04") in codes(base.replace("[Service]\n", "[Service]\nType=oneshot\nRestart=always\n")))
    t("After online without Wants -> SD05", ("medium", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nAfter=network-online.target\n")))
    t("Wants online without After -> SD05", ("medium", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nWants=network-online.target\n")))
    t("syslog.target obsolete -> SD05 low", ("low", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nAfter=syslog.target\n")))
    t("typo directive -> SD08 with suggestion", any("did you mean RestartSec" in f[3] for f in R(base.replace("[Service]\n", "[Service]\nRestartSecs=5\n"))["findings"]))
    t("invalid Restart value -> SD08 high", ("high", "SD08") in codes(base.replace("[Service]\n", "[Service]\nRestart=on-faliure\n")))
    t("invalid value ignored, earlier valid one stays effective", R(base.replace("[Service]\n", "[Service]\nRestart=always\n"), "[Service]\nRestart=on-faliure\n")["restart"] == "always")
    t("drop-in lines are valid key=value", all("=" in l or l.startswith(("#", "[")) for l in dropin(R(base)).splitlines()))
    t("bad boolean -> SD08 medium", ("medium", "SD08") in codes(base.replace("[Service]\n", "[Service]\nPrivateTmp=maybe\n")))
    t("StartLimitBurst in [Service] -> SD09", ("medium", "SD09") in codes(base.replace("[Service]\n", "[Service]\nStartLimitBurst=3\n")))
    t("WantedBy in [Service] -> SD09", ("medium", "SD09") in codes(base.replace("[Service]\n", "[Service]\nWantedBy=multi-user.target\n")))
    t("no [Install] -> SD11 medium", ("medium", "SD11") in codes("[Service]\nExecStart=/usr/bin/a\n"))
    t("WantedBy=default.target -> SD11 low", ("low", "SD11") in codes(base.replace("multi-user.target", "default.target")))
    t("duplicate scalar -> SD13", ("low", "SD13") in codes(base.replace("[Service]\n", "[Service]\nUser=a\nUser=b\n")))
    t("drop-in override is not a duplicate", ("low", "SD13") not in codes(base.replace("[Service]\n", "[Service]\nUser=a\n"), "[Service]\nUser=b\n"))
    t("drop-in value wins", R(base.replace("[Service]\n", "[Service]\nUser=a\n"), "[Service]\nUser=b\n")["user"] == "b")
    t("ProtectHome with /home app -> SD14 high", ("high", "SD14") in codes(base.replace("/usr/bin/app", "/home/deploy/app/run").replace("[Service]\n", "[Service]\nProtectHome=yes\n")))
    t("MDWE with node -> SD14 high", ("high", "SD14") in codes(base.replace("/usr/bin/app", "/usr/bin/node server.js").replace("[Service]\n", "[Service]\nMemoryDenyWriteExecute=yes\n")))
    t("ProtectSystem=strict write path -> SD14", ("medium", "SD14") in codes(base.replace("/usr/bin/app", "/usr/bin/app --log-file=/var/log/app/app.log").replace("[Service]\n", "[Service]\nProtectSystem=strict\n")))
    t("LogsDirectory clears strict write", ("medium", "SD14") not in codes(base.replace("/usr/bin/app", "/usr/bin/app --log-file=/var/log/app/app.log").replace("[Service]\n", "[Service]\nProtectSystem=strict\nLogsDirectory=app\n")))
    t("CAP_SYS_ADMIN -> SD07 high", ("high", "SD07") in codes(base.replace("[Service]\n", "[Service]\nAmbientCapabilities=CAP_SYS_ADMIN\n")))
    t("+ prefix -> SD01 medium", ("medium", "SD01") in codes(base.replace("[Service]\n", "[Service]\nUser=a\nExecStartPre=+/usr/bin/setup\n")))
    t("TimeoutStopSec=infinity -> SD12", ("medium", "SD12") in codes(base.replace("[Service]\n", "[Service]\nTimeoutStopSec=infinity\n")))
    t("continuation lines joined", R("[Service]\nExecStart=/usr/bin/app \\\n  --port 80\nUser=a\n[Install]\nWantedBy=multi-user.target\n")["findings"] is not None and
      parse("[Service]\nExecStart=/usr/bin/app \\\n  --port 80\n", "x")["sections"]["Service"]["ExecStart"][0][0] == "/usr/bin/app --port 80")
    t("bare exposure of minimal unit is 10", R(base)["exposure"] == 10.0)
    t("ProtectSystem=full counts half", abs(R(base.replace("[Service]\n", "[Service]\nProtectSystem=full\n"))["exposure"] - 9.5) < 0.01)
    try:
        R("[Unit]\nDescription=x\n")
        t("no [Service] rejected", False)
    except InputError:
        t("no [Service] rejected", True)
    t("report has verdict and table", "**Verdict:" in report([R(base)]) and "| Sev | Code |" in report([R(base)]))
    for n, ok in tests:
        print("%s  %s" % ("PASS" if ok else "FAIL", n))
    p = sum(ok for _, ok in tests)
    print("%d/%d passed" % (p, len(tests)))
    return 0 if p == len(tests) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Review systemd .service units for reliability and hardening.")
    ap.add_argument("units", nargs="*", help="UNIT.service, optionally followed by drop-in .conf files; use ',' between separate units")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--dropin", action="store_true", help="print only the suggested hardening drop-in(s)")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.units:
        ap.error("give at least one .service file")
    groups, cur = [], []
    for u in a.units:
        if u == ",":
            groups.append(cur); cur = []
        elif u.endswith(".service") and cur:
            groups.append(cur); cur = [u]
        else:
            cur.append(u)
    groups.append(cur)
    try:
        res = [run_files(g) for g in groups if g]
    except InputError as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    if a.json:
        print(json.dumps([{**r, "findings": [dict(zip(("severity", "code", "where", "finding", "fix"), f)) for f in r["findings"]]} for r in res], indent=2))
    elif a.dropin:
        print("\n\n".join(dropin(r) for r in res))
    else:
        sys.stdout.write(report(res))
    return 1 if any(f[0] == "high" for r in res for f in r["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityLinuxConfiguration+2
F@f
0
1 / 4Next