Skip to content

Fix compare validation safety followups - #462

Merged
mohanagy merged 2 commits into
nextfrom
compare-review-followups
Jun 1, 2026
Merged

mohanagy merged 2 commits into
nextfrom
compare-review-followups

Conversation

@mohanagy

@mohanagy mohanagy commented Jun 1, 2026 •

Copy link
Copy Markdown
Owner

Summary\n- disclose native-agent implement validation work in compare warnings and add a dedicated validation timeout\n- bound post-run validation commands and harden targeted test-path command construction\n- fix prerelease README next-only links and extend release hygiene coverage\n\n## Testing\n- npm run release:verify\n- npm run typecheck\n- npm run build\n- CI=1 npm run test:run

Summary by CodeRabbit

  • New Features

    • Added --validation-timeout CLI option for compare (default 120s); warnings surface timeout info when relevant
    • Validation commands now time out instead of hanging during implement runs with native-agent mode
  • Bug Fixes

    • Test paths with special characters or leading - are properly escaped/prefixed to avoid misinterpretation
  • Documentation

    • README telemetry and docs links updated to point to prerelease branch
  • Tests

    • Added coverage for validation timeout behavior, test-path escaping, and prerelease README link checks

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 611f310d-97ab-489d-aaec-12bac30549be

📥 Commits

Reviewing files that changed from the base of the PR and between 3aafbf6 and d70c4c6.

📒 Files selected for processing (1)
  • src/infrastructure/compare.ts

📝 Walkthrough

Walkthrough

This PR adds configurable validation timeouts for native-agent "implement" compare runs, enforces prerelease-only README doc links to target blob/next, and introduces shared shell-escaping utilities used when building test command arguments.

Changes

Validation Timeout and Release Hygiene Enhancements

Layer / File(s) Summary
Shell escaping utility functions
src/shared/shell.ts
shellEscape returns platform-aware single-quoted strings; shellEscapeIfNeeded conditionally applies escaping only when input contains unsafe characters.
Prerelease README link validation
.github/scripts/verify-release-hygiene.mjs, README.md, tests/unit/release-hygiene.test.ts
Release hygiene script enforces that prerelease versions link NEXT_ONLY_README_PATHS documentation to blob/next/... only. README links to telemetry docs updated to next branch. Test fixtures refactored to support custom README content and new test case validates the allowlist behavior for prerelease versions.
CLI validation timeout option
src/cli/parser.ts
CompareCliOptions gains validationTimeoutSeconds: number. parseCompareArgs parses --validation-timeout S / --validation-timeout=S with default 120 seconds and positive-decimal validation; COMPARE_USAGE documents the flag.
CLI compare command warning and timeout forwarding
src/cli/main.ts
New compareWarningMessage(options) helper computes dynamic warnings extending base compare warning when --task implement meets --baseline-mode native_agent, mentioning local validation commands and timeout. CLI forwards validationTimeoutSeconds into runCompareCommand and updates help text and confirmation prompt.
Compare infrastructure validation command timeout
src/infrastructure/compare.ts
GenerateCompareArtifactsInput adds optional validationTimeoutSeconds. runImplementationValidationCommands accepts timeoutMs and runs each command with per-command AbortController timeouts, marking timed-out commands as failed and appending a timeout message to stderr. runShellCommand uses detached process groups on non-Windows and improves abort handling. executeNativeAgentCompare computes and forwards the millisecond timeout to both baseline and Madar validation runs. Local shellEscape removed in favor of the shared import.
Test path shell escaping in implementation pack
src/runtime/implementation-pack.ts
buildImplementationPackGuidance uses shellEscapeIfNeeded and new prefixTestPathFlagLikeArg helper when constructing npm run test:run commands, ensuring test paths with spaces/metacharacters are quoted and paths starting with - are prefixed with ./.
CLI parsing and integration tests
tests/unit/cli.test.ts
parseCompareArgs test cases updated to assert validationTimeoutSeconds (default 120). Help text assertions include --validation-timeout. Integration test verifies --validation-timeout 45 passes through. New test confirms implement+native_agent shows validation timeout in warnings. Usage error strings updated.
Compare infrastructure timeout tests
tests/unit/compare-native-agent.test.ts
New unit test verifies implement-task validation commands time out rather than hang by running executeNativeAgentCompare with a small validationTimeoutSeconds against a fixture with a slow typecheck script.
Implementation pack test path escaping tests
tests/unit/implementation-pack.test.ts
New helper buildQuotedTestPathGraph(testFilePath) and tests validate buildImplementationPackGuidance formats validation_commands correctly: quoting unsafe paths and prefixing dash-leading paths with ./.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

  • mohanagy/madar#461: Both PRs modify release-hygiene verification to enforce prerelease (-) README/changelog link targets resolving to blob/next rather than main.
  • mohanagy/madar#445: Both PRs extend native-agent compare "implement" execution path in src/infrastructure/compare.ts with validation configuration; this PR adds per-command timeouts while that PR extends the implement workflow.
  • mohanagy/madar#366: Both PRs modify executeNativeAgentCompare native-agent flow to add/propagate timeout configuration.

Poem

🐰 I nudge the clocks and tuck commands to rest,
Quoted paths and timeouts help them do their best.
Prerelease notes now point to next with pride,
Safe shells, swift aborts — we hop on with a stride!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Title check ✅ Passed The title accurately describes the main objective: addressing validation safety improvements in the compare command following a review.
Description check ✅ Passed The description covers key changes and includes a testing section with verification commands, meeting template requirements.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch compare-review-followups

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

@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

🧹 Nitpick comments (3)
.github/scripts/verify-release-hygiene.mjs (2)

13-16: 💤 Low value

Consider adding a comment explaining "next-only" paths.

The NEXT_ONLY_README_PATHS allowlist would benefit from a brief comment explaining what makes these paths "next-only" (e.g., documentation that only exists or is only accurate on the next branch for prereleases).

🤖 Prompt for 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.

In @.github/scripts/verify-release-hygiene.mjs around lines 13 - 16, Add a brief
comment above the NEXT_ONLY_README_PATHS Set explaining that these are readme
files that exist or are only accurate on the "next" branch (used for prerelease
builds), why they are allowlisted (to avoid hygiene failures when running
verify-release-hygiene on non-main branches), and give one-sentence examples
(e.g., docs that reference upcoming features or enterprise offers only present
on next). Reference the symbol NEXT_ONLY_README_PATHS and place the comment
immediately above its declaration.

57-61: ⚡ Quick win

Improve error message to show invalid links.

When the assertion fails, developers would benefit from seeing which specific links are invalid and what branch they're pointing to instead of just knowing that "next-only README doc links must target blob/next."

🔍 Proposed enhancement
-  assert.deepEqual(
-    invalidTargets,
-    [],
-    'next-only README doc links must target blob/next for prereleases',
-  )
+  assert.deepEqual(
+    invalidTargets,
+    [],
+    `next-only README doc links must target blob/next for prereleases. Invalid links: ${invalidTargets.join(', ')}`,
+  )
🤖 Prompt for 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.

In @.github/scripts/verify-release-hygiene.mjs around lines 57 - 61, The
assertion on invalidTargets using assert.deepEqual currently provides only a
static message; update the failure output to include the actual invalidTargets
details so devs can see which links and branches are wrong. Change the assertion
around invalidTargets (the assert.deepEqual call) to include the invalidTargets
data in the error string (e.g., serialize invalidTargets with JSON.stringify or
util.inspect) or replace the assert with a conditional throw that constructs a
message containing the descriptive text plus the serialized invalidTargets for
easier debugging.
tests/unit/release-hygiene.test.ts (1)

136-149: 💤 Low value

Consider adding explicit positive test case.

The test validates that incorrect next-only links are rejected, but there's no explicit test showing that a prerelease with correct blob/next links for next-only docs passes validation. While the test at line 88-100 implicitly covers this by running verification on the actual codebase, an explicit positive test case would make the coverage more obvious.

📝 Example test case
it('accepts next-only README doc links that target next for prereleases', () => {
  withReleaseReadmeFixture(
    '0.27.7-next.0',
    [
      '[release notes](https://github.com/mohanagy/madar/blob/next/CHANGELOG.md#0277-next0---2026-05-29)',
      '[enterprise offer](https://github.com/mohanagy/madar/blob/next/docs/team-enterprise-offer.md)',
      '[telemetry](https://github.com/mohanagy/madar/blob/next/docs/telemetry.md)',
      '',
    ].join('\n'),
    (runVerify) => {
      expect(runVerify).not.toThrow()
    },
  )
})
🤖 Prompt for 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.

In `@tests/unit/release-hygiene.test.ts` around lines 136 - 149, Add an explicit
positive test that verifies prerelease READMEs with next-only links pointing to
blob/next pass validation: create a new it(...) using withReleaseReadmeFixture
with a prerelease version like '0.27.7-next.0', provide README lines where
next-only doc links use 'https://.../blob/next/...' (e.g. CHANGELOG and docs
paths), and assert expect(runVerify).not.toThrow(); this mirrors the failing
test but ensures correct next-targeted links in the
withReleaseReadmeFixture/runVerify flow are accepted.
🤖 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 `@src/infrastructure/compare.ts`:
- Around line 3007-3016: runImplementationValidationCommands currently awaits
runShellCommand with an AbortController but can hang if the child
process/descendants don't close promptly; change it to enforce a hard bound like
runNativeAgentArmWithTimeout by wrapping the await in a bounded Promise.race (or
move the logic into runShellCommand) that races the runShellCommand promise
against a timeout promise that resolves/rejects after timeoutMs + optional
grace, calls controller.abort(), and ensures proper cleanup (clearTimeout, kill
child if needed) so the validation path always resolves when timeoutMs elapses;
reference runImplementationValidationCommands, runShellCommand,
runNativeAgentArmWithTimeout, timeoutMs, controller/AbortController and
timeoutHandle when locating where to add the bounded race and cleanup.

In `@src/shared/shell.ts`:
- Around line 2-5: The win32 branch of shellEscape is already using
PowerShell-style single-quote escaping but the code and/or tests imply cmd.exe;
update the implementation and surrounding comment in the shellEscape function so
it explicitly documents and preserves PowerShell-style escaping for Windows
(keep the platform === 'win32' branch that returns the value with doubled single
quotes), and ensure call sites that spawn commands on Windows (which use
powershell.exe -NoProfile -Command with spawn(..., { shell: false })) are
documented to require this PowerShell escaping; reference the shellEscape
function and the platform === 'win32' branch when making the change.

---

Nitpick comments:
In @.github/scripts/verify-release-hygiene.mjs:
- Around line 13-16: Add a brief comment above the NEXT_ONLY_README_PATHS Set
explaining that these are readme files that exist or are only accurate on the
"next" branch (used for prerelease builds), why they are allowlisted (to avoid
hygiene failures when running verify-release-hygiene on non-main branches), and
give one-sentence examples (e.g., docs that reference upcoming features or
enterprise offers only present on next). Reference the symbol
NEXT_ONLY_README_PATHS and place the comment immediately above its declaration.
- Around line 57-61: The assertion on invalidTargets using assert.deepEqual
currently provides only a static message; update the failure output to include
the actual invalidTargets details so devs can see which links and branches are
wrong. Change the assertion around invalidTargets (the assert.deepEqual call) to
include the invalidTargets data in the error string (e.g., serialize
invalidTargets with JSON.stringify or util.inspect) or replace the assert with a
conditional throw that constructs a message containing the descriptive text plus
the serialized invalidTargets for easier debugging.

In `@tests/unit/release-hygiene.test.ts`:
- Around line 136-149: Add an explicit positive test that verifies prerelease
READMEs with next-only links pointing to blob/next pass validation: create a new
it(...) using withReleaseReadmeFixture with a prerelease version like
'0.27.7-next.0', provide README lines where next-only doc links use
'https://.../blob/next/...' (e.g. CHANGELOG and docs paths), and assert
expect(runVerify).not.toThrow(); this mirrors the failing test but ensures
correct next-targeted links in the withReleaseReadmeFixture/runVerify flow are
accepted.
🪄 Autofix (Beta)

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cee63cd9-0f0c-4dda-a4d9-4ac231a387b2

📥 Commits

Reviewing files that changed from the base of the PR and between 091f252 and 3aafbf6.

📒 Files selected for processing (11)
  • .github/scripts/verify-release-hygiene.mjs
  • README.md
  • src/cli/main.ts
  • src/cli/parser.ts
  • src/infrastructure/compare.ts
  • src/runtime/implementation-pack.ts
  • src/shared/shell.ts
  • tests/unit/cli.test.ts
  • tests/unit/compare-native-agent.test.ts
  • tests/unit/implementation-pack.test.ts
  • tests/unit/release-hygiene.test.ts

Comment on lines +3007 to +3016
const controller = new AbortController()
const timeoutHandle = setTimeout(() => {
controller.abort()
}, timeoutMs)
let execution: { exitCode: number; stdout: string; stderr: string }
try {
execution = await runShellCommand(command, { cwd: workspaceRoot, signal: controller.signal })
} finally {
clearTimeout(timeoutHandle)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Show the validation timeout path and the already-bounded native-agent arm timeout path side by side.
sed -n '2948,3038p' src/infrastructure/compare.ts
printf '\n---\n'
sed -n '3499,3567p' src/infrastructure/compare.ts

Repository: mohanagy/madar

Length of output: 5080


Make the validation timeout truly bounded in runImplementationValidationCommands.

runImplementationValidationCommands aborts after timeoutMs, but it still awaits runShellCommand(...). In runShellCommand, the abort handler only does child.kill() and the promise resolves only on child.on('close'), so if the shell/descendants don’t close pipes promptly, the await can hang past --validation-timeout. Wrap runShellCommand with the same kind of bounded Promise.race/grace approach used by runNativeAgentArmWithTimeout (or move the bound into runShellCommand) so the validation path resolves/times out even if the process doesn’t settle quickly.

🤖 Prompt for 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.

In `@src/infrastructure/compare.ts` around lines 3007 - 3016,
runImplementationValidationCommands currently awaits runShellCommand with an
AbortController but can hang if the child process/descendants don't close
promptly; change it to enforce a hard bound like runNativeAgentArmWithTimeout by
wrapping the await in a bounded Promise.race (or move the logic into
runShellCommand) that races the runShellCommand promise against a timeout
promise that resolves/rejects after timeoutMs + optional grace, calls
controller.abort(), and ensures proper cleanup (clearTimeout, kill child if
needed) so the validation path always resolves when timeoutMs elapses; reference
runImplementationValidationCommands, runShellCommand,
runNativeAgentArmWithTimeout, timeoutMs, controller/AbortController and
timeoutHandle when locating where to add the bounded race and cleanup.

Comment thread src/shared/shell.ts
Comment on lines +2 to +5
if (platform === 'win32') {
return `'${value.replaceAll("'", "''")}'`
}
return `'${value.replaceAll("'", `'\"'\"'`)}'`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Locate all usages of shell escaping helpers
rg -n --type=ts -C3 '\bshellEscape(IfNeeded)?\b' src

# 2) Locate process execution callsites
rg -n --type=ts -C4 '\b(exec|execFile|spawn)\s*\(' src

# 3) Confirm whether shell mode is enabled and which shell is configured
rg -n --type=ts -C4 'shell\s*:' src

Repository: mohanagy/madar

Length of output: 11834


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find any cmd.exe usage
rg -n --type=ts 'cmd\.exe' src

# Show how shellEscape is consumed (compare + implementation-pack)
rg -n --type=ts 'shellEscapeIfNeeded|shellEscape\(' src/infrastructure/compare.ts src/runtime/implementation-pack.ts src/infrastructure/review-compare.ts src/shared/shell.ts

# Inspect the Windows execution branches near the earlier spawn callsites
sed -n '220,280p' src/infrastructure/review-compare.ts
sed -n '360,460p' src/infrastructure/compare.ts
sed -n '2890,2990p' src/infrastructure/compare.ts
sed -n '1310,1375p' src/runtime/implementation-pack.ts

Repository: mohanagy/madar

Length of output: 40


🏁 Script executed:

#!/bin/bash
set -euo pipefail

ls -la src/infrastructure src/runtime src/shared || true
ls -la src/infrastructure | head

# Find any cmd.exe usage
rg -n --type=ts 'cmd\.exe' src || true

# Show how shellEscape is consumed
rg -n --type=ts 'shellEscapeIfNeeded|shellEscape\(' \
  src/infrastructure/compare.ts src/runtime/implementation-pack.ts src/infrastructure/review-compare.ts src/shared/shell.ts || true

# Print relevant Windows execution branches (bounded reads)
if [ -f src/infrastructure/review-compare.ts ]; then
  nl -ba src/infrastructure/review-compare.ts | sed -n '200,280p'
fi
if [ -f src/infrastructure/compare.ts ]; then
  nl -ba src/infrastructure/compare.ts | sed -n '280,460p'
  nl -ba src/infrastructure/compare.ts | sed -n '2890,3020p'
fi
if [ -f src/runtime/implementation-pack.ts ]; then
  nl -ba src/runtime/implementation-pack.ts | sed -n '1290,1385p'
fi

Repository: mohanagy/madar

Length of output: 7223


Fix Windows quoting concern in shellEscape: it’s PowerShell, not cmd.exe.

The win32 branch in src/shared/shell.ts returns PowerShell-style single-quoted strings ('...' with doubled '), and the call sites on Windows execute commands via powershell.exe -NoProfile -Command ... with spawn(..., { shell: false }) (not cmd.exe). So single-quote escaping here is appropriate for the actual execution shell.

🤖 Prompt for 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.

In `@src/shared/shell.ts` around lines 2 - 5, The win32 branch of shellEscape is
already using PowerShell-style single-quote escaping but the code and/or tests
imply cmd.exe; update the implementation and surrounding comment in the
shellEscape function so it explicitly documents and preserves PowerShell-style
escaping for Windows (keep the platform === 'win32' branch that returns the
value with doubled single quotes), and ensure call sites that spawn commands on
Windows (which use powershell.exe -NoProfile -Command with spawn(..., { shell:
false })) are documented to require this PowerShell escaping; reference the
shellEscape function and the platform === 'win32' branch when making the change.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy
mohanagy merged commit 3bf8060 into next Jun 1, 2026
7 checks passed
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.

1 participant