Skip to content

Commit 13c6cb5

Browse files
authored
feat(runner): add declarative JSON gate policy (#34)
* feat(runner): add declarative JSON gate policy * feat(profiles): publish config schema * fix(profiles): preserve ClawHub gate behavior * fix(gate): align alias and schema validation
1 parent 3d041c6 commit 13c6cb5

26 files changed

Lines changed: 2304 additions & 265 deletions

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ Custom profiles can be created in `.clawscan.yml`.
195195
This is useful for version controlling iterations on your profile, creating multiple profiles to run over the same skills, etc
196196

197197
```yaml
198+
# yaml-language-server: $schema=https://raw.githubusercontent.com/openclaw/clawscan/main/schemas/clawscan.schema.json
199+
198200
version: 1
199201
profiles:
200202
review:
@@ -213,6 +215,9 @@ profiles:
213215
- < {{ prompt:./prompt.md }}
214216
```
215217
218+
The published schema provides editor completion and catches invalid profile
219+
fields before a scan starts. ClawScan also validates every config at runtime.
220+
216221
## Judge Harness
217222
218223
`--judge` hands scanner evidence to an external agent command so it can inspect

‎cmd/clawscan/main.go‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ func printRunSummary(w io.Writer, result runner.RunTargetsResult, outputPath str
341341
if len(summary.GateRules) > 0 {
342342
details := make([]string, 0, len(summary.GateRules))
343343
for _, rule := range summary.GateRules {
344-
details = append(details, fmt.Sprintf("%s exit %d -> %s", rule.Scanner, rule.ExitCode, rule.Action))
344+
details = append(details, gateRuleSummary(rule))
345345
}
346346
fmt.Fprintf(w, " (%s)", strings.Join(details, ", "))
347347
}
@@ -362,6 +362,19 @@ func printRunSummary(w io.Writer, result runner.RunTargetsResult, outputPath str
362362
}
363363
}
364364

365+
func gateRuleSummary(rule runner.FiredGateRule) string {
366+
if rule.ExitCode != nil {
367+
return fmt.Sprintf("%s exit %d -> %s", rule.Scanner, *rule.ExitCode, rule.Action)
368+
}
369+
if rule.Path != "" && len(rule.Value) > 0 {
370+
return fmt.Sprintf("%s %s %s=%s -> %s", rule.Scanner, rule.Rule, rule.Path, rule.Value, rule.Action)
371+
}
372+
if rule.Path != "" {
373+
return fmt.Sprintf("%s %s %s -> %s", rule.Scanner, rule.Rule, rule.Path, rule.Action)
374+
}
375+
return fmt.Sprintf("%s %s -> %s", rule.Scanner, rule.Rule, rule.Action)
376+
}
377+
365378
func printBenchmarkSummary(w io.Writer, artifact runner.BenchmarkArtifact, outputPath string) {
366379
fmt.Fprintf(w, "benchmark: %s\n", artifact.Benchmark.ID)
367380
fmt.Fprintf(w, "split: %s\n", artifact.Benchmark.Split)

‎cmd/clawscan/main_test.go‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ profiles:
222222
"clawhub:",
223223
"clawhub-aig:",
224224
"- skillspector",
225+
"- clawscan-static",
225226
"- aig",
226227
} {
227228
if !strings.Contains(stdout, want) {
@@ -234,6 +235,9 @@ profiles:
234235
if strings.Contains(stdout, "local-review:") {
235236
t.Fatalf("verbose profiles output should not include project profile:\n%s", stdout)
236237
}
238+
if strings.Contains(stdout, "gate:") {
239+
t.Fatalf("embedded profiles should preserve their existing gate-free contract:\n%s", stdout)
240+
}
237241
}
238242

239243
func TestRunCommandBenchmarkListPrintsCatalogTable(t *testing.T) {
@@ -515,10 +519,11 @@ func TestRunCommandWritesDefaultOutputAndPrintsKeyValueSummary(t *testing.T) {
515519
}
516520

517521
func TestPrintRunSummaryIncludesGateVerdictAndFiredRule(t *testing.T) {
522+
exitCode := 3
518523
artifact := runner.Artifact{
519524
Gate: "block",
520525
GateRules: []runner.FiredGateRule{
521-
{Scanner: "my-scanner", Rule: "blockOnExitCode", ExitCode: 3, Action: "block"},
526+
{Scanner: "my-scanner", Rule: "blockOnExitCode", ExitCode: &exitCode, Action: "block"},
522527
},
523528
Scanners: map[string]runner.ScannerResult{},
524529
}
@@ -529,6 +534,27 @@ func TestPrintRunSummaryIncludesGateVerdictAndFiredRule(t *testing.T) {
529534
}
530535
}
531536

537+
func TestPrintRunSummaryIncludesDeclarativeJSONGateRule(t *testing.T) {
538+
artifact := runner.Artifact{
539+
Gate: "warn",
540+
GateRules: []runner.FiredGateRule{
541+
{
542+
Scanner: "skillspector",
543+
Rule: "high-finding",
544+
Path: "filtered_findings[].severity",
545+
Value: json.RawMessage(`"HIGH"`),
546+
Action: "warn",
547+
},
548+
},
549+
Scanners: map[string]runner.ScannerResult{},
550+
}
551+
var output strings.Builder
552+
printRunSummary(&output, runner.RunTargetsResult{Single: &artifact}, "")
553+
if !strings.Contains(output.String(), `gate: warn (skillspector high-finding filtered_findings[].severity="HIGH" -> warn)`) {
554+
t.Fatalf("summary missing declarative JSON gate rule:\n%s", output.String())
555+
}
556+
}
557+
532558
func TestPrintRunSummaryKeepsBlockAcrossBatchOrder(t *testing.T) {
533559
for _, runs := range [][]runner.Artifact{
534560
{{Gate: "warn", Scanners: map[string]runner.ScannerResult{}}, {Gate: "block", Scanners: map[string]runner.ScannerResult{}}},

‎docs/profiles.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ Custom profiles can be created in `.clawscan.yml`.
6464
This is useful for version controlling iterations on your profile, creating multiple profiles to run over the same skills, etc
6565

6666
```yaml
67+
# yaml-language-server: $schema=https://raw.githubusercontent.com/openclaw/clawscan/main/schemas/clawscan.schema.json
68+
6769
version: 1
6870
profiles:
6971
review:
@@ -86,6 +88,11 @@ profiles:
8688
- < {{ prompt:./prompt.md }}
8789
```
8890
91+
The schema gives editors completion and catches misspelled fields, invalid
92+
types, unsupported values, and malformed gate rules before a scan starts.
93+
ClawScan still validates the file when it loads so correctness does not depend
94+
on editor support.
95+
8996
Sandbox mounts must use existing absolute host paths. A string mount is
9097
read-only; set `write: true` only for a directory the scanner genuinely needs
9198
to modify. The CLI equivalents are repeatable `--sandbox-mount /path` and

‎docs/scanners.md‎

Lines changed: 97 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ clawscan scanners
1717
clawscan scanners skillspector
1818
```
1919

20-
## User-defined scanners
20+
## Profile scanner configuration
2121

2222
A trusted config can mix built-in scanner IDs with user-defined command
2323
scanners. The config schema uses the existing `profiles.<name>.scanners` list:
@@ -28,7 +28,24 @@ version: 1
2828
profiles:
2929
review:
3030
scanners:
31-
- clawscan-static
31+
- id: skillspector
32+
gate:
33+
rules:
34+
- id: do-not-install
35+
path: risk_assessment.recommendation
36+
equals: DO_NOT_INSTALL
37+
action: block
38+
- id: critical-finding
39+
path: filtered_findings[].severity
40+
equals: CRITICAL
41+
action: block
42+
- id: clawscan-static
43+
gate:
44+
rules:
45+
- id: any-finding
46+
path: findings[]
47+
exists: true
48+
action: warn
3249
- id: my-scanner
3350
command: my-scanner --json {{target}}
3451
env:
@@ -39,11 +56,21 @@ profiles:
3956
- skill
4057
- plugin
4158
gate:
59+
rules:
60+
- id: high-risk
61+
path: result.risk
62+
equals: high
63+
action: warn
4264
blockOnExitCode: nonzero
4365
```
4466
45-
String entries select built-in scanners. Object entries define a scanner for
46-
that config-backed run and accept these fields:
67+
String entries select built-in scanners without gate policy. An object with a
68+
registered built-in `id` and no `command` selects that built-in and can attach
69+
gate rules. The rules inspect its existing JSON output; the scanner does not
70+
need to implement ClawScan-specific policy or change its exit codes.
71+
72+
An object with a `command` defines a user-provided scanner for that
73+
config-backed run. The same JSON rules work for built-in and command scanners:
4774

4875
| Field | Required | Meaning |
4976
| --- | --- | --- |
@@ -52,7 +79,58 @@ that config-backed run and accept these fields:
5279
| `env` | no | Required non-secret environment variable names passed to the scanner. Their values are not automatically redacted from scanner error text. |
5380
| `secretEnv` | no | Required secret environment variable names passed to the scanner. Their values are redacted from scanner error text regardless of how the names are spelled. |
5481
| `targets` | no | Supported target kinds: `skill`, `plugin`, and/or `url`. Defaults to `skill` and `url`. |
55-
| `gate` | no | Exit-code policy with optional `blockOnExitCode` and `warnOnExitCode` rules. |
82+
| `gate` | no | JSON and/or exit-code policy applied after the scanner completes. |
83+
84+
### JSON gate rules
85+
86+
`gate.rules` evaluates the scanner's raw JSON without rewriting it. Every rule
87+
has:
88+
89+
| Field | Required | Meaning |
90+
| --- | --- | --- |
91+
| `id` | yes | Stable name reported in `gateRules`; IDs must be unique within one scanner gate. |
92+
| `path` | yes | One path or an ordered list of aliases. Paths use dotted object fields, with `[]` after a field to traverse every array item. Separate alternative field names with the pipe character. Array indexes and other expression syntax are not supported. |
93+
| `action` | yes | `warn` or `block`. |
94+
| `equals` | one condition | Matches a string, number, or boolean exactly. String comparison is case-sensitive. |
95+
| `exists` | one condition | Must be `true`; matches when the path resolves to at least one value. |
96+
| `normalize` | no | `identifier` makes string `equals` matching case-insensitive and treats spaces and hyphens like underscores. It cannot be used with numbers, booleans, or `exists`. |
97+
| `fallback` | no | `root` makes the first path whose root field exists authoritative, even when a nested field is missing. Use this when a preferred filtered collection must override legacy raw collections. |
98+
99+
Specify exactly one of `equals` or `exists: true`. A rule fires at most once,
100+
even when several paths or array items match. The fired artifact records the
101+
path that matched. A path list is an ordered fallback: ClawScan evaluates the
102+
first path with a non-empty value and ignores later aliases, whether or not its
103+
value matches. Empty strings and `null` fall through to the next alias. An
104+
explicitly empty traversed array remains authoritative, letting a preferred
105+
filtered result override legacy raw-result fields. Missing paths, empty arrays,
106+
and type mismatches do not fire. Within one path segment, `|` alternatives are
107+
resolved separately for each object, using the first present field; if that
108+
field is empty, the rule can still fall through to the next path. For
109+
`fallback: root`, a present root field prevents later path aliases from being
110+
consulted. For example, `findings[].severity|risk_severity` checks `severity`
111+
and then `risk_severity` on each finding. An immutable third-party scanner can
112+
be gated without a wrapper:
113+
114+
```yaml
115+
scanners:
116+
- id: third-party
117+
command: third-party scan --json {{target}}
118+
gate:
119+
rules:
120+
- id: critical-risk
121+
path:
122+
- result.risk
123+
- result.risk_level
124+
equals: critical
125+
normalize: identifier
126+
action: block
127+
- id: any-policy-violation
128+
path: result.violations[]
129+
exists: true
130+
action: warn
131+
```
132+
133+
### Exit-code rules
56134

57135
Each exit-code rule accepts one integer from 0 through 124, a list such as
58136
`[1, 2, 3]`, or the string `nonzero`. The block and warning rules may not
@@ -66,22 +144,27 @@ gate:
66144
warnOnExitCode: 1
67145
```
68146

147+
JSON and exit-code rules can be combined on the same scanner. A gate-eligible
148+
process exit code is preserved alongside raw JSON, and all fired rules
149+
participate in the same strongest-action decision.
150+
69151
After every selected scanner finishes, ClawScan records the strongest fired
70152
action as the top-level artifact `gate`: `block` wins over `warn`, and an
71153
artifact with no fired rules records `"gate": "pass"`. Each fired rule is also
72-
listed in `gateRules` with its scanner ID, rule name, exit code, and action.
73-
Gate actions are record-only: `block` does not stop later scanners or the
74-
judge, and it does not change ClawScan's process exit status. For enforcement,
75-
inspect `gate` and `gateRules` on a single run, `runs[].gate` and
154+
listed in `gateRules` with its scanner ID, rule ID, and action. Exit-code rules
155+
include `exitCode`; JSON rules include `path` and, for `equals`, the matched
156+
`value`. Gate actions are record-only: `block` does not stop later scanners or
157+
the judge, and it does not change ClawScan's process exit status. For
158+
enforcement, inspect `gate` and `gateRules` on a single run, `runs[].gate` and
76159
`runs[].gateRules` in a batch, or `cases[].run.gate` and
77160
`cases[].run.gateRules` in a benchmark. The human scan summary aggregates the
78161
strongest batch action; the benchmark summary does not aggregate gate actions.
79162

80-
Skipped scanners do not fire gate rules. A scanner result with status `failed`
81-
also does not fire an exit-code rule; a nonzero command that still returned
82-
valid JSON has status `completed` and can fire one. Valid JSON from a timeout,
83-
signal, or reserved infrastructure exit is still preserved, but its omitted
84-
`exitCode` means it cannot fire a gate rule.
163+
Skipped or failed scanners do not fire gate rules. A nonzero command that still
164+
returned valid JSON has status `completed` and can fire both JSON and exit-code
165+
rules. Valid JSON from a timeout, signal, or reserved infrastructure exit is
166+
still preserved, but the failed scanner does not fire gate rules and its
167+
`exitCode` is omitted.
85168

86169
The command must write JSON to stdout. ClawScan preserves valid stdout as the
87170
scanner's raw evidence; empty or non-JSON stdout produces a failed scanner

‎go.mod‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,8 @@ go 1.26.1
44

55
require (
66
github.com/alchemy/json5 v0.2.0
7+
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
78
gopkg.in/yaml.v3 v3.0.1
89
)
10+
11+
require golang.org/x/text v0.14.0 // indirect

‎go.sum‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
github.com/alchemy/json5 v0.2.0 h1:M8hmUpCyGlzdiWaxY4RI/rDcLAlFTtjB6j49eUpk+FE=
22
github.com/alchemy/json5 v0.2.0/go.mod h1:kVE7UoCjGVIlxOXFCzKn6T34nyC/OctNTNG81MLOqiw=
3+
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
4+
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
5+
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
6+
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
7+
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
8+
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
39
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
410
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
511
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

0 commit comments

Comments
 (0)