Skip to content

fix: address Codacy post-merge findings on PR #28 - #29

Merged
ThePlenkov merged 20 commits into
mainfrom
fix/codacy-post-merge-pr28
Aug 12, 2026
Merged

ThePlenkov merged 20 commits into
mainfrom
fix/codacy-post-merge-pr28

Conversation

@ThePlenkov

@ThePlenkov ThePlenkov commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Summary

Addresses 3 Codacy findings that appeared on PR #28 after merge:

  • scripts/sarif-to-annotations.py:190 — Normalize SARIF artifactLocation URIs by stripping file:// scheme and leading slashes so GitHub Actions receives a path relative to the repository root
  • .agents/skills/gc-watchdog/watchdog.sh:60 — Narrow MAYOR grep to whole-word match (grep -w) and add head -1 to avoid multi-line variable values
  • .agents/skills/gc-watchdog/watchdog.sh:62 — Add head -1 to SUSPENDED grep for consistency with SESSIONS and CONTROLLER parsing

Threads resolved on merged PR #28: PRRT_kwDOTyoI9s6YYoxo, PRRT_kwDOTyoI9s6YYoxq, PRRT_kwDOTyoI9s6YYoxy

Test plan

  • python3 -c "import ast; ast.parse(open('scripts/sarif-to-annotations.py').read())" — syntax OK
  • bash -n .agents/skills/gc-watchdog/watchdog.sh — syntax OK
  • CI green on this PR

Generated with Devin


Summary by cubic

Fixes post-merge findings from PR #28 by hardening SARIF parsing, GC watchdog parsing/filters, and merge-stack post-merge cleanup. Adds a documented post-merge runbook and regression tests, and restores correct GitHub Actions annotations.

  • Bug Fixes
    • SARIF: Normalize all artifactLocation URIs with urllib.parse (supports file://, file:/, uppercase, https://), decode to repo-relative paths, and emit only positive-int coordinates (skip booleans/invalid). Enforce a 100 MB byte limit with UTF-8 validation and fail on non-list runs while allowing missing runs. Added scripts/test_sarif_to_annotations.py with e2e coverage.
    • Watchdog: Parse harness.mayor, Sessions:, Suspended:, and Controller: with anchored, first-match logic via shared _parse_gc_status; count real beads with sv-[a-zA-Z0-9]{3,}(\.[0-9]+)?; exclude only complete wisp/nudge IDs (including hierarchical). Added test-source markers and scripts/test_gc_watchdog.py regressions.
    • Merge stack: Verify lower-branch content for squash merges via trial git merge-tree --write-tree; validate the resulting tree OID (SHA-1 or SHA-256) and type; resolve each lower PR’s head branch via gh pr view and use it for verification/deletion; fetch origin once and fail closed on fetch; keep unverified lower PRs/branches open. Documented in engdocs/runbooks/merge-stack-post-merge.md and referenced by pack/formulas/merge-stack.toml. Added scripts/test_merge_stack.py and scripts/testlib.py.

Written for commit 15aeef3. Summary will update on new commits.

Review in cubic

- sarif-to-annotations.py: normalize artifactLocation URIs by stripping
  file:// scheme and leading slashes so GitHub Actions receives a path
  relative to the repository root
- gc-watchdog/watchdog.sh: add head -1 to MAYOR and SUSPENDED grep
  pipelines for consistency with SESSIONS and CONTROLLER parsing;
  narrow MAYOR grep to whole-word match on harness.mayor

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Improved watchdog status detection and filtering for valid issue identifiers.
    • Improved SARIF annotation paths by normalizing and decoding URI formats.
    • Improved SARIF validation for malformed locations, invalid coordinates, oversized files, and invalid input.
    • Improved merge workflows by verifying complete content matches before closing and deleting lower branches; uncertain merges now retain branches.
  • Documentation

    • Added guidance for post-merge cleanup and verification procedures.
  • Tests

    • Added regression coverage for watchdog, SARIF conversion, and merge-stack verification.

Walkthrough

The watchdog expands issue filtering and centralizes status parsing. The SARIF converter adds URI, coordinate, input-size, encoding, and schema validation. The merge workflow uses trial merge-tree verification before lower-PR cleanup. Standalone tests cover all three changes.

Changes

Watchdog filtering

Layer / File(s) Summary
Issue and status parsing
.agents/skills/gc-watchdog/watchdog.sh, scripts/test_gc_watchdog.py
Issue identifiers support hierarchical suffixes while exact wisp and nudge identifiers remain excluded. Status parsing selects the first matching entry. Tests cover filtering, parser behavior, failures, and missing fields.

SARIF conversion

Layer / File(s) Summary
SARIF input and annotation validation
scripts/sarif-to-annotations.py, scripts/test_sarif_to_annotations.py, scripts/testlib.py
Artifact URIs are decoded into relative paths. Coordinates require positive integers. Standard input has a 100 MB byte limit and strict UTF-8 decoding. Invalid runs values reach validation. Tests cover these behaviors.

Merge-stack cleanup

Layer / File(s) Summary
Lower-branch content verification
pack/formulas/merge-stack.toml, engdocs/runbooks/merge-stack-post-merge.md, scripts/test_merge_stack.py
The workflow delegates cleanup to the runbook. The runbook verifies lower-PR content with git merge-tree, validates tree object IDs, and closes and deletes branches only after successful verification. Tests cover included, unmerged, unrelated, and invalid results.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • sverka-dev/sverka#28: Refines the same watchdog, SARIF converter, and merge-stack implementations.

Suggested labels: baz: needs review, size:XXL

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title accurately identifies the Codacy-related fixes, although it does not mention the added regression tests and merge-stack changes.
Description check ✅ Passed The description clearly explains the Codacy fixes, related hardening, regression tests, documentation, and test status.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/codacy-post-merge-pr28

Comment @coderabbitai help to get the list of available commands.

@baz-reviewer

baz-reviewer Bot commented Aug 11, 2026

Copy link
Copy Markdown

Merger

Needs Review

The runbook has a diff-confirmed data-integrity risk: each LOWER_PR uses a fixed placeholder branch instead of resolving its own head branch, so verification and deletion can target the wrong branch. CI also did not run, so human review is needed before merging.

Commit b227505 · Evaluated 2026-08-12 00:07 UTC

Review this PR on Baz | Customize your next review

@amazon-q-developer amazon-q-developer 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.

Review Summary

This PR addresses Codacy findings from PR #28 with fixes for grep patterns and URI normalization. The bash script changes look good, but there's a critical logic error in the Python URI parsing that would cause incorrect file paths to be sent to GitHub Actions.

Critical Issue

  • scripts/sarif-to-annotations.py:198 — URI parsing bug that extracts only the filename instead of the full path for non-file:// schemes, breaking GitHub Actions annotations

Changes Reviewed

  • ✅ watchdog.sh: grep improvements with -w and head -1 for robustness
  • ⚠️ sarif-to-annotations.py: URI normalization logic has a path extraction bug

Please fix the identified issue before merging.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

Comment thread scripts/sarif-to-annotations.py Outdated
@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

@qodo-code-review

qodo-code-review Bot commented Aug 11, 2026

Copy link
Copy Markdown

PR Summary by Qodo

Fix Codacy findings: safer SARIF parsing, watchdog parsing, and merge-stack cleanup

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Normalize SARIF artifact URIs and validate coordinates for safe GitHub annotations.
• Refactor GC watchdog parsing/counting and add regression coverage for edge cases.
• Document and test merge-stack squash verification using git merge-tree tree comparison.
Diagram

graph TD
  A["SARIF producer"] --> B["scripts/sarif-to-annotations.py"] --> C["GitHub Actions annotations"]
  D["gc status output"] --> E[".agents/.../watchdog.sh"]
  F["pack/formulas/merge-stack.toml"] --> G["git + gh CLI"]
  F --> H["engdocs runbook"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Adopt pytest/unittest instead of a custom test runner
  • ➕ Better reporting, fixtures, skipping, and CI integration out of the box
  • ➕ Easier extension as test count grows
  • ➖ Adds/assumes a dependency and test convention across the repo
  • ➖ More setup than standalone scripts if CI doesn’t already run Python tests
2. Use a dedicated SARIF parser library
  • ➕ Stronger schema handling and fewer hand-rolled edge cases
  • ➕ Potentially clearer intent for SARIF semantics
  • ➖ Additional dependency surface area for a small utility
  • ➖ May still need custom normalization for GitHub Actions paths
3. Keep merge-stack cleanup as script automation (not runbook)
  • ➕ Less manual error; can enforce verification before closing/deleting
  • ➕ Centralizes policy and logging
  • ➖ More engineering effort and ongoing maintenance
  • ➖ Higher blast radius if automation is wrong

Recommendation: The current approach is appropriate for the repo’s apparent style: small, dependency-free utilities with targeted regression tests. The custom scripts/testlib.py is minimal but sufficient to lock in the Codacy-driven fixes without pulling in a full test framework; if test coverage expands further, migrating to pytest would be the next sensible step.

Files changed (9) +897 / -33

Bug fix (2) +59 / -18
watchdog.shRefactor watchdog parsing and harden bead counting filters +24/-7

Refactor watchdog parsing and harden bead counting filters

• Extracts a sourceable '_parse_gc_status' helper (with first-match semantics) and uses it in the main loop to avoid multi-line/over-match issues. Tightens 'count_real_issues' matching to support uppercase and hierarchical IDs while excluding only exact wisp/nudge IDs.

.agents/skills/gc-watchdog/watchdog.sh

sarif-to-annotations.pyNormalize SARIF URIs and validate coordinates to prevent unsafe annotations +35/-11

Normalize SARIF URIs and validate coordinates to prevent unsafe annotations

• Uses 'urllib.parse' to normalize 'artifactLocation.uri' into decoded, repo-relative paths and avoids dropping intermediate segments. Validates location coordinates as positive integers (skipping invalid/boolean values) and hardens stdin handling with a strict 100MB byte limit plus UTF-8 validation; also fails on malformed non-list 'runs'.

scripts/sarif-to-annotations.py

Tests (5) +731 / -0
test_gc_watchdog.pyAdd regression tests for watchdog parsers and bead counting +202/-0

Add regression tests for watchdog parsers and bead counting

• Introduces standalone tests that source the watchdog helper section to exercise '_parse_gc_status' and 'count_real_issues'. Covers hierarchical/uppercase IDs, wisp/nudge exclusion precision, and bd failure signaling.

scripts/test_gc_watchdog.py

test_merge_stack.pyAdd regression tests for squash-merge inclusion verification via merge-tree +186/-0

Add regression tests for squash-merge inclusion verification via merge-tree

• Creates temporary git repos to validate that 'merge-tree --write-tree' correctly detects whether a lower branch’s content is included in main after a squash-like commit. Includes version gating for git < 2.38 and rejects invalid merge-tree outputs.

scripts/test_merge_stack.py

test_sarif_to_annotations.pyAdd tests for SARIF URI normalization, coordinate validation, and main() hardening +238/-0

Add tests for SARIF URI normalization, coordinate validation, and main() hardening

• Validates URI normalization across file/https schemes, query/fragment removal, percent-decoding, and leading-slash stripping. Adds tests ensuring invalid coordinates are skipped (preventing workflow-command injection) and main() rejects invalid UTF-8 / malformed runs.

scripts/test_sarif_to_annotations.py

test_testlib.pyAdd regression tests for scripts/testlib.py runner behavior +81/-0

Add regression tests for scripts/testlib.py runner behavior

• Tests the minimal runner’s exit codes and output formatting for pass/fail/error cases. Ensures summary counts and FAIL line prefixes are stable for CI/log parsing.

scripts/test_testlib.py

testlib.pyIntroduce minimal shared Python test runner for standalone scripts +24/-0

Introduce minimal shared Python test runner for standalone scripts

• Adds a tiny dependency-free 'run_tests()' helper used by the new regression scripts. Standardizes PASS/FAIL/ERROR output and returns non-zero on any failure/error.

scripts/testlib.py

Documentation (1) +94 / -0
merge-stack-post-merge.mdAdd merge-stack post-merge cleanup runbook (squash-aware verification) +94/-0

Add merge-stack post-merge cleanup runbook (squash-aware verification)

• Documents how to close lower PRs and delete branches after a squash merge by verifying tree equality via 'git merge-tree --write-tree'. Includes safety checks (single fetch, OID/type validation) and guidance to retain anything unverified.

engdocs/runbooks/merge-stack-post-merge.md

Other (1) +13 / -15
merge-stack.tomlReplace inline cleanup instructions with runbook reference +13/-15

Replace inline cleanup instructions with runbook reference

• Removes the outdated ancestry-based cleanup steps and points operators to the new runbook. Clarifies the squash-merge caveat and the 'merge-tree'-based verification approach.

pack/formulas/merge-stack.toml

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

Pull Request Overview

While this PR is technically 'Up to Standards' according to Codacy, there are significant implementation risks and testing gaps. The logic for URI normalization in scripts/sarif-to-annotations.py is fragile and likely to fail on complex URIs (e.g., those with ports or query strings). In watchdog.sh, the hardening of the 'Suspended:' variable extraction is inconsistent with the 'MAYOR' variable, leaving it vulnerable to false positives from lines like 'Total Suspended:'.

Most importantly, there are no functional tests provided for these changes. The current verification relies solely on syntax validation, which does not confirm that URI paths are correctly relative or that shell extractions handle multi-line inputs as intended.

About this PR

  • The PR does not include functional tests to verify the URI normalization logic or the shell script's grep improvements. Relying solely on syntax validation is insufficient for changes affecting path resolution and variable extraction.

Test suggestions

  • Verify SARIF 'file://' URIs are converted to relative paths (e.g., 'file:///path/to/file' -> 'path/to/file')
  • Verify SARIF URIs with other schemes (e.g., 'https://host/path') have the authority stripped
  • Verify 'watchdog.sh' correctly handles multiple 'harness.mayor' matches by selecting the first whole-word match
  • Verify 'watchdog.sh' correctly handles multiple 'Suspended:' matches by selecting the first occurrence
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. Verify SARIF 'file://' URIs are converted to relative paths (e.g., 'file:///path/to/file' -> 'path/to/file')
2. Verify SARIF URIs with other schemes (e.g., 'https://host/path') have the authority stripped
3. Verify 'watchdog.sh' correctly handles multiple 'harness.mayor' matches by selecting the first whole-word match
4. Verify 'watchdog.sh' correctly handles multiple 'Suspended:' matches by selecting the first occurrence

TIP Improve review quality by adding custom instructions
TIP How was this review? Give us feedback

Comment thread .agents/skills/gc-watchdog/watchdog.sh Outdated
Comment thread scripts/sarif-to-annotations.py Outdated
- sarif-to-annotations.py: replace manual string splitting with
  urllib.parse.urlparse to correctly extract the path component
  from absolute URIs (file://, https:// with ports/query/fragments).
  Fixes logic error where split("/", 3)[-1] dropped intermediate
  path segments.
- gc-watchdog/watchdog.sh: add -w flag to Suspended: grep to avoid
  matching lines like "Total Suspended:"

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills/gc-watchdog/watchdog.sh:
- Line 60: Update the STATUS parsing assignment for MAYOR to use a literal grep
pattern for “harness.mayor”, preferably with grep -m1 -wF and the existing
status extraction pipeline, so similarly named status lines cannot be selected.

In `@scripts/sarif-to-annotations.py`:
- Around line 191-199: Update the file URI normalization logic around file_uri
to parse URI components before emitting the file value: remove the authority for
file://localhost paths, use only the path without query or fragment, and
preserve unrecognized forms such as FILE:/src/a.ts unchanged. Add regression
tests covering localhost, query/fragment, and uppercase FILE scheme inputs.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 012f8eef-942e-494d-b634-a014c274d3c9

📥 Commits

Reviewing files that changed from the base of the PR and between 1ffc0bd and 1a09aa2.

📒 Files selected for processing (2)
  • .agents/skills/gc-watchdog/watchdog.sh
  • scripts/sarif-to-annotations.py
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Amazon Q Developer
🔇 Additional comments (1)
.agents/skills/gc-watchdog/watchdog.sh (1)

60-60: 🩺 Stability & Availability

Do not flag these pipelines for pipefail. watchdog.sh uses set -uo pipefail, not set -e; a SIGPIPE status does not stop the watchdog. grep -m1 can also cause SIGPIPE from the preceding echo on large input.

			> Likely an incorrect or invalid review comment.

Comment thread .agents/skills/gc-watchdog/watchdog.sh Outdated
Comment thread scripts/sarif-to-annotations.py Outdated
- gc-watchdog/watchdog.sh: use grep -m1 -wF for literal fixed-string
  match on "harness.mayor" (dot is a regex wildcard in grep -w)
- sarif-to-annotations.py: handle file:/ (single slash) URI form in
  addition to file://, broaden scheme detection to catch FILE:/
  uppercase variants

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@qodo-code-review

qodo-code-review Bot commented Aug 11, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Tests assume main branch ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
scripts/test_merge_stack.py creates a new git repo with git init but later checks out main,
which fails on environments where the default initial branch is not named main. This can make the
new regression tests fail before any assertions run.
Code

scripts/test_merge_stack.py[R75-79]

+def _create_repo() -> str:
+    tmp = tempfile.mkdtemp(prefix="merge-stack-test-")
+    _run_git(tmp, "init")
+    _run_git(tmp, "config", "user.email", "test@example.com")
+    _run_git(tmp, "config", "user.name", "Test User")
Evidence
The helper repo is initialized without specifying an initial branch name, but the tests later
unconditionally check out main, which will not exist when git init created master (or another
default).

scripts/test_merge_stack.py[75-80]
scripts/test_merge_stack.py[99-113]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`scripts/test_merge_stack.py` initializes a temporary git repository with `git init` and then later assumes a `main` branch exists (via `git checkout main`). On systems where the default initial branch is `master` (or any other name), the tests error out immediately.

## Issue Context
This is a portability/reliability issue in the newly added regression tests. The tests should not depend on the user's global git config (`init.defaultBranch`) to decide the initial branch name.

## Fix Focus Areas
- scripts/test_merge_stack.py[75-80]

## Suggested fix
After `git init`, explicitly create/checkout `main` before the first commit, e.g.:
- `git checkout -b main` (works even on an empty repo), or
- `git init -b main` (supported on modern git).

This ensures later `git checkout main` calls succeed deterministically.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. run_tests lacks regression tests 📘 Rule violation ▣ Testability ⭐ New
Description
A new non-trivial test runner (run_tests) was added but no automated test asserts its exit-code
and failure-reporting behavior, so regressions could cause CI/test scripts to report success even
when tests fail. This violates the requirement that non-trivial implementation changes be covered by
tests.
Code

scripts/testlib.py[R7-10]

+def run_tests(tests: Sequence[Callable[[], None]]) -> int:
+    """Run a list of no-arg test functions and print a summary."""
+    passed = 0
+    failed = 0
Evidence
PR Compliance ID 2649776 requires automated tests for non-trivial implementation changes.
run_tests() adds logic for pass/fail/error handling and exit codes, but the only references are
sys.exit(run_tests(...)) calls in the standalone scripts, with no test that would fail if
run_tests returned the wrong status for failures.

Rule 2649776: Require tests for all non-trivial implementation code changes
scripts/testlib.py[7-24]
scripts/test_gc_watchdog.py[200-201]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`scripts/testlib.py` introduces `run_tests()`, but there are no regression tests that verify its critical behavior (e.g., returning non-zero when a test fails or errors).

## Issue Context
The new standalone test scripts (`scripts/test_gc_watchdog.py`, `scripts/test_merge_stack.py`, `scripts/test_sarif_to_annotations.py`) rely on `sys.exit(run_tests(...))`. If `run_tests` regresses to always return `0` (or mis-count failures), these scripts can falsely pass.

## Fix Focus Areas
- scripts/testlib.py[7-24]
- scripts/test_gc_watchdog.py[200-201]
- scripts/test_merge_stack.py[185-186]
- scripts/test_sarif_to_annotations.py[237-238]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Invalid bash in instructions ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The post-merge cleanup snippet includes the literal line For each lower PR in the stack: inside a
bash-style command block; if a user copy/pastes the block into a shell, this line will run as a
command and error (and may halt the sequence under set -e/automation).
Code

pack/formulas/merge-stack.toml[R105-106]

+     For each lower PR in the stack:
+       # Squash merge creates a new commit on main, so ancestry checks
Evidence
The After merge: section is formatted as a runnable shell sequence (`if ! git fetch origin; then
... else ...), but the newly inserted For each lower PR in the stack:` line is not valid bash
syntax unless it is commented or turned into an actual loop construct.

pack/formulas/merge-stack.toml[94-107]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The merge-stack post-merge instructions contain a non-shell prose line (`For each lower PR in the stack:`) embedded within a sequence of shell commands. If the instructions are copy/pasted as a bash block (or executed under stricter error handling), this will produce a `command not found` error and can interrupt the intended cleanup flow.

### Issue Context
This text sits in the `After merge:` section alongside executable commands (`git fetch origin`, `BASE_TREE=...`, etc.), so readers will naturally treat it as runnable shell.

### Fix Focus Areas
- pack/formulas/merge-stack.toml[105-106]

### Suggested fix
Convert `For each lower PR in the stack:` into a shell comment (e.g., `# For each lower PR in the stack:`) or replace it with an explicit loop skeleton (`for ...; do ... done`) so the block is syntactically valid when copy/pasted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Runbook steps outside engdocs/ ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New/updated engineering runbook content was added to pack/formulas/merge-stack.toml, which is
outside the required engdocs/ directory. This can cause engineering documentation to be scattered
and harder to audit and maintain.
Code

pack/formulas/merge-stack.toml[R98-101]

+   # Fetch origin once before verifying any lower PR; if it fails, none of the
+   # lower PRs can be safely proven as included, so retain all of them.
+   if ! git fetch origin; then
+     echo "WARNING: git fetch origin failed — cannot verify lower PRs; retaining all lower PRs and branches"
Evidence
PR Compliance ID 2663932 requires engineering documentation files touched by the change to be placed
under engdocs/. The modified section in pack/formulas/merge-stack.toml adds/updates
human-oriented runbook instructions (e.g., post-merge verification and PR closing steps) outside
engdocs/.

Rule 2663932: Place engineering documentation under engdocs/ directory
pack/formulas/merge-stack.toml[94-115]
pack/formulas/merge-stack.toml[143-151]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Engineering documentation/runbook content was modified outside `engdocs/`, violating the repository documentation placement requirement.

## Issue Context
`pack/formulas/merge-stack.toml` contains detailed operational instructions (e.g., fetch/verify/close PR workflow). If this guidance is meant to be human-consumed documentation, it should live under `engdocs/` and the formula should link/reference it.

## Fix Focus Areas
- pack/formulas/merge-stack.toml[98-115]
- pack/formulas/merge-stack.toml[143-149]
- pack/formulas/merge-stack.toml[151-151]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (3)
5. Fragile merge-tree output parsing ✓ Resolved 🐞 Bug ☼ Reliability
Description
The merge-stack cleanup instructions merge git merge-tree stderr into stdout and then treat the
first output line as the merged tree OID, without validating it as an OID. Any diagnostic output (or
output format change) can cause a false mismatch vs origin/main^{tree}, leading to unnecessary
branch retention even when content is included.
Code

pack/formulas/merge-stack.toml[R124-126]

+         MERGED_TREE=$(printf '%s\n' "$MERGE_OUTPUT" | head -1)
+         if [ "$MERGED_TREE" = "$BASE_TREE" ]; then
+           CONTENT_INCLUDED=true
Evidence
The instructions currently capture combined stdout/stderr from git merge-tree and then use `head
-1` as the merged tree identifier, but do not ensure that the captured first line is actually the
tree OID. Git’s documented merge-tree --write-tree mode returns an OID and also supports
--no-messages, indicating additional non-OID output can exist and should be suppressed/handled
when scripting.

pack/formulas/merge-stack.toml[113-129]
🌐 Documents git merge-tree [--write-tree] ... &lt;branch1&gt; &lt;branch2&gt; and notes --write-tree returns the merged tree OID; also lists --no-messages to suppress merge informational output, which is helpful for robust scripting/parsing.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`pack/formulas/merge-stack.toml` documents a branch-deletion safety check based on comparing `origin/main^{tree}` to the tree produced by `git merge-tree --write-tree`. The snippet currently captures `2>&1` into `MERGE_OUTPUT` and then uses `head -1` as the tree OID, but does not validate that the line is actually a Git tree object id.

This makes the check brittle: any diagnostic text (or future output format change) can corrupt the parsed value and incorrectly keep `CONTENT_INCLUDED=false`.

### Issue Context
This is documentation/recipe code, but it is meant to be executed by operators/agents; false negatives increase manual cleanup and reduce trust in the procedure.

### Fix Focus Areas
- pack/formulas/merge-stack.toml[113-129]

### Suggested change
- Keep stdout/stderr separate (don’t use `2>&1` for the value you compare).
- Prefer `git merge-tree --write-tree --no-messages ...`.
- Parse and validate the OID (e.g., match `^[0-9a-f]{40}$` or `git cat-file -t "$MERGED_TREE"` equals `tree`) before comparing it to `BASE_TREE`.
- If validation fails, treat it as “unverified” (current conservative behavior), but make the parsing robust so clean success paths work reliably.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. watchdog.sh changes lack tests ✓ Resolved 📘 Rule violation ▣ Testability
Description
The updated ID-filtering regex and status-field parsing logic in watchdog.sh was changed without
adding or updating any automated test that would fail on regressions. This violates the requirement
that non-trivial implementation changes be covered by tests.
Code

.agents/skills/gc-watchdog/watchdog.sh[R43-44]

+    | { grep -E '^\s*[○◐●] sv-[a-z0-9]{3,}(\.[0-9]+)?($| )' || true; } \
+    | { grep -vE '^\s*[○◐●] sv-(wisp|nudge)(\.[0-9]+)?($|[[:space:]])' || true; } \
Evidence
PR Compliance ID 2649776 requires at least one automated test covering non-trivial code changes. The
updated logic in count_real_issues() (regex) and the status parsing lines were changed here, but
no corresponding watchdog-focused test was added/updated alongside these changes.

Rule 2649776: Require tests for all non-trivial implementation code changes
.agents/skills/gc-watchdog/watchdog.sh[43-44]
.agents/skills/gc-watchdog/watchdog.sh[61-63]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`watchdog.sh`’s filtering/parsing logic was modified (regex changes and `grep` behavior changes) without accompanying automated coverage.

## Issue Context
The compliance checklist requires tests for non-trivial implementation changes; without coverage, these regex/parsing tweaks can silently change counts/health signals and cause incorrect watchdog behavior.

## Fix Focus Areas
- .agents/skills/gc-watchdog/watchdog.sh[43-44]
- .agents/skills/gc-watchdog/watchdog.sh[61-63]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. parse_location lacks automated tests ✓ Resolved 📘 Rule violation ≡ Correctness
Description
The modified parse_location adds URI-normalization branches without automated coverage, and its
handling of non-file:// absolute URIs strips only the scheme and authority, leaving paths such as
org/repo/blob/main/src/a.py instead of the repository-relative src/a.py. This can cause GitHub
Actions annotations generated from SARIF web URIs to target incorrect or nonexistent files, with
regressions remaining undetected.
Code

scripts/sarif-to-annotations.py[R193-199]

+    if file_uri.startswith("file://"):
+        file_uri = file_uri[len("file://"):]
+    elif "://" in file_uri:
+        # Drop any other absolute URI scheme (http://, https://, etc.) —
+        # keep only the path component after the authority.
+        file_uri = file_uri.split("/", 3)[-1] if "/" in file_uri.split("://", 1)[1] else ""
+    file_uri = file_uri.lstrip("/")
Evidence
The PR adds conditional URI parsing and path normalization in parse_location, but repository
search found no tests referencing it. For https://github.com/org/repo/blob/main/src/a.py,
file_uri.split("/", 3)[-1] produces org/repo/blob/main/src/a.py, which is not the
repository-relative source path; this value is passed directly as the file= property in the
emitted workflow command at line 230, so the annotation may not attach to the correct file or line.

Rule 2669776: Require tests for all non-trivial implementation code changes
scripts/sarif-to-annotations.py[193-199]
scripts/sarif-to-annotations.py[195-198]
scripts/sarif-to-annotations.py[229-230]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Add automated coverage for the modified `parse_location` URI-normalization behavior and correct the handling of absolute non-`file://` URIs. The current `file_uri.split("/", 3)[-1]` logic leaves URL path components such as `org/repo/blob/main/src/a.py`, causing GitHub Actions annotations to reference an incorrect or nonexistent file instead of the repository-relative source path.

## Issue Context
The compliance requirement mandates tests for non-trivial implementation changes. `parse_location()` extracts `file_uri` from `result.locations[0].physicalLocation.artifactLocation.uri` and passes the normalized value directly into the `file=` parameter of the emitted GitHub workflow annotation. SARIF tools may provide absolute URIs other than `file://`, such as `https://...`; the SARIF specification also supports `uriBaseId` for resolving relative locations, but this behavior is not considered here.

## Fix Focus Areas
- scripts/sarif-to-annotations.py[193-199]
- scripts/test_sarif_to_annotations.py[1-1]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

8. Runbook not copy-paste safe ✓ Resolved 🐞 Bug ⚙ Maintainability ⭐ New
Description
The new runbook’s bash block uses angle-bracket placeholders inside a for ... in ... list (e.g.
<lower-pr-1>), which bash parses as input redirection if not replaced. This can cause the runbook
snippet to fail immediately when copy/pasted during an incident/cleanup workflow.
Code

engdocs/runbooks/merge-stack-post-merge.md[R38-41]

+     # For each lower PR in the stack (replace placeholders with real values):
+     for LOWER_PR in <lower-pr-1> <lower-pr-2>; do
+       LOWER_REF="origin/<lower-head-branch>"
+       CONTENT_INCLUDED=false
Evidence
The code block explicitly includes <lower-pr-1>/<lower-pr-2> in the word list of a for loop,
which is invalid shell syntax if pasted verbatim.

engdocs/runbooks/merge-stack-post-merge.md[38-41]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The runbook’s bash snippet contains unquoted tokens like `<lower-pr-1>` in a `for` loop. In bash, a word beginning with `<` is treated as redirection syntax, so the snippet is not copy/paste safe unless the operator edits it first.

## Issue Context
The runbook already instructs users to replace placeholders, but using a placeholder style that is syntactically invalid in shell increases the chance of a failed (or partially executed) operational workflow.

## Fix Focus Areas
- engdocs/runbooks/merge-stack-post-merge.md[38-41]

## Suggested fix
Replace angle-bracket placeholders with shell-safe placeholders that still clearly signal “replace me”, e.g.:
- `LOWER_PR_1 LOWER_PR_2` (or `__LOWER_PR_1__ __LOWER_PR_2__`), and similarly for branch placeholders.
Optionally add a short note above the code block: "This block is a template; replace placeholder values before running."

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context
✅ Compliance rules (platform): 8 rules
Review mode: ⚖️ Balanced: The push changes executable watchdog parsing and a merge-stack cleanup template that can affect PR closure and branch deletion, so it carries real operational risk despite being modest in size.

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous review results

Review updated until commit 15aeef3

Results up to commit 1a09aa2 🚀 Fast


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. parse_location lacks automated tests ✓ Resolved 📘 Rule violation ≡ Correctness
Description
The modified parse_location adds URI-normalization branches without automated coverage, and its
handling of non-file:// absolute URIs strips only the scheme and authority, leaving paths such as
org/repo/blob/main/src/a.py instead of the repository-relative src/a.py. This can cause GitHub
Actions annotations generated from SARIF web URIs to target incorrect or nonexistent files, with
regressions remaining undetected.
Code

scripts/sarif-to-annotations.py[R193-199]

+    if file_uri.startswith("file://"):
+        file_uri = file_uri[len("file://"):]
+    elif "://" in file_uri:
+        # Drop any other absolute URI scheme (http://, https://, etc.) —
+        # keep only the path component after the authority.
+        file_uri = file_uri.split("/", 3)[-1] if "/" in file_uri.split("://", 1)[1] else ""
+    file_uri = file_uri.lstrip("/")
Evidence
The PR adds conditional URI parsing and path normalization in parse_location, but repository
search found no tests referencing it. For https://github.com/org/repo/blob/main/src/a.py,
file_uri.split("/", 3)[-1] produces org/repo/blob/main/src/a.py, which is not the
repository-relative source path; this value is passed directly as the file= property in the
emitted workflow command at line 230, so the annotation may not attach to the correct file or line.

Rule 2669776: Require tests for all non-trivial implementation code changes
scripts/sarif-to-annotations.py[193-199]
scripts/sarif-to-annotations.py[195-198]
scripts/sarif-to-annotations.py[229-230]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Add automated coverage for the modified `parse_location` URI-normalization behavior and correct the handling of absolute non-`file://` URIs. The current `file_uri.split("/", 3)[-1]` logic leaves URL path components such as `org/repo/blob/main/src/a.py`, causing GitHub Actions annotations to reference an incorrect or nonexistent file instead of the repository-relative source path.

## Issue Context
The compliance requirement mandates tests for non-trivial implementation changes. `parse_location()` extracts `file_uri` from `result.locations[0].physicalLocation.artifactLocation.uri` and passes the normalized value directly into the `file=` parameter of the emitted GitHub workflow annotation. SARIF tools may provide absolute URIs other than `file://`, such as `https://...`; the SARIF specification also supports `uriBaseId` for resolving relative locations, but this behavior is not considered here.

## Fix Focus Areas
- scripts/sarif-to-annotations.py[193-199]
- scripts/test_sarif_to_annotations.py[1-1]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit f2a4a90 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Fragile merge-tree output parsing ✓ Resolved 🐞 Bug ☼ Reliability
Description
The merge-stack cleanup instructions merge git merge-tree stderr into stdout and then treat the
first output line as the merged tree OID, without validating it as an OID. Any diagnostic output (or
output format change) can cause a false mismatch vs origin/main^{tree}, leading to unnecessary
branch retention even when content is included.
Code

pack/formulas/merge-stack.toml[R124-126]

+         MERGED_TREE=$(printf '%s\n' "$MERGE_OUTPUT" | head -1)
+         if [ "$MERGED_TREE" = "$BASE_TREE" ]; then
+           CONTENT_INCLUDED=true
Evidence
The instructions currently capture combined stdout/stderr from git merge-tree and then use `head
-1` as the merged tree identifier, but do not ensure that the captured first line is actually the
tree OID. Git’s documented merge-tree --write-tree mode returns an OID and also supports
--no-messages, indicating additional non-OID output can exist and should be suppressed/handled
when scripting.

pack/formulas/merge-stack.toml[113-129]
🌐 Documents git merge-tree [--write-tree] ... &lt;branch1&gt; &lt;branch2&gt; and notes --write-tree returns the merged tree OID; also lists --no-messages to suppress merge informational output, which is helpful for robust scripting/parsing.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`pack/formulas/merge-stack.toml` documents a branch-deletion safety check based on comparing `origin/main^{tree}` to the tree produced by `git merge-tree --write-tree`. The snippet currently captures `2>&1` into `MERGE_OUTPUT` and then uses `head -1` as the tree OID, but does not validate that the line is actually a Git tree object id.

This makes the check brittle: any diagnostic text (or future output format change) can corrupt the parsed value and incorrectly keep `CONTENT_INCLUDED=false`.

### Issue Context
This is documentation/recipe code, but it is meant to be executed by operators/agents; false negatives increase manual cleanup and reduce trust in the procedure.

### Fix Focus Areas
- pack/formulas/merge-stack.toml[113-129]

### Suggested change
- Keep stdout/stderr separate (don’t use `2>&1` for the value you compare).
- Prefer `git merge-tree --write-tree --no-messages ...`.
- Parse and validate the OID (e.g., match `^[0-9a-f]{40}$` or `git cat-file -t "$MERGED_TREE"` equals `tree`) before comparing it to `BASE_TREE`.
- If validation fails, treat it as “unverified” (current conservative behavior), but make the parsing robust so clean success paths work reliably.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. watchdog.sh changes lack tests ✓ Resolved 📘 Rule violation ▣ Testability
Description
The updated ID-filtering regex and status-field parsing logic in watchdog.sh was changed without
adding or updating any automated test that would fail on regressions. This violates the requirement
that non-trivial implementation changes be covered by tests.
Code

.agents/skills/gc-watchdog/watchdog.sh[R43-44]

+    | { grep -E '^\s*[○◐●] sv-[a-z0-9]{3,}(\.[0-9]+)?($| )' || true; } \
+    | { grep -vE '^\s*[○◐●] sv-(wisp|nudge)(\.[0-9]+)?($|[[:space:]])' || true; } \
Evidence
PR Compliance ID 2649776 requires at least one automated test covering non-trivial code changes. The
updated logic in count_real_issues() (regex) and the status parsing lines were changed here, but
no corresponding watchdog-focused test was added/updated alongside these changes.

Rule 2649776: Require tests for all non-trivial implementation code changes
.agents/skills/gc-watchdog/watchdog.sh[43-44]
.agents/skills/gc-watchdog/watchdog.sh[61-63]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`watchdog.sh`’s filtering/parsing logic was modified (regex changes and `grep` behavior changes) without accompanying automated coverage.

## Issue Context
The compliance checklist requires tests for non-trivial implementation changes; without coverage, these regex/parsing tweaks can silently change counts/health signals and cause incorrect watchdog behavior.

## Fix Focus Areas
- .agents/skills/gc-watchdog/watchdog.sh[43-44]
- .agents/skills/gc-watchdog/watchdog.sh[61-63]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 4cefcc1 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Invalid bash in instructions ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The post-merge cleanup snippet includes the literal line For each lower PR in the stack: inside a
bash-style command block; if a user copy/pastes the block into a shell, this line will run as a
command and error (and may halt the sequence under set -e/automation).
Code

pack/formulas/merge-stack.toml[R105-106]

+     For each lower PR in the stack:
+       # Squash merge creates a new commit on main, so ancestry checks
Evidence
The After merge: section is formatted as a runnable shell sequence (`if ! git fetch origin; then
... else ...), but the newly inserted For each lower PR in the stack:` line is not valid bash
syntax unless it is commented or turned into an actual loop construct.

pack/formulas/merge-stack.toml[94-107]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The merge-stack post-merge instructions contain a non-shell prose line (`For each lower PR in the stack:`) embedded within a sequence of shell commands. If the instructions are copy/pasted as a bash block (or executed under stricter error handling), this will produce a `command not found` error and can interrupt the intended cleanup flow.

### Issue Context
This text sits in the `After merge:` section alongside executable commands (`git fetch origin`, `BASE_TREE=...`, etc.), so readers will naturally treat it as runnable shell.

### Fix Focus Areas
- pack/formulas/merge-stack.toml[105-106]

### Suggested fix
Convert `For each lower PR in the stack:` into a shell comment (e.g., `# For each lower PR in the stack:`) or replace it with an explicit loop skeleton (`for ...; do ... done`) so the block is syntactically valid when copy/pasted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Runbook steps outside engdocs/ ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New/updated engineering runbook content was added to pack/formulas/merge-stack.toml, which is
outside the required engdocs/ directory. This can cause engineering documentation to be scattered
and harder to audit and maintain.
Code

pack/formulas/merge-stack.toml[R98-101]

+   # Fetch origin once before verifying any lower PR; if it fails, none of the
+   # lower PRs can be safely proven as included, so retain all of them.
+   if ! git fetch origin; then
+     echo "WARNING: git fetch origin failed — cannot verify lower PRs; retaining all lower PRs and branches"
Evidence
PR Compliance ID 2663932 requires engineering documentation files touched by the change to be placed
under engdocs/. The modified section in pack/formulas/merge-stack.toml adds/updates
human-oriented runbook instructions (e.g., post-merge verification and PR closing steps) outside
engdocs/.

Rule 2663932: Place engineering documentation under engdocs/ directory
pack/formulas/merge-stack.toml[94-115]
pack/formulas/merge-stack.toml[143-151]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Engineering documentation/runbook content was modified outside `engdocs/`, violating the repository documentation placement requirement.

## Issue Context
`pack/formulas/merge-stack.toml` contains detailed operational instructions (e.g., fetch/verify/close PR workflow). If this guidance is meant to be human-consumed documentation, it should live under `engdocs/` and the formula should link/reference it.

## Fix Focus Areas
- pack/formulas/merge-stack.toml[98-115]
- pack/formulas/merge-stack.toml[143-149]
- pack/formulas/merge-stack.toml[151-151]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

Comment thread scripts/sarif-to-annotations.py Outdated
ThePlenkov and others added 2 commits August 12, 2026 00:03
13 tests covering: empty locations, relative paths, absolute paths,
file:// (triple slash, localhost, single slash, uppercase scheme),
query/fragment stripping, https:// URIs, URL-encoded paths, and
region field extraction.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- sarif-to-annotations.py: validate location coordinates are positive
  integers before emitting (skip non-int/negative/string values to
  prevent workflow-command injection)
- sarif-to-annotations.py: distinguish missing runs field from falsey
  non-list values ({} , "", 0, false now exit 2 instead of passing)
- sarif-to-annotations.py: read from stdin.buffer and check byte length
  (not character count) for accurate 100MB limit on multibyte UTF-8
- gc-watchdog/watchdog.sh: broaden bead ID regex to sv-[a-z0-9]{3,}
  with optional .N hierarchical suffix (was {4,} which excluded
  valid 3-char IDs like sv-a1b and hierarchical sv-a1b.1)
- merge-stack.toml: replace git merge-base --is-ancestor with content
  diff check for squash merges (squash creates new commit, ancestry
  check always fails)
- test_sarif_to_annotations.py: +4 tests for integer validation

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills/gc-watchdog/watchdog.sh:
- Line 43: Update the exclusion matching adjacent to the watchdog’s ID
extraction pipeline so the wisp and nudge filters match only complete IDs,
allowing an optional hierarchical suffix and requiring a field boundary.
Preserve exclusions for exact `sv-wisp` and `sv-nudge` IDs while keeping IDs
such as `sv-wispish` and `sv-nudgeable` in the results.

In `@pack/formulas/merge-stack.toml`:
- Around line 105-107: The merge-stack verification currently compares diff
sizes rather than confirming that lower-branch content exists on origin/main.
Replace the DIFF_ON_MAIN/BRANCH_CHANGES threshold logic in the merge decision
with a content-aware Git check, such as a temporary three-way merge or tree
comparison, and only proceed with PR closure and branch deletion when
verification succeeds; retain the branch when verification is inconclusive. Add
a regression case covering a larger unrelated main diff.

In `@scripts/sarif-to-annotations.py`:
- Around line 230-240: The coordinate validation loop in
scripts/sarif-to-annotations.py (lines 230-240) must reject Boolean values
before the integer check so values such as startLine=True are not emitted;
continue accepting only positive integers. Add a regression test in
scripts/test_sarif_to_annotations.py (lines 110-140) covering startLine=True and
asserting that the invalid coordinate is omitted.

In `@scripts/test_sarif_to_annotations.py`:
- Around line 143-161: Add end-to-end tests invoking main for invalid UTF-8
input, malformed runs, and missing or null runs values, then register them in
TESTS. Each case must assert the expected exit status and corresponding error
output while preserving the existing unit-test coverage.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4b60091f-8cf8-4858-a6ef-70f32eefeb2a

📥 Commits

Reviewing files that changed from the base of the PR and between 1a09aa2 and 4c6d037.

📒 Files selected for processing (4)
  • .agents/skills/gc-watchdog/watchdog.sh
  • pack/formulas/merge-stack.toml
  • scripts/sarif-to-annotations.py
  • scripts/test_sarif_to_annotations.py
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🪛 Ruff (0.16.1)
scripts/test_sarif_to_annotations.py

[warning] 20-20: Missing return type annotation for private function _loc

(ANN202)


[warning] 20-20: Missing type annotation for **region

(ANN003)


[warning] 28-28: Missing return type annotation for private function _file_uri

(ANN202)


[warning] 101-101: Missing return type annotation for private function _annotation_line

(ANN202)


[warning] 101-101: Missing type annotation for **region

(ANN003)


[warning] 106-106: Unpacked variable is_error is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)


[warning] 170-172: try-except within a loop incurs performance overhead

(PERF203)


[warning] 173-173: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (9)
scripts/sarif-to-annotations.py (4)

192-198: Normalize relative URI references.

Line 195 bypasses parsing for relative SARIF URI references. As a result, src/a%20b.ts remains encoded, and relative query or fragment components remain in file. Parse and decode every artifact URI before emitting its path.

  • scripts/sarif-to-annotations.py#L192-L198: apply urlparse and unquote to relative URI references too.
  • scripts/test_sarif_to_annotations.py#L95-L97: add encoded relative-path and relative query/fragment cases.
Proposed fix
-    if "://" in file_uri or "file:/" in file_uri.lower():
-        parsed = urlparse(file_uri)
-        file_uri = unquote(parsed.path)
+    parsed = urlparse(file_uri)
+    file_uri = unquote(parsed.path)
#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from urllib.parse import unquote, urlparse

cases = {
    "src/a%20b.ts": "src/a b.ts",
    "src/a.ts?line=1#fragment": "src/a.ts",
}
for uri, expected in cases.items():
    actual = unquote(urlparse(uri).path).lstrip("/")
    assert actual == expected, (uri, actual, expected)
PY

33-33: LGTM!


257-274: LGTM!


298-302: LGTM!

scripts/test_sarif_to_annotations.py (2)

1-92: LGTM!


164-181: LGTM!

.agents/skills/gc-watchdog/watchdog.sh (3)

63-63: Anchor the Suspended: match at the start of the line.

grep -w "Suspended:" still matches Total Suspended:. Therefore, head -1 can extract the wrong status value. Use an anchored first-match pattern.

Proposed fix
-  SUSPENDED=$(echo "$STATUS" | grep -w "Suspended:" | head -1 | awk '{print $2}')
+  SUSPENDED=$(printf '%s\n' "$STATUS" | grep -m1 -E '^[[:space:]]*Suspended:' | awk '{print $2}')

25-26: LGTM!


61-61: LGTM!

Comment thread .agents/skills/gc-watchdog/watchdog.sh Outdated
Comment thread pack/formulas/merge-stack.toml Outdated
Comment thread scripts/sarif-to-annotations.py
Comment thread scripts/test_sarif_to_annotations.py
devin-ai-integration Bot and others added 2 commits August 11, 2026 23:11
Co-Authored-By: Petr Plenkov <petr.plenkov@gmail.com>
Co-Authored-By: Petr Plenkov <petr.plenkov@gmail.com>
…ests

Co-Authored-By: Petr Plenkov <petr.plenkov@gmail.com>
@ThePlenkov
ThePlenkov marked this pull request as draft August 12, 2026 00:07
Co-Authored-By: Petr Plenkov <petr.plenkov@gmail.com>
@sonarqubecloud

Copy link
Copy Markdown

@ThePlenkov
ThePlenkov marked this pull request as ready for review August 12, 2026 00:14
@cubic-dev-ai

cubic-dev-ai Bot commented Aug 12, 2026

Copy link
Copy Markdown

Running ultrareview automatically — The PR modifies production automation (git merge-stack cleanup with branch deletion, GC watchdog parsing, and SARIF annotation logic) where subtle bugs could cause erroneous branch deletion or broken CI annotations, warranting a deep multi-pass review.. I'll post findings when complete.

@cubic-dev-ai

cubic-dev-ai Bot commented Aug 12, 2026

Copy link
Copy Markdown

I can't run this ultrareview because you've reached your trial's review limit. Trial plans have lower review limits than paid plans. Upgrade now to resume reviews.

To help optimise your usage, you can tune cubic to get the most out of your usage limits:

Learn more →

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

Pull Request Overview

This PR resolves the targeted Codacy findings regarding SARIF normalization and GC watchdog parsing. It also introduces a more robust branch cleanup strategy using git merge-tree to support squash-merge workflows and a new runbook.

While the implementation appears sound and meets the primary acceptance criteria, there is a notable discrepancy between the PR's title/summary ('address 3 Codacy findings') and the actual breadth of changes, which includes significant infrastructure and cleanup logic. Codacy analysis confirms the code is currently up to standards.

About this PR

  • The scope of this PR is broader than the '3 Codacy findings' mentioned in the title. It introduces a new runbook and a complex git-based verification system for merge stacks. While the technical quality is high, ensure this additional scope is intended for this specific fix.

Test suggestions

  • Verify SARIF artifactLocation URIs are correctly normalized from absolute paths and file:// schemes.
  • Ensure SARIF coordinate validation rejects non-integer or non-positive values (including booleans).
  • Test that GC watchdog correctly parses individual status fields and ignores repeated or irrelevant lines.
  • Confirm that real bead IDs are counted while ephemeral wisp/nudge IDs are excluded in the watchdog.
  • Verify that git merge-tree logic correctly identifies content inclusion for squash merges even when ancestry check fails.

TIP Improve review quality by adding custom instructions
TIP How was this review? Give us feedback

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 15aeef3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant