Skip to content

Commit 37e23ad

Browse files
authored
refactor: consolidate scanner evidence checks and judge input handling (#184)
* refactor: share scanner evidence handling and fixture helpers * test(runtime): qualify the reviewed evidence trimming source
1 parent a7fe574 commit 37e23ad

15 files changed

Lines changed: 111 additions & 213 deletions

‎.github/workflows/runtime-image-production-contract.yml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ permissions:
88

99
jobs:
1010
native:
11-
name: Qualify locked production SDKs (040f4fa)
11+
name: Qualify locked production SDKs (3b382df)
1212
if: github.event_name == 'pull_request'
1313
runs-on: ubuntu-22.04
1414
timeout-minutes: 25
@@ -24,7 +24,7 @@ jobs:
2424
- name: Checkout exact reviewed candidate
2525
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
2626
with:
27-
ref: 040f4fa1322145047a1280a2aae828627ad9ebfa
27+
ref: 3b382df8f8b77e10e342585f24b0ef25bc401790
2828
fetch-depth: 2
2929
path: candidate
3030
persist-credentials: false
@@ -59,7 +59,7 @@ jobs:
5959
if: always()
6060
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
6161
with:
62-
name: production-scanner-contract-040f4fa
62+
name: production-scanner-contract-3b382df
6363
path: |
6464
${{ runner.temp }}/clawscan-production-contract/inputs.json
6565
${{ runner.temp }}/clawscan-production-contract/result.json

‎cmd/clawscan/main_test.go‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1469,26 +1469,14 @@ func TestRunCommandDoesNotLeakPresentSecrets(t *testing.T) {
14691469

14701470
func writeSkill(t *testing.T, dir string, content string) {
14711471
t.Helper()
1472-
if err := os.MkdirAll(dir, 0o755); err != nil {
1473-
t.Fatal(err)
1474-
}
1475-
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {
1476-
t.Fatal(err)
1477-
}
1472+
writeFile(t, filepath.Join(dir, "SKILL.md"), content)
14781473
}
14791474

14801475
func writePlugin(t *testing.T, dir string, id string) {
14811476
t.Helper()
1482-
if err := os.MkdirAll(dir, 0o755); err != nil {
1483-
t.Fatal(err)
1484-
}
14851477
manifest := `{"id":"` + id + `","name":"Probe Plugin","contracts":{"tools":["probe_tool"]}}`
1486-
if err := os.WriteFile(filepath.Join(dir, "openclaw.plugin.json"), []byte(manifest), 0o644); err != nil {
1487-
t.Fatal(err)
1488-
}
1489-
if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte("// synthetic probe\n"), 0o644); err != nil {
1490-
t.Fatal(err)
1491-
}
1478+
writeFile(t, filepath.Join(dir, "openclaw.plugin.json"), manifest)
1479+
writeFile(t, filepath.Join(dir, "index.js"), "// synthetic probe\n")
14921480
}
14931481

14941482
func writeFile(t *testing.T, path string, content string) {

‎docker/clawscan-runtime/judges/clawscan_decisions_judge.py‎

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -968,35 +968,25 @@ def trim_manifest(floor):
968968
evidence["artifactManifest"] = manifest[:keep]
969969
return True
970970

971-
def trim_gaps(floor):
972-
candidates = [item for item in gap_lists(evidence["scanners"]) if len(item["records"]) > floor]
973-
if not candidates:
971+
def trim_largest(items, key, floor):
972+
largest = max(items, key=lambda item: len(item[key]), default=None)
973+
if largest is None or len(largest[key]) <= floor:
974974
return False
975-
largest = max(candidates, key=lambda item: len(item["records"]))
976-
keep = shrink(len(largest["records"]), floor)
977-
largest["omitted"] += len(largest["records"]) - keep
978-
largest["records"] = largest["records"][:keep]
979-
return True
980-
981-
def trim_children(floor):
982-
candidates = [item for item in bundled_lists(evidence) if len(item["children"]) > floor]
983-
if not candidates:
984-
return False
985-
largest = max(candidates, key=lambda item: len(item["children"]))
986-
keep = shrink(len(largest["children"]), floor)
987-
largest["omitted"] += len(largest["children"]) - keep
988-
largest["children"] = largest["children"][:keep]
975+
values = largest[key]
976+
keep = shrink(len(values), floor)
977+
largest["omitted"] += len(values) - keep
978+
largest[key] = values[:keep]
989979
return True
990980

991981
stages = [
992982
lambda: trim_findings(DEFAULT_MAX_FINDING_QUESTIONS),
993983
lambda: trim_manifest(50),
994-
lambda: trim_gaps(6),
995-
lambda: trim_children(10),
984+
lambda: trim_largest(gap_lists(evidence["scanners"]), "records", 6),
985+
lambda: trim_largest(bundled_lists(evidence), "children", 10),
996986
lambda: trim_findings(0),
997987
lambda: trim_manifest(0),
998-
lambda: trim_gaps(0),
999-
lambda: trim_children(0),
988+
lambda: trim_largest(gap_lists(evidence["scanners"]), "records", 0),
989+
lambda: trim_largest(bundled_lists(evidence), "children", 0),
1000990
]
1001991
stage = 0
1002992
while not evidence_fits(evidence):

‎docker/clawscan-runtime/tests/test_decisions_judge.py‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -371,17 +371,10 @@ def test_final_evidence_respects_value_and_byte_limits(self):
371371
code, result, stderr = self.run_judge(workspace, "--max-findings", "2000")
372372
self.assertEqual(code, 0, stderr)
373373
evidence = self.evidence()
374-
size = len(json.dumps(evidence, separators=(",", ":"), ensure_ascii=False).encode())
375-
values, depth = judge.json_stats(evidence)
376-
self.assertLessEqual(size, judge.EVIDENCE_JSON_BUDGET_BYTES)
377-
self.assertLessEqual(values, judge.API_JSON_PART_VALUES)
378-
self.assertLessEqual(depth, judge.API_JSON_PART_DEPTH)
379-
recorded = result["decision"]["input"]["evidenceJson"]
380-
self.assertEqual(recorded, {"bytes": size, "values": values, "depth": depth})
374+
self.assert_final_limits(result)
381375
counts = evidence["findingCounts"]
382376
self.assertEqual(counts["total"], 2000)
383377
self.assertEqual(counts["included"], len(evidence["findings"]))
384-
self.assertEqual(counts["included"] + counts["omitted"], 2000)
385378
self.assertEqual(len(evidence["artifactManifest"]) + evidence["artifactCounts"]["manifestOmitted"], 451)
386379
self.assertEqual([finding["index"] for finding in evidence["findings"]], list(range(counts["included"])))
387380

‎internal/runner/aig_mcp_template_test.go‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package runner
22

33
import (
4-
"encoding/json"
54
"os"
65
"path/filepath"
76
"reflect"
@@ -122,10 +121,10 @@ func TestTemplateTargetCanonicalSelectorAndPrecedence(t *testing.T) {
122121

123122
func TestTemplateTargetRejectsUnsafeOrRetiredSelectors(t *testing.T) {
124123
for _, selector := range []any{"../CLAW.md", "/CLAW.md", "x/../CLAW.md", "x//CLAW.md", "manifest.json", true, "missing/CLAW.md", "x\\CLAW.md", "././CLAW.md"} {
125-
t.Run(strings.ReplaceAll(strings.TrimSpace(string(mustTemplateJSON(t, selector))), "/", "_"), func(t *testing.T) {
124+
t.Run(strings.ReplaceAll(strings.TrimSpace(string(mustMarshalJSON(t, selector))), "/", "_"), func(t *testing.T) {
126125
root := t.TempDir()
127126
pkg := map[string]any{"openclaw": map[string]any{"template": selector}}
128-
if err := os.WriteFile(filepath.Join(root, "package.json"), mustTemplateJSON(t, pkg), 0600); err != nil {
127+
if err := os.WriteFile(filepath.Join(root, "package.json"), mustMarshalJSON(t, pkg), 0600); err != nil {
129128
t.Fatal(err)
130129
}
131130
if _, err := resolveTarget(root); err == nil {
@@ -142,15 +141,6 @@ func TestTemplateTargetRejectsUnsafeOrRetiredSelectors(t *testing.T) {
142141
}
143142
}
144143

145-
func mustTemplateJSON(t *testing.T, value any) []byte {
146-
t.Helper()
147-
data, err := json.Marshal(value)
148-
if err != nil {
149-
t.Fatal(err)
150-
}
151-
return data
152-
}
153-
154144
func TestTemplateStagingRejectsEscapingLinksAndOversizedVendoredFiles(t *testing.T) {
155145
root := templateFixture(t)
156146
if err := os.Symlink(t.TempDir(), filepath.Join(root, "escape")); err != nil {

‎internal/runner/aig_scanner_test.go‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func TestValidateRequirementsRejectsAIGWithoutAPIKey(t *testing.T) {
6464

6565
func TestAIGScannerRunsLocalCLIAndPreservesSARIF(t *testing.T) {
6666
target := createAIGTestSkill(t)
67-
commandRunner := &aigRecordingCommandRunner{output: aigSARIF}
67+
commandRunner := &reportFileCommandRunner{outputFlag: "-o", output: aigSARIF}
6868
opts, err := ParseArgs([]string{target, "--scanner", "aig", "--sandbox", "off"})
6969
if err != nil {
7070
t.Fatal(err)
@@ -118,7 +118,7 @@ func TestAIGScannerRecordsOpenAIKeyFallback(t *testing.T) {
118118
}
119119
artifact, err := Run(opts, RunContext{
120120
Env: map[string]string{"OPENAI_API_KEY": "secret-openai-key"},
121-
CommandRunner: &aigRecordingCommandRunner{output: aigSARIF},
121+
CommandRunner: &reportFileCommandRunner{outputFlag: "-o", output: aigSARIF},
122122
})
123123
if err != nil {
124124
t.Fatal(err)
@@ -182,11 +182,12 @@ func TestAIGScannerDockerRunMountsTargetAndOutputDirectory(t *testing.T) {
182182
func TestAIGScannerCompletesNonZeroExitWithValidSARIF(t *testing.T) {
183183
target := createAIGTestSkill(t)
184184
exitCode := 1
185-
commandRunner := &aigRecordingCommandRunner{
186-
output: aigSARIF,
187-
stderr: "findings require review",
188-
err: errors.New("exit status 1"),
189-
exitCode: &exitCode,
185+
commandRunner := &reportFileCommandRunner{
186+
outputFlag: "-o",
187+
output: aigSARIF,
188+
stderr: "findings require review",
189+
err: errors.New("exit status 1"),
190+
exitCode: &exitCode,
190191
}
191192
opts, err := ParseArgs([]string{target, "--scanner", "aig", "--sandbox", "off"})
192193
if err != nil {
@@ -232,7 +233,7 @@ func TestAIGScannerFailsMissingOrInvalidSARIF(t *testing.T) {
232233
}
233234
artifact, err := Run(opts, RunContext{
234235
Env: map[string]string{"LLM_API_KEY": "present"},
235-
CommandRunner: &aigRecordingCommandRunner{output: test.output},
236+
CommandRunner: &reportFileCommandRunner{outputFlag: "-o", output: test.output},
236237
})
237238
if err != nil {
238239
t.Fatal(err)
@@ -263,7 +264,7 @@ func TestAIGScannerSkipsUnsupportedTargets(t *testing.T) {
263264
}
264265
artifact, err := Run(opts, RunContext{
265266
Env: map[string]string{"LLM_API_KEY": "present"},
266-
CommandRunner: &aigRecordingCommandRunner{output: aigSARIF},
267+
CommandRunner: &reportFileCommandRunner{outputFlag: "-o", output: aigSARIF},
267268
})
268269
if err != nil {
269270
t.Fatal(err)
@@ -347,18 +348,19 @@ func createAIGTestSkill(t *testing.T) string {
347348
return target
348349
}
349350

350-
type aigRecordingCommandRunner struct {
351-
calls []commandCall
352-
output string
353-
stderr string
354-
err error
355-
exitCode *int
351+
type reportFileCommandRunner struct {
352+
outputFlag string
353+
calls []commandCall
354+
output string
355+
stderr string
356+
err error
357+
exitCode *int
356358
}
357359

358-
func (runner *aigRecordingCommandRunner) Run(command string, args []string, cwd string, timeout time.Duration) (CommandOutput, error) {
360+
func (runner *reportFileCommandRunner) Run(command string, args []string, cwd string, timeout time.Duration) (CommandOutput, error) {
359361
runner.calls = append(runner.calls, commandCall{command: command, args: append([]string(nil), args...), cwd: cwd})
360362
if runner.output != "" {
361-
outputPath := argValue(args, "-o")
363+
outputPath := argValue(args, runner.outputFlag)
362364
if outputPath != "" {
363365
if err := os.WriteFile(outputPath, []byte(runner.output), 0o644); err != nil {
364366
return CommandOutput{Stderr: runner.stderr}, err

‎internal/runner/cisco_scanner_test.go‎

Lines changed: 13 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"path/filepath"
88
"strings"
99
"testing"
10-
"time"
1110
)
1211

1312
func TestCiscoScannerCompletesWithJSONOutputFile(t *testing.T) {
@@ -17,7 +16,7 @@ func TestCiscoScannerCompletesWithJSONOutputFile(t *testing.T) {
1716
t.Fatal(err)
1817
}
1918
const ciscoJSON = `{"scanner":"cisco","findings":[]}`
20-
runner := &ciscoRecordingCommandRunner{output: ciscoJSON}
19+
runner := &reportFileCommandRunner{outputFlag: "--output", output: ciscoJSON}
2120
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
2221
if err != nil {
2322
t.Fatal(err)
@@ -59,7 +58,7 @@ func TestCiscoScannerCompletesWithJSONOutputFile(t *testing.T) {
5958
}
6059

6160
func TestCiscoScannerUsesResultDirAsDockerSandboxCWD(t *testing.T) {
62-
commandRunner := &ciscoRecordingCommandRunner{output: `{"scanner":"cisco","findings":[]}`}
61+
commandRunner := &reportFileCommandRunner{outputFlag: "--output", output: `{"scanner":"cisco","findings":[]}`}
6362
result, err := (ExternalScannerRunner{
6463
CommandRunner: commandRunner,
6564
Env: map[string]string{},
@@ -87,7 +86,7 @@ func TestCiscoScannerEnablesUpstreamAnalyzersFromEnv(t *testing.T) {
8786
if err := os.Mkdir(target, 0o755); err != nil {
8887
t.Fatal(err)
8988
}
90-
runner := &ciscoRecordingCommandRunner{output: `{"scanner":"cisco","findings":[]}`}
89+
runner := &reportFileCommandRunner{outputFlag: "--output", output: `{"scanner":"cisco","findings":[]}`}
9190
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
9291
if err != nil {
9392
t.Fatal(err)
@@ -130,7 +129,7 @@ func TestCiscoScannerOutputFileIsPreservedInArtifactBundle(t *testing.T) {
130129
}
131130
out := filepath.Join(dir, "clawscan-results", "artifact.json")
132131
const ciscoJSON = `{"scanner":"cisco","findings":[{"id":"network"}]}`
133-
runner := &ciscoRecordingCommandRunner{output: ciscoJSON}
132+
runner := &reportFileCommandRunner{outputFlag: "--output", output: ciscoJSON}
134133
opts, err := ParseArgs([]string{target, "--scanner", "cisco", "--output", out})
135134
if err != nil {
136135
t.Fatal(err)
@@ -164,11 +163,12 @@ func TestCiscoScannerCompletesNonZeroExitWithJSONOutputFile(t *testing.T) {
164163
}
165164
const ciscoJSON = `{"scanner":"cisco","findings":[{"id":"pipeline-risk"}]}`
166165
exitCode := 1
167-
runner := &ciscoRecordingCommandRunner{
168-
output: ciscoJSON,
169-
stderr: "high severity findings",
170-
err: errors.New("exit status 1"),
171-
exitCode: &exitCode,
166+
runner := &reportFileCommandRunner{
167+
outputFlag: "--output",
168+
output: ciscoJSON,
169+
stderr: "high severity findings",
170+
err: errors.New("exit status 1"),
171+
exitCode: &exitCode,
172172
}
173173
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
174174
if err != nil {
@@ -202,7 +202,7 @@ func TestCiscoScannerFailsMissingOutputFile(t *testing.T) {
202202
if err := os.Mkdir(target, 0o755); err != nil {
203203
t.Fatal(err)
204204
}
205-
runner := &ciscoRecordingCommandRunner{}
205+
runner := &reportFileCommandRunner{outputFlag: "--output"}
206206
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
207207
if err != nil {
208208
t.Fatal(err)
@@ -232,7 +232,7 @@ func TestCiscoScannerFailsInvalidJSONOutputFile(t *testing.T) {
232232
if err := os.Mkdir(target, 0o755); err != nil {
233233
t.Fatal(err)
234234
}
235-
runner := &ciscoRecordingCommandRunner{output: "not json"}
235+
runner := &reportFileCommandRunner{outputFlag: "--output", output: "not json"}
236236
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
237237
if err != nil {
238238
t.Fatal(err)
@@ -262,7 +262,7 @@ func TestRunDispatchesCiscoScannerInsteadOfGenericSkipped(t *testing.T) {
262262
if err := os.Mkdir(target, 0o755); err != nil {
263263
t.Fatal(err)
264264
}
265-
runner := &ciscoRecordingCommandRunner{output: `{"ok":true}`}
265+
runner := &reportFileCommandRunner{outputFlag: "--output", output: `{"ok":true}`}
266266
opts, err := ParseArgs([]string{target, "--scanner", "cisco"})
267267
if err != nil {
268268
t.Fatal(err)
@@ -283,27 +283,6 @@ func TestRunDispatchesCiscoScannerInsteadOfGenericSkipped(t *testing.T) {
283283
}
284284
}
285285

286-
type ciscoRecordingCommandRunner struct {
287-
calls []commandCall
288-
output string
289-
stderr string
290-
err error
291-
exitCode *int
292-
}
293-
294-
func (r *ciscoRecordingCommandRunner) Run(command string, args []string, cwd string, timeout time.Duration) (CommandOutput, error) {
295-
r.calls = append(r.calls, commandCall{command: command, args: append([]string(nil), args...), cwd: cwd})
296-
if r.output != "" {
297-
outputPath := argValue(args, "--output")
298-
if outputPath != "" {
299-
if err := os.WriteFile(outputPath, []byte(r.output), 0o644); err != nil {
300-
return CommandOutput{Stderr: r.stderr}, err
301-
}
302-
}
303-
}
304-
return CommandOutput{Stderr: r.stderr, ExitCode: r.exitCode}, r.err
305-
}
306-
307286
func argValue(args []string, name string) string {
308287
for i, arg := range args {
309288
if arg == name && i+1 < len(args) {

0 commit comments

Comments
 (0)