@srobroek/pi-code-challenge 0.0.0-stage → 2.0.3

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 (39) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/LICENSE +202 -0
  3. package/README.md +73 -2
  4. package/agents/code-challenger.md +64 -0
  5. package/agents/refactor-challenger.md +81 -0
  6. package/extensions/index.js +3862 -0
  7. package/formulas/code-challenge.formula.toml +102 -0
  8. package/formulas/mol-challenge-challenge.formula.toml +66 -0
  9. package/formulas/mol-challenge-decide.formula.toml +58 -0
  10. package/formulas/mol-challenge-deliver.formula.toml +70 -0
  11. package/formulas/mol-challenge-intake.formula.toml +68 -0
  12. package/formulas/mol-challenge-lens.formula.toml +59 -0
  13. package/formulas/mol-challenge-refute.formula.toml +77 -0
  14. package/formulas/mol-challenge-research.formula.toml +61 -0
  15. package/formulas/mol-challenge-scan.formula.toml +61 -0
  16. package/package.json +38 -4
  17. package/skills/code-challenge/SKILL.md +83 -0
  18. package/skills/code-challenge/references/decide.md +31 -0
  19. package/skills/code-challenge/references/decisions.schema.json +21 -0
  20. package/skills/code-challenge/references/evidence.md +17 -0
  21. package/skills/code-challenge/references/intake-questions.md +49 -0
  22. package/skills/code-challenge/references/lens-dead-code.md +20 -0
  23. package/skills/code-challenge/references/lens-efficiency.md +21 -0
  24. package/skills/code-challenge/references/lens-hand-rolled-library.md +18 -0
  25. package/skills/code-challenge/references/lens-hand-rolled-stdlib.md +20 -0
  26. package/skills/code-challenge/references/lens-observability.md +20 -0
  27. package/skills/code-challenge/references/lens-optimisation.md +20 -0
  28. package/skills/code-challenge/references/lens-over-engineering.md +21 -0
  29. package/skills/code-challenge/references/lens-performance.md +18 -0
  30. package/skills/code-challenge/references/lens-scope.md +31 -0
  31. package/skills/code-challenge/references/lens-simplification.md +23 -0
  32. package/skills/code-challenge/references/lens-stability.md +21 -0
  33. package/skills/code-challenge/references/lens-structure.md +26 -0
  34. package/skills/code-challenge/references/lens-tests.md +20 -0
  35. package/skills/code-challenge/references/library-scoring.md +54 -0
  36. package/skills/code-challenge/references/report.schema.json +125 -0
  37. package/skills/code-challenge/references/run-storage.md +22 -0
  38. package/skills/code-challenge/references/scan.md +36 -0
  39. package/skills/code-challenge/references/schemas.md +37 -0
@@ -0,0 +1,83 @@
1
+ ---
2
+ name: code-challenge
3
+ description: Challenges code for scope against its design, simplification, performance, stability and structure; triggers on challenge this code.
4
+ ---
5
+
6
+ # Code challenge
7
+
8
+ Challenge existing code and return findings with evidence. Plan only: this skill edits no source file. Started by the `/code-challenge` command (`auto` runs it autonomously) or by a request such as "challenge this module", "what can we simplify" or "is any of this hand-rolled".
9
+
10
+ TRIGGER
11
+ + a request to find simplification, performance, stability, dead-code, library or structure wins in existing code
12
+ + a request to check code against its design or docs: missing requirements, drift, scope creep, features built beyond the design
13
+ + a large diff, a new module or a new dependency that needs a second look
14
+ - reviewing a diff for defects before merge -> `code-reviewer` agent
15
+ - a single suspected bug -> `quality-code-design`
16
+ - auditing the test suite itself -> `quality-test-audit`
17
+
18
+ GATES
19
+ ASK Running benchmarks in interactive mode, once, at INTAKE.
20
+ ASK Posting a PR or MR comment. Autonomous mode never posts.
21
+ ASK Installing an analyzer. Report a missing one as a gap.
22
+ ASK Passing `allowCode` to `challenge_scan`, unless the user said they trust the repository. Without it, report the skipped analyzers as gaps.
23
+
24
+ ## Modes and depth
25
+
26
+ Mode: **interactive** (default) asks through `parley_ask` when it is available, otherwise through the host's question tool, otherwise as one numbered batch of questions in chat, at INTAKE and DECIDE. **Autonomous** (`auto`) asks only at INTAKE, and only what the arguments and the repository cannot answer; it decides by the rule in [references/decide.md](references/decide.md) and logs every choice.
27
+
28
+ | Depth | Phases | Rules |
29
+ |---|---|---|
30
+ | `quick` | INTAKE, SCAN, CHALLENGE, DELIVER (chat report only) | no build-needing analyzers, no RESEARCH, no REFUTE, no beads; every finding is marked unrefuted |
31
+ | `standard` (default) | all seven | build-needing analyzers allowed; REFUTE checks every finding above low impact |
32
+ | `deep` | all seven | REFUTE checks every finding; RESEARCH also runs the reverse direction (dependencies replaceable by native code); benchmarks run; test protection gaps handed to `quality-test-audit` |
33
+
34
+ Each phase is also a beads formula (`mol-challenge-<phase>`) and the full run is `code-challenge`; install them with `challenge_setup`. A phase can run alone when its input file exists in the run directory. The formulas are optional tracking: the run directory holds the run's data and is the source of truth. Pour the `code-challenge` molecule only when the user wants a step per phase in beads; the pour carries the same `run_id`, and its steps do not replace the files. A run that skips the pour loses nothing.
35
+
36
+ ## Rules
37
+
38
+ MUST Give every finding a lens, a locator, an impact, a blast radius and an evidence tier (`proven`, `measured` or `hypothesis`): [references/evidence.md](references/evidence.md).
39
+ MUST Record test protection (`protected`, `partial`, `unprotected`) on every simplification, library and structure finding.
40
+ MUST Write `decisions.jsonl` as you go: every decision, blocker, ambiguity, choice and inference is one JSON line, appended when it happens and never rewritten. Schema: [references/schemas.md](references/schemas.md).
41
+ MUST Store the run in `<git-dir>/code-challenge/<run-id>/`: [references/run-storage.md](references/run-storage.md).
42
+ NOT Report a performance claim without a measurement. A suspicion is a `hypothesis`.
43
+ NOT Report a finding as `proven` from analyzer output alone.
44
+ NOT Invent a lens or an analyzer rule; use the thirteen lenses below.
45
+
46
+ ## Lenses
47
+
48
+ One reference per lens, each with what to look for, the evidence needed and the steering skills to load. A steering skill is optional: `lang-<language>-…` takes the target's language (`lang-go-quality`), and a skill that is not installed is skipped and named in the report's `gaps`.
49
+
50
+ | Lens | Reference |
51
+ |---|---|
52
+ | scope (design and docs conformance) | [lens-scope.md](references/lens-scope.md) |
53
+ | simplification | [lens-simplification.md](references/lens-simplification.md) |
54
+ | over-engineering | [lens-over-engineering.md](references/lens-over-engineering.md) |
55
+ | optimisation (algorithm) | [lens-optimisation.md](references/lens-optimisation.md) |
56
+ | performance (measured) | [lens-performance.md](references/lens-performance.md) |
57
+ | efficiency (waste) | [lens-efficiency.md](references/lens-efficiency.md) |
58
+ | stability | [lens-stability.md](references/lens-stability.md) |
59
+ | hand-rolled, standard library or framework | [lens-hand-rolled-stdlib.md](references/lens-hand-rolled-stdlib.md) |
60
+ | hand-rolled, third-party library | [lens-hand-rolled-library.md](references/lens-hand-rolled-library.md) |
61
+ | dead code | [lens-dead-code.md](references/lens-dead-code.md) |
62
+ | observability | [lens-observability.md](references/lens-observability.md) |
63
+ | structure (including abstraction seams) | [lens-structure.md](references/lens-structure.md) |
64
+ | tests (light, static) | [lens-tests.md](references/lens-tests.md) |
65
+
66
+ ## Tools
67
+
68
+ `challenge_lib_facts` returns library facts from deps.dev, OSV, the registries and GitHub (see [references/library-scoring.md](references/library-scoring.md) for its input and output). `challenge_scan` runs the SCAN analyzers (see [references/scan.md](references/scan.md) for its input and output). `challenge_validate` checks a run's `report.json` and `decisions.jsonl` against the schemas (see [references/schemas.md](references/schemas.md)).
69
+
70
+ ## Workflow
71
+
72
+ 1. INTAKE: LOAD [references/intake-questions.md](references/intake-questions.md) and ask its batch (interactive), or infer the answers and ask only for a missing target or depth (autonomous). Create the run directory and `run_id`. -> `intake.json` written; the pluggability answer and its signal logged to `decisions.jsonl`.
73
+ 2. SCAN: LOAD [references/scan.md](references/scan.md) and run the analyzers for the languages in the target; `quick` skips build-needing ones. `challenge_scan` runs only analyzers that execute no repository or downloaded code unless you pass `allowCode: true`; pass it only for a repository the user trusts or after asking them, and never on your own judgment for a repository you did not write. -> `scan.json` listing every hit with tool, rule, `path:line` and whether the rule is enabled in the repo, and every analyzer that could not run named as a gap.
74
+ 3. CHALLENGE: for each selected lens, LOAD its reference and spawn one `code-challenger` agent per lens in parallel (reviewer tier), with a brief naming the lens, the target, the scan hits and the frozen surfaces, and for the scope lens the design sources from `intake.json`. The brief MUST list the absolute paths of `references/lens-<lens>.md` and `references/evidence.md`, resolved from the skill's base directory: a scout sees a sampled file list and otherwise reads no lens reference. When the host caps parallel subagents, group related lenses and run the scouts one after another: simplification, over-engineering and dead-code; scope alone; optimisation, performance and efficiency; the rest by pairs. A grouped brief names every lens and reference path of its group. Log the grouping as a `choice` line in `decisions.jsonl` and name it in `gaps`. Reject a scout reply that lacks the line `References read:` or lists fewer references than the brief named (every lens reference of its group plus `evidence.md`); re-ask once with the missing paths. The line ends the reply, after the agent's own `VERDICT:` first line; a brief never asks for it first. If the second reply is still short, record a gap naming the lens and the unread references, and mark its findings as read without the reference. The scouts and the critic only read and reply; you (the lead) spawn them, merge the replies, collapse one root cause into one finding, and write every file. -> `findings.json` with each finding at a locator, a tier and a test-protection value.
75
+ 4. RESEARCH (standard, deep): for each library-lens finding LOAD [references/library-scoring.md](references/library-scoring.md); gather facts, score 2 to 4 candidates, apply the gates. -> `research.json` with per-criterion scores, gate results and the "keep what exists" baseline for each finding.
76
+ 5. REFUTE (standard, deep): you send the findings to the `refactor-challenger` agent (reviewer tier) as a brief of observable facts only: locator, claim, tool or reading, proposal, evidence. Split a finding that bundles proposals which can be decided separately into one entry per proposal, each with its own tier, blast radius and contract flag. Keep what was observed in the code, what is inferred from it and what a command reproduced in separate fields. An empty reply is not a verdict: send the same brief again once; if the second reply is empty too, log a `blocker` line and mark those findings unrefuted. -> `verdicts.json` with KEEP, DOWNGRADE or DROP and a cited rationale per finding; a DROP leaves the offer list.
77
+ 6. DECIDE: LOAD [references/decide.md](references/decide.md). Interactive: batches of up to 12 through `parley_ask`. Autonomous: accept only a surviving, `proven` or `measured`, low-blast-radius finding that keeps its contract and is not a scope finding; defer the rest. -> every finding has a status and `decided_by`, with one `decisions.jsonl` line each.
78
+ 7. DELIVER: write `report.json` against [references/report.schema.json](references/report.schema.json) and `decisions.jsonl` against [references/decisions.schema.json](references/decisions.schema.json); print the report in chat; create the epic and child beads for accepted findings (standard, deep); draft the PR comment. -> both files pass `challenge_validate`, the chat report names the run directory, and the comment is posted only after the user confirms.
79
+
80
+ ## Subagents
81
+
82
+ - `code-challenger`: read-only, advisory, always autonomous. It skips INTAKE and takes its target and lens from the brief. Its verdict never blocks a merge. The orchestrator may also spawn it beside `code-reviewer` for large diffs.
83
+ - `refactor-challenger`: read-only critic that attacks each finding at REFUTE. It accepts this skill's brief and the sniff skill's brief.
@@ -0,0 +1,31 @@
1
+ # DECIDE and DELIVER
2
+
3
+ ## DECIDE
4
+
5
+ Input: findings that survived REFUTE (KEEP or DOWNGRADE). `DROP` findings are listed in the report as dropped and are not offered.
6
+
7
+ Order by impact, then evidence tier (`proven` and `measured` first), then low blast radius.
8
+
9
+ ### Interactive
10
+
11
+ Offer findings through `parley_ask` (fallback: the `question` tool) in batches of up to 12, highest impact first. Each question shows the finding id, title, evidence tier, `test_protection`, the proposal and a recommended answer. Choices: accept, defer, reject. Log each answer to `decisions.jsonl` with `by: user`. Findings the user does not reach stay `deferred`.
12
+
13
+ ### Autonomous
14
+
15
+ No questions. Accept a finding only when all hold:
16
+ 1. REFUTE verdict is KEEP (after downgrade it is a DOWNGRADE, which defers).
17
+ 2. Evidence tier is `proven` or `measured`.
18
+ 3. `blast_radius` is `low` and `changes_contract` is not true.
19
+ 4. The lens is not `scope`. Whether the code or the design is wrong is the user's call.
20
+
21
+ When REFUTE ran, its `tier`, `blast_radius` and `changes_contract` for a finding replace the scout's: the critic checked the claim apart from the scout, so its values are the ones the rule reads. Write them into the finding and log each changed value as a `choice` line naming the old and the new value. A field the critic left empty keeps the scout's value, and the empty field is a gap. A bug fix that restores documented behaviour and keeps every public signature, wire format and config key does not change the contract; if it changes any of those, the critic's `changes_contract: true` stands.
22
+
23
+ Everything else is `deferred`. Set `decided_by: autonomous-rule` and log one line per finding, plus a line for every blocker, ambiguity and choice made along the way. Autonomous mode never edits code, never posts, and never asks.
24
+
25
+ ## DELIVER
26
+
27
+ 1. Write `report.json` (validate against `report.schema.json`) and `report.md`; print `report.md` in chat with the run directory path. Start with counts, then accepted findings, then deferred ones.
28
+ 2. Standard and deep depth: create a beads epic for the run and one child bead per accepted finding, carrying the finding's evidence, proposal and test protection. Without `bd`, list the findings in the report and say so in `gaps`.
29
+ 3. Draft a PR or MR comment in `comment_draft` when the target is a branch with an open PR. Post it only after the user confirms; autonomous mode never posts.
30
+ 4. Plan only. Hand accepted beads to the coder on approval; this skill changes no source file. Hand deep test-suite work to `quality-test-audit`.
31
+ 5. List every gap: missing analyzers, benchmarks not run, areas not read, lenses skipped.
@@ -0,0 +1,21 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/srobroek/harness-plugins/plugins/code-challenge/decisions.schema.json",
4
+ "title": "code-challenge decision",
5
+ "description": "One line of decisions.jsonl. Append-only; one object per line.",
6
+ "type": "object",
7
+ "required": ["ts", "run_id", "phase", "kind", "subject", "choice", "reason", "by"],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "ts": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" },
11
+ "run_id": { "type": "string", "pattern": "^[0-9]{8}-[0-9]{6}-[a-z0-9-]{1,24}$" },
12
+ "phase": { "enum": ["INTAKE", "SCAN", "CHALLENGE", "RESEARCH", "REFUTE", "DECIDE", "DELIVER"] },
13
+ "kind": { "enum": ["decision", "blocker", "ambiguity", "choice", "inference"] },
14
+ "subject": { "type": "string", "minLength": 1 },
15
+ "choice": { "type": "string", "minLength": 1 },
16
+ "reason": { "type": "string", "minLength": 1 },
17
+ "by": { "enum": ["user", "agent", "autonomous-rule"] },
18
+ "finding_id": { "type": "string", "pattern": "^F[0-9]+$" },
19
+ "alternatives": { "type": "array", "items": { "type": "string", "minLength": 1 } }
20
+ }
21
+ }
@@ -0,0 +1,17 @@
1
+ # Evidence rule
2
+
3
+ Every finding carries one evidence tier. Without a tier and a locator (`path:line`), a finding does not exist.
4
+
5
+ | Tier | Meaning | Examples |
6
+ |---|---|---|
7
+ | `proven` | A reader can confirm it from a tool result or a quoted fact, without trusting you | a failing test, the count of callers from LSP references, a registry or OSV record, an analyzer hit confirmed by a reachability search |
8
+ | `measured` | A number from a command run on this code | benchmark with noise, install size, call count, build time |
9
+ | `hypothesis` | Argued from reading; not confirmed | plausible hot path, a branch you could not exercise, a fit not yet checked against call sites |
10
+
11
+ Rules:
12
+ - MUST Put the command or the source (URL, file and line) in `evidence.detail` or `evidence.command`.
13
+ - MUST Mark a performance, speed, size or memory claim `measured` or `hypothesis`; never `proven`.
14
+ - NOT Upgrade a tier because several lenses agree. Agreement is not evidence.
15
+ - NOT Report an analyzer hit alone as `proven`; analyzers have false positives (dynamic dispatch, macros, generated code, framework conventions).
16
+ - An analyzer hit for a rule that the repository does not enable is tagged "rule not enabled in repo" and still needs its own evidence. Respect the repository's suppressions (`# noqa`, `//nolint`, `eslint-disable`, per-file ignores): a suppression with a reason is a decision, not a finding.
17
+ - A finding that changes a public signature, wire format, config key or documented behaviour sets `changes_contract: true` and never carries `blast_radius: low`. "Public" is the public surface in [intake-questions.md](intake-questions.md): an export that is not an entry point, a registered surface or documented, and has no importer outside its module tree, is internal; removing it changes no contract.
@@ -0,0 +1,49 @@
1
+ # Intake questions
2
+
3
+ Phase INTAKE. Ask in one batch with `parley_ask`; fall back to the `question` tool when parley is absent. Put a recommended answer on every question. Autonomous mode asks only what the command arguments and the repository cannot answer, and logs each inference to `decisions.jsonl` with kind `inference`.
4
+
5
+ | # | Question | Default when unanswered | Inferred from (autonomous) |
6
+ |---|---|---|---|
7
+ | 1 | Target: which paths, packages or diff range? | the whole repository | command argument, current branch diff |
8
+ | 2 | Depth: `quick`, `standard` or `deep`? | `standard` | argument; `quick` for a diff under 300 lines |
9
+ | 3 | Lenses: all 13, or a subset? | all 13 | a lens named in the request |
10
+ | 4 | Is pluggability expected (more backends or providers, or frequent change in this area)? | no | see the seam signals below |
11
+ | 5 | Which behaviour is frozen (public API, wire format, config keys, CLI flags)? | the public surface (see below) and everything documented | exports, docs, schema files |
12
+ | 6 | May the run execute benchmarks and build-needing tools? (No: the performance lens is dropped, see [lens-performance.md](lens-performance.md).) | interactive: ask once; autonomous: yes at `standard` and `deep` | depth |
13
+ | 7 | How are tests run, and how long do they take? | the repo's check command | `package.json` scripts, `justfile`, CI |
14
+ | 8 | Deliver beads for accepted findings and a PR comment draft? | beads yes, comment no | an open PR for the branch |
15
+ | 9 | Which documents define what the target must do (spec, plan, decision record, bead, issue, PR description)? | every design source that the search below finds | see the design sources below |
16
+
17
+ ## Public surface (question 5 default)
18
+
19
+ An `export` keyword alone does not make code public. Freeze what a consumer outside the module tree can reach:
20
+ - the package's entry points: the files its manifest names (`main`, `exports`, `bin`, a plugin's registered entry) and what they export;
21
+ - registered tool, command and hook names and their schemas, wire formats, config keys and CLI flags;
22
+ - a shared library's exports that have an importer outside their own package;
23
+ - anything the docs describe.
24
+
25
+ An export that is none of the frozen surfaces above and has no importer outside its own module tree (none in other packages, `tests/` or `scripts/`) is internal. An entry point counts as frozen even with no source importer, because the host loads it through its manifest. Removing an internal export changes no contract: a dead-code finding for it may carry `blast_radius: low` and `changes_contract: false`, provided the reachability searches in [lens-dead-code.md](lens-dead-code.md) found no importer. Log the frozen list to `intake.json`.
26
+
27
+ ## Design sources (question 9, autonomous)
28
+
29
+ The scope lens ([lens-scope.md](lens-scope.md)) reads these sources. Collect every one that exists and covers the target, and log each with its path or id:
30
+ - `specs/<feature>/`: `spec.md`, `plan.md` and `tasks.md`
31
+ - `docs/`, the decision records in `docs/adr/` or `docs/decisions/`, and the README sections about the target
32
+ - the bead named in the branch name or the commit messages: `bd show <id>` gives its description, design and acceptance fields and its parent epic
33
+ - the open PR or MR description, and the issues it links
34
+
35
+ When the search finds no source, the answer is "none", and the scope lens checks only the docs against the code.
36
+
37
+ ## Pluggability signals (question 4, autonomous)
38
+
39
+ Answer yes when at least one holds, and log which one:
40
+ - two or more implementations of one interface, or two or more providers of one kind
41
+ - provider config keys (`provider`, `backend`, `driver`, `adapter`) in config or schema files
42
+ - the roadmap, README or `docs/` mention more backends, providers or plugins
43
+ - an existing `adapters/`, `providers/` or `backends/` directory
44
+
45
+ Answer no otherwise. With no signal, an extra abstraction layer is an OVER-ENGINEERING finding, never a STRUCTURE gap.
46
+
47
+ ## Output
48
+
49
+ Write `intake.json` in the run directory (see [run-storage.md](run-storage.md)): target, depth, lenses, pluggable (bool plus the signal), frozen surfaces, benchmark allowance, test command, delivery choices, design sources.
@@ -0,0 +1,20 @@
1
+ # Lens: dead code
2
+
3
+ Find code nothing reaches.
4
+
5
+ - unused functions, exports, files, dependencies, feature flags that are always one value
6
+ - unreachable branches, commented-out code, parameters never read
7
+ - config keys nobody reads; tests for removed behaviour
8
+
9
+ Analyzer output is a lead, not proof: dynamic dispatch, reflection, framework conventions, public API and generated code hide callers. Before you call code dead, search for string references, dynamic imports, entry points in manifests, docs and other repositories that consume the package.
10
+
11
+ Scope each reachability search to the roots that can consume the code: the module's own tree, the repository's tests and scripts, and the packages that depend on it. Exclude copies that are not consumers: worktrees (`.worktrees/`, `.git/`), generated output (`dist/`, build directories, files a build copies into harness trees) and vendored code. A repository-wide search through those copies is slow and finds the code's own duplicates. When a search times out, narrow its roots and run it again; a timed-out search is a gap, never "no references".
12
+
13
+ ## Evidence needed
14
+
15
+ - `proven`: the analyzer hit plus a search for every reachability path named above, each with its result.
16
+ - `hypothesis`: an analyzer hit alone, or exported API with possible external users.
17
+
18
+ ## Steering
19
+
20
+ `lang-<language>-quality` (dead-code tools per language: knip, vulture, deadcode, cargo-machete), `quality-test-audit` for obsolete tests.
@@ -0,0 +1,21 @@
1
+ # Lens: efficiency (waste)
2
+
3
+ Find work that is done and thrown away, or resources held longer than needed. This is waste, not slowness: the code may be fast and still wasteful.
4
+
5
+ - reading or parsing a file or response more than once; fetching fields nobody uses
6
+ - polling where an event exists; retries without a ceiling; cache missing where the same pure call repeats, or a cache with no invalidation story
7
+ - large copies of data that a borrow, view or stream avoids
8
+ - CI steps, builds or tests that rerun unchanged work; dependencies pulled in for one call
9
+ - idle goroutines, tasks, timers or connections not released
10
+
11
+ Weigh cost against what it saves: a clearer code path often beats a saved millisecond.
12
+
13
+ ## Evidence needed
14
+
15
+ - `proven`: the redundant operation shown twice on one path with `path:line` for each.
16
+ - `measured`: the saved bytes, calls or seconds counted.
17
+ - `hypothesis`: the waste is plausible but the path frequency is unknown.
18
+
19
+ ## Steering
20
+
21
+ `quality-profiling`, `lang-<language>-profiling`, `toolchain-quality-observability` for counting calls and bytes in production.
@@ -0,0 +1,18 @@
1
+ # Lens: hand-rolled code that a third-party library covers (and the reverse)
2
+
3
+ Two directions.
4
+
5
+ Forward: code that re-implements a solved problem no standard library covers (rate limiting, schema validation, diffing, semver, retry with jitter, parsing a niche format).
6
+
7
+ Reverse: a dependency that native code or a lighter library replaces; a dependency used for one function; duplicate libraries for one job; a heavy library where the standard library now suffices.
8
+
9
+ Run RESEARCH for every finding: 2 to 4 candidates scored with [library-scoring.md](library-scoring.md), plus "keep what exists" as a candidate. Evaluate partial adoption plus an extension. Hard gates are an unpatched CVE and an incompatible licence only; maintenance is a weighted signal. Record the migration cost and test protection of the call sites.
10
+
11
+ ## Evidence needed
12
+
13
+ - `proven` for the facts (version, licence, CVE state, release date) with the source URL; `hypothesis` for fit until the call sites and the library's edge-case handling were read.
14
+ - `measured` for size or speed claims, with the command.
15
+
16
+ ## Steering
17
+
18
+ `lang-<language>-libraries` (preferred libraries per language), `quality-code-policy` (a dependency the user did not name needs approval), `challenge_lib_facts` for the facts.
@@ -0,0 +1,20 @@
1
+ # Lens: hand-rolled code that the standard library or framework covers
2
+
3
+ Find code that re-implements what the language's standard library, the runtime or the framework already ships.
4
+
5
+ - manual deep clone, debounce, retry, URL, path, date, UUID or base64 handling
6
+ - hand-written parsers for formats the stdlib reads (JSON, CSV, TOML, query strings)
7
+ - hand-built middleware, routing, validation or logging that the framework provides
8
+ - polyfills for features the minimum supported runtime already has (check the engine range)
9
+ - obsolete idioms flagged by modernisation rules (`modernize`, `UP`, `FURB`)
10
+
11
+ Check the minimum supported version before you propose a newer API. Record test protection: the replacement must keep edge-case behaviour (empty input, unicode, time zones).
12
+
13
+ ## Evidence needed
14
+
15
+ - `proven`: the stdlib or framework doc URL or the `context7` result for the exact API, plus the version in which it appeared, plus a line-by-line list of the edge cases both handle.
16
+ - `hypothesis`: the API exists but an edge case differs or is undocumented.
17
+
18
+ ## Steering
19
+
20
+ `lang-<language>-libraries` (the preferred standard-library and framework choices), `quality-code-policy` (standard library and framework features come before a listed library, before custom code).
@@ -0,0 +1,20 @@
1
+ # Lens: observability
2
+
3
+ Find places where a failure or slowdown would be invisible.
4
+
5
+ - errors logged without context, or logged and rethrown (double logging), or swallowed
6
+ - no request or correlation id across a service boundary; unstructured logs; `print` or `console.log` left in
7
+ - no metric or trace around I/O, queues or retries; high-cardinality labels
8
+ - secrets or personal data in logs; log levels misused
9
+ - health or readiness missing where a platform expects it
10
+
11
+ Prefer the framework's middleware (one place for ids, logs, traces and metrics) over per-call edits, and OpenTelemetry over OTLP as the telemetry standard.
12
+
13
+ ## Evidence needed
14
+
15
+ - `proven`: the call path shown with `path:line` where the signal is missing, and the failure it would hide.
16
+ - `hypothesis`: the signal may exist elsewhere (a sidecar, a gateway). Say where you did not look.
17
+
18
+ ## Steering
19
+
20
+ `toolchain-quality-observability` (the standard stack and checks), `lang-<language>-quality` (log and lint rules), `quality-code-policy` (cross-cutting concerns live in middleware).
@@ -0,0 +1,20 @@
1
+ # Lens: optimisation (algorithm)
2
+
3
+ Find algorithmic cost that a better structure removes. This lens is about complexity class, not machine time; machine time belongs to [lens-performance.md](lens-performance.md).
4
+
5
+ - nested loops over the same collections (O(n*m) where a map lookup gives O(n+m))
6
+ - repeated linear search, `includes` in a loop, sorting inside a loop, repeated regex compile
7
+ - N+1 queries or calls, recomputation of a pure value, missing early exit
8
+ - string building by repeated concatenation in a loop
9
+
10
+ Judge n from the code: unbounded user data or a fixed list of five. A quadratic over five items is no finding.
11
+
12
+ ## Evidence needed
13
+
14
+ - `proven`: the complexity argument plus the origin of n (a request size, a table, a config list) quoted at `path:line`.
15
+ - `measured`: a benchmark at a realistic n shows the cost; the output is in the finding.
16
+ - `hypothesis`: n unknown or the hot path unconfirmed.
17
+
18
+ ## Steering
19
+
20
+ `quality-profiling` before any speed claim, `lang-<language>-profiling` for the language's profiler and benchmark tool.
@@ -0,0 +1,21 @@
1
+ # Lens: over-engineering
2
+
3
+ Find structure that has no second user.
4
+
5
+ - an interface, factory, registry or plugin point with one implementation and no signal that a second is coming
6
+ - configuration for values that never vary; generics with one instantiation
7
+ - layers that only delegate; events or queues where a direct call works
8
+ - extension hooks nobody calls
9
+
10
+ Apply the seam rule shared with [lens-structure.md](lens-structure.md): whether pluggability is expected is a product question answered at INTAKE (or inferred from signals and logged). Where no signal exists, an extra abstraction is an over-engineering finding here, never a structure gap. Where a signal exists, do not flag the seam.
11
+
12
+ Propose the inline form and name what must stay (a public contract, a test seam that tests use). Record test protection.
13
+
14
+ ## Evidence needed
15
+
16
+ - `proven`: count the implementations and callers with `grep` or LSP references and quote the count; confirm no config, doc or roadmap signal for a second user.
17
+ - `hypothesis`: the count is one but a signal is ambiguous. Say which.
18
+
19
+ ## Steering
20
+
21
+ `quality-code-policy` (SOLID and invariants beat YAGNI at real boundaries; YAGNI elsewhere), `architecture-guide` for boundaries.
@@ -0,0 +1,18 @@
1
+ # Lens: performance (measured)
2
+
3
+ Findings here need a measurement. When INTAKE did not allow benchmarks, no finding can reach `measured`: INTAKE drops this lens from `lenses`, logs a `choice` line and names the dropped lens in `gaps`. Scouts file speed suspicions under optimisation or efficiency as `hypothesis`. A run must keep at least one lens, because `report.json` rejects an empty `lenses`: when performance was the only lens, interactive mode asks for a replacement lens, and autonomous mode uses `optimisation` and logs the default as an `inference` line. The report then lists the replacement lens and the gap. A suspicion without one stays a hypothesis and goes to [lens-optimisation.md](lens-optimisation.md) or [lens-efficiency.md](lens-efficiency.md) as that lens's finding.
4
+
5
+ - slow endpoints, builds, tests or start-up named by the user or by CI timings
6
+ - allocation hot spots, lock contention, blocking calls on an async path, serial I/O that can overlap
7
+ - bundle or binary size growth
8
+
9
+ Method: reproduce the cost, profile, name the top frame, estimate the best-case gain from that frame, then propose. Run benchmarks only when INTAKE allowed them (interactive asks once; autonomous allows them at standard and deep). Never run a benchmark against production or shared services.
10
+
11
+ ## Evidence needed
12
+
13
+ - `measured` only: the command, the numbers before, and the noise (repeat runs or the tool's confidence interval). A single run is a `hypothesis`.
14
+ - State the machine and load conditions; a loaded laptop skews numbers.
15
+
16
+ ## Steering
17
+
18
+ `quality-profiling` (method), `lang-go-profiling`, `lang-python-profiling`, `lang-rust-profiling`, `lang-typescript-profiling` (tools per language).
@@ -0,0 +1,31 @@
1
+ # Lens: scope
2
+
3
+ Check the target against its design and its docs. INTAKE question 9 lists the design sources (see [intake-questions.md](intake-questions.md)). Read every source before you read the code.
4
+
5
+ Look for four kinds of gap:
6
+ - missing: a requirement or an acceptance criterion has no code, or only part of it does. A documented flag, option or error case that the code lacks counts too.
7
+ - drift: the code differs from the design or the docs. Examples: another default, another name, another error. Docs that describe behaviour the code lacks count too.
8
+ - unrequested: no design source asks for a feature, flag, endpoint, config key, command or dependency (scope creep).
9
+ - over-built: the design asks for a feature, and the code builds more. Examples: options, modes, formats or generality that the design does not name.
10
+
11
+ Keep one cause as one finding:
12
+ - over-engineering counts the implementations and callers of an abstraction. Scope compares a capability with the design. When a design source decides the question, the finding is scope. Otherwise it is over-engineering.
13
+ - dead code is unreachable. Unrequested code is reachable, but no design source asks for it.
14
+ - the seam rule in [lens-structure.md](lens-structure.md) still holds. A design source that expects more backends is a pluggability signal, so the seam is not over-built.
15
+
16
+ The design can be wrong instead of the code. Every proposal names both options:
17
+ - change the code: implement, align or remove
18
+ - change the design source to record what the code does
19
+
20
+ Removing a reachable feature sets `changes_contract`. Aligning documented behaviour sets it too.
21
+
22
+ With no design source, check the docs against the code (drift) and nothing else. Log a `blocker` line and add the gap `scope: no design source`. Report unrequested and over-built candidates as `hypothesis` at most.
23
+
24
+ ## Evidence needed
25
+
26
+ - `proven`: quote the design line (`path:line`, or the bead id and field) beside the code locator. For a missing item, list the searches that found no implementation, each with its command and result. For unrequested code, list the searches of every design source that found no mention.
27
+ - `hypothesis`: the design is silent or ambiguous, the code is newer than the design, or the README is the only source. Say which, and quote what the source says.
28
+
29
+ ## Steering
30
+
31
+ `quality-code-policy` (YAGNI, research-first reuse), `architecture-guide` for the documented architecture.
@@ -0,0 +1,23 @@
1
+ # Lens: simplification
2
+
3
+ Find code that does in many steps what fewer would do, keeping behaviour identical.
4
+
5
+ - nested conditionals that flatten with early returns or a lookup table
6
+ - a loop that rebuilds what a standard collection method gives
7
+ - needless intermediate variables, wrapper functions that only forward, boolean flags that select between two functions
8
+ - state kept in two places, or a conversion to a type and straight back
9
+ - repeated option or error handling a single helper would hold
10
+
11
+ Keep this lens apart from over-engineering: simplification shortens code that is needed; over-engineering removes structure nobody needs (see [lens-over-engineering.md](lens-over-engineering.md)).
12
+
13
+ Record test protection on every finding: `protected` (a test fails if behaviour changes), `partial` or `unprotected`. An unprotected simplification that touches branches gets a note to add a test first.
14
+
15
+ ## Evidence needed
16
+
17
+ - `proven`: the two forms are equivalent by reading both and by a test or type check that exercises every branch removed. Name the test.
18
+ - `hypothesis`: equivalence argued by reading only. Say which branch you could not exercise.
19
+ - Never `measured`: a simplification claims no speed.
20
+
21
+ ## Steering
22
+
23
+ `quality-code-policy`, `lang-<language>-quality` for the language's idioms, `quality-test-audit` when protection is missing across a whole module.
@@ -0,0 +1,21 @@
1
+ # Lens: stability
2
+
3
+ Find code that fails under conditions it will meet.
4
+
5
+ - swallowed errors, broad catch or bare `except`, ignored return values, `unwrap` or non-null assertions on external data
6
+ - missing timeouts, cancellation, retries with backoff, or limits on size, depth and concurrency
7
+ - races: shared mutable state, check-then-act on files or rows, non-atomic writes
8
+ - resource leaks: files, sockets, processes, temp directories, listeners
9
+ - unclear failure behaviour at boundaries (partial writes, half-applied batches)
10
+ - unsafe assumptions: clock, locale, path separators, encoding
11
+
12
+ Name the trigger: the input or event that makes it fail.
13
+
14
+ ## Evidence needed
15
+
16
+ - `proven`: a failing test or a reproduction command with output; or a type or lint rule that flags it.
17
+ - `hypothesis`: a trigger argued from the code and not reproduced. Say what would reproduce it.
18
+
19
+ ## Steering
20
+
21
+ `lang-<language>-quality` (error handling and lint rules), `quality-code-policy`, `toolchain-quality-observability` for the signals that show the failure in production.
@@ -0,0 +1,26 @@
1
+ # Lens: structure
2
+
3
+ Find code organised in a way that hurts change.
4
+
5
+ - duplication of knowledge that changes together (not merely similar text)
6
+ - coupling: modules that know each other's internals; dependency cycles; wrong dependency direction
7
+ - cohesion: a module that does unrelated jobs; god modules and god classes; long parameter lists that hide a missing type
8
+ - boundaries: layers crossed, domain code that imports transport or storage
9
+ - naming that misleads
10
+
11
+ ## Abstraction seams
12
+
13
+ Where the product expects pluggable code, frequent change, or more backends or providers, flag business logic tied directly to one backend: SDK calls, database clients, HTTP clients or provider APIs scattered through the domain. Propose the right seam: a port and adapter interface, the framework's middleware (Hono, ASGI, tower or `net/http` wrappers), or a standard abstraction library.
14
+
15
+ Whether pluggability is expected is a product question. INTAKE asks it in interactive mode; autonomous mode infers it from signals (see [intake-questions.md](intake-questions.md)) and logs the inference to `decisions.jsonl`. With no signal, extra abstraction is an over-engineering finding in [lens-over-engineering.md](lens-over-engineering.md), never a gap here. The two lenses share this rule so they never contradict each other.
16
+
17
+ Record test protection. Hand deep restructuring to the refactor mode of the coder after approval.
18
+
19
+ ## Evidence needed
20
+
21
+ - `proven`: the import graph, a duplication count with locations, or a cycle listing, from a tool or from `grep` output.
22
+ - `hypothesis`: a judgement about cohesion or naming. Name the signal that would change your mind.
23
+
24
+ ## Steering
25
+
26
+ `architecture-guide`, `architecture-ownership`, `quality-code-policy`, `lang-<language>-quality`.
@@ -0,0 +1,20 @@
1
+ # Lens: tests (light, static)
2
+
3
+ A light static pass over tests that protect the challenged code. This lens never runs the suite and never rewrites tests; deep work goes to `quality-test-audit`, which stays standalone.
4
+
5
+ - missing tests for the code a finding challenges
6
+ - tests that mirror the implementation (assert on internal calls or copy the logic)
7
+ - cases that differ only in data and should be parametrised
8
+ - sleeps and fixed waits instead of conditions
9
+ - a test that cannot fail (no assertion, assertion on a constant)
10
+
11
+ Every simplification, library and structure finding already records `test_protection`; this lens covers the tests themselves.
12
+
13
+ ## Evidence needed
14
+
15
+ - `proven`: the test file and line, and the quoted pattern.
16
+ - `hypothesis`: protection inferred from names only; you did not read the assertions.
17
+
18
+ ## Steering
19
+
20
+ `quality-testing`, `quality-test-audit` (the deep audit; recommend it, never inline it), `lang-<language>-quality`.
@@ -0,0 +1,54 @@
1
+ # Library scoring
2
+
3
+ Phase RESEARCH, for the two library lenses: hand-rolled code that a library replaces, and the reverse (a dependency that native code or a lighter library replaces).
4
+
5
+ Collect facts with `challenge_lib_facts` and `context7` for API coverage. Never score from memory.
6
+
7
+ ## The facts tool
8
+
9
+ Input: `{ ecosystem: "npm" | "pypi" | "crates" | "go", packages: [{ name, version? }] }`, 1 to 6 packages. Pass `version` to get the OSV advisories of the version the repository uses. Output: `{ ecosystem, fetchedAt, packages[] }`, facts only and no verdict. Each package has:
10
+
11
+ - `latest {version, publishedAt}`, `releases {last12Months, last24Months, monthsSinceLast}`, `deprecated`, `yanked`
12
+ - `licence` (SPDX ids), `downloads {lastWeek, lastMonth, last90Days}`, `dependents`, `dependencies {direct, transitive}`, `size {unpackedBytes, downloadBytes}`, `types`, `modules` (npm: `esm`, `cjs` or `dual`)
13
+ - `repo {url, stars, openIssues, openPullRequests, lastCommit, contributors, archived}`
14
+ - `vulnerabilities {latest[], requested[]}`: OSV ids, fetched fresh on every call
15
+ - `gates {unpatchedCve, licenceNotAllowed, failed[]}`: the two hard gates below, from the latest version's advisories and the licence allowlist
16
+ - `missing[]`: each source that failed, as `<source>: <reason>`
17
+
18
+ A field is `null` when no source gave it, and a gate is `null` when its data is missing. Treat a `null` gate as unknown, not as a pass: read the registry page or the OSV record with `webfetch` and cite the URL. Everything except OSV is cached for 7 days. `gates.unpatchedCve` means the latest version still carries an advisory; for the version the repository uses, compare `vulnerabilities.requested` with `vulnerabilities.latest` to see whether upgrading fixes it.
19
+
20
+ Pick 2 to 4 candidates, including "keep the hand-rolled code" as a candidate. Evaluate partial adoption plus an extension over a full swap when the library covers most of the need.
21
+
22
+ ## Gates
23
+
24
+ A candidate that trips a gate scores nothing and is listed as rejected with the reason. Only two gates exist:
25
+ 1. An unpatched CVE in the version range the repository would use (OSV record with no fixed release).
26
+ 2. A licence incompatible with the repository's own.
27
+
28
+ Maintenance is a weighted signal, never a gate.
29
+
30
+ ## Weights
31
+
32
+ Total 100, ranked fit > compat > stability > maintained > popularity > footprint > migration.
33
+
34
+ | Criterion | Weight | Scores 0 to 1 by |
35
+ |---|---|---|
36
+ | fit | 30 | share of the needed behaviour covered, edge cases included (read the docs and issues, not the README) |
37
+ | compat | 20 | works with the repo's runtime, language version, framework and existing dependencies |
38
+ | stability | 15 | semver discipline, changelog quality, breaking-change history, 1.0 or later |
39
+ | maintained | 12 | last release inside 12 months scores at least 0.5; 12 months without a release and with open unanswered security issues scores 0 |
40
+ | popularity | 8 | downloads and dependents, relative to alternatives |
41
+ | footprint | 8 | install size, transitive dependencies, build cost |
42
+ | migration | 7 | call sites to change, test protection of those sites, API shape difference |
43
+
44
+ `score = sum(weight * value)`. Report the per-criterion values, not only the total. A candidate beats "keep" only with a margin of at least 10 points over the existing option's score and a fit of at least 0.7. Both numbers are tunable defaults: a repository or the user may set another margin or fit floor at INTAKE, and the report then states the values it used.
45
+
46
+ ## Reverse direction
47
+
48
+ For each direct dependency used for one or two functions, ask whether the standard library or framework now covers it, or a lighter library does. For JavaScript, check the e18e replacement lists (`@e18e/depend` reads them). Score the same way, with "keep the dependency" as the baseline.
49
+
50
+ ## Evidence
51
+
52
+ A swap claim is `measured` only when the benchmark or install-size output is in the report. A claim from registry data is `proven` for the fact (version, licence, CVE) and `hypothesis` for the fit until the call sites were read.
53
+
54
+ See `lang-*-libraries` for the repository's preferred libraries per language, and `quality-code-policy` for the rule that a dependency the user did not name needs approval.