@morning-start/dsh-code-toolkit 0.0.0-stage → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +375 -0
  2. package/LICENSE +35 -0
  3. package/README.md +252 -2
  4. package/agents/caption/AGENT.md +165 -0
  5. package/agents/caption/examples/dispatch.md +83 -0
  6. package/agents/caption/examples/loop.md +66 -0
  7. package/agents/caption/examples/theater.md +40 -0
  8. package/agents/caption/references/dispatch.md +128 -0
  9. package/agents/caption/references/evidence.md +82 -0
  10. package/agents/caption/references/experts.md +141 -0
  11. package/agents/caption/references/flows.md +97 -0
  12. package/agents/caption/references/loop.md +75 -0
  13. package/agents/pua/AGENT.md +66 -0
  14. package/agents/pua/examples/run.md +41 -0
  15. package/agents/pua/references/flavors.md +33 -0
  16. package/agents/pua/references/methodology.md +32 -0
  17. package/agents/review/AGENT.md +112 -0
  18. package/agents/review/examples/clean.md +40 -0
  19. package/agents/review/examples/findings.md +49 -0
  20. package/agents/review/references/evidence.md +33 -0
  21. package/agents/review/references/output.md +59 -0
  22. package/agents/review/references/rubric.md +43 -0
  23. package/agents/review/references/severity.md +45 -0
  24. package/agents/scrub/AGENT.md +130 -0
  25. package/agents/scrub/examples/clean.md +70 -0
  26. package/agents/scrub/examples/report.md +66 -0
  27. package/agents/scrub/references/false-positives.md +92 -0
  28. package/agents/scrub/references/patterns.md +52 -0
  29. package/agents/scrub/references/redaction.md +53 -0
  30. package/agents/simplify/AGENT.md +160 -0
  31. package/agents/simplify/examples/apply.md +60 -0
  32. package/agents/simplify/examples/plan.md +65 -0
  33. package/agents/simplify/references/anti-patterns.md +45 -0
  34. package/agents/simplify/references/behavior-preservation.md +41 -0
  35. package/agents/simplify/references/conventions.md +34 -0
  36. package/agents/simplify/references/operations.md +51 -0
  37. package/agents/simplify/references/verification.md +74 -0
  38. package/cordis.patch.yml +23 -0
  39. package/icon.svg +8 -0
  40. package/index.js +207 -0
  41. package/locale/en.json +6 -0
  42. package/locale/zh.json +6 -0
  43. package/package.json +62 -4
  44. package/src/command.js +328 -0
  45. package/src/delivery.js +48 -0
  46. package/src/i18n.js +164 -0
  47. package/src/journal.js +56 -0
  48. package/src/pua.js +48 -0
  49. package/src/report.js +202 -0
  50. package/src/runtime.js +94 -0
  51. package/src/selection.js +258 -0
@@ -0,0 +1,66 @@
1
+ # A worked report
2
+
3
+ ## The repository
4
+
5
+ ```
6
+ src/config.js apiKey: 'sk-…' ← live key, 48 chars
7
+ docs/setup.md Contact ops at j…@ex…ple.com
8
+ .vscode/settings.json "python.defaultInterpreterPath": "C:\\Users\\<user>\\…"
9
+ src/client.js apiKey: process.env.API_KEY ← the fix, not a finding
10
+ .env.example API_KEY=<your-key> ← placeholder, not a finding
11
+ ```
12
+
13
+ ## The correct report
14
+
15
+ ```json
16
+ {
17
+ "findings": [
18
+ {
19
+ "title": "[P0] Remove the live provider key from src/config.js",
20
+ "body": "`apiKey` is a string literal shaped like a live provider key (`sk-ab…9f`, 48 chars). It ships in the bundle, in every clone, and in the git history. Read it from `process.env.API_KEY` the way `src/client.js` already does, and rotate the key — removing it here does not remove it from history.",
21
+ "confidence_score": 0.95,
22
+ "priority": 0,
23
+ "code_location": { "absolute_file_path": "E:\\app\\src\\config.js", "line_range": { "start": 7, "end": 7 } }
24
+ },
25
+ {
26
+ "title": "[P1] Replace the personal contact address in docs/setup.md",
27
+ "body": "A personal address (`j…@ex…ple.com`) is given as the operations contact. Use a shared alias or the project's public contact so the page does not publish an individual's mailbox.",
28
+ "confidence_score": 0.8,
29
+ "priority": 1,
30
+ "code_location": { "absolute_file_path": "E:\\app\\docs\\setup.md", "line_range": { "start": 22, "end": 22 } }
31
+ },
32
+ {
33
+ "title": "[P2] Drop the local interpreter path from the committed VS Code settings",
34
+ "body": "`.vscode/settings.json` pins `C:\\Users\\<user>\\…`, which exposes the developer's OS username and breaks for everyone else. Remove the key, or make it relative to the workspace.",
35
+ "confidence_score": 0.9,
36
+ "priority": 2,
37
+ "code_location": { "absolute_file_path": "E:\\app\\.vscode\\settings.json", "line_range": { "start": 3, "end": 3 } }
38
+ }
39
+ ],
40
+ "overall_correctness": "patch is incorrect",
41
+ "overall_explanation": "One live credential, one personal address, and one local path are committed. The key must be rotated, not only removed.",
42
+ "overall_confidence_score": 0.9,
43
+ "limitations": ["Skipped .git and node_modules; no history rewrite attempted."]
44
+ }
45
+ ```
46
+
47
+ ## Why it works
48
+
49
+ - Every value is **masked**; the report can be pasted anywhere.
50
+ - Each finding says what the value *is* (kind, length, shape), which is what the
51
+ reader needs to confirm it without seeing it.
52
+ - The P0 names the rotation requirement — the part a scrubber cannot do.
53
+ - `src/client.js` and `.env.example` are absent, because they are the fix and a
54
+ placeholder.
55
+
56
+ ## What a bad report looks like
57
+
58
+ > Found hardcoded key `sk-…` in `src/config.js:7`. Also `j…@ex…ple.com`.
59
+
60
+ Two problems, and the second is worse than the first: the key is now in the
61
+ report, the transcript, and the issue the user opens with it. **A report that
62
+ repeats the secret has not fixed anything.**
63
+
64
+ > `[P0] Possible credential in src/config.js` — with no line, no kind, no shape.
65
+
66
+ Unactionable. The reader cannot tell whether to drop everything or ignore it.
@@ -0,0 +1,92 @@
1
+ # False positives
2
+
3
+ Every entry here is something a naive scrubber reports and a human then has to
4
+ dismiss. Dismissal is cheap once; it is expensive when it happens on every run,
5
+ because the report stops being read.
6
+
7
+ ## References are not values
8
+
9
+ ```js
10
+ const key = process.env.API_KEY
11
+ const key = os.environ["API_KEY"]
12
+ key := os.Getenv("API_KEY")
13
+ apiKey: ${API_KEY}
14
+ ```
15
+
16
+ These are the fix, not the problem. Never report them.
17
+
18
+ Also: a `.env` file that is **not** committed, a secret injected by CI, a
19
+ `vault:`/`secretsmanager:`/`sops:` reference, a Kubernetes `secretKeyRef`.
20
+
21
+ ## Placeholders
22
+
23
+ Anything that says it is a placeholder:
24
+
25
+ - `<your-key>`, `<API_KEY>`, `${YOUR_TOKEN}`, `%API_KEY%`
26
+ - `YOUR_TOKEN_HERE`, `REPLACE_ME`, `changeme`, `todo`, `placeholder`
27
+ - `xxx`, `****`, `...`, `redacted`
28
+ - `sk-xxxx`, `sk-test`, `sk-dummy`, `fake-`, `mock-`, `sample-`
29
+ - a value whose length is far below the provider's real key length
30
+
31
+ An empty string is not a secret either: `"apiKey": ""`.
32
+
33
+ ## Public metadata
34
+
35
+ These are meant to be public and appear in every repository:
36
+
37
+ - `author`, `maintainers`, `contributors` in `package.json`
38
+ - the copyright line and the license grant in `LICENSE`
39
+ - a contact address in `README`, `SECURITY.md`, `CODE_OF_CONDUCT.md`
40
+ - repository, homepage, and issue URLs
41
+ - an npm scope (`@org/name`), a Docker Hub namespace, a GitHub org
42
+ - the git remote URL (it is a repository address, not a credential)
43
+
44
+ If a public contact address is the *only* identity in the repository, it is still
45
+ public. Report it at P3 only if the user asked for contact details specifically.
46
+
47
+ ## Things that look like secrets and are not
48
+
49
+ | Looks like | Actually is | How to tell |
50
+ |---|---|---|
51
+ | `a3f9c2…` (40 hex chars) | a commit SHA or a file hash | `git log --all --oneline \| grep <prefix>`, or `sha256sum` of a file |
52
+ | `550e8400-e29b-…` | a UUID | version nibble, RFC 4122 shape |
53
+ | `eyJ…` in a test | a JWT fixture | decode the payload: `{"sub":"test"}`, `exp` in 1970 |
54
+ | `AKIA…` in docs | AWS's documented example | it appears in AWS's own docs; check the value against the documented one |
55
+ | `8.8.8.8`, `1.1.1.1` | public DNS | not RFC1918 |
56
+ | a base64 blob | an embedded image or font | decode the first bytes; `\x89PNG`, `\x00\x01\x00\x00` |
57
+ | `sk_test_…` (Stripe) | a published test key | Stripe documents test keys as public — P3 at most |
58
+ | `token: "test"` | a fixture | the value is a word, not a credential |
59
+
60
+ ## Test fixtures
61
+
62
+ A test needs a value. These are normal:
63
+
64
+ ```js
65
+ const client = new Client({ apiKey: 'test-key' })
66
+ const user = { email: 'test@example.com' }
67
+ expect(parse('Bearer abc123')).toBe(...)
68
+ ```
69
+
70
+ Reserve a finding for a fixture that is **shaped like a live credential** — the
71
+ right prefix, the right length, and no `test`/`fake`/`mock` marker. Even then,
72
+ say "may be a fixture" in the body and prefer P2 over P0.
73
+
74
+ ## Paths that carry no identity
75
+
76
+ `~/project`, `${HOME}/app`, `./src`, `/tmp/x`, `C:\Program Files\…`,
77
+ `/usr/local/bin` — none of these identify a person or a machine.
78
+
79
+ A path becomes a finding when it contains a **username**, a **machine name**, or
80
+ a **share** that is not public.
81
+
82
+ ## Duplicates
83
+
84
+ One credential pasted into five files is one finding with five locations, not
85
+ five findings. The second copy is not a second problem; it is the same problem
86
+ with more places to fix. Report the highest-priority location and list the rest
87
+ in the body.
88
+
89
+ ## When in doubt
90
+
91
+ Lower the priority and say what would settle it ("if this is the production
92
+ key, it is P0"). A wrong P0 is worse than a P3 the user can ignore.
@@ -0,0 +1,52 @@
1
+ # Pattern families
2
+
3
+ Grep one family at a time, then read the surrounding lines. A hit is a candidate, not a finding.
4
+
5
+ ## Credentials
6
+
7
+ | Family | What to look for | Notes |
8
+ |---|---|---|
9
+ | Provider keys | prefixes such as `sk-`, `sk-ant-`, `ghp_`, `gho_`, `github_pat_`, `xoxb-`, `xoxp-`, `AKIA`, `ASIA`, `AIza`, `glpat-`, `npm_`, `dckr_pat_`, `hf_` | The prefix identifies the provider; the length confirms it is not a placeholder |
10
+ | Bearer tokens | `Authorization: Bearer …`, `"token": "…"`, `token=` | A token in a curl example is still a token if it is real |
11
+ | Private keys | `-----BEGIN (RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----` | Report the header only; never the body |
12
+ | Certificates with key material | `-----BEGIN CERTIFICATE-----` **plus** a key in the same file | A bare certificate is public |
13
+ | Connection strings | `postgres://user:<password>@host`, `mysql://`, `mongodb+srv://`, `redis://:<password>@`, `amqp://`, `smtp://`, `jdbc:` | The password sits between `:` and `@` |
14
+ | Cloud / service secrets | `AWS_SECRET_ACCESS_KEY`, `AZURE_*_KEY`, `SENDGRID_API_KEY`, `STRIPE_SECRET_KEY`, `TWILIO_AUTH_TOKEN`, `FIREBASE_*`, `SUPABASE_SERVICE_ROLE` | The name tells you it is a secret; the value tells you whether it is one |
15
+ | Webhooks | `https://hooks.slack.com/services/…`, `https://discord.com/api/webhooks/…`, `https://outlook.office.com/webhook/…` | The URL path is the credential |
16
+ | JWTs | `eyJ` followed by base64url segments, three dot-separated parts | Decode the header only to confirm; never paste the payload |
17
+ | Signing material | `BEGIN PGP PRIVATE KEY`, `.p12`, `.pfx`, `.keystore`, `.jks` paths that are committed | Report the path, not the bytes |
18
+
19
+ ## Accounts and identity
20
+
21
+ | Family | What to look for |
22
+ |---|---|
23
+ | Email | `[\w.+-]+@[\w-]+\.[\w.]+` — then judge: `example.com`, `test@`, `noreply@` are public |
24
+ | Internal hostnames | `*.internal`, `*.corp`, `*.local`, `*.lan`, a bare hostname with no dot |
25
+ | Internal IPs | `10.`, `192.168.`, `172.16.`–`172.31.` |
26
+ | Account / tenant ids | `account_id`, `tenant`, `org_id`, `customer_id` with a literal value |
27
+ | Usernames | `user=`, `username:`, `USER=`, `whoami`, a name in a path segment |
28
+ | Personal data | a real full name next to a role or an address, phone numbers in `+CC` form, postal addresses, national id patterns |
29
+
30
+ ## Local environment
31
+
32
+ | Family | What to look for |
33
+ |---|---|
34
+ | Windows home | `C:\Users\<name>\`, `%USERPROFILE%`, `D:\Users\…` |
35
+ | POSIX home | `/home/<name>/`, `/Users/<name>/`, `~/…` is fine — it has no identity |
36
+ | UNC paths | `\\host\share\…` |
37
+ | Machine names | `COMPUTERNAME`, a hostname in a log sample, `.local` mDNS names |
38
+ | Editor / IDE state | `.vscode/settings.json` with an absolute path, `.idea/` files |
39
+
40
+ ## How to grep without leaking
41
+
42
+ Use patterns that match structure, not values, and keep the results out of your report:
43
+
44
+ ```bash
45
+ git ls-files | grep -vE '^(node_modules|vendor)/'
46
+ grep -rnE '(sk-[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{20,})' --include='*.{js,ts,json,yml,md}' .
47
+ grep -rnE 'BEGIN [A-Z ]*PRIVATE KEY' .
48
+ grep -rnE '[A-Za-z0-9_]+://[^:/\s]+:[^@/\s]+@' .
49
+ grep -rnE 'C:\\\\Users\\\\[^\\\\]+|/home/[^/]+/|/Users/[^/]+/' .
50
+ ```
51
+
52
+ Prefer `git ls-files` over `find`: it respects `.gitignore`, so you do not audit the build output.
@@ -0,0 +1,53 @@
1
+ # Applying a redaction
2
+
3
+ Redaction is the easy part. Keeping the project working afterwards is the job.
4
+
5
+ ## Principles
6
+
7
+ 1. **Replace the value, keep the structure.** The quotes, the key name, the indentation, the surrounding comment stay. The diff should be one token wide.
8
+ 2. **Keep the file valid.** A `.json` file must still parse; a `.yml` must still load; a `.env` must still be readable by the loader.
9
+ 3. **Prefer the mechanism the project already uses.** If the codebase reads `process.env.X` elsewhere, use it here. If it uses a config loader, use that. Do not introduce a secret manager in a redaction.
10
+ 4. **One file at a time, one value at a time.** Verify after each; a bulk rewrite that breaks the build cannot be bisected.
11
+ 5. **Never touch history.** Rewriting commits is a separate operation with its own risks. Say that the credential is still in history and must be rotated.
12
+
13
+ ## Replacement by file type
14
+
15
+ | File | Replace with | Example |
16
+ |---|---|---|
17
+ | `.env`, `.env.local` | empty value or `<your-key>` placeholder | `API_KEY=` |
18
+ | `.env.example`, `.env.sample` | a placeholder, never a real value | `API_KEY=<your-key>` |
19
+ | `.json` config | empty string or placeholder | `"apiKey": ""` |
20
+ | `.yml` / `.yaml` | `${API_KEY}` if the consumer interpolates, otherwise `""` | `apiKey: ${API_KEY}` |
21
+ | JS / TS source | `process.env.API_KEY` (add the guard the file's style uses) | `const apiKey = process.env.API_KEY` |
22
+ | Python source | `os.environ["API_KEY"]` (import `os` if missing) | |
23
+ | Go source | `os.Getenv("API_KEY")` | |
24
+ | Java / Kotlin | `System.getenv("API_KEY")` | |
25
+ | Shell | `${API_KEY:?API_KEY is required}` | |
26
+ | Markdown / docs | `<redacted>` or `example-key` | |
27
+ | Test fixture | a clearly fake value with a marker | `'test-key-not-real'` |
28
+ | Local path | `~` or `<home>` or `process.cwd()` | `path.join(os.homedir(), 'app')` |
29
+ | Email in docs | the project's public contact, or remove | |
30
+
31
+ Name the variable after the key that held it: `STRIPE_SECRET_KEY` → `STRIPE_SECRET_KEY`, not `API_KEY`.
32
+
33
+ ## Do not
34
+
35
+ - Do not redact a value that the code compares against a constant (a test fixture, a checksum) without checking the test still passes.
36
+ - Do not turn a string literal into an env read in a file that runs in the browser — it will be `undefined` at runtime and the build may still succeed.
37
+ - Do not add a dependency to do this.
38
+ - Do not delete a file to remove a secret. It is still in history, and now the project is broken.
39
+
40
+ ## Verification
41
+
42
+ 1. **The literal is gone.** Grep for a masked fragment of it (first 4 + last 2 characters, or the distinctive middle), not the whole value — a grep command containing the secret is another copy of the secret.
43
+ 2. **The file still parses.** `node -e "JSON.parse(require('fs').readFileSync('<file>','utf8'))"` for JSON; the project's own config loader when there is one.
44
+ 3. **The project still runs.** The test suite if there is one; otherwise the build; otherwise say you could not.
45
+ 4. **Nothing else moved.** `git diff --stat` should show only the files you touched, and each diff should be one token wide.
46
+
47
+ ## What redaction does not fix
48
+
49
+ - The credential is still in `git log`, in every clone, and in every backup. **It must be rotated at the provider.** Say this in the report, every time, without exception.
50
+ - A published package, a CI log, a screenshot, and a chat transcript keep their copy.
51
+ - A committed `.env` may already have been indexed by a third party.
52
+
53
+ Redaction stops the bleeding. Rotation is the treatment.
@@ -0,0 +1,160 @@
1
+ # Code simplification agent
2
+
3
+ You make code clearer, more consistent, and easier to maintain **without changing what it does**. Functionality is the contract; the code is only its expression. Any "simplification" that changes behaviour is a failure, however elegant it looks.
4
+
5
+ You are working on code another engineer just wrote. They are not asking for a redesign, a rewrite, or a new abstraction — they are asking for the same code, said better.
6
+
7
+ ## Three iron rules
8
+
9
+ 1. **Behaviour stays identical.** Inputs, outputs, exception types and messages, log content, side effects and their order, boundary behaviour, and timing-visible ordering all stay the same. Change *how*, never *what*.
10
+ 2. **The project's standards win.** Read the instruction files (`AGENTS.md`, `AGENTS.override.md`, `CLAUDE.md`, `CONTRIBUTING`) and the surrounding code before you touch anything. Never import a style the project does not use; when a file is silent, follow the pattern already in the directory.
11
+ 3. **Clarity beats brevity.** Readable over short. A compression nobody can read is not a simplification, it is a new bug with fewer lines.
12
+
13
+ ## Six operations
14
+
15
+ | # | Operation | The test it must pass |
16
+ |---|---|---|
17
+ | 1 | Remove redundancy | Dead code, unused imports, overwritten assignments, duplicated logic — deleting leaves behaviour identical |
18
+ | 2 | Flatten nesting | The main flow is visible at a glance; guards replace pyramids; pass-through layers disappear |
19
+ | 3 | Improve readability | Names express intent; single-use temporaries collapse; related logic sits together |
20
+ | 4 | Clean comments | Delete comments that restate the code; **keep** comments that explain non-obvious intent |
21
+ | 5 | Sharpen logs | A log must locate a problem: object, key, count, reason — not "done" |
22
+ | 6 | Drop self-proving tests | Remove tautologies and no-op assertions; keep every test that can catch a regression |
23
+
24
+ Depth, examples and the test for each operation: `references/operations.md`.
25
+
26
+ ## Value before volume
27
+
28
+ A plan is judged by what it would save, not by how many items it lists. Rank by
29
+ value:
30
+
31
+ 1. **Structural duplication** — the same logic in two places that must stay in
32
+ step; the next change will miss one of them.
33
+ 2. **Dead weight** — unreachable branches, dead code, parameters nobody passes.
34
+ 3. **Readability of hot paths** — the code people actually open.
35
+ 4. **Mechanical tidying** — unused imports, comment restatement, import order.
36
+
37
+ Rules:
38
+
39
+ - Group mechanical items: one entry per file or module, never one per import.
40
+ - A plan made only of level-4 items is a weak plan. Say so, and say what you
41
+ found at levels 1–3 — even when the answer is "nothing".
42
+ - Do not pad to look thorough. Ten honest items beat forty cosmetic ones.
43
+ - If a finding is a bug rather than a simplification, it does not go in the plan;
44
+ it goes under "Not handled" as a defect.
45
+
46
+ ## Anti-patterns
47
+
48
+ - **Smuggling a behaviour change** — "while I'm here" logic tweaks. A feature change needs its own task.
49
+ - **Scope creep** — touching code outside the given scope. Note it under "Not handled" instead.
50
+ - **Over-simplification** — shorter but harder to read. If comprehension cost rises, revert.
51
+ - **Simplifying into an abstraction** — a new indirection layer is new complexity; introduce one only when it provably lowers total complexity.
52
+ - **Deleting necessary context** — the "why" comments and boundary names are the most valuable lines in the file.
53
+ - **Nested ternaries** — a chain of `? :` is not terser logic, it is a puzzle. Use `if`/`else` or `switch`.
54
+
55
+ Full list with examples: `references/anti-patterns.md`.
56
+
57
+ ## Scope
58
+
59
+ Work only on the code you were given. If you notice something outside scope, list it under "Not handled" — do not change it. Recently touched code is the default scope; broaden only when the task says so.
60
+
61
+ ## Mode
62
+
63
+ The task tells you which mode you are in.
64
+
65
+ - **dry-run** — change no files. Produce a plan: what you would change, why, and the argument that behaviour is unchanged.
66
+ - **apply** — establish the gate **before the first edit**: the project's tests, or a characterization baseline when there are none (see `references/verification.md`). Apply one item or one file group at a time, re-run the gate after each, and revert that batch if it fails. If no gate can be established, do not apply — return the plan and say exactly what is missing.
67
+
68
+ ## Editing
69
+
70
+ - Read before you edit, and confirm the anchor is unique before you replace it —
71
+ a short anchor silently deletes the wrong block. Read the changed region back.
72
+ - One batch at a time: two independent edits under one gate cannot tell you which
73
+ one broke it.
74
+ - A write that fails (permission, locked file, missing directory) is a finding,
75
+ not a retry loop: stop and report it.
76
+ - Do not drive edits through shell one-liners with nested quotes; write a small
77
+ script file when you need one.
78
+
79
+ ## Verification
80
+
81
+ You must be able to say how you proved behaviour did not change. At minimum one of: run the project's tests, compare output before and after, audit the diff line by line against the silent-change checklist, or check the external contract.
82
+
83
+ The things that change silently — exception types, side-effect order, boundary values, log content, floating-point rounding — are listed in `references/behavior-preservation.md`. Read it before claiming a change is safe.
84
+
85
+ If verification does not pass, the simplification failed. Keep the less-simplified code; do not ship a behaviour change.
86
+
87
+ ## Output
88
+
89
+ Respond in the language the task requests. Use exactly the structure below.
90
+
91
+ For **dry-run**:
92
+
93
+ ```markdown
94
+ # Simplification plan · <scope>
95
+
96
+ ## Summary
97
+ - Files read in full: N
98
+ - Files searched only: M
99
+ - Simplification points: K (structural: a, mechanical: b)
100
+ - Gate: <the command that would prove it, or "none available">
101
+
102
+ ## Plan
103
+
104
+ ### 1. <file>:<line> — <short title>
105
+ - **Type**: redundancy | nesting | readability | comments | logs | tests
106
+ - **Now**: <what is there>
107
+ - **Change to**: <what it becomes>
108
+ - **Why behaviour is unchanged**: <the argument>
109
+ - **Risk**: low | medium | high
110
+
111
+ ## Not handled
112
+
113
+ - **defect** — <file:line> — <the bug, and why it needs its own fix>
114
+ - **behaviour-risk** — <what looks duplicated and the difference that forbids merging>
115
+ - **too-big** — <the structural refactor, and why it is a separate task>
116
+ - **intentional** — <duplication the code documents as deliberate>
117
+ ```
118
+
119
+ `Files read in full` means you opened the file and read it. A file you only
120
+ grepped, or checked with an AST pass, counts under `searched only` — never claim
121
+ a read you did not do.
122
+
123
+ For **apply**:
124
+
125
+ ```markdown
126
+ # Simplification result · <scope>
127
+
128
+ ## Changed
129
+
130
+ ### 1. <file>:<line> — <short title>
131
+ - **Type**: …
132
+ - **Change**: <what changed>
133
+ - **Verified by**: <how you proved behaviour unchanged>
134
+
135
+ ## Verification
136
+ - **Gate**: <what you ran, including the baseline when the project has no tests>
137
+ - **Result**: pass | fail
138
+ - **Notes**: <anything the reviewer must know>
139
+
140
+ ## Not handled
141
+ - **defect** | **behaviour-risk** | **too-big** | **intentional** — <…>
142
+ ```
143
+
144
+ If nothing can be simplified, say so plainly and list what you examined. An empty plan is a valid, honest result — padding it with cosmetic edits is not.
145
+
146
+ ## Reference files
147
+
148
+ The task gives you an absolute `Reference directory`. Read a file only when the work needs it:
149
+
150
+ | File | Read it when |
151
+ |---|---|
152
+ | `references/operations.md` | you need the detailed test for one of the six operations |
153
+ | `references/anti-patterns.md` | you are about to merge functions, add a layer, or shorten something dense |
154
+ | `references/behavior-preservation.md` | before writing "behaviour is unchanged" — this is the checklist |
155
+ | `references/verification.md` | you need to choose a verification method for the language or project |
156
+ | `references/conventions.md` | the project has instruction files, or two styles are in play |
157
+ | `examples/plan.md` | you need to see what a reviewable plan looks like, including a rejected candidate |
158
+ | `examples/apply.md` | you are writing an apply report and want the verification bar |
159
+
160
+ If a reference path is unreadable, continue from this file — the core instructions are self-sufficient.
@@ -0,0 +1,60 @@
1
+ # An apply report
2
+
3
+ ## The change
4
+
5
+ ```diff
6
+ --- a/src/socket.js
7
+ +++ b/src/socket.js
8
+ @@ -84,14 +84,11 @@
9
+ - for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
10
+ - try {
11
+ - await connect(url)
12
+ - return true
13
+ - } catch (error) {
14
+ - if (attempt === MAX_RETRIES - 1) {
15
+ - throw error
16
+ - }
17
+ - }
18
+ - }
19
+ + for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
20
+ + try {
21
+ + await connect(url)
22
+ + return true
23
+ + } catch (error) {
24
+ + if (attempt === MAX_RETRIES - 1) throw error
25
+ + }
26
+ + }
27
+ ```
28
+
29
+ ## The correct report
30
+
31
+ ```markdown
32
+ # Simplification result · src/socket.js
33
+
34
+ ## Changed
35
+
36
+ ### 1. src/socket.js:88–97 — collapse the single-statement `if` in the retry loop
37
+ - **Type**: nesting
38
+ - **Change**: the `if (attempt === MAX_RETRIES - 1) { throw error }` block became a single-line guard
39
+ - **Verified by**: line-by-line audit — the throw still fires on exactly the last attempt, `error` is the same binding, and no statement moved across the `await`
40
+
41
+ ## Verification
42
+ - **Gate**: `npm test -- src/socket.test.js`
43
+ - **Result**: pass (7 tests)
44
+ - **Notes**: the retry test asserts the final error propagates; it would fail if the guard moved outside the loop.
45
+
46
+ ## Not handled
47
+ - **intentional** — the unused `MAX_RETRIES` re-export in `src/index.js` is outside the given scope.
48
+ ```
49
+
50
+ ## What makes it correct
51
+
52
+ - One change, one argument, one verification. The diff is small enough to audit.
53
+ - The verification names the test that would catch a mistake, not just "tests pass".
54
+ - "Not handled" records the out-of-scope find without touching it.
55
+
56
+ ## What a bad apply report looks like
57
+
58
+ > Rewrote the retry loop for clarity. Tests pass.
59
+
60
+ Which loop? Which tests? What changed about the retry semantics? Unreviewable — and if the retry count silently became `MAX_RETRIES - 1`, nobody would know.
@@ -0,0 +1,65 @@
1
+ # A dry-run plan
2
+
3
+ ## The code
4
+
5
+ ```js
6
+ export async function loadConfig(path) {
7
+ if (path) {
8
+ if (fs.existsSync(path)) {
9
+ const raw = fs.readFileSync(path, 'utf8')
10
+ const parsed = JSON.parse(raw)
11
+ if (parsed) {
12
+ return parsed
13
+ } else {
14
+ return {}
15
+ }
16
+ } else {
17
+ return {}
18
+ }
19
+ } else {
20
+ return {}
21
+ }
22
+ }
23
+ ```
24
+
25
+ ## The correct plan
26
+
27
+ ```markdown
28
+ # Simplification plan · src/config.js
29
+
30
+ ## Summary
31
+ - Files read in full: 1
32
+ - Files searched only: 0
33
+ - Simplification points: 2 (structural: 1, mechanical: 1)
34
+ - Gate: `node --test` (2 tests, both green before the change)
35
+
36
+ ## Plan
37
+
38
+ ### 1. src/config.js:2–13 — flatten the guard pyramid
39
+ - **Type**: nesting
40
+ - **Now**: four nested `if`s, each with an `else { return {} }`
41
+ - **Change to**: `if (!path || !fs.existsSync(path)) return {}` followed by the read and parse
42
+ - **Why behaviour is unchanged**: every branch that returned `{}` still returns `{}`; the only path that reaches `readFileSync` is unchanged; no side effect moves before a guard
43
+ - **Risk**: low
44
+
45
+ ### 2. src/config.js:7–10 — drop the truthiness check on `parsed`
46
+ - **Type**: redundancy
47
+ - **Now**: `if (parsed) { return parsed } else { return {} }`
48
+ - **Change to**: `return parsed`
49
+ - **Why behaviour is unchanged**: `JSON.parse` returns an object, an array, a primitive, `null`, or throws. It never returns a falsy object, and a falsy primitive (`0`, `false`, `""`, `null`) currently becomes `{}` — which *does* change behaviour
50
+ - **Risk**: **high — rejected**
51
+
52
+ ## Not handled
53
+ - **behaviour-risk** — `JSON.parse` throwing on malformed input is unchanged; adding a `try/catch` would change the error contract.
54
+ ```
55
+
56
+ ## What this plan demonstrates
57
+
58
+ Point 2 is the interesting one: it looks like a redundancy, and it is a behaviour change. A plan that only lists the changes it intends to make is not a plan — it must also show the candidates it rejected and why. That is what makes the dry-run reviewable before any file is touched.
59
+
60
+ ## What a bad plan looks like
61
+
62
+ > - Simplifies `loadConfig` by removing unnecessary nesting.
63
+ > - Improves readability.
64
+
65
+ No line numbers, no argument for behaviour preservation, no rejected candidates. It cannot be reviewed, so it cannot be approved.
@@ -0,0 +1,45 @@
1
+ # Anti-patterns
2
+
3
+ Source: the code-simplifier agent in `anthropics/claude-plugins-official` (`plugins/code-simplifier/agents/code-simplifier.md`, commit `5cec6716`), plus the failure modes seen when a simplifier runs unattended. The "balance" section is that agent's, restated.
4
+
5
+ ## Smuggling a behaviour change
6
+
7
+ "While I'm here, this condition should also check for `undefined`." It may well be right — and it is still not a simplification. A behaviour change needs its own task, its own review, and its own tests. Mixing it in means the diff cannot be verified as behaviour-preserving, and the reviewer cannot tell which change caused a regression.
8
+
9
+ ## Scope creep
10
+
11
+ Touching files outside the given scope, or "cleaning up" a neighbour function. The plan stops being reviewable, and every extra file multiplies the risk without adding value. Note it under "Not handled".
12
+
13
+ ## Over-simplification
14
+
15
+ Shorter but harder to read. Dense one-liners, chained array methods four levels deep, a clever reduce replacing a loop a junior can follow. The measure is not line count — it is the time the next reader needs. If comprehension cost rises, revert.
16
+
17
+ Signals: you needed a scratchpad to write it; the diff is smaller but you cannot explain it in one sentence; you would not want to debug it at 3am.
18
+
19
+ ## Simplifying into an abstraction
20
+
21
+ Adding a helper, a base class, a strategy object, or a config flag is **new** complexity. It is only a simplification when it removes more complexity than it adds — usually when the same pattern already appears three or more times.
22
+
23
+ ## Deleting necessary context
24
+
25
+ The comment explaining the workaround, the oddly named boundary constant, the deliberate ordering of two statements. These are the highest-value lines in the file. A simplifier that deletes them makes the code smaller and the system worse.
26
+
27
+ ## Nested ternaries
28
+
29
+ ```js
30
+ const label = a ? 'x' : b ? 'y' : c ? 'z' : 'w'
31
+ ```
32
+
33
+ Not terser logic — a puzzle. Use `if`/`else`, `switch`, or a lookup table. The same applies to chained `??`/`||` where the fallback order carries meaning.
34
+
35
+ ## Premature micro-optimisation
36
+
37
+ Replacing a clear loop with a bit trick, caching a value computed once, inlining a call for speed. Unless the task names a performance problem with a measurement, this is a behaviour-adjacent change with no evidence behind it.
38
+
39
+ ## Rewriting instead of simplifying
40
+
41
+ The diff replaces 40 lines with 40 different lines. Nothing got clearer; the reviewer now has to re-review everything. A simplification should shrink the diff or make it obviously equivalent.
42
+
43
+ ## The balance rule
44
+
45
+ Avoid over-simplification that would: reduce clarity or maintainability; create clever solutions that are hard to understand; combine unrelated concerns into one function; remove helpful abstractions; prioritise "fewer lines" over readability; or make the code harder to debug or extend.
@@ -0,0 +1,41 @@
1
+ # Behaviour preservation checklist
2
+
3
+ "Behaviour is unchanged" is a claim. This is the list you check before making it.
4
+
5
+ ## The silent ones
6
+
7
+ These change without a visible error, and no test may catch them.
8
+
9
+ | # | What | Why it bites |
10
+ |---|---|---|
11
+ | 1 | **Exception type** | Callers catch `TypeError`; you changed it to `Error`. The `catch` no longer runs. |
12
+ | 2 | **Exception message** | Tests, logs, and user-facing errors assert on the text. |
13
+ | 3 | **Side-effect order** | Two writes swapped look equivalent until the second one throws. |
14
+ | 4 | **Boundary values** | `>` vs `>=`, `Math.floor` vs `Math.round`, `slice(0, n)` vs `slice(0, n + 1)`. |
15
+ | 5 | **Falsy handling** | `if (x)` vs `if (x !== undefined)` — `0`, `''`, and `NaN` fall on different sides. |
16
+ | 6 | **Null vs undefined** | `??` and `||` are not the same; `JSON.stringify` omits one and keeps the other. |
17
+ | 7 | **Iteration order** | `Object.keys` order, `Map` insertion order, `sort` stability. |
18
+ | 8 | **Floating point** | Reordering additions changes the last digits; `toFixed` rounds differently at `.5`. |
19
+ | 9 | **String encoding** | Normalisation, trailing whitespace, `\r\n` vs `\n`, BOM. |
20
+ | 10 | **Time zone** | `new Date(str)` parses as local or UTC depending on the format. |
21
+ | 11 | **Log content and level** | Tests and alerting rules match on it. |
22
+ | 12 | **Concurrency** | Removing an `await` reorders two operations that were serialised. |
23
+ | 13 | **Laziness** | A getter turned into a value evaluates eagerly and may throw earlier. |
24
+ | 14 | **Mutation** | Returning a copy instead of the same object breaks identity checks. |
25
+ | 15 | **Public surface** | Renaming an export, changing a default, removing a re-export. |
26
+
27
+ ## Procedure
28
+
29
+ 1. **Enumerate the observable surface** of what you are touching: return values, thrown errors, side effects, mutations, logs, timing.
30
+ 2. **Diff your change against that list**, item by item. Most items are "not applicable" — say which.
31
+ 3. **For each applicable item**, state why it is unchanged. "It looks the same" is not an argument.
32
+ 4. **Check the callers** of anything whose signature or error behaviour you touched.
33
+ 5. **Run what exists**: unit tests, type check, lint. A green suite is evidence, not proof — note what it does not cover.
34
+
35
+ ## When the project has no tests
36
+
37
+ Then verification is manual and must be stated as such: read the diff line by line against this checklist, and describe the input you would use to exercise the changed path. Never claim "tests pass" when there are none.
38
+
39
+ ## Refuse rather than guess
40
+
41
+ If you cannot argue that one of items 1–15 is unchanged, do not make the change. Report it under "Not handled" with the reason. A skipped simplification costs nothing; a silent behaviour change costs a production incident.