From e5c2889359a716b70b8f1975ba639144028076be Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:46:00 +0200 Subject: [PATCH 1/4] feat(efficacy): build the lazysections and lazyrefold arms for round 6 - lazysections: the templates' emitter with --sections, same roots and declined list as the other emitted arms; the map is the root, the section files land at .agents/sections/ where it names them, out of the index - lazyrefold: lazyref built at the parent of the check-loop commit (a8079352^ = 4e1de818); named without a hyphen, since trial names and hypothesis labels split an arm's word on one - self-tests: lazyref and lazyrefold differ by that commit's quality.md lines alone, all in "Static checks", read from the templates' own diff; the section files hold exactly the inline root's rule blocks, each named once by the map; no on-demand arm tells the agent to read everything at the start; each check proven by a planted fault - both arms added to harness.ARMS and to C1's registered arms, which changes C1's registration digest (no C1 trial has run) - docs: journey, building block view, ADR-026's arm list, FR-13-22 to 24 The arms are pinned at the open templates branch refs (lazysections at d6da8f33, feat/check-loop's tip; lazyrefold at 4e1de818). Every arm is re-pinned at one ref once the templates PRs merge. Refs #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/05-building-block-view.md | 4 +- docs/coverage.md | 3 + .../026-every-arm-is-built-by-a-script.md | 2 +- docs/journeys/prepare/generate-the-arms.md | 10 +- docs/requirements.md | 3 + tests/efficacy/arms/lazyrefold/CLAUDE.md | 40 ++ .../efficacy/arms/lazyrefold/generation.json | 109 +++++ tests/efficacy/arms/lazysections/CLAUDE.md | 257 ++++++++++ .../arms/lazysections/generation.json | 175 +++++++ .../sections/backend-api/api-contract.md | 21 + .../sections/backend-api/api-first.md | 8 + .../backend-api/backward-compatibility.md | 10 + .../backend-api/deprecation-strategy.md | 14 + .../sections/backend-api/pagination.md | 6 + .../backend-api/protocol-selection.md | 18 + .../sections/backend-api/statelessness.md | 8 + .../sections/backend-api/versioning.md | 9 + .../sections/backend-auth/authentication.md | 54 +++ .../sections/backend-auth/authorization.md | 67 +++ .../backend-auth/general-principles.md | 62 +++ .../sections/backend-auth/observability.md | 64 +++ .../sections/backend-auth/testing.md | 66 +++ .../sections/backend-auth/token-transport.md | 63 +++ .../sections/backend-database/connections.md | 10 + .../sections/backend-database/indexing.md | 9 + .../sections/backend-database/queries.md | 14 + .../backend-database/schema-changes.md | 11 + .../sections/backend-database/soft-deletes.md | 9 + .../sections/backend-database/testing.md | 58 +++ .../sections/backend-database/transactions.md | 10 + .../sections/backend-http/admin-processes.md | 10 + .../authentication-and-authorisation.md | 26 + .../sections/backend-http/error-responses.md | 12 + .../sections/backend-http/handler-design.md | 8 + .../sections/backend-http/http-methods.md | 7 + .../sections/backend-http/port-binding.md | 8 + .../backend-http/process-lifecycle.md | 21 + .../sections/backend-http/query-parameters.md | 10 + .../sections/backend-http/request-headers.md | 10 + .../backend-http/resource-representation.md | 23 + .../base-data-governance/audit-trail.md | 20 + .../data-classification.md | 20 + .../base-data-governance/data-ownership.md | 13 + .../base-data-governance/pii-handling.md | 19 + .../base-data-governance/retention.md | 17 + .../sections/base-data-modeling/data-types.md | 17 + .../base-data-modeling/naming-conventions.md | 9 + .../base-data-modeling/normalization.md | 14 + .../base-data-modeling/relationships.md | 18 + .../base-data-modeling/schema-evolution.md | 19 + .../base-docs/adopting-shared-rules.md | 20 + .../sections/base-docs/cold-readers.md | 13 + .../sections/base-docs/diagrams-and-assets.md | 13 + .../sections/base-docs/disagreements.md | 14 + .../sections/base-docs/docs-as-code.md | 8 + .../sections/base-docs/generated-files.md | 17 + .../sections/base-docs/line-width.md | 24 + .../base-docs/output-file-by-agent.md | 13 + .../sections/base-docs/rule-language.md | 17 + .../sections/base-docs/session-handoff.md | 23 + .../base-docs/single-source-of-truth.md | 11 + .../sections/base-docs/standard-documents.md | 13 + .../lazysections/sections/base-docs/upkeep.md | 14 + .../sections/base-docs/writing-style.md | 17 + .../sections/base-git/ci-evidence.md | 15 + .../lazysections/sections/base-git/commits.md | 17 + .../sections/base-git/existing-changes.md | 15 + .../sections/base-git/off-limits-paths.md | 35 ++ .../sections/base-git/pull-requests.md | 11 + .../base-git/regenerated-artifacts.md | 47 ++ .../sections/base-git/updating-a-branch.md | 14 + .../sections/base-quality/architecture.md | 8 + .../sections/base-quality/check-trust.md | 13 + .../sections/base-quality/comments.md | 14 + .../sections/base-quality/completion.md | 16 + .../sections/base-quality/complexity.md | 17 + .../sections/base-quality/debug-code.md | 18 + .../sections/base-quality/dependencies.md | 33 ++ .../base-quality/deprecation-and-renames.md | 14 + .../base-quality/destructive-operations.md | 21 + .../base-quality/encoding-and-line-endings.md | 48 ++ .../sections/base-quality/enforcement.md | 13 + .../sections/base-quality/errors.md | 16 + .../sections/base-quality/library-output.md | 11 + .../sections/base-quality/module-structure.md | 8 + .../sections/base-quality/naming.md | 13 + .../sections/base-quality/new-constraints.md | 8 + .../sections/base-quality/principles.md | 17 + .../base-quality/rejected-mechanisms.md | 10 + .../sections/base-quality/static-checks.md | 30 ++ .../sections/base-review/ci-signals.md | 14 + .../sections/base-review/deviations.md | 10 + .../sections/base-review/must-checklist.md | 19 + .../base-review/picking-up-an-issue.md | 25 + .../sections/base-review/planning.md | 13 + .../sections/base-review/principle.md | 11 + .../sections/base-review/priority-order.md | 22 + .../sections/base-review/should-checklist.md | 12 + .../sections/base-review/structure-audit.md | 13 + .../base-review/verifying-a-finding.md | 57 +++ .../base-security/agent-secrets-handling.md | 28 ++ .../sections/base-security/authentication.md | 54 +++ .../cross-site-request-forgery-csrf.md | 33 ++ .../deserialization-and-data-integrity.md | 23 + .../sections/base-security/error-handling.md | 22 + .../base-security/injection-prevention.md | 18 + .../base-security/input-validation.md | 23 + .../sections/base-security/logging.md | 26 + .../base-security/output-encoding-xss.md | 22 + .../sections/base-security/secrets-in-code.md | 17 + .../base-security/security-headers.md | 32 ++ .../base-security/session-management.md | 20 + .../base-security/transport-security.md | 18 + .../sections/base-testing/call-sites.md | 11 + .../sections/base-testing/coverage.md | 58 +++ .../sections/base-testing/drift-guards.md | 15 + .../sections/base-testing/empty-results.md | 24 + .../base-testing/external-definitions.md | 14 + .../sections/base-testing/fault-injection.md | 15 + .../sections/base-testing/guard-use.md | 25 + .../sections/base-testing/isolation.md | 22 + .../sections/base-testing/provenance.md | 14 + .../sections/base-testing/real-data.md | 12 + .../sections/base-testing/rendered-output.md | 11 + .../sections/base-testing/test-types.md | 58 +++ .../sections/base-testing/testability.md | 58 +++ .../sections/base-testing/thresholds.md | 10 + .../sections/base-testing/unique-resources.md | 9 + .../sections/base-testing/worker-leaks.md | 12 + .../frontend-ux/accessibility-testing.md | 30 ++ .../frontend-ux/accessibility-wcag-2-1-aa.md | 24 + .../sections/frontend-ux/browser-support.md | 7 + .../sections/frontend-ux/design-system.md | 8 + .../sections/frontend-ux/ux-principles.md | 11 + tests/efficacy/generate_arm.py | 443 ++++++++++++++++-- tests/efficacy/harness.py | 69 ++- 136 files changed, 3624 insertions(+), 62 deletions(-) create mode 100644 tests/efficacy/arms/lazyrefold/CLAUDE.md create mode 100644 tests/efficacy/arms/lazyrefold/generation.json create mode 100644 tests/efficacy/arms/lazysections/CLAUDE.md create mode 100644 tests/efficacy/arms/lazysections/generation.json create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/api-contract.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/api-first.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/backward-compatibility.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/deprecation-strategy.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/pagination.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/protocol-selection.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/statelessness.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-api/versioning.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/authentication.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/authorization.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/general-principles.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/observability.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/testing.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-auth/token-transport.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/connections.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/indexing.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/queries.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/schema-changes.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/soft-deletes.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/testing.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-database/transactions.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/admin-processes.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/authentication-and-authorisation.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/error-responses.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/handler-design.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/http-methods.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/port-binding.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/process-lifecycle.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/query-parameters.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/request-headers.md create mode 100644 tests/efficacy/arms/lazysections/sections/backend-http/resource-representation.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-governance/audit-trail.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-governance/data-classification.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-governance/data-ownership.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-governance/pii-handling.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-governance/retention.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-modeling/data-types.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-modeling/naming-conventions.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-modeling/normalization.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-modeling/relationships.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-data-modeling/schema-evolution.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/adopting-shared-rules.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/cold-readers.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/diagrams-and-assets.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/disagreements.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/docs-as-code.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/generated-files.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/line-width.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/output-file-by-agent.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/rule-language.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/session-handoff.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/single-source-of-truth.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/standard-documents.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/upkeep.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-docs/writing-style.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/ci-evidence.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/commits.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/existing-changes.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/off-limits-paths.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/pull-requests.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/regenerated-artifacts.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-git/updating-a-branch.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/architecture.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/check-trust.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/comments.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/completion.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/complexity.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/debug-code.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/dependencies.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/deprecation-and-renames.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/destructive-operations.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/encoding-and-line-endings.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/enforcement.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/errors.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/library-output.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/module-structure.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/naming.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/new-constraints.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/principles.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/rejected-mechanisms.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-quality/static-checks.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/ci-signals.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/deviations.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/must-checklist.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/picking-up-an-issue.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/planning.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/principle.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/priority-order.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/should-checklist.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/structure-audit.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-review/verifying-a-finding.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/agent-secrets-handling.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/authentication.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/cross-site-request-forgery-csrf.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/deserialization-and-data-integrity.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/error-handling.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/injection-prevention.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/input-validation.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/logging.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/output-encoding-xss.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/secrets-in-code.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/security-headers.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/session-management.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-security/transport-security.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/call-sites.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/coverage.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/drift-guards.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/empty-results.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/external-definitions.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/fault-injection.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/guard-use.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/isolation.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/provenance.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/real-data.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/rendered-output.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/test-types.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/testability.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/thresholds.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/unique-resources.md create mode 100644 tests/efficacy/arms/lazysections/sections/base-testing/worker-leaks.md create mode 100644 tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-testing.md create mode 100644 tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-wcag-2-1-aa.md create mode 100644 tests/efficacy/arms/lazysections/sections/frontend-ux/browser-support.md create mode 100644 tests/efficacy/arms/lazysections/sections/frontend-ux/design-system.md create mode 100644 tests/efficacy/arms/lazysections/sections/frontend-ux/ux-principles.md diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index e566429..a061028 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -15,7 +15,7 @@ dependency with its keyword. | Block | Responsibility | Reads | Writes | | ----- | -------------- | ----- | ------ | -| `generate_arm.py` | Builds one arm's file by script, with no model call: fixed text, the templates' emitter, its skills apart or inlined, or a map of the chain's topics. Scans the output for leaks and named tools; its self-test rebuilds every committed arm and fails on any difference | `brief.txt`, the templates source | `arms//CLAUDE.md`, `generation.json` | +| `generate_arm.py` | Builds one arm's file by script, with no model call: fixed text, the templates' emitter, its skills apart, inlined or cut into section files, or a map of the chain's topics. Scans the output for leaks, named tools and, in an on-demand arm, a read of everything at the start; its self-test rebuilds every committed arm and fails on any difference, on section files that part from the inline root's rules, and on a `lazyrefold` that differs from `lazyref` by more than the check-loop commit | `brief.txt`, the templates source | `arms//CLAUDE.md`, its skills or section files, `generation.json` | | `harness.py` | Prepares each workspace, runs the agent in isolation, catches reach, freezes the result, keeps the run record current. Holds a run naming a round to that round's registration, and starts its change tasks from one fixture per block | The specs, the arm files, the change prompt, the fixture manifest and its tarballs | The run root | | `reuse.py` | Copies an earlier round's trials and readings into a new root, with their tool lock | An earlier root | The run root, the scoring area | | `progress.py` | Watches a run: one bar per arm, its voided tries, its cost and the trial running; then its scoring: one bar per arm, the security readings and the trial being scored; then its judging: one bar per arm of judgings out of those owed, the failures still owed and the blind label in hand. Redrawn every 30 s. Read-only | The run records, the scoring area | The console | @@ -36,7 +36,7 @@ dependency with its keyword. | `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 | | `change-fixtures.json` | The builds a named round's change task starts from, one per block, each with its tarball's sha256 and the baseline readings that qualified it | harness | -| `arms//CLAUDE.md` | Each arm's context file. `arms//skills/` holds a skills arm's skills | harness | +| `arms//CLAUDE.md` | Each arm's context file. `arms//skills/` holds a skills arm's skills, placed at `.claude/skills/`; `arms/lazysections/sections/` holds the section files, placed at `.agents/sections/`, where the map names them | 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 fa9e8c1..112045a 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -204,6 +204,9 @@ when: | FR-13-18 | Self-test | `reuse.py` "a named round's trials copied on keep its round in the run record's header"
`reuse.py` "a reuse never mixes a named round's trials with others"
`reuse.py` "a trial copied within a named round names that round in its origin"
`report.py` "trials reused within one named round pair with those run there" | | FR-13-19 | Self-test | `report.py` "a named round is refused until its registration document is on main before its first trial"
`report.py` "a trial reused within its named round counts toward when the round began" | | FR-13-20 | Self-test | `archive.py` "a C1 change task's score changed in the archive fails the verify" | +| FR-13-22 | Self-test | `generate_arm.py` "the section files hold every rule block the inline root does, and no other"
`generate_arm.py` "the sections map names every section file once, under .agents/sections/"
`generate_arm.py` "a rule dropped from a section file, or a file the map does not name, is reported"
`harness.py` "the lazysections arm's files land where its map names them, out of the index" | +| FR-13-23 | Self-test | `generate_arm.py` "lazyref and lazyrefold differ by the check-loop commit's lines alone, all in its section"
`generate_arm.py` "a line changed besides the commit's, one of its lines missing, or one outside its section is reported"
`harness.py` "round 6's lazyrefold vendors at its own recorded ref, lazysections vendors nothing" | +| FR-13-24 | Self-test | `generate_arm.py` "no on-demand arm tells the agent to read everything at startup"
`generate_arm.py` "a root telling the agent to read everything at the start is caught" | ## 14 One run at a time diff --git a/docs/decisions/026-every-arm-is-built-by-a-script.md b/docs/decisions/026-every-arm-is-built-by-a-script.md index 90f89e5..f2d5b7c 100644 --- a/docs/decisions/026-every-arm-is-built-by-a-script.md +++ b/docs/decisions/026-every-arm-is-built-by-a-script.md @@ -70,7 +70,7 @@ no more. | ----------- | ------ | | `inline` changes | The emitter's file is 1,778 lines at `9abed019`, against the 552 a model wrote for round 5e: a new arm, with no round-5e reading | | `skills` changes | Its root now carries the brief's paragraphs on personal data and on boundaries, which it lacked; a new arm too | -| Round 6's arms | `none`, `reference`, `inline`, `skills`, `lazyref`, `lazyskills`, and those #169 adds | +| Round 6's arms | `none`, `reference`, `inline`, `skills`, `lazyref`, `lazyskills`, and the two #169 adds: `lazysections`, the emitter's section files, and `lazyrefold`, `lazyref` before the check-loop change | | The report still reads arm files from the checkout | The pilot arms' files stay so a pilot report can count their lines, until #171 | ## History diff --git a/docs/journeys/prepare/generate-the-arms.md b/docs/journeys/prepare/generate-the-arms.md index 3d2e32a..764e662 100644 --- a/docs/journeys/prepare/generate-the-arms.md +++ b/docs/journeys/prepare/generate-the-arms.md @@ -16,14 +16,16 @@ Assumptions: - The arms, all built with no model call ([ADR-026](../../decisions/026-every-arm-is-built-by-a-script.md)): `reference`, `lazyref` and `lazyskills` as fixed text, `inline` and - `skills` from the templates' emitter + `skills` from the templates' emitter, `lazysections` from its sections + mode, and `lazyrefold` as `lazyref` at the parent of the templates commit + that cuts the check loop to one check command - All times are estimates ## Steps | # | Who | Step | Time | Notes | | - | --- | ---- | ---- | ----- | -| 1 | Operator | Runs the generator's self test | 2 min | Proves the scans and the fact filling can fail, and rebuilds every committed arm | +| 1 | Operator | Runs the generator's self test | 2 min | Proves the scans and the fact filling can fail, rebuilds every committed arm, and checks the on-demand arms: no read of everything at the start, `lazyrefold` against `lazyref`, the section files against the inline root | | 2 | Operator | Dry-runs each arm at the round's ref | 1 min each | Builds and scans the files, writes nothing under `arms/` | | 3 | Generator | Builds each arm, at a root outside this repository | 1 min each | The same ref gives the same bytes | | 4 | Operator | Reads each `generation.json`: ref, chain, commit, how the file was built, its size, both scans | 5 min | The report reads it from there | @@ -36,6 +38,8 @@ Assumptions: py tests/efficacy/generate_arm.py --self-test py tests/efficacy/generate_arm.py --arm inline --ref --root --dry-run py tests/efficacy/generate_arm.py --arm inline --ref --root --replace +py tests/efficacy/generate_arm.py --arm lazysections --ref --root +py tests/efficacy/generate_arm.py --arm lazyrefold --ref ^ --root ``` ## Findings @@ -45,3 +49,5 @@ py tests/efficacy/generate_arm.py --arm inline --ref --root ` +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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-api/pagination.md b/tests/efficacy/arms/lazysections/sections/backend-api/pagination.md new file mode 100644 index 0000000..f255bc5 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-api/pagination.md @@ -0,0 +1,6 @@ +# Backend — API Design + +## Pagination +- 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/lazysections/sections/backend-api/protocol-selection.md b/tests/efficacy/arms/lazysections/sections/backend-api/protocol-selection.md new file mode 100644 index 0000000..9f6d424 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-api/protocol-selection.md @@ -0,0 +1,18 @@ +# Backend — API Design + +## Protocol selection + +| 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-api/statelessness.md b/tests/efficacy/arms/lazysections/sections/backend-api/statelessness.md new file mode 100644 index 0000000..37eabdb --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-api/statelessness.md @@ -0,0 +1,8 @@ +# Backend — API Design + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-api/versioning.md b/tests/efficacy/arms/lazysections/sections/backend-api/versioning.md new file mode 100644 index 0000000..8a1fdb9 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-api/versioning.md @@ -0,0 +1,9 @@ +# Backend — API Design + +## Versioning +- 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) diff --git a/tests/efficacy/arms/lazysections/sections/backend-auth/authentication.md b/tests/efficacy/arms/lazysections/sections/backend-auth/authentication.md new file mode 100644 index 0000000..8587c4c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/authentication.md @@ -0,0 +1,54 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-auth/authorization.md b/tests/efficacy/arms/lazysections/sections/backend-auth/authorization.md new file mode 100644 index 0000000..cd600ac --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/authorization.md @@ -0,0 +1,67 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-auth/general-principles.md b/tests/efficacy/arms/lazysections/sections/backend-auth/general-principles.md new file mode 100644 index 0000000..c4b362a --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/general-principles.md @@ -0,0 +1,62 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "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 + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-auth/observability.md b/tests/efficacy/arms/lazysections/sections/backend-auth/observability.md new file mode 100644 index 0000000..349c0d1 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/observability.md @@ -0,0 +1,64 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-auth/testing.md b/tests/efficacy/arms/lazysections/sections/backend-auth/testing.md new file mode 100644 index 0000000..9c01615 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/testing.md @@ -0,0 +1,66 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 + +## 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/lazysections/sections/backend-auth/token-transport.md b/tests/efficacy/arms/lazysections/sections/backend-auth/token-transport.md new file mode 100644 index 0000000..daaf334 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-auth/token-transport.md @@ -0,0 +1,63 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/connections.md b/tests/efficacy/arms/lazysections/sections/backend-database/connections.md new file mode 100644 index 0000000..e20c032 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/connections.md @@ -0,0 +1,10 @@ +# Backend — Database Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/indexing.md b/tests/efficacy/arms/lazysections/sections/backend-database/indexing.md new file mode 100644 index 0000000..3408607 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/indexing.md @@ -0,0 +1,9 @@ +# Backend — Database Conventions + +## Indexing + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/queries.md b/tests/efficacy/arms/lazysections/sections/backend-database/queries.md new file mode 100644 index 0000000..14e8ba6 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/queries.md @@ -0,0 +1,14 @@ +# Backend — Database Conventions + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/schema-changes.md b/tests/efficacy/arms/lazysections/sections/backend-database/schema-changes.md new file mode 100644 index 0000000..e487e60 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/schema-changes.md @@ -0,0 +1,11 @@ +# Backend — Database Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/soft-deletes.md b/tests/efficacy/arms/lazysections/sections/backend-database/soft-deletes.md new file mode 100644 index 0000000..4ac30dd --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/soft-deletes.md @@ -0,0 +1,9 @@ +# Backend — Database Conventions + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/backend-database/testing.md b/tests/efficacy/arms/lazysections/sections/backend-database/testing.md new file mode 100644 index 0000000..2c0b76b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/testing.md @@ -0,0 +1,58 @@ +# 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 + +# Backend — Database Conventions + +## 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/lazysections/sections/backend-database/transactions.md b/tests/efficacy/arms/lazysections/sections/backend-database/transactions.md new file mode 100644 index 0000000..6708f1e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-database/transactions.md @@ -0,0 +1,10 @@ +# Backend — Database Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/admin-processes.md b/tests/efficacy/arms/lazysections/sections/backend-http/admin-processes.md new file mode 100644 index 0000000..56a9288 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/admin-processes.md @@ -0,0 +1,10 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/authentication-and-authorisation.md b/tests/efficacy/arms/lazysections/sections/backend-http/authentication-and-authorisation.md new file mode 100644 index 0000000..272bc34 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/authentication-and-authorisation.md @@ -0,0 +1,26 @@ +# Backend — HTTP Conventions + +## 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/lazysections/sections/backend-http/error-responses.md b/tests/efficacy/arms/lazysections/sections/backend-http/error-responses.md new file mode 100644 index 0000000..ed0d1d4 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/error-responses.md @@ -0,0 +1,12 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/handler-design.md b/tests/efficacy/arms/lazysections/sections/backend-http/handler-design.md new file mode 100644 index 0000000..51a4bd4 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/handler-design.md @@ -0,0 +1,8 @@ +# Backend — HTTP Conventions + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/http-methods.md b/tests/efficacy/arms/lazysections/sections/backend-http/http-methods.md new file mode 100644 index 0000000..a20ae79 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/http-methods.md @@ -0,0 +1,7 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/port-binding.md b/tests/efficacy/arms/lazysections/sections/backend-http/port-binding.md new file mode 100644 index 0000000..85a865a --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/port-binding.md @@ -0,0 +1,8 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/process-lifecycle.md b/tests/efficacy/arms/lazysections/sections/backend-http/process-lifecycle.md new file mode 100644 index 0000000..e7e1408 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/process-lifecycle.md @@ -0,0 +1,21 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/query-parameters.md b/tests/efficacy/arms/lazysections/sections/backend-http/query-parameters.md new file mode 100644 index 0000000..be0570b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/query-parameters.md @@ -0,0 +1,10 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/request-headers.md b/tests/efficacy/arms/lazysections/sections/backend-http/request-headers.md new file mode 100644 index 0000000..fb15d40 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/request-headers.md @@ -0,0 +1,10 @@ +# Backend — HTTP Conventions + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/backend-http/resource-representation.md b/tests/efficacy/arms/lazysections/sections/backend-http/resource-representation.md new file mode 100644 index 0000000..3215d72 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/backend-http/resource-representation.md @@ -0,0 +1,23 @@ +# Backend — HTTP Conventions + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-governance/audit-trail.md b/tests/efficacy/arms/lazysections/sections/base-data-governance/audit-trail.md new file mode 100644 index 0000000..1461b5f --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-governance/audit-trail.md @@ -0,0 +1,20 @@ +# Base — Data Governance + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +## Audit trail + +- 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/lazysections/sections/base-data-governance/data-classification.md b/tests/efficacy/arms/lazysections/sections/base-data-governance/data-classification.md new file mode 100644 index 0000000..9722628 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-governance/data-classification.md @@ -0,0 +1,20 @@ +# Base — Data Governance + +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 + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-governance/data-ownership.md b/tests/efficacy/arms/lazysections/sections/base-data-governance/data-ownership.md new file mode 100644 index 0000000..b873179 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-governance/data-ownership.md @@ -0,0 +1,13 @@ +# Base — Data Governance + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +## Data 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-governance/pii-handling.md b/tests/efficacy/arms/lazysections/sections/base-data-governance/pii-handling.md new file mode 100644 index 0000000..853946b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-governance/pii-handling.md @@ -0,0 +1,19 @@ +# Base — Data Governance + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +## PII handling + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-governance/retention.md b/tests/efficacy/arms/lazysections/sections/base-data-governance/retention.md new file mode 100644 index 0000000..b3bd5ce --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-governance/retention.md @@ -0,0 +1,17 @@ +# Base — Data Governance + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-modeling/data-types.md b/tests/efficacy/arms/lazysections/sections/base-data-modeling/data-types.md new file mode 100644 index 0000000..0a3a492 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-modeling/data-types.md @@ -0,0 +1,17 @@ +# 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. + +## Data 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/lazysections/sections/base-data-modeling/naming-conventions.md b/tests/efficacy/arms/lazysections/sections/base-data-modeling/naming-conventions.md new file mode 100644 index 0000000..603ccc3 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-modeling/naming-conventions.md @@ -0,0 +1,9 @@ +# 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 + +- Use one naming convention per store for every table or collection, + field, key and index; record it in the project's context file diff --git a/tests/efficacy/arms/lazysections/sections/base-data-modeling/normalization.md b/tests/efficacy/arms/lazysections/sections/base-data-modeling/normalization.md new file mode 100644 index 0000000..fa69195 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-modeling/normalization.md @@ -0,0 +1,14 @@ +# 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. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-data-modeling/relationships.md b/tests/efficacy/arms/lazysections/sections/base-data-modeling/relationships.md new file mode 100644 index 0000000..5e74f3c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-modeling/relationships.md @@ -0,0 +1,18 @@ +# 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. + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-data-modeling/schema-evolution.md b/tests/efficacy/arms/lazysections/sections/base-data-modeling/schema-evolution.md new file mode 100644 index 0000000..7db738b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-data-modeling/schema-evolution.md @@ -0,0 +1,19 @@ +# 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. + +## Schema 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/adopting-shared-rules.md b/tests/efficacy/arms/lazysections/sections/base-docs/adopting-shared-rules.md new file mode 100644 index 0000000..3c517d7 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/adopting-shared-rules.md @@ -0,0 +1,20 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Adopting shared rules + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/cold-readers.md b/tests/efficacy/arms/lazysections/sections/base-docs/cold-readers.md new file mode 100644 index 0000000..0b1e362 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/cold-readers.md @@ -0,0 +1,13 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Cold readers + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/diagrams-and-assets.md b/tests/efficacy/arms/lazysections/sections/base-docs/diagrams-and-assets.md new file mode 100644 index 0000000..6b6533c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/diagrams-and-assets.md @@ -0,0 +1,13 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Diagrams and assets + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/disagreements.md b/tests/efficacy/arms/lazysections/sections/base-docs/disagreements.md new file mode 100644 index 0000000..0e363a2 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/disagreements.md @@ -0,0 +1,14 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/docs-as-code.md b/tests/efficacy/arms/lazysections/sections/base-docs/docs-as-code.md new file mode 100644 index 0000000..912a4d7 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/docs-as-code.md @@ -0,0 +1,8 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Docs as code + +- Keep technical documentation in the repository, in Markdown, under the + same review as code diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/generated-files.md b/tests/efficacy/arms/lazysections/sections/base-docs/generated-files.md new file mode 100644 index 0000000..b77b0b5 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/generated-files.md @@ -0,0 +1,17 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Generated files + +- 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/line-width.md b/tests/efficacy/arms/lazysections/sections/base-docs/line-width.md new file mode 100644 index 0000000..aba7c64 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/line-width.md @@ -0,0 +1,24 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Line width + +- Wrap Markdown at the width the project declares, never at one written + into a rule + +### Enforcing the width + +- 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/output-file-by-agent.md b/tests/efficacy/arms/lazysections/sections/base-docs/output-file-by-agent.md new file mode 100644 index 0000000..2b5f4c4 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/output-file-by-agent.md @@ -0,0 +1,13 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Output file by agent + +| 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/lazysections/sections/base-docs/rule-language.md b/tests/efficacy/arms/lazysections/sections/base-docs/rule-language.md new file mode 100644 index 0000000..2bceb45 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/rule-language.md @@ -0,0 +1,17 @@ +# Base — Documentation + +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 | diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/session-handoff.md b/tests/efficacy/arms/lazysections/sections/base-docs/session-handoff.md new file mode 100644 index 0000000..26a3e11 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/session-handoff.md @@ -0,0 +1,23 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Session handoff + +- At a natural boundary a project MAY keep a short handoff file in the + repository: a "Now and next" section rewritten each session, and lasting + facts only where no authoritative source (code, history, ADRs, issues) + holds them +- Treat a missing handoff file as no defect, and a boundary as no reason + to end the session +- Where the project keeps one: + - Name it `HANDOFF.md`, at the repository root, with the sections "Now + and next" and "Lasting facts" + - Keep it in the repository, never in an agent tool's own store, so any + agent reads it + - Read it when a session starts + - State in "Now and next" where the work stands and the next step + - Point at the decision record or issue that holds a decision or a plan; + never copy it + - Prune a lasting fact once it stops being true + - Keep it out of the agent context files, which hold no progress log diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/single-source-of-truth.md b/tests/efficacy/arms/lazysections/sections/base-docs/single-source-of-truth.md new file mode 100644 index 0000000..04f48d7 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/single-source-of-truth.md @@ -0,0 +1,11 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/standard-documents.md b/tests/efficacy/arms/lazysections/sections/base-docs/standard-documents.md new file mode 100644 index 0000000..42483a9 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/standard-documents.md @@ -0,0 +1,13 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## Standard documents + +- Carry these three in every project (MUST); their layout is the project's own + +| 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 | diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/upkeep.md b/tests/efficacy/arms/lazysections/sections/base-docs/upkeep.md new file mode 100644 index 0000000..9847d54 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/upkeep.md @@ -0,0 +1,14 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-docs/writing-style.md b/tests/efficacy/arms/lazysections/sections/base-docs/writing-style.md new file mode 100644 index 0000000..848700c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-docs/writing-style.md @@ -0,0 +1,17 @@ +# Base — Documentation + +Which documents a project keeps, and how they stay true. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-git/ci-evidence.md b/tests/efficacy/arms/lazysections/sections/base-git/ci-evidence.md new file mode 100644 index 0000000..62924c9 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/ci-evidence.md @@ -0,0 +1,15 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-git/commits.md b/tests/efficacy/arms/lazysections/sections/base-git/commits.md new file mode 100644 index 0000000..ed66d9f --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/commits.md @@ -0,0 +1,17 @@ +# Base — Git Conventions + +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) diff --git a/tests/efficacy/arms/lazysections/sections/base-git/existing-changes.md b/tests/efficacy/arms/lazysections/sections/base-git/existing-changes.md new file mode 100644 index 0000000..18a9b14 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/existing-changes.md @@ -0,0 +1,15 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-git/off-limits-paths.md b/tests/efficacy/arms/lazysections/sections/base-git/off-limits-paths.md new file mode 100644 index 0000000..61358a5 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/off-limits-paths.md @@ -0,0 +1,35 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## 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/lazysections/sections/base-git/pull-requests.md b/tests/efficacy/arms/lazysections/sections/base-git/pull-requests.md new file mode 100644 index 0000000..4a84719 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/pull-requests.md @@ -0,0 +1,11 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-git/regenerated-artifacts.md b/tests/efficacy/arms/lazysections/sections/base-git/regenerated-artifacts.md new file mode 100644 index 0000000..fe44a97 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/regenerated-artifacts.md @@ -0,0 +1,47 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## Regenerated artifacts + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-git/updating-a-branch.md b/tests/efficacy/arms/lazysections/sections/base-git/updating-a-branch.md new file mode 100644 index 0000000..69b2616 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-git/updating-a-branch.md @@ -0,0 +1,14 @@ +# Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +## 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 + +- Regenerate derived artifacts and re-run the staleness comparison after + every such merge, and stage what they produce diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/architecture.md b/tests/efficacy/arms/lazysections/sections/base-quality/architecture.md new file mode 100644 index 0000000..8050acf --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/architecture.md @@ -0,0 +1,8 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Architecture + +- Compute derived counts and statistics from the data; never hardcode them +- Remove unused modules, assets and data files promptly diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/check-trust.md b/tests/efficacy/arms/lazysections/sections/base-quality/check-trust.md new file mode 100644 index 0000000..46b4ca8 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/check-trust.md @@ -0,0 +1,13 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Check trust + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/comments.md b/tests/efficacy/arms/lazysections/sections/base-quality/comments.md new file mode 100644 index 0000000..01b4be2 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/comments.md @@ -0,0 +1,14 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/completion.md b/tests/efficacy/arms/lazysections/sections/base-quality/completion.md new file mode 100644 index 0000000..c754bd9 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/completion.md @@ -0,0 +1,16 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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/lazysections/sections/base-quality/complexity.md b/tests/efficacy/arms/lazysections/sections/base-quality/complexity.md new file mode 100644 index 0000000..14cb6f3 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/complexity.md @@ -0,0 +1,17 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/debug-code.md b/tests/efficacy/arms/lazysections/sections/base-quality/debug-code.md new file mode 100644 index 0000000..ead6bd0 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/debug-code.md @@ -0,0 +1,18 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/dependencies.md b/tests/efficacy/arms/lazysections/sections/base-quality/dependencies.md new file mode 100644 index 0000000..57723f3 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/dependencies.md @@ -0,0 +1,33 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 + +- Where a dependency is optional, run one CI leg without it installed, + importing the package (MUST) + +### Import bans + +- 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. diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/deprecation-and-renames.md b/tests/efficacy/arms/lazysections/sections/base-quality/deprecation-and-renames.md new file mode 100644 index 0000000..5ccbf5d --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/deprecation-and-renames.md @@ -0,0 +1,14 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Deprecation and renames + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/destructive-operations.md b/tests/efficacy/arms/lazysections/sections/base-quality/destructive-operations.md new file mode 100644 index 0000000..fe8199f --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/destructive-operations.md @@ -0,0 +1,21 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Destructive operations + +- 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 +``` diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/encoding-and-line-endings.md b/tests/efficacy/arms/lazysections/sections/base-quality/encoding-and-line-endings.md new file mode 100644 index 0000000..5a82d9d --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/encoding-and-line-endings.md @@ -0,0 +1,48 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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. diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/enforcement.md b/tests/efficacy/arms/lazysections/sections/base-quality/enforcement.md new file mode 100644 index 0000000..8b996e2 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/enforcement.md @@ -0,0 +1,13 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Enforcement + +- Enforce these conventions through the gates: editor, pre-commit, CI +- Merge to `main` only with passing tests + +### Generated output + +- Make a generator emit output that passes the linters natively; a needed + `lint --fix` is a generator bug (MUST) diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/errors.md b/tests/efficacy/arms/lazysections/sections/base-quality/errors.md new file mode 100644 index 0000000..3deb1e9 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/errors.md @@ -0,0 +1,16 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/library-output.md b/tests/efficacy/arms/lazysections/sections/base-quality/library-output.md new file mode 100644 index 0000000..8238d03 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/library-output.md @@ -0,0 +1,11 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/module-structure.md b/tests/efficacy/arms/lazysections/sections/base-quality/module-structure.md new file mode 100644 index 0000000..23e836e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/module-structure.md @@ -0,0 +1,8 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Module structure + +- Keep a CLI a thin layer over a library that holds its logic +- Keep constants beside the functions that use them diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/naming.md b/tests/efficacy/arms/lazysections/sections/base-quality/naming.md new file mode 100644 index 0000000..f67d77c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/naming.md @@ -0,0 +1,13 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/new-constraints.md b/tests/efficacy/arms/lazysections/sections/base-quality/new-constraints.md new file mode 100644 index 0000000..1149c53 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/new-constraints.md @@ -0,0 +1,8 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## New constraints + +- Run a new constraint (a rule, a check, a tightened bound, a narrowed + exemption) against the existing corpus before it merges (MUST) diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/principles.md b/tests/efficacy/arms/lazysections/sections/base-quality/principles.md new file mode 100644 index 0000000..b914e66 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/principles.md @@ -0,0 +1,17 @@ +# Base — Quality Attributes + +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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/rejected-mechanisms.md b/tests/efficacy/arms/lazysections/sections/base-quality/rejected-mechanisms.md new file mode 100644 index 0000000..0635c2e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/rejected-mechanisms.md @@ -0,0 +1,10 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Rejected mechanisms + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-quality/static-checks.md b/tests/efficacy/arms/lazysections/sections/base-quality/static-checks.md new file mode 100644 index 0000000..1469f97 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-quality/static-checks.md @@ -0,0 +1,30 @@ +# Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +## Static checks + +- Adopt the language's static type checker at its strictest setting where + the language has one, and keep it clean (MUST) +- Annotate every public function's parameters and return type where the + language allows it (MUST) +- Annotate types as the code is written +- Adopt a linter and a formatter, and keep both clean (MUST) +- Give the project one check command running format, lint, types and + tests, and run it in CI +- While working, run the narrowest check that covers the affected + behaviour and its dependents +- Run the full check command before each commit and at completion; an + unchanged, passing full check satisfies both +- Do not re-run a check whose inputs have not changed since it passed +- Batch independent fixes before re-running; re-run earlier when needed to + diagnose or to verify a prerequisite fix + +```bash + + + +``` + +Pass condition: all three print nothing. Each command is the project's own, +in its quiet mode. diff --git a/tests/efficacy/arms/lazysections/sections/base-review/ci-signals.md b/tests/efficacy/arms/lazysections/sections/base-review/ci-signals.md new file mode 100644 index 0000000..bcc4844 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/ci-signals.md @@ -0,0 +1,14 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-review/deviations.md b/tests/efficacy/arms/lazysections/sections/base-review/deviations.md new file mode 100644 index 0000000..41bf633 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/deviations.md @@ -0,0 +1,10 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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/lazysections/sections/base-review/must-checklist.md b/tests/efficacy/arms/lazysections/sections/base-review/must-checklist.md new file mode 100644 index 0000000..51b470a --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/must-checklist.md @@ -0,0 +1,19 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/picking-up-an-issue.md b/tests/efficacy/arms/lazysections/sections/base-review/picking-up-an-issue.md new file mode 100644 index 0000000..ec0dbda --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/picking-up-an-issue.md @@ -0,0 +1,25 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## Picking up an 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/planning.md b/tests/efficacy/arms/lazysections/sections/base-review/planning.md new file mode 100644 index 0000000..2dd1ed4 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/planning.md @@ -0,0 +1,13 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/principle.md b/tests/efficacy/arms/lazysections/sections/base-review/principle.md new file mode 100644 index 0000000..a25ea2d --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/principle.md @@ -0,0 +1,11 @@ +# Base — Peer 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/priority-order.md b/tests/efficacy/arms/lazysections/sections/base-review/priority-order.md new file mode 100644 index 0000000..7831d73 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/priority-order.md @@ -0,0 +1,22 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## Priority order + +Review in this order, most critical first. The quality rules, and any +language quality rules the project carries, are 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/should-checklist.md b/tests/efficacy/arms/lazysections/sections/base-review/should-checklist.md new file mode 100644 index 0000000..71fddb8 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/should-checklist.md @@ -0,0 +1,12 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/structure-audit.md b/tests/efficacy/arms/lazysections/sections/base-review/structure-audit.md new file mode 100644 index 0000000..316cbec --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/structure-audit.md @@ -0,0 +1,13 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-review/verifying-a-finding.md b/tests/efficacy/arms/lazysections/sections/base-review/verifying-a-finding.md new file mode 100644 index 0000000..93330f0 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-review/verifying-a-finding.md @@ -0,0 +1,57 @@ +# Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +## Verifying a finding + +- Label a finding unverified until it is demonstrated (MUST) + +### From reading + +- [ ] 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 + +- [ ] 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 + +- [ ] 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 + +- [ ] 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-security/agent-secrets-handling.md b/tests/efficacy/arms/lazysections/sections/base-security/agent-secrets-handling.md new file mode 100644 index 0000000..b82b0eb --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/agent-secrets-handling.md @@ -0,0 +1,28 @@ +# Base — Application 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. + +## Agent secrets handling + +- 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/lazysections/sections/base-security/authentication.md b/tests/efficacy/arms/lazysections/sections/base-security/authentication.md new file mode 100644 index 0000000..8587c4c --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/authentication.md @@ -0,0 +1,54 @@ +# Base — Application 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. + +## Authentication + +- 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 + +- 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 + +# Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +## Authentication + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/cross-site-request-forgery-csrf.md b/tests/efficacy/arms/lazysections/sections/base-security/cross-site-request-forgery-csrf.md new file mode 100644 index 0000000..db331ac --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/cross-site-request-forgery-csrf.md @@ -0,0 +1,33 @@ +# Base — Application 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. + +## Cross-site request forgery (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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/deserialization-and-data-integrity.md b/tests/efficacy/arms/lazysections/sections/base-security/deserialization-and-data-integrity.md new file mode 100644 index 0000000..128e208 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/deserialization-and-data-integrity.md @@ -0,0 +1,23 @@ +# Base — Application 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. + +## Deserialization and data 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/error-handling.md b/tests/efficacy/arms/lazysections/sections/base-security/error-handling.md new file mode 100644 index 0000000..d581946 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/error-handling.md @@ -0,0 +1,22 @@ +# Base — Application 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. + +## Error handling + +- 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" diff --git a/tests/efficacy/arms/lazysections/sections/base-security/injection-prevention.md b/tests/efficacy/arms/lazysections/sections/base-security/injection-prevention.md new file mode 100644 index 0000000..c1d101a --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/injection-prevention.md @@ -0,0 +1,18 @@ +# Base — Application 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. + +## Injection prevention + +- 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` diff --git a/tests/efficacy/arms/lazysections/sections/base-security/input-validation.md b/tests/efficacy/arms/lazysections/sections/base-security/input-validation.md new file mode 100644 index 0000000..5d58bfd --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/input-validation.md @@ -0,0 +1,23 @@ +# Base — Application 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 + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/logging.md b/tests/efficacy/arms/lazysections/sections/base-security/logging.md new file mode 100644 index 0000000..fcdc931 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/logging.md @@ -0,0 +1,26 @@ +# Base — Application 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. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/output-encoding-xss.md b/tests/efficacy/arms/lazysections/sections/base-security/output-encoding-xss.md new file mode 100644 index 0000000..612a0d3 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/output-encoding-xss.md @@ -0,0 +1,22 @@ +# Base — Application 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. + +## Output encoding (XSS) + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/secrets-in-code.md b/tests/efficacy/arms/lazysections/sections/base-security/secrets-in-code.md new file mode 100644 index 0000000..2f4f6f5 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/secrets-in-code.md @@ -0,0 +1,17 @@ +# Base — Application 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. + +## Secrets in code + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/security-headers.md b/tests/efficacy/arms/lazysections/sections/base-security/security-headers.md new file mode 100644 index 0000000..87a9501 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/security-headers.md @@ -0,0 +1,32 @@ +# Base — Application 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. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/session-management.md b/tests/efficacy/arms/lazysections/sections/base-security/session-management.md new file mode 100644 index 0000000..2a8d1cf --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/session-management.md @@ -0,0 +1,20 @@ +# Base — Application 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. + +## Session management + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-security/transport-security.md b/tests/efficacy/arms/lazysections/sections/base-security/transport-security.md new file mode 100644 index 0000000..0e9049e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-security/transport-security.md @@ -0,0 +1,18 @@ +# Base — Application 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. + +## Transport security + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/call-sites.md b/tests/efficacy/arms/lazysections/sections/base-testing/call-sites.md new file mode 100644 index 0000000..c19ce9e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/call-sites.md @@ -0,0 +1,11 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Call sites + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/coverage.md b/tests/efficacy/arms/lazysections/sections/base-testing/coverage.md new file mode 100644 index 0000000..2c0b76b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/coverage.md @@ -0,0 +1,58 @@ +# 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 + +# Backend — Database Conventions + +## 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/lazysections/sections/base-testing/drift-guards.md b/tests/efficacy/arms/lazysections/sections/base-testing/drift-guards.md new file mode 100644 index 0000000..9ee7691 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/drift-guards.md @@ -0,0 +1,15 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Drift guards + +- 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/lazysections/sections/base-testing/empty-results.md b/tests/efficacy/arms/lazysections/sections/base-testing/empty-results.md new file mode 100644 index 0000000..6a39370 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/empty-results.md @@ -0,0 +1,24 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Empty results + +### 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/external-definitions.md b/tests/efficacy/arms/lazysections/sections/base-testing/external-definitions.md new file mode 100644 index 0000000..3685a34 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/external-definitions.md @@ -0,0 +1,14 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## External definitions + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/fault-injection.md b/tests/efficacy/arms/lazysections/sections/base-testing/fault-injection.md new file mode 100644 index 0000000..62e2755 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/fault-injection.md @@ -0,0 +1,15 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Fault injection + +- 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/guard-use.md b/tests/efficacy/arms/lazysections/sections/base-testing/guard-use.md new file mode 100644 index 0000000..825d1b8 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/guard-use.md @@ -0,0 +1,25 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Guard use + +- 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. diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/isolation.md b/tests/efficacy/arms/lazysections/sections/base-testing/isolation.md new file mode 100644 index 0000000..37b63e6 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/isolation.md @@ -0,0 +1,22 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Isolation + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/provenance.md b/tests/efficacy/arms/lazysections/sections/base-testing/provenance.md new file mode 100644 index 0000000..5741a7e --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/provenance.md @@ -0,0 +1,14 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/real-data.md b/tests/efficacy/arms/lazysections/sections/base-testing/real-data.md new file mode 100644 index 0000000..a471587 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/real-data.md @@ -0,0 +1,12 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/rendered-output.md b/tests/efficacy/arms/lazysections/sections/base-testing/rendered-output.md new file mode 100644 index 0000000..3bca454 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/rendered-output.md @@ -0,0 +1,11 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Rendered output + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/test-types.md b/tests/efficacy/arms/lazysections/sections/base-testing/test-types.md new file mode 100644 index 0000000..2c0b76b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/test-types.md @@ -0,0 +1,58 @@ +# 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 + +# Backend — Database Conventions + +## 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/lazysections/sections/base-testing/testability.md b/tests/efficacy/arms/lazysections/sections/base-testing/testability.md new file mode 100644 index 0000000..2c0b76b --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/testability.md @@ -0,0 +1,58 @@ +# 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 + +# Backend — Database Conventions + +## 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/lazysections/sections/base-testing/thresholds.md b/tests/efficacy/arms/lazysections/sections/base-testing/thresholds.md new file mode 100644 index 0000000..cd70f0d --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/thresholds.md @@ -0,0 +1,10 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Thresholds + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/unique-resources.md b/tests/efficacy/arms/lazysections/sections/base-testing/unique-resources.md new file mode 100644 index 0000000..f15f8ba --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/unique-resources.md @@ -0,0 +1,9 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Unique resources + +- 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) diff --git a/tests/efficacy/arms/lazysections/sections/base-testing/worker-leaks.md b/tests/efficacy/arms/lazysections/sections/base-testing/worker-leaks.md new file mode 100644 index 0000000..0713b58 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/base-testing/worker-leaks.md @@ -0,0 +1,12 @@ +# Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +## Worker leaks + +- 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 diff --git a/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-testing.md b/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-testing.md new file mode 100644 index 0000000..b635fb4 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-testing.md @@ -0,0 +1,30 @@ +# Frontend — UX Principles + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-wcag-2-1-aa.md b/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-wcag-2-1-aa.md new file mode 100644 index 0000000..bc534d0 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/frontend-ux/accessibility-wcag-2-1-aa.md @@ -0,0 +1,24 @@ +# Frontend — UX Principles + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/frontend-ux/browser-support.md b/tests/efficacy/arms/lazysections/sections/frontend-ux/browser-support.md new file mode 100644 index 0000000..cf4d1a7 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/frontend-ux/browser-support.md @@ -0,0 +1,7 @@ +# Frontend — UX Principles + +## Browser support + +- 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/arms/lazysections/sections/frontend-ux/design-system.md b/tests/efficacy/arms/lazysections/sections/frontend-ux/design-system.md new file mode 100644 index 0000000..1cd6471 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/frontend-ux/design-system.md @@ -0,0 +1,8 @@ +# Frontend — UX Principles + +## 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 diff --git a/tests/efficacy/arms/lazysections/sections/frontend-ux/ux-principles.md b/tests/efficacy/arms/lazysections/sections/frontend-ux/ux-principles.md new file mode 100644 index 0000000..a31ac67 --- /dev/null +++ b/tests/efficacy/arms/lazysections/sections/frontend-ux/ux-principles.md @@ -0,0 +1,11 @@ +# Frontend — UX Principles + +## 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 diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index ba00218..9e39c67 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -12,9 +12,15 @@ 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 +- `lazysections` is what `resolve_chain.py --emit --sections` builds: a root + file that maps each topic to a section file, read the first time the work + touches it, and the section files, every adopted rule in one of them +- `lazyrefold` is `lazyref` built at the parent of the templates commit that + cuts the check loop to one check command, so the two differ by it alone -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. +It writes `arms//CLAUDE.md` (and, for an arm with skills or section +files, those beside it), and refuses to keep a result the specification +leaked into. The same ref gives the same bytes, so the self-test rebuilds every committed arm and fails on any difference. It still refuses to overwrite an existing @@ -23,6 +29,7 @@ import argparse import datetime +import difflib import io import json import os @@ -30,11 +37,12 @@ import shutil import subprocess import sys +import tarfile import tempfile import textwrap from harness import (ROUND5_DECLINED, ROUND5_REF, # noqa: E402 - ROUND5_ROOTS, + ROUND5_ROOTS, SECTIONS_INTO, TEMPLATES_ENV, VENDORED, TrialError, source_record, templates_root, assert_outside_repository, read_input) @@ -46,17 +54,34 @@ # The arms this module makes, each with the directory under `arms/` its file # and record live in, and how it is made: fixed text, the templates' emitter -# with its skills apart or inlined, or a map of the chain's topics read as -# files or loaded as skills. An arm a model or a person writes would change -# with every writing, so none is made here. +# with its skills apart, inlined or cut into section files, or a map of the +# chain's topics read as files or loaded as skills. An arm a model or a +# person writes would change with every writing, so none is made here. GENERATED = { "reference": {"dir": "reference", "kind": "fixed"}, "inline": {"dir": "inline", "kind": "emit", "inline_skills": True}, "skills": {"dir": "skills", "kind": "emit", "inline_skills": False}, "lazyref": {"dir": "lazyref", "kind": "map", "load": "read"}, "lazyskills": {"dir": "lazyskills", "kind": "map", "load": "skill"}, + "lazysections": {"dir": "lazysections", "kind": "emit", + "inline_skills": False, "sections": True}, + "lazyrefold": {"dir": "lazyrefold", "kind": "map", "load": "read"}, } +# The arms that hand the agent its rules on demand rather than up front. No +# such arm may tell the agent to read everything at the start, or it loads +# the whole chain and measures nothing of loading on demand. +ON_DEMAND = ("lazyref", "lazyskills", "lazysections", "lazyrefold") + +# The templates commit that cuts the check loop to one check command run +# before each commit, the file it changes and the section it changes there. +# `lazyrefold` is `lazyref` built at its parent, so the pair measures it. +CHECK_LOOP = {"commit": "a8079352", "file": "templates/core/quality.md", + "section": "## Static checks"} + +# Where the templates' emitter writes its skills, inside its output. +EMITTED_SKILLS = ".agents/skills" + # Every arm with a generation record under `arms/`, by its directory: the # arms built here, and the pilot's written arms, whose records stay so a # pilot round's report still cites how each was made and what it vendored. @@ -69,9 +94,25 @@ def output_path(arm): return os.path.join(HERE, "arms", GENERATED[arm]["dir"], "CLAUDE.md") -def skills_path(arm): - """Where an arm's generated skills are committed, one folder a kind.""" - return os.path.join(HERE, "arms", GENERATED[arm]["dir"], "skills") +def parts_path(arm): + """Where an arm's generated skills, one folder a kind, or its section + files, one folder a template, are committed.""" + return os.path.join(HERE, "arms", GENERATED[arm]["dir"], + "sections" if GENERATED[arm].get("sections") + else "skills") + + +def read_tree(base, newline=None): + """Every file under a folder, {path below it, with `/`: text}; empty + where the folder does not exist.""" + files = {} + for folder, _, names in os.walk(base): + for name in names: + path = os.path.join(folder, name) + relative = os.path.relpath(path, base).replace(os.sep, "/") + with io.open(path, encoding="utf-8", newline=newline) as handle: + files[relative] = handle.read() + return dict(sorted(files.items())) def record_path(arm): @@ -352,19 +393,21 @@ def fill_facts(text, brief): return text -def emit_arm(tree, roots, brief, inline_skills): +def emit_arm(tree, roots, brief, entry): """An arm the templates' emitter builds: the root file with its facts - filled, and {kind: SKILL.md text}, empty where the skills are inlined - into the root.""" + filled, and its skills or section files, {path below their folder: + text}, empty where the skills are inlined into the root.""" out = tempfile.mkdtemp(prefix="efficacy-emit-") declined = os.path.join(out, "declined.txt") with io.open(declined, "w", encoding="utf-8", newline="\n") as handle: - handle.write("".join(entry + "\n" for entry in ROUND5_DECLINED)) + handle.write("".join(line + "\n" for line in ROUND5_DECLINED)) + flags = (["--inline-skills"] if entry["inline_skills"] else []) \ + + (["--sections"] if entry.get("sections") else []) try: proc = subprocess.run( [sys.executable, "tools/resolve_chain.py", "--emit", os.path.join(out, "emitted"), "--declined", declined] - + (["--inline-skills"] if inline_skills else []) + roots, + + flags + roots, cwd=tree, capture_output=True, text=True, encoding="utf-8") if proc.returncode != 0: raise TrialError("the emitter failed: %s" @@ -372,21 +415,18 @@ def emit_arm(tree, roots, brief, inline_skills): with io.open(os.path.join(out, "emitted", "AGENTS.md"), encoding="utf-8") as h: root = fill_facts(h.read(), brief) - skills = {} - base = os.path.join(out, "emitted", ".agents", "skills") - for kind in sorted(os.listdir(base)) if os.path.isdir(base) else []: - with io.open(os.path.join(base, kind, "SKILL.md"), - encoding="utf-8") as h: - skills[kind] = h.read() - return root, skills + folder = SECTIONS_INTO if entry.get("sections") else EMITTED_SKILLS + parts = read_tree(os.path.join(out, "emitted", *folder.split("/"))) + return root, parts finally: shutil.rmtree(out, ignore_errors=True) def build_arm(arm, ref, brief): - """One arm's files at a templates ref: (document, {kind: SKILL.md text}, - what the record says of how they were built). The same arm, ref and - brief always give the same files.""" + """One arm's files at a templates ref: (document, its skills or section + files as {path below their folder: text}, what the record says of how + they were built). The same arm, ref and brief always give the same + files.""" entry = GENERATED[arm] tree = worktree_at(ref) try: @@ -395,43 +435,234 @@ def build_arm(arm, ref, brief): ["git", "-C", tree, "rev-parse", "HEAD"], capture_output=True, text=True, encoding="utf-8").stdout.strip(), "resolved_files": files} - skills = {} + parts = {} if entry["kind"] == "fixed": document = reference_text(files, brief) elif entry["kind"] == "emit": - document, skills = emit_arm(tree, ROUND5_ROOTS, brief, - entry["inline_skills"]) + document, parts = emit_arm(tree, ROUND5_ROOTS, brief, entry) details["declined"] = ROUND5_DECLINED details["inline_skills"] = entry["inline_skills"] + if entry.get("sections"): + details["sections"] = True else: rows = moments(tree, files) document = map_text(rows, entry["load"], brief) if entry["load"] == "skill": - skills = template_skills(tree, rows) + parts = {"%s/SKILL.md" % kind: text for kind, text + in sorted(template_skills(tree, rows).items())} details["load"] = entry["load"] details["moments"] = [{"skill": kind, "moment": description, "file": name} for kind, description, name in rows] finally: remove_worktree(tree) - return document.rstrip() + "\n", skills, details + return document.rstrip() + "\n", parts, details def committed_arm(arm): - """An arm's committed files: (document, {kind: SKILL.md text}), or None - where the arm has no committed file.""" + """An arm's committed files: (document, its skills or section files as + {path below their folder: text}), or None where the arm has no + committed file.""" path = output_path(arm) if not os.path.isfile(path): return None with io.open(path, encoding="utf-8", newline="") as handle: document = handle.read() - skills = {} - base = skills_path(arm) - for kind in sorted(os.listdir(base)) if os.path.isdir(base) else []: - with io.open(os.path.join(base, kind, "SKILL.md"), encoding="utf-8", - newline="") as handle: - skills[kind] = handle.read() - return document, skills + return document, read_tree(parts_path(arm), newline="") + + +def vendored_files(ref): + """The templates a vendoring arm's workspace carries at a ref, as + {workspace path: text}.""" + proc = subprocess.run(["git", "-C", templates_root(), "archive", + "--format=tar", ref, VENDORED["path"]], + capture_output=True) + if proc.returncode != 0: + raise TrialError("could not export %s at %s: %s" + % (VENDORED["path"], ref, + proc.stderr.decode("utf-8", "replace").strip())) + files = {} + with tarfile.open(fileobj=io.BytesIO(proc.stdout)) as archive: + for member in archive.getmembers(): + if member.isfile(): + data = archive.extractfile(member).read() + files["%s/%s" % (VENDORED["into"], member.name)] = \ + data.decode("utf-8", "replace") + return files + + +def templates_git(*args): + """What a git command prints in the templates clone; raises on a + non-zero status.""" + proc = subprocess.run(["git", "-C", templates_root()] + list(args), + capture_output=True, text=True, encoding="utf-8") + if proc.returncode != 0: + raise TrialError("git %s failed in the templates clone: %s" + % (" ".join(args), proc.stderr.strip())) + return proc.stdout + + +def changed_lines(old, new): + """The files two sets of files differ in, {path: (removed lines, added + lines)}, a file missing from one set read as empty.""" + changed = {} + for path in sorted(set(old) | set(new)): + before = old.get(path, "").splitlines() + after = new.get(path, "").splitlines() + if before == after: + continue + removed, added = [], [] + matcher = difflib.SequenceMatcher(None, before, after, autojunk=False) + for tag, i1, i2, j1, j2 in matcher.get_opcodes(): + if tag != "equal": + removed += before[i1:i2] + added += after[j1:j2] + changed[path] = (removed, added) + return changed + + +HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") + + +def section_span(text, heading): + """The 1-based lines a level-two section runs over, its heading to the + line before the next level-two heading outside a fence; None where the + text has no such heading.""" + lines, start, fence = text.splitlines(), None, False + for number, line in enumerate(lines, 1): + if line.lstrip().startswith("```"): + fence = not fence + elif not fence and line.startswith("## "): + if start is not None: + return start, number - 1 + if line.rstrip() == heading: + start = number + return (start, len(lines)) if start is not None else None + + +def commit_change(change): + """A templates commit's change to one file: (removed lines, added + lines), from the templates' own diff of that commit, and whether every + changed line lies in the named section, before and after.""" + commit, name = change["commit"], change["file"] + before = templates_git("show", "%s^:%s" % (commit, name)) + after = templates_git("show", "%s:%s" % (commit, name)) + spans = (section_span(before, change["section"]), + section_span(after, change["section"])) + removed, added, inside, hunks = [], [], None not in spans, False + for line in templates_git("diff", "-U0", "--no-color", "--no-ext-diff", + "%s^" % commit, commit, "--", + name).splitlines(): + hunk = HUNK.match(line) + if hunk: + hunks = True + for (start, count), span in zip( + ((hunk.group(1), hunk.group(2)), + (hunk.group(3), hunk.group(4))), spans): + start, count = int(start), int(count or 1) + if count and span and not (span[0] <= start + and start + count - 1 <= span[1]): + inside = False + elif hunks and line.startswith("-"): + removed.append(line[1:]) + elif hunks and line.startswith("+"): + added.append(line[1:]) + return removed, added, inside and bool(removed or added) + + +def pair_findings(old, new, path, change): + """What makes two arms' files differ by more or less than one file's + change: a file that differs besides `path`, or a change to it other + than the lines given.""" + changed = changed_lines(old, new) + findings = ["%s differs too" % other for other in changed + if other != path] + if changed.get(path, ([], [])) != change: + findings.append("%s does not differ by exactly the commit's lines" + % path) + return findings + + +def heading_blocks(text): + """A Markdown text cut at each heading outside a fence: each block's + heading path and its non-blank lines that are not headings.""" + blocks, stack, fence = [((), [])], [], None + for line in text.splitlines(): + run = re.match(r"^\s*(`{3,}|~{3,})", line) + heading = None if (fence or run) else re.match(r"^(#{1,6})\s", line) + if run: + mark = run.group(1) + if fence is None: + fence = mark + elif mark[0] == fence[0] and len(mark) >= len(fence): + fence = None + if heading: + level = len(heading.group(1)) + while stack and stack[-1][0] >= level: + stack.pop() + stack.append((level, line)) + blocks.append((tuple(h for _, h in stack), [])) + elif line.strip(): + blocks[-1][1].append(line) + return [(path, tuple(body)) for path, body in blocks if body] + + +# The heading the inline root puts its procedures under. The root's own +# blocks carry no rule: the lines opening its rules and its procedures, and +# each procedure's description of its kind, the first block under it. +PROCEDURES = "## Procedures" + + +def union_findings(inline_root, sections): + """Where the section files and the inline root's rules part ways, block + by block: a rule block no section file holds, and a block a section + file holds that no rule block is.""" + rules = inline_root.split("\n## Rules\n", 1)[-1] + owed = {body for path, body in heading_blocks(rules) + if path and path != (PROCEDURES,) + and not (len(path) == 2 and path[0] == PROCEDURES)} + held = {body for text in sections.values() + for _, body in heading_blocks(text)} + return (["no section file holds: %s" % body[0] + for body in sorted(owed - held)] + + ["no adopted rule is: %s" % body[0] + for body in sorted(held - owed)]) + + +SECTION_PATH = re.compile(r"`(" + re.escape(SECTIONS_INTO) + r"/[^`]+)`") + + +def map_findings(root, sections): + """What a sections map gets wrong: a section file it names other than + once, or a path it names that is no section file.""" + named = SECTION_PATH.findall(root) + paths = ["%s/%s" % (SECTIONS_INTO, name) for name in sections] + return (["the map names %s %d times" % (path, named.count(path)) + for path in paths if named.count(path) != 1] + + ["the map names %s, which is no section file" % path + for path in sorted(set(named) - set(paths))]) + + +# What telling the agent to read everything at the start looks like: a +# sentence that reads or loads every template, section, skill or file, with +# a moment before the work, and no negation. "Do not read them before the +# work starts" and "the first time the work touches a topic, read it" pass. +READ_ALL = re.compile(r"\b(read|load)\b.*\b(every|each|all)\b.*" + r"\b(templates?|sections?|skills?|files?|rules?)\b", + re.IGNORECASE) +UP_FRONT = re.compile(r"\b(before (starting|you start|any|the work|work)|" + r"at (the )?(start|outset)|startup|up ?front|" + r"at session start)\b", re.IGNORECASE) +NEGATED = re.compile(r"\b(do not|don't|never|not)\b", re.IGNORECASE) + + +def startup_reads(text): + """Each sentence of a text telling the agent to read everything at the + start; empty where it tells no such thing.""" + sentences = re.split(r"(?<=[.!?])\s+", " ".join(text.split())) + return [sentence for sentence in sentences + if READ_ALL.search(sentence) and UP_FRONT.search(sentence) + and not NEGATED.search(sentence)] def parse_args(argv): @@ -656,6 +887,109 @@ def self_test(): print("every committed arm is what the script builds at its recorded " "ref, byte for byte, the same twice") print("every committed arm's root opens with the brief, verbatim") + return on_demand_checks(records, brief) + + +def on_demand_checks(records, brief): + """What the on-demand arms owe beyond a rebuild; 0 where it all holds, + 1 at the first check that fails. + + Requires every on-demand arm committed, and no root of one telling the + agent to read everything at the start, where a planted root saying so + is caught. Requires `lazyref` and `lazyrefold` to differ by the + check-loop commit's lines alone, and the section files to hold the + inline root's rule blocks and no other, each named once by its map; a + planted fault in each is caught. + """ + missing = [arm for arm in ON_DEMAND if arm not in records] + if missing: + print("FAIL: on-demand arms not committed: %s" % ", ".join(missing)) + return 1 + + # Every file of an on-demand arm is scanned, its skills and section + # files too. The up-front arm is the natural control: `reference` tells + # the agent to read every template before the work starts, so the scan + # must fire on it, and on a sentence saying so planted in a root. + arms = {arm: committed_arm(arm) for arm in ON_DEMAND} + told = {arm: [sentence for text in [document] + list(parts.values()) + for sentence in startup_reads(text)] + for arm, (document, parts) in arms.items()} + told = {arm: found for arm, found in told.items() if found} + planted = arms["lazysections"][0] + ("\nRead every section file below " + "at startup, before any work.\n") + if told or not startup_reads(planted) \ + or not startup_reads(committed_arm("reference")[0]): + print("FAIL: an on-demand root tells the agent to read everything " + "at the start, or the scan misses one that does: %r" % told) + return 1 + print("no on-demand arm tells the agent to read everything at startup") + print("a root telling the agent to read everything at the start is " + "caught") + + # `lazyrefold` is `lazyref` at the check-loop commit's parent: its + # record names that parent, and the two arms' workspaces, root and + # vendored templates, differ by that commit's lines alone, each in the + # one section it changes. + commit = CHECK_LOOP["commit"] + parent = templates_git("rev-parse", "%s^" % commit).strip() + if templates_git("rev-parse", records["lazyrefold"]["ref"]).strip() \ + != parent: + print("FAIL: lazyrefold is not built at the check-loop commit's " + "parent, %s" % parent[:8]) + return 1 + old = dict(vendored_files(parent), + **{"CLAUDE.md": committed_arm("lazyrefold")[0]}) + new = dict(vendored_files(commit), + **{"CLAUDE.md": build_arm("lazyref", commit, brief)[0]}) + removed, added, inside = commit_change(CHECK_LOOP) + path = "%s/%s" % (VENDORED["into"], CHECK_LOOP["file"]) + findings = pair_findings(old, new, path, (removed, added)) + if findings or not inside: + print("FAIL: lazyref and lazyrefold differ by more or less than the " + "check-loop commit's lines in %s: %r" + % (CHECK_LOOP["section"], findings)) + return 1 + print("lazyref and lazyrefold differ by the check-loop commit's lines " + "alone, all in its section") + extra = dict(new, **{"CLAUDE.md": new["CLAUDE.md"] + "- Check twice\n"}) + short = dict(new, **{path: new[path].replace(added[-1] + "\n", "", 1)}) + if not pair_findings(old, extra, path, (removed, added)) \ + or not pair_findings(old, short, path, (removed, added)) \ + or commit_change(dict(CHECK_LOOP, section="## Naming"))[2]: + print("FAIL: a line changed besides the commit's, one of its lines " + "missing, or a line outside its section is not reported") + return 1 + print("a line changed besides the commit's, one of its lines missing, or " + "one outside its section is reported") + + # The section files and the inline root are two packagings of one rule + # set at one ref, so each rule block of the one is a block of the other. + document, sections = committed_arm("lazysections") + inline = build_arm("inline", records["lazysections"]["ref"], brief)[0] + findings = union_findings(inline, sections) \ + + map_findings(document, sections) + if findings: + print("FAIL: the section files and the adopted rules part ways, or " + "the map misnames a file: %r" % findings[:5]) + return 1 + print("the section files hold every rule block the inline root does, " + "and no other") + print("the sections map names every section file once, under %s/" + % SECTIONS_INTO) + name = sorted(sections)[0] + lines = sections[name].splitlines(True) + last = max(i for i, line in enumerate(lines) + if line.strip() and not line.startswith("#")) + dropped = dict(sections, + **{name: "".join(lines[:last] + lines[last + 1:])}) + unmapped = dict(sections, **{"extra/unmapped.md": "# Extra\n\n- A rule\n"}) + if not union_findings(inline, dropped) \ + or not map_findings(document, unmapped): + print("FAIL: a rule dropped from a section file, or a file the map " + "does not name, is not reported") + return 1 + print("a rule dropped from a section file, or a file the map does not " + "name, is reported") return 0 @@ -689,13 +1023,13 @@ def main(argv): record = {"arm": arm, "kind": entry["kind"], "ref": options.ref, "source": source_record(options.ref), "roots": ROUND5_ROOTS, "started_at": started_at.isoformat(timespec="seconds")} - document, skills, details = build_arm(arm, options.ref, read_brief()) + document, parts, details = build_arm(arm, options.ref, read_brief()) record.update(details) print("chain at %s (%s): %d unique files" % (options.ref, record["commit"][:8], len(record["resolved_files"]))) - texts = [document] + list(skills.values()) + texts = [document] + list(parts.values()) leak = scan("\n".join(texts), "built files", NON_INVENTABLE) record["output_leak"] = leak if leak is not None: @@ -712,34 +1046,47 @@ def main(argv): % ", ".join(tools)) return write_record(options.root, record, started_at) or 1 + told = [sentence for text in texts for sentence in startup_reads(text)] + if told and arm in ON_DEMAND: + record["outcome"] = "refused: reads everything at the start" + print("refused: an on-demand arm's files tell the agent to read " + "everything at the start: %r" % told) + return write_record(options.root, record, started_at) or 1 + # A dry run of any arm stops here: it writes nothing under `arms/`, # so it never replaces a committed file or its record. + unit = "section files" if entry.get("sections") else "skills" if options.dry_run: record["outcome"] = "dry-run" print("dry run: %s would be %d words%s; nothing written under arms/" % (output, len(document.split()), - ", with %d skills" % len(skills) if skills else "")) + ", with %d %s" % (len(parts), unit) if parts else "")) return write_record(options.root, record, started_at) os.makedirs(os.path.dirname(output), exist_ok=True) with io.open(output, "w", encoding="utf-8", newline="\n") as handle: handle.write(document) - shutil.rmtree(skills_path(arm), ignore_errors=True) - for kind, text in skills.items(): - path = os.path.join(skills_path(arm), kind, "SKILL.md") + shutil.rmtree(parts_path(arm), ignore_errors=True) + for name, text in parts.items(): + path = os.path.join(parts_path(arm), *name.split("/")) os.makedirs(os.path.dirname(path), exist_ok=True) with io.open(path, "w", encoding="utf-8", newline="\n") as handle: handle.write(text) - if skills: - record["skills"] = {kind: len(text.split()) - for kind, text in skills.items()} + + # A skill is named by its folder, a section file by its path. + if parts and entry.get("sections"): + record["sections"] = {name: len(text.split()) + for name, text in parts.items()} + elif parts: + record["skills"] = {name.split("/")[0]: len(text.split()) + for name, text in parts.items()} record["outcome"] = "generated" record["output"] = output record["output_lines"] = document.rstrip("\n").count("\n") + 1 record["output_words"] = len(document.split()) print("wrote %s: %d lines, %d words%s" % (output, record["output_lines"], record["output_words"], - ", %d skills" % len(skills) if skills else "")) + ", %d %s" % (len(parts), unit) if parts else "")) keep_record(record, record_path(arm)) print("Record kept beside it: %s" % record_path(arm)) return write_record(options.root, record, started_at) diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index 0e3d3bf..27a6d89 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -136,6 +136,10 @@ # Code loads skills from on demand. SKILLS_INTO = ".claude/skills" +# Where the `lazysections` arm's section files go in the workspace: the +# folder the emitted map names each file under, read as plain files. +SECTIONS_INTO = ".agents/sections" + # The arms, each a word, and the context file each starts with, relative to # `arms/`. Arm `none` carries no file: it is the bare agent. An arm's # vendored ref comes from its generation record. `generate_arm.py` builds @@ -162,6 +166,13 @@ "each", "context": "lazyskills/CLAUDE.md", "skills": "lazyskills/skills"}, + "lazysections": {"label": "the emitted map, one section file per topic, " + "read on demand", + "context": "lazysections/CLAUDE.md", + "sections": "lazysections/sections"}, + "lazyrefold": {"label": "the templates before the one-command check, " + "mapped to the work, read on demand", + "context": "lazyrefold/CLAUDE.md", "vendor": VENDORED}, } # The rounds from 6 on, each as registered: its spec, its arms, and per task @@ -176,7 +187,7 @@ "spec": {"name": "normal", "file": "SPEC.md", "sha256": ROUND6_SPEC[1]}, "arms": ["none", "reference", "inline", "skills", "lazyref", - "lazyskills"], + "lazyskills", "lazysections", "lazyrefold"], "tasks": { "build": { "k": 15, @@ -586,19 +597,25 @@ def arm_vendor(arm): return dict(vendor) -def place_skills(workspace, source): - """Copy an arm's skills to where Claude Code loads them, kept out of the - workspace's index like the vendored templates, so no size or scope - metric counts them; return the kinds placed.""" - target = os.path.join(workspace, *SKILLS_INTO.split("/")) +def place_files(workspace, source, into): + """Copy an arm's skills or section files to `into` in the workspace, + kept out of its index like the vendored templates, so no size or scope + metric counts them; return the names placed at the top.""" + target = os.path.join(workspace, *into.split("/")) shutil.copytree(source, target) exclude = os.path.join(workspace, ".git", "info", "exclude") os.makedirs(os.path.dirname(exclude), exist_ok=True) with io.open(exclude, "a", encoding="utf-8", newline="\n") as handle: - handle.write("/%s/\n" % SKILLS_INTO) + handle.write("/%s/\n" % into) return sorted(os.listdir(target)) +def place_skills(workspace, source): + """Copy an arm's skills to where Claude Code loads them; return the + kinds placed.""" + return place_files(workspace, source, SKILLS_INTO) + + def prepare_workspace(arm, trial, root, spec=SPEC): """Create the starting workspace for one trial; return its path and the record of what was vendored into it, None for every arm but the hybrid. @@ -625,8 +642,8 @@ def prepare_workspace(arm, trial, root, spec=SPEC): def install_arm(workspace, arm): """Give a workspace, not yet a repository, its arm's context: the file, - the vendored templates, the skills; `git init` it; return what was - vendored, None for an arm that vendors nothing.""" + the vendored templates, the skills or section files; `git init` it; + return what was vendored, None for an arm that vendors nothing.""" context = ARMS[arm]["context"] if context: source = os.path.join(ARMS_DIR, context) @@ -647,6 +664,12 @@ def install_arm(workspace, arm): raise TrialError("arm %s needs its skills at %s, which do not " "exist" % (arm, source)) place_skills(workspace, source) + if ARMS[arm].get("sections"): + source = os.path.join(ARMS_DIR, ARMS[arm]["sections"]) + if not os.path.isdir(source): + raise TrialError("arm %s needs its section files at %s, which do " + "not exist" % (arm, source)) + place_files(workspace, source, SECTIONS_INTO) return vendored @@ -4095,6 +4118,34 @@ def round5_checks(): "the index", kinds == ["review"] and os.path.isfile(placed) and git(workspace, "status", "--porcelain") == "")) + + # The emitted map names each section file by its path in the workspace, + # so the files must land there, as plain files kept out of the index. + sections = os.path.join(scratch, "lazysections-1") + os.makedirs(sections) + install_arm(sections, "lazysections") + git(sections, "add", "-A") + with io.open(os.path.join(sections, "CLAUDE.md"), + encoding="utf-8") as handle: + named = re.findall(r"`(%s/[^`]+)`" % re.escape(SECTIONS_INTO), + handle.read()) + checks.append(("the lazysections arm's files land where its map names " + "them, out of the index", + bool(named) + and all(os.path.isfile(os.path.join(sections, + *path.split("/"))) + for path in named) + and git(sections, "ls-files").splitlines() + == ["CLAUDE.md"])) + record = os.path.join(ARMS_DIR, "lazyrefold", "generation.json") + with io.open(record, encoding="utf-8") as handle: + recorded = json.load(handle).get("ref") + checks.append(("round 6's lazyrefold vendors at its own recorded ref, " + "lazysections vendors nothing", + recorded is not None + and arm_vendor("lazyrefold")["ref"] == recorded + and arm_vendor("lazysections") is None + and ARMS["lazysections"].get("skills") is None)) remove_tree(scratch) return checks From a84b1e949ac45e3f0d5f0409e41aba5e33d14723 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:19:33 +0200 Subject: [PATCH 2/4] fix(efficacy): pair the committed lazyref and lazyrefold, and read section files as map uses - the check-loop pair check now reads each arm's committed root and the templates vendored at the ref its record names, the pair a trial gets, not a lazyref built for the check; a lazyref committed at another ref is planted and reported - lazyref regenerated by the arm script at the check-loop commit (a8079352), so the committed pair differs by that rule alone; its map is unchanged, only its record's ref moves. Both arms are re-pinned once the templates PRs merge - report: the lazysections arm's map is its section files, and a Read or a shell read of one (by path, wildcard or a directory moved into) counts as a use, so map_uses() measures its trials - docs: FR-13-22 and FR-13-23 rows and coverage, the journey's ref note Refs #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +- docs/journeys/prepare/generate-the-arms.md | 2 +- docs/requirements.md | 4 +- tests/efficacy/arms/lazyref/generation.json | 15 ++-- tests/efficacy/generate_arm.py | 26 ++++-- tests/efficacy/report.py | 91 +++++++++++++++++---- 6 files changed, 106 insertions(+), 36 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 5bfe72e..79734fa 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -204,8 +204,8 @@ when: | FR-13-18 | Self-test | `reuse.py` "a named round's trials copied on keep its round in the run record's header"
`reuse.py` "a reuse never mixes a named round's trials with others"
`reuse.py` "a trial copied within a named round names that round in its origin"
`report.py` "trials reused within one named round pair with those run there" | | FR-13-19 | Self-test | `report.py` "a named round is refused until its registration document is on main before its first trial"
`report.py` "a trial reused within its named round counts toward when the round began" | | FR-13-20 | Self-test | `archive.py` "a C1 change task's score changed in the archive fails the verify" | -| FR-13-22 | Self-test | `generate_arm.py` "the section files hold every rule block the inline root does, and no other"
`generate_arm.py` "the sections map names every section file once, under .agents/sections/"
`generate_arm.py` "a rule dropped from a section file, or a file the map does not name, is reported"
`harness.py` "the lazysections arm's files land where its map names them, out of the index" | -| FR-13-23 | Self-test | `generate_arm.py` "lazyref and lazyrefold differ by the check-loop commit's lines alone, all in its section"
`generate_arm.py` "a line changed besides the commit's, one of its lines missing, or one outside its section is reported"
`harness.py` "round 6's lazyrefold vendors at its own recorded ref, lazysections vendors nothing" | +| FR-13-22 | Self-test | `generate_arm.py` "the section files hold every rule block the inline root does, and no other"
`generate_arm.py` "the sections map names every section file once, under .agents/sections/"
`generate_arm.py` "a rule dropped from a section file, or a file the map does not name, is reported"
`harness.py` "the lazysections arm's files land where its map names them, out of the index"
`report.py` "the sections arm's map is its section files, and a Read or a shell read of one counts as a use" | +| FR-13-23 | Self-test | `generate_arm.py` "lazyref and lazyrefold differ by the check-loop commit's lines alone, all in its section"
`generate_arm.py` "a line changed besides the commit's, one of its lines missing, or one outside its section is reported"
`generate_arm.py` "a lazyref committed at another ref than the check-loop commit is reported"
`harness.py` "round 6's lazyrefold vendors at its own recorded ref, lazysections vendors nothing" | | FR-13-24 | Self-test | `generate_arm.py` "no on-demand arm tells the agent to read everything at startup"
`generate_arm.py` "a root telling the agent to read everything at the start is caught" | ## 14 One run at a time diff --git a/docs/journeys/prepare/generate-the-arms.md b/docs/journeys/prepare/generate-the-arms.md index 764e662..c20cda4 100644 --- a/docs/journeys/prepare/generate-the-arms.md +++ b/docs/journeys/prepare/generate-the-arms.md @@ -50,4 +50,4 @@ py tests/efficacy/generate_arm.py --arm lazyrefold --ref | 2 | The emitted `skills` root lacked the brief's paragraphs on personal data and on boundaries, and no check read an emitted root | Settled in [ADR-026](../../decisions/026-every-arm-is-built-by-a-script.md), rule 4 | | 3 | The emitter builds no hybrid file, and the templates' rules forbid one that names template files | Settled in [ADR-026](../../decisions/026-every-arm-is-built-by-a-script.md); `hybrid` runs no more | | 4 | #169 names the check-loop control `lazyref-old`, but an arm's word carries no hyphen: trial names, voided-workspace names and hypothesis labels split on it | Open, 2026-11-15: built as `lazyrefold`; rename only with those readers | -| 5 | `lazysections` and `lazyrefold` are built at the open templates branch (`d6da8f33`, and `4e1de818`, the parent of `a8079352`) while the other arms stay at `9abed019` | Open: every arm is re-pinned at one ref once templates #2495, #2496 and #2498 merge | +| 5 | `lazysections`, `lazyref` and `lazyrefold` are built at the open templates branch (`d6da8f33`; `a8079352`, the check-loop commit; `4e1de818`, its parent) while the other arms stay at `9abed019` | Open: every arm is re-pinned at one ref once templates #2495, #2496 and #2498 merge | diff --git a/docs/requirements.md b/docs/requirements.md index abdd9ea..4c090fe 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -214,8 +214,8 @@ | FR-13-18 | The benchmark shall reuse a named round's trials under a run record naming that round and its registration's digest, and never reuse trials into a root of another round, a named round's into a root of none, or another round's into a named round's; name the round and its digest in each reused trial's origin, and pair a trial reused within one named round, under one digest, with the trials run there. | Reuse, Report | | FR-13-19 | The benchmark shall refuse a named round's report unless the document its registration entry names exists and landed on `main` before the round's first trial, unchanged since, a trial reused within the round counting toward its start. | Report | | FR-13-20 | The benchmark shall verify an archive by the report's own reading of its round, through one entry point, a named round's change tasks and its reach rule included. | Archive, Report | -| FR-13-22 | The benchmark shall build the `lazysections` arm with the templates' emitter in its sections mode, for the chain and declined list the other emitted arms take, place its section files where its map names them, out of the workspace's index, and fail its self-test where the section files' rule blocks differ from the inline root's, or the map names a section file other than once. | Arm generator, Harness | -| FR-13-23 | The benchmark shall build the `lazyrefold` arm as `lazyref` at the parent of the templates commit that cuts the check loop to one check command, and fail its self-test where the two arms' files differ by other than that commit's lines, all within the section it changes. | Arm generator | +| FR-13-22 | The benchmark shall build the `lazysections` arm with the templates' emitter in its sections mode, for the chain and declined list the other emitted arms take, place its section files where its map names them, out of the workspace's index, and fail its self-test where the section files' rule blocks differ from the inline root's, or the map names a section file other than once; and count a trial's Read or shell read of a section file as a use of its map. | Arm generator, Harness, Report | +| FR-13-23 | The benchmark shall build the `lazyrefold` arm as `lazyref` at the parent of the templates commit that cuts the check loop to one check command, and fail its self-test where the two committed arms' workspace files, at the refs their records name, differ by other than that commit's lines, all within the section it changes. | Arm generator | | FR-13-24 | The benchmark shall refuse an on-demand arm (`lazyref`, `lazyskills`, `lazysections`, `lazyrefold`) whose files tell the agent to read everything at the start. | Arm generator | ### 14 One run at a time diff --git a/tests/efficacy/arms/lazyref/generation.json b/tests/efficacy/arms/lazyref/generation.json index 44c5b73..6ff612b 100644 --- a/tests/efficacy/arms/lazyref/generation.json +++ b/tests/efficacy/arms/lazyref/generation.json @@ -1,12 +1,11 @@ { "arm": "lazyref", "kind": "map", - "output_model": null, - "ref": "9abed019", + "ref": "a8079352", "source": { "remote": "https://github.com/solid-ai-dev/solid-ai-templates.git", - "ref": "9abed019", - "commit": "9abed01916b941d9ed2f8daa8ff8c3b28f0718fd" + "ref": "a8079352", + "commit": "a8079352249dec0db5cdabc9f2e78d1c49362154" }, "roots": [ "backend-api", @@ -16,8 +15,8 @@ "base-security", "base-data-governance" ], - "started_at": "2026-11-13T14:45:13", - "commit": "9abed01916b941d9ed2f8daa8ff8c3b28f0718fd", + "started_at": "2026-11-16T08:09:29", + "commit": "a8079352249dec0db5cdabc9f2e78d1c49362154", "resolved_files": [ "templates/core/quality.md", "templates/core/git.md", @@ -101,10 +100,10 @@ "file": "templates/data/data-governance.md" } ], - "budget": null, "output_leak": null, + "named_tooling": [], "outcome": "generated", - "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark-regen\\tests\\efficacy\\arms\\lazyref\\CLAUDE.md", + "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark-arms\\tests\\efficacy\\arms\\lazyref\\CLAUDE.md", "output_lines": 40, "output_words": 393 } \ No newline at end of file diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index 9e39c67..c207998 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -42,7 +42,7 @@ import textwrap from harness import (ROUND5_DECLINED, ROUND5_REF, # noqa: E402 - ROUND5_ROOTS, SECTIONS_INTO, + ROUND5_ROOTS, SECTIONS_INTO, arm_vendor, TEMPLATES_ENV, VENDORED, TrialError, source_record, templates_root, assert_outside_repository, read_input) @@ -937,10 +937,16 @@ def on_demand_checks(records, brief): print("FAIL: lazyrefold is not built at the check-loop commit's " "parent, %s" % parent[:8]) return 1 - old = dict(vendored_files(parent), - **{"CLAUDE.md": committed_arm("lazyrefold")[0]}) - new = dict(vendored_files(commit), - **{"CLAUDE.md": build_arm("lazyref", commit, brief)[0]}) + + # The pair compared is the one a trial gets: each arm's committed root + # and the templates vendored at the ref the harness reads from its + # record, not a build made here, which no trial runs. + def installed(arm, ref=None): + """An arm's workspace files: its committed root and the templates + vendored at `ref`, by default the one its record names.""" + return dict(vendored_files(ref or arm_vendor(arm)["ref"]), + **{"CLAUDE.md": committed_arm(arm)[0]}) + old, new = installed("lazyrefold"), installed("lazyref") removed, added, inside = commit_change(CHECK_LOOP) path = "%s/%s" % (VENDORED["into"], CHECK_LOOP["file"]) findings = pair_findings(old, new, path, (removed, added)) @@ -962,6 +968,16 @@ def on_demand_checks(records, brief): print("a line changed besides the commit's, one of its lines missing, or " "one outside its section is reported") + # A `lazyref` committed at another ref than the check-loop commit, as + # one left at an earlier round's, makes a pair no trial should read. + stale = installed("lazyref", "%s^" % parent) + if not pair_findings(old, stale, path, (removed, added)): + print("FAIL: a lazyref committed at another ref than the check-loop " + "commit is not reported") + return 1 + print("a lazyref committed at another ref than the check-loop commit is " + "reported") + # The section files and the inline root are two packagings of one rule # set at one ref, so each rule block of the one is a block of the other. document, sections = committed_arm("lazysections") diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index b24039a..e1a113a 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -40,7 +40,8 @@ from generate_arm import RECORDED, record_path # noqa: E402 from harness import (ARMS, ARMS_DIR, PROMPT, REGISTRATIONS, # noqa: E402 ROUND5_ARMS, ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, - ROUND5E_ARMS, SCORABLE, TEMPLATES_ENV, VENDORED, VOIDING, + ROUND5E_ARMS, SCORABLE, SECTIONS_INTO, TEMPLATES_ENV, + VENDORED, VOIDING, TrialError, canonical, git, reach, read_transcripts, read_change_prompt, recorded_round, registration_digest, scoring_area, split_name, @@ -3128,6 +3129,12 @@ def round5d_section(trials, table, results, seed, margins, TEMPLATE_OPERAND = re.compile(re.escape(VENDORED["into"] + "/") + r"(templates/[\w./*?\[\]-]+)") +# A section file named in an operand, by its path in the workspace: the +# `lazysections` arm's map names each so, and a read under any directory +# above it, the workspace's own included, reads the same file. +SECTION_OPERAND = re.compile(r"(" + re.escape(SECTIONS_INTO + "/") + + r"[\w./*?\[\]-]+)") + # A redirection that writes no file: to the null device, or of one stream # into another. Taken out of a command before it is read for a write. NULL_REDIRECT = re.compile( @@ -3331,11 +3338,11 @@ def shell_writes(command): return first_writing_command(command) is not None -def shell_reads(command, known=()): +def shell_reads(command, known=(), operand=TEMPLATE_OPERAND): """The templates a shell command reads, as (index of its simple command, template) in order: every one a reading command names under - the vendored copy, a wildcard operand standing for each template of the - map it matches.""" + the vendored copy, or as `operand` names one, a wildcard operand + standing for each template of the map it matches.""" found = [] directory = "" commands = simple_commands(command, keep_quotes=True) @@ -3352,19 +3359,19 @@ def named(tokens): templates = [] for token in itertools.chain.from_iterable(map(brace_expanded, tokens)): - matched = TEMPLATE_OPERAND.findall(token) + matched = operand.findall(token) # A path with no vendored copy in it may be relative to the # directory an earlier command of the call moved into. if not matched and directory and not token.startswith("-"): - matched = TEMPLATE_OPERAND.findall(posixpath.normpath( + matched = operand.findall(posixpath.normpath( posixpath.join(directory, token.strip("'\"")))) - for operand in matched: - if any(mark in operand for mark in "*?["): + for path in matched: + if any(mark in path for mark in "*?["): templates.extend(template for template in known - if glob_matches(operand, template)) - elif operand.endswith(".md"): - templates.append(operand) + if glob_matches(path, template)) + elif path.endswith(".md"): + templates.append(path) return templates for index, (word, text) in enumerate(commands): words = [token for token in words_of(text) @@ -3412,7 +3419,8 @@ def named(tokens): if word in SHELL_PROGRAMS: for piece in program_code(text, bodies).split("\n"): found.extend((index, template) for _, template - in shell_reads(unquoted(piece), known)) + in shell_reads(unquoted(piece), known, + operand)) continue if word not in READ_COMMANDS: continue @@ -3447,9 +3455,14 @@ def pattern_attached(token): def mapped_templates(arm): """What an arm's file points the agent at: the skills it carries, by - name, or the templates it vendors, by path; empty for an arm with - neither.""" + name, its section files, by their path in the workspace, or the + templates it vendors, by path; empty for an arm with none of them.""" entry = ARMS.get(arm) or {} + if entry.get("sections"): + folder = os.path.join(ARMS_DIR, entry["sections"]) + return sorted("%s/%s" % (SECTIONS_INTO, os.path.relpath( + os.path.join(base, name), folder).replace(os.sep, "/")) + for base, _, names in os.walk(folder) for name in names) if entry.get("skills"): folder = os.path.join(ARMS_DIR, entry["skills"]) return sorted(os.listdir(folder)) if os.path.isdir(folder) else [] @@ -3529,7 +3542,8 @@ def map_use(files, arm, templates=None, delegated=()): """How one trial used what its file points at, from its transcripts: each template read from the vendored copy or loaded as a skill, as (turn, template) in order, the turn of the trial's first write to a - file of its own, or None, and how many of the uses a subagent made. + file of its own, or None, and how many of the uses a subagent made. A + section file counts as a template, by its path in the workspace. A subagent's transcript, in `delegated`, is read after the session's, its calls charged to the turn of the session's line it points back to, @@ -3540,6 +3554,10 @@ def map_use(files, arm, templates=None, delegated=()): known = set(mapped_templates(arm) if templates is None else templates) marker = VENDORED["into"] + "/" named = re.compile(re.escape(marker) + r"(templates/[\w./-]+\.md)") + reads = entry.get("vendor") or entry.get("sections") + if entry.get("sections"): + named = re.compile(r"(" + re.escape(SECTIONS_INTO + "/") + + r"[\w./-]+\.md)") def mapped(templates): """Those of the templates that are on the arm's map.""" @@ -3580,14 +3598,17 @@ def mapped(templates): # writing one came before the write. if name in SHELLS: writes_at = first_writing_command(command) - if name in SHELLS and entry.get("vendor"): - for index, template in shell_reads(command, sorted(known)): + if name in SHELLS and reads: + for index, template in shell_reads( + command, sorted(known), + SECTION_OPERAND if entry.get("sections") + else TEMPLATE_OPERAND): if template in known or not known: found.append(template) if first_write is None and (writes_at is None or index < writes_at): before.add(template) - elif name == "Read" and entry.get("vendor"): + elif name == "Read" and reads: path = str(given.get("file_path") or "").replace("\\", "/") found = mapped(named.findall(path)) elif name == "Skill" and entry.get("skills"): @@ -4520,6 +4541,40 @@ def stamped(kind, message_id, uuid, *blocks): checks.append(("an arm's map is its skills or its vendored chain, and the " "bare arm has none", got == ([], 13, 13), got)) + # The sections arm's map is its section files, by their path in the + # workspace, and a Read or a shell read of one is a use: by its path, + # through a wildcard, or relative to a directory moved into. + sections = mapped_templates("lazysections") + folder = tempfile.mkdtemp(prefix="efficacy-report-sections-") + planted = os.path.join(folder, "sections.jsonl") + static = "%s/base-quality/static-checks.md" % SECTIONS_INTO + contract = "%s/backend-api/api-contract.md" % SECTIONS_INTO + first = "%s/backend-api/api-first.md" % SECTIONS_INTO + naming = "%s/base-quality/naming.md" % SECTIONS_INTO + with io.open(planted, "w", encoding="utf-8", newline="\n") as handle: + handle.write(line("assistant", "c1", call( + "Read", file_path="C:\\pen\\%s" % static.replace("/", "\\")))) + handle.write(line("assistant", "c2", call( + "Bash", command="cat %s/backend-api/api-*.md" % SECTIONS_INTO))) + handle.write(line("assistant", "c3", call("Write", file_path="x.py"))) + handle.write(line("assistant", "c4", call( + "Bash", command="cd %s && head base-quality/naming.md" + % SECTIONS_INTO))) + handle.write(line("assistant", "c5", call( + "Read", file_path="/pen/%s/templates/core/quality.md" % into))) + used = map_use([planted], "lazysections", sections) + shutil.rmtree(folder, ignore_errors=True) + wanted = {"uses": [(1, static), (2, contract), (2, first), (4, naming)], + "first_write": 3, + "before_write": sorted([static, contract, first]), + "by_subagent": 0} + checks.append(("the sections arm's map is its section files, and a Read " + "or a shell read of one counts as a use", + len(sections) > 1 and static in sections + and all(path.startswith(SECTIONS_INTO + "/") + for path in sections) + and used == wanted, used)) + # Two arms better on two rows, the cheaper first; one out on task # success; three held, by cost; the fifth in rank stays out of round 6. costs = {"inline": 10.0, "hybrid": 8.0, "reference": 6.0, "skills": 5.0, From 7e83dba0e498ab0396259193e00b649b5525a4cd Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:34:48 +0200 Subject: [PATCH 3/4] fix(efficacy): read the map's use in a named round's report too - main() reads map uses wherever the run holds an arm whose file points at a map, named round or not, not only in a round-5e run - a named round's report prints the existing use-of-the-map table, with no H7 note beside it - self-test: a planted C1 run root whose lazysections trial reads two section files before its first write prints that arm's row and its per-trial reads in the report Refs #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/report.py | 85 +++++++++++++++++++++++++++++++++++++--- 3 files changed, 82 insertions(+), 7 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 79734fa..88ec0f5 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -204,7 +204,7 @@ when: | FR-13-18 | Self-test | `reuse.py` "a named round's trials copied on keep its round in the run record's header"
`reuse.py` "a reuse never mixes a named round's trials with others"
`reuse.py` "a trial copied within a named round names that round in its origin"
`report.py` "trials reused within one named round pair with those run there" | | FR-13-19 | Self-test | `report.py` "a named round is refused until its registration document is on main before its first trial"
`report.py` "a trial reused within its named round counts toward when the round began" | | FR-13-20 | Self-test | `archive.py` "a C1 change task's score changed in the archive fails the verify" | -| FR-13-22 | Self-test | `generate_arm.py` "the section files hold every rule block the inline root does, and no other"
`generate_arm.py` "the sections map names every section file once, under .agents/sections/"
`generate_arm.py` "a rule dropped from a section file, or a file the map does not name, is reported"
`harness.py` "the lazysections arm's files land where its map names them, out of the index"
`report.py` "the sections arm's map is its section files, and a Read or a shell read of one counts as a use" | +| FR-13-22 | Self-test | `generate_arm.py` "the section files hold every rule block the inline root does, and no other"
`generate_arm.py` "the sections map names every section file once, under .agents/sections/"
`generate_arm.py` "a rule dropped from a section file, or a file the map does not name, is reported"
`harness.py` "the lazysections arm's files land where its map names them, out of the index"
`report.py` "the sections arm's map is its section files, and a Read or a shell read of one counts as a use"
`report.py` "a named round's report prints its sections arm's use of the map" | | FR-13-23 | Self-test | `generate_arm.py` "lazyref and lazyrefold differ by the check-loop commit's lines alone, all in its section"
`generate_arm.py` "a line changed besides the commit's, one of its lines missing, or one outside its section is reported"
`generate_arm.py` "a lazyref committed at another ref than the check-loop commit is reported"
`harness.py` "round 6's lazyrefold vendors at its own recorded ref, lazysections vendors nothing" | | FR-13-24 | Self-test | `generate_arm.py` "no on-demand arm tells the agent to read everything at startup"
`generate_arm.py` "a root telling the agent to read everything at the start is caught" | diff --git a/docs/requirements.md b/docs/requirements.md index 4c090fe..db9110c 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -214,7 +214,7 @@ | FR-13-18 | The benchmark shall reuse a named round's trials under a run record naming that round and its registration's digest, and never reuse trials into a root of another round, a named round's into a root of none, or another round's into a named round's; name the round and its digest in each reused trial's origin, and pair a trial reused within one named round, under one digest, with the trials run there. | Reuse, Report | | FR-13-19 | The benchmark shall refuse a named round's report unless the document its registration entry names exists and landed on `main` before the round's first trial, unchanged since, a trial reused within the round counting toward its start. | Report | | FR-13-20 | The benchmark shall verify an archive by the report's own reading of its round, through one entry point, a named round's change tasks and its reach rule included. | Archive, Report | -| FR-13-22 | The benchmark shall build the `lazysections` arm with the templates' emitter in its sections mode, for the chain and declined list the other emitted arms take, place its section files where its map names them, out of the workspace's index, and fail its self-test where the section files' rule blocks differ from the inline root's, or the map names a section file other than once; and count a trial's Read or shell read of a section file as a use of its map. | Arm generator, Harness, Report | +| FR-13-22 | The benchmark shall build the `lazysections` arm with the templates' emitter in its sections mode, for the chain and declined list the other emitted arms take, place its section files where its map names them, out of the workspace's index, and fail its self-test where the section files' rule blocks differ from the inline root's, or the map names a section file other than once; and count a trial's Read or shell read of a section file as a use of its map, printed in a named round's report. | Arm generator, Harness, Report | | FR-13-23 | The benchmark shall build the `lazyrefold` arm as `lazyref` at the parent of the templates commit that cuts the check loop to one check command, and fail its self-test where the two committed arms' workspace files, at the refs their records name, differ by other than that commit's lines, all within the section it changes. | Arm generator | | FR-13-24 | The benchmark shall refuse an on-demand arm (`lazyref`, `lazyskills`, `lazysections`, `lazyrefold`) whose files tell the agent to read everything at the start. | Arm generator | diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index e1a113a..16d7e1f 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -1969,6 +1969,15 @@ def write_report(root, trials, table, results, seed, out_dir, margins_of(trials), uses, iso)) lines.append("") + # A named round reads its on-demand arms' use of their maps too, with + # no pilot hypothesis beside it. + if named_round(trials) is not None: + uses = report_uses(root, trials) if uses is None else uses + if uses and map_use_rows(trials, uses): + lines.extend(map_use_lines(trials, uses, "## Use of the map", + h7=False)) + lines.append("") + lines.append("## Raw numbers, per trial") lines.append("") lines.append("| Metric | %s |" % " | ".join(names)) @@ -3626,6 +3635,15 @@ def mapped(templates): else None, "by_subagent": by_subagent} +def report_uses(root, trials): + """The map uses a report reads: every trial's, wherever the run holds an + arm whose file points at a map, named round or not; None where it holds + none.""" + if not any(mapped_templates(arm_of(name)) for name in trials): + return None + return map_uses(root, trials) + + def map_uses(root, trials): """Every trial's map use, by name, for the arms whose file points at the templates and whose transcripts the root still holds.""" @@ -3732,10 +3750,10 @@ def map_use_detail(trials, uses): return lines -def map_use_lines(trials, uses): - """The use-of-the-map table and the note beside H7.""" +def map_use_lines(trials, uses, heading="### Use of the map", h7=True): + """The use-of-the-map table and, with `h7`, the note beside H7.""" rows = map_use_rows(trials, uses) - lines = ["### Use of the map", "", + lines = [heading, "", "From each trial's transcript: the templates it read from the " "vendored copy or loaded as skills, counted once each, the " "turn the first happened at, and how many came before the " @@ -3756,7 +3774,7 @@ def shown(value, places=1): row["arm"], row["trials"], row["total"], shown(row["read"]), shown(row["before"]), shown(row["first"], 0), row["up_front"], row["wrote"])) - note = h7_note(rows) + note = h7_note(rows) if h7 else None if note: lines.extend(["", "Beside H7: %s" % note]) lines.append("") @@ -8591,6 +8609,62 @@ def judged(model, design, readability): ] +def named_map_use_checks(seed): + """A named round's report reads its on-demand arms' use of their maps: + a planted C1 run whose `lazysections` trial read two section files + before its first write prints that arm's row, through the same reading + of the root `main()` makes.""" + scratch = tempfile.mkdtemp(prefix="efficacy-report-named-map-use-") + workspace = os.path.join(scratch, "pen", "lazysections-1") + folder = os.path.join(scratch, "home", ".claude", "projects", + re.sub(r"[^A-Za-z0-9]", "-", + os.path.abspath(workspace))) + os.makedirs(folder) + first = "%s/base-quality/static-checks.md" % SECTIONS_INTO + second = "%s/base-quality/naming.md" % SECTIONS_INTO + calls = [("Read", {"file_path": "%s/%s" % (workspace, first)}), + ("Bash", {"command": "cat %s" % second}), + ("Write", {"file_path": "%s/app.py" % workspace})] + with io.open(os.path.join(folder, "session.jsonl"), "w", + encoding="utf-8", newline="\n") as handle: + for turn, (name, given) in enumerate(calls, 1): + handle.write(json.dumps({"type": "assistant", "message": { + "id": "m%d" % turn, "content": [{ + "type": "tool_use", "id": "t%d" % turn, "name": name, + "input": given}]}}) + "\n") + with io.open(os.path.join(scratch, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"round": "C1", "trials": [{ + "round": "C1", "task": "build", "arm": "lazysections", + "block": 1, "trial": 1, "outcome": "completed", + "workspace": workspace, + "started_at": "2000-01-01T00:00:00"}]}, handle) + trials = planted_change_run("any-revision") + trials["lazysections-1"] = {"scores": {}, "judge": None, + "security": None, "change": None} + for trial in trials.values(): + trial["round"] = "C1" + table = collect(trials) + results = contrasts(table, seed, crossed_labels(trials)) + target = write_report(scratch, trials, table, results, seed, + out_dir=os.path.join(scratch, "out"), + uses=report_uses(scratch, trials)) + with io.open(target[:-len(".md")] + "-record.md", + encoding="utf-8") as handle: + text = handle.read() + shutil.rmtree(scratch, ignore_errors=True) + row = next((line for line in text.splitlines() + if line.startswith("| lazysections | 1 |")), None) + total = len(mapped_templates("lazysections")) + return [ + ("a named round's report prints its sections arm's use of the map", + "## Use of the map" in text and "Beside H7" not in text + and row == "| lazysections | 1 | %d | 2.0 | 2.0 | 1 | 0 of 1 |" + % total and "| lazysections-1 | 3 | 0 | 1: %s, 2: %s |" + % (first, second) in text, row), + ] + + def documents_checks(seed): """A run writes three documents: a plain report with the radars and a verdict per approach naming its deciding measures, an appendix of three @@ -8788,6 +8862,7 @@ def self_test(seed): checks.extend(withdrawal_checks(seed)) checks.extend(executive_checks(seed)) checks.extend(documents_checks(seed)) + checks.extend(named_map_use_checks(seed)) checks.extend(cross_checks(seed)) checks.extend(exclusion_checks()) checks.extend(round5_checks()) @@ -8998,7 +9073,7 @@ def main(argv): disagree(results, check) iso = (iso_reading(trials, options.seed, withdrawn) if iso_rules(trials) or posthoc_iso else None) - uses = map_uses(options.root, trials) if is_round5e(trials) else None + uses = report_uses(options.root, trials) target = write_report(options.root, trials, table, results, options.seed, out_dir, withdrawn, check, iso, uses) From f138ba76b8e453de231ef86577c02dd0d109cccf Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:31:04 +0200 Subject: [PATCH 4/4] feat(efficacy): declare round 6's contrasts for the new arms - each new arm against none: lazysections - none, lazyrefold - none - the check loop: lazyref - lazyrefold - the section files against the arms whose rules they repackage, as the C1 reading registers them: lazysections - lazyref, lazysections - reference - each new arm described in plain words for the report's "Each approach" - self-test: a run of none, lazysections and lazyrefold alone has declared contrasts and an "Each approach" entry for each new arm Refs #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- tests/efficacy/report.py | 45 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 88ec0f5..7c52784 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -165,7 +165,7 @@ when: | -- | ---- | ---------- | | FR-12-01 | Self-test | `report.py` "a contrast crossing rounds carries no verdict and counts nowhere"
`report.py` "a comparison across rounds reads as not given, not too few runs" | | FR-12-02 | Self-test | `report.py` "a contrast across rounds is unpaired, with a verdict"
`report.py` "a round-5d run reads H4 against a reused `none`, unpaired"
`report.py` "an unpaired contrast leaves out two trials, not blocks"
`report.py` "a contrast crosses rounds where its arms ran in different roots, reused or not"
`reuse.py` "a trial copied on keeps the root it ran in as its origin" | -| FR-12-03 | Self-test | `report.py` "it prints every declared contrast its arms ran"
`report.py` "a three-arm run prints only its own contrasts" | +| FR-12-03 | Self-test | `report.py` "it prints every declared contrast its arms ran"
`report.py` "a three-arm run prints only its own contrasts"
`report.py` "a run of round 6's new arms reads each against none, in plain words" | | FR-12-04 | Self-test | `report.py` "round 5 reports the files it supersedes without a verdict" | | FR-12-05 | Self-test | `report.py` "the report links its appendix, and the appendix the record"
`report.py` "the appendix holds what produced the results, the radar's axes and the verdict vector, and nothing else" | | FR-12-06 | Self-test | `report.py` "the radar draws a panel per arm, with the bare ring, in both themes"
`report.py` "an axis is better minus worse over its rows with a verdict, None without one"
`report.py` "the summary is the radar, one image per theme" | diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 16d7e1f..cda03a3 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -110,7 +110,15 @@ ("lazyskills", "lazyref"), ("lazyref", "skills"), ("lazyskills", "reference"), ("lazyref", "hand"), ("lazyskills", "hand"), - ("lazyref", "short"), ("lazyskills", "short")) + ("lazyref", "short"), ("lazyskills", "short"), + + # Round 6 (C1): each new arm against none; the check loop, + # lazyref against itself before the change; and the section + # files against the arms whose rules they repackage, lazyref + # read whole on demand and reference read up front. + ("lazysections", "none"), ("lazyrefold", "none"), + ("lazyref", "lazyrefold"), + ("lazysections", "lazyref"), ("lazysections", "reference")) # Declared before the run. "up" improves upward, "down" # improves downward, "neutral" is reported without a verdict. @@ -2231,6 +2239,10 @@ def vector_lines(results, active): "read when that work starts", "lazyskills": "the same map, each template loaded as a skill when that " "work starts", + "lazysections": "a short file that maps each topic to a small file of " + "its rules, read when the work first touches it", + "lazyrefold": "the same map as lazyref, at the templates from before " + "the one check command", } # Each radar axis in plain words, as a sentence names it. @@ -8609,6 +8621,36 @@ def judged(model, design, readability): ] +def c1_contrast_checks(seed): + """A run of round 6's new arms alone reads each against the bare arm: + it has declared contrasts, and its report says each approach in plain + words.""" + trials = {trial_name(arm, block): { + "scores": {}, "judge": None, "security": None, "round": "C1", + "change": {"suite_revision": "any-revision", + "change_suite": {"value": 0.5 + block / 100.0, + "missing": None}}} + for arm in ("none", "lazysections", "lazyrefold") + for block in range(1, 4)} + active = active_contrasts(trials) + table = collect(trials) + results = contrasts(table, seed, crossed_labels(trials)) + scratch = tempfile.mkdtemp(prefix="efficacy-report-c1-contrasts-") + try: + text = "\n".join(plain_report_lines(scratch, trials, table, results, + {}, "appendix.md", 3)) + finally: + shutil.rmtree(scratch, ignore_errors=True) + return [ + ("a run of round 6's new arms reads each against none, in plain " + "words", ("lazysections", "none") in active + and ("lazyrefold", "none") in active + and "### `lazysections`" in text and "### `lazyrefold`" in text + and all(PLAIN_ARMS.get(arm) for arm in ("lazysections", + "lazyrefold")), active), + ] + + def named_map_use_checks(seed): """A named round's report reads its on-demand arms' use of their maps: a planted C1 run whose `lazysections` trial read two section files @@ -8863,6 +8905,7 @@ def self_test(seed): checks.extend(executive_checks(seed)) checks.extend(documents_checks(seed)) checks.extend(named_map_use_checks(seed)) + checks.extend(c1_contrast_checks(seed)) checks.extend(cross_checks(seed)) checks.extend(exclusion_checks()) checks.extend(round5_checks())