Skip to content

scaffold-project.py and adopt-project.py: three functions ran past Sonar's cognitive-complexity limit, so each is split into the phases its own comments already name (#138) - #144

Merged
brettheap merged 3 commits into
mainfrom
refactor/scaffold-adopt-cognitive-complexity
Sep 12, 2026
Merged

brettheap merged 3 commits into
mainfrom
refactor/scaffold-adopt-cognitive-complexity

Conversation

@brettheap

@brettheap brettheap commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Lane: openreposhape-2 (openRepoShape-2)
Claim: #138 (comment)

Closes #138.

What was wrong

SonarCloud had python:S3776 — cognitive complexity ≤ 15 — open on the three
acting functions of the two repository-CREATING tools, including the largest
single function in this repository.

function cc before cc after how it was split
scaffold-project.py _scaffold 85 7 The fourteen phases its own # ---- the two legs ---- section comments already marked became fourteen module-level helpers: _elector, _identity, _declaration, _check_referent_chain + _check_one_name + _check_declared_names, _shape_revision, _repository_urls, _leg_visibility, _print_plan + _print_declared_classification + _print_plan_actions, _refuse_existing_trees, _create_remotes, _private_leg_note, _seed_legs, _build_assembly_root, _set_topics. What is left is those calls in order, plus the substitution table.
adopt-project.py cmd_plan 17 2 _checked_plan_inputs (every value the plan will record, defaulted and checked) and _print_plan_report (what it says to the terminal once the file is on disk).
adopt-project.py cmd_execute 24 8 _checked_plan_values, _repository_urls, _leg_paths, _refuse_unconsented_seeding, _build_the_legs, _commit_the_split, _open_the_pull_request, _set_the_topic — the (a)/(b)/(c)/(d) phases the file's own section comments have named all along.

"cc before" is SonarCloud's own number for main at d682127, queried rather
than guessed; "cc after" is complexipy 8.0.1, which implements the same
SonarSource specification. Nothing in either file now measures above 10, and
the 10 is scaffold-project.py's _reusable_remotes, which was already there
and was never flagged.

No new idea was invented for either file. adopt-project.py has kept
_create_leg_remotes, _extract_leg, _seed_leg, _mount_the_legs,
_template_values, _split_message and _verify as module-level private
helpers since it was written; this finishes applying that shape to the two
functions that had outgrown it, and gives scaffold-project.py the same one.

What landed

Two files, and only those two: scaffold-project.py and adopt-project.py.
No digest-pinned copy is touched — nothing under templates/, nothing in
scripts/, no contract, no workflow — so no project's update-shape.py check
moves and no estate re-pin is owed for this.

Behaviour is byte-identical, and that is the point. Every message string,
every refusal id, every gh and git argument vector, and the ORDER of all
of them, are moved rather than edited. No argparse text moved either, so
docs/cli.md is unchanged and needed no regeneration.

Three orderings are load-bearing and are now called out where they live:

  • scaffold-project.py still parses --elected-on before anything is created
    and before the elector is resolved, so an explicit --reference cannot let
    a malformed date reach a manifest field no reader can use; the naming policy
    is still loaded after the elector refusal; and the local remote directory is
    still created after the --dry-run return and after the existing-tree
    refusal, so a refused run leaves no directory behind.
  • adopt-project.py execute still checks its untrusted plan values in the
    order legs.spec_path, legs.code_path, adopt_branch,
    tracking_branch, org, so a plan with two bad values still names the
    first one. _checked_plan_values running before _repository_urls is what
    holds that.

Six helpers report a failure by return value where the old bodies returned
2 from the middle of themselves — _seed_legs, _build_the_legs and
_commit_the_split return None; _build_assembly_root,
_open_the_pull_request and _set_the_topic return False. Each caller
turns that back into the same exit code, after the same stderr block, in the
same place. _leg_visibility returns the visibility rather than assigning
args.visibility in place, and the caller does the assignment.

One helper deliberately did NOT take the guard clause the others took:
_private_leg_note keeps its block nested under its own condition, because
tests/test_free_plan_hint.py::test_every_creating_tool_calls_the_hint reads
scaffold-project.py as TEXT and asserts the exact indentation of the
free_plan_secret_hint( call. A guard clause dedents it and that test fails —
correctly, since it is checking that all three creating tools call the hint
with their own org and it cannot check that if the call moves.

No bug was found while restructuring, so there is no follow-up to file from
this.

How it was proven

Full suite, from this worktree, in three foreground chunks:

tests/test_[a-m]*.py    366 passed, 1 skipped   (41.84s)
tests/test_[n-s]*.py    679 passed              (2:44)
tests/test_[t-z]*.py     91 passed              (18.71s)
                       ----
                       1136 passed, 1 skipped

That is the expected baseline for main today, unchanged. No flake was seen.

The suites that actually drive these two tools end to end — into BARE
repositories in a temporary directory, with no network — are
tests/test_scaffold_e2e.py, tests/test_scaffold_pin_and_reuse.py,
tests/test_reuse_visibility.py, tests/test_reference_default.py,
tests/test_setup_project_py.py, tests/test_setup_sh.py,
tests/test_openreposhape_command.py, tests/test_adopt_plan.py,
tests/test_adopt_e2e.py and tests/test_adopt_spec_only.py. Each was run
against its own commit before it was pushed, and
tests/test_free_plan_hint.py caught the one indentation change described
above while the first commit was still local.

tests/test_cli_reference.py passes with docs/cli.md untouched, which is
the proof that no --help text moved. tests/test_repo_hygiene.py and
tests/test_commit_trailers.py pass, so both files still compile under the
shipped-file rule and the materializer copy lists still account for every
template file.

The authority on the rule itself is this pull request's own SonarCloud
analysis, and the PR-scoped issue query is posted as a comment once it has
run.

🤖 Generated with Claude Code

Summary by Sourcery

Enhancements:

  • Split the scaffold and adopt command workflows into phase-specific helpers to reduce cognitive complexity while preserving their existing behavior and operation order.

brettheap and others added 2 commits September 12, 2026 10:35
…ve complexity 85, so the phases its own section comments already named are now functions (#138)

SonarCloud's `python:S3776` had the largest single function in this repository
open at 85 against a limit of 15. It ran the argument validation, the elector
fallback, the pin declaration, the referent chain, the three-name naming check,
the shape revision, the URL arithmetic, the visibility inheritance, the
substitution table, the plan print, the existing-tree refusal, the three
repository creations, the two seed pushes, the assembly root, the topics and
the next-steps block in one body — with `# ---- the two legs ----` style
comments already marking where one phase stopped and the next began. Those
comments are now function boundaries, in the shape `adopt-project.py` has used
since it was written: module-level private helpers labelled `(a)`, `(b)`, `(c)`
in their own docstrings, called in order by a thin driver.

`_scaffold` is 85 -> 7. Nothing else in the file is above 10, and the 10 is
`_reusable_remotes`, which was already there. The `# noqa: C901` it wore is
gone with the reason for it.

Behaviour is unchanged by construction and by test. Every message string, every
refusal id, every `gh` and `git` argument vector and the order of all of them
are moved rather than edited. Three orderings are load-bearing and are called
out where they now live: `--elected-on` is still parsed before anything is
created and before the elector is resolved, so an explicit `--reference` cannot
let a malformed date through; the naming policy is still loaded after the
elector refusal; and the local remote directory is still created after the
dry-run return and after the existing-tree refusal, so a refused run leaves no
directory behind.

Two small shapes changed and neither is visible from outside. `_seed_legs` and
`_build_assembly_root` report a REFUSED push by returning None and False
instead of returning 2 from the middle of the old body — the caller turns that
back into the same exit 2, after the same two stderr blocks. `_leg_visibility`
returns the visibility the two new legs are created at rather than assigning
`args.visibility` in place; the caller does the assignment, so the manifest
value and both the NOTE and WARNING lines are what they were.

`_private_leg_note` keeps the block nested under its own condition rather than
taking the guard clause the other helpers took, because
`tests/test_free_plan_hint.py::test_every_creating_tool_calls_the_hint` reads
this file as text and asserts the exact indentation of the
`free_plan_secret_hint(` call. A guard clause would have dedented it and the
test would have been right to fail: it is checking that all three creating
tools call the hint with their own org, and it cannot check that if the call
moves.

No argparse text moved, so `docs/cli.md` is unchanged and
`tests/test_cli_reference.py` passes without a regeneration.

Lane: openreposhape-2 (openRepoShape-2)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ecking, their remote arithmetic and their reporting inline at cognitive complexity 17 and 24, so each is now the phase helpers this file already writes everywhere else (#138)

SonarCloud's `python:S3776` had both of `adopt-project.py`'s acting
subcommands open against a limit of 15. Neither needed a new idea to fix: the
file has kept `_create_leg_remotes`, `_extract_leg`, `_seed_leg`,
`_mount_the_legs`, `_template_values`, `_split_message` and `_verify` as
module-level private helpers since it was written, and `cmd_execute` already
labels its phases `(a)`, `(b)`, `(c)`, `(d)` in section comments. The work was
to finish applying that shape to the two functions that had outgrown it.

    cmd_plan     17 -> 2      cmd_execute   24 -> 8

`cmd_plan` gives up `_checked_plan_inputs` — every value the plan will record,
defaulted and checked — and `_print_plan_report`, what it says to the terminal
once the file is on disk. `cmd_execute` gives up `_checked_plan_values`,
`_repository_urls`, `_leg_paths`, `_refuse_unconsented_seeding`,
`_build_the_legs`, `_commit_the_split`, `_open_the_pull_request` and
`_set_the_topic`; what is left is the seventeen calls those phases are, in
order, with the section comments still between them.

Behaviour is unchanged by construction and by test. Every message string, every
refusal id, every `git` and `gh` argument vector and the order of all of them
are moved rather than edited.

The one thing that had to be preserved deliberately is the ORDER OF THE
REFUSALS over untrusted plan input. `execute` checks `legs.spec_path`,
`legs.code_path`, `adopt_branch`, `tracking_branch` and then `org`, and a plan
with two bad values must still name the first one; `_checked_plan_values` runs
before `_repository_urls`, which is what holds that. `local` moved into
`_repository_urls` with the URLs it decides, which is safe because it is a
pure read of `--local-remote-dir` that nothing observes.

Four helpers report a failure by return value where the old body returned 2
from the middle of itself: `_build_the_legs` and `_commit_the_split` return
None, `_open_the_pull_request` and `_set_the_topic` return False. The caller
turns each back into the same exit, after the same stderr block, in the same
place. `_set_the_topic`'s docstring keeps the whole of the comment that
explained why a topic that will not set must not suppress the verification
table, because that is the reason it returns a bool instead of exiting.

No argparse text moved, so `docs/cli.md` is unchanged and
`tests/test_cli_reference.py` passes without a regeneration.

Lane: openreposhape-2 (openRepoShape-2)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Copilot AI lite review requested due to automatic review settings September 12, 2026 14:45

@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.

Sorry @brettheap, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 3 days and 10 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@sourcery-ai

sourcery-ai Bot commented Sep 12, 2026

Copy link
Copy Markdown

Reviewer's Guide

Refactors the three SonarCloud-flagged orchestration functions into phase-aligned private helpers, retaining byte-identical behavior, ordering, diagnostics, and exit semantics while bringing each function below the cognitive-complexity threshold.

Flow diagram for scaffold project phases

flowchart TD
    A["_scaffold"] --> B["Validate inputs and _identity"]
    B --> C["_declaration and _check_declared_names"]
    C --> D["_shape_revision and _repository_urls"]
    D --> E["_leg_visibility and _print_plan"]
    E --> F{"--dry-run?"}
    F -- "yes" --> G["Return 0"]
    F -- "no" --> H["_refuse_existing_trees"]
    H --> I["_create_remotes and _private_leg_note"]
    I --> J["_seed_legs"]
    J --> K["_build_assembly_root"]
    K --> L["_set_topics"]
Loading

Flow diagram for adopt execute phases

flowchart TD
    A["cmd_execute"] --> B["_checked_plan_values"]
    B --> C["_repository_urls"]
    C --> D["_leg_paths and _refuse_unconsented_seeding"]
    D --> E["_create_leg_remotes"]
    E --> F["_build_the_legs"]
    F --> G["_commit_the_split"]
    G --> H{"local remote?"}
    H -- "no" --> I["_open_the_pull_request"]
    I --> J["_set_the_topic"]
    H -- "yes" --> K["_verify"]
    J --> K
Loading

File-Level Changes

Change Details Files
Split the scaffold workflow into ordered, module-level phase helpers while preserving behavior and failure semantics.
  • Extract validation, identity/declaration checks, shape and repository setup, visibility, plan output, remote creation, leg seeding, assembly construction, and topic updates.
  • Preserve load-bearing ordering, exact messages and command arguments, dry-run behavior, refusal handling, and the text-sensitive private-leg hint indentation.
  • Convert selected early exit returns into helper return values that the orchestrator maps back to the original exit code.
scaffold-project.py
Decompose adoption planning and execution into focused helpers without changing the command workflows.
  • Move plan input validation and terminal reporting out of cmd_plan.
  • Extract execute-phase validation, URL/path derivation, seeding consent checks, leg building, split commit, pull request creation, and topic setting.
  • Preserve untrusted-value validation order, command ordering, diagnostics, verification reporting, and exit behavior.
adopt-project.py
Reduce Sonar cognitive complexity in all three flagged functions while keeping the change limited to the two executable tools.
  • Lower scaffold-project.py _scaffold from 85 to 7 and adopt-project.py cmd_plan/cmd_execute from 17/24 to 2/8.
  • Avoid changes to templates, scripts, contracts, workflows, CLI documentation, or digest-pinned copies.
scaffold-project.py
adopt-project.py

Assessment against linked issues

Issue Objective Addressed Explanation
#138 Refactor scaffold-project.py::_scaffold into phase-specific helpers so its cognitive complexity is reduced from 85 to within Sonar's allowed limit. ✅
#138 Refactor adopt-project.py::cmd_plan and adopt-project.py::cmd_execute into phase-specific helpers so both comply with Sonar's cognitive-complexity limit. ✅
#138 Preserve the existing behavior while restructuring the functions, including messages, exit codes, output and call ordering, CLI behavior, and handling of failures. ✅

Possibly linked issues


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

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.

🟢 Approval recommended

The reviewed refactors preserve existing behavior with no unresolved blocking issues.

Pull request overview

Refactors scaffold and adoption workflows into focused helpers, reducing cognitive complexity while preserving behavior and command ordering.

Changes:

  • Split scaffold-project.py into phase-specific helpers.
  • Split adopt-project.py plan and execution flows.
  • Preserved CLI behavior, output, validation, and error handling.
File summaries
File Description
scaffold-project.py Extracts scaffolding phases into private helpers.
adopt-project.py Extracts plan validation and execution phases into private helpers.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Lite

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

…because every line in it addresses a repository by its `<org>/<name>` or its clone URL (#138)

SonarCloud's `python:S1172` on the pull request, and it is right: the split
handed the new helper the same four dictionaries its neighbours take, without
checking which of them this phase actually uses. It creates the three remotes
by `repositories[role]` and `urls[role]` and never wants the bare name, so the
parameter is dropped and the docstring says why, to stop the next reader
adding it back for symmetry.

No behaviour changes: the argument was unread.

Lane: openreposhape-2 (openRepoShape-2)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Copilot AI review requested due to automatic review settings September 12, 2026 14:56
@sonarqubecloud

Copy link
Copy Markdown

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 1abd0149e3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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.

🟢 Approval recommended

The reviewed refactors preserve existing behavior and have no unresolved issues.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@brettheap

Copy link
Copy Markdown
Contributor Author

Lane: openreposhape-2 (openRepoShape-2)

PR-scoped SonarCloud query at head 05a5f4a, the authority on the rule this pull request exists to satisfy:

curl -s 'https://sonarcloud.io/api/issues/search?componentKeys=opensoft_openRepoShape&pullRequest=144&statuses=OPEN&ps=100'
  total OPEN issues on PR 144: 0

No python:S3776 in either file, and no NEW issue of any other rule. The first analysis of this branch did find one — python:S1172, an unused names parameter the split had handed _create_remotes for symmetry with its neighbours — and 05a5f4a removes it, which is the third commit here.

CI: tests pass (3m38s), tests-macos pass (5m34s), tests-windows pass (12m57s), SonarCloud Code Analysis pass. Full suite locally: 1136 passed, 1 skipped, the unchanged baseline for main.

Reviewers: Copilot recommended approval with 0 comments, twice (before and after the S1172 fix). Sourcery declined — own review budget of 250,000 diff characters spent for the last 7 days. Codex was asked and is over quota today.

@brettheap
brettheap merged commit fd1b3f9 into main Sep 12, 2026
6 checks passed
@brettheap
brettheap deleted the refactor/scaffold-adopt-cognitive-complexity branch September 12, 2026 15:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants