diff --git a/.changes/code-metrics/work-resolve-issue-issue-18001-44954461570-1-b0a70733.md b/.changes/code-metrics/work-resolve-issue-issue-18001-44954461570-1-b0a70733.md new file mode 100644 index 00000000000..07671bdd4b2 --- /dev/null +++ b/.changes/code-metrics/work-resolve-issue-issue-18001-44954461570-1-b0a70733.md @@ -0,0 +1,12 @@ +--- +bump: minor +--- + +### Changed + +- **The personal override moves to `docs/conventions/code-metrics.local.yaml`** ([#18001](https://github.com/melodic-software/claude-code-plugins/issues/18001)), beside the team file, per the config-cascade layers. The plugin declares no `userConfig` option, so there is no user-global file layer. Recommended `.gitignore` line: `docs/conventions/**/*.local.*`. +- **Dual-read window for the old paths.** `~/.claude/code-metrics.yaml` is still read below the team file, and `.claude/code-metrics.local.yaml` is still read as the personal layer while the new file is absent. Each run prints one warning per old file naming where its keys go; with both personal files present the new one wins and the warning names both. A later release stops reading the old paths. + +### Added + +- **`/code-metrics:setup apply --copy-old`** copies the old personal files into `docs/conventions/code-metrics.local.yaml` after a `--preview` and a yes, naming each key it copies or skips and leaving the old files in place. A key of the old user-global file that the team file sets is not copied, so the effective configuration does not change. `/code-metrics:setup check` names each old file it finds. diff --git a/docs/contracts/config-cascade/README.md b/docs/contracts/config-cascade/README.md index 85e2efd3e8d..dec8e184831 100644 --- a/docs/contracts/config-cascade/README.md +++ b/docs/contracts/config-cascade/README.md @@ -686,7 +686,7 @@ its conformance cell. | `disk-hygiene` | no-floor | `.claude/disk-hygiene.json` | user-global + team | team over user-global; `--policy` replaces both | additive standing layers | declared deviation; no personal override layer | | `ai-briefing` | no-floor | `.claude/ai-briefing/` | team only | team only | no personal override | declared deviation; team-only, no personal override (#3580). Named profile selection (`--profile`, `active_profile`, or `.claude/ai-briefing//`) is profile selection, not a `*.local.*` cascade layer. `sources.md`, optional `audience.md`, and optional `brand.json` are tracked profile files in the selected directory, not personal overrides | | `code-tidying` | no-floor | `.claude/tidy-lanes/.md` | team only | team only; residual wholesale if no `## Merge semantics` | per-section when declared | declared deviation; no user-global or `*.local.*` personal override (#723). Team layer over a bundled default. A project lane declaring `## Merge semantics` merges per-section with its bundled lane (`Scope` per-section override, watch-for patterns additive, per `docs-prose` #701 and `shell-tooling` #724). Residual deviation: a project lane that declares nothing still resolves project-only wholesale, the first-match fallback retained in #701 so unmigrated consumer lanes keep working, undeclared at the layer that takes it. Personal variation is limited to lane names the team does not track, an uncommitted `.claude/tidy-lanes/.md` never added to the index; gitignoring a path the team already tracks does not make it personal | -| `code-metrics` | no-floor | `docs/conventions/code-metrics.yaml` (ADR 0064; schema `plugins/code-metrics/schemas/code-metrics.schema.json`) | all three | later layer | per-key | conforms (per-key override, declared because every value is a scalar or a closed list: `scope.exclude` and `lanes..collectors.` replace whole), except declared divergences from "Resolution algorithm": (1) the root is `git rev-parse --show-toplevel`, else the working directory, and `CLAUDE_PROJECT_DIR` is not read (`plugins/code-metrics/scripts/resolve-config.py:221-234`; step 1); (2) no home-root or same-file classification of the team and personal override paths (`resolve-config.py:236-252`; step 2). The team layer is the docs file alone: the retired `.claude` team file of earlier releases is never read (`resolve-config.py:244-252`), and `/code-metrics:setup check` reports it. A layer outside the YAML subset reads as absent, and a value of the wrong shape is dropped by file, key and value and resolves from a valid higher layer, else the bundled default, never a lower layer; neither stops the run (`resolve-config.py:133-165,273-297`; ADR 0064 Decision 7). Unknown keys inert. Keys owned by [`plugins/code-metrics/reference/config.md`](../../../plugins/code-metrics/reference/config.md). Written (team layer only, carrying every declared key of a retired `.claude` file) by `/code-metrics:setup apply`; read by every audit skill. The consumer's `.claude/ecosystems/.yaml` files are a separate convention (ecosystem-commands); this surface does not absorb them. **Claim:** the plugin implements this row with the declared divergences above. **Basis:** `plugins/code-metrics/reference/config.md` "Layers and merge form" and the cited `resolve-config.py` lines. **As of:** 2026-11-02. **Recheck:** when that section adds a layer, changes merge form, or starts owning an ecosystem-commands key | +| `code-metrics` | no-floor | team `docs/conventions/code-metrics.yaml` (ADR 0064; schema `plugins/code-metrics/schemas/code-metrics.schema.json`); personal override `docs/conventions/code-metrics.local.yaml`; no `userConfig` option | team + personal override, plus the old files of the dual-read window | later layer | per-key | conforms to [the layers](#the-layers) (per-key override, declared because every value is a scalar or a closed list: `scope.exclude` and `lanes..collectors.` replace whole), except declared divergences from "Resolution algorithm": (1) the root is `git rev-parse --show-toplevel`, else the working directory, and `CLAUDE_PROJECT_DIR` is not read (`plugins/code-metrics/scripts/resolve-config.py:244-257`; step 1); (2) no home-root or same-file classification of the team and personal override paths (`resolve-config.py:267-321`; step 2). The team layer is the docs file alone: the retired `.claude` team file of earlier releases is never read (`resolve-config.py:275-321`), and `/code-metrics:setup check` reports it. A layer outside the YAML subset reads as absent, and a value of the wrong shape is dropped by file, key and value and resolves from a valid higher layer, else the bundled default, never a lower layer; neither stops the run (`resolve-config.py:149-188,342-366`; ADR 0064 Decision 7). Unknown keys inert. Keys owned by [`plugins/code-metrics/reference/config.md`](../../../plugins/code-metrics/reference/config.md). The team and personal override files sit at `docs/conventions/` whatever home the repository binds. Dual-read window: the old `~/.claude/code-metrics.yaml` is still read below the team layer, and the old `.claude/code-metrics.local.yaml` as the personal layer only while the new personal file is absent or outside the YAML subset; each run names each old file in one warning, and removing those reads is a later change. Written by `/code-metrics:setup apply`: the team layer, carrying every declared key of a retired `.claude` team file, and, through `apply --copy-old` after a preview, the personal override, carrying the old personal files' keys and leaving those files in place; read by every audit skill. The consumer's `.claude/ecosystems/.yaml` files are a separate convention (ecosystem-commands); this surface does not absorb them. **Claim:** the plugin implements this row with the declared divergences above. **Basis:** `plugins/code-metrics/reference/config.md` "Layers and merge form" and the cited `resolve-config.py` lines. **As of:** 2026-11-21. **Recheck:** when that section adds a layer, changes merge form, or starts owning an ecosystem-commands key | | `repo-fleet-hygiene` | no-floor | `.claude/repo-fleet-hygiene.conf` | user-global + team | `--config` then team then user-global | whole-file, no per-key | declared deviation; whole-file precedence (explicit `--config` > team > user-global fallback), no per-key merge, no personal override layer (#1099) | | `work-items` | no-floor | the `tracker` mapping of `/work-items.yaml` | team + personal override | personal override on the allowlist | per-key personal override | declared deviation ([ADR 0015](../../adr/0015-bind-the-tracker-at-repo-root-with-an-allowlisted-personal-overlay.md), superseded by ADR 0075): layers live in the convention home, not under `.claude/`; personal override (`/work-items.local.yaml`) merges per-key over a deny-by-default allowlist (lease TTL, jira/linear/gitea auth identity, `docs`); deliberately no user-global layer, since a cross-repo personal rung would reopen the per-user provider trap the allowlist forecloses. Anchors at the repo root (`CLAUDE_PROJECT_DIR`, else git toplevel), no CWD climb. The personal override's gitignore line is outside the `.claude/**/*.local.*` one-liner, so `/work-items:setup apply` appends it, announced, a declared exception to the recommend default (ADR 0015) | | `work-items` (recurring schedule) | no-floor | `.github/recurring-schedule.json` | team only | team only | single-layer | declared deviation ([ADR 0042](../../adr/0042-ratify-consumer-config-location-outliers-in-place.md)): the schedule lives under `.github/`, not `.claude/`, tracked and team-shared with no user-global layer and no personal override. Written by `track add` and `track recheck`; read by `track audit`, `done`, `due`, `search` and `stats`, by `work` candidate discovery, and by `setup`, which also writes it; anchors at `CLAUDE_PROJECT_DIR`, else git toplevel. Separate from the tracker binding row above | diff --git a/plugins/code-metrics/README.md b/plugins/code-metrics/README.md index ebb69d447ef..21776f2f27f 100644 --- a/plugins/code-metrics/README.md +++ b/plugins/code-metrics/README.md @@ -73,11 +73,15 @@ run continues. ## Configuration -This plugin has no `userConfig`. Everything tunable lives in three layers: user-global -(`~/.claude/code-metrics.yaml`), team (`docs/conventions/code-metrics.yaml`, tracked, checked by +This plugin has no `userConfig`. Everything tunable lives in two file layers: team +(`docs/conventions/code-metrics.yaml`, tracked, checked by [`schemas/code-metrics.schema.json`](schemas/code-metrics.schema.json); the retired team file -under `.claude/` is not read, and `/code-metrics:setup apply` moves its keys), and personal override (`.claude/code-metrics.local.yaml`, gitignored; recommended line -`.claude/**/*.local.*`) with per-key override, and every key has a bundled default +under `.claude/` is not read, and `/code-metrics:setup apply` moves its keys) and personal override +(`docs/conventions/code-metrics.local.yaml`, gitignored; recommended line +`docs/conventions/**/*.local.*`) with per-key override. The old `~/.claude/code-metrics.yaml` and +`.claude/code-metrics.local.yaml` are still read, each with a warning, until a later release +([dual-read window](reference/config.md#layers-and-merge-form)); `/code-metrics:setup apply` +copies their keys. Every key has a bundled default (`scripts/config-defaults.json`), so the plugin works with no configuration at all; the one opinionated default is `scope.exclude`, which drops `node_modules`, `vendor`, `dist`, and `build` directories at any depth and reports what it dropped, and a team file that sets the key replaces @@ -86,9 +90,9 @@ the list whole. The consumer's and `enabled`. References ship with their provenance: cyclomatic 20 cites ISO/IEC 5055:2021 ยง8.2.117; the 1000-line file default is the plugin's own number and says so. Files are written in a documented YAML subset (block style, flow sequences of scalars, no flow mappings). Every key: -`reference/config.md`; `/code-metrics:setup` writes the team layer and probes the collectors. - -This plugin still reads, or reports as retired, the `.claude/` paths named here; until the plugin migrates, keep config where this page says it is read, then move it where [config locations](reference/config-locations.md) says. +`reference/config.md`; `/code-metrics:setup` writes the team layer, copies old personal files into +the personal override, and probes the collectors. Where each layer lives across this marketplace's +plugins: [config locations](reference/config-locations.md). ## The report diff --git a/plugins/code-metrics/reference/config.md b/plugins/code-metrics/reference/config.md index de0efa843ea..9e51b374a5e 100644 --- a/plugins/code-metrics/reference/config.md +++ b/plugins/code-metrics/reference/config.md @@ -2,22 +2,34 @@ Every tunable value in this plugin resolves through one set of config layers. This document is their contract: the layers, the merge form, the YAML subset, and every key with its default and -provenance. `/code-metrics:setup` writes the team layer; every audit skill reads the resolved +provenance. `/code-metrics:setup` writes the team layer, and the personal override only when it +copies old files there; every audit skill reads the resolved document at run time and prints the layer that supplied any value a personal layer changed. The JSON Schema for every layer's keys is [`schemas/code-metrics.schema.json`](../schemas/code-metrics.schema.json). ## Layers and merge form -The surface follows the marketplace's config-cascade convention. Three layers, each optional, -resolved in this order over the bundled defaults (`scripts/config-defaults.json`): +The surface follows the marketplace's config-cascade convention ([config locations](config-locations.md)). +The layers, each optional, resolve in this order over the bundled defaults +(`scripts/config-defaults.json`): | Order | Layer | Path | Belongs to | |---|---|---|---| -| 1 | user-global | `~/.claude/code-metrics.yaml` | the operator, across repositories | +| 1 | `userConfig` | none: the plugin declares no `userConfig` option | the operator, across repositories | | 2 | team | `/docs/conventions/code-metrics.yaml` | the repository, tracked | -| 3 | personal override | `/.claude/code-metrics.local.yaml` | one operator in one repository, gitignored | +| 3 | personal override | `/docs/conventions/code-metrics.local.yaml` | one operator in one repository, gitignored | -This plugin still reads, or reports as retired, the `.claude/` paths named here; until the plugin migrates, keep config where this page says it is read, then move it where [config locations](config-locations.md) says. +**Dual-read window.** Two old paths are still read, and each run prints one warning naming the +old file and where its keys go: + +| Old path | Read as | When | +|---|---|---| +| `~/.claude/code-metrics.yaml` | layer `user-global`, below the team file | while it exists, since no file supplies the `userConfig` layer | +| `/.claude/code-metrics.local.yaml` | layer `local` | only while `docs/conventions/code-metrics.local.yaml` is absent or outside the YAML subset; with both present the new file wins and the warning names both | + +`/code-metrics:setup check` names each old file it finds, and `/code-metrics:setup apply` +offers to copy their keys into `docs/conventions/code-metrics.local.yaml`, leaving the old files in +place. A later release stops reading the old paths. The team layer is `docs/conventions/code-metrics.yaml` alone. The team file earlier releases read from the repository's `.claude/` directory is retired and never read. `/code-metrics:setup check` @@ -37,11 +49,12 @@ holding a newline, carriage return or tab, a `scope.exclude` glob the matcher ca A later layer replaces an earlier layer's value key by key; a key absent from a later layer keeps the earlier value; a list (`scope.exclude`, `lanes..collectors.`) is a closed value and is replaced whole, never concatenated. Unknown keys are inert. All three layers absent is -valid. The recommended consumer `.gitignore` line for the personal override is `.claude/**/*.local.*`; the -plugin never edits your `.gitignore`. +valid. The recommended consumer `.gitignore` line for the personal override is +`docs/conventions/**/*.local.*`; the plugin never edits your `.gitignore`. The consumer's `.claude/ecosystems/.yaml` files (the ecosystem-commands convention) resolve -through the same three layers for their `globs` (which replace the bundled extension map for that +through that convention's own layers (`~/.claude/ecosystems/.yaml`, then the repository's +`.yaml` and `.local.yaml`) for their `globs` (which replace the bundled extension map for that lane) and `enabled` (a resolved `false` opts the lane out). Only a lane named under `lanes` reads its file: the bundled lanes, plus any extra id a layer lists there. A record whose id is not listed creates no lane, because a record need not describe a programming language (a lint-only @@ -67,10 +80,10 @@ warning. The files the globs match form the `rust` lane. With no shipped collect measure on that lane reads `unavailable` with the reason `no shipped collector for the rust lane`, except `file_lines`, which walks the `other` lane's collectors so the files keep their line count. -The user-global layer is looked up under `$HOME`; `CODE_METRICS_HOME`, when set, replaces that -directory for one run (the plugin's own suites use it to point at a scratch home, and a consumer -can use it the same way to try a personal layer without touching `~/.claude`). It is the only -environment variable the cascade reads; no key is settable from the environment. +The old user-global file and the ecosystem files' home layer are looked up under `$HOME`; +`CODE_METRICS_HOME`, when set, replaces that directory for one run (the plugin's own suites use it +to point at a scratch home). It is the only environment variable the cascade reads; no key is +settable from the environment. ## The YAML subset diff --git a/plugins/code-metrics/reference/several-repositories.md b/plugins/code-metrics/reference/several-repositories.md index bd0e05196d2..a90a1aeb717 100644 --- a/plugins/code-metrics/reference/several-repositories.md +++ b/plugins/code-metrics/reference/several-repositories.md @@ -29,8 +29,8 @@ With no target form, nothing here applies: each skill runs exactly as its own bo - **Paths stay relative.** A path given with a target form (a scope path, `--artifacts`, `--registry`, `--memory-dir`) must be relative, and is read from each root; refuse an absolute one before the fan-out, since it would point every repository at one file or one directory. A - repository that lacks a named path, or a registry its resolved configuration names (the - user-global layer applies to every repository), reports the usage error as that repository's + repository that lacks a named path, or a registry its resolved configuration names (an old + user-global file, still read, applies to every repository), reports the usage error as that repository's failure, and the others still run. - **Every other argument** (`--json`, `--keep`, `--findings`) passes to each repository's run unchanged. diff --git a/plugins/code-metrics/schemas/code-metrics.schema.json b/plugins/code-metrics/schemas/code-metrics.schema.json index 20c85ec32a7..6e190a4c98e 100644 --- a/plugins/code-metrics/schemas/code-metrics.schema.json +++ b/plugins/code-metrics/schemas/code-metrics.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/melodic-software/claude-code-plugins/main/plugins/code-metrics/schemas/code-metrics.schema.json", "title": "code-metrics team config", - "description": "Schema for a repository's docs/conventions/code-metrics.yaml, the team layer of the code-metrics plugin (ADR 0064). The same keys are valid in ~/.claude/code-metrics.yaml and .claude/code-metrics.local.yaml. Every key is optional; the plugin's reference/config.md gives each key's default and meaning. Reader: scripts/resolve-config.py, which drops an invalid value by name and keeps running.", + "description": "Schema for a repository's docs/conventions/code-metrics.yaml, the team layer of the code-metrics plugin (ADR 0064). The same keys are valid in the personal override docs/conventions/code-metrics.local.yaml and in the old files the dual-read window still reads, ~/.claude/code-metrics.yaml and .claude/code-metrics.local.yaml. Every key is optional; the plugin's reference/config.md gives each key's default and meaning. Reader: scripts/resolve-config.py, which drops an invalid value by name and keeps running.", "type": "object", "additionalProperties": false, "$defs": { diff --git a/plugins/code-metrics/scripts/dispatch.sh b/plugins/code-metrics/scripts/dispatch.sh index 652ee05fcec..fa3469fbf08 100755 --- a/plugins/code-metrics/scripts/dispatch.sh +++ b/plugins/code-metrics/scripts/dispatch.sh @@ -27,13 +27,16 @@ # scope as cwd-relative `lanepath` rows and stops, producing no document. # # Configuration: without `--config`, the cascade is resolved here through -# scripts/resolve-config.py (bundled defaults, then ~/.claude/code-metrics.yaml, -# docs/conventions/code-metrics.yaml, .claude/code-metrics.local.yaml, plus the -# consumer's .claude/ecosystems/.yaml files); CODE_METRICS_HOME overrides -# the home directory the user-global layer is read from. `--config` takes a +# scripts/resolve-config.py (bundled defaults, then +# docs/conventions/code-metrics.yaml and docs/conventions/code-metrics.local.yaml, +# plus the consumer's .claude/ecosystems/.yaml files). The old +# ~/.claude/code-metrics.yaml and .claude/code-metrics.local.yaml are still read, +# each with a warning, during the dual-read window; CODE_METRICS_HOME overrides +# the home directory the old user-global file is read from. `--config` takes a # pre-resolved JSON document (the resolver's output) instead. Either way the # resolved document supplies the references, `scope.exclude`, the per-lane -# collector overrides, and the ecosystem globs and opt-outs. +# collector overrides, and the ecosystem globs and opt-outs. Layers: +# https://github.com/melodic-software/claude-code-plugins/blob/main/docs/contracts/config-cascade/README.md#the-layers # # Exit: 0 the document was produced (including an `empty` run); 2 usage or # environment error; 3 a resolved collector ran and produced no parseable diff --git a/plugins/code-metrics/scripts/dispatch.test.sh b/plugins/code-metrics/scripts/dispatch.test.sh index e25c439f79d..d05be32b0d2 100755 --- a/plugins/code-metrics/scripts/dispatch.test.sh +++ b/plugins/code-metrics/scripts/dispatch.test.sh @@ -5,6 +5,7 @@ # nothing executable is committed). The adapters themselves (scc.py, # line-counter.py) and report.py are exercised through the dispatcher. # test-scope: plugins/code-metrics/scripts/collectors/*.py plugins/code-metrics/scripts/fixtures/* +# test-scope: .claude/ecosystems/*.yaml # runs from the repo root, so the config resolver reads its lanes set -uo pipefail unset GIT_DIR GIT_WORK_TREE GIT_CONFIG export GIT_CONFIG_GLOBAL="${GIT_CONFIG_GLOBAL:-/dev/null}" GIT_CONFIG_NOSYSTEM=1 @@ -474,6 +475,43 @@ assert_doc "ecosystem globs redefine the bash lane" "$out" \ 'any(r["file"]=="x.bats" and r["lane"]=="bash" for r in d["measures"]) and not any(r["file"]=="plain.sh" for r in d["measures"])' assert_doc "lanes.dotnet.enabled false opts the lane out" "$out" \ 'not any(r["lane"]=="dotnet" for r in d["run"]) and not any(r["file"]=="C.cs" for r in d["measures"])' + +# 10b. The personal layer: docs/conventions/code-metrics.local.yaml beats the +# team file; the old .claude/code-metrics.local.yaml applies only while it +# is absent, and each run names the old file on stderr (the dual-read +# window: https://github.com/melodic-software/claude-code-plugins/issues/18001). +personal="$repo/docs/conventions/code-metrics.local.yaml" +old_personal="$repo/.claude/code-metrics.local.yaml" +file_lines_is() { + printf 'next(t for t in d["thresholds"] if t["measure"]=="file_lines")["reference"]==%s and next(t for t in d["thresholds"] if t["measure"]=="file_lines")["layer"]=="local"' "$1" +} +stderr_has() { + case "$(cat "$err_file")" in + *"$2"*) pass "$1" ;; + *) fail "$1" "stderr contains: $2" "$(head -c 600 "$err_file")" ;; + esac +} +err_file="$(mktemp)" +printf 'size:\n file_lines: 3\n' >"$personal" +out="$(cd "$repo" && PATH="$EMPTY_PATH" CODE_METRICS_HOME="$home" CLAUDE_PLUGIN_ROOT="$SCRIPT_DIR/.." bash "$SCRIPT" audit-size --measures file_lines --all 2>"$err_file")" +assert_doc "the new personal file alone supplies the reference" "$out" "$(file_lines_is 3)" +if grep -q 'old personal override' "$err_file"; then + fail "the new personal file alone prints no old-path warning" "no old personal override warning" "$(head -c 600 "$err_file")" +else + pass "the new personal file alone prints no old-path warning" +fi +rm -f "$personal" +printf 'size:\n file_lines: 4\n' >"$old_personal" +out="$(cd "$repo" && PATH="$EMPTY_PATH" CODE_METRICS_HOME="$home" CLAUDE_PLUGIN_ROOT="$SCRIPT_DIR/.." bash "$SCRIPT" audit-size --measures file_lines --all 2>"$err_file")" +assert_doc "an old personal file alone still applies" "$out" "$(file_lines_is 4)" +stderr_has "an old personal file alone is named with its new location" "/.claude/code-metrics.local.yaml is the old personal override, still read as the personal layer; move it to " +stderr_has "the old-path warning names the new location" "/docs/conventions/code-metrics.local.yaml (/code-metrics:setup apply --copy-old)" +printf 'size:\n file_lines: 3\n' >"$personal" +out="$(cd "$repo" && PATH="$EMPTY_PATH" CODE_METRICS_HOME="$home" CLAUDE_PLUGIN_ROOT="$SCRIPT_DIR/.." bash "$SCRIPT" audit-size --measures file_lines --all 2>"$err_file")" +assert_doc "with both personal files the new one wins" "$out" "$(file_lines_is 3)" +stderr_has "with both personal files the warning names both" "/.claude/code-metrics.local.yaml is the old personal override and is not read because " +stderr_has "the both-files warning names the new file" "/docs/conventions/code-metrics.local.yaml exists" +rm -f "$err_file" rm -rf "$repo" "$home" # 11. --config with a pre-resolved document: the collector override narrows the diff --git a/plugins/code-metrics/scripts/fixtures/config/local.yaml b/plugins/code-metrics/scripts/fixtures/config/local.yaml index bcad770dffe..87a63d7d3d6 100644 --- a/plugins/code-metrics/scripts/fixtures/config/local.yaml +++ b/plugins/code-metrics/scripts/fixtures/config/local.yaml @@ -1,4 +1,5 @@ -# Fixture: the personal override (.claude/code-metrics.local.yaml). One -# operator's exclusion, additive over the team file. +# Fixture: the personal override (docs/conventions/code-metrics.local.yaml). One +# operator's exclusion, additive over the team file. Layers: +# https://github.com/melodic-software/claude-code-plugins/blob/main/docs/contracts/config-cascade/README.md#the-layers scope: exclude: ["vendor/**"] diff --git a/plugins/code-metrics/scripts/fixtures/config/user.yaml b/plugins/code-metrics/scripts/fixtures/config/user.yaml index e3901b35bc5..cf1185191ba 100644 --- a/plugins/code-metrics/scripts/fixtures/config/user.yaml +++ b/plugins/code-metrics/scripts/fixtures/config/user.yaml @@ -1,5 +1,6 @@ -# Fixture: the user-global layer (~/.claude/code-metrics.yaml). Sets two -# references that the team layer then overrides one of. +# Fixture: the old user-global file (~/.claude/code-metrics.yaml). Sets two +# references that the team layer then overrides one of. Dual-read window: +# https://github.com/melodic-software/claude-code-plugins/issues/18001 complexity: cyclomatic: reference: 10 diff --git a/plugins/code-metrics/scripts/resolve-config.py b/plugins/code-metrics/scripts/resolve-config.py index 30cbbdd3169..45c103553e5 100755 --- a/plugins/code-metrics/scripts/resolve-config.py +++ b/plugins/code-metrics/scripts/resolve-config.py @@ -7,9 +7,19 @@ whole): 0. bundled defaults scripts/config-defaults.json - 1. user-global ~/.claude/code-metrics.yaml + 1. userConfig none: the plugin declares no userConfig option 2. team /docs/conventions/code-metrics.yaml - 3. personal override /.claude/code-metrics.local.yaml + 3. personal override /docs/conventions/code-metrics.local.yaml + +Dual-read window: two old paths are still read, each with one warning per run +naming the old file and where its keys go. + + ~/.claude/code-metrics.yaml read as layer `user-global`, below team, + since no file supplies the userConfig layer + /.claude/code-metrics.local.yaml + read as layer `local` only while the + docs/conventions personal file is absent + or outside the YAML subset The team file earlier releases read from the repository's .claude directory is not read; /code-metrics:setup check reports it and apply moves its keys. @@ -22,8 +32,10 @@ default, never from a lower layer. The consumer's ecosystem files (`.claude/ecosystems/.yaml`, the -marketplace-wide ecosystem-commands convention) resolve through the same three -layers for their `globs` and `enabled` keys. Only a lane in the resolved +marketplace-wide ecosystem-commands convention) resolve through that +convention's three layers (`~/.claude/ecosystems/.yaml`, then the +repository's `.yaml` and `.local.yaml`) for their `globs` and +`enabled` keys. Only a lane in the resolved `lanes` mapping reads its ecosystem file: the bundled lanes, plus any id a layer lists under `lanes`. A record whose id no layer lists creates no lane. @@ -252,14 +264,61 @@ def layer_paths(home: str, root: str, stem: str) -> list[tuple[str, str]]: ] -def surface_layer_paths(home: str, root: str) -> list[tuple[str, str]]: - """The plugin's own three layers; the team layer is the docs file alone. +def old_layer_paths(home: str, root: str) -> dict[str, str]: + """The pre-cascade user-global and personal override paths, by layer.""" + return { + "user-global": os.path.join(home, ".claude", f"{SURFACE}.yaml"), + "local": os.path.join(root, ".claude", f"{SURFACE}.local.yaml"), + } + - `docs/conventions/code-metrics.yaml` is the team layer (ADR 0064). The - older team file in the repository's `.claude` directory is never read. +def surface_layer_paths( + home: str, root: str, warnings: list[str] | None = None +) -> list[tuple[str, str]]: + """The plugin's file layers, with the old paths the dual-read window keeps. + + The team and personal override files sit in `docs/conventions/` + (config-cascade, "The layers"). The older team file in the repository's + `.claude` directory is never read. An old user-global or personal file is + read in its layer's place and named in one warning each. """ - paths = layer_paths(home, root, SURFACE) - paths[1] = ("team", os.path.join(root, "docs", "conventions", f"{SURFACE}.yaml")) + warnings = [] if warnings is None else warnings + conventions = os.path.join(root, "docs", "conventions") + personal = os.path.join(conventions, f"{SURFACE}.local.yaml") + old = old_layer_paths(home, root) + paths = [("team", os.path.join(conventions, f"{SURFACE}.yaml"))] + if os.path.isfile(old["user-global"]): + paths.insert(0, ("user-global", old["user-global"])) + warnings.append( + f"{old['user-global']} is the old user-global file, still read below the " + "team layer; the plugin has no userConfig option, so copy the keys this " + f"repository needs to {personal} (/code-metrics:setup apply --copy-old); " + "it applies to every repository, so keep it until each repository that " + "relies on it has copied its keys" + ) + if os.path.isfile(personal) and os.path.isfile(old["local"]): + if _load_layer(personal, []) is None: + paths.extend([("local", old["local"]), ("local", personal)]) + warnings.append( + f"{old['local']} is the old personal override, still read as the " + f"personal layer because {personal} is outside the YAML subset; fix " + f"{personal}, then delete the old file" + ) + else: + paths.append(("local", personal)) + warnings.append( + f"{old['local']} is the old personal override and is not read because " + f"{personal} exists; move any key it still holds to {personal} and " + "delete the old file" + ) + elif os.path.isfile(personal): + paths.append(("local", personal)) + elif os.path.isfile(old["local"]): + paths.append(("local", old["local"])) + warnings.append( + f"{old['local']} is the old personal override, still read as the personal " + f"layer; move it to {personal} (/code-metrics:setup apply --copy-old)" + ) return paths @@ -571,7 +630,7 @@ def main(argv: list[str]) -> int: ) return 2 else: - layer_files = surface_layer_paths(args.home, root) + layer_files = surface_layer_paths(args.home, root, warnings) def discovered(lane: str) -> list[tuple[str, str]]: return layer_paths(args.home, root, os.path.join("ecosystems", lane)) diff --git a/plugins/code-metrics/scripts/test_resolve_config.py b/plugins/code-metrics/scripts/test_resolve_config.py index 1fae5c5c0dc..1911c3e03b2 100755 --- a/plugins/code-metrics/scripts/test_resolve_config.py +++ b/plugins/code-metrics/scripts/test_resolve_config.py @@ -585,6 +585,85 @@ def test_with_both_files_only_the_docs_file_is_read(self) -> None: d["_files"], [f"{root.as_posix()}/docs/conventions/code-metrics.yaml"] ) + def _personal(self, tmp: str, new: str | None, old: str | None, user: str | None): + home = Path(tmp) / "home" + root = Path(tmp) / "repo" + (root / "docs" / "conventions").mkdir(parents=True) + paths = { + "new": root / "docs" / "conventions" / "code-metrics.local.yaml", + "old": root / ".claude" / "code-metrics.local.yaml", + "user": home / ".claude" / "code-metrics.yaml", + } + for name, text in (("new", new), ("old", old), ("user", user)): + if text is not None: + paths[name].parent.mkdir(parents=True, exist_ok=True) + paths[name].write_text(text, encoding="utf-8") + result = run("--home", str(home), "--repo-root", str(root)) + self.assertEqual(result.returncode, 0, result.stderr) + return json.loads(result.stdout), result.stderr, paths + + def test_the_personal_layer_reads_the_docs_conventions_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + d, err, paths = self._personal(tmp, "size:\n file_lines: 610\n", None, None) + self.assertEqual( + d["_provenance"]["size.file_lines"], {"value": 610, "layer": "local"} + ) + self.assertEqual(d["_files"], [paths["new"].as_posix()]) + self.assertEqual(err, "") + + def test_an_old_personal_file_alone_applies_with_a_warning(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + d, err, paths = self._personal(tmp, None, "size:\n file_lines: 620\n", None) + self.assertEqual( + d["_provenance"]["size.file_lines"], {"value": 620, "layer": "local"} + ) + warnings = [w for w in d["_warnings"] if str(paths["old"]) in w] + self.assertEqual(len(warnings), 1, d["_warnings"]) + self.assertIn(str(paths["new"]), warnings[0]) + self.assertEqual(err.count(str(paths["old"])), 1) + + def test_with_both_personal_files_the_new_one_wins_and_both_are_named(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + d, _, paths = self._personal( + tmp, "size:\n file_lines: 610\n", "size:\n file_lines: 620\n", None + ) + self.assertEqual(d["size"]["file_lines"], 610) + self.assertNotIn(paths["old"].as_posix(), d["_files"]) + self.assertTrue( + any( + str(paths["old"]) in w and str(paths["new"]) in w + for w in d["_warnings"] + ), + d["_warnings"], + ) + + def test_an_unparsable_new_personal_file_leaves_the_old_one_applied(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + d, _, paths = self._personal( + tmp, "size: { file_lines: 610 }\n", "size:\n file_lines: 620\n", None + ) + self.assertEqual(d["size"]["file_lines"], 620) + self.assertTrue( + any( + str(paths["old"]) in w and "outside the YAML subset" in w + for w in d["_warnings"] + ), + d["_warnings"], + ) + + def test_an_old_user_global_file_applies_below_team_with_a_warning(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + d, _, paths = self._personal( + tmp, None, None, "size:\n file_lines: 700\n mode: iso-8.2.115\n" + ) + self.assertEqual( + d["_provenance"]["size.file_lines"], + {"value": 700, "layer": "user-global"}, + ) + warnings = [w for w in d["_warnings"] if str(paths["user"]) in w] + self.assertEqual(len(warnings), 1, d["_warnings"]) + self.assertIn("userConfig", warnings[0]) + def test_all_layers_absent_is_the_bundled_defaults(self) -> None: with tempfile.TemporaryDirectory() as tmp: result = run("--home", tmp, "--repo-root", tmp) diff --git a/plugins/code-metrics/skills/audit-coverage/SKILL.md b/plugins/code-metrics/skills/audit-coverage/SKILL.md index c2ea5c3f2a5..7e6aefa4964 100644 --- a/plugins/code-metrics/skills/audit-coverage/SKILL.md +++ b/plugins/code-metrics/skills/audit-coverage/SKILL.md @@ -146,8 +146,8 @@ does not land on one of the well-known names. ## Configuration -Everything tunable resolves through the code-metrics layers (user-global, team -`docs/conventions/code-metrics.yaml`, personal override; per-key override; keys in `${CLAUDE_PLUGIN_ROOT}/reference/config.md`): +Everything tunable resolves through the code-metrics layers (team +`docs/conventions/code-metrics.yaml`, personal override `docs/conventions/code-metrics.local.yaml`; per-key override; keys in `${CLAUDE_PLUGIN_ROOT}/reference/config.md`): | Key | Default | Effect | |---|---|---| diff --git a/plugins/code-metrics/skills/audit-duplication/SKILL.md b/plugins/code-metrics/skills/audit-duplication/SKILL.md index 65168ac3e21..768701f6bfd 100644 --- a/plugins/code-metrics/skills/audit-duplication/SKILL.md +++ b/plugins/code-metrics/skills/audit-duplication/SKILL.md @@ -115,8 +115,8 @@ your notes and compare by hand. ## Configuration -Everything tunable resolves through the code-metrics layers (user-global, team -`docs/conventions/code-metrics.yaml`, personal override; per-key override; keys in `${CLAUDE_PLUGIN_ROOT}/reference/config.md`): +Everything tunable resolves through the code-metrics layers (team +`docs/conventions/code-metrics.yaml`, personal override `docs/conventions/code-metrics.local.yaml`; per-key override; keys in `${CLAUDE_PLUGIN_ROOT}/reference/config.md`): `duplication.min_tokens` (default 50), `duplication.min_lines` (default 5), `duplication.ignore` (globs handed to the detector's own ignore option), `duplication.max_size` (default `1mb`, binary units; a larger file is left out of the scan and reported), `duplication.max_lines` diff --git a/plugins/code-metrics/skills/audit/actions/complexity.md b/plugins/code-metrics/skills/audit/actions/complexity.md index 6d6823b1771..2a0b45ceaac 100644 --- a/plugins/code-metrics/skills/audit/actions/complexity.md +++ b/plugins/code-metrics/skills/audit/actions/complexity.md @@ -78,8 +78,8 @@ you, and why no threshold here is a verdict. ## Configuration -Everything tunable resolves through the code-metrics layers (user-global, team -`docs/conventions/code-metrics.yaml`, personal override; per-key override; keys in `/reference/config.md`): the three +Everything tunable resolves through the code-metrics layers (team +`docs/conventions/code-metrics.yaml`, personal override `docs/conventions/code-metrics.local.yaml`; per-key override; keys in `/reference/config.md`): the three references above, scope exclusions (`scope.exclude`, which by default drops `node_modules`, `vendor`, `dist`, and `build` directories at any depth and reports each pattern's count), sanctioned-replication registries (`scope.registries`), the base ref (`scope.base`), and the diff --git a/plugins/code-metrics/skills/audit/actions/size.md b/plugins/code-metrics/skills/audit/actions/size.md index 31cfda19bb7..6a86b34b1e1 100644 --- a/plugins/code-metrics/skills/audit/actions/size.md +++ b/plugins/code-metrics/skills/audit/actions/size.md @@ -129,8 +129,8 @@ here is in scope, unlike the long file met in passing under "Acting on a long fi ## Configuration -Everything tunable resolves through the code-metrics layers (user-global, team -`docs/conventions/code-metrics.yaml`, personal override; per-key override; keys in `/reference/config.md`): the reference +Everything tunable resolves through the code-metrics layers (team +`docs/conventions/code-metrics.yaml`, personal override `docs/conventions/code-metrics.local.yaml`; per-key override; keys in `/reference/config.md`): the reference (`size.file_lines`), the check rule (`size.check`, above), the mode (`size.mode`: `file-lines`, or `iso-8.2.115`, which adds a `function_lines` measure comparing each function's non-empty lines against `size.function_lines_pct` of the file's, from a collector that reports function ranges such as diff --git a/plugins/code-metrics/skills/audit/actions/type-debt.md b/plugins/code-metrics/skills/audit/actions/type-debt.md index b3040fbf55e..0995e2c847d 100644 --- a/plugins/code-metrics/skills/audit/actions/type-debt.md +++ b/plugins/code-metrics/skills/audit/actions/type-debt.md @@ -65,8 +65,8 @@ your notes and compare by hand. ## Configuration -Everything tunable resolves through the code-metrics layers (user-global, team -`docs/conventions/code-metrics.yaml`, personal override; +Everything tunable resolves through the code-metrics layers (team +`docs/conventions/code-metrics.yaml`, personal override `docs/conventions/code-metrics.local.yaml`; per-key override; keys in `/reference/config.md`): the reference (`type_debt.reference`, `null` by default), scope exclusions (`scope.exclude`), a per-lane opt-out (`lanes..enabled: false`, which drops that lane even under `--all`), and the per-lane diff --git a/plugins/code-metrics/skills/audit/scripts/audit-size.test.sh b/plugins/code-metrics/skills/audit/scripts/audit-size.test.sh index c3e2d5938c4..0ab34f51eed 100755 --- a/plugins/code-metrics/skills/audit/scripts/audit-size.test.sh +++ b/plugins/code-metrics/skills/audit/scripts/audit-size.test.sh @@ -116,12 +116,26 @@ out="$(gate --check --all)" assert_eq "--check over --all cannot decide (exit 2)" 2 "$?" assert_contains "--check over --all says it needs the change scope" "$out" "needs the change scope" -printf '.claude/\n' >"$GATE/.gitignore" -printf 'size:\n check: report\n' >"$GATE/.claude/code-metrics.local.yaml" +printf '.claude/\ndocs/conventions/**/*.local.*\n' >"$GATE/.gitignore" +printf 'size:\n check: report\n' >"$GATE/docs/conventions/code-metrics.local.yaml" out="$(gate --check)" assert_eq "a personal override of report wins over the team rule (exit 0)" 0 "$?" assert_contains "the report names the personal layer" "$out" "\`size.check\` is \`report\` (local)" -rm -f "$GATE/.claude/code-metrics.local.yaml" "$GATE/.gitignore" +case "$out" in +*"old personal override"*) fail "the new personal file alone prints no old-path warning" "no warning" "$out" ;; +*) pass "the new personal file alone prints no old-path warning" ;; +esac +rm -f "$GATE/docs/conventions/code-metrics.local.yaml" +printf 'size:\n check: report\n' >"$GATE/.claude/code-metrics.local.yaml" +out="$(gate --check)" +assert_eq "an old personal file alone still applies (exit 0)" 0 "$?" +assert_contains "an old personal file alone is named with its new location" "$out" "/.claude/code-metrics.local.yaml is the old personal override, still read as the personal layer; move it to " +printf 'size:\n check: crossing-or-growth\n' >"$GATE/.claude/code-metrics.local.yaml" +printf 'size:\n check: report\n' >"$GATE/docs/conventions/code-metrics.local.yaml" +out="$(gate --check)" +assert_eq "with both personal files the new one wins (exit 0)" 0 "$?" +assert_contains "with both personal files the warning names both" "$out" "/docs/conventions/code-metrics.local.yaml exists" +rm -f "$GATE/.claude/code-metrics.local.yaml" "$GATE/docs/conventions/code-metrics.local.yaml" "$GATE/.gitignore" team $' file_lines: 50\n check: crossing\n' gate --check >/dev/null diff --git a/plugins/code-metrics/skills/principles/reference/thresholds.md b/plugins/code-metrics/skills/principles/reference/thresholds.md index 1fe989252bb..5202cad5543 100644 --- a/plugins/code-metrics/skills/principles/reference/thresholds.md +++ b/plugins/code-metrics/skills/principles/reference/thresholds.md @@ -87,8 +87,8 @@ them argue against it directly. ## Setting your own -Every reference resolves across three layers, user-global (`~/.claude/code-metrics.yaml`) then -team (`docs/conventions/code-metrics.yaml`) then personal override, with per-key override: setting one key replaces that value and leaves the +Every reference resolves across two file layers, team (`docs/conventions/code-metrics.yaml`) then +personal override (`docs/conventions/code-metrics.local.yaml`), with per-key override: setting one key replaces that value and leaves the rest of the defaults intact. The full key list is [`reference/config.md`](../../../reference/config.md), and `/code-metrics:setup` writes the team file and probes the collectors. The report prints the layer that supplied any value a personal layer changed, so a number that differs from a teammate's is diff --git a/plugins/code-metrics/skills/setup/SKILL.md b/plugins/code-metrics/skills/setup/SKILL.md index 23ccfeac7e2..b3c0d790c92 100644 --- a/plugins/code-metrics/skills/setup/SKILL.md +++ b/plugins/code-metrics/skills/setup/SKILL.md @@ -1,5 +1,5 @@ --- -description: "Verify or configure the code-metrics plugin for this repository: `check` probes the interpreter, every configuration layer (user-global, team, personal override, and the consumer's ecosystem files) for the YAML subset and the tracked-file guard, prints every reference with the layer that supplied it, and runs each collector adapter's probe and one measure on a bundled fixture (a version and the measure, or missing with its install hint); `apply` writes the tracked `docs/conventions/code-metrics.yaml` team layer per key, carrying every declared key of a retired `.claude/code-metrics.yaml`, idempotently, never installing a tool and never editing `.gitignore`. Use when: 'set up code-metrics', 'configure code metrics', 'is code-metrics configured', 'which collectors are installed', 'set the cyclomatic reference', 'change the file length reference', 'code-metrics setup', or an audit skill reports a configuration layer it could not read." +description: "Verify or configure the code-metrics plugin for this repository: `check` probes the interpreter, every configuration layer (team, personal override, old files still read, and the consumer's ecosystem files) for the YAML subset and the tracked-file guard, prints every reference with the layer that supplied it, and runs each collector adapter's probe and one measure on a bundled fixture (a version and the measure, or missing with its install hint); `apply` writes the tracked `docs/conventions/code-metrics.yaml` team layer per key, carrying every declared key of a retired `.claude/code-metrics.yaml`, and copies old personal files after a preview, idempotently, never installing a tool and never editing `.gitignore`. Use when: 'set up code-metrics', 'configure code metrics', 'is code-metrics configured', 'which collectors are installed', 'set the cyclomatic reference', 'change the file length reference', 'code-metrics setup', or an audit skill reports a configuration layer it could not read." argument-hint: "[check|apply] [= ...]" user-invocable: true disable-model-invocation: true @@ -10,17 +10,18 @@ shell: bash ## Purpose Every reference the plugin prints, every lane's collector order, the scope exclusions, and the -coverage artifact paths resolve through one consumer surface, layered as user-global -(`~/.claude/code-metrics.yaml`), team (`docs/conventions/code-metrics.yaml`, tracked; schema -`${CLAUDE_PLUGIN_ROOT}/schemas/code-metrics.schema.json`), and personal override -(`.claude/code-metrics.local.yaml`, gitignored) with per-key override. The team file of earlier -releases, `.claude/code-metrics.yaml`, is retired and never read; `apply` moves its keys. All three layers absent is -a valid state: every key has a bundled default. This skill is the check-centric setup for that -surface and for the external collectors the audits probe: `check` inspects and verifies, `apply` -persists, and neither installs anything. Keys, defaults, and provenance: -`${CLAUDE_PLUGIN_ROOT}/reference/config.md`. - -This plugin still reads, or reports as retired, the `.claude/` paths named here; until the plugin migrates, keep config where this page says it is read, then move it where [config locations](../../reference/config-locations.md) says. +coverage artifact paths resolve through one consumer surface, layered as team +(`docs/conventions/code-metrics.yaml`, tracked; schema +`${CLAUDE_PLUGIN_ROOT}/schemas/code-metrics.schema.json`) and personal override +(`docs/conventions/code-metrics.local.yaml`, gitignored) with per-key override; the plugin has no +`userConfig` option ([config locations](../../reference/config-locations.md)). The team file of +earlier releases, `.claude/code-metrics.yaml`, is retired and never read; `apply` moves its keys. +The old user-global `~/.claude/code-metrics.yaml` and personal `.claude/code-metrics.local.yaml` +are still read during the dual-read window, each named in a warning on every run; `apply --copy-old` +copies their keys. Every layer absent is a valid state: every key has a bundled default. This +skill is the check-centric setup for that surface and for the external collectors the audits probe: +`check` inspects and verifies, `apply` persists, and neither installs anything. Keys, defaults, +provenance, and the dual-read window: `${CLAUDE_PLUGIN_ROOT}/reference/config.md`. Action routing: no argument or `check` runs the check; `apply` runs the check first, then persists. `apply` is non-interactive when complete `=` arguments are supplied @@ -39,18 +40,23 @@ Rows, each PASS, FAIL, WARN, or INFO: 1. **python**: the interpreter resolved (`python3`, `python`, or `py -3`) and the plugin's floor. FAIL stops the table: Python is required for correctness, so name the remediation. -2. **layer user-global / team / local**: absent (INFO), or present and parsed in the YAML subset - the plugin reads (block mappings, block sequences, flow sequences of scalars, scalars, - comments). A flow mapping, anchor, tag, or block scalar is FAIL with its line; the operator - rewrites the file in block style. +2. **layer userConfig / user-global / team / local**: `userConfig` is INFO (the plugin declares + no option). Each file layer is absent (INFO), or present and parsed in the YAML subset the + plugin reads (block mappings, block sequences, flow sequences of scalars, scalars, comments). A + flow mapping, anchor, tag, or block scalar is FAIL with its line; the operator rewrites the file + in block style. `user-global` appears only while the old `~/.claude/code-metrics.yaml` exists. **layer team location** is WARN when the retired `.claude/code-metrics.yaml` exists: the plugin does not read it, so `apply` moves its keys, or, once the docs file exists, the operator deletes it. + **layer user-global location** and **layer local location** are WARN when an old + `~/.claude/code-metrics.yaml` or `.claude/code-metrics.local.yaml` exists, naming the file and + whether it is still read; `apply --copy-old` copies its keys. 3. **layer team tracked**: `git check-ignore -v` on the team file reports no match (a match is FAIL with the rule: an ignored team layer never reaches the team) and `git ls-files --error-unmatch` sees it (untracked is WARN: written but uncommitted). -4. **layer local ignored**: the personal override is gitignored, else WARN with the recommended consumer - line `.claude/**/*.local.*`. Recommend the line; never edit the consumer's `.gitignore`. +4. **layer local ignored**: the personal override is gitignored, else WARN with the recommended + consumer line `docs/conventions/**/*.local.*` (`.claude/**/*.local.*` for an old personal file + still read). Recommend the line; never edit the consumer's `.gitignore`. 5. **ecosystem `.yaml`**: each consumer ecosystem file parses. PASS when its lane is in the resolved `lanes` mapping (a bundled lane, or one a layer lists): its `globs` and `enabled` override lane detection. WARN naming the missing `lanes.` entry when no layer lists the @@ -98,7 +104,23 @@ Exit 0 with no FAIL row, 1 with one, 2 on a usage or environment error. tell the operator to delete it. A symlinked, hard-linked or non-regular target or retired file, or a symlinked `docs/`, `docs/conventions/` or `.claude/`, is refused with exit 1 and nothing written. -4. **Verify.** Re-run `check`; report the persisted values from its table, never from the write +4. **Copy old personal files.** When `check` shows a **layer user-global location** or **layer + local location** row, offer the copy. Preview it first and show the operator every line: + + ```bash + "${CLAUDE_SKILL_DIR}/scripts/setup-apply.py" --copy-old --preview + ``` + + Each key prints as `copy:` or `not copied:` with its file and reason. Every key of the old + `.claude/code-metrics.local.yaml` is copied. A key of the old user-global file is not copied when + the team file sets it, since the team file already wins over that file and the personal override + would win over the team. A key the personal override already sets is kept. On an explicit yes, + run the same command without `--preview`, which writes + `docs/conventions/code-metrics.local.yaml` and leaves the old files in place. The old + `.claude/code-metrics.local.yaml` is the operator's to delete once `check` shows the values they + expect. The old user-global file applies to every repository: tell the operator to keep it until + each repository that relies on it has run the copy. Without a yes, write nothing. +5. **Verify.** Re-run `check`; report the persisted values from its table, never from the write alone. The tracked-file pair decides the outcome: a WARN `written but untracked` means "commit it to share with the team", never success; an ignored team file is FAIL and the operator's `.gitignore` is theirs to fix. @@ -112,7 +134,8 @@ bundled default. ## What this skill does not do - Install, download, or `npx`-fetch a collector. It prints install hints; the operator installs. -- Write the user-global or local layers. Those are personal files the operator edits. +- Write the personal override except through `apply --copy-old` after a preview and a yes, or + touch an old file. Personal files are the operator's to edit and delete. - Write Claude Code user settings or `pluginConfigs`; the plugin has no `userConfig`. - Edit the consumer's `.gitignore`; it recommends the one recursive line. - Run an audit. The audit skills read the same resolved document at run time. diff --git a/plugins/code-metrics/skills/setup/evals/evals.json b/plugins/code-metrics/skills/setup/evals/evals.json index 2f4083550dd..f2cba1af71d 100644 --- a/plugins/code-metrics/skills/setup/evals/evals.json +++ b/plugins/code-metrics/skills/setup/evals/evals.json @@ -31,13 +31,13 @@ "id": 3, "name": "apply-without-arguments-interviews-one-key-at-a-time-and-never-touches-gitignore", "prompt": "/code-metrics:setup apply", - "expected_output": "Runs check, then interviews one key at a time with a recommendation first (the cyclomatic reference with its ISO citation and the two alternatives, the file-length reference with its plugin-default label, exclusions, lanes), preserves keys the existing file carries, writes only the team file, and recommends the .claude/**/*.local.* ignore line without editing .gitignore.", + "expected_output": "Runs check, then interviews one key at a time with a recommendation first (the cyclomatic reference with its ISO citation and the two alternatives, the file-length reference with its plugin-default label, exclusions, lanes), preserves keys the existing file carries, writes only the team file, and recommends the docs/conventions/**/*.local.* ignore line without editing .gitignore.", "files": [], "expectations": [ "Interviews one key at a time, leading with a recommendation and its provenance", "Preserves keys already present in the existing team file", - "Recommends the recursive .claude/**/*.local.* line rather than editing .gitignore", - "Writes only docs/conventions/code-metrics.yaml, never the user-global or local layers" + "Recommends the recursive docs/conventions/**/*.local.* line rather than editing .gitignore", + "Writes only docs/conventions/code-metrics.yaml, never the personal override or an old user-global or personal file" ] } ] diff --git a/plugins/code-metrics/skills/setup/scripts/setup-apply.py b/plugins/code-metrics/skills/setup/scripts/setup-apply.py index 5cc4b19799c..12a150afc19 100755 --- a/plugins/code-metrics/skills/setup/scripts/setup-apply.py +++ b/plugins/code-metrics/skills/setup/scripts/setup-apply.py @@ -2,6 +2,16 @@ """Write or update the consumer's team configuration file, idempotently. setup-apply.py [--dir | --file ] [=...] + setup-apply.py --copy-old [--preview] [--dir ] [--home ] + +`--copy-old` copies the old personal files into the personal override, +`/docs/conventions/code-metrics.local.yaml`: every key of +`/.claude/code-metrics.local.yaml`, and each key of the old +user-global `/.claude/code-metrics.yaml` the team file does not set +(`--home` defaults to $CODE_METRICS_HOME, else $HOME). A key the personal +override already sets is kept. Each key copied or not copied is printed with +its file; `--preview` prints the result and writes nothing. The old files are +left in place. The target is `/docs/conventions/code-metrics.yaml` (or `--file`); with neither option the root is what `git rev-parse --show-toplevel` reports @@ -43,7 +53,10 @@ from typing import Any, Callable MIN_PYTHON = (3, 9) -USAGE = " setup-apply.py [--dir | --file ] [=...]" +USAGE = ( + " setup-apply.py [--dir | --file ] [=...]\n" + " setup-apply.py --copy-old [--preview] [--dir ] [--home ]" +) HERE = os.path.dirname(os.path.abspath(__file__)) PLUGIN_ROOT = os.path.abspath(os.path.join(HERE, "..", "..", "..")) SCRIPTS = os.path.join(PLUGIN_ROOT, "scripts") @@ -58,10 +71,15 @@ HEADER = ( "# code-metrics configuration (team layer). Contract: the plugin's reference/config.md;\n" "# schema: the plugin's schemas/code-metrics.schema.json.\n" - "# Layers: ~/.claude/code-metrics.yaml, this file, .claude/code-metrics.local.yaml (per-key override).\n" + "# Layers: this file, then docs/conventions/code-metrics.local.yaml (per-key override).\n" +) +PERSONAL_HEADER = ( + "# code-metrics personal override (gitignored). Contract: the plugin's reference/config.md.\n" + "# Layers: docs/conventions/code-metrics.yaml, then this file (per-key override).\n" ) TEAM_PARTS = ["docs", "conventions"] TEAM_FILE = os.path.join(*TEAM_PARTS, "code-metrics.yaml") +PERSONAL_NAME = "code-metrics.local.yaml" LEGACY_FILE = os.path.join(".claude", "code-metrics.yaml") NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) @@ -286,13 +304,149 @@ def write_file(target: str, text: str, recheck: Callable[[], bool]) -> None: raise +def _leaves(node: Any, prefix: str = "") -> dict[str, Any]: + """Every leaf of a mapping by dotted key; a list is one closed value.""" + out: dict[str, Any] = {} + for key, value in (node or {}).items(): + dotted = f"{prefix}.{key}" if prefix else str(key) + if isinstance(value, dict) and value: + out.update(_leaves(value, dotted)) + else: + out[dotted] = value + return out + + +def _git_root() -> str: + try: + probe = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + capture_output=True, + text=True, + check=False, + ) + top = probe.stdout.strip() if probe.returncode == 0 else "" + except OSError: + top = "" + return top or os.getcwd() + + +def copy_old(root: str, home: str, preview: bool) -> int: + """Copy the old user-global and personal files into the personal override. + + The old `.claude/code-metrics.local.yaml` keys are copied whole. A key of + the old user-global file is copied unless the team file sets it, since the + team layer already wins over that file and the personal override would + win over the team. Keys the personal override already sets are kept. The + old files are left in place. With `preview`, nothing is written. + """ + real_root = os.path.realpath(root) + old_user = os.path.join(home, ".claude", "code-metrics.yaml") + old_local = os.path.join(root, ".claude", PERSONAL_NAME) + target = os.path.join(root, *TEAM_PARTS, PERSONAL_NAME) + + def check_target() -> bool: + return check_chain(root, real_root, TEAM_PARTS, PERSONAL_NAME) + + try: + user_doc = ( + read_mapping(old_user)[1] if check_file(old_user, old_user, None) else None + ) + local_doc = ( + read_mapping(old_local)[1] + if check_chain(root, real_root, [".claude"], PERSONAL_NAME) + else None + ) + team_doc = ( + read_mapping(os.path.join(root, TEAM_FILE))[1] + if check_chain(root, real_root, TEAM_PARTS, "code-metrics.yaml") + else {} + ) + existing_text, existing = read_mapping(target) if check_target() else ("", {}) + except (UnsafePath, OSError) as exc: + print(f"setup-apply.py: {exc}; nothing written", file=sys.stderr) + return 1 + except ValueError_ as exc: + print(f"setup-apply.py: {exc}", file=sys.stderr) + return 2 + if user_doc is None and local_doc is None: + print(f"no old file found ({old_user}, {old_local}); nothing to copy") + return 0 + def setter(keys: dict[str, Any], key: str) -> str | None: + return next((k for k in keys if key == k or key.startswith(k + ".")), None) + + team_keys = _leaves(team_doc) + kept = _leaves(existing) + doc: dict[str, Any] = {} + lines: list[str] = [] + for source, layer_doc in ((old_user, user_doc), (old_local, local_doc)): + for key, value in _leaves(layer_doc).items(): + shadow = setter(team_keys, key) if source == old_user else None + if shadow is not None: + lines.append( + f"not copied: {key} from {source}: the team file sets {shadow}, " + "which already wins over the user-global file" + ) + elif setter(kept, key) is not None: + lines.append(f"not copied: {key} from {source}: {target} already sets it") + else: + set_dotted(doc, key, value) + lines.append(f"copy: {key} from {source}") + for key, value in kept.items(): + set_dotted(doc, key, value) + if lines: + print("\n".join(lines)) + if existing_text and yaml_subset.parse(existing_text) == doc: + print(f"already configured: {target}") + return 0 + if not doc: + print("nothing to copy") + return 0 + body = "\n".join(dump(doc)) + "\n" + if preview: + print(f"preview, nothing written: {target} would read:\n{PERSONAL_HEADER}{body}") + return 0 + try: + for depth in range(1, len(TEAM_PARTS) + 1): + rel = os.path.join(*TEAM_PARTS[:depth]) + if not check_dir(os.path.join(root, rel), rel, real_root): + os.mkdir(os.path.join(root, rel)) + check_target() + write_file(target, PERSONAL_HEADER + body, check_target) + except (UnsafePath, OSError) as exc: + print(f"setup-apply.py: {exc}; nothing written", file=sys.stderr) + return 1 + print(f"written: {target}") + if os.path.isfile(old_user): + print( + f"left in place: {old_user}; it applies to every repository, so keep it " + "until each repository that relies on it has run --copy-old" + ) + if os.path.isfile(old_local): + print(f"left in place: {old_local}; delete it once check shows the values you expect") + return 0 + + def main(argv: list[str]) -> int: target = None root: str | None = None + home = os.environ.get("CODE_METRICS_HOME") or os.environ.get("HOME") or "/" + copy_mode = preview = False assignments: list[str] = [] i = 0 while i < len(argv): arg = argv[i] + if arg in ("--copy-old", "--preview"): + copy_mode = copy_mode or arg == "--copy-old" + preview = preview or arg == "--preview" + i += 1 + continue + if arg == "--home": + if i + 1 >= len(argv): + print("setup-apply.py: --home needs a value", file=sys.stderr) + return 2 + home = argv[i + 1] + i += 2 + continue if arg in ("--dir", "--file"): if i + 1 >= len(argv): print(f"setup-apply.py: {arg} needs a value", file=sys.stderr) @@ -316,20 +470,22 @@ def main(argv: list[str]) -> int: return 2 assignments.append(arg) i += 1 + if copy_mode or preview: + file_given = target is not None and ( + root is None + or os.path.abspath(target) != os.path.abspath(os.path.join(root, TEAM_FILE)) + ) + if not copy_mode or assignments or file_given: + print( + "setup-apply.py: --copy-old [--preview] takes only --dir and --home", + file=sys.stderr, + ) + return 2 + return copy_old(root or _git_root(), home, preview) if target is None: # No --dir: the repository root when git resolves one, else the cwd, # so the skill needs no command substitution in its allowed command. - try: - probe = subprocess.run( - ["git", "rev-parse", "--show-toplevel"], - capture_output=True, - text=True, - check=False, - ) - top = probe.stdout.strip() if probe.returncode == 0 else "" - except OSError: - top = "" - root = top or os.getcwd() + root = _git_root() target = os.path.join(root, TEAM_FILE) real_root = os.path.realpath(root) if root is not None else "" team = root is not None and os.path.abspath(target) == os.path.abspath( diff --git a/plugins/code-metrics/skills/setup/scripts/setup-check.sh b/plugins/code-metrics/skills/setup/scripts/setup-check.sh index a4d39f2e60b..2b6f0632768 100755 --- a/plugins/code-metrics/skills/setup/scripts/setup-check.sh +++ b/plugins/code-metrics/skills/setup/scripts/setup-check.sh @@ -98,13 +98,22 @@ check_layer() { elif git -C "$REPO_ROOT" check-ignore -q "$rel" 2>/dev/null; then row PASS "layer $name ignored" "the personal override is gitignored" else - row WARN "layer $name ignored" "the personal override is NOT gitignored; recommended consumer .gitignore line: .claude/**/*.local.* (the plugin never edits your .gitignore)" + local line="docs/conventions/**/*.local.*" + [[ "$rel" == .claude/* ]] && line=".claude/**/*.local.*" + row WARN "layer $name ignored" "the personal override is NOT gitignored; recommended consumer .gitignore line: $line (the plugin never edits your .gitignore)" fi } -check_layer "user-global" "$HOME_DIR/.claude/code-metrics.yaml" n/a +old_user="$HOME_DIR/.claude/code-metrics.yaml" +old_local="$REPO_ROOT/.claude/code-metrics.local.yaml" +personal_file="$REPO_ROOT/docs/conventions/code-metrics.local.yaml" +row INFO "layer userConfig" "none: the plugin declares no userConfig option" +if [[ -f "$old_user" ]]; then + row WARN "layer user-global location" "$old_user is the old user-global file, still read below the team layer during the dual-read window; /code-metrics:setup apply --copy-old copies the keys this repository needs to $personal_file; keep the old file until each repository that relies on it has copied its keys" + check_layer "user-global" "$old_user" n/a +fi team_file="$REPO_ROOT/docs/conventions/code-metrics.yaml" retired_file="$REPO_ROOT/.claude/code-metrics.yaml" -if [[ -f "$retired_file" && ! "$retired_file" -ef "$HOME_DIR/.claude/code-metrics.yaml" ]]; then +if [[ -f "$retired_file" && ! "$retired_file" -ef "$old_user" ]]; then if [[ -f "$team_file" ]]; then row WARN "layer team location" "$retired_file is the retired team file and is not read; delete it" else @@ -112,7 +121,24 @@ if [[ -f "$retired_file" && ! "$retired_file" -ef "$HOME_DIR/.claude/code-metric fi fi check_layer "team" "$team_file" yes -check_layer "local" "$REPO_ROOT/.claude/code-metrics.local.yaml" no +if [[ -f "$old_local" && -f "$personal_file" ]]; then + # The resolver keeps reading the old file while the new one is outside the + # YAML subset (resolve-config.py surface_layer_paths), so both are checked. + # Dual-read window: https://github.com/melodic-software/claude-code-plugins/issues/18001 + if "${PY[@]}" "$SCRIPTS/yaml_subset.py" "$personal_file" >/dev/null 2>&1; then + row WARN "layer local location" "$old_local is the old personal override and is not read because $personal_file exists; delete it once its keys are there" + check_layer "local" "$personal_file" no + else + row WARN "layer local location" "$old_local is the old personal override, still read because $personal_file is outside the YAML subset; fix $personal_file, then delete the old file" + check_layer "local" "$old_local" no + check_layer "local" "$personal_file" no + fi +elif [[ -f "$old_local" ]]; then + row WARN "layer local location" "$old_local is the old personal override, still read during the dual-read window; /code-metrics:setup apply --copy-old copies its keys to $personal_file" + check_layer "local" "$old_local" no +else + check_layer "local" "$personal_file" no +fi # The resolver reads an ecosystem record only for a lane in the resolved # `lanes` mapping whose id matches its LANE_ID pattern, so the configuration diff --git a/plugins/code-metrics/skills/setup/scripts/setup-check.test.sh b/plugins/code-metrics/skills/setup/scripts/setup-check.test.sh index 5221013ed6f..d7f7224fde2 100755 --- a/plugins/code-metrics/skills/setup/scripts/setup-check.test.sh +++ b/plugins/code-metrics/skills/setup/scripts/setup-check.test.sh @@ -46,7 +46,13 @@ trap 'rm -rf "$home" "$repo"' EXIT out="$(bash "$SCRIPT" --repo-root "$repo" --home "$home")" rc=$? assert_eq "no config exits 0" 0 "$rc" -assert_contains "user-global layer absent" "$out" "INFO layer user-global" +assert_contains "the userConfig layer is named" "$out" "INFO layer userConfig" +if grep -q "layer user-global" <<<"$out"; then + fail "no old user-global file, no user-global row" "no layer user-global row" "$(printf '%s' "$out" | head -c 600)" +else + pass "no old user-global file, no user-global row" +fi +assert_row "the personal layer is the docs file" "$out" "INFO layer local +absent \($repo/docs/conventions/code-metrics.local.yaml\)" assert_contains "team layer absent" "$out" "INFO layer team" assert_row "bundled default reference" "$out" "reference file_lines +1000 \(layer: bundled default\)" adapters="$(find "$PLUGIN_ROOT/scripts/collectors" -maxdepth 1 -name '*.py' ! -name 'test_*' ! -name 'adapter_paths.py' | wc -l | tr -d ' ')" @@ -100,7 +106,35 @@ rc=$? assert_eq "ignored team file exits 1" 1 "$rc" assert_contains "ignored team file fails" "$out" "FAIL layer team tracked" assert_contains "unignored personal override warns with the gitignore line" "$out" ".claude/**/*.local.*" +assert_row "an old personal file alone is read and named" "$out" "WARN layer local location +$repo/.claude/code-metrics.local.yaml is the old personal override, still read" +assert_row "an old personal file alone supplies its values" "$out" "reference file_lines +7 \(layer: local\)" rm -f "$repo/.gitignore" +printf 'size:\n file_lines: 8\n' >"$repo/docs/conventions/code-metrics.local.yaml" +out="$(bash "$SCRIPT" --repo-root "$repo" --home "$home")" +assert_row "with both personal files the new one wins" "$out" "reference file_lines +8 \(layer: local\)" +assert_row "with both personal files the warning names both" "$out" "WARN layer local location +$repo/.claude/code-metrics.local.yaml is the old personal override and is not read because $repo/docs/conventions/code-metrics.local.yaml exists" +assert_contains "the new personal file warns with its gitignore line" "$out" "docs/conventions/**/*.local.*" +printf 'size: { file_lines: 1 }\n' >"$repo/docs/conventions/code-metrics.local.yaml" +out="$(bash "$SCRIPT" --repo-root "$repo" --home "$home")" +assert_row "a new personal file outside the subset leaves the old one read" "$out" "WARN layer local location +$repo/.claude/code-metrics.local.yaml is the old personal override, still read because $repo/docs/conventions/code-metrics.local.yaml is outside the YAML subset" +assert_row "the old personal file read in its place is parse-checked" "$out" "PASS layer local +$repo/.claude/code-metrics.local.yaml parses" +assert_row "the new personal file outside the subset fails" "$out" "FAIL layer local +$repo/docs/conventions/code-metrics.local.yaml is outside the YAML subset" +assert_row "the old personal file supplies its values" "$out" "reference file_lines +7 \(layer: local\)" +printf 'size:\n file_lines: 8\n' >"$repo/docs/conventions/code-metrics.local.yaml" +rm -f "$repo/.claude/code-metrics.local.yaml" +out="$(bash "$SCRIPT" --repo-root "$repo" --home "$home")" +assert_row "the new personal file alone is read" "$out" "reference file_lines +8 \(layer: local\)" +if grep -q "layer local location" <<<"$out"; then + fail "the new personal file alone gets no old-path row" "no layer local location row" "$(printf '%s' "$out" | head -c 600)" +else + pass "the new personal file alone gets no old-path row" +fi +rm -f "$repo/docs/conventions/code-metrics.local.yaml" +mkdir -p "$home/.claude" +printf 'complexity:\n cyclomatic:\n reference: 11\n' >"$home/.claude/code-metrics.yaml" +out="$(bash "$SCRIPT" --repo-root "$repo" --home "$home")" +assert_row "an old user-global file is named" "$out" "WARN layer user-global location +$home/.claude/code-metrics.yaml is the old user-global file, still read" +assert_row "an old user-global file supplies its values" "$out" "reference cyclomatic +11 \(layer: user-global\)" mkdir -p "$home/.claude" printf 'lanes:\n typescript: { enabled: true }\n' >"$home/.claude/code-metrics.yaml" diff --git a/plugins/code-metrics/skills/setup/scripts/test_setup_apply.py b/plugins/code-metrics/skills/setup/scripts/test_setup_apply.py index c1e0f702d0e..c21e7cd8d60 100755 --- a/plugins/code-metrics/skills/setup/scripts/test_setup_apply.py +++ b/plugins/code-metrics/skills/setup/scripts/test_setup_apply.py @@ -261,6 +261,100 @@ def test_unknown_carried_keys_are_dropped_and_named(self) -> None: self.assertIn("size.bogus", result.stderr) self.assertNotIn("gho_example", target.read_text(encoding="utf-8")) + def _old_layout(self, tmp: str) -> tuple[Path, Path, Path]: + home = Path(tmp) / "home" + root = Path(tmp) / "repo" + (home / ".claude").mkdir(parents=True) + (root / ".claude").mkdir(parents=True) + (root / "docs" / "conventions").mkdir(parents=True) + return home, root, root / "docs" / "conventions" / "code-metrics.local.yaml" + + def _resolve(self, home: Path, root: Path) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(RESOLVER), "--home", str(home), "--repo-root", str(root)], + capture_output=True, + text=True, + check=True, + ) + + def test_copy_old_previews_then_copies_and_leaves_the_old_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + home, root, personal = self._old_layout(tmp) + old_user = home / ".claude" / "code-metrics.yaml" + old_local = root / ".claude" / "code-metrics.local.yaml" + old_user.write_text( + "size:\n file_lines: 700\ncomplexity:\n cyclomatic:\n reference: 9\n", + encoding="utf-8", + ) + old_local.write_text("size:\n file_lines: 650\n", encoding="utf-8") + (root / "docs" / "conventions" / "code-metrics.yaml").write_text( + "complexity:\n cyclomatic:\n reference: 12\n", encoding="utf-8" + ) + before = self._resolve(home, root) + self.assertIn(str(old_user), before.stderr) + self.assertIn(str(old_local), before.stderr) + + preview = run("--copy-old", "--preview", "--dir", str(root), "--home", str(home)) + self.assertEqual(preview.returncode, 0, preview.stderr) + self.assertIn("preview, nothing written", preview.stdout) + self.assertFalse(personal.exists()) + + result = run("--copy-old", "--dir", str(root), "--home", str(home)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + yaml_subset.parse(personal.read_text(encoding="utf-8")), + {"size": {"file_lines": 650}}, + ) + self.assertIn( + f"not copied: complexity.cyclomatic.reference from {old_user}", + result.stdout, + ) + self.assertTrue(old_user.is_file() and old_local.is_file()) + self.assertIn( + f"left in place: {old_user}; it applies to every repository, so keep it", + result.stdout, + ) + self.assertIn(f"left in place: {old_local}; delete it once", result.stdout) + self.assertNotIn("and delete the old file", before.stderr) + + after = self._resolve(home, root) + + def strip(out: str) -> dict: + return {k: v for k, v in json.loads(out).items() if not k.startswith("_")} + + self.assertEqual(strip(after.stdout), strip(before.stdout)) + self.assertIn(str(personal), after.stderr) + self.assertIn("is not read because", after.stderr) + + again = run("--copy-old", "--dir", str(root), "--home", str(home)) + self.assertIn("already configured", again.stdout) + + def test_copy_old_keeps_keys_the_personal_override_sets(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + home, root, personal = self._old_layout(tmp) + (root / ".claude" / "code-metrics.local.yaml").write_text( + "size:\n file_lines: 650\n mode: iso-8.2.115\n", encoding="utf-8" + ) + personal.write_text("size:\n file_lines: 600\n", encoding="utf-8") + result = run("--copy-old", "--dir", str(root), "--home", str(home)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + yaml_subset.parse(personal.read_text(encoding="utf-8")), + {"size": {"file_lines": 600, "mode": "iso-8.2.115"}}, + ) + self.assertIn("size.file_lines", result.stdout) + self.assertIn("already sets it", result.stdout) + + def test_copy_old_with_no_old_file_writes_nothing(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + home, root, personal = self._old_layout(tmp) + result = run("--copy-old", "--dir", str(root), "--home", str(home)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("no old file found", result.stdout) + self.assertFalse(personal.exists()) + self.assertEqual(run("--copy-old", "size.file_lines=1").returncode, 2) + self.assertEqual(run("--preview", "--dir", str(root)).returncode, 2) + def test_help_prints_usage_even_with_docstrings_stripped(self) -> None: # python -OO drops __doc__, which --help printed. result = subprocess.run( diff --git a/plugins/code-metrics/skills/setup/templates/config-template.yaml b/plugins/code-metrics/skills/setup/templates/config-template.yaml index c8f5b8e4193..2caedad8090 100644 --- a/plugins/code-metrics/skills/setup/templates/config-template.yaml +++ b/plugins/code-metrics/skills/setup/templates/config-template.yaml @@ -3,8 +3,9 @@ # key keeps the bundled default. Written in the YAML subset the plugin reads: # block mappings, block sequences, flow sequences of scalars, scalars, and # comments (no flow mappings, anchors, tags, or block scalars). Layers: -# ~/.claude/code-metrics.yaml, this file, .claude/code-metrics.local.yaml, -# merged per key. Keys and provenance: the plugin's reference/config.md. +# this file, then docs/conventions/code-metrics.local.yaml, merged per key +# (https://github.com/melodic-software/claude-code-plugins/blob/main/docs/contracts/config-cascade/README.md#the-layers). +# Keys and provenance: the plugin's reference/config.md. scope: default: change # change | all