Skip to content

fix(#5705): run the post-script when the scan was the only failure - #10085

Draft
andrewevansrh wants to merge 3 commits into
fullsend-ai:mainfrom
andrewevansrh:agent/5705-post-script-gating
Draft

andrewevansrh wants to merge 3 commits into
fullsend-ai:mainfrom
andrewevansrh:agent/5705-post-script-gating

Conversation

@andrewevansrh

Copy link
Copy Markdown
Contributor

Stacked PR — do not merge before #10084 (which needs #10082). Draft on
purpose: this branch is #10082 + #10084 plus one commit, so the diff shown here
is cumulative. Review the delta with
git diff agent/5705-spanning-private-keys..agent/5705-post-script-gating.
Once the two below it land on main, this is rebased onto main, its diff
shrinks to its own commit, and it is marked ready for review.

Summary

Part 3 of 3 split out of #9699 (part 1: #10082, part 2: #10084).

A failed output scan fails the run, and the gate that decides whether to run the
post-script treated every scan failure as fatal to posting, so a completed review
was thrown away because one unrelated file somewhere else under the run directory
could not be sanitized.

What changed

  • internal/cli/run.go: the gate runs the post-script when a scan failure is
    the run's only failure and the harness result file (agent-result.json by
    default) survived the scan and still holds a JSON object. Causes are kept apart
    instead of flattened into one joined error — postScanArtifactsError carries
    the scan and chain outcomes and postScanError the terminal outcome — so a run
    that also timed out, broke its audit chain or reported a transcript error keeps
    that cause's outcome, and a broken chain vetoes posting regardless of the scan.
    A result file the scan replaced with a fail-closed marker, or one the scan
    failed on and could not quarantine, is never posted.
  • quiet: the printed log counts the paths a failed scan could not handle
    instead of naming them (ADR 0163), and the completion comment does the same,
    since an output file name is the agent's to choose and Actions log masking does
    not apply to a comment. The run error and telemetry keep the path at every
    level.

Verification

  • go test ./internal/cli (one unrelated pre-existing failure,
    TestPrepare_LocallyPresentImageSkipsPullButRunsPreflight, fails on main too)
  • go test ./internal/security/
  • make lint

Note: Generated with assistance from DeepSeek V4.1 Flash

…slashes

The output sanitizer ran every pattern as a raw text replace over all
output files. When an agent quoted code inside a JSON string value, a
pattern matched up to the quote delimiter and swallowed the backslash
escaping it, so the rewritten document was no longer valid JSON and
downstream jq in post-review.sh failed with exit status 5.

Two changes close that:

- SanitizeJSONDocument and SanitizeJSONLines rewrite JSON output through
  a token-preserving walk instead of a text replace. Every object key and
  scalar leaf is scanned on its own and re-encoded, so redaction inside a
  value cannot touch the framing. Member order, duplicate keys and exact
  number literals survive, a leading UTF-8 BOM is stripped and restored,
  and a clean document comes back byte for byte.
- The redactor no longer includes a delimiter-escaping backslash in a
  captured value, and Mask returns "***" when the prefix it would keep
  carries an escape or a quote delimiter, so the mask itself can never
  break the string it is spliced into.

Content that cannot be redacted in place is replaced with a valid
fail-closed JSON marker rather than corrupted JSON, and the marker reason
is reported to the operator.

BREAKING CHANGE: a JSON document or JSONL record whose secret cannot be
localized is now replaced with a `{"error":"output removed because …"}`
marker instead of being written back with a broken or partial redaction,
so tooling that reads those files sees the marker where the agent's
content used to be.

Signed-off-by: anevans <anevans@redhat.com>
… or records

A JSON document can carry a private key one fragment per member: BEGIN in
one string, body lines in the next, END in a third. Masking any single
member removes the marker the block's own pattern needs, and the bytes
scan that runs after the rewrite sees no block any more, so the body was
written back in clear text.

Such a block is now detected on a decoded view of the document or stream,
before anything is rewritten, and neutralized member by member. The
boundary members always carry marker text and are masked even when a
marker is split across two of them; a member in between is masked when it
carries a marker, a run that looks like PEM body material, or joins with
its neighbours into text that does. Object keys keep their names unless
the name itself is block content, so a review that merely quotes the PEM
header in one finding and the footer in another keeps the shape and the
enum values review-result.schema.json requires, instead of being dropped
by schema validation. Records carrying part of a block across a record
boundary are replaced with a fail-closed marker, because the record
framing cannot be rewritten.

A body split so that one-character and longer chunks alternate is a known
residual; uniform chunks and complete body lines are masked.

Signed-off-by: anevans <anevans@redhat.com>
… failure

A failed output scan fails the run, and the gate that decides whether to
run the post-script treated every scan failure as fatal to posting, so a
completed review was thrown away because one unrelated file somewhere
else under the run directory could not be sanitized.

The gate now runs the post-script when a scan failure is the run's only
failure and the harness result file survived the scan and still holds a
JSON object. Causes are kept apart rather than flattened into one join:
the scan and chain outcomes are carried in a postScanArtifactsError and
the terminal outcome in a postScanError, so a run that also timed out,
broke its audit chain or reported a transcript error keeps that cause's
outcome, and a broken chain vetoes posting regardless of the scan. A
result file the scan replaced with a fail-closed marker, or one the scan
failed on and could not quarantine, is never posted.

At quiet, the printed log counts the paths a failed scan could not handle
instead of naming them (ADR 0163), and the completion comment does the
same, since an output file name is the agent's to choose and Actions log
masking does not apply to a comment. The run error and telemetry keep the
path at every level.

Signed-off-by: anevans <anevans@redhat.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 4:01 PM UTC · Completed 4:15 PM UTC

Commit: 2399a12 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $3.10

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

Site preview

Preview: https://d91f6daf-site.fullsend-ai.workers.dev

Commit: 2399a129e9bae9f3caaa8014b0a5c4f361b4ac16

@fullsend-ai-review fullsend-ai-review Bot added the risk/moderate PR risk: moderate label Dec 3, 2026
@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Large cumulative diff and high churn in CLI run logic are balanced by zero protected path or dependency changes, solid test coverage, an established contributor, and a clear linked issue without risk labels or unresolved discussions.

@fullsend-ai-review

Copy link
Copy Markdown

Review

Dependency scoping was not applied: the stacked parent PR #10084 is a draft and unapproved, so the full cumulative diff was reviewed.

Findings

High

  • [fail-open] internal/cli/run.go:4496 — The failed-result veto checks a different iteration from the one a post-script can consume. The gate is always given iteration-<runCount>/output, but the post-loop validation sweep can select an earlier iteration (validatedIterNum) that the post-script receives via FULLSEND_VALIDATED_ITERATION_DIR. If sanitization and quarantine fail for that earlier result while the final iteration's result is clean, failedOn checks only the final result and the new scan-only branch permits the post-script, so the earlier unredacted result can be published. Previously any scan failure skipped the post-script.
    Remediation: Resolve the output directory the post-script will actually consume (iteration-<validatedIterNum>/output when applicable) before invoking the gate and apply both the veto and result parsing to it. Add a regression test with a sweep-selected earlier iteration whose sanitization and quarantine fail.

Medium

  • [secret-exposure] internal/security/jsonsanitize.go:484 — isSchemaConstrainedField trusts the member name without validating the value. A PEM body split into chunks under the 16-character textCarriesKeyMaterial floor and stored under schema-named members (e.g. file) between masked BEGIN/END markers survives in order, and the final whole-value scan cannot recognize the block once its markers are masked. The JSONL path has the same exemption. Needs a deliberately adversarial layout.
    Remediation: Validate exempted values against the schema's enum/pattern, or conservatively mask short base64-like fragments under those keys inside a detected PEM span. Add JSON and JSONL regression tests.
  • [logic-error] internal/security/jsonsanitize.go:416 — In spanningPrivateKeys the main loop masks any string between a spanning BEGIN/END pair when valueCarriesKeyMaterial(i) is true, without the isSchemaConstrainedField check that only maskSpanBody applies. A valid review that quotes both markers will have an intervening schema-constrained value such as "repo": "ExampleOrg2/ExampleRepo" replaced with the private-key mask, violating the schema's repo pattern and recreating the lost-review failure this change targets.
    Remediation: Distinguish schema-constrained values from PEM material before the per-leaf heuristic, in both the document and JSONL paths, and add regression cases with mixed-case, digit-containing repository names and paths between quoted markers.
  • [architectural-conflict] internal/cli/run.go:4532 — The new scanOnly && !transcriptErrorOverride branch runs the credentialed post-script after a failed output scan. The gate vetoes on the result file itself, but other files the scan could not handle remain in the output directory, so a post-script reading beyond the result file could consume unsanitized content.
    Remediation: Quarantine or remove every file the scan failed on before running the post-script in this case, or document that post-scripts must read only the result file after a scan failure.
  • [incomplete-doc] docs/cli/run.md:468 — The 'How a run ends' section (not modified by this PR) omits output-scan and audit-chain failures, and does not say that a scan failure as the run's only failure still runs the post-script when the result file survived the scan and parses as a JSON object, or that a fail-closed removal marker never qualifies. The behavior is documented only in docs/contributing/runtime-implementation.md.
    Remediation: Update docs/cli/run.md under '## How a run ends' consistently with the new runtime-implementation text.

Low

  • [edge-case] internal/security/jsonsanitize.go:184 — Framing-spanning registered runtime secrets are checked only after rewriteJSONTokens drops inter-token whitespace, so a registered literal containing framing with whitespace can stop matching and its fragments survive instead of failing closed. The trigger is contrived.
    Remediation: Optionally detect such matches on the original bytes before the rewrite and add an overlapping-rewrite test.

Labels: PR changes Go code in the run command and output sanitizer.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

@fullsend-ai-review fullsend-ai-review 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.

See the review comment for full details.

Comment thread internal/cli/run.go
var scanErr *outputScanError
scanFailed := errors.As(runErr, &scanErr)
if scanFailed {
if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[high] fail-open

The failed-result veto checks a different iteration from the one a post-script can consume. The caller always passes iteration-/output to postScriptGate, but the post-loop validation sweep can select an earlier iteration (validatedIterNum) and the post-script environment then supplies that earlier directory via FULLSEND_VALIDATED_ITERATION_DIR. If sanitization and quarantine fail for the earlier selected result while the final iteration has a clean, parseable result, failedOn checks only the final result and the new scan-only branch permits the post-script, so the earlier unredacted result can be published. Before this change any scan failure skipped the post-script, so the exposure is new.

Suggested fix: Resolve the output directory the post-script will actually consume (iteration-/output when validation_loop is set and validatedIterNum > 0) before invoking the gate, and apply both the scan-failure veto and result parsing to that directory. Add a regression test with a sweep-selected earlier iteration whose sanitization and quarantine fail and a clean final-iteration result.

continue
}
valBytes := v.decoded.Bytes()[v.ranges[i].start:v.ranges[i].end]
if isSchemaConstrainedField(v.memberKeys[i], string(valBytes)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] secret-exposure

The schema-field exemption (isSchemaConstrainedField) trusts the member name without validating the value, so a PEM body split into chunks shorter than textCarriesKeyMaterial's 16-character floor and stored under schema-named members (e.g. "file") between masked BEGIN/END markers survives in order; the final whole-value scan cannot recognize the block once its markers are masked. The JSONL path has the same exemption. Exploitation needs a deliberately adversarial layout (the commit documents comparable residuals), so severity is medium.

Suggested fix: Do not exempt values solely because the member name resembles a review-schema field: validate the value against the schema's enum/pattern, or conservatively mask short base64-like fragments under those keys inside a detected PEM span. Add JSON and JSONL regression tests with a real key body split into short chunks.

}
continue
}
if atBoundary || v.valueCarriesKeyMaterial(i) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] logic-error

In spanningPrivateKeys the main loop masks any string between a spanning BEGIN/END pair when valueCarriesKeyMaterial(i) is true, without the isSchemaConstrainedField check that only maskSpanBody applies. A valid review that quotes the BEGIN marker in one string and the END marker in a later one will have an intervening schema-constrained value such as "repo": "ExampleOrg2/ExampleRepo" (matches privateKeyMaterialRe and pemBodyRun) replaced with the private-key mask, violating review-result.schema.json's repo pattern and recreating the lost-review failure this change targets. Mixed-case paths containing a digit are affected the same way.

Suggested fix: Distinguish valid schema-constrained values from PEM material before applying the per-leaf heuristic, consistently in the document and JSONL paths, and add regression cases with mixed-case, digit-containing repository names and paths between quoted markers.

Comment thread internal/cli/run.go
// completed report into silence: when the agent's own result file survived
// the scan and still parses, the post-script runs and the run still fails
// (#5705).
if scanOnly && !transcriptErrorOverride {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] architectural-conflict

The new scanOnly && !transcriptErrorOverride branch runs the credentialed post-script after a failed output scan. The gate vetoes on the harness result file itself (failedOn, removal-marker rejection), but other files the scan could not handle remain in the output directory, so a post-script that reads beyond the result file could consume unsanitized content, weakening the fail-closed stance of host-side output scanning.

Suggested fix: Quarantine or remove every file the scan failed on before running the post-script in this case, or document explicitly that post-scripts must read only the result file when a scan failure occurred.

// a leaf scan cannot see: a runtime value or a private-key block that spans
// JSON framing (for example a PEM block split across members) and so cannot
// be mapped back to a single leaf.
sanitizedOut, outputFindings := redactJSONOutput(out, p)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] edge-case

Runtime secrets that span JSON framing are checked only after rewriteJSONTokens, which re-renders the document without original inter-token whitespace whenever any leaf forces a rewrite. A registered runtime literal containing framing with whitespace (e.g. "part-a", "next":"part-b") then no longer matches the rewritten bytes and both fragments survive instead of failing closed. The trigger is contrived (a real secret containing a quote appears escaped inside a JSON string), hence low.

Suggested fix: Optionally detect framing-spanning registered runtime matches on the original bytes before the rewrite, and add an overlapping-rewrite test for documents and JSONL streams.

@fullsend-ai-review fullsend-ai-review Bot added go Pull requests that update go code component/runner Agent runner behavior and lifecycle labels Dec 3, 2026
@codecov

codecov Bot commented Dec 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.85795% with 65 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/security/jsonsanitize.go 90.89% 35 Missing and 24 partials ⚠️
internal/security/redactor.go 86.95% 4 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

andrewevansrh added a commit to andrewevansrh/fullsend that referenced this pull request Dec 3, 2026
…slashes

The output sanitizer ran every pattern as a raw text replace over all
output files. When an agent quoted code inside a JSON string value, a
pattern matched up to the quote delimiter and swallowed the backslash
escaping it, so the rewritten document was no longer valid JSON and
downstream jq in post-review.sh failed with exit status 5.

Three changes address that:

- The redactor no longer includes a delimiter-escaping backslash in a
  captured value, and Mask returns "***" when the prefix it would keep
  carries an escape or a quote delimiter, so the mask itself can never
  break the string it is spliced into. A double-quoted json_field value
  that ends in a literal backslash is matched by a bounded branch that
  keeps the closing quote out of the capture, so an adjacent field's
  delimiter and credential are no longer swallowed.
- The json_field pattern spans escaped and multiline quoted values
  without running on to a later field's quote.
- SanitizeJSONDocument and SanitizeJSONLines add a structural path:
  JSON output is rewritten by a token-preserving walk instead of a text
  replace. Every object key and scalar leaf is scanned on its own and
  re-encoded, so redaction inside a value cannot touch the framing.
  Member order, duplicate keys and exact number literals survive, a
  leading UTF-8 BOM is stripped and restored, and a clean document comes
  back byte for byte. Content that cannot be redacted in place is
  replaced with a valid fail-closed JSON marker rather than corrupted
  JSON, and a cross-record match replaces only the records it covers.

The structural path is a library primitive at this commit: the CLI output
scan still calls the text pipeline, and wiring it in, with the operator
alert for a replaced file, lands in the stacked PR that changes
scanOutputFiles (fullsend-ai#10085).

BREAKING CHANGE: a value masked as json_field now yields "***" instead of
its first four bytes plus "..." whenever that prefix would carry a
backslash or a quote delimiter, and json_field matches escaped-quote and
multiline quoted values that it previously did not, so sanitized output
text and finding details differ for those inputs.

Signed-off-by: anevans <anevans@redhat.com>
andrewevansrh added a commit to andrewevansrh/fullsend that referenced this pull request Dec 3, 2026
…slashes

The output sanitizer ran every pattern as a raw text replace over all
output files. When an agent quoted code inside a JSON string value, a
pattern matched up to the quote delimiter and swallowed the backslash
escaping it, so the rewritten document was no longer valid JSON and
downstream jq in post-review.sh failed with exit status 5.

Three changes address that:

- The redactor no longer includes a delimiter-escaping backslash in a
  captured value, and Mask returns "***" when the prefix it would keep
  carries an escape or a quote delimiter, so the mask itself can never
  break the string it is spliced into. A double-quoted json_field value
  that ends in a literal backslash is matched by a bounded branch that
  keeps the closing quote out of the capture, so an adjacent field's
  delimiter and credential are no longer swallowed.
- The json_field pattern spans escaped and multiline quoted values
  without running on to a later field's quote.
- SanitizeJSONDocument and SanitizeJSONLines add a structural path:
  JSON output is rewritten by a token-preserving walk instead of a text
  replace. Every object key and scalar leaf is scanned on its own and
  re-encoded, so redaction inside a value cannot touch the framing.
  Member order, duplicate keys and exact number literals survive, a
  leading UTF-8 BOM is stripped and restored, and a clean document comes
  back byte for byte. Content that cannot be redacted in place is
  replaced with a valid fail-closed JSON marker rather than corrupted
  JSON, and a cross-record match replaces only the records it covers.

The structural path is a library primitive at this commit: the CLI output
scan still calls the text pipeline, and wiring it in, with the operator
alert for a replaced file, lands in the stacked PR that changes
scanOutputFiles (fullsend-ai#10085).

BREAKING CHANGE: a value masked as json_field now yields "***" instead of
its first four bytes plus "..." whenever that prefix would carry a
backslash or a quote delimiter, and json_field matches escaped-quote and
multiline quoted values that it previously did not, so sanitized output
text and finding details differ for those inputs.

Signed-off-by: anevans <anevans@redhat.com>
andrewevansrh added a commit to andrewevansrh/fullsend that referenced this pull request Dec 3, 2026
…slashes

The output sanitizer ran every pattern as a raw text replace over all
output files. When an agent quoted code inside a JSON string value, a
pattern matched up to the quote delimiter and swallowed the backslash
escaping it, so the rewritten document was no longer valid JSON and
downstream jq in post-review.sh failed with exit status 5.

Three changes address that:

- The redactor no longer includes a delimiter-escaping backslash in a
  captured value, and Mask returns "***" when the prefix it would keep
  carries an escape or a quote delimiter, so the mask itself can never
  break the string it is spliced into. A double-quoted json_field value
  that ends in a literal backslash is matched by a bounded branch that
  keeps the closing quote out of the capture, so an adjacent field's
  delimiter and credential are no longer swallowed.
- The json_field pattern spans escaped and multiline quoted values
  without running on to a later field's quote.
- SanitizeJSONDocument and SanitizeJSONLines add a structural path:
  JSON output is rewritten by a token-preserving walk instead of a text
  replace. Every object key and scalar leaf is scanned on its own and
  re-encoded, so redaction inside a value cannot touch the framing.
  Member order, duplicate keys and exact number literals survive, a
  leading UTF-8 BOM is stripped and restored, and a clean document comes
  back byte for byte. An array under a sensitive member keeps that
  member's name for its elements, so a token list is masked even when an
  element matches no pattern of its own; a nested object does not, since
  its members carry their own names. Content that cannot be redacted in place is
  replaced with a valid fail-closed JSON marker rather than corrupted
  JSON, and a cross-record match replaces only the records it covers.

The structural path is a library primitive at this commit: the CLI output
scan still calls the text pipeline, and wiring it in, with the operator
alert for a replaced file, lands in the stacked PR that changes
scanOutputFiles (fullsend-ai#10085).

BREAKING CHANGE: a value masked as json_field now yields "***" instead of
its first four bytes plus "..." whenever that prefix would carry a
backslash or a quote delimiter, and json_field matches escaped-quote and
multiline quoted values that it previously did not, so sanitized output
text and finding details differ for those inputs.

Signed-off-by: anevans <anevans@redhat.com>

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Council verdict: REQUEST CHANGES (4 of 7 personas requested changes: adversary, fullsend, gaze-testing, testing; architect approved with advisories, curator and guard approved)

This PR is part 3 of the #5705 stack: the post-script now runs when the output scan is the only failure and the result file survived and still parses as JSON, while the run itself still fails and the causes stay separate (postScanError). The core gate idea is sound. Two HIGH findings block: the gate veto checks the wrong directory, and the new telemetry tests mutate shared global state.

High

  1. internal/cli/run.go:4496: the gate veto checks the final iteration output dir while the post-script consumes FULLSEND_VALIDATED_ITERATION_DIR (the earlier validated iteration). An unredacted earlier result stays publishable, and no new test models the multi-iteration layout. Four personas (adversary, fullsend, gaze-testing, testing) converged here; this confirms the standing review's high finding at this line.
  2. internal/cli/scan_output_telemetry_test.go:180: tests mutate the shared runtime-secret registry and toggle GITHUB_ACTIONS across subtests sharing process state; races under -race -parallel.

Medium (6): symlink-following scan and quarantine (run.go:7465); unsanitized sibling files reachable by the post-script in the scan-only branch (run.go:4530); agentResultFile marker rejections without direct contract tests (run.go:4628); discarded AppendFinding errors plus a security dir that does not exist until after the scan (run.go:7536); root-skip on the quarantine and unreadable-file tests, which skip on the merging platform (scan_output_telemetry_test.go:320); marker-replaced result file reaching the post-script on a successful scan (run.go:4630).

Low (6): triplicated finding-handling blocks (run.go:7568); docs framing count-only logging as quiet-mode behavior (runtime-implementation.md:667); testify and jq subprocess conventions in the new gate tests (run_postscan_test.go:12); nine fixtures bundled in one test function (scan_output_telemetry_test.go:111); ~250 new lines in the run.go God file (run.go:4389); seven positional parameters on scanOutputFilesWithWriter (run.go:7451).

CI: all checks pass or skip; no PR-caused failures. Local gates did not run: the PR head comes from a fork whose author has read permission, so the code is not fetched or run automatically (UNTRUSTED_HEAD).

From what I can tell, the gate design and its error taxonomy hold up; the directory mismatch in the veto is the one thing standing between this and an approve.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread internal/cli/run.go
var scanErr *outputScanError
scanFailed := errors.As(runErr, &scanErr)
if scanFailed {
if resultFile, ok := agentResultFile(h, outputDir); ok && scanErr.failedOn(resultFile) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[HIGH] security: gate veto checks the final iteration output dir, not the one the post-script consumes

The veto here checks scanErr.failedOn(agentResultFile(...)) against outputDir, the final run directory; run.go:2499 builds it as filepath.Join(runDir, iteration-runCount, output). The post-script instead consumes the result under FULLSEND_VALIDATED_ITERATION_DIR, which points at the earlier sweep-validated iteration.

Would the gate still pass when iteration 2's result fails sanitization or gets quarantined while iteration 3 is clean? failedOn names only the final iteration's file, the scan-only branch runs, and the post-script reads the still-unredacted earlier result.

None of the 13 new TestPostScriptGate subtests models this multi-iteration layout; the loop subtests all use validationPassed=false. A regression test in the run_validation_loop_test.go harness (two iterations, sweep validates iteration 1, outputScanError.failedOn names iteration-1/output/agent-result.json, final iteration clean) would pin the intended refusal.

This confirms the standing review's high finding at this line. (adversary, fullsend, gaze-testing, testing)

} {
content, err := os.ReadFile(p.path)
require.NoError(t, err)
assert.True(t, json.Valid(content), "sanitized %s must remain valid JSON: %s", filepath.Base(p.path), string(content))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[HIGH] test-isolation: shared global registry and env mutation across subtests

These tests call ResetRuntimeSecretsForTest and RegisterRuntimeSecret on a package-level slice guarded only by an RWMutex, and toggle GITHUB_ACTIONS with t.Setenv across subtests that share process state (TC-002, TC-004).

What happens under go test -race with parallel subtests, or once these subtests adopt t.Parallel()? The registry mutations race between subtests, and t.Setenv panics inside parallel tests.

Worth moving each fixture into a subtest that owns its registry state, or injecting the registry per test? That keeps the suite safe as it grows. (gaze-testing)

Comment thread internal/cli/run.go
unreadable, unwritable := 0, 0
// At quiet, unreadable, unwritable and unsanitizable files are counted, not
// named, in the printed log. The collected failures still name each file and
// wrap its cause, so telemetry keeps the full text, and the returned error's

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[MEDIUM] path-safety: scan and quarantine follow filesystem symlinks unverified

The walk callback passes raw walked paths to os.ReadFile, writeFile, and quarantineOutput's os.WriteFile/os.Remove. Nothing calls os.Lstat or verifies the resolved path stays under outputDir.

Could an agent-created symlink under the run dir redirect the scan read, or the fail-closed marker write, to host files outside the output tree? The walk reports the entry as a file, so containment checks never see the redirection.

Worth adding an os.Lstat symlink check, or resolving each path and confirming containment under outputDir, before any read or write? (adversary)

Comment thread internal/cli/run.go
// A scan failure fails the run, but one unreadable, unwritable or
// unsanitizable file anywhere under the run directory must not turn a
// completed report into silence: when the agent's own result file survived
// the scan and still parses, the post-script runs and the run still fails

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[MEDIUM] security: scan-only post-script path leaves unsanitized sibling files reachable

quarantineOutput contains write, read, and sanitize failures, but walk failures on directories are recorded without quarantine, and a failure to quarantine a read-only file leaves the original in place with only a generic error.

In the scan-only branch the post-script runs while such files remain in the output dir. Could post-script globbing beyond agent-result.json consume unredacted bytes from a sibling the scan could not handle?

This is the residual of the standing review's medium finding here: the gate now vetoes the run on the result file itself, and the open question is whether every file the scan could not handle is quarantined or removed before the post-script starts. (fullsend)

Comment thread internal/cli/run.go
if json.Unmarshal(data, &obj) != nil || obj == nil {
return "", false
}
// A file the output scan replaced with a fail-closed marker is valid JSON

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[MEDIUM] contract-coverage: agentResultFile's new rejection paths have no direct contract tests

agentResultFile now returns not-a-result for security.OutputRemoval markers and for unwritableOutputMarker bytes. Both new contractual returns are exercised only indirectly through postScriptGate; no test asserts the (path, ok) return directly.

Would a table-driven contract test over the marker variants keep these rejections pinned as the function grows? Right now a regression in the marker comparison surfaces only as an indirect gate behavior change. (gaze-testing)

the marker from every later scan, so such a block is detected on a decoded view
of the document or stream before anything is rewritten, and handled where it
lives. The members the match starts and ends in carry marker text, so they are
always masked — even when a marker is split across two members and neither

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[LOW] documentation: count-only logging is framed as quiet-mode behavior

This passage says that in quiet mode the printed log counts unscannable files, but the code now counts at every verbosity without a per-file StepWarn; the counters increment regardless and the warning is quiet-gated per finding.

Is the doc describing the old behavior, or is the intent that counting stays quiet only? Either the doc needs an update or the quiet gating returns; worth aligning the two. (fullsend)

"path/filepath"
"strings"
"testing"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[LOW] test-conventions: testify and jq subprocess diverge from the repo's testing conventions

This new file mixes testify assert/require with a jq subprocess (exec.LookPath plus exec.Command, no testing.Short guard), which diverges from go.md TC-001, TC-002, and TC-011. The choice is consistent with some existing codebase patterns, so this reads as a convention question rather than a defect.

Is the jq dependency intentional, given the suite otherwise parses JSON in process? (gaze-testing)

// file was valid JSON before sanitization, scanOutputFiles structurally sanitizes
// string leaves so that the file on disk remains structurally valid JSON and
// secrets are completely redacted (fail-closed, #5705).
func TestScanOutputFiles_PreservesJSONStructuralValidity(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[LOW] test-structure: nine fixtures bundled in one function with interleaved setup

TestScanOutputFiles_PreservesJSONStructuralValidity declares nine fixtures in one function; jsonFile8 is set up between fixtures 5 and 6, and assertions interleave with setup. A mid-test require failure aborts the remaining fixtures.

Would table-driven or per-fixture subtests fit here, matching TestPostScriptRepoEnv and TestFailureStatusDetail in the same package? (testing)

Comment thread internal/cli/run.go
@@ -4399,6 +4389,72 @@ func runTerminalError(hasLoop, validationPassed, timedOut bool, exitCode int, ex
return nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[LOW] architectural-patterns: post-scan error taxonomy and control flow add ~250 lines to run.go

The new postScanError, postScanArtifactsError, and outputScanError types, their helpers, and the gate helpers land in run.go, already the largest file in the package. The scan, quarantine, and gate logic is cohesive enough to live in a dedicated scan_output.go (AP-004).

Is a follow-up extraction worth scheduling, or would moving it now churn the stacked PRs? (architect)

Comment thread internal/cli/run.go
// failure without introducing mutable package state.
type sanitizeDocumentFn func([]byte, *security.Pipeline) ([]byte, []security.Finding, error)

// sanitizeLinesFn sanitizes one JSONL stream record by record.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[LOW] coding-conventions: scanOutputFilesWithWriter takes seven positional parameters

The signature carries outputDir, traceID, progressVerbosity, printer, writeFile, sanitizeDocument, sanitizeLines. That is at the threshold where an options struct reads better, especially with the test seams already grouped (AP-001, AP-002).

Worth a small scanOptions struct in a follow-up, or is the parameter list settled now that the tests inject through it? (architect)

This branch was successfully deployed

1 active deployment
site-preview — 2399a129 Deployed Dec 3, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component/runner Agent runner behavior and lifecycle go Pull requests that update go code risk/moderate PR risk: moderate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants