From 7e4cfe1aa164d722cbd4c718311c1687d205776f Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:56:55 +0200 Subject: [PATCH] feat(efficacy): round 5e's map arms, the templates read or loaded on demand Two fixed-text arms made from round 5's chain and the templates' manifest, with no model call: `lazyref` maps each template's topics to the vendored file to read when the work first touches them, `lazyskills` maps the same topics to a skill holding that template verbatim. The two roots name the same moments in the same order, so the arms differ in the loading mechanism alone. The harness knows both arms, builds them from round 5's spec, and proves the agent sees any arm's skills before a run. The report names them in plain words. Round 5e's registration states the arms, the order, H7 to H9 and what the report still needs. Closes #135's groundwork; #85, #134. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DpT5xNajarzjtZvD46RAGT --- docs/architecture/05-building-block-view.md | 2 +- docs/coverage.md | 1 + docs/requirements.md | 1 + docs/rounds/README.md | 1 + docs/rounds/round-5e.md | 176 +++++++++++ tests/efficacy/arms/lazyref/CLAUDE.md | 22 ++ tests/efficacy/arms/lazyref/generation.json | 110 +++++++ tests/efficacy/arms/lazyskills/CLAUDE.md | 22 ++ .../efficacy/arms/lazyskills/generation.json | 125 ++++++++ .../lazyskills/skills/backend-api/SKILL.md | 103 +++++++ .../lazyskills/skills/backend-auth/SKILL.md | 92 ++++++ .../skills/backend-database/SKILL.md | 75 +++++ .../lazyskills/skills/backend-http/SKILL.md | 132 +++++++++ .../skills/base-data-governance/SKILL.md | 81 ++++++ .../skills/base-data-modeling/SKILL.md | 72 +++++ .../arms/lazyskills/skills/base-docs/SKILL.md | 182 ++++++++++++ .../arms/lazyskills/skills/base-git/SKILL.md | 147 ++++++++++ .../lazyskills/skills/base-quality/SKILL.md | 275 ++++++++++++++++++ .../lazyskills/skills/base-review/SKILL.md | 188 ++++++++++++ .../lazyskills/skills/base-security/SKILL.md | 266 +++++++++++++++++ .../lazyskills/skills/base-testing/SKILL.md | 238 +++++++++++++++ .../lazyskills/skills/frontend-ux/SKILL.md | 86 ++++++ tests/efficacy/generate_arm.py | 212 +++++++++++++- tests/efficacy/harness.py | 37 ++- tests/efficacy/report.py | 4 + 25 files changed, 2634 insertions(+), 16 deletions(-) create mode 100644 docs/rounds/round-5e.md create mode 100644 tests/efficacy/arms/lazyref/CLAUDE.md create mode 100644 tests/efficacy/arms/lazyref/generation.json create mode 100644 tests/efficacy/arms/lazyskills/CLAUDE.md create mode 100644 tests/efficacy/arms/lazyskills/generation.json create mode 100644 tests/efficacy/arms/lazyskills/skills/backend-api/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/backend-auth/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/backend-database/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/backend-http/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-data-governance/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-data-modeling/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-docs/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-git/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-quality/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-review/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-security/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/base-testing/SKILL.md create mode 100644 tests/efficacy/arms/lazyskills/skills/frontend-ux/SKILL.md diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index c4c4474..99b419f 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -35,7 +35,7 @@ dependency with its keyword. | `SPEC-thin.md` | The same contract without the practices, for `--spec thin` | harness | | `brief.txt` | What an adopter would type: domain, stack, personal data, boundaries | `generate_arm.py` | | `change-prompt.txt` | The change task's prompt, naming everything its grader drives | harness | -| `arms//CLAUDE.md` | Each arm's context file. `arms/skills/skills/` holds the skills arm's skills | harness | +| `arms//CLAUDE.md` | Each arm's context file. `arms//skills/` holds a skills arm's skills | harness | | `arms//generation.json` | How each generated file was made | `report.py` | | `scoring-requirements.txt` | The scoring tools, resolved once into the tool lock | `score.py` | | `toolconfig/` | `ruff.toml` and `mypy.ini`, the one configuration every arm is measured under | `score.py` | diff --git a/docs/coverage.md b/docs/coverage.md index 01353e5..e691fac 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -180,6 +180,7 @@ when: | FR-13-03 | Self-test | `archive.py` "readings, judgings, map and lock come; bundles do not"
`archive.py` "the original tarball's hash is recorded"
`archive.py` "the revisions are recorded"
`archive.py` "a reading changed in the archive fails the verify" | | FR-13-04 | Self-test | `archive.py` "a reading changed after the stamp is a problem"
`archive.py` "the report refuses docs/audits/ without a current stamp"
`report.py` "a report into a templates source's docs/audits needs the stamp" | | FR-13-05 | Self-test | `archive.py` "the restored root reads as the original does"
`archive.py` "a restored record points at the restored tarball and void"
`archive.py` "a restored transcript keeps its time" | +| FR-13-06 | Self-test | `generate_arm.py` "the two map arms name the same moments in the chain's order"
`generate_arm.py` "the reading map names every template of the chain once, under docs/solid-ai-templates/"
`generate_arm.py` "each template skill is its template verbatim, named by the manifest"
`generate_arm.py` "a chain file the manifest does not describe is refused" | ## 14 One run at a time diff --git a/docs/requirements.md b/docs/requirements.md index cc98047..4f63cfb 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -188,6 +188,7 @@ | FR-13-03 | The benchmark shall archive every reading, judging, map and lock, with a hash per file, and fail the verify on a changed one. | Archive | | FR-13-04 | The benchmark shall refuse to write a report under `docs/audits/` once a reading changed since the archive was verified. | Archive, Report | | FR-13-05 | The benchmark shall restore an archive so it reads as the original root does, its records pointing at the restored files. | Archive | +| FR-13-06 | The benchmark shall build a map arm's root from the chain and the templates' manifest alone, the same moments in the same order for both map arms, and each `lazyskills` skill holding one template verbatim. | Arm generator | ### 14 One run at a time diff --git a/docs/rounds/README.md b/docs/rounds/README.md index 9f9d958..b871015 100644 --- a/docs/rounds/README.md +++ b/docs/rounds/README.md @@ -22,6 +22,7 @@ the specification, `M` the builder model and `T` the task | [Round 5b](round-5b.md) | 2026-10-29, after round 5 stopped; stopped after its first start | Round 5's question, with a prompt that tells every arm the spec is the approved plan | | [Round 5c](round-5c.md) | 2026-10-29, after round 5b stopped | Round 5b's question, with each trial's workspace in a pen of its own | | [Round 5d](round-5d.md) | 2026-10-31, while round 5c ran | Whether a person's short file does what the templates do, at their length and at its own | +| [Round 5e](round-5e.md) | 2026-11-05, while round 5d ran | Whether a template read at the moment the work touches its topics does what one read up front does, as a file and as a skill | ## Reports diff --git a/docs/rounds/round-5e.md b/docs/rounds/round-5e.md new file mode 100644 index 0000000..f0b766a --- /dev/null +++ b/docs/rounds/round-5e.md @@ -0,0 +1,176 @@ +# Round 5e registration + +Registered on 2026-11-05, while round 5d ran and before any round-5e trial ran. +Round 5d keeps its registration as it was when its first trial ran; this one is +a registration of its own. + +## 13e. Round 5e: the templates on demand, against rounds 5c and 5d + +### 13e.1 What it takes from rounds 5c and 5d + +Round 5e runs [round 5d's registration](round-5d.md) as it stands at `1baac26`: +block A, the spec at its registered sha256, `claude-sonnet-5` at effort `high`, +round 5b's prompt, the pen, the judge, the scoring on Python 3.12, the CLI +pinned at 2.1.314, the verdict rules of 13d.7, the radar of 13d.8 and the +round-6 screen of 13d.9. + +The hidden suite is the revision at `8caaaa3`: the same tests as round 5d's +(the build imported afresh for every test), plus entry 9 of its ambiguities +file, which grades nothing new. + +Three things differ: the arms, the order, and what is reused. + +### 13e.2 The arms + +| Arm | Trials | Where they come from | +| --- | --- | --- | +| `lazyref` | 15, fresh | `arms/lazyref/CLAUDE.md`, made for 5e | +| `lazyskills` | 15, fresh | `arms/lazyskills/`, root and 13 skills, made for 5e | +| `none`, `reference`, `skills` | 15 each, reused | Round 5c's, re-scored in 5d's root | +| `hand`, `short` | 15 each, reused | Round 5d's, scored and read | + +Both fresh arms live under `tests/efficacy/arms/`. They are fixed text, made by +`generate_arm.py` from round 5's chain at `9086e0ff` and the templates' +manifest, with no model call. Each row of their table is one template of the +chain, in the chain's order, and the moment that calls for it is the manifest's +own one-line description of that template. No person chose the moments, and the +two arms take them from the same source, so their tables differ in one column +alone. + +**`lazyref`** maps each moment to the vendored template file. + +- The root says: do not read the templates before the work starts; the first + time the work touches a template's topics, read that template and apply every + rule it holds that fits this project. +- The templates are vendored at `docs/solid-ai-templates/` at the recorded ref, + as `reference` vendors them. +- 22 lines and 2,088 bytes, sha256 + `8c7f7698568643823988e4f9a7e4ade9d30f3965cb065e1dd7ee4117050b5d67`, with its + generation record beside it. + +**`lazyskills`** maps each moment to a skill holding that template. + +- The root says the same, with "load that template's skill" in place of "read + that template". +- Thirteen skills under `.claude/skills/`, one per template of the chain, each + named by the template's manifest id, described by the manifest's one line, + and holding the template verbatim: 76,023 bytes in all. +- 22 lines and 1,535 bytes, sha256 + `f98060a1d04263b6a630728d614d38ed2efc14385c07c789aad157883dffc5de`, with its + generation record beside it. + +**The reused arms** come with round 5d's root and tool lock, so every contrast +is graded by one suite. + +Why: round 5c's `reference` is lazy in packaging only. Its root says "before +starting work, read each template below", and 13 of its 15 agents read all 13 +templates whole before the first line of code, 161 KB in two turns. Its +`skills` arm, whose skills were offered by description alone, loaded none of +them. So no pilot arm has yet measured a rule read at the moment it applies. +Round 5e asks that question twice, once with a file read and once with a skill +load, and nothing else differs between its two arms. + +### 13e.3 The order + +One run of `lazyref` and `lazyskills` at K = 15, in a run root of round 5e's +own: 30 trials in the rotated order. + +- The run starts `lazyref-1`, `lazyskills-1`, and each block starts one arm + later. +- The two arms share every block, so `lazyskills` minus `lazyref` is paired. +- No fresh `none`, `reference` or `skills` runs beside them, so drift against + rounds 5c and 5d goes unchecked, as in round 5d. The CLI is pinned. + +### 13e.4 Hypotheses + +A contrast with a round 5c or round 5d arm is unpaired, read as 13d.4 reads +one. The paired contrast is read as 13d.4 reads H6. + +**H7, on demand against up front.** A template read when the work touches its +topics delivers at least what the same template read before the work starts +delivers. + +| | | +| --- | --- | +| Contrast | `lazyref` minus round 5c's `reference`, unpaired | +| Primary rows | the round's primary rows, below | +| Supported | every primary row is held or better | +| Refuted | any primary row is worse | + +**H8, a skill against a file.** Loading a template as a skill delivers at least +what reading it as a file delivers, the moments being the same. + +| | | +| --- | --- | +| Contrast | `lazyskills` minus `lazyref`, paired within the block | +| Primary rows | the round's primary rows, below | +| Supported | every primary row is held or better | +| Refuted | any primary row is worse | + +**H9, one skill per template against one skill per task.** Templates loaded +whole as skills, at a named moment, deliver at least what task skills offered +by description deliver. + +| | | +| --- | --- | +| Contrast | `lazyskills` minus round 5c's `skills`, unpaired | +| Primary rows | the round's primary rows, below | +| Supported | every primary row is held or better | +| Refuted | any primary row is worse | + +**The primary rows** are round 5d's: the hidden suite's pass rate, the security +and data-protection probe pass rates, each on working builds, and the judge's +security and data-protection rows. Reliability is a row of its own, as 13d.7 +says. Adherence is printed without a verdict. + +H7 to H9 are read under the rules of 13d.7, and each verdict is printed with +its confidence and the arm's profile. + +**Against `none`, no hypothesis.** Each fresh arm is read against round 5c's +`none` by the rules of 13d.7, with no verdict of its own: the reading feeds the +round-6 screen of 13d.9, which round 5e's arms join as candidates. + +**Secondary, no verdict:** + +- every metric of [ch. 8.6](../architecture/08-crosscutting-concepts.md) for + each fresh arm against round 5c's `none`, `reference` and `skills` and round + 5d's `hand` and `short`; +- cost, turns, tokens and wall time, and the words each arm puts in context on + every turn; +- **use of the map**, per trial, from the transcript: how many templates the + agent read (`lazyref`, a read of a file under the vendored path) or loaded + (`lazyskills`, a skill call naming one of the arm's skills), which ones, the + turn each happened at, and how many happened before the trial's first write + to a file of its own. Round 5c's `reference` read 13 of 13 in turns 1 and 2; + a map arm that does the same has not measured on-demand reading, and the + report says so beside H7. + +### 13e.5 Before the first trial + +Done with this registration: + +- `generate_arm.py` makes the two map arms from the chain and the manifest, the + same moments in the same order for both, and refuses a chain file the + manifest does not describe +- both arms are generated and committed with their records +- the harness reads them from their files, vendors the templates for `lazyref`, + places the skills for `lazyskills`, proves before the run that the agent sees + them, and builds both from round 5's spec at its registered content +- the report names both arms in plain words + +The report still gains, with a self-test for each: + +- round 5c's `reference` and `skills` and round 5d's `hand` and `short` read + with their scores, judgings, security readings and tool lock, as 13d.5 reads + round 5c's `none` +- the contrasts of H7 and H9, unpaired, and H8, paired +- the use-of-the-map rows of 13e.4, read from the transcripts +- the round-6 screen of 13d.9 with round 5e's arms among the candidates + +### 13e.6 When it runs + +After round 5d's last trial is in, scored, judged and reported. Its 30 trials +take about 20 hours at round 5c's pace and spend the plan's limit, so the run +waits for the owner's go. + +Nothing in this registration changes once a round-5e trial has run. diff --git a/tests/efficacy/arms/lazyref/CLAUDE.md b/tests/efficacy/arms/lazyref/CLAUDE.md new file mode 100644 index 0000000..8aa9a64 --- /dev/null +++ b/tests/efficacy/arms/lazyref/CLAUDE.md @@ -0,0 +1,22 @@ +# tariff + +The project's rules are the templates below, one per topic. Do not read them +before the work starts. The first time the work touches a template's topics, +read that template, vendored at `docs/solid-ai-templates/` at the revision the +project adopted; then apply every rule it holds that fits this project. + +| When the work first touches | Read first | +| --- | --- | +| Architecture, code style, calibration, tool trust, testing | `docs/solid-ai-templates/templates/core/quality.md` | +| Committer identity, branching, pull requests, CI evidence, regenerated artifacts, off-limits paths, .gitignore | `docs/solid-ai-templates/templates/core/git.md` | +| Rule language, standard documents, upkeep, line width, writing style, diagrams, generated files, agent output files | `docs/solid-ai-templates/templates/core/docs.md` | +| Test types, isolation, assertions, proving a change | `docs/solid-ai-templates/templates/core/testing.md` | +| Peer review priority, MUST/SHOULD checklists, deviation rules | `docs/solid-ai-templates/templates/core/review.md` | +| Port, lifecycle, admin tasks, handlers, headers, methods, payloads, errors, auth | `docs/solid-ai-templates/templates/backend/http.md` | +| API-first, contracts, versioning, deprecation, pagination | `docs/solid-ai-templates/templates/backend/api.md` | +| Application security rules — input, output, injection, auth, sessions, TLS, headers | `docs/solid-ai-templates/templates/security/security.md` | +| Authn/authz, JWT, RBAC, sessions, API keys | `docs/solid-ai-templates/templates/backend/auth.md` | +| Migrations, transactions, parameterised queries, connection pooling | `docs/solid-ai-templates/templates/backend/database.md` | +| UX principles, WCAG 2.1 AA, accessibility testing, design system, browser support | `docs/solid-ai-templates/templates/frontend/ux.md` | +| Schema design, naming, normalization, relationships, data types | `docs/solid-ai-templates/templates/data/data-modeling.md` | +| Classification, PII handling, retention, ownership, audit trail | `docs/solid-ai-templates/templates/data/data-governance.md` | diff --git a/tests/efficacy/arms/lazyref/generation.json b/tests/efficacy/arms/lazyref/generation.json new file mode 100644 index 0000000..ad0b00c --- /dev/null +++ b/tests/efficacy/arms/lazyref/generation.json @@ -0,0 +1,110 @@ +{ + "arm": "lazyref", + "kind": "map", + "output_model": null, + "ref": "9086e0ff", + "source": { + "remote": "https://github.com/solid-ai-dev/solid-ai-templates.git", + "ref": "9086e0ff", + "commit": "9086e0ffc454fbff1d234601822257ce5e40a004" + }, + "roots": [ + "backend-api", + "backend-auth", + "backend-database", + "frontend-ux", + "base-security", + "base-data-governance" + ], + "started_at": "2026-11-05T09:51:58", + "commit": "9086e0ffc454fbff1d234601822257ce5e40a004", + "resolved_files": [ + "templates/core/quality.md", + "templates/core/git.md", + "templates/core/docs.md", + "templates/core/testing.md", + "templates/core/review.md", + "templates/backend/http.md", + "templates/backend/api.md", + "templates/security/security.md", + "templates/backend/auth.md", + "templates/backend/database.md", + "templates/frontend/ux.md", + "templates/data/data-modeling.md", + "templates/data/data-governance.md" + ], + "load": "read", + "moments": [ + { + "skill": "base-quality", + "moment": "Architecture, code style, calibration, tool trust, testing", + "file": "templates/core/quality.md" + }, + { + "skill": "base-git", + "moment": "Committer identity, branching, pull requests, CI evidence, regenerated artifacts, off-limits paths, .gitignore", + "file": "templates/core/git.md" + }, + { + "skill": "base-docs", + "moment": "Rule language, standard documents, upkeep, line width, writing style, diagrams, generated files, agent output files", + "file": "templates/core/docs.md" + }, + { + "skill": "base-testing", + "moment": "Test types, isolation, assertions, proving a change", + "file": "templates/core/testing.md" + }, + { + "skill": "base-review", + "moment": "Peer review priority, MUST/SHOULD checklists, deviation rules", + "file": "templates/core/review.md" + }, + { + "skill": "backend-http", + "moment": "Port, lifecycle, admin tasks, handlers, headers, methods, payloads, errors, auth", + "file": "templates/backend/http.md" + }, + { + "skill": "backend-api", + "moment": "API-first, contracts, versioning, deprecation, pagination", + "file": "templates/backend/api.md" + }, + { + "skill": "base-security", + "moment": "Application security rules \u2014 input, output, injection, auth, sessions, TLS, headers", + "file": "templates/security/security.md" + }, + { + "skill": "backend-auth", + "moment": "Authn/authz, JWT, RBAC, sessions, API keys", + "file": "templates/backend/auth.md" + }, + { + "skill": "backend-database", + "moment": "Migrations, transactions, parameterised queries, connection pooling", + "file": "templates/backend/database.md" + }, + { + "skill": "frontend-ux", + "moment": "UX principles, WCAG 2.1 AA, accessibility testing, design system, browser support", + "file": "templates/frontend/ux.md" + }, + { + "skill": "base-data-modeling", + "moment": "Schema design, naming, normalization, relationships, data types", + "file": "templates/data/data-modeling.md" + }, + { + "skill": "base-data-governance", + "moment": "Classification, PII handling, retention, ownership, audit trail", + "file": "templates/data/data-governance.md" + } + ], + "budget": null, + "output_leak": null, + "outcome": "generated", + "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark\\tests\\efficacy\\arms\\lazyref\\CLAUDE.md", + "output_lines": 22, + "output_words": 229 +} \ No newline at end of file diff --git a/tests/efficacy/arms/lazyskills/CLAUDE.md b/tests/efficacy/arms/lazyskills/CLAUDE.md new file mode 100644 index 0000000..e49453f --- /dev/null +++ b/tests/efficacy/arms/lazyskills/CLAUDE.md @@ -0,0 +1,22 @@ +# tariff + +The project's rules are the templates below, one per topic. Do not read them +before the work starts. The first time the work touches a template's topics, +load that template's skill; then apply every rule it holds that fits this +project. + +| When the work first touches | Load first | +| --- | --- | +| Architecture, code style, calibration, tool trust, testing | `base-quality` | +| Committer identity, branching, pull requests, CI evidence, regenerated artifacts, off-limits paths, .gitignore | `base-git` | +| Rule language, standard documents, upkeep, line width, writing style, diagrams, generated files, agent output files | `base-docs` | +| Test types, isolation, assertions, proving a change | `base-testing` | +| Peer review priority, MUST/SHOULD checklists, deviation rules | `base-review` | +| Port, lifecycle, admin tasks, handlers, headers, methods, payloads, errors, auth | `backend-http` | +| API-first, contracts, versioning, deprecation, pagination | `backend-api` | +| Application security rules — input, output, injection, auth, sessions, TLS, headers | `base-security` | +| Authn/authz, JWT, RBAC, sessions, API keys | `backend-auth` | +| Migrations, transactions, parameterised queries, connection pooling | `backend-database` | +| UX principles, WCAG 2.1 AA, accessibility testing, design system, browser support | `frontend-ux` | +| Schema design, naming, normalization, relationships, data types | `base-data-modeling` | +| Classification, PII handling, retention, ownership, audit trail | `base-data-governance` | diff --git a/tests/efficacy/arms/lazyskills/generation.json b/tests/efficacy/arms/lazyskills/generation.json new file mode 100644 index 0000000..dfc41dc --- /dev/null +++ b/tests/efficacy/arms/lazyskills/generation.json @@ -0,0 +1,125 @@ +{ + "arm": "lazyskills", + "kind": "map", + "output_model": null, + "ref": "9086e0ff", + "source": { + "remote": "https://github.com/solid-ai-dev/solid-ai-templates.git", + "ref": "9086e0ff", + "commit": "9086e0ffc454fbff1d234601822257ce5e40a004" + }, + "roots": [ + "backend-api", + "backend-auth", + "backend-database", + "frontend-ux", + "base-security", + "base-data-governance" + ], + "started_at": "2026-11-05T09:52:07", + "commit": "9086e0ffc454fbff1d234601822257ce5e40a004", + "resolved_files": [ + "templates/core/quality.md", + "templates/core/git.md", + "templates/core/docs.md", + "templates/core/testing.md", + "templates/core/review.md", + "templates/backend/http.md", + "templates/backend/api.md", + "templates/security/security.md", + "templates/backend/auth.md", + "templates/backend/database.md", + "templates/frontend/ux.md", + "templates/data/data-modeling.md", + "templates/data/data-governance.md" + ], + "load": "skill", + "moments": [ + { + "skill": "base-quality", + "moment": "Architecture, code style, calibration, tool trust, testing", + "file": "templates/core/quality.md" + }, + { + "skill": "base-git", + "moment": "Committer identity, branching, pull requests, CI evidence, regenerated artifacts, off-limits paths, .gitignore", + "file": "templates/core/git.md" + }, + { + "skill": "base-docs", + "moment": "Rule language, standard documents, upkeep, line width, writing style, diagrams, generated files, agent output files", + "file": "templates/core/docs.md" + }, + { + "skill": "base-testing", + "moment": "Test types, isolation, assertions, proving a change", + "file": "templates/core/testing.md" + }, + { + "skill": "base-review", + "moment": "Peer review priority, MUST/SHOULD checklists, deviation rules", + "file": "templates/core/review.md" + }, + { + "skill": "backend-http", + "moment": "Port, lifecycle, admin tasks, handlers, headers, methods, payloads, errors, auth", + "file": "templates/backend/http.md" + }, + { + "skill": "backend-api", + "moment": "API-first, contracts, versioning, deprecation, pagination", + "file": "templates/backend/api.md" + }, + { + "skill": "base-security", + "moment": "Application security rules \u2014 input, output, injection, auth, sessions, TLS, headers", + "file": "templates/security/security.md" + }, + { + "skill": "backend-auth", + "moment": "Authn/authz, JWT, RBAC, sessions, API keys", + "file": "templates/backend/auth.md" + }, + { + "skill": "backend-database", + "moment": "Migrations, transactions, parameterised queries, connection pooling", + "file": "templates/backend/database.md" + }, + { + "skill": "frontend-ux", + "moment": "UX principles, WCAG 2.1 AA, accessibility testing, design system, browser support", + "file": "templates/frontend/ux.md" + }, + { + "skill": "base-data-modeling", + "moment": "Schema design, naming, normalization, relationships, data types", + "file": "templates/data/data-modeling.md" + }, + { + "skill": "base-data-governance", + "moment": "Classification, PII handling, retention, ownership, audit trail", + "file": "templates/data/data-governance.md" + } + ], + "budget": null, + "output_leak": null, + "skills": { + "base-quality": 1629, + "base-git": 999, + "base-docs": 1175, + "base-testing": 1439, + "base-review": 1257, + "backend-http": 899, + "backend-api": 668, + "base-security": 1581, + "backend-auth": 609, + "backend-database": 465, + "frontend-ux": 525, + "base-data-modeling": 449, + "base-data-governance": 515 + }, + "outcome": "generated", + "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark\\tests\\efficacy\\arms\\lazyskills\\CLAUDE.md", + "output_lines": 22, + "output_words": 221 +} \ No newline at end of file diff --git a/tests/efficacy/arms/lazyskills/skills/backend-api/SKILL.md b/tests/efficacy/arms/lazyskills/skills/backend-api/SKILL.md new file mode 100644 index 0000000..b9110d1 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/backend-api/SKILL.md @@ -0,0 +1,103 @@ +--- +name: backend-api +description: API-first, contracts, versioning, deprecation, pagination +--- + +# Backend — API Design +[ID: backend-api] +[DEPENDS ON: templates/backend/http.md] + +## API-first +[LOAD: change-api] +- Design API-first (MUST): agree and document the public contract before + implementation begins (MUST), so client teams work in parallel and the + API is testable without a frontend +- Record any deviation from API-first in a decision record with its + justification (MUST) + +## Protocol selection +[ID: backend-api-protocols] +[LOAD: change-api] + +| Protocol | Use when | +|-----------|-----------------------------------------------------------------------------------------------------| +| REST | Default. External APIs, browser/mobile clients, third-party integrations, ops/admin endpoints | +| gRPC | Internal service-to-service, performance-critical paths, streaming, polyglot teams sharing a schema | +| GraphQL | Frontend-facing APIs where clients need flexible querying and over-fetching is a real problem | +| WebSocket | Real-time push, bidirectional streams where HTTP polling is not viable | +| Messaging | Async, fire-and-forget, event-driven | + +- Start with REST; deviate only with a reason in a decision record +- Combine REST for external and ops endpoints with gRPC for internal hot + paths (MAY) +- Justify any other pair of API styles in one service in a decision + record; two surfaces double the maintenance +- Never use gRPC as the primary interface for browser clients + +## API contract +[LOAD: change-api] +- Give every API the machine-readable contract of its kind, even when it + runs over HTTP (MUST): + - an OpenAPI specification for REST + - protobuf for gRPC + - a GraphQL schema + - a message schema for messaging +- Keep the contract current (MUST); a stale contract is worse than none +- Cover every resource, operation, parameter, response schema, error + response and authentication requirement in the contract +- Keep a changelog of API changes across versions +- Assert that the enums, operations and error codes in code match the + contract, so drift fails a test, not a consumer +- Contract-test a running instance against cases generated from the + contract +- Give the contract a revision of its own, apart from the package version + and from the API version +- Bump the contract revision for every contract change, additive ones + included; never bump it for a release that leaves the contract unchanged + +## Versioning +[LOAD: change-api] +- Keep every API version backward compatible (MUST) +- Version the API in the URI path prefix: `/v1/`, `/v2/` +- Start at `v1`; introduce `v2` only when a breaking change is unavoidable +- Use a custom request header (`Api-Version: 2`) where a path prefix does + not fit +- Never version through the media type (MUST NOT) + +## Backward compatibility +[LOAD: change-api] +- Release a new API version for every breaking change: a removed or + renamed response field, a changed field type, a switched auth scheme +- Treat as breaking, too, a changed verb or path, wire protocol or + Content-Type, and business logic that changes observable results +- Never bump the API version for an additive change (MUST NOT): a new + optional field, endpoint, verb or query parameter keeps `/v1/` and moves + only the contract revision + +## Deprecation strategy +[LOAD: deprecate] +When a breaking change is introduced: + +1. Deploy the new version alongside the old one +2. Add the `Deprecation` header to all responses from the old version with + the Unix timestamp of when deprecation started: + `Deprecation: @` +3. Optionally add the `Sunset` header with the planned removal date: + `Sunset: ` +4. Notify all consumers and agree on a migration timeline +5. Remove the old version only after the sunset date has passed; without + a `Sunset` header, only after the timeline agreed in step 4 ends + +## Statelessness +[ID: backend-api-statelessness] +- Keep APIs stateless (MUST): store no client context on the server + between requests +- Carry everything a request needs in the request itself (MUST) +- Keep session state in the client or a dedicated session store, never in + the API service + +## Pagination +[LOAD: change-api] +- Paginate every collection endpoint (MUST); never return an unbounded list +- Use `limit` and `offset` (or cursor-based) pagination +- Include navigation links or cursors (`next`, `prev`) in the response diff --git a/tests/efficacy/arms/lazyskills/skills/backend-auth/SKILL.md b/tests/efficacy/arms/lazyskills/skills/backend-auth/SKILL.md new file mode 100644 index 0000000..26b8632 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/backend-auth/SKILL.md @@ -0,0 +1,92 @@ +--- +name: backend-auth +description: Authn/authz, JWT, RBAC, sessions, API keys +--- + +# Backend — Authentication and Authorization +[ID: backend-auth] +[DEPENDS ON: templates/security/security.md, templates/backend/http.md] + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends `security/security.md`, "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## General principles + +- Keep authentication (who are you?) and authorization (what can you do?) + in separate layers; they are separate concerns +- Never implement your own cryptographic primitives — use well-audited libraries +- Fail closed: deny access by default; grant explicitly +- Centralise auth logic; never scatter permission checks across route handlers + +## Authentication +[EXTEND: security-authn] + +- Prefer delegating authentication to an identity provider (IdP) over + rolling your own +- Expire an access token within 15 minutes when the service issues tokens + itself +- Issue refresh tokens only to user sessions, such as a browser or mobile + client; rotate each on use and expire it within 7 days +- Never issue a refresh token to a service +- Authenticate a service by credentials of its own, such as OAuth 2.0 + client credentials, mutual TLS or a scoped API key (below) +- Validate every signed token's signature, expiry, issuer and audience +- Reject a token that lacks any required claim +- Store refresh tokens server-side, in a database or a dedicated session + store, so they can be revoked; stateless refresh tokens cannot be + invalidated before expiry + +## Token transport +[ID: backend-auth-token-transport] + +- Send access tokens in the `Authorization: Bearer ` header (MUST) +- Do NOT accept tokens in query parameters — they appear in server logs and + browser history +- Store a browser client's refresh tokens in `httpOnly`, `Secure`, + `SameSite=Strict` cookies (MUST) +- Never store refresh tokens in `localStorage` or JavaScript-accessible memory + +## Authorization + +- Use role-based access control (RBAC) as the baseline (SHOULD): + assign permissions to roles, assign roles to users +- Add attribute-based access control (ABAC) as a layer on top of RBAC for + fine-grained needs +- Replace RBAC with ABAC only with a reason in a decision record +- Enforce authorization at the service layer, not only at the route layer; + a route that passes auth may call a service that operates on another + user's data +- Never trust client-supplied IDs for ownership checks — always verify that + the authenticated user owns or has access to the requested resource + +## API keys (service-to-service) + +- Issue API keys with the minimum required scope +- Hash API keys before storing — treat them like passwords +- Rotate API keys on a schedule and immediately on suspected compromise +- Log every API key usage with the key ID (not the key value) and the + calling service identity + +## Observability + +- Log authentication failures at WARN to the security log, with IP and + user agent +- Name the account by its opaque user ID when it exists; never log the + submitted username or password +- Log authorization failures at WARN with user ID, resource, and action +- Alert on a spike in auth failures; it may indicate a credential stuffing + attack + +## Testing + +- Cover permission logic with unit tests for all role combinations, + including edge cases (no role, multiple roles, deprecated role) +- Assert in an integration test that a protected endpoint rejects an + unauthenticated request with an unauthenticated status, such as HTTP 401 +- Assert in an integration test that it rejects an authenticated request + lacking permission with a permission-denied status, such as HTTP 403 +- Test token expiry: assert that an expired token is rejected +- Test token revocation where refresh tokens exist: assert that a revoked + refresh token cannot obtain a new access token diff --git a/tests/efficacy/arms/lazyskills/skills/backend-database/SKILL.md b/tests/efficacy/arms/lazyskills/skills/backend-database/SKILL.md new file mode 100644 index 0000000..8394d45 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/backend-database/SKILL.md @@ -0,0 +1,75 @@ +--- +name: backend-database +description: Migrations, transactions, parameterised queries, connection pooling +--- + +# Backend — Database Conventions +[ID: backend-database] + +## Schema changes + +- Make every schema change through a migration committed to source + control — never edit the database manually +- Never regenerate or modify a migration that is already merged +- Write one migration per logical change — do not batch unrelated schema + changes +- Provide a `down` migration for every `up`; where reversal would lose + data, say so in the migration and get approval before applying it + +## Queries + +- Parameterise every query that takes a value; never build a query by + string interpolation +- Bound every query an interactive request runs with a limit or + pagination; a filter alone is no bound, since a filter on a flag can + still match millions of rows +- Stream or batch a deliberate export or batch scan, never load it whole +- Select only the columns or fields the code uses — never every column by + default +- Fetch related data for a set of rows in one query or batch, never one + query per row in a loop (N+1) + +## Indexing +[LOAD: migrate-data] + +- Index every foreign key column — not every engine does so automatically +- Add composite indexes for common multi-column filter + sort combinations +- Avoid over-indexing write-heavy tables — each index adds write overhead +- Drop unused indexes — check the engine's index usage statistics + regularly + +## Transactions + +- Wrap multi-step writes in a transaction — commit only after all writes + succeed +- Never leave a transaction open across a request boundary +- Keep transactions short — do not call external services inside a transaction +- Use an isolation level stronger than the engine's default only when + genuinely required + +## Connections + +- Use a connection pool — never open a new connection per request +- Inject the database session/connection as a dependency — no global DB + handles +- Set the pool size explicitly from the instance count and the + database's connection cap, so all instances together stay under it +- Monitor pool exhaustion — alert when pool wait time exceeds threshold + +## Soft deletes + +- Use soft deletes (`deleted_at` timestamp) only when audit history is + required; otherwise use hard deletes +- If using soft deletes, filter deleted rows out of every query by + default — never return deleted rows to callers +- Keep an append-only audit log table instead of soft deletes (MAY) + +## Testing +[EXTEND: base-testing] + +- Reset state between test runs — truncate tables or wrap each test in a + transaction rolled back after completion +- Do not substitute a different database engine in tests, such as an + in-memory one — behaviour differences cause false passes +- Never run schema migrations against a production database inside a test + suite diff --git a/tests/efficacy/arms/lazyskills/skills/backend-http/SKILL.md b/tests/efficacy/arms/lazyskills/skills/backend-http/SKILL.md new file mode 100644 index 0000000..4ea3c2f --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/backend-http/SKILL.md @@ -0,0 +1,132 @@ +--- +name: backend-http +description: Port, lifecycle, admin tasks, handlers, headers, methods, payloads, errors, auth +--- + +# Backend — HTTP Conventions +[ID: backend-http] + +## Port binding + +- Read the port from an environment variable such as `PORT`; never + hardcode it (MUST) +- Use a well-known default in development, and the port the platform + assigns in production + +## Process lifecycle + +- Start fast — keep initialisation short (MUST) +- Shut down gracefully on a stop signal (`SIGTERM`) in order: stop + accepting new requests, let in-flight ones finish until the drain + deadline, cancel what remains, wait up to a bounded cancellation period, + release resources, then exit (MUST) +- Release resources when the cancellation period ends, even when some + cancelled work is still running +- Force-exit when the whole shutdown, from draining to releasing + resources, passes its hard deadline (MUST) +- Set the drain deadline plus the cancellation period below the hard + deadline, leaving time to release resources +- Fit the hard deadline inside the grace period the platform allows + before it kills the process +- Recover cleanly when a process is killed without warning (`SIGKILL`, + power loss) (MUST) +- Keep no state in process memory that a restart cannot rebuild; put it in + an external store, so any instance can be replaced + +## Admin processes + +- Run one-off tasks (migrations, data fixes, REPL sessions) with the + application's code, config and dependencies (MUST) +- Commit admin scripts to the repository; never run them as ad-hoc shell + commands (MUST) +- Prefer idempotent scripts — safe to re-run +- Never run an admin task against production without a tested rollback plan + +## Handler design + +- Keep handlers thin: decode request → call service → encode response +- Never put business logic in a handler; delegate it to a service layer +- Validate all incoming request data before processing +- Set a timeout on every outbound call (HTTP clients, database queries) + +## Query parameters + +- Parse a typed query parameter explicitly so you can distinguish three + states: absent (use the default), present-and-valid (use it), and + present-but-invalid (raise 400) +- Never rely on a parsing helper that returns the default on a malformed + value; it silently turns a client error into a successful default-valued + 200 + +## Request headers + +- Read every header name case-insensitively, as RFC 9110 defines them + (MUST) +- Avoid the `X-` prefix on custom headers (SHOULD NOT); RFC 6648 + deprecated this convention +- Use a vendor or application-specific prefix on a custom header instead + (SHOULD) + +## HTTP methods + +- Never let a GET or HEAD request change resource state; RFC 9110 defines + both as safe +- Make every PUT and DELETE idempotent, as RFC 9110 defines them + +## Resource representation + +- Make a text payload's field types conform to the relevant ISO standard + (MUST): + - Date and time values: ISO 8601 + - Language codes: ISO 639 + - Country codes: ISO 3166-1 alpha-2 + - Currency codes: ISO 4217 +- Serialise any JSON integer outside ±(2^53 − 1), -9007199254740991 to + 9007199254740991, as a string (MUST); JavaScript cannot represent one + beyond that range precisely, in either direction +- Reject non-finite values in an endpoint that serialises computed floats + to JSON (MUST); `NaN`/`Infinity` are not valid RFC 8259 JSON +- Configure the JSON encoder to reject them, so it fails loud at the + serialisation boundary (a 500) instead of emitting a bare `NaN` token + that strict parsers reject +- Represent an undefined computed float in JSON as `null`, normalised + before serialisation +- Document such a JSON field as nullable in the contract +- Return only the fields the caller needs (MUST); never pad a payload + with fields that are not consumed + +## Error responses + +- Use consistent error response shape across all endpoints +- Never return stack traces, internal paths, or implementation details to the + client +- Use 4xx for client errors, 5xx for server errors — never use 200 for errors +- Carry a gRPC or GraphQL error the way its protocol defines instead: a + gRPC status code over HTTP 200, a GraphQL `errors` array under + GraphQL-over-HTTP's status rules +- Set an explicit `Content-Type` on every JSON response + +## Authentication and authorisation + +- Serve all API traffic over HTTPS outside local development (MUST); + plain HTTP is not acceptable in staging or production +- Give access tokens a short, finite lifetime (MUST) +- Enforce both authentication and authorisation on every external API + endpoint (MUST), except a public endpoint the project declares +- Make a public endpoint only a declared read, or a declared write that + must run before the caller has an identity, such as a sign-up, sign-in, + account recovery or a contact form +- Declare each public endpoint in the route definition and the API + contract, in the change that makes it public; a public catalogue stays + public, the account records beside it stay protected +- Require authentication at minimum on internal API endpoints (SHOULD) +- Never make any other write endpoint accessible without a valid + authenticated identity (MUST NOT) +- Apply authentication and authorisation before any business logic runs +- Rate-limit each public endpoint per client — never expose an unbounded + write operation +- Return no account data from a public write +- Rate-limit a sign-in or recovery endpoint per account and per client +- Answer a sign-up or recovery request the same way, in content and + timing, whether or not the account exists +- Make each recovery token single-use, short-lived and bound to one account diff --git a/tests/efficacy/arms/lazyskills/skills/base-data-governance/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-data-governance/SKILL.md new file mode 100644 index 0000000..69eaae4 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-data-governance/SKILL.md @@ -0,0 +1,81 @@ +--- +name: base-data-governance +description: Classification, PII handling, retention, ownership, audit trail +--- + +# Base — Data Governance +[ID: base-data-governance] +[DEPENDS ON: templates/data/data-modeling.md] + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +## Data classification +[ID: data-governance-classification] + +- Classify every data field into one of four tiers: + - **Public** — safe to expose (product names, documentation) + - **Internal** — business-sensitive, not for external use + (internal metrics, cost data) + - **Confidential** — restricted access (customer PII, financial + records, API keys) + - **Restricted** — highest sensitivity (passwords, payment card + data, health records) +- Document the classification in the schema or data dictionary (MUST) +- Match access controls to the classification tier (MUST) +- Grant confidential and restricted data only to the roles or identities + that need it + +## PII handling +[ID: data-governance-pii] + +- Identify all personally identifiable information (PII) fields + in the schema — name, email, phone, address, IP, device IDs +- Encrypt PII at rest and in transit (MUST) +- Minimize PII collection — do not store what you do not need +- Provide a mechanism to delete PII — hard delete or anonymize, never + just soft-delete it +- Never put PII in application logs, error messages, or stack traces + (MUST NOT); the audit trail is a separate store, not a log +- Keep the client IP, the one PII field a security log may hold, in that + log alone, access-restricted and purged when its retention ends +- Mask or redact PII in non-production environments + +## Retention +[ID: data-governance-retention] + +- Define a retention policy for each data category — document + how long data is kept and when it is purged +- Meet every regulation that applies to the data in each retention + period (MUST) +- Implement automated purging — do not rely on manual cleanup +- Apply retention policies to audit logs and backups too +- Never retain backups indefinitely +- Document the purge mechanism: soft delete → hard delete after + N days, or direct hard delete + +## Data ownership +[ID: data-governance-ownership] + +- Designate an owner for every data domain (users, orders, inventory) + (MUST) — a team or individual accountable for quality, access, and + lifecycle +- Have the data owner approve schema changes and access grants +- Document data ownership in the schema or data dictionary + +## Audit trail +[ID: data-governance-audit] + +- Log every change to confidential and restricted data (MUST): + who changed what, when, and the previous value +- Never record a credential's or secret's value in the audit trail, old or + new (MUST NOT); record that it changed, who changed it and when +- Record a PII field's change the same way, without its values, so + deleting the PII leaves no copy in the append-only trail +- Keep the audit trail in its own store, never in application logs, + with access restricted to the tier of the data it records +- Make audit logs append-only (MUST); never let application code edit + or delete them +- Include the actor (user ID or service identity), timestamp, + action (create, update, delete), and affected record diff --git a/tests/efficacy/arms/lazyskills/skills/base-data-modeling/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-data-modeling/SKILL.md new file mode 100644 index 0000000..762f499 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-data-modeling/SKILL.md @@ -0,0 +1,72 @@ +--- +name: base-data-modeling +description: Schema design, naming, normalization, relationships, data types +--- + +# Base — Data Modeling +[ID: base-data-modeling] + +Rules for schema design, naming, normalization, and relationships, in any +store: a relational database, a document store or a static data file. + +## Naming conventions +[ID: data-modeling-naming] + +- Use one naming convention per store for every table or collection, + field, key and index; record it in the project's context file + +## Normalization +[ID: data-modeling-normalization] + +- Give every table or collection a primary key — prefer surrogate keys for + internal use, natural keys for external-facing APIs +- Store each fact in one place by default — duplicate it only when + measured read performance requires it +- Never pack several values into one string field, such as + comma-separated values — use a list or a related record +- Document the rationale when intentionally denormalizing + +## Relationships +[ID: data-modeling-relationships] + +- Never rely on application code alone to keep references valid +- Enforce valid references with the store's own constraint where it has + one, else with a check that every reference resolves +- Decide for every reference what deleting its target does: + - delete the referencing records for strong ownership + - clear the reference for a weak one + - refuse the delete when an orphan indicates a bug +- Keep a record apart, referenced by key, unless it has no life outside + its parent +- Document a self-referencing relationship's (e.g. `parent_id`) maximum + depth and cycle prevention strategy (MUST) + +## Schema evolution +[ID: data-modeling-evolution] + +- Run every schema change through a versioned migration (MUST); never + change a production schema by hand +- Prefer additive changes, such as a new field, table or collection +- Keep an additive change compatible with old writers: add a field + optional or with a default, never required without one where records + exist +- Give every destructive change (drop or rename a field) a migration plan: + add new → migrate data → drop old (MUST) +- Include both up and down steps in every migration (MUST) +- Say so where a down step cannot restore the data, and get approval + before applying that migration +- Test migrations against a production-like dataset before deploying + +## Data types +[ID: data-modeling-types] + +- Use the most specific type the store offers — a date type, not a + string, for dates +- Store timestamps in UTC — convert to local time at the + presentation layer +- Store monetary values as integers in minor units or as a decimal type — + never floating point +- Use `UUID` or `ULID` for distributed ID generation — auto-increment + is acceptable for single-database systems +- Document a maximum length for every text field (MUST); unbounded text + invites abuse and complicates indexing diff --git a/tests/efficacy/arms/lazyskills/skills/base-docs/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-docs/SKILL.md new file mode 100644 index 0000000..853b194 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-docs/SKILL.md @@ -0,0 +1,182 @@ +--- +name: base-docs +description: Rule language, standard documents, upkeep, line width, writing style, diagrams, generated files, agent output files +--- + +# Base — Documentation + +[ID: base-docs] + +Which documents a project keeps, and how they stay true. + +## Rule language + +- Read a plain imperative ("Use X", "Never Y") as MUST or MUST NOT +- Add an RFC 2119 key word where strength matters: SHOULD or MAY for a + weaker rule, MUST to stress an absolute one + +| Word | Meaning | +| --- | --- | +| MUST | Absolute requirement; a deviation needs an approver's sign-off | +| MUST NOT | Absolute prohibition; a deviation needs an approver's sign-off | +| SHOULD | Recommended; a deviation needs a justification | +| SHOULD NOT | Not recommended; may be ignored with a justification | +| MAY | Optional; the developer decides | + +## Standard documents + +[LOAD: write-docs] + +- Carry these three in every project (MUST); their layout is the project's + own, and `templates/core/agents.md` offers a default for the agent files + +| File | Purpose | +| --- | --- | +| `README.md` | What the project is and how to use it | +| `AGENTS.md` | Agent context and project rules, for any agent | +| `CLAUDE.md` | Agent context and project rules, for Claude Code | + +## Single source of truth + +- Keep the project structure in `README.md` only, and reference it + elsewhere +- Keep the agent files' project-structure section a pointer to the README + plus placement rules, never a second directory tree +- Never reference a file, component or service that does not exist + +## Upkeep + +- Update every document a change touches, in the same commit: + - `CLAUDE.md` when architecture, stack, design rules or conventions change + - `README.md` when structure, stack or setup steps change + - `AGENTS.md` whenever `CLAUDE.md` changes, so the two agree +- Write in present tense; past or future tense signals a stale document +- Write as little as needed; a document that drifts is worse than none +- Remove redundant, inconsistent or outdated text promptly (SHOULD), in + its own change when it is unrelated to the one that finds it + +## Disagreements + +- Establish which is wrong before changing a document or the system it + contradicts +- Check whether the rule is inherited: a document generated from a template + can drift while the system still matches the template +- Never act on the document alone when the observed state is defensible + (MUST NOT) +- Read the document, observe the system, find the rule that governs both, + then fix whichever one that rule does not support + +## Adopting shared rules + +[LOAD: generate-context] + +- Treat template rules as candidates; the project chooses what it adopts +- Adopt a rule when it addresses a named local defect, a requirement or a + credible material risk; a preventive security control needs no incident +- Never let a template update create compliance work, tickets or decision + records by itself (MUST NOT); a newer tag alone is no reason to move the + pin +- Record a declined candidate in at most one line, if at all (MAY), in the + existing pull request or discussion +- Keep adopted rules in force until the project changes them, and keep the + operative selection in the project's context file +- Inline this adoption boundary in a reference or hybrid context file + (MUST), so a new upstream MUST cannot widen the adopted set +- Assess security fixes in tools the project runs promptly; review new + conventions when a project need warrants it + +## Line width + +- Wrap Markdown at the width the project declares, never at one written + into a rule + +### Enforcing the width + +[LOAD: add-check] + +- Declare the width as the line-length setting in the Markdown linter's + configuration (MUST); the linter reads no other file, so a width set only + for editors goes unenforced +- Keep any second copy of the width, such as `.editorconfig` for editors, + equal to the linter's +- Declare in the same place which of fenced blocks, table rows and headings + are exempt +- Exempt a line only where it cannot wrap: an unbreakable token, a bare + URL, a Markdown link, or a single-line directive a parser reads whole +- Enforce the width with the Markdown linter's line-length rule in CI + (MUST); a project that declares no width has no rule +- Pass that CI run the configuration and the files to lint explicitly + (MUST) + +## Writing style + +- Use bold and italic sparingly: never bold inline code or a whole + sentence, and use at most one short bold label per list item +- Code-format only identifiers: file names, paths, environment variables +- Summarise a method, constant or flag in prose and link to its source; + never transcribe its definition +- Put a command the reader runs in a fenced block, exactly as typed +- Point at a self-documenting source, such as `--help`, a generated schema + or generated API docs, rather than restating it; document only what it + cannot state itself +- State a count about the tree only inside a block a generator writes and + gates, or in a dated record; elsewhere name the thing without counting it + +## Cold readers + +[ID: docs-cold-reader] + +- State the symptom before the mechanism +- Expand a term taken from the code at its first use, or avoid it +- Show a real example rather than describe one +- Keep to one idea per sentence +- Separate how bad it is now from how bad it becomes +- Apply these to every ticket, pull request and defect record an agent + writes; the record outlives the session + +## Diagrams and assets + +[LOAD: write-docs] + +- Commit every editable source beside its rendered output; never commit a + binary-only diagram +- Give a committed artefact one authority: commit its editable source or + its generator, never both +- Never use proprietary formats such as Word, Illustrator or Affinity + Designer +- Split a diagram that serves two purposes into two + +## Docs as code + +[LOAD: write-docs] + +- Keep technical documentation in the repository, in Markdown, under the + same review as code + +## Generated files + +[LOAD: regenerate] + +- Start every generated file with a banner naming the tool that wrote it + and the command that refreshes it (SHOULD) +- Give every generator a `--check` flag that re-renders in memory and exits + non-zero on a diff or a missing file, and require it in pre-commit and CI + (SHOULD) +- Re-render to judge staleness; never rely on inspection, above all for a + visual or binary output such as a diagram export +- Exclude generated paths from formatters (SHOULD) +- Re-run the generator when its inputs change; never edit its output +- Preserve human-entered content when refreshing a generated file, or fail + naming what would be discarded (MUST) + +## Output file by agent + +[LOAD: generate-context] + +| Agent | Context file | +| --- | --- | +| Claude Code | `CLAUDE.md` | +| Cursor | `.cursor/rules/project.mdc` | +| GitHub Copilot | `.github/copilot-instructions.md` | +| OpenAI Codex CLI | `AGENTS.md` | +| Generic or other | `AGENTS.md` | diff --git a/tests/efficacy/arms/lazyskills/skills/base-git/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-git/SKILL.md new file mode 100644 index 0000000..3cf11a2 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-git/SKILL.md @@ -0,0 +1,147 @@ +--- +name: base-git +description: Committer identity, branching, pull requests, CI evidence, regenerated artifacts, off-limits paths, .gitignore +--- + +# Base — Git Conventions + +[ID: base-git] + +How changes are committed, reviewed, verified and merged. + +## Commits + +- Commit under your full name and one consistent email; never change + identity mid-project +- Work on a branch; never commit directly to `main` +- Never commit build output, dependency directories or secrets +- Commit a generated file only when the project tracks it on purpose, under + the regeneration rules below +- Treat every repository as public: no secret, credential or sensitive + value in source or history +- Keep a `.gitignore` (MUST) covering dependencies, build output, secrets, + editor state, OS files and coverage output +- Commit lockfiles (MUST) + +## Existing changes + +- Inspect the working tree and the index before starting a task +- Never discard, reset, stash or overwrite a change the task did not make + (MUST NOT) +- Never clear the tree to obtain a clean test baseline; ask the owner +- Stage only the changes the task made: a whole file only when it held no + prior change, otherwise only the task's hunks; never stage everything +- Read the staged diff before committing; it holds only the task's changes +- Stop and ask when a task change and a prior change share a hunk +- Report a pre-existing change that blocks the task rather than removing it + +## Pull requests + +- Keep a pull request to one concern (SHOULD) +- Test locally before committing +- Review the diff against the base before merging, in the order security, + correctness, clarity, conventions +- Merge only after the review passes and CI is green + +## CI evidence + +- Read the CI run for the push before describing a change as good; a local + run is evidence about one platform +- Treat a pull request with no registered check as not passed: wait until + one registers, then watch every check to completion +- Never merge while a check is failing, cancelled or not yet registered +- Re-run a verification a pull request body claims once the base has moved + since it was written; above all a proof of absence +- Read a new or changed workflow's first run in its real environment, and + require a verdict from it before trusting the workflow + +## Updating a branch + +- Never force-push, including with `--force-with-lease` (MUST NOT) +- Bring a branch up to date by merging the base into it; never rebase and + force-push + +### Regenerating after a merge + +[LOAD: regenerate] + +- Regenerate derived artifacts and re-run the staleness comparison after + every such merge, and stage what they produce + +## Regenerated artifacts + +[LOAD: regenerate] + +- Regenerate a derived artifact in the change that edits its source, and + stage both together (MUST) +- Name the regeneration trigger beside the sources it derives from (MUST) +- Run the staleness comparison after the edit, and again after any merge + that brings another branch's sources in (MUST) + +```bash + || exit 1 +git ls-files --error-unmatch -- > /dev/null || exit 1 +git diff --exit-code --stat -- +``` + +- Read the staged copy as the baseline: the comparison runs before the + commit, and in a clean checkout, such as CI's, the index is the commit +- Require a zero status; a failed regenerator, an artifact that is not + staged and any diff each fail it +- Treat any diff as a staged artifact that does not match its sources +- Treat a regenerator that fails this on a current artifact as defective: + it is not idempotent +- Summarise the visible impact before and after in the pull request body: + a verdict matrix, a delta table, a screenshot diff +- Open a tracked follow-up naming the stale files, by name or glob, where + regeneration is too expensive to bundle (MUST) +- Drop a regenerated file whose diff is line endings only: + +```bash +git diff --ignore-cr-at-eol +``` + +- Read an empty diff as noise, and drop the file with + `git checkout -- ` +- Never drop a file on `--ignore-all-space`; it hides `"a b"` becoming + `"ab"` +- Read any other whitespace-only diff before dropping it +- Open every regenerated binary artifact in a viewer or an image-read tool, + and confirm it tracks its source +- Regenerate a known-current control artifact first; a non-zero diff there + means the environment disagrees with the committed files +- Reconcile a non-zero control diff before committing anything regenerated +- Pair a spot-check of three to five representative artifacts with one + population metric when a change regenerates many + +## Off-limits paths + +- Declare an Off-limits section in the project's context file, listing the + paths that MUST NOT change without explicit approval (MUST) +- Offer this default set for the project to cut down: auth and session + code, payment code, migrations, `.env*` and secrets, and CI/CD + workflows +- Propose a change inside an off-limits path before making it, with a + rollback strategy and the tests that would catch a regression (MUST) +- Treat an approval as covering the proposed plan, never the whole path +- Apply the restriction to executable content: steps, commands, flags, + permissions, triggers, pins +- Treat a diff confined to prose as ordinary work +- Treat a comment a tool reads as executable, such as a linter disable or + a coverage pragma +- Classify by the diff: it is prose only when removing every comment line + leaves nothing +- Name an off-limits path at the top of the change's summary whenever the + diff touches one, proposal or not (MUST) + +```bash +pre-commit run report-off-limits-paths --hook-stage manual --all-files --verbose +``` + +- Require the paths-declared and files-changed counts above zero +- Pass each path as a `--path` argument, kept beside the declared list; + `--base` defaults to `origin/main` +- State every off-limits line in the summary as an escalation; it is not + a failure +- Run it after committing: at or behind the base with a clean tree it + prints `not applicable`, and a base that does not resolve fails it diff --git a/tests/efficacy/arms/lazyskills/skills/base-quality/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-quality/SKILL.md new file mode 100644 index 0000000..eeb0bf2 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-quality/SKILL.md @@ -0,0 +1,275 @@ +--- +name: base-quality +description: Architecture, code style, calibration, tool trust, testing +--- + +# Base — Quality Attributes + +[ID: base-quality] + +How code is designed, kept clean, swept and checked. + +## Principles + +- Keep one authoritative representation of each piece of knowledge (DRY); + the third copy is a bug +- Extract shared logic only where substantial logic repeats; a few similar + lines inline are not duplication +- Choose the simplest solution a stated requirement justifies (KISS) +- Build what is needed now, never for a hypothetical requirement (YAGNI) +- Record beside every deferral the concrete condition that reopens it +- Delete a path once evidence shows it unreachable or obsolete: no caller, + or a retired input +- Treat a real-data probe that never reaches a path as a lead, not proof; + a sample misses rare cases + +## Architecture + +- Compute derived counts and statistics from the data; never hardcode them +- Remove unused modules, assets and data files promptly + +## Naming + +- Name a function with a verb, a class or module with a noun, and a boolean + with `is`, `has` or `can` +- Rename a name that needs a comment to explain it +- Use the same name for the same concept in every module +- Name a public enum member, CLI flag or result discriminator for the + capability it offers, never the library behind it: `Transport.HEADED`, + not `Transport.PLAYWRIGHT` (MUST). A private symbol MAY name its library + +## Complexity + +- Keep cognitive complexity at or under 15 per function +- Nest at most three levels; use guard clauses and early returns +- Replace a boolean flag that selects behaviour with an enum or two named + functions +- Name every magic number and magic string as a constant +- Size a tuned threshold, such as a latency alert, from its measured + distribution (p95, p99, maximum legitimate); name the data source in + the constant's docstring +- Take a limit a specification fixes, such as a protocol's maximum + message size, from that specification and name it, never from an + observed percentile + +## Dependencies + +- Keep the module graph acyclic; break a cycle with a third module or an + interface, never with a divergent local copy +- Keep coupling shallow: a change inside one module MUST NOT require + changes in unrelated modules +- Talk only to direct dependencies, and keep together what changes together + (SHOULD) +- Reach a heavy, native or platform-limited dependency through one module + that owns its import and names the install command when it is missing + +### Optional dependencies + +[LOAD: add-dependency] + +- Where a dependency is optional, run one CI leg without it installed, + importing the package (MUST) + +### Import bans + +[LOAD: add-check] + +- Declare a directional import ban where one part of the tree must not + import another (MAY), and check every ban declared + +```bash +pre-commit run find-import-bans --all-files --verbose +``` + +Pass condition: the bans-declared and modules-inspected counts are above +zero and `import-ban violations` is zero. Each ban is a +`--forbid IMPORTER:IMPORTED` argument; `not applicable` means none is +declared. + +## Errors + +- Validate input at boundaries and fail at once on invalid state +- Read a value from its source-of-truth field, and raise when the field is + missing; never fall back to a value derived from a slug, name or hash +- Bound every wait on another thread, process or connection, report why it + gave up, and check the worker's liveness as well as the deadline +- Never break a public catch contract: a raise callers catch by a built-in + type keeps that type +- Add an error type only where a caller could act differently +- Never let a caller-side input filter stand in for a precondition: widen + the filter, or assert the precondition inside the function + +## Deprecation and renames + +[LOAD: deprecate] + +- Deprecate a public symbol, naming its replacement, before a later change + removes it +- Deprecate every part of one call site together, such as a method and its + keyword arguments, or break the whole call; never alias the outer name + alone +- Retire a concept by sweeping every surface that still instructs its use, + tickets and plans included, until a search returns only historical + records + +## Module structure + +- Keep a CLI a thin layer over a library that holds its logic +- Keep constants beside the functions that use them + +## Library output + +[ID: quality-library-output] + +- Never write to the host's standard output or error from a library, and + never configure logging beyond the library's own logger (MUST) +- Make the library's logger injectable, falling back to its module logger +- Check the silence in a fresh process; a test runner's handler hides the + default + +## Encoding and line endings + +- Encode every committed text file in UTF-8, with LF line endings (MUST) +- Keep identifiers ASCII (MUST); comments, docstrings, strings and + documentation carry no charset restriction + +```bash +pre-commit run check-ascii-identifiers --all-files --verbose +``` + +Pass condition: the inspected count is above zero and +`non-ASCII identifiers` is zero. The hook reads Python; `not applicable` +means the project tracks none. + +- Set a program's output encoding explicitly, and pin its line ending where + another program reads the output +- Commit a `.gitattributes` with `* text=auto`, adding `eol=lf` for hard + LF +- Mark a text path exempt from LF with `-text` in `.gitattributes` +- Check line endings on every tracked file, whatever its name, exempting a + `-text` file; count a file Git files `i/-text` as binary only when it + holds a NUL byte +- Let a linter format on save, and keep manual style rules to a minimum + (SHOULD) + +```bash +seen=0 exempt=0 binary=0 bad=() +while IFS= read -r -d '' rec; do + info=${rec%%$'\t'*} path=${rec#*$'\t'} seen=$((seen + 1)) + case " ${info#*attr/} " in *" -text "*) exempt=$((exempt + 1)); continue ;; esac + case $info in "i/ "* | i/lf* | i/none*) continue ;; esac + nuls=$(git cat-file blob ":0:$path" | tr -dc '\000' | wc -c) + [[ $info == i/-text* && $nuls -gt 0 ]] && binary=$((binary + 1)) && continue + bad+=("$path") +done < <(git ls-files -z --eol) +printf 'files inspected: %d\nexempt by -text: %d\n' "$seen" "$exempt" +printf 'binary by content: %d\nfiles not filed i/lf: %d\n' "$binary" "${#bad[@]}" +for f in "${bad[@]}"; do echo " $f"; done +[ "$seen" -gt 0 ] && [ "${#bad[@]}" -eq 0 ] +``` + +Pass condition: exit zero, given only when the inspected count is above +zero and the not-`i/lf` count is zero. An empty `i/none` file passes; a +stray carriage return, filed `i/-text` with no NUL byte, still fails. + +## Comments + +- Prefer code that needs no comment; comment only intent the code cannot + express +- Re-verify a comment explaining why something is safe whenever the code + is next read +- Never cite a ticket, PR or ADR number in a code comment, docstring or + commented configuration; state the substance (MUST NOT) +- Name a source (author, year, method) where non-obvious or scientific + logic needs one (MAY) + +## Debug code + +- Commit no debug output (`print()`, `console.log()`) and no hardcoded + breakpoint +- Delete commented-out code +- Gate debug tooling behind a flag or environment variable, off by default + +### Probe scripts + +- Write a probe, a throwaway script that measures data or behaviour, + rather than guess +- Delete a probe before the commit that uses its findings (MUST) +- Keep findings in source comments, decision records or docs, never in + the probe + +## Rejected mechanisms + +[ID: quality-rejected-mechanism-sweep] + +- Grep the codebase for a construct a comment records as not working, + before moving on: `grep -rn '' ` +- Read every hit as a suspected instance of the same defect, not a style + question + +## New constraints + +[ID: quality-constraint-corpus-sweep] +[LOAD: add-check] + +- Run a new constraint (a rule, a check, a tightened bound, a narrowed + exemption) against the existing corpus before it merges (MUST) + +## Destructive operations + +[ID: quality-destructive-ownership] + +- Delete, truncate, overwrite or kill only what the operation can prove it + created: process ancestry, a key scheme, a filename prefix, a marker file + or an ownership tag; never a path, a configuration value or a file + extension +- Find nothing where the proof is unavailable: no error, no prompt, no + guess +- Validate the input as well: reject an empty configuration value, and + match the key scheme +- Apply this to every reaper: a cache clean, an output-directory clear, a + log rotation, a temp-file sweep + +``` +match on ".html" wrong directory -> README.html deleted +match on "[0-9a-f]{16}.html" wrong directory -> nothing matched +``` + +## Check trust + +[ID: quality-cross-validation] + +- Confirm a validation, scraping, migration or codemod tool is correct + before acting on its output in bulk +- Treat a physically implausible output as a tool defect: fix it, re-run, + then apply +- Cross-check an independent source before overwriting stored data with a + source that looks wrong +- Never weaken the rule behind a check to make it green or quiet + +## Enforcement + +- Enforce these conventions through the gates: editor, pre-commit, CI +- Merge to `main` only with passing tests + +### Generated output + +[LOAD: regenerate] + +- Make a generator emit output that passes the linters natively; a needed + `lint --fix` is a generator bug (MUST) + +## Completion + +[ID: quality-completion] + +Adding pagination, for example, ends with bounded results, their tests and +an updated contract. It does not end with a rewrite of the service layer. + +- Finish a task when the requested behaviour works through the entry point + its user or caller reaches, and the checks that prove it pass +- Report a check that could not run as not run, never as a pass +- Add an abstraction, infrastructure or a process step only when a stated + requirement, a demonstrated defect or a material risk justifies it +- Report a problem found outside the task, or file it as its own task, + rather than fixing it in the same change (SHOULD) diff --git a/tests/efficacy/arms/lazyskills/skills/base-review/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-review/SKILL.md new file mode 100644 index 0000000..98fa7a1 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-review/SKILL.md @@ -0,0 +1,188 @@ +--- +name: base-review +description: Peer review priority, MUST/SHOULD checklists, deviation rules +--- + +# Base — Peer Review + +[ID: base-review] + +How a change is reviewed, and how a finding is proven before it is reported. + +## Principle + +- Peer-review all code before merging (MUST) +- Hold the reviewer accountable for what merges, and the developer for what + they write +- Put reviews ahead of your own development; a blocked review blocks the + team + +## Priority order + +[LOAD: review] + +Review in this order, most critical first. `templates/core/quality.md`, and +any language quality template the project carries, is the standard for +items 2 to 4. + +1. **Security**: anything exploitable, any credential or licence problem +2. **Correctness**: wrong results, unhandled failures, race conditions +3. **Clarity**: obscure names, deep nesting, high cognitive complexity, + boolean flag parameters +4. **Conventions**: deviations from the project's agreed patterns + +The order above is by area; weigh each finding separately. + +- Label each finding a demonstrated defect, a deviation from a policy the + project adopted, or a suggestion +- Block a merge only on a defect or a policy deviation; leave a + suggestion to the author + +## MUST checklist + +- [ ] No credential, token or sensitive value appears in a committed file +- [ ] Every failure path is handled; no silent catch, no swallowed exception +- [ ] Every new dependency carries a licence the project's policy allows +- [ ] Significant logic and architectural decisions are documented +- [ ] Existing documentation matches the code after the change +- [ ] Every changed section was re-read whole, not only the changed line +- [ ] Every claim changed text makes about itself, such as a count or "all", + was checked by counting with a tool +- [ ] Input from outside the process, such as a URL parameter, is + validated as untrusted before it is destructured, indexed or used as + a key +- [ ] A refactor preserves behaviour on every path: each case, direction and + mode, including null handling, sort order and boundary values + +## SHOULD checklist + +- [ ] Each non-trivial function has a unit test per relevant variant +- [ ] Coverage does not fall +- [ ] Lint errors and warnings do not rise +- [ ] Each third-party dependency is necessary, understood and maintained +- [ ] No new abstraction without two call sites, and no new dependency + without a documented reason + +## CI signals + +- Read the log of a red check before calling the pull request green or red +- Separate an infrastructure failure (the check could not run) from a diff + failure (it ran and found something), and say which in the merge decision +- File a separate task for an infrastructure failure, and note it in the + merge decision +- Never retry until green without saying so (MUST NOT) +- Never bypass a failing check by skipping hooks or by an admin merge + unless the maintainer explicitly accepts the risk (MUST NOT) + +## Structure audit + +- Run a structure audit, which checks project completeness rather than + changed files, after a new project setup, a framework or stack migration, + a new major layer, and before a release milestone +- Verify every MUST in the base templates (the standard documents, a + `.gitignore`) and in the project's layer and stack templates +- Verify each sub-clause of a MUST separately; a rule requiring examples and + their output is two checks + +## Picking up an issue + +[LOAD: start-issue] + +- Re-read the target for existing coverage before writing anything; an + issue describes the tree on its filing date +- Verify everything the issue cites as existing, and run what it proposes + against the tree before adopting it +- Check the open pull requests and the decisions accepted since the filing + date for work that already closes or moves it +- Restate the scope before starting when it has moved since filing +- Read what a cited sibling change shipped, not what it proposed +- Resolve each cited version identifier against its source; a superseded + one still resolves +- Treat a closed classification in the acceptance criteria as a claim: + sort every member yourself before acting on any + + ``` + criteria: "each check runs on Linux or macOS" + sorted: 9 Linux, 2 macOS, 1 neither -- it runs only on Windows + ``` + +- Name each member that fits no branch, and the branch it fails + +## Planning + +- Produce a plan before implementing a feature or a non-trivial change: the + files, the signatures or outline, the edge cases, and the assumptions +- Never write implementation code until the plan is approved (MUST NOT) +- Skip the plan for one-line fixes, typos, changes the requester has + specified in full, and work whose approach the requester already approved +- Stay inside the approved plan; when a constraint invalidates it, stop and + re-surface the options + +## Verifying a finding + +- Label a finding unverified until it is demonstrated (MUST) + +### From reading + +[LOAD: verify-finding] + +- [ ] Reproduce the defect before reporting it: run the path +- [ ] Read a passing test that contradicts the reproduction before blaming + the code; it may pin a decision + +### From a measurement + +[LOAD: verify-finding] + +- [ ] The tool measures the rule's unit: bytes are not characters +- [ ] The tool measured the claimed scope, not a diff, sample or partition; + a whole-codebase claim comes from a whole-codebase run (MUST) +- [ ] The mode that produced each kept number is recorded beside it +- [ ] One flagged item was checked by hand +- [ ] Each count carrying a finding was produced twice, by different means +- [ ] A zero was checked by finding one positive by hand +- [ ] The tool fails loudly on unsupported input rather than exiting clean + (SHOULD) + +### From an extraction + +[LOAD: verify-finding] + +- [ ] An element reported absent was checked against the raw artifact +- [ ] Extracted size was compared with the raw artifact, and known elements + survived the round trip +- [ ] The claim is scoped to what was inspected: "not verifiable from the + extract", never "missing" + +### From a probe + +[LOAD: verify-finding] + +- [ ] The probe ran under the conditions the finding is about, such as its + user, credential and environment +- [ ] A claim the probe cannot make under those conditions is scoped to the + ones it tested + +### From an agent + +- Check an agent's finding against the file, commit or document that + settles it before acting on it or repeating it +- Distinguish a verified negative from a failed lookup, and say which +- Count a finding several agents agree on as one finding +- Correct a finding you passed on that proves wrong, and name what the + check showed +- Reconcile a finding with a verified record it contradicts before + changing anything: confirm both read the same artifact, prefer the more + specific evidence, and record the outcome +- Record a reversal of a documented decision, with its reason, in the + artifact that documented it +- Give a verifying agent the existing record and ask it to reconcile, not + re-derive +- Never delete a record because a check "could not confirm" it (MUST NOT) + +## Deviations + +- Explain a deviation from a SHOULD rule in the pull request +- Land a deviation from a MUST or MUST NOT rule only with a designated + approver's sign-off and its reason recorded in the pull request (MUST) +- Never waive a MUST or MUST NOT rule yourself; stop and ask the approver diff --git a/tests/efficacy/arms/lazyskills/skills/base-security/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-security/SKILL.md new file mode 100644 index 0000000..14ab799 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-security/SKILL.md @@ -0,0 +1,266 @@ +--- +name: base-security +description: Application security rules — input, output, injection, auth, sessions, TLS, headers +--- + +# Base — Application Security + +[ID: base-security] + +Apply these cross-cutting security rules to application code in every +project, regardless of language or framework. + +The sections below cover the OWASP Top 10 categories: injection, broken +access control, cryptographic failures, insecure design, security +misconfiguration, vulnerable components, identification and authentication +failures, software and data integrity failures, logging and monitoring +failures, and server-side request forgery. + +## Input validation + +[ID: security-input] + +- Validate all external input at the system boundary — the first point + where untrusted data enters the application +- Validate complex input with a schema validation library; never + hand-write it +- Use an allowlist, not a blocklist — define what is valid, reject + everything else +- Reject invalid input with a clear error; do not silently coerce or strip + fields +- Do not repeat the boundary's schema validation in inner layers; a + function still asserts the preconditions it relies on + +## Output encoding (XSS) + +[ID: security-output] + +- Encode dynamic data for its rendering context at the point of output: + HTML, URL, JavaScript, SQL, shell +- Encode on output, not on input — store the raw value, encode when + rendering +- Use the encoding the framework or template engine provides +- Never insert user-supplied data through a raw-HTML path that bypasses + auto-escaping +- Apply the encoding that matches each context; HTML encoding does not + prevent URL injection + +## Injection prevention + +[ID: security-injection] + +- Use parameterized queries for all database access; never concatenate user + input into SQL strings +- Escape shell arguments when invoking external commands, or use API + alternatives that do not invoke a shell +- Never pass user input to dynamic code execution, such as an `eval` + +## Authentication + +[ID: security-authn] + +- Hash passwords with a modern algorithm: bcrypt, scrypt, or Argon2 — never + MD5, SHA-1, or plain SHA-256 +- Require a minimum password length and reject known-breached passwords; + never impose composition rules (NIST SP 800-63B) +- Use constant-time comparison for secrets and tokens; timing attacks leak + information through response time +- Lock accounts or throttle after repeated failed attempts + +## Session management + +[ID: security-sessions] + +- Generate session IDs with a cryptographic random generator +- Regenerate the session ID after login; this prevents session fixation +- Set cookie flags: `HttpOnly`, `Secure`, `SameSite=Lax` (or `Strict` for + sensitive applications) +- Expire sessions after an idle period: 30 minutes for sensitive + applications, configurable otherwise +- Invalidate sessions on logout; do not rely on cookie expiry alone + +## Cross-site request forgery (CSRF) + +[ID: security-csrf] + +- Give every state-changing request a CSRF defence (MUST) when the session + is authenticated by an ambient credential +- Treat as ambient any credential the browser attaches on its own: a + cookie, HTTP Basic, or a client certificate +- Use the framework's built-in CSRF middleware; never hand-roll token + generation or comparison +- Treat `SameSite=Lax` on the session cookie as defence in depth, not the + defence; it does not cover top-level `POST` navigation on older browsers, + and a subdomain takeover defeats it +- Prefer the synchroniser token pattern +- Use the signed double-submit cookie where the server holds no session + state, with the token bound to the session identifier +- Validate the token on every `POST`, `PUT`, `PATCH` and `DELETE`, never on + `GET` +- Never change state on a `GET` request (MUST NOT) +- Treat an API authenticated only by a bearer token the client attaches + explicitly as needing no CSRF token; the browser never adds that header + on its own +- Require a CSRF token on a bearer-token API that also accepts cookie + authentication + +## Secrets in code + +[ID: security-secrets] + +- Never hardcode secrets, API keys, tokens, or credentials in source files +- Keep local secret files out of version control +- Rotate a secret immediately if it is accidentally committed; removing it + from git history is not sufficient, since the secret is compromised + +## Transport security + +[ID: security-transport] + +- Use HTTPS everywhere, with no exceptions for production traffic +- Enable HSTS on all production sites (MUST), with `includeSubDomains` and + a minimum `max-age` of one year +- Require TLS 1.2 as the minimum version; disable TLS 1.0 and 1.1 +- Use strong cipher suites; disable known-weak ciphers + +## Security headers + +[ID: security-headers] + +- Set security headers on every HTTP response at the reverse proxy or + middleware level, not per route +- Set these required headers: + - `Content-Security-Policy` — start strict, relax only what a page needs + - `X-Content-Type-Options: nosniff` + - `X-Frame-Options: DENY` (or CSP `frame-ancestors`) + - `Strict-Transport-Security` (see Transport security) + - `Referrer-Policy: strict-origin-when-cross-origin` + - `Permissions-Policy` — disable unused browser APIs +- Map each static asset type to its `Content-Type` in code when enabling + `nosniff`; the browser then never corrects a wrong one +- Never let MIME resolution depend on the host when `nosniff` is enabled + (MUST NOT) +- When enabling `nosniff`, verify script and style execution in a real + browser, not just status codes +- Never use `unsafe-inline` or `unsafe-eval` in CSP without a written + justification +- Do not expose server version or technology stack in headers; remove + `X-Powered-By`, `Server` version strings + +## Error handling + +[ID: security-errors] + +- Never expose stack traces, internal paths, or database errors to end + users; return generic error messages externally +- Log full error details server-side for debugging +- Use consistent error response formats; do not leak internal structure + through varying error shapes +- Return each error through the protocol's own error signal, never as a + success +- Do not reveal whether a resource exists via error messages: login errors + should say "invalid credentials", not "user not found" vs "wrong password" + +## Logging + +[ID: security-logging] + +- Never log secrets, tokens or passwords +- Never log personally identifiable information (PII), except the client + IP in the security log below +- Sanitize log output; user-supplied data in logs can enable log injection + attacks +- Log security-relevant events: authentication attempts, access denials, + privilege changes, configuration changes +- Include enough context for investigation: timestamp, an opaque user ID, + action, result; never a name, email or submitted username +- Record the client IP only in the security log, access-restricted and + purged at the end of its retention period +- Retain security logs for a defined period; compliance may require 90 + days to 7 years + +## CORS + +[ID: security-cors] + +- Restrict `Access-Control-Allow-Origin` to specific known origins; never + use `*` for authenticated endpoints +- Do not reflect the `Origin` header back as `Access-Control-Allow-Origin` + without validation +- Restrict allowed methods and headers to what the API actually needs + +## Deserialization and data integrity + +[ID: security-integrity] + +- Never deserialize untrusted data with a format that can instantiate + arbitrary types; use a data-only format such as JSON +- Validate the structure and types of deserialized data before use; treat + it as untrusted input +- Verify integrity of downloaded artifacts, updates, and dependencies; use + checksums or digital signatures +- Pin dependency versions and verify checksums in lockfiles; do not trust + upstream registries blindly +- Use pinned, verified steps and images in CI/CD pipelines (MUST) +- Never pull `latest` tags in production CI/CD pipelines + +## Server-Side Request Forgery (SSRF) + +[ID: security-ssrf] + +- Never pass user-supplied URLs directly to server-side HTTP clients; + validate and sanitize first +- Allowlist permitted destination hosts and schemes; reject anything not + on the list +- Block a request whose resolved address is not public, in IPv4 and IPv6 + alike: loopback, private, link-local, unique-local, shared, unspecified, + multicast and reserved ranges +- Unwrap an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`) to its IPv4 + form before classifying it +- Classify with an address library, never a hand-kept CIDR list +- Use the standard library's address module where the runtime has one, + and a maintained external library where it has none +- Test each excluded category by its own predicate; a library's single + "is public" test can still admit multicast +- Resolve the hostname once, validate the IP, and connect only to that + address; a client that resolves the name again can be rebound by DNS +- Keep TLS verifying the certificate against the original hostname when + the connection is pinned to the validated address +- Disable HTTP redirects in server-side HTTP clients, or resolve and + validate each redirect's destination the same way +- Limit response size and timeout for outbound requests to prevent + resource exhaustion + +## File uploads + +[ID: security-uploads] + +- Validate file type by content (magic bytes), not by extension or MIME + type; both are trivially spoofed +- Enforce maximum file size at the boundary +- Store uploads outside the web root; never serve user uploads from the + same domain without sanitization +- Generate random filenames; do not use the original filename (path + traversal risk) +- Scan uploaded files for malware if the application serves them to other + users + +## Agent secrets handling + +[ID: security-agent-secrets] + +- Never read, print, or cat files that may contain secrets (MUST NOT): + `.env`, `credentials.json`, `*-key*`, `*.pem`, `*.key`, + `serviceaccount.json`, `secrets.yaml` +- Never echo, log, or display environment variable values (MUST NOT) +- Check a variable's presence by its exact name without printing its value, + and treat a set but empty variable as absent +- Never include secret values in commit messages, PR descriptions, or + conversation output (MUST NOT) +- Warn the user (MUST) before committing files that commonly contain + secrets (`.env`, `credentials.json`, private keys) +- Verify a secret's presence by a match count or an existence check, + never by printing it +- Flag a secret exposed in a session to the user immediately: name the + exposed secret, recommend immediate rotation, and note that session + history may be cached or logged diff --git a/tests/efficacy/arms/lazyskills/skills/base-testing/SKILL.md b/tests/efficacy/arms/lazyskills/skills/base-testing/SKILL.md new file mode 100644 index 0000000..1fc9375 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/base-testing/SKILL.md @@ -0,0 +1,238 @@ +--- +name: base-testing +description: Test types, isolation, assertions, proving a change +--- + +# Base — Testing + +[ID: base-testing] + +What to test, how to keep tests honest, and how to prove a change. + +## Test types + +Classify a test by the boundary it crosses, not by who runs it or which +tool drives it. + +| Type | Boundary crossed | Focus | +| --- | --- | --- | +| Unit | None | One function or class in isolation | +| Integration | Process or component | Interaction with a real dependency | +| System | System | The product against its requirements | +| Regression | Any, reusing existing tests | Unintended change | +| Exploratory | Any, unscripted | Unexpected behaviour | + +- Double only what a unit test would cross a boundary to reach: I/O, time, + randomness, another process +- Keep deterministic in-process collaborators real +- Use the real dependency for the boundary an integration test covers; you + MAY double the unrelated ones +- Add a regression test for every fixed defect (SHOULD) + +## Coverage + +- Cover every happy path the functional requirements define +- Cover negative inputs and edge cases as well (SHOULD) +- Cover each dependency's faults at every tier: unavailable, malformed + response, timeout, degraded operation (SHOULD) +- Meet the project's coverage threshold for new code before merging +- Never let coverage regress between releases +- Run every unit test from CI, with no human step +- Name a test so the name alone states the unit, the input and the expected + outcome (SHOULD) +- Run a unit that reads a structured external artifact against real + production data once before calling its suite complete, and add a + regression test for each gap it shows + +## Testability + +- Keep business logic in pure functions, and push I/O to thin adapters at + the edges (SHOULD) +- Inject dependencies rather than construct them in the code under test + (SHOULD) +- Split a function that needs more than two mocks to test (SHOULD) +- Treat code that is hard to test as a design problem + +## Isolation + +[ID: base-testing-general] + +- Test behaviour, not implementation details +- Set or clear every environment variable a test depends on, in that test; + never rely on the ambient process state +- Treat a test that passes or fails by run order as an isolation bug +- Wait on a condition with a deadline, never a fixed sleep +- Never enumerate, signal or terminate a process the test did not start + (MUST NOT) +- Never mutate host state outside the working directory: the process + table, system services, the registry, the user's applications (MUST NOT) +- Stub every seam through which the code under test reaches a host + resource the test does not own, even when its subject is already faked +- Keep the dependency an integration test covers real, isolated to that + test, such as a throwaway container or a temporary database +- Investigate a failing test before anything else; never skip or suppress + one without a documented reason +- Check the test's own logic first when it behaves unexpectedly + +## External definitions + +[ID: testing-external-definition] + +- Assert at least one case against a fixed vector the specification + publishes, wherever a format is defined outside the codebase (MUST) +- Never take a round trip through your own encoder and decoder as proof + that either is correct +- Assert what an object does, not the type the runtime reports for it +- Assert that a misuse fails, and which error only where the interface + declares one +- Never assert an exception class the runtime raises on its own + +## Guard use + +[ID: testing-guard-is-used] + +- Assert that the code under test takes a guard, not only that the guard + works, where the guard exists for other code to take (MUST) +- Prefer a behavioural assertion, such as "a stopped component does no + work" +- Otherwise wrap the real guard in a recorder that logs entry and exit, and + assert the order of the work against it +- Pair every "does nothing" assertion with its "does something" control +- Sweep the module for sibling guards when one proves inert + +```bash +MODULE= +FIELD= +echo "references to $FIELD in $MODULE: $(grep -c "$FIELD" "$MODULE" || true)" +grep -n "$FIELD" "$MODULE" || true +``` + +Pass condition: the count is at least two and the listed lines include a +consumer. A count of one is the assignment alone: the guard is built and +never consulted. + +## Provenance + +[ID: testing-assert-provenance] + +- Assert the source of a value, not the value, where a fix changes where it + comes from +- For such a fix, inject a source that yields a different value, and assert + the code overrides it +- Treat a new test that passes against the unfixed code as aimed at the + wrong property, not as proof the fix was unnecessary +- Substitute at the name the module under test reads, not on the module + that defines the type + +## Thresholds + +[ID: testing-name-what-pinned] + +- State, beside every threshold assertion, the property it gates, the + conditions it was calibrated under and what to do when an improvement + moves it +- Name the property in the failure message, not only the observed value + +## Empty results + +[ID: testing-negative-assertion-coverage] + +### Reach + +- Assert that a test expecting no violations reached its inputs: compare + the files it discovered against what its roots should cover (MUST) +- Fail on that comparison; never print a count for a reader to notice +- Report every occurrence, not the first per line or per file +- Fail an "every item holds" assertion when the set shrinks unexpectedly +- Give the coverage assertion its own test and its own message (SHOULD) +- Assert that each item declares its own value where a permissive default + exists; prefer a default that is not a legal value + +### Floors + +- Assert a known floor, not mere non-emptiness +- Size the floor from a measurement, and state the derivation beside the + constant +- Use the measured count for an append-only corpus, and a stated margin + below it for one that churns + +## Fault injection + +[ID: testing-platform-fault-injection] +[LOAD: write-tests] + +- Reproduce a fault that depends on the OS, filesystem, locale or + interpreter with a double at the real call's seam; never wait for the + platform to supply it (MUST) +- Clear a transient fault as it fires; give a permanent fault its own + double (MUST) +- Name the platform the evidence came from wherever a test clears a + suspected component +- Distrust a suspect cleared on one platform; retest it on the platforms + the evidence did not cover (SHOULD) + +## Unique resources + +[ID: testing-unique-resource-allocation] +[LOAD: write-tests] + +- Allocate a per-test port, directory, database or queue from a + module-level counter or a fixture, never from a counter on a class other + tests inherit (MUST) + +## Worker leaks + +[ID: testing-worker-leak-guard] +[LOAD: write-tests] + +- Assert after every test that no thread, subprocess or server the suite + started survives it (MUST) +- Run the assertion per test, not once at session end +- Name the leak in the message, and the fix: join with a timeout, never + sleep +- Leave the assertion on permanently + +## Call sites + +[ID: testing-shared-path-breadth] + +- Exercise every call site of a changed shared path, not only the reported + case (MUST) +- Run the ground-truth comparison on every entity that uses the path +- Re-run every consumer that derives a committed artifact from the changed + surface, and keep that list beside the surface + +## Real data + +[ID: testing-fix-fires-on-real-data] + +- Drive a diagnostic view through the production entry point behind a + flag, never a separate command with its own setup +- Run the real pipeline on the input a fix targets, and diff its output + against the expected values +- Never take passing unit tests, suites and staleness checks as proof that + the fix fired + +## Rendered output + +[ID: testing-verify-the-render] + +- Verify a visual change on its rendered output, read headless off the + pixels or the resolved DOM, never off the source (MUST) +- Capture the render before the change as well as after it (SHOULD) +- Confirm the build is fresh before re-editing a change that still looks + wrong + +## Drift guards + +[ID: testing-drift-guard] + +- Give every fact stored in two places a test that fails when the copies + diverge, such as: + - a documented limit and its constant + - live routes and the API contract + - the runtime version and the package metadata + - an export list and the module's bindings +- Introspect the live artifact rather than hardcode the expected value + (SHOULD) +- Assert one direction: the derived copy matches the source of truth diff --git a/tests/efficacy/arms/lazyskills/skills/frontend-ux/SKILL.md b/tests/efficacy/arms/lazyskills/skills/frontend-ux/SKILL.md new file mode 100644 index 0000000..9a07241 --- /dev/null +++ b/tests/efficacy/arms/lazyskills/skills/frontend-ux/SKILL.md @@ -0,0 +1,86 @@ +--- +name: frontend-ux +description: UX principles, WCAG 2.1 AA, accessibility testing, design system, browser support +--- + +# Frontend — UX Principles + +[ID: frontend-ux] +[DEPENDS ON: templates/core/quality.md] + +## UX principles + +- Make every view usable on a small screen, not only on a desktop one +- Show only what the user needs at each step +- Never use a dark pattern: misleading UI, a forced action, a hidden cost +- Use the same interaction pattern for the same task throughout +- Treat a slow interface as a UX defect +- Make every component behave as it looks: what looks like a button acts + like one + +## Accessibility — WCAG 2.1 AA + +- Meet WCAG 2.1 AA +- Keep text contrast at 4.5:1 or more, 3:1 for large text +- Make every interactive element reachable and operable by keyboard +- Never put a click handler on a non-focusable element (MUST NOT); it adds + no tab stop or keyboard activation +- Use a native interactive element for such a control instead: a button, a + link or another native control +- Style focus with `:focus-visible`, not `:focus`, which also outlines + mouse clicks +- Keep a visible focus indicator on every focusable element, links and nav + links included (MUST); links often lack one even where buttons have it +- Never convey meaning by colour alone +- Give images descriptive `alt` text, and decorative ones `alt=""` +- Use semantic HTML: landmark elements and a correct heading hierarchy +- Give an icon-only or ambiguous control, such as a social link, a + descriptive `aria-label`; never add one where visible text already names + the control +- Make an accessible name contain the control's visible text, ideally at + its start (WCAG 2.5.3, Label in Name) +- Close menus on Escape and restore focus + +## Accessibility testing + +Automated tools catch about 30–40% of WCAG issues, so AA takes manual +testing too. + +### Automated (run in CI) + +- Scan rendered pages or components with an automated accessibility + checker in CI; merge on zero violations + +### Manual (run before shipping new interactive components) + +- Tab through the whole feature without a mouse: every action reachable, + focus order logical, no focus trap but an intentional modal +- Test it with one screen reader, such as NVDA, VoiceOver or TalkBack, and + check every content and state change is announced +- Zoom to 200%: nothing clipped or overlapping, and no horizontal scroll + at a 1280px viewport +- Check Windows High Contrast or the forced-colors media query: no + information lost when colours are overridden + +### Criteria for done + +A feature is not complete until: + +- [ ] The automated accessibility check reports zero violations +- [ ] Keyboard navigation verified manually +- [ ] Screen reader walkthrough completed for new interactive elements + +## Design system + +- Use the project's design system where one exists; never build an ad-hoc + component that duplicates one of its patterns +- Take design tokens (colours, spacing, typography, radii, breakpoints) + from the design system (MUST); never hardcode a visual value + +## Browser support + +[ID: frontend-ux-browsers] + +- Support the last two versions of Chrome, Firefox, Safari and Edge by + default +- Degrade gracefully where a browser lacks a feature diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index e3664fa..01e526c 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -10,10 +10,14 @@ 88 characters - `skills` is what `resolve_chain.py --emit` builds, the facts filled from the brief +- `lazyref` and `lazyskills` are fixed text too: a map from the topics the + manifest gives each template of the chain to that template, read as a file + or loaded as a skill the first time the work touches one of them, and for + `lazyskills` one skill per template, holding it verbatim -It writes `arms//CLAUDE.md` (and, for `skills`, the skills beside it), -and refuses to keep a result the specification leaked into, or one over its -arm's budget. +It writes `arms//CLAUDE.md` (and, for an arm with skills, the skills +beside it), and refuses to keep a result the specification leaked into, or +one over its arm's budget. Run it once per arm. Re-running it produces a different file and therefore a different arm, so it refuses to overwrite an existing one without @@ -30,6 +34,7 @@ import subprocess import sys import tempfile +import textwrap import time from harness import (ROUND5_DECLINED, ROUND5_REF, # noqa: E402 @@ -47,9 +52,10 @@ # The arms this module makes, each with the directory under `arms/` its file # and record live in, and how it is made: fixed text, a model generation in -# one of `agents.md`'s models, or the emitter, and a model arm's budget as -# (lines, width) where it has one. `hand` is a person's file, kept verbatim -# with no record, so it is not made here. +# one of `agents.md`'s models, the emitter, or a map of the chain's topics +# read as files or loaded as skills, and a model arm's budget as (lines, +# width) where it has one. `hand` is a person's file, kept verbatim with no +# record, so it is not made here. GENERATED = { "reference": {"dir": "reference", "kind": "fixed"}, "inline": {"dir": "inline", "kind": "model", "model": "inline"}, @@ -57,6 +63,8 @@ "skills": {"dir": "skills", "kind": "emit"}, "short": {"dir": "short", "kind": "model", "model": "inline", "budget": (40, 88)}, + "lazyref": {"dir": "lazyref", "kind": "map", "load": "read"}, + "lazyskills": {"dir": "lazyskills", "kind": "map", "load": "skill"}, } @@ -337,6 +345,120 @@ def reference_text(files): return REFERENCE.format(into=VENDORED["into"], files=listed) +# The templates' manifest: one entry per template, with the file it lives in +# and its one-line description. The fields are frozen for the 3.x line, so +# three line patterns read them without a YAML library. +MANIFEST = os.path.join("templates", "manifest.yaml") +MANIFEST_ID = re.compile(r"^\s*- id: (\S+)\s*$") +MANIFEST_FIELD = re.compile(r"^\s*(file|description|deprecated): (.*?)\s*$") + + +def read_manifest(tree): + """The manifest's live entries, {file: (id, description)}, a deprecated + entry never shadowing the one that replaces it.""" + found_entries = [] + with io.open(os.path.join(tree, MANIFEST), encoding="utf-8") as handle: + for line in handle: + found = MANIFEST_ID.match(line) + if found: + found_entries.append({"id": found.group(1)}) + continue + found = MANIFEST_FIELD.match(line) + if found and found_entries: + found_entries[-1][found.group(1)] = found.group(2) + # An entry is read whole before it counts, since its fields come in any + # order and a deprecation may follow its description. + entries = {} + for entry in found_entries: + if "file" in entry and "description" in entry \ + and "deprecated" not in entry: + entries.setdefault(entry["file"], + (entry["id"], entry["description"])) + return entries + + +def moments(tree, files): + """Each template of the chain with the moment that calls for it: (id, + description, file), in the chain's order. + + The moment is the manifest's own description of the template, so the + map puts no person's judgement into the arm, and the two map arms name + the same moments from the same source. + """ + entries = read_manifest(tree) + rows = [] + for name in files: + if name not in entries: + raise TrialError("%s is in the chain and not in the manifest, so " + "the map has no moment for it" % name) + kind, description = entries[name] + rows.append((kind, description, name)) + return rows + + +# The map arms' root file. The two differ in one column and one verb: what +# the agent does when a moment arrives, read a vendored file or load a skill. +# Everything before the table says the same thing in both, so the arms +# measure the mechanism and not the wording. +MAP = """\ +# tariff + +{paragraph} + +| When the work first touches | {column} | +| --- | --- | +{rows} +""" + +MAP_PARAGRAPH = ("The project's rules are the templates below, one per topic. " + "Do not read them before the work starts. {when}, {act}; " + "then apply every rule it holds that fits this project.") + +MAP_LOAD = { + "read": { + "when": "The first time the work touches a template's topics", + "act": "read that template, vendored at `{into}/` at the revision " + "the project adopted", + "column": "Read first", + "cell": "`{into}/{file}`", + }, + "skill": { + "when": "The first time the work touches a template's topics", + "act": "load that template's skill", + "column": "Load first", + "cell": "`{kind}`", + }, +} + + +def map_text(rows, load): + """A map arm's root file: the same moments, in the same order, for + either way of loading.""" + words = MAP_LOAD[load] + into = VENDORED["into"] + table = "\n".join( + "| %s | %s |" % (description, + words["cell"].format(into=into, file=name, kind=kind)) + for kind, description, name in rows) + paragraph = textwrap.fill( + MAP_PARAGRAPH.format(when=words["when"], + act=words["act"].format(into=into)), width=79) + return MAP.format(paragraph=paragraph, column=words["column"], rows=table) + + +def template_skills(tree, rows): + """One skill per template of the chain, {id: SKILL.md text}: the + manifest's description as what the skill is for, and the template + verbatim as its body.""" + skills = {} + for kind, description, name in rows: + with io.open(os.path.join(tree, name), encoding="utf-8") as handle: + body = handle.read() + skills[kind] = ("---\nname: %s\ndescription: %s\n---\n\n%s" + % (kind, description, body)) + return skills + + def fill_facts(text): """The emitted root file with every fact slot filled from the brief.""" for slot, value in FACTS.items(): @@ -469,6 +591,73 @@ def self_test(): print("the reference text names every file under %s/, the same twice" % VENDORED["into"]) + # A map is checked against a small tree of its own: a manifest with a + # deprecated entry sharing a live one's file, and two templates. + tree = tempfile.mkdtemp(prefix="efficacy-map-self-test-") + try: + chain = ["templates/core/quality.md", "templates/backend/api.md"] + bodies = {chain[0]: "# Quality\n\n- Keep it simple (MUST)\n", + chain[1]: "# API\n\n- Version the contract\n"} + for name, body in bodies.items(): + path = os.path.join(tree, *name.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with io.open(path, "w", encoding="utf-8", newline="\n") as h: + h.write(body) + manifest = os.path.join(tree, MANIFEST) + with io.open(manifest, "w", encoding="utf-8", newline="\n") as h: + h.write("version: \"1.0\"\n\nbase:\n" + " - id: old-quality\n file: templates/core/quality.md\n" + " description: An old name\n" + " deprecated: base-quality\n" + " - id: base-quality\n file: templates/core/quality.md\n" + " description: Architecture, code style, testing\n" + "backend:\n" + " - id: backend-api\n file: templates/backend/api.md\n" + " description: API-first, contracts, versioning\n") + rows = moments(tree, chain) + reading = map_text(rows, "read") + loading = map_text(rows, "skill") + first = [line.split(" | ")[0] for line in reading.splitlines() + if line.startswith("| ") and not line.startswith("| ---")] + second = [line.split(" | ")[0] for line in loading.splitlines() + if line.startswith("| ") and not line.startswith("| ---")] + expected = ["| When the work first touches", + "| Architecture, code style, testing", + "| API-first, contracts, versioning"] + if first != expected or second != expected: + print("FAIL: the two map arms do not name the same moments in " + "the chain's order: %r, %r" % (first, second)) + return 1 + print("the two map arms name the same moments in the chain's order") + if any(reading.count("`%s/%s`" % (VENDORED["into"], name)) != 1 + for name in chain) or "`base-quality`" in reading: + print("FAIL: the reading map does not name every template once " + "under the vendored path") + return 1 + print("the reading map names every template of the chain once, under " + "%s/" % VENDORED["into"]) + skills = template_skills(tree, rows) + head = "---\nname: backend-api\ndescription: API-first, contracts, " \ + "versioning\n---\n\n" + if sorted(skills) != ["backend-api", "base-quality"] \ + or skills["backend-api"] != head + bodies[chain[1]] \ + or "`backend-api`" not in loading: + print("FAIL: a template skill is not its template verbatim under " + "the manifest's name and description") + return 1 + print("each template skill is its template verbatim, named by the " + "manifest") + try: + moments(tree, chain + ["templates/core/git.md"]) + print("FAIL: a chain file the manifest does not describe was " + "given a moment") + return 1 + except TrialError: + pass + print("a chain file the manifest does not describe is refused") + finally: + shutil.rmtree(tree, ignore_errors=True) + known = " ".join(FACTS) if SLOT.search(fill_facts(known)): print("FAIL: a known fact slot was left unfilled") @@ -567,6 +756,15 @@ def main(argv): elif entry["kind"] == "emit": document, skills = emit_arm(tree, ROUND5_ROOTS) record["declined"] = ROUND5_DECLINED + elif entry["kind"] == "map": + rows = moments(tree, files) + document = map_text(rows, entry["load"]) + if entry["load"] == "skill": + skills = template_skills(tree, rows) + record["load"] = entry["load"] + record["moments"] = [{"skill": kind, "moment": description, + "file": name} + for kind, description, name in rows] else: prompt = build_prompt(tree, arm, files) finally: @@ -612,7 +810,7 @@ def main(argv): os.makedirs(os.path.dirname(output), exist_ok=True) with io.open(output, "w", encoding="utf-8", newline="\n") as handle: handle.write(document.rstrip() + "\n") - if entry["kind"] == "emit": + if skills: shutil.rmtree(skills_path(arm), ignore_errors=True) for kind, text in skills.items(): path = os.path.join(skills_path(arm), kind, "SKILL.md") diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index cb6183c..cf9338f 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -82,6 +82,10 @@ # at its registered content, against round 5c's arms. ROUND5D_ARMS = ("hand", "short") +# Round 5e runs the two map arms under the same design: the templates read +# as files, or loaded as skills, at the moment the work touches their topics. +ROUND5E_ARMS = ("lazyref", "lazyskills") + # The release every generated arm is produced from, and the one the hybrid # arm's vendored templates are taken at, fixed before the first round: the # last 2.x, before the v3.0 split moves any template. @@ -145,6 +149,12 @@ "context": "inline/CLAUDE.md"}, "skills": {"label": "the emitted root file and task skills", "context": "skills/CLAUDE.md", "skills": "skills/skills"}, + "lazyref": {"label": "the templates, mapped to the work, read on demand", + "context": "lazyref/CLAUDE.md", "vendor": VENDORED}, + "lazyskills": {"label": "the templates, mapped to the work, one skill " + "each", + "context": "lazyskills/CLAUDE.md", + "skills": "lazyskills/skills"}, } def trial_name(arm, block): @@ -1547,11 +1557,11 @@ def spec_digest(path): def spec_problem(arms, spec_name, digest): """Why a run of these arms may not build from this spec, or None. - A run holding a round-5 or round-5d arm builds from the spec round 5 - registers, at the content it registers; any other run is not checked - here. + A run holding a round-5, round-5d or round-5e arm builds from the spec + round 5 registers, at the content it registers; any other run is not + checked here. """ - if not set(arms) & set(ROUND5_ARMS + ROUND5D_ARMS): + if not set(arms) & set(ROUND5_ARMS + ROUND5D_ARMS + ROUND5E_ARMS): return None name, registered = ROUND5_SPEC if spec_name != name: @@ -3398,6 +3408,14 @@ def round5_checks(): and ARMS["skills"].get("skills") is not None), ("an arm that vendors nothing has no vendored ref", arm_vendor("none") is None and arm_vendor("inline") is None), + ("round 5e's arms: lazyref vendors, lazyskills has skills, and both " + "build from round 5's spec", + ARMS["lazyref"].get("vendor") is not None + and ARMS["lazyref"].get("skills") is None + and ARMS["lazyskills"].get("skills") is not None + and ARMS["lazyskills"].get("vendor") is None + and spec_problem(["lazyref"], "thin", ROUND5_SPEC[1]) is not None + and spec_problem(["lazyskills"], *ROUND5_SPEC) is None), ] record = os.path.join(ARMS_DIR, "hybrid", "generation.json") with io.open(record, encoding="utf-8") as handle: @@ -3692,17 +3710,20 @@ def main(argv): print("generator ready: %s" % ready) # Files in `.claude/skills/` are not skills an agent sees until the - # CLI discovers them, so a run with the skills arm proves it first. - if "skills" in arms: + # CLI discovers them, so a run with an arm carrying skills proves it + # first, for each such arm. + for arm in arms: + if not ARMS[arm].get("skills"): + continue try: seen = assert_skills_discovered( home, agent_environment, agent_executable(), - os.path.join(ARMS_DIR, ARMS["skills"]["skills"])) + os.path.join(ARMS_DIR, ARMS[arm]["skills"])) except (TrialError, subprocess.TimeoutExpired) as error: print("refused: %s" % error) lib.print_verdict(False, "0 trial(s), 0 done, 1 refused") return 1 - print("the agent sees the skills arm's %d skills" % len(seen)) + print("the agent sees the %s arm's %d skills" % (arm, len(seen))) started_at = now() run_file = os.path.join( diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index f203e1b..b806b7a 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -1959,6 +1959,10 @@ def vector_lines(results, active): "skills": "a root file plus one skill per kind of task", "hand": "a short file a person wrote", "short": "the templates' rules cut down to 40 lines", + "lazyref": "a short file that maps each kind of work to the template to " + "read when that work starts", + "lazyskills": "the same map, each template loaded as a skill when that " + "work starts", } # Each radar axis in plain words, as a sentence names it.