Skip to content

validate-pins.py rechecks a declared neutral-product pin's referent - #15

Merged
brettheap merged 1 commit into
mainfrom
neutral-pin-recheck-and-leg-gitignores
Sep 4, 2026
Merged

brettheap merged 1 commit into
mainfrom
neutral-pin-recheck-and-leg-gitignores

Conversation

@brettheap

@brettheap brettheap commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Lane: repo-shape

What

Today validate-pins.py rechecks the spec, code and shape pins on every run
but never rechecks a neutral-product pin a declared descendant carries
(neutral_product_pins: in project.yaml, e.g. contracts/openglass-pin.yaml
written by scaffold-project.py --pin openGlass@<sha>). A claim of descent
(<Domainx><Product> descends from open<Product> only because it pins it —
Brett Heap, 2026-09-02) was therefore checked once, at scaffold time, and
never again.

How the digest is recomputed, and from what

For each neutral_product_pins: entry, validate-pins.py locates
contracts/<product lowercased>-pin.yaml, verifies commit is 40 hex and
revision_kind: commit, then recomputes the sorted-ls-tree-r-v1 digest
exactly the way scaffold-project.py --pin computed it originally:

  1. Offline, from a local checkout, tried in order: --pin-source PRODUCT=PATH (or a bare PATH when one declared pin has no more specific
    answer), SHAPE_PIN_SOURCE_<PRODUCT> in the environment, or a checkout
    sitting beside the assembly root and named for the pinned repository
    (opensoft/openGlass → ../openGlass).
  2. Else via gh api — repos/<repo>/git/trees/<commit>?recursive=1 — the
    new tree_digest_from_gh in scripts/repo_shape.py, which reads the exact
    same endpoint and computes the digest the exact same way
    pin_digest_from_gh in scaffold-project.py already does, so a re-check
    and the tool that wrote the pin agree by construction.
  3. Else a named SKIP, never a failure — a project with no reachable
    checkout of its referent and no gh answer is not thereby lying about its
    descent. Success prints ok openGlass: pin commit <sha> digest recomputes (<how>); a mismatch is FINDING neutral-pin-digest-mismatch.

Wired into bootstrap.py's pin section for free: bootstrap.py already runs
scripts/validate-pins.py as a subprocess and inherits its stdout/stderr, so
no code change was needed there — verified by running bootstrap.py against
a freshly scaffolded pinned project (see test output below).

.gitignore for the leg templates

Added .gitignore to templates/code-root/ and templates/spec-root/
(Python + editor/OS noise for code; editor/OS noise only for spec) so a
freshly scaffolded leg doesn't go dirty with __pycache__/ after its first
validate run. Both templates are copied generically by
shape_materialize.copy_tree (no explicit per-file list, unlike the
assembly-root template's TEMPLATED/COPIED_VERBATIM/NEUTRAL_PIN_TEMPLATE
lists) into a directory scaffold-project.py builds itself — there is no
collision to arbitrate for these two, because adopt-project.py never
touches templates/code-root/ or templates/spec-root/ at all: an adopted
project's spec and code legs are extracted from the source repository's own
history, not materialized from these templates.

Tests

tests/test_neutral_pin_validator.py (new, 11 tests): recompute from a bare
--pin-source, a keyed PRODUCT=PATH one, the env var, and a sibling
checkout; a digest mismatch and an unreadable explicit source as findings; a
non-hex commit and a missing pin file as refusals; a bad revision_kind as a
finding; a project with no declared pins unaffected; and the
no-source-available case skipped via a stubbed gh binary — fully offline,
mirroring how test_scaffold_pin_and_reuse.py already stubs gh for the
scaffold's own unreadable-pin case.

python3 -m pytest tests -q
266 passed

Notes

  • README.md documents the recheck; its length cap moves 388 → 401 in
    tests/test_repo_hygiene.py, following the same pattern as its seven prior
    moves (a cap that grows for a rule the standard actually gained).
  • Since templates/assembly-root/scripts/validate-pins.py is copied verbatim
    into every scaffolded project, this bumps that file's sha256 in a project's
    own contracts/shape-pin.yaml. Adopted and scaffolded projects pick this
    check up on their next update-shape.py apply, not before.
  • No changes to scaffold-project.py itself — its own pin_digest_from_gh
    and tests are untouched; the shared gh-api digest logic was added
    net-new to repo_shape.py (tree_digest_from_gh) rather than refactored
    out of the scaffold, to keep this change isolated to the re-check surface.

🤖 Generated with Claude Code

https://claude.ai/code/session_015WekBEXf55Xv64psGe5t3T

Summary by Sourcery

Recheck neutral-product pin referents during pin validation so declared descent claims remain verifiable over time.

New Features:

  • Recheck declared neutral-product pin referents by validating their commit metadata and recomputed tree digests from local checkouts or GitHub.
  • Support explicit, environment-based, and sibling-checkout sources for offline neutral-product pin validation, with named skips when no source is available.

Bug Fixes:

  • Detect neutral-product pin drift that could previously go unnoticed after the initial scaffold-time validation.

Enhancements:

  • Add shared GitHub recursive-tree digest computation and ignore files to code and spec templates to prevent validation-generated workspace noise.

Documentation:

  • Document neutral-product pin referent rechecking and its offline, GitHub, and skip behavior.

Tests:

  • Add comprehensive tests covering neutral-product pin validation sources, drift, malformed pins, missing referents, skips, and unaffected projects.

`project.yaml`'s `neutral_product_pins:` is a claim of descent
(`<Domainx><Product>` descends from `open<Product>` only because it pins it,
Brett Heap 2026-09-02); until now nothing ever checked that claim again after
`scaffold-project.py --pin` first wrote it. `validate-pins.py` already
rechecks the spec, code and shape pins on every run — this extends the same
lockstep discipline to the neutral-product pins a descendant carries.

For each `neutral_product_pins:` entry it locates
`contracts/<product lowercased>-pin.yaml`, verifies `commit` is 40 hex and
`revision_kind: commit`, and recomputes the `sorted-ls-tree-r-v1` digest
EXACTLY the way the scaffold computed it in the first place:

  - offline from a local checkout, in order: `--pin-source PRODUCT=PATH`
    (or a bare PATH when one pin has no more specific answer),
    `SHAPE_PIN_SOURCE_<PRODUCT>` in the environment, or a checkout sitting
    beside the assembly root and named for the pinned repository;
  - else via `gh api repos/<repo>/git/trees/<commit>?recursive=1` (the new
    `tree_digest_from_gh` in repo_shape.py — the same shape of data
    `pin_digest_from_gh` in scaffold-project.py already reads, so a
    re-check and the tool that wrote the pin compute the same number);
  - else a named SKIP, never a failure — a project with no reachable
    checkout of its referent is not thereby lying about its descent.

A digest that recomputes differently is `FINDING neutral-pin-digest-mismatch`;
a missing pin file the declaration still names, a malformed commit, or a
source that cannot answer are reported the same way the leg and shape pins
already are (Refusal or FINDING, matching their severity).

Since `templates/assembly-root/scripts/validate-pins.py` is COPIED VERBATIM
into every scaffolded project, its sha256 in that project's
`contracts/shape-pin.yaml` moves — a scaffolded or adopted project picks up
this check on its next `update-shape.py apply`, not before.

Also adds `.gitignore` to `templates/code-root/` and `templates/spec-root/`
(Python + editor/OS noise; spec gets editor/OS noise only) so a freshly
scaffolded leg does not go dirty with `__pycache__/` after its first
validate run. Both templates are materialized by `copy_tree` generically
(no explicit per-file list, unlike the assembly-root template) into a
directory `scaffold-project.py` built itself, so there is no collision to
arbitrate — `adopt-project.py` never touches these two templates at all,
since an adopted project's spec and code legs are extracted from the
source repository's own history instead.

README.md documents the recheck; its own length cap moves 388 -> 401
(test_repo_hygiene.py) for the same reason it has moved seven times before:
prose earning its lines for a rule the standard actually gained.

Tests: tests/test_neutral_pin_validator.py — recompute from a bare
--pin-source, a keyed one, the env var, and a sibling checkout; a digest
mismatch and an unreadable explicit source as findings; a non-hex commit
and a missing pin file as refusals; a bad revision_kind as a finding; a
project with no declared pins unaffected; and the no-source-available case
skipped via a stubbed `gh` (offline, like the scaffold's own equivalent
test). `python3 -m pytest tests -q`: 266 passed.

Lane: repo-shape
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_015WekBEXf55Xv64psGe5t3T
Copilot AI lite review requested due to automatic review settings September 4, 2026 02:12
@sourcery-ai

sourcery-ai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR makes validate-pins.py continuously verify declared neutral-product pin referents, using an identical local or GitHub recursive-tree digest computation to scaffold-time pinning, while distinguishing actionable drift from unanswerable checks; it adds focused coverage, template hygiene, and documentation.

Sequence diagram for neutral-product pin revalidation

sequenceDiagram
    participant Validator as validate-pins.py
    participant Project as project.yaml
    participant Pin as neutral-product pin
    participant Source as Local checkout
    participant GitHub as gh api
    participant Digest as repo_shape.py

    Validator->>Project: load_yaml()
    Project-->>Validator: neutral_product_pins
    Validator->>Pin: load_yaml()
    Pin-->>Validator: commit, revision_kind, tree_sha256
    Validator->>Source: resolve_neutral_pin_source()
    alt local source available
        Source-->>Validator: checkout path
        Validator->>Digest: tree_digest()
    else no local source
        Validator->>GitHub: tree_digest_from_gh()
        GitHub-->>Validator: recursive tree JSON
        Validator->>Digest: compute sorted-ls-tree-r-v1 digest
    end
    alt digest matches
        Validator-->>Validator: Report.note()
    else digest differs
        Validator-->>Validator: Report.finding(neutral-pin-digest-mismatch)
    else no source or gh answer
        Validator-->>Validator: Report.skip()
    end
Loading

Flow diagram for neutral-product pin source resolution

flowchart TD
    A[Declared neutral_product_pins entry] --> B[Locate contracts/product-pin.yaml]
    B --> C{Pin metadata valid?}
    C -->|No| D[Refusal or finding]
    C -->|Yes| E{Explicit PRODUCT=PATH?}
    E -->|Yes| H[tree_digest from local checkout]
    E -->|No| F{SHAPE_PIN_SOURCE_PRODUCT?}
    F -->|Yes| H
    F -->|No| G{Sibling checkout exists?}
    G -->|Yes| H
    G -->|No| I{Bare --pin-source PATH?}
    I -->|Yes| H
    I -->|No| J[tree_digest_from_gh via gh api]
    H --> K{Digest matches recorded value?}
    J --> K
    K -->|Yes| L[Report ok]
    K -->|No| M[FINDING neutral-pin-digest-mismatch]
    J -->|No answer| N[Named SKIP]
Loading

File-Level Changes

Change Details Files
Extend pin validation to recheck each declared neutral-product pin's referent and tree digest.
  • Validate the referenced pin file, commit format, revision kind, digest definition, and recorded tree digest.
  • Resolve offline sources in explicit, environment, sibling-checkout, then GitHub API order.
  • Report digest drift as findings, malformed/missing metadata as findings or refusals, and unavailable sources as named skips.
  • Add CLI support for repeatable bare or product-keyed --pin-source options.
templates/assembly-root/scripts/validate-pins.py
Add GitHub recursive-tree digest computation shared by the validator's remote fallback.
  • Fetch repos/<repo>/git/trees/<commit>?recursive=1 with gh api.
  • Reproduce the sorted ls-tree digest format, retaining submodules and rejecting truncated or unreadable responses.
scripts/repo_shape.py
Cover the new validation behavior and keep generated project legs clean after validation.
  • Add 11 tests for local source resolution, mismatch and metadata handling, missing sources, skips, and unaffected projects.
  • Add language-appropriate ignore files to code and spec templates.
tests/test_neutral_pin_validator.py
templates/code-root/.gitignore
templates/spec-root/.gitignore
Document the neutral-product referent recheck and update the README hygiene limit.
  • Explain source precedence, GitHub fallback, skip semantics, and digest drift reporting.
  • Raise the tested README line cap to match the added documentation.
README.md
tests/test_repo_hygiene.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sonarqubecloud

sonarqubecloud Bot commented Sep 4, 2026

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="templates/assembly-root/scripts/validate-pins.py" line_range="322-330" />
<code_context>
+    env_value = os.environ.get(env_name)
+    if env_value:
+        return Path(env_value), f"${env_name}"
+    sibling = root.parent / repo_basename(repository)
+    if (sibling / ".git").exists():
+        return sibling, f"sibling checkout ({sibling})"
+    if default_source is not None:
+        return default_source, "--pin-source"
+    return None, None
+
</code_context>
<issue_to_address>
**issue (bug_risk):** A bare `--pin-source PATH` is ignored whenever the sibling checkout exists, because sibling resolution runs before the default source. The explicitly supplied checkout is therefore not used even though the documented lookup order gives `--pin-source` precedence over environment and sibling sources.

**Triggers:** When a bare `--pin-source` is supplied and a checkout named after the pinned repository also exists beside the assembly root.

**Suggested fix:** Check `default_source` before the environment and sibling fallbacks, or define and enforce that sibling resolution intentionally outranks a bare source.

```suggestion
    if default_source is not None:
        return default_source, "--pin-source"
    env_name = pin_source_env_name(product)
    env_value = os.environ.get(env_name)
    if env_value:
        return Path(env_value), f"${env_name}"
    sibling = root.parent / repo_basename(repository)
    if (sibling / ".git").exists():
        return sibling, f"sibling checkout ({sibling})"
```
</issue_to_address>

### Comment 2
<location path="scripts/repo_shape.py" line_range="547-549" />
<code_context>
+            f"the forge truncated its tree listing for {repository} @ "
+            f"{commit}, so the digest would be computed over a PARTIAL tree",
+        )
+    records = sorted(
+        f"{row['mode']} {row['type']} {row['sha']}\t{row['path']}".encode()
+        for row in payload.get("tree") or [] if row.get("type") != "tree")
+    digest = hashlib.sha256()
+    for record in records:
</code_context>
<issue_to_address>
**issue (bug_risk):** A syntactically valid but malformed `gh api` response crashes with `AttributeError` or `KeyError` when `payload` is not a mapping or a tree row lacks `mode`, `type`, `sha`, or `path`. The validator never reaches its documented named SKIP path for an unreadable response.

**Triggers:** When `gh` exits successfully but returns an unexpected JSON shape or an incomplete tree row.

**Suggested fix:** Validate that the payload is a mapping, `tree` is a list, and every retained row has the required fields; raise `Refusal("gh-response-unreadable", ...)` for malformed data.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: templates/assembly-root/scripts/validate-pins.py:330, scripts/repo_shape.py:549


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +322 to +330
env_name = pin_source_env_name(product)
env_value = os.environ.get(env_name)
if env_value:
return Path(env_value), f"${env_name}"
sibling = root.parent / repo_basename(repository)
if (sibling / ".git").exists():
return sibling, f"sibling checkout ({sibling})"
if default_source is not None:
return default_source, "--pin-source"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): A bare --pin-source PATH is ignored whenever the sibling checkout exists, because sibling resolution runs before the default source. The explicitly supplied checkout is therefore not used even though the documented lookup order gives --pin-source precedence over environment and sibling sources.

Triggers: When a bare --pin-source is supplied and a checkout named after the pinned repository also exists beside the assembly root.

Suggested fix: Check default_source before the environment and sibling fallbacks, or define and enforce that sibling resolution intentionally outranks a bare source.

Suggested change
env_name = pin_source_env_name(product)
env_value = os.environ.get(env_name)
if env_value:
return Path(env_value), f"${env_name}"
sibling = root.parent / repo_basename(repository)
if (sibling / ".git").exists():
return sibling, f"sibling checkout ({sibling})"
if default_source is not None:
return default_source, "--pin-source"
if default_source is not None:
return default_source, "--pin-source"
env_name = pin_source_env_name(product)
env_value = os.environ.get(env_name)
if env_value:
return Path(env_value), f"${env_name}"
sibling = root.parent / repo_basename(repository)
if (sibling / ".git").exists():
return sibling, f"sibling checkout ({sibling})"

Comment thread scripts/repo_shape.py
Comment on lines +547 to +549
records = sorted(
f"{row['mode']} {row['type']} {row['sha']}\t{row['path']}".encode()
for row in payload.get("tree") or [] if row.get("type") != "tree")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): A syntactically valid but malformed gh api response crashes with AttributeError or KeyError when payload is not a mapping or a tree row lacks mode, type, sha, or path. The validator never reaches its documented named SKIP path for an unreadable response.

Triggers: When gh exits successfully but returns an unexpected JSON shape or an incomplete tree row.

Suggested fix: Validate that the payload is a mapping, tree is a list, and every retained row has the required fields; raise Refusal("gh-response-unreadable", ...) for malformed data.

@brettheap
brettheap merged commit be488ed into main Sep 4, 2026
4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

New neutral-pin and GitHub-tree handling paths need additional input validation and payload-shape robustness to avoid incorrect file resolution and unhandled exceptions.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR extends the repo-shape pin validation surface so that declared neutral-product descent pins (neutral_product_pins: + contracts/<product>-pin.yaml) are rechecked on each validate-pins.py run by recomputing their tree digest from either a local checkout or gh api, with a named SKIP when neither is available.

Changes:

  • Add neutral-product pin recheck logic to templates/assembly-root/scripts/validate-pins.py, including a new repeatable --pin-source [PRODUCT=]PATH flag and SKIP reporting.
  • Introduce tree_digest_from_gh in scripts/repo_shape.py to compute the same sorted-ls-tree-r-v1 digest from GitHub’s recursive tree API.
  • Add comprehensive offline-focused tests for neutral pin validation and update template .gitignore files and README documentation.
File summaries
File Description
tests/test_repo_hygiene.py Updates README line-cap assertion and embeds the rationale for the cap bump.
tests/test_neutral_pin_validator.py Adds a new test suite covering neutral-product pin recheck behavior and edge cases.
templates/spec-root/.gitignore Prevents common editor/OS noise from dirtying freshly scaffolded spec legs.
templates/code-root/.gitignore Prevents Python/cache/editor/OS noise from dirtying freshly scaffolded code legs.
templates/assembly-root/scripts/validate-pins.py Implements the neutral-product pin recheck feature (local sources, gh api, and SKIP path).
scripts/repo_shape.py Adds tree_digest_from_gh to support digest recomputation via GitHub API.
README.md Documents the new neutral-product pin referent recheck behavior and skip semantics.
Review details

Suppressed comments (1)

templates/assembly-root/scripts/validate-pins.py:470

  • --pin-source parsing currently accepts malformed values like openGlass= (empty path), =../openGlass (empty product), or an empty string, which turns into Path('') (the current directory) and can produce surprising validations. Reject malformed --pin-source values with a refusal so the caller gets an actionable error.
        product, sep, path = raw.partition("=")
        if sep:
            keyed_sources[product.casefold()] = Path(path)
        else:
            default_source = Path(raw)
  • Files reviewed: 7/7 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +349 to +356
if not isinstance(product, str) or not product:
report.finding(
"neutral-pin-entry-malformed",
f"project.yaml neutral_product_pins entry {product!r} is not "
"a non-empty product name",
)
continue
pin_path = root / "contracts" / f"{product.lower()}-pin.yaml"
Comment thread scripts/repo_shape.py
Comment on lines +547 to +549
records = sorted(
f"{row['mode']} {row['type']} {row['sha']}\t{row['path']}".encode()
for row in payload.get("tree") or [] if row.get("type") != "tree")
Comment on lines +373 to +388
if pin.get("revision_kind") != "commit":
report.finding(
"neutral-pin-tag-only",
f"{rel}: revision_kind is {pin.get('revision_kind')!r}. A tag "
"can be moved and a commit cannot; a pin is a commit or it is "
"nothing.",
)
commit = str(pin.get("commit") or "")
if not COMMIT_RE.match(commit):
raise Refusal(
"neutral-pin-tag-only",
f"{rel}: `commit:` is {commit!r}, which is not 40 hex. An "
"abbreviated oid, a branch or a tag is a moving reference.",
)
commit = commit.lower()
repository = str(pin.get("source_repository") or "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants