diff --git a/.claude/skills/morphic-changing-the-ir/SKILL.md b/.claude/skills/morphic-changing-the-ir/SKILL.md index 1d94ff4b6..4bfee910b 100644 --- a/.claude/skills/morphic-changing-the-ir/SKILL.md +++ b/.claude/skills/morphic-changing-the-ir/SKILL.md @@ -5,9 +5,9 @@ description: Use when changing anything under ir/ or pass/ (types, codecs, walks # Changing the IR -The IR is the ABI (`CLAUDE.md`, invariant 1): a change to it is a change to every stage that reads -it. `docs/ir/README.md` leads to what is normative for its shapes, `CLAUDE.md` gives the Go -representation they take, and architecture §2.5 says how a change lands. +The IR is the ABI (`CLAUDE.md`, invariant 1). `docs/ir/README.md` leads to what is normative for +its shapes, `CLAUDE.md` gives the Go representation they take, and architecture §2.5 says how a +change lands. ## Before writing it @@ -20,8 +20,9 @@ representation they take, and architecture §2.5 says how a change lands. count that fact (`references/ir-lessons.md#measure-the-premise`). 4. Weigh designs that differ in that fact, one of them outside the issue's framing (`references/ir-lessons.md#weigh-the-framing`), prototyping each emitter mechanism against its - layer's requirements (`references/ir-lessons.md#prototype-against-every-requirement`), and write - each loser's reason in `docs/ir` beside the winner. + layer's requirements + (`references/designing-emitters.md#prototype-against-every-requirement`), and write each loser's + reason in `docs/ir` beside the winner. 5. Name the check that will hold it: an `irverify` rule, a codec test or a lint rule, or, for a rule in `docs/emitters`, a `T-` in `docs/emitters/testing/mandatory-tests.md` the rule cites. @@ -31,22 +32,24 @@ Passes: architecture §2.2. - **Version.** Bump `IRVersion` as `docs/ir/ir-version.md` says. `TestIRVersion_PinsTheEncodedShape` and `TestIRVersion_HistoryRecordsEachGeneration` catch a shape change, and - `TestIRVersion_PinsTheNames` a renamed symbol. A change of meaning with no change of shape, such as - a lowering that starts filling a member, or a hint moved at a position + `TestIRVersion_PinsTheNames` a moved name: a canonical word sequence or a hint that an emitter + renders an SDK identifier from (`docs/ir/ir-version.md`, "A change to a name moves it too"). + Renaming a Go declaration moves neither. A change of meaning with no change of shape, such as a + lowering that starts filling a member, or a hint moved at a position `testdata/golden/openapi/hint_positions.yaml` does not write, is the bump no test sees: make it, with the row's `meaning`. `git diff origin/main... -- testdata | grep -E '^-\s*"(canonical|hint)"'` - lists the names a branch moved. A diagnostic shape change can also move `engine/report`'s - `SchemaVersion` (`references/ir-lessons.md#report-schema-version`). + lists the names a branch moved. The bump's history entry lists each ID form and diagnostic code + the change moves (`references/ir-lessons.md#entry-lists-moved-ids-and-codes`). A diagnostic shape + change can also move `engine/report`'s `SchemaVersion` + (`references/ir-lessons.md#report-schema-version`). - **Other PRs.** After each merge moving a version, check no version repeats (`references/ir-lessons.md#version-collisions`). - **Mentions.** A position only mentioning a type needs more than classifying (`references/ir-lessons.md#mention-is-no-use`). - **Hand lists.** A new field, ID class or sum kind meets classification tests in `ir` and `ir/irverify`; `references/ir-lessons.md` says which list each meets. -- **Census.** Run `go test ./cmd/morphic-census -update` when a case sets a fact listed in - `testdata/unwitnessed.golden.txt`. -- **Goldens.** A version bump rewrites none, but a new namespace in a compiler's `Namespaces` - rewrites the `idSpaces` of every one (`references/ir-lessons.md#new-id-namespace`). +- **Goldens.** A new namespace in a compiler's `Namespaces` rewrites the `idSpaces` of every golden + (`references/ir-lessons.md#new-id-namespace`). - **Values.** A lowering writing a value a field never held, one a consumer switches on, or withdrawing one, changes no shape, so no test sees it: bump for its meaning (`references/ir-lessons.md#widened-field-values`). @@ -54,12 +57,12 @@ Passes: architecture §2.2. node changing kind at its ID bumps (`references/ir-lessons.md#kind-change-at-an-id-bumps`). - **Old wording.** Amending a rule sweeps the sentences that stated it, code blocks included (`.claude/skills/morphic-verifying-changes/references/sweep-every-site.md#sweep-prose-a-meaning-change-falsifies`). -- **Emitters.** Once an emitter reads the field, architecture §2.5 says the change lands whole. - **Breaking.** A version bump's title takes `!`, and its commit and PR bodies say what an older consumer sees (`docs/ir/ir-version.md`, `morphic-shipping-prs`). ## References - `references/ir-lessons.md`: version bumps, hand lists, namespaces, invariants, field values, - flattened members and emitter design rules. + flattened members, premises. +- `references/designing-emitters.md`: emitter design rules. - `references/verifier-and-codecs.md`: what the verifier, text predicates and codecs must reach. diff --git a/.claude/skills/morphic-changing-the-ir/references/designing-emitters.md b/.claude/skills/morphic-changing-the-ir/references/designing-emitters.md new file mode 100644 index 000000000..56235d197 --- /dev/null +++ b/.claude/skills/morphic-changing-the-ir/references/designing-emitters.md @@ -0,0 +1,93 @@ +# Designing emitters + +What a design in `docs/emitters` meets that its own text does not say: the inputs each rule reads, +the order its steps run in, and the requirements of the layer a mechanism lives in. + +## Check a design rule against every input it reads +`design-rule-over-its-document` + +- **Rule.** When an IR or emitter design states a rule, placement argument or step order, list + its inputs from their declarations: each field of every IR type it reads, every `TypeKind` and + enumeration value those fields reach, each kind's `docs/ir` page, and each sibling section of + its document, cited, not restated + (`.claude/skills/morphic-verifying-changes/references/derive-never-maintain.md#single-source-no-restatement`). + Say whether each changes the answer, compiling a minimal spec for one the golden spec lacks. + Check a step order by `references/designing-emitters.md#step-order-both-ways`. +- **Why.** A placement covered one per-target table and not its twin, an import step preceded the + steps renaming what it imports (#1019), and #1329's rules missed fields, enumeration values, + kind documents and restated sections (#1402). +- **Probe.** `go doc -all ./ir ` and + `awk '/^\040{0,3}(\140{3}|~{3})/{c=!c}!c&&/^#/{print FNR": "$0}' `; an input + with no stated effect is unchecked. + +## Check a step order against what later steps change and declare +`step-order-both-ways` + +- **Rule.** Check a step order both ways: what each step reads that a later one changes, and what + each adds to that a later one declares. A step adding to a declaration runs after the step + declaring it. Also take + `references/designing-emitters.md#step-table-names-what-a-rule-changes` and + `references/designing-emitters.md#derived-fact-after-its-input`. +- **Why.** An import step preceded the steps renaming what it imports (#1019). At #1340's + `4cb221a80`, `docs/emitters/refine/steps.md` placed `LowerRedaction` before + `BuildRequestShaping`, whose request types it gives a redacting form, and `MarkStability` before + the steps declaring the methods it marks; reading only what each step reads passed both (#1630). +- **Probe.** List the order with + `awk -F'|' '/^\| \140/{print NR": "$2}' docs/emitters/refine/steps.md`, and beside each step + what it reads and adds to, against the steps after it, as the ordering paragraph of + `docs/emitters/refine/pipeline.md` argues each placement. + +## Name what a new rule changes in every refine step table +`step-table-names-what-a-rule-changes` + +- **Rule.** A rule in `docs/emitters` that changes what a refine step produces or reads names it in + that step's row of `docs/emitters/refine/steps.md` and in each target's step table under + `docs/emitters/targets`. +- **Why.** #1740 added per-variant `Required` and `Redacted` to `TypePlan.Composed`, updating + `LowerModels` and `ProjectVisibilityShapes` while leaving `LowerOptionality` and `LowerRedaction` + reading `TypePlan.Required` and `TypePlan.Redacted` alone (#1720). +- **Probe.** For each field the change adds to a plan type, + `git grep -n '' -- docs/emitters/refine/steps.md docs/emitters/targets` names every step + row that reads it. + +## Check every derived fact's producer and consumer against the step order +`derived-fact-after-its-input` + +- **Rule.** A rule deriving a fact some step reads (a file, a unit, an import) from a fact another + step settles (an identifier) names both steps and checks the pair against + `docs/emitters/refine/steps.md`'s order. +- **Why.** #1738 at `01f5c2b28` derived a Go file name from a declaration's identifier while + `ComputeImports` ran before `RenderCasing`, failing with `time redeclared in this block`; #1740 + left `LowerOptionality` and `LowerRedaction` reading stale fields (#1754). +- **Probe.** `git grep -nE 'ComputeImports|RenderCasing|ResolveCollisions|PlaceDeclarations' -- docs/emitters` + beside each derived fact the change states. + +## Prototype a specified mechanism against every requirement on its layer +`prototype-against-every-requirement` + +- **Rule.** Prototype a mechanism a design document specifies on the target's own library, against + every requirement the emitter documents put on the layer it runs in, not only the property it is + for, and name each requirement's result in the document. +- **Why.** Three decode mechanisms in turn passed a prototype of their cost and failed a sibling + document's requirement: builders could not reach a variant in another output unit, a second + `json.WithUnmarshalers` replaced a caller's own, and Kotlin `@Contextual` fields threw under a + caller's own `Json` (#1329); a `must|never|only` grep missed #1340's "every error message" + (#1631). +- **Probe.** With `` each entry of `ls docs/emitters` the mechanism runs in, + `grep -rnwE 'must|never|only|every|each|all|always' docs/emitters/README.md docs/emitters/contract docs/emitters/testing docs/emitters/ docs/emitters/targets/` + lists the candidate requirements; each that bears on the mechanism has a prototype run, or is + unmet. + +## Shape a declaration from what an additive change leaves alone +`declaration-reads-its-definition` + +- **Rule.** A plan fact that shapes a declaration, such as a closed sum against a struct of + pointers, reads what adding a member, a variant or an operation leaves as it was, such as the + type's value type and row, never one member's value or the operations reaching it. Where it + must read a fact such a change moves, the document names that fact and the break it causes the + declaration's callers. +- **Why.** A fix to #1329's member rule read which way a union travels, so a new operation would + flip its form; an enum lowered as text once a member passed `int64` would turn + `type Code int64` into `type Code string` (#1334). +- **Probe.** Add a member, a variant and an operation to a fixture: the declaration's form holds, + or the document names its break. diff --git a/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md b/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md index 1d9264b2a..b7734fd8b 100644 --- a/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md +++ b/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md @@ -1,8 +1,9 @@ # IR lessons What an IR change meets that `docs/ir` does not say: other branches claiming the same version, -hand lists that must name a new field, guarantees a type held without stating them, and emitter -design rules. +hand lists that must name a new field, guarantees a type held without stating them, and the +premises a design rests on. `references/designing-emitters.md` holds the rules for an emitter +design. ## The PR merging second takes the next version `version-collisions` @@ -31,6 +32,20 @@ design rules. while `morphic-changing-the-ir` named `IRVersion` alone (#2129). - **Probe.** `go test ./engine/report -run TestSchemaVersion_PinsTheEncodedShape`. +## A history entry lists the ID forms and diagnostic codes its change moves +`entry-lists-moved-ids-and-codes` + +- **Rule.** A bump's entry in `docs/ir/version-history.md` lists the ID forms and diagnostic codes + its change moves, as `docs/ir/ir-version.md` ("A bump's entry names the IDs and codes its change + moves") says. +- **Why.** Nothing asked an entry to list either move (#2399): 0.69.0 (#1977) names neither form of + its moved property IDs, nor 0.70.0 (#1996) a finding moved to `openapi/composition-lowering`. +- **Probe.** IDs, indices reduced, and codes: + `git diff origin/main... -- testdata | perl -lne 'print "$1 $2" =~ s{/\d+(?![^/])}{/}gr if /^([-+]).*"(?:id|code)": "([^"]*)"/' | sort | uniq -c`. + A form or code printed with `-` moved or went; its hunks name the construct. On `9562ea46d^!` + it prints `p/openapi//properties/

` going and + `p/composed//oneOf//allOf/allOf/properties/

` coming. + ## Classify every field you add to package ir, walker state included `classify-ir-fields` @@ -111,16 +126,19 @@ design rules. in a second document requiring a scheme neither declares: it reports `openapi/unresolved-security-scheme` and no `ir/unresolved-auth-space`. -## Expect a new ID namespace to rewrite every golden document +## A new ID namespace rewrites every golden; a composed key needs none `new-id-namespace` - **Rule.** `Document.IDSpaces` declares what a compiler can mint, not what a document uses, and - goldens store it, so a new entry in a compiler's `Namespaces` changes every golden document, where - a version bump changes none. Show that no other line moved, land a spec that mints the namespace, - and trial-merge the open PRs + goldens store it, so a new entry in a compiler's `Namespaces` changes every golden, unlike a + version bump: show no other line moved, land a spec minting it, and trial-merge the open PRs (`.claude/skills/morphic-shipping-prs/references/merging-main.md#trial-merge-open-prs`). + `composedMember`'s `composed` keys below `/allOf` name no source construct + (`docs/compilers/openapi.md#allof-redeclared-property`), so a node minted at one needs no new + namespace, only an injective key (`references/ir-lessons.md#minted-key-injective`). - **Why.** One entry in the `auth` list changed all 128 goldens by one hunk each, and `TestNamespaces_DeclaredAreExactlyWhatTheCorpusUses` refused it while no spec minted it (#1213). + No rule named the `composed` key (#2347). - **Probe.** `go test ./compilers/openapi/e2e -run 'TestConformance|TestGolden' -update`, then `git diff -U0 -- testdata | grep -E '^[-+] ' | sort | uniq -c` prints the namespace's lines alone. @@ -221,7 +239,8 @@ design rules. - **Rule.** A lowering that mints a new node of a declared kind, moves a reference to another node, or adds an ID namespace changes no key's meaning, IDs being opaque to consumers - (`docs/ir/identity.md`), and bumps nothing. A node changing kind at an existing ID takes + (`docs/ir/identity.md`), and bumps nothing. A moved `Provenance.Pointer` takes + `references/ir-lessons.md#moved-provenance-pointer`; a node changing kind at an existing ID takes `references/ir-lessons.md#kind-change-at-an-id-bumps`; a value a consumer switches on takes `references/ir-lessons.md#widened-field-values`. - **Why.** The redeclared-field merge added the `composed` namespace and minted composed models @@ -241,6 +260,22 @@ design rules. - **Probe.** `git show 632099c95 --stat -- ir/document.go docs/ir/version-history.md` lists both files for `0.42.0`. +## A moved provenance pointer alone bumps nothing; a class recording another place does +`moved-provenance-pointer` + +- **Rule.** A node recording another `Provenance.Pointer` changes a value, not a key's meaning, + and bumps nothing, its ID moving with it where `docs/ir/identity.md#what-irverify-holds` ties + the two. A hint composed from that position, as + `commonFor` in `compilers/openapi/internal/schema/hoist.go` composes an anonymous node's, moves + too, and `SKILL.md`'s Version step decides the bump. A change to which place a whole class + records, such as use site or declaration, changes the key's meaning and bumps `IRVersion` with + the row's `meaning` (`docs/ir/ir-version.md`). +- **Why.** #1009 bumped to `0.17.0` at an unchanged shape when each node another file declares + moved from its use site to its declaration, and the skill said nothing of one node's pointer + moving (#2346). +- **Probe.** `git show 461d16e32 -- ir/irversion_test.go` adds the `0.17.0` row, its `meaning` + saying what each document declares is lowered there. + ## Ask each reader of a widened or unfilled field what it did with the old value `widened-field-consumers` @@ -282,108 +317,33 @@ design rules. (`success: {enum: [false]}` over `success: {enum: [true]}`); the reader yields the later declaration's values, not an empty set. -## Check a design rule against every input it reads -`design-rule-over-its-document` - -- **Rule.** When an IR or emitter design states a rule, placement argument or step order, list - its inputs from their declarations: each field of every IR type it reads, every `TypeKind` and - enumeration value those fields reach, each kind's `docs/ir` page, and each sibling section of - its document, cited, not restated - (`.claude/skills/morphic-verifying-changes/references/derive-never-maintain.md#single-source-no-restatement`). - Say whether each changes the answer, compiling a minimal spec for one the golden spec lacks. - Check a step order by `references/ir-lessons.md#step-order-both-ways`. -- **Why.** A placement covered one per-target table and not its twin, an import step preceded the - steps renaming what it imports (#1019), and #1329's rules missed fields, enumeration values, - kind documents and restated sections (#1402). -- **Probe.** `go doc -all ./ir ` and - `awk '/^\040{0,3}(\140{3}|~{3})/{c=!c}!c&&/^#/{print FNR": "$0}' `; an input - with no stated effect is unchecked. - -## Check a step order against what later steps change and declare -`step-order-both-ways` - -- **Rule.** Check a step order both ways: what each step reads that a later one changes, and what - each adds to that a later one declares. A step adding to a declaration runs after the step - declaring it. Also take `references/ir-lessons.md#step-table-names-what-a-rule-changes` and - `references/ir-lessons.md#derived-fact-after-its-input`. -- **Why.** An import step preceded the steps renaming what it imports (#1019). At 4cb221a80, - `docs/emitters/refine/steps.md` placed `LowerRedaction` before `BuildRequestShaping`, whose - request types it gives a redacting form, and `MarkStability` before the steps declaring the - methods it marks; reading only what each step reads passed both (#1630). -- **Probe.** List the order with - `awk -F'|' '/^\| \140/{print NR": "$2}' docs/emitters/refine/steps.md`, and beside each step - what it reads and adds to, against the steps after it, as the ordering paragraph of - `docs/emitters/refine/pipeline.md` argues each placement. - -## Name what a new rule changes in every refine step table -`step-table-names-what-a-rule-changes` - -- **Rule.** A rule in `docs/emitters` that changes what a refine step produces or reads names it in - that step's row of `docs/emitters/refine/steps.md` and in each target's step table under - `docs/emitters/targets`. -- **Why.** #1740 added per-variant `Required` and `Redacted` to `TypePlan.Composed`, updating - `LowerModels` and `ProjectVisibilityShapes` while leaving `LowerOptionality` and `LowerRedaction` - reading `TypePlan.Required` and `TypePlan.Redacted` alone (#1720). -- **Probe.** For each field the change adds to a plan type, - `git grep -n '' -- docs/emitters/refine/steps.md docs/emitters/targets` names every step - row that reads it. - -## Check every derived fact's producer and consumer against the step order -`derived-fact-after-its-input` - -- **Rule.** A rule deriving a fact some step reads (a file, a unit, an import) from a fact another - step settles (an identifier) names both steps and checks the pair against - `docs/emitters/refine/steps.md`'s order. -- **Why.** #1738 at `01f5c2b28` derived a Go file name from a declaration's identifier while - `ComputeImports` ran before `RenderCasing`, failing with `time redeclared in this block`; #1740 - left `LowerOptionality` and `LowerRedaction` reading stale fields (#1754). -- **Probe.** `git grep -nE 'ComputeImports|RenderCasing|ResolveCollisions|PlaceDeclarations' -- docs/emitters` - beside each derived fact the change states. - -## Prototype a specified mechanism against every requirement on its layer -`prototype-against-every-requirement` - -- **Rule.** Prototype a mechanism a design document specifies on the target's own library, against - every requirement the emitter documents put on the layer it runs in, not only the property it is - for, and name each requirement's result in the document. -- **Why.** Three decode mechanisms in turn passed a prototype of their cost and failed a sibling - document's requirement: builders could not reach a variant in another output unit, a second - `json.WithUnmarshalers` replaced a caller's own, and Kotlin `@Contextual` fields threw under a - caller's own `Json` (#1329); a `must|never|only` grep missed #1340's "every error message" - (#1631). -- **Probe.** With `` each entry of `ls docs/emitters` the mechanism runs in, - `grep -rnwE 'must|never|only|every|each|all|always' docs/emitters/README.md docs/emitters/contract docs/emitters/testing docs/emitters/ docs/emitters/targets/` - lists the candidate requirements; each that bears on the mechanism has a prototype run, or is - unmet. - -## Shape a declaration from what an additive change leaves alone -`declaration-reads-its-definition` - -- **Rule.** A plan fact that shapes a declaration, such as a closed sum against a struct of - pointers, reads what adding a member, a variant or an operation leaves as it was, such as the - type's value type and row, never one member's value or the operations reaching it. Where it - must read a fact such a change moves, the document names that fact and the break it causes the - declaration's callers. -- **Why.** A fix to #1329's member rule read which way a union travels, so a new operation would - flip its form; an enum lowered as text once a member passed `int64` would turn - `type Code int64` into `type Code string` (#1334). -- **Probe.** Add a member, a variant and an operation to a fixture: the declaration's form holds, - or the document names its break. - ## Count what a design assumes about real input before choosing it `measure-the-premise` - **Rule.** Before choosing a shape a consumer will use, write the job they do with it and the fact - about real input it rests on, then count it on the golden spec and the corpus, through `ir`'s - own derivations + about real input it rests on, then count it on the golden spec and corpus through `ir`'s own + derivations (`.claude/skills/morphic-reviewing-prs/references/design.md#program-from-the-document`). - A program running the proposed rules shows only that they are total, since it assumes that fact; - a worked example, chosen because it fits, shows nothing. + A program running the proposed rules shows only that they are total, assuming that fact; + a worked example, chosen because it fits, shows nothing; for code not yet built, + `references/ir-lessons.md#premise-about-planned-code`. - **Why.** A design kept one error type per body, as a worked example had it, and a run placed every failure, yet most operations with several error bodies used one type for all, status telling failures apart, uncounted until a reviewer asked (#1167). -- **Probe.** For each decision in the PR body, name its premise and the command that could - have falsified it. A decision with neither is unproved. +- **Probe.** Each decision in the PR body names its premise and a command that could falsify it; + one with neither is unproved. + +## Search the design documents for a premise about code not yet built +`premise-about-planned-code` + +- **Rule.** A premise about code that only `docs/` plans, such as what a configuration layer will + hold, is measured by searching every Go block and table under `docs/` for the type, field or call + it names, quoting each hit against the premise beside the golden-spec count. +- **Why.** A decoder keeping a `null` inside a raw JSON member was taken to disagree with no + document on the premise that no planned layer holds raw JSON, while + `docs/emitters/contract/shaping-hints.md` gave a hint an `ir.RawValue` map (#2310). +- **Probe.** `git grep -nE 'jsontext\.Value|RawValue' -- docs/emitters` lists the hint among its + hits. ## Reach an unexported IR derivation through `export_test.go`, never a copy `measure-through-irs-own-derivation` diff --git a/.claude/skills/morphic-checking-style/references/departures.md b/.claude/skills/morphic-checking-style/references/departures.md index 14683db7f..7e9c910a5 100644 --- a/.claude/skills/morphic-checking-style/references/departures.md +++ b/.claude/skills/morphic-checking-style/references/departures.md @@ -187,6 +187,22 @@ the rule here rather than reading it across. satisfying one of `optionalInterfaces` in `internal/archtest/assertion_test.go` without its assertion. +## Keep a name long and literal at any scope +`names-long-at-any-scope` + +- **Rule.** Rules 2.1 and 2.18 size a name to its scope, allowing one letter or `cfg` in a few + lines. Here a name is long, literal and unabbreviated at any scope, bar the one-letter names + `.claude/skills/morphic-designing-code/references/design-rules.md#name-what-it-holds` allows, + the standard-library conventions `r io.Reader` and `w io.Writer` among them, and the `ctx` and + `err` that `CLAUDE.md` writes. Rule 2.18's point 5, no type information in a name, still holds. + `.golangci.yml` leaves off `varnamelen`, which both rules name, as it measures how far a name is + used from where it is declared. +- **Why.** Names that needed their comments left the code unreadable to its owner (#2130); a + reviewer reading chapter 02 could accept `ts *compile.Types` in a short function (#2394). +- **Probe.** `grep -c varnamelen .golangci.yml` prints 0, and + `.claude/skills/morphic-designing-code/references/design-rules.md#one-letter-names-by-kind` + lists a change's one-letter names. + ## Hold the shadowing rule's package-level half in review `shadowing-package-half-unheld` @@ -203,17 +219,32 @@ the rule here rather than reading it across. locals over `type fake`, including `internal/harness/presence_internal_test.go` and `internal/harness/spelling_internal_test.go`, plus 5 local-over-local). +## Start an enum at one, name its zero, or say the zero is its default +`enum-zero-states-its-meaning` + +- **Rule.** Rule 5.28 binds: a zero an unset field or a miss produces must not pass for a member + chosen on purpose, as + `.claude/skills/morphic-designing-code/references/design-rules.md#type-the-form` says of every + absent state. An enum starts at `iota + 1`, names its zero for the unset state (`NoRole`, + `FormatNone`), or, where unset means the zero member, says so in that constant's comment, as + `idRequired` in `ir/idpositions.go` does. +- **Why.** 44 of 65 enums starting at `iota` did so at an ordinary member saying nothing of their + zero, and `typemap.Found`'s zero was `Exact`, the value `Lookup` returned beside `false` on a + miss (#2305, #2308, #2378). +- **Probe.** `git grep -nE '^[[:space:]]+[[:alnum:]_]+ +[[:alnum:]_.]+ += iota( //.*)?$' -- '*.go' ':!*_test.go' ':!*testdata*'` + lists each enum starting at zero. + ## Hold a new line to a rule the tree still breaks `rules-the-tree-still-breaks` - **Rule.** Rule 10.6 bars the `http.DefaultClient` `engine/reader/disk.go` falls back to (#1036), - rule 6.15 the `cmp.Diff` failures most tests print with no direction key (#1206), and rule 6.24 - the test doubles with no behaviour prefix (#1279). A line a change adds is held to the rule, since - surrounding code is no defence (`CLAUDE.md`, "Correctness comes first"). A row leaves this rule - when its issue's fix lands. + 6.15 `cmp.Diff` failures printing no direction key (#1206), 6.24 test doubles with no behaviour + prefix (#1279), and 5.28 enums with an unexplained ordinary zero (#2378). A line a change adds is + held to the rule, since surrounding code is no defence (`CLAUDE.md`, "Correctness comes first"). + A row leaves when its issue's fix lands. - **Why.** The list is what someone met and filed, not every rule the tree breaks: rules 6.15 and 6.24 went unlisted until reviews raised them (#1192, #1208). The fallback waits on a time bound for a network read (#1036, #1173). - **Probe.** `git grep -n 'http.DefaultClient' -- 'engine/reader/*.go' ':!*_test.go'`, and the - commands in #1206 and #1279. `gh issue list --state open --limit 1000 --search styleguide` lists - what else is filed. + commands in #1206, #1279 and #2378. `gh issue list --state open --limit 1000 --search styleguide` + lists what else is filed. diff --git a/.claude/skills/morphic-curating-skills/SKILL.md b/.claude/skills/morphic-curating-skills/SKILL.md index 606719c9f..7d544b72d 100644 --- a/.claude/skills/morphic-curating-skills/SKILL.md +++ b/.claude/skills/morphic-curating-skills/SKILL.md @@ -37,25 +37,26 @@ List the skills with `grep -h '^description:' .claude/skills/*/SKILL.md`, not a - **Probe.** The command or planted defect that shows whether it holds, unless the Rule is one. ``` -Word caps, evidence pinning and citation form live in `references/rule-format.md`. +Word caps, evidence, citations, headings and routing live in `references/rule-format.md`. ## Limits -- A `SKILL.md` body stays within 500 words. Its description stays within 500 characters, as every - session loads it, and starts "Use when": it says when to load the skill, never what it does, - as an agent follows a summary, not the body. Other frontmatter follows - `https://agentskills.io/specification`. +- A `SKILL.md` body stays within 500 words. Its description stays within 500 characters and + starts "Use when": it says when to load the skill, never what it does, as an agent follows a + summary, not the body. Other frontmatter follows `https://agentskills.io/specification`. - A reference file stays within 4,000 words. A full file takes a rule only by merging or removing one. - Everything works from a fresh clone's root, where paths start, bar those inside the skill's folder, and paths sit in code spans the lint holds to the tree. -- Scripts are executable Python 3.14, standard library only, each with a `test_.py` beside it. +- Scripts are executable Python 3.14, standard library only, each beside a `test_.py`. Run a skill's tests with `python3.14 -m unittest discover -s .claude/skills//scripts`. ## Upkeep -- Run `python3.14 .claude/skills/morphic-curating-skills/scripts/skills_lint.py` after every edit: - no gate runs it. +- Run `python3.14 .claude/skills/morphic-curating-skills/scripts/skills_lint.py`, which no gate + runs, and + `go test ./internal/archtest ./compilers/openapi/internal/canary ./compilers/openapi/e2e -run '^TestDocuments_LinksResolve$|^TestDocuments_NameOnlyTestsThatExist$|^TestDocuments_OpenNoLineWithAPlus$|^TestDocuments_CiteNoRetiredPage$|^TestAgentFiles_ReachAntigravity$|^TestRecord_CitationsNameAnEntry$|^TestLoweringSpec_CitationsNameARule$'` + after every edit. - After changing a Why, confirm each item it cites is the work its clause describes. - A lesson failing again means its skill failed: sharpen the wording or trigger, not add a copy. - An edit to `CLAUDE.md`, `AGENTS.md` or a skill needs the maintainer's own message, or an open diff --git a/.claude/skills/morphic-curating-skills/references/rule-format.md b/.claude/skills/morphic-curating-skills/references/rule-format.md index 49d19bb04..7daa11ca2 100644 --- a/.claude/skills/morphic-curating-skills/references/rule-format.md +++ b/.claude/skills/morphic-curating-skills/references/rule-format.md @@ -1,7 +1,60 @@ # Rule format A rule stays within 150 words by `wc -w`, heading and key included, or becomes two, the first -citing the second. No narrative, dates or first person, and no count a command beside it does not -derive, bar a Why's evidence, measured as the Probe asks and pinned by an issue, a merged PR or a -revision, never an open PR. Cite a rule as `references/.md#`, from another skill by its -full path. +citing the second. A cut made to fit the cap never drops a fact the rule's Probe needs or anything +a closing issue asked for, such as a platform's spelling, a step or an option. +`.claude/skills/morphic-reviewing-prs/references/claims-and-process.md#cut-against-mains-words` +checks a cut for what `main`'s words held, and +`.claude/skills/morphic-shipping-prs/references/closing-issues.md#closing-issue-met-at-its-site` +for each step a closing issue's Direction asks. No narrative, dates or first person, and no count a +command beside it does not derive, bar a Why's evidence, measured as the Probe asks. That evidence +is pinned by an issue, a merged PR or a revision +(`references/rule-format.md#pin-a-revision-where-it-stays`), never by a claim resting on an open +PR's moving head. A Why may name an open PR as its evidence's source when the pin is durable; the +PR adding the citation is such a pin, merged by the time the citation lands. +`gh pr view --json state --jq .state` prints a cited PR's `OPEN`, `CLOSED` or `MERGED`. Cite a +rule as `references/.md#`, from another skill by its full path. + +## Pin a revision to `main` or to the PR whose head holds it +`pin-a-revision-where-it-stays` + +- **Rule.** A revision a Why or Probe cites is on `main`, or is named with the PR whose head holds + it (#N's ``): after a squash merge only `pull//head` reaches a branch's commits, and an + open PR's head is fetched there too. +- **Why.** Skills cited revisions of open and squashed PRs, such as #1340's `4cb221a80`, naming no + PR holding them (#2379). +- **Probe.** `git merge-base --is-ancestor origin/main; echo $?` prints 0 for a revision on + `main`. Off it, `gh api 'repos/{owner}/{repo}/commits//pulls' --jq '.[].number'` lists the + PRs holding it, the cited #N among them, and + `git fetch -q origin pull//head && git merge-base --is-ancestor FETCH_HEAD; echo $?` + prints 0. Either check prints 1 outside it and 128 for a hash the clone lacks; the API call + exits 1 for one GitHub lacks. + +## Hold a rule's heading and key to its Rule's scope after every edit to either +`heading-matches-the-rule` + +- **Rule.** After every edit to a rule's heading or key, or to its Rule, read the heading and key + against the Rule's scope: who acts, when, and which cases. Neither may be narrower, sending a + reader past the rule, or wider, sending one to it for a case it does not cover. No lint judges + scope: author and reviewer read it. +- **Why.** Headings disagreed with their Rule in #1338, #1510 and #2379, which headed + `.claude/skills/morphic-planning-work/references/large-changes.md#re-search-the-tracker-before-the-build` + for a design reviewed over days while its Rule asked before every build (#2402). +- **Probe.** `git diff -U20 origin/main...HEAD -- .claude/skills | grep -E -A1 '^[-+ ](## |- \*\*Rule\.)'` + prints each heading and key near a change beside its Rule's opening; with #2379's + `67bbcf87a` for `HEAD`, that heading beside "Right before the build starts". + +## Route each rule a change adds, moves or rewords, and keep each topic line it shortens whole +`each-rule-is-routed` + +- **Rule.** Each rule a change adds, moves or rewords is reached by a citation, or by the topics + its file's line in its `SKILL.md` gives (under References in most skills). A topic line a change + shortens still covers every rule its file holds. The skills lint checks that each citation names + a rule, not that each rule is named. +- **Why.** #2379 cut topics from three References lines whose files still held the rules, and + added `.claude/skills/morphic-verifying-changes/references/differentials.md#memo-across-charged-walks` + cited from nowhere and outside its file's topics (#2406). +- **Probe.** For each such key, + `git grep -n -F '#' -- .claude CLAUDE.md AGENTS.md CONTRIBUTING.md docs` lists its + citations; with none, read its file's topic line. `grep -n '^## ' ` lists the rules a + shortened line must still cover. diff --git a/.claude/skills/morphic-curating-skills/scripts/skills_lint.py b/.claude/skills/morphic-curating-skills/scripts/skills_lint.py index 437baccae..fe539d84b 100755 --- a/.claude/skills/morphic-curating-skills/scripts/skills_lint.py +++ b/.claude/skills/morphic-curating-skills/scripts/skills_lint.py @@ -11,11 +11,11 @@ summary line. Exit 0 when clean, 1 on a finding, 2 when it cannot run or finds no skill to check. Each rule in a reference is held to the format morphic-curating-skills gives. Scripts are executable Python 3.14, declared in their first line and a PEP 723 script block, with the standard library only -and a test_.py beside each. A span shaped as an ir/ or pass/ diagnostic code is no path, and -a path the tree lacks may name the Go toolchain's sources, which `go env GOROOT` locates; where go -cannot say, the lint stops and says so. A Go name spelled `Name` in `path/to/file.go` on one line -is held to what that file declares. A SKILL.md body spells no $ before a digit, which the skill -loader replaces with an argument. +and a test_.py beside each. A span naming a diagnostic code the module builds is no path, +and a path the tree lacks may name the Go toolchain's sources, which `go env GOROOT` locates; where +go cannot say, the lint stops and says so. A Go name spelled `Name` in `path/to/file.go`, on one +line or wrapped onto the next, is held to what that file declares. A SKILL.md body spells no $ +before a digit, which the skill loader replaces with an argument. """ import argparse @@ -26,6 +26,7 @@ import subprocess import sys import traceback +from collections.abc import Iterator from pathlib import Path MAX_BODY_WORDS = 500 @@ -64,9 +65,7 @@ SPAN = re.compile(r"`([^` ]+)`") ANY_SPAN = re.compile(r"`[^`]*`") PROSE_PATH = re.compile(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.*-]+)+") -LINK = re.compile(r"\]\(([^)#]+)") LINK_TARGET = re.compile(r"\]\([^)]*\)") -TEST = re.compile(r"(?:^|[^A-Za-z0-9_])(Test[A-Z][A-Za-z0-9_]*)") # A Go name placed in a file: `Name` in `path/to/file.go`. NAME_IN_FILE = re.compile(r"`([A-Za-z_]\w*)` in `([^`\s]+\.go)`") # A const, var or type group, or a struct or interface type, up to what closes it, which gofmt @@ -77,12 +76,6 @@ # A § after the name of a document it can be in, a line break between them allowed: one of the # design documents SECTION holds to the tree, or an RFC. Any other names no document. NAMED_SECTION = re.compile(r"(?:architecture(?:\.md)?|RFC \d+)\s?§") -KEY = re.compile(r"(parser-library|compilers/openapi)\.md#([a-z0-9-]+)") -# A section of a design tree, cited as GitHub anchors its heading. -DESIGN_SECTION = re.compile(r"docs/((?:ir|emitters)/[A-Za-z0-9_/-]+\.md)#([A-Za-z0-9_-]+)") -# A design tree's name from when it was a single page, which names nothing now. -RETIRED = re.compile(r"(?:ir|emitter)-design") -HEADING = re.compile(r"#{1,6} +(.+)") # A fenced block's opening or closing run, as CommonMark reads one: three or more backticks or # tildes, indented by at most three spaces, then the info string. FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$") @@ -101,15 +94,15 @@ # doubled. DOUBLE_QUOTED = re.compile(r'"((?:[^"\\]|\\.)*)"(?:[ \t]+#.*)?') SINGLE_QUOTED = re.compile(r"'((?:[^']|'')*)'(?:[ \t]+#.*)?") -TEST_DECL = re.compile(r"^func (Test[A-Za-z0-9_]*)\(", re.M) # What follows the colon of a suffix a path may carry: a line, a line and column, or a range. LINE = r"[0-9]+(?::[0-9]+|-[0-9]+)?$" LINE_SUFFIX = re.compile(":" + LINE) # A code span holding a "/" names a repository path unless its form marks it as something else: # a JSON pointer or device (/), a flag (-), a pattern (+, [, |, ^ or \), a shell variable's value -# ($), a placeholder (, {owner}), or a colon before anything but a line suffix, as a URL, a -# refspec (main:refs/x) and a pathspec's magic (:/, :(top)) hold, which no path here does. -NOT_A_PATH = re.compile(r"^(?:/|-|\+|\$)|:(?!" + LINE + r")|[\[<>{}|^\\]") +# ($), a placeholder (, {owner}), a formula or call (a parenthesis inside it, which no tracked +# path holds), or a colon before anything but a line suffix, as a URL, a refspec (main:refs/x) and a +# pathspec's magic (:/, :(top)) hold, which no path here does. +NOT_A_PATH = re.compile(r"^(?:/|-|\+|\$)|:(?!" + LINE + r")|[\[<>{}|^\\()]") # The first segments of what a span names outside the tree. Any other first segment is held to # the tree, then to the Go toolchain's sources, so a misspelt or renamed directory is reported # rather than passed. @@ -119,14 +112,20 @@ "go": "a Go package", "golang.org": "a Go module", "runtime": "a Go package", - "openapi": "a diagnostic code", "refs": "a git ref", "repos": "a GitHub REST API path", } -# A diagnostic code under ir/ or pass/, such as ir/duplicate-property-id: lowercase words joined by -# hyphens. No directory there holds a hyphen, so the shape names no path, and, as with an openapi/ -# code, the code itself is not looked up: an invented code in that shape passes (#2296). -DIAGNOSTIC_CODE = re.compile(r"(?:ir|pass)/[a-z0-9]+(?:-[a-z0-9]+)+") +# How a Go file builds a diagnostic code: a string literal holding a prefix, a slash and lowercase +# words joined by hyphens, such as "openapi/validation"; a family, a literal head, one expression +# and a literal tail on one line, as "ir/duplicate-" + noun + "-id"; a name bound to a literal +# ending its line; and a name joined to more words by a "/", as diag.Validation + "/" + class. A +# name starts at a word boundary, so the tail of a longer identifier is none. A media type or an +# import path is a literal too, which lets a span naming one pass. +CODE_WORDS = "[a-z0-9]+(?:-[a-z0-9]+)*" +CODE_LITERAL = re.compile(f'"([a-z0-9]+/{CODE_WORDS})"') +CODE_FAMILY = re.compile(r'"([a-z0-9]+/[a-z0-9-]*)" *\+[^"+\n]+\+ *"([a-z0-9-]+)"') +CODE_NAME = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*) *= *" + CODE_LITERAL.pattern + " *$", re.M) +CODE_JOIN = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]*) *\+ *"/" *\+') # A file named without its directory, such as `sweep.py`; a suffix such as `_test.go` is none. BARE_FILE = re.compile(r"[A-Za-z0-9][\w.-]*\.(go|md|py|yaml|yml|json|txt)") # A path below the toolchain's src, as path_word leaves one, with GO_ENV_GOROOT folded into $GOROOT @@ -149,22 +148,32 @@ def listing(root: Path, *args: str) -> list[str]: return [f for f in git(root, "ls-files", "-z", *args).split("\0") if f] -def load_tree(root: Path) -> tuple[set[str], set[str], set[str]]: - """Return the first segment of every tracked path, every declared Go test name with each - family prefix of it, as TestA_B declares TestA, and the path of every file the tree holds: - each one git lists, untracked ones included and ignored ones not, that is on disk. A test is - read from any of those files, so a skill can name one before its file is staged.""" +def load_tree(root: Path) -> tuple[set[str], set[str]]: + """Return the first segment of every tracked path and the path of every file the tree holds: + each one git lists, untracked ones included and ignored ones not, that is on disk.""" top_level = {".claude"} | {f.split("/", 1)[0] for f in listing(root)} listed = listing(root, "--cached", "--others", "--exclude-standard") - known, tests = {f for f in listed if (root / f).is_file()}, set() + return top_level, {f for f in listed if (root / f).is_file()} + + +def declared_codes(root: Path, known: set[str]) -> re.Pattern[str]: + """Return what matches each diagnostic code the module at root builds in the files of known, + untracked ones included, so a skill can name a code before its file is staged: each + CODE_LITERAL, each CODE_FAMILY with words for its expression, and each code a CODE_JOIN builds + below a literal its name is bound to.""" + forms, bound, joined = set(), set(), set() for f in known: - if f.endswith("_test.go"): - for name in TEST_DECL.findall((root / f).read_text(errors="replace")): - parts = name.split("_") - tests.update("_".join(parts[:i]) for i in range(1, len(parts) + 1)) - if not tests: - raise RuntimeError("found no declared test, so a test name cannot be checked") - return top_level, tests, known + # The Go files that build the module, which leave out tests and testdata fixtures. + if not f.endswith(".go") or f.endswith("_test.go") or "testdata" in f.split("/"): + continue + source = (root / f).read_text(errors="replace") + forms.update(map(re.escape, CODE_LITERAL.findall(source))) + forms.update(re.escape(head) + CODE_WORDS + re.escape(tail) + for head, tail in CODE_FAMILY.findall(source)) + bound.update(CODE_NAME.findall(source)) + joined.update(CODE_JOIN.findall(source)) + forms.update(re.escape(code + "/") + CODE_WORDS for name, code in bound if name in joined) + return re.compile("|".join(sorted(forms)) or "(?!)") def go_sources(root: Path) -> Path | None: @@ -200,6 +209,14 @@ def declares(source: str, name: str) -> bool: return any(re.search(rf"^\t{n}\b", body, re.M) for body in GO_BLOCK.findall(source)) +def starting_on(pattern: re.Pattern[str], line: str, following: str) -> Iterator[re.Match[str]]: + """Return each match of pattern that starts on line, read on into following, the next line, + as a Go name placed in a file and a section citation wrap at their spaces. A match starting on + following is that line's to report.""" + joined = line + " " + following.lstrip() + return itertools.takewhile(lambda m: m.start() < len(line), pattern.finditer(joined)) + + def cites_alone(key: str) -> str: """Say that a span or prose cites a rule by its #key alone, naming no file to hold it to.""" return f"cites {key} by its key alone: cite references/.md{key}" @@ -250,9 +267,11 @@ def rule_bullets(block: list[str]) -> tuple[list[list[str]], list[int]]: class Linter: - def __init__(self, root: Path, top_level: set[str], tests: set[str], known: set[str], - files: list[Path], toolchain: Path): - self.root, self.top_level, self.tests, self.files = root, top_level, tests, files + def __init__(self, root: Path, top_level: set[str], known: set[str], files: list[Path], + toolchain: Path): + self.root, self.top_level, self.files = root, top_level, files + # What matches the diagnostic codes the module builds, which a span names, not a path. + self.codes = declared_codes(root, known) # The Go toolchain's src, which a path the tree lacks may name. self.toolchain = toolchain # The tree a clone holds, as load_tree lists it, with each directory above a file: a path @@ -420,9 +439,10 @@ def check_split_spans(self, f: Path) -> None: inside = not inside def check_names(self, d: Path, f: Path) -> None: - """Hold every path, link, skill, test, Go name, section, keyed entry and rule a file names - to the tree, and record each bare span that may be a rule key, which run judges once every - key is known.""" + """Hold every path, skill, Go name, section and rule a file names to the tree, and record + each bare span that may be a rule key, which run judges once every key is known. Links, + headings and test names are internal/archtest's to hold, and a keyed entry is held by the + test that reads its document through internal/keydoc.""" text = f.read_text() named = {m.end() - 1 for m in NAMED_SECTION.finditer(text)} for m in re.finditer("§", text): @@ -449,43 +469,25 @@ def check_names(self, d: Path, f: Path) -> None: self.report(f, i, why) # Prose joins words with a slash (I/O, kept/dropped), so a path there is held only # when its first segment is a tracked entry; one in a span is held whatever it starts - # with. Inline code spans are checked above, so prose and markdown links skip them. - unspanned = ANY_SPAN.sub("", line) - prose = LINK_TARGET.sub("]", unspanned) + # with. Prose leaves out the spans checked above and each link's target, which + # internal/archtest holds. + prose = LINK_TARGET.sub("]", ANY_SPAN.sub("", line)) for p in PROSE_PATH.findall(prose): p = p.rstrip(".,;:)") if self.first_is_tracked(p) and (why := self.missing(d, p)): self.report(f, i, why) for key in PROSE_CITE.findall(prose) if i > prose_from else (): self.report(f, i, cites_alone(key)) - for target in LINK.findall(unspanned): - if target.startswith(("http", "mailto:")): - continue - if why := self.absent(target, os.path.relpath(f.parent / target, self.root)): - self.report(f, i, f"link target {why}") - for name in TEST.findall(line): - if name not in self.tests: - self.report(f, i, f"no test named {name}") - for name, path in NAME_IN_FILE.findall(line): + following = lines[i] if i < len(lines) else "" + for m in starting_on(NAME_IN_FILE, line, following): + name, path = m.groups() held = self.root / path if held.is_file() and not declares(held.read_text(errors="replace"), name): self.report(f, i, f"{path} declares no {name}") - # A section citation wraps at its spaces, so read on into the next line. - joined = line + " " + (lines[i].lstrip() if i < len(lines) else "") - for m in SECTION.finditer(joined): - if m.start() >= len(line): - break # it starts on the next line, which reports it + for m in starting_on(SECTION, line, following): doc, num = m.groups() if not self.has(doc, r"^#{2,6} +" + re.escape(num) + r"([. ]|$)"): self.report(f, i, f"docs/{doc}.md has no section {num}") - for doc, key in KEY.findall(line): - if not self.has(doc, "^### `" + re.escape(key) + "`"): - self.report(f, i, f"docs/{doc}.md has no entry {key}") - for doc, anchor in DESIGN_SECTION.findall(line): - if anchor not in self.design_anchors(doc): - self.report(f, i, f"docs/{doc} has no heading {anchor}") - if RETIRED.search(line): - self.report(f, i, "names a retired page: cite a document of docs/ir or docs/emitters") def check_span(self, d: Path, f: Path, line: int, tok: str) -> None: shown, tok = tok, path_word(tok) @@ -512,10 +514,10 @@ def missing(self, d: Path, p: str, shown: str = "") -> str | None: skill for its own references/ and scripts/, then to the repository, which holds a scripts/ of its own, giving the skill's reason when neither holds it, and to the repository otherwise. A path is held up to a #entry, a line suffix or its first wildcard, and ./... - names the module's packages. A diagnostic code's shape under ir/ or pass/ is None too, as is - a path the tree lacks that names the Go toolchain's sources. The reason names shown, the - path as a span wrote it, where p has been read out of that spelling.""" - if DIAGNOSTIC_CODE.fullmatch(p): + names the module's packages. A code the module builds is None too, as is a path the tree + lacks that names the Go toolchain's sources. The reason names shown, the path as a span + wrote it, where p has been read out of that spelling.""" + if self.codes.fullmatch(p): return None rel = LINE_SUFFIX.sub("", p.removeprefix("./").split("#", 1)[0]).split("*", 1)[0] rel = "" if rel == "..." else rel.removesuffix("/...").rstrip("/") @@ -570,18 +572,6 @@ def absent(self, shown: str, rel: str) -> str | None: return f"{shown} is ignored by git, so no clone holds it" return f"{shown} does not exist" - def design_anchors(self, doc: str) -> set[str]: - """Return the anchors GitHub gives the headings of a design document, outside its code - fences, as internal/archtest reads them too.""" - path = self.root / "docs" / doc - found, fenced = set(), False - for line in path.read_text().splitlines() if path.is_file() else (): - fenced ^= line.startswith("```") - heading = HEADING.fullmatch(line) - if heading and not fenced: - found.add(re.sub(r"[^\w\- ]", "", heading[1].lower()).replace(" ", "-")) - return found - def has(self, doc: str, pattern: str) -> bool: path = self.root / "docs" / f"{doc}.md" return path.is_file() and re.search(pattern, path.read_text(), re.M) is not None @@ -644,13 +634,13 @@ def findings(root: Path) -> tuple[int, list[str]]: skills = root / ".claude" / "skills" if not skills.is_dir() or not any(d.is_dir() for d in skills.iterdir()): raise RuntimeError(f"found no skill under {skills}, so nothing was checked") - top_level, tests, known = load_tree(root) + top_level, known = load_tree(root) toolchain = go_sources(root) if toolchain is None: raise RuntimeError( "cannot locate the Go toolchain's sources; standard-library paths not checked") files = [root / f for f in sorted(known) if f.startswith(".claude/skills/")] - lint = Linter(root, top_level, tests, known, files, toolchain) + lint = Linter(root, top_level, known, files, toolchain) return lint.run(), lint.findings diff --git a/.claude/skills/morphic-curating-skills/scripts/test_skills_lint.py b/.claude/skills/morphic-curating-skills/scripts/test_skills_lint.py index e6c32517b..4b796d764 100644 --- a/.claude/skills/morphic-curating-skills/scripts/test_skills_lint.py +++ b/.claude/skills/morphic-curating-skills/scripts/test_skills_lint.py @@ -26,7 +26,7 @@ description: Use when testing. --- -See `references/r.md`, `scripts/tool.py`, `ir/a.go`, ir/a.go, TestKnown, TestKnown_Case, +See `references/r.md`, `scripts/tool.py`, `ir/a.go`, ir/a.go, architecture §4.3, docs/parser-library.md#known, `morphic-harness` and [a link](references/r.md). Run `go test ./ir/... $(python3.14 scripts/tool.py)` or `go run ./cmd/morphic-harness ` and `gh api repos/{owner}/{repo}`, by `references/r.md#do-the-thing` and @@ -35,7 +35,7 @@ Hold `docs/parser-library.md#known`, `docs/ir/models.md#the-flattening`, `ir/a.go:1` and `ir/*.go` up to the entry, line or glob. Links to [a site](https://example.com/a/b) and [mail](mailto:x@example.com) leave the tree. """ -RULE = ("## Do the thing\n`do-the-thing`\n\n- **Rule.** Do it, as `ir/a.go` and TestKnown do.\n" +RULE = ("## Do the thing\n`do-the-thing`\n\n- **Rule.** Do it, as `ir/a.go` does.\n" "- **Why.** It broke\n once (#1).\n- **Probe.** architecture §4.3.\n") GOOD_REFERENCE = "# R\n\nWhat these rules are about.\n\n" + RULE @@ -56,10 +56,9 @@ def script(root: Path, rel: str, text: str) -> Path: def fixture(root: Path) -> None: """Write a tree holding one clean skill and everything it names.""" - write(root, "docs/parser-library.md", "### `known`\n") + write(root, "docs/parser-library.md", "") write(root, "docs/architecture.md", "## 4. Types\n\n### 4.3 Unions\n") - write(root, "docs/ir/models.md", "# Models\n\n```\n# not a heading\n```\n\n## The flattening\n") - write(root, "docs/ir/README.md", "# IR\n\n## Design rules\n\n## snake_case names\n") + write(root, "docs/ir/models.md", "") write(root, "ir/a.go", "package ir\n") write(root, "cmd/morphic-harness/main.go", "package main\n") skill = ".claude/skills/good-skill/" @@ -87,9 +86,8 @@ def tearDown(self): def lint(self, toolchain: Path | None = None): files = [p for p in (self.root / ".claude" / "skills").rglob("*") if p.is_file()] top_level = {"docs", "ir", "pass", "cmd", "internal", ".claude"} - tests = {"TestKnown", "TestKnown_Case"} on_disk = {p.relative_to(self.root).as_posix() for p in self.root.rglob("*") if p.is_file()} - lint = skills_lint.Linter(self.root, top_level, tests, on_disk - self.ignored, files, + lint = skills_lint.Linter(self.root, top_level, on_disk - self.ignored, files, self.toolchain if toolchain is None else toolchain) return lint.run(), lint.findings @@ -108,9 +106,8 @@ def test_a_skill_without_its_file_or_whole_frontmatter_is_reported(self): def test_each_planted_problem_is_reported(self): skill = ".claude/skills/Bad_Skill/" front = "---\nname: other\ndescription: For tests.\n---\n\n" - body = ("Bad `ir/nope.go`, prose ir/gone.go, TestMissing, architecture §99.1," - " parser-library.md#nope,\n" - "`morphic-nope`, [x](references/none.md), /U" "sers/someone.\n" + body = ("Bad `ir/nope.go`, prose ir/gone.go, architecture §99.1,\n" + "`morphic-nope`, /U" "sers/someone.\n" "Run `python3 scripts/gone.py --flag` and `go test ./ir/nope/...`, by `no-rule`.\n" "Cite `do-the-thing`, `references/r.md#gone` and " "`.claude/skills/good-skill/references/r.md#gone`, and `gone.py` alone.\n") @@ -126,16 +123,13 @@ def test_each_planted_problem_is_reported(self): "single hyphens", f"{bad}SKILL.md:1: frontmatter name must be 'Bad_Skill'", f'{bad}SKILL.md:1: description must start "Use when"', - f"{bad}SKILL.md: body is 530 words, over 500", + f"{bad}SKILL.md: body is 527 words, over 500", f"{bad}references/orphan.md: 4001 words, over 4000", f"{bad}references/orphan.md: not named in {bad}SKILL.md", f"{bad}SKILL.md:7: ir/nope.go does not exist", f"{bad}SKILL.md:7: ir/gone.go does not exist", - f"{bad}SKILL.md:7: no test named TestMissing", f"{bad}SKILL.md:7: docs/architecture.md has no section 99.1", - f"{bad}SKILL.md:7: docs/parser-library.md has no entry nope", f"{bad}SKILL.md:8: no skill or command named morphic-nope", - f"{bad}SKILL.md:8: link target references/none.md does not exist", f"{bad}scripts/new.py: has no test_new.py beside it", f"{bad}scripts/new.py: not named in {bad}SKILL.md", f'{bad}scripts/new.py: declares no `requires-python = ">=3.14"` script block', @@ -188,7 +182,7 @@ def test_a_span_path_is_held_whatever_its_first_segment(self): # Each span below names no repository path, by its form or by its first segment. elsewhere = ("`/components/schemas`, `-o=/dev/null`, `:(exclude)*/x.go`, `+(a/b)`, " "`[[:alnum:]]/x`, `http://h/x`, `/`, `origin/main`, " - "`go/types`, `runtime/metrics`, `golang.org/x/exp`, `openapi/cyclic-ref`, " + "`go/types`, `runtime/metrics`, `golang.org/x/exp`, " "`.git/info/exclude`, `_test.go`, `./...`.\n") # A misspelt or renamed first segment is held in a span and in a command, never in # prose, where words join with a slash. @@ -198,17 +192,6 @@ def test_a_span_path_is_held_whatever_its_first_segment(self): want = [f"{skill}:{n}: {p} does not exist" for p in ("gone/a.go", "./gone/b", "./gone/...")] self.assertEqual(sorted(self.lint()[1]), sorted(want)) - def test_a_markdown_link_inside_inline_code_is_not_checked(self): - skill = ".claude/skills/good-skill/SKILL.md" - line = (r"Run `git grep -nE '[(*\[ ]()[\[(,)]' -- docs` and see " - "[`ir/a.go`](references/r.md), [`code`](references/missing.md) and " - "[broken](references/none.md).\n") - write(self.root, skill, GOOD_SKILL + line) - n = GOOD_SKILL.count("\n") + 1 - want = [f"{skill}:{n}: link target references/missing.md does not exist", - f"{skill}:{n}: link target references/none.md does not exist"] - self.assertEqual(sorted(self.lint()[1]), sorted(want)) - def test_a_github_api_repos_path_in_a_span_is_not_a_tree_path(self): skill = ".claude/skills/good-skill/SKILL.md" line = ("Run `gh api 'repos/dexpace/morphic/issues?state=all&per_page=1'` and " @@ -217,22 +200,39 @@ def test_a_github_api_repos_path_in_a_span_is_not_a_tree_path(self): n = GOOD_SKILL.count("\n") + 1 self.assertEqual(self.lint()[1], [f"{skill}:{n}: gone/a.go does not exist"]) - def test_a_span_shaped_as_an_ir_or_pass_code_names_no_path(self): + def test_a_span_naming_a_declared_code_names_no_path(self): skill = ".claude/skills/good-skill/SKILL.md" - # ir and pass are tracked, as in the repository, and no Go file declares any code here. - write(self.root, "ir/a.go", "package ir\n") - write(self.root, "pass/p.go", "package pass\n") + # A code is declared by a literal in a Go file the module builds, never in a test, a + # testdata fixture or a file of another kind, and only in a code's shape: a literal with a + # capital or a second slash declares none. ir and pass are tracked, as in the repository. + write(self.root, "ir/codes.go", 'package ir\n\nconst (\n' + '\tauth = "ir/unresolved-auth-space"\n\tdup = "ir/duplicate-property-id"\n' + '\tstep = "ir/2-step"\n\tcapital = "ir/Bad-Code"\n\tdeep = "ir/no/such-code"\n)\n') + write(self.root, "pass/p.go", 'package pass\n\nvar code = "pass/example-outside-type"\n') + write(self.root, "engine/e.go", + 'package engine\n\nconst c = "engine/unrecognized-format"\n') + write(self.root, "compilers/compile/c.go", + 'package compile\n\nconst c = "compile/registry-refused"\n') + write(self.root, "compilers/openapi/d.go", + 'package openapi\n\nconst c = "openapi/cyclic-ref"\n') + write(self.root, "ir/codes_test.go", 'package ir\n\nconst c = "ir/test-only-code"\n') + write(self.root, "ir/testdata/f.go", 'package f\n\nconst c = "ir/fixture-code"\n') + write(self.root, "ir/codes.md", 'Retired: "ir/document-only-code".\n') good = ("Codes `ir/unresolved-auth-space`, `ir/duplicate-property-id`, " - "`pass/example-outside-type`, `ir/2-step`,\n" + "`pass/example-outside-type`, `ir/2-step`, `compile/registry-refused`,\n" + "`engine/unrecognized-format`, `openapi/cyclic-ref`,\n" "command `grep ir/unresolved-auth-space ir/a.go`, prose ir/unresolved-auth-space, " "pass/example-outside-type.\n") bad = ("Not codes: `ir/duplicate-`, `ir/nosuchpkg`, `ir/Bad-Code`, `ir/no-such/a.go`, " "`ir/no/such-code`,\n" - "decorated `./ir/unresolved-auth-space`, `ir/unresolved-auth-space:1`, " - "[x](ir/unresolved-auth-space),\n" - "missing `ir/nope.go`, `pass/gone.go` and prose pass/nope.go.\n") + "decorated `./ir/unresolved-auth-space` and `ir/unresolved-auth-space:1`,\n" + "missing `ir/nope.go`, `pass/gone.go`, `compile/gone.go`, `engine/gone.go`, " + "`openapi/gone.go` and prose pass/nope.go,\n" + "undeclared `ir/bogus-code`, `compile/registry-refusd`, `openapi/no-such-code`, " + "`ir/test-only-code`, `ir/fixture-code`, `ir/document-only-code`, command " + "`grep pass/bogus-code ir/a.go` and prose ir/bogus-code.\n") write(self.root, skill, GOOD_SKILL + good + bad) - n = GOOD_SKILL.count("\n") + 3 + n = GOOD_SKILL.count("\n") + 4 want = [ f"{skill}:{n}: ir/duplicate- does not exist", f"{skill}:{n}: ir/nosuchpkg does not exist", @@ -241,17 +241,68 @@ def test_a_span_shaped_as_an_ir_or_pass_code_names_no_path(self): f"{skill}:{n}: ir/no/such-code does not exist", f"{skill}:{n + 1}: ./ir/unresolved-auth-space does not exist", f"{skill}:{n + 1}: ir/unresolved-auth-space:1 does not exist", - f"{skill}:{n + 1}: link target ir/unresolved-auth-space does not exist", f"{skill}:{n + 2}: ir/nope.go does not exist", f"{skill}:{n + 2}: pass/gone.go does not exist", + f"{skill}:{n + 2}: compile/gone.go does not exist", + f"{skill}:{n + 2}: engine/gone.go does not exist", + f"{skill}:{n + 2}: openapi/gone.go does not exist", f"{skill}:{n + 2}: pass/nope.go does not exist", + f"{skill}:{n + 3}: ir/bogus-code does not exist", + f"{skill}:{n + 3}: compile/registry-refusd does not exist", + f"{skill}:{n + 3}: openapi/no-such-code does not exist", + f"{skill}:{n + 3}: ir/test-only-code does not exist", + f"{skill}:{n + 3}: ir/fixture-code does not exist", + f"{skill}:{n + 3}: ir/document-only-code does not exist", + f"{skill}:{n + 3}: pass/bogus-code does not exist", + f"{skill}:{n + 3}: ir/bogus-code does not exist", ] self.assertEqual(sorted(self.lint()[1]), sorted(want)) + def test_a_code_built_from_parts_names_no_path(self): + skill = ".claude/skills/good-skill/SKILL.md" + # A family is a literal head, one expression and a literal tail on one line, read where a + # binding heads it too; a join adds words below a code a name is bound to, and a name never + # joined, bound to nothing or bound to more than a literal builds nothing. A name is read + # whole, never as the tail of a longer identifier. A family is read with or without spaces + # around its plus signs, as pass/validate_refs.go writes one without. + write(self.root, "ir/irverify/dup.go", 'package irverify\n\nfunc code(c Class) string {\n' + '\treturn "ir/duplicate-" + ir.RefNoun(c) + "-id"\n}\n') + write(self.root, "ir/irverify/head.go", + 'package irverify\n\nvar head = "ir/a-b" + noun + "-c"\n' + 'var tight = "pass/t-"+noun+"-u"\n') + write(self.root, "compilers/openapi/diag.go", 'package diag\n\nconst (\n' + '\tValidation = "openapi/validation"\n\tBound = "pass/bound-code"\n' + '\tdéjàValidation = "pass/stale"\n)\n') + write(self.root, "compilers/openapi/rules.go", 'package specrules\n\n' + 'var keyed = "pass/keyed" + suffix\n\n' + 'func add(class string) string { return diag.Validation+"/"+class }\n' + 'func other(key, rest string) string { return key + "/" + rest }\n' + 'func more(rest string) string { return keyed + "/" + rest }\n' + 'func stale(rest string) string { return déjàBound + "/" + rest }\n' + 'func split(noun string) (string, string) {\n\thead := "ir/split" + noun\n' + '\ttail := noun + "-c"\n\treturn head, tail\n}\n') + good = ("Codes `ir/duplicate-property-id`, `ir/duplicate-enummember-id`, `ir/a-bx-c`, " + "`ir/a-b`,\n`openapi/validation`, `openapi/validation/validation-type-mismatch`, " + "`pass/t-x-u` and `pass/bound-code`.\n") + bad = ("Not codes: `ir/duplicate-property`, `ir/duplicate-id`, `openapi/validation/`,\n" + "`openapi/validation/Bad`, `pass/bound-code/extra` and `pass/key-x`,\n" + "`pass/keyed/more`, `pass/stale/x` and `ir/splitx-c`.\n") + write(self.root, skill, GOOD_SKILL + good + bad) + n = GOOD_SKILL.count("\n") + 3 + want = [f"{skill}:{n}: {code} does not exist" + for code in ("ir/duplicate-property", "ir/duplicate-id", "openapi/validation/")] + want += [f"{skill}:{n + 1}: {code} does not exist" + for code in ("openapi/validation/Bad", "pass/bound-code/extra", "pass/key-x")] + want += [f"{skill}:{n + 2}: {code} does not exist" + for code in ("pass/keyed/more", "pass/stale/x", "ir/splitx-c")] + self.assertEqual(sorted(self.lint()[1]), sorted(want)) + def test_a_pattern_or_a_ref_in_a_span_names_no_path(self): skill = ".claude/skills/good-skill/SKILL.md" - # Each holds a "/" in a form no repository path takes: a pattern, a ref or a refspec. + # Each holds a "/" in a form no repository path takes: a pattern, a ref, a refspec or a + # formula. spans = ("`grep -E 'testify|go-cmp|golang.org/x/tools'`, `sed 's/^a/b/'`, " + "`2 + 2/(log2(n) + 2)`, " "`grep 'a\\/b'`, `refs/remotes/origin/main`, " "`git fetch main:refs/remotes/origin/main`, " "`git restore --worktree :/`, `git grep -n x -- :(top)gone/d.go`, " @@ -367,7 +418,8 @@ def test_a_go_name_placed_in_a_file_is_held_to_its_declarations(self): "`ir/b.go` and `Lost` in `ir/gone.go`.\n" "`Called` in `ir/b.go`, `Local` in `ir/b.go`, `Inside` in `ir/b.go`, `Later` in " "`ir/b.go` and `Fiel` in `ir/b.go`.\n") - write(self.root, skill, GOOD_SKILL + named + also + lost) + wrapped = "A wrapped `Free` in\n `ir/b.go` passes, and `Wrapt` in\n `ir/b.go` does not.\n" + write(self.root, skill, GOOD_SKILL + named + also + lost + wrapped) n = GOOD_SKILL.count("\n") + 4 want = [f"{skill}:{n}: ir/b.go declares no Mentioned", f"{skill}:{n}: ir/b.go declares no Buried", @@ -378,7 +430,8 @@ def test_a_go_name_placed_in_a_file_is_held_to_its_declarations(self): f"{skill}:{n + 1}: ir/b.go declares no Local", f"{skill}:{n + 1}: ir/b.go declares no Inside", f"{skill}:{n + 1}: ir/b.go declares no Later", - f"{skill}:{n + 1}: ir/b.go declares no Fiel"] + f"{skill}:{n + 1}: ir/b.go declares no Fiel", + f"{skill}:{n + 3}: ir/b.go declares no Wrapt"] self.assertEqual(sorted(self.lint()[1]), sorted(want)) def test_a_path_git_ignores_is_held_as_no_clone_has_it(self): @@ -394,18 +447,16 @@ def test_a_path_git_ignores_is_held_as_no_clone_has_it(self): write(Path(self.dir.name), "outside.md", "x\n") write(self.root, skill, GOOD_SKILL + "Ignored: `docs/plan.md`, `go run ./cmd/morphic-local`, prose docs/plan.md, " - "[the plan](../../../docs/plan.md), `morphic-local`, " - "`references/local.md#local-rule`, `references/local.md`,\nand outside: [x](../../../../outside.md), " - "but `ir/./a.go` is in the tree.\n") + "`morphic-local`, `references/local.md#local-rule`, `references/local.md`,\n" + "and outside: `../outside.md`, but `ir/./a.go` is in the tree.\n") n = GOOD_SKILL.count("\n") + 1 lost = "is ignored by git, so no clone holds it" want = [f"{skill}:{n}: docs/plan.md {lost}", f"{skill}:{n}: ./cmd/morphic-local {lost}", f"{skill}:{n}: docs/plan.md {lost}", - f"{skill}:{n}: link target ../../../docs/plan.md {lost}", f"{skill}:{n}: no skill or command named morphic-local", f"{skill}:{n}: references/local.md {lost}", f"{skill}:{n}: references/local.md {lost}", - f"{skill}:{n + 1}: link target ../../../../outside.md does not exist"] + f"{skill}:{n + 1}: ../outside.md does not exist"] self.assertEqual(sorted(self.lint()[1]), sorted(want)) def test_a_code_span_broken_across_lines_is_reported_once(self): @@ -442,28 +493,14 @@ def test_a_section_naming_no_document_is_reported(self): want = f"{skill}:{n}: a § names no document: name it first, as in architecture §N" self.assertEqual(self.lint()[1], [want]) - def test_the_ir_design_is_cited_by_heading_and_not_by_number(self): + def test_a_design_citation_naming_no_file_or_a_bare_section_is_reported(self): skill = ".claude/skills/good-skill/SKILL.md" - write(self.root, skill, GOOD_SKILL + "See `docs/ir/models.md#the-flattening` and\n" - "`docs/ir/models.md#gone`, `docs/ir/models.md#not-a-heading`,\n" - "`docs/ir/gone.md#x`, and ir-design §4.3.\n") + write(self.root, skill, GOOD_SKILL + "See `docs/ir/gone.md#x` and models §4.3.\n") n = GOOD_SKILL.count("\n") + 1 - want = [f"{skill}:{n + 1}: docs/ir/models.md has no heading gone", - f"{skill}:{n + 1}: docs/ir/models.md has no heading not-a-heading", - f"{skill}:{n + 2}: a § names no document: name it first, as in architecture §N", - f"{skill}:{n + 2}: names a retired page: cite a document of docs/ir or docs/emitters", - f"{skill}:{n + 2}: docs/ir/gone.md#x does not exist", - f"{skill}:{n + 2}: docs/ir/gone.md has no heading x"] + want = [f"{skill}:{n}: a § names no document: name it first, as in architecture §N", + f"{skill}:{n}: docs/ir/gone.md#x does not exist"] self.assertEqual(sorted(self.lint()[1]), sorted(want)) - def test_a_design_citation_is_read_in_the_root_and_past_an_underscore(self): - skill = ".claude/skills/good-skill/SKILL.md" - write(self.root, skill, GOOD_SKILL + "See `docs/ir/README.md#design-rules`,\n" - "`docs/ir/README.md#snake_case-names`, and\n" - "`docs/ir/README.md#gone`.\n") - n = GOOD_SKILL.count("\n") + 1 - self.assertEqual(self.lint()[1], [f"{skill}:{n + 2}: docs/ir/README.md has no heading gone"]) - def test_a_scalar_is_read_as_yaml_reads_it(self): cases = {"Use when: plain": "Use when: plain", "'it''s'": "it's", '"a \\"b\\" \\\\c"': 'a "b" \\c', "''": "", "": "", @@ -690,37 +727,29 @@ def test_help_prints_the_usage_and_lints_nothing(self): class LoadTreeTest(unittest.TestCase): - def test_tests_top_level_entries_and_every_file_path_are_read(self): + def test_top_level_entries_and_every_file_path_are_read(self): with tempfile.TemporaryDirectory() as d: root = Path(d) env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"} git = ["git", "-C", d] subprocess.run(git + ["init", "-q"], check=True, env=env) - write(root, "ir/a_test.go", "package ir\n\nfunc TestA_B(t *testing.T) {}\n") - # A file go test does not compile declares no test, whatever a function is called. - write(root, "ir/a.go", "package ir\n\nfunc TestHelper(t testing.TB) {}\n") + write(root, "ir/a.go", "package ir\n") write(root, "ir/gone.go", "package ir\n") - write(root, "ir/gone_test.go", "package ir\n\nfunc TestGone(t *testing.T) {}\n") # Names git would quote and escape, as it does one holding a non-ASCII letter. - write(root, "données/b_test.go", "package d\n\nfunc TestB(t *testing.T) {}\n") + write(root, "données/b.go", "package d\n") write(root, ".gitignore", "out/\n") subprocess.run(git + ["add", "-A"], check=True, env=env) subprocess.run(git + ["commit", "-qm", "x"], check=True, env=env) write(root, "scripts/new.py", "") write(root, "notes/café.md", "") write(root, "out/built.txt", "") - # A test written beside the skill naming it, which is not staged yet, and a built one. - write(root, "ir/new_test.go", "package ir\n\nfunc TestNew_Case(t *testing.T) {}\n") - write(root, "out/built_test.go", "package o\n\nfunc TestBuilt(t *testing.T) {}\n") - # A tracked test file deleted mid-change, as before a git rm, declares nothing. - for gone in ("gone.go", "gone_test.go"): - (root / "ir" / gone).unlink() - top_level, tests, known = skills_lint.load_tree(root) + # A tracked file deleted mid-change, as before a git rm. + (root / "ir" / "gone.go").unlink() + top_level, known = skills_lint.load_tree(root) self.assertEqual(top_level, {".claude", ".gitignore", "ir", "données"}) - self.assertEqual(tests, {"TestA", "TestA_B", "TestB", "TestNew", "TestNew_Case"}) - self.assertEqual(known, {".gitignore", "ir/a.go", "ir/a_test.go", "données/b_test.go", - "ir/new_test.go", "scripts/new.py", "notes/café.md"}, + self.assertEqual(known, {".gitignore", "ir/a.go", "données/b.go", "scripts/new.py", + "notes/café.md"}, "untracked files count, and ignored or deleted ones do not") @@ -757,7 +786,6 @@ def test_a_run_lints_with_the_toolchain_go_names_at_the_root(self): with tempfile.TemporaryDirectory() as d: root = Path(d) / "repo" fixture(root) - write(root, "ir/a_test.go", "package ir\n\nfunc TestKnown_Case(t *testing.T) {}\n") skill = ".claude/skills/good-skill/SKILL.md" write(root, skill, GOOD_SKILL + "Read `internal/runtime/maps`.\n") subprocess.run(["git", "-C", str(root), "init", "-q"], check=True) @@ -782,7 +810,6 @@ def test_missing_go_stops_with_one_line_and_no_path_findings(self): with tempfile.TemporaryDirectory() as d: root = Path(d) / "repo" fixture(root) - write(root, "ir/a_test.go", "package ir\n\nfunc TestKnown_Case(t *testing.T) {}\n") skill = ".claude/skills/good-skill/SKILL.md" write(root, skill, GOOD_SKILL + "Read `encoding/json/v2` and `internal/runtime/maps`.\n") subprocess.run([git, "-C", str(root), "init", "-q"], check=True) @@ -819,9 +846,6 @@ def test_each_outcome_has_its_exit_status(self): fixture(root) subprocess.run(["git", "-C", str(root), "init", "-q"], check=True) subprocess.run(["git", "-C", str(root), "add", "-A"], check=True) - self.assertEqual(self.run_lint(root)[0], 2, "a tree declaring no test") - write(root, "ir/a_test.go", "package ir\n\nfunc TestKnown_Case(t *testing.T) {}\n") - subprocess.run(["git", "-C", str(root), "add", "-A"], check=True) code, out = self.run_lint(root) self.assertEqual((code, out), (0, "skills_lint: clean (1 skills)\n")) # Seen only in the skill files the lint lists from git, not by any rule check. diff --git a/.claude/skills/morphic-designing-code/SKILL.md b/.claude/skills/morphic-designing-code/SKILL.md index 6be4f198d..030b56f4b 100644 --- a/.claude/skills/morphic-designing-code/SKILL.md +++ b/.claude/skills/morphic-designing-code/SKILL.md @@ -34,7 +34,7 @@ Each row names a rule and code to copy. | a call into code the package does not own | `references/design-rules.md#catch-reaches-one-goroutine` | `taggedMappingRefusal` in `compilers/openapi/internal/load/load.go` | | a shape a caller or another consumer will use | `.claude/skills/morphic-changing-the-ir/references/ir-lessons.md#measure-the-premise` | `Deprecation` in `ir/docs.go` | | a flattened member's reader | `.claude/skills/morphic-changing-the-ir/references/ir-lessons.md#flattened-member-declarations` | `member` in `compilers/openapi/internal/schema/tagreadings.go` | -| a rule or decision another package or phase already makes | `references/design-rules.md#decide-once` | `Inferred` in `ir/inferred.go` | +| a rule or decision another package or phase already makes | `references/deciding-once.md#decide-once` | `Inferred` in `ir/inferred.go` | | a reading the parser library already makes | `.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md#reuse-library-readings` | `Pointer` in `compilers/openapi/internal/fragment/fragment.go` | | a helper or algorithm another site may hold | `references/design-rules.md#share-only-what-means-the-same`, `references/design-rules.md#fallback-suits-the-decision` | `hoistScalar` in `compilers/openapi/internal/schema/scalar.go` | | code that needs no morphic concept | `references/design-rules.md#domain-free-code-lives-apart` | `Catch` in `barrier/barrier.go` | @@ -43,9 +43,12 @@ Each row names a rule and code to copy. ## Already checked -Leave function caps, `modernize`, layering, method caps, reachability and `callShapeBaseline` to -`.golangci.yml` and `internal/archtest`, and cost claims to `morphic-measuring-performance`. +Leave function caps, `modernize`, layering, method caps' receivers (functions: +`references/design-rules.md#function-over-a-type-is-its-method`), reachability and +`callShapeBaseline` to `.golangci.yml` and `internal/archtest`, and cost claims to +`morphic-measuring-performance`. ## References -- `references/design-rules.md`: the rules the table names, with their costs. +- `references/design-rules.md` and `references/deciding-once.md`: the table's rules, and folding + declarations, with their costs. diff --git a/.claude/skills/morphic-designing-code/references/deciding-once.md b/.claude/skills/morphic-designing-code/references/deciding-once.md new file mode 100644 index 000000000..10523dfc6 --- /dev/null +++ b/.claude/skills/morphic-designing-code/references/deciding-once.md @@ -0,0 +1,108 @@ +# Deciding once + +Where a fact is decided, once and by one implementation, what a remembered reading's key holds, +and how several declarations of one thing fold into it. +`references/design-rules.md` holds the other design rules. + +## Decide a fact once, or ask the code that decides +`decide-once` + +- **Rule.** Decide a fact one phase sets and another reports or acts on once, recording it on the + value read later or asking the deciding code; a phase that cannot says why in a comment. Call + library readings (`.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md#reuse-library-readings`, + `.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md#override-a-library-misreading`); + a mirror stays only where no library call answers, held by a differential + (`.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md#mirror-library-read-rules-exactly`, + `.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md#acyclic-trees`). +- **Why.** In `compilers/openapi/internal/schema`, `disjoint` parted from `disjointAtoms` (#2077); + `declaresPositionScoped` drifted thrice (#138, #1053, #2009); #1016 and #2132 deleted copies + (#2280). +- **Probe.** Find each predicate behind a message or later phase (`git grep -n`) and compile a grid + over kinds, value sets and formats (#2077's `EnumEnum`/`ConstConst`/`StrEnum`). + +## Implement a specification rule once across all spellings +`one-rule-one-implementation` + +- **Rule.** A lowering rule the specification states once for every place it can be written is + implemented once, each spelling reaching it. An implementation per spelling leaves mixed spellings + to none of them. +- **Why.** Separate `oneOf`/`anyOf` lowerings for standalone schemas, beside `allOf` and on `allOf` + entries left a `oneOf` beside an `allOf` whose partner sat on an entry to fall between them + (#2110, #2129). +- **Probe.** Write the mixed spelling (a `oneOf` beside an `allOf` whose partner sits on an entry) + and compile it beside each pure spelling. + +## Fold several declarations of one thing from the whole set +`fold-the-whole-set` + +- **Rule.** A merge of several declarations of one thing chooses from all of them at once, never + folding each into what the ones before it left (where it cannot, it folds in steps by + `references/deciding-once.md#stage-a-stepwise-fold`); refuses values the result cannot admit + before any first-wins tiebreak; reports every drop; and bounds any pairwise judgement it makes. + Sweep it with three declarations in all six orders, as pairs cannot show a chain's order + dependence. +- **Why.** #1000's allOf merge first folded a field's declarations as a chain, so + `int32, uint32, uint16` reported an overlap and kept `uint32` verbatim while + `uint16, int32, uint32` reported nothing; a 741-pair sweep was clean, and only triples showed it + (#1000). +- **Probe.** The triple sweep in every order gives each result and report alike, up to the ties + the merge reports. + +## Stage a stepwise fold's nodes and register them once +`stage-a-stepwise-fold` + +- **Rule.** Where a fold cannot choose from the whole set at once + (`references/deciding-once.md#fold-the-whole-set`) and runs in steps, each making a node at an ID + the type registry holds once, hold each step's node in a working set keyed by that ID, read that + set before the registry at every later step, and register once after the last step, so only the + final node is registered and one no later step keeps never is. +- **Why.** A ring of three models each redeclaring `id` as another enum, folded pairwise with each + step registered, ended in `compile/registry-refused` and kept the first fold's `b, c, d` where all + three meet at `c, d` (#2370). +- **Probe.** `references/deciding-once.md#fold-the-whole-set`'s triple sweep compiles with no + `compile/registry-refused` and to one registry; with a plant registering each step's node, it + reports that code. + +## Key a remembered reading on everything it reads that can vary +`remembered-reading-keys-what-it-reads` + +- **Rule.** A remembered reading's key (`ReadOncePerRun` in + `compilers/openapi/internal/lowering/lowering.go`) holds everything the reading reads that can + differ between callers: the context's document, through it its dialect, and what a function or + interface it is handed answers by (`references/deciding-once.md#handed-in-answers-join-the-key`). + `admissionsIn` in `compilers/openapi/internal/schema/admission.go` keys admissions by the asking + dialect. +- **Why.** #1996 keyed an `allOf` decision by schema alone while reading `c.SchemaRules()`, leaking + the first caller's dialect across documents (#2093). +- **Probe.** List what the reading and its callees read off the context + (`references/deciding-once.md#context-reads-listed-by-type`); each that can differ between + callers sits in the key. + +## Key a remembered reading on what a function or interface it is handed answers by +`handed-in-answers-join-the-key` + +- **Rule.** A function or interface a remembered reading is handed, as the receiver or a parameter + of the caller of `ReadOncePerRun` or a field of one, is read too: the key holds what its answers + vary by, or it answers alike for every caller, listed by type + (`.claude/skills/morphic-verifying-changes/references/sweep-every-site.md#sweep-a-typed-mechanism-by-type`). +- **Why.** `merge` reads through a handed-in `FieldDeclarationContext` answering per asking + document, which no context read shows (#2319). +- **Probe.** `go run golang.org/x/tools/cmd/callgraph -algo cha -format '{{define "v"}}{{.Name}}{{$u:=.Type.Underlying}}{{if eq (printf "%T" $u) "*types.Pointer"}}{{$u = $u.Elem.Underlying}}{{end}}:{{printf "%T" $u}}{{if eq (printf "%T" $u) "*types.Struct"}}{{range $j := $u.NumFields}} .{{($u.Field $j).Name}}:{{printf "%T" ($u.Field $j).Type.Underlying}}{{end}}{{end}} {{end}}{{.Callee}}|{{.Caller}}|{{with .Caller.Signature.Recv}}{{template "v" .}}{{end}}{{range $i := $.Caller.Signature.Params.Len}}{{template "v" ($.Caller.Signature.Params.At $i)}}{{end}}' ./compilers/... | grep -E '^[^|]*ReadOncePerRun.*types\.(Interface|Signature)'` + lists each, `error` and `any` included, a closure under its own: `operation.readSchema`, whose + key's `part` pairs with `branch.read`. + +## List a remembered reading's context reads by type +`context-reads-listed-by-type` + +- **Rule.** List what a reading and its callees read off a `lowering.Ctx` or `service.Ctx` by type + (`.claude/skills/morphic-verifying-changes/references/sweep-every-site.md#sweep-a-typed-mechanism-by-type`): + each call to a method of a type those packages declare, by `callgraph -algo cha`, as + `-algo static` skips a closure passed as a value, a reading's own body included; and each read + of their exported fields by name, other types' fields of that name included, so each line is + read. +- **Why.** A grep by the names most lowerings give a context missed `there.Rules()` and calls + through `dc`, `use`, `in` and `entryCtx` (#2379). +- **Probe.** `go run golang.org/x/tools/cmd/callgraph -algo cha -format '{{.Filename}}:{{.Line}} {{.Callee}}' ./compilers/... | grep -E '/(lowering|service)\.[[:alnum:]_]+\)\.'` + lists `compilers/openapi/internal/schema/twin.go:49`; with + `f=$(for p in ./compilers/openapi/internal/{lowering,service}; do go doc $p Ctx; done | awk '/^\t[A-Z]/ {print $1}' | paste -sd'|' -)`, + `grep -rnE "\.($f)([^[:alnum:]_]|$)" --include='*.go' compilers` lists the field reads. diff --git a/.claude/skills/morphic-designing-code/references/design-rules.md b/.claude/skills/morphic-designing-code/references/design-rules.md index 1731460c9..9a0dd478c 100644 --- a/.claude/skills/morphic-designing-code/references/design-rules.md +++ b/.claude/skills/morphic-designing-code/references/design-rules.md @@ -2,22 +2,65 @@ How new code keeps scaling with the document, takes the next format and emitter without a rewrite, and stays simple. Each rule is a cost a later refactor or performance change had to pay. +`references/deciding-once.md` holds the rules on deciding a fact once and folding declarations. -## Write a function of what it reads, not a method on a growing struct +## Write a function of what it reads; split a type or package as it grows `functional-core` - **Rule.** A lowering, check, pass or helper is a function of its inputs (a context, the document, its options) returning its value and diagnostics (in `irverify`, its violations). A run's - accumulators are locals of the function owning it, bar - `references/design-rules.md#shared-run-state`. A method belongs on a type only when it reads or - guards that type's own state, and a type nearing the method cap is split by the state its methods - read. -- **Why.** The OpenAPI lowerer reached 159 methods on 13 fields without one long function, and - dissolving it into functions of an immutable context ended in #217. The cap that now holds it - counts `compilers/` alone (#1159). + accumulators are its owning function's locals, bar `references/design-rules.md#shared-run-state`. + A method belongs on a type only when it reads or guards that type's state. A type nearing the + method cap splits by the state its methods read + (`references/design-rules.md#function-over-a-type-is-its-method`), a package past 300 free + functions by phase (`references/design-rules.md#split-a-package-by-phase`). +- **Why.** The OpenAPI lowerer reached 159 methods on 13 fields without one long function, until + #217 dissolved it into functions of an immutable context. The cap now holding it counts + `compilers/` alone (#1159). - **Probe.** For a type outside `compilers/`, against `maxMethodsPerType`: `git grep -hE '^func \(([[:alnum:]_]+ )?\*?(\[[^]]*\])?\) ' -- ':(glob)

/*.go' ':!*_test.go' | wc -l`. +## Count a function over a type as one of its methods +`function-over-a-type-is-its-method` + +- **Rule.** A function in a type's package taking it, or a pointer to it, as any of its parameters + and reading its fields counts toward its method cap, as it could be a method; another package's, + such as each lowering over `lowering.Ctx`, counts for none. #2377 lists the types over 20, and + `references/design-rules.md#leave-a-type-by-a-narrower-input` says how one sheds a function. +- **Why.** `reftable`'s `binder` held 20 methods and 15 functions over it (#2365). A first-parameter + count is evaded by reordering parameters, and misses 34 of the 40 functions taking + `allOfComposition`, 28 of them after `lowering.Ctx` at 4a7a384c9 (#2377). +- **Probe.** Beside the receiver count `references/design-rules.md#functional-core` gives, read each + function this lists for a field read; it misses a signature wrapping or holding a parenthesis + before the type: + `git grep -hE '^func [[:alnum:]_]+(\[[^]]*\])?\(([^()]*[ ,])?\*?(\[[^]]*\])?[,)]' -- ':(glob)/*.go' ':!*_test.go'`. + +## Shed a function from a type by giving it the narrower input it reads +`leave-a-type-by-a-narrower-input` + +- **Rule.** A type over the cap sheds a function by giving it the narrower input it reads, as #2081 + moved `admission`'s methods to `lowering.Ctx` and a `declarationSet` reader, never by making a + method a function over the same type, which still counts while `internal/archtest`, counting + receivers, stays green. +- **Why.** `reftable`'s `binder` held 20 methods beside 15 functions over it, and a builder near the + cap read that as the convention (#2365). +- **Probe.** `references/design-rules.md#function-over-a-type-is-its-method`'s count for the type + falls across the change. + +## Probe a grown package's phases, and split one past 300 free functions +`split-a-package-by-phase` + +- **Rule.** A package past 300 free functions splits by phase: read, build, keep and report + (#2408 splits `schema`). Probe each grown package, marking phases by a parameter (`schema`'s + builds take `*compile.Types`, its reads `*statement.Schema` without it); a listed file mixes + phases where something besides its build calls a read. + `TestRegistryFreeFiles_NameNoRegistry` holds its listed `schema` files free of `compile.Types`; + a cross-package measure waits for a proxy omitting a build's reads of its own source. +- **Why.** `schema` reached 755 free functions, 21 of its 55 files mixing phases, under the method + cap, growing #2083's copied build decisions and #2077's disagreeing phases (#2398). +- **Probe.** This counts free functions, listing mixed files: + `awk '/^func [A-Za-z]/{free++} /^func /{if(index($0,""))build[FILENAME]; else if(index($0,""))read[FILENAME]} END{print free; for (file in build) if (file in read) print file}' $(git ls-files ':(glob)/*.go' ':!*_test.go') ` over a spec declaring the read node after the - reader, and over #1978's `$ref` cycle. + reader, and #1978's `$ref` cycle. ## Prune a visitor to the path to its carriers `prune-a-visitor-to-its-carriers` @@ -108,12 +143,13 @@ and stays simple. Each rule is a cost a later refactor or performance change had an `Index` that indexes nothing), a question for a bool (`HasFilename`), and its type's noun for a parameter (`schema`, not `s`). One letter names only a loop counter, a receiver, a comparison pair or a standard-library convention (`t *testing.T`). A figurative word, an abbreviation or a - noun another package uses otherwise is renamed, not explained in a doc comment. + noun another package uses otherwise is renamed, not explained in a doc comment, but a normative + document's term stays, figurative or not + (`references/design-rules.md#normative-term-outranks-figurative`). - **Why.** Names that needed their comments, and comments that needed other coined names, left the code and the compiled IR unreadable to their owner (#2130). -- **Probe.** This lists a change's one-letter parameters, and - `references/design-rules.md#read-each-declared-name` reads the rest: - `git diff origin/main -- '*.go' | grep -nE '^\+func [A-Za-z][^(]*\((.*[, ])?[a-z] [*A-Za-z.]+[,)]'`. +- **Probe.** `references/design-rules.md#one-letter-names-by-kind` lists a change's one-letter + names, and `references/design-rules.md#read-each-declared-name` reads the rest. ## Read each name a change declares against what it holds `read-each-declared-name` @@ -129,6 +165,31 @@ and stays simple. Each rule is a cost a later refactor or performance change had reading it: `git diff origin/main -U0 -- '*.go' | grep -nE '^\+.*(:= |\b(var|const|func|type) )'`. +## Hold each one-letter parameter, field and local a change adds +`one-letter-names-by-kind` + +- **Rule.** Hold each one-letter name the probe lists (a parameter of a function, method or + function literal, a struct field, a `:=` or `var` local) to + `references/design-rules.md#name-what-it-holds`. The probe passes a receiver, a `for` + statement's first variable, counter or not, `t *testing.T` and a parameter list's leading pair + sharing a type (`(k, v string)`). Reading lines, it misses a wrapped signature's parameter not + opening its line. An `internal/lintrules` analyzer waits on #2410. +- **Why.** The probe read only an unwrapped function with no receiver, listing 1 of #2393's 6 + one-letter names. +- **Probe.** `git diff origin/main -- '*.go' | grep -nE -e '^\+.*func( \([^()]*\))?( [[:alnum:]_]+)?(\[.*\])?\(([^()][^()]+, )?[a-z] [][*.]*[[:alpha:]]' -e '^\+[[:space:]]+[a-z](, [a-z])* +[][*.]*[[:alpha:]]' -e '^\+[[:space:]]+((if|switch|case) |for [[:alnum:]_]+, )?([[:alnum:]_]+, )*[a-z](, [[:alnum:]_]+)* := ' -e '^\+[[:space:]]*var ([[:alnum:]_]+, )*[a-z][ ,]' | grep -vE '\([tbfm] \*?testing\.[[:alpha:]]+(, ([[:alnum:]_]{2,}|_)( [^,()]+)?)*\)'`. + +## Keep a normative document's term, even a figurative one +`normative-term-outranks-figurative` + +- **Rule.** Where a normative document (the source format's specification, `docs/ir`, + `docs/compilers/.md`, `docs/emitters`) uses a word as its term for a concept, the code + takes that word, figurative or not, so a name leads to its document. A change to the term + changes the document first. +- **Why.** `travelsAs` takes the documents' "travels as", a figurative term the naming rule both + asked for and renamed (#2395). +- **Probe.** Before renaming a name as figurative, `git grep -n -w '' -- docs/` lists the + word's uses, a normative one keeping the name. + ## Place shared code by its second user `second-user` @@ -149,14 +210,30 @@ and stays simple. Each rule is a cost a later refactor or performance change had - **Rule.** Add no wrapper, re-export or helper that only forwards a call or supplies one argument: call the function. Add an interface only for a second implementation or a seam a test uses, and - an option only with a caller that sets it. The second user decides where code goes, not what is - built before it exists. + an option or parameter only where production sets it + (`references/design-rules.md#production-sets-each-parameter`). The second user decides where + code goes, not what is built beforehand. - **Why.** Three of the hoisting helpers' six methods were one-line delegations (#195), four wrappers only supplied the source index and swallowed diagnostics (#199), and a re-export gave one call two spellings and a false dependency (#1100). Members only tests reached were removed, and are now refused (#1122). - **Probe.** Each new function does more than call another, each new interface has two - implementations or a test seam, and `go test ./internal/archtest` passes. + implementations or a test seam, each new option or parameter passes + `references/design-rules.md#production-sets-each-parameter`; `go test ./internal/archtest` + passes. + +## Add an option or parameter only where production sets it to a value it uses +`production-sets-each-parameter` + +- **Rule.** An option or parameter production passes only as nil, a zero or a no-op, for tests + alone to fill, is refused as a function only tests call is. A test may replace or wrap what + production sets, as `OnVerify` in `engine/export_test.go` wraps the engine's verifier. +- **Why.** `internal/archtest` counts a function's callers, not what they pass, so a parameter + production hands nil passes it (#2359); a line grep missed split and value calls (#2379). +- **Probe.** `go run golang.org/x/tools/cmd/callgraph -algo cha -format '{{.Filename}}:{{.Line}} {{.Callee}}' ./... | grep -E '\.(\[.*\])?$'` + lists each production call, a value call under each function of its signature: refused where + each passes nil, zero or a no-op. `git grep -nE '(^|[^[:alnum:]_])