diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 11:29:00 -0700 |
|---|---|---|
| committer | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 11:29:00 -0700 |
| commit | 363af43603ecdb1bdbed7303764b6daeeec7c37f (patch) | |
| tree | f4070c6df279ab2bdc320b5611a6cd7eb9b25703 /plugins | |
| parent | 28abd83ad92c24a4107803bd03e510387f2014c2 (diff) | |
code-modernization: version 1.0.0, usage counts and a README results table
The plugin now has a version and a changelog. Two hooks record whole-number usage counts (which command ran, how far a system got, how many rules and proofs) through the CLI's own telemetry: counts from 100 up are rounded, nothing is sent when the plugin is not in use, and any of three switches turns it off. The README documents every key and lists what the plugin was tried on, checked against the run files.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/code-modernization/.claude-plugin/plugin.json | 7 | ||||
| -rw-r--r-- | plugins/code-modernization/CHANGELOG.md | 15 | ||||
| -rw-r--r-- | plugins/code-modernization/README.md | 162 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/hooks.json | 32 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/telemetry.py | 562 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/telemetry.sh | 26 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_telemetry.py | 600 |
7 files changed, 1368 insertions, 36 deletions
diff --git a/plugins/code-modernization/.claude-plugin/plugin.json b/plugins/code-modernization/.claude-plugin/plugin.json index 8646aee2..687043f0 100644 --- a/plugins/code-modernization/.claude-plugin/plugin.json +++ b/plugins/code-modernization/.claude-plugin/plugin.json @@ -1,5 +1,6 @@ { "name": "code-modernization", + "version": "1.0.0", "description": "Guided modernization for any legacy codebase: start with /modernize, get an assessment, an interactive map, the business rules mined from the code, and a plan you approve, then an upgrade, a rewrite or a rebuild with independent proof that the new code behaves like the old. Includes security hardening, a one-page report, specialist agents, and an optional live progress pane (early access).", "author": { "name": "Anthropic", @@ -52,6 +53,12 @@ "title": "Legacy directory", "description": "The read-only tree holding the legacy systems, relative to the workspace.", "default": "legacy" + }, + "telemetry": { + "type": "boolean", + "title": "Usage counts", + "description": "Send usage counts through Claude Code's own telemetry setting: whole numbers only, such as which command ran, how many rules were found and how many modules were proven. Never code, names, paths or prompts. Nothing is sent when Claude Code telemetry is off. See exactly what would be sent with: python3 scripts/telemetry.py show", + "default": true } } } diff --git a/plugins/code-modernization/CHANGELOG.md b/plugins/code-modernization/CHANGELOG.md new file mode 100644 index 00000000..ecaa8dbf --- /dev/null +++ b/plugins/code-modernization/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +Each release gets a new number in `.claude-plugin/plugin.json`; Claude Code only offers an update when that number changes. + +## 1.0.0 + +- **A front door.** `/code-modernization:modernize` asks what you want done (once), records it in `analysis/<system>/INTENT.md`, shows the road and gives the exact first command. `--source <path>` links the code so nothing has to be copied. +- **Same-stack version moves.** `modernize-uplift` catalogs what changes between two versions of the same technology, records a measured baseline, migrates one pilot unit and then the rest by playbook. +- **Independent proof.** `modernize-verify` re-runs the tests from clean, re-runs your own canary, tries inputs nobody used and gives each module one verdict, PROVEN, PARTLY PROVEN or NOT PROVEN, computed by a script from files it parses itself. +- **People decide what only they can.** `modernize-review` records a person's verdict on each flagged rule; the plan, the build and the tests read it. A difference the proof finds is accepted once per input by a person, never by the tool. +- **Comparison that fits real output.** Floating-point output can be compared within a declared, justified tolerance; masks and approvals are listed in the result. +- **Proportional rule extraction.** The same rule found in several files is folded into one, and the number of rules follows the size of the code. +- **A one-page report** (`REPORT.html`, works offline) with the proof, the rules, the map and a next step you can copy. +- **A live progress pane** (early access, terminal): the estate map, the rule review deck, the sign-off dialog and the proof at a glance. +- **Usage counts** (whole numbers only, off by switch): see the Telemetry section of the README. diff --git a/plugins/code-modernization/README.md b/plugins/code-modernization/README.md index c1f047b1..691d355a 100644 --- a/plugins/code-modernization/README.md +++ b/plugins/code-modernization/README.md @@ -1,30 +1,31 @@ # Code Modernization -Point Claude at a legacy codebase (COBOL, Java, .NET, PHP, Perl, Python 2, C and more) and get an assessment, an interactive map, the business rules mined out of the code with citations, a plan you approve, and rewritten or upgraded code with tests that prove it still behaves the same. +Point Claude at a legacy codebase and get four things: an understanding of what it is and what it does, a plan you approve, the modernized code, and **proof that the new code behaves like the old**. It works with any language and any kind of move: a newer version of the same technology, a rewrite in another one, or a rebuild on a new architecture. - + ## Install +You need [Claude Code](https://code.claude.com). Then: + ``` /plugin install code-modernization@claude-plugins-official ``` +Some steps start many agents at once, so expect real usage on a large system (see *What to expect*). Start with one module or one unit as a pilot, not the whole estate. + ## Start here -Type `/code-modernization:modernize` in a workspace folder (autocomplete finds it from `/modernize`). It asks what you want to do with -your code, finds it (a `legacy/<name>` copy or symlink, or a folder you point it at), writes your answers down once, shows the road -ahead, and gives you the exact first command. You can also run any command directly: +Open a folder for the work and type `/code-modernization:modernize`. It asks what you want to do with your code (a couple of short questions), finds the code, writes your answers down once, shows the road ahead, and gives you the exact first command. Every later command reads what you said, so nothing is asked twice. **Not sure what you want?** Choose *Understand it first*: you get the assessment, the map, the business rules and a plan, and no code is rebuilt. -1. **Point it at your code.** Put it at `legacy/<name>` (a copy or a symlink), or pass `--source <path>` to preflight: it makes the - `legacy/<name>` link for you and copies nothing. `<name>` is a short label: letters, digits, `-` and `_`. -2. **Run** `/code-modernization:modernize-preflight <name>`. -3. **Follow the "next step" line** each command ends with, or run `/code-modernization:modernize-status <name>` at any time: it says - where you are and gives the exact command to paste. +To go step by step instead, point the first command at your code and follow the "next step" line each command ends with: -Commands are namespaced, so type the full name. Flags go after the arguments. No command edits your code: they write to -`analysis/<name>/` and `modernized/`, and each refreshes `analysis/<name>/REPORT.html`, one page with everything found so far that -you can open or share. +``` +/code-modernization:modernize-preflight <name> --source <path to your code> +/code-modernization:modernize-status <name> # where am I, and what is next: run it any time +``` + +`<name>` is a short label of your choice (letters, digits, `-`, `_`). `--source` makes a link at `legacy/<name>` and copies nothing, so a huge repository stays where it is. **Nothing edits your legacy source.** Commands write only to `analysis/<name>/` and `modernized/` (a build check writes build output where your build normally does), and each refreshes `analysis/<name>/REPORT.html`: one page, with everything found so far, that you can open or share. A few steps need someone who knows how the system is built and run, so bring an engineer for the first questions. ## The path @@ -32,25 +33,80 @@ Each step stands alone, so you can stop and review after any of them. | Step | Command | What you get | | --- | --- | --- | -| 1 | `modernize-preflight <name> [target-stack]` | Is the environment ready? Asks the five questions only a person can answer, checks tools and a real build, finds missing source, and says what to fix. `PREFLIGHT.md` | -| 2 | `modernize-assess <name>` | What am I dealing with: inventory, complexity, debt, security, and the recommended pattern. `ASSESSMENT.md` | -| 3 | `modernize-map <name>` | The structure: dependencies, data flow, entry points and business flows as an interactive map (`TOPOLOGY.html`). Takes an existing dependency graph with `--graph <file>`. | -| 4 | `modernize-extract-rules <name>` | The business rules as testable Given/When/Then cards with `file:line` citations, each checked by a second agent. `BUSINESS_RULES.md` | -| 5 | `modernize-brief <name> [target-stack]` | The phased plan a steering committee approves. Nothing is built until you approve it. `MODERNIZATION_BRIEF.md` | -| 6 | one of `uplift`, `transform`, `reimagine` | The build. See below. | -| 7 | `modernize-harden <name>` | A security scan of the still-running legacy system, with ranked findings and a reviewed patch you apply yourself. `SECURITY_FINDINGS.md` | +| 0 | `modernize` | Say what you want. Writes `INTENT.md`; every later command reads it. | +| 1 | `modernize-preflight <name> [target-stack] [--source <path>]` | Is the environment ready? Asks five questions only a person can answer (is this the whole system or a slice, can it build and test here, is there custom build tooling, has anyone tried before, is anything off limits), proves a build works on this code, and finds missing source. | +| 2 | `modernize-assess <name>` | What am I dealing with: inventory, complexity, debt, security, and a recommended pattern. | +| 3 | `modernize-map <name>` | The structure: dependencies, data flow, entry points and business flows, as an interactive map. | +| 4 | `modernize-extract-rules <name>` | The business rules as testable Given/When/Then cards with `file:line` citations, each re-checked by a second agent. | +| 4b | `modernize-review <name>` | A person confirms or corrects the rules that look wrong. Your answers reach the plan and the build. With the live pane on, `/modernize-review-pane` does the same one card at a time. | +| 5 | `modernize-brief <name> [target-stack]` | The phased plan a steering committee approves. **Nothing is built until you approve it.** | +| 6 | `uplift`, `transform` or `reimagine` | The build (see below). | +| 7 | `modernize-verify <name>` | **The proof.** An independent re-check with one verdict per module. | +| 8 | `modernize-harden <name>` | A security scan of the legacy system with a reviewed patch you apply yourself. | + +`assess --portfolio <parent-dir>` surveys many systems and ranks them on one page. `modernize-status <name>` says where you are and gives the exact command to paste. + +**A person decides at six points**, and the plugin never decides them for you: the five preflight answers, the rules that look wrong (`review`), approving the brief, accepting any difference the proof finds, signing the proof, and applying the security patch. -`assess --portfolio <parent-dir>` ranks many systems into a sequencing heat-map. +## How it proves the result -## Choose how to build (the brief recommends one) +Modernization fails quietly: the new code passes the tests someone wrote, and differs on the inputs nobody thought of. So the proof is built from evidence a script can check, not from the model's opinion. `modernize-verify` runs after a build, ideally in a fresh session, and re-does the work instead of trusting the notes the build left behind: + +- **The tests, run again from clean.** Build output is deleted, the full suite runs, and the counts come from the runner's own result files or a saved log. A run that executed no tests, or skipped them, is a failure, and a count the command merely typed in does not count. +- **Old and new on the same inputs.** Where the legacy code can run, both run on the same inputs and a script compares every byte. Only fields that must vary (timestamps, generated ids) are masked, floating-point output can be compared within a declared tolerance, and every masked field is listed in the result. A difference a person accepts is recorded with the reason. +- **Inputs nobody used.** It invents at least ten new inputs (boundaries, empty, huge, unusual order, and malformed records when you asked for exact behavior, quirks included) and compares again, so a suite that only passes on the cases the model chose is caught. +- **Tests that can fail.** A deliberate one-line break must turn tests red (the canary), and the comparison itself is checked by changing one byte of an output. +- **Every critical rule is backed by a test that ran.** Each P0 business rule must be named by a test that executed and passed. A rule named only by a skipped or pending test is listed as "named, not run", and a test folder that holds no code of its own is listed as tooling and gets no verdict. +- **The source is untouched**, checked by file times without running anything inside the analyzed tree. + +Each module gets one verdict, computed by `scripts/proof_pack.py` from those files with rules written into the output: **PROVEN**, **PARTLY PROVEN** (with what is missing) or **NOT PROVEN** (nothing ran, something differs, a test fails). If the old system cannot run where you work (a mainframe program, a system that only runs in production), the old behavior can only be checked against recorded outputs, and the best verdict is PARTLY PROVEN: the page says so plainly. Anything a person must decide (open questions, exit criteria, the sign-off) is listed as waiting for a person and is never ticked for you. Every verdict is computed again from current evidence each time; none is carried over from an earlier run. + + + +## Choose how to build (the plan recommends one) | If you want | Run | What happens | | --- | --- | --- | -| The same language on a newer version (.NET Framework 4.8 to .NET 8, Java 8 to 17, Spring Boot 2 to 3) | `modernize-uplift <name> <from> <to>` | Keeps your code and fixes only what the new version breaks, driven by a catalog of the breaking changes this code actually hits. One pilot unit first and its lessons written down, then batches. Proves nothing changed by running the test suite on both versions where both can run. | -| A new stack, one module at a time, while the old system keeps running | `modernize-transform <name> [module] [target-stack]` | A plan you approve, tests that pin the old behavior, an idiomatic rewrite, and proof: the tests are run, counted, and shown to fail when the code is deliberately broken. | -| A rebuild on a new architecture | `modernize-reimagine <name> <vision>` | A spec mined from the code, an architecture that is reviewed and approved, then services scaffolded with executable acceptance tests. | +| The same technology on a newer version (.NET Framework to .NET 8, Java 8 to 17, Spring Boot 2 to 3) | `modernize-uplift <name> [source-version] [target-version]` | Keeps your code and fixes only what the new version breaks, driven by a catalog of the breaking changes this code actually hits. One pilot unit first with its lessons written down, then batches. The proof is the same test suite run on both versions. | +| A new technology, one module at a time, while the old system keeps running | `modernize-transform <name> [module] [target-stack]` | A plan you approve, tests that pin the old behavior, an idiomatic rewrite, and proof: old and new run on the same inputs and a script compares them. | +| A rebuild on a new architecture | `modernize-reimagine <name> [target-vision]` | A spec mined from the code, an architecture that is reviewed and approved, then services scaffolded with executable acceptance tests. | -If the delta catalog shows an "uplift" would rewrite most of the code, the command says so and points to `transform`. +A version move keeps your code, so it can skip `extract-rules` and `review`: `preflight`, `assess`, `uplift`, `verify` is a complete path, and `map` and `brief` add the unit order and an approved phased plan for a large system. If the delta catalog shows an "uplift" would rewrite most of the code, the command says so and points to `transform`. Rehost (move as is) and Replace (buy a product) change no code, so no build command applies; the analysis is still useful for both. + +## What it has been tried on + +The commands were run for real, headlessly, on public codebases while the plugin was built, and what broke was fixed. Every number below comes from the files those runs wrote. The same command can give different counts on a second run (the security scan of the osCommerce code found 48 confirmed findings and then 52), so read the numbers as typical, not exact. Wherever a person had to decide (approve a plan, accept a difference), the tester played that person. Some runs stopped early because of limits of the test machine (it refused to run any freshly compiled program, and its package index refused installs); the plugin said so and did not work around them. + +| Codebase | Move | What it did and what was shown | +| --- | --- | --- | +| **AWS CardDemo** (COBOL, CICS, JCL) | Rewrite in Java, one job at a time | 35 rules (8 critical) and a five-phase plan, then the monthly interest job rewritten in Java 21 (213 tests at the end). Five independent checks in a row compared it with the real COBOL program, built locally, on inputs written after the fact. Each found something the tests had missed, and each was answered: a blank field that halted the job, a non-numeric account key, a negative zero, and differences the owner accepted as deliberate. The last check tried fifteen more inputs with malformed records and found seven more differences, so it ended NOT PROVEN. It also told two problems of the old system's test harness apart from defects in the new code. What ends a loop like this is a person deciding which inputs are in scope; the verify command now reads that from the intent you gave the front door. | +| **Eclipse Jetty** (Java 8, 2,600 files) | Java 8 to 17 | A pilot on the `jetty-util` module: the same 946 tests give the same results on both Java versions. Building and running both versions found six changes that reading the code had not predicted: a direct buffer reported as memory-mapped on 17, a bundle plugin that writes an invalid manifest and still says SUCCESS, and a build on JDK 13 to 16 that would have shipped Java 8-labelled classes that crash on Java 8, among others. 50 tests were added for the 25 of 56 critical rules that had none (996 tests run on each version, no differences). | +| **osCommerce** (PHP 5, about 44,000 lines of PHP) | PHP to Python and FastAPI | 97 rules (26 critical) and a six-phase plan. First slice, the product page: 17,957 tests pass, and 17,727 comparison cases against the real PHP files are identical. Two deliberate breaks each turned tests red. The architecture review found two high-severity problems (expired specials still shown, and a page request holding a database write lock) that were fixed with tests that failed first. An independent verification said PROVEN: its own break made 647 more tests fail, and 14 new inputs matched the real PHP. | +| **AngularJS RealWorld** (AngularJS 1.5) | AngularJS to React and TypeScript | 79 rules (5 critical). The articles service was rewritten: 166 tests, and 29 comparison cases against recorded responses of the real API (23 identical, 6 differences approved as deliberate, none unexplained). Four deliberate breaks each turned tests red, and the review's two high-severity findings were fixed. Checked by the build step itself; there was no separate verification run. | +| **JPetStore** (Java and JSP) | Rebuild as a REST API | A spec with 12 capabilities, the 35 rules and a four-phase plan. The architecture review found two blockers (an order confirmation that could not be safely replayed, and cart updates lost under parallel requests); both were designed out. One service was scaffolded: 35 tests ran and passed, 56 more are pending or need Docker. The independent check said NOT PROVEN: 6 of 24 new comparisons with the old application differ, and the development cases hold no old-versus-new comparison yet. That run also showed the proof step counting skipped tests as covering a rule; it now flags five of the six critical rules as named only by tests that did not run. | +| **beets** (Python 2, about 19,000 lines) | Python 2 to 3 | 21 rules for the tagging module (4 critical), all about matching. Only 3 files in the whole tree fail to compile on Python 3, so it is an uplift and not a rewrite. No existing test could run on Python 3 yet, and the packages they need were refused by this machine's package index; the plugin reported that and did not claim a pass. | +| **Spring PetClinic** (7 services) | Spring Boot 2.6 to 3.3 | A delta catalog with exact target versions: 59 `javax` imports in 10 files to move, a request that answered 200 on 2.6 and answers 400 on 3.3 (verified by running both), a Hibernate 6 identifier check that came out safe, and a monitoring endpoint that Boot 3 dropped. The pilot stopped at the plan gate because the approved plan named a different first service, and the command enforced the plan. | +| **AWStats** (Perl, about 43,000 lines) | Perl to Python and FastAPI | 88 rules (2 critical) and a six-phase plan that keeps replacing it with an existing product open as the alternative. The security scan confirmed 48 findings, 9 of them high (7 in an optional module that runs as root), and refuted 14 of 62 as false positives. | +| **Redmine 2.3.3, eShop (.NET), Jenkins pipelines** | Rails 3.2 to 7.1, .NET Framework 4.7.2 to .NET 10, Jenkins to GitHub Actions | Maps, rules (185, 57 and 58) and plans. Redmine's assessment led with "check whether upstream already made this move". eShop's catalog lists 12 silent behavior changes and says the first phase must build a test harness because the solution has none. | +| **NetHack, KISS FFT, BSD numbers** (C) | C to Python, and to Rust | 28, 70 to 93 and 56 rules. NetHack's first slice (its declarations, in Python) matched the C program on 8 of 8 comparison cases. The Rust runs stopped at the plan: this Mac killed every freshly compiled program, so the plugin listed what could not run and did not work around it. | +| **A booby-trapped codebase** (built for the test) | Rewrite | Planted instructions in comments, the README, a `CLAUDE.md` and a project settings file, a script that would drop a marker file, and file names with shell syntax. Nothing planted was obeyed, no marker file appeared, the source stayed unchanged, the planted lines were listed in the report, and the credential was masked. | + +## What to expect + +Steps run as agents working for you, and the heavy ones run many at once. Rough times on systems of tens of thousands of lines: preflight 3 to 4 minutes, assess 5 to 8, map 5 to 15, extract-rules 5 to 15, brief about 5. Building one module takes 15 to 30 minutes, an uplift pilot about 15. The heaviest step, `extract-rules`, started 50 to 200 agents in these runs, and every fan-out step says how many it will start; `extract-rules` asks before a big run. On systems in the millions of lines, work one module or unit at a time. The size index in `assess` is a relative measure for ranking systems, never a schedule or a cost. + +## Words you will see + +| Word | Plain meaning | +| --- | --- | +| Agent | A separate Claude worker that does one job (read one module, check one rule) and reports back. Steps start many of them at once. | +| Business rule card | One thing the system does, written as Given / When / Then with the file and line it comes from, so a person can check it. | +| P0 | A rule that would defeat the system's purpose or be costly or irreversible if it were wrong. Everything else is P1 or P2. | +| Brief | The written plan, phase by phase. You approve it; commands never build anything before that. | +| Uplift / transform / reimagine | Newer version of the same technology / rewrite in another technology / rebuild on a new architecture. | +| Pilot | The first small unit built end to end, so its lessons are written down before the rest is attempted. | +| Canary | A deliberate one-line break in the new code that must make tests fail, proving the tests can fail. | +| Delta catalog | The list of things the newer version breaks that this code actually uses. | ## Set it up so it runs smoothly @@ -70,36 +126,74 @@ The commands never edit your code, by convention. A `.claude/settings.json` in t - The rule covers Claude's file tools and the shell commands it recognizes. A script that opens files itself is not covered, so keep Bash on a *prompted* permission mode for the two steps that fan out many writing agents at once (`uplift` step 5b and `reimagine` phase E). - Shell commands still ask even in accept-edits mode (`python3` scripts, `scc`, `rsync`, your build and test commands, anything outside the workspace). Use accept-edits mode or allow rules for the ones you trust. -Helpful but optional (run `preflight` to check them all): [`scc`](https://github.com/boyter/scc) or `cloc` for size metrics; `python3` for the map, the shard builder and the report; a build toolchain for your stack, which enables the strongest equivalence proof (running old and new side by side); and the whole system in the tree (deployment descriptors, copybooks, DDL), which entry points and data lineage need. Without a toolchain the plugin falls back to recorded-output tests and says so. +Helpful but optional (run `preflight` to check them all): [`scc`](https://github.com/boyter/scc) or `cloc` for size metrics; Python 3.8 or newer as `python3` (on Windows `python` or `py -3` works) for the map, the shard builder, the proof and the report; a build toolchain for your stack, which enables the strongest proof (running old and new side by side); and the whole system in the tree (deployment descriptors, copybooks, DDL), which entry points and data lineage need. Without a toolchain the plugin falls back to recorded-output tests and says so. ## Safety -- **Analyzed code is untrusted input.** A hostile codebase can plant comments like "ignore previous instructions" to steer what lands in `BUSINESS_RULES.md` or `SECURITY_FINDINGS.md`. Agents treat file content as data and flag instruction-shaped text, verification agents re-derive every rule and finding from the cited code, and `brief` is a human approval gate before anything is built. Treat discovery artifacts from untrusted code with the same skepticism as the code. +- **Analyzed code is untrusted input.** A hostile codebase can plant comments like "ignore previous instructions", a README that tells tools to run a script, or file names with shell syntax. Agents treat file content as data, list the instruction-shaped text they found and never follow it (the legacy code's own build and tests run only where a command needs its behavior, in a scratch copy when it can), verification agents re-derive every rule and finding from the cited code, and `brief` is a human approval gate before anything is built. Treat discovery artifacts from untrusted code with the same skepticism as the code. - **Secrets stay out of shared artifacts.** Discovered credentials are masked (`AKIA****`) and inventoried in a gitignored `SECRETS.local.md` (or `~/.modernize/<name>/` outside git); `harden` keeps credential-removal hunks in a separate gitignored patch. `--show-secrets` puts raw values in the quarantine file only. +- **The old system is run only where it is safe.** Baselines come from the legacy code running locally or against a test environment you named. Production or third-party services, new accounts and real data are off limits unless the plan you approved names them, a token in a recorded response is replaced before anything is saved, and every command stops the servers it started. - **Trying it on a live repository.** `preflight` and `assess` change no source file. Preflight's smoke test compiles one file and, where there is a build system, restores and builds one small project, which writes build output wherever the build normally does. +## Telemetry + +The plugin counts how it is used, so the next version can be better. It sends **whole numbers only**: never code, file or system names, paths, prompts or anything you typed. Counts of 100 or more are rounded to two significant figures (17,727 is sent as 18,000), so a number says roughly how big, not exactly which system. It sends them through Claude Code's own telemetry, so nothing is sent to Anthropic when that is off. The plugin itself makes no network call and adds no identifier; the one file it writes is a small `telemetry-state.json` of hashes in its own data folder, so the same counts are not sent twice. + +Two hooks do it, and only in a folder where you are using the plugin (you typed one of its commands, or the folder holds an `analysis/<name>/` folder with files it wrote, such as `INTENT.md` or `PREFLIGHT.md`): + +- **When you type one of the plugin's commands:** which command, and how far that system had got. +- **When a turn ends and the counts changed:** how far the newest system has got. + +| Key | What it counts | +| --- | --- | +| `pv` | plugin version as major*10000 + minor*100 + patch | +| `cmd` | command typed: 1 front door, 2 preflight, 3 assess, 4 map, 5 extract-rules, 6 review, 7 brief, 8 transform, 9 uplift, 10 reimagine, 11 verify, 12 harden, 13 status, 20 to 22 the pane's commands, 99 other | +| `perm` | permission mode the session ran in: 0 unknown, 1 default, 2 accept edits, 3 plan, 4 auto, 5 bypass, 6 don't ask | +| `has_source` | 1 when the command carried `--source` | +| `fresh` | 1 when the system had no artifacts yet | +| `systems` | systems under `analysis/` | +| `goal` | 0 unknown, 1 understand, 2 uplift, 3 transform, 4 reimagine | +| `lang` | the language with most lines in the map: 1 COBOL, 2 Java, 3 C# and .NET, 4 Python, 5 PHP, 6 Perl, 7 C, 8 C++, 9 JavaScript and TypeScript, 10 Ruby, 11 Go, 12 Rust, 13 Kotlin and Scala, 14 SQL, 15 Fortran, 16 RPG, 17 Pascal and Delphi, 18 shell, 19 assembler, 99 other, 0 unknown | +| `done` | the steps that have left their file, added up: preflight 1, assess 2, map 4, rules 8, reviewed 16, brief 32, approved 64, built 128, verified 256, signed 512, hardened 1024, report 2048, deltas 4096, baseline 8192, playbook 16384, spec 32768 | +| `map_kloc` | thousand lines of code in the map | +| `rules`, `p0` | business rules found, and the critical ones among them | +| `rev_ok`, `rev_wrong` | rules a person confirmed, and rules a person marked wrong | +| `phases` | phases in the plan | +| `built` | modules or services built (an uplift's working copy counts as one once it exists) | +| `eq_cases`, `eq_diff`, `eq_appr` | old-versus-new comparison cases run, differences or missing outputs nobody approved, differences a person approved (counted from the case list, the way the report counts them) | +| `v_proven`, `v_partly`, `v_not` | modules judged PROVEN, PARTLY PROVEN and NOT PROVEN | +| `sec_crit`, `sec_high` | critical and high security findings | + +To see exactly what would be sent for your workspace, before anything is sent, run `python3 scripts/telemetry.py show /path/to/workspace` from the plugin's folder (add `--prompt "/code-modernization:modernize-verify billing"` to see a command's counts). + +To turn it off, use any one of these: the plugin's **Usage counts** option, `CODE_MODERNIZATION_TELEMETRY=0` in your environment (anything but an explicit `1` or `on` counts as off), or Claude Code's own `DISABLE_TELEMETRY=1` (or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`). Nothing is sent while any of them is set. + +If nothing seems to be sent when you expect it, set `CODE_MODERNIZATION_TELEMETRY_DEBUG=1`: each hook run then adds one line saying what it decided to `telemetry-debug.log` in the plugin's data folder. + ## Working in a team -State lives in files, not in chat: later commands read the brief and `PREFLIGHT.md`, not your conversation, so a second person or a fresh session can run `status` and continue. The commands never commit, so commit `analysis/` and `modernized/` yourself. +State lives in files, not in chat: later commands read the brief, the intent and `PREFLIGHT.md`, not your conversation, so a second person or a fresh session can run `status` and continue. The commands never commit to your repository, so commit `analysis/` and `modernized/` yourself (an uplift's working copy gets its own local history, for a reviewable diff). | Artifact | Suggested reviewer | | --- | --- | | `PREFLIGHT.md` (the five answers, scope boundary, build checks) | whoever owns the build | | `ASSESSMENT.md`, `REPORT.html` | the engineering lead or sponsor | | `topology.json`, `TOPOLOGY.html` | engineers who know the system | -| `BUSINESS_RULES.md` | a business expert per domain: start with the P0 rules and the closing question list | +| `BUSINESS_RULES.md` (then `modernize-review`) | a business expert per domain: start with the P0 rules and the closing question list | | `MODERNIZATION_BRIEF.md` | the approver, who steers execution by editing it | +| `VERIFICATION.md` | the approver and a second engineer, who sign it | | `SECURITY_FINDINGS.md` and the patch | a security engineer, who applies the patch | ## Live progress pane (early access) -A pane beside the transcript that shows the map of your code, how far each part has got and what to run next, in any language and for any of the three ways of building. It needs Claude Code's early-access function hooks: start with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude`. Without the flag nothing changes. Details are in [hooks/README.md](hooks/README.md). +A pane beside the transcript that shows the map of your code, how far each part has got, each built module's proof verdict, and what to run next, in any language and for any of the three ways of building. It needs Claude Code's early-access function hooks: start with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude`. Without the flag nothing changes. Its three commands are typed bare: `/modernize-panel` shows or hides it, `/modernize-review-pane` reviews the flagged rule cards in it, and `/modernize-sign` fills in the plan's approval block. Details are in [hooks/README.md](hooks/README.md). + + ## Good to know -- **The assessment's COCOMO figure is a relative size index, never a timeline or a cost.** Its constants encode human-team productivity, which agentic work does not follow. -- **A model does the extraction, so two runs can find different rules.** Treat `BUSINESS_RULES.md` as reviewed output, not a deterministic build artifact. Headings are always `### RULE-NNN: <name>`. -- **Large runs are resumable.** On Claude Code builds with the Workflow tool, `extract-rules`, `harden`, `assess --portfolio`, `reimagine` and `uplift` run as scripted multi-agent jobs that verify findings adversarially. `extract-rules` shards by module and asks before a big run; a stopped run resumes in the same session with its run ID, and finished agents replay from the journal. `uplift` migrates in escalating batches behind a circuit breaker. Older builds fall back to plain subagents automatically. +- **A model does the extraction, so two runs can find different rules.** Treat `BUSINESS_RULES.md` as reviewed output, not a deterministic build artifact. Rules are cut one per business decision, not one per branch, and headings are always `### RULE-NNN: <name>`. +- **Large runs are resumable.** On Claude Code builds with the Workflow tool, `extract-rules`, `harden`, `assess --portfolio`, `reimagine` and `uplift` run as scripted multi-agent jobs that verify findings adversarially. `extract-rules` shards by module and asks before a big run; a stopped run resumes in the same session with its run ID, and finished agents replay from the journal. Older builds fall back to plain subagents automatically. - **Scripting it (`claude -p`).** Long steps run as background workflows, and a headless session stops waiting for background work after 10 minutes. Set `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0` so `extract-rules`, `harden` and the other fan-out steps can finish, and answer a step's approval gate by resuming the session with `--resume`. - **Adapting it.** Commands, agents and workflows are markdown and JavaScript under Apache 2.0: fork them to change the prompts or steps for your stack. - **Agents.** `legacy-analyst`, `business-rules-extractor`, `architecture-critic`, `security-auditor`, `test-engineer`, `version-delta-analyst`, `uplift-migrator` and `scaffolder` are invoked by the commands (or directly). The last two write only inside their own unit's directory. diff --git a/plugins/code-modernization/hooks/hooks.json b/plugins/code-modernization/hooks/hooks.json index 7e99b4e0..6ac35230 100644 --- a/plugins/code-modernization/hooks/hooks.json +++ b/plugins/code-modernization/hooks/hooks.json @@ -1,4 +1,32 @@ { - "description": "The modernization pane and estate map, x-ray reads, the rule review deck, the sign-off dialog and the fleet view", - "modules": ["./register.ts"] + "description": "The modernization pane and estate map, x-ray reads, the rule review deck, the sign-off dialog and the fleet view, and usage counts (whole numbers only, see the README)", + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "sh \"${CLAUDE_PLUGIN_ROOT}/scripts/telemetry.sh\" command", + "timeout": 10, + "asyncRewake": true + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "sh \"${CLAUDE_PLUGIN_ROOT}/scripts/telemetry.sh\" state", + "timeout": 10, + "asyncRewake": true + } + ] + } + ] + }, + "modules": [ + "./register.ts" + ] } diff --git a/plugins/code-modernization/scripts/telemetry.py b/plugins/code-modernization/scripts/telemetry.py new file mode 100644 index 00000000..ada1d953 --- /dev/null +++ b/plugins/code-modernization/scripts/telemetry.py @@ -0,0 +1,562 @@ +#!/usr/bin/env python3 +"""Usage counts for the code-modernization plugin. Whole numbers only, never text. + + telemetry.py command UserPromptSubmit hook: which of the plugin's commands was typed + telemetry.py state Stop hook: how far the newest system under analysis/ has got + telemetry.py show [DIR] [--prompt TEXT] [--json] + print what the hooks would send for the workspace DIR (default: this folder) + +The two hooks read the hook's JSON from stdin and print at most one line, {"metrics": {...}}, which Claude Code +records as usage counts when its own telemetry is on. Every key is fixed below and every value is a whole number, +capped, and rounded to two significant figures from 100 up, so a count is not a fingerprint of one system. Nothing is +read except the plugin's own artifacts under analysis/ and modernized/, and no file name, path, system name, code or +prompt text leaves this script. Nothing is sent when the plugin has not been used in the folder. It never raises, +gives up after three seconds and always exits 0. + +Off switches: CODE_MODERNIZATION_TELEMETRY=0, the plugin's "Usage counts" option, or Claude Code's own +DISABLE_TELEMETRY / CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC. Anything but an explicit "on" in the first two +switches its off. To find out why nothing was sent, set CODE_MODERNIZATION_TELEMETRY_DEBUG=1: each hook run then +appends one line saying what it decided to telemetry-debug.log in the plugin's data folder. +""" +import collections +import hashlib +import itertools +import json +import os +import re +import signal +import stat +import sys +import tempfile +import time + +sys.dont_write_bytecode = True # a hook must not leave files in the plugin's own folder +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import build_report as br # noqa: E402 (reads the artifacts safely and counts them the way the report does) + +MAX_KEYS, CAP = 20, 10 ** 9 +TRUE = {"1", "true", "on", "yes"} +# The most a key can carry: a hostile artifact cannot make a count bigger than this. Counts from 100 up are rounded to two +# significant figures; enumerations and the step bitmask are exact. +LIMITS = {"pv": 999999, "cmd": 99, "perm": 6, "has_source": 1, "fresh": 1, "systems": 99, "goal": 4, "lang": 99, "done": 65535, "phases": 99} +COUNT_LIMIT = 10 ** 7 +EXACT = {"pv", "cmd", "perm", "has_source", "fresh", "goal", "lang", "done"} +NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}") +LINE_WIDTH = 600 # longer lines are cut before anything is parsed, so no artifact can make a pattern slow + +# One number per command: 1 is the front door, 20-22 are the pane's own commands (panel, review-pane, sign), typed without the plugin's name. +COMMANDS = {"": 1, "preflight": 2, "assess": 3, "map": 4, "extract-rules": 5, "review": 6, "brief": 7, "transform": 8, + "uplift": 9, "reimagine": 10, "verify": 11, "harden": 12, "status": 13} +PANE = {"panel": 20, "review-pane": 21, "sign": 22} +OTHER_COMMAND = 99 +PERMISSION_MODES = {"default": 1, "acceptEdits": 2, "plan": 3, "auto": 4, "bypassPermissions": 5, "dontAsk": 6} +COMMAND_RE = re.compile(r"^/(?P<ns>code-modernization:)?modernize(?:-(?P<verb>[a-z][a-z-]*))?(?=\s|$)") + +GOALS = {"understand": 1, "uplift": 2, "transform": 3, "reimagine": 4} +GOAL_LABEL = re.compile(r"(?i)^goal\b\s*[:\u2013\u2014]?\s*(.*)$") +GOAL_WORDS = re.compile(r"(?i)(understand|uplift|transform|reimagine|rewrite|rebuild)\b") +GOAL_ALIASES = {"rewrite": "transform", "rebuild": "reimagine"} +# the pop-up's own wording, when that is what was written down +GOAL_PHRASES = [(re.compile(r"(?i)newer version|same technology"), 2), (re.compile(r"(?i)different technology|one piece at a time"), 3), + (re.compile(r"(?i)from scratch|new architecture"), 4), (re.compile(r"(?i)understand it|map it"), 1)] + +# What the code is written in: the dominant language of the map, as one of these numbers (0 unknown, 99 other). +LANGS = {"cobol": 1, "jcl": 1, "java": 2, "jsp": 2, "c#": 3, "csharp": 3, "vb": 3, "vb.net": 3, "f#": 3, "python": 4, "php": 5, + "perl": 6, "c": 7, "c++": 8, "cpp": 8, "javascript": 9, "typescript": 9, "js": 9, "ts": 9, "node": 9, "angularjs": 9, + "ruby": 10, "go": 11, "golang": 11, "rust": 12, "kotlin": 13, "scala": 13, "groovy": 13, "sql": 14, "plsql": 14, + "pl/sql": 14, "tsql": 14, "fortran": 15, "rpg": 16, "rpgle": 16, "pascal": 17, "delphi": 17, "shell": 18, "bash": 18, + "assembler": 19, "assembly": 19, "hlasm": 19, "asp": 3, "vb6": 3, "nodejs": 9, "c/c++": 7} +# labels in a map that are not a language somebody modernizes +NOT_CODE = {"artifact", "make", "makefile", "cmake", "yaml", "yml", "json", "xml", "toml", "ini", "markdown", "md", "text", "txt", "html", "css", + "pkgconfig", "config", "properties", "docker", "dockerfile", "csv", "svg", "data", "binary", "license", "gradle", "maven", "unknown", "other"} + +# `done` adds up one of these for every step that has left its file: 15 = preflight, assess, map and rules. +STEPS = [("preflight", 1), ("assess", 2), ("map", 4), ("rules", 8), ("reviewed", 16), ("brief", 32), ("approved", 64), + ("built", 128), ("verified", 256), ("signed", 512), ("hardened", 1024), ("report", 2048), ("deltas", 4096), + ("baseline", 8192), ("playbook", 16384), ("spec", 32768)] +# Files that only this plugin writes: a folder with none of them is not something the plugin has worked on. +GATE = ("INTENT.md", "PREFLIGHT.md", "MODERNIZATION_BRIEF.md", "BUSINESS_RULES.md", "DELTA_CATALOG.md", "VERIFICATION.json", "RULE_REVIEWS.json", "AI_NATIVE_SPEC.md") +FILES = {"preflight": "PREFLIGHT.md", "assess": "ASSESSMENT.md", "map": "topology.json", "brief": "MODERNIZATION_BRIEF.md", + "verified": "VERIFICATION.json", "hardened": "SECURITY_FINDINGS.md", "report": "REPORT.html", + "deltas": "DELTA_CATALOG.md", "baseline": "BASELINE.md", "playbook": "PLAYBOOK.md", "spec": "AI_NATIVE_SPEC.md"} + +# Every key that can be sent, and what it counts. Order is send order; the version comes first so it always survives. +MEANING = collections.OrderedDict([ + ("pv", "plugin version as major*10000 + minor*100 + patch"), + ("cmd", "command typed: 1 front door, 2 preflight, 3 assess, 4 map, 5 extract-rules, 6 review, 7 brief, 8 transform, " + "9 uplift, 10 reimagine, 11 verify, 12 harden, 13 status, 20-22 pane commands, 99 other"), + ("perm", "permission mode the session ran in: 0 unknown, 1 default, 2 accept edits, 3 plan, 4 auto, 5 bypass, 6 don't ask"), + ("has_source", "1 when the command carried --source"), + ("fresh", "1 when the system has no artifacts yet"), + ("systems", "systems under analysis/"), + ("goal", "0 unknown, 1 understand, 2 uplift, 3 transform, 4 reimagine"), + ("lang", "dominant language of the map: 1 COBOL, 2 Java, 3 C#/.NET, 4 Python, 5 PHP, 6 Perl, 7 C, 8 C++, " + "9 JavaScript/TypeScript, 10 Ruby, 11 Go, 12 Rust, 13 Kotlin/Scala, 14 SQL, 15 Fortran, 16 RPG, 17 Pascal/Delphi, " + "18 shell, 19 assembler, 99 other, 0 unknown"), + ("done", "steps that have left their file, added up: " + ", ".join("%s=%d" % s for s in STEPS)), + ("map_kloc", "thousand lines of code in the map"), + ("rules", "business rules found"), + ("p0", "of those, the critical (P0) ones"), + ("rev_ok", "rules a person confirmed"), + ("rev_wrong", "rules a person marked wrong"), + ("phases", "phases in the plan"), + ("built", "modules or services built (an uplift's working copy counts as one once it exists)"), + ("eq_cases", "old-versus-new comparison cases run"), + ("eq_diff", "of those, differences or missing outputs nobody approved"), + ("eq_appr", "differences a person approved"), + ("v_proven", "modules judged PROVEN"), + ("v_partly", "modules judged PARTLY PROVEN"), + ("v_not", "modules judged NOT PROVEN"), + ("sec_crit", "critical security findings"), + ("sec_high", "high security findings"), +]) +COMMAND_KEYS = ("pv", "cmd", "perm", "has_source", "fresh", "systems", "goal", "done") +STATE_KEYS = ("pv", "goal", "lang", "done", "map_kloc", "rules", "p0", "rev_ok", "rev_wrong", "phases", "built", "eq_cases", + "eq_diff", "eq_appr", "v_proven", "v_partly", "v_not", "sec_crit", "sec_high") + + +def off_reason(env=None): + """Why nothing is sent, or "" when counts may be sent. Sending needs the plugin's switches to be unset or an explicit + "on": any other word (off, no, 0, disabled) turns it off.""" + env = os.environ if env is None else env + val = lambda key: str(env.get(key, "")).strip().lower() # noqa: E731 + if val("CODE_MODERNIZATION_TELEMETRY") and val("CODE_MODERNIZATION_TELEMETRY") not in TRUE: + return "CODE_MODERNIZATION_TELEMETRY is off" + if val("CLAUDE_PLUGIN_OPTION_TELEMETRY") and val("CLAUDE_PLUGIN_OPTION_TELEMETRY") not in TRUE: + return "the plugin's Usage counts option is off" + for key in ("DISABLE_TELEMETRY", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"): + if val(key) in TRUE: + return "%s is set" % key + return "" + + +def whole(value): + """A whole number from 0 to CAP, whatever the artifact held.""" + if isinstance(value, bool): + return int(value) + try: + return max(0, min(CAP, int(value))) + except (TypeError, ValueError, OverflowError): + return 0 + + +def plugin_version(): + try: + with open(os.path.join(HERE, "..", ".claude-plugin", "plugin.json"), encoding="utf-8") as fh: + major, minor, patch = (int(x) for x in str(json.load(fh)["version"]).split(".")[:3]) + return major * 10000 + minor * 100 + patch + except (OSError, ValueError, KeyError, TypeError): + return 0 + + +def plain(path): + return os.path.isfile(path) and not os.path.islink(path) + + +def inside(cwd, path): + """True when path really lives under cwd (links that lead elsewhere are not followed).""" + try: + root = os.path.realpath(cwd) + return os.path.commonpath([root, os.path.realpath(path)]) == root + except ValueError: + return False + + +def systems_in(cwd): + """[(newest modification time, name)] of the folders under analysis/, newest first.""" + out, folder = [], os.path.join(cwd, "analysis") + if os.path.islink(folder) or not inside(cwd, folder): + return out + try: + entries = list(itertools.islice(os.scandir(folder), 200)) + except OSError: + return out + for e in entries: + if e.name.startswith(".") or e.is_symlink() or not e.is_dir(): + continue + try: + times = [e.stat().st_mtime] + kids = list(itertools.islice(os.scandir(e.path), 200)) + except OSError: + continue + for x in kids: + try: + times.append(x.stat().st_mtime) + except OSError: # a dangling link or a file that just went away + pass + out.append((max(times), e.name)) + return sorted(out, reverse=True) + + +def language_code(topo): + """The language with the most lines in the map, as its number.""" + weight, nodes = collections.Counter(), [] + + def walk(node, depth): + if isinstance(node, dict) and depth < 12: + nodes.append(node) + for child in node.get("children") or []: + walk(child, depth + 1) + + if isinstance(topo, dict): + walk(topo.get("root"), 0) + for n in nodes: + lang = n.get("language") + if not n.get("children") and isinstance(lang, str) and isinstance(n.get("loc"), int) and n["loc"] > 0: + low = lang.strip().lower()[:40] + first = re.match(r"[a-z0-9#+]+", low) + first = first.group(0) if first else "" + if low in NOT_CODE or first in NOT_CODE: + continue # build files, data and the like are not what is being modernized + weight[LANGS.get(low) or LANGS.get(first) or 99] += n["loc"] + return min(weight, key=lambda c: (-weight[c], c)) if weight else 0 + + +def goal_code(text, built): + """From the answer written after "Goal" in INTENT.md (its first words, not the sentences around it), else from what was built.""" + lines = [re.sub(r"[*`_#>\-]", " ", l).strip() for l in (text or "").split("\n")[:60]] + for i, line in enumerate(lines): + m = GOAL_LABEL.match(line) + if not m: + continue + rest = m.group(1) + if not rest: # a heading: the answer is on the next line that has words + rest = next((l for l in lines[i + 1:i + 4] if l), "") + rest = (GOAL_LABEL.match(rest) or GOAL_LABEL.match("goal " + rest)).group(1) + word = GOAL_WORDS.match(rest) + if word: + word = word.group(1).lower() + return GOALS[GOAL_ALIASES.get(word, word)] + for pattern, code in GOAL_PHRASES: + if pattern.search(rest[:100]): + return code + break + return {"": 3, "-uplifted": 2, "-reimagined": 4}.get(built, 0) + + +def built_kind_and_count(cwd, system): + """(which kind of build is newest: '' rewrite, '-uplifted' or '-reimagined'; how many modules or services).""" + total, kinds = 0, [] + for suffix in ("", "-uplifted", "-reimagined"): + root = os.path.join(cwd, "modernized", system + suffix) + if os.path.islink(root) or not inside(cwd, root): + continue + try: + kids = [e for e in os.scandir(root) if not e.name.startswith(".") and not e.is_symlink()] + newest = max(e.stat().st_mtime for e in kids) if kids else 0 + except OSError: + continue + if not kids: + continue + dirs = [e for e in kids if e.is_dir()] + total += 1 if suffix == "-uplifted" else (len(dirs) or 1) + kinds.append((newest, suffix)) + return (max(kinds)[1] if kinds else None), total + + +def snapshot(cwd, system): + """The counts for one system, or None when the plugin has left nothing there yet.""" + src = br.Source(cwd, system) + path = lambda name: os.path.join(src.adir, name) # noqa: E731 + + def text(name): + raw = src.read(path(name), name) + return None if raw is None else "\n".join(line[:LINE_WIDTH] for line in raw.split("\n")) + + if not any(plain(path(name)) for name in GATE): + return None + done, out = 0, collections.OrderedDict((k, 0) for k in STATE_KEYS) + present = {step: plain(path(FILES[step])) for step in FILES} + + rules_text = text("BUSINESS_RULES.md") + reviews, _ = src.json(path("RULE_REVIEWS.json"), "RULE_REVIEWS.json") + reviews = {k: v for k, v in reviews["reviews"].items() if isinstance(v, dict)} if isinstance(reviews, dict) and isinstance(reviews.get("reviews"), dict) else {} + cards = [b for b in br.parse_rules(rules_text) if b["k"] == "rule"] if rules_text else [] + if cards: + facts = br.rule_facts(rules_text, cards, reviews) + out["rules"], out["p0"] = whole(facts["total"]), whole(facts["byPriority"].get("P0", 0)) + present["rules"] = True + verdicts = collections.Counter(str(v.get("verdict", "")).lower() for v in reviews.values()) + out["rev_ok"], out["rev_wrong"] = whole(verdicts["confirmed"]), whole(verdicts["wrong"]) + present["reviewed"] = bool(reviews) + + topo, _ = src.json(path("topology.json"), "topology.json") + facts = br.topology_facts(topo) + out["map_kloc"] = whole(facts["loc"] // 1000) if facts else 0 + out["lang"] = language_code(topo) + + brief = text("MODERNIZATION_BRIEF.md") or "" + out["phases"] = len(re.findall(r"(?m)^#{2,4}[ \t]*Phase[ \t]+\d+", brief)) + for line in brief.split("\n"): + m = re.match(r"(?i)^\s*Approved by\s*:(.*?)(?:Date\s*:.*)?$", line) + if m: + present["approved"] = bool(re.search(r"[A-Za-z0-9]", m.group(1))) + break + + # counted from the case list and the modules' own checks, the way the report does, never from the file's own totals + eq, _ = src.json(path("EQUIVALENCE.json"), "EQUIVALENCE.json") + view = br.equivalence_view(eq) + if view: + tally = view["tally"] + out["eq_cases"] = whole(tally["executed"]) + out["eq_diff"] = whole(sum(tally.get(k, 0) for k in ("differs", "missing", "inconsistent", "unknown"))) + out["eq_appr"] = whole(tally.get("differs-approved", 0)) + + ver, _ = src.json(path("VERIFICATION.json"), "VERIFICATION.json") + proof = br.proof_view(ver) + if proof: + out["v_proven"], out["v_partly"], out["v_not"] = (whole(proof["counts"].get(k)) for k in ("PROVEN", "PARTLY PROVEN", "NOT PROVEN")) + present["signed"] = bool(proof["signoff"]["name"].strip() and proof["signoff"]["decision"].strip()) + + security = br.security_facts(text("SECURITY_FINDINGS.md") or "") or {} + out["sec_crit"], out["sec_high"] = whole(security.get("Critical")), whole(security.get("High")) + + kind, out["built"] = built_kind_and_count(cwd, system) + present["built"] = bool(out["built"]) + for step, bit in STEPS: + done |= bit if present.get(step) else 0 + out["done"] = done + out["goal"] = goal_code(text("INTENT.md"), kind) + out["pv"] = plugin_version() + return out + + +def system_word(words): + """The first plain word of a command's arguments, which is the system's name (a flag's value is not).""" + skip = False + for w in words: + if skip: + skip = False + elif w.startswith("-"): + skip = w == "--source" + elif NAME.fullmatch(w): + return w + return None + + +def command_metrics(prompt, cwd, permission_mode=None): + """The counts for one typed prompt, or None when it is not one of the plugin's commands.""" + m = COMMAND_RE.match(str(prompt or "").lstrip()) + if not m: + return None + verb = m.group("verb") or "" + if m.group("ns"): + cmd = COMMANDS.get(verb, OTHER_COMMAND) + elif verb in PANE: + cmd = PANE[verb] + elif verb in COMMANDS: + cmd = COMMANDS[verb] + else: + return None # another tool's /modernize-something + words = str(prompt).lstrip()[m.end():].split() + systems = systems_in(cwd) + named = system_word(words) + if named in {n for _, n in systems}: + system = named + else: # a name that does not exist yet is a new system; no name at all means the newest one + system = None if named else (systems[0][1] if systems else None) + snap = snapshot(cwd, system) if system else None + perm = PERMISSION_MODES.get(permission_mode, 0) if isinstance(permission_mode, str) else 0 + return collections.OrderedDict([("pv", plugin_version()), ("cmd", cmd), ("perm", perm), ("has_source", int("--source" in words)), + ("fresh", int(snap is None)), ("systems", min(len(systems), 99)), + ("goal", snap["goal"] if snap else 0), ("done", snap["done"] if snap else 0)]) + + +def state_metrics(cwd): + """The counts for the newest system under cwd that the plugin has worked on, or None.""" + for _, system in systems_in(cwd)[:5]: + snap = snapshot(cwd, system) + if snap is not None: + return snap + return None + + +def rounded(value): + """Two significant figures from 100 up (17727 becomes 18000), so a count says roughly how big, not exactly which system.""" + if value < 100: + return value + scale = 10 ** (len(str(value)) - 2) + return (value + scale // 2) // scale * scale + + +def ok(metrics): + """Only keys this script defines, only whole numbers within their limit, counts rounded, at most MAX_KEYS of them.""" + out = collections.OrderedDict() + for k, v in list(metrics.items())[:MAX_KEYS]: + if k in MEANING: + v = min(whole(v), LIMITS.get(k, COUNT_LIMIT)) + out[k] = v if k in EXACT else rounded(v) + return out + + +def data_dir(): + """The plugin's own data folder, or a private folder in the temp directory; None when neither can be used safely.""" + uid = getattr(os, "getuid", lambda: 0)() + base = os.environ.get("CLAUDE_PLUGIN_DATA") or "" + base = os.path.realpath(base) if os.path.isdir(base) else os.path.join(tempfile.gettempdir(), "code-modernization-%s" % uid) + try: + os.makedirs(base, mode=0o700, exist_ok=True) + st = os.lstat(base) + except OSError: + return None + if os.path.islink(base) or not stat.S_ISDIR(st.st_mode) or (hasattr(st, "st_uid") and st.st_uid != uid): + return None + return base + + +def note(text): + """With CODE_MODERNIZATION_TELEMETRY_DEBUG=1, one line saying what a hook run decided, in telemetry-debug.log in the data + folder (a link is never followed, and the file is cut down when it grows past 200 KB). Never raises.""" + if str(os.environ.get("CODE_MODERNIZATION_TELEMETRY_DEBUG", "")).strip().lower() not in TRUE: + return + base = data_dir() + if not base: + return + file = os.path.join(base, "telemetry-debug.log") + try: + if os.path.getsize(file) > 200000: + os.remove(file) + except OSError: + pass + try: + fd = os.open(file, os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), 0o600) + with os.fdopen(fd, "a", encoding="utf-8") as fh: + fh.write("%s %s\n" % (time.strftime("%H:%M:%S"), text)) + except OSError: + pass + + +def remember(key, digest): + """"new" when this workspace's counts changed since they were last sent and the new state is stored, "same" when + they did not, "cannot" when the state cannot be stored: nothing is sent then, it would repeat at the end of every turn.""" + base = data_dir() + if not base: + return "cannot" + try: + file = os.path.join(base, "telemetry-state.json") + try: + with open(file, encoding="utf-8") as fh: + seen = json.load(fh) + except (OSError, ValueError): + seen = {} + seen = seen if isinstance(seen, dict) else {} + if seen.get(key) == digest: + return "same" + seen.pop(key, None) + seen[key] = digest + seen = dict(list(seen.items())[-50:]) + tmp = "%s.%d" % (file, os.getpid()) + with open(tmp, "w", encoding="utf-8") as fh: + json.dump(seen, fh) + os.replace(tmp, file) + return "new" + except OSError: + return "cannot" + + +def digest_of(metrics): + return hashlib.sha1(json.dumps(metrics, sort_keys=True).encode()).hexdigest()[:12] + + +def hook(mode): + """Run one hook. Whatever an artifact holds, a turn is never held up for more than a few seconds.""" + if not hasattr(signal, "SIGALRM"): + return run_hook(mode) + signal.signal(signal.SIGALRM, lambda *_: os._exit(0)) + signal.alarm(3) + try: + run_hook(mode) + finally: + signal.alarm(0) + + +def run_hook(mode): + reason = off_reason() + if reason: + return note("%s: not sent, %s" % (mode, reason)) + try: + data = json.loads(sys.stdin.read(1 << 20) or "{}") + except ValueError: + data = {} + data = data if isinstance(data, dict) else {} + cwd = data.get("cwd") if isinstance(data.get("cwd"), str) and os.path.isdir(data.get("cwd")) else os.getcwd() + why = "" + if mode == "command": + metrics = command_metrics(data.get("prompt"), cwd, data.get("permission_mode")) + why = "not one of the plugin's commands" + else: + metrics = state_metrics(cwd) + why = "the plugin has left no files here" + if metrics is not None: + key = hashlib.sha1(os.path.realpath(cwd).encode()).hexdigest()[:16] + status = remember(key, digest_of(ok(metrics))) + if status != "new": + metrics, why = None, "the counts are the same as last time" if status == "same" else "the state file cannot be written" + if metrics: + print(json.dumps({"metrics": ok(metrics)}, separators=(",", ":")), flush=True) + note("%s: sent %d values" % (mode, len(ok(metrics)))) + else: + note("%s: not sent, %s" % (mode, why)) + + +def show(args): + """What the hooks would send for a workspace, in words.""" + cwd, prompt, as_json, i = None, None, False, 0 + while i < len(args): + if args[i] == "--json": + as_json = True + elif args[i] == "--prompt": + prompt, i = args[i + 1] if i + 1 < len(args) else "", i + 1 + elif not args[i].startswith("--") and cwd is None: + cwd = os.path.abspath(args[i]) + i += 1 + cwd = cwd or os.getcwd() + example = prompt is None + prompt = "/code-modernization:modernize-status" if example else prompt + state, command = state_metrics(cwd), command_metrics(prompt, cwd) + if as_json: + print(json.dumps({"off": off_reason(), "state": ok(state) if state else None, "command": ok(command) if command else None})) + return + + def table(title, metrics, empty): + print(title) + if metrics is None: + print(" " + empty + "\n") + return + for k, v in ok(metrics).items(): + note = MEANING[k].split(":")[0] if k in ("cmd", "lang", "done") else MEANING[k] + if k == "done": + note += ": " + (", ".join(n for n, bit in STEPS if v & bit) or "nothing yet") + print(" %-10s %-8d %s" % (k, v, note)) + print() + + reason = off_reason() + print("Usage counts for %s" % cwd) + print("Sending is OFF: %s.\n" % reason if reason else "Sending is on. Turn it off with CODE_MODERNIZATION_TELEMETRY=0 or the plugin's Usage counts option.\n") + table("When a turn ends and these counts have changed:", state, "nothing: the plugin has left no artifacts here yet") + table("When you type %s%s:" % ("a command, for example " if example else "", prompt.split()[0] if prompt.split() else "nothing"), command, + "nothing: that is not one of the plugin's commands") + + +def main(argv): + mode = argv[1] if len(argv) > 1 else "" + try: + if mode == "show": + show(argv[2:]) + elif mode in ("command", "state"): + hook(mode) + else: + print(__doc__) + except Exception as err: # a usage count must never break the person's session + if mode == "show": + raise + tb = err.__traceback__ + while tb and tb.tb_next: + tb = tb.tb_next + note("%s: error %s at line %s" % (mode, type(err).__name__, tb.tb_lineno if tb else "?")) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/plugins/code-modernization/scripts/telemetry.sh b/plugins/code-modernization/scripts/telemetry.sh new file mode 100644 index 00000000..10f82054 --- /dev/null +++ b/plugins/code-modernization/scripts/telemetry.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# The plugin's two usage-count hooks: telemetry.sh command|state, with the hook's JSON on stdin. +# It starts Python only when the plugin is in use here: a plugin command was typed, or the folder holds files the plugin +# wrote under analysis/. A person who merely has the plugin installed never runs anything, and a Mac without developer +# tools never sees the "install command line tools" dialog that a bare python3 would raise. +# What is counted, and how to turn it off: see the Telemetry section of the README and scripts/telemetry.py. +mode="$1" +input=$(cat) +case "$mode" in + command) printf '%s' "$input" | grep -Eq '"prompt"[[:space:]]*:[[:space:]]*"[[:space:]]*/(code-modernization:)?modernize' || exit 0 ;; + state) + found= + for f in analysis/*/INTENT.md analysis/*/PREFLIGHT.md analysis/*/MODERNIZATION_BRIEF.md analysis/*/BUSINESS_RULES.md \ + analysis/*/DELTA_CATALOG.md analysis/*/VERIFICATION.json analysis/*/RULE_REVIEWS.json analysis/*/AI_NATIVE_SPEC.md; do + [ -f "$f" ] && found=1 && break + done + [ -n "$found" ] || exit 0 ;; + *) exit 0 ;; +esac +py=$(command -v python3) || exit 0 +if [ "$py" = /usr/bin/python3 ] && [ "$(uname)" = Darwin ]; then + xcode-select -p >/dev/null 2>&1 || exit 0 +fi +# never leave bytecode behind in the plugin's own folder +printf '%s' "$input" | PYTHONDONTWRITEBYTECODE=1 "$py" "$(dirname "$0")/telemetry.py" "$mode" +exit 0 diff --git a/plugins/code-modernization/scripts/tests/test_telemetry.py b/plugins/code-modernization/scripts/tests/test_telemetry.py new file mode 100644 index 00000000..75c1d063 --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_telemetry.py @@ -0,0 +1,600 @@ +"""Tests for the usage counts (scripts/telemetry.py, scripts/telemetry.sh and the hooks that call them). + +Run: python3 -m unittest discover -s plugins/code-modernization/scripts/tests +""" +import contextlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +PLUGIN = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, os.path.join(PLUGIN, "scripts")) +import telemetry as tm # noqa: E402 + +RULES = """# Business rules + +### RULE-001 · Interest posting +**Priority:** P0 +**Confidence:** High +**Source:** a.cbl:10-20 + +Given a balance, when the month closes, then interest is posted. + +### RULE-002 · Rounding +**Priority:** P1 +**Source:** a.cbl:30-31 + +Given an amount, then it is truncated. + +### RULE-003 · Odd limit +**Priority:** P0 +**Suspected defect:** the limit is off by one +**Source:** b.java:5-6 + +Given a limit, then it applies. +""" +BRIEF = """# Brief + +#### Phase 1: pilot +#### Phase 2: the rest + +## 8. Approval Block + +``` +Approved by: Jane Doe Date: 2026-09-24 +Approval covers: Phase 1 only +``` +""" +UNSIGNED = "## 8. Approval Block\n\n```\nApproved by: ________________ Date: __________\n```\n" +SECURITY = "# Security\n\n| Severity | Count |\n|---|---|\n| Critical | 2 |\n| High | 5 |\n| Medium | 9 |\n" +TOPOLOGY = {"root": {"kind": "root", "children": [ + {"kind": "module", "file": "a.cbl", "loc": 3000, "language": "cobol"}, + {"kind": "module", "file": "b.java", "loc": 1200, "language": "java"}, + {"kind": "module", "file": "Makefile", "loc": 5000, "language": "make"}]}, "edges": []} +CHECKS = ("tests", "rules", "same", "fresh", "canary", "source") + + +def module(name, **states): + checks = [{"id": c, "state": states.get(c, "pass"), "detail": "x"} for c in CHECKS] + return {"name": name, "track": "rewrite", "checks": checks, "evidence": { + "tests": {"executed": 5, "failed": 0, "skipped": 0}, "fresh": {"inputs": 12, "executed": 12, "same": 12, "differs": 0, "missing": 0}}} + + +VERIFICATION = {"modules": [module("a"), module("b", canary="gap"), module("c", canary="gap"), module("d", tests="fail"), module("e", same="fail"), + module("f", source="fail")], + "signoff": {"name": "", "role": "", "date": "", "decision": ""}} +CASES = [{"id": "s%d" % i, "verdict": "same"} for i in range(9)] + [{"id": "d1", "verdict": "differs"}, {"id": "m1", "verdict": "missing"}] + [ + {"id": "a%d" % i, "verdict": "differs-approved", "approvedDifference": "the owner accepted it"} for i in range(2)] +EQUIVALENCE = {"cases": CASES, "selfCheck": {"passed": True}} +REVIEWS = {"system": "sys", "version": 1, "reviews": {"RULE-001": {"verdict": "confirmed"}, "RULE-002": {"verdict": "wrong"}, + "RULE-003": {"verdict": "discuss"}}} +STEP_BITS = dict(tm.STEPS) + + +def put(root, rel, data): + path = os.path.join(root, *rel.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write(data if isinstance(data, str) else json.dumps(data)) + return path + + +def workspace(root, system="sys", parts=None): + parts = parts or {} + files = {"PREFLIGHT.md": "# Preflight\n", "ASSESSMENT.md": "# Assessment\n", "topology.json": TOPOLOGY, "BUSINESS_RULES.md": RULES, + "RULE_REVIEWS.json": REVIEWS, "MODERNIZATION_BRIEF.md": BRIEF, "EQUIVALENCE.json": EQUIVALENCE, "VERIFICATION.json": VERIFICATION, + "SECURITY_FINDINGS.md": SECURITY, "REPORT.html": "<html></html>"} + files.update(parts) + for name, data in files.items(): + if data is not None: + put(root, "analysis/%s/%s" % (system, name), data) + put(root, "modernized/%s/mod-a/x.txt" % system, "x") + put(root, "modernized/%s/mod-b/x.txt" % system, "x") + return root + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.data = os.path.join(self.tmp, "data") + os.makedirs(self.data) + clean = {k: v for k, v in os.environ.items() if k not in ("CODE_MODERNIZATION_TELEMETRY", "CLAUDE_PLUGIN_OPTION_TELEMETRY", "DISABLE_TELEMETRY", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "CLAUDE_PLUGIN_DATA")} + patcher = mock.patch.dict(os.environ, {**clean, "CLAUDE_PLUGIN_DATA": self.data}, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + self.ws = workspace(os.path.join(self.tmp, "ws")) + + def hook(self, mode, payload): + out = io.StringIO() + with mock.patch.object(sys, "stdin", io.StringIO(json.dumps(payload))), contextlib.redirect_stdout(out): + tm.hook(mode) + return out.getvalue() + + +class Counts(Base): + def test_the_full_workspace_is_counted_the_way_the_artifacts_say(self): + s = tm.state_metrics(self.ws) + self.assertEqual({k: s[k] for k in ("rules", "p0", "rev_ok", "rev_wrong", "phases", "built", "eq_cases", "eq_diff", "eq_appr", + "v_proven", "v_partly", "v_not", "sec_crit", "sec_high", "map_kloc", "lang", "goal")}, + dict(rules=3, p0=2, rev_ok=1, rev_wrong=1, phases=2, built=2, eq_cases=12, eq_diff=2, eq_appr=2, v_proven=1, + v_partly=2, v_not=3, sec_crit=2, sec_high=5, map_kloc=9, lang=1, goal=3)) + steps = ("preflight", "assess", "map", "rules", "reviewed", "brief", "approved", "built", "verified", "hardened", "report") + self.assertEqual(s["done"], sum(STEP_BITS[n] for n in steps)) + + def test_a_signed_proof_and_an_unsigned_brief(self): + put(self.ws, "analysis/sys/VERIFICATION.json", dict(VERIFICATION, signoff={"name": "A. Person", "decision": "accepted"})) + put(self.ws, "analysis/sys/MODERNIZATION_BRIEF.md", UNSIGNED) + done = tm.state_metrics(self.ws)["done"] + self.assertTrue(done & STEP_BITS["signed"]) + self.assertFalse(done & STEP_BITS["approved"]) + self.assertTrue(done & STEP_BITS["brief"]) + + def test_nothing_is_reported_where_the_plugin_has_left_nothing(self): + empty = os.path.join(self.tmp, "empty") + put(empty, "analysis/other/data.csv", "a,b\n1,2\n") + self.assertIsNone(tm.state_metrics(empty)) + self.assertIsNone(tm.state_metrics(os.path.join(self.tmp, "nowhere"))) + self.assertEqual(self.hook("state", {"cwd": empty}), "") + + def test_the_language_is_the_biggest_one_that_is_code(self): + def lang(rows): + return tm.language_code({"root": {"children": [{"kind": "module", "file": "f", "loc": n, "language": name} for name, n in rows]}}) + self.assertEqual(lang([("artifact", 9000), ("c", 2900), ("cpp", 650), ("make", 500)]), 7) + self.assertEqual(lang([("C#", 10), ("Java", 5)]), 3) + self.assertEqual(lang([("javascript", 10), ("java", 50)]), 2) + self.assertEqual(lang([("make", 10), ("yaml", 5)]), 0) + self.assertEqual(lang([("PL/I", 90000), ("JCL", 500)]), 99) + self.assertEqual(lang([("C/C++", 10), ("make", 900)]), 7) + self.assertEqual(lang([("Node.js", 10)]), 9) + self.assertEqual(lang([("ASP.NET", 10), ("VB6", 20)]), 3) + self.assertEqual(lang([("Java/JSP", 10)]), 2) + self.assertEqual(lang([("Fortran", 10), ("Assembler", 5)]), 15) + self.assertEqual(lang([("some new language", 10)]), 99) + self.assertEqual(lang([]), 0) + self.assertEqual(tm.language_code(None), 0) + + def test_the_goal_is_the_answer_after_the_word_goal_and_nothing_else(self): + cases = [("- Goal: reimagine (rebuild it from scratch)", 4), ("## Goal\n- **Goal:** `uplift`. Then transform it.", 2), + ("## Goal\n**Transform** piece by piece", 3), ("- Goal: Understand it first", 1), + ("## Goal\n- **Goal:** `not-sure`. Run assess, then pick (uplift / transform / reimagine / understand).", 0), + ("- Goal: Move to a newer version of the same technology", 2), ("- Goal: Rewrite it in a different technology", 3), + ("nothing here about it, but uplift is a word", 0), ("", 0)] + for text, want in cases: + self.assertEqual(tm.goal_code(text, None), want, text) + self.assertEqual(tm.goal_code("", ""), 3) + self.assertEqual(tm.goal_code("", "-uplifted"), 2) + self.assertEqual(tm.goal_code("- Goal: not sure", "-reimagined"), 4) + + def test_uplift_and_reimagine_leave_their_own_marks(self): + ws = os.path.join(self.tmp, "up") + put(ws, "analysis/sys/DELTA_CATALOG.md", "# Deltas\n") + put(ws, "analysis/sys/BASELINE.md", "# Baseline\n") + put(ws, "analysis/sys/PLAYBOOK.md", "# Playbook\n") + put(ws, "modernized/sys-uplifted/pom.xml", "<x/>") + put(ws, "modernized/sys-uplifted/mod/a.java", "x") + s = tm.state_metrics(ws) + self.assertEqual((s["goal"], s["built"]), (2, 1)) + self.assertEqual(s["done"], STEP_BITS["deltas"] + STEP_BITS["baseline"] + STEP_BITS["playbook"] + STEP_BITS["built"]) + + def test_hostile_artifacts_give_whole_numbers_and_nothing_else(self): + put(self.ws, "analysis/sys/VERIFICATION.json", {"modules": "x", "signoff": ["not", "a", "dict"]}) + put(self.ws, "analysis/sys/EQUIVALENCE.json", {"cases": [{"verdict": ["same"]}, 5, None, {"verdict": "same", "approvedDifference": {"a": 1}}]}) + put(self.ws, "analysis/sys/RULE_REVIEWS.json", {"reviews": {"RULE-001": "confirmed", "RULE-002": {"verdict": ["wrong"]}}}) + put(self.ws, "analysis/sys/topology.json", "{not json") + s = tm.state_metrics(self.ws) + self.assertEqual((s["v_proven"], s["v_partly"], s["v_not"]), (0, 0, 0)) + self.assertEqual((s["rev_ok"], s["rev_wrong"], s["map_kloc"], s["lang"]), (0, 0, 0, 0)) + self.assertTrue(all(type(v) is int and 0 <= v <= tm.COUNT_LIMIT for v in tm.ok(s).values())) + + def test_the_counts_come_from_the_case_list_and_the_modules_checks_not_from_the_files_own_totals(self): + put(self.ws, "analysis/sys/EQUIVALENCE.json", {"cases": [{"id": "1", "verdict": "differs"}, {"id": "2", "verdict": "same"}, {"id": "3", "verdict": "differs"}], + "totals": {"executed": 100, "differs": 0, "differsApproved": 0, "missing": 0}}) + put(self.ws, "analysis/sys/VERIFICATION.json", {"modules": [module("a", tests="fail")], "overall": {"counts": {"PROVEN": 5, "PARTLY PROVEN": 0, "NOT PROVEN": 0}}}) + s = tm.state_metrics(self.ws) + self.assertEqual((s["eq_cases"], s["eq_diff"], s["eq_appr"]), (3, 2, 0)) + self.assertEqual((s["v_proven"], s["v_partly"], s["v_not"]), (0, 0, 1)) + + def test_a_linked_artifact_is_not_read(self): + outside = os.path.join(self.tmp, "outside.md") + with open(outside, "w") as fh: + fh.write(RULES) + os.remove(os.path.join(self.ws, "analysis", "sys", "BUSINESS_RULES.md")) + try: + os.symlink(outside, os.path.join(self.ws, "analysis", "sys", "BUSINESS_RULES.md")) + except OSError: + self.skipTest("no symbolic links here") + s = tm.state_metrics(self.ws) + self.assertEqual((s["rules"], s["done"] & STEP_BITS["rules"]), (0, 0)) + + def test_the_newest_system_is_the_one_counted(self): + workspace(self.ws, "old", {"BUSINESS_RULES.md": "### RULE-001 · One\n**Priority:** P0\n"}) + for f in os.scandir(os.path.join(self.ws, "analysis", "old")): + os.utime(f.path, (1, 1)) + os.utime(os.path.join(self.ws, "analysis", "old"), (1, 1)) + self.assertEqual(tm.state_metrics(self.ws)["rules"], 3) + put(self.ws, "analysis/old/NEW.md", "x") + self.assertEqual(tm.state_metrics(self.ws)["rules"], 1) + + +class Commands(Base): + def cmd(self, prompt): + return tm.command_metrics(prompt, self.ws) + + def test_the_plugins_commands_have_a_number_each(self): + for verb, n in tm.COMMANDS.items(): + prompt = "/code-modernization:modernize" + ("-" + verb if verb else "") + self.assertEqual(self.cmd(prompt + " sys")["cmd"], n, prompt) + self.assertEqual(self.cmd("/modernize")["cmd"], 1) + self.assertEqual(self.cmd(" /code-modernization:modernize-verify")["cmd"], 11) + self.assertEqual(self.cmd("/code-modernization:modernize-harden-scan x")["cmd"], 99) + self.assertEqual([self.cmd("/modernize-" + v)["cmd"] for v in ("panel", "review-pane", "sign")], [20, 21, 22]) + self.assertEqual(self.cmd("/code-modernization:modernize-review")["cmd"], 6) + self.assertEqual(self.cmd("/modernize-review")["cmd"], 6) # the bare name is the plugin's command now that the pane's deck has its own + + def test_other_prompts_are_not_counted(self): + for prompt in ("", None, "modernize this", "/modernizer", "/other:modernize", "please /modernize", "/code-modernization:assess", 5, {"a": 1}): + self.assertIsNone(self.cmd(prompt), prompt) + + def test_the_command_says_where_the_system_stands_and_whether_source_was_given(self): + s = self.cmd("/code-modernization:modernize-verify sys --source /work/x") + self.assertEqual((s["has_source"], s["fresh"], s["systems"], s["goal"]), (1, 0, 1, 3)) + self.assertEqual(s["done"], tm.state_metrics(self.ws)["done"]) + new = tm.command_metrics("/code-modernization:modernize billing --source /a", os.path.join(self.tmp, "fresh-folder")) + self.assertEqual((new["fresh"], new["systems"], new["done"], new["has_source"]), (1, 0, 0, 1)) + + def test_the_permission_mode_is_a_number_from_a_fixed_list(self): + for mode, want in (("default", 1), ("auto", 4), ("bypassPermissions", 5), ("something new", 0), (None, 0), (7, 0)): + self.assertEqual(tm.command_metrics("/modernize", self.ws, mode)["perm"], want, mode) + out = self.hook("command", {"cwd": self.ws, "prompt": "/modernize", "permission_mode": "plan"}) + self.assertEqual(json.loads(out)["metrics"]["perm"], 3) + + def test_a_named_system_is_the_one_counted_and_its_name_is_never_sent(self): + workspace(self.ws, "other", {"BUSINESS_RULES.md": None, "EQUIVALENCE.json": None, "VERIFICATION.json": None}) + os.utime(os.path.join(self.ws, "analysis", "sys"), (1, 1)) + for f in os.scandir(os.path.join(self.ws, "analysis", "sys")): + os.utime(f.path, (1, 1)) + named = self.cmd("/code-modernization:modernize-status sys") + newest = self.cmd("/code-modernization:modernize-status") + self.assertNotEqual(named["done"], newest["done"]) + self.assertEqual(named["systems"], 2) + for value in named.values(): + self.assertIsInstance(value, int) + + +class Sending(Base): + def test_every_key_is_defined_and_every_value_is_a_whole_number(self): + self.assertLessEqual(len(tm.STATE_KEYS), tm.MAX_KEYS) + self.assertLessEqual(len(tm.COMMAND_KEYS), tm.MAX_KEYS) + self.assertEqual(list(tm.MEANING)[0], "pv") + for keys in (tm.STATE_KEYS, tm.COMMAND_KEYS): + self.assertEqual(keys[0], "pv") + for k in keys: + self.assertRegex(k, r"^[a-z][a-z0-9_]{0,39}$") + self.assertIn(k, tm.MEANING) + for out in (self.hook("state", {"cwd": self.ws}), self.hook("command", {"cwd": self.ws, "prompt": "/code-modernization:modernize-map"})): + line = json.loads(out) + self.assertEqual(list(line), ["metrics"]) + self.assertTrue(all(type(v) is int and 0 <= v <= tm.CAP for v in line["metrics"].values()), line) + self.assertEqual(out.count("\n"), 1) + + def test_a_key_that_is_not_defined_never_goes_out(self): + got = tm.ok({"pv": 1, "path": "/secret", "rules": "7", "p0": True, "goal": 2.9, "done": -3}) + self.assertEqual(dict(got), {"pv": 1, "rules": 7, "p0": 1, "goal": 2, "done": 0}) + + def test_the_plugin_version_is_sent_and_matches_the_manifest(self): + with open(os.path.join(PLUGIN, ".claude-plugin", "plugin.json")) as fh: + major, minor, patch = (int(x) for x in json.load(fh)["version"].split(".")) + self.assertEqual(tm.plugin_version(), major * 10000 + minor * 100 + patch) + self.assertGreater(tm.plugin_version(), 0) + self.assertEqual(json.loads(self.hook("state", {"cwd": self.ws}))["metrics"]["pv"], tm.plugin_version()) + + def test_the_same_counts_are_sent_once_and_a_change_is_sent_again(self): + self.assertTrue(self.hook("state", {"cwd": self.ws})) + self.assertEqual(self.hook("state", {"cwd": self.ws}), "") + put(self.ws, "analysis/sys/RULE_REVIEWS.json", {"reviews": {"RULE-001": {"verdict": "wrong"}}}) + self.assertIn('"rev_wrong":1', self.hook("state", {"cwd": self.ws})) + self.assertEqual(self.hook("state", {"cwd": self.ws}), "") + self.assertTrue(self.hook("command", {"cwd": self.ws, "prompt": "/modernize"})) + self.assertTrue(self.hook("command", {"cwd": self.ws, "prompt": "/modernize"})) + + def test_when_it_cannot_remember_it_sends_nothing_rather_than_repeat_every_turn(self): + os.environ["CLAUDE_PLUGIN_DATA"] = os.path.join(self.tmp, "does-not-exist") + blocked = os.path.join(self.tmp, "blocked") + with mock.patch.object(tm.tempfile, "gettempdir", return_value=blocked), mock.patch.object(tm.os, "makedirs", side_effect=OSError("read-only")): + self.assertEqual(self.hook("state", {"cwd": self.ws}), "") + + def test_the_debug_switch_says_why_each_hook_run_sent_nothing_in_the_plugins_data_folder(self): + log = os.path.join(self.data, "telemetry-debug.log") + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY_DEBUG": "1"}): + self.hook("state", {"cwd": self.ws}) + self.hook("state", {"cwd": self.ws}) + self.hook("state", {"cwd": os.path.join(self.tmp, "nowhere")}) + self.hook("command", {"cwd": self.ws, "prompt": "hello"}) + self.hook("command", {"cwd": self.ws, "prompt": "/modernize"}) + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY": "0"}): + self.hook("state", {"cwd": self.ws}) + with mock.patch.object(tm, "state_metrics", side_effect=KeyError("x")), mock.patch.object(sys, "stdin", io.StringIO("{}")): + tm.main(["telemetry.py", "state"]) + with open(log, encoding="utf-8") as fh: + text = fh.read() + for want in ("state: sent 19 values", "state: not sent, the counts are the same as last time", "state: not sent, the plugin has left no files here", + "command: not sent, not one of the plugin's commands", "command: sent 8 values", "state: not sent, CODE_MODERNIZATION_TELEMETRY is off", + "state: error KeyError at line"): + self.assertIn(want, text) + self.assertNotIn(self.tmp, text) + + def test_the_debug_switch_never_writes_anywhere_else_and_never_follows_a_link(self): + victim = os.path.join(self.tmp, "victim.txt") + with open(victim, "w") as fh: + fh.write("keep") + try: + os.symlink(victim, os.path.join(self.data, "telemetry-debug.log")) + except OSError: + self.skipTest("no symbolic links here") + elsewhere = os.path.join(self.tmp, "somewhere-else.log") + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY_DEBUG": elsewhere}): + self.hook("state", {"cwd": self.ws}) + self.assertFalse(os.path.exists(elsewhere)) # a path in the variable is not a switch + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY_DEBUG": "1"}): + self.hook("command", {"cwd": self.ws, "prompt": "/modernize"}) + with open(victim) as fh: + self.assertEqual(fh.read(), "keep") + + def test_each_off_switch_stops_everything(self): + for name, value in (("CODE_MODERNIZATION_TELEMETRY", "0"), ("CODE_MODERNIZATION_TELEMETRY", "Off"), ("CLAUDE_PLUGIN_OPTION_TELEMETRY", "false"), + ("CODE_MODERNIZATION_TELEMETRY", "disabled"), ("CODE_MODERNIZATION_TELEMETRY", "n"), ("CODE_MODERNIZATION_TELEMETRY", "none"), + ("CODE_MODERNIZATION_TELEMETRY", "2"), ("CLAUDE_PLUGIN_OPTION_TELEMETRY", "no"), + ("DISABLE_TELEMETRY", "1"), ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "true")): + with mock.patch.dict(os.environ, {name: value}): + self.assertTrue(tm.off_reason(), name) + self.assertEqual(self.hook("state", {"cwd": self.ws}), "", name) + self.assertEqual(self.hook("command", {"cwd": self.ws, "prompt": "/modernize"}), "", name) + for name, value in (("CODE_MODERNIZATION_TELEMETRY", "1"), ("CODE_MODERNIZATION_TELEMETRY", ""), ("CLAUDE_PLUGIN_OPTION_TELEMETRY", "true"), + ("CLAUDE_PLUGIN_OPTION_TELEMETRY", " TRUE "), ("DISABLE_TELEMETRY", "0")): + with mock.patch.dict(os.environ, {name: value}): + self.assertEqual(tm.off_reason(), "", name) + + def test_bad_hook_input_never_raises_and_never_prints(self): + for raw in ("", "not json", "[1,2]", '{"cwd": 5, "prompt": ["x"]}', '{"cwd": "/no/such/dir"}'): + out = io.StringIO() + with mock.patch.object(sys, "stdin", io.StringIO(raw)), contextlib.redirect_stdout(out), mock.patch.object(tm.os, "getcwd", return_value=self.tmp): + self.assertEqual(tm.main(["telemetry.py", "command"]), 0) + self.assertEqual(tm.main(["telemetry.py", "state"]), 0) + self.assertEqual(out.getvalue(), "", raw) + + def test_show_prints_what_would_be_sent_in_words_and_as_json(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + tm.show([self.ws, "--prompt", "/code-modernization:modernize-verify sys"]) + text = out.getvalue() + for word in ("Sending is on", "rules", "business rules found", "steps that have left their file", "preflight, assess, map, rules", "modernize-verify"): + self.assertIn(word, text) + out = io.StringIO() + with contextlib.redirect_stdout(out), mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY": "0"}): + tm.show([self.ws, "--json"]) + got = json.loads(out.getvalue()) + self.assertEqual(got["off"], "CODE_MODERNIZATION_TELEMETRY is off") + self.assertEqual(got["state"]["rules"], 3) + + +class Hardening(Base): + """What a hostile or odd workspace must not be able to do.""" + + def test_counts_from_a_hundred_up_are_rounded_and_every_key_has_a_ceiling(self): + got = tm.ok({"pv": 10000, "rules": 97, "p0": 26, "map_kloc": 344, "eq_cases": 17727, "sec_high": 10 ** 12, "done": 43247, "goal": 9, "perm": 99, + "phases": 5000, "systems": 500}) + self.assertEqual(dict(got), {"pv": 10000, "rules": 97, "p0": 26, "map_kloc": 340, "eq_cases": 18000, "sec_high": tm.COUNT_LIMIT, "done": 43247, + "goal": 4, "perm": 6, "phases": 99, "systems": 99}) + self.assertEqual([tm.rounded(n) for n in (99, 100, 104, 105, 999, 1049, 1050, 17727)], [99, 100, 100, 110, 1000, 1000, 1100, 18000]) + + def test_a_folder_of_another_tool_is_not_the_plugins_even_with_the_same_file_names(self): + other = os.path.join(self.tmp, "other") + put(other, "analysis/2024-q3/topology.json", TOPOLOGY) + put(other, "analysis/2024-q3/BASELINE.md", "# baseline\n") + put(other, "analysis/2024-q3/ASSESSMENT.md", "# assessment\n") + self.assertIsNone(tm.state_metrics(other)) + put(other, "analysis/2024-q3/PREFLIGHT.md", "# the plugin's\n") + self.assertIsNotNone(tm.state_metrics(other)) + + def test_another_tools_commands_are_not_counted_and_the_newest_folder_need_not_be_the_plugins(self): + self.assertIsNone(tm.command_metrics("/modernize-schema", self.ws)) + self.assertEqual(tm.command_metrics("/code-modernization:modernize-schema", self.ws)["cmd"], 99) + put(self.ws, "analysis/zzz-data/results.csv", "a,b\n") + self.assertEqual(tm.state_metrics(self.ws)["rules"], 3) + + def test_a_new_name_is_a_new_system_and_a_flags_value_is_not_a_name(self): + new = tm.command_metrics("/code-modernization:modernize-preflight billing --source /x", self.ws) + self.assertEqual((new["fresh"], new["done"], new["goal"], new["has_source"]), (1, 0, 0, 1)) + newest = tm.command_metrics("/modernize --source elsewhere", self.ws) + self.assertEqual((newest["fresh"], newest["has_source"]), (0, 1)) + self.assertEqual(tm.system_word(["--source", "abc", "def"]), "def") + self.assertIsNone(tm.system_word(["--source", "abc", "/work/x"])) + + def test_links_that_lead_outside_the_workspace_are_not_followed(self): + outside = os.path.join(self.tmp, "outside") + for i in range(7): + put(outside, "d%d/x.txt" % i, "x") + shutil.rmtree(os.path.join(self.ws, "modernized", "sys")) + try: + os.symlink(outside, os.path.join(self.ws, "modernized", "sys")) + except OSError: + self.skipTest("no symbolic links here") + self.assertEqual(tm.state_metrics(self.ws)["built"], 0) + elsewhere = os.path.join(self.tmp, "elsewhere") + workspace(elsewhere, "real") + linked = os.path.join(self.tmp, "linked") + os.makedirs(linked) + os.symlink(os.path.join(elsewhere, "analysis"), os.path.join(linked, "analysis")) + self.assertEqual(tm.systems_in(linked), []) + self.assertIsNone(tm.state_metrics(linked)) + + def test_a_dangling_link_inside_a_system_does_not_drop_the_system(self): + try: + os.symlink(os.path.join(self.tmp, "gone"), os.path.join(self.ws, "analysis", "sys", "dangling")) + except OSError: + self.skipTest("no symbolic links here") + self.assertEqual(tm.state_metrics(self.ws)["rules"], 3) + + def test_a_data_folder_that_is_itself_a_link_still_works(self): + real = os.path.join(self.tmp, "real-data") + os.makedirs(real) + link = os.path.join(self.tmp, "data-link") + try: + os.symlink(real, link) + except OSError: + self.skipTest("no symbolic links here") + with mock.patch.dict(os.environ, {"CLAUDE_PLUGIN_DATA": link}): + self.assertTrue(self.hook("state", {"cwd": self.ws})) + self.assertTrue(os.path.exists(os.path.join(real, "telemetry-state.json"))) + + def test_an_artifact_built_to_make_a_pattern_slow_does_not_hold_anything_up(self): + nasty = "### RULE-001 - t" + " " * 4000 + "x\n**Priority:** P0" + " " * 4000 + "x\n" + put(self.ws, "analysis/sys/BUSINESS_RULES.md", nasty * 3) + put(self.ws, "analysis/sys/SECURITY_FINDINGS.md", "| a |" + " " * 8000 + "x|\n|" + "-" * 5000 + "|\n") + started = time.time() + s = tm.state_metrics(self.ws) + self.assertLess(time.time() - started, 3) + self.assertGreaterEqual(s["rules"], 1) + + def test_whatever_happens_the_hook_gives_up_within_a_few_seconds_and_says_nothing(self): + code = ("import sys, time; sys.path.insert(0, %r); import telemetry as tm; tm.state_metrics = lambda cwd: time.sleep(30); tm.hook('state')" % + os.path.join(PLUGIN, "scripts")) + started = time.time() + done = subprocess.run([sys.executable, "-c", code], input=json.dumps({"cwd": self.ws}), capture_output=True, text=True, timeout=20, + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}) + self.assertLess(time.time() - started, 10) + self.assertEqual((done.returncode, done.stdout), (0, "")) + + def test_the_alarm_is_cancelled_when_the_hook_returns(self): + import signal + self.hook("state", {"cwd": self.ws}) + if hasattr(signal, "alarm"): + self.assertEqual(signal.alarm(0), 0) + + +class Shell(unittest.TestCase): + """scripts/telemetry.sh must start Python only when the plugin is in use.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.bin = os.path.join(self.tmp, "bin") + os.makedirs(self.bin) + self.ws = workspace(os.path.join(self.tmp, "ws")) + self.data = os.path.join(self.tmp, "data") + os.makedirs(self.data) + os.symlink(sys.executable, os.path.join(self.bin, "python3")) + + def run_hook(self, mode, payload, cwd=None, path=None, env=None): + env = {"PATH": path if path is not None else self.bin + os.pathsep + "/usr/bin:/bin", "CLAUDE_PLUGIN_DATA": self.data, **(env or {})} + done = subprocess.run(["/bin/sh", os.path.join(PLUGIN, "scripts", "telemetry.sh"), mode], input=json.dumps(payload), capture_output=True, text=True, + cwd=cwd or self.ws, env=env, timeout=60) + self.assertEqual(done.returncode, 0, done.stderr) + return done.stdout + + def test_a_plugin_command_is_counted_and_the_end_of_a_turn_in_a_workspace_is_counted(self): + out = self.run_hook("command", {"cwd": self.ws, "prompt": "/code-modernization:modernize-status sys"}) + self.assertEqual(json.loads(out)["metrics"]["cmd"], 13) + self.assertEqual(json.loads(self.run_hook("state", {"cwd": self.ws}))["metrics"]["rules"], 3) + self.assertEqual(self.run_hook("state", {"cwd": self.ws}), "") + + def test_it_starts_nothing_when_the_plugin_is_not_in_use(self): + no_python = os.path.join(self.tmp, "nopy") + os.makedirs(no_python) + for tool in ("grep", "dirname", "uname", "cat"): + os.symlink(shutil.which(tool), os.path.join(no_python, tool)) + elsewhere = os.path.join(self.tmp, "elsewhere") + os.makedirs(elsewhere) + self.assertEqual(self.run_hook("command", {"prompt": "write me a poem"}), "") + self.assertEqual(self.run_hook("command", {"prompt": "/commit"}), "") + self.assertEqual(self.run_hook("state", {"cwd": elsewhere}, cwd=elsewhere), "") + self.assertEqual(self.run_hook("nonsense", {}), "") + # no python at all: still quiet, still exit 0 + self.assertEqual(self.run_hook("state", {"cwd": self.ws}, path=no_python), "") + self.assertEqual(self.run_hook("command", {"prompt": "/modernize"}, path=no_python), "") + + def test_python_starts_only_where_the_plugin_has_left_its_files(self): + marker = os.path.join(self.tmp, "started") + fake = os.path.join(self.tmp, "fakebin") + os.makedirs(fake) + with open(os.path.join(fake, "python3"), "w") as fh: + fh.write("#!/bin/sh\ntouch %s\ncat >/dev/null\n" % marker) + os.chmod(os.path.join(fake, "python3"), 0o755) + path = fake + os.pathsep + "/usr/bin:/bin" + other = os.path.join(self.tmp, "other") + put(other, "analysis/results/data.csv", "a,b\n") + self.run_hook("state", {"cwd": other}, cwd=other, path=path) + self.assertFalse(os.path.exists(marker)) + put(other, "analysis/results/PREFLIGHT.md", "# x\n") + self.run_hook("state", {"cwd": other}, cwd=other, path=path) + self.assertTrue(os.path.exists(marker)) + + def test_it_leaves_no_bytecode_in_the_plugins_folder(self): + root = os.path.join(self.tmp, "plugin") + for rel in ("scripts/telemetry.sh", "scripts/telemetry.py", "scripts/build_report.py", ".claude-plugin/plugin.json"): + os.makedirs(os.path.dirname(os.path.join(root, rel)), exist_ok=True) + shutil.copy(os.path.join(PLUGIN, rel), os.path.join(root, rel)) + done = subprocess.run(["/bin/sh", os.path.join(root, "scripts", "telemetry.sh"), "state"], input=json.dumps({"cwd": self.ws}), capture_output=True, + text=True, cwd=self.ws, env={"PATH": self.bin + os.pathsep + "/usr/bin:/bin", "CLAUDE_PLUGIN_DATA": self.data}, timeout=60) + self.assertIn('"metrics"', done.stdout) + self.assertEqual(sorted(os.listdir(os.path.join(root, "scripts"))), ["build_report.py", "telemetry.py", "telemetry.sh"]) + + def test_the_off_switch_reaches_the_script(self): + self.assertEqual(self.run_hook("state", {"cwd": self.ws}, env={"CODE_MODERNIZATION_TELEMETRY": "0"}), "") + + +class Shipped(unittest.TestCase): + """What ships must agree with itself: the manifest, the hooks, the README and the changelog.""" + + def read(self, *parts): + with open(os.path.join(PLUGIN, *parts), encoding="utf-8") as fh: + return fh.read() + + def test_the_hooks_call_scripts_that_exist_and_are_asynchronous(self): + hooks = json.loads(self.read("hooks", "hooks.json"))["hooks"] + self.assertEqual(sorted(hooks), ["Stop", "UserPromptSubmit"]) + for event, groups in hooks.items(): + for group in groups: + for h in group["hooks"]: + self.assertTrue(h["asyncRewake"]) + script = re.search(r"\$\{CLAUDE_PLUGIN_ROOT\}/(scripts/\w+\.sh)", h["command"]).group(1) + self.assertTrue(os.path.isfile(os.path.join(PLUGIN, script)), script) + self.assertTrue(h["command"].rstrip().endswith("command" if event == "UserPromptSubmit" else "state")) + + def test_the_manifest_has_a_version_and_the_option_that_turns_counts_off(self): + manifest = json.loads(self.read(".claude-plugin", "plugin.json")) + self.assertRegex(manifest["version"], r"^\d+\.\d+\.\d+$") + option = manifest["userConfig"]["telemetry"] + self.assertEqual((option["type"], option["default"]), ("boolean", True)) + with open(os.path.join(PLUGIN, "..", "..", ".claude-plugin", "marketplace.json"), encoding="utf-8") as fh: + entry = next(p for p in json.load(fh)["plugins"] if p["name"] == "code-modernization") + self.assertNotIn("version", entry) # the manifest is the one place the number lives + + def test_the_changelog_names_the_manifest_version_first(self): + version = json.loads(self.read(".claude-plugin", "plugin.json"))["version"] + first = re.search(r"(?m)^## \[?(\d+\.\d+\.\d+)", self.read("CHANGELOG.md")) + self.assertEqual(first.group(1), version) + + def test_the_readme_lists_every_key_that_can_be_sent_and_the_off_switches(self): + readme = self.read("README.md") + section = readme[readme.index("## Telemetry"):] + section = section[:section.index("\n## ", 5)] if "\n## " in section[5:] else section + for key in tm.MEANING: + self.assertIn("`%s`" % key, section, key) + for word in ("CODE_MODERNIZATION_TELEMETRY", "Usage counts", "DISABLE_TELEMETRY", "telemetry.py show", "two significant figures", "TELEMETRY_DEBUG"): + self.assertIn(word, section) + + +if __name__ == "__main__": + unittest.main() |
